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.

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