Coverage Report

Created: 2026-12-01 06:56

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/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
0
#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
0
#define RC_BALANCE_AIM         0.99f
33
0
#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
0
#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
0
#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
0
#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.03k
{
52
    /* unsigned long is 32 bits on Windows: widen before multiplying. */
53
1.03k
    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.03k
    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.03k
    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.03k
    rc->resMean = 0;
66
1.03k
    rc->resStep = rc->resDen = rc->resRem = 0;
67
1.03k
    rc->resCap = 0;
68
1.03k
    rc->resFill = 0;
69
1.03k
    if (cbr)
70
0
    {
71
0
        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
0
        rc->resDen = (unsigned int)sampleRate;
76
0
        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
0
        rc->resCap = (int)numChannels * AAC_MAX_BITS_PER_CH - rc->resMean - (rc->resStep ? 1 : 0);
80
0
        if (rc->resCap < 0)
81
0
            rc->resCap = 0;
82
0
        rc->resFill = (int)(rc->resCap * RC_RESERVOIR_START);
83
0
    }
84
1.03k
    rc->resMinBits = 0;
85
1.03k
    rc->stuffedBits = 0;
86
1.03k
    rc->sbrBits = 0;
87
1.03k
    rc->prevWant = 0;
88
1.03k
}
89
90
int RateControlReservoirAfter(const RateControl *rc, int payloadBits)
91
0
{
92
    /* Below zero the decoder stalls (only a frame that cannot shrink even at
93
       MINQUAL gets here); above capacity the fill saturates. */
94
0
    int fill = rc->resFill + rc->resMean - payloadBits;
95
0
    if (fill < 0)
96
0
        fill = 0;
97
0
    else if (fill > rc->resCap)
98
0
        fill = rc->resCap;
99
0
    return fill;
100
0
}
101
102
int RateControlFrameCap(RateControl *rc)
103
6.80k
{
104
6.80k
    int avail;
105
106
6.80k
    if (!rc->resMean)
107
6.80k
        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
0
    avail = rc->resMean + rc->resFill;
113
0
    rc->resMinBits = rc->resMean + rc->resFill - rc->resCap;
114
0
    if (rc->resMinBits > avail - 16)
115
0
        rc->resMinBits = avail - 16;
116
0
    if (rc->resMinBits < 0)
117
0
        rc->resMinBits = 0;
118
0
    return avail;
119
6.80k
}
120
121
float RateControlUpdate(RateControl *rc, int payloadBits,
122
                        float quality, float maxqual)
123
0
{
124
0
    int desbits = rc->frameBudget;
125
0
    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
0
    int sentBits = payloadBits;
130
0
    int totalBits = payloadBits - rc->stuffedBits;
131
0
    int reservoir = (rc->resMean > 0);
132
0
    int sbrCharge;
133
0
    float fix;
134
135
0
    if (reservoir)
136
0
    {
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
0
        rc->resFill = RateControlReservoirAfter(rc, sentBits);
150
0
        rc->resRem += rc->resStep;
151
0
        rc->resMean = rc->frameBudget;
152
0
        if (rc->resRem >= rc->resDen)
153
0
        {
154
0
            rc->resRem -= rc->resDen;
155
0
            rc->resMean++;
156
0
        }
157
0
    }
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
0
    {
166
0
        int prev = rc->sbrBitsAcc;
167
0
        rc->sbrBitsAcc = (prev < 0)
168
0
            ? (sbrBits << RC_SBR_EWMA_SHIFT)
169
0
            : (prev + sbrBits - (prev >> RC_SBR_EWMA_SHIFT));
170
0
    }
171
0
    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
0
    int coreTarget = (int)(desbits * RC_BALANCE_AIM) - sbrCharge;
181
0
    if (reservoir && rc->stuffedBits > 0 && rc->resFill > rc->resCap / 2)
182
0
        coreTarget += (rc->resFill - rc->resCap / 2) / RC_BALANCE_AMORT;
183
0
    int coreBits = totalBits - sbrBits;
184
0
    int lend;
185
0
    int bound = RC_BALANCE_FRAMES * desbits;
186
0
    int diff = coreTarget - coreBits;
187
0
    rc->balance += diff;
188
0
    if (rc->balance > bound)
189
0
        rc->balance = bound;
190
0
    else if (rc->balance < -bound)
191
0
        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
0
    lend = rc->balance / RC_BALANCE_AMORT;
198
199
0
    int floored = 0;
200
0
    int capped = 0;
201
0
    {
202
0
        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
0
        if (reservoir)
207
0
        {
208
            /* resFill is post-frame: the next frame's window, net of SBR. */
209
0
            int coreFloor = rc->resMean + rc->resFill - rc->resCap - sbrCharge;
210
0
            int coreCap = rc->resMean + rc->resFill - sbrCharge;
211
0
            if (aim < coreFloor)
212
0
            {
213
0
                aim = coreFloor;
214
0
                floored = 1;
215
0
            }
216
0
            if (aim > coreCap)
217
0
                aim = coreCap;
218
            /* A frame this size will not fit the next cap: correct down
219
               whole now rather than bust and retry. */
220
0
            capped = (coreBits > coreCap);
221
0
        }
222
0
        if (coreBits > 0)
223
0
            fix = (float)aim / (float)coreBits;
224
0
        else
225
0
            fix = 1.0f;
226
0
    }
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
0
    float damping = RC_DAMPING_FACTOR;
231
0
    float fillRatio = 0.5f + 0.5f * (float)rc->balance / (float)bound;
232
0
    if (fillRatio < 0.25f || fillRatio > 0.75f)
233
0
        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
0
    if (floored)
247
0
    {
248
0
        if (fix > 1.5f) fix = 1.5f;
249
0
    }
250
0
    else if (capped)
251
0
    {
252
0
        if (fix < 0.5f) fix = 0.5f;
253
0
    }
254
0
    else
255
0
        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
0
    if (fix > 1.0f && rc->stuffedBits > 0 && rc->prevWant > 0
261
0
        && coreBits <= rc->prevWant + rc->prevWant / 50)
262
0
        fix = 1.0f;
263
0
    rc->prevWant = (rc->stuffedBits > 0) ? coreBits : 0;
264
265
    /* Skip small adjustments (< 0.5%) to keep quality steady */
266
0
    if (fabsf(fix - 1.0f) > 0.005f) {
267
0
        if (!floored && !capped)
268
0
            fix = (fix < 0.80f) ? 0.80f : ((fix > 1.20f) ? 1.20f : fix);
269
0
        quality *= fix;
270
0
    }
271
272
0
    if (quality > maxqual)
273
0
        quality = maxqual;
274
0
    if (quality < MINQUAL)
275
0
        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
0
    return quality;
292
0
}
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