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

RTCUtils.js 52KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417
  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(ds => {
  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 = ds.slice(0);
  347. } else if (compareAvailableMediaDevices(ds)) {
  348. onMediaDevicesListChanged(ds);
  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. /**
  387. * Apply function with arguments if function exists.
  388. * Do nothing if function not provided.
  389. * @param {function} [fn] function to apply
  390. * @param {Array} [args=[]] arguments for function
  391. */
  392. function maybeApply(fn, args) {
  393. fn && fn(...args);
  394. }
  395. const getUserMediaStatus = {
  396. initialized: false,
  397. callbacks: []
  398. };
  399. /**
  400. * Wrap `getUserMedia` to allow others to know if it was executed at least
  401. * once or not. Wrapper function uses `getUserMediaStatus` object.
  402. * @param {Function} getUserMedia native function
  403. * @returns {Function} wrapped function
  404. */
  405. function wrapGetUserMedia(getUserMedia) {
  406. return function(constraints, successCallback, errorCallback) {
  407. getUserMedia(constraints, stream => {
  408. maybeApply(successCallback, [ stream ]);
  409. if (!getUserMediaStatus.initialized) {
  410. getUserMediaStatus.initialized = true;
  411. getUserMediaStatus.callbacks.forEach(callback => callback());
  412. getUserMediaStatus.callbacks.length = 0;
  413. }
  414. }, error => {
  415. maybeApply(errorCallback, [ error ]);
  416. });
  417. };
  418. }
  419. /**
  420. * Execute function after getUserMedia was executed at least once.
  421. * @param {Function} callback function to execute after getUserMedia
  422. */
  423. function afterUserMediaInitialized(callback) {
  424. if (getUserMediaStatus.initialized) {
  425. callback();
  426. } else {
  427. getUserMediaStatus.callbacks.push(callback);
  428. }
  429. }
  430. /**
  431. * Wrapper function which makes enumerateDevices to wait
  432. * until someone executes getUserMedia first time.
  433. * @param {Function} enumerateDevices native function
  434. * @returns {Funtion} wrapped function
  435. */
  436. function wrapEnumerateDevices(enumerateDevices) {
  437. return function(callback) {
  438. // enumerate devices only after initial getUserMedia
  439. afterUserMediaInitialized(() => {
  440. enumerateDevices().then(callback, err => {
  441. logger.error('cannot enumerate devices: ', err);
  442. callback([]);
  443. });
  444. });
  445. };
  446. }
  447. /**
  448. * Use old MediaStreamTrack to get devices list and
  449. * convert it to enumerateDevices format.
  450. * @param {Function} callback function to call when received devices list.
  451. */
  452. function enumerateDevicesThroughMediaStreamTrack(callback) {
  453. MediaStreamTrack.getSources(
  454. sources => callback(sources.map(convertMediaStreamTrackSource)));
  455. }
  456. /**
  457. * Converts MediaStreamTrack Source to enumerateDevices format.
  458. * @param {Object} source
  459. */
  460. function convertMediaStreamTrackSource(source) {
  461. const kind = (source.kind || '').toLowerCase();
  462. return {
  463. facing: source.facing || null,
  464. label: source.label,
  465. // theoretically deprecated MediaStreamTrack.getSources should
  466. // not return 'audiooutput' devices but let's handle it in any
  467. // case
  468. kind: kind
  469. ? kind === 'audiooutput' ? kind : `${kind}input`
  470. : null,
  471. deviceId: source.id,
  472. groupId: source.groupId || null
  473. };
  474. }
  475. /**
  476. * Handles the newly created Media Streams.
  477. * @param streams the new Media Streams
  478. * @param resolution the resolution of the video streams
  479. * @returns {*[]} object that describes the new streams
  480. */
  481. function handleLocalStream(streams, resolution) {
  482. let audioStream, desktopStream, videoStream;
  483. const res = [];
  484. // XXX The function obtainAudioAndVideoPermissions has examined the type of
  485. // the browser, its capabilities, etc. and has taken the decision whether to
  486. // invoke getUserMedia per device (e.g. Firefox) or once for both audio and
  487. // video (e.g. Chrome). In order to not duplicate the logic here, examine
  488. // the specified streams and figure out what we've received based on
  489. // obtainAudioAndVideoPermissions' decision.
  490. if (streams) {
  491. // As mentioned above, certian types of browser (e.g. Chrome) support
  492. // (with a result which meets our requirements expressed bellow) calling
  493. // getUserMedia once for both audio and video.
  494. const audioVideo = streams.audioVideo;
  495. if (audioVideo) {
  496. const audioTracks = audioVideo.getAudioTracks();
  497. if (audioTracks.length) {
  498. // eslint-disable-next-line new-cap
  499. audioStream = new webkitMediaStream();
  500. for (let i = 0; i < audioTracks.length; i++) {
  501. audioStream.addTrack(audioTracks[i]);
  502. }
  503. }
  504. const videoTracks = audioVideo.getVideoTracks();
  505. if (videoTracks.length) {
  506. // eslint-disable-next-line new-cap
  507. videoStream = new webkitMediaStream();
  508. for (let j = 0; j < videoTracks.length; j++) {
  509. videoStream.addTrack(videoTracks[j]);
  510. }
  511. }
  512. } else {
  513. // On other types of browser (e.g. Firefox) we choose (namely,
  514. // obtainAudioAndVideoPermissions) to call getUsermedia per device
  515. // (type).
  516. audioStream = streams.audio;
  517. videoStream = streams.video;
  518. }
  519. // Again, different choices on different types of browser.
  520. desktopStream = streams.desktopStream || streams.desktop;
  521. }
  522. if (desktopStream) {
  523. res.push({
  524. stream: desktopStream,
  525. track: desktopStream.getVideoTracks()[0],
  526. mediaType: MediaType.VIDEO,
  527. videoType: VideoType.DESKTOP
  528. });
  529. }
  530. if (audioStream) {
  531. res.push({
  532. stream: audioStream,
  533. track: audioStream.getAudioTracks()[0],
  534. mediaType: MediaType.AUDIO,
  535. videoType: null
  536. });
  537. }
  538. if (videoStream) {
  539. res.push({
  540. stream: videoStream,
  541. track: videoStream.getVideoTracks()[0],
  542. mediaType: MediaType.VIDEO,
  543. videoType: VideoType.CAMERA,
  544. resolution
  545. });
  546. }
  547. return res;
  548. }
  549. /**
  550. * Represents a default implementation of setting a <tt>MediaStream</tt> as the
  551. * source of a video element that tries to be browser-agnostic through feature
  552. * checking. Note though that it was not completely clear from the predating
  553. * browser-specific implementations what &quot;videoSrc&quot; was because one
  554. * implementation of {@link RTCUtils#getVideoSrc} would return
  555. * <tt>MediaStream</tt> (e.g. Firefox), another a <tt>string</tt> representation
  556. * of the <tt>URL</tt> of the <tt>MediaStream</tt> (e.g. Chrome) and the return
  557. * value was only used by {@link RTCUIHelper#getVideoId} which itself did not
  558. * appear to be used anywhere. Generally, the implementation will try to follow
  559. * the related standards i.e. work with the <tt>srcObject</tt> and <tt>src</tt>
  560. * properties of the specified <tt>element</tt> taking into account vender
  561. * prefixes.
  562. *
  563. * @param element the element whose video source/src is to be set to the
  564. * specified <tt>stream</tt>
  565. * @param {MediaStream} stream the <tt>MediaStream</tt> to set as the video
  566. * source/src of <tt>element</tt>
  567. */
  568. function defaultSetVideoSrc(element, stream) {
  569. // srcObject
  570. let srcObjectPropertyName = 'srcObject';
  571. if (!(srcObjectPropertyName in element)) {
  572. srcObjectPropertyName = 'mozSrcObject';
  573. if (!(srcObjectPropertyName in element)) {
  574. srcObjectPropertyName = null;
  575. }
  576. }
  577. if (srcObjectPropertyName) {
  578. element[srcObjectPropertyName] = stream;
  579. return;
  580. }
  581. // src
  582. let src;
  583. if (stream) {
  584. src = stream.jitsiObjectURL;
  585. // Save the created URL for stream so we can reuse it and not keep
  586. // creating URLs.
  587. if (!src) {
  588. stream.jitsiObjectURL
  589. = src
  590. = (URL || webkitURL).createObjectURL(stream);
  591. }
  592. }
  593. element.src = src || '';
  594. }
  595. // Options parameter is to pass config options. Currently uses only "useIPv6".
  596. class RTCUtils extends Listenable {
  597. constructor() {
  598. super(eventEmitter);
  599. }
  600. init(options) {
  601. if (typeof options.disableAEC === 'boolean') {
  602. disableAEC = options.disableAEC;
  603. logger.info(`Disable AEC: ${disableAEC}`);
  604. }
  605. if (typeof options.disableNS === 'boolean') {
  606. disableNS = options.disableNS;
  607. logger.info(`Disable NS: ${disableNS}`);
  608. }
  609. return new Promise((resolve, reject) => {
  610. if (RTCBrowserType.isFirefox()) {
  611. const FFversion = RTCBrowserType.getFirefoxVersion();
  612. if (FFversion < 40) {
  613. rejectWithWebRTCNotSupported(
  614. `Firefox version too old: ${FFversion}.`
  615. + ' Required >= 40.',
  616. reject);
  617. return;
  618. }
  619. this.peerconnection = mozRTCPeerConnection;
  620. this.getUserMedia
  621. = wrapGetUserMedia(
  622. navigator.mozGetUserMedia.bind(navigator));
  623. this.enumerateDevices
  624. = wrapEnumerateDevices(
  625. navigator.mediaDevices.enumerateDevices.bind(
  626. navigator.mediaDevices));
  627. this.pcConstraints = {};
  628. this.attachMediaStream
  629. = wrapAttachMediaStream((element, stream) => {
  630. // srcObject is being standardized and FF will
  631. // eventually support that unprefixed. FF also supports
  632. // the "element.src = URL.createObjectURL(...)" combo,
  633. // but that will be deprecated in favour of srcObject.
  634. //
  635. // https://groups.google.com/forum/#!topic/
  636. // mozilla.dev.media/pKOiioXonJg
  637. // https://github.com/webrtc/samples/issues/302
  638. if (element) {
  639. defaultSetVideoSrc(element, stream);
  640. if (stream) {
  641. element.play();
  642. }
  643. }
  644. return element;
  645. });
  646. this.getStreamID = function(stream) {
  647. let id = stream.id;
  648. if (!id) {
  649. let tracks = stream.getVideoTracks();
  650. if (!tracks || tracks.length === 0) {
  651. tracks = stream.getAudioTracks();
  652. }
  653. id = tracks[0].id;
  654. }
  655. return SDPUtil.filterSpecialChars(id);
  656. };
  657. /* eslint-disable no-global-assign, no-native-reassign */
  658. RTCSessionDescription = mozRTCSessionDescription;
  659. RTCIceCandidate = mozRTCIceCandidate;
  660. /* eslint-enable no-global-assign, no-native-reassign */
  661. } else if (RTCBrowserType.isChrome()
  662. || RTCBrowserType.isOpera()
  663. || RTCBrowserType.isNWJS()
  664. || RTCBrowserType.isElectron()
  665. || RTCBrowserType.isReactNative()) {
  666. this.peerconnection = webkitRTCPeerConnection;
  667. const getUserMedia
  668. = navigator.webkitGetUserMedia.bind(navigator);
  669. if (navigator.mediaDevices) {
  670. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  671. this.enumerateDevices
  672. = wrapEnumerateDevices(
  673. navigator.mediaDevices.enumerateDevices.bind(
  674. navigator.mediaDevices));
  675. } else {
  676. this.getUserMedia = getUserMedia;
  677. this.enumerateDevices
  678. = enumerateDevicesThroughMediaStreamTrack;
  679. }
  680. this.attachMediaStream
  681. = wrapAttachMediaStream((element, stream) => {
  682. defaultSetVideoSrc(element, stream);
  683. return element;
  684. });
  685. this.getStreamID = function(stream) {
  686. // A. MediaStreams from FF endpoints have the characters '{'
  687. // and '}' that make jQuery choke.
  688. // B. The react-native-webrtc implementation that we use on
  689. // React Native at the time of this writing returns a number
  690. // for the id of MediaStream. Let's just say that a number
  691. // contains no special characters.
  692. const id = stream.id;
  693. // XXX The return statement is affected by automatic
  694. // semicolon insertion (ASI). No line terminator is allowed
  695. // between the return keyword and the expression.
  696. return (
  697. typeof id === 'number'
  698. ? id
  699. : SDPUtil.filterSpecialChars(id));
  700. };
  701. this.pcConstraints = { optional: [] };
  702. // Allows sending of video to be suspended if the bandwidth
  703. // estimation is too low.
  704. if (!options.disableSuspendVideo) {
  705. this.pcConstraints.optional.push(
  706. { googSuspendBelowMinBitrate: true });
  707. }
  708. if (options.useIPv6) {
  709. // https://code.google.com/p/webrtc/issues/detail?id=2828
  710. this.pcConstraints.optional.push({ googIPv6: true });
  711. }
  712. if (!webkitMediaStream.prototype.getVideoTracks) {
  713. webkitMediaStream.prototype.getVideoTracks = function() {
  714. return this.videoTracks;
  715. };
  716. }
  717. if (!webkitMediaStream.prototype.getAudioTracks) {
  718. webkitMediaStream.prototype.getAudioTracks = function() {
  719. return this.audioTracks;
  720. };
  721. }
  722. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  723. // Detect IE/Safari
  724. const webRTCReadyCb = () => {
  725. this.peerconnection = RTCPeerConnection;
  726. this.getUserMedia = window.getUserMedia;
  727. this.enumerateDevices
  728. = enumerateDevicesThroughMediaStreamTrack;
  729. this.attachMediaStream
  730. = wrapAttachMediaStream((element, stream) => {
  731. if (stream) {
  732. if (stream.id === 'dummyAudio'
  733. || stream.id === 'dummyVideo') {
  734. return;
  735. }
  736. // The container must be visible in order to
  737. // play or attach the stream when Temasys plugin
  738. // is in use
  739. const containerSel = $(element);
  740. if (RTCBrowserType.isTemasysPluginUsed()
  741. && !containerSel.is(':visible')) {
  742. containerSel.show();
  743. }
  744. const video
  745. = stream.getVideoTracks().length > 0;
  746. if (video && !$(element).is(':visible')) {
  747. throw new Error(
  748. 'video element must be visible to'
  749. + ' attach video stream');
  750. }
  751. }
  752. return attachMediaStream(element, stream);
  753. });
  754. this.getStreamID
  755. = stream => SDPUtil.filterSpecialChars(stream.label);
  756. onReady(
  757. options,
  758. this.getUserMediaWithConstraints.bind(this));
  759. };
  760. const webRTCReadyPromise
  761. = new Promise(r => AdapterJS.webRTCReady(r));
  762. // Resolve or reject depending on whether the Temasys plugin is
  763. // installed.
  764. AdapterJS.WebRTCPlugin.isPluginInstalled(
  765. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  766. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  767. AdapterJS.WebRTCPlugin.pluginInfo.type,
  768. /* installed */ () => {
  769. webRTCReadyPromise.then(() => {
  770. webRTCReadyCb();
  771. resolve();
  772. });
  773. },
  774. /* not installed */ () => {
  775. const error
  776. = new Error('Temasys plugin is not installed');
  777. error.name = 'WEBRTC_NOT_READY';
  778. error.webRTCReadyPromise = webRTCReadyPromise;
  779. reject(error);
  780. });
  781. } else {
  782. rejectWithWebRTCNotSupported(
  783. 'Browser does not appear to be WebRTC-capable',
  784. reject);
  785. return;
  786. }
  787. // Call onReady() if Temasys plugin is not used
  788. if (!RTCBrowserType.isTemasysPluginUsed()) {
  789. onReady(options, this.getUserMediaWithConstraints.bind(this));
  790. resolve();
  791. }
  792. });
  793. }
  794. /**
  795. * @param {string[]} um required user media types
  796. * @param {function} successCallback
  797. * @param {Function} failureCallback
  798. * @param {Object} [options] optional parameters
  799. * @param {string} options.resolution
  800. * @param {number} options.bandwidth
  801. * @param {number} options.fps
  802. * @param {string} options.desktopStream
  803. * @param {string} options.cameraDeviceId
  804. * @param {string} options.micDeviceId
  805. **/
  806. getUserMediaWithConstraints(
  807. um,
  808. successCallback,
  809. failureCallback,
  810. options = {}) {
  811. const constraints = getConstraints(um, options);
  812. logger.info('Get media constraints', constraints);
  813. try {
  814. this.getUserMedia(
  815. constraints,
  816. stream => {
  817. logger.log('onUserMediaSuccess');
  818. setAvailableDevices(um, stream);
  819. successCallback(stream);
  820. },
  821. error => {
  822. setAvailableDevices(um, undefined);
  823. logger.warn('Failed to get access to local media. Error ',
  824. error, constraints);
  825. if (failureCallback) {
  826. failureCallback(
  827. new JitsiTrackError(error, constraints, um));
  828. }
  829. });
  830. } catch (e) {
  831. logger.error('GUM failed: ', e);
  832. if (failureCallback) {
  833. failureCallback(new JitsiTrackError(e, constraints, um));
  834. }
  835. }
  836. }
  837. /**
  838. * Creates the local MediaStreams.
  839. * @param {Object} [options] optional parameters
  840. * @param {Array} options.devices the devices that will be requested
  841. * @param {string} options.resolution resolution constraints
  842. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with
  843. * the following structure {stream: the Media Stream, type: "audio" or
  844. * "video", videoType: "camera" or "desktop"} will be returned trough the
  845. * Promise, otherwise JitsiTrack objects will be returned.
  846. * @param {string} options.cameraDeviceId
  847. * @param {string} options.micDeviceId
  848. * @returns {*} Promise object that will receive the new JitsiTracks
  849. */
  850. obtainAudioAndVideoPermissions(options = {}) {
  851. const self = this;
  852. const dsOptions = options.desktopSharingExtensionExternalInstallation;
  853. return new Promise((resolve, reject) => {
  854. const successCallback = function(stream) {
  855. resolve(handleLocalStream(stream, options.resolution));
  856. };
  857. options.devices = options.devices || [ 'audio', 'video' ];
  858. if (!screenObtainer.isSupported()
  859. && options.devices.indexOf('desktop') !== -1) {
  860. reject(new Error('Desktop sharing is not supported!'));
  861. }
  862. if (RTCBrowserType.isFirefox()
  863. // XXX The react-native-webrtc implementation that we
  864. // utilize on React Native at the time of this writing does
  865. // not support the MediaStream constructors defined by
  866. // https://www.w3.org/TR/mediacapture-streams/#constructors
  867. // and instead has a single constructor which expects (an
  868. // NSNumber as) a MediaStream ID.
  869. || RTCBrowserType.isReactNative()
  870. || RTCBrowserType.isTemasysPluginUsed()) {
  871. const GUM = function(device, s, e) {
  872. this.getUserMediaWithConstraints(device, s, e, options);
  873. };
  874. const deviceGUM = {
  875. 'audio': GUM.bind(self, [ 'audio' ]),
  876. 'video': GUM.bind(self, [ 'video' ])
  877. };
  878. if (screenObtainer.isSupported()) {
  879. deviceGUM.desktop = screenObtainer.obtainStream.bind(
  880. screenObtainer,
  881. dsOptions);
  882. }
  883. // With FF/IE we can't split the stream into audio and video
  884. // because FF doesn't support media stream constructors. So, we
  885. // need to get the audio stream separately from the video stream
  886. // using two distinct GUM calls. Not very user friendly :-( but
  887. // we don't have many other options neither.
  888. //
  889. // Note that we pack those 2 streams in a single object and pass
  890. // it to the successCallback method.
  891. obtainDevices({
  892. devices: options.devices,
  893. streams: [],
  894. successCallback,
  895. errorCallback: reject,
  896. deviceGUM
  897. });
  898. } else {
  899. const hasDesktop = options.devices.indexOf('desktop') > -1;
  900. if (hasDesktop) {
  901. options.devices.splice(
  902. options.devices.indexOf('desktop'),
  903. 1);
  904. }
  905. options.resolution = options.resolution || '360';
  906. if (options.devices.length) {
  907. this.getUserMediaWithConstraints(
  908. options.devices,
  909. stream => {
  910. const audioDeviceRequested
  911. = options.devices.indexOf('audio') !== -1;
  912. const videoDeviceRequested
  913. = options.devices.indexOf('video') !== -1;
  914. const audioTracksReceived
  915. = stream.getAudioTracks().length > 0;
  916. const videoTracksReceived
  917. = stream.getVideoTracks().length > 0;
  918. if ((audioDeviceRequested && !audioTracksReceived)
  919. || (videoDeviceRequested
  920. && !videoTracksReceived)) {
  921. self.stopMediaStream(stream);
  922. // We are getting here in case if we requested
  923. // 'audio' or 'video' devices or both, but
  924. // didn't get corresponding MediaStreamTrack in
  925. // response stream. We don't know the reason why
  926. // this happened, so reject with general error.
  927. // eslint-disable-next-line no-shadow
  928. const devices = [];
  929. if (audioDeviceRequested
  930. && !audioTracksReceived) {
  931. devices.push('audio');
  932. }
  933. if (videoDeviceRequested
  934. && !videoTracksReceived) {
  935. devices.push('video');
  936. }
  937. // we are missing one of the media we requested
  938. // in order to get the actual error that caused
  939. // this missing media we will call one more time
  940. // getUserMedia so we can obtain the actual
  941. // error (Example usecases are requesting
  942. // audio and video and video device is missing
  943. // or device is denied to be used and chrome is
  944. // set to not ask for permissions)
  945. self.getUserMediaWithConstraints(
  946. devices,
  947. () => {
  948. // we already failed to obtain this
  949. // media, so we are not supposed in any
  950. // way to receive success for this call
  951. // any way we will throw an error to be
  952. // sure the promise will finish
  953. reject(new JitsiTrackError(
  954. { name: 'UnknownError' },
  955. getConstraints(
  956. options.devices,
  957. options),
  958. devices)
  959. );
  960. },
  961. error => {
  962. // rejects with real error for not
  963. // obtaining the media
  964. reject(error);
  965. }, options);
  966. return;
  967. }
  968. if (hasDesktop) {
  969. screenObtainer.obtainStream(
  970. dsOptions,
  971. desktopStream => {
  972. successCallback({ audioVideo: stream,
  973. desktopStream });
  974. }, error => {
  975. self.stopMediaStream(stream);
  976. reject(error);
  977. });
  978. } else {
  979. successCallback({ audioVideo: stream });
  980. }
  981. },
  982. error => reject(error),
  983. options);
  984. } else if (hasDesktop) {
  985. screenObtainer.obtainStream(
  986. dsOptions,
  987. stream => successCallback({ desktopStream: stream }),
  988. error => reject(error));
  989. }
  990. }
  991. });
  992. }
  993. getDeviceAvailability() {
  994. return devices;
  995. }
  996. isRTCReady() {
  997. return rtcReady;
  998. }
  999. _isDeviceListAvailable() {
  1000. if (!rtcReady) {
  1001. throw new Error('WebRTC not ready yet');
  1002. }
  1003. return Boolean(navigator.mediaDevices
  1004. && navigator.mediaDevices.enumerateDevices
  1005. && typeof MediaStreamTrack !== 'undefined'
  1006. && MediaStreamTrack.getSources);
  1007. }
  1008. /**
  1009. * Returns a promise which can be used to make sure that the WebRTC stack
  1010. * has been initialized.
  1011. *
  1012. * @returns {Promise} which is resolved only if the WebRTC stack is ready.
  1013. * Note that currently we do not detect stack initialization failure and
  1014. * the promise is never rejected(unless unexpected error occurs).
  1015. */
  1016. onRTCReady() {
  1017. if (rtcReady) {
  1018. return Promise.resolve();
  1019. }
  1020. return new Promise(resolve => {
  1021. const listener = () => {
  1022. eventEmitter.removeListener(RTCEvents.RTC_READY, listener);
  1023. resolve();
  1024. };
  1025. eventEmitter.addListener(RTCEvents.RTC_READY, listener);
  1026. // We have no failed event, so... it either resolves or nothing
  1027. // happens
  1028. });
  1029. }
  1030. /**
  1031. * Checks if its possible to enumerate available cameras/microphones.
  1032. *
  1033. * @returns {Promise<boolean>} a Promise which will be resolved only once
  1034. * the WebRTC stack is ready, either with true if the device listing is
  1035. * available available or with false otherwise.
  1036. */
  1037. isDeviceListAvailable() {
  1038. return this.onRTCReady().then(this._isDeviceListAvailable.bind(this));
  1039. }
  1040. /**
  1041. * Returns true if changing the input (camera / microphone) or output
  1042. * (audio) device is supported and false if not.
  1043. * @params {string} [deviceType] - type of device to change. Default is
  1044. * undefined or 'input', 'output' - for audio output device change.
  1045. * @returns {boolean} true if available, false otherwise.
  1046. */
  1047. isDeviceChangeAvailable(deviceType) {
  1048. return deviceType === 'output' || deviceType === 'audiooutput'
  1049. ? isAudioOutputDeviceChangeAvailable
  1050. : RTCBrowserType.isChrome()
  1051. || RTCBrowserType.isFirefox()
  1052. || RTCBrowserType.isOpera()
  1053. || RTCBrowserType.isTemasysPluginUsed()
  1054. || RTCBrowserType.isNWJS()
  1055. || RTCBrowserType.isElectron();
  1056. }
  1057. /**
  1058. * A method to handle stopping of the stream.
  1059. * One point to handle the differences in various implementations.
  1060. * @param mediaStream MediaStream object to stop.
  1061. */
  1062. stopMediaStream(mediaStream) {
  1063. mediaStream.getTracks().forEach(track => {
  1064. // stop() not supported with IE
  1065. if (!RTCBrowserType.isTemasysPluginUsed() && track.stop) {
  1066. track.stop();
  1067. }
  1068. });
  1069. // leave stop for implementation still using it
  1070. if (mediaStream.stop) {
  1071. mediaStream.stop();
  1072. }
  1073. // The MediaStream implementation of the react-native-webrtc project has
  1074. // an explicit release method that is to be invoked in order to release
  1075. // used resources such as memory.
  1076. if (mediaStream.release) {
  1077. mediaStream.release();
  1078. }
  1079. // if we have done createObjectURL, lets clean it
  1080. const url = mediaStream.jitsiObjectURL;
  1081. if (url) {
  1082. delete mediaStream.jitsiObjectURL;
  1083. (URL || webkitURL).revokeObjectURL(url);
  1084. }
  1085. }
  1086. /**
  1087. * Returns whether the desktop sharing is enabled or not.
  1088. * @returns {boolean}
  1089. */
  1090. isDesktopSharingEnabled() {
  1091. return screenObtainer.isSupported();
  1092. }
  1093. /**
  1094. * Sets current audio output device.
  1095. * @param {string} deviceId - id of 'audiooutput' device from
  1096. * navigator.mediaDevices.enumerateDevices(), 'default' for default
  1097. * device
  1098. * @returns {Promise} - resolves when audio output is changed, is rejected
  1099. * otherwise
  1100. */
  1101. setAudioOutputDevice(deviceId) {
  1102. if (!this.isDeviceChangeAvailable('output')) {
  1103. Promise.reject(
  1104. new Error('Audio output device change is not supported'));
  1105. }
  1106. return featureDetectionAudioEl.setSinkId(deviceId)
  1107. .then(() => {
  1108. audioOutputDeviceId = deviceId;
  1109. audioOutputChanged = true;
  1110. logger.log(`Audio output device set to ${deviceId}`);
  1111. eventEmitter.emit(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1112. deviceId);
  1113. });
  1114. }
  1115. /**
  1116. * Returns currently used audio output device id, '' stands for default
  1117. * device
  1118. * @returns {string}
  1119. */
  1120. getAudioOutputDevice() {
  1121. return audioOutputDeviceId;
  1122. }
  1123. /**
  1124. * Returns list of available media devices if its obtained, otherwise an
  1125. * empty array is returned/
  1126. * @returns {Array} list of available media devices.
  1127. */
  1128. getCurrentlyAvailableMediaDevices() {
  1129. return currentlyAvailableMediaDevices;
  1130. }
  1131. /**
  1132. * Returns event data for device to be reported to stats.
  1133. * @returns {MediaDeviceInfo} device.
  1134. */
  1135. getEventDataForActiveDevice(device) {
  1136. const deviceList = [];
  1137. const deviceData = {
  1138. 'deviceId': device.deviceId,
  1139. 'kind': device.kind,
  1140. 'label': device.label,
  1141. 'groupId': device.groupId
  1142. };
  1143. deviceList.push(deviceData);
  1144. return { deviceList };
  1145. }
  1146. }
  1147. /**
  1148. * Rejects a Promise because WebRTC is not supported.
  1149. *
  1150. * @param {string} errorMessage - The human-readable message of the Error which
  1151. * is the reason for the rejection.
  1152. * @param {Function} reject - The reject function of the Promise.
  1153. * @returns {void}
  1154. */
  1155. function rejectWithWebRTCNotSupported(errorMessage, reject) {
  1156. const error = new Error(errorMessage);
  1157. // WebRTC is not supported either natively or via a known plugin such as
  1158. // Temasys.
  1159. // XXX The Error class already has a property name which is commonly used to
  1160. // detail the represented error in a non-human-readable way (in contrast to
  1161. // the human-readable property message). I explicitly did not want to
  1162. // introduce a new specific property.
  1163. // FIXME None of the existing JitsiXXXErrors seemed to be appropriate
  1164. // recipients of the constant WEBRTC_NOT_SUPPORTED so I explicitly chose to
  1165. // leave it as a magic string at the time of this writing.
  1166. error.name = 'WEBRTC_NOT_SUPPORTED';
  1167. logger.error(errorMessage);
  1168. reject(error);
  1169. }
  1170. const rtcUtils = new RTCUtils();
  1171. function obtainDevices(options) {
  1172. if (!options.devices || options.devices.length === 0) {
  1173. return options.successCallback(options.streams || {});
  1174. }
  1175. const device = options.devices.splice(0, 1);
  1176. options.deviceGUM[device](
  1177. stream => {
  1178. options.streams = options.streams || {};
  1179. options.streams[device] = stream;
  1180. obtainDevices(options);
  1181. },
  1182. error => {
  1183. Object.keys(options.streams).forEach(
  1184. d => rtcUtils.stopMediaStream(options.streams[d]));
  1185. logger.error(
  1186. `failed to obtain ${device} stream - stop`, error);
  1187. options.errorCallback(error);
  1188. });
  1189. }
  1190. // In case of IE we continue from 'onReady' callback
  1191. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  1192. // once it is initialized.
  1193. function onReady(options, GUM) {
  1194. rtcReady = true;
  1195. eventEmitter.emit(RTCEvents.RTC_READY, true);
  1196. screenObtainer.init(options, GUM);
  1197. // Initialize rawEnumerateDevicesWithCallback
  1198. initRawEnumerateDevicesWithCallback();
  1199. if (rtcUtils.isDeviceListAvailable() && rawEnumerateDevicesWithCallback) {
  1200. rawEnumerateDevicesWithCallback(ds => {
  1201. currentlyAvailableMediaDevices = ds.splice(0);
  1202. eventEmitter.emit(RTCEvents.DEVICE_LIST_AVAILABLE,
  1203. currentlyAvailableMediaDevices);
  1204. if (isDeviceChangeEventSupported) {
  1205. navigator.mediaDevices.addEventListener(
  1206. 'devicechange',
  1207. () => rtcUtils.enumerateDevices(onMediaDevicesListChanged));
  1208. } else {
  1209. pollForAvailableMediaDevices();
  1210. }
  1211. });
  1212. }
  1213. }
  1214. /**
  1215. * Wraps original attachMediaStream function to set current audio output device
  1216. * if this is supported.
  1217. * @param {Function} origAttachMediaStream
  1218. * @returns {Function}
  1219. */
  1220. function wrapAttachMediaStream(origAttachMediaStream) {
  1221. return function(element, stream) {
  1222. // eslint-disable-next-line prefer-rest-params
  1223. const res = origAttachMediaStream.apply(rtcUtils, arguments);
  1224. if (stream
  1225. && rtcUtils.isDeviceChangeAvailable('output')
  1226. && stream.getAudioTracks
  1227. && stream.getAudioTracks().length
  1228. // we skip setting audio output if there was no explicit change
  1229. && audioOutputChanged) {
  1230. element.setSinkId(rtcUtils.getAudioOutputDevice())
  1231. .catch(function(ex) {
  1232. const err
  1233. = new JitsiTrackError(ex, null, [ 'audiooutput' ]);
  1234. GlobalOnErrorHandler.callUnhandledRejectionHandler({
  1235. promise: this,
  1236. reason: err
  1237. });
  1238. logger.warn('Failed to set audio output device for the '
  1239. + 'element. Default audio output device will be used '
  1240. + 'instead',
  1241. element, err);
  1242. });
  1243. }
  1244. return res;
  1245. };
  1246. }
  1247. export default rtcUtils;