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 50KB

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