Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

RTCUtils.js 50KB

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