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

RTCUtils.js 72KB

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