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.

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