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 39KB

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