modified lib-jitsi-meet dev repo
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 69KB

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