Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

ConnectionQuality.js 16KB

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