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

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