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

RTCUtils.js 53KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458
  1. /* global $,
  2. __filename,
  3. attachMediaStream,
  4. MediaStreamTrack,
  5. RTCIceCandidate: true,
  6. RTCPeerConnection,
  7. RTCSessionDescription: true,
  8. mozRTCIceCandidate,
  9. mozRTCPeerConnection,
  10. mozRTCSessionDescription,
  11. webkitMediaStream,
  12. webkitRTCPeerConnection,
  13. webkitURL
  14. */
  15. import CameraFacingMode from '../../service/RTC/CameraFacingMode';
  16. import EventEmitter from 'events';
  17. import { getLogger } from 'jitsi-meet-logger';
  18. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  19. import JitsiTrackError from '../../JitsiTrackError';
  20. import Listenable from '../util/Listenable';
  21. import * as MediaType from '../../service/RTC/MediaType';
  22. import Resolutions from '../../service/RTC/Resolutions';
  23. import RTCBrowserType from './RTCBrowserType';
  24. import RTCEvents from '../../service/RTC/RTCEvents';
  25. import screenObtainer from './ScreenObtainer';
  26. import SDPUtil from '../xmpp/SDPUtil';
  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. = RTCBrowserType.isTemasysPluginUsed()
  33. ? require('./adapter.screenshare')
  34. : undefined;
  35. const eventEmitter = new EventEmitter();
  36. const AVAILABLE_DEVICES_POLL_INTERVAL_TIME = 3000; // ms
  37. const devices = {
  38. audio: false,
  39. video: false
  40. };
  41. // Currently audio output device change is supported only in Chrome and
  42. // default output always has 'default' device ID
  43. let audioOutputDeviceId = 'default'; // default device
  44. // whether user has explicitly set a device to use
  45. let audioOutputChanged = false;
  46. // Disables Acoustic Echo Cancellation
  47. let disableAEC = false;
  48. // Disables Noise Suppression
  49. let disableNS = false;
  50. const featureDetectionAudioEl = document.createElement('audio');
  51. const isAudioOutputDeviceChangeAvailable
  52. = typeof featureDetectionAudioEl.setSinkId !== 'undefined';
  53. let currentlyAvailableMediaDevices;
  54. /**
  55. * "rawEnumerateDevicesWithCallback" will be initialized only after WebRTC is
  56. * ready. Otherwise it is too early to assume that the devices listing is not
  57. * supported.
  58. */
  59. let rawEnumerateDevicesWithCallback;
  60. /**
  61. *
  62. */
  63. function initRawEnumerateDevicesWithCallback() {
  64. rawEnumerateDevicesWithCallback = navigator.mediaDevices
  65. && navigator.mediaDevices.enumerateDevices
  66. ? function(callback) {
  67. navigator.mediaDevices.enumerateDevices().then(
  68. callback,
  69. () => callback([]));
  70. }
  71. // Safari:
  72. // "ReferenceError: Can't find variable: MediaStreamTrack"
  73. // when Temasys plugin is not installed yet, have to delay this call
  74. // until WebRTC is ready.
  75. : MediaStreamTrack && MediaStreamTrack.getSources
  76. ? function(callback) {
  77. MediaStreamTrack.getSources(
  78. sources =>
  79. callback(sources.map(convertMediaStreamTrackSource)));
  80. }
  81. : undefined;
  82. }
  83. // TODO: currently no browser supports 'devicechange' event even in nightly
  84. // builds so no feature/browser detection is used at all. However in future this
  85. // should be changed to some expression. Progress on 'devicechange' event
  86. // implementation for Chrome/Opera/NWJS can be tracked at
  87. // https://bugs.chromium.org/p/chromium/issues/detail?id=388648, for Firefox -
  88. // at https://bugzilla.mozilla.org/show_bug.cgi?id=1152383. More information on
  89. // 'devicechange' event can be found in spec -
  90. // http://w3c.github.io/mediacapture-main/#event-mediadevices-devicechange
  91. // TODO: check MS Edge
  92. const isDeviceChangeEventSupported = false;
  93. let rtcReady = false;
  94. /**
  95. *
  96. * @param constraints
  97. * @param resolution
  98. */
  99. function setResolutionConstraints(constraints, resolution) {
  100. const isAndroid = RTCBrowserType.isAndroid();
  101. if (Resolutions[resolution]) {
  102. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  103. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  104. } else if (isAndroid) {
  105. // FIXME can't remember if the purpose of this was to always request
  106. // low resolution on Android ? if yes it should be moved up front
  107. constraints.video.mandatory.minWidth = 320;
  108. constraints.video.mandatory.minHeight = 180;
  109. constraints.video.mandatory.maxFrameRate = 15;
  110. }
  111. if (constraints.video.mandatory.minWidth) {
  112. constraints.video.mandatory.maxWidth
  113. = constraints.video.mandatory.minWidth;
  114. }
  115. if (constraints.video.mandatory.minHeight) {
  116. constraints.video.mandatory.maxHeight
  117. = constraints.video.mandatory.minHeight;
  118. }
  119. }
  120. /**
  121. * @param {string[]} um required user media types
  122. *
  123. * @param {Object} [options={}] optional parameters
  124. * @param {string} options.resolution
  125. * @param {number} options.bandwidth
  126. * @param {number} options.fps
  127. * @param {string} options.desktopStream
  128. * @param {string} options.cameraDeviceId
  129. * @param {string} options.micDeviceId
  130. * @param {CameraFacingMode} options.facingMode
  131. * @param {bool} firefox_fake_device
  132. */
  133. function getConstraints(um, options) {
  134. const constraints = { audio: false,
  135. video: false };
  136. // Don't mix new and old style settings for Chromium as this leads
  137. // to TypeError in new Chromium versions. @see
  138. // https://bugs.chromium.org/p/chromium/issues/detail?id=614716
  139. // This is a temporary solution, in future we will fully split old and
  140. // new style constraints when new versions of Chromium and Firefox will
  141. // have stable support of new constraints format. For more information
  142. // @see https://github.com/jitsi/lib-jitsi-meet/pull/136
  143. const isNewStyleConstraintsSupported
  144. = RTCBrowserType.isFirefox()
  145. || RTCBrowserType.isReactNative()
  146. || RTCBrowserType.isTemasysPluginUsed();
  147. if (um.indexOf('video') >= 0) {
  148. // same behaviour as true
  149. constraints.video = { mandatory: {},
  150. optional: [] };
  151. if (options.cameraDeviceId) {
  152. if (isNewStyleConstraintsSupported) {
  153. // New style of setting device id.
  154. constraints.video.deviceId = options.cameraDeviceId;
  155. }
  156. // Old style.
  157. constraints.video.optional.push({
  158. sourceId: options.cameraDeviceId
  159. });
  160. } else {
  161. // Prefer the front i.e. user-facing camera (to the back i.e.
  162. // environment-facing camera, for example).
  163. // TODO: Maybe use "exact" syntax if options.facingMode is defined,
  164. // but this probably needs to be decided when updating other
  165. // constraints, as we currently don't use "exact" syntax anywhere.
  166. const facingMode = options.facingMode || CameraFacingMode.USER;
  167. if (isNewStyleConstraintsSupported) {
  168. constraints.video.facingMode = facingMode;
  169. }
  170. constraints.video.optional.push({
  171. facingMode
  172. });
  173. }
  174. if (options.minFps || options.maxFps || options.fps) {
  175. // for some cameras it might be necessary to request 30fps
  176. // so they choose 30fps mjpg over 10fps yuy2
  177. if (options.minFps || options.fps) {
  178. // Fall back to options.fps for backwards compatibility
  179. options.minFps = options.minFps || options.fps;
  180. constraints.video.mandatory.minFrameRate = options.minFps;
  181. }
  182. if (options.maxFps) {
  183. constraints.video.mandatory.maxFrameRate = options.maxFps;
  184. }
  185. }
  186. setResolutionConstraints(constraints, options.resolution);
  187. }
  188. if (um.indexOf('audio') >= 0) {
  189. if (RTCBrowserType.isReactNative()) {
  190. // The react-native-webrtc project that we're currently using
  191. // expects the audio constraint to be a boolean.
  192. constraints.audio = true;
  193. } else if (RTCBrowserType.isFirefox()) {
  194. if (options.micDeviceId) {
  195. constraints.audio = {
  196. mandatory: {},
  197. deviceId: options.micDeviceId, // new style
  198. optional: [ {
  199. sourceId: options.micDeviceId // old style
  200. } ] };
  201. } else {
  202. constraints.audio = true;
  203. }
  204. } else {
  205. // same behaviour as true
  206. constraints.audio = { mandatory: {},
  207. optional: [] };
  208. if (options.micDeviceId) {
  209. if (isNewStyleConstraintsSupported) {
  210. // New style of setting device id.
  211. constraints.audio.deviceId = options.micDeviceId;
  212. }
  213. // Old style.
  214. constraints.audio.optional.push({
  215. sourceId: options.micDeviceId
  216. });
  217. }
  218. // if it is good enough for hangouts...
  219. constraints.audio.optional.push(
  220. { googEchoCancellation: !disableAEC },
  221. { googAutoGainControl: true },
  222. { googNoiseSupression: !disableNS },
  223. { googHighpassFilter: true },
  224. { googNoiseSuppression2: !disableNS },
  225. { googEchoCancellation2: !disableAEC },
  226. { googAutoGainControl2: true }
  227. );
  228. }
  229. }
  230. if (um.indexOf('screen') >= 0) {
  231. if (RTCBrowserType.isChrome()) {
  232. constraints.video = {
  233. mandatory: {
  234. chromeMediaSource: 'screen',
  235. maxWidth: window.screen.width,
  236. maxHeight: window.screen.height,
  237. maxFrameRate: 3
  238. },
  239. optional: []
  240. };
  241. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  242. constraints.video = {
  243. optional: [
  244. {
  245. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  246. }
  247. ]
  248. };
  249. } else if (RTCBrowserType.isFirefox()) {
  250. constraints.video = {
  251. mozMediaSource: 'window',
  252. mediaSource: 'window'
  253. };
  254. } else {
  255. const errmsg
  256. = '\'screen\' WebRTC media source is supported only in Chrome'
  257. + ' and with Temasys plugin';
  258. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  259. logger.error(errmsg);
  260. }
  261. }
  262. if (um.indexOf('desktop') >= 0) {
  263. constraints.video = {
  264. mandatory: {
  265. chromeMediaSource: 'desktop',
  266. chromeMediaSourceId: options.desktopStream,
  267. maxWidth: window.screen.width,
  268. maxHeight: window.screen.height,
  269. maxFrameRate: 3
  270. },
  271. optional: []
  272. };
  273. }
  274. if (options.bandwidth) {
  275. if (!constraints.video) {
  276. // same behaviour as true
  277. constraints.video = { mandatory: {},
  278. optional: [] };
  279. }
  280. constraints.video.optional.push({ bandwidth: options.bandwidth });
  281. }
  282. // we turn audio for both audio and video tracks, the fake audio & video
  283. // seems to work only when enabled in one getUserMedia call, we cannot get
  284. // fake audio separate by fake video this later can be a problem with some
  285. // of the tests
  286. if (RTCBrowserType.isFirefox() && options.firefox_fake_device) {
  287. // seems to be fixed now, removing this experimental fix, as having
  288. // multiple audio tracks brake the tests
  289. // constraints.audio = true;
  290. constraints.fake = true;
  291. }
  292. return constraints;
  293. }
  294. /**
  295. * Sets the availbale devices based on the options we requested and the
  296. * streams we received.
  297. * @param um the options we requested to getUserMedia.
  298. * @param stream the stream we received from calling getUserMedia.
  299. */
  300. function setAvailableDevices(um, stream) {
  301. const audioTracksReceived = stream && stream.getAudioTracks().length > 0;
  302. const videoTracksReceived = stream && stream.getVideoTracks().length > 0;
  303. if (um.indexOf('video') !== -1) {
  304. devices.video = videoTracksReceived;
  305. }
  306. if (um.indexOf('audio') !== -1) {
  307. devices.audio = audioTracksReceived;
  308. }
  309. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  310. }
  311. /**
  312. * Checks if new list of available media devices differs from previous one.
  313. * @param {MediaDeviceInfo[]} newDevices - list of new devices.
  314. * @returns {boolean} - true if list is different, false otherwise.
  315. */
  316. function compareAvailableMediaDevices(newDevices) {
  317. if (newDevices.length !== currentlyAvailableMediaDevices.length) {
  318. return true;
  319. }
  320. return (
  321. newDevices
  322. .map(mediaDeviceInfoToJSON)
  323. .sort()
  324. .join('')
  325. !== currentlyAvailableMediaDevices
  326. .map(mediaDeviceInfoToJSON)
  327. .sort()
  328. .join(''));
  329. /**
  330. *
  331. * @param info
  332. */
  333. function mediaDeviceInfoToJSON(info) {
  334. return JSON.stringify({
  335. kind: info.kind,
  336. deviceId: info.deviceId,
  337. groupId: info.groupId,
  338. label: info.label,
  339. facing: info.facing
  340. });
  341. }
  342. }
  343. /**
  344. * Periodically polls enumerateDevices() method to check if list of media
  345. * devices has changed. This is temporary workaround until 'devicechange' event
  346. * will be supported by browsers.
  347. */
  348. function pollForAvailableMediaDevices() {
  349. // Here we use plain navigator.mediaDevices.enumerateDevices instead of
  350. // wrapped because we just need to know the fact the devices changed, labels
  351. // do not matter. This fixes situation when we have no devices initially,
  352. // and then plug in a new one.
  353. if (rawEnumerateDevicesWithCallback) {
  354. rawEnumerateDevicesWithCallback(ds => {
  355. // We don't fire RTCEvents.DEVICE_LIST_CHANGED for the first time
  356. // we call enumerateDevices(). This is the initial step.
  357. if (typeof currentlyAvailableMediaDevices === 'undefined') {
  358. currentlyAvailableMediaDevices = ds.slice(0);
  359. } else if (compareAvailableMediaDevices(ds)) {
  360. onMediaDevicesListChanged(ds);
  361. }
  362. window.setTimeout(pollForAvailableMediaDevices,
  363. AVAILABLE_DEVICES_POLL_INTERVAL_TIME);
  364. });
  365. }
  366. }
  367. /**
  368. * Event handler for the 'devicechange' event.
  369. *
  370. * @param {MediaDeviceInfo[]} devices - list of media devices.
  371. * @emits RTCEvents.DEVICE_LIST_CHANGED
  372. */
  373. function onMediaDevicesListChanged(devicesReceived) {
  374. currentlyAvailableMediaDevices = devicesReceived.slice(0);
  375. logger.info(
  376. 'list of media devices has changed:',
  377. currentlyAvailableMediaDevices);
  378. const videoInputDevices
  379. = currentlyAvailableMediaDevices.filter(d => d.kind === 'videoinput');
  380. const audioInputDevices
  381. = currentlyAvailableMediaDevices.filter(d => d.kind === 'audioinput');
  382. const videoInputDevicesWithEmptyLabels
  383. = videoInputDevices.filter(d => d.label === '');
  384. const audioInputDevicesWithEmptyLabels
  385. = audioInputDevices.filter(d => d.label === '');
  386. if (videoInputDevices.length
  387. && videoInputDevices.length
  388. === videoInputDevicesWithEmptyLabels.length) {
  389. devices.video = false;
  390. }
  391. if (audioInputDevices.length
  392. && audioInputDevices.length
  393. === audioInputDevicesWithEmptyLabels.length) {
  394. devices.audio = false;
  395. }
  396. eventEmitter.emit(RTCEvents.DEVICE_LIST_CHANGED, devicesReceived);
  397. }
  398. /**
  399. * Apply function with arguments if function exists.
  400. * Do nothing if function not provided.
  401. * @param {function} [fn] function to apply
  402. * @param {Array} [args=[]] arguments for function
  403. */
  404. function maybeApply(fn, args) {
  405. fn && fn(...args);
  406. }
  407. const getUserMediaStatus = {
  408. initialized: false,
  409. callbacks: []
  410. };
  411. /**
  412. * Wrap `getUserMedia` to allow others to know if it was executed at least
  413. * once or not. Wrapper function uses `getUserMediaStatus` object.
  414. * @param {Function} getUserMedia native function
  415. * @returns {Function} wrapped function
  416. */
  417. function wrapGetUserMedia(getUserMedia) {
  418. return function(constraints, successCallback, errorCallback) {
  419. getUserMedia(constraints, stream => {
  420. maybeApply(successCallback, [ stream ]);
  421. if (!getUserMediaStatus.initialized) {
  422. getUserMediaStatus.initialized = true;
  423. getUserMediaStatus.callbacks.forEach(callback => callback());
  424. getUserMediaStatus.callbacks.length = 0;
  425. }
  426. }, error => {
  427. maybeApply(errorCallback, [ error ]);
  428. });
  429. };
  430. }
  431. /**
  432. * Execute function after getUserMedia was executed at least once.
  433. * @param {Function} callback function to execute after getUserMedia
  434. */
  435. function afterUserMediaInitialized(callback) {
  436. if (getUserMediaStatus.initialized) {
  437. callback();
  438. } else {
  439. getUserMediaStatus.callbacks.push(callback);
  440. }
  441. }
  442. /**
  443. * Wrapper function which makes enumerateDevices to wait
  444. * until someone executes getUserMedia first time.
  445. * @param {Function} enumerateDevices native function
  446. * @returns {Funtion} wrapped function
  447. */
  448. function wrapEnumerateDevices(enumerateDevices) {
  449. return function(callback) {
  450. // enumerate devices only after initial getUserMedia
  451. afterUserMediaInitialized(() => {
  452. enumerateDevices().then(callback, err => {
  453. logger.error('cannot enumerate devices: ', err);
  454. callback([]);
  455. });
  456. });
  457. };
  458. }
  459. /**
  460. * Use old MediaStreamTrack to get devices list and
  461. * convert it to enumerateDevices format.
  462. * @param {Function} callback function to call when received devices list.
  463. */
  464. function enumerateDevicesThroughMediaStreamTrack(callback) {
  465. MediaStreamTrack.getSources(
  466. sources => callback(sources.map(convertMediaStreamTrackSource)));
  467. }
  468. /**
  469. * Converts MediaStreamTrack Source to enumerateDevices format.
  470. * @param {Object} source
  471. */
  472. function convertMediaStreamTrackSource(source) {
  473. const kind = (source.kind || '').toLowerCase();
  474. return {
  475. facing: source.facing || null,
  476. label: source.label,
  477. // theoretically deprecated MediaStreamTrack.getSources should
  478. // not return 'audiooutput' devices but let's handle it in any
  479. // case
  480. kind: kind
  481. ? kind === 'audiooutput' ? kind : `${kind}input`
  482. : null,
  483. deviceId: source.id,
  484. groupId: source.groupId || null
  485. };
  486. }
  487. /**
  488. * Handles the newly created Media Streams.
  489. * @param streams the new Media Streams
  490. * @param resolution the resolution of the video streams
  491. * @returns {*[]} object that describes the new streams
  492. */
  493. function handleLocalStream(streams, resolution) {
  494. let audioStream, desktopStream, videoStream;
  495. const res = [];
  496. // XXX The function obtainAudioAndVideoPermissions has examined the type of
  497. // the browser, its capabilities, etc. and has taken the decision whether to
  498. // invoke getUserMedia per device (e.g. Firefox) or once for both audio and
  499. // video (e.g. Chrome). In order to not duplicate the logic here, examine
  500. // the specified streams and figure out what we've received based on
  501. // obtainAudioAndVideoPermissions' decision.
  502. if (streams) {
  503. // As mentioned above, certian types of browser (e.g. Chrome) support
  504. // (with a result which meets our requirements expressed bellow) calling
  505. // getUserMedia once for both audio and video.
  506. const audioVideo = streams.audioVideo;
  507. if (audioVideo) {
  508. const audioTracks = audioVideo.getAudioTracks();
  509. if (audioTracks.length) {
  510. // eslint-disable-next-line new-cap
  511. audioStream = new webkitMediaStream();
  512. for (let i = 0; i < audioTracks.length; i++) {
  513. audioStream.addTrack(audioTracks[i]);
  514. }
  515. }
  516. const videoTracks = audioVideo.getVideoTracks();
  517. if (videoTracks.length) {
  518. // eslint-disable-next-line new-cap
  519. videoStream = new webkitMediaStream();
  520. for (let j = 0; j < videoTracks.length; j++) {
  521. videoStream.addTrack(videoTracks[j]);
  522. }
  523. }
  524. } else {
  525. // On other types of browser (e.g. Firefox) we choose (namely,
  526. // obtainAudioAndVideoPermissions) to call getUsermedia per device
  527. // (type).
  528. audioStream = streams.audio;
  529. videoStream = streams.video;
  530. }
  531. // Again, different choices on different types of browser.
  532. desktopStream = streams.desktopStream || streams.desktop;
  533. }
  534. if (desktopStream) {
  535. res.push({
  536. stream: desktopStream,
  537. track: desktopStream.getVideoTracks()[0],
  538. mediaType: MediaType.VIDEO,
  539. videoType: VideoType.DESKTOP
  540. });
  541. }
  542. if (audioStream) {
  543. res.push({
  544. stream: audioStream,
  545. track: audioStream.getAudioTracks()[0],
  546. mediaType: MediaType.AUDIO,
  547. videoType: null
  548. });
  549. }
  550. if (videoStream) {
  551. res.push({
  552. stream: videoStream,
  553. track: videoStream.getVideoTracks()[0],
  554. mediaType: MediaType.VIDEO,
  555. videoType: VideoType.CAMERA,
  556. resolution
  557. });
  558. }
  559. return res;
  560. }
  561. /**
  562. * Represents a default implementation of setting a <tt>MediaStream</tt> as the
  563. * source of a video element that tries to be browser-agnostic through feature
  564. * checking. Note though that it was not completely clear from the predating
  565. * browser-specific implementations what &quot;videoSrc&quot; was because one
  566. * implementation of {@link RTCUtils#getVideoSrc} would return
  567. * <tt>MediaStream</tt> (e.g. Firefox), another a <tt>string</tt> representation
  568. * of the <tt>URL</tt> of the <tt>MediaStream</tt> (e.g. Chrome) and the return
  569. * value was only used by {@link RTCUIHelper#getVideoId} which itself did not
  570. * appear to be used anywhere. Generally, the implementation will try to follow
  571. * the related standards i.e. work with the <tt>srcObject</tt> and <tt>src</tt>
  572. * properties of the specified <tt>element</tt> taking into account vender
  573. * prefixes.
  574. *
  575. * @param element the element whose video source/src is to be set to the
  576. * specified <tt>stream</tt>
  577. * @param {MediaStream} stream the <tt>MediaStream</tt> to set as the video
  578. * source/src of <tt>element</tt>
  579. */
  580. function defaultSetVideoSrc(element, stream) {
  581. // srcObject
  582. let srcObjectPropertyName = 'srcObject';
  583. if (!(srcObjectPropertyName in element)) {
  584. srcObjectPropertyName = 'mozSrcObject';
  585. if (!(srcObjectPropertyName in element)) {
  586. srcObjectPropertyName = null;
  587. }
  588. }
  589. if (srcObjectPropertyName) {
  590. element[srcObjectPropertyName] = stream;
  591. return;
  592. }
  593. // src
  594. let src;
  595. if (stream) {
  596. src = stream.jitsiObjectURL;
  597. // Save the created URL for stream so we can reuse it and not keep
  598. // creating URLs.
  599. if (!src) {
  600. stream.jitsiObjectURL
  601. = src
  602. = (URL || webkitURL).createObjectURL(stream);
  603. }
  604. }
  605. element.src = src || '';
  606. }
  607. /**
  608. *
  609. */
  610. class RTCUtils extends Listenable {
  611. /**
  612. *
  613. */
  614. constructor() {
  615. super(eventEmitter);
  616. }
  617. /**
  618. *
  619. * @param options
  620. */
  621. init(options) {
  622. if (typeof options.disableAEC === 'boolean') {
  623. disableAEC = options.disableAEC;
  624. logger.info(`Disable AEC: ${disableAEC}`);
  625. }
  626. if (typeof options.disableNS === 'boolean') {
  627. disableNS = options.disableNS;
  628. logger.info(`Disable NS: ${disableNS}`);
  629. }
  630. return new Promise((resolve, reject) => {
  631. if (RTCBrowserType.isFirefox()) {
  632. const FFversion = RTCBrowserType.getFirefoxVersion();
  633. if (FFversion < 40) {
  634. rejectWithWebRTCNotSupported(
  635. `Firefox version too old: ${FFversion}.`
  636. + ' Required >= 40.',
  637. reject);
  638. return;
  639. }
  640. this.peerconnection = mozRTCPeerConnection;
  641. this.getUserMedia
  642. = wrapGetUserMedia(
  643. navigator.mozGetUserMedia.bind(navigator));
  644. this.enumerateDevices
  645. = wrapEnumerateDevices(
  646. navigator.mediaDevices.enumerateDevices.bind(
  647. navigator.mediaDevices));
  648. this.pcConstraints = {};
  649. this.attachMediaStream
  650. = wrapAttachMediaStream((element, stream) => {
  651. // srcObject is being standardized and FF will
  652. // eventually support that unprefixed. FF also supports
  653. // the "element.src = URL.createObjectURL(...)" combo,
  654. // but that will be deprecated in favour of srcObject.
  655. //
  656. // https://groups.google.com/forum/#!topic/
  657. // mozilla.dev.media/pKOiioXonJg
  658. // https://github.com/webrtc/samples/issues/302
  659. if (element) {
  660. defaultSetVideoSrc(element, stream);
  661. if (stream) {
  662. element.play();
  663. }
  664. }
  665. return element;
  666. });
  667. this.getStreamID = function(stream) {
  668. let id = stream.id;
  669. if (!id) {
  670. let tracks = stream.getVideoTracks();
  671. if (!tracks || tracks.length === 0) {
  672. tracks = stream.getAudioTracks();
  673. }
  674. id = tracks[0].id;
  675. }
  676. return SDPUtil.filterSpecialChars(id);
  677. };
  678. /* eslint-disable no-global-assign, no-native-reassign */
  679. RTCSessionDescription = mozRTCSessionDescription;
  680. RTCIceCandidate = mozRTCIceCandidate;
  681. /* eslint-enable no-global-assign, no-native-reassign */
  682. } else if (RTCBrowserType.isChrome()
  683. || RTCBrowserType.isOpera()
  684. || RTCBrowserType.isNWJS()
  685. || RTCBrowserType.isElectron()
  686. || RTCBrowserType.isReactNative()) {
  687. this.peerconnection = webkitRTCPeerConnection;
  688. const getUserMedia
  689. = navigator.webkitGetUserMedia.bind(navigator);
  690. if (navigator.mediaDevices) {
  691. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  692. this.enumerateDevices
  693. = wrapEnumerateDevices(
  694. navigator.mediaDevices.enumerateDevices.bind(
  695. navigator.mediaDevices));
  696. } else {
  697. this.getUserMedia = getUserMedia;
  698. this.enumerateDevices
  699. = enumerateDevicesThroughMediaStreamTrack;
  700. }
  701. this.attachMediaStream
  702. = wrapAttachMediaStream((element, stream) => {
  703. defaultSetVideoSrc(element, stream);
  704. return element;
  705. });
  706. this.getStreamID = function(stream) {
  707. // A. MediaStreams from FF endpoints have the characters '{'
  708. // and '}' that make jQuery choke.
  709. // B. The react-native-webrtc implementation that we use on
  710. // React Native at the time of this writing returns a number
  711. // for the id of MediaStream. Let's just say that a number
  712. // contains no special characters.
  713. const id = stream.id;
  714. // XXX The return statement is affected by automatic
  715. // semicolon insertion (ASI). No line terminator is allowed
  716. // between the return keyword and the expression.
  717. return (
  718. typeof id === 'number'
  719. ? id
  720. : SDPUtil.filterSpecialChars(id));
  721. };
  722. this.pcConstraints = { optional: [] };
  723. // Allows sending of video to be suspended if the bandwidth
  724. // estimation is too low.
  725. if (!options.disableSuspendVideo) {
  726. this.pcConstraints.optional.push(
  727. { googSuspendBelowMinBitrate: true });
  728. }
  729. if (options.useIPv6) {
  730. // https://code.google.com/p/webrtc/issues/detail?id=2828
  731. this.pcConstraints.optional.push({ googIPv6: true });
  732. }
  733. if (!webkitMediaStream.prototype.getVideoTracks) {
  734. webkitMediaStream.prototype.getVideoTracks = function() {
  735. return this.videoTracks;
  736. };
  737. }
  738. if (!webkitMediaStream.prototype.getAudioTracks) {
  739. webkitMediaStream.prototype.getAudioTracks = function() {
  740. return this.audioTracks;
  741. };
  742. }
  743. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  744. // Detect IE/Safari
  745. const webRTCReadyCb = () => {
  746. this.peerconnection = RTCPeerConnection;
  747. this.getUserMedia = window.getUserMedia;
  748. this.enumerateDevices
  749. = enumerateDevicesThroughMediaStreamTrack;
  750. this.attachMediaStream
  751. = wrapAttachMediaStream((element, stream) => {
  752. if (stream) {
  753. if (stream.id === 'dummyAudio'
  754. || stream.id === 'dummyVideo') {
  755. return;
  756. }
  757. // The container must be visible in order to
  758. // play or attach the stream when Temasys plugin
  759. // is in use
  760. const containerSel = $(element);
  761. if (RTCBrowserType.isTemasysPluginUsed()
  762. && !containerSel.is(':visible')) {
  763. containerSel.show();
  764. }
  765. const video
  766. = stream.getVideoTracks().length > 0;
  767. if (video && !$(element).is(':visible')) {
  768. throw new Error(
  769. 'video element must be visible to'
  770. + ' attach video stream');
  771. }
  772. }
  773. return attachMediaStream(element, stream);
  774. });
  775. this.getStreamID
  776. = stream => SDPUtil.filterSpecialChars(stream.label);
  777. onReady(
  778. options,
  779. this.getUserMediaWithConstraints.bind(this));
  780. };
  781. const webRTCReadyPromise
  782. = new Promise(r => AdapterJS.webRTCReady(r));
  783. // Resolve or reject depending on whether the Temasys plugin is
  784. // installed.
  785. AdapterJS.WebRTCPlugin.isPluginInstalled(
  786. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  787. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  788. AdapterJS.WebRTCPlugin.pluginInfo.type,
  789. /* installed */ () => {
  790. webRTCReadyPromise.then(() => {
  791. webRTCReadyCb();
  792. resolve();
  793. });
  794. },
  795. /* not installed */ () => {
  796. const error
  797. = new Error('Temasys plugin is not installed');
  798. error.name = 'WEBRTC_NOT_READY';
  799. error.webRTCReadyPromise = webRTCReadyPromise;
  800. reject(error);
  801. });
  802. } else {
  803. rejectWithWebRTCNotSupported(
  804. 'Browser does not appear to be WebRTC-capable',
  805. reject);
  806. return;
  807. }
  808. // Call onReady() if Temasys plugin is not used
  809. if (!RTCBrowserType.isTemasysPluginUsed()) {
  810. onReady(options, this.getUserMediaWithConstraints.bind(this));
  811. resolve();
  812. }
  813. });
  814. }
  815. /* eslint-disable max-params */
  816. /**
  817. * @param {string[]} um required user media types
  818. * @param {function} successCallback
  819. * @param {Function} failureCallback
  820. * @param {Object} [options] optional parameters
  821. * @param {string} options.resolution
  822. * @param {number} options.bandwidth
  823. * @param {number} options.fps
  824. * @param {string} options.desktopStream
  825. * @param {string} options.cameraDeviceId
  826. * @param {string} options.micDeviceId
  827. **/
  828. getUserMediaWithConstraints(
  829. um,
  830. successCallback,
  831. failureCallback,
  832. options = {}) {
  833. const constraints = getConstraints(um, options);
  834. logger.info('Get media constraints', constraints);
  835. try {
  836. this.getUserMedia(
  837. constraints,
  838. stream => {
  839. logger.log('onUserMediaSuccess');
  840. setAvailableDevices(um, stream);
  841. successCallback(stream);
  842. },
  843. error => {
  844. setAvailableDevices(um, undefined);
  845. logger.warn('Failed to get access to local media. Error ',
  846. error, constraints);
  847. if (failureCallback) {
  848. failureCallback(
  849. new JitsiTrackError(error, constraints, um));
  850. }
  851. });
  852. } catch (e) {
  853. logger.error('GUM failed: ', e);
  854. if (failureCallback) {
  855. failureCallback(new JitsiTrackError(e, constraints, um));
  856. }
  857. }
  858. }
  859. /* eslint-enable max-params */
  860. /**
  861. * Creates the local MediaStreams.
  862. * @param {Object} [options] optional parameters
  863. * @param {Array} options.devices the devices that will be requested
  864. * @param {string} options.resolution resolution constraints
  865. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with
  866. * the following structure {stream: the Media Stream, type: "audio" or
  867. * "video", videoType: "camera" or "desktop"} will be returned trough the
  868. * Promise, otherwise JitsiTrack objects will be returned.
  869. * @param {string} options.cameraDeviceId
  870. * @param {string} options.micDeviceId
  871. * @returns {*} Promise object that will receive the new JitsiTracks
  872. */
  873. obtainAudioAndVideoPermissions(options = {}) {
  874. const self = this;
  875. const dsOptions = options.desktopSharingExtensionExternalInstallation;
  876. return new Promise((resolve, reject) => {
  877. const successCallback = function(stream) {
  878. resolve(handleLocalStream(stream, options.resolution));
  879. };
  880. options.devices = options.devices || [ 'audio', 'video' ];
  881. if (!screenObtainer.isSupported()
  882. && options.devices.indexOf('desktop') !== -1) {
  883. reject(new Error('Desktop sharing is not supported!'));
  884. }
  885. if (RTCBrowserType.isFirefox()
  886. // XXX The react-native-webrtc implementation that we
  887. // utilize on React Native at the time of this writing does
  888. // not support the MediaStream constructors defined by
  889. // https://www.w3.org/TR/mediacapture-streams/#constructors
  890. // and instead has a single constructor which expects (an
  891. // NSNumber as) a MediaStream ID.
  892. || RTCBrowserType.isReactNative()
  893. || RTCBrowserType.isTemasysPluginUsed()) {
  894. const GUM = function(device, s, e) {
  895. this.getUserMediaWithConstraints(device, s, e, options);
  896. };
  897. const deviceGUM = {
  898. 'audio': GUM.bind(self, [ 'audio' ]),
  899. 'video': GUM.bind(self, [ 'video' ])
  900. };
  901. if (screenObtainer.isSupported()) {
  902. deviceGUM.desktop = screenObtainer.obtainStream.bind(
  903. screenObtainer,
  904. dsOptions);
  905. }
  906. // With FF/IE we can't split the stream into audio and video
  907. // because FF doesn't support media stream constructors. So, we
  908. // need to get the audio stream separately from the video stream
  909. // using two distinct GUM calls. Not very user friendly :-( but
  910. // we don't have many other options neither.
  911. //
  912. // Note that we pack those 2 streams in a single object and pass
  913. // it to the successCallback method.
  914. obtainDevices({
  915. devices: options.devices,
  916. streams: [],
  917. successCallback,
  918. errorCallback: reject,
  919. deviceGUM
  920. });
  921. } else {
  922. const hasDesktop = options.devices.indexOf('desktop') > -1;
  923. if (hasDesktop) {
  924. options.devices.splice(
  925. options.devices.indexOf('desktop'),
  926. 1);
  927. }
  928. options.resolution = options.resolution || '360';
  929. if (options.devices.length) {
  930. this.getUserMediaWithConstraints(
  931. options.devices,
  932. stream => {
  933. const audioDeviceRequested
  934. = options.devices.indexOf('audio') !== -1;
  935. const videoDeviceRequested
  936. = options.devices.indexOf('video') !== -1;
  937. const audioTracksReceived
  938. = stream.getAudioTracks().length > 0;
  939. const videoTracksReceived
  940. = stream.getVideoTracks().length > 0;
  941. if ((audioDeviceRequested && !audioTracksReceived)
  942. || (videoDeviceRequested
  943. && !videoTracksReceived)) {
  944. self.stopMediaStream(stream);
  945. // We are getting here in case if we requested
  946. // 'audio' or 'video' devices or both, but
  947. // didn't get corresponding MediaStreamTrack in
  948. // response stream. We don't know the reason why
  949. // this happened, so reject with general error.
  950. // eslint-disable-next-line no-shadow
  951. const devices = [];
  952. if (audioDeviceRequested
  953. && !audioTracksReceived) {
  954. devices.push('audio');
  955. }
  956. if (videoDeviceRequested
  957. && !videoTracksReceived) {
  958. devices.push('video');
  959. }
  960. // we are missing one of the media we requested
  961. // in order to get the actual error that caused
  962. // this missing media we will call one more time
  963. // getUserMedia so we can obtain the actual
  964. // error (Example usecases are requesting
  965. // audio and video and video device is missing
  966. // or device is denied to be used and chrome is
  967. // set to not ask for permissions)
  968. self.getUserMediaWithConstraints(
  969. devices,
  970. () => {
  971. // we already failed to obtain this
  972. // media, so we are not supposed in any
  973. // way to receive success for this call
  974. // any way we will throw an error to be
  975. // sure the promise will finish
  976. reject(new JitsiTrackError(
  977. { name: 'UnknownError' },
  978. getConstraints(
  979. options.devices,
  980. options),
  981. devices)
  982. );
  983. },
  984. error => {
  985. // rejects with real error for not
  986. // obtaining the media
  987. reject(error);
  988. }, options);
  989. return;
  990. }
  991. if (hasDesktop) {
  992. screenObtainer.obtainStream(
  993. dsOptions,
  994. desktopStream => {
  995. successCallback({ audioVideo: stream,
  996. desktopStream });
  997. }, error => {
  998. self.stopMediaStream(stream);
  999. reject(error);
  1000. });
  1001. } else {
  1002. successCallback({ audioVideo: stream });
  1003. }
  1004. },
  1005. error => reject(error),
  1006. options);
  1007. } else if (hasDesktop) {
  1008. screenObtainer.obtainStream(
  1009. dsOptions,
  1010. stream => successCallback({ desktopStream: stream }),
  1011. error => reject(error));
  1012. }
  1013. }
  1014. });
  1015. }
  1016. /**
  1017. *
  1018. */
  1019. getDeviceAvailability() {
  1020. return devices;
  1021. }
  1022. /**
  1023. *
  1024. */
  1025. isRTCReady() {
  1026. return rtcReady;
  1027. }
  1028. /**
  1029. *
  1030. */
  1031. _isDeviceListAvailable() {
  1032. if (!rtcReady) {
  1033. throw new Error('WebRTC not ready yet');
  1034. }
  1035. return Boolean(navigator.mediaDevices
  1036. && navigator.mediaDevices.enumerateDevices
  1037. && typeof MediaStreamTrack !== 'undefined'
  1038. && MediaStreamTrack.getSources);
  1039. }
  1040. /**
  1041. * Returns a promise which can be used to make sure that the WebRTC stack
  1042. * has been initialized.
  1043. *
  1044. * @returns {Promise} which is resolved only if the WebRTC stack is ready.
  1045. * Note that currently we do not detect stack initialization failure and
  1046. * the promise is never rejected(unless unexpected error occurs).
  1047. */
  1048. onRTCReady() {
  1049. if (rtcReady) {
  1050. return Promise.resolve();
  1051. }
  1052. return new Promise(resolve => {
  1053. const listener = () => {
  1054. eventEmitter.removeListener(RTCEvents.RTC_READY, listener);
  1055. resolve();
  1056. };
  1057. eventEmitter.addListener(RTCEvents.RTC_READY, listener);
  1058. // We have no failed event, so... it either resolves or nothing
  1059. // happens
  1060. });
  1061. }
  1062. /**
  1063. * Checks if its possible to enumerate available cameras/microphones.
  1064. *
  1065. * @returns {Promise<boolean>} a Promise which will be resolved only once
  1066. * the WebRTC stack is ready, either with true if the device listing is
  1067. * available available or with false otherwise.
  1068. */
  1069. isDeviceListAvailable() {
  1070. return this.onRTCReady().then(this._isDeviceListAvailable.bind(this));
  1071. }
  1072. /**
  1073. * Returns true if changing the input (camera / microphone) or output
  1074. * (audio) device is supported and false if not.
  1075. * @params {string} [deviceType] - type of device to change. Default is
  1076. * undefined or 'input', 'output' - for audio output device change.
  1077. * @returns {boolean} true if available, false otherwise.
  1078. */
  1079. isDeviceChangeAvailable(deviceType) {
  1080. return deviceType === 'output' || deviceType === 'audiooutput'
  1081. ? isAudioOutputDeviceChangeAvailable
  1082. : RTCBrowserType.isChrome()
  1083. || RTCBrowserType.isFirefox()
  1084. || RTCBrowserType.isOpera()
  1085. || RTCBrowserType.isTemasysPluginUsed()
  1086. || RTCBrowserType.isNWJS()
  1087. || RTCBrowserType.isElectron();
  1088. }
  1089. /**
  1090. * A method to handle stopping of the stream.
  1091. * One point to handle the differences in various implementations.
  1092. * @param mediaStream MediaStream object to stop.
  1093. */
  1094. stopMediaStream(mediaStream) {
  1095. mediaStream.getTracks().forEach(track => {
  1096. // stop() not supported with IE
  1097. if (!RTCBrowserType.isTemasysPluginUsed() && track.stop) {
  1098. track.stop();
  1099. }
  1100. });
  1101. // leave stop for implementation still using it
  1102. if (mediaStream.stop) {
  1103. mediaStream.stop();
  1104. }
  1105. // The MediaStream implementation of the react-native-webrtc project has
  1106. // an explicit release method that is to be invoked in order to release
  1107. // used resources such as memory.
  1108. if (mediaStream.release) {
  1109. mediaStream.release();
  1110. }
  1111. // if we have done createObjectURL, lets clean it
  1112. const url = mediaStream.jitsiObjectURL;
  1113. if (url) {
  1114. delete mediaStream.jitsiObjectURL;
  1115. (URL || webkitURL).revokeObjectURL(url);
  1116. }
  1117. }
  1118. /**
  1119. * Returns whether the desktop sharing is enabled or not.
  1120. * @returns {boolean}
  1121. */
  1122. isDesktopSharingEnabled() {
  1123. return screenObtainer.isSupported();
  1124. }
  1125. /**
  1126. * Sets current audio output device.
  1127. * @param {string} deviceId - id of 'audiooutput' device from
  1128. * navigator.mediaDevices.enumerateDevices(), 'default' for default
  1129. * device
  1130. * @returns {Promise} - resolves when audio output is changed, is rejected
  1131. * otherwise
  1132. */
  1133. setAudioOutputDevice(deviceId) {
  1134. if (!this.isDeviceChangeAvailable('output')) {
  1135. Promise.reject(
  1136. new Error('Audio output device change is not supported'));
  1137. }
  1138. return featureDetectionAudioEl.setSinkId(deviceId)
  1139. .then(() => {
  1140. audioOutputDeviceId = deviceId;
  1141. audioOutputChanged = true;
  1142. logger.log(`Audio output device set to ${deviceId}`);
  1143. eventEmitter.emit(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1144. deviceId);
  1145. });
  1146. }
  1147. /**
  1148. * Returns currently used audio output device id, '' stands for default
  1149. * device
  1150. * @returns {string}
  1151. */
  1152. getAudioOutputDevice() {
  1153. return audioOutputDeviceId;
  1154. }
  1155. /**
  1156. * Returns list of available media devices if its obtained, otherwise an
  1157. * empty array is returned/
  1158. * @returns {Array} list of available media devices.
  1159. */
  1160. getCurrentlyAvailableMediaDevices() {
  1161. return currentlyAvailableMediaDevices;
  1162. }
  1163. /**
  1164. * Returns event data for device to be reported to stats.
  1165. * @returns {MediaDeviceInfo} device.
  1166. */
  1167. getEventDataForActiveDevice(device) {
  1168. const deviceList = [];
  1169. const deviceData = {
  1170. 'deviceId': device.deviceId,
  1171. 'kind': device.kind,
  1172. 'label': device.label,
  1173. 'groupId': device.groupId
  1174. };
  1175. deviceList.push(deviceData);
  1176. return { deviceList };
  1177. }
  1178. }
  1179. /**
  1180. * Rejects a Promise because WebRTC is not supported.
  1181. *
  1182. * @param {string} errorMessage - The human-readable message of the Error which
  1183. * is the reason for the rejection.
  1184. * @param {Function} reject - The reject function of the Promise.
  1185. * @returns {void}
  1186. */
  1187. function rejectWithWebRTCNotSupported(errorMessage, reject) {
  1188. const error = new Error(errorMessage);
  1189. // WebRTC is not supported either natively or via a known plugin such as
  1190. // Temasys.
  1191. // XXX The Error class already has a property name which is commonly used to
  1192. // detail the represented error in a non-human-readable way (in contrast to
  1193. // the human-readable property message). I explicitly did not want to
  1194. // introduce a new specific property.
  1195. // FIXME None of the existing JitsiXXXErrors seemed to be appropriate
  1196. // recipients of the constant WEBRTC_NOT_SUPPORTED so I explicitly chose to
  1197. // leave it as a magic string at the time of this writing.
  1198. error.name = 'WEBRTC_NOT_SUPPORTED';
  1199. logger.error(errorMessage);
  1200. reject(error);
  1201. }
  1202. const rtcUtils = new RTCUtils();
  1203. /**
  1204. *
  1205. * @param options
  1206. */
  1207. function obtainDevices(options) {
  1208. if (!options.devices || options.devices.length === 0) {
  1209. return options.successCallback(options.streams || {});
  1210. }
  1211. const device = options.devices.splice(0, 1);
  1212. options.deviceGUM[device](
  1213. stream => {
  1214. options.streams = options.streams || {};
  1215. options.streams[device] = stream;
  1216. obtainDevices(options);
  1217. },
  1218. error => {
  1219. Object.keys(options.streams).forEach(
  1220. d => rtcUtils.stopMediaStream(options.streams[d]));
  1221. logger.error(
  1222. `failed to obtain ${device} stream - stop`, error);
  1223. options.errorCallback(error);
  1224. });
  1225. }
  1226. /**
  1227. * In case of IE we continue from 'onReady' callback passed to RTCUtils
  1228. * constructor. It will be invoked by Temasys plugin once it is initialized.
  1229. *
  1230. * @param options
  1231. * @param GUM
  1232. */
  1233. function onReady(options, GUM) {
  1234. rtcReady = true;
  1235. eventEmitter.emit(RTCEvents.RTC_READY, true);
  1236. screenObtainer.init(options, GUM);
  1237. // Initialize rawEnumerateDevicesWithCallback
  1238. initRawEnumerateDevicesWithCallback();
  1239. if (rtcUtils.isDeviceListAvailable() && rawEnumerateDevicesWithCallback) {
  1240. rawEnumerateDevicesWithCallback(ds => {
  1241. currentlyAvailableMediaDevices = ds.splice(0);
  1242. eventEmitter.emit(RTCEvents.DEVICE_LIST_AVAILABLE,
  1243. currentlyAvailableMediaDevices);
  1244. if (isDeviceChangeEventSupported) {
  1245. navigator.mediaDevices.addEventListener(
  1246. 'devicechange',
  1247. () => rtcUtils.enumerateDevices(onMediaDevicesListChanged));
  1248. } else {
  1249. pollForAvailableMediaDevices();
  1250. }
  1251. });
  1252. }
  1253. }
  1254. /**
  1255. * Wraps original attachMediaStream function to set current audio output device
  1256. * if this is supported.
  1257. * @param {Function} origAttachMediaStream
  1258. * @returns {Function}
  1259. */
  1260. function wrapAttachMediaStream(origAttachMediaStream) {
  1261. return function(element, stream) {
  1262. // eslint-disable-next-line prefer-rest-params
  1263. const res = origAttachMediaStream.apply(rtcUtils, arguments);
  1264. if (stream
  1265. && rtcUtils.isDeviceChangeAvailable('output')
  1266. && stream.getAudioTracks
  1267. && stream.getAudioTracks().length
  1268. // we skip setting audio output if there was no explicit change
  1269. && audioOutputChanged) {
  1270. element.setSinkId(rtcUtils.getAudioOutputDevice())
  1271. .catch(function(ex) {
  1272. const err
  1273. = new JitsiTrackError(ex, null, [ 'audiooutput' ]);
  1274. GlobalOnErrorHandler.callUnhandledRejectionHandler({
  1275. promise: this, // eslint-disable-line no-invalid-this
  1276. reason: err
  1277. });
  1278. logger.warn('Failed to set audio output device for the '
  1279. + 'element. Default audio output device will be used '
  1280. + 'instead',
  1281. element, err);
  1282. });
  1283. }
  1284. return res;
  1285. };
  1286. }
  1287. export default rtcUtils;