modified lib-jitsi-meet dev repo
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

RTCUtils.js 38KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  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 AVAILABLE_DEVICES_POLL_INTERVAL_TIME = 3000; // ms
  20. var devices = {
  21. audio: true,
  22. video: true
  23. };
  24. var audioOuputDeviceId = ''; // default device
  25. var featureDetectionAudioEl = document.createElement('audio');
  26. var isAudioOutputDeviceChangeAvailable =
  27. typeof featureDetectionAudioEl.setSinkId !== 'undefined';
  28. var currentlyAvailableMediaDevices = [];
  29. // TODO: currently no browser supports 'devicechange' event even in nightly
  30. // builds so no feature/browser detection is used at all. However in future this
  31. // should be changed to some expression. Progress on 'devicechange' event
  32. // implementation for Chrome/Opera/NWJS can be tracked at
  33. // https://bugs.chromium.org/p/chromium/issues/detail?id=388648, for Firefox -
  34. // at https://bugzilla.mozilla.org/show_bug.cgi?id=1152383. More information on
  35. // 'devicechange' event can be found in spec -
  36. // http://w3c.github.io/mediacapture-main/#event-mediadevices-devicechange
  37. // TODO: check MS Edge
  38. var isDeviceChangeEventSupported = false;
  39. var rtcReady = false;
  40. function setResolutionConstraints(constraints, resolution) {
  41. var isAndroid = RTCBrowserType.isAndroid();
  42. if (Resolutions[resolution]) {
  43. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  44. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  45. }
  46. else if (isAndroid) {
  47. // FIXME can't remember if the purpose of this was to always request
  48. // low resolution on Android ? if yes it should be moved up front
  49. constraints.video.mandatory.minWidth = 320;
  50. constraints.video.mandatory.minHeight = 180;
  51. constraints.video.mandatory.maxFrameRate = 15;
  52. }
  53. if (constraints.video.mandatory.minWidth)
  54. constraints.video.mandatory.maxWidth =
  55. constraints.video.mandatory.minWidth;
  56. if (constraints.video.mandatory.minHeight)
  57. constraints.video.mandatory.maxHeight =
  58. constraints.video.mandatory.minHeight;
  59. }
  60. /**
  61. * @param {string[]} um required user media types
  62. *
  63. * @param {Object} [options={}] optional parameters
  64. * @param {string} options.resolution
  65. * @param {number} options.bandwidth
  66. * @param {number} options.fps
  67. * @param {string} options.desktopStream
  68. * @param {string} options.cameraDeviceId
  69. * @param {string} options.micDeviceId
  70. * @param {bool} firefox_fake_device
  71. */
  72. function getConstraints(um, options) {
  73. var constraints = {audio: false, video: false};
  74. if (um.indexOf('video') >= 0) {
  75. // same behaviour as true
  76. constraints.video = { mandatory: {}, optional: [] };
  77. if (options.cameraDeviceId) {
  78. // new style of settings device id (FF only)
  79. constraints.video.deviceId = options.cameraDeviceId;
  80. // old style
  81. constraints.video.optional.push({
  82. sourceId: options.cameraDeviceId
  83. });
  84. }
  85. constraints.video.optional.push({ googLeakyBucket: true });
  86. setResolutionConstraints(constraints, options.resolution);
  87. }
  88. if (um.indexOf('audio') >= 0) {
  89. if (!RTCBrowserType.isFirefox()) {
  90. // same behaviour as true
  91. constraints.audio = { mandatory: {}, optional: []};
  92. if (options.micDeviceId) {
  93. // new style of settings device id (FF only)
  94. constraints.audio.deviceId = options.micDeviceId;
  95. // old style
  96. constraints.audio.optional.push({
  97. sourceId: options.micDeviceId
  98. });
  99. }
  100. // if it is good enough for hangouts...
  101. constraints.audio.optional.push(
  102. {googEchoCancellation: true},
  103. {googAutoGainControl: true},
  104. {googNoiseSupression: true},
  105. {googHighpassFilter: true},
  106. {googNoisesuppression2: true},
  107. {googEchoCancellation2: true},
  108. {googAutoGainControl2: true}
  109. );
  110. } else {
  111. if (options.micDeviceId) {
  112. constraints.audio = {
  113. mandatory: {},
  114. deviceId: options.micDeviceId, // new style
  115. optional: [{
  116. sourceId: options.micDeviceId // old style
  117. }]};
  118. } else {
  119. constraints.audio = true;
  120. }
  121. }
  122. }
  123. if (um.indexOf('screen') >= 0) {
  124. if (RTCBrowserType.isChrome()) {
  125. constraints.video = {
  126. mandatory: {
  127. chromeMediaSource: "screen",
  128. googLeakyBucket: true,
  129. maxWidth: window.screen.width,
  130. maxHeight: window.screen.height,
  131. maxFrameRate: 3
  132. },
  133. optional: []
  134. };
  135. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  136. constraints.video = {
  137. optional: [
  138. {
  139. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  140. }
  141. ]
  142. };
  143. } else if (RTCBrowserType.isFirefox()) {
  144. constraints.video = {
  145. mozMediaSource: "window",
  146. mediaSource: "window"
  147. };
  148. } else {
  149. logger.error(
  150. "'screen' WebRTC media source is supported only in Chrome" +
  151. " and with Temasys plugin");
  152. }
  153. }
  154. if (um.indexOf('desktop') >= 0) {
  155. constraints.video = {
  156. mandatory: {
  157. chromeMediaSource: "desktop",
  158. chromeMediaSourceId: options.desktopStream,
  159. googLeakyBucket: true,
  160. maxWidth: window.screen.width,
  161. maxHeight: window.screen.height,
  162. maxFrameRate: 3
  163. },
  164. optional: []
  165. };
  166. }
  167. if (options.bandwidth) {
  168. if (!constraints.video) {
  169. //same behaviour as true
  170. constraints.video = {mandatory: {}, optional: []};
  171. }
  172. constraints.video.optional.push({bandwidth: options.bandwidth});
  173. }
  174. if(options.minFps || options.maxFps || options.fps) {
  175. // for some cameras it might be necessary to request 30fps
  176. // so they choose 30fps mjpg over 10fps yuy2
  177. if (!constraints.video) {
  178. // same behaviour as true;
  179. constraints.video = {mandatory: {}, optional: []};
  180. }
  181. if(options.minFps || options.fps) {
  182. options.minFps = options.minFps || options.fps; //Fall back to options.fps for backwards compatibility
  183. constraints.video.mandatory.minFrameRate = options.minFps;
  184. }
  185. if(options.maxFps) {
  186. constraints.video.mandatory.maxFrameRate = options.maxFps;
  187. }
  188. }
  189. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  190. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  191. // this later can be a problem with some of the tests
  192. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  193. {
  194. // seems to be fixed now, removing this experimental fix, as having
  195. // multiple audio tracks brake the tests
  196. //constraints.audio = true;
  197. constraints.fake = true;
  198. }
  199. return constraints;
  200. }
  201. function setAvailableDevices(um, available) {
  202. if (um.indexOf("video") != -1) {
  203. devices.video = available;
  204. }
  205. if (um.indexOf("audio") != -1) {
  206. devices.audio = available;
  207. }
  208. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  209. }
  210. /**
  211. * Checks if new list of available media devices differs from previous one.
  212. * @param {MediaDeviceInfo[]} newDevices - list of new devices.
  213. * @returns {boolean} - true if list is different, false otherwise.
  214. */
  215. function compareAvailableMediaDevices(newDevices) {
  216. if (newDevices.length !== currentlyAvailableMediaDevices.length) {
  217. return true;
  218. }
  219. return newDevices.map(mediaDeviceInfoToJSON).sort().join('') !==
  220. currentlyAvailableMediaDevices.map(mediaDeviceInfoToJSON).sort().join('');
  221. function mediaDeviceInfoToJSON(info) {
  222. return JSON.stringify({
  223. kind: info.kind,
  224. deviceId: info.deviceId,
  225. groupId: info.groupId,
  226. label: info.label,
  227. facing: info.facing
  228. });
  229. }
  230. }
  231. /**
  232. * Periodically polls enumerateDevices() method to check if list of media
  233. * devices has changed. This is temporary workaround until 'devicechange' event
  234. * will be supported by browsers.
  235. */
  236. function pollForAvailableMediaDevices() {
  237. RTCUtils.enumerateDevices(function (devices) {
  238. if (compareAvailableMediaDevices(devices)) {
  239. onMediaDevicesListChanged(devices);
  240. }
  241. window.setTimeout(pollForAvailableMediaDevices,
  242. AVAILABLE_DEVICES_POLL_INTERVAL_TIME);
  243. });
  244. }
  245. /**
  246. * Event handler for the 'devicechange' event.
  247. * @param {MediaDeviceInfo[]} devices - list of media devices.
  248. * @emits RTCEvents.DEVICE_LIST_CHANGED
  249. */
  250. function onMediaDevicesListChanged(devices) {
  251. currentlyAvailableMediaDevices = devices;
  252. eventEmitter.emit(RTCEvents.DEVICE_LIST_CHANGED, devices);
  253. logger.info('list of media devices has changed:', devices);
  254. }
  255. // In case of IE we continue from 'onReady' callback
  256. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  257. // once it is initialized.
  258. function onReady (options, GUM) {
  259. rtcReady = true;
  260. eventEmitter.emit(RTCEvents.RTC_READY, true);
  261. screenObtainer.init(options, GUM);
  262. if (isDeviceChangeEventSupported && RTCUtils.isDeviceListAvailable()) {
  263. navigator.mediaDevices.addEventListener('devicechange', function () {
  264. RTCUtils.enumerateDevices(onMediaDevicesListChanged);
  265. });
  266. } else if (RTCUtils.isDeviceListAvailable()) {
  267. pollForAvailableMediaDevices();
  268. }
  269. }
  270. /**
  271. * Apply function with arguments if function exists.
  272. * Do nothing if function not provided.
  273. * @param {function} [fn] function to apply
  274. * @param {Array} [args=[]] arguments for function
  275. */
  276. function maybeApply(fn, args) {
  277. if (fn) {
  278. fn.apply(null, args || []);
  279. }
  280. }
  281. var getUserMediaStatus = {
  282. initialized: false,
  283. callbacks: []
  284. };
  285. /**
  286. * Wrap `getUserMedia` to allow others to know if it was executed at least
  287. * once or not. Wrapper function uses `getUserMediaStatus` object.
  288. * @param {Function} getUserMedia native function
  289. * @returns {Function} wrapped function
  290. */
  291. function wrapGetUserMedia(getUserMedia) {
  292. return function (constraints, successCallback, errorCallback) {
  293. getUserMedia(constraints, function (stream) {
  294. maybeApply(successCallback, [stream]);
  295. if (!getUserMediaStatus.initialized) {
  296. getUserMediaStatus.initialized = true;
  297. getUserMediaStatus.callbacks.forEach(function (callback) {
  298. callback();
  299. });
  300. getUserMediaStatus.callbacks.length = 0;
  301. }
  302. }, function (error) {
  303. maybeApply(errorCallback, [error]);
  304. });
  305. };
  306. }
  307. /**
  308. * Create stub device which equals to auto selected device.
  309. * @param {string} kind if that should be `audio` or `video` device
  310. * @returns {Object} stub device description in `enumerateDevices` format
  311. */
  312. function createAutoDeviceInfo(kind) {
  313. return {
  314. facing: null,
  315. label: 'Auto',
  316. kind: kind,
  317. deviceId: '',
  318. groupId: ''
  319. };
  320. }
  321. /**
  322. * Execute function after getUserMedia was executed at least once.
  323. * @param {Function} callback function to execute after getUserMedia
  324. */
  325. function afterUserMediaInitialized(callback) {
  326. if (getUserMediaStatus.initialized) {
  327. callback();
  328. } else {
  329. getUserMediaStatus.callbacks.push(callback);
  330. }
  331. }
  332. /**
  333. * Wrapper function which makes enumerateDevices to wait
  334. * until someone executes getUserMedia first time.
  335. * @param {Function} enumerateDevices native function
  336. * @returns {Funtion} wrapped function
  337. */
  338. function wrapEnumerateDevices(enumerateDevices) {
  339. return function (callback) {
  340. // enumerate devices only after initial getUserMedia
  341. afterUserMediaInitialized(function () {
  342. enumerateDevices().then(function (devices) {
  343. //add auto devices
  344. devices.unshift(
  345. createAutoDeviceInfo('audioinput'),
  346. createAutoDeviceInfo('videoinput'),
  347. createAutoDeviceInfo('audiooutput')
  348. );
  349. callback(devices);
  350. }, function (err) {
  351. console.error('cannot enumerate devices: ', err);
  352. // return only auto devices
  353. callback([
  354. createAutoDeviceInfo('audioinput'),
  355. createAutoDeviceInfo('videoinput'),
  356. createAutoDeviceInfo('audiooutput')
  357. ]);
  358. });
  359. });
  360. };
  361. }
  362. /**
  363. * Use old MediaStreamTrack to get devices list and
  364. * convert it to enumerateDevices format.
  365. * @param {Function} callback function to call when received devices list.
  366. */
  367. function enumerateDevicesThroughMediaStreamTrack (callback) {
  368. MediaStreamTrack.getSources(function (sources) {
  369. var devices = sources.map(function (source) {
  370. var kind = (source.kind || '').toLowerCase();
  371. return {
  372. facing: source.facing || null,
  373. label: source.label,
  374. // theoretically deprecated MediaStreamTrack.getSources should
  375. // not return 'audiooutput' devices but let's handle it in any
  376. // case
  377. kind: kind
  378. ? (kind === 'audiooutput' ? kind : kind + 'input')
  379. : null,
  380. deviceId: source.id,
  381. groupId: source.groupId || null
  382. };
  383. });
  384. //add auto devices
  385. devices.unshift(
  386. createAutoDeviceInfo('audioinput'),
  387. createAutoDeviceInfo('videoinput'),
  388. createAutoDeviceInfo('audiooutput')
  389. );
  390. callback(devices);
  391. });
  392. }
  393. function obtainDevices(options) {
  394. if(!options.devices || options.devices.length === 0) {
  395. return options.successCallback(options.streams || {});
  396. }
  397. var device = options.devices.splice(0, 1);
  398. var devices = [];
  399. devices.push(device);
  400. options.deviceGUM[device](function (stream) {
  401. options.streams = options.streams || {};
  402. options.streams[device] = stream;
  403. obtainDevices(options);
  404. },
  405. function (error) {
  406. Object.keys(options.streams).forEach(function(device) {
  407. RTCUtils.stopMediaStream(options.streams[device]);
  408. });
  409. logger.error(
  410. "failed to obtain " + device + " stream - stop", error);
  411. options.errorCallback(JitsiTrackErrors.parseError(error, devices));
  412. });
  413. }
  414. /**
  415. * Handles the newly created Media Streams.
  416. * @param streams the new Media Streams
  417. * @param resolution the resolution of the video streams
  418. * @returns {*[]} object that describes the new streams
  419. */
  420. function handleLocalStream(streams, resolution) {
  421. var audioStream, videoStream, desktopStream, res = [];
  422. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  423. // an object with two properties: audioStream, videoStream.
  424. if (window.webkitMediaStream) {
  425. var audioVideo = streams.audioVideo;
  426. if (audioVideo) {
  427. var audioTracks = audioVideo.getAudioTracks();
  428. if (audioTracks.length) {
  429. audioStream = new webkitMediaStream();
  430. for (var i = 0; i < audioTracks.length; i++) {
  431. audioStream.addTrack(audioTracks[i]);
  432. }
  433. }
  434. var videoTracks = audioVideo.getVideoTracks();
  435. if (videoTracks.length) {
  436. videoStream = new webkitMediaStream();
  437. for (var j = 0; j < videoTracks.length; j++) {
  438. videoStream.addTrack(videoTracks[j]);
  439. }
  440. }
  441. }
  442. // FIXME Checking streams here is unnecessary because there's
  443. // streams.audioVideo above.
  444. if (streams)
  445. desktopStream = streams.desktopStream;
  446. }
  447. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  448. if (streams) {
  449. audioStream = streams.audio;
  450. videoStream = streams.video;
  451. desktopStream = streams.desktop;
  452. }
  453. }
  454. if (desktopStream)
  455. res.push({
  456. stream: desktopStream,
  457. track: desktopStream.getVideoTracks()[0],
  458. mediaType: MediaType.VIDEO,
  459. videoType: VideoType.DESKTOP
  460. });
  461. if(audioStream)
  462. res.push({
  463. stream: audioStream,
  464. track: audioStream.getAudioTracks()[0],
  465. mediaType: MediaType.AUDIO,
  466. videoType: null
  467. });
  468. if(videoStream)
  469. res.push({
  470. stream: videoStream,
  471. track: videoStream.getVideoTracks()[0],
  472. mediaType: MediaType.VIDEO,
  473. videoType: VideoType.CAMERA,
  474. resolution: resolution
  475. });
  476. return res;
  477. }
  478. /**
  479. * Wraps original attachMediaStream function to set current audio output device
  480. * if this is supported.
  481. * @param {Function} origAttachMediaStream
  482. * @returns {Function}
  483. */
  484. function wrapAttachMediaStream(origAttachMediaStream) {
  485. return function(element, stream) {
  486. var res = origAttachMediaStream.apply(RTCUtils, arguments);
  487. if (RTCUtils.isDeviceChangeAvailable('output') &&
  488. stream.getAudioTracks && stream.getAudioTracks().length) {
  489. element.setSinkId(RTCUtils.getAudioOutputDevice())
  490. .catch(function (ex) {
  491. logger.error('Failed to set audio output on element',
  492. element, ex);
  493. });
  494. }
  495. return res;
  496. }
  497. }
  498. //Options parameter is to pass config options. Currently uses only "useIPv6".
  499. var RTCUtils = {
  500. init: function (options) {
  501. return new Promise(function(resolve, reject) {
  502. if (RTCBrowserType.isFirefox()) {
  503. var FFversion = RTCBrowserType.getFirefoxVersion();
  504. if (FFversion < 40) {
  505. logger.error(
  506. "Firefox version too old: " + FFversion +
  507. ". Required >= 40.");
  508. reject(new Error("Firefox version too old: " + FFversion +
  509. ". Required >= 40."));
  510. return;
  511. }
  512. this.peerconnection = mozRTCPeerConnection;
  513. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  514. this.enumerateDevices = wrapEnumerateDevices(
  515. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  516. );
  517. this.pc_constraints = {};
  518. this.attachMediaStream = wrapAttachMediaStream(function (element, stream) {
  519. // srcObject is being standardized and FF will eventually
  520. // support that unprefixed. FF also supports the
  521. // "element.src = URL.createObjectURL(...)" combo, but that
  522. // will be deprecated in favour of srcObject.
  523. //
  524. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  525. // https://github.com/webrtc/samples/issues/302
  526. if (!element)
  527. return;
  528. element.mozSrcObject = stream;
  529. element.play();
  530. return element;
  531. });
  532. this.getStreamID = function (stream) {
  533. var id = stream.id;
  534. if (!id) {
  535. var tracks = stream.getVideoTracks();
  536. if (!tracks || tracks.length === 0) {
  537. tracks = stream.getAudioTracks();
  538. }
  539. id = tracks[0].id;
  540. }
  541. return SDPUtil.filter_special_chars(id);
  542. };
  543. this.getVideoSrc = function (element) {
  544. if (!element)
  545. return null;
  546. return element.mozSrcObject;
  547. };
  548. this.setVideoSrc = function (element, src) {
  549. if (element)
  550. element.mozSrcObject = src;
  551. };
  552. RTCSessionDescription = mozRTCSessionDescription;
  553. RTCIceCandidate = mozRTCIceCandidate;
  554. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera() || RTCBrowserType.isNWJS()) {
  555. this.peerconnection = webkitRTCPeerConnection;
  556. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  557. if (navigator.mediaDevices) {
  558. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  559. this.enumerateDevices = wrapEnumerateDevices(
  560. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  561. );
  562. } else {
  563. this.getUserMedia = getUserMedia;
  564. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  565. }
  566. this.attachMediaStream = wrapAttachMediaStream(function (element, stream) {
  567. // saves the created url for the stream, so we can reuse it
  568. // and not keep creating urls
  569. if (!stream.jitsiObjectURL) {
  570. stream.jitsiObjectURL
  571. = webkitURL.createObjectURL(stream);
  572. }
  573. element.src = stream.jitsiObjectURL;
  574. return element;
  575. });
  576. this.getStreamID = function (stream) {
  577. // Streams from FF endpoints have the characters '{' and '}'
  578. // that make jQuery choke.
  579. return SDPUtil.filter_special_chars(stream.id);
  580. };
  581. this.getVideoSrc = function (element) {
  582. if (!element)
  583. return null;
  584. return element.getAttribute("src");
  585. };
  586. this.setVideoSrc = function (element, src) {
  587. if (!src) {
  588. src = '';
  589. }
  590. if (element)
  591. element.setAttribute("src", src);
  592. };
  593. // DTLS should now be enabled by default but..
  594. this.pc_constraints = {'optional': [
  595. {'DtlsSrtpKeyAgreement': 'true'}
  596. ]};
  597. if (options.useIPv6) {
  598. // https://code.google.com/p/webrtc/issues/detail?id=2828
  599. this.pc_constraints.optional.push({googIPv6: true});
  600. }
  601. if (RTCBrowserType.isAndroid()) {
  602. this.pc_constraints = {}; // disable DTLS on Android
  603. }
  604. if (!webkitMediaStream.prototype.getVideoTracks) {
  605. webkitMediaStream.prototype.getVideoTracks = function () {
  606. return this.videoTracks;
  607. };
  608. }
  609. if (!webkitMediaStream.prototype.getAudioTracks) {
  610. webkitMediaStream.prototype.getAudioTracks = function () {
  611. return this.audioTracks;
  612. };
  613. }
  614. }
  615. // Detect IE/Safari
  616. else if (RTCBrowserType.isTemasysPluginUsed()) {
  617. //AdapterJS.WebRTCPlugin.setLogLevel(
  618. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  619. var self = this;
  620. AdapterJS.webRTCReady(function (isPlugin) {
  621. self.peerconnection = RTCPeerConnection;
  622. self.getUserMedia = window.getUserMedia;
  623. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  624. self.attachMediaStream = wrapAttachMediaStream(function (element, stream) {
  625. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  626. return;
  627. }
  628. var isVideoStream = !!stream.getVideoTracks().length;
  629. if (isVideoStream && !$(element).is(':visible')) {
  630. throw new Error('video element must be visible to attach video stream');
  631. }
  632. return attachMediaStream(element, stream);
  633. });
  634. self.getStreamID = function (stream) {
  635. return SDPUtil.filter_special_chars(stream.label);
  636. };
  637. self.getVideoSrc = function (element) {
  638. if (!element) {
  639. logger.warn("Attempt to get video SRC of null element");
  640. return null;
  641. }
  642. var children = element.children;
  643. for (var i = 0; i !== children.length; ++i) {
  644. if (children[i].name === 'streamId') {
  645. return children[i].value;
  646. }
  647. }
  648. //logger.info(element.id + " SRC: " + src);
  649. return null;
  650. };
  651. self.setVideoSrc = function (element, src) {
  652. //logger.info("Set video src: ", element, src);
  653. if (!src) {
  654. attachMediaStream(element, null);
  655. } else {
  656. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  657. var stream
  658. = AdapterJS.WebRTCPlugin.plugin
  659. .getStreamWithId(
  660. AdapterJS.WebRTCPlugin.pageId, src);
  661. attachMediaStream(element, stream);
  662. }
  663. };
  664. onReady(options, self.getUserMediaWithConstraints);
  665. resolve();
  666. });
  667. } else {
  668. try {
  669. logger.error('Browser does not appear to be WebRTC-capable');
  670. } catch (e) {
  671. }
  672. reject('Browser does not appear to be WebRTC-capable');
  673. return;
  674. }
  675. // Call onReady() if Temasys plugin is not used
  676. if (!RTCBrowserType.isTemasysPluginUsed()) {
  677. onReady(options, this.getUserMediaWithConstraints);
  678. resolve();
  679. }
  680. }.bind(this));
  681. },
  682. /**
  683. * @param {string[]} um required user media types
  684. * @param {function} success_callback
  685. * @param {Function} failure_callback
  686. * @param {Object} [options] optional parameters
  687. * @param {string} options.resolution
  688. * @param {number} options.bandwidth
  689. * @param {number} options.fps
  690. * @param {string} options.desktopStream
  691. * @param {string} options.cameraDeviceId
  692. * @param {string} options.micDeviceId
  693. **/
  694. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  695. options = options || {};
  696. var resolution = options.resolution;
  697. var constraints = getConstraints(um, options);
  698. logger.info("Get media constraints", constraints);
  699. try {
  700. this.getUserMedia(constraints,
  701. function (stream) {
  702. logger.log('onUserMediaSuccess');
  703. setAvailableDevices(um, true);
  704. success_callback(stream);
  705. },
  706. function (error) {
  707. setAvailableDevices(um, false);
  708. logger.warn('Failed to get access to local media. Error ',
  709. error, constraints);
  710. if (failure_callback) {
  711. failure_callback(error, resolution);
  712. }
  713. });
  714. } catch (e) {
  715. logger.error('GUM failed: ', e);
  716. if (failure_callback) {
  717. failure_callback(e);
  718. }
  719. }
  720. },
  721. /**
  722. * Creates the local MediaStreams.
  723. * @param {Object} [options] optional parameters
  724. * @param {Array} options.devices the devices that will be requested
  725. * @param {string} options.resolution resolution constraints
  726. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  727. * type: "audio" or "video", videoType: "camera" or "desktop"}
  728. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  729. * @param {string} options.cameraDeviceId
  730. * @param {string} options.micDeviceId
  731. * @returns {*} Promise object that will receive the new JitsiTracks
  732. */
  733. obtainAudioAndVideoPermissions: function (options) {
  734. var self = this;
  735. options = options || {};
  736. return new Promise(function (resolve, reject) {
  737. var successCallback = function (stream) {
  738. resolve(handleLocalStream(stream, options.resolution));
  739. };
  740. options.devices = options.devices || ['audio', 'video'];
  741. if(!screenObtainer.isSupported()
  742. && options.devices.indexOf("desktop") !== -1){
  743. reject(new Error("Desktop sharing is not supported!"));
  744. }
  745. if (RTCBrowserType.isFirefox() ||
  746. RTCBrowserType.isTemasysPluginUsed()) {
  747. var GUM = function (device, s, e) {
  748. this.getUserMediaWithConstraints(device, s, e, options);
  749. };
  750. var deviceGUM = {
  751. "audio": GUM.bind(self, ["audio"]),
  752. "video": GUM.bind(self, ["video"])
  753. };
  754. if(screenObtainer.isSupported()){
  755. deviceGUM["desktop"] = screenObtainer.obtainStream.bind(
  756. screenObtainer);
  757. }
  758. // With FF/IE we can't split the stream into audio and video because FF
  759. // doesn't support media stream constructors. So, we need to get the
  760. // audio stream separately from the video stream using two distinct GUM
  761. // calls. Not very user friendly :-( but we don't have many other
  762. // options neither.
  763. //
  764. // Note that we pack those 2 streams in a single object and pass it to
  765. // the successCallback method.
  766. obtainDevices({
  767. devices: options.devices,
  768. streams: [],
  769. successCallback: successCallback,
  770. errorCallback: reject,
  771. deviceGUM: deviceGUM
  772. });
  773. } else {
  774. var hasDesktop = options.devices.indexOf('desktop') > -1;
  775. if (hasDesktop) {
  776. options.devices.splice(options.devices.indexOf("desktop"), 1);
  777. }
  778. options.resolution = options.resolution || '360';
  779. if(options.devices.length) {
  780. this.getUserMediaWithConstraints(
  781. options.devices,
  782. function (stream) {
  783. if((options.devices.indexOf("audio") !== -1 &&
  784. !stream.getAudioTracks().length) ||
  785. (options.devices.indexOf("video") !== -1 &&
  786. !stream.getVideoTracks().length))
  787. {
  788. self.stopMediaStream(stream);
  789. reject(JitsiTrackErrors.parseError(
  790. new Error("Unable to get the audio and " +
  791. "video tracks."),
  792. options.devices));
  793. return;
  794. }
  795. if(hasDesktop) {
  796. screenObtainer.obtainStream(
  797. function (desktopStream) {
  798. successCallback({audioVideo: stream,
  799. desktopStream: desktopStream});
  800. }, function (error) {
  801. self.stopMediaStream(stream);
  802. reject(
  803. JitsiTrackErrors.parseError(error,
  804. options.devices));
  805. });
  806. } else {
  807. successCallback({audioVideo: stream});
  808. }
  809. },
  810. function (error) {
  811. reject(JitsiTrackErrors.parseError(error,
  812. options.devices));
  813. },
  814. options);
  815. } else if (hasDesktop) {
  816. screenObtainer.obtainStream(
  817. function (stream) {
  818. successCallback({desktopStream: stream});
  819. }, function (error) {
  820. reject(
  821. JitsiTrackErrors.parseError(error,
  822. ["desktop"]));
  823. });
  824. }
  825. }
  826. }.bind(this));
  827. },
  828. addListener: function (eventType, listener) {
  829. eventEmitter.on(eventType, listener);
  830. },
  831. removeListener: function (eventType, listener) {
  832. eventEmitter.removeListener(eventType, listener);
  833. },
  834. getDeviceAvailability: function () {
  835. return devices;
  836. },
  837. isRTCReady: function () {
  838. return rtcReady;
  839. },
  840. /**
  841. * Checks if its possible to enumerate available cameras/micropones.
  842. * @returns {boolean} true if available, false otherwise.
  843. */
  844. isDeviceListAvailable: function () {
  845. var isEnumerateDevicesAvailable
  846. = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  847. if (isEnumerateDevicesAvailable) {
  848. return true;
  849. }
  850. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  851. },
  852. /**
  853. * Returns true if changing the input (camera / microphone) or output
  854. * (audio) device is supported and false if not.
  855. * @params {string} [deviceType] - type of device to change. Default is
  856. * undefined or 'input', 'output' - for audio output device change.
  857. * @returns {boolean} true if available, false otherwise.
  858. */
  859. isDeviceChangeAvailable: function (deviceType) {
  860. return deviceType === 'output' || deviceType === 'audiooutput'
  861. ? isAudioOutputDeviceChangeAvailable
  862. : RTCBrowserType.isChrome() ||
  863. RTCBrowserType.isFirefox() ||
  864. RTCBrowserType.isOpera() ||
  865. RTCBrowserType.isTemasysPluginUsed()||
  866. RTCBrowserType.isNWJS();
  867. },
  868. /**
  869. * A method to handle stopping of the stream.
  870. * One point to handle the differences in various implementations.
  871. * @param mediaStream MediaStream object to stop.
  872. */
  873. stopMediaStream: function (mediaStream) {
  874. mediaStream.getTracks().forEach(function (track) {
  875. // stop() not supported with IE
  876. if (!RTCBrowserType.isTemasysPluginUsed() && track.stop) {
  877. track.stop();
  878. }
  879. });
  880. // leave stop for implementation still using it
  881. if (mediaStream.stop) {
  882. mediaStream.stop();
  883. }
  884. // if we have done createObjectURL, lets clean it
  885. if (mediaStream.jitsiObjectURL) {
  886. webkitURL.revokeObjectURL(mediaStream.jitsiObjectURL);
  887. }
  888. },
  889. /**
  890. * Returns whether the desktop sharing is enabled or not.
  891. * @returns {boolean}
  892. */
  893. isDesktopSharingEnabled: function () {
  894. return screenObtainer.isSupported();
  895. },
  896. /**
  897. * Sets current audio output device.
  898. * @param {string} deviceId - id of 'audiooutput' device from
  899. * navigator.mediaDevices.enumerateDevices(), '' for default device
  900. * @returns {Promise} - resolves when audio output is changed, is rejected
  901. * otherwise
  902. */
  903. setAudioOutputDevice: function (deviceId) {
  904. if (!this.isDeviceChangeAvailable('output')) {
  905. Promise.reject(
  906. new Error('Audio output device change is not supported'));
  907. }
  908. return featureDetectionAudioEl.setSinkId(deviceId)
  909. .then(function() {
  910. audioOuputDeviceId = deviceId;
  911. logger.log('Audio output device set to ' + deviceId);
  912. eventEmitter.emit(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  913. deviceId);
  914. });
  915. },
  916. /**
  917. * Returns currently used audio output device id, '' stands for default
  918. * device
  919. * @returns {string}
  920. */
  921. getAudioOutputDevice: function () {
  922. return audioOuputDeviceId;
  923. }
  924. };
  925. module.exports = RTCUtils;