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

RTCUtils.js 55KB

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