Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

RTCUtils.js 50KB

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