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.

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