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

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