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

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