Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

ConnectionQuality.js 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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 < 15000) {
  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. conference.on(
  251. ConferenceEvents.SERVER_REGION_CHANGED,
  252. serverRegion => {
  253. this._localStats.serverRegion = serverRegion;
  254. });
  255. conference.on(
  256. ConferenceEvents.PROPERTIES_CHANGED,
  257. properties => {
  258. this._localStats.bridgeCount
  259. = Number((properties || {})['bridge-count']);
  260. }
  261. );
  262. }
  263. /**
  264. * Sets _timeVideoUnmuted if it was previously unset. If it was already set,
  265. * doesn't change it.
  266. */
  267. _maybeUpdateUnmuteTime() {
  268. if (this._timeVideoUnmuted < 0) {
  269. this._timeVideoUnmuted = window.performance.now();
  270. }
  271. }
  272. /**
  273. * Calculates a new "connection quality" value.
  274. * @param videoType {VideoType} the type of the video source (camera or
  275. * a screen capture).
  276. * @param isMuted {boolean} whether the local video is muted.
  277. * @param resolutionName {Resolution} the input resolution used by the
  278. * camera.
  279. * @returns {*} the newly calculated connection quality.
  280. */
  281. _calculateConnectionQuality(videoType, isMuted, resolutionName) {
  282. // resolutionName is an index into Resolutions (where "720" is
  283. // "1280x720" and "960" is "960x720" ...).
  284. const resolution = Resolutions[resolutionName];
  285. let quality = 100;
  286. let packetLoss;
  287. // TODO: take into account packet loss for received streams
  288. if (this._localStats.packetLoss) {
  289. packetLoss = this._localStats.packetLoss.upload;
  290. // Ugly Hack Alert (UHA):
  291. // The packet loss for the upload direction is calculated based on
  292. // incoming RTCP Receiver Reports. Since we don't have RTCP
  293. // termination for audio, these reports come from the actual
  294. // receivers in the conference and therefore the reported packet
  295. // loss includes loss from the bridge to the receiver.
  296. // When we are sending video this effect is small, because the
  297. // number of video packets is much larger than the number of audio
  298. // packets (and our calculation is based on the total number of
  299. // received and lost packets).
  300. // When video is muted, however, the effect might be significant,
  301. // but we don't know what it is. We do know that it is positive, so
  302. // as a temporary solution, until RTCP termination is implemented
  303. // for the audio streams, we relax the packet loss checks here.
  304. if (isMuted) {
  305. packetLoss *= 0.5;
  306. }
  307. }
  308. if (isMuted || !resolution || videoType === VideoType.DESKTOP
  309. || this._timeIceConnected < 0
  310. || this._timeVideoUnmuted < 0) {
  311. // Calculate a value based on packet loss only.
  312. if (packetLoss === undefined) {
  313. logger.error('Cannot calculate connection quality, unknown '
  314. + 'packet loss.');
  315. quality = 100;
  316. } else if (packetLoss <= 2) {
  317. quality = 100; // Full 5 bars.
  318. } else if (packetLoss <= 4) {
  319. quality = 70; // 4 bars
  320. } else if (packetLoss <= 6) {
  321. quality = 50; // 3 bars
  322. } else if (packetLoss <= 8) {
  323. quality = 30; // 2 bars
  324. } else if (packetLoss <= 12) {
  325. quality = 10; // 1 bars
  326. } else {
  327. quality = 0; // Still 1 bar, but slower climb-up.
  328. }
  329. } else {
  330. // Calculate a value based on the sending bitrate.
  331. // Figure out if simulcast is in use
  332. const activeTPC = this._conference.getActivePeerConnection();
  333. const isSimulcastOn
  334. = Boolean(activeTPC && activeTPC.isSimulcastOn());
  335. const newVideoBitrateCap
  336. = activeTPC && activeTPC.bandwidthLimiter
  337. && activeTPC.bandwidthLimiter.getBandwidthLimit('video');
  338. // If we had a cap set but there isn't one now, then it has
  339. // just been 'lifted', so we should treat this like a new
  340. // ramp up.
  341. if (!newVideoBitrateCap && videoBitrateCap) {
  342. this._timeLastBwCapRemoved = window.performance.now();
  343. // Set the start bitrate to whatever we were just capped to
  344. startBitrate = videoBitrateCap;
  345. }
  346. videoBitrateCap = newVideoBitrateCap;
  347. // time since sending of video was enabled.
  348. const millisSinceStart = window.performance.now()
  349. - Math.max(this._timeVideoUnmuted,
  350. this._timeIceConnected,
  351. this._timeLastBwCapRemoved);
  352. // expected sending bitrate in perfect conditions
  353. let target
  354. = getTarget(isSimulcastOn, resolution, millisSinceStart);
  355. target = Math.min(0.9 * target, MAX_TARGET_BITRATE);
  356. if (videoBitrateCap) {
  357. target = Math.min(target, videoBitrateCap);
  358. }
  359. quality = 100 * this._localStats.bitrate.upload / target;
  360. // Whatever the bitrate, drop early if there is significant loss
  361. if (packetLoss && packetLoss >= 10) {
  362. quality = Math.min(quality, 30);
  363. }
  364. }
  365. // Make sure that the quality doesn't climb quickly
  366. if (this._lastConnectionQualityUpdate > 0) {
  367. const maxIncreasePerSecond = 2;
  368. const prevConnectionQuality = this._localStats.connectionQuality;
  369. const diffSeconds
  370. = (window.performance.now() - this._lastConnectionQualityUpdate)
  371. / 1000;
  372. quality
  373. = Math.min(
  374. quality,
  375. prevConnectionQuality
  376. + (diffSeconds * maxIncreasePerSecond));
  377. }
  378. return Math.min(100, quality);
  379. }
  380. /**
  381. * Updates the localConnectionQuality value
  382. * @param values {number} the new value. Should be in [0, 100].
  383. */
  384. _updateLocalConnectionQuality(value) {
  385. this._localStats.connectionQuality = value;
  386. this._lastConnectionQualityUpdate = window.performance.now();
  387. }
  388. /**
  389. * Broadcasts the local statistics to all other participants in the
  390. * conference.
  391. */
  392. _broadcastLocalStats() {
  393. // Send only the data that remote participants care about.
  394. const data = {
  395. bitrate: this._localStats.bitrate,
  396. packetLoss: this._localStats.packetLoss,
  397. connectionQuality: this._localStats.connectionQuality,
  398. jvbRTT: this._localStats.jvbRTT,
  399. serverRegion: this._localStats.serverRegion
  400. };
  401. try {
  402. this._conference.broadcastEndpointMessage({
  403. type: STATS_MESSAGE_TYPE,
  404. values: data });
  405. } catch (e) {
  406. // We often hit this in the beginning of a call, before the data
  407. // channel is ready. It is not a big problem, because we will
  408. // send the statistics again after a few seconds, and the error is
  409. // already logged elsewhere. So just ignore it.
  410. // let errorMsg = "Failed to broadcast local stats";
  411. // logger.error(errorMsg, e);
  412. // GlobalOnErrorHandler.callErrorHandler(
  413. // new Error(errorMsg + ": " + e));
  414. }
  415. }
  416. /**
  417. * Updates the local statistics
  418. * @param {TraceablePeerConnection} tpc the peerconnection which emitted
  419. * the stats
  420. * @param data new statistics
  421. */
  422. _updateLocalStats(tpc, data) {
  423. // Update jvbRTT
  424. if (!tpc.isP2P) {
  425. const jvbRTT
  426. = data.transport
  427. && data.transport.length && data.transport[0].rtt;
  428. this._localStats.jvbRTT = jvbRTT ? jvbRTT : undefined;
  429. }
  430. // Do not continue with processing of other stats if they do not
  431. // originate from the active peerconnection
  432. if (tpc !== this._conference.getActivePeerConnection()) {
  433. return;
  434. }
  435. let key;
  436. const updateLocalConnectionQuality
  437. = !this._conference.isConnectionInterrupted();
  438. const localVideoTrack
  439. = this._conference.getLocalVideoTrack();
  440. const videoType
  441. = localVideoTrack ? localVideoTrack.videoType : undefined;
  442. const isMuted = localVideoTrack ? localVideoTrack.isMuted() : true;
  443. const resolution = localVideoTrack ? localVideoTrack.resolution : null;
  444. if (!isMuted) {
  445. this._maybeUpdateUnmuteTime();
  446. }
  447. // Copy the fields already in 'data'.
  448. for (key in data) {
  449. if (data.hasOwnProperty(key)) {
  450. this._localStats[key] = data[key];
  451. }
  452. }
  453. // And re-calculate the connectionQuality field.
  454. if (updateLocalConnectionQuality) {
  455. this._updateLocalConnectionQuality(
  456. this._calculateConnectionQuality(
  457. videoType,
  458. isMuted,
  459. resolution));
  460. }
  461. this.eventEmitter.emit(
  462. ConnectionQualityEvents.LOCAL_STATS_UPDATED,
  463. this._localStats);
  464. this._broadcastLocalStats();
  465. }
  466. /**
  467. * Updates remote statistics
  468. * @param id the id of the remote participant
  469. * @param data the statistics received
  470. */
  471. _updateRemoteStats(id, data) {
  472. // Use only the fields we need
  473. this._remoteStats[id] = {
  474. bitrate: data.bitrate,
  475. packetLoss: data.packetLoss,
  476. connectionQuality: data.connectionQuality,
  477. jvbRTT: data.jvbRTT,
  478. serverRegion: data.serverRegion
  479. };
  480. this.eventEmitter.emit(
  481. ConnectionQualityEvents.REMOTE_STATS_UPDATED,
  482. id,
  483. this._remoteStats[id]);
  484. }
  485. /**
  486. * Returns the local statistics.
  487. * Exported only for use in jitsi-meet-torture.
  488. */
  489. getStats() {
  490. return this._localStats;
  491. }
  492. }