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.

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