You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RTCUtils.js 51KB

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