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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. /**
  134. *
  135. * @param conference
  136. * @param eventEmitter
  137. * @param options
  138. */
  139. constructor(conference, eventEmitter, options) {
  140. this.eventEmitter = eventEmitter;
  141. /**
  142. * The owning JitsiConference.
  143. */
  144. this._conference = conference;
  145. /**
  146. * Whether simulcast is supported. Note that even if supported, it is
  147. * currently not used for screensharing.
  148. */
  149. this._simulcast
  150. = !options.disableSimulcast && RTCBrowserType.supportsSimulcast();
  151. /**
  152. * Holds statistics about the local connection quality.
  153. */
  154. this._localStats = { connectionQuality: 100 };
  155. /**
  156. * The time this._localStats.connectionQuality was last updated.
  157. */
  158. this._lastConnectionQualityUpdate = -1;
  159. /**
  160. * Maps a participant ID to an object holding connection quality
  161. * statistics received from this participant.
  162. */
  163. this._remoteStats = {};
  164. /**
  165. * The time that the ICE state last changed to CONNECTED. We use this
  166. * to calculate how much time we as a sender have had to ramp-up.
  167. */
  168. this._timeIceConnected = -1;
  169. /**
  170. * The time that local video was unmuted. We use this to calculate how
  171. * much time we as a sender have had to ramp-up.
  172. */
  173. this._timeVideoUnmuted = -1;
  174. // We assume a global startBitrate value for the sake of simplicity.
  175. if (options.startBitrate && options.startBitrate > 0) {
  176. startBitrate = options.startBitrate;
  177. }
  178. // TODO: consider ignoring these events and letting the user of
  179. // lib-jitsi-meet handle these separately.
  180. conference.on(
  181. ConferenceEvents.CONNECTION_INTERRUPTED,
  182. () => {
  183. this._updateLocalConnectionQuality(0);
  184. this.eventEmitter.emit(
  185. ConnectionQualityEvents.LOCAL_STATS_UPDATED,
  186. this._localStats);
  187. this._broadcastLocalStats();
  188. });
  189. conference.room.addListener(
  190. XMPPEvents.ICE_CONNECTION_STATE_CHANGED,
  191. (jingleSession, newState) => {
  192. if (!jingleSession.isP2P && newState === 'connected') {
  193. this._timeIceConnected = window.performance.now();
  194. }
  195. });
  196. // Listen to DataChannel message from other participants in the
  197. // conference, and update the _remoteStats field accordingly.
  198. conference.on(
  199. ConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  200. (participant, payload) => {
  201. if (payload.type === STATS_MESSAGE_TYPE) {
  202. this._updateRemoteStats(
  203. participant.getId(), payload.values);
  204. }
  205. });
  206. // Listen to local statistics events originating from the RTC module
  207. // and update the _localStats field.
  208. // Oh, and by the way, the resolutions of all remote participants are
  209. // also piggy-backed in these "local" statistics. It's obvious, really,
  210. // if one carefully reads the *code* (but not the docs) in
  211. // UI/VideoLayout/VideoLayout.js#updateLocalConnectionStats in
  212. // jitsi-meet
  213. // TODO: We should keep track of the remote resolution in _remoteStats,
  214. // and notify about changes via separate events.
  215. conference.on(
  216. ConferenceEvents.CONNECTION_STATS,
  217. this._updateLocalStats.bind(this));
  218. // Save the last time we were unmuted.
  219. conference.on(
  220. ConferenceEvents.TRACK_MUTE_CHANGED,
  221. track => {
  222. if (track.isVideoTrack()) {
  223. if (track.isMuted()) {
  224. this._timeVideoUnmuted = -1;
  225. } else {
  226. this._maybeUpdateUnmuteTime();
  227. }
  228. }
  229. });
  230. conference.on(
  231. ConferenceEvents.TRACK_ADDED,
  232. track => {
  233. if (track.isVideoTrack() && !track.isMuted()) {
  234. this._maybeUpdateUnmuteTime();
  235. }
  236. });
  237. }
  238. /**
  239. * Sets _timeVideoUnmuted if it was previously unset. If it was already set,
  240. * doesn't change it.
  241. */
  242. _maybeUpdateUnmuteTime() {
  243. if (this._timeVideoUnmuted < 0) {
  244. this._timeVideoUnmuted = window.performance.now();
  245. }
  246. }
  247. /**
  248. * Calculates a new "connection quality" value.
  249. * @param videoType {VideoType} the type of the video source (camera or
  250. * a screen capture).
  251. * @param isMuted {boolean} whether the local video is muted.
  252. * @param resolutionName {Resolution} the input resolution used by the
  253. * camera.
  254. * @returns {*} the newly calculated connection quality.
  255. */
  256. _calculateConnectionQuality(videoType, isMuted, resolutionName) {
  257. // resolutionName is an index into Resolutions (where "720" is
  258. // "1280x720" and "960" is "960x720" ...).
  259. const resolution = Resolutions[resolutionName];
  260. let quality = 100;
  261. let packetLoss;
  262. // TODO: take into account packet loss for received streams
  263. if (this._localStats.packetLoss) {
  264. packetLoss = this._localStats.packetLoss.upload;
  265. // Ugly Hack Alert (UHA):
  266. // The packet loss for the upload direction is calculated based on
  267. // incoming RTCP Receiver Reports. Since we don't have RTCP
  268. // termination for audio, these reports come from the actual
  269. // receivers in the conference and therefore the reported packet
  270. // loss includes loss from the bridge to the receiver.
  271. // When we are sending video this effect is small, because the
  272. // number of video packets is much larger than the number of audio
  273. // packets (and our calculation is based on the total number of
  274. // received and lost packets).
  275. // When video is muted, however, the effect might be significant,
  276. // but we don't know what it is. We do know that it is positive, so
  277. // as a temporary solution, until RTCP termination is implemented
  278. // for the audio streams, we relax the packet loss checks here.
  279. if (isMuted) {
  280. packetLoss *= 0.5;
  281. }
  282. }
  283. if (isMuted || !resolution || videoType === VideoType.DESKTOP
  284. || this._timeIceConnected < 0
  285. || this._timeVideoUnmuted < 0) {
  286. // Calculate a value based on packet loss only.
  287. if (packetLoss === undefined) {
  288. logger.error('Cannot calculate connection quality, unknown '
  289. + 'packet loss.');
  290. quality = 100;
  291. } else if (packetLoss <= 2) {
  292. quality = 100; // Full 5 bars.
  293. } else if (packetLoss <= 4) {
  294. quality = 70; // 4 bars
  295. } else if (packetLoss <= 6) {
  296. quality = 50; // 3 bars
  297. } else if (packetLoss <= 8) {
  298. quality = 30; // 2 bars
  299. } else if (packetLoss <= 12) {
  300. quality = 10; // 1 bars
  301. } else {
  302. quality = 0; // Still 1 bar, but slower climb-up.
  303. }
  304. } else {
  305. // Calculate a value based on the sending bitrate.
  306. // time since sending of video was enabled.
  307. const millisSinceStart = window.performance.now()
  308. - Math.max(this._timeVideoUnmuted, this._timeIceConnected);
  309. // expected sending bitrate in perfect conditions
  310. let target
  311. = getTarget(this._simulcast, resolution, millisSinceStart);
  312. target = 0.9 * target;
  313. quality = 100 * this._localStats.bitrate.upload / target;
  314. // Whatever the bitrate, drop early if there is significant loss
  315. if (packetLoss && packetLoss >= 10) {
  316. quality = Math.min(quality, 30);
  317. }
  318. }
  319. // Make sure that the quality doesn't climb quickly
  320. if (this._lastConnectionQualityUpdate > 0) {
  321. const maxIncreasePerSecond = 2;
  322. const prevConnectionQuality = this._localStats.connectionQuality;
  323. const diffSeconds
  324. = (window.performance.now() - this._lastConnectionQualityUpdate)
  325. / 1000;
  326. quality
  327. = Math.min(
  328. quality,
  329. prevConnectionQuality
  330. + (diffSeconds * maxIncreasePerSecond));
  331. }
  332. return Math.min(100, quality);
  333. }
  334. /**
  335. * Updates the localConnectionQuality value
  336. * @param values {number} the new value. Should be in [0, 100].
  337. */
  338. _updateLocalConnectionQuality(value) {
  339. this._localStats.connectionQuality = value;
  340. this._lastConnectionQualityUpdate = window.performance.now();
  341. }
  342. /**
  343. * Broadcasts the local statistics to all other participants in the
  344. * conference.
  345. */
  346. _broadcastLocalStats() {
  347. // Send only the data that remote participants care about.
  348. const data = {
  349. bitrate: this._localStats.bitrate,
  350. packetLoss: this._localStats.packetLoss,
  351. connectionQuality: this._localStats.connectionQuality
  352. };
  353. // TODO: It looks like the remote participants don't really "care"
  354. // about the resolution, and they look at their local rendered
  355. // resolution instead. Consider removing this.
  356. const localVideoTrack
  357. = this._conference.getLocalVideoTrack();
  358. if (localVideoTrack && localVideoTrack.resolution) {
  359. data.resolution = localVideoTrack.resolution;
  360. }
  361. try {
  362. this._conference.broadcastEndpointMessage({
  363. type: STATS_MESSAGE_TYPE,
  364. values: data });
  365. } catch (e) {
  366. // We often hit this in the beginning of a call, before the data
  367. // channel is ready. It is not a big problem, because we will
  368. // send the statistics again after a few seconds, and the error is
  369. // already logged elsewhere. So just ignore it.
  370. // let errorMsg = "Failed to broadcast local stats";
  371. // logger.error(errorMsg, e);
  372. // GlobalOnErrorHandler.callErrorHandler(
  373. // new Error(errorMsg + ": " + e));
  374. }
  375. }
  376. /**
  377. * Updates the local statistics
  378. * @param data new statistics
  379. */
  380. _updateLocalStats(data) {
  381. let key;
  382. const updateLocalConnectionQuality
  383. = !this._conference.isConnectionInterrupted();
  384. const localVideoTrack
  385. = this._conference.getLocalVideoTrack();
  386. const videoType
  387. = localVideoTrack ? localVideoTrack.videoType : undefined;
  388. const isMuted = localVideoTrack ? localVideoTrack.isMuted() : true;
  389. const resolution = localVideoTrack ? localVideoTrack.resolution : null;
  390. if (!isMuted) {
  391. this._maybeUpdateUnmuteTime();
  392. }
  393. // Copy the fields already in 'data'.
  394. for (key in data) {
  395. if (data.hasOwnProperty(key)) {
  396. this._localStats[key] = data[key];
  397. }
  398. }
  399. // And re-calculate the connectionQuality field.
  400. if (updateLocalConnectionQuality) {
  401. this._updateLocalConnectionQuality(
  402. this._calculateConnectionQuality(
  403. videoType,
  404. isMuted,
  405. resolution));
  406. }
  407. this.eventEmitter.emit(
  408. ConnectionQualityEvents.LOCAL_STATS_UPDATED,
  409. this._localStats);
  410. this._broadcastLocalStats();
  411. }
  412. /**
  413. * Updates remote statistics
  414. * @param id the id of the remote participant
  415. * @param data the statistics received
  416. */
  417. _updateRemoteStats(id, data) {
  418. // Use only the fields we need
  419. this._remoteStats[id] = {
  420. bitrate: data.bitrate,
  421. packetLoss: data.packetLoss,
  422. connectionQuality: data.connectionQuality
  423. };
  424. this.eventEmitter.emit(
  425. ConnectionQualityEvents.REMOTE_STATS_UPDATED,
  426. id,
  427. this._remoteStats[id]);
  428. }
  429. /**
  430. * Returns the local statistics.
  431. * Exported only for use in jitsi-meet-torture.
  432. */
  433. getStats() {
  434. return this._localStats;
  435. }
  436. }