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

QualityController.ts 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. import { getLogger } from '@jitsi/logger';
  2. import JitsiConference from '../../JitsiConference';
  3. import { JitsiConferenceEvents } from '../../JitsiConferenceEvents';
  4. import { CodecMimeType } from '../../service/RTC/CodecMimeType';
  5. import RTCEvents from '../../service/RTC/RTCEvents';
  6. import {
  7. DEFAULT_LAST_N,
  8. LAST_N_UNLIMITED,
  9. VIDEO_CODECS_BY_COMPLEXITY,
  10. VIDEO_QUALITY_LEVELS
  11. } from '../../service/RTC/StandardVideoQualitySettings';
  12. import JitsiLocalTrack from '../RTC/JitsiLocalTrack';
  13. import TraceablePeerConnection from '../RTC/TraceablePeerConnection';
  14. import JingleSessionPC from '../xmpp/JingleSessionPC';
  15. import { CodecSelection } from './CodecSelection';
  16. import ReceiveVideoController from './ReceiveVideoController';
  17. import SendVideoController from './SendVideoController';
  18. const logger = getLogger(__filename);
  19. // Period for which the client will wait for the cpu limitation flag to be reset in the peerconnection stats before it
  20. // attempts to rectify the situation by attempting a codec switch.
  21. const LIMITED_BY_CPU_TIMEOUT = 60000;
  22. // The min. value that lastN will be set to while trying to fix video qaulity issues.
  23. const MIN_LAST_N = 3;
  24. enum QualityLimitationReason {
  25. BANDWIDTH = 'bandwidth',
  26. CPU = 'cpu',
  27. NONE = 'none'
  28. }
  29. interface IResolution {
  30. height: number;
  31. width: number;
  32. }
  33. interface IOutboundRtpStats {
  34. codec: CodecMimeType;
  35. encodeTime: number;
  36. qualityLimitationReason: QualityLimitationReason;
  37. resolution: IResolution;
  38. timestamp: number;
  39. }
  40. interface ISourceStats {
  41. avgEncodeTime: number;
  42. codec: CodecMimeType;
  43. encodeResolution: number;
  44. localTrack: JitsiLocalTrack;
  45. qualityLimitationReason: QualityLimitationReason;
  46. timestamp: number;
  47. tpc: TraceablePeerConnection;
  48. }
  49. interface ITrackStats {
  50. encodeResolution: number;
  51. encodeTime: number;
  52. qualityLimitationReason: QualityLimitationReason;
  53. }
  54. interface IVideoConstraints {
  55. maxHeight: number;
  56. sourceName: string;
  57. }
  58. /* eslint-disable require-jsdoc */
  59. export class FixedSizeArray {
  60. private _data: ISourceStats[];
  61. private _maxSize: number;
  62. constructor(size: number) {
  63. this._maxSize = size;
  64. this._data = [];
  65. }
  66. add(item: ISourceStats): void {
  67. if (this._data.length >= this._maxSize) {
  68. this._data.shift();
  69. }
  70. this._data.push(item);
  71. }
  72. get(index: number): ISourceStats | undefined {
  73. if (index < 0 || index >= this._data.length) {
  74. throw new Error('Index out of bounds');
  75. }
  76. return this._data[index];
  77. }
  78. size(): number {
  79. return this._data.length;
  80. }
  81. }
  82. /* eslint-enable require-jsdoc */
  83. /**
  84. * QualityController class that is responsible for maintaining optimal video quality experience on the local endpoint
  85. * by controlling the codec, encode resolution and receive resolution of the remote video streams. It also makes
  86. * adjustments based on the outbound and inbound rtp stream stats reported by the underlying peer connection.
  87. */
  88. export class QualityController {
  89. private _codecController: CodecSelection;
  90. private _conference: JitsiConference;
  91. private _enableAdaptiveMode: boolean;
  92. private _encodeTimeStats: Map<number, FixedSizeArray>;
  93. private _isLastNRampupBlocked: boolean;
  94. private _lastNRampupTime: number;
  95. private _lastNRampupTimeout: number | undefined;
  96. private _limitedByCpuTimeout: number | undefined;
  97. private _receiveVideoController: ReceiveVideoController;
  98. private _sendVideoController: SendVideoController;
  99. /**
  100. *
  101. * @param {JitsiConference} conference - The JitsiConference instance.
  102. * @param {Object} options - video quality settings passed through config.js.
  103. */
  104. constructor(conference: JitsiConference, options: {
  105. enableAdaptiveMode: boolean;
  106. jvb: object;
  107. lastNRampupTime: number;
  108. p2p: object;
  109. }) {
  110. this._conference = conference;
  111. const { jvb, p2p } = options;
  112. this._codecController = new CodecSelection(conference, { jvb,
  113. p2p });
  114. this._enableAdaptiveMode = options.enableAdaptiveMode;
  115. this._encodeTimeStats = new Map();
  116. this._isLastNRampupBlocked = false;
  117. this._lastNRampupTime = options.lastNRampupTime;
  118. this._receiveVideoController = new ReceiveVideoController(conference);
  119. this._sendVideoController = new SendVideoController(conference);
  120. this._conference.on(
  121. JitsiConferenceEvents._MEDIA_SESSION_STARTED,
  122. (session: JingleSessionPC) => {
  123. this._codecController.selectPreferredCodec(session);
  124. this._receiveVideoController.onMediaSessionStarted(session);
  125. this._sendVideoController.onMediaSessionStarted(session);
  126. });
  127. this._conference.on(
  128. JitsiConferenceEvents._MEDIA_SESSION_ACTIVE_CHANGED,
  129. () => this._sendVideoController.configureConstraintsForLocalSources());
  130. this._conference.on(
  131. JitsiConferenceEvents.CONFERENCE_VISITOR_CODECS_CHANGED,
  132. (codecList: CodecMimeType[]) => this._codecController.updateVisitorCodecs(codecList));
  133. // Debounce the calls to codec selection when there is a burst of joins and leaves.
  134. const debouncedSelectCodec = this._debounce(
  135. () => this._codecController.selectPreferredCodec(this._conference.jvbJingleSession),
  136. 1000);
  137. this._conference.on(JitsiConferenceEvents.USER_JOINED, debouncedSelectCodec.bind(this));
  138. this._conference.on(JitsiConferenceEvents.USER_LEFT, debouncedSelectCodec.bind(this));
  139. this._conference.rtc.on(
  140. RTCEvents.SENDER_VIDEO_CONSTRAINTS_CHANGED,
  141. (videoConstraints: IVideoConstraints) =>
  142. this._sendVideoController.onSenderConstraintsReceived(videoConstraints));
  143. this._conference.on(
  144. JitsiConferenceEvents.ENCODE_TIME_STATS_RECEIVED,
  145. (tpc: TraceablePeerConnection, stats: Map<number, IOutboundRtpStats>) =>
  146. this._processOutboundRtpStats(tpc, stats));
  147. }
  148. /**
  149. * Creates a debounced function that delays the execution of the provided function until after the specified delay
  150. * has elapsed. Unlike typical debounce implementations, the timer does not reset when the function is called again
  151. * within the delay period.
  152. *
  153. * @param {Function} func - The function to be debounced.
  154. * @param {number} delay - The delay in milliseconds.
  155. * @returns {Function} - The debounced function.
  156. */
  157. _debounce(func: Function, delay: number) { // eslint-disable-line @typescript-eslint/no-unsafe-function-type
  158. return function(...args: any) {
  159. /* eslint-disable @typescript-eslint/no-invalid-this */
  160. if (!this._timer) {
  161. this._timer = setTimeout(() => {
  162. this._timer = null;
  163. func.apply(this, args);
  164. }, delay);
  165. }
  166. /* eslint-enable @typescript-eslint/no-invalid-this */
  167. };
  168. }
  169. /**
  170. * Adjusts the lastN value so that fewer remote video sources are received from the bridge in an attempt to improve
  171. * encode resolution of the outbound video streams based on cpuLimited parameter passed. If cpuLimited is false,
  172. * the lastN value will slowly be ramped back up to the channelLastN value set in config.js.
  173. *
  174. * @param {boolean} cpuLimited - whether the endpoint is cpu limited or not.
  175. * @returns boolean - Returns true if an action was taken, false otherwise.
  176. */
  177. _lowerOrRaiseLastN(cpuLimited: boolean): boolean {
  178. const lastN = this.receiveVideoController.getLastN();
  179. let newLastN = lastN;
  180. if (cpuLimited && (lastN !== LAST_N_UNLIMITED && lastN <= MIN_LAST_N)) {
  181. return false;
  182. }
  183. // If channelLastN is not set or set to -1 in config.js, the client will ramp up lastN to only up to 25.
  184. let { channelLastN = DEFAULT_LAST_N } = this._conference.options.config;
  185. channelLastN = channelLastN === LAST_N_UNLIMITED ? DEFAULT_LAST_N : channelLastN;
  186. if (cpuLimited) {
  187. const videoStreamsReceived = this._conference.getForwardedSources().length;
  188. newLastN = Math.floor(videoStreamsReceived / 2);
  189. if (newLastN < MIN_LAST_N) {
  190. newLastN = MIN_LAST_N;
  191. }
  192. // Increment lastN by 1 every LAST_N_RAMPUP_TIME (60) secs.
  193. } else if (lastN < channelLastN) {
  194. newLastN++;
  195. }
  196. if (newLastN === lastN) {
  197. return false;
  198. }
  199. const isStillLimitedByCpu = newLastN < channelLastN;
  200. this.receiveVideoController.setLastNLimitedByCpu(isStillLimitedByCpu);
  201. logger.info(`QualityController - setting lastN=${newLastN}, limitedByCpu=${isStillLimitedByCpu}`);
  202. this.receiveVideoController.setLastN(newLastN);
  203. return true;
  204. }
  205. /**
  206. * Adjusts the requested resolution for remote video sources by updating the receiver constraints in an attempt to
  207. * improve the encode resolution of the outbound video streams.
  208. * @return {void}
  209. */
  210. _maybeLowerReceiveResolution(): void {
  211. const currentConstraints = this.receiveVideoController.getCurrentReceiverConstraints();
  212. const individualConstraints = currentConstraints.constraints;
  213. let maxHeight = 0;
  214. if (individualConstraints && Object.keys(individualConstraints).length) {
  215. for (const value of Object.values(individualConstraints)) {
  216. const v: any = value;
  217. maxHeight = Math.max(maxHeight, v.maxHeight);
  218. }
  219. }
  220. const currentLevel = VIDEO_QUALITY_LEVELS.findIndex(lvl => lvl.height <= maxHeight);
  221. // Do not lower the resolution to less than 180p.
  222. if (VIDEO_QUALITY_LEVELS[currentLevel].height === 180) {
  223. return;
  224. }
  225. this.receiveVideoController.setPreferredReceiveMaxFrameHeight(VIDEO_QUALITY_LEVELS[currentLevel + 1].height);
  226. }
  227. /**
  228. * Updates the codec preference order for the local endpoint on the active media session and switches the video
  229. * codec if needed.
  230. *
  231. * @param {number} trackId - The track ID of the local video track for which stats have been captured.
  232. * @returns {boolean} - Returns true if video codec was changed.
  233. */
  234. _maybeSwitchVideoCodec(trackId: number): boolean {
  235. const stats = this._encodeTimeStats.get(trackId);
  236. const { codec, encodeResolution, localTrack } = stats.get(stats.size() - 1);
  237. const codecsByVideoType = VIDEO_CODECS_BY_COMPLEXITY[localTrack.getVideoType()];
  238. const codecIndex = codecsByVideoType.findIndex(val => val === codec.toLowerCase());
  239. // Do nothing if the encoder is using the lowest complexity codec already.
  240. if (codecIndex === codecsByVideoType.length - 1) {
  241. return false;
  242. }
  243. if (!this._limitedByCpuTimeout) {
  244. this._limitedByCpuTimeout = window.setTimeout(() => {
  245. this._limitedByCpuTimeout = undefined;
  246. const updatedStats = this._encodeTimeStats.get(trackId);
  247. const latestSourceStats: ISourceStats = updatedStats.get(updatedStats.size() - 1);
  248. const expectedSendResolution
  249. = Math.min(localTrack.maxEnabledResolution, localTrack.getCaptureResolution());
  250. // If the encoder is still limited by CPU, switch to a lower complexity codec.
  251. if (latestSourceStats.qualityLimitationReason === QualityLimitationReason.CPU
  252. || encodeResolution < expectedSendResolution) {
  253. return this.codecController.changeCodecPreferenceOrder(localTrack, codec);
  254. }
  255. }, LIMITED_BY_CPU_TIMEOUT);
  256. }
  257. return false;
  258. }
  259. /**
  260. * Adjusts codec, lastN or receive resolution based on the send resolution (of the outbound streams) and limitation
  261. * reported by the browser in the WebRTC stats. Recovery is also attempted if the limitation goes away. No action
  262. * is taken if the adaptive mode has been disabled through config.js.
  263. *
  264. * @param {ISourceStats} sourceStats - The outbound-rtp stats for a local video track.
  265. * @returns {void}
  266. */
  267. _performQualityOptimizations(sourceStats: ISourceStats): void {
  268. // Do not attempt run time adjustments if the adaptive mode is disabled.
  269. if (!this._enableAdaptiveMode) {
  270. return;
  271. }
  272. const { encodeResolution, localTrack, qualityLimitationReason, tpc } = sourceStats;
  273. // Older browser versions might not report the resolution in the stats.
  274. if (Number.isNaN(encodeResolution)) {
  275. return;
  276. }
  277. const trackId = localTrack.rtcId;
  278. if (encodeResolution === tpc.calculateExpectedSendResolution(localTrack)) {
  279. if (this._limitedByCpuTimeout) {
  280. window.clearTimeout(this._limitedByCpuTimeout);
  281. this._limitedByCpuTimeout = undefined;
  282. }
  283. if (qualityLimitationReason === QualityLimitationReason.NONE
  284. && this.receiveVideoController.isLastNLimitedByCpu()) {
  285. if (!this._lastNRampupTimeout && !this._isLastNRampupBlocked) {
  286. // Ramp up the number of received videos if CPU limitation no longer exists. If the cpu
  287. // limitation returns as a consequence, do not attempt to ramp up again, continue to
  288. // increment the lastN value otherwise until it is equal to the channelLastN value.
  289. this._lastNRampupTimeout = window.setTimeout(() => {
  290. this._lastNRampupTimeout = undefined;
  291. const updatedStats = this._encodeTimeStats.get(trackId);
  292. const latestSourceStats: ISourceStats = updatedStats.get(updatedStats.size() - 1);
  293. if (latestSourceStats.qualityLimitationReason === QualityLimitationReason.CPU) {
  294. this._isLastNRampupBlocked = true;
  295. } else {
  296. this._lowerOrRaiseLastN(false /* raise */);
  297. }
  298. }, this._lastNRampupTime);
  299. }
  300. }
  301. return;
  302. }
  303. // Do nothing if the limitation reason is bandwidth since the browser will dynamically adapt the outbound
  304. // resolution based on available uplink bandwith. Otherwise,
  305. // 1. Switch the codec to the lowest complexity one incrementally.
  306. // 2. Switch to a lower lastN value, cutting the receive videos by half in every iteration until
  307. // MIN_LAST_N value is reached.
  308. // 3. Lower the receive resolution of individual streams up to 180p.
  309. if (qualityLimitationReason === QualityLimitationReason.CPU) {
  310. if (this._lastNRampupTimeout) {
  311. window.clearTimeout(this._lastNRampupTimeout);
  312. this._lastNRampupTimeout = undefined;
  313. this._isLastNRampupBlocked = true;
  314. }
  315. const codecSwitched = this._maybeSwitchVideoCodec(trackId);
  316. if (!codecSwitched && !this._limitedByCpuTimeout) {
  317. const lastNChanged = this._lowerOrRaiseLastN(true /* lower */);
  318. if (!lastNChanged) {
  319. this.receiveVideoController.setReceiveResolutionLimitedByCpu(true);
  320. this._maybeLowerReceiveResolution();
  321. }
  322. }
  323. }
  324. }
  325. /**
  326. * Processes the outbound RTP stream stats as reported by the WebRTC peerconnection and makes runtime adjustments
  327. * to the client for better quality experience if the adaptive mode is enabled.
  328. *
  329. * @param {TraceablePeerConnection} tpc - The underlying WebRTC peerconnection where stats have been captured.
  330. * @param {Map<number, IOutboundRtpStats>} stats - Outbound-rtp stream stats per SSRC.
  331. * @returns void
  332. */
  333. _processOutboundRtpStats(tpc: TraceablePeerConnection, stats: Map<number, IOutboundRtpStats>): void {
  334. const activeSession = this._conference.getActiveMediaSession();
  335. // Process stats only for the active media session.
  336. if (activeSession.peerconnection !== tpc) {
  337. return;
  338. }
  339. const statsPerTrack = new Map();
  340. for (const ssrc of stats.keys()) {
  341. const { codec, encodeTime, qualityLimitationReason, resolution, timestamp } = stats.get(ssrc);
  342. const track = tpc.getTrackBySSRC(ssrc);
  343. const trackId = track.rtcId;
  344. let existingStats = statsPerTrack.get(trackId);
  345. const encodeResolution = Math.min(resolution?.height, resolution?.width);
  346. const ssrcStats = {
  347. encodeResolution,
  348. encodeTime,
  349. qualityLimitationReason
  350. };
  351. if (existingStats) {
  352. existingStats.codec = codec;
  353. existingStats.timestamp = timestamp;
  354. existingStats.trackStats.push(ssrcStats);
  355. } else {
  356. existingStats = {
  357. codec,
  358. timestamp,
  359. trackStats: [ ssrcStats ]
  360. };
  361. statsPerTrack.set(trackId, existingStats);
  362. }
  363. }
  364. // Aggregate the stats for multiple simulcast streams with different SSRCs but for the same video stream.
  365. for (const trackId of statsPerTrack.keys()) {
  366. const { codec, timestamp, trackStats } = statsPerTrack.get(trackId);
  367. const totalEncodeTime = trackStats
  368. .map((stat: ITrackStats) => stat.encodeTime)
  369. .reduce((totalValue: number, currentValue: number) => totalValue + currentValue, 0);
  370. const avgEncodeTime: number = totalEncodeTime / trackStats.length;
  371. const { qualityLimitationReason = QualityLimitationReason.NONE }
  372. = trackStats
  373. .find((stat: ITrackStats) => stat.qualityLimitationReason !== QualityLimitationReason.NONE) ?? {};
  374. const encodeResolution: number = trackStats
  375. .map((stat: ITrackStats) => stat.encodeResolution)
  376. .reduce((resolution: number, currentValue: number) => Math.max(resolution, currentValue), 0);
  377. const localTrack = this._conference.getLocalVideoTracks().find(t => t.rtcId === trackId);
  378. const exisitingStats: FixedSizeArray = this._encodeTimeStats.get(trackId);
  379. const sourceStats = {
  380. avgEncodeTime,
  381. codec,
  382. encodeResolution,
  383. qualityLimitationReason,
  384. localTrack,
  385. timestamp,
  386. tpc
  387. };
  388. if (exisitingStats) {
  389. exisitingStats.add(sourceStats);
  390. } else {
  391. // Save stats for only the last 5 mins.
  392. const data = new FixedSizeArray(300);
  393. data.add(sourceStats);
  394. this._encodeTimeStats.set(trackId, data);
  395. }
  396. logger.debug(`Encode stats for ${localTrack}: codec=${codec}, time=${avgEncodeTime},`
  397. + `resolution=${encodeResolution}, qualityLimitationReason=${qualityLimitationReason}`);
  398. this._performQualityOptimizations(sourceStats);
  399. }
  400. }
  401. /**
  402. * Gets the codec controller instance.
  403. */
  404. get codecController() {
  405. return this._codecController;
  406. }
  407. /**
  408. * Gets the receive video controller instance.
  409. */
  410. get receiveVideoController() {
  411. return this._receiveVideoController;
  412. }
  413. /**
  414. * Gets the send video controller instance.
  415. */
  416. get sendVideoController() {
  417. return this._sendVideoController;
  418. }
  419. }