Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

ConnectionQuality.js 18KB

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