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

ConnectionQuality.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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(__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. /**
  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. // TODO: consider ignoring these events and letting the user of
  127. // lib-jitsi-meet handle these separately.
  128. conference.on(
  129. ConferenceEvents.CONNECTION_INTERRUPTED,
  130. () => {
  131. this._updateLocalConnectionQuality(0);
  132. this.eventEmitter.emit(
  133. ConnectionQualityEvents.LOCAL_STATS_UPDATED,
  134. this._localStats);
  135. this._broadcastLocalStats();
  136. });
  137. conference.room.addListener(
  138. XMPPEvents.ICE_CONNECTION_STATE_CHANGED,
  139. (jingleSession, newState) => {
  140. if (!jingleSession.isP2P && newState === 'connected') {
  141. this._timeIceConnected = window.performance.now();
  142. }
  143. });
  144. // Listen to DataChannel message from other participants in the
  145. // conference, and update the _remoteStats field accordingly.
  146. // TODO - Delete this when all the mobile endpoints switch to using the new Colibri
  147. // message format for sending the endpoint stats.
  148. conference.on(
  149. ConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  150. (participant, payload) => {
  151. if (payload.type === STATS_MESSAGE_TYPE) {
  152. this._updateRemoteStats(
  153. participant.getId(), payload.values);
  154. }
  155. });
  156. conference.on(
  157. ConferenceEvents.ENDPOINT_STATS_RECEIVED,
  158. (participant, payload) => {
  159. this._updateRemoteStats(participant.getId(), payload);
  160. });
  161. if (!this._options.config.disableLocalStats) {
  162. // Listen to local statistics events originating from the RTC module and update the _localStats field.
  163. conference.statistics.addConnectionStatsListener(this._updateLocalStats.bind(this));
  164. }
  165. // Save the last time we were unmuted.
  166. conference.on(
  167. ConferenceEvents.TRACK_MUTE_CHANGED,
  168. track => {
  169. if (track.isVideoTrack()) {
  170. if (track.isMuted()) {
  171. this._timeVideoUnmuted = -1;
  172. } else {
  173. this._maybeUpdateUnmuteTime();
  174. }
  175. }
  176. });
  177. conference.on(
  178. ConferenceEvents.TRACK_ADDED,
  179. track => {
  180. if (track.isVideoTrack() && !track.isMuted()) {
  181. this._maybeUpdateUnmuteTime();
  182. }
  183. });
  184. conference.rtc.on(
  185. RTCEvents.LOCAL_TRACK_MAX_ENABLED_RESOLUTION_CHANGED,
  186. track => {
  187. this._localStats.maxEnabledResolution = track.maxEnabledResolution;
  188. });
  189. conference.on(
  190. ConferenceEvents.SERVER_REGION_CHANGED,
  191. serverRegion => {
  192. this._localStats.serverRegion = serverRegion;
  193. });
  194. conference.on(
  195. ConferenceEvents.PROPERTIES_CHANGED,
  196. properties => {
  197. this._localStats.bridgeCount
  198. = Number((properties || {})['bridge-count']);
  199. }
  200. );
  201. }
  202. /**
  203. * Sets _timeVideoUnmuted if it was previously unset. If it was already set,
  204. * doesn't change it.
  205. */
  206. _maybeUpdateUnmuteTime() {
  207. if (this._timeVideoUnmuted < 0) {
  208. this._timeVideoUnmuted = window.performance.now();
  209. }
  210. }
  211. /**
  212. * Calculates a new "connection quality" value.
  213. * @param videoType {VideoType} the type of the video source (camera or a screen capture).
  214. * @param isMuted {boolean} whether the local video is muted.
  215. * @param resolutionName {Resolution} the input resolution used by the camera.
  216. * @returns {*} the newly calculated connection quality.
  217. */
  218. _calculateConnectionQuality(videoType, isMuted, resolutionName) {
  219. // resolutionName is an index into Resolutions (where "720" is
  220. // "1280x720" and "960" is "960x720" ...).
  221. const resolution = Resolutions[resolutionName];
  222. let quality = 100;
  223. let packetLoss;
  224. // TODO: take into account packet loss for received streams
  225. if (this._localStats.packetLoss) {
  226. packetLoss = this._localStats.packetLoss.upload;
  227. // Ugly Hack Alert (UHA):
  228. // The packet loss for the upload direction is calculated based on
  229. // incoming RTCP Receiver Reports. Since we don't have RTCP
  230. // termination for audio, these reports come from the actual
  231. // receivers in the conference and therefore the reported packet
  232. // loss includes loss from the bridge to the receiver.
  233. // When we are sending video this effect is small, because the
  234. // number of video packets is much larger than the number of audio
  235. // packets (and our calculation is based on the total number of
  236. // received and lost packets).
  237. // When video is muted, however, the effect might be significant,
  238. // but we don't know what it is. We do know that it is positive, so
  239. // as a temporary solution, until RTCP termination is implemented
  240. // for the audio streams, we relax the packet loss checks here.
  241. if (isMuted) {
  242. packetLoss *= 0.5;
  243. }
  244. }
  245. if (isMuted || !resolution || videoType === VideoType.DESKTOP
  246. || this._timeIceConnected < 0
  247. || this._timeVideoUnmuted < 0) {
  248. // Calculate a value based on packet loss only.
  249. if (packetLoss === undefined) {
  250. logger.error('Cannot calculate connection quality, unknown '
  251. + 'packet loss.');
  252. quality = 100;
  253. } else if (packetLoss <= 2) {
  254. quality = 100; // Full 5 bars.
  255. } else if (packetLoss <= 4) {
  256. quality = 70; // 4 bars
  257. } else if (packetLoss <= 6) {
  258. quality = 50; // 3 bars
  259. } else if (packetLoss <= 8) {
  260. quality = 30; // 2 bars
  261. } else if (packetLoss <= 12) {
  262. quality = 10; // 1 bars
  263. } else {
  264. quality = 0; // Still 1 bar, but slower climb-up.
  265. }
  266. } else {
  267. // Calculate a value based on the send video bitrate on the active TPC.
  268. const activeTPC = this._conference.getActivePeerConnection();
  269. if (activeTPC) {
  270. // Time since sending of video was enabled.
  271. const millisSinceStart = window.performance.now()
  272. - Math.max(this._timeVideoUnmuted, this._timeIceConnected);
  273. const statsInterval = this._options.config?.pcStatsInterval ?? 10000;
  274. // Expected sending bitrate in perfect conditions.
  275. let target = getTarget(
  276. activeTPC.doesTrueSimulcast(),
  277. resolution,
  278. millisSinceStart,
  279. activeTPC.getTargetVideoBitrates());
  280. target = Math.min(target, MAX_TARGET_BITRATE);
  281. // Calculate the quality only after the stats are available (after video was enabled).
  282. if (millisSinceStart > statsInterval) {
  283. quality = 100 * this._localStats.bitrate.upload / target;
  284. }
  285. }
  286. // Whatever the bitrate, drop early if there is significant loss
  287. if (packetLoss && packetLoss >= 10) {
  288. quality = Math.min(quality, 30);
  289. }
  290. }
  291. // Make sure that the quality doesn't climb quickly
  292. if (this._lastConnectionQualityUpdate > 0) {
  293. const maxIncreasePerSecond = 2;
  294. const prevConnectionQuality = this._localStats.connectionQuality;
  295. const diffSeconds = (window.performance.now() - this._lastConnectionQualityUpdate) / 1000;
  296. quality = Math.min(quality, prevConnectionQuality + (diffSeconds * maxIncreasePerSecond));
  297. }
  298. return Math.min(100, quality);
  299. }
  300. /**
  301. * Updates the localConnectionQuality value
  302. * @param values {number} the new value. Should be in [0, 100].
  303. */
  304. _updateLocalConnectionQuality(value) {
  305. this._localStats.connectionQuality = value;
  306. this._lastConnectionQualityUpdate = window.performance.now();
  307. }
  308. /**
  309. * Broadcasts the local statistics to all other participants in the
  310. * conference.
  311. */
  312. _broadcastLocalStats() {
  313. // Send only the data that remote participants care about.
  314. const data = {
  315. bitrate: this._localStats.bitrate,
  316. packetLoss: this._localStats.packetLoss,
  317. connectionQuality: this._localStats.connectionQuality,
  318. jvbRTT: this._localStats.jvbRTT,
  319. serverRegion: this._localStats.serverRegion,
  320. maxEnabledResolution: this._localStats.maxEnabledResolution
  321. };
  322. try {
  323. this._conference.sendEndpointStatsMessage(data);
  324. } catch (err) {
  325. // Ignore the error as we might hit it in the beginning of the call before the channel is ready.
  326. // The statistics will be sent again after few seconds and error is logged elseware as well.
  327. }
  328. }
  329. /**
  330. * Updates the local statistics
  331. * @param {TraceablePeerConnection} tpc the peerconnection which emitted
  332. * the stats
  333. * @param data new statistics
  334. */
  335. _updateLocalStats(tpc, data) {
  336. // Update jvbRTT
  337. if (!tpc.isP2P) {
  338. const jvbRTT
  339. = data.transport
  340. && data.transport.length && data.transport[0].rtt;
  341. this._localStats.jvbRTT = jvbRTT ? jvbRTT : undefined;
  342. }
  343. // Do not continue with processing of other stats if they do not
  344. // originate from the active peerconnection
  345. if (tpc !== this._conference.getActivePeerConnection()) {
  346. return;
  347. }
  348. let key;
  349. const updateLocalConnectionQuality
  350. = !this._conference.isConnectionInterrupted();
  351. const localVideoTrack
  352. = this._conference.getLocalVideoTrack();
  353. const videoType
  354. = localVideoTrack ? localVideoTrack.videoType : undefined;
  355. const isMuted = localVideoTrack ? localVideoTrack.isMuted() : true;
  356. const resolution = localVideoTrack
  357. ? Math.min(localVideoTrack.resolution, localVideoTrack.maxEnabledResolution) : null;
  358. if (!isMuted) {
  359. this._maybeUpdateUnmuteTime();
  360. }
  361. // Copy the fields already in 'data'.
  362. for (key in data) {
  363. if (data.hasOwnProperty(key)) {
  364. this._localStats[key] = data[key];
  365. }
  366. }
  367. // And re-calculate the connectionQuality field.
  368. if (updateLocalConnectionQuality) {
  369. this._updateLocalConnectionQuality(
  370. this._calculateConnectionQuality(
  371. videoType,
  372. isMuted,
  373. resolution));
  374. }
  375. this.eventEmitter.emit(
  376. ConnectionQualityEvents.LOCAL_STATS_UPDATED,
  377. this._localStats);
  378. this._broadcastLocalStats();
  379. }
  380. /**
  381. * Updates remote statistics
  382. * @param id the id of the remote participant
  383. * @param data the statistics received
  384. */
  385. _updateRemoteStats(id, data) {
  386. // Use only the fields we need
  387. this._remoteStats[id] = {
  388. bitrate: data.bitrate,
  389. packetLoss: data.packetLoss,
  390. connectionQuality: data.connectionQuality,
  391. jvbRTT: data.jvbRTT,
  392. serverRegion: data.serverRegion,
  393. maxEnabledResolution: data.maxEnabledResolution
  394. };
  395. this.eventEmitter.emit(
  396. ConnectionQualityEvents.REMOTE_STATS_UPDATED,
  397. id,
  398. this._remoteStats[id]);
  399. }
  400. /**
  401. * Returns the local statistics.
  402. * Exported only for use in jitsi-meet-torture.
  403. */
  404. getStats() {
  405. return this._localStats;
  406. }
  407. }