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 46KB

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