Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

ConnectionQuality.js 19KB

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