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

RTCUtils.js 72KB

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