您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

RTCUtils.js 50KB

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