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

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