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

RTCUtils.js 52KB

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