Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

RTCUtils.js 69KB

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