Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

RTCUtils.js 50KB

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