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.

ConnectionQuality.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. import * as ConnectionQualityEvents
  2. from '../../service/connectivity/ConnectionQualityEvents';
  3. import * as ConferenceEvents from '../../JitsiConferenceEvents';
  4. import { getLogger } from 'jitsi-meet-logger';
  5. const XMPPEvents = require('../../service/xmpp/XMPPEvents');
  6. const VideoType = require('../../service/RTC/VideoType');
  7. const Resolutions = require('../../service/RTC/Resolutions');
  8. const logger = getLogger(__filename);
  9. /**
  10. * The value to use for the "type" field for messages sent by ConnectionQuality
  11. * over the data channel.
  12. */
  13. const STATS_MESSAGE_TYPE = 'stats';
  14. /**
  15. * See media/engine/simulcast.ss from webrtc.org
  16. */
  17. const kSimulcastFormats = [
  18. { width: 1920,
  19. height: 1080,
  20. layers: 3,
  21. max: 5000,
  22. target: 4000,
  23. min: 800 },
  24. { width: 1280,
  25. height: 720,
  26. layers: 3,
  27. max: 2500,
  28. target: 2500,
  29. min: 600 },
  30. { width: 960,
  31. height: 540,
  32. layers: 3,
  33. max: 900,
  34. target: 900,
  35. min: 450 },
  36. { width: 640,
  37. height: 360,
  38. layers: 2,
  39. max: 700,
  40. target: 500,
  41. min: 150 },
  42. { width: 480,
  43. height: 270,
  44. layers: 2,
  45. max: 450,
  46. target: 350,
  47. min: 150 },
  48. { width: 320,
  49. height: 180,
  50. layers: 1,
  51. max: 200,
  52. target: 150,
  53. min: 30 }
  54. ];
  55. /**
  56. * The initial bitrate for video in kbps.
  57. */
  58. let startBitrate = 800;
  59. /**
  60. * Gets the expected bitrate (in kbps) in perfect network conditions.
  61. * @param simulcast {boolean} whether simulcast is enabled or not.
  62. * @param resolution {Resolution} the resolution.
  63. * @param millisSinceStart {number} the number of milliseconds since sending
  64. * video started.
  65. */
  66. function getTarget(simulcast, resolution, millisSinceStart) {
  67. // Completely ignore the bitrate in the first 5 seconds, as the first
  68. // event seems to fire very early and the value is suspicious and causes
  69. // false positives.
  70. if (millisSinceStart < 5000) {
  71. return 1;
  72. }
  73. let target = 0;
  74. let height = Math.min(resolution.height, resolution.width);
  75. if (simulcast) {
  76. // Find the first format with height no bigger than ours.
  77. let simulcastFormat = kSimulcastFormats.find(f => f.height <= height);
  78. if (simulcastFormat) {
  79. // Sum the target fields from all simulcast layers for the given
  80. // resolution (e.g. 720p + 360p + 180p).
  81. for (height = simulcastFormat.height; height >= 180; height /= 2) {
  82. const targetHeight = height;
  83. simulcastFormat
  84. = kSimulcastFormats.find(f => f.height === targetHeight);
  85. if (simulcastFormat) {
  86. target += simulcastFormat.target;
  87. } else {
  88. break;
  89. }
  90. }
  91. }
  92. } else {
  93. // See GetMaxDefaultVideoBitrateKbps in
  94. // media/engine/webrtcvideoengine2.cc from webrtc.org
  95. const pixels = resolution.width * resolution.height;
  96. if (pixels <= 320 * 240) {
  97. target = 600;
  98. } else if (pixels <= 640 * 480) {
  99. target = 1700;
  100. } else if (pixels <= 960 * 540) {
  101. target = 2000;
  102. } else {
  103. target = 2500;
  104. }
  105. }
  106. // Allow for an additional 1 second for ramp up -- delay any initial drop
  107. // of connection quality by 1 second.
  108. return Math.min(target, rampUp(Math.max(0, millisSinceStart - 1000)));
  109. }
  110. /**
  111. * Gets the bitrate to which GCC would have ramped up in perfect network
  112. * conditions after millisSinceStart milliseconds.
  113. * @param millisSinceStart {number} the number of milliseconds since sending
  114. * video was enabled.
  115. */
  116. function rampUp(millisSinceStart) {
  117. if (millisSinceStart > 60000) {
  118. return Number.MAX_SAFE_INTEGER;
  119. }
  120. // According to GCC the send side bandwidth estimation grows with at most
  121. // 8% per second.
  122. // https://tools.ietf.org/html/draft-ietf-rmcat-gcc-02#section-5.5
  123. return startBitrate * Math.pow(1.08, millisSinceStart / 1000);
  124. }
  125. /**
  126. * A class which monitors the local statistics coming from the RTC modules, and
  127. * calculates a "connection quality" value, in percent, for the media
  128. * connection. A value of 100% indicates a very good network connection, and a
  129. * value of 0% indicates a poor connection.
  130. */
  131. export default class ConnectionQuality {
  132. /**
  133. *
  134. * @param conference
  135. * @param eventEmitter
  136. * @param options
  137. */
  138. constructor(conference, eventEmitter, options) {
  139. this.eventEmitter = eventEmitter;
  140. /**
  141. * The owning JitsiConference.
  142. */
  143. this._conference = conference;
  144. /**
  145. * Holds statistics about the local connection quality.
  146. */
  147. this._localStats = {
  148. connectionQuality: 100,
  149. jvbRTT: undefined
  150. };
  151. /**
  152. * The time this._localStats.connectionQuality was last updated.
  153. */
  154. this._lastConnectionQualityUpdate = -1;
  155. /**
  156. * Maps a participant ID to an object holding connection quality
  157. * statistics received from this participant.
  158. */
  159. this._remoteStats = {};
  160. /**
  161. * The time that the ICE state last changed to CONNECTED. We use this
  162. * to calculate how much time we as a sender have had to ramp-up.
  163. */
  164. this._timeIceConnected = -1;
  165. /**
  166. * The time that local video was unmuted. We use this to calculate how
  167. * much time we as a sender have had to ramp-up.
  168. */
  169. this._timeVideoUnmuted = -1;
  170. // We assume a global startBitrate value for the sake of simplicity.
  171. if (options.startBitrate && options.startBitrate > 0) {
  172. startBitrate = options.startBitrate;
  173. }
  174. // TODO: consider ignoring these events and letting the user of
  175. // lib-jitsi-meet handle these separately.
  176. conference.on(
  177. ConferenceEvents.CONNECTION_INTERRUPTED,
  178. () => {
  179. this._updateLocalConnectionQuality(0);
  180. this.eventEmitter.emit(
  181. ConnectionQualityEvents.LOCAL_STATS_UPDATED,
  182. this._localStats);
  183. this._broadcastLocalStats();
  184. });
  185. conference.room.addListener(
  186. XMPPEvents.ICE_CONNECTION_STATE_CHANGED,
  187. (jingleSession, newState) => {
  188. if (!jingleSession.isP2P && newState === 'connected') {
  189. this._timeIceConnected = window.performance.now();
  190. }
  191. });
  192. // Listen to DataChannel message from other participants in the
  193. // conference, and update the _remoteStats field accordingly.
  194. conference.on(
  195. ConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  196. (participant, payload) => {
  197. if (payload.type === STATS_MESSAGE_TYPE) {
  198. this._updateRemoteStats(
  199. participant.getId(), payload.values);
  200. }
  201. });
  202. // Listen to local statistics events originating from the RTC module
  203. // and update the _localStats field.
  204. // Oh, and by the way, the resolutions of all remote participants are
  205. // also piggy-backed in these "local" statistics. It's obvious, really,
  206. // if one carefully reads the *code* (but not the docs) in
  207. // UI/VideoLayout/VideoLayout.js#updateLocalConnectionStats in
  208. // jitsi-meet
  209. // TODO: We should keep track of the remote resolution in _remoteStats,
  210. // and notify about changes via separate events.
  211. conference.statistics.addConnectionStatsListener(
  212. this._updateLocalStats.bind(this));
  213. // Save the last time we were unmuted.
  214. conference.on(
  215. ConferenceEvents.TRACK_MUTE_CHANGED,
  216. track => {
  217. if (track.isVideoTrack()) {
  218. if (track.isMuted()) {
  219. this._timeVideoUnmuted = -1;
  220. } else {
  221. this._maybeUpdateUnmuteTime();
  222. }
  223. }
  224. });
  225. conference.on(
  226. ConferenceEvents.TRACK_ADDED,
  227. track => {
  228. if (track.isVideoTrack() && !track.isMuted()) {
  229. this._maybeUpdateUnmuteTime();
  230. }
  231. });
  232. }
  233. /**
  234. * Sets _timeVideoUnmuted if it was previously unset. If it was already set,
  235. * doesn't change it.
  236. */
  237. _maybeUpdateUnmuteTime() {
  238. if (this._timeVideoUnmuted < 0) {
  239. this._timeVideoUnmuted = window.performance.now();
  240. }
  241. }
  242. /**
  243. * Calculates a new "connection quality" value.
  244. * @param videoType {VideoType} the type of the video source (camera or
  245. * a screen capture).
  246. * @param isMuted {boolean} whether the local video is muted.
  247. * @param resolutionName {Resolution} the input resolution used by the
  248. * camera.
  249. * @returns {*} the newly calculated connection quality.
  250. */
  251. _calculateConnectionQuality(videoType, isMuted, resolutionName) {
  252. // resolutionName is an index into Resolutions (where "720" is
  253. // "1280x720" and "960" is "960x720" ...).
  254. const resolution = Resolutions[resolutionName];
  255. let quality = 100;
  256. let isSimulcastOn;
  257. let millisSinceStart;
  258. let packetLoss;
  259. let target;
  260. // TODO: take into account packet loss for received streams
  261. if (this._localStats.packetLoss) {
  262. packetLoss = this._localStats.packetLoss.upload;
  263. // Ugly Hack Alert (UHA):
  264. // The packet loss for the upload direction is calculated based on
  265. // incoming RTCP Receiver Reports. Since we don't have RTCP
  266. // termination for audio, these reports come from the actual
  267. // receivers in the conference and therefore the reported packet
  268. // loss includes loss from the bridge to the receiver.
  269. // When we are sending video this effect is small, because the
  270. // number of video packets is much larger than the number of audio
  271. // packets (and our calculation is based on the total number of
  272. // received and lost packets).
  273. // When video is muted, however, the effect might be significant,
  274. // but we don't know what it is. We do know that it is positive, so
  275. // as a temporary solution, until RTCP termination is implemented
  276. // for the audio streams, we relax the packet loss checks here.
  277. if (isMuted) {
  278. packetLoss *= 0.5;
  279. }
  280. }
  281. if (isMuted || !resolution || videoType === VideoType.DESKTOP
  282. || this._timeIceConnected < 0
  283. || this._timeVideoUnmuted < 0) {
  284. // Calculate a value based on packet loss only.
  285. if (packetLoss === undefined) {
  286. logger.error('Cannot calculate connection quality, unknown '
  287. + 'packet loss.');
  288. quality = 100;
  289. } else if (packetLoss <= 2) {
  290. quality = 100; // Full 5 bars.
  291. } else if (packetLoss <= 4) {
  292. quality = 70; // 4 bars
  293. } else if (packetLoss <= 6) {
  294. quality = 50; // 3 bars
  295. } else if (packetLoss <= 8) {
  296. quality = 30; // 2 bars
  297. } else if (packetLoss <= 12) {
  298. quality = 10; // 1 bars
  299. } else {
  300. quality = 0; // Still 1 bar, but slower climb-up.
  301. }
  302. } else {
  303. // Calculate a value based on the sending bitrate.
  304. // time since sending of video was enabled.
  305. millisSinceStart = window.performance.now()
  306. - Math.max(this._timeVideoUnmuted, this._timeIceConnected);
  307. // Figure out if simulcast is in use
  308. const activeTPC = this._conference.getActivePeerConnection();
  309. isSimulcastOn
  310. = Boolean(activeTPC && activeTPC.isSimulcastOn());
  311. // expected sending bitrate in perfect conditions
  312. target
  313. = getTarget(isSimulcastOn, resolution, millisSinceStart);
  314. target = 0.9 * target;
  315. quality = 100 * this._localStats.bitrate.upload / target;
  316. // Whatever the bitrate, drop early if there is significant loss
  317. if (packetLoss && packetLoss >= 10) {
  318. quality = Math.min(quality, 30);
  319. }
  320. }
  321. // Make sure that the quality doesn't climb quickly
  322. if (this._lastConnectionQualityUpdate > 0) {
  323. const maxIncreasePerSecond = 2;
  324. const prevConnectionQuality = this._localStats.connectionQuality;
  325. const diffSeconds
  326. = (window.performance.now() - this._lastConnectionQualityUpdate)
  327. / 1000;
  328. quality
  329. = Math.min(
  330. quality,
  331. prevConnectionQuality
  332. + (diffSeconds * maxIncreasePerSecond));
  333. }
  334. const connectionQuality = Math.min(100, quality);
  335. console.debug('calculated connection quality', JSON.stringify({
  336. connectionQuality,
  337. isMuted,
  338. isSimulcastOn,
  339. lastUpdate: this._lastConnectionQualityUpdate,
  340. millisSinceStart,
  341. packetLoss,
  342. resolution,
  343. target,
  344. upload: this._localStats.bitrate
  345. && this._localStats.bitrate.upload
  346. }));
  347. return connectionQuality;
  348. }
  349. /**
  350. * Updates the localConnectionQuality value
  351. * @param values {number} the new value. Should be in [0, 100].
  352. */
  353. _updateLocalConnectionQuality(value) {
  354. this._localStats.connectionQuality = value;
  355. this._lastConnectionQualityUpdate = window.performance.now();
  356. }
  357. /**
  358. * Broadcasts the local statistics to all other participants in the
  359. * conference.
  360. */
  361. _broadcastLocalStats() {
  362. // Send only the data that remote participants care about.
  363. const data = {
  364. bitrate: this._localStats.bitrate,
  365. packetLoss: this._localStats.packetLoss,
  366. connectionQuality: this._localStats.connectionQuality,
  367. jvbRTT: this._localStats.jvbRTT
  368. };
  369. try {
  370. this._conference.broadcastEndpointMessage({
  371. type: STATS_MESSAGE_TYPE,
  372. values: data });
  373. } catch (e) {
  374. // We often hit this in the beginning of a call, before the data
  375. // channel is ready. It is not a big problem, because we will
  376. // send the statistics again after a few seconds, and the error is
  377. // already logged elsewhere. So just ignore it.
  378. // let errorMsg = "Failed to broadcast local stats";
  379. // logger.error(errorMsg, e);
  380. // GlobalOnErrorHandler.callErrorHandler(
  381. // new Error(errorMsg + ": " + e));
  382. }
  383. }
  384. /**
  385. * Updates the local statistics
  386. * @param {TraceablePeerConnection} tpc the peerconnection which emitted
  387. * the stats
  388. * @param data new statistics
  389. */
  390. _updateLocalStats(tpc, data) {
  391. // Update jvbRTT
  392. if (!tpc.isP2P) {
  393. const jvbRTT
  394. = data.transport
  395. && data.transport.length && data.transport[0].rtt;
  396. this._localStats.jvbRTT = jvbRTT ? jvbRTT : undefined;
  397. }
  398. // Do not continue with processing of other stats if they do not
  399. // originate from the active peerconnection
  400. if (tpc !== this._conference.getActivePeerConnection()) {
  401. return;
  402. }
  403. let key;
  404. const updateLocalConnectionQuality
  405. = !this._conference.isConnectionInterrupted();
  406. const localVideoTrack
  407. = this._conference.getLocalVideoTrack();
  408. const videoType
  409. = localVideoTrack ? localVideoTrack.videoType : undefined;
  410. const isMuted = localVideoTrack ? localVideoTrack.isMuted() : true;
  411. const resolution = localVideoTrack ? localVideoTrack.resolution : null;
  412. if (!isMuted) {
  413. this._maybeUpdateUnmuteTime();
  414. }
  415. // Copy the fields already in 'data'.
  416. for (key in data) {
  417. if (data.hasOwnProperty(key)) {
  418. this._localStats[key] = data[key];
  419. }
  420. }
  421. // And re-calculate the connectionQuality field.
  422. if (updateLocalConnectionQuality) {
  423. this._updateLocalConnectionQuality(
  424. this._calculateConnectionQuality(
  425. videoType,
  426. isMuted,
  427. resolution));
  428. }
  429. this.eventEmitter.emit(
  430. ConnectionQualityEvents.LOCAL_STATS_UPDATED,
  431. this._localStats);
  432. this._broadcastLocalStats();
  433. }
  434. /**
  435. * Updates remote statistics
  436. * @param id the id of the remote participant
  437. * @param data the statistics received
  438. */
  439. _updateRemoteStats(id, data) {
  440. // Use only the fields we need
  441. this._remoteStats[id] = {
  442. bitrate: data.bitrate,
  443. packetLoss: data.packetLoss,
  444. connectionQuality: data.connectionQuality,
  445. jvbRTT: data.jvbRTT
  446. };
  447. this.eventEmitter.emit(
  448. ConnectionQualityEvents.REMOTE_STATS_UPDATED,
  449. id,
  450. this._remoteStats[id]);
  451. }
  452. /**
  453. * Returns the local statistics.
  454. * Exported only for use in jitsi-meet-torture.
  455. */
  456. getStats() {
  457. return this._localStats;
  458. }
  459. }