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 55KB

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