您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

RTCUtils.js 51KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385
  1. /* global $,
  2. __filename,
  3. attachMediaStream,
  4. MediaStreamTrack,
  5. RTCIceCandidate,
  6. RTCPeerConnection,
  7. RTCSessionDescription,
  8. mozRTCIceCandidate,
  9. mozRTCPeerConnection,
  10. mozRTCSessionDescription,
  11. webkitMediaStream,
  12. webkitRTCPeerConnection,
  13. webkitURL
  14. */
  15. import CameraFacingMode from '../../service/RTC/CameraFacingMode';
  16. import EventEmitter from 'events';
  17. import { getLogger } from 'jitsi-meet-logger';
  18. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  19. import JitsiTrackError from '../../JitsiTrackError';
  20. import Listenable from '../util/Listenable';
  21. import * as MediaType from '../../service/RTC/MediaType';
  22. import Resolutions from '../../service/RTC/Resolutions';
  23. import RTCBrowserType from './RTCBrowserType';
  24. import RTCEvents from '../../service/RTC/RTCEvents';
  25. import screenObtainer from './ScreenObtainer';
  26. import SDPUtil from '../xmpp/SDPUtil';
  27. import VideoType from '../../service/RTC/VideoType';
  28. const logger = getLogger(__filename);
  29. // XXX Don't require Temasys unless it's to be used because it doesn't run on
  30. // React Native, for example.
  31. const AdapterJS
  32. = RTCBrowserType.isTemasysPluginUsed()
  33. ? require('./adapter.screenshare')
  34. : undefined;
  35. const eventEmitter = new EventEmitter();
  36. const AVAILABLE_DEVICES_POLL_INTERVAL_TIME = 3000; // ms
  37. const devices = {
  38. audio: false,
  39. video: false
  40. };
  41. // Currently audio output device change is supported only in Chrome and
  42. // default output always has 'default' device ID
  43. let audioOutputDeviceId = 'default'; // default device
  44. // whether user has explicitly set a device to use
  45. let audioOutputChanged = false;
  46. // Disables Acoustic Echo Cancellation
  47. let disableAEC = false;
  48. // Disables Noise Suppression
  49. let disableNS = false;
  50. const featureDetectionAudioEl = document.createElement('audio');
  51. const isAudioOutputDeviceChangeAvailable
  52. = typeof featureDetectionAudioEl.setSinkId !== 'undefined';
  53. let currentlyAvailableMediaDevices;
  54. let rawEnumerateDevicesWithCallback;
  55. /**
  56. * "rawEnumerateDevicesWithCallback" will be initialized only after WebRTC is
  57. * ready. Otherwise it is too early to assume that the devices listing is not
  58. * supported.
  59. */
  60. function initRawEnumerateDevicesWithCallback() {
  61. rawEnumerateDevicesWithCallback = navigator.mediaDevices
  62. && navigator.mediaDevices.enumerateDevices
  63. ? function(callback) {
  64. navigator.mediaDevices.enumerateDevices().then(
  65. callback,
  66. () => callback([]));
  67. }
  68. // Safari:
  69. // "ReferenceError: Can't find variable: MediaStreamTrack"
  70. // when Temasys plugin is not installed yet, have to delay this call
  71. // until WebRTC is ready.
  72. : MediaStreamTrack && MediaStreamTrack.getSources
  73. ? function(callback) {
  74. MediaStreamTrack.getSources(
  75. sources =>
  76. callback(sources.map(convertMediaStreamTrackSource)));
  77. }
  78. : undefined;
  79. }
  80. // TODO: currently no browser supports 'devicechange' event even in nightly
  81. // builds so no feature/browser detection is used at all. However in future this
  82. // should be changed to some expression. Progress on 'devicechange' event
  83. // implementation for Chrome/Opera/NWJS can be tracked at
  84. // https://bugs.chromium.org/p/chromium/issues/detail?id=388648, for Firefox -
  85. // at https://bugzilla.mozilla.org/show_bug.cgi?id=1152383. More information on
  86. // 'devicechange' event can be found in spec -
  87. // http://w3c.github.io/mediacapture-main/#event-mediadevices-devicechange
  88. // TODO: check MS Edge
  89. const isDeviceChangeEventSupported = false;
  90. let rtcReady = false;
  91. function setResolutionConstraints(constraints, resolution) {
  92. const isAndroid = RTCBrowserType.isAndroid();
  93. if (Resolutions[resolution]) {
  94. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  95. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  96. } else if (isAndroid) {
  97. // FIXME can't remember if the purpose of this was to always request
  98. // low resolution on Android ? if yes it should be moved up front
  99. constraints.video.mandatory.minWidth = 320;
  100. constraints.video.mandatory.minHeight = 180;
  101. constraints.video.mandatory.maxFrameRate = 15;
  102. }
  103. if (constraints.video.mandatory.minWidth) {
  104. constraints.video.mandatory.maxWidth
  105. = constraints.video.mandatory.minWidth;
  106. }
  107. if (constraints.video.mandatory.minHeight) {
  108. constraints.video.mandatory.maxHeight
  109. = constraints.video.mandatory.minHeight;
  110. }
  111. }
  112. /**
  113. * @param {string[]} um required user media types
  114. *
  115. * @param {Object} [options={}] optional parameters
  116. * @param {string} options.resolution
  117. * @param {number} options.bandwidth
  118. * @param {number} options.fps
  119. * @param {string} options.desktopStream
  120. * @param {string} options.cameraDeviceId
  121. * @param {string} options.micDeviceId
  122. * @param {CameraFacingMode} options.facingMode
  123. * @param {bool} firefox_fake_device
  124. */
  125. function getConstraints(um, options) {
  126. const constraints = { audio: false,
  127. video: false };
  128. // Don't mix new and old style settings for Chromium as this leads
  129. // to TypeError in new Chromium versions. @see
  130. // https://bugs.chromium.org/p/chromium/issues/detail?id=614716
  131. // This is a temporary solution, in future we will fully split old and
  132. // new style constraints when new versions of Chromium and Firefox will
  133. // have stable support of new constraints format. For more information
  134. // @see https://github.com/jitsi/lib-jitsi-meet/pull/136
  135. const isNewStyleConstraintsSupported
  136. = RTCBrowserType.isFirefox()
  137. || RTCBrowserType.isReactNative()
  138. || RTCBrowserType.isTemasysPluginUsed();
  139. if (um.indexOf('video') >= 0) {
  140. // same behaviour as true
  141. constraints.video = { mandatory: {},
  142. optional: [] };
  143. if (options.cameraDeviceId) {
  144. if (isNewStyleConstraintsSupported) {
  145. // New style of setting device id.
  146. constraints.video.deviceId = options.cameraDeviceId;
  147. }
  148. // Old style.
  149. constraints.video.optional.push({
  150. sourceId: options.cameraDeviceId
  151. });
  152. } else {
  153. // Prefer the front i.e. user-facing camera (to the back i.e.
  154. // environment-facing camera, for example).
  155. // TODO: Maybe use "exact" syntax if options.facingMode is defined,
  156. // but this probably needs to be decided when updating other
  157. // constraints, as we currently don't use "exact" syntax anywhere.
  158. const facingMode = options.facingMode || CameraFacingMode.USER;
  159. if (isNewStyleConstraintsSupported) {
  160. constraints.video.facingMode = facingMode;
  161. }
  162. constraints.video.optional.push({
  163. facingMode
  164. });
  165. }
  166. if (options.minFps || options.maxFps || options.fps) {
  167. // for some cameras it might be necessary to request 30fps
  168. // so they choose 30fps mjpg over 10fps yuy2
  169. if (options.minFps || options.fps) {
  170. options.minFps = options.minFps || options.fps; // Fall back to options.fps for backwards compatibility
  171. constraints.video.mandatory.minFrameRate = options.minFps;
  172. }
  173. if (options.maxFps) {
  174. constraints.video.mandatory.maxFrameRate = options.maxFps;
  175. }
  176. }
  177. setResolutionConstraints(constraints, options.resolution);
  178. }
  179. if (um.indexOf('audio') >= 0) {
  180. if (RTCBrowserType.isReactNative()) {
  181. // The react-native-webrtc project that we're currently using
  182. // expects the audio constraint to be a boolean.
  183. constraints.audio = true;
  184. } else if (RTCBrowserType.isFirefox()) {
  185. if (options.micDeviceId) {
  186. constraints.audio = {
  187. mandatory: {},
  188. deviceId: options.micDeviceId, // new style
  189. optional: [ {
  190. sourceId: options.micDeviceId // old style
  191. } ] };
  192. } else {
  193. constraints.audio = true;
  194. }
  195. } else {
  196. // same behaviour as true
  197. constraints.audio = { mandatory: {},
  198. optional: [] };
  199. if (options.micDeviceId) {
  200. if (isNewStyleConstraintsSupported) {
  201. // New style of setting device id.
  202. constraints.audio.deviceId = options.micDeviceId;
  203. }
  204. // Old style.
  205. constraints.audio.optional.push({
  206. sourceId: options.micDeviceId
  207. });
  208. }
  209. // if it is good enough for hangouts...
  210. constraints.audio.optional.push(
  211. { googEchoCancellation: !disableAEC },
  212. { googAutoGainControl: true },
  213. { googNoiseSupression: !disableNS },
  214. { googHighpassFilter: true },
  215. { googNoiseSuppression2: !disableNS },
  216. { googEchoCancellation2: !disableAEC },
  217. { googAutoGainControl2: true }
  218. );
  219. }
  220. }
  221. if (um.indexOf('screen') >= 0) {
  222. if (RTCBrowserType.isChrome()) {
  223. constraints.video = {
  224. mandatory: {
  225. chromeMediaSource: 'screen',
  226. maxWidth: window.screen.width,
  227. maxHeight: window.screen.height,
  228. maxFrameRate: 3
  229. },
  230. optional: []
  231. };
  232. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  233. constraints.video = {
  234. optional: [
  235. {
  236. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  237. }
  238. ]
  239. };
  240. } else if (RTCBrowserType.isFirefox()) {
  241. constraints.video = {
  242. mozMediaSource: 'window',
  243. mediaSource: 'window'
  244. };
  245. } else {
  246. const errmsg
  247. = '\'screen\' WebRTC media source is supported only in Chrome'
  248. + ' and with Temasys plugin';
  249. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  250. logger.error(errmsg);
  251. }
  252. }
  253. if (um.indexOf('desktop') >= 0) {
  254. constraints.video = {
  255. mandatory: {
  256. chromeMediaSource: 'desktop',
  257. chromeMediaSourceId: options.desktopStream,
  258. maxWidth: window.screen.width,
  259. maxHeight: window.screen.height,
  260. maxFrameRate: 3
  261. },
  262. optional: []
  263. };
  264. }
  265. if (options.bandwidth) {
  266. if (!constraints.video) {
  267. // same behaviour as true
  268. constraints.video = { mandatory: {},
  269. optional: [] };
  270. }
  271. constraints.video.optional.push({ bandwidth: options.bandwidth });
  272. }
  273. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  274. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  275. // this later can be a problem with some of the tests
  276. if (RTCBrowserType.isFirefox() && options.firefox_fake_device) {
  277. // seems to be fixed now, removing this experimental fix, as having
  278. // multiple audio tracks brake the tests
  279. // constraints.audio = true;
  280. constraints.fake = true;
  281. }
  282. return constraints;
  283. }
  284. /**
  285. * Sets the availbale devices based on the options we requested and the
  286. * streams we received.
  287. * @param um the options we requested to getUserMedia.
  288. * @param stream the stream we received from calling getUserMedia.
  289. */
  290. function setAvailableDevices(um, stream) {
  291. const audioTracksReceived = stream && stream.getAudioTracks().length > 0;
  292. const videoTracksReceived = stream && stream.getVideoTracks().length > 0;
  293. if (um.indexOf('video') != -1) {
  294. devices.video = videoTracksReceived;
  295. }
  296. if (um.indexOf('audio') != -1) {
  297. devices.audio = audioTracksReceived;
  298. }
  299. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  300. }
  301. /**
  302. * Checks if new list of available media devices differs from previous one.
  303. * @param {MediaDeviceInfo[]} newDevices - list of new devices.
  304. * @returns {boolean} - true if list is different, false otherwise.
  305. */
  306. function compareAvailableMediaDevices(newDevices) {
  307. if (newDevices.length !== currentlyAvailableMediaDevices.length) {
  308. return true;
  309. }
  310. return (
  311. newDevices
  312. .map(mediaDeviceInfoToJSON)
  313. .sort()
  314. .join('')
  315. !== currentlyAvailableMediaDevices
  316. .map(mediaDeviceInfoToJSON)
  317. .sort()
  318. .join(''));
  319. function mediaDeviceInfoToJSON(info) {
  320. return JSON.stringify({
  321. kind: info.kind,
  322. deviceId: info.deviceId,
  323. groupId: info.groupId,
  324. label: info.label,
  325. facing: info.facing
  326. });
  327. }
  328. }
  329. /**
  330. * Periodically polls enumerateDevices() method to check if list of media
  331. * devices has changed. This is temporary workaround until 'devicechange' event
  332. * will be supported by browsers.
  333. */
  334. function pollForAvailableMediaDevices() {
  335. // Here we use plain navigator.mediaDevices.enumerateDevices instead of
  336. // wrapped because we just need to know the fact the devices changed, labels
  337. // do not matter. This fixes situation when we have no devices initially,
  338. // and then plug in a new one.
  339. if (rawEnumerateDevicesWithCallback) {
  340. rawEnumerateDevicesWithCallback(devices => {
  341. // We don't fire RTCEvents.DEVICE_LIST_CHANGED for the first time
  342. // we call enumerateDevices(). This is the initial step.
  343. if (typeof currentlyAvailableMediaDevices === 'undefined') {
  344. currentlyAvailableMediaDevices = devices.slice(0);
  345. } else if (compareAvailableMediaDevices(devices)) {
  346. onMediaDevicesListChanged(devices);
  347. }
  348. window.setTimeout(pollForAvailableMediaDevices,
  349. AVAILABLE_DEVICES_POLL_INTERVAL_TIME);
  350. });
  351. }
  352. }
  353. /**
  354. * Event handler for the 'devicechange' event.
  355. *
  356. * @param {MediaDeviceInfo[]} devices - list of media devices.
  357. * @emits RTCEvents.DEVICE_LIST_CHANGED
  358. */
  359. function onMediaDevicesListChanged(devicesReceived) {
  360. currentlyAvailableMediaDevices = devicesReceived.slice(0);
  361. logger.info('list of media devices has changed:', currentlyAvailableMediaDevices);
  362. const videoInputDevices
  363. = currentlyAvailableMediaDevices.filter(d => d.kind === 'videoinput');
  364. const audioInputDevices
  365. = currentlyAvailableMediaDevices.filter(d => d.kind === 'audioinput');
  366. const videoInputDevicesWithEmptyLabels
  367. = videoInputDevices.filter(d => d.label === '');
  368. const audioInputDevicesWithEmptyLabels
  369. = audioInputDevices.filter(d => d.label === '');
  370. if (videoInputDevices.length
  371. && videoInputDevices.length === videoInputDevicesWithEmptyLabels.length) {
  372. devices.video = false;
  373. }
  374. if (audioInputDevices.length
  375. && audioInputDevices.length === audioInputDevicesWithEmptyLabels.length) {
  376. devices.audio = false;
  377. }
  378. eventEmitter.emit(RTCEvents.DEVICE_LIST_CHANGED, devicesReceived);
  379. }
  380. // In case of IE we continue from 'onReady' callback
  381. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  382. // once it is initialized.
  383. function onReady(options, GUM) {
  384. rtcReady = true;
  385. eventEmitter.emit(RTCEvents.RTC_READY, true);
  386. screenObtainer.init(options, GUM);
  387. // Initialize rawEnumerateDevicesWithCallback
  388. initRawEnumerateDevicesWithCallback();
  389. if (rtcUtils.isDeviceListAvailable() && rawEnumerateDevicesWithCallback) {
  390. rawEnumerateDevicesWithCallback(devices => {
  391. currentlyAvailableMediaDevices = devices.splice(0);
  392. eventEmitter.emit(RTCEvents.DEVICE_LIST_AVAILABLE,
  393. currentlyAvailableMediaDevices);
  394. if (isDeviceChangeEventSupported) {
  395. navigator.mediaDevices.addEventListener(
  396. 'devicechange',
  397. () => rtcUtils.enumerateDevices(onMediaDevicesListChanged));
  398. } else {
  399. pollForAvailableMediaDevices();
  400. }
  401. });
  402. }
  403. }
  404. /**
  405. * Apply function with arguments if function exists.
  406. * Do nothing if function not provided.
  407. * @param {function} [fn] function to apply
  408. * @param {Array} [args=[]] arguments for function
  409. */
  410. function maybeApply(fn, args) {
  411. fn && fn(...args);
  412. }
  413. const getUserMediaStatus = {
  414. initialized: false,
  415. callbacks: []
  416. };
  417. /**
  418. * Wrap `getUserMedia` to allow others to know if it was executed at least
  419. * once or not. Wrapper function uses `getUserMediaStatus` object.
  420. * @param {Function} getUserMedia native function
  421. * @returns {Function} wrapped function
  422. */
  423. function wrapGetUserMedia(getUserMedia) {
  424. return function(constraints, successCallback, errorCallback) {
  425. getUserMedia(constraints, stream => {
  426. maybeApply(successCallback, [ stream ]);
  427. if (!getUserMediaStatus.initialized) {
  428. getUserMediaStatus.initialized = true;
  429. getUserMediaStatus.callbacks.forEach(callback => callback());
  430. getUserMediaStatus.callbacks.length = 0;
  431. }
  432. }, error => {
  433. maybeApply(errorCallback, [ error ]);
  434. });
  435. };
  436. }
  437. /**
  438. * Execute function after getUserMedia was executed at least once.
  439. * @param {Function} callback function to execute after getUserMedia
  440. */
  441. function afterUserMediaInitialized(callback) {
  442. if (getUserMediaStatus.initialized) {
  443. callback();
  444. } else {
  445. getUserMediaStatus.callbacks.push(callback);
  446. }
  447. }
  448. /**
  449. * Wrapper function which makes enumerateDevices to wait
  450. * until someone executes getUserMedia first time.
  451. * @param {Function} enumerateDevices native function
  452. * @returns {Funtion} wrapped function
  453. */
  454. function wrapEnumerateDevices(enumerateDevices) {
  455. return function(callback) {
  456. // enumerate devices only after initial getUserMedia
  457. afterUserMediaInitialized(() => {
  458. enumerateDevices().then(callback, err => {
  459. logger.error('cannot enumerate devices: ', err);
  460. callback([]);
  461. });
  462. });
  463. };
  464. }
  465. /**
  466. * Use old MediaStreamTrack to get devices list and
  467. * convert it to enumerateDevices format.
  468. * @param {Function} callback function to call when received devices list.
  469. */
  470. function enumerateDevicesThroughMediaStreamTrack(callback) {
  471. MediaStreamTrack.getSources(
  472. sources => callback(sources.map(convertMediaStreamTrackSource)));
  473. }
  474. /**
  475. * Converts MediaStreamTrack Source to enumerateDevices format.
  476. * @param {Object} source
  477. */
  478. function convertMediaStreamTrackSource(source) {
  479. const kind = (source.kind || '').toLowerCase();
  480. return {
  481. facing: source.facing || null,
  482. label: source.label,
  483. // theoretically deprecated MediaStreamTrack.getSources should
  484. // not return 'audiooutput' devices but let's handle it in any
  485. // case
  486. kind: kind
  487. ? kind === 'audiooutput' ? kind : `${kind}input`
  488. : null,
  489. deviceId: source.id,
  490. groupId: source.groupId || null
  491. };
  492. }
  493. function obtainDevices(options) {
  494. if (!options.devices || options.devices.length === 0) {
  495. return options.successCallback(options.streams || {});
  496. }
  497. const device = options.devices.splice(0, 1);
  498. const devices = [];
  499. devices.push(device);
  500. options.deviceGUM[device](
  501. stream => {
  502. options.streams = options.streams || {};
  503. options.streams[device] = stream;
  504. obtainDevices(options);
  505. },
  506. error => {
  507. Object.keys(options.streams).forEach(device => {
  508. rtcUtils.stopMediaStream(options.streams[device]);
  509. });
  510. logger.error(
  511. `failed to obtain ${device} stream - stop`, error);
  512. options.errorCallback(error);
  513. });
  514. }
  515. /**
  516. * Handles the newly created Media Streams.
  517. * @param streams the new Media Streams
  518. * @param resolution the resolution of the video streams
  519. * @returns {*[]} object that describes the new streams
  520. */
  521. function handleLocalStream(streams, resolution) {
  522. let audioStream, desktopStream, videoStream;
  523. const res = [];
  524. // XXX The function obtainAudioAndVideoPermissions has examined the type of
  525. // the browser, its capabilities, etc. and has taken the decision whether to
  526. // invoke getUserMedia per device (e.g. Firefox) or once for both audio and
  527. // video (e.g. Chrome). In order to not duplicate the logic here, examine
  528. // the specified streams and figure out what we've received based on
  529. // obtainAudioAndVideoPermissions' decision.
  530. if (streams) {
  531. // As mentioned above, certian types of browser (e.g. Chrome) support
  532. // (with a result which meets our requirements expressed bellow) calling
  533. // getUserMedia once for both audio and video.
  534. const audioVideo = streams.audioVideo;
  535. if (audioVideo) {
  536. const audioTracks = audioVideo.getAudioTracks();
  537. if (audioTracks.length) {
  538. // eslint-disable-next-line new-cap
  539. audioStream = new webkitMediaStream();
  540. for (let i = 0; i < audioTracks.length; i++) {
  541. audioStream.addTrack(audioTracks[i]);
  542. }
  543. }
  544. const videoTracks = audioVideo.getVideoTracks();
  545. if (videoTracks.length) {
  546. // eslint-disable-next-line new-cap
  547. videoStream = new webkitMediaStream();
  548. for (let j = 0; j < videoTracks.length; j++) {
  549. videoStream.addTrack(videoTracks[j]);
  550. }
  551. }
  552. } else {
  553. // On other types of browser (e.g. Firefox) we choose (namely,
  554. // obtainAudioAndVideoPermissions) to call getUsermedia per device
  555. // (type).
  556. audioStream = streams.audio;
  557. videoStream = streams.video;
  558. }
  559. // Again, different choices on different types of browser.
  560. desktopStream = streams.desktopStream || streams.desktop;
  561. }
  562. if (desktopStream) {
  563. res.push({
  564. stream: desktopStream,
  565. track: desktopStream.getVideoTracks()[0],
  566. mediaType: MediaType.VIDEO,
  567. videoType: VideoType.DESKTOP
  568. });
  569. }
  570. if (audioStream) {
  571. res.push({
  572. stream: audioStream,
  573. track: audioStream.getAudioTracks()[0],
  574. mediaType: MediaType.AUDIO,
  575. videoType: null
  576. });
  577. }
  578. if (videoStream) {
  579. res.push({
  580. stream: videoStream,
  581. track: videoStream.getVideoTracks()[0],
  582. mediaType: MediaType.VIDEO,
  583. videoType: VideoType.CAMERA,
  584. resolution
  585. });
  586. }
  587. return res;
  588. }
  589. /**
  590. * Wraps original attachMediaStream function to set current audio output device
  591. * if this is supported.
  592. * @param {Function} origAttachMediaStream
  593. * @returns {Function}
  594. */
  595. function wrapAttachMediaStream(origAttachMediaStream) {
  596. return function(element, stream) {
  597. // eslint-disable-next-line prefer-rest-params
  598. const res = origAttachMediaStream.apply(rtcUtils, arguments);
  599. if (stream
  600. && rtcUtils.isDeviceChangeAvailable('output')
  601. && stream.getAudioTracks
  602. && stream.getAudioTracks().length
  603. // we skip setting audio output if there was no explicit change
  604. && audioOutputChanged) {
  605. element.setSinkId(rtcUtils.getAudioOutputDevice())
  606. .catch(function(ex) {
  607. const err = new JitsiTrackError(ex, null, [ 'audiooutput' ]);
  608. GlobalOnErrorHandler.callUnhandledRejectionHandler(
  609. { promise: this,
  610. reason: err });
  611. logger.warn('Failed to set audio output device for the '
  612. + 'element. Default audio output device will be used '
  613. + 'instead',
  614. element, err);
  615. });
  616. }
  617. return res;
  618. };
  619. }
  620. /**
  621. * Represents a default implementation of setting a <tt>MediaStream</tt> as the
  622. * source of a video element that tries to be browser-agnostic through feature
  623. * checking. Note though that it was not completely clear from the predating
  624. * browser-specific implementations what &quot;videoSrc&quot; was because one
  625. * implementation of {@link RTCUtils#getVideoSrc} would return
  626. * <tt>MediaStream</tt> (e.g. Firefox), another a <tt>string</tt> representation
  627. * of the <tt>URL</tt> of the <tt>MediaStream</tt> (e.g. Chrome) and the return
  628. * value was only used by {@link RTCUIHelper#getVideoId} which itself did not
  629. * appear to be used anywhere. Generally, the implementation will try to follow
  630. * the related standards i.e. work with the <tt>srcObject</tt> and <tt>src</tt>
  631. * properties of the specified <tt>element</tt> taking into account vender
  632. * prefixes.
  633. *
  634. * @param element the element whose video source/src is to be set to the
  635. * specified <tt>stream</tt>
  636. * @param {MediaStream} stream the <tt>MediaStream</tt> to set as the video
  637. * source/src of <tt>element</tt>
  638. */
  639. function defaultSetVideoSrc(element, stream) {
  640. // srcObject
  641. let srcObjectPropertyName = 'srcObject';
  642. if (!(srcObjectPropertyName in element)) {
  643. srcObjectPropertyName = 'mozSrcObject';
  644. if (!(srcObjectPropertyName in element)) {
  645. srcObjectPropertyName = null;
  646. }
  647. }
  648. if (srcObjectPropertyName) {
  649. element[srcObjectPropertyName] = stream;
  650. return;
  651. }
  652. // src
  653. let src;
  654. if (stream) {
  655. src = stream.jitsiObjectURL;
  656. // Save the created URL for stream so we can reuse it and not keep
  657. // creating URLs.
  658. if (!src) {
  659. stream.jitsiObjectURL
  660. = src
  661. = (URL || webkitURL).createObjectURL(stream);
  662. }
  663. }
  664. element.src = src || '';
  665. }
  666. // Options parameter is to pass config options. Currently uses only "useIPv6".
  667. class RTCUtils extends Listenable {
  668. constructor() {
  669. super(eventEmitter);
  670. }
  671. init(options) {
  672. if (typeof options.disableAEC === 'boolean') {
  673. disableAEC = options.disableAEC;
  674. logger.info(`Disable AEC: ${disableAEC}`);
  675. }
  676. if (typeof options.disableNS === 'boolean') {
  677. disableNS = options.disableNS;
  678. logger.info(`Disable NS: ${disableNS}`);
  679. }
  680. return new Promise((resolve, reject) => {
  681. if (RTCBrowserType.isFirefox()) {
  682. const FFversion = RTCBrowserType.getFirefoxVersion();
  683. if (FFversion < 40) {
  684. rejectWithWebRTCNotSupported(
  685. `Firefox version too old: ${FFversion}.`
  686. + ' Required >= 40.',
  687. reject);
  688. return;
  689. }
  690. this.peerconnection = mozRTCPeerConnection;
  691. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  692. this.enumerateDevices = wrapEnumerateDevices(
  693. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  694. );
  695. this.pc_constraints = {};
  696. this.attachMediaStream = wrapAttachMediaStream((element, stream) => {
  697. // srcObject is being standardized and FF will eventually
  698. // support that unprefixed. FF also supports the
  699. // "element.src = URL.createObjectURL(...)" combo, but that
  700. // will be deprecated in favour of srcObject.
  701. //
  702. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  703. // https://github.com/webrtc/samples/issues/302
  704. if (element) {
  705. defaultSetVideoSrc(element, stream);
  706. if (stream) {
  707. element.play();
  708. }
  709. }
  710. return element;
  711. });
  712. this.getStreamID = function(stream) {
  713. let id = stream.id;
  714. if (!id) {
  715. let tracks = stream.getVideoTracks();
  716. if (!tracks || tracks.length === 0) {
  717. tracks = stream.getAudioTracks();
  718. }
  719. id = tracks[0].id;
  720. }
  721. return SDPUtil.filter_special_chars(id);
  722. };
  723. RTCSessionDescription = mozRTCSessionDescription; // eslint-disable-line
  724. RTCIceCandidate = mozRTCIceCandidate; // eslint-disable-line
  725. } else if (RTCBrowserType.isChrome()
  726. || RTCBrowserType.isOpera()
  727. || RTCBrowserType.isNWJS()
  728. || RTCBrowserType.isElectron()
  729. || RTCBrowserType.isReactNative()) {
  730. this.peerconnection = webkitRTCPeerConnection;
  731. const getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  732. if (navigator.mediaDevices) {
  733. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  734. this.enumerateDevices = wrapEnumerateDevices(
  735. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  736. );
  737. } else {
  738. this.getUserMedia = getUserMedia;
  739. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  740. }
  741. this.attachMediaStream = wrapAttachMediaStream((element, stream) => {
  742. defaultSetVideoSrc(element, stream);
  743. return element;
  744. });
  745. this.getStreamID = function(stream) {
  746. // A. MediaStreams from FF endpoints have the characters '{'
  747. // and '}' that make jQuery choke.
  748. // B. The react-native-webrtc implementation that we use on
  749. // React Native at the time of this writing returns a number
  750. // for the id of MediaStream. Let's just say that a number
  751. // contains no special characters.
  752. const id = stream.id;
  753. // XXX The return statement is affected by automatic
  754. // semicolon insertion (ASI). No line terminator is allowed
  755. // between the return keyword and the expression.
  756. return (
  757. typeof id === 'number'
  758. ? id
  759. : SDPUtil.filter_special_chars(id));
  760. };
  761. this.pc_constraints = { optional: [] };
  762. // Allows sending of video to be suspended if the bandwidth
  763. // estimation is too low.
  764. if (!options.disableSuspendVideo) {
  765. this.pc_constraints.optional.push(
  766. { googSuspendBelowMinBitrate: true });
  767. }
  768. if (options.useIPv6) {
  769. // https://code.google.com/p/webrtc/issues/detail?id=2828
  770. this.pc_constraints.optional.push({ googIPv6: true });
  771. }
  772. if (!webkitMediaStream.prototype.getVideoTracks) {
  773. webkitMediaStream.prototype.getVideoTracks = function() {
  774. return this.videoTracks;
  775. };
  776. }
  777. if (!webkitMediaStream.prototype.getAudioTracks) {
  778. webkitMediaStream.prototype.getAudioTracks = function() {
  779. return this.audioTracks;
  780. };
  781. }
  782. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  783. // Detect IE/Safari
  784. const webRTCReadyCb = () => {
  785. this.peerconnection = RTCPeerConnection;
  786. this.getUserMedia = window.getUserMedia;
  787. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  788. this.attachMediaStream = wrapAttachMediaStream((element, stream) => {
  789. if (stream) {
  790. if (stream.id === 'dummyAudio'
  791. || stream.id === 'dummyVideo') {
  792. return;
  793. }
  794. // The container must be visible in order to play or
  795. // attach the stream when Temasys plugin is in use
  796. const containerSel = $(element);
  797. if (RTCBrowserType.isTemasysPluginUsed()
  798. && !containerSel.is(':visible')) {
  799. containerSel.show();
  800. }
  801. const video = stream.getVideoTracks().length > 0;
  802. if (video && !$(element).is(':visible')) {
  803. throw new Error(
  804. 'video element must be visible to attach'
  805. + ' video stream');
  806. }
  807. }
  808. return attachMediaStream(element, stream);
  809. });
  810. this.getStreamID
  811. = stream => SDPUtil.filter_special_chars(stream.label);
  812. onReady(
  813. options,
  814. this.getUserMediaWithConstraints.bind(this));
  815. };
  816. const webRTCReadyPromise
  817. = new Promise(resolve => AdapterJS.webRTCReady(resolve));
  818. // Resolve or reject depending on whether the Temasys plugin is
  819. // installed.
  820. AdapterJS.WebRTCPlugin.isPluginInstalled(
  821. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  822. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  823. AdapterJS.WebRTCPlugin.pluginInfo.type,
  824. /* installed */ () => {
  825. webRTCReadyPromise.then(() => {
  826. webRTCReadyCb();
  827. resolve();
  828. });
  829. },
  830. /* not installed */ () => {
  831. const error
  832. = new Error('Temasys plugin is not installed');
  833. error.name = 'WEBRTC_NOT_READY';
  834. error.webRTCReadyPromise = webRTCReadyPromise;
  835. reject(error);
  836. });
  837. } else {
  838. rejectWithWebRTCNotSupported(
  839. 'Browser does not appear to be WebRTC-capable',
  840. reject);
  841. return;
  842. }
  843. // Call onReady() if Temasys plugin is not used
  844. if (!RTCBrowserType.isTemasysPluginUsed()) {
  845. onReady(options, this.getUserMediaWithConstraints.bind(this));
  846. resolve();
  847. }
  848. });
  849. }
  850. /**
  851. * @param {string[]} um required user media types
  852. * @param {function} success_callback
  853. * @param {Function} failure_callback
  854. * @param {Object} [options] optional parameters
  855. * @param {string} options.resolution
  856. * @param {number} options.bandwidth
  857. * @param {number} options.fps
  858. * @param {string} options.desktopStream
  859. * @param {string} options.cameraDeviceId
  860. * @param {string} options.micDeviceId
  861. **/
  862. getUserMediaWithConstraints(um, success_callback, failure_callback, options) {
  863. options = options || {};
  864. const constraints = getConstraints(um, options);
  865. logger.info('Get media constraints', constraints);
  866. try {
  867. this.getUserMedia(
  868. constraints,
  869. stream => {
  870. logger.log('onUserMediaSuccess');
  871. setAvailableDevices(um, stream);
  872. success_callback(stream);
  873. },
  874. error => {
  875. setAvailableDevices(um, undefined);
  876. logger.warn('Failed to get access to local media. Error ',
  877. error, constraints);
  878. if (failure_callback) {
  879. failure_callback(
  880. new JitsiTrackError(error, constraints, um));
  881. }
  882. });
  883. } catch (e) {
  884. logger.error('GUM failed: ', e);
  885. if (failure_callback) {
  886. failure_callback(new JitsiTrackError(e, constraints, um));
  887. }
  888. }
  889. }
  890. /**
  891. * Creates the local MediaStreams.
  892. * @param {Object} [options] optional parameters
  893. * @param {Array} options.devices the devices that will be requested
  894. * @param {string} options.resolution resolution constraints
  895. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  896. * type: "audio" or "video", videoType: "camera" or "desktop"}
  897. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  898. * @param {string} options.cameraDeviceId
  899. * @param {string} options.micDeviceId
  900. * @returns {*} Promise object that will receive the new JitsiTracks
  901. */
  902. obtainAudioAndVideoPermissions(options) {
  903. const self = this;
  904. options = options || {};
  905. const dsOptions = options.desktopSharingExtensionExternalInstallation;
  906. return new Promise((resolve, reject) => {
  907. const successCallback = function(stream) {
  908. resolve(handleLocalStream(stream, options.resolution));
  909. };
  910. options.devices = options.devices || [ 'audio', 'video' ];
  911. if (!screenObtainer.isSupported()
  912. && options.devices.indexOf('desktop') !== -1) {
  913. reject(new Error('Desktop sharing is not supported!'));
  914. }
  915. if (RTCBrowserType.isFirefox()
  916. // XXX The react-native-webrtc implementation that we
  917. // utilize on React Native at the time of this writing does
  918. // not support the MediaStream constructors defined by
  919. // https://www.w3.org/TR/mediacapture-streams/#constructors
  920. // and instead has a single constructor which expects (an
  921. // NSNumber as) a MediaStream ID.
  922. || RTCBrowserType.isReactNative()
  923. || RTCBrowserType.isTemasysPluginUsed()) {
  924. const GUM = function(device, s, e) {
  925. this.getUserMediaWithConstraints(device, s, e, options);
  926. };
  927. const deviceGUM = {
  928. 'audio': GUM.bind(self, [ 'audio' ]),
  929. 'video': GUM.bind(self, [ 'video' ])
  930. };
  931. if (screenObtainer.isSupported()) {
  932. deviceGUM.desktop = screenObtainer.obtainStream.bind(
  933. screenObtainer,
  934. dsOptions);
  935. }
  936. // With FF/IE we can't split the stream into audio and video because FF
  937. // doesn't support media stream constructors. So, we need to get the
  938. // audio stream separately from the video stream using two distinct GUM
  939. // calls. Not very user friendly :-( but we don't have many other
  940. // options neither.
  941. //
  942. // Note that we pack those 2 streams in a single object and pass it to
  943. // the successCallback method.
  944. obtainDevices({
  945. devices: options.devices,
  946. streams: [],
  947. successCallback,
  948. errorCallback: reject,
  949. deviceGUM
  950. });
  951. } else {
  952. const hasDesktop = options.devices.indexOf('desktop') > -1;
  953. if (hasDesktop) {
  954. options.devices.splice(options.devices.indexOf('desktop'), 1);
  955. }
  956. options.resolution = options.resolution || '360';
  957. if (options.devices.length) {
  958. this.getUserMediaWithConstraints(
  959. options.devices,
  960. stream => {
  961. const audioDeviceRequested
  962. = options.devices.indexOf('audio') !== -1;
  963. const videoDeviceRequested
  964. = options.devices.indexOf('video') !== -1;
  965. const audioTracksReceived
  966. = stream.getAudioTracks().length > 0;
  967. const videoTracksReceived
  968. = stream.getVideoTracks().length > 0;
  969. if ((audioDeviceRequested && !audioTracksReceived)
  970. || (videoDeviceRequested && !videoTracksReceived)) {
  971. self.stopMediaStream(stream);
  972. // We are getting here in case if we requested
  973. // 'audio' or 'video' devices or both, but
  974. // didn't get corresponding MediaStreamTrack in
  975. // response stream. We don't know the reason why
  976. // this happened, so reject with general error.
  977. const devices = [];
  978. if (audioDeviceRequested && !audioTracksReceived) {
  979. devices.push('audio');
  980. }
  981. if (videoDeviceRequested && !videoTracksReceived) {
  982. devices.push('video');
  983. }
  984. // we are missing one of the media we requested
  985. // in order to get the actual error that caused
  986. // this missing media we will call one more time
  987. // getUserMedia so we can obtain the actual
  988. // error (Example usecases are requesting
  989. // audio and video and video device is missing
  990. // or device is denied to be used and chrome is
  991. // set to not ask for permissions)
  992. self.getUserMediaWithConstraints(
  993. devices,
  994. () => {
  995. // we already failed to obtain this
  996. // media, so we are not supposed in any
  997. // way to receive success for this call
  998. // any way we will throw an error to be
  999. // sure the promise will finish
  1000. reject(new JitsiTrackError(
  1001. { name: 'UnknownError' },
  1002. getConstraints(
  1003. options.devices, options),
  1004. devices)
  1005. );
  1006. },
  1007. error => {
  1008. // rejects with real error for not
  1009. // obtaining the media
  1010. reject(error);
  1011. }, options);
  1012. return;
  1013. }
  1014. if (hasDesktop) {
  1015. screenObtainer.obtainStream(
  1016. dsOptions,
  1017. desktopStream => {
  1018. successCallback({ audioVideo: stream,
  1019. desktopStream });
  1020. }, error => {
  1021. self.stopMediaStream(stream);
  1022. reject(error);
  1023. });
  1024. } else {
  1025. successCallback({ audioVideo: stream });
  1026. }
  1027. },
  1028. error => reject(error),
  1029. options);
  1030. } else if (hasDesktop) {
  1031. screenObtainer.obtainStream(
  1032. dsOptions,
  1033. stream => successCallback({ desktopStream: stream }),
  1034. error => reject(error));
  1035. }
  1036. }
  1037. });
  1038. }
  1039. getDeviceAvailability() {
  1040. return devices;
  1041. }
  1042. isRTCReady() {
  1043. return rtcReady;
  1044. }
  1045. _isDeviceListAvailable() {
  1046. if (!rtcReady) {
  1047. throw new Error('WebRTC not ready yet');
  1048. }
  1049. return Boolean(navigator.mediaDevices
  1050. && navigator.mediaDevices.enumerateDevices
  1051. && typeof MediaStreamTrack !== 'undefined'
  1052. && MediaStreamTrack.getSources);
  1053. }
  1054. /**
  1055. * Returns a promise which can be used to make sure that the WebRTC stack
  1056. * has been initialized.
  1057. *
  1058. * @returns {Promise} which is resolved only if the WebRTC stack is ready.
  1059. * Note that currently we do not detect stack initialization failure and
  1060. * the promise is never rejected(unless unexpected error occurs).
  1061. */
  1062. onRTCReady() {
  1063. if (rtcReady) {
  1064. return Promise.resolve();
  1065. }
  1066. return new Promise(resolve => {
  1067. const listener = () => {
  1068. eventEmitter.removeListener(RTCEvents.RTC_READY, listener);
  1069. resolve();
  1070. };
  1071. eventEmitter.addListener(RTCEvents.RTC_READY, listener);
  1072. // We have no failed event, so... it either resolves or nothing
  1073. // happens
  1074. });
  1075. }
  1076. /**
  1077. * Checks if its possible to enumerate available cameras/microphones.
  1078. *
  1079. * @returns {Promise<boolean>} a Promise which will be resolved only once
  1080. * the WebRTC stack is ready, either with true if the device listing is
  1081. * available available or with false otherwise.
  1082. */
  1083. isDeviceListAvailable() {
  1084. return this.onRTCReady().then(this._isDeviceListAvailable.bind(this));
  1085. }
  1086. /**
  1087. * Returns true if changing the input (camera / microphone) or output
  1088. * (audio) device is supported and false if not.
  1089. * @params {string} [deviceType] - type of device to change. Default is
  1090. * undefined or 'input', 'output' - for audio output device change.
  1091. * @returns {boolean} true if available, false otherwise.
  1092. */
  1093. isDeviceChangeAvailable(deviceType) {
  1094. return deviceType === 'output' || deviceType === 'audiooutput'
  1095. ? isAudioOutputDeviceChangeAvailable
  1096. : RTCBrowserType.isChrome()
  1097. || RTCBrowserType.isFirefox()
  1098. || RTCBrowserType.isOpera()
  1099. || RTCBrowserType.isTemasysPluginUsed()
  1100. || RTCBrowserType.isNWJS()
  1101. || RTCBrowserType.isElectron();
  1102. }
  1103. /**
  1104. * A method to handle stopping of the stream.
  1105. * One point to handle the differences in various implementations.
  1106. * @param mediaStream MediaStream object to stop.
  1107. */
  1108. stopMediaStream(mediaStream) {
  1109. mediaStream.getTracks().forEach(track => {
  1110. // stop() not supported with IE
  1111. if (!RTCBrowserType.isTemasysPluginUsed() && track.stop) {
  1112. track.stop();
  1113. }
  1114. });
  1115. // leave stop for implementation still using it
  1116. if (mediaStream.stop) {
  1117. mediaStream.stop();
  1118. }
  1119. // The MediaStream implementation of the react-native-webrtc project has
  1120. // an explicit release method that is to be invoked in order to release
  1121. // used resources such as memory.
  1122. if (mediaStream.release) {
  1123. mediaStream.release();
  1124. }
  1125. // if we have done createObjectURL, lets clean it
  1126. const url = mediaStream.jitsiObjectURL;
  1127. if (url) {
  1128. delete mediaStream.jitsiObjectURL;
  1129. (URL || webkitURL).revokeObjectURL(url);
  1130. }
  1131. }
  1132. /**
  1133. * Returns whether the desktop sharing is enabled or not.
  1134. * @returns {boolean}
  1135. */
  1136. isDesktopSharingEnabled() {
  1137. return screenObtainer.isSupported();
  1138. }
  1139. /**
  1140. * Sets current audio output device.
  1141. * @param {string} deviceId - id of 'audiooutput' device from
  1142. * navigator.mediaDevices.enumerateDevices(), 'default' for default
  1143. * device
  1144. * @returns {Promise} - resolves when audio output is changed, is rejected
  1145. * otherwise
  1146. */
  1147. setAudioOutputDevice(deviceId) {
  1148. if (!this.isDeviceChangeAvailable('output')) {
  1149. Promise.reject(
  1150. new Error('Audio output device change is not supported'));
  1151. }
  1152. return featureDetectionAudioEl.setSinkId(deviceId)
  1153. .then(() => {
  1154. audioOutputDeviceId = deviceId;
  1155. audioOutputChanged = true;
  1156. logger.log(`Audio output device set to ${deviceId}`);
  1157. eventEmitter.emit(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1158. deviceId);
  1159. });
  1160. }
  1161. /**
  1162. * Returns currently used audio output device id, '' stands for default
  1163. * device
  1164. * @returns {string}
  1165. */
  1166. getAudioOutputDevice() {
  1167. return audioOutputDeviceId;
  1168. }
  1169. /**
  1170. * Returns list of available media devices if its obtained, otherwise an
  1171. * empty array is returned/
  1172. * @returns {Array} list of available media devices.
  1173. */
  1174. getCurrentlyAvailableMediaDevices() {
  1175. return currentlyAvailableMediaDevices;
  1176. }
  1177. /**
  1178. * Returns event data for device to be reported to stats.
  1179. * @returns {MediaDeviceInfo} device.
  1180. */
  1181. getEventDataForActiveDevice(device) {
  1182. const devices = [];
  1183. const deviceData = {
  1184. 'deviceId': device.deviceId,
  1185. 'kind': device.kind,
  1186. 'label': device.label,
  1187. 'groupId': device.groupId
  1188. };
  1189. devices.push(deviceData);
  1190. return { deviceList: devices };
  1191. }
  1192. }
  1193. /**
  1194. * Rejects a Promise because WebRTC is not supported.
  1195. *
  1196. * @param {string} errorMessage - The human-readable message of the Error which
  1197. * is the reason for the rejection.
  1198. * @param {Function} reject - The reject function of the Promise.
  1199. * @returns {void}
  1200. */
  1201. function rejectWithWebRTCNotSupported(errorMessage, reject) {
  1202. const error = new Error(errorMessage);
  1203. // WebRTC is not supported either natively or via a known plugin such as
  1204. // Temasys.
  1205. // XXX The Error class already has a property name which is commonly used to
  1206. // detail the represented error in a non-human-readable way (in contrast to
  1207. // the human-readable property message). I explicitly did not want to
  1208. // introduce a new specific property.
  1209. // FIXME None of the existing JitsiXXXErrors seemed to be appropriate
  1210. // recipients of the constant WEBRTC_NOT_SUPPORTED so I explicitly chose to
  1211. // leave it as a magic string at the time of this writing.
  1212. error.name = 'WEBRTC_NOT_SUPPORTED';
  1213. logger.error(errorMessage);
  1214. reject(error);
  1215. }
  1216. const rtcUtils = new RTCUtils();
  1217. export default rtcUtils;