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

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