Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

RTCUtils.js 52KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451
  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(navigator.mediaDevices
  1029. && navigator.mediaDevices.enumerateDevices
  1030. && typeof MediaStreamTrack !== 'undefined'
  1031. && MediaStreamTrack.getSources);
  1032. }
  1033. /**
  1034. * Returns a promise which can be used to make sure that the WebRTC stack
  1035. * has been initialized.
  1036. *
  1037. * @returns {Promise} which is resolved only if the WebRTC stack is ready.
  1038. * Note that currently we do not detect stack initialization failure and
  1039. * the promise is never rejected(unless unexpected error occurs).
  1040. */
  1041. onRTCReady() {
  1042. if (rtcReady) {
  1043. return Promise.resolve();
  1044. }
  1045. return new Promise(resolve => {
  1046. const listener = () => {
  1047. eventEmitter.removeListener(RTCEvents.RTC_READY, listener);
  1048. resolve();
  1049. };
  1050. eventEmitter.addListener(RTCEvents.RTC_READY, listener);
  1051. // We have no failed event, so... it either resolves or nothing
  1052. // happens
  1053. });
  1054. }
  1055. /**
  1056. * Checks if its possible to enumerate available cameras/microphones.
  1057. *
  1058. * @returns {Promise<boolean>} a Promise which will be resolved only once
  1059. * the WebRTC stack is ready, either with true if the device listing is
  1060. * available available or with false otherwise.
  1061. */
  1062. isDeviceListAvailable() {
  1063. return this.onRTCReady().then(this._isDeviceListAvailable.bind(this));
  1064. }
  1065. /**
  1066. * Returns true if changing the input (camera / microphone) or output
  1067. * (audio) device is supported and false if not.
  1068. * @params {string} [deviceType] - type of device to change. Default is
  1069. * undefined or 'input', 'output' - for audio output device change.
  1070. * @returns {boolean} true if available, false otherwise.
  1071. */
  1072. isDeviceChangeAvailable(deviceType) {
  1073. return deviceType === 'output' || deviceType === 'audiooutput'
  1074. ? isAudioOutputDeviceChangeAvailable
  1075. : RTCBrowserType.isChrome()
  1076. || RTCBrowserType.isFirefox()
  1077. || RTCBrowserType.isOpera()
  1078. || RTCBrowserType.isTemasysPluginUsed()
  1079. || RTCBrowserType.isNWJS()
  1080. || RTCBrowserType.isElectron();
  1081. }
  1082. /**
  1083. * A method to handle stopping of the stream.
  1084. * One point to handle the differences in various implementations.
  1085. * @param mediaStream MediaStream object to stop.
  1086. */
  1087. stopMediaStream(mediaStream) {
  1088. mediaStream.getTracks().forEach(track => {
  1089. // stop() not supported with IE
  1090. if (!RTCBrowserType.isTemasysPluginUsed() && track.stop) {
  1091. track.stop();
  1092. }
  1093. });
  1094. // leave stop for implementation still using it
  1095. if (mediaStream.stop) {
  1096. mediaStream.stop();
  1097. }
  1098. // The MediaStream implementation of the react-native-webrtc project has
  1099. // an explicit release method that is to be invoked in order to release
  1100. // used resources such as memory.
  1101. if (mediaStream.release) {
  1102. mediaStream.release();
  1103. }
  1104. // if we have done createObjectURL, lets clean it
  1105. const url = mediaStream.jitsiObjectURL;
  1106. if (url) {
  1107. delete mediaStream.jitsiObjectURL;
  1108. (URL || webkitURL).revokeObjectURL(url);
  1109. }
  1110. }
  1111. /**
  1112. * Returns whether the desktop sharing is enabled or not.
  1113. * @returns {boolean}
  1114. */
  1115. isDesktopSharingEnabled() {
  1116. return screenObtainer.isSupported();
  1117. }
  1118. /**
  1119. * Sets current audio output device.
  1120. * @param {string} deviceId - id of 'audiooutput' device from
  1121. * navigator.mediaDevices.enumerateDevices(), 'default' for default
  1122. * device
  1123. * @returns {Promise} - resolves when audio output is changed, is rejected
  1124. * otherwise
  1125. */
  1126. setAudioOutputDevice(deviceId) {
  1127. if (!this.isDeviceChangeAvailable('output')) {
  1128. Promise.reject(
  1129. new Error('Audio output device change is not supported'));
  1130. }
  1131. return featureDetectionAudioEl.setSinkId(deviceId)
  1132. .then(() => {
  1133. audioOutputDeviceId = deviceId;
  1134. audioOutputChanged = true;
  1135. logger.log(`Audio output device set to ${deviceId}`);
  1136. eventEmitter.emit(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1137. deviceId);
  1138. });
  1139. }
  1140. /**
  1141. * Returns currently used audio output device id, '' stands for default
  1142. * device
  1143. * @returns {string}
  1144. */
  1145. getAudioOutputDevice() {
  1146. return audioOutputDeviceId;
  1147. }
  1148. /**
  1149. * Returns list of available media devices if its obtained, otherwise an
  1150. * empty array is returned/
  1151. * @returns {Array} list of available media devices.
  1152. */
  1153. getCurrentlyAvailableMediaDevices() {
  1154. return currentlyAvailableMediaDevices;
  1155. }
  1156. /**
  1157. * Returns event data for device to be reported to stats.
  1158. * @returns {MediaDeviceInfo} device.
  1159. */
  1160. getEventDataForActiveDevice(device) {
  1161. const deviceList = [];
  1162. const deviceData = {
  1163. 'deviceId': device.deviceId,
  1164. 'kind': device.kind,
  1165. 'label': device.label,
  1166. 'groupId': device.groupId
  1167. };
  1168. deviceList.push(deviceData);
  1169. return { deviceList };
  1170. }
  1171. }
  1172. /**
  1173. * Rejects a Promise because WebRTC is not supported.
  1174. *
  1175. * @param {string} errorMessage - The human-readable message of the Error which
  1176. * is the reason for the rejection.
  1177. * @param {Function} reject - The reject function of the Promise.
  1178. * @returns {void}
  1179. */
  1180. function rejectWithWebRTCNotSupported(errorMessage, reject) {
  1181. const error = new Error(errorMessage);
  1182. // WebRTC is not supported either natively or via a known plugin such as
  1183. // Temasys.
  1184. // XXX The Error class already has a property name which is commonly used to
  1185. // detail the represented error in a non-human-readable way (in contrast to
  1186. // the human-readable property message). I explicitly did not want to
  1187. // introduce a new specific property.
  1188. // FIXME None of the existing JitsiXXXErrors seemed to be appropriate
  1189. // recipients of the constant WEBRTC_NOT_SUPPORTED so I explicitly chose to
  1190. // leave it as a magic string at the time of this writing.
  1191. error.name = 'WEBRTC_NOT_SUPPORTED';
  1192. logger.error(errorMessage);
  1193. reject(error);
  1194. }
  1195. const rtcUtils = new RTCUtils();
  1196. /**
  1197. *
  1198. * @param options
  1199. */
  1200. function obtainDevices(options) {
  1201. if (!options.devices || options.devices.length === 0) {
  1202. return options.successCallback(options.streams || {});
  1203. }
  1204. const device = options.devices.splice(0, 1);
  1205. options.deviceGUM[device](
  1206. stream => {
  1207. options.streams = options.streams || {};
  1208. options.streams[device] = stream;
  1209. obtainDevices(options);
  1210. },
  1211. error => {
  1212. Object.keys(options.streams).forEach(
  1213. d => rtcUtils.stopMediaStream(options.streams[d]));
  1214. logger.error(
  1215. `failed to obtain ${device} stream - stop`, error);
  1216. options.errorCallback(error);
  1217. });
  1218. }
  1219. /**
  1220. * In case of IE we continue from 'onReady' callback passed to RTCUtils
  1221. * constructor. It will be invoked by Temasys plugin once it is initialized.
  1222. *
  1223. * @param options
  1224. * @param GUM
  1225. */
  1226. function onReady(options, GUM) {
  1227. rtcReady = true;
  1228. eventEmitter.emit(RTCEvents.RTC_READY, true);
  1229. screenObtainer.init(options, GUM);
  1230. // Initialize rawEnumerateDevicesWithCallback
  1231. initRawEnumerateDevicesWithCallback();
  1232. if (rtcUtils.isDeviceListAvailable() && rawEnumerateDevicesWithCallback) {
  1233. rawEnumerateDevicesWithCallback(ds => {
  1234. currentlyAvailableMediaDevices = ds.splice(0);
  1235. eventEmitter.emit(RTCEvents.DEVICE_LIST_AVAILABLE,
  1236. currentlyAvailableMediaDevices);
  1237. if (isDeviceChangeEventSupported) {
  1238. navigator.mediaDevices.addEventListener(
  1239. 'devicechange',
  1240. () => rtcUtils.enumerateDevices(onMediaDevicesListChanged));
  1241. } else {
  1242. pollForAvailableMediaDevices();
  1243. }
  1244. });
  1245. }
  1246. }
  1247. /**
  1248. * Wraps original attachMediaStream function to set current audio output device
  1249. * if this is supported.
  1250. * @param {Function} origAttachMediaStream
  1251. * @returns {Function}
  1252. */
  1253. function wrapAttachMediaStream(origAttachMediaStream) {
  1254. return function(element, stream) {
  1255. // eslint-disable-next-line prefer-rest-params
  1256. const res = origAttachMediaStream.apply(rtcUtils, arguments);
  1257. if (stream
  1258. && rtcUtils.isDeviceChangeAvailable('output')
  1259. && stream.getAudioTracks
  1260. && stream.getAudioTracks().length
  1261. // we skip setting audio output if there was no explicit change
  1262. && audioOutputChanged) {
  1263. element.setSinkId(rtcUtils.getAudioOutputDevice())
  1264. .catch(function(ex) {
  1265. const err
  1266. = new JitsiTrackError(ex, null, [ 'audiooutput' ]);
  1267. GlobalOnErrorHandler.callUnhandledRejectionHandler({
  1268. promise: this, // eslint-disable-line no-invalid-this
  1269. reason: err
  1270. });
  1271. logger.warn('Failed to set audio output device for the '
  1272. + 'element. Default audio output device will be used '
  1273. + 'instead',
  1274. element, err);
  1275. });
  1276. }
  1277. return res;
  1278. };
  1279. }
  1280. export default rtcUtils;