Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

RTCUtils.js 52KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529
  1. /* global
  2. __filename,
  3. MediaStreamTrack,
  4. RTCIceCandidate: true,
  5. RTCPeerConnection,
  6. RTCSessionDescription: true
  7. */
  8. import EventEmitter from 'events';
  9. import { getLogger } from 'jitsi-meet-logger';
  10. import clonedeep from 'lodash.clonedeep';
  11. import JitsiTrackError from '../../JitsiTrackError';
  12. import * as JitsiTrackErrors from '../../JitsiTrackErrors';
  13. import CameraFacingMode from '../../service/RTC/CameraFacingMode';
  14. import * as MediaType from '../../service/RTC/MediaType';
  15. import RTCEvents from '../../service/RTC/RTCEvents';
  16. import Resolutions from '../../service/RTC/Resolutions';
  17. import VideoType from '../../service/RTC/VideoType';
  18. import { AVAILABLE_DEVICE } from '../../service/statistics/AnalyticsEvents';
  19. import browser from '../browser';
  20. import SDPUtil from '../sdp/SDPUtil';
  21. import Statistics from '../statistics/statistics';
  22. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  23. import Listenable from '../util/Listenable';
  24. import screenObtainer from './ScreenObtainer';
  25. const logger = getLogger(__filename);
  26. // Require adapter only for certain browsers. This is being done for
  27. // react-native, which has its own shims, and while browsers are being migrated
  28. // over to use adapter's shims.
  29. if (browser.usesAdapter()) {
  30. require('webrtc-adapter');
  31. }
  32. const eventEmitter = new EventEmitter();
  33. const AVAILABLE_DEVICES_POLL_INTERVAL_TIME = 3000; // ms
  34. /**
  35. * Default resolution to obtain for video tracks if no resolution is specified.
  36. * This default is used for old gum flow only, as new gum flow uses
  37. * {@link DEFAULT_CONSTRAINTS}.
  38. */
  39. const OLD_GUM_DEFAULT_RESOLUTION = 720;
  40. /**
  41. * Default devices to obtain when no specific devices are specified. This
  42. * default is used for old gum flow only.
  43. */
  44. const OLD_GUM_DEFAULT_DEVICES = [ 'audio', 'video' ];
  45. /**
  46. * Default MediaStreamConstraints to use for calls to getUserMedia.
  47. *
  48. * @private
  49. */
  50. const DEFAULT_CONSTRAINTS = {
  51. video: {
  52. height: {
  53. ideal: 720,
  54. max: 720,
  55. min: 180
  56. },
  57. width: {
  58. ideal: 1280,
  59. max: 1280,
  60. min: 320
  61. }
  62. }
  63. };
  64. /**
  65. * The default frame rate for Screen Sharing.
  66. */
  67. export const SS_DEFAULT_FRAME_RATE = 5;
  68. // Currently audio output device change is supported only in Chrome and
  69. // default output always has 'default' device ID
  70. let audioOutputDeviceId = 'default'; // default device
  71. // whether user has explicitly set a device to use
  72. let audioOutputChanged = false;
  73. // Disables all audio processing
  74. let disableAP = false;
  75. // Disables Acoustic Echo Cancellation
  76. let disableAEC = false;
  77. // Disables Noise Suppression
  78. let disableNS = false;
  79. // Disables Automatic Gain Control
  80. let disableAGC = false;
  81. // Disables Highpass Filter
  82. let disableHPF = false;
  83. // Enables stereo.
  84. let stereo = null;
  85. const featureDetectionAudioEl = document.createElement('audio');
  86. const isAudioOutputDeviceChangeAvailable
  87. = typeof featureDetectionAudioEl.setSinkId !== 'undefined';
  88. let availableDevices = [];
  89. let availableDevicesPollTimer;
  90. /**
  91. * An empty function.
  92. */
  93. function emptyFuncton() {
  94. // no-op
  95. }
  96. /**
  97. *
  98. * @param constraints
  99. * @param isNewStyleConstraintsSupported
  100. * @param resolution
  101. */
  102. function setResolutionConstraints(
  103. constraints,
  104. isNewStyleConstraintsSupported,
  105. resolution) {
  106. if (Resolutions[resolution]) {
  107. if (isNewStyleConstraintsSupported) {
  108. constraints.video.width = {
  109. ideal: Resolutions[resolution].width
  110. };
  111. constraints.video.height = {
  112. ideal: Resolutions[resolution].height
  113. };
  114. }
  115. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  116. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  117. }
  118. if (constraints.video.mandatory.minWidth) {
  119. constraints.video.mandatory.maxWidth
  120. = constraints.video.mandatory.minWidth;
  121. }
  122. if (constraints.video.mandatory.minHeight) {
  123. constraints.video.mandatory.maxHeight
  124. = constraints.video.mandatory.minHeight;
  125. }
  126. }
  127. /**
  128. * @param {string[]} um required user media types
  129. *
  130. * @param {Object} [options={}] optional parameters
  131. * @param {string} options.resolution
  132. * @param {number} options.bandwidth
  133. * @param {number} options.fps
  134. * @param {string} options.desktopStream
  135. * @param {string} options.cameraDeviceId
  136. * @param {string} options.micDeviceId
  137. * @param {CameraFacingMode} options.facingMode
  138. * @param {bool} firefox_fake_device
  139. * @param {Object} options.frameRate - used only for dekstop sharing.
  140. * @param {Object} options.frameRate.min - Minimum fps
  141. * @param {Object} options.frameRate.max - Maximum fps
  142. * @param {bool} options.screenShareAudio - Used by electron clients to
  143. * enable system audio screen sharing.
  144. */
  145. function getConstraints(um, options = {}) {
  146. const constraints = {
  147. audio: false,
  148. video: false
  149. };
  150. // Don't mix new and old style settings for Chromium as this leads
  151. // to TypeError in new Chromium versions. @see
  152. // https://bugs.chromium.org/p/chromium/issues/detail?id=614716
  153. // This is a temporary solution, in future we will fully split old and
  154. // new style constraints when new versions of Chromium and Firefox will
  155. // have stable support of new constraints format. For more information
  156. // @see https://github.com/jitsi/lib-jitsi-meet/pull/136
  157. const isNewStyleConstraintsSupported
  158. = browser.isFirefox()
  159. || browser.isWebKitBased()
  160. || browser.isReactNative();
  161. if (um.indexOf('video') >= 0) {
  162. // same behaviour as true
  163. constraints.video = { mandatory: {},
  164. optional: [] };
  165. if (options.cameraDeviceId) {
  166. if (isNewStyleConstraintsSupported) {
  167. // New style of setting device id.
  168. constraints.video.deviceId = options.cameraDeviceId;
  169. }
  170. // Old style.
  171. constraints.video.mandatory.sourceId = options.cameraDeviceId;
  172. } else {
  173. // Prefer the front i.e. user-facing camera (to the back i.e.
  174. // environment-facing camera, for example).
  175. // TODO: Maybe use "exact" syntax if options.facingMode is defined,
  176. // but this probably needs to be decided when updating other
  177. // constraints, as we currently don't use "exact" syntax anywhere.
  178. const facingMode = options.facingMode || CameraFacingMode.USER;
  179. if (isNewStyleConstraintsSupported) {
  180. constraints.video.facingMode = facingMode;
  181. }
  182. constraints.video.optional.push({
  183. facingMode
  184. });
  185. }
  186. if (options.minFps || options.maxFps || options.fps) {
  187. // for some cameras it might be necessary to request 30fps
  188. // so they choose 30fps mjpg over 10fps yuy2
  189. if (options.minFps || options.fps) {
  190. // Fall back to options.fps for backwards compatibility
  191. options.minFps = options.minFps || options.fps;
  192. constraints.video.mandatory.minFrameRate = options.minFps;
  193. }
  194. if (options.maxFps) {
  195. constraints.video.mandatory.maxFrameRate = options.maxFps;
  196. }
  197. }
  198. setResolutionConstraints(
  199. constraints, isNewStyleConstraintsSupported, options.resolution);
  200. }
  201. if (um.indexOf('audio') >= 0) {
  202. if (browser.isReactNative()) {
  203. // The react-native-webrtc project that we're currently using
  204. // expects the audio constraint to be a boolean.
  205. constraints.audio = true;
  206. } else if (browser.isFirefox()) {
  207. if (options.micDeviceId) {
  208. constraints.audio = {
  209. mandatory: {},
  210. deviceId: options.micDeviceId, // new style
  211. optional: [ {
  212. sourceId: options.micDeviceId // old style
  213. } ] };
  214. } else {
  215. constraints.audio = true;
  216. }
  217. } else {
  218. // same behaviour as true
  219. constraints.audio = { mandatory: {},
  220. optional: [] };
  221. if (options.micDeviceId) {
  222. if (isNewStyleConstraintsSupported) {
  223. // New style of setting device id.
  224. constraints.audio.deviceId = options.micDeviceId;
  225. }
  226. // Old style.
  227. constraints.audio.optional.push({
  228. sourceId: options.micDeviceId
  229. });
  230. }
  231. // if it is good enough for hangouts...
  232. constraints.audio.optional.push(
  233. { echoCancellation: !disableAEC && !disableAP },
  234. { googEchoCancellation: !disableAEC && !disableAP },
  235. { googAutoGainControl: !disableAGC && !disableAP },
  236. { googNoiseSuppression: !disableNS && !disableAP },
  237. { googHighpassFilter: !disableHPF && !disableAP },
  238. { googNoiseSuppression2: !disableNS && !disableAP },
  239. { googEchoCancellation2: !disableAEC && !disableAP },
  240. { googAutoGainControl2: !disableAGC && !disableAP }
  241. );
  242. }
  243. }
  244. if (um.indexOf('screen') >= 0) {
  245. if (browser.isChrome()) {
  246. constraints.video = {
  247. mandatory: getSSConstraints({
  248. ...options,
  249. source: 'screen'
  250. }),
  251. optional: []
  252. };
  253. } else if (browser.isFirefox()) {
  254. constraints.video = {
  255. mozMediaSource: 'window',
  256. mediaSource: 'window',
  257. frameRate: options.frameRate || {
  258. min: SS_DEFAULT_FRAME_RATE,
  259. max: SS_DEFAULT_FRAME_RATE
  260. }
  261. };
  262. } else {
  263. const errmsg
  264. = '\'screen\' WebRTC media source is supported only in Chrome'
  265. + ' and Firefox';
  266. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  267. logger.error(errmsg);
  268. }
  269. }
  270. if (um.indexOf('desktop') >= 0) {
  271. constraints.video = {
  272. mandatory: getSSConstraints({
  273. ...options,
  274. source: 'desktop'
  275. }),
  276. optional: []
  277. };
  278. // Audio screen sharing for electron only works for screen type devices.
  279. // i.e. when the user shares the whole desktop.
  280. if (browser.isElectron() && options.screenShareAudio
  281. && (options.desktopStream.indexOf('screen') >= 0)) {
  282. // Provide constraints as described by the electron desktop capturer
  283. // documentation here:
  284. // https://www.electronjs.org/docs/api/desktop-capturer
  285. // Note. The documentation specifies that chromeMediaSourceId should not be present
  286. // which, in the case a users has multiple monitors, leads to them being shared all
  287. // at once. However we tested with chromeMediaSourceId present and it seems to be
  288. // working properly and also takes care of the previously mentioned issue.
  289. constraints.audio = { mandatory: {
  290. chromeMediaSource: constraints.video.mandatory.chromeMediaSource
  291. } };
  292. }
  293. }
  294. if (options.bandwidth) {
  295. if (!constraints.video) {
  296. // same behaviour as true
  297. constraints.video = { mandatory: {},
  298. optional: [] };
  299. }
  300. constraints.video.optional.push({ bandwidth: options.bandwidth });
  301. }
  302. // we turn audio for both audio and video tracks, the fake audio & video
  303. // seems to work only when enabled in one getUserMedia call, we cannot get
  304. // fake audio separate by fake video this later can be a problem with some
  305. // of the tests
  306. if (browser.isFirefox() && options.firefox_fake_device) {
  307. // seems to be fixed now, removing this experimental fix, as having
  308. // multiple audio tracks brake the tests
  309. // constraints.audio = true;
  310. constraints.fake = true;
  311. }
  312. return constraints;
  313. }
  314. /**
  315. * Creates a constraints object to be passed into a call to getUserMedia.
  316. *
  317. * @param {Array} um - An array of user media types to get. The accepted
  318. * types are "video", "audio", and "desktop."
  319. * @param {Object} options - Various values to be added to the constraints.
  320. * @param {string} options.cameraDeviceId - The device id for the video
  321. * capture device to get video from.
  322. * @param {Object} options.constraints - Default constraints object to use
  323. * as a base for the returned constraints.
  324. * @param {Object} options.desktopStream - The desktop source id from which
  325. * to capture a desktop sharing video.
  326. * @param {string} options.facingMode - Which direction the camera is
  327. * pointing to.
  328. * @param {string} options.micDeviceId - The device id for the audio capture
  329. * device to get audio from.
  330. * @param {Object} options.frameRate - used only for dekstop sharing.
  331. * @param {Object} options.frameRate.min - Minimum fps
  332. * @param {Object} options.frameRate.max - Maximum fps
  333. * @private
  334. * @returns {Object}
  335. */
  336. function newGetConstraints(um = [], options = {}) {
  337. // Create a deep copy of the constraints to avoid any modification of
  338. // the passed in constraints object.
  339. const constraints = clonedeep(options.constraints || DEFAULT_CONSTRAINTS);
  340. if (um.indexOf('video') >= 0) {
  341. if (!constraints.video) {
  342. constraints.video = {};
  343. }
  344. // Override the constraints on Safari because of the following webkit bug.
  345. // https://bugs.webkit.org/show_bug.cgi?id=210932
  346. // Camera doesn't start on older macOS versions if min/max constraints are specified.
  347. // TODO: remove this hack when the bug fix is available on Mojave, Sierra and High Sierra.
  348. if (browser.isWebKitBased()) {
  349. if (constraints.video.height && constraints.video.height.ideal) {
  350. constraints.video.height = { ideal: clonedeep(constraints.video.height.ideal) };
  351. } else {
  352. logger.warn('Ideal camera height missing, camera may not start properly');
  353. }
  354. if (constraints.video.width && constraints.video.width.ideal) {
  355. constraints.video.width = { ideal: clonedeep(constraints.video.width.ideal) };
  356. } else {
  357. logger.warn('Ideal camera width missing, camera may not start properly');
  358. }
  359. }
  360. if (options.cameraDeviceId) {
  361. constraints.video.deviceId = options.cameraDeviceId;
  362. } else {
  363. const facingMode = options.facingMode || CameraFacingMode.USER;
  364. constraints.video.facingMode = facingMode;
  365. }
  366. } else {
  367. constraints.video = false;
  368. }
  369. if (um.indexOf('audio') >= 0) {
  370. if (!constraints.audio || typeof constraints.audio === 'boolean') {
  371. constraints.audio = {};
  372. }
  373. constraints.audio = {
  374. autoGainControl: !disableAGC && !disableAP,
  375. deviceId: options.micDeviceId,
  376. echoCancellation: !disableAEC && !disableAP,
  377. noiseSuppression: !disableNS && !disableAP
  378. };
  379. if (stereo) {
  380. Object.assign(constraints.audio, { channelCount: 2 });
  381. }
  382. } else {
  383. constraints.audio = false;
  384. }
  385. if (um.indexOf('desktop') >= 0) {
  386. if (!constraints.video || typeof constraints.video === 'boolean') {
  387. constraints.video = {};
  388. }
  389. constraints.video = {
  390. mandatory: getSSConstraints({
  391. ...options,
  392. source: 'desktop'
  393. })
  394. };
  395. }
  396. return constraints;
  397. }
  398. /**
  399. * Generates GUM constraints for screen sharing.
  400. *
  401. * @param {Object} options - The options passed to
  402. * <tt>obtainAudioAndVideoPermissions</tt>.
  403. * @returns {Object} - GUM constraints.
  404. *
  405. * TODO: Currently only the new GUM flow and Chrome is using the method. We
  406. * should make it work for all use cases.
  407. */
  408. function getSSConstraints(options = {}) {
  409. const {
  410. desktopStream,
  411. frameRate = {
  412. min: SS_DEFAULT_FRAME_RATE,
  413. max: SS_DEFAULT_FRAME_RATE
  414. }
  415. } = options;
  416. const { max, min } = frameRate;
  417. const constraints = {
  418. chromeMediaSource: options.source,
  419. maxWidth: window.screen.width,
  420. maxHeight: window.screen.height
  421. };
  422. if (typeof min === 'number') {
  423. constraints.minFrameRate = min;
  424. }
  425. if (typeof max === 'number') {
  426. constraints.maxFrameRate = max;
  427. }
  428. if (typeof desktopStream !== 'undefined') {
  429. constraints.chromeMediaSourceId = desktopStream;
  430. }
  431. return constraints;
  432. }
  433. /**
  434. * Updates the granted permissions based on the options we requested and the
  435. * streams we received.
  436. * @param um the options we requested to getUserMedia.
  437. * @param stream the stream we received from calling getUserMedia.
  438. */
  439. function updateGrantedPermissions(um, stream) {
  440. const audioTracksReceived
  441. = Boolean(stream) && stream.getAudioTracks().length > 0;
  442. const videoTracksReceived
  443. = Boolean(stream) && stream.getVideoTracks().length > 0;
  444. const grantedPermissions = {};
  445. if (um.indexOf('video') !== -1) {
  446. grantedPermissions.video = videoTracksReceived;
  447. }
  448. if (um.indexOf('audio') !== -1) {
  449. grantedPermissions.audio = audioTracksReceived;
  450. }
  451. eventEmitter.emit(RTCEvents.PERMISSIONS_CHANGED, grantedPermissions);
  452. }
  453. /**
  454. * Checks if new list of available media devices differs from previous one.
  455. * @param {MediaDeviceInfo[]} newDevices - list of new devices.
  456. * @returns {boolean} - true if list is different, false otherwise.
  457. */
  458. function compareAvailableMediaDevices(newDevices) {
  459. if (newDevices.length !== availableDevices.length) {
  460. return true;
  461. }
  462. /* eslint-disable newline-per-chained-call */
  463. return (
  464. newDevices.map(mediaDeviceInfoToJSON).sort().join('')
  465. !== availableDevices
  466. .map(mediaDeviceInfoToJSON).sort().join(''));
  467. /* eslint-enable newline-per-chained-call */
  468. /**
  469. *
  470. * @param info
  471. */
  472. function mediaDeviceInfoToJSON(info) {
  473. return JSON.stringify({
  474. kind: info.kind,
  475. deviceId: info.deviceId,
  476. groupId: info.groupId,
  477. label: info.label,
  478. facing: info.facing
  479. });
  480. }
  481. }
  482. /**
  483. * Sends analytics event with the passed device list.
  484. *
  485. * @param {Array<MediaDeviceInfo>} deviceList - List with info about the
  486. * available devices.
  487. * @returns {void}
  488. */
  489. function sendDeviceListToAnalytics(deviceList) {
  490. const audioInputDeviceCount
  491. = deviceList.filter(d => d.kind === 'audioinput').length;
  492. const audioOutputDeviceCount
  493. = deviceList.filter(d => d.kind === 'audiooutput').length;
  494. const videoInputDeviceCount
  495. = deviceList.filter(d => d.kind === 'videoinput').length;
  496. const videoOutputDeviceCount
  497. = deviceList.filter(d => d.kind === 'videooutput').length;
  498. deviceList.forEach(device => {
  499. const attributes = {
  500. 'audio_input_device_count': audioInputDeviceCount,
  501. 'audio_output_device_count': audioOutputDeviceCount,
  502. 'video_input_device_count': videoInputDeviceCount,
  503. 'video_output_device_count': videoOutputDeviceCount,
  504. 'device_id': device.deviceId,
  505. 'device_group_id': device.groupId,
  506. 'device_kind': device.kind,
  507. 'device_label': device.label
  508. };
  509. Statistics.sendAnalytics(AVAILABLE_DEVICE, attributes);
  510. });
  511. }
  512. /**
  513. * Update known devices.
  514. *
  515. * @param {Array<Object>} pds - The new devices.
  516. * @returns {void}
  517. *
  518. * NOTE: Use this function as a shared callback to handle both the devicechange event and the polling implementations.
  519. * This prevents duplication and works around a chrome bug (verified to occur on 68) where devicechange fires twice in
  520. * a row, which can cause async post devicechange processing to collide.
  521. */
  522. function updateKnownDevices(pds) {
  523. if (compareAvailableMediaDevices(pds)) {
  524. onMediaDevicesListChanged(pds);
  525. }
  526. }
  527. /**
  528. * Event handler for the 'devicechange' event.
  529. *
  530. * @param {MediaDeviceInfo[]} devices - list of media devices.
  531. * @emits RTCEvents.DEVICE_LIST_CHANGED
  532. */
  533. function onMediaDevicesListChanged(devicesReceived) {
  534. availableDevices = devicesReceived.slice(0);
  535. logger.info('list of media devices has changed:', availableDevices);
  536. sendDeviceListToAnalytics(availableDevices);
  537. // Used by tracks to update the real device id before the consumer of lib-jitsi-meet receives the new device list.
  538. eventEmitter.emit(RTCEvents.DEVICE_LIST_WILL_CHANGE, availableDevices);
  539. eventEmitter.emit(RTCEvents.DEVICE_LIST_CHANGED, availableDevices);
  540. }
  541. /**
  542. * Handles the newly created Media Streams.
  543. * @param streams the new Media Streams
  544. * @param resolution the resolution of the video streams
  545. * @returns {*[]} object that describes the new streams
  546. */
  547. function handleLocalStream(streams, resolution) {
  548. let audioStream, desktopStream, videoStream;
  549. const res = [];
  550. // XXX The function obtainAudioAndVideoPermissions has examined the type of
  551. // the browser, its capabilities, etc. and has taken the decision whether to
  552. // invoke getUserMedia per device (e.g. Firefox) or once for both audio and
  553. // video (e.g. Chrome). In order to not duplicate the logic here, examine
  554. // the specified streams and figure out what we've received based on
  555. // obtainAudioAndVideoPermissions' decision.
  556. if (streams) {
  557. // As mentioned above, certian types of browser (e.g. Chrome) support
  558. // (with a result which meets our requirements expressed bellow) calling
  559. // getUserMedia once for both audio and video.
  560. const audioVideo = streams.audioVideo;
  561. if (audioVideo) {
  562. const audioTracks = audioVideo.getAudioTracks();
  563. if (audioTracks.length) {
  564. audioStream = new MediaStream();
  565. for (let i = 0; i < audioTracks.length; i++) {
  566. audioStream.addTrack(audioTracks[i]);
  567. }
  568. }
  569. const videoTracks = audioVideo.getVideoTracks();
  570. if (videoTracks.length) {
  571. videoStream = new MediaStream();
  572. for (let j = 0; j < videoTracks.length; j++) {
  573. videoStream.addTrack(videoTracks[j]);
  574. }
  575. }
  576. audioVideo.release && audioVideo.release(false);
  577. } else {
  578. // On other types of browser (e.g. Firefox) we choose (namely,
  579. // obtainAudioAndVideoPermissions) to call getUserMedia per device
  580. // (type).
  581. audioStream = streams.audio;
  582. videoStream = streams.video;
  583. }
  584. desktopStream = streams.desktop;
  585. }
  586. if (desktopStream) {
  587. const { stream, sourceId, sourceType } = desktopStream;
  588. res.push({
  589. stream,
  590. sourceId,
  591. sourceType,
  592. track: stream.getVideoTracks()[0],
  593. mediaType: MediaType.VIDEO,
  594. videoType: VideoType.DESKTOP
  595. });
  596. }
  597. if (audioStream) {
  598. res.push({
  599. stream: audioStream,
  600. track: audioStream.getAudioTracks()[0],
  601. mediaType: MediaType.AUDIO,
  602. videoType: null
  603. });
  604. }
  605. if (videoStream) {
  606. res.push({
  607. stream: videoStream,
  608. track: videoStream.getVideoTracks()[0],
  609. mediaType: MediaType.VIDEO,
  610. videoType: VideoType.CAMERA,
  611. resolution
  612. });
  613. }
  614. return res;
  615. }
  616. /**
  617. *
  618. */
  619. class RTCUtils extends Listenable {
  620. /**
  621. *
  622. */
  623. constructor() {
  624. super(eventEmitter);
  625. }
  626. /**
  627. * Depending on the browser, sets difference instance methods for
  628. * interacting with user media and adds methods to native WebRTC-related
  629. * objects. Also creates an instance variable for peer connection
  630. * constraints.
  631. *
  632. * @param {Object} options
  633. * @returns {void}
  634. */
  635. init(options = {}) {
  636. if (typeof options.disableAEC === 'boolean') {
  637. disableAEC = options.disableAEC;
  638. logger.info(`Disable AEC: ${disableAEC}`);
  639. }
  640. if (typeof options.disableNS === 'boolean') {
  641. disableNS = options.disableNS;
  642. logger.info(`Disable NS: ${disableNS}`);
  643. }
  644. if (typeof options.disableAP === 'boolean') {
  645. disableAP = options.disableAP;
  646. logger.info(`Disable AP: ${disableAP}`);
  647. }
  648. if (typeof options.disableAGC === 'boolean') {
  649. disableAGC = options.disableAGC;
  650. logger.info(`Disable AGC: ${disableAGC}`);
  651. }
  652. if (typeof options.disableHPF === 'boolean') {
  653. disableHPF = options.disableHPF;
  654. logger.info(`Disable HPF: ${disableHPF}`);
  655. }
  656. if (typeof options.audioQuality?.stereo === 'boolean') {
  657. stereo = options.audioQuality.stereo;
  658. logger.info(`Stereo: ${stereo}`);
  659. }
  660. window.clearInterval(availableDevicesPollTimer);
  661. availableDevicesPollTimer = undefined;
  662. if (browser.usesNewGumFlow()) {
  663. this.RTCPeerConnectionType = RTCPeerConnection;
  664. this.attachMediaStream
  665. = wrapAttachMediaStream((element, stream) => {
  666. if (element) {
  667. element.srcObject = stream;
  668. }
  669. });
  670. this.getStreamID = ({ id }) => id;
  671. this.getTrackID = ({ id }) => id;
  672. } else if (browser.isReactNative()) {
  673. this.RTCPeerConnectionType = RTCPeerConnection;
  674. this.attachMediaStream = undefined; // Unused on React Native.
  675. this.getStreamID = function({ id }) {
  676. // The react-native-webrtc implementation that we use at the
  677. // time of this writing returns a number for the id of
  678. // MediaStream. Let's just say that a number contains no special
  679. // characters.
  680. return (
  681. typeof id === 'number'
  682. ? id
  683. : SDPUtil.filterSpecialChars(id));
  684. };
  685. this.getTrackID = ({ id }) => id;
  686. } else {
  687. const message = 'Endpoint does not appear to be WebRTC-capable';
  688. logger.error(message);
  689. throw new Error(message);
  690. }
  691. this.pcConstraints = browser.isChromiumBased() || browser.isReactNative()
  692. ? { optional: [
  693. { googScreencastMinBitrate: 100 },
  694. { googCpuOveruseDetection: true }
  695. ] }
  696. : {};
  697. screenObtainer.init(
  698. options,
  699. this.getUserMediaWithConstraints.bind(this));
  700. if (this.isDeviceListAvailable()) {
  701. this.enumerateDevices(ds => {
  702. availableDevices = ds.slice(0);
  703. logger.debug('Available devices: ', availableDevices);
  704. sendDeviceListToAnalytics(availableDevices);
  705. eventEmitter.emit(
  706. RTCEvents.DEVICE_LIST_AVAILABLE,
  707. availableDevices);
  708. if (browser.supportsDeviceChangeEvent()) {
  709. navigator.mediaDevices.addEventListener(
  710. 'devicechange',
  711. () => this.enumerateDevices(emptyFuncton));
  712. } else {
  713. // Periodically poll enumerateDevices() method to check if
  714. // list of media devices has changed.
  715. availableDevicesPollTimer = window.setInterval(
  716. () => this.enumerateDevices(emptyFuncton),
  717. AVAILABLE_DEVICES_POLL_INTERVAL_TIME);
  718. }
  719. });
  720. }
  721. }
  722. /**
  723. *
  724. * @param {Function} callback
  725. */
  726. enumerateDevices(callback) {
  727. navigator.mediaDevices.enumerateDevices()
  728. .then(devices => {
  729. updateKnownDevices(devices);
  730. callback(devices);
  731. })
  732. .catch(error => {
  733. logger.warn(`Failed to enumerate devices. ${error}`);
  734. updateKnownDevices([]);
  735. callback([]);
  736. });
  737. }
  738. /* eslint-disable max-params */
  739. /**
  740. * @param {string[]} um required user media types
  741. * @param {Object} [options] optional parameters
  742. * @param {string} options.resolution
  743. * @param {number} options.bandwidth
  744. * @param {number} options.fps
  745. * @param {string} options.desktopStream
  746. * @param {string} options.cameraDeviceId
  747. * @param {string} options.micDeviceId
  748. * @param {Object} options.frameRate - used only for dekstop sharing.
  749. * @param {Object} options.frameRate.min - Minimum fps
  750. * @param {Object} options.frameRate.max - Maximum fps
  751. * @param {bool} options.screenShareAudio - Used by electron clients to
  752. * enable system audio screen sharing.
  753. * @param {number} options.timeout - The timeout in ms for GUM.
  754. * @returns {Promise} Returns a media stream on success or a JitsiTrackError
  755. * on failure.
  756. **/
  757. getUserMediaWithConstraints(um, options = {}) {
  758. const {
  759. timeout,
  760. ...otherOptions
  761. } = options;
  762. const constraints = getConstraints(um, otherOptions);
  763. logger.info('Get media constraints', JSON.stringify(constraints));
  764. return this._getUserMedia(um, constraints, timeout);
  765. }
  766. /**
  767. * Acquires a media stream via getUserMedia that
  768. * matches the given constraints
  769. *
  770. * @param {array} umDevices which devices to acquire (e.g. audio, video)
  771. * @param {Object} constraints - Stream specifications to use.
  772. * @param {number} timeout - The timeout in ms for GUM.
  773. * @returns {Promise}
  774. */
  775. _getUserMedia(umDevices, constraints = {}, timeout = 0) {
  776. return new Promise((resolve, reject) => {
  777. let gumTimeout, timeoutExpired = false;
  778. if (typeof timeout === 'number' && !isNaN(timeout) && timeout > 0) {
  779. gumTimeout = setTimeout(() => {
  780. timeoutExpired = true;
  781. gumTimeout = undefined;
  782. reject(new JitsiTrackError(JitsiTrackErrors.TIMEOUT));
  783. }, timeout);
  784. }
  785. navigator.mediaDevices.getUserMedia(constraints)
  786. .then(stream => {
  787. logger.log('onUserMediaSuccess');
  788. updateGrantedPermissions(umDevices, stream);
  789. if (!timeoutExpired) {
  790. if (typeof gumTimeout !== 'undefined') {
  791. clearTimeout(gumTimeout);
  792. }
  793. resolve(stream);
  794. }
  795. })
  796. .catch(error => {
  797. logger.warn(`Failed to get access to local media. ${error} ${JSON.stringify(constraints)}`);
  798. const jitsiError = new JitsiTrackError(error, constraints, umDevices);
  799. if (!timeoutExpired) {
  800. if (typeof gumTimeout !== 'undefined') {
  801. clearTimeout(gumTimeout);
  802. }
  803. reject(error);
  804. }
  805. if (jitsiError.name === JitsiTrackErrors.PERMISSION_DENIED) {
  806. updateGrantedPermissions(umDevices, undefined);
  807. }
  808. // else {
  809. // Probably the error is not caused by the lack of permissions and we don't need to update them.
  810. // }
  811. });
  812. });
  813. }
  814. /**
  815. * Acquire a display stream via the screenObtainer. This requires extra
  816. * logic compared to use screenObtainer versus normal device capture logic
  817. * in RTCUtils#_getUserMedia.
  818. *
  819. * @param {Object} options
  820. * @param {string[]} options.desktopSharingSources
  821. * @param {Object} options.desktopSharingFrameRate
  822. * @param {Object} options.desktopSharingFrameRate.min - Minimum fps
  823. * @param {Object} options.desktopSharingFrameRate.max - Maximum fps
  824. * @returns {Promise} A promise which will be resolved with an object which
  825. * contains the acquired display stream. If desktop sharing is not supported
  826. * then a rejected promise will be returned.
  827. */
  828. _newGetDesktopMedia(options) {
  829. if (!screenObtainer.isSupported()) {
  830. return Promise.reject(new Error('Desktop sharing is not supported!'));
  831. }
  832. return new Promise((resolve, reject) => {
  833. screenObtainer.obtainStream(
  834. this._parseDesktopSharingOptions(options),
  835. stream => {
  836. resolve(stream);
  837. },
  838. error => {
  839. reject(error);
  840. });
  841. });
  842. }
  843. /* eslint-enable max-params */
  844. /**
  845. * Creates the local MediaStreams.
  846. * @param {Object} [options] optional parameters
  847. * @param {Array} options.devices the devices that will be requested
  848. * @param {string} options.resolution resolution constraints
  849. * @param {string} options.cameraDeviceId
  850. * @param {string} options.micDeviceId
  851. * @param {Object} options.desktopSharingFrameRate
  852. * @param {Object} options.desktopSharingFrameRate.min - Minimum fps
  853. * @param {Object} options.desktopSharingFrameRate.max - Maximum fps
  854. * @returns {*} Promise object that will receive the new JitsiTracks
  855. */
  856. obtainAudioAndVideoPermissions(options = {}) {
  857. options.devices = options.devices || [ ...OLD_GUM_DEFAULT_DEVICES ];
  858. options.resolution = options.resolution || OLD_GUM_DEFAULT_RESOLUTION;
  859. const requestingDesktop = options.devices.includes('desktop');
  860. if (requestingDesktop && !screenObtainer.isSupported()) {
  861. return Promise.reject(
  862. new Error('Desktop sharing is not supported!'));
  863. }
  864. return this._getAudioAndVideoStreams(options).then(streams =>
  865. handleLocalStream(streams, options.resolution));
  866. }
  867. /**
  868. * Performs one call to getUserMedia for audio and/or video and another call
  869. * for desktop.
  870. *
  871. * @param {Object} options - An object describing how the gUM request should
  872. * be executed. See {@link obtainAudioAndVideoPermissions} for full options.
  873. * @returns {*} Promise object that will receive the new JitsiTracks on
  874. * success or a JitsiTrackError on failure.
  875. */
  876. _getAudioAndVideoStreams(options) {
  877. const requestingDesktop = options.devices.includes('desktop');
  878. options.devices = options.devices.filter(device =>
  879. device !== 'desktop');
  880. const gumPromise = options.devices.length
  881. ? this.getUserMediaWithConstraints(options.devices, options)
  882. : Promise.resolve(null);
  883. return gumPromise
  884. .then(avStream => {
  885. // If any requested devices are missing, call gum again in
  886. // an attempt to obtain the actual error. For example, the
  887. // requested video device is missing or permission was
  888. // denied.
  889. const missingTracks
  890. = this._getMissingTracks(options.devices, avStream);
  891. if (missingTracks.length) {
  892. this.stopMediaStream(avStream);
  893. return this.getUserMediaWithConstraints(
  894. missingTracks, options)
  895. // GUM has already failed earlier and this success
  896. // handling should not be reached.
  897. .then(() => Promise.reject(new JitsiTrackError(
  898. { name: 'UnknownError' },
  899. getConstraints(options.devices, options),
  900. missingTracks)));
  901. }
  902. return avStream;
  903. })
  904. .then(audioVideo => {
  905. if (!requestingDesktop) {
  906. return { audioVideo };
  907. }
  908. if (options.desktopSharingSourceDevice) {
  909. this.stopMediaStream(audioVideo);
  910. throw new Error('Using a camera as screenshare source is'
  911. + 'not supported on this browser.');
  912. }
  913. return new Promise((resolve, reject) => {
  914. screenObtainer.obtainStream(
  915. this._parseDesktopSharingOptions(options),
  916. desktop => resolve({
  917. audioVideo,
  918. desktop
  919. }),
  920. error => {
  921. if (audioVideo) {
  922. this.stopMediaStream(audioVideo);
  923. }
  924. reject(error);
  925. });
  926. });
  927. });
  928. }
  929. /**
  930. * Private utility for determining if the passed in MediaStream contains
  931. * tracks of the type(s) specified in the requested devices.
  932. *
  933. * @param {string[]} requestedDevices - The track types that are expected to
  934. * be includes in the stream.
  935. * @param {MediaStream} stream - The MediaStream to check if it has the
  936. * expected track types.
  937. * @returns {string[]} An array of string with the missing track types. The
  938. * array will be empty if all requestedDevices are found in the stream.
  939. */
  940. _getMissingTracks(requestedDevices = [], stream) {
  941. const missingDevices = [];
  942. const audioDeviceRequested = requestedDevices.includes('audio');
  943. const audioTracksReceived
  944. = stream && stream.getAudioTracks().length > 0;
  945. if (audioDeviceRequested && !audioTracksReceived) {
  946. missingDevices.push('audio');
  947. }
  948. const videoDeviceRequested = requestedDevices.includes('video');
  949. const videoTracksReceived
  950. = stream && stream.getVideoTracks().length > 0;
  951. if (videoDeviceRequested && !videoTracksReceived) {
  952. missingDevices.push('video');
  953. }
  954. return missingDevices;
  955. }
  956. /**
  957. * Returns an object formatted for specifying desktop sharing parameters.
  958. *
  959. * @param {Object} options - Takes in the same options object as
  960. * {@link obtainAudioAndVideoPermissions}.
  961. * @returns {Object}
  962. */
  963. _parseDesktopSharingOptions(options) {
  964. return {
  965. desktopSharingSources: options.desktopSharingSources,
  966. gumOptions: {
  967. frameRate: options.desktopSharingFrameRate
  968. }
  969. };
  970. }
  971. /**
  972. * Gets streams from specified device types. This function intentionally
  973. * ignores errors for upstream to catch and handle instead.
  974. *
  975. * @param {Object} options - A hash describing what devices to get and
  976. * relevant constraints.
  977. * @param {string[]} options.devices - The types of media to capture. Valid
  978. * values are "desktop", "audio", and "video".
  979. * @param {Object} options.desktopSharingFrameRate
  980. * @param {Object} options.desktopSharingFrameRate.min - Minimum fps
  981. * @param {Object} options.desktopSharingFrameRate.max - Maximum fps
  982. * @param {String} options.desktopSharingSourceDevice - The device id or
  983. * label for a video input source that should be used for screensharing.
  984. * @returns {Promise} The promise, when successful, will return an array of
  985. * meta data for the requested device type, which includes the stream and
  986. * track. If an error occurs, it will be deferred to the caller for
  987. * handling.
  988. */
  989. newObtainAudioAndVideoPermissions(options) {
  990. logger.info('Using the new gUM flow');
  991. const {
  992. timeout,
  993. ...otherOptions
  994. } = options;
  995. const mediaStreamsMetaData = [];
  996. // Declare private functions to be used in the promise chain below.
  997. // These functions are declared in the scope of this function because
  998. // they are not being used anywhere else, so only this function needs to
  999. // know about them.
  1000. /**
  1001. * Executes a request for desktop media if specified in options.
  1002. *
  1003. * @returns {Promise}
  1004. */
  1005. const maybeRequestDesktopDevice = function() {
  1006. const umDevices = otherOptions.devices || [];
  1007. const isDesktopDeviceRequested
  1008. = umDevices.indexOf('desktop') !== -1;
  1009. if (!isDesktopDeviceRequested) {
  1010. return Promise.resolve();
  1011. }
  1012. const {
  1013. desktopSharingSourceDevice,
  1014. desktopSharingSources,
  1015. desktopSharingFrameRate
  1016. } = otherOptions;
  1017. // Attempt to use a video input device as a screenshare source if
  1018. // the option is defined.
  1019. if (desktopSharingSourceDevice) {
  1020. const matchingDevice
  1021. = availableDevices && availableDevices.find(device =>
  1022. device.kind === 'videoinput'
  1023. && (device.deviceId === desktopSharingSourceDevice
  1024. || device.label === desktopSharingSourceDevice));
  1025. if (!matchingDevice) {
  1026. return Promise.reject(new JitsiTrackError(
  1027. { name: 'ConstraintNotSatisfiedError' },
  1028. {},
  1029. [ desktopSharingSourceDevice ]
  1030. ));
  1031. }
  1032. const requestedDevices = [ 'video' ];
  1033. // Leverage the helper used by {@link _newGetDesktopMedia} to
  1034. // get constraints for the desktop stream.
  1035. const { gumOptions } = this._parseDesktopSharingOptions(otherOptions);
  1036. const constraints = {
  1037. video: {
  1038. ...gumOptions,
  1039. deviceId: matchingDevice.deviceId
  1040. }
  1041. };
  1042. return this._getUserMedia(requestedDevices, constraints, timeout)
  1043. .then(stream => {
  1044. return {
  1045. sourceType: 'device',
  1046. stream
  1047. };
  1048. });
  1049. }
  1050. return this._newGetDesktopMedia({
  1051. desktopSharingSources,
  1052. desktopSharingFrameRate
  1053. });
  1054. }.bind(this);
  1055. /**
  1056. * Creates a meta data object about the passed in desktopStream and
  1057. * pushes the meta data to the internal array mediaStreamsMetaData to be
  1058. * returned later.
  1059. *
  1060. * @param {MediaStreamTrack} desktopStream - A track for a desktop
  1061. * capture.
  1062. * @returns {void}
  1063. */
  1064. const maybeCreateAndAddDesktopTrack = function(desktopStream) {
  1065. if (!desktopStream) {
  1066. return;
  1067. }
  1068. const { stream, sourceId, sourceType } = desktopStream;
  1069. const desktopAudioTracks = stream.getAudioTracks();
  1070. if (desktopAudioTracks.length) {
  1071. const desktopAudioStream = new MediaStream(desktopAudioTracks);
  1072. mediaStreamsMetaData.push({
  1073. stream: desktopAudioStream,
  1074. sourceId,
  1075. sourceType,
  1076. track: desktopAudioStream.getAudioTracks()[0]
  1077. });
  1078. }
  1079. const desktopVideoTracks = stream.getVideoTracks();
  1080. if (desktopVideoTracks.length) {
  1081. const desktopVideoStream = new MediaStream(desktopVideoTracks);
  1082. mediaStreamsMetaData.push({
  1083. stream: desktopVideoStream,
  1084. sourceId,
  1085. sourceType,
  1086. track: desktopVideoStream.getVideoTracks()[0],
  1087. videoType: VideoType.DESKTOP
  1088. });
  1089. }
  1090. };
  1091. /**
  1092. * Executes a request for audio and/or video, as specified in options.
  1093. * By default both audio and video will be captured if options.devices
  1094. * is not defined.
  1095. *
  1096. * @returns {Promise}
  1097. */
  1098. const maybeRequestCaptureDevices = function() {
  1099. const umDevices = otherOptions.devices || [ 'audio', 'video' ];
  1100. const requestedCaptureDevices = umDevices.filter(device => device === 'audio' || device === 'video');
  1101. if (!requestedCaptureDevices.length) {
  1102. return Promise.resolve();
  1103. }
  1104. const constraints = newGetConstraints(
  1105. requestedCaptureDevices, otherOptions);
  1106. logger.info('Got media constraints: ', JSON.stringify(constraints));
  1107. return this._getUserMedia(requestedCaptureDevices, constraints, timeout);
  1108. }.bind(this);
  1109. /**
  1110. * Splits the passed in media stream into separate audio and video
  1111. * streams and creates meta data objects for each and pushes them to the
  1112. * internal array mediaStreamsMetaData to be returned later.
  1113. *
  1114. * @param {MediaStreamTrack} avStream - A track for with audio and/or
  1115. * video track.
  1116. * @returns {void}
  1117. */
  1118. const maybeCreateAndAddAVTracks = function(avStream) {
  1119. if (!avStream) {
  1120. return;
  1121. }
  1122. const audioTracks = avStream.getAudioTracks();
  1123. if (audioTracks.length) {
  1124. const audioStream = new MediaStream(audioTracks);
  1125. mediaStreamsMetaData.push({
  1126. stream: audioStream,
  1127. track: audioStream.getAudioTracks()[0],
  1128. effects: otherOptions.effects
  1129. });
  1130. }
  1131. const videoTracks = avStream.getVideoTracks();
  1132. if (videoTracks.length) {
  1133. const videoStream = new MediaStream(videoTracks);
  1134. mediaStreamsMetaData.push({
  1135. stream: videoStream,
  1136. track: videoStream.getVideoTracks()[0],
  1137. videoType: VideoType.CAMERA,
  1138. effects: otherOptions.effects
  1139. });
  1140. }
  1141. };
  1142. return maybeRequestDesktopDevice()
  1143. .then(maybeCreateAndAddDesktopTrack)
  1144. .then(maybeRequestCaptureDevices)
  1145. .then(maybeCreateAndAddAVTracks)
  1146. .then(() => mediaStreamsMetaData)
  1147. .catch(error => {
  1148. mediaStreamsMetaData.forEach(({ stream }) => {
  1149. this.stopMediaStream(stream);
  1150. });
  1151. return Promise.reject(error);
  1152. });
  1153. }
  1154. /**
  1155. * Checks whether it is possible to enumerate available cameras/microphones.
  1156. *
  1157. * @returns {boolean} {@code true} if the device listing is available;
  1158. * {@code false}, otherwise.
  1159. */
  1160. isDeviceListAvailable() {
  1161. return Boolean(
  1162. navigator.mediaDevices
  1163. && navigator.mediaDevices.enumerateDevices);
  1164. }
  1165. /**
  1166. * Returns true if changing the input (camera / microphone) or output
  1167. * (audio) device is supported and false if not.
  1168. * @params {string} [deviceType] - type of device to change. Default is
  1169. * undefined or 'input', 'output' - for audio output device change.
  1170. * @returns {boolean} true if available, false otherwise.
  1171. */
  1172. isDeviceChangeAvailable(deviceType) {
  1173. return deviceType === 'output' || deviceType === 'audiooutput'
  1174. ? isAudioOutputDeviceChangeAvailable
  1175. : true;
  1176. }
  1177. /**
  1178. * A method to handle stopping of the stream.
  1179. * One point to handle the differences in various implementations.
  1180. * @param mediaStream MediaStream object to stop.
  1181. */
  1182. stopMediaStream(mediaStream) {
  1183. if (!mediaStream) {
  1184. return;
  1185. }
  1186. mediaStream.getTracks().forEach(track => {
  1187. if (track.stop) {
  1188. track.stop();
  1189. }
  1190. });
  1191. // leave stop for implementation still using it
  1192. if (mediaStream.stop) {
  1193. mediaStream.stop();
  1194. }
  1195. // The MediaStream implementation of the react-native-webrtc project has
  1196. // an explicit release method that is to be invoked in order to release
  1197. // used resources such as memory.
  1198. if (mediaStream.release) {
  1199. mediaStream.release();
  1200. }
  1201. }
  1202. /**
  1203. * Returns whether the desktop sharing is enabled or not.
  1204. * @returns {boolean}
  1205. */
  1206. isDesktopSharingEnabled() {
  1207. return screenObtainer.isSupported();
  1208. }
  1209. /**
  1210. * Sets current audio output device.
  1211. * @param {string} deviceId - id of 'audiooutput' device from
  1212. * navigator.mediaDevices.enumerateDevices(), 'default' for default
  1213. * device
  1214. * @returns {Promise} - resolves when audio output is changed, is rejected
  1215. * otherwise
  1216. */
  1217. setAudioOutputDevice(deviceId) {
  1218. if (!this.isDeviceChangeAvailable('output')) {
  1219. return Promise.reject(
  1220. new Error('Audio output device change is not supported'));
  1221. }
  1222. return featureDetectionAudioEl.setSinkId(deviceId)
  1223. .then(() => {
  1224. audioOutputDeviceId = deviceId;
  1225. audioOutputChanged = true;
  1226. logger.log(`Audio output device set to ${deviceId}`);
  1227. eventEmitter.emit(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1228. deviceId);
  1229. });
  1230. }
  1231. /**
  1232. * Returns currently used audio output device id, '' stands for default
  1233. * device
  1234. * @returns {string}
  1235. */
  1236. getAudioOutputDevice() {
  1237. return audioOutputDeviceId;
  1238. }
  1239. /**
  1240. * Returns list of available media devices if its obtained, otherwise an
  1241. * empty array is returned/
  1242. * @returns {Array} list of available media devices.
  1243. */
  1244. getCurrentlyAvailableMediaDevices() {
  1245. return availableDevices;
  1246. }
  1247. /**
  1248. * Returns whether available devices have permissions granted
  1249. * @returns {Boolean}
  1250. */
  1251. arePermissionsGrantedForAvailableDevices() {
  1252. return availableDevices.some(device => Boolean(device.label));
  1253. }
  1254. /**
  1255. * Returns event data for device to be reported to stats.
  1256. * @returns {MediaDeviceInfo} device.
  1257. */
  1258. getEventDataForActiveDevice(device) {
  1259. const deviceList = [];
  1260. const deviceData = {
  1261. 'deviceId': device.deviceId,
  1262. 'kind': device.kind,
  1263. 'label': device.label,
  1264. 'groupId': device.groupId
  1265. };
  1266. deviceList.push(deviceData);
  1267. return { deviceList };
  1268. }
  1269. /**
  1270. * Configures the given PeerConnection constraints to either enable or
  1271. * disable (according to the value of the 'enable' parameter) the
  1272. * 'googSuspendBelowMinBitrate' option.
  1273. * @param constraints the constraints on which to operate.
  1274. * @param enable {boolean} whether to enable or disable the suspend video
  1275. * option.
  1276. */
  1277. setSuspendVideo(constraints, enable) {
  1278. if (!constraints.optional) {
  1279. constraints.optional = [];
  1280. }
  1281. // Get rid of all "googSuspendBelowMinBitrate" constraints (we assume
  1282. // that the elements of constraints.optional contain a single property).
  1283. constraints.optional
  1284. = constraints.optional.filter(
  1285. c => !c.hasOwnProperty('googSuspendBelowMinBitrate'));
  1286. if (enable) {
  1287. constraints.optional.push({ googSuspendBelowMinBitrate: 'true' });
  1288. }
  1289. }
  1290. }
  1291. const rtcUtils = new RTCUtils();
  1292. /**
  1293. * Wraps original attachMediaStream function to set current audio output device
  1294. * if this is supported.
  1295. * @param {Function} origAttachMediaStream
  1296. * @returns {Function}
  1297. */
  1298. function wrapAttachMediaStream(origAttachMediaStream) {
  1299. return function(element, stream) {
  1300. // eslint-disable-next-line prefer-rest-params
  1301. const res = origAttachMediaStream.apply(rtcUtils, arguments);
  1302. if (stream
  1303. && rtcUtils.isDeviceChangeAvailable('output')
  1304. && stream.getAudioTracks
  1305. && stream.getAudioTracks().length
  1306. // we skip setting audio output if there was no explicit change
  1307. && audioOutputChanged) {
  1308. element.setSinkId(rtcUtils.getAudioOutputDevice())
  1309. .catch(function(ex) {
  1310. const err
  1311. = new JitsiTrackError(ex, null, [ 'audiooutput' ]);
  1312. GlobalOnErrorHandler.callUnhandledRejectionHandler({
  1313. promise: this, // eslint-disable-line no-invalid-this
  1314. reason: err
  1315. });
  1316. logger.warn(
  1317. 'Failed to set audio output device for the element.'
  1318. + ' Default audio output device will be used'
  1319. + ' instead',
  1320. element,
  1321. err);
  1322. });
  1323. }
  1324. return res;
  1325. };
  1326. }
  1327. export default rtcUtils;