Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

RTCUtils.js 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. import { getLogger } from '@jitsi/logger';
  2. import { cloneDeep } from 'lodash-es';
  3. import 'webrtc-adapter';
  4. import JitsiTrackError from '../../JitsiTrackError';
  5. import * as JitsiTrackErrors from '../../JitsiTrackErrors';
  6. import { CameraFacingMode } from '../../service/RTC/CameraFacingMode';
  7. import RTCEvents from '../../service/RTC/RTCEvents';
  8. import Resolutions from '../../service/RTC/Resolutions';
  9. import { VideoType } from '../../service/RTC/VideoType';
  10. import { AVAILABLE_DEVICE } from '../../service/statistics/AnalyticsEvents';
  11. import browser from '../browser';
  12. import Statistics from '../statistics/statistics';
  13. import Listenable from '../util/Listenable';
  14. import { isValidNumber } from '../util/MathUtil';
  15. import screenObtainer from './ScreenObtainer';
  16. const logger = getLogger('modules/RTC/RTCUtils');
  17. const AVAILABLE_DEVICES_POLL_INTERVAL_TIME = 3000; // ms
  18. /**
  19. * Default MediaStreamConstraints to use for calls to getUserMedia.
  20. *
  21. * @private
  22. */
  23. const DEFAULT_CONSTRAINTS = {
  24. video: {
  25. height: {
  26. ideal: 720,
  27. max: 720,
  28. min: 180
  29. },
  30. width: {
  31. ideal: 1280,
  32. max: 1280,
  33. min: 320
  34. },
  35. frameRate: {
  36. min: 15,
  37. max: 30
  38. }
  39. }
  40. };
  41. // Currently audio output device change is supported only in Chrome and
  42. // default output always has 'default' device ID
  43. let audioOutputDeviceId = 'default'; // default device
  44. // whether user has explicitly set a device to use
  45. let audioOutputChanged = false;
  46. // Disables all audio processing
  47. let disableAP = false;
  48. // Disables Acoustic Echo Cancellation
  49. let disableAEC = false;
  50. // Disables Noise Suppression
  51. let disableNS = false;
  52. // Disables Automatic Gain Control
  53. let disableAGC = false;
  54. // Enables stereo.
  55. let stereo = null;
  56. const featureDetectionAudioEl = document.createElement('audio');
  57. const isAudioOutputDeviceChangeAvailable
  58. = typeof featureDetectionAudioEl.setSinkId !== 'undefined';
  59. let availableDevices = [];
  60. let availableDevicesPollTimer;
  61. /**
  62. * An empty function.
  63. */
  64. function emptyFuncton() {
  65. // no-op
  66. }
  67. /**
  68. * Creates a constraints object to be passed into a call to getUserMedia.
  69. *
  70. * @param {Array} um - An array of user media types to get. The accepted types are "video", "audio", and "desktop."
  71. * @param {Object} options - Various values to be added to the constraints.
  72. * @param {string} options.cameraDeviceId - The device id for the video capture device to get video from.
  73. * @param {Object} options.constraints - Default constraints object to use as a base for the returned constraints.
  74. * @param {Object} options.desktopStream - The desktop source id from which to capture a desktop sharing video.
  75. * @param {string} options.facingMode - Which direction the camera is pointing to (applicable on mobile)
  76. * @param {string} options.micDeviceId - The device id for the audio capture device to get audio from.
  77. * @private
  78. * @returns {Object}
  79. */
  80. function getConstraints(um = [], options = {}) {
  81. // Create a deep copy of the constraints to avoid any modification of the passed in constraints object.
  82. const constraints = cloneDeep(options.constraints || DEFAULT_CONSTRAINTS);
  83. if (um.indexOf('video') >= 0) {
  84. if (!constraints.video) {
  85. constraints.video = {};
  86. }
  87. // The "resolution" option is a shortcut and takes precendence.
  88. if (Resolutions[options.resolution]) {
  89. const r = Resolutions[options.resolution];
  90. constraints.video.height = { ideal: r.height };
  91. constraints.video.width = { ideal: r.width };
  92. }
  93. if (!constraints.video.frameRate) {
  94. constraints.video.frameRate = DEFAULT_CONSTRAINTS.video.frameRate;
  95. }
  96. // Override the constraints on Safari because of the following webkit bug.
  97. // https://bugs.webkit.org/show_bug.cgi?id=210932
  98. // Camera doesn't start on older macOS versions if min/max constraints are specified.
  99. // TODO: remove this hack when the bug fix is available on Mojave, Sierra and High Sierra.
  100. if (browser.isWebKitBased()) {
  101. if (constraints.video.height && constraints.video.height.ideal) {
  102. constraints.video.height = { ideal: constraints.video.height.ideal };
  103. } else {
  104. logger.warn('Ideal camera height missing, camera may not start properly');
  105. }
  106. if (constraints.video.width && constraints.video.width.ideal) {
  107. constraints.video.width = { ideal: constraints.video.width.ideal };
  108. } else {
  109. logger.warn('Ideal camera width missing, camera may not start properly');
  110. }
  111. }
  112. if (options.cameraDeviceId) {
  113. constraints.video.deviceId = { exact: options.cameraDeviceId };
  114. } else if (browser.isMobileDevice()) {
  115. constraints.video.facingMode = options.facingMode || CameraFacingMode.USER;
  116. }
  117. } else {
  118. constraints.video = false;
  119. }
  120. if (um.indexOf('audio') >= 0) {
  121. if (!constraints.audio || typeof constraints.audio === 'boolean') {
  122. constraints.audio = {};
  123. }
  124. constraints.audio = {
  125. autoGainControl: !disableAGC && !disableAP,
  126. echoCancellation: !disableAEC && !disableAP,
  127. noiseSuppression: !disableNS && !disableAP
  128. };
  129. if (options.micDeviceId) {
  130. constraints.audio.deviceId = { exact: options.micDeviceId };
  131. }
  132. if (stereo) {
  133. Object.assign(constraints.audio, { channelCount: 2 });
  134. }
  135. } else {
  136. constraints.audio = false;
  137. }
  138. return constraints;
  139. }
  140. /**
  141. * Checks if new list of available media devices differs from previous one.
  142. * @param {MediaDeviceInfo[]} newDevices - list of new devices.
  143. * @returns {boolean} - true if list is different, false otherwise.
  144. */
  145. function compareAvailableMediaDevices(newDevices) {
  146. if (newDevices.length !== availableDevices.length) {
  147. return true;
  148. }
  149. /* eslint-disable newline-per-chained-call */
  150. return (
  151. newDevices.map(mediaDeviceInfoToJSON).sort().join('')
  152. !== availableDevices
  153. .map(mediaDeviceInfoToJSON).sort().join(''));
  154. /* eslint-enable newline-per-chained-call */
  155. /**
  156. *
  157. * @param info
  158. */
  159. function mediaDeviceInfoToJSON(info) {
  160. return JSON.stringify({
  161. kind: info.kind,
  162. deviceId: info.deviceId,
  163. groupId: info.groupId,
  164. label: info.label,
  165. facing: info.facing
  166. });
  167. }
  168. }
  169. /**
  170. * Sends analytics event with the passed device list.
  171. *
  172. * @param {Array<MediaDeviceInfo>} deviceList - List with info about the
  173. * available devices.
  174. * @returns {void}
  175. */
  176. function sendDeviceListToAnalytics(deviceList) {
  177. const audioInputDeviceCount
  178. = deviceList.filter(d => d.kind === 'audioinput').length;
  179. const audioOutputDeviceCount
  180. = deviceList.filter(d => d.kind === 'audiooutput').length;
  181. const videoInputDeviceCount
  182. = deviceList.filter(d => d.kind === 'videoinput').length;
  183. const videoOutputDeviceCount
  184. = deviceList.filter(d => d.kind === 'videooutput').length;
  185. deviceList.forEach(device => {
  186. const attributes = {
  187. 'audio_input_device_count': audioInputDeviceCount,
  188. 'audio_output_device_count': audioOutputDeviceCount,
  189. 'video_input_device_count': videoInputDeviceCount,
  190. 'video_output_device_count': videoOutputDeviceCount,
  191. 'device_id': device.deviceId,
  192. 'device_group_id': device.groupId,
  193. 'device_kind': device.kind,
  194. 'device_label': device.label
  195. };
  196. Statistics.sendAnalytics(AVAILABLE_DEVICE, attributes);
  197. });
  198. }
  199. /**
  200. *
  201. */
  202. class RTCUtils extends Listenable {
  203. /**
  204. *
  205. */
  206. constructor() {
  207. super();
  208. this._initOnce = false;
  209. }
  210. /**
  211. * Depending on the browser, sets difference instance methods for
  212. * interacting with user media and adds methods to native WebRTC-related
  213. * objects. Also creates an instance variable for peer connection
  214. * constraints.
  215. *
  216. * @param {Object} options
  217. * @returns {void}
  218. */
  219. init(options = {}) {
  220. if (typeof options.disableAEC === 'boolean') {
  221. disableAEC = options.disableAEC;
  222. logger.info(`Disable AEC: ${disableAEC}`);
  223. }
  224. if (typeof options.disableNS === 'boolean') {
  225. disableNS = options.disableNS;
  226. logger.info(`Disable NS: ${disableNS}`);
  227. }
  228. if (typeof options.disableAP === 'boolean') {
  229. disableAP = options.disableAP;
  230. logger.info(`Disable AP: ${disableAP}`);
  231. }
  232. if (typeof options.disableAGC === 'boolean') {
  233. disableAGC = options.disableAGC;
  234. logger.info(`Disable AGC: ${disableAGC}`);
  235. }
  236. if (typeof options.audioQuality?.stereo === 'boolean') {
  237. stereo = options.audioQuality.stereo;
  238. logger.info(`Stereo: ${stereo}`);
  239. }
  240. if (this._initOnce) {
  241. return;
  242. }
  243. // Anything beyond this point needs to be initialized only once.
  244. this._initOnce = true;
  245. window.clearInterval(availableDevicesPollTimer);
  246. availableDevicesPollTimer = undefined;
  247. screenObtainer.init(options);
  248. this.enumerateDevices(ds => {
  249. availableDevices = ds.slice(0);
  250. logger.debug('Available devices: ', availableDevices);
  251. sendDeviceListToAnalytics(availableDevices);
  252. this.eventEmitter.emit(
  253. RTCEvents.DEVICE_LIST_AVAILABLE,
  254. availableDevices);
  255. if (browser.supportsDeviceChangeEvent()) {
  256. navigator.mediaDevices.addEventListener(
  257. 'devicechange',
  258. () => this.enumerateDevices(emptyFuncton));
  259. } else {
  260. // Periodically poll enumerateDevices() method to check if
  261. // list of media devices has changed.
  262. availableDevicesPollTimer = window.setInterval(
  263. () => this.enumerateDevices(emptyFuncton),
  264. AVAILABLE_DEVICES_POLL_INTERVAL_TIME);
  265. }
  266. });
  267. }
  268. /**
  269. * Attaches the given media stream to the given element.
  270. *
  271. * @param {*} element DOM element.
  272. * @param {*} stream MediaStream.
  273. * @returns Promise<void>
  274. */
  275. attachMediaStream(element, stream) {
  276. if (element) {
  277. element.srcObject = stream;
  278. }
  279. if (element && stream
  280. && this.isDeviceChangeAvailable('output')
  281. && stream.getAudioTracks().length
  282. // we skip setting audio output if there was no explicit change
  283. && audioOutputChanged) {
  284. return element.setSinkId(this.getAudioOutputDevice()).catch(ex => {
  285. const err
  286. = new JitsiTrackError(ex, null, [ 'audiooutput' ]);
  287. logger.warn(
  288. 'Failed to set audio output device for the element.'
  289. + ' Default audio output device will be used'
  290. + ' instead',
  291. element?.id,
  292. err);
  293. throw err;
  294. });
  295. }
  296. return Promise.resolve();
  297. }
  298. /**
  299. *
  300. * @param {Function} callback
  301. */
  302. enumerateDevices(callback) {
  303. navigator.mediaDevices.enumerateDevices()
  304. .then(devices => {
  305. this._updateKnownDevices(devices);
  306. callback(devices);
  307. })
  308. .catch(error => {
  309. logger.warn(`Failed to enumerate devices. ${error}`);
  310. this._updateKnownDevices([]);
  311. callback([]);
  312. });
  313. }
  314. /**
  315. * Acquires a media stream via getUserMedia that
  316. * matches the given constraints
  317. *
  318. * @param {array} umDevices which devices to acquire (e.g. audio, video)
  319. * @param {Object} constraints - Stream specifications to use.
  320. * @param {number} timeout - The timeout in ms for GUM.
  321. * @returns {Promise}
  322. */
  323. _getUserMedia(umDevices, constraints = {}, timeout = 0) {
  324. return new Promise((resolve, reject) => {
  325. let gumTimeout, timeoutExpired = false;
  326. if (isValidNumber(timeout) && timeout > 0) {
  327. gumTimeout = setTimeout(() => {
  328. timeoutExpired = true;
  329. gumTimeout = undefined;
  330. reject(new JitsiTrackError(JitsiTrackErrors.TIMEOUT));
  331. }, timeout);
  332. }
  333. navigator.mediaDevices.getUserMedia(constraints)
  334. .then(stream => {
  335. logger.info('onUserMediaSuccess');
  336. this._updateGrantedPermissions(umDevices, stream);
  337. if (!timeoutExpired) {
  338. if (typeof gumTimeout !== 'undefined') {
  339. clearTimeout(gumTimeout);
  340. }
  341. resolve(stream);
  342. }
  343. })
  344. .catch(error => {
  345. logger.warn(`Failed to get access to local media. ${error} ${JSON.stringify(constraints)}`);
  346. const jitsiError = new JitsiTrackError(error, constraints, umDevices);
  347. if (!timeoutExpired) {
  348. if (typeof gumTimeout !== 'undefined') {
  349. clearTimeout(gumTimeout);
  350. }
  351. reject(jitsiError);
  352. }
  353. if (jitsiError.name === JitsiTrackErrors.PERMISSION_DENIED) {
  354. this._updateGrantedPermissions(umDevices, undefined);
  355. }
  356. });
  357. });
  358. }
  359. /**
  360. * Acquire a display stream via the screenObtainer. This requires extra
  361. * logic compared to use screenObtainer versus normal device capture logic
  362. * in RTCUtils#_getUserMedia.
  363. *
  364. * @param {Object} options - Optional parameters.
  365. * @returns {Promise} A promise which will be resolved with an object which
  366. * contains the acquired display stream. If desktop sharing is not supported
  367. * then a rejected promise will be returned.
  368. */
  369. _getDesktopMedia(options) {
  370. if (!screenObtainer.isSupported()) {
  371. return Promise.reject(new Error('Desktop sharing is not supported!'));
  372. }
  373. return new Promise((resolve, reject) => {
  374. screenObtainer.obtainStream(
  375. stream => {
  376. resolve(stream);
  377. },
  378. error => {
  379. reject(error);
  380. },
  381. options);
  382. });
  383. }
  384. /**
  385. * Private utility for determining if the passed in MediaStream contains
  386. * tracks of the type(s) specified in the requested devices.
  387. *
  388. * @param {string[]} requestedDevices - The track types that are expected to
  389. * be includes in the stream.
  390. * @param {MediaStream} stream - The MediaStream to check if it has the
  391. * expected track types.
  392. * @returns {string[]} An array of string with the missing track types. The
  393. * array will be empty if all requestedDevices are found in the stream.
  394. */
  395. _getMissingTracks(requestedDevices = [], stream) {
  396. const missingDevices = [];
  397. const audioDeviceRequested = requestedDevices.includes('audio');
  398. const audioTracksReceived
  399. = stream && stream.getAudioTracks().length > 0;
  400. if (audioDeviceRequested && !audioTracksReceived) {
  401. missingDevices.push('audio');
  402. }
  403. const videoDeviceRequested = requestedDevices.includes('video');
  404. const videoTracksReceived
  405. = stream && stream.getVideoTracks().length > 0;
  406. if (videoDeviceRequested && !videoTracksReceived) {
  407. missingDevices.push('video');
  408. }
  409. return missingDevices;
  410. }
  411. /**
  412. * Event handler for the 'devicechange' event.
  413. *
  414. * @param {MediaDeviceInfo[]} devices - list of media devices.
  415. * @emits RTCEvents.DEVICE_LIST_CHANGED
  416. */
  417. _onMediaDevicesListChanged(devicesReceived) {
  418. availableDevices = devicesReceived.slice(0);
  419. logger.info('list of media devices has changed:', availableDevices);
  420. sendDeviceListToAnalytics(availableDevices);
  421. // Used by tracks to update the real device id before the consumer of lib-jitsi-meet receives the
  422. // new device list.
  423. this.eventEmitter.emit(RTCEvents.DEVICE_LIST_WILL_CHANGE, availableDevices);
  424. this.eventEmitter.emit(RTCEvents.DEVICE_LIST_CHANGED, availableDevices);
  425. }
  426. /**
  427. * Update known devices.
  428. *
  429. * @param {Array<Object>} pds - The new devices.
  430. * @returns {void}
  431. *
  432. * NOTE: Use this function as a shared callback to handle both the devicechange event and the
  433. * polling implementations.
  434. * This prevents duplication and works around a chrome bug (verified to occur on 68) where devicechange
  435. * fires twice in a row, which can cause async post devicechange processing to collide.
  436. */
  437. _updateKnownDevices(pds) {
  438. if (compareAvailableMediaDevices(pds)) {
  439. this._onMediaDevicesListChanged(pds);
  440. }
  441. }
  442. /**
  443. * Updates the granted permissions based on the options we requested and the
  444. * streams we received.
  445. * @param um the options we requested to getUserMedia.
  446. * @param stream the stream we received from calling getUserMedia.
  447. */
  448. _updateGrantedPermissions(um, stream) {
  449. const audioTracksReceived
  450. = Boolean(stream) && stream.getAudioTracks().length > 0;
  451. const videoTracksReceived
  452. = Boolean(stream) && stream.getVideoTracks().length > 0;
  453. const grantedPermissions = {};
  454. if (um.indexOf('video') !== -1) {
  455. grantedPermissions.video = videoTracksReceived;
  456. }
  457. if (um.indexOf('audio') !== -1) {
  458. grantedPermissions.audio = audioTracksReceived;
  459. }
  460. this.eventEmitter.emit(RTCEvents.PERMISSIONS_CHANGED, grantedPermissions);
  461. }
  462. /**
  463. * Gets streams from specified device types. This function intentionally
  464. * ignores errors for upstream to catch and handle instead.
  465. *
  466. * @param {Object} options - A hash describing what devices to get and
  467. * relevant constraints.
  468. * @param {string[]} options.devices - The types of media to capture. Valid
  469. * values are "desktop", "audio", and "video".
  470. * @param {Object} options.desktopSharingFrameRate
  471. * @param {Object} options.desktopSharingFrameRate.min - Minimum fps
  472. * @param {Object} options.desktopSharingFrameRate.max - Maximum fps
  473. * @param {String} options.desktopSharingSourceDevice - The device id or
  474. * label for a video input source that should be used for screensharing.
  475. * @param {Array<string>} options.desktopSharingSources - The types of sources ("screen", "window", etc)
  476. * from which the user can select what to share.
  477. * @returns {Promise} The promise, when successful, will return an array of
  478. * meta data for the requested device type, which includes the stream and
  479. * track. If an error occurs, it will be deferred to the caller for
  480. * handling.
  481. */
  482. obtainAudioAndVideoPermissions(options) {
  483. const {
  484. timeout,
  485. ...otherOptions
  486. } = options;
  487. const mediaStreamsMetaData = [];
  488. let constraints = {};
  489. // Declare private functions to be used in the promise chain below.
  490. // These functions are declared in the scope of this function because
  491. // they are not being used anywhere else, so only this function needs to
  492. // know about them.
  493. /**
  494. * Executes a request for desktop media if specified in options.
  495. *
  496. * @returns {Promise}
  497. */
  498. const maybeRequestDesktopDevice = function() {
  499. const umDevices = otherOptions.devices || [];
  500. const isDesktopDeviceRequested
  501. = umDevices.indexOf('desktop') !== -1;
  502. if (!isDesktopDeviceRequested) {
  503. return Promise.resolve();
  504. }
  505. const {
  506. desktopSharingSourceDevice,
  507. desktopSharingSources,
  508. resolution
  509. } = otherOptions;
  510. // Attempt to use a video input device as a screenshare source if
  511. // the option is defined.
  512. if (desktopSharingSourceDevice) {
  513. const matchingDevice
  514. = availableDevices && availableDevices.find(device =>
  515. device.kind === 'videoinput'
  516. && (device.deviceId === desktopSharingSourceDevice
  517. || device.label === desktopSharingSourceDevice));
  518. if (!matchingDevice) {
  519. return Promise.reject(new JitsiTrackError(
  520. { name: 'ConstraintNotSatisfiedError' },
  521. {},
  522. [ desktopSharingSourceDevice ]
  523. ));
  524. }
  525. const requestedDevices = [ 'video' ];
  526. const deviceConstraints = {
  527. video: {
  528. deviceId: matchingDevice.deviceId
  529. // frameRate is omited here on purpose since this is a device that we'll pretend is a screen.
  530. }
  531. };
  532. return this._getUserMedia(requestedDevices, deviceConstraints, timeout)
  533. .then(stream => {
  534. return {
  535. sourceType: 'device',
  536. stream
  537. };
  538. });
  539. }
  540. return this._getDesktopMedia({
  541. desktopSharingSources,
  542. resolution });
  543. }.bind(this);
  544. /**
  545. * Creates a meta data object about the passed in desktopStream and
  546. * pushes the meta data to the internal array mediaStreamsMetaData to be
  547. * returned later.
  548. *
  549. * @param {MediaStreamTrack} desktopStream - A track for a desktop
  550. * capture.
  551. * @returns {void}
  552. */
  553. const maybeCreateAndAddDesktopTrack = function(desktopStream) {
  554. if (!desktopStream) {
  555. return;
  556. }
  557. const { stream, sourceId, sourceType } = desktopStream;
  558. const desktopAudioTracks = stream.getAudioTracks();
  559. if (desktopAudioTracks.length) {
  560. const desktopAudioStream = new MediaStream(desktopAudioTracks);
  561. mediaStreamsMetaData.push({
  562. stream: desktopAudioStream,
  563. sourceId,
  564. sourceType,
  565. track: desktopAudioStream.getAudioTracks()[0]
  566. });
  567. }
  568. const desktopVideoTracks = stream.getVideoTracks();
  569. if (desktopVideoTracks.length) {
  570. const desktopVideoStream = new MediaStream(desktopVideoTracks);
  571. mediaStreamsMetaData.push({
  572. stream: desktopVideoStream,
  573. sourceId,
  574. sourceType,
  575. track: desktopVideoStream.getVideoTracks()[0],
  576. videoType: VideoType.DESKTOP
  577. });
  578. }
  579. };
  580. /**
  581. * Executes a request for audio and/or video, as specified in options.
  582. * By default both audio and video will be captured if options.devices
  583. * is not defined.
  584. *
  585. * @returns {Promise}
  586. */
  587. const maybeRequestCaptureDevices = function() {
  588. const umDevices = otherOptions.devices || [ 'audio', 'video' ];
  589. const requestedCaptureDevices = umDevices.filter(device => device === 'audio' || device === 'video');
  590. if (!requestedCaptureDevices.length) {
  591. return Promise.resolve();
  592. }
  593. constraints = getConstraints(requestedCaptureDevices, otherOptions);
  594. logger.info('Got media constraints: ', JSON.stringify(constraints));
  595. return this._getUserMedia(requestedCaptureDevices, constraints, timeout);
  596. }.bind(this);
  597. /**
  598. * Splits the passed in media stream into separate audio and video
  599. * streams and creates meta data objects for each and pushes them to the
  600. * internal array mediaStreamsMetaData to be returned later.
  601. *
  602. * @param {MediaStreamTrack} avStream - A track for with audio and/or
  603. * video track.
  604. * @returns {void}
  605. */
  606. const maybeCreateAndAddAVTracks = function(avStream) {
  607. if (!avStream) {
  608. return;
  609. }
  610. const audioTracks = avStream.getAudioTracks();
  611. if (audioTracks.length) {
  612. const audioStream = new MediaStream(audioTracks);
  613. mediaStreamsMetaData.push({
  614. constraints: constraints.audio,
  615. stream: audioStream,
  616. track: audioStream.getAudioTracks()[0],
  617. effects: otherOptions.effects
  618. });
  619. }
  620. const videoTracks = avStream.getVideoTracks();
  621. if (videoTracks.length) {
  622. const videoStream = new MediaStream(videoTracks);
  623. mediaStreamsMetaData.push({
  624. constraints: constraints.video,
  625. stream: videoStream,
  626. track: videoStream.getVideoTracks()[0],
  627. videoType: VideoType.CAMERA,
  628. effects: otherOptions.effects
  629. });
  630. }
  631. };
  632. return maybeRequestDesktopDevice()
  633. .then(maybeCreateAndAddDesktopTrack)
  634. .then(maybeRequestCaptureDevices)
  635. .then(maybeCreateAndAddAVTracks)
  636. .then(() => mediaStreamsMetaData)
  637. .catch(error => {
  638. mediaStreamsMetaData.forEach(({ stream }) => {
  639. this.stopMediaStream(stream);
  640. });
  641. return Promise.reject(error);
  642. });
  643. }
  644. /**
  645. * Returns true if changing the input (camera / microphone) or output
  646. * (audio) device is supported and false if not.
  647. * @params {string} [deviceType] - type of device to change. Default is
  648. * undefined or 'input', 'output' - for audio output device change.
  649. * @returns {boolean} true if available, false otherwise.
  650. */
  651. isDeviceChangeAvailable(deviceType) {
  652. if (deviceType === 'output' || deviceType === 'audiooutput') {
  653. return isAudioOutputDeviceChangeAvailable;
  654. }
  655. return true;
  656. }
  657. /**
  658. * A method to handle stopping of the stream.
  659. * One point to handle the differences in various implementations.
  660. * @param mediaStream MediaStream object to stop.
  661. */
  662. stopMediaStream(mediaStream) {
  663. if (!mediaStream) {
  664. return;
  665. }
  666. mediaStream.getTracks().forEach(track => {
  667. if (track.stop) {
  668. track.stop();
  669. }
  670. });
  671. // leave stop for implementation still using it
  672. if (mediaStream.stop) {
  673. mediaStream.stop();
  674. }
  675. // The MediaStream implementation of the react-native-webrtc project has
  676. // an explicit release method that is to be invoked in order to release
  677. // used resources such as memory.
  678. if (mediaStream.release) {
  679. mediaStream.release();
  680. }
  681. }
  682. /**
  683. * Returns whether the desktop sharing is enabled or not.
  684. * @returns {boolean}
  685. */
  686. isDesktopSharingEnabled() {
  687. return screenObtainer.isSupported();
  688. }
  689. /**
  690. * Sets current audio output device.
  691. * @param {string} deviceId - id of 'audiooutput' device from
  692. * navigator.mediaDevices.enumerateDevices(), 'default' for default
  693. * device
  694. * @returns {Promise} - resolves when audio output is changed, is rejected
  695. * otherwise
  696. */
  697. setAudioOutputDevice(deviceId) {
  698. if (!this.isDeviceChangeAvailable('output')) {
  699. return Promise.reject(
  700. new Error('Audio output device change is not supported'));
  701. }
  702. return featureDetectionAudioEl.setSinkId(deviceId)
  703. .then(() => {
  704. audioOutputDeviceId = deviceId;
  705. audioOutputChanged = true;
  706. logger.debug(`Audio output device set to ${deviceId}`);
  707. this.eventEmitter.emit(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  708. deviceId);
  709. });
  710. }
  711. /**
  712. * Sets the capture frame rate for desktop tracks.
  713. *
  714. * @param {number} maxFps - max fps to be used as the capture frame rate.
  715. * @returns {void}
  716. */
  717. setDesktopSharingFrameRate(maxFps) {
  718. screenObtainer.setDesktopSharingFrameRate(maxFps);
  719. }
  720. /**
  721. * Returns currently used audio output device id, '' stands for default
  722. * device
  723. * @returns {string}
  724. */
  725. getAudioOutputDevice() {
  726. return audioOutputDeviceId;
  727. }
  728. /**
  729. * Returns list of available media devices if its obtained, otherwise an
  730. * empty array is returned/
  731. * @returns {Array} list of available media devices.
  732. */
  733. getCurrentlyAvailableMediaDevices() {
  734. return availableDevices;
  735. }
  736. /**
  737. * Returns event data for device to be reported to stats.
  738. * @returns {MediaDeviceInfo} device.
  739. */
  740. getEventDataForActiveDevice(device) {
  741. const deviceList = [];
  742. const deviceData = {
  743. deviceId: device.deviceId,
  744. kind: device.kind,
  745. label: device.label,
  746. groupId: device.groupId
  747. };
  748. deviceList.push(deviceData);
  749. return { deviceList };
  750. }
  751. /**
  752. * Returns <tt>true<tt/> if a WebRTC MediaStream identified by given stream
  753. * ID is considered a valid "user" stream which means that it's not a
  754. * "receive only" stream nor a "mixed" JVB stream.
  755. *
  756. * Clients that implement Unified Plan, such as Firefox use recvonly
  757. * "streams/channels/tracks" for receiving remote stream/tracks, as opposed
  758. * to Plan B where there are only 3 channels: audio, video and data.
  759. *
  760. * @param {string} streamId The id of WebRTC MediaStream.
  761. * @returns {boolean}
  762. */
  763. isUserStreamById(streamId) {
  764. return streamId && streamId !== 'mixedmslabel' && streamId !== 'default';
  765. }
  766. }
  767. export default new RTCUtils();