Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

RTCUtils.js 46KB

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