Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

RTCUtils.js 47KB

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