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

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