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