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

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