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

RTCUtils.js 50KB

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