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

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