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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  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 JitsiMeetJSError = require("../../JitsiMeetJSErrors");
  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(JitsiMeetJSError.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. var self = this;
  357. if (RTCBrowserType.isFirefox()) {
  358. var FFversion = RTCBrowserType.getFirefoxVersion();
  359. if (FFversion >= 40) {
  360. this.peerconnection = mozRTCPeerConnection;
  361. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  362. this.enumerateDevices = wrapEnumerateDevices(
  363. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  364. );
  365. this.pc_constraints = {};
  366. this.attachMediaStream = function (element, stream) {
  367. // srcObject is being standardized and FF will eventually
  368. // support that unprefixed. FF also supports the
  369. // "element.src = URL.createObjectURL(...)" combo, but that
  370. // will be deprecated in favour of srcObject.
  371. //
  372. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  373. // https://github.com/webrtc/samples/issues/302
  374. if (!element[0])
  375. return;
  376. element[0].mozSrcObject = stream;
  377. element[0].play();
  378. };
  379. this.getStreamID = function (stream) {
  380. var id = stream.id;
  381. if (!id) {
  382. var tracks = stream.getVideoTracks();
  383. if (!tracks || tracks.length === 0) {
  384. tracks = stream.getAudioTracks();
  385. }
  386. id = tracks[0].id;
  387. }
  388. return SDPUtil.filter_special_chars(id);
  389. };
  390. this.getVideoSrc = function (element) {
  391. if (!element)
  392. return null;
  393. return element.mozSrcObject;
  394. };
  395. this.setVideoSrc = function (element, src) {
  396. if (element)
  397. element.mozSrcObject = src;
  398. };
  399. RTCSessionDescription = mozRTCSessionDescription;
  400. RTCIceCandidate = mozRTCIceCandidate;
  401. } else {
  402. logger.error(
  403. "Firefox version too old: " + FFversion + ". Required >= 40.");
  404. window.location.href = 'unsupported_browser.html';
  405. return;
  406. }
  407. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  408. this.peerconnection = webkitRTCPeerConnection;
  409. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  410. if (navigator.mediaDevices) {
  411. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  412. this.enumerateDevices = wrapEnumerateDevices(
  413. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  414. );
  415. } else {
  416. this.getUserMedia = getUserMedia;
  417. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  418. }
  419. this.attachMediaStream = function (element, stream) {
  420. element.attr('src', webkitURL.createObjectURL(stream));
  421. };
  422. this.getStreamID = function (stream) {
  423. // streams from FF endpoints have the characters '{' and '}'
  424. // that make jQuery choke.
  425. return SDPUtil.filter_special_chars(stream.id);
  426. };
  427. this.getVideoSrc = function (element) {
  428. if (!element)
  429. return null;
  430. return element.getAttribute("src");
  431. };
  432. this.setVideoSrc = function (element, src) {
  433. if (element)
  434. element.setAttribute("src", src);
  435. };
  436. // DTLS should now be enabled by default but..
  437. this.pc_constraints = {'optional': [
  438. {'DtlsSrtpKeyAgreement': 'true'}
  439. ]};
  440. if (options.useIPv6) {
  441. // https://code.google.com/p/webrtc/issues/detail?id=2828
  442. this.pc_constraints.optional.push({googIPv6: true});
  443. }
  444. if (RTCBrowserType.isAndroid()) {
  445. this.pc_constraints = {}; // disable DTLS on Android
  446. }
  447. if (!webkitMediaStream.prototype.getVideoTracks) {
  448. webkitMediaStream.prototype.getVideoTracks = function () {
  449. return this.videoTracks;
  450. };
  451. }
  452. if (!webkitMediaStream.prototype.getAudioTracks) {
  453. webkitMediaStream.prototype.getAudioTracks = function () {
  454. return this.audioTracks;
  455. };
  456. }
  457. }
  458. // Detect IE/Safari
  459. else if (RTCBrowserType.isTemasysPluginUsed()) {
  460. //AdapterJS.WebRTCPlugin.setLogLevel(
  461. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  462. AdapterJS.webRTCReady(function (isPlugin) {
  463. self.peerconnection = RTCPeerConnection;
  464. self.getUserMedia = window.getUserMedia;
  465. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  466. self.attachMediaStream = function (elSel, stream) {
  467. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  468. return;
  469. }
  470. attachMediaStream(elSel[0], stream);
  471. };
  472. self.getStreamID = function (stream) {
  473. var id = SDPUtil.filter_special_chars(stream.label);
  474. return id;
  475. };
  476. self.getVideoSrc = function (element) {
  477. if (!element) {
  478. logger.warn("Attempt to get video SRC of null element");
  479. return null;
  480. }
  481. var children = element.children;
  482. for (var i = 0; i !== children.length; ++i) {
  483. if (children[i].name === 'streamId') {
  484. return children[i].value;
  485. }
  486. }
  487. //logger.info(element.id + " SRC: " + src);
  488. return null;
  489. };
  490. self.setVideoSrc = function (element, src) {
  491. //logger.info("Set video src: ", element, src);
  492. if (!src) {
  493. logger.warn("Not attaching video stream, 'src' is null");
  494. return;
  495. }
  496. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  497. var stream = AdapterJS.WebRTCPlugin.plugin
  498. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  499. attachMediaStream(element, stream);
  500. };
  501. onReady(options, self.getUserMediaWithConstraints);
  502. });
  503. } else {
  504. try {
  505. logger.error('Browser does not appear to be WebRTC-capable');
  506. } catch (e) {
  507. }
  508. return;
  509. }
  510. // Call onReady() if Temasys plugin is not used
  511. if (!RTCBrowserType.isTemasysPluginUsed()) {
  512. onReady(options, self.getUserMediaWithConstraints);
  513. }
  514. },
  515. /**
  516. * @param {string[]} um required user media types
  517. * @param {function} success_callback
  518. * @param {Function} failure_callback
  519. * @param {Object} [options] optional parameters
  520. * @param {string} options.resolution
  521. * @param {number} options.bandwidth
  522. * @param {number} options.fps
  523. * @param {string} options.desktopStream
  524. * @param {string} options.cameraDeviceId
  525. * @param {string} options.micDeviceId
  526. **/
  527. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  528. options = options || {};
  529. resolution = options.resolution;
  530. var constraints = getConstraints(
  531. um, options);
  532. logger.info("Get media constraints", constraints);
  533. try {
  534. this.getUserMedia(constraints,
  535. function (stream) {
  536. logger.log('onUserMediaSuccess');
  537. setAvailableDevices(um, true);
  538. success_callback(stream);
  539. },
  540. function (error) {
  541. setAvailableDevices(um, false);
  542. logger.warn('Failed to get access to local media. Error ',
  543. error, constraints);
  544. if (failure_callback) {
  545. failure_callback(error, resolution);
  546. }
  547. });
  548. } catch (e) {
  549. logger.error('GUM failed: ', e);
  550. if (failure_callback) {
  551. failure_callback(e);
  552. }
  553. }
  554. },
  555. /**
  556. * Creates the local MediaStreams.
  557. * @param {Object} [options] optional parameters
  558. * @param {Array} options.devices the devices that will be requested
  559. * @param {string} options.resolution resolution constraints
  560. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  561. * type: "audio" or "video", videoType: "camera" or "desktop"}
  562. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  563. * @param {string} options.cameraDeviceId
  564. * @param {string} options.micDeviceId
  565. * @returns {*} Promise object that will receive the new JitsiTracks
  566. */
  567. obtainAudioAndVideoPermissions: function (options) {
  568. var self = this;
  569. options = options || {};
  570. return new Promise(function (resolve, reject) {
  571. var successCallback = function (stream) {
  572. resolve(handleLocalStream(stream, options.resolution));
  573. };
  574. options.devices = options.devices || ['audio', 'video'];
  575. if(!screenObtainer.isSupported()
  576. && options.devices.indexOf("desktop") !== -1){
  577. reject(new Error("Desktop sharing is not supported!"));
  578. }
  579. if (RTCBrowserType.isFirefox() ||
  580. RTCBrowserType.isTemasysPluginUsed()) {
  581. var GUM = function (device, s, e) {
  582. this.getUserMediaWithConstraints(device, s, e, options);
  583. }
  584. var deviceGUM = {
  585. "audio": GUM.bind(self, ["audio"]),
  586. "video": GUM.bind(self, ["video"]),
  587. "desktop": screenObtainer.obtainStream
  588. }
  589. // With FF/IE we can't split the stream into audio and video because FF
  590. // doesn't support media stream constructors. So, we need to get the
  591. // audio stream separately from the video stream using two distinct GUM
  592. // calls. Not very user friendly :-( but we don't have many other
  593. // options neither.
  594. //
  595. // Note that we pack those 2 streams in a single object and pass it to
  596. // the successCallback method.
  597. obtainDevices({
  598. devices: options.devices,
  599. successCallback: successCallback,
  600. errorCallback: reject,
  601. deviceGUM: deviceGUM
  602. });
  603. } else {
  604. var hasDesktop = false;
  605. if(hasDesktop = options.devices.indexOf("desktop") !== -1) {
  606. options.devices.splice(options.devices.indexOf("desktop"), 1);
  607. }
  608. options.resolution = options.resolution || '360';
  609. if(options.devices.length) {
  610. this.getUserMediaWithConstraints(
  611. options.devices,
  612. function (stream) {
  613. if(hasDesktop) {
  614. screenObtainer.obtainStream(
  615. function (desktopStream) {
  616. successCallback({audioVideo: stream,
  617. desktopStream: desktopStream});
  618. }, function (error) {
  619. reject(
  620. JitsiMeetJSError.parseError(error));
  621. });
  622. } else {
  623. successCallback({audioVideo: stream});
  624. }
  625. },
  626. function (error) {
  627. reject(JitsiMeetJSError.parseError(error));
  628. },
  629. options);
  630. } else if (hasDesktop) {
  631. screenObtainer.obtainStream(
  632. function (stream) {
  633. successCallback({desktopStream: stream});
  634. }, function (error) {
  635. reject(
  636. JitsiMeetJSError.parseError(error));
  637. });
  638. }
  639. }
  640. }.bind(this));
  641. },
  642. addListener: function (eventType, listener) {
  643. eventEmitter.on(eventType, listener);
  644. },
  645. removeListener: function (eventType, listener) {
  646. eventEmitter.removeListener(eventType, listener);
  647. },
  648. getDeviceAvailability: function () {
  649. return devices;
  650. },
  651. isRTCReady: function () {
  652. return rtcReady;
  653. },
  654. /**
  655. * Checks if its possible to enumerate available cameras/micropones.
  656. * @returns {boolean} true if available, false otherwise.
  657. */
  658. isDeviceListAvailable: function () {
  659. var isEnumerateDevicesAvailable = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  660. if (isEnumerateDevicesAvailable) {
  661. return true;
  662. }
  663. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  664. },
  665. /**
  666. * A method to handle stopping of the stream.
  667. * One point to handle the differences in various implementations.
  668. * @param mediaStream MediaStream object to stop.
  669. */
  670. stopMediaStream: function (mediaStream) {
  671. mediaStream.getTracks().forEach(function (track) {
  672. // stop() not supported with IE
  673. if (track.stop) {
  674. track.stop();
  675. }
  676. });
  677. // leave stop for implementation still using it
  678. if (mediaStream.stop) {
  679. mediaStream.stop();
  680. }
  681. }
  682. };
  683. module.exports = RTCUtils;