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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  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. track: desktopStream.getVideoTracks()[0],
  373. mediaType: MediaType.VIDEO,
  374. videoType: VideoType.DESKTOP
  375. });
  376. if(audioStream)
  377. res.push({
  378. stream: audioStream,
  379. track: audioStream.getAudioTracks()[0],
  380. mediaType: MediaType.AUDIO,
  381. videoType: null
  382. });
  383. if(videoStream)
  384. res.push({
  385. stream: videoStream,
  386. track: videoStream.getVideoTracks()[0],
  387. mediaType: MediaType.VIDEO,
  388. videoType: VideoType.CAMERA,
  389. resolution: resolution
  390. });
  391. return res;
  392. }
  393. //Options parameter is to pass config options. Currently uses only "useIPv6".
  394. var RTCUtils = {
  395. init: function (options) {
  396. return new Promise(function(resolve, reject) {
  397. if (RTCBrowserType.isFirefox()) {
  398. var FFversion = RTCBrowserType.getFirefoxVersion();
  399. if (FFversion < 40) {
  400. logger.error(
  401. "Firefox version too old: " + FFversion +
  402. ". Required >= 40.");
  403. reject(new Error("Firefox version too old: " + FFversion +
  404. ". Required >= 40."));
  405. return;
  406. }
  407. this.peerconnection = mozRTCPeerConnection;
  408. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  409. this.enumerateDevices = wrapEnumerateDevices(
  410. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  411. );
  412. this.pc_constraints = {};
  413. this.attachMediaStream = function (element, stream) {
  414. // srcObject is being standardized and FF will eventually
  415. // support that unprefixed. FF also supports the
  416. // "element.src = URL.createObjectURL(...)" combo, but that
  417. // will be deprecated in favour of srcObject.
  418. //
  419. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  420. // https://github.com/webrtc/samples/issues/302
  421. if (!element)
  422. return;
  423. element.mozSrcObject = stream;
  424. element.play();
  425. return element;
  426. };
  427. this.getStreamID = function (stream) {
  428. var id = stream.id;
  429. if (!id) {
  430. var tracks = stream.getVideoTracks();
  431. if (!tracks || tracks.length === 0) {
  432. tracks = stream.getAudioTracks();
  433. }
  434. id = tracks[0].id;
  435. }
  436. return SDPUtil.filter_special_chars(id);
  437. };
  438. this.getVideoSrc = function (element) {
  439. if (!element)
  440. return null;
  441. return element.mozSrcObject;
  442. };
  443. this.setVideoSrc = function (element, src) {
  444. if (element)
  445. element.mozSrcObject = src;
  446. };
  447. RTCSessionDescription = mozRTCSessionDescription;
  448. RTCIceCandidate = mozRTCIceCandidate;
  449. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera() || RTCBrowserType.isNWJS()) {
  450. this.peerconnection = webkitRTCPeerConnection;
  451. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  452. if (navigator.mediaDevices) {
  453. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  454. this.enumerateDevices = wrapEnumerateDevices(
  455. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  456. );
  457. } else {
  458. this.getUserMedia = getUserMedia;
  459. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  460. }
  461. this.attachMediaStream = function (element, stream) {
  462. // saves the created url for the stream, so we can reuse it
  463. // and not keep creating urls
  464. if (!stream.jitsiObjectURL) {
  465. stream.jitsiObjectURL
  466. = webkitURL.createObjectURL(stream);
  467. }
  468. element.src = stream.jitsiObjectURL;
  469. return element;
  470. };
  471. this.getStreamID = function (stream) {
  472. // streams from FF endpoints have the characters '{' and '}'
  473. // that make jQuery choke.
  474. return SDPUtil.filter_special_chars(stream.id);
  475. };
  476. this.getVideoSrc = function (element) {
  477. if (!element)
  478. return null;
  479. return element.getAttribute("src");
  480. };
  481. this.setVideoSrc = function (element, src) {
  482. if (!src) {
  483. src = '';
  484. }
  485. if (element)
  486. element.setAttribute("src", src);
  487. };
  488. // DTLS should now be enabled by default but..
  489. this.pc_constraints = {'optional': [
  490. {'DtlsSrtpKeyAgreement': 'true'}
  491. ]};
  492. if (options.useIPv6) {
  493. // https://code.google.com/p/webrtc/issues/detail?id=2828
  494. this.pc_constraints.optional.push({googIPv6: true});
  495. }
  496. if (RTCBrowserType.isAndroid()) {
  497. this.pc_constraints = {}; // disable DTLS on Android
  498. }
  499. if (!webkitMediaStream.prototype.getVideoTracks) {
  500. webkitMediaStream.prototype.getVideoTracks = function () {
  501. return this.videoTracks;
  502. };
  503. }
  504. if (!webkitMediaStream.prototype.getAudioTracks) {
  505. webkitMediaStream.prototype.getAudioTracks = function () {
  506. return this.audioTracks;
  507. };
  508. }
  509. }
  510. // Detect IE/Safari
  511. else if (RTCBrowserType.isTemasysPluginUsed()) {
  512. //AdapterJS.WebRTCPlugin.setLogLevel(
  513. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  514. var self = this;
  515. AdapterJS.webRTCReady(function (isPlugin) {
  516. self.peerconnection = RTCPeerConnection;
  517. self.getUserMedia = window.getUserMedia;
  518. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  519. self.attachMediaStream = function (element, stream) {
  520. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  521. return;
  522. }
  523. var isVideoStream = !!stream.getVideoTracks().length;
  524. if (isVideoStream && !$(element).is(':visible')) {
  525. throw new Error('video element must be visible to attach video stream');
  526. }
  527. return attachMediaStream(element, stream);
  528. };
  529. self.getStreamID = function (stream) {
  530. var id = SDPUtil.filter_special_chars(stream.label);
  531. return id;
  532. };
  533. self.getVideoSrc = function (element) {
  534. if (!element) {
  535. logger.warn("Attempt to get video SRC of null element");
  536. return null;
  537. }
  538. var children = element.children;
  539. for (var i = 0; i !== children.length; ++i) {
  540. if (children[i].name === 'streamId') {
  541. return children[i].value;
  542. }
  543. }
  544. //logger.info(element.id + " SRC: " + src);
  545. return null;
  546. };
  547. self.setVideoSrc = function (element, src) {
  548. //logger.info("Set video src: ", element, src);
  549. if (!src) {
  550. attachMediaStream(element, null);
  551. } else {
  552. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  553. var stream
  554. = AdapterJS.WebRTCPlugin.plugin
  555. .getStreamWithId(
  556. AdapterJS.WebRTCPlugin.pageId, src);
  557. attachMediaStream(element, stream);
  558. }
  559. };
  560. onReady(options, self.getUserMediaWithConstraints);
  561. resolve();
  562. });
  563. } else {
  564. try {
  565. logger.error('Browser does not appear to be WebRTC-capable');
  566. } catch (e) {
  567. }
  568. reject('Browser does not appear to be WebRTC-capable');
  569. return;
  570. }
  571. // Call onReady() if Temasys plugin is not used
  572. if (!RTCBrowserType.isTemasysPluginUsed()) {
  573. onReady(options, this.getUserMediaWithConstraints);
  574. resolve();
  575. }
  576. }.bind(this));
  577. },
  578. /**
  579. * @param {string[]} um required user media types
  580. * @param {function} success_callback
  581. * @param {Function} failure_callback
  582. * @param {Object} [options] optional parameters
  583. * @param {string} options.resolution
  584. * @param {number} options.bandwidth
  585. * @param {number} options.fps
  586. * @param {string} options.desktopStream
  587. * @param {string} options.cameraDeviceId
  588. * @param {string} options.micDeviceId
  589. **/
  590. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  591. options = options || {};
  592. var resolution = options.resolution;
  593. var constraints = getConstraints(um, options);
  594. logger.info("Get media constraints", constraints);
  595. try {
  596. this.getUserMedia(constraints,
  597. function (stream) {
  598. logger.log('onUserMediaSuccess');
  599. setAvailableDevices(um, true);
  600. success_callback(stream);
  601. },
  602. function (error) {
  603. setAvailableDevices(um, false);
  604. logger.warn('Failed to get access to local media. Error ',
  605. error, constraints);
  606. if (failure_callback) {
  607. failure_callback(error, resolution);
  608. }
  609. });
  610. } catch (e) {
  611. logger.error('GUM failed: ', e);
  612. if (failure_callback) {
  613. failure_callback(e);
  614. }
  615. }
  616. },
  617. /**
  618. * Creates the local MediaStreams.
  619. * @param {Object} [options] optional parameters
  620. * @param {Array} options.devices the devices that will be requested
  621. * @param {string} options.resolution resolution constraints
  622. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  623. * type: "audio" or "video", videoType: "camera" or "desktop"}
  624. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  625. * @param {string} options.cameraDeviceId
  626. * @param {string} options.micDeviceId
  627. * @returns {*} Promise object that will receive the new JitsiTracks
  628. */
  629. obtainAudioAndVideoPermissions: function (options) {
  630. var self = this;
  631. options = options || {};
  632. return new Promise(function (resolve, reject) {
  633. var successCallback = function (stream) {
  634. resolve(handleLocalStream(stream, options.resolution));
  635. };
  636. options.devices = options.devices || ['audio', 'video'];
  637. if(!screenObtainer.isSupported()
  638. && options.devices.indexOf("desktop") !== -1){
  639. reject(new Error("Desktop sharing is not supported!"));
  640. }
  641. if (RTCBrowserType.isFirefox() ||
  642. RTCBrowserType.isTemasysPluginUsed()) {
  643. var GUM = function (device, s, e) {
  644. this.getUserMediaWithConstraints(device, s, e, options);
  645. };
  646. var deviceGUM = {
  647. "audio": GUM.bind(self, ["audio"]),
  648. "video": GUM.bind(self, ["video"])
  649. };
  650. if(screenObtainer.isSupported()){
  651. deviceGUM["desktop"] = screenObtainer.obtainStream.bind(
  652. screenObtainer);
  653. }
  654. // With FF/IE we can't split the stream into audio and video because FF
  655. // doesn't support media stream constructors. So, we need to get the
  656. // audio stream separately from the video stream using two distinct GUM
  657. // calls. Not very user friendly :-( but we don't have many other
  658. // options neither.
  659. //
  660. // Note that we pack those 2 streams in a single object and pass it to
  661. // the successCallback method.
  662. obtainDevices({
  663. devices: options.devices,
  664. streams: [],
  665. successCallback: successCallback,
  666. errorCallback: reject,
  667. deviceGUM: deviceGUM
  668. });
  669. } else {
  670. var hasDesktop = options.devices.indexOf('desktop') > -1;
  671. if (hasDesktop) {
  672. options.devices.splice(options.devices.indexOf("desktop"), 1);
  673. }
  674. options.resolution = options.resolution || '360';
  675. if(options.devices.length) {
  676. this.getUserMediaWithConstraints(
  677. options.devices,
  678. function (stream) {
  679. if((options.devices.indexOf("audio") !== -1 &&
  680. !stream.getAudioTracks().length) ||
  681. (options.devices.indexOf("video") !== -1 &&
  682. !stream.getVideoTracks().length))
  683. {
  684. self.stopMediaStream(stream);
  685. reject(JitsiTrackErrors.parseError(
  686. new Error("Unable to get the audio and " +
  687. "video tracks."),
  688. options.devices));
  689. return;
  690. }
  691. if(hasDesktop) {
  692. screenObtainer.obtainStream(
  693. function (desktopStream) {
  694. successCallback({audioVideo: stream,
  695. desktopStream: desktopStream});
  696. }, function (error) {
  697. self.stopMediaStream(stream);
  698. reject(
  699. JitsiTrackErrors.parseError(error,
  700. options.devices));
  701. });
  702. } else {
  703. successCallback({audioVideo: stream});
  704. }
  705. },
  706. function (error) {
  707. reject(JitsiTrackErrors.parseError(error,
  708. options.devices));
  709. },
  710. options);
  711. } else if (hasDesktop) {
  712. screenObtainer.obtainStream(
  713. function (stream) {
  714. successCallback({desktopStream: stream});
  715. }, function (error) {
  716. reject(
  717. JitsiTrackErrors.parseError(error,
  718. ["desktop"]));
  719. });
  720. }
  721. }
  722. }.bind(this));
  723. },
  724. addListener: function (eventType, listener) {
  725. eventEmitter.on(eventType, listener);
  726. },
  727. removeListener: function (eventType, listener) {
  728. eventEmitter.removeListener(eventType, listener);
  729. },
  730. getDeviceAvailability: function () {
  731. return devices;
  732. },
  733. isRTCReady: function () {
  734. return rtcReady;
  735. },
  736. /**
  737. * Checks if its possible to enumerate available cameras/micropones.
  738. * @returns {boolean} true if available, false otherwise.
  739. */
  740. isDeviceListAvailable: function () {
  741. var isEnumerateDevicesAvailable
  742. = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  743. if (isEnumerateDevicesAvailable) {
  744. return true;
  745. }
  746. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  747. },
  748. /**
  749. * Returns true if changing the camera / microphone device is supported and
  750. * false if not.
  751. */
  752. isDeviceChangeAvailable: function () {
  753. return RTCBrowserType.isChrome() ||
  754. RTCBrowserType.isFirefox() ||
  755. RTCBrowserType.isOpera() ||
  756. RTCBrowserType.isTemasysPluginUsed();
  757. },
  758. /**
  759. * A method to handle stopping of the stream.
  760. * One point to handle the differences in various implementations.
  761. * @param mediaStream MediaStream object to stop.
  762. */
  763. stopMediaStream: function (mediaStream) {
  764. mediaStream.getTracks().forEach(function (track) {
  765. // stop() not supported with IE
  766. if (!RTCBrowserType.isTemasysPluginUsed() && track.stop) {
  767. track.stop();
  768. }
  769. });
  770. // leave stop for implementation still using it
  771. if (mediaStream.stop) {
  772. mediaStream.stop();
  773. }
  774. // if we have done createObjectURL, lets clean it
  775. if (mediaStream.jitsiObjectURL) {
  776. webkitURL.revokeObjectURL(mediaStream.jitsiObjectURL);
  777. }
  778. },
  779. /**
  780. * Returns whether the desktop sharing is enabled or not.
  781. * @returns {boolean}
  782. */
  783. isDesktopSharingEnabled: function () {
  784. return screenObtainer.isSupported();
  785. }
  786. };
  787. module.exports = RTCUtils;