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

RTCUtils.js 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  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 devices = {
  20. audio: true,
  21. video: true
  22. };
  23. var rtcReady = false;
  24. function setResolutionConstraints(constraints, resolution) {
  25. var isAndroid = RTCBrowserType.isAndroid();
  26. if (Resolutions[resolution]) {
  27. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  28. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  29. }
  30. else if (isAndroid) {
  31. // FIXME can't remember if the purpose of this was to always request
  32. // low resolution on Android ? if yes it should be moved up front
  33. constraints.video.mandatory.minWidth = 320;
  34. constraints.video.mandatory.minHeight = 180;
  35. constraints.video.mandatory.maxFrameRate = 15;
  36. }
  37. if (constraints.video.mandatory.minWidth)
  38. constraints.video.mandatory.maxWidth =
  39. constraints.video.mandatory.minWidth;
  40. if (constraints.video.mandatory.minHeight)
  41. constraints.video.mandatory.maxHeight =
  42. constraints.video.mandatory.minHeight;
  43. }
  44. /**
  45. * @param {string[]} um required user media types
  46. *
  47. * @param {Object} [options={}] optional parameters
  48. * @param {string} options.resolution
  49. * @param {number} options.bandwidth
  50. * @param {number} options.fps
  51. * @param {string} options.desktopStream
  52. * @param {string} options.cameraDeviceId
  53. * @param {string} options.micDeviceId
  54. * @param {bool} firefox_fake_device
  55. */
  56. function getConstraints(um, options) {
  57. var constraints = {audio: false, video: false};
  58. if (um.indexOf('video') >= 0) {
  59. // same behaviour as true
  60. constraints.video = { mandatory: {}, optional: [] };
  61. if (options.cameraDeviceId) {
  62. // new style of settings device id (FF only)
  63. constraints.video.deviceId = options.cameraDeviceId;
  64. // old style
  65. constraints.video.optional.push({
  66. sourceId: options.cameraDeviceId
  67. });
  68. }
  69. constraints.video.optional.push({ googLeakyBucket: true });
  70. setResolutionConstraints(constraints, options.resolution);
  71. }
  72. if (um.indexOf('audio') >= 0) {
  73. if (!RTCBrowserType.isFirefox()) {
  74. // same behaviour as true
  75. constraints.audio = { mandatory: {}, optional: []};
  76. if (options.micDeviceId) {
  77. // new style of settings device id (FF only)
  78. constraints.audio.deviceId = options.micDeviceId;
  79. // old style
  80. constraints.audio.optional.push({
  81. sourceId: options.micDeviceId
  82. });
  83. }
  84. // if it is good enough for hangouts...
  85. constraints.audio.optional.push(
  86. {googEchoCancellation: true},
  87. {googAutoGainControl: true},
  88. {googNoiseSupression: true},
  89. {googHighpassFilter: true},
  90. {googNoisesuppression2: true},
  91. {googEchoCancellation2: true},
  92. {googAutoGainControl2: true}
  93. );
  94. } else {
  95. if (options.micDeviceId) {
  96. constraints.audio = {
  97. mandatory: {},
  98. deviceId: options.micDeviceId, // new style
  99. optional: [{
  100. sourceId: options.micDeviceId // old style
  101. }]};
  102. } else {
  103. constraints.audio = true;
  104. }
  105. }
  106. }
  107. if (um.indexOf('screen') >= 0) {
  108. if (RTCBrowserType.isChrome()) {
  109. constraints.video = {
  110. mandatory: {
  111. chromeMediaSource: "screen",
  112. googLeakyBucket: true,
  113. maxWidth: window.screen.width,
  114. maxHeight: window.screen.height,
  115. maxFrameRate: 3
  116. },
  117. optional: []
  118. };
  119. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  120. constraints.video = {
  121. optional: [
  122. {
  123. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  124. }
  125. ]
  126. };
  127. } else if (RTCBrowserType.isFirefox()) {
  128. constraints.video = {
  129. mozMediaSource: "window",
  130. mediaSource: "window"
  131. };
  132. } else {
  133. logger.error(
  134. "'screen' WebRTC media source is supported only in Chrome" +
  135. " and with Temasys plugin");
  136. }
  137. }
  138. if (um.indexOf('desktop') >= 0) {
  139. constraints.video = {
  140. mandatory: {
  141. chromeMediaSource: "desktop",
  142. chromeMediaSourceId: options.desktopStream,
  143. googLeakyBucket: true,
  144. maxWidth: window.screen.width,
  145. maxHeight: window.screen.height,
  146. maxFrameRate: 3
  147. },
  148. optional: []
  149. };
  150. }
  151. if (options.bandwidth) {
  152. if (!constraints.video) {
  153. //same behaviour as true
  154. constraints.video = {mandatory: {}, optional: []};
  155. }
  156. constraints.video.optional.push({bandwidth: options.bandwidth});
  157. }
  158. if (options.fps) {
  159. // for some cameras it might be necessary to request 30fps
  160. // so they choose 30fps mjpg over 10fps yuy2
  161. if (!constraints.video) {
  162. // same behaviour as true;
  163. constraints.video = {mandatory: {}, optional: []};
  164. }
  165. constraints.video.mandatory.minFrameRate = options.fps;
  166. }
  167. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  168. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  169. // this later can be a problem with some of the tests
  170. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  171. {
  172. // seems to be fixed now, removing this experimental fix, as having
  173. // multiple audio tracks brake the tests
  174. //constraints.audio = true;
  175. constraints.fake = true;
  176. }
  177. return constraints;
  178. }
  179. function setAvailableDevices(um, available) {
  180. if (um.indexOf("video") != -1) {
  181. devices.video = available;
  182. }
  183. if (um.indexOf("audio") != -1) {
  184. devices.audio = available;
  185. }
  186. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  187. }
  188. // In case of IE we continue from 'onReady' callback
  189. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  190. // once it is initialized.
  191. function onReady (options, GUM) {
  192. rtcReady = true;
  193. eventEmitter.emit(RTCEvents.RTC_READY, true);
  194. screenObtainer.init(options, GUM);
  195. }
  196. /**
  197. * Apply function with arguments if function exists.
  198. * Do nothing if function not provided.
  199. * @param {function} [fn] function to apply
  200. * @param {Array} [args=[]] arguments for function
  201. */
  202. function maybeApply(fn, args) {
  203. if (fn) {
  204. fn.apply(null, args || []);
  205. }
  206. }
  207. var getUserMediaStatus = {
  208. initialized: false,
  209. callbacks: []
  210. };
  211. /**
  212. * Wrap `getUserMedia` to allow others to know if it was executed at least
  213. * once or not. Wrapper function uses `getUserMediaStatus` object.
  214. * @param {Function} getUserMedia native function
  215. * @returns {Function} wrapped function
  216. */
  217. function wrapGetUserMedia(getUserMedia) {
  218. return function (constraints, successCallback, errorCallback) {
  219. getUserMedia(constraints, function (stream) {
  220. maybeApply(successCallback, [stream]);
  221. if (!getUserMediaStatus.initialized) {
  222. getUserMediaStatus.initialized = true;
  223. getUserMediaStatus.callbacks.forEach(function (callback) {
  224. callback();
  225. });
  226. getUserMediaStatus.callbacks.length = 0;
  227. }
  228. }, function (error) {
  229. maybeApply(errorCallback, [error]);
  230. });
  231. };
  232. }
  233. /**
  234. * Create stub device which equals to auto selected device.
  235. * @param {string} kind if that should be `audio` or `video` device
  236. * @returns {Object} stub device description in `enumerateDevices` format
  237. */
  238. function createAutoDeviceInfo(kind) {
  239. return {
  240. facing: null,
  241. label: 'Auto',
  242. kind: kind,
  243. deviceId: '',
  244. groupId: ''
  245. };
  246. }
  247. /**
  248. * Execute function after getUserMedia was executed at least once.
  249. * @param {Function} callback function to execute after getUserMedia
  250. */
  251. function afterUserMediaInitialized(callback) {
  252. if (getUserMediaStatus.initialized) {
  253. callback();
  254. } else {
  255. getUserMediaStatus.callbacks.push(callback);
  256. }
  257. }
  258. /**
  259. * Wrapper function which makes enumerateDevices to wait
  260. * until someone executes getUserMedia first time.
  261. * @param {Function} enumerateDevices native function
  262. * @returns {Funtion} wrapped function
  263. */
  264. function wrapEnumerateDevices(enumerateDevices) {
  265. return function (callback) {
  266. // enumerate devices only after initial getUserMedia
  267. afterUserMediaInitialized(function () {
  268. enumerateDevices().then(function (devices) {
  269. //add auto devices
  270. devices.unshift(
  271. createAutoDeviceInfo('audioinput'),
  272. createAutoDeviceInfo('videoinput')
  273. );
  274. callback(devices);
  275. }, function (err) {
  276. console.error('cannot enumerate devices: ', err);
  277. // return only auto devices
  278. callback([createAutoDeviceInfo('audioinput'),
  279. createAutoDeviceInfo('videoinput')]);
  280. });
  281. });
  282. };
  283. }
  284. /**
  285. * Use old MediaStreamTrack to get devices list and
  286. * convert it to enumerateDevices format.
  287. * @param {Function} callback function to call when received devices list.
  288. */
  289. function enumerateDevicesThroughMediaStreamTrack (callback) {
  290. MediaStreamTrack.getSources(function (sources) {
  291. var devices = sources.map(function (source) {
  292. var kind = (source.kind || '').toLowerCase();
  293. return {
  294. facing: source.facing || null,
  295. label: source.label,
  296. kind: kind ? kind + 'input': null,
  297. deviceId: source.id,
  298. groupId: source.groupId || null
  299. };
  300. });
  301. //add auto devices
  302. devices.unshift(
  303. createAutoDeviceInfo('audioinput'),
  304. createAutoDeviceInfo('videoinput')
  305. );
  306. callback(devices);
  307. });
  308. }
  309. function obtainDevices(options) {
  310. if(!options.devices || options.devices.length === 0) {
  311. return options.successCallback(options.streams || {});
  312. }
  313. var device = options.devices.splice(0, 1);
  314. var devices = [];
  315. devices.push(device);
  316. options.deviceGUM[device](function (stream) {
  317. options.streams = options.streams || {};
  318. options.streams[device] = stream;
  319. obtainDevices(options);
  320. },
  321. function (error) {
  322. Object.keys(options.streams).forEach(function(device) {
  323. RTCUtils.stopMediaStream(options.streams[device]);
  324. });
  325. logger.error(
  326. "failed to obtain " + device + " stream - stop", error);
  327. options.errorCallback(JitsiTrackErrors.parseError(error, devices));
  328. });
  329. }
  330. /**
  331. * Handles the newly created Media Streams.
  332. * @param streams the new Media Streams
  333. * @param resolution the resolution of the video streams
  334. * @returns {*[]} object that describes the new streams
  335. */
  336. function handleLocalStream(streams, resolution) {
  337. var audioStream, videoStream, desktopStream, res = [];
  338. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  339. // an object with two properties: audioStream, videoStream.
  340. if (window.webkitMediaStream) {
  341. var audioVideo = streams.audioVideo;
  342. if (audioVideo) {
  343. var audioTracks = audioVideo.getAudioTracks();
  344. if(audioTracks.length) {
  345. audioStream = new webkitMediaStream();
  346. for (var i = 0; i < audioTracks.length; i++) {
  347. audioStream.addTrack(audioTracks[i]);
  348. }
  349. }
  350. var videoTracks = audioVideo.getVideoTracks();
  351. if(videoTracks.length) {
  352. videoStream = new webkitMediaStream();
  353. for (var j = 0; j < videoTracks.length; j++) {
  354. videoStream.addTrack(videoTracks[j]);
  355. }
  356. }
  357. }
  358. if (streams && streams.desktopStream)
  359. desktopStream = streams.desktopStream;
  360. }
  361. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  362. if (streams && streams.audio)
  363. audioStream = streams.audio;
  364. if (streams && streams.video)
  365. videoStream = streams.video;
  366. if(streams && streams.desktop)
  367. desktopStream = streams.desktop;
  368. }
  369. if (desktopStream)
  370. res.push({
  371. stream: desktopStream,
  372. type: MediaType.VIDEO,
  373. videoType: VideoType.DESKTOP
  374. });
  375. if(audioStream)
  376. res.push({
  377. stream: audioStream,
  378. type: MediaType.AUDIO,
  379. videoType: null
  380. });
  381. if(videoStream)
  382. res.push({
  383. stream: videoStream,
  384. type: MediaType.VIDEO,
  385. videoType: VideoType.CAMERA,
  386. resolution: resolution
  387. });
  388. return res;
  389. }
  390. //Options parameter is to pass config options. Currently uses only "useIPv6".
  391. var RTCUtils = {
  392. init: function (options) {
  393. return new Promise(function(resolve, reject) {
  394. if (RTCBrowserType.isFirefox()) {
  395. var FFversion = RTCBrowserType.getFirefoxVersion();
  396. if (FFversion < 40) {
  397. logger.error(
  398. "Firefox version too old: " + FFversion +
  399. ". Required >= 40.");
  400. reject(new Error("Firefox version too old: " + FFversion +
  401. ". Required >= 40."));
  402. return;
  403. }
  404. this.peerconnection = mozRTCPeerConnection;
  405. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  406. this.enumerateDevices = wrapEnumerateDevices(
  407. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  408. );
  409. this.pc_constraints = {};
  410. this.attachMediaStream = function (element, stream) {
  411. // srcObject is being standardized and FF will eventually
  412. // support that unprefixed. FF also supports the
  413. // "element.src = URL.createObjectURL(...)" combo, but that
  414. // will be deprecated in favour of srcObject.
  415. //
  416. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  417. // https://github.com/webrtc/samples/issues/302
  418. if (!element)
  419. return;
  420. element.mozSrcObject = stream;
  421. element.play();
  422. return element;
  423. };
  424. this.getStreamID = function (stream) {
  425. var id = stream.id;
  426. if (!id) {
  427. var tracks = stream.getVideoTracks();
  428. if (!tracks || tracks.length === 0) {
  429. tracks = stream.getAudioTracks();
  430. }
  431. id = tracks[0].id;
  432. }
  433. return SDPUtil.filter_special_chars(id);
  434. };
  435. this.getVideoSrc = function (element) {
  436. if (!element)
  437. return null;
  438. return element.mozSrcObject;
  439. };
  440. this.setVideoSrc = function (element, src) {
  441. if (element)
  442. element.mozSrcObject = src;
  443. };
  444. RTCSessionDescription = mozRTCSessionDescription;
  445. RTCIceCandidate = mozRTCIceCandidate;
  446. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera() || RTCBrowserType.isNWJS()) {
  447. this.peerconnection = webkitRTCPeerConnection;
  448. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  449. if (navigator.mediaDevices) {
  450. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  451. this.enumerateDevices = wrapEnumerateDevices(
  452. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  453. );
  454. } else {
  455. this.getUserMedia = getUserMedia;
  456. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  457. }
  458. this.attachMediaStream = function (element, stream) {
  459. // saves the created url for the stream, so we can reuse it
  460. // and not keep creating urls
  461. if (!stream.jitsiObjectURL) {
  462. stream.jitsiObjectURL
  463. = webkitURL.createObjectURL(stream);
  464. }
  465. element.src = stream.jitsiObjectURL;
  466. return element;
  467. };
  468. this.getStreamID = function (stream) {
  469. // streams from FF endpoints have the characters '{' and '}'
  470. // that make jQuery choke.
  471. return SDPUtil.filter_special_chars(stream.id);
  472. };
  473. this.getVideoSrc = function (element) {
  474. if (!element)
  475. return null;
  476. return element.getAttribute("src");
  477. };
  478. this.setVideoSrc = function (element, src) {
  479. if (!src) {
  480. src = '';
  481. }
  482. if (element)
  483. element.setAttribute("src", src);
  484. };
  485. // DTLS should now be enabled by default but..
  486. this.pc_constraints = {'optional': [
  487. {'DtlsSrtpKeyAgreement': 'true'}
  488. ]};
  489. if (options.useIPv6) {
  490. // https://code.google.com/p/webrtc/issues/detail?id=2828
  491. this.pc_constraints.optional.push({googIPv6: true});
  492. }
  493. if (RTCBrowserType.isAndroid()) {
  494. this.pc_constraints = {}; // disable DTLS on Android
  495. }
  496. if (!webkitMediaStream.prototype.getVideoTracks) {
  497. webkitMediaStream.prototype.getVideoTracks = function () {
  498. return this.videoTracks;
  499. };
  500. }
  501. if (!webkitMediaStream.prototype.getAudioTracks) {
  502. webkitMediaStream.prototype.getAudioTracks = function () {
  503. return this.audioTracks;
  504. };
  505. }
  506. }
  507. // Detect IE/Safari
  508. else if (RTCBrowserType.isTemasysPluginUsed()) {
  509. //AdapterJS.WebRTCPlugin.setLogLevel(
  510. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  511. var self = this;
  512. AdapterJS.webRTCReady(function (isPlugin) {
  513. self.peerconnection = RTCPeerConnection;
  514. self.getUserMedia = window.getUserMedia;
  515. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  516. self.attachMediaStream = function (element, stream) {
  517. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  518. return;
  519. }
  520. var isVideoStream = !!stream.getVideoTracks().length;
  521. if (isVideoStream && !$(element).is(':visible')) {
  522. throw new Error('video element must be visible to attach video stream');
  523. }
  524. return attachMediaStream(element, stream);
  525. };
  526. self.getStreamID = function (stream) {
  527. var id = SDPUtil.filter_special_chars(stream.label);
  528. return id;
  529. };
  530. self.getVideoSrc = function (element) {
  531. if (!element) {
  532. logger.warn("Attempt to get video SRC of null element");
  533. return null;
  534. }
  535. var children = element.children;
  536. for (var i = 0; i !== children.length; ++i) {
  537. if (children[i].name === 'streamId') {
  538. return children[i].value;
  539. }
  540. }
  541. //logger.info(element.id + " SRC: " + src);
  542. return null;
  543. };
  544. self.setVideoSrc = function (element, src) {
  545. //logger.info("Set video src: ", element, src);
  546. if (!src) {
  547. attachMediaStream(element, null);
  548. } else {
  549. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  550. var stream
  551. = AdapterJS.WebRTCPlugin.plugin
  552. .getStreamWithId(
  553. AdapterJS.WebRTCPlugin.pageId, src);
  554. attachMediaStream(element, stream);
  555. }
  556. };
  557. onReady(options, self.getUserMediaWithConstraints);
  558. resolve();
  559. });
  560. } else {
  561. try {
  562. logger.error('Browser does not appear to be WebRTC-capable');
  563. } catch (e) {
  564. }
  565. reject('Browser does not appear to be WebRTC-capable');
  566. return;
  567. }
  568. // Call onReady() if Temasys plugin is not used
  569. if (!RTCBrowserType.isTemasysPluginUsed()) {
  570. onReady(options, this.getUserMediaWithConstraints);
  571. resolve();
  572. }
  573. }.bind(this));
  574. },
  575. /**
  576. * @param {string[]} um required user media types
  577. * @param {function} success_callback
  578. * @param {Function} failure_callback
  579. * @param {Object} [options] optional parameters
  580. * @param {string} options.resolution
  581. * @param {number} options.bandwidth
  582. * @param {number} options.fps
  583. * @param {string} options.desktopStream
  584. * @param {string} options.cameraDeviceId
  585. * @param {string} options.micDeviceId
  586. **/
  587. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  588. options = options || {};
  589. var resolution = options.resolution;
  590. var constraints = getConstraints(um, options);
  591. logger.info("Get media constraints", constraints);
  592. try {
  593. this.getUserMedia(constraints,
  594. function (stream) {
  595. logger.log('onUserMediaSuccess');
  596. setAvailableDevices(um, true);
  597. success_callback(stream);
  598. },
  599. function (error) {
  600. setAvailableDevices(um, false);
  601. logger.warn('Failed to get access to local media. Error ',
  602. error, constraints);
  603. if (failure_callback) {
  604. failure_callback(error, resolution);
  605. }
  606. });
  607. } catch (e) {
  608. logger.error('GUM failed: ', e);
  609. if (failure_callback) {
  610. failure_callback(e);
  611. }
  612. }
  613. },
  614. /**
  615. * Creates the local MediaStreams.
  616. * @param {Object} [options] optional parameters
  617. * @param {Array} options.devices the devices that will be requested
  618. * @param {string} options.resolution resolution constraints
  619. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  620. * type: "audio" or "video", videoType: "camera" or "desktop"}
  621. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  622. * @param {string} options.cameraDeviceId
  623. * @param {string} options.micDeviceId
  624. * @returns {*} Promise object that will receive the new JitsiTracks
  625. */
  626. obtainAudioAndVideoPermissions: function (options) {
  627. var self = this;
  628. options = options || {};
  629. return new Promise(function (resolve, reject) {
  630. var successCallback = function (stream) {
  631. resolve(handleLocalStream(stream, options.resolution));
  632. };
  633. options.devices = options.devices || ['audio', 'video'];
  634. if(!screenObtainer.isSupported()
  635. && options.devices.indexOf("desktop") !== -1){
  636. reject(new Error("Desktop sharing is not supported!"));
  637. }
  638. if (RTCBrowserType.isFirefox() ||
  639. RTCBrowserType.isTemasysPluginUsed()) {
  640. var GUM = function (device, s, e) {
  641. this.getUserMediaWithConstraints(device, s, e, options);
  642. };
  643. var deviceGUM = {
  644. "audio": GUM.bind(self, ["audio"]),
  645. "video": GUM.bind(self, ["video"])
  646. };
  647. if(screenObtainer.isSupported()){
  648. deviceGUM["desktop"] = screenObtainer.obtainStream.bind(
  649. screenObtainer);
  650. }
  651. // With FF/IE we can't split the stream into audio and video because FF
  652. // doesn't support media stream constructors. So, we need to get the
  653. // audio stream separately from the video stream using two distinct GUM
  654. // calls. Not very user friendly :-( but we don't have many other
  655. // options neither.
  656. //
  657. // Note that we pack those 2 streams in a single object and pass it to
  658. // the successCallback method.
  659. obtainDevices({
  660. devices: options.devices,
  661. streams: [],
  662. successCallback: successCallback,
  663. errorCallback: reject,
  664. deviceGUM: deviceGUM
  665. });
  666. } else {
  667. var hasDesktop = options.devices.indexOf('desktop') > -1;
  668. if (hasDesktop) {
  669. options.devices.splice(options.devices.indexOf("desktop"), 1);
  670. }
  671. options.resolution = options.resolution || '360';
  672. if(options.devices.length) {
  673. this.getUserMediaWithConstraints(
  674. options.devices,
  675. function (stream) {
  676. if((options.devices.indexOf("audio") !== -1 &&
  677. !stream.getAudioTracks().length) ||
  678. (options.devices.indexOf("video") !== -1 &&
  679. !stream.getVideoTracks().length))
  680. {
  681. self.stopMediaStream(stream);
  682. reject(JitsiTrackErrors.parseError(
  683. new Error("Unable to get the audio and " +
  684. "video tracks."),
  685. options.devices));
  686. return;
  687. }
  688. if(hasDesktop) {
  689. screenObtainer.obtainStream(
  690. function (desktopStream) {
  691. successCallback({audioVideo: stream,
  692. desktopStream: desktopStream});
  693. }, function (error) {
  694. self.stopMediaStream(stream);
  695. reject(
  696. JitsiTrackErrors.parseError(error,
  697. options.devices));
  698. });
  699. } else {
  700. successCallback({audioVideo: stream});
  701. }
  702. },
  703. function (error) {
  704. reject(JitsiTrackErrors.parseError(error,
  705. options.devices));
  706. },
  707. options);
  708. } else if (hasDesktop) {
  709. screenObtainer.obtainStream(
  710. function (stream) {
  711. successCallback({desktopStream: stream});
  712. }, function (error) {
  713. reject(
  714. JitsiTrackErrors.parseError(error,
  715. ["desktop"]));
  716. });
  717. }
  718. }
  719. }.bind(this));
  720. },
  721. addListener: function (eventType, listener) {
  722. eventEmitter.on(eventType, listener);
  723. },
  724. removeListener: function (eventType, listener) {
  725. eventEmitter.removeListener(eventType, listener);
  726. },
  727. getDeviceAvailability: function () {
  728. return devices;
  729. },
  730. isRTCReady: function () {
  731. return rtcReady;
  732. },
  733. /**
  734. * Checks if its possible to enumerate available cameras/micropones.
  735. * @returns {boolean} true if available, false otherwise.
  736. */
  737. isDeviceListAvailable: function () {
  738. var isEnumerateDevicesAvailable
  739. = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  740. if (isEnumerateDevicesAvailable) {
  741. return true;
  742. }
  743. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  744. },
  745. /**
  746. * Returns true if changing the camera / microphone device is supported and
  747. * false if not.
  748. */
  749. isDeviceChangeAvailable: function () {
  750. return RTCBrowserType.isChrome() ||
  751. RTCBrowserType.isFirefox() ||
  752. RTCBrowserType.isOpera() ||
  753. RTCBrowserType.isTemasysPluginUsed();
  754. },
  755. /**
  756. * A method to handle stopping of the stream.
  757. * One point to handle the differences in various implementations.
  758. * @param mediaStream MediaStream object to stop.
  759. */
  760. stopMediaStream: function (mediaStream) {
  761. mediaStream.getTracks().forEach(function (track) {
  762. // stop() not supported with IE
  763. if (!RTCBrowserType.isTemasysPluginUsed() && track.stop) {
  764. track.stop();
  765. }
  766. });
  767. // leave stop for implementation still using it
  768. if (mediaStream.stop) {
  769. mediaStream.stop();
  770. }
  771. // if we have done createObjectURL, lets clean it
  772. if (mediaStream.jitsiObjectURL) {
  773. webkitURL.revokeObjectURL(mediaStream.jitsiObjectURL);
  774. }
  775. },
  776. /**
  777. * Returns whether the desktop sharing is enabled or not.
  778. * @returns {boolean}
  779. */
  780. isDesktopSharingEnabled: function () {
  781. return screenObtainer.isSupported();
  782. }
  783. };
  784. module.exports = RTCUtils;