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 17KB

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