2 * AAC encoder NMR (noise-to-mask ratio) scalefactor coder
3 * Copyright (c) 2026 Lynne <dev@lynne.ee>
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 * AAC encoder NMR scalefactor coder.
25 * Optimizes the same noise-to-mask objective as the two-loop coder, but with an
26 * optimal Viterbi search over scalefactors instead of a heuristic loop. For each
27 * coded band the per-scalefactor distortion/bits curve is precomputed, then a
28 * trellis over the (window-group, band) coding sequence minimizes
29 * sum_g = dist_g(sf_g)/threshold_g +
30 * lambda * (spectral_bits_g(sf_g) + scalefactor_differential_bits)
31 * with |sf_g - sf_{g-1}| <= SCALE_MAX_DIFF as a constraint, and lambda
32 * binary-searched so the coded size meets the per-frame bit budget
34 * Perceptual noise substitution (PNS) is integrated into the same objective: once
35 * the trellis settles on its operating lambda, each noise-like band (flagged by
36 * mark_pns) is offered a terminal "code as noise" candidate whose cost is
37 * nmr_pns + lambda*NMR_PNS_BITS. Because NMR_PNS_BITS is far below a band's spectral bit
38 * count, this candidate only wins when lambda is large, i.e. when the encoder is
39 * struggling to hold the bitrate. The bits freed by the chosen PNS bands are
40 * then re-spent by a second trellis pass over the remaining bands.
43#ifndef AVCODEC_AACCODER_NMR_H
44#define AVCODEC_AACCODER_NMR_H
57/* differential scalefactor coding cost, clamped to the legal delta range */
58 #define NMR_SFBITS(d) ff_aac_scalefactor_bits[av_clip((d) + SCALE_DIFF_ZERO, 0, 2*SCALE_MAX_DIFF)]
60 #define NMR_ITERS 14 /* lambda binary-search iters */
61 #define NMR_IFINE 9 /* fine-pass lambda iters */
62 #define NMR_CITERS 7 /* coarse-pass lambda iters */
63 #define NMR_CWARM 5 /* coarse-pass iters when warm-started off the previous frame's
64 * lambda: the bracket spans 10 octaves instead of ~43, so fewer
65 * bisection steps reach the same resolution */
66#define NMR_COARSE 8 /* two-pass coarse->fine grid step, cuts the Viterbi ncand^2 with no
67 * quality loss, 0 disables it (single full-resolution pass) */
68#define NMR_STEP 1 /* fine-pass scalefactor candidate granularity */
70#define NMR_PNS_BITS 9 /* approx cost in bits of signalling PNS */
72 /* Spectral-hole fill: noise-like bands the trellis left mostly empty are filled with
73 * energy-matched noise (PNS); an audible hole sounds worse than matched noise. */
74#define NMR_PNS_HOLE_FRAC 0.5f
75#define NMR_PNS_HOLE_SPREAD 0.5f
77/* RC servo gain: scale the corridor centre by exp2(-K*fill/R) each frame to hold
78 * the long-run mean rate; without it a bad centre drifts for dozens of frames. */
79#define NMR_RC_K_CBR 0.5f
81 #define NMR_RC_ITERS 8 /* lambda bisection iters when clamping an over-cap frame */
82/* Corridor: bisect within [lam_rc/NMR_RC_CORR, lam_rc*NMR_RC_CORR] so quality stays
83 * smooth while per-frame demand is tracked; 1.5 cuts lambda jitter ~25%. */
84 #define NMR_RC_CORR 1.5f
86/* Reservoir half-window (bits/ch); swept 512/1536/3072, 1536 optimal. */
87 #define NMR_CBR_BUF 1536
88 /* Slew limit on the FINAL operating lambda per frame; bits deviate instead,
89 * the reservoir absorbs. See memory: aac-castanets-transient-rc. */
91#define NMR_SLEW_RUN 1.15f /* within short runs */
92#define NMR_RC_CITERS 3 /* corridor coarse-pass iters */
94/* Transition premask: an attack cannot mask backwards; clamp a START frame's
95 * thresholds toward the previous long frame's. */
96#define NMR_TRANS_PM 2.0f
98/* Zero-decision hysteresis: previously-coded bands need this margin below
99 * threshold to zero (marginal bands flicker audibly otherwise). */
100#define NMR_ZERO_STICKY 0.5f
102 /* Transient bit-burst: an isolated onset (preceded by >= NMR_BURST_GAP long frames)
103 * is coded NMR_BURST_GAIN x finer, held uniform across the run, repaid from steady stretches. */
104#define NMR_BURST_GAP 10
105 #define NMR_BURST_GAIN 8.0f
106 /* Dense-beat boost: short runs with gap < NMR_BURST_GAP get a budget factor
107 * ramping with the gap (starvation-scaled at the use site). */
108#define NMR_SHORT_BOOST 2.0f
109#define NMR_RC_FITERS 4 /* corridor fine-pass iters */
110 #define NMR_RC_TRACK 0.1f /* per-frame pull of the corridor centre toward the realized lambda */
112/* PNS noise-distortion gate: only bands coded well above the masking floor become noise. */
113#define NMR_PNS_NDGATE 4.0f
115/* Energy/threshold cap for PNS: loud bands (energy >> mask) yield clipping random peaks;
116 * only near-masked bands are safe substitution targets. */
117#define NMR_PNS_MAX_ET 8.0f
119/* Operating-lambda floor for PNS: below it the encoder is not struggling, so
120 * substituting real texture for 9 signalling bits is net-negative. */
121 #define NMR_PNS_LAM 100.0f
123/* PNS decision hysteresis: enter and leave both cost a margin. */
124#define NMR_PNS_ENTER 0.7f
125 #define NMR_PNS_STAY 1.4f
126 /* PNS debounce: enter after NMR_PNS_ON consecutive wants, leave after
127 * NMR_PNS_OFF (chronically marginal bands never qualify). */
132 * Viterbi over the coding sequence act[0..nact-1] (indices into the per-band
133 * curves nd/nb), with lambda binary-searched so the coded size ~ destbits.
134 * Fills chosen[band] for every band referenced by act. Returns the operating
135 * lambda. node cost = dist/threshold + lambda*spectral_bits;
136 * edge cost = lambda*sf_differential_bits; |delta sf| <= SCALE_MAX_DIFF hard.
140 const int *blo,
const int *bnc,
int step,
141 const int *act,
int nact,
int destbits,
int *chosen,
142 float lo_l,
float hi_l,
int iters)
145 float lamsf[2*
SCALE_MAX_DIFF + 1];
/* lam*sfdiff bit cost, per lambda */
152 for (
int it = 0; it < iters; it++) {
153 lam =
sqrtf(lo_l * hi_l);
158 for (
int o = 0; o < bnc[
b0]; o++)
159 dp[o] = nd[
b0][o] + lam * nb[
b0][o];
/* anchor band node cost */
161 for (
int k = 1; k < nact; k++) {
162 int b = act[k], pb = act[k-1];
163 memcpy(dpp, dp,
sizeof(dp));
164 for (
int o = 0; o < bnc[
b]; o++)
165 node[o] = nd[
b][o] + lam * nb[
b][o];
166 /* dp[o] = node[o] + min_op(dpp[op] + edge cost) */
167 s->aacdsp.nmr_trellis_step(dp, bp[k], dpp, node, lamsf,
168 bnc[
b], bnc[pb], blo[
b] - blo[pb], step,
173 int beo = 0,
b = act[nact-1];
175 for (
int o = 0; o < bnc[
b]; o++)
176 if (dp[o] < bec) { bec = dp[o]; beo = o; }
178 for (
int k = nact-1; k > 0; k--)
179 chosen[act[k-1]] = bp[k][chosen[act[k]]];
183 for (
int k = 0; k < nact; k++)
184 total += nb[act[k]][chosen[act[k]]];
185 for (
int k = 1; k < nact; k++)
186 total +=
NMR_SFBITS((blo[act[k]]+chosen[act[k]]*step) - (blo[act[k-1]]+chosen[act[k-1]]*step));
191 /* check if we went over budget, go coarser if we did */
192 if (total > destbits)
200/* Build one coded band's (dist/threshold, bits) cost curve, candidates sf = lo + o*step
201 * for o in [0,maxn), stopping when the band would drop (cb <= 0). Returns the bit count. */
203 int start,
int lo,
int step,
int maxn,
float invthr,
204 float maxval,
float *nd_row,
int *nb_row)
207 for (
int o = 0; o < maxn && lo + o*step <=
SCALE_MAX_POS; o++) {
219 nd_row[ncand] = (dist - btot) * invthr;
220 nb_row[ncand] = btot;
226/* Zero a channel with nothing codeable; stale band_types would resurrect
227 * bands with chain-illegal scalefactors. */
230 for (
int i = 0;
i < 128;
i++) {
238 /* Per-channel setup into slot t: short-block threshold shaping, the
239 * allocation law, zero decisions, and the PASS 1 coarse candidate curves.
240 * Returns the coded-band count; 0 = nothing codeable (caller bails). */
247 int allz = 0, cutoff = 1024, nbnd = 0;
249 uint8_t *zprev =
s->nmr->zero_prev[
s->cur_channel & 15];
251 memset(zprev, 1, 128);
260 /* band cutoff index for this frame's window size; the bandwidth is fixed
261 * at init and shared with the psy model */
264 /* Short-block shaping: temporal premask + per-window threshold flatten. */
266 const float pm_p1 = 0.1f, pm_p2 = 2.0f, pm_p3 = 4.0f;
268 float t1 = FLT_MAX, t2 = FLT_MAX;
/* original thr of w-1, w-2 */
271 float th =
b->threshold;
273 b->threshold =
FFMAX(
c, th*pm_p1);
279 float sum = 0.0f, esum = 0.0f;
int n = 0;
282 if (
b->energy >
b->threshold &&
b->threshold > 0.0f) { sum +=
b->threshold; esum +=
b->energy; n++; }
285 /* keep each window codeable: cap the mean 12dB under the
286 * window's mean audible energy */
290 if (
b->energy >
b->threshold &&
b->threshold > 0.0f)
298 /* Allocation law; short frames blend to softer energy exponents under
299 * pressure (roll anti-starvation, see memory). */
300 float a_ae = 0.443f, a_at = 0.111f;
302 /* blend to mask-weighted exponents under rate pressure */
303 a_ae += (0.35f - a_ae) *
s->nmr->press;
304 a_at += (0.3f - a_at) *
s->nmr->press;
309 float uplim = 0.0f, ener = 0.0f, spread = 2.0f;
313 /* pre-decided intensity band (right channel): keep its
314 * signalling, it is not trellis-coded */
320 /* M/S side bands: zero-reluctance scaled by side/mid ratio (a tiny
321 * side IS the image; zeroing it flickers). */
322 if ((t->
cur_ch & 1) &&
s->nmr &&
s->nmr->pair &&
323 s->nmr->smode_band[(t->
cur_ch >> 1) & 7][
w*16+
g] == 1) {
324 const FFPsyBand *
mb = &
s->psy.ch[
s->cur_channel - 1].psy_bands[
w*16+
g];
328 const FFPsyBand *bb = &
s->psy.ch[
s->cur_channel].psy_bands[(
w+w2)*16+
g];
332 zthr_mul *= 0.25f + 0.75f *
av_clipf(ratio / 0.3f, 0.0f, 1.0f);
335 FFPsyBand *band = &
s->psy.ch[
s->cur_channel].psy_bands[(
w+w2)*16+
g];
348 t->
thr_real[
w*16+
g] = uplim;
/* real mask, before the allocation law (PNS gate) */
349 if (nz && ener > 0.0f && uplim > 0.0f)
/* allocation law */
350 uplim =
expf(a_ae * logf(ener) + a_at * logf(uplim));
351 t->
thr[
w*16+
g] = uplim;
360 /* transition premask (see NMR_TRANS_PM) */
364 s->nmr->thr_prev_ok[ci]) {
366 if (t->
thr[
g] > 0.0f &&
s->nmr->thr_prev[ci][
g] > 0.0f)
370 s->nmr->thr_prev[ci][
g] = t->
thr[
g];
371 s->nmr->thr_prev_ok[ci] = 1;
373 s->nmr->thr_prev_ok[t->
cur_ch & 15] = 0;
376 s->aacdsp.abs_pow34(
s->scoefs, sce->
coeffs, 1024);
379 /* TNS synthesis gain per band: the decoder re-amplifies residual-domain
380 * quantization noise by the whitening gain (shorts only). */
381 for (
int i = 0;
i < 128;
i++)
385 for (
int w = 0;
w < 8;
w++) {
392 for (
int g =
FFMIN(bottom2, mmm2);
g <
FFMIN(top2, mmm2);
g++) {
396 const FFPsyBand *pb = &
s->psy.ch[
s->cur_channel].psy_bands[
w*16+
g];
397 for (
int k = s0; k < s1; k++)
405 /* finest codeable scalefactor and max value per band */
415 /* PASS 1: coarse candidate curves per coded band
416 * (the lambda search runs on this cheap grid, PASS 2 refines the winner) */
423 float invthr = 1.0f /
FFMAX(t->
thr[
w*16+
g], 1e-9f);
425 invthr, t->
maxvals[
w*16+
g], nd[nbnd], nb[nbnd]);
426 if (t->
tnsg[
w*16+
g] > 1.0f)
427 for (
int o = 0; o < ncand; o++)
428 nd[nbnd][o] *= t->
tnsg[
w*16+
g];
430 /* nothing codeable: drop the group band incl. subwindow
431 * flags (group flag is re-derived by ANDing) */
438 t->
bst[nbnd] = start;
440 t->
bnc[nbnd] = ncand;
449 for (
int b = 0;
b < nbnd;
b++) {
457/* total bits of a slot's current chosen[] on grid `step`, incl. sf deltas */
461 for (
int k = 0; k < t->
nact; k++)
463 for (
int k = 1; k < t->
nact; k++)
469/* Run every slot's trellis at one fixed lambda; returns the pooled bits. */
473 for (
int k = 0; k < nsl; k++) {
484 /* Bisect ONE shared lambda across the slots so the POOLED bits meet destbits.
485 * This is the CPE budget pool: bits flow to whichever channel of the pair has
486 * demand at the common operating point, instead of an equal per-channel split. */
488 int destbits,
float lo_l,
float hi_l,
int iters)
491 for (
int it = 0; it < iters; it++) {
492 lam =
sqrtf(lo_l * hi_l);
496 /* over budget -> go coarser */
497 if (total > destbits)
505/* Write a solved slot back into its channel: band types, scalefactors, and the
506 * SCALE_MAX_DIFF legality fixups. Verbatim from the pre-pool single-channel tail. */
512 for (
int b = 0;
b < t->
nbnd;
b++) {
524 {
/* record the bits this solve accounted for; the encoder compares them
525 * against the channel's real output to keep the budget honest */
526 int tot = 0, prevb = -1;
527 for (
int b = 0;
b < t->
nbnd;
b++) {
535 s->nmr->counted[t->
cur_ch] = tot;
538 /* SCALE_MAX_DIFF condition:
539 * re-clamp, codebook fixup, drop uncodeable, set global gain
540 * NOISE_BT bands keep their own scalefactor chain via set_special_band_scalefactors) */
542 uint8_t nextband[128];
563 /* drop subwindow flags too, see the PASS 1 drop above */
576 /* every band must carry a chain-legal scalefactor (re-clamp, codebook
577 * fixup, global gain) */
579 int last = sce->
sf_idx[0];
593/* Solve one element group (a solo channel, or a CPE pair pooled under one
594 * shared lambda and one pooled budget), then PNS and commit. */
596 const float lambda,
NMRSlot *
const *sl,
int nsl,
597 int chans,
int rc_eligible,
int rc_global,
598 int rc_rate_frame,
int rc_bmax)
602 int destbits = avctx->
bit_rate * 1024.0 / avctx->
sample_rate / bch * (lambda / 120.f) * chans;
605 float rc_off = 1.0f, lam_dem = 0.0f;
607 for (
int k = 0; k < nsl; k++)
608 is8_any |= sl[k]->is8;
610 if (
s->psy.bitres.alloc >= 0)
611 destbits =
s->psy.bitres.alloc *
613 if (rc_global &&
s->psy.bitres.alloc >= 0) {
614 /* CBR target: nominal + repayment, bounded +-30%/frame */
616 destbits = (rr +
av_clipd(
s->nmr->rc_fill / 2.0, -0.3 * rr, 0.3 * rr)) * chans /
s->channels;
617 }
else if (rc_eligible &&
s->psy.bitres.alloc >= 0) {
618 /* pre-bootstrap CBR frames: target nominal (psy bitres is cold) */
621 destbits =
FFMIN(destbits, 5800 * chans);
622 /* honest budget: subtract the measured non-trellis overhead (section data, ICS,
623 * sf/PNS signalling), which is rate-dependent hence adaptive. */
624 if (
s->nmr->side_inited)
625 destbits =
av_clip(destbits - (
int)(
s->nmr->side_ema * chans /
s->channels), 64, 5800 * chans);
627 /* Held transient burst, bank-aware: spend banked bits, never borrow deep
628 * (payback troughs starve the next transient). */
629 if (
s->nmr->run_burst > 1.0f) {
630 int extra = destbits * (
s->nmr->run_burst - 1.0f);
631 int avail =
FFMAX(0, (
int)((
s->nmr->rc_fill + rc_bmax / 2) * (
int64_t)chans /
s->channels));
632 destbits =
av_clip(destbits +
FFMIN(extra, avail), 64, 6800 * chans);
636 /* corridor bisect around the servoed centre; pressure = stateless
637 * rc_off multiplier (folding it into lam_rc winds up) */
640 int tot, hardcap, rc_cap;
643 cen =
s->nmr->lam_rc * rc_off;
645 /* transient burst: widen the lower bound so the boosted destbits can
646 * actually pour into the onset frame */
647 if (is8_any &&
s->nmr->run_burst > 1.0f)
648 lo /=
s->nmr->run_burst;
653 for (
int k = 0; k < nsl; k++)
655 hardcap =
av_clip((
int)(5800.f *
FFMIN(1.f, lambda / 120.f)), 256, 5800) * chans;
656 /* legality cap only; no spend-floor (rc_off spends the bank) */
657 rc_cap =
FFMIN(hardcap, (
s->nmr->rc_fill + rc_rate_frame + rc_bmax) * chans /
s->channels);
662 /* per-frame bisection, warm-started off the previous frame's lambda;
663 * a result at the bracket edge means redo the full search */
664 float lam0 =
s->nmr->lam[sl[0]->
cur_ch];
668 if (lam < lam0/16.0f || lam > lam0*16.0f)
677 * refine each band at full granularity (NMR_STEP) in a +/-cstep window
678 * around the coarse pick, then re-solve. Recovers single-pass quality while the
679 * lambda search stayed cheap on the coarse grid. */
681 /* nmr_speed, 0 = slowest/best, higher = faster; see the option docs. */
683 for (
int k = 0; k < nsl; k++) {
689 /* the pow34 spectrum and the quantize cache are per-channel state */
690 s->aacdsp.abs_pow34(
s->scoefs, t->
sce->
coeffs, 1024);
692 for (
int b = 0;
b < t->
nbnd;
b++) {
700 for (
int o = 0; o < ncand; o++)
706 /* fine pass: narrow corridor around the coarse solve */
713 lam_dem = lam;
/* demand-solved lambda, pre bucket clamp: what content wants */
716 /* legality clamp, then the quality slew limiter */
717 int hardcap =
av_clip((
int)(5800.f *
FFMIN(1.f, lambda / 120.f)), 256, 5800) * chans;
719 for (
int k = 0; k < nsl; k++)
721 rc_cap =
FFMIN(hardcap, (
s->nmr->rc_fill + rc_rate_frame + rc_bmax) * chans /
s->channels);
725 if (
s->nmr->lam_slew > 0.0f) {
727 /* hold lambda near-constant within short runs; bits follow content */
729 /* a deliberate onset burst may dive as far as its widened corridor
730 * allows; the RECOVERY back up is what must stay gradual */
731 kdn = (is8_any &&
s->nmr->run_burst > 1.0f) ?
NMR_SLEW *
s->nmr->run_burst :
733 if (lam >
s->nmr->lam_slew * kup || lam < s->nmr->lam_slew / kdn) {
734 lam =
av_clipf(lam,
s->nmr->lam_slew / kdn,
s->nmr->lam_slew * kup);
736 /* never at the price of an illegal reservoir excursion */
742 s->nmr->lam_slew = lam;
745 for (
int k = 0; k < nsl; k++)
746 s->nmr->lam[sl[k]->
cur_ch] = lam;
/* warm start for the next frame */
747 {
/* nd: mean achieved dist/real-mask (dimensionless starvation +
748 * noise-class signal) */
749 float ndsum = 0.0f;
int ndn = 0;
750 for (
int k = 0; k < nsl; k++) {
753 for (
int b_ = 0; b_ < t->
nact; b_++) {
761 /* long frames only (short groups inflate the ratio) */
762 if (ndn >= 8 && !is8_any) {
763 float nd = ndsum / ndn;
764 s->nmr->nd_ema =
s->nmr->nd_ema > 0.0f ?
765 0.95f *
s->nmr->nd_ema + 0.05f * nd : nd;
768 {
/* track short vs long operating lambda (dense-beat boost scaling) */
769 float *ema = is8_any ? &
s->nmr->lam_short_ema : &
s->nmr->lam_long_ema;
770 *ema = *ema > 0.0f ? 0.9f * *ema + 0.1f * lam : lam;
771 /* sustained-strain floor: snaps down at any comfortable moment,
772 * recovers only slowly, so bursty content cannot bank pressure
773 * credit between its lambda valleys. */
774 s->nmr->lam_floor =
s->nmr->lam_floor > 0.0f ?
775 fminf(
s->nmr->lam_floor * 1.02f, lam) : lam;
777 {
/* shared rate-pressure ramp: lambda vs nd-scaled anchors */
780 ramp =
s->nmr->lam_long_ema > 0.0f ?
782 (350.0f *
scale - 120.0f *
scale), 0.0f, 1.0f) : 0.0f;
783 /* transparency veto: lambda*nd below ~74 = comfortable */
784 if (
s->nmr->nd_ema > 0.0f)
785 ramp *=
av_clipf((
s->nmr->lam_long_ema *
s->nmr->nd_ema - 60.0f) /
786 (120.0f - 60.0f), 0.0f, 1.0f);
787 s->nmr->press = ramp;
790 /* track the centre toward the CONTENT lambda (demand-solved, pressure
791 * divided out); clamped lambda is rate noise, not content */
794 }
else if (rc_eligible) {
795 /* bootstrap the servo off the first substantive frame (silent lead-ins
796 * have degenerate budgets) */
798 for (
int k = 0; k < nsl; k++)
799 nbnd_max =
FFMAX(nbnd_max, sl[k]->nbnd);
801 s->nmr->lam_rc =
av_clipf(lam, 1e-4f, 1e4f);
802 s->nmr->lam_slew =
s->nmr->lam_rc;
806 {
/* PNS, per channel at the group's operating lambda */
809 for (
int k = 0; k < nsl; k++) {
814 /* band 0 (lowest freq) is kept as the global-gain / sf-chain anchor */
815 for (
int b = 1;
b < t->
nbnd;
b++) {
818 float nmr_pns, cost_keep, cost_pns, frac;
822 int was =
s->nmr->pns_prev[t->
cur_ch & 15][bi];
824 int want = 0, force_exit = 0;
826 /* (can_pns was already checked above; gates below fill `want`) */
828 force_exit = 1;
/* loud-band guard */
829 }
else if (lam > pns_lam) {
830 /* Spectral-hole fill: a noise-like band left mostly empty */
837 /* replace only a band coded audibly badly; cost of
838 * energy-matched noise = its non-noise-like fraction */
839 nmr_pns =
FFMAX(0.0f, t->
pener[bi] * (1.0f - spread*spread))
843 want = cost_pns < cost_keep *
bias;
846 {
/* debounce; near-mask deletion candidates skip entry
847 * (noise beats the ~silent rendition they'd get) */
848 uint8_t *ron = &
s->nmr->pns_run_on [t->
cur_ch & 15][bi];
849 uint8_t *roff = &
s->nmr->pns_run_off[t->
cur_ch & 15][bi];
851 if (want) {
if (*ron < 255) (*ron)++; *roff = 0; }
852 else {
if (*roff < 255) (*roff)++; *ron = 0; }
858 want = 1;
/* physics-hysteresis: noise until audible */
869 for (
int b = 0;
b < t->
nbnd;
b++)
873 pns_total += pns_count;
876 /* re-solve over the survivors: at fixed lambda the allocation is
877 * the same except for the repaired sf-delta chain; in bisection
878 * mode re-spend the freed budget */
887 for (
int k = 0; k < nsl; k++) {
889 uint8_t *pp =
s->nmr->pns_prev[t->
cur_ch & 15];
890 uint8_t now[128] = {0};
891 for (
int b = 0;
b < t->
nbnd;
b++)
894 memcpy(pp, now, 128);
896 for (
int k = 0; k < nsl; k++)
907 /* Global-lambda RC: one solve per frame at a servoed centre lambda; the reservoir
908 * holds the long-run mean rate. Bypassed for VBR (-q:a) and the bootstrap frame. */
911 /* Signed reservoir; soft steering (bounded repay + rc_off), hard cap =
916 int rc_global, defer;
919 s->nmr->counted[
s->cur_channel] = 0;
922 /* the decoder bit reservoir starts FULL: seed it so the head may frontload */
931 n->
pending = 0;
/* a deferred first channel never crosses a frame */
932 /* latch the RC mode per frame: a mid-frame bootstrap must not flip
933 * the CPE defer logic between channels */
936 /* Transient burst run state: set at run start and held across the run so
937 * coding stays uniform; repaid from the reservoir's steady stretches. */
944 /* dense-beat boost, scaled by measured short-frame starvation */
955 /* the frame closing a run (the STOP) absorbs the corridor recoil
956 * of the boosted shorts; give it half the run's factor so the
957 * repayment spreads into the steady stretch instead */
963 rc_global = rc_eligible && n->
rc_gl;
965 /* CPE budget pool: under global-lambda RC, defer the pair's first channel
966 * and solve both against one pooled budget when the second one arrives. */
967 defer = n->
pair && rc_global;
978 n->
pending = 1;
/* wait for the partner channel */
984 int nsl = 0, chans = 1;
989 sl[nsl++] = &n->
slot[0];
991 sl[nsl++] = &n->
slot[1];
992 }
else if (t->
nact) {
996 return;
/* nothing codeable in the group */
998 rc_eligible, rc_global, rc_rate_frame, rc_bmax);
1002#endif /* AVCODEC_AACCODER_NMR_H */
AAC definitions and structures.
#define SCALE_MAX_DIFF
maximum scalefactor difference allowed by standard
@ INTENSITY_BT
Scalefactor data are intensity stereo positions (in phase).
@ INTENSITY_BT2
Scalefactor data are intensity stereo positions (out of phase).
@ RESERVED_BT
Band types following are encoded differently from others.
@ NOISE_BT
Spectral data are scaled white noise not coded in the bitstream.
#define SCALE_MAX_POS
scalefactor index maximum value
static void search_for_quantizers_nmr(AVCodecContext *avctx, AACEncContext *s, SingleChannelElement *sce, const float lambda)
static float nmr_solve_slots(AACEncContext *s, NMRSlot *const *sl, int nsl, int step, int destbits, float lo_l, float hi_l, int iters)
static int nmr_setup_channel(AVCodecContext *avctx, AACEncContext *s, SingleChannelElement *sce, NMRSlot *t)
static void nmr_solve_group(AVCodecContext *avctx, AACEncContext *s, const float lambda, NMRSlot *const *sl, int nsl, int chans, int rc_eligible, int rc_global, int rc_rate_frame, int rc_bmax)
#define NMR_PNS_HOLE_SPREAD
#define NMR_PNS_HOLE_FRAC
static int nmr_slot_bits(const NMRSlot *t, const int(*nb)[NMR_NCAND], int step)
static int nmr_eval_slots(AACEncContext *s, NMRSlot *const *sl, int nsl, int step, float lam)
static int nmr_band_curve(AACEncContext *s, SingleChannelElement *sce, int w, int g, int start, int lo, int step, int maxn, float invthr, float maxval, float *nd_row, int *nb_row)
#define NMR_SFBITS(d)
AAC encoder NMR scalefactor coder.
static float nmr_solve(AACEncContext *s, const float(*nd)[NMR_NCAND], const int(*nb)[NMR_NCAND], const int *blo, const int *bnc, int step, const int *act, int nact, int destbits, int *chosen, float lo_l, float hi_l, int iters)
Viterbi over the coding sequence act[0..nact-1] (indices into the per-band curves nd/nb),...
static void nmr_commit_channel(AACEncContext *s, NMRSlot *t)
static void nmr_bail_channel(SingleChannelElement *sce)
void ff_quantize_band_cost_cache_init(struct AACEncContext *s)
#define NMR_NCAND
per-band scalefactor candidates above the finest codeable sf (NMR coder)
static float quantize_band_cost_cached(struct AACEncContext *s, int w, int g, const float *in, const float *scaled, int size, int scale_idx, int cb, const float lambda, const float uplim, int *bits, float *energy, int rtz)
static void ff_init_nextband_map(const SingleChannelElement *sce, uint8_t *nextband)
static int find_min_book(float maxval, int sf)
static float find_max_val(int group_len, int swb_size, const float *scaled)
static uint8_t coef2minsf(float coef)
Return the minimum scalefactor where the quantized coef does not clip.
static int ff_sfdelta_can_remove_band(const SingleChannelElement *sce, const uint8_t *nextband, int prev_sf, int band)
const uint8_t ff_aac_scalefactor_bits[121]
static const int8_t filt[NUMTAPS *2]
static float win(SuperEqualizerContext *s, float n, int N)
Libavcodec external API header.
#define i(width, name, range_min, range_max)
static __device__ float sqrtf(float a)
float fminf(float, float)
#define AV_CODEC_FLAG_QSCALE
Use fixed qscale.
static void scale(int *out, const int *in, const int w, const int h, const int shift)
int frames_since_short
long-block frames since the last short run (the "gap"): large = isolated transient
NMRSlot slot[2]
pair slots (solo solves use slot 0)
float run_burst
transient bit-burst factor, set at run start and held across the short run
int rc_fill
virtual bit reservoir fill, + = bits saved vs nominal
int rc_gl
rc_global latched at frame start: the corridor bootstrap must not flip the CPE defer logic between ch...
float lam_short_ema
smoothed operating lambda of short frames
int64_t rc_frame_num
frame the reservoir was last advanced for
float lam_long_ema
smoothed operating lambda of long frames
int pending
slot 0 holds a deferred first channel
int prev_was_short
previous frame was a short block (for run-start detection)
float lam_rc
global-lambda rate control: operating lambda, 0 until bootstrapped
int rc_fill_seeded
reservoir seeded full at stream start (decoder buffer starts full)
int pair
current element is a CPE: pool the pair budget
int nb_channels
Number of channels in this layout.
main external API structure.
AVChannelLayout ch_layout
Audio channel layout.
int global_quality
Global quality for codecs which cannot change it per frame.
int64_t frame_num
Frame counter, set by libavcodec.
int bit_rate_tolerance
number of bits the bitstream is allowed to diverge from the reference.
int64_t bit_rate
the average bitrate
int sample_rate
samples per second
int flags
AV_CODEC_FLAG_*.
single band psychoacoustic information
uint8_t max_sfb
number of scalefactor bands per group
int num_swb
number of scalefactor window bands
const uint8_t * swb_sizes
table of scalefactor band sizes for a particular window
enum WindowSequence window_sequence[2]
const uint16_t * swb_offset
table of offsets to the lowest spectral coefficient of a scalefactor band, sfb, for a particular wind...
NMR coder per-band candidate cost curves (~96 KiB) and rate-control carry-over.
float pspread[128]
band tonality spread (1 = noise)
float tnsg[128]
TNS synthesis gain per band for THIS solve (1 = uncovered), M/S-aware (pair max)
int bst[128]
window group, swb, coef start
struct SingleChannelElement * sce
int bnc[128]
number of candidates
float thr_real[128]
real masking threshold (PNS gates)
uint8_t is_pns[128]
band coded as noise
int si
curve-bank index (nd/nb slot)
float pener[128]
band energy (PNS noise target)
float thr[128]
allocation-law effective threshold
int bidx[128]
sce band index (w*16+g)
int nbnd
coded-band count, 0 = nothing codeable
int blo[128]
finest candidate scalefactor
int act[128]
active (non-PNS) band coding order
int is8
EIGHT_SHORT frame.
int cur_ch
encoder channel index (psy/cache context)
Single Channel Element - used for both SCE and LFE elements.
uint8_t zeroes[128]
band is not coded
float coeffs[1024]
coefficients for IMDCT, maybe processed
uint8_t can_pns[128]
band is allowed to PNS (informative)
float pns_ener[128]
Noise energy values.
enum BandType band_type[128]
band types
IndividualChannelStream ics
int sf_idx[128]
scalefactor indices
static double cb(void *priv, double x, double y)
static float mean(const float *input, int size)
static double b0(void *priv, double x, double y)
static int bias(int x, int c)