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

QualityController.ts 18KB

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