您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

RTCUtils.js 32KB

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