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

ConnectionQuality.js 18KB

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