Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

RTCUtils.js 42KB

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