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

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