/src/faac/libfaac/ratecontrol.c
Line | Count | Source |
1 | | /* |
2 | | * FAAC - Freeware Advanced Audio Coder |
3 | | * Copyright (C) 2003-2017 Krzysztof Nikiel |
4 | | * Copyright (C) 2026 Nils Schimmelmann |
5 | | * |
6 | | * This library is free software; you can redistribute it and/or |
7 | | * modify it under the terms of the GNU Lesser General Public |
8 | | * License as published by the Free Software Foundation; either |
9 | | * version 2.1 of the License, or (at your option) any later version. |
10 | | * |
11 | | * This library is distributed in the hope that it will be useful, |
12 | | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
13 | | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
14 | | * Lesser General Public License for more details. |
15 | | */ |
16 | | |
17 | | #include <math.h> |
18 | | #include <stdint.h> |
19 | | |
20 | | #include "ratecontrol.h" |
21 | | #include "coder.h" |
22 | | #include "quantize.h" |
23 | | #include "stats.h" |
24 | | |
25 | 6.68k | #define RC_DAMPING_FACTOR 0.6f /* Control loop damping */ |
26 | | |
27 | | /* AIM banks against slightly under the nominal frame budget, so the average |
28 | | * comes out a ceiling rather than a midpoint. AMORT spreads the balance over |
29 | | * that many frames; it trades bitrate accuracy against coding efficiency and is |
30 | | * the dominant lever here. Bitrate error alone cannot see efficiency, and ranks |
31 | | * this arm behind alternatives that simply spend more bits. */ |
32 | 6.68k | #define RC_BALANCE_AIM 0.99f |
33 | 7.96k | #define RC_BALANCE_AMORT 32 |
34 | | |
35 | | /* How far the account may run in either direction, in frames of budget. |
36 | | * Symmetric on purpose: capacity is only two frames, so bounding one side |
37 | | * tighter leaves the arm biased toward the side it still remembers. */ |
38 | 6.68k | #define RC_BALANCE_FRAMES 4 |
39 | | |
40 | | /* Time constant of the SBR payload average, as a right shift: 1/16 per frame, |
41 | | so ~16 frames (0.37 s at 48 kHz). Long enough to average out the payload's |
42 | | frame-to-frame swing, short enough to follow a real change in content. */ |
43 | 13.3k | #define RC_SBR_EWMA_SHIFT 4 |
44 | | |
45 | | /* Opening fill of the reservoir, as a fraction of capacity: full lets a stream |
46 | | end that many bits over budget, empty caps the first frame at the mean. */ |
47 | 1.26k | #define RC_RESERVOIR_START 0.5f |
48 | | |
49 | | void RateControlReset(RateControl *rc, unsigned int numChannels, |
50 | | unsigned long bitRate, unsigned long sampleRate, int cbr) |
51 | 1.90k | { |
52 | | /* unsigned long is 32 bits on Windows: widen before multiplying. */ |
53 | 1.90k | rc->frameBudget = (int)((uint64_t)numChannels * bitRate * FRAME_LEN / sampleRate); |
54 | | |
55 | | /* A signed account opens square at zero: any nonzero start is credit the |
56 | | stream never earned, which `lend` then spends. */ |
57 | 1.90k | rc->balance = 0; |
58 | | /* Negative means "no frame seen yet"; the first frame seeds the average |
59 | | rather than dragging it up from zero over the whole time constant. */ |
60 | 1.90k | rc->sbrBitsAcc = -1; |
61 | | |
62 | | /* The reservoir is the decoder buffer (AAC_MAX_BITS_PER_CH per channel) |
63 | | refilled at the mean rate. ABR/VBR leave resMean 0: no cap, no floor, |
64 | | buffer_fullness stays 0x7FF. */ |
65 | 1.90k | rc->resMean = 0; |
66 | 1.90k | rc->resStep = rc->resDen = rc->resRem = 0; |
67 | 1.90k | rc->resCap = 0; |
68 | 1.90k | rc->resFill = 0; |
69 | 1.90k | if (cbr) |
70 | 1.26k | { |
71 | 1.26k | rc->resMean = rc->frameBudget; |
72 | | /* A budget that is not a whole number of bits per frame still has to |
73 | | average out, or the decoder buffer drifts by the fraction every |
74 | | frame: the remainder is carried into the frames that follow. */ |
75 | 1.26k | rc->resDen = (unsigned int)sampleRate; |
76 | 1.26k | rc->resStep = (unsigned int)((uint64_t)numChannels * bitRate * FRAME_LEN - (uint64_t)rc->frameBudget * sampleRate); |
77 | | /* The carried bit makes the largest credit frameBudget + 1, which the |
78 | | buffer must still hold. */ |
79 | 1.26k | rc->resCap = (int)numChannels * AAC_MAX_BITS_PER_CH - rc->resMean - (rc->resStep ? 1 : 0); |
80 | 1.26k | if (rc->resCap < 0) |
81 | 0 | rc->resCap = 0; |
82 | 1.26k | rc->resFill = (int)(rc->resCap * RC_RESERVOIR_START); |
83 | 1.26k | } |
84 | 1.90k | rc->resMinBits = 0; |
85 | 1.90k | rc->stuffedBits = 0; |
86 | 1.90k | rc->sbrBits = 0; |
87 | 1.90k | rc->prevWant = 0; |
88 | 1.90k | } |
89 | | |
90 | | int RateControlReservoirAfter(const RateControl *rc, int payloadBits) |
91 | 25.7k | { |
92 | | /* Below zero the decoder stalls (only a frame that cannot shrink even at |
93 | | MINQUAL gets here); above capacity the fill saturates. */ |
94 | 25.7k | int fill = rc->resFill + rc->resMean - payloadBits; |
95 | 25.7k | if (fill < 0) |
96 | 11.5k | fill = 0; |
97 | 14.2k | else if (fill > rc->resCap) |
98 | 264 | fill = rc->resCap; |
99 | 25.7k | return fill; |
100 | 25.7k | } |
101 | | |
102 | | int RateControlFrameCap(RateControl *rc) |
103 | 7.44k | { |
104 | 7.44k | int avail; |
105 | | |
106 | 7.44k | if (!rc->resMean) |
107 | 2.03k | return 0; |
108 | | |
109 | | /* A frame may spend mean + fill; one that would overflow the buffer is |
110 | | stuffed up to the floor. The floor stays two bytes under the cap: fill |
111 | | is byte-granular, and at zero capacity the two would meet. */ |
112 | 5.41k | avail = rc->resMean + rc->resFill; |
113 | 5.41k | rc->resMinBits = rc->resMean + rc->resFill - rc->resCap; |
114 | 5.41k | if (rc->resMinBits > avail - 16) |
115 | 753 | rc->resMinBits = avail - 16; |
116 | 5.41k | if (rc->resMinBits < 0) |
117 | 3.15k | rc->resMinBits = 0; |
118 | 5.41k | return avail; |
119 | 7.44k | } |
120 | | |
121 | | float RateControlUpdate(RateControl *rc, int payloadBits, |
122 | | float quality, float maxqual) |
123 | 6.68k | { |
124 | 6.68k | int desbits = rc->frameBudget; |
125 | 6.68k | int sbrBits = rc->sbrBits; |
126 | | /* The reservoir is charged every bit sent; the controller only the bits |
127 | | the coder chose, or a stuffed frame reads as on budget and quality |
128 | | never rises to replace the stuffing with signal. */ |
129 | 6.68k | int sentBits = payloadBits; |
130 | 6.68k | int totalBits = payloadBits - rc->stuffedBits; |
131 | 6.68k | int reservoir = (rc->resMean > 0); |
132 | 6.68k | int sbrCharge; |
133 | 6.68k | float fix; |
134 | | |
135 | 6.68k | if (reservoir) |
136 | 5.34k | { |
137 | | #ifdef FAAC_STATS |
138 | | if (rc->resFill + rc->resMean - sentBits < 0) |
139 | | g_faacStats.resUnderflowFrames++; |
140 | | g_faacStats.resFrames++; |
141 | | g_faacStats.resTotalBits += sentBits; |
142 | | g_faacStats.resStuffBits += rc->stuffedBits; |
143 | | if (rc->resCap > 0) |
144 | | { |
145 | | float pct = 100.0f * (float)rc->resFill / (float)rc->resCap; |
146 | | if (pct < g_faacStats.minResFill) g_faacStats.minResFill = pct; |
147 | | } |
148 | | #endif |
149 | 5.34k | rc->resFill = RateControlReservoirAfter(rc, sentBits); |
150 | 5.34k | rc->resRem += rc->resStep; |
151 | 5.34k | rc->resMean = rc->frameBudget; |
152 | 5.34k | if (rc->resRem >= rc->resDen) |
153 | 1.78k | { |
154 | 1.78k | rc->resRem -= rc->resDen; |
155 | 1.78k | rc->resMean++; |
156 | 1.78k | } |
157 | 5.34k | } |
158 | | |
159 | | /* SBR payload is not fixed overhead: at 48 kHz it runs 135-255 bits against |
160 | | a 2048-bit budget. Charging the frame's own `sbrBits` makes the |
161 | | controller answer for a quantity it does not control -- a payload spike |
162 | | enters the ledger as core debt, and `lend` squeezes core quality to |
163 | | repay it. Charging the running average lets the spike reach the output |
164 | | rate instead. On LC `sbrBits` is 0. */ |
165 | 6.68k | { |
166 | 6.68k | int prev = rc->sbrBitsAcc; |
167 | 6.68k | rc->sbrBitsAcc = (prev < 0) |
168 | 6.68k | ? (sbrBits << RC_SBR_EWMA_SHIFT) |
169 | 6.68k | : (prev + sbrBits - (prev >> RC_SBR_EWMA_SHIFT)); |
170 | 6.68k | } |
171 | 6.68k | sbrCharge = rc->sbrBitsAcc >> RC_SBR_EWMA_SHIFT; |
172 | | |
173 | | /* Settle the frame against the account. The balance is signed and both |
174 | | directions are kept: forgiving credit but not debt biases the loop by |
175 | | however much each clip drew. One CORE setpoint serves the account and |
176 | | `fix` alike -- the frame's budget less what SBR was charged, against |
177 | | what the core actually spent. A stuffed CBR frame left the under-aim |
178 | | as fill elements, so past half full the aim rises to spend it as signal. |
179 | | Without stuffing a different aim only moves bits between frames. */ |
180 | 6.68k | int coreTarget = (int)(desbits * RC_BALANCE_AIM) - sbrCharge; |
181 | 6.68k | if (reservoir && rc->stuffedBits > 0 && rc->resFill > rc->resCap / 2) |
182 | 1.28k | coreTarget += (rc->resFill - rc->resCap / 2) / RC_BALANCE_AMORT; |
183 | 6.68k | int coreBits = totalBits - sbrBits; |
184 | 6.68k | int lend; |
185 | 6.68k | int bound = RC_BALANCE_FRAMES * desbits; |
186 | 6.68k | int diff = coreTarget - coreBits; |
187 | 6.68k | rc->balance += diff; |
188 | 6.68k | if (rc->balance > bound) |
189 | 749 | rc->balance = bound; |
190 | 5.93k | else if (rc->balance < -bound) |
191 | 2.03k | rc->balance = -bound; |
192 | | |
193 | | /* What this frame may lean on, signed and amortized: a credit lets a |
194 | | complex frame overspend, a debt holds the next frames under budget |
195 | | until it is repaid. Amortizing is what keeps a deep balance from being |
196 | | worked off in one lurch. */ |
197 | 6.68k | lend = rc->balance / RC_BALANCE_AMORT; |
198 | | |
199 | 6.68k | int floored = 0; |
200 | 6.68k | int capped = 0; |
201 | 6.68k | { |
202 | 6.68k | int aim = coreTarget + lend; |
203 | | /* Aim inside the next frame's [floor, cap]: a frame stuffed to the |
204 | | floor spends those bits anyway, so they may as well be signal; a |
205 | | frame aimed under the cap fits without a retry. */ |
206 | 6.68k | if (reservoir) |
207 | 5.34k | { |
208 | | /* resFill is post-frame: the next frame's window, net of SBR. */ |
209 | 5.34k | int coreFloor = rc->resMean + rc->resFill - rc->resCap - sbrCharge; |
210 | 5.34k | int coreCap = rc->resMean + rc->resFill - sbrCharge; |
211 | 5.34k | if (aim < coreFloor) |
212 | 86 | { |
213 | 86 | aim = coreFloor; |
214 | 86 | floored = 1; |
215 | 86 | } |
216 | 5.34k | if (aim > coreCap) |
217 | 810 | aim = coreCap; |
218 | | /* A frame this size will not fit the next cap: correct down |
219 | | whole now rather than bust and retry. */ |
220 | 5.34k | capped = (coreBits > coreCap); |
221 | 5.34k | } |
222 | 6.68k | if (coreBits > 0) |
223 | 6.68k | fix = (float)aim / (float)coreBits; |
224 | 0 | else |
225 | 0 | fix = 1.0f; |
226 | 6.68k | } |
227 | | |
228 | | /* Stiffer damping when the account is far off center. Removing this |
229 | | and the deadband below costs 16 kHz speech MOS under ABR. */ |
230 | 6.68k | float damping = RC_DAMPING_FACTOR; |
231 | 6.68k | float fillRatio = 0.5f + 0.5f * (float)rc->balance / (float)bound; |
232 | 6.68k | if (fillRatio < 0.25f || fillRatio > 0.75f) |
233 | 3.71k | damping = 0.85f; |
234 | | #ifdef FAAC_STATS |
235 | | { |
236 | | float fillPct = fillRatio * 100.0f; |
237 | | g_faacStats.totalBalanceRatio += fillPct; |
238 | | if (fillPct < g_faacStats.minBalanceRatio) g_faacStats.minBalanceRatio = fillPct; |
239 | | if (fillPct > g_faacStats.maxBalanceRatio) g_faacStats.maxBalanceRatio = fillPct; |
240 | | g_faacStats.balanceFrames++; |
241 | | } |
242 | | #endif |
243 | | |
244 | | /* A frame stuffed to the floor pays those bits anyway, so the rise to |
245 | | it is undamped; the cap catches a real overshoot. */ |
246 | 6.68k | if (floored) |
247 | 86 | { |
248 | 86 | if (fix > 1.5f) fix = 1.5f; |
249 | 86 | } |
250 | 6.59k | else if (capped) |
251 | 887 | { |
252 | 887 | if (fix < 0.5f) fix = 0.5f; |
253 | 887 | } |
254 | 5.70k | else |
255 | 5.70k | fix = (fix - 1.0f) * damping + 1.0f; |
256 | | |
257 | | /* Hold quality across stuffed frames that do not answer to it (a pause |
258 | | cannot reach the floor at any quality); raising it winds the |
259 | | controller up and the first frame after the pause busts the cap. */ |
260 | 6.68k | if (fix > 1.0f && rc->stuffedBits > 0 && rc->prevWant > 0 |
261 | 1.40k | && coreBits <= rc->prevWant + rc->prevWant / 50) |
262 | 805 | fix = 1.0f; |
263 | 6.68k | rc->prevWant = (rc->stuffedBits > 0) ? coreBits : 0; |
264 | | |
265 | | /* Skip small adjustments (< 0.5%) to keep quality steady */ |
266 | 6.68k | if (fabsf(fix - 1.0f) > 0.005f) { |
267 | 5.84k | if (!floored && !capped) |
268 | 4.90k | fix = (fix < 0.80f) ? 0.80f : ((fix > 1.20f) ? 1.20f : fix); |
269 | 5.84k | quality *= fix; |
270 | 5.84k | } |
271 | | |
272 | 6.68k | if (quality > maxqual) |
273 | 153 | quality = maxqual; |
274 | 6.68k | if (quality < MINQUAL) |
275 | 167 | quality = MINQUAL; |
276 | | |
277 | | #ifdef FAAC_STATS |
278 | | { |
279 | | int overshot = (totalBits > desbits); |
280 | | g_faacStats.sumDesBits += desbits; |
281 | | if (overshot) g_faacStats.sumOverBits += (totalBits - desbits); |
282 | | else { g_faacStats.underFrames++; g_faacStats.sumUnderBits += (desbits - totalBits); } |
283 | | int atFloor = (quality <= MINQUAL); |
284 | | if (atFloor) g_faacStats.minqualFrames++; |
285 | | if (quality >= maxqual) g_faacStats.maxqualFrames++; |
286 | | if (overshot) g_faacStats.overshootFrames++; |
287 | | if (overshot && atFloor) g_faacStats.minqualOvershootFrames++; |
288 | | } |
289 | | #endif |
290 | | |
291 | 6.68k | return quality; |
292 | 6.68k | } |
293 | | |
294 | | #ifdef FAAC_STATS |
295 | | void RateControlStatsInit(void) |
296 | | { |
297 | | g_faacStats.minBalanceRatio = 100.0f; |
298 | | g_faacStats.minResFill = 100.0f; |
299 | | } |
300 | | |
301 | | void RateControlStatsPrint(FILE *out) |
302 | | { |
303 | | if (g_faacStats.balanceFrames > 0) |
304 | | { |
305 | | fprintf(out, " Rate Control & Cap : Bit Balance = %5.1f%% (min %5.1f%%, max %5.1f%%) | Peak Retries = %5.1f%% (%u/%u)\n", |
306 | | g_faacStats.totalBalanceRatio / g_faacStats.balanceFrames, |
307 | | g_faacStats.minBalanceRatio, g_faacStats.maxBalanceRatio, |
308 | | 100.0 * g_faacStats.peakRetryFrames / g_faacStats.totalFrames, |
309 | | g_faacStats.peakRetryFrames, g_faacStats.totalFrames); |
310 | | } |
311 | | /* Not under balanceFrames: capped VBR cuts bands without ever updating the balance. */ |
312 | | if (g_faacStats.totalFrames > 0) |
313 | | { |
314 | | fprintf(out, " Band Cuts : %u of %u frames | refits = %u\n", |
315 | | g_faacStats.peakZeroFrames, g_faacStats.totalFrames, g_faacStats.peakRefits); |
316 | | } |
317 | | if (g_faacStats.resFrames > 0) |
318 | | { |
319 | | fprintf(out, " Bit Reservoir (CBR) : Fill min = %5.1f%% | Bound Retries = %5.1f%% (%u/%u) | Underflows = %u | Stuffing = %5.2f%% of stream\n", |
320 | | g_faacStats.minResFill, |
321 | | 100.0 * g_faacStats.resBoundRetryFrames / g_faacStats.resFrames, |
322 | | g_faacStats.resBoundRetryFrames, g_faacStats.resFrames, |
323 | | g_faacStats.resUnderflowFrames, |
324 | | g_faacStats.resTotalBits > 0 ? 100.0 * g_faacStats.resStuffBits / g_faacStats.resTotalBits : 0.0); |
325 | | } |
326 | | if (g_faacStats.balanceFrames > 0) |
327 | | { |
328 | | unsigned int rcf = g_faacStats.balanceFrames; |
329 | | fprintf(out, " Bit Error : mean over = %7.1f bits (%u fr) | mean under = %7.1f bits (%u fr) | net = %+6.2f%% of target\n", |
330 | | g_faacStats.overshootFrames ? g_faacStats.sumOverBits / g_faacStats.overshootFrames : 0.0, |
331 | | g_faacStats.overshootFrames, |
332 | | g_faacStats.underFrames ? g_faacStats.sumUnderBits / g_faacStats.underFrames : 0.0, |
333 | | g_faacStats.underFrames, |
334 | | g_faacStats.sumDesBits > 0 ? 100.0 * (g_faacStats.sumOverBits - g_faacStats.sumUnderBits) / g_faacStats.sumDesBits : 0.0); |
335 | | fprintf(out, " Quality Clamp : Overshoot = %5.1f%% (%u/%u) | at MINQUAL = %5.1f%% | overshoot AND floored = %5.1f%% | at MAXQUAL = %5.1f%%\n", |
336 | | 100.0 * g_faacStats.overshootFrames / rcf, g_faacStats.overshootFrames, rcf, |
337 | | 100.0 * g_faacStats.minqualFrames / rcf, |
338 | | 100.0 * g_faacStats.minqualOvershootFrames / rcf, |
339 | | 100.0 * g_faacStats.maxqualFrames / rcf); |
340 | | } |
341 | | } |
342 | | #endif |