You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ConnectionQuality.js 19KB

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