Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

ConnectionQuality.js 17KB

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