Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

RTCUtils.js 52KB

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