您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ConnectionQuality.js 15KB

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