Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

RTCUtils.js 56KB

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