Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

RTCUtils.js 38KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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. return element ? element.getAttribute("src") : null;
  583. };
  584. this.setVideoSrc = function (element, src) {
  585. if (element)
  586. element.setAttribute("src", src || '');
  587. };
  588. // DTLS should now be enabled by default but..
  589. this.pc_constraints = {'optional': [
  590. {'DtlsSrtpKeyAgreement': 'true'}
  591. ]};
  592. if (options.useIPv6) {
  593. // https://code.google.com/p/webrtc/issues/detail?id=2828
  594. this.pc_constraints.optional.push({googIPv6: true});
  595. }
  596. if (RTCBrowserType.isAndroid()) {
  597. this.pc_constraints = {}; // disable DTLS on Android
  598. }
  599. if (!webkitMediaStream.prototype.getVideoTracks) {
  600. webkitMediaStream.prototype.getVideoTracks = function () {
  601. return this.videoTracks;
  602. };
  603. }
  604. if (!webkitMediaStream.prototype.getAudioTracks) {
  605. webkitMediaStream.prototype.getAudioTracks = function () {
  606. return this.audioTracks;
  607. };
  608. }
  609. }
  610. // Detect IE/Safari
  611. else if (RTCBrowserType.isTemasysPluginUsed()) {
  612. //AdapterJS.WebRTCPlugin.setLogLevel(
  613. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  614. var self = this;
  615. AdapterJS.webRTCReady(function (isPlugin) {
  616. self.peerconnection = RTCPeerConnection;
  617. self.getUserMedia = window.getUserMedia;
  618. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  619. self.attachMediaStream = wrapAttachMediaStream(function (element, stream) {
  620. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  621. return;
  622. }
  623. var isVideoStream = !!stream.getVideoTracks().length;
  624. if (isVideoStream && !$(element).is(':visible')) {
  625. throw new Error('video element must be visible to attach video stream');
  626. }
  627. return attachMediaStream(element, stream);
  628. });
  629. self.getStreamID = function (stream) {
  630. return SDPUtil.filter_special_chars(stream.label);
  631. };
  632. self.getVideoSrc = function (element) {
  633. if (!element) {
  634. logger.warn("Attempt to get video SRC of null element");
  635. return null;
  636. }
  637. var children = element.children;
  638. for (var i = 0; i !== children.length; ++i) {
  639. if (children[i].name === 'streamId') {
  640. return children[i].value;
  641. }
  642. }
  643. //logger.info(element.id + " SRC: " + src);
  644. return null;
  645. };
  646. self.setVideoSrc = function (element, src) {
  647. //logger.info("Set video src: ", element, src);
  648. if (!src) {
  649. attachMediaStream(element, null);
  650. } else {
  651. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  652. var stream
  653. = AdapterJS.WebRTCPlugin.plugin
  654. .getStreamWithId(
  655. AdapterJS.WebRTCPlugin.pageId, src);
  656. attachMediaStream(element, stream);
  657. }
  658. };
  659. onReady(options, self.getUserMediaWithConstraints);
  660. resolve();
  661. });
  662. } else {
  663. try {
  664. logger.error('Browser does not appear to be WebRTC-capable');
  665. } catch (e) {
  666. }
  667. reject('Browser does not appear to be WebRTC-capable');
  668. return;
  669. }
  670. // Call onReady() if Temasys plugin is not used
  671. if (!RTCBrowserType.isTemasysPluginUsed()) {
  672. onReady(options, this.getUserMediaWithConstraints);
  673. resolve();
  674. }
  675. }.bind(this));
  676. },
  677. /**
  678. * @param {string[]} um required user media types
  679. * @param {function} success_callback
  680. * @param {Function} failure_callback
  681. * @param {Object} [options] optional parameters
  682. * @param {string} options.resolution
  683. * @param {number} options.bandwidth
  684. * @param {number} options.fps
  685. * @param {string} options.desktopStream
  686. * @param {string} options.cameraDeviceId
  687. * @param {string} options.micDeviceId
  688. **/
  689. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  690. options = options || {};
  691. var resolution = options.resolution;
  692. var constraints = getConstraints(um, options);
  693. logger.info("Get media constraints", constraints);
  694. try {
  695. this.getUserMedia(constraints,
  696. function (stream) {
  697. logger.log('onUserMediaSuccess');
  698. setAvailableDevices(um, true);
  699. success_callback(stream);
  700. },
  701. function (error) {
  702. setAvailableDevices(um, false);
  703. logger.warn('Failed to get access to local media. Error ',
  704. error, constraints);
  705. if (failure_callback) {
  706. failure_callback(error, resolution);
  707. }
  708. });
  709. } catch (e) {
  710. logger.error('GUM failed: ', e);
  711. if (failure_callback) {
  712. failure_callback(e);
  713. }
  714. }
  715. },
  716. /**
  717. * Creates the local MediaStreams.
  718. * @param {Object} [options] optional parameters
  719. * @param {Array} options.devices the devices that will be requested
  720. * @param {string} options.resolution resolution constraints
  721. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  722. * type: "audio" or "video", videoType: "camera" or "desktop"}
  723. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  724. * @param {string} options.cameraDeviceId
  725. * @param {string} options.micDeviceId
  726. * @returns {*} Promise object that will receive the new JitsiTracks
  727. */
  728. obtainAudioAndVideoPermissions: function (options) {
  729. var self = this;
  730. options = options || {};
  731. return new Promise(function (resolve, reject) {
  732. var successCallback = function (stream) {
  733. resolve(handleLocalStream(stream, options.resolution));
  734. };
  735. options.devices = options.devices || ['audio', 'video'];
  736. if(!screenObtainer.isSupported()
  737. && options.devices.indexOf("desktop") !== -1){
  738. reject(new Error("Desktop sharing is not supported!"));
  739. }
  740. if (RTCBrowserType.isFirefox() ||
  741. RTCBrowserType.isTemasysPluginUsed()) {
  742. var GUM = function (device, s, e) {
  743. this.getUserMediaWithConstraints(device, s, e, options);
  744. };
  745. var deviceGUM = {
  746. "audio": GUM.bind(self, ["audio"]),
  747. "video": GUM.bind(self, ["video"])
  748. };
  749. if(screenObtainer.isSupported()){
  750. deviceGUM["desktop"] = screenObtainer.obtainStream.bind(
  751. screenObtainer);
  752. }
  753. // With FF/IE we can't split the stream into audio and video because FF
  754. // doesn't support media stream constructors. So, we need to get the
  755. // audio stream separately from the video stream using two distinct GUM
  756. // calls. Not very user friendly :-( but we don't have many other
  757. // options neither.
  758. //
  759. // Note that we pack those 2 streams in a single object and pass it to
  760. // the successCallback method.
  761. obtainDevices({
  762. devices: options.devices,
  763. streams: [],
  764. successCallback: successCallback,
  765. errorCallback: reject,
  766. deviceGUM: deviceGUM
  767. });
  768. } else {
  769. var hasDesktop = options.devices.indexOf('desktop') > -1;
  770. if (hasDesktop) {
  771. options.devices.splice(options.devices.indexOf("desktop"), 1);
  772. }
  773. options.resolution = options.resolution || '360';
  774. if(options.devices.length) {
  775. this.getUserMediaWithConstraints(
  776. options.devices,
  777. function (stream) {
  778. if((options.devices.indexOf("audio") !== -1 &&
  779. !stream.getAudioTracks().length) ||
  780. (options.devices.indexOf("video") !== -1 &&
  781. !stream.getVideoTracks().length))
  782. {
  783. self.stopMediaStream(stream);
  784. reject(JitsiTrackErrors.parseError(
  785. new Error("Unable to get the audio and " +
  786. "video tracks."),
  787. options.devices));
  788. return;
  789. }
  790. if(hasDesktop) {
  791. screenObtainer.obtainStream(
  792. function (desktopStream) {
  793. successCallback({audioVideo: stream,
  794. desktopStream: desktopStream});
  795. }, function (error) {
  796. self.stopMediaStream(stream);
  797. reject(
  798. JitsiTrackErrors.parseError(error,
  799. options.devices));
  800. });
  801. } else {
  802. successCallback({audioVideo: stream});
  803. }
  804. },
  805. function (error) {
  806. reject(JitsiTrackErrors.parseError(error,
  807. options.devices));
  808. },
  809. options);
  810. } else if (hasDesktop) {
  811. screenObtainer.obtainStream(
  812. function (stream) {
  813. successCallback({desktopStream: stream});
  814. }, function (error) {
  815. reject(
  816. JitsiTrackErrors.parseError(error,
  817. ["desktop"]));
  818. });
  819. }
  820. }
  821. }.bind(this));
  822. },
  823. addListener: function (eventType, listener) {
  824. eventEmitter.on(eventType, listener);
  825. },
  826. removeListener: function (eventType, listener) {
  827. eventEmitter.removeListener(eventType, listener);
  828. },
  829. getDeviceAvailability: function () {
  830. return devices;
  831. },
  832. isRTCReady: function () {
  833. return rtcReady;
  834. },
  835. /**
  836. * Checks if its possible to enumerate available cameras/micropones.
  837. * @returns {boolean} true if available, false otherwise.
  838. */
  839. isDeviceListAvailable: function () {
  840. var isEnumerateDevicesAvailable
  841. = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  842. if (isEnumerateDevicesAvailable) {
  843. return true;
  844. }
  845. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  846. },
  847. /**
  848. * Returns true if changing the input (camera / microphone) or output
  849. * (audio) device is supported and false if not.
  850. * @params {string} [deviceType] - type of device to change. Default is
  851. * undefined or 'input', 'output' - for audio output device change.
  852. * @returns {boolean} true if available, false otherwise.
  853. */
  854. isDeviceChangeAvailable: function (deviceType) {
  855. return deviceType === 'output' || deviceType === 'audiooutput'
  856. ? isAudioOutputDeviceChangeAvailable
  857. : RTCBrowserType.isChrome() ||
  858. RTCBrowserType.isFirefox() ||
  859. RTCBrowserType.isOpera() ||
  860. RTCBrowserType.isTemasysPluginUsed()||
  861. RTCBrowserType.isNWJS();
  862. },
  863. /**
  864. * A method to handle stopping of the stream.
  865. * One point to handle the differences in various implementations.
  866. * @param mediaStream MediaStream object to stop.
  867. */
  868. stopMediaStream: function (mediaStream) {
  869. mediaStream.getTracks().forEach(function (track) {
  870. // stop() not supported with IE
  871. if (!RTCBrowserType.isTemasysPluginUsed() && track.stop) {
  872. track.stop();
  873. }
  874. });
  875. // leave stop for implementation still using it
  876. if (mediaStream.stop) {
  877. mediaStream.stop();
  878. }
  879. // if we have done createObjectURL, lets clean it
  880. if (mediaStream.jitsiObjectURL) {
  881. webkitURL.revokeObjectURL(mediaStream.jitsiObjectURL);
  882. }
  883. },
  884. /**
  885. * Returns whether the desktop sharing is enabled or not.
  886. * @returns {boolean}
  887. */
  888. isDesktopSharingEnabled: function () {
  889. return screenObtainer.isSupported();
  890. },
  891. /**
  892. * Sets current audio output device.
  893. * @param {string} deviceId - id of 'audiooutput' device from
  894. * navigator.mediaDevices.enumerateDevices(), '' for default device
  895. * @returns {Promise} - resolves when audio output is changed, is rejected
  896. * otherwise
  897. */
  898. setAudioOutputDevice: function (deviceId) {
  899. if (!this.isDeviceChangeAvailable('output')) {
  900. Promise.reject(
  901. new Error('Audio output device change is not supported'));
  902. }
  903. return featureDetectionAudioEl.setSinkId(deviceId)
  904. .then(function() {
  905. audioOuputDeviceId = deviceId;
  906. logger.log('Audio output device set to ' + deviceId);
  907. eventEmitter.emit(RTCEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  908. deviceId);
  909. });
  910. },
  911. /**
  912. * Returns currently used audio output device id, '' stands for default
  913. * device
  914. * @returns {string}
  915. */
  916. getAudioOutputDevice: function () {
  917. return audioOuputDeviceId;
  918. }
  919. };
  920. module.exports = RTCUtils;