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