You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RTCUtils.js 43KB

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