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

RTCUtils.js 52KB

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