您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ConnectionQuality.js 17KB

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