Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

RTCUtils.js 51KB

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