您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

RTCUtils.js 72KB

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