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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539
  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 } = desktopStream;
  565. res.push({
  566. stream,
  567. sourceId,
  568. track: stream.getVideoTracks()[0],
  569. mediaType: MediaType.VIDEO,
  570. videoType: VideoType.DESKTOP
  571. });
  572. }
  573. if (audioStream) {
  574. res.push({
  575. stream: audioStream,
  576. track: audioStream.getAudioTracks()[0],
  577. mediaType: MediaType.AUDIO,
  578. videoType: null
  579. });
  580. }
  581. if (videoStream) {
  582. res.push({
  583. stream: videoStream,
  584. track: videoStream.getVideoTracks()[0],
  585. mediaType: MediaType.VIDEO,
  586. videoType: VideoType.CAMERA,
  587. resolution
  588. });
  589. }
  590. return res;
  591. }
  592. /**
  593. * Represents a default implementation of setting a <tt>MediaStream</tt> as the
  594. * source of a video element that tries to be browser-agnostic through feature
  595. * checking. Note though that it was not completely clear from the predating
  596. * browser-specific implementations what &quot;videoSrc&quot; was because one
  597. * implementation of {@link RTCUtils#getVideoSrc} would return
  598. * <tt>MediaStream</tt> (e.g. Firefox), another a <tt>string</tt> representation
  599. * of the <tt>URL</tt> of the <tt>MediaStream</tt> (e.g. Chrome) and the return
  600. * value was only used by {@link RTCUIHelper#getVideoId} which itself did not
  601. * appear to be used anywhere. Generally, the implementation will try to follow
  602. * the related standards i.e. work with the <tt>srcObject</tt> and <tt>src</tt>
  603. * properties of the specified <tt>element</tt> taking into account vender
  604. * prefixes.
  605. *
  606. * @param element the element whose video source/src is to be set to the
  607. * specified <tt>stream</tt>
  608. * @param {MediaStream} stream the <tt>MediaStream</tt> to set as the video
  609. * source/src of <tt>element</tt>
  610. */
  611. function defaultSetVideoSrc(element, stream) {
  612. // srcObject
  613. let srcObjectPropertyName = 'srcObject';
  614. if (!(srcObjectPropertyName in element)) {
  615. srcObjectPropertyName = 'mozSrcObject';
  616. if (!(srcObjectPropertyName in element)) {
  617. srcObjectPropertyName = null;
  618. }
  619. }
  620. if (srcObjectPropertyName) {
  621. element[srcObjectPropertyName] = stream;
  622. return;
  623. }
  624. // src
  625. let src;
  626. if (stream) {
  627. src = stream.jitsiObjectURL;
  628. // Save the created URL for stream so we can reuse it and not keep
  629. // creating URLs.
  630. if (!src) {
  631. stream.jitsiObjectURL
  632. = src
  633. = (URL || webkitURL).createObjectURL(stream);
  634. }
  635. }
  636. element.src = src || '';
  637. }
  638. /**
  639. *
  640. */
  641. class RTCUtils extends Listenable {
  642. /**
  643. *
  644. */
  645. constructor() {
  646. super(eventEmitter);
  647. }
  648. /**
  649. *
  650. * @param options
  651. */
  652. init(options) {
  653. if (typeof options.disableAEC === 'boolean') {
  654. disableAEC = options.disableAEC;
  655. logger.info(`Disable AEC: ${disableAEC}`);
  656. }
  657. if (typeof options.disableNS === 'boolean') {
  658. disableNS = options.disableNS;
  659. logger.info(`Disable NS: ${disableNS}`);
  660. }
  661. return new Promise((resolve, reject) => {
  662. if (RTCBrowserType.isFirefox()) {
  663. const FFversion = RTCBrowserType.getFirefoxVersion();
  664. if (FFversion < 40) {
  665. rejectWithWebRTCNotSupported(
  666. `Firefox version too old: ${FFversion}.`
  667. + ' Required >= 40.',
  668. reject);
  669. return;
  670. }
  671. this.RTCPeerConnectionType = mozRTCPeerConnection;
  672. this.getUserMedia
  673. = wrapGetUserMedia(
  674. navigator.mozGetUserMedia.bind(navigator));
  675. this.enumerateDevices
  676. = wrapEnumerateDevices(
  677. navigator.mediaDevices.enumerateDevices.bind(
  678. navigator.mediaDevices));
  679. this.pcConstraints = {};
  680. this.attachMediaStream
  681. = wrapAttachMediaStream((element, stream) => {
  682. // srcObject is being standardized and FF will
  683. // eventually support that unprefixed. FF also supports
  684. // the "element.src = URL.createObjectURL(...)" combo,
  685. // but that will be deprecated in favour of srcObject.
  686. //
  687. // https://groups.google.com/forum/#!topic/
  688. // mozilla.dev.media/pKOiioXonJg
  689. // https://github.com/webrtc/samples/issues/302
  690. if (element) {
  691. defaultSetVideoSrc(element, stream);
  692. if (stream) {
  693. element.play();
  694. }
  695. }
  696. return element;
  697. });
  698. this.getStreamID = function(stream) {
  699. let id = stream.id;
  700. if (!id) {
  701. let tracks = stream.getVideoTracks();
  702. if (!tracks || tracks.length === 0) {
  703. tracks = stream.getAudioTracks();
  704. }
  705. id = tracks[0].id;
  706. }
  707. return SDPUtil.filterSpecialChars(id);
  708. };
  709. this.getTrackID = function(track) {
  710. return track.id;
  711. };
  712. /* eslint-disable no-global-assign, no-native-reassign */
  713. RTCSessionDescription = mozRTCSessionDescription;
  714. RTCIceCandidate = mozRTCIceCandidate;
  715. /* eslint-enable no-global-assign, no-native-reassign */
  716. } else if (RTCBrowserType.isChrome()
  717. || RTCBrowserType.isOpera()
  718. || RTCBrowserType.isNWJS()
  719. || RTCBrowserType.isElectron()
  720. || RTCBrowserType.isReactNative()) {
  721. this.RTCPeerConnectionType = webkitRTCPeerConnection;
  722. const getUserMedia
  723. = navigator.webkitGetUserMedia.bind(navigator);
  724. if (navigator.mediaDevices) {
  725. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  726. this.enumerateDevices
  727. = wrapEnumerateDevices(
  728. navigator.mediaDevices.enumerateDevices.bind(
  729. navigator.mediaDevices));
  730. } else {
  731. this.getUserMedia = getUserMedia;
  732. this.enumerateDevices
  733. = enumerateDevicesThroughMediaStreamTrack;
  734. }
  735. this.attachMediaStream
  736. = wrapAttachMediaStream((element, stream) => {
  737. defaultSetVideoSrc(element, stream);
  738. return element;
  739. });
  740. this.getStreamID = function(stream) {
  741. // A. MediaStreams from FF endpoints have the characters '{'
  742. // and '}' that make jQuery choke.
  743. // B. The react-native-webrtc implementation that we use on
  744. // React Native at the time of this writing returns a number
  745. // for the id of MediaStream. Let's just say that a number
  746. // contains no special characters.
  747. const id = stream.id;
  748. // XXX The return statement is affected by automatic
  749. // semicolon insertion (ASI). No line terminator is allowed
  750. // between the return keyword and the expression.
  751. return (
  752. typeof id === 'number'
  753. ? id
  754. : SDPUtil.filterSpecialChars(id));
  755. };
  756. this.getTrackID = function(track) {
  757. return track.id;
  758. };
  759. this.pcConstraints = { optional: [] };
  760. // Allows sending of video to be suspended if the bandwidth
  761. // estimation is too low.
  762. if (!options.disableSuspendVideo) {
  763. this.pcConstraints.optional.push(
  764. { googSuspendBelowMinBitrate: true });
  765. }
  766. if (options.useIPv6) {
  767. // https://code.google.com/p/webrtc/issues/detail?id=2828
  768. this.pcConstraints.optional.push({ googIPv6: true });
  769. }
  770. if (!webkitMediaStream.prototype.getVideoTracks) {
  771. webkitMediaStream.prototype.getVideoTracks = function() {
  772. return this.videoTracks;
  773. };
  774. }
  775. if (!webkitMediaStream.prototype.getAudioTracks) {
  776. webkitMediaStream.prototype.getAudioTracks = function() {
  777. return this.audioTracks;
  778. };
  779. }
  780. } else if (RTCBrowserType.isEdge()) {
  781. this.RTCPeerConnectionType = ortcRTCPeerConnection;
  782. this.getUserMedia
  783. = wrapGetUserMedia(
  784. navigator.mediaDevices.getUserMedia.bind(
  785. navigator.mediaDevices),
  786. true);
  787. this.enumerateDevices
  788. = wrapEnumerateDevices(
  789. navigator.mediaDevices.enumerateDevices.bind(
  790. navigator.mediaDevices));
  791. this.attachMediaStream
  792. = wrapAttachMediaStream((element, stream) => {
  793. defaultSetVideoSrc(element, stream);
  794. return element;
  795. });
  796. // ORTC does not generate remote MediaStreams so those are
  797. // manually created by the ORTC shim. This means that their
  798. // id (internally generated) does not match the stream id
  799. // signaled into the remote SDP. Therefore, the shim adds a
  800. // custom jitsiRemoteId property with the original stream id.
  801. this.getStreamID = function(stream) {
  802. const id = stream.jitsiRemoteId || stream.id;
  803. return SDPUtil.filterSpecialChars(id);
  804. };
  805. // Remote MediaStreamTracks generated by ORTC (within a
  806. // RTCRtpReceiver) have an internally/random id which does not
  807. // match the track id signaled in the remote SDP. The shim adds
  808. // a custom jitsi-id property with the original track id.
  809. this.getTrackID = function(track) {
  810. return track.jitsiRemoteId || track.id;
  811. };
  812. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  813. // Detect IE/Safari
  814. const webRTCReadyCb = () => {
  815. this.RTCPeerConnectionType = RTCPeerConnection;
  816. this.getUserMedia = window.getUserMedia;
  817. this.enumerateDevices
  818. = enumerateDevicesThroughMediaStreamTrack;
  819. this.attachMediaStream
  820. = wrapAttachMediaStream((element, stream) => {
  821. if (stream) {
  822. if (stream.id === 'dummyAudio'
  823. || stream.id === 'dummyVideo') {
  824. return;
  825. }
  826. // The container must be visible in order to
  827. // play or attach the stream when Temasys plugin
  828. // is in use
  829. const containerSel = $(element);
  830. if (RTCBrowserType.isTemasysPluginUsed()
  831. && !containerSel.is(':visible')) {
  832. containerSel.show();
  833. }
  834. const video
  835. = stream.getVideoTracks().length > 0;
  836. if (video && !$(element).is(':visible')) {
  837. throw new Error(
  838. 'video element must be visible to'
  839. + ' attach video stream');
  840. }
  841. }
  842. return attachMediaStream(element, stream);
  843. });
  844. this.getStreamID
  845. = stream => SDPUtil.filterSpecialChars(stream.label);
  846. this.getTrackID
  847. = track => track.id;
  848. onReady(
  849. options,
  850. this.getUserMediaWithConstraints.bind(this));
  851. };
  852. const webRTCReadyPromise
  853. = new Promise(r => AdapterJS.webRTCReady(r));
  854. // Resolve or reject depending on whether the Temasys plugin is
  855. // installed.
  856. AdapterJS.WebRTCPlugin.isPluginInstalled(
  857. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  858. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  859. AdapterJS.WebRTCPlugin.pluginInfo.type,
  860. /* installed */ () => {
  861. webRTCReadyPromise.then(() => {
  862. webRTCReadyCb();
  863. resolve();
  864. });
  865. },
  866. /* not installed */ () => {
  867. const error
  868. = new Error('Temasys plugin is not installed');
  869. error.name = 'WEBRTC_NOT_READY';
  870. error.webRTCReadyPromise = webRTCReadyPromise;
  871. reject(error);
  872. });
  873. } else {
  874. rejectWithWebRTCNotSupported(
  875. 'Browser does not appear to be WebRTC-capable',
  876. reject);
  877. return;
  878. }
  879. // Call onReady() if Temasys plugin is not used
  880. if (!RTCBrowserType.isTemasysPluginUsed()) {
  881. onReady(options, this.getUserMediaWithConstraints.bind(this));
  882. resolve();
  883. }
  884. });
  885. }
  886. /* eslint-disable max-params */
  887. /**
  888. * @param {string[]} um required user media types
  889. * @param {function} successCallback
  890. * @param {Function} failureCallback
  891. * @param {Object} [options] optional parameters
  892. * @param {string} options.resolution
  893. * @param {number} options.bandwidth
  894. * @param {number} options.fps
  895. * @param {string} options.desktopStream
  896. * @param {string} options.cameraDeviceId
  897. * @param {string} options.micDeviceId
  898. **/
  899. getUserMediaWithConstraints(
  900. um,
  901. successCallback,
  902. failureCallback,
  903. options = {}) {
  904. const constraints = getConstraints(um, options);
  905. logger.info('Get media constraints', constraints);
  906. try {
  907. this.getUserMedia(
  908. constraints,
  909. stream => {
  910. logger.log('onUserMediaSuccess');
  911. setAvailableDevices(um, stream);
  912. successCallback(stream);
  913. },
  914. error => {
  915. setAvailableDevices(um, undefined);
  916. logger.warn('Failed to get access to local media. Error ',
  917. error, constraints);
  918. if (failureCallback) {
  919. failureCallback(
  920. new JitsiTrackError(error, constraints, um));
  921. }
  922. });
  923. } catch (e) {
  924. logger.error('GUM failed: ', e);
  925. if (failureCallback) {
  926. failureCallback(new JitsiTrackError(e, constraints, um));
  927. }
  928. }
  929. }
  930. /* eslint-enable max-params */
  931. /**
  932. * Creates the local MediaStreams.
  933. * @param {Object} [options] optional parameters
  934. * @param {Array} options.devices the devices that will be requested
  935. * @param {string} options.resolution resolution constraints
  936. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with
  937. * the following structure {stream: the Media Stream, type: "audio" or
  938. * "video", videoType: "camera" or "desktop"} will be returned trough the
  939. * Promise, otherwise JitsiTrack objects will be returned.
  940. * @param {string} options.cameraDeviceId
  941. * @param {string} options.micDeviceId
  942. * @returns {*} Promise object that will receive the new JitsiTracks
  943. */
  944. obtainAudioAndVideoPermissions(options = {}) {
  945. const self = this;
  946. const dsOptions = options.desktopSharingExtensionExternalInstallation;
  947. return new Promise((resolve, reject) => {
  948. const successCallback = function(stream) {
  949. resolve(handleLocalStream(stream, options.resolution));
  950. };
  951. options.devices = options.devices || [ 'audio', 'video' ];
  952. if (!screenObtainer.isSupported()
  953. && options.devices.indexOf('desktop') !== -1) {
  954. reject(new Error('Desktop sharing is not supported!'));
  955. }
  956. if (RTCBrowserType.isFirefox()
  957. // XXX The react-native-webrtc implementation that we
  958. // utilize on React Native at the time of this writing does
  959. // not support the MediaStream constructors defined by
  960. // https://www.w3.org/TR/mediacapture-streams/#constructors
  961. // and instead has a single constructor which expects (an
  962. // NSNumber as) a MediaStream ID.
  963. || RTCBrowserType.isReactNative()
  964. || RTCBrowserType.isTemasysPluginUsed()) {
  965. const GUM = function(device, s, e) {
  966. this.getUserMediaWithConstraints(device, s, e, options);
  967. };
  968. const deviceGUM = {
  969. 'audio': GUM.bind(self, [ 'audio' ]),
  970. 'video': GUM.bind(self, [ 'video' ])
  971. };
  972. if (screenObtainer.isSupported()) {
  973. deviceGUM.desktop = screenObtainer.obtainStream.bind(
  974. screenObtainer,
  975. dsOptions);
  976. }
  977. // With FF/IE we can't split the stream into audio and video
  978. // because FF doesn't support media stream constructors. So, we
  979. // need to get the audio stream separately from the video stream
  980. // using two distinct GUM calls. Not very user friendly :-( but
  981. // we don't have many other options neither.
  982. //
  983. // Note that we pack those 2 streams in a single object and pass
  984. // it to the successCallback method.
  985. obtainDevices({
  986. devices: options.devices,
  987. streams: [],
  988. successCallback,
  989. errorCallback: reject,
  990. deviceGUM
  991. });
  992. } else {
  993. const hasDesktop = options.devices.indexOf('desktop') > -1;
  994. if (hasDesktop) {
  995. options.devices.splice(
  996. options.devices.indexOf('desktop'),
  997. 1);
  998. }
  999. options.resolution = options.resolution || '360';
  1000. if (options.devices.length) {
  1001. this.getUserMediaWithConstraints(
  1002. options.devices,
  1003. stream => {
  1004. const audioDeviceRequested
  1005. = options.devices.indexOf('audio') !== -1;
  1006. const videoDeviceRequested
  1007. = options.devices.indexOf('video') !== -1;
  1008. const audioTracksReceived
  1009. = stream.getAudioTracks().length > 0;
  1010. const videoTracksReceived
  1011. = stream.getVideoTracks().length > 0;
  1012. if ((audioDeviceRequested && !audioTracksReceived)
  1013. || (videoDeviceRequested
  1014. && !videoTracksReceived)) {
  1015. self.stopMediaStream(stream);
  1016. // We are getting here in case if we requested
  1017. // 'audio' or 'video' devices or both, but
  1018. // didn't get corresponding MediaStreamTrack in
  1019. // response stream. We don't know the reason why
  1020. // this happened, so reject with general error.
  1021. // eslint-disable-next-line no-shadow
  1022. const devices = [];
  1023. if (audioDeviceRequested
  1024. && !audioTracksReceived) {
  1025. devices.push('audio');
  1026. }
  1027. if (videoDeviceRequested
  1028. && !videoTracksReceived) {
  1029. devices.push('video');
  1030. }
  1031. // we are missing one of the media we requested
  1032. // in order to get the actual error that caused
  1033. // this missing media we will call one more time
  1034. // getUserMedia so we can obtain the actual
  1035. // error (Example usecases are requesting
  1036. // audio and video and video device is missing
  1037. // or device is denied to be used and chrome is
  1038. // set to not ask for permissions)
  1039. self.getUserMediaWithConstraints(
  1040. devices,
  1041. () => {
  1042. // we already failed to obtain this
  1043. // media, so we are not supposed in any
  1044. // way to receive success for this call
  1045. // any way we will throw an error to be
  1046. // sure the promise will finish
  1047. reject(new JitsiTrackError(
  1048. { name: 'UnknownError' },
  1049. getConstraints(
  1050. options.devices,
  1051. options),
  1052. devices)
  1053. );
  1054. },
  1055. error => {
  1056. // rejects with real error for not
  1057. // obtaining the media
  1058. reject(error);
  1059. }, options);
  1060. return;
  1061. }
  1062. if (hasDesktop) {
  1063. screenObtainer.obtainStream(
  1064. dsOptions,
  1065. desktop => {
  1066. successCallback({ audioVideo: stream,
  1067. desktop });
  1068. }, error => {
  1069. self.stopMediaStream(stream);
  1070. reject(error);
  1071. });
  1072. } else {
  1073. successCallback({ audioVideo: stream });
  1074. }
  1075. },
  1076. error => reject(error),
  1077. options);
  1078. } else if (hasDesktop) {
  1079. screenObtainer.obtainStream(
  1080. dsOptions,
  1081. desktop => successCallback({ desktop }),
  1082. error => reject(error));
  1083. }
  1084. }
  1085. });
  1086. }
  1087. /**
  1088. *
  1089. */
  1090. getDeviceAvailability() {
  1091. return devices;
  1092. }
  1093. /**
  1094. *
  1095. */
  1096. isRTCReady() {
  1097. return rtcReady;
  1098. }
  1099. /**
  1100. *
  1101. */
  1102. _isDeviceListAvailable() {
  1103. if (!rtcReady) {
  1104. throw new Error('WebRTC not ready yet');
  1105. }
  1106. return Boolean(
  1107. (navigator.mediaDevices
  1108. && navigator.mediaDevices.enumerateDevices)
  1109. || (typeof MediaStreamTrack !== 'undefined'
  1110. && MediaStreamTrack.getSources));
  1111. }
  1112. /**
  1113. * Returns a promise which can be used to make sure that the WebRTC stack
  1114. * has been initialized.
  1115. *
  1116. * @returns {Promise} which is resolved only if the WebRTC stack is ready.
  1117. * Note that currently we do not detect stack initialization failure and
  1118. * the promise is never rejected(unless unexpected error occurs).
  1119. */
  1120. onRTCReady() {
  1121. if (rtcReady) {
  1122. return Promise.resolve();
  1123. }
  1124. return new Promise(resolve => {
  1125. const listener = () => {
  1126. eventEmitter.removeListener(RTCEvents.RTC_READY, listener);
  1127. resolve();
  1128. };
  1129. eventEmitter.addListener(RTCEvents.RTC_READY, listener);
  1130. // We have no failed event, so... it either resolves or nothing
  1131. // happens
  1132. });
  1133. }
  1134. /**
  1135. * Checks if its possible to enumerate available cameras/microphones.
  1136. *
  1137. * @returns {Promise<boolean>} a Promise which will be resolved only once
  1138. * the WebRTC stack is ready, either with true if the device listing is
  1139. * available available or with false otherwise.
  1140. */
  1141. isDeviceListAvailable() {
  1142. return this.onRTCReady().then(this._isDeviceListAvailable.bind(this));
  1143. }
  1144. /**
  1145. * Returns true if changing the input (camera / microphone) or output
  1146. * (audio) device is supported and false if not.
  1147. * @params {string} [deviceType] - type of device to change. Default is
  1148. * undefined or 'input', 'output' - for audio output device change.
  1149. * @returns {boolean} true if available, false otherwise.
  1150. */
  1151. isDeviceChangeAvailable(deviceType) {
  1152. return deviceType === 'output' || deviceType === 'audiooutput'
  1153. ? isAudioOutputDeviceChangeAvailable
  1154. : RTCBrowserType.isChrome()
  1155. || RTCBrowserType.isFirefox()
  1156. || RTCBrowserType.isOpera()
  1157. || RTCBrowserType.isTemasysPluginUsed()
  1158. || RTCBrowserType.isNWJS()
  1159. || RTCBrowserType.isElectron()
  1160. || RTCBrowserType.isEdge();
  1161. }
  1162. /**
  1163. * A method to handle stopping of the stream.
  1164. * One point to handle the differences in various implementations.
  1165. * @param mediaStream MediaStream object to stop.
  1166. */
  1167. stopMediaStream(mediaStream) {
  1168. mediaStream.getTracks().forEach(track => {
  1169. // stop() not supported with IE
  1170. if (!RTCBrowserType.isTemasysPluginUsed() && track.stop) {
  1171. track.stop();
  1172. }
  1173. });
  1174. // leave stop for implementation still using it
  1175. if (mediaStream.stop) {
  1176. mediaStream.stop();
  1177. }
  1178. // The MediaStream implementation of the react-native-webrtc project has
  1179. // an explicit release method that is to be invoked in order to release
  1180. // used resources such as memory.
  1181. if (mediaStream.release) {
  1182. mediaStream.release();
  1183. }
  1184. // if we have done createObjectURL, lets clean it
  1185. const url = mediaStream.jitsiObjectURL;
  1186. if (url) {
  1187. delete mediaStream.jitsiObjectURL;
  1188. (URL || webkitURL).revokeObjectURL(url);
  1189. }
  1190. }
  1191. /**
  1192. * Returns whether the desktop sharing is enabled or not.
  1193. * @returns {boolean}
  1194. */
  1195. isDesktopSharingEnabled() {
  1196. return screenObtainer.isSupported();
  1197. }
  1198. /**
  1199. * Sets current audio output device.
  1200. * @param {string} deviceId - id of 'audiooutput' device from
  1201. * navigator.mediaDevices.enumerateDevices(), 'default' for default
  1202. * device
  1203. * @returns {Promise} - resolves when audio output is changed, is rejected
  1204. * otherwise
  1205. */
  1206. setAudioOutputDevice(deviceId) {
  1207. if (!this.isDeviceChangeAvailable('output')) {
  1208. Promise.reject(
  1209. new Error('Audio output device change is not supported'));
  1210. }
  1211. return featureDetectionAudioEl.setSinkId(deviceId)
  1212. .then(() => {
  1213. audioOutputDeviceId = deviceId;
  1214. audioOutputChanged = true;
  1215. logger.log(`Audio output device set to ${deviceId}`);
  1216. eventEmitter.emit(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1217. deviceId);
  1218. });
  1219. }
  1220. /**
  1221. * Returns currently used audio output device id, '' stands for default
  1222. * device
  1223. * @returns {string}
  1224. */
  1225. getAudioOutputDevice() {
  1226. return audioOutputDeviceId;
  1227. }
  1228. /**
  1229. * Returns list of available media devices if its obtained, otherwise an
  1230. * empty array is returned/
  1231. * @returns {Array} list of available media devices.
  1232. */
  1233. getCurrentlyAvailableMediaDevices() {
  1234. return currentlyAvailableMediaDevices;
  1235. }
  1236. /**
  1237. * Returns event data for device to be reported to stats.
  1238. * @returns {MediaDeviceInfo} device.
  1239. */
  1240. getEventDataForActiveDevice(device) {
  1241. const deviceList = [];
  1242. const deviceData = {
  1243. 'deviceId': device.deviceId,
  1244. 'kind': device.kind,
  1245. 'label': device.label,
  1246. 'groupId': device.groupId
  1247. };
  1248. deviceList.push(deviceData);
  1249. return { deviceList };
  1250. }
  1251. }
  1252. /**
  1253. * Rejects a Promise because WebRTC is not supported.
  1254. *
  1255. * @param {string} errorMessage - The human-readable message of the Error which
  1256. * is the reason for the rejection.
  1257. * @param {Function} reject - The reject function of the Promise.
  1258. * @returns {void}
  1259. */
  1260. function rejectWithWebRTCNotSupported(errorMessage, reject) {
  1261. const error = new Error(errorMessage);
  1262. // WebRTC is not supported either natively or via a known plugin such as
  1263. // Temasys.
  1264. // XXX The Error class already has a property name which is commonly used to
  1265. // detail the represented error in a non-human-readable way (in contrast to
  1266. // the human-readable property message). I explicitly did not want to
  1267. // introduce a new specific property.
  1268. // FIXME None of the existing JitsiXXXErrors seemed to be appropriate
  1269. // recipients of the constant WEBRTC_NOT_SUPPORTED so I explicitly chose to
  1270. // leave it as a magic string at the time of this writing.
  1271. error.name = 'WEBRTC_NOT_SUPPORTED';
  1272. logger.error(errorMessage);
  1273. reject(error);
  1274. }
  1275. const rtcUtils = new RTCUtils();
  1276. /**
  1277. *
  1278. * @param options
  1279. */
  1280. function obtainDevices(options) {
  1281. if (!options.devices || options.devices.length === 0) {
  1282. return options.successCallback(options.streams || {});
  1283. }
  1284. const device = options.devices.splice(0, 1);
  1285. options.deviceGUM[device](
  1286. stream => {
  1287. options.streams = options.streams || {};
  1288. options.streams[device] = stream;
  1289. obtainDevices(options);
  1290. },
  1291. error => {
  1292. Object.keys(options.streams).forEach(
  1293. d => rtcUtils.stopMediaStream(options.streams[d]));
  1294. logger.error(
  1295. `failed to obtain ${device} stream - stop`, error);
  1296. options.errorCallback(error);
  1297. });
  1298. }
  1299. /**
  1300. * In case of IE we continue from 'onReady' callback passed to RTCUtils
  1301. * constructor. It will be invoked by Temasys plugin once it is initialized.
  1302. *
  1303. * @param options
  1304. * @param GUM
  1305. */
  1306. function onReady(options, GUM) {
  1307. rtcReady = true;
  1308. eventEmitter.emit(RTCEvents.RTC_READY, true);
  1309. screenObtainer.init(options, GUM);
  1310. // Initialize rawEnumerateDevicesWithCallback
  1311. initRawEnumerateDevicesWithCallback();
  1312. if (rtcUtils.isDeviceListAvailable() && rawEnumerateDevicesWithCallback) {
  1313. rawEnumerateDevicesWithCallback(ds => {
  1314. currentlyAvailableMediaDevices = ds.splice(0);
  1315. eventEmitter.emit(RTCEvents.DEVICE_LIST_AVAILABLE,
  1316. currentlyAvailableMediaDevices);
  1317. if (isDeviceChangeEventSupported) {
  1318. navigator.mediaDevices.addEventListener(
  1319. 'devicechange',
  1320. () => rtcUtils.enumerateDevices(onMediaDevicesListChanged));
  1321. } else {
  1322. pollForAvailableMediaDevices();
  1323. }
  1324. });
  1325. }
  1326. }
  1327. /**
  1328. * Wraps original attachMediaStream function to set current audio output device
  1329. * if this is supported.
  1330. * @param {Function} origAttachMediaStream
  1331. * @returns {Function}
  1332. */
  1333. function wrapAttachMediaStream(origAttachMediaStream) {
  1334. return function(element, stream) {
  1335. // eslint-disable-next-line prefer-rest-params
  1336. const res = origAttachMediaStream.apply(rtcUtils, arguments);
  1337. if (stream
  1338. && rtcUtils.isDeviceChangeAvailable('output')
  1339. && stream.getAudioTracks
  1340. && stream.getAudioTracks().length
  1341. // we skip setting audio output if there was no explicit change
  1342. && audioOutputChanged) {
  1343. element.setSinkId(rtcUtils.getAudioOutputDevice())
  1344. .catch(function(ex) {
  1345. const err
  1346. = new JitsiTrackError(ex, null, [ 'audiooutput' ]);
  1347. GlobalOnErrorHandler.callUnhandledRejectionHandler({
  1348. promise: this, // eslint-disable-line no-invalid-this
  1349. reason: err
  1350. });
  1351. logger.warn('Failed to set audio output device for the '
  1352. + 'element. Default audio output device will be used '
  1353. + 'instead',
  1354. element, err);
  1355. });
  1356. }
  1357. return res;
  1358. };
  1359. }
  1360. export default rtcUtils;