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

RTCUtils.js 56KB

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