Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

ConnectionQuality.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. }
  228. if (isMuted || !resolution || videoType === VideoType.DESKTOP
  229. || this._timeIceConnected < 0
  230. || this._timeVideoUnmuted < 0) {
  231. // Calculate a value based on packet loss only.
  232. if (packetLoss === undefined) {
  233. logger.error('Cannot calculate connection quality, unknown '
  234. + 'packet loss.');
  235. quality = 100;
  236. } else if (packetLoss <= 2) {
  237. quality = 100; // Full 5 bars.
  238. } else if (packetLoss <= 4) {
  239. quality = 70; // 4 bars
  240. } else if (packetLoss <= 6) {
  241. quality = 50; // 3 bars
  242. } else if (packetLoss <= 8) {
  243. quality = 30; // 2 bars
  244. } else if (packetLoss <= 12) {
  245. quality = 10; // 1 bars
  246. } else {
  247. quality = 0; // Still 1 bar, but slower climb-up.
  248. }
  249. } else {
  250. // Calculate a value based on the send video bitrate on the active TPC.
  251. const activeTPC = this._conference.getActivePeerConnection();
  252. if (activeTPC) {
  253. // Time since sending of video was enabled.
  254. const millisSinceStart = window.performance.now()
  255. - Math.max(this._timeVideoUnmuted, this._timeIceConnected);
  256. const statsInterval = this._options.config?.pcStatsInterval ?? 10000;
  257. // Expected sending bitrate in perfect conditions.
  258. let target = getTarget(
  259. activeTPC.doesTrueSimulcast(),
  260. resolution,
  261. millisSinceStart,
  262. activeTPC.getTargetVideoBitrates());
  263. target = Math.min(target, MAX_TARGET_BITRATE);
  264. // Calculate the quality only after the stats are available (after video was enabled).
  265. if (millisSinceStart > statsInterval) {
  266. quality = 100 * this._localStats.bitrate.upload / target;
  267. }
  268. }
  269. // Whatever the bitrate, drop early if there is significant loss
  270. if (packetLoss && packetLoss >= 10) {
  271. quality = Math.min(quality, 30);
  272. }
  273. }
  274. // Make sure that the quality doesn't climb quickly
  275. if (this._lastConnectionQualityUpdate > 0) {
  276. const maxIncreasePerSecond = 2;
  277. const prevConnectionQuality = this._localStats.connectionQuality;
  278. const diffSeconds = (window.performance.now() - this._lastConnectionQualityUpdate) / 1000;
  279. quality = Math.min(quality, prevConnectionQuality + (diffSeconds * maxIncreasePerSecond));
  280. }
  281. return Math.min(100, quality);
  282. }
  283. /**
  284. * Updates the localConnectionQuality value
  285. * @param values {number} the new value. Should be in [0, 100].
  286. */
  287. _updateLocalConnectionQuality(value) {
  288. this._localStats.connectionQuality = value;
  289. this._lastConnectionQualityUpdate = window.performance.now();
  290. }
  291. /**
  292. * Broadcasts the local statistics to all other participants in the
  293. * conference.
  294. */
  295. _broadcastLocalStats() {
  296. // Send only the data that remote participants care about.
  297. const data = {
  298. bitrate: this._localStats.bitrate,
  299. packetLoss: this._localStats.packetLoss,
  300. connectionQuality: this._localStats.connectionQuality,
  301. jvbRTT: this._localStats.jvbRTT,
  302. serverRegion: this._localStats.serverRegion,
  303. maxEnabledResolution: this._localStats.maxEnabledResolution
  304. };
  305. try {
  306. this._conference.sendEndpointStatsMessage(data);
  307. } catch (err) {
  308. // Ignore the error as we might hit it in the beginning of the call before the channel is ready.
  309. // The statistics will be sent again after few seconds and error is logged elseware as well.
  310. }
  311. }
  312. /**
  313. * Updates the local statistics
  314. * @param {TraceablePeerConnection} tpc the peerconnection which emitted
  315. * the stats
  316. * @param data new statistics
  317. */
  318. _updateLocalStats(tpc, data) {
  319. // Update jvbRTT
  320. if (!tpc.isP2P) {
  321. const jvbRTT
  322. = data.transport
  323. && data.transport.length && data.transport[0].rtt;
  324. this._localStats.jvbRTT = jvbRTT ? jvbRTT : undefined;
  325. }
  326. // Do not continue with processing of other stats if they do not
  327. // originate from the active peerconnection
  328. if (tpc !== this._conference.getActivePeerConnection()) {
  329. return;
  330. }
  331. let key;
  332. const updateLocalConnectionQuality
  333. = !this._conference.isConnectionInterrupted();
  334. const localVideoTrack
  335. = this._conference.getLocalVideoTrack();
  336. const videoType
  337. = localVideoTrack ? localVideoTrack.videoType : undefined;
  338. const isMuted = localVideoTrack ? localVideoTrack.isMuted() : true;
  339. const resolution = localVideoTrack
  340. ? Math.min(localVideoTrack.resolution, localVideoTrack.maxEnabledResolution) : null;
  341. if (!isMuted) {
  342. this._maybeUpdateUnmuteTime();
  343. }
  344. // Copy the fields already in 'data'.
  345. for (key in data) {
  346. if (data.hasOwnProperty(key)) {
  347. this._localStats[key] = data[key];
  348. }
  349. }
  350. // And re-calculate the connectionQuality field.
  351. if (updateLocalConnectionQuality) {
  352. this._updateLocalConnectionQuality(
  353. this._calculateConnectionQuality(
  354. videoType,
  355. isMuted,
  356. resolution));
  357. }
  358. this.eventEmitter.emit(
  359. ConnectionQualityEvents.LOCAL_STATS_UPDATED,
  360. this._localStats);
  361. this._broadcastLocalStats();
  362. }
  363. /**
  364. * Updates remote statistics
  365. * @param id the id of the remote participant
  366. * @param data the statistics received
  367. */
  368. _updateRemoteStats(id, data) {
  369. // Use only the fields we need
  370. this._remoteStats[id] = {
  371. bitrate: data.bitrate,
  372. packetLoss: data.packetLoss,
  373. connectionQuality: data.connectionQuality,
  374. jvbRTT: data.jvbRTT,
  375. serverRegion: data.serverRegion,
  376. maxEnabledResolution: data.maxEnabledResolution
  377. };
  378. this.eventEmitter.emit(
  379. ConnectionQualityEvents.REMOTE_STATS_UPDATED,
  380. id,
  381. this._remoteStats[id]);
  382. }
  383. /**
  384. * Returns the local statistics.
  385. * Exported only for use in jitsi-meet-torture.
  386. */
  387. getStats() {
  388. return this._localStats;
  389. }
  390. }