You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RTCUtils.js 51KB

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