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

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