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

RTCUtils.js 52KB

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