Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

RTCUtils.js 52KB

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