modified lib-jitsi-meet dev repo
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

RTCUtils.js 51KB

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