You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RTCUtils.js 46KB

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