FFmpeg
aaccoder_nmr.h
Go to the documentation of this file.
1 /*
2  * AAC encoder NMR (noise-to-mask ratio) scalefactor coder
3  * Copyright (c) 2026 Lynne <dev@lynne.ee>
4  *
5  * This file is part of FFmpeg.
6  *
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.
11  *
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.
16  *
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
20  */
21 
22 /**
23  * AAC encoder NMR scalefactor coder.
24  *
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
33  *
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.
41  */
42 
43 #ifndef AVCODEC_AACCODER_NMR_H
44 #define AVCODEC_AACCODER_NMR_H
45 
46 #include <float.h>
47 #include <string.h>
48 #include "libavutil/mathematics.h"
49 #include "mathops.h"
50 #include "avcodec.h"
51 #include "put_bits.h"
52 #include "aac.h"
53 #include "aacenc.h"
54 #include "aactab.h"
55 #include "aacenctab.h"
56 
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)]
59 
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 */
69 
70 #define NMR_PNS_BITS 9 /* approx cost in bits of signalling PNS */
71 
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
76 
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
80 
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
85 
86 /* Leaky-bucket half-depth (bits/ch); 512 is the sweet spot — tighter rebounds as
87  * frames cannot hit the narrow window. Clamped to the 6144 bits/ch decoder buffer. */
88 #define NMR_CBR_BUF 512
89 #define NMR_RC_CITERS 3 /* corridor coarse-pass iters */
90 
91 /* Transient bit-burst: an isolated onset (preceded by >= NMR_BURST_GAP long frames)
92  * is coded NMR_BURST_GAIN x finer, held uniform across the run, repaid from steady stretches. */
93 #define NMR_BURST_GAP 10
94 #define NMR_BURST_GAIN 8.0f
95 #define NMR_RC_FITERS 4 /* corridor fine-pass iters */
96 #define NMR_RC_TRACK 0.1f /* per-frame pull of the corridor centre toward the realized lambda */
97 
98 /* PNS noise-distortion gate: only bands coded well above the masking floor become noise. */
99 #define NMR_PNS_NDGATE 4.0f
100 
101 /* Energy/threshold cap for PNS: loud bands (energy >> mask) yield clipping random peaks;
102  * only near-masked bands are safe substitution targets. */
103 #define NMR_PNS_MAX_ET 8.0f
104 
105 /* Operating-lambda floor for PNS: below it the encoder is not struggling, so
106  * substituting real texture for 9 signalling bits is net-negative. */
107 #define NMR_PNS_LAM 100.0f
108 
109 /**
110  * Viterbi over the coding sequence act[0..nact-1] (indices into the per-band
111  * curves nd/nb), with lambda binary-searched so the coded size ~ destbits.
112  * Fills chosen[band] for every band referenced by act. Returns the operating
113  * lambda. node cost = dist/threshold + lambda*spectral_bits;
114  * edge cost = lambda*sf_differential_bits; |delta sf| <= SCALE_MAX_DIFF hard.
115  */
116 static float nmr_solve(AACEncContext *s,
117  const float (*nd)[NMR_NCAND], const int (*nb)[NMR_NCAND],
118  const int *blo, const int *bnc, int step,
119  const int *act, int nact, int destbits, int *chosen,
120  float lo_l, float hi_l, int iters)
121 {
122  float dp[NMR_NCAND], dpp[NMR_NCAND], node[NMR_NCAND];
123  float lamsf[2*SCALE_MAX_DIFF + 1]; /* lam*sfdiff bit cost, per lambda */
124  uint8_t bp[128][NMR_NCAND];
125  float lam = 1.0f;
126 
127  if (nact <= 0)
128  return lam;
129 
130  for (int it = 0; it < iters; it++) {
131  lam = sqrtf(lo_l * hi_l);
132  for (int i = 0; i <= 2*SCALE_MAX_DIFF; i++)
133  lamsf[i] = lam * ff_aac_scalefactor_bits[i]; /* edge cost for this lambda */
134 
135  int b0 = act[0];
136  for (int o = 0; o < bnc[b0]; o++)
137  dp[o] = nd[b0][o] + lam * nb[b0][o]; /* anchor band node cost */
138 
139  for (int k = 1; k < nact; k++) {
140  int b = act[k], pb = act[k-1];
141  memcpy(dpp, dp, sizeof(dp));
142  for (int o = 0; o < bnc[b]; o++)
143  node[o] = nd[b][o] + lam * nb[b][o];
144  /* dp[o] = node[o] + min_op(dpp[op] + edge cost) */
145  s->aacdsp.nmr_trellis_step(dp, bp[k], dpp, node, lamsf,
146  bnc[b], bnc[pb], blo[b] - blo[pb], step,
148  }
149 
150  /* backtrack */
151  int beo = 0, b = act[nact-1];
152  float bec = FLT_MAX;
153  for (int o = 0; o < bnc[b]; o++)
154  if (dp[o] < bec) { bec = dp[o]; beo = o; }
155  chosen[b] = beo;
156  for (int k = nact-1; k > 0; k--)
157  chosen[act[k-1]] = bp[k][chosen[act[k]]];
158 
159  /* calc cost */
160  int total = 0;
161  for (int k = 0; k < nact; k++)
162  total += nb[act[k]][chosen[act[k]]];
163  for (int k = 1; k < nact; k++)
164  total += NMR_SFBITS((blo[act[k]]+chosen[act[k]]*step) - (blo[act[k-1]]+chosen[act[k-1]]*step));
165 
166  if (it == iters - 1)
167  break;
168 
169  /* check if we went over budget, go coarser if we did */
170  if (total > destbits)
171  lo_l = lam;
172  else
173  hi_l = lam;
174  }
175  return lam;
176 }
177 
178 /* Build one coded band's (dist/threshold, bits) cost curve, candidates sf = lo + o*step
179  * for o in [0,maxn), stopping when the band would drop (cb <= 0). Returns the bit count. */
180 static int nmr_band_curve(AACEncContext *s, SingleChannelElement *sce, int w, int g,
181  int start, int lo, int step, int maxn, float invthr,
182  float maxval, float *nd_row, int *nb_row)
183 {
184  int ncand = 0;
185  for (int o = 0; o < maxn && lo + o*step <= SCALE_MAX_POS; o++) {
186  int sf = lo + o*step, btot = 0, cb = find_min_book(maxval, sf);
187  float dist = 0.0f;
188  if (cb <= 0)
189  break;
190  for (int w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
191  int bb;
192  dist += quantize_band_cost_cached(s, w + w2, g, sce->coeffs + start + w2*128,
193  s->scoefs + start + w2*128, sce->ics.swb_sizes[g],
194  sf, cb, 1.0f, INFINITY, &bb, NULL, 0);
195  btot += bb;
196  }
197  nd_row[ncand] = (dist - btot) * invthr;
198  nb_row[ncand] = btot;
199  ncand++;
200  }
201  return ncand;
202 }
203 
204 static void search_for_quantizers_nmr(AVCodecContext *avctx,
205  AACEncContext *s,
207  const float lambda)
208 {
209  int bch = ((avctx->flags & AV_CODEC_FLAG_QSCALE) ? 2.0f : avctx->ch_layout.nb_channels);
210  int destbits = avctx->bit_rate * 1024.0 / avctx->sample_rate / bch * (lambda / 120.f);
211  int allz = 0, cutoff = 1024, nbnd = 0;
212 
213  float thr[128]; /* allocation-law effective threshold (drives the trellis) */
214  float thr_real[128]; /* real masking threshold (perceptual gates: PNS) */
215  float pener[128]; /* band energy (for PNS noise target) */
216  float pspread[128]; /* band tonality spread (1 = noise) */
217  int minsf[128];
218  float maxvals[128];
219 
220  /* coded-band trellis state (indexed 0..nbnd-1) */
221  int bidx[128]; /* sce band index (w*16+g) */
222  int bw[128], bg[128], bst[128]; /* window group, swb, coef start per coded band */
223  int blo[128]; /* finest candidate scalefactor */
224  int bnc[128]; /* number of candidates */
225  int chosen[128];
226  int act[128]; /* active (non-PNS) band coding order */
227  uint8_t is_pns[128]; /* trellis band coded as noise */
228 
229  float (*nd)[NMR_NCAND] = s->nmr->nd; /* dist / threshold per candidate (heap) */
230  int (*nb)[NMR_NCAND] = s->nmr->nb; /* spectral bits per candidate (heap) */
231 
232  /* two-pass coarse->fine grid step (see NMR_COARSE), the lambda search runs on
233  * the cheap coarse grid, PASS 2 refines the winner at NMR_STEP granularity */
234  const int cstep = NMR_COARSE > 0 ? NMR_COARSE : NMR_STEP;
235 
236  s->nmr->counted[s->cur_channel] = 0;
237 
238  /* Global-lambda RC: one solve per frame at a servoed centre lambda; the reservoir
239  * holds the long-run mean rate. Bypassed for VBR (-q:a) and the bootstrap frame. */
240  int rc_eligible = !(avctx->flags & AV_CODEC_FLAG_QSCALE) && avctx->bit_rate > 0 &&
241  avctx->bit_rate_tolerance != 0;
242  /* Leaky-bucket reservoir: rc_fill (signed +-rc_bmax); the spend-floor/cap below force
243  * lambda so no frame banks past +rc_bmax or borrows past -rc_bmax. */
244  int rc_rate_frame = avctx->bit_rate * 1024.0 / avctx->sample_rate;
245  int rc_bmax = FFMIN(FFMAX(6144 * s->channels - rc_rate_frame, 256), NMR_CBR_BUF * s->channels);
246  if (rc_eligible && avctx->frame_num != s->nmr->rc_frame_num) {
247  if (s->nmr->rc_frame_num > 0 && s->nmr->lam_rc > 0.0f)
248  s->nmr->rc_fill = av_clip(s->nmr->rc_fill + rc_rate_frame - s->last_frame_pb_count,
249  -rc_bmax, rc_bmax);
250  s->nmr->rc_frame_num = avctx->frame_num;
251 
252  /* Transient burst run state: set at run start and held across the run so
253  * coding stays uniform; repaid from the reservoir's steady stretches. */
254  int is_short = sce->ics.window_sequence[0] == EIGHT_SHORT_SEQUENCE;
255  if (is_short) {
256  if (!s->nmr->prev_was_short) /* run start */
257  s->nmr->run_burst = s->nmr->frames_since_short >= NMR_BURST_GAP
258  ? NMR_BURST_GAIN : 1.0f;
259  s->nmr->frames_since_short = 0;
260  } else {
261  s->nmr->run_burst = 1.0f;
262  s->nmr->frames_since_short++;
263  }
264  s->nmr->prev_was_short = is_short;
265  }
266  int rc_global = rc_eligible && s->nmr->lam_rc > 0.0f;
267 
268  if (s->psy.bitres.alloc >= 0)
269  destbits = s->psy.bitres.alloc *
270  (lambda / (avctx->global_quality ? avctx->global_quality : 120));
271  if (rc_global && s->psy.bitres.alloc >= 0)
272  /* uniform CBR target: nominal rate plus fast reservoir repayment */
273  destbits = (avctx->bit_rate * 1024.0 / avctx->sample_rate
274  + s->nmr->rc_fill / 2.0) / s->channels;
275  destbits = FFMIN(destbits, 5800);
276  /* honest budget: subtract the measured non-trellis overhead (section data, ICS,
277  * sf/PNS signalling), which is rate-dependent hence adaptive. */
278  if (s->nmr->side_inited)
279  destbits = av_clip(destbits - (int)(s->nmr->side_ema / s->channels), 64, 5800);
280 
281  /* Apply the held transient burst factor (set in the run-state machine above). */
282  if (sce->ics.window_sequence[0] == EIGHT_SHORT_SEQUENCE && s->nmr->run_burst > 1.0f)
283  destbits = av_clip((int)(destbits * s->nmr->run_burst), 64, 6800);
284 
285  /* band cutoff index for this frame's window size; the bandwidth is fixed
286  * at init and shared with the psy model */
287  cutoff = s->bandwidth * 2 * (1024 / sce->ics.num_windows) / avctx->sample_rate;
288 
289  /* Short-block transient noise shaping (pairs with short-block TNS): temporal
290  * premasking clamps each window's threshold toward the preceding windows'
291  * (Apple's preEchoReduction), and flat-residual flattens each window's thresholds
292  * to their per-window mean so TNS synthesis has a white floor to concentrate. */
294  const float pm_p1 = 0.1f, pm_p2 = 2.0f, pm_p3 = 4.0f;
295  for (int g = 0; g < sce->ics.num_swb; g++) {
296  float t1 = FLT_MAX, t2 = FLT_MAX; /* original thr of w-1, w-2 */
297  for (int w = 0; w < sce->ics.num_windows; w++) {
298  FFPsyBand *b = &s->psy.ch[s->cur_channel].psy_bands[w*16+g];
299  float t = b->threshold;
300  float c = FFMIN(t, FFMIN(t1*pm_p2, t2*pm_p3));
301  b->threshold = FFMAX(c, t*pm_p1);
302  t2 = t1; t1 = t;
303  }
304  }
305  {
306  for (int w = 0; w < sce->ics.num_windows; w++) {
307  float sum = 0.0f; int n = 0;
308  for (int g = 0; g < sce->ics.num_swb; g++) {
309  FFPsyBand *b = &s->psy.ch[s->cur_channel].psy_bands[w*16+g];
310  if (b->energy > b->threshold && b->threshold > 0.0f) { sum += b->threshold; n++; }
311  }
312  if (n > 0) {
313  float mean = sum / n;
314  for (int g = 0; g < sce->ics.num_swb; g++) {
315  FFPsyBand *b = &s->psy.ch[s->cur_channel].psy_bands[w*16+g];
316  if (b->energy > b->threshold && b->threshold > 0.0f)
317  b->threshold = mean;
318  }
319  }
320  }
321  }
322  }
323 
324  /* Allocation curve to favour high frequencies */
325  const float a_ae = 0.443f, a_at = 0.111f;
326  for (int w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
327  int start = 0;
328  for (int g = 0; g < sce->ics.num_swb; start += sce->ics.swb_sizes[g++]) {
329  float uplim = 0.0f, ener = 0.0f, spread = 2.0f;
330  int nz = 0;
331  if (sce->band_type[w*16+g] == INTENSITY_BT ||
332  sce->band_type[w*16+g] == INTENSITY_BT2) {
333  /* pre-decided intensity band (right channel): keep its
334  * signalling, it is not trellis-coded */
335  for (int w2 = 0; w2 < sce->ics.group_len[w]; w2++)
336  sce->zeroes[(w+w2)*16+g] = 0;
337  continue;
338  }
339  for (int w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
340  FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
341  ener += band->energy;
342  spread = FFMIN(spread, band->spread);
343  if (start >= cutoff || band->energy <= band->threshold || band->threshold == 0.0f) {
344  sce->zeroes[(w+w2)*16+g] = 1;
345  continue;
346  }
347  uplim += band->threshold;
348  nz = 1;
349  }
350  sce->zeroes[w*16+g] = !nz;
351  thr_real[w*16+g] = uplim; /* real mask, before the allocation law (PNS gate) */
352  if (nz && ener > 0.0f && uplim > 0.0f)
353  uplim = expf(a_ae * logf(ener) + a_at * logf(uplim));
354  thr[w*16+g] = uplim;
355  pener[w*16+g] = ener;
356  pspread[w*16+g] = spread;
357  allz |= nz;
358  }
359  }
360  if (!allz)
361  goto bail;
362 
363  s->aacdsp.abs_pow34(s->scoefs, sce->coeffs, 1024);
365 
366  /* finest codeable scalefactor and max value per band */
367  for (int w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
368  int start = w*128;
369  for (int g = 0; g < sce->ics.num_swb; g++) {
370  maxvals[w*16+g] = find_max_val(sce->ics.group_len[w], sce->ics.swb_sizes[g], s->scoefs + start);
371  minsf[w*16+g] = maxvals[w*16+g] > 0 ? coef2minsf(maxvals[w*16+g]) : 0;
372  start += sce->ics.swb_sizes[g];
373  }
374  }
375 
376  /* PASS 1:
377  * precompute each coded band's cost curve at the coarse candidate step
378  * (the lambda search runs on this cheap grid, PASS 2 refines the winner) */
379  {
380  for (int w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
381  int start = w*128;
382  for (int g = 0; g < sce->ics.num_swb; g++) {
383  if (!sce->zeroes[w*16+g] && maxvals[w*16+g] > 0 && nbnd < 128) {
384  int lo = av_clip(minsf[w*16+g], 0, SCALE_MAX_POS);
385  float invthr = 1.0f / FFMAX(thr[w*16+g], 1e-9f);
386  int ncand = nmr_band_curve(s, sce, w, g, start, lo, cstep, NMR_NCAND,
387  invthr, maxvals[w*16+g], nd[nbnd], nb[nbnd]);
388  if (ncand == 0) {
389  /* nothing codeable -> drop the whole group band. The
390  * subwindow flags must be cleared too: the encoder later
391  * re-derives the group flag by ANDing them, which would
392  * resurrect the band with a never-assigned scalefactor. */
393  for (int w2 = 0; w2 < sce->ics.group_len[w]; w2++)
394  sce->zeroes[(w+w2)*16+g] = 1;
395  } else {
396  bidx[nbnd] = w*16+g;
397  bw[nbnd] = w;
398  bg[nbnd] = g;
399  bst[nbnd] = start;
400  blo[nbnd] = lo;
401  bnc[nbnd] = ncand;
402  nbnd++;
403  }
404  }
405  start += sce->ics.swb_sizes[g];
406  }
407  }
408  }
409  if (!nbnd)
410  goto bail;
411 
412  /* solve the trellis over all coded bands, then offer PNS at the operating
413  * lambda and re-solve over the survivors with the freed budget */
414  {
415  int nact = nbnd, pns_count = 0;
416  float lam0 = s->nmr->lam[s->cur_channel];
417  float lam;
418 
419  for (int b = 0; b < nbnd; b++) {
420  act[b] = b;
421  is_pns[b] = 0;
422  }
423  if (rc_global) {
424  /* bisect to this frame's bit demand within the corridor around the
425  * servoed lambda: per-frame psy demand is tracked, but lambda cannot
426  * jump, which keeps quality smooth across frames */
427  float lo = s->nmr->lam_rc / NMR_RC_CORR;
428  /* Transient burst: widen the lower lambda bound so the bisection can actually
429  * pour the boosted destbits into an onset frame (finer coding kills the
430  * pre-echo); reservoir servo repays it from the steady frames. run_burst==1 on
431  * non-onset frames leaves the corridor unchanged. */
432  if (sce->ics.window_sequence[0] == EIGHT_SHORT_SEQUENCE && s->nmr->run_burst > 1.0f)
433  lo /= s->nmr->run_burst;
434  lam = nmr_solve(s, nd, nb, blo, bnc, cstep, act, nact, destbits, chosen,
435  lo, s->nmr->lam_rc * NMR_RC_CORR,
436  NMR_RC_CITERS);
437 
438  int tot = 0;
439  for (int k = 0; k < nact; k++)
440  tot += nb[act[k]][chosen[act[k]]];
441  for (int k = 1; k < nact; k++)
442  tot += NMR_SFBITS((blo[act[k]]+chosen[act[k]]*cstep) - (blo[act[k-1]]+chosen[act[k-1]]*cstep));
443  int hardcap = av_clip((int)(5800.f * FFMIN(1.f, lambda / 120.f)), 256, 5800);
444  /* leaky-bucket window: don't borrow past -rc_bmax (cap) or bank past +rc_bmax (floor) */
445  int rc_cap = FFMIN(hardcap, (s->nmr->rc_fill + rc_rate_frame + rc_bmax) / s->channels);
446  int rc_floor = FFMAX(0, (s->nmr->rc_fill + rc_rate_frame - rc_bmax) / s->channels);
447  if (tot > rc_cap)
448  lam = nmr_solve(s, nd, nb, blo, bnc, cstep, act, nact, rc_cap, chosen,
449  lam, 1e4f, NMR_CITERS);
450  else if (tot < rc_floor)
451  lam = nmr_solve(s, nd, nb, blo, bnc, cstep, act, nact, rc_floor, chosen,
452  1e-9f, lam, NMR_CITERS);
453  } else if (NMR_COARSE > 0 && lam0 > 0.0f) {
454  /* per-frame bisection; lambda is strongly frame-correlated, so when a
455  * previous frame's operating lambda exists, bisect a narrow bracket
456  * around it. A result near the bracket edge means the budget crossing
457  * lies outside (hard content transition) == redo the full search. */
458  lam = nmr_solve(s, nd, nb, blo, bnc, cstep, act, nact, destbits, chosen,
459  lam0/32.0f, lam0*32.0f, NMR_CWARM);
460  if (lam < lam0/16.0f || lam > lam0*16.0f)
461  lam0 = 0.0f;
462  }
463  if (!rc_global && lam0 <= 0.0f)
464  lam = nmr_solve(s, nd, nb, blo, bnc, cstep, act, nact, destbits, chosen,
465  1e-9f, 1e4f, NMR_COARSE > 0 ? NMR_CITERS : NMR_ITERS);
466 
467  /* PASS 2:
468  * refine each band at full granularity (NMR_STEP) in a +/-cstep window
469  * around the coarse pick, then re-solve. Recovers single-pass quality while the
470  * lambda search stayed cheap on the coarse grid. */
471  if (NMR_COARSE > 0) {
472  /* nmr_speed, 0 = slowest/best, higher = faster. It narrows the fine
473  * refine +/-window (scalefactors) below NMR_COARSE: at speed 0 the window
474  * spans the whole coarse-grid gap, so the two-pass result matches the
475  * exhaustive single-pass search.
476  * Each speed level shaves one sf off the window.
477  * At @64k mono (Zim / xRT): speed 0 -> 0.00095/15x,
478  * 2 -> 0.00096/18x, 3 -> 0.00100/20x, 4 -> 0.00103/22x */
479  int win = NMR_COARSE - av_clip(s->options.nmr_speed, 0, 4);
480  for (int b = 0; b < nbnd; b++) {
481  int center = blo[b] + chosen[b]*cstep;
482  int flo = av_clip(center - win, av_clip(minsf[bidx[b]], 0, SCALE_MAX_POS), SCALE_MAX_POS);
483  int maxn = FFMIN(NMR_NCAND, 2*win/NMR_STEP + 1);
484  float invthr = 1.0f / FFMAX(thr[bidx[b]], 1e-9f);
485  int ncand = nmr_band_curve(s, sce, bw[b], bg[b], bst[b], flo, NMR_STEP, maxn,
486  invthr, maxvals[bidx[b]], nd[b], nb[b]);
487  blo[b] = flo;
488  bnc[b] = FFMAX(1, ncand);
489  }
490  /* fine pass: narrow corridor around the coarse solve */
491  if (rc_global)
492  lam = nmr_solve(s, nd, nb, blo, bnc, NMR_STEP, act, nact, destbits, chosen,
493  lam/2.0f, lam*2.0f, NMR_RC_FITERS);
494  else
495  lam = nmr_solve(s, nd, nb, blo, bnc, NMR_STEP, act, nact, destbits, chosen,
496  lam/16.0f, lam*16.0f, NMR_IFINE);
497  }
498 
499  if (rc_global) {
500  /* leaky-bucket clamp: keep the frame within [rc_floor, rc_cap] so the reservoir
501  * stays in +-rc_bmax -- clamp lambda UP if it would borrow past the cap, DOWN if it
502  * would bank past the floor (spend-floor). The hard cap follows the encoder's outer
503  * lambda so the (rare) hard-overflow re-encode -- which shrinks that lambda -- always
504  * converges; on the first pass lambda is nominal and this is 5800. */
505  int hardcap = av_clip((int)(5800.f * FFMIN(1.f, lambda / 120.f)), 256, 5800);
506  int tot = 0;
507  for (int k = 0; k < nact; k++)
508  tot += nb[act[k]][chosen[act[k]]];
509  for (int k = 1; k < nact; k++)
510  tot += NMR_SFBITS((blo[act[k]]+chosen[act[k]]*NMR_STEP) - (blo[act[k-1]]+chosen[act[k-1]]*NMR_STEP));
511  int rc_cap = FFMIN(hardcap, (s->nmr->rc_fill + rc_rate_frame + rc_bmax) / s->channels);
512  int rc_floor = FFMAX(0, (s->nmr->rc_fill + rc_rate_frame - rc_bmax) / s->channels);
513  if (tot > rc_cap)
514  lam = nmr_solve(s, nd, nb, blo, bnc, NMR_STEP, act, nact, rc_cap, chosen,
515  lam, 1e4f, NMR_RC_ITERS);
516  else if (tot < rc_floor)
517  lam = nmr_solve(s, nd, nb, blo, bnc, NMR_STEP, act, nact, rc_floor, chosen,
518  1e-9f, lam, NMR_RC_ITERS);
519  }
520 
521  s->nmr->lam[s->cur_channel] = lam; /* warm start for the next frame */
522  if (rc_global) {
523  /* drag the corridor centre toward the realized lambda so it follows
524  * content drift faster than the reservoir term alone */
525  float c = s->nmr->lam_rc * powf(lam / s->nmr->lam_rc, NMR_RC_TRACK);
526  /* then servo the centre off the reservoir error so the long-run rate
527  * returns to nominal. rc_fill>0 = bits banked (undershooting) -> lower
528  * lambda to spend them; <0 -> raise it. This is what holds the mean;
529  * the corridor tracking alone has no rate authority and a bad centre
530  * would otherwise drift for dozens of frames, starving each one. */
531  float R = avctx->bit_rate * 1024.0 / avctx->sample_rate;
532  c *= exp2f(-NMR_RC_K_CBR * s->nmr->rc_fill / R);
533  s->nmr->lam_rc = av_clipf(c, 1e-6f, 1e4f);
534  } else if (rc_eligible && nbnd >= 8) {
535  /* bootstrap the servo off the first substantive frame; near-silent
536  * lead-in frames have degenerate budgets that rail the bisection to
537  * a nonsense lambda and would poison the whole stream */
538  s->nmr->lam_rc = av_clipf(lam, 1e-4f, 10.0f);
539  }
540 
541  { /* PNS */
542  const float pns_lam = NMR_PNS_LAM;
543  /* band 0 (lowest freq) is kept as the global-gain / sf-chain anchor */
544  for (int b = 1; b < nbnd; b++) {
545  int bi = bidx[b];
546  float spread = pspread[bi];
547  float nmr_pns, cost_keep, cost_pns, frac;
548  if (!sce->can_pns[bi])
549  continue;
550 
551  /* Loud-band guard: never substitute a band whose energy is far above the
552  * masking threshold -- energy-matched noise on a dominant band clips/pops
553  * (and is audibly wrong). PNS is for near-masked noise only. */
554  if (pener[bi] > NMR_PNS_MAX_ET * thr_real[bi])
555  continue;
556 
557  /* Struggle gate: no PNS at all unless the encoder is genuinely under bit
558  * pressure (high operating lambda). */
559  if (lam <= pns_lam)
560  continue;
561 
562  /* Spectral-hole fill: a noise-like band the trellis left mostly empty */
563  frac = nd[b][chosen[b]] * thr[bi] / FFMAX(pener[bi], 1e-9f);
564  if (spread > NMR_PNS_HOLE_SPREAD && frac > NMR_PNS_HOLE_FRAC) {
565  is_pns[b] = 1;
566  pns_count++;
567  continue;
568  }
569 
570  /* Only replace a band that is being coded audibly badly */
571  if (nd[b][chosen[b]] * thr[bi] <= NMR_PNS_NDGATE * thr_real[bi])
572  continue;
573 
574  /* perceptual cost of replacing the band with energy-matched noise:
575  * the non-noise-like fraction of its energy, in dist/threshold units */
576  nmr_pns = FFMAX(0.0f, pener[bi] * (1.0f - spread*spread))
577  / FFMAX(thr[bi], 1e-9f);
578  cost_keep = nd[b][chosen[b]] + lam * nb[b][chosen[b]];
579  cost_pns = nmr_pns + lam * NMR_PNS_BITS;
580  if (cost_pns < cost_keep) {
581  is_pns[b] = 1;
582  pns_count++;
583  }
584  }
585  if (pns_count) {
586  int budget2 = destbits - pns_count * NMR_PNS_BITS;
587  nact = 0;
588  for (int b = 0; b < nbnd; b++)
589  if (!is_pns[b])
590  act[nact++] = b;
591  /* re-solve over the survivors: at fixed lambda the allocation is
592  * the same except for the repaired sf-delta chain; in bisection
593  * mode re-spend the freed budget */
594  if (rc_global)
595  nmr_solve(s, nd, nb, blo, bnc, NMR_STEP, act, nact, budget2, chosen,
596  lam, lam, 1);
597  else
598  nmr_solve(s, nd, nb, blo, bnc, NMR_STEP, act, nact, budget2, chosen,
599  1e-9f, 1e4f, NMR_ITERS);
600  }
601  }
602  for (int b = 0; b < nbnd; b++) {
603  int bi = bidx[b];
604  if (is_pns[b]) {
605  sce->band_type[bi] = NOISE_BT;
606  sce->zeroes[bi] = 0;
607  sce->pns_ener[bi] = pener[bi] * FFMIN(1.0f, pspread[bi]*pspread[bi]);
608  } else {
609  sce->sf_idx[bi] = av_clip(blo[b] + chosen[b]*NMR_STEP, 0, SCALE_MAX_POS);
610  }
611  }
612 
613  { /* record the bits this solve accounted for; the encoder compares them
614  * against the channel's real output to keep the budget honest */
615  int tot = 0, prevb = -1;
616  for (int b = 0; b < nbnd; b++) {
617  if (is_pns[b])
618  continue;
619  tot += nb[b][chosen[b]];
620  if (prevb >= 0)
621  tot += NMR_SFBITS((blo[b]+chosen[b]*NMR_STEP) - (blo[prevb]+chosen[prevb]*NMR_STEP));
622  prevb = b;
623  }
624  s->nmr->counted[s->cur_channel] = tot;
625  }
626  }
627 
628  /* SCALE_MAX_DIFF condition:
629  * re-clamp, codebook fixup, drop uncodeable, set global gain
630  * NOISE_BT bands keep their own scalefactor chain via set_special_band_scalefactors) */
631  {
632  uint8_t nextband[128];
633  int prev = -1;
634  ff_init_nextband_map(sce, nextband);
635  for (int w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
636  for (int g = 0; g < sce->ics.num_swb; g++) {
637  if (sce->band_type[w*16+g] == NOISE_BT ||
638  sce->band_type[w*16+g] == INTENSITY_BT ||
639  sce->band_type[w*16+g] == INTENSITY_BT2)
640  continue;
641  if (sce->zeroes[w*16+g]) {
642  sce->band_type[w*16+g] = 0;
643  continue;
644  }
645 
646  if (prev != -1)
647  sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], prev - SCALE_MAX_DIFF, prev + SCALE_MAX_DIFF);
648  sce->band_type[w*16+g] = find_min_book(maxvals[w*16+g], sce->sf_idx[w*16+g]);
649  if (sce->band_type[w*16+g] <= 0) {
650  if (!ff_sfdelta_can_remove_band(sce, nextband, prev, w*16+g)) {
651  sce->band_type[w*16+g] = 1;
652  } else {
653  /* drop subwindow flags too, see the PASS 1 drop above */
654  for (int w2 = 0; w2 < sce->ics.group_len[w]; w2++)
655  sce->zeroes[(w+w2)*16+g] = 1;
656  sce->band_type[w*16+g] = 0;
657  continue;
658  }
659  }
660  if (prev == -1)
661  sce->sf_idx[0] = sce->sf_idx[w*16+g]; /* global gain */
662  prev = sce->sf_idx[w*16+g];
663  }
664  }
665 
666  /* Every band, coded or not, must carry a chain-legal scalefactor: the
667  * codebook trellis (encode_window_bands_info) may later absorb a dropped
668  * band into a nonzero section, resurrecting it, and its sf then gets
669  * coded. Forward-fill with the previous coded sf (delta 0, cheapest);
670  * leading bands get the global gain. */
671  if (prev != -1) {
672  int last = sce->sf_idx[0];
673  for (int w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
674  for (int g = 0; g < sce->ics.num_swb; g++) {
675  if (!sce->zeroes[w*16+g] && sce->band_type[w*16+g] != NOISE_BT &&
676  sce->band_type[w*16+g] < RESERVED_BT)
677  last = sce->sf_idx[w*16+g];
678  else if (sce->band_type[w*16+g] < RESERVED_BT && (w*16+g) > 0)
679  sce->sf_idx[w*16+g] = last;
680  }
681  }
682  }
683  }
684  return;
685 
686 bail:
687  /* Nothing codeable in this channel. Leave a fully consistent state: any
688  * stale nonzero band_type acts as a codebook lower bound in the encoder's
689  * section trellis (encode_window_bands_info), which would forbid the zero
690  * section and resurrect the band with a stale, chain-illegal scalefactor.
691  * Pre-decided intensity bands keep their signalling. */
692  for (int i = 0; i < 128; i++) {
693  if (sce->band_type[i] == INTENSITY_BT || sce->band_type[i] == INTENSITY_BT2)
694  continue;
695  sce->zeroes[i] = 1;
696  sce->band_type[i] = 0;
697  }
698 }
699 
700 #endif /* AVCODEC_AACCODER_NMR_H */
NMR_RC_TRACK
#define NMR_RC_TRACK
Definition: aaccoder_nmr.h:93
av_clip
#define av_clip
Definition: common.h:100
INFINITY
#define INFINITY
Definition: mathematics.h:118
SingleChannelElement::can_pns
uint8_t can_pns[128]
band is allowed to PNS (informative)
Definition: aacenc.h:117
AVCodecContext::sample_rate
int sample_rate
samples per second
Definition: avcodec.h:1040
cb
static double cb(void *priv, double x, double y)
Definition: vf_geq.c:247
aacenctab.h
AV_CODEC_FLAG_QSCALE
#define AV_CODEC_FLAG_QSCALE
Use fixed qscale.
Definition: avcodec.h:213
SingleChannelElement::zeroes
uint8_t zeroes[128]
band is not coded
Definition: aacenc.h:116
step
trying all byte sequences megabyte in length and selecting the best looking sequence will yield cases to try But a word about which is also called distortion Distortion can be quantified by almost any quality measurement one chooses the sum of squared differences is used but more complex methods that consider psychovisual effects can be used as well It makes no difference in this discussion First step
Definition: rate_distortion.txt:58
b
#define b
Definition: input.c:43
NMR_RC_CORR
#define NMR_RC_CORR
Definition: aaccoder_nmr.h:81
R
#define R
Definition: huffyuv.h:44
expf
#define expf(x)
Definition: libm.h:285
float.h
mathematics.h
ff_sfdelta_can_remove_band
static int ff_sfdelta_can_remove_band(const SingleChannelElement *sce, const uint8_t *nextband, int prev_sf, int band)
Definition: aacenc_utils.h:208
FFMAX
#define FFMAX(a, b)
Definition: macros.h:47
AVChannelLayout::nb_channels
int nb_channels
Number of channels in this layout.
Definition: channel_layout.h:329
NMR_PNS_LAM
#define NMR_PNS_LAM
Definition: aaccoder_nmr.h:104
SCALE_MAX_POS
#define SCALE_MAX_POS
scalefactor index maximum value
Definition: aac.h:93
win
static float win(SuperEqualizerContext *s, float n, int N)
Definition: af_superequalizer.c:119
IndividualChannelStream::num_swb
int num_swb
number of scalefactor window bands
Definition: aacdec.h:178
SingleChannelElement::coeffs
float coeffs[1024]
coefficients for IMDCT, maybe processed
Definition: aacenc.h:121
NMR_ITERS
#define NMR_ITERS
Definition: aaccoder_nmr.h:60
AVCodecContext::ch_layout
AVChannelLayout ch_layout
Audio channel layout.
Definition: avcodec.h:1055
AVCodecContext::flags
int flags
AV_CODEC_FLAG_*.
Definition: avcodec.h:500
AVCodecContext::bit_rate_tolerance
int bit_rate_tolerance
number of bits the bitstream is allowed to diverge from the reference.
Definition: avcodec.h:1227
SingleChannelElement::ics
IndividualChannelStream ics
Definition: aacdec.h:218
NMR_RC_CITERS
#define NMR_RC_CITERS
Definition: aaccoder_nmr.h:86
NMR_PNS_NDGATE
#define NMR_PNS_NDGATE
Definition: aaccoder_nmr.h:96
float
float
Definition: af_crystalizer.c:122
NOISE_BT
@ NOISE_BT
Spectral data are scaled white noise not coded in the bitstream.
Definition: aac.h:75
AVCodecContext::global_quality
int global_quality
Global quality for codecs which cannot change it per frame.
Definition: avcodec.h:1235
IndividualChannelStream::swb_sizes
const uint8_t * swb_sizes
table of scalefactor band sizes for a particular window
Definition: aacenc.h:85
g
const char * g
Definition: vf_curves.c:128
EIGHT_SHORT_SEQUENCE
@ EIGHT_SHORT_SEQUENCE
Definition: aac.h:66
INTENSITY_BT2
@ INTENSITY_BT2
Scalefactor data are intensity stereo positions (out of phase).
Definition: aac.h:76
nmr_band_curve
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)
Definition: aaccoder_nmr.h:177
exp2f
#define exp2f(x)
Definition: libm.h:295
search_for_quantizers_nmr
static void search_for_quantizers_nmr(AVCodecContext *avctx, AACEncContext *s, SingleChannelElement *sce, const float lambda)
Definition: aaccoder_nmr.h:201
if
if(ret)
Definition: filter_design.txt:179
quantize_band_cost_cached
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)
Definition: aacenc_quantization_misc.h:31
INTENSITY_BT
@ INTENSITY_BT
Scalefactor data are intensity stereo positions (in phase).
Definition: aac.h:77
NULL
#define NULL
Definition: coverity.c:32
AVCodecContext::bit_rate
int64_t bit_rate
the average bitrate
Definition: avcodec.h:493
NMR_COARSE
#define NMR_COARSE
Definition: aaccoder_nmr.h:64
mathops.h
FFPsyBand
single band psychoacoustic information
Definition: psymodel.h:50
aac.h
aactab.h
sqrtf
static __device__ float sqrtf(float a)
Definition: cuda_runtime.h:184
ff_init_nextband_map
static void ff_init_nextband_map(const SingleChannelElement *sce, uint8_t *nextband)
Definition: aacenc_utils.h:175
av_clipf
av_clipf
Definition: af_crystalizer.c:122
nmr_solve
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 act0..nact-1, with lambda binary-searched so the coded size ~ destbi...
Definition: aaccoder_nmr.h:113
NMR_RC_FITERS
#define NMR_RC_FITERS
Definition: aaccoder_nmr.h:92
c
Undefined Behavior In the C some operations are like signed integer dereferencing freed accessing outside allocated Undefined Behavior must not occur in a C it is not safe even if the output of undefined operations is unused The unsafety may seem nit picking but Optimizing compilers have in fact optimized code on the assumption that no undefined Behavior occurs Optimizing code based on wrong assumptions can and has in some cases lead to effects beyond the output of computations The signed integer overflow problem in speed critical code Code which is highly optimized and works with signed integers sometimes has the problem that often the output of the computation does not c
Definition: undefined.txt:32
SingleChannelElement::sf_idx
int sf_idx[128]
scalefactor indices
Definition: aacenc.h:115
ff_aac_scalefactor_bits
const uint8_t ff_aac_scalefactor_bits[121]
Definition: aactab.c:200
coef2minsf
static uint8_t coef2minsf(float coef)
Return the minimum scalefactor where the quantized coef does not clip.
Definition: aacenc_utils.h:133
NMR_BURST_GAP
#define NMR_BURST_GAP
Definition: aaccoder_nmr.h:90
IndividualChannelStream::window_sequence
enum WindowSequence window_sequence[2]
Definition: aacdec.h:171
f
f
Definition: af_crystalizer.c:122
powf
#define powf(x, y)
Definition: libm.h:52
i
#define i(width, name, range_min, range_max)
Definition: cbs_h264.c:63
NMR_NCAND
#define NMR_NCAND
per-band scalefactor candidates above the finest codeable sf (NMR coder)
Definition: aacenc.h:171
NMR_IFINE
#define NMR_IFINE
Definition: aaccoder_nmr.h:61
NMR_PNS_BITS
#define NMR_PNS_BITS
Definition: aaccoder_nmr.h:67
SingleChannelElement::band_type
enum BandType band_type[128]
band types
Definition: aacdec.h:221
SCALE_MAX_DIFF
#define SCALE_MAX_DIFF
maximum scalefactor difference allowed by standard
Definition: aac.h:94
SingleChannelElement::pns_ener
float pns_ener[128]
Noise energy values.
Definition: aacenc.h:119
NMR_PNS_MAX_ET
#define NMR_PNS_MAX_ET
Definition: aaccoder_nmr.h:100
NMR_PNS_HOLE_FRAC
#define NMR_PNS_HOLE_FRAC
Definition: aaccoder_nmr.h:71
SingleChannelElement
Single Channel Element - used for both SCE and LFE elements.
Definition: aacdec.h:217
IndividualChannelStream::num_windows
int num_windows
Definition: aacdec.h:179
find_min_book
static int find_min_book(float maxval, int sf)
Definition: aacenc_utils.h:68
FFPsyBand::threshold
float threshold
Definition: psymodel.h:53
NMR_BURST_GAIN
#define NMR_BURST_GAIN
Definition: aaccoder_nmr.h:91
s
uint8_t s
Definition: llvidencdsp.c:39
FFMIN
#define FFMIN(a, b)
Definition: macros.h:49
avcodec.h
AVCodecContext::frame_num
int64_t frame_num
Frame counter, set by libavcodec.
Definition: avcodec.h:1883
RESERVED_BT
@ RESERVED_BT
Band types following are encoded differently from others.
Definition: aac.h:74
NMR_CITERS
#define NMR_CITERS
Definition: aaccoder_nmr.h:62
AACEncContext
AAC encoder context.
Definition: aacenc.h:204
FFPsyBand::energy
float energy
Definition: psymodel.h:52
AVCodecContext
main external API structure.
Definition: avcodec.h:443
NMR_CBR_BUF
#define NMR_CBR_BUF
Definition: aaccoder_nmr.h:85
mean
static float mean(const float *input, int size)
Definition: vf_nnedi.c:861
NMR_RC_ITERS
#define NMR_RC_ITERS
Definition: aaccoder_nmr.h:78
NMR_STEP
#define NMR_STEP
Definition: aaccoder_nmr.h:65
find_max_val
static float find_max_val(int group_len, int swb_size, const float *scaled)
Definition: aacenc_utils.h:56
NMR_PNS_HOLE_SPREAD
#define NMR_PNS_HOLE_SPREAD
Definition: aaccoder_nmr.h:72
it
s EdgeDetect Foobar g libavfilter vf_edgedetect c libavfilter vf_foobar c edit libavfilter and add an entry for foobar following the pattern of the other filters edit libavfilter allfilters and add an entry for foobar following the pattern of the other filters configure make j< whatever > ffmpeg ffmpeg i you should get a foobar png with Lena edge detected That s it
Definition: writing_filters.txt:31
NMR_RC_K_CBR
#define NMR_RC_K_CBR
Definition: aaccoder_nmr.h:76
w
uint8_t w
Definition: llvidencdsp.c:39
NMR_SFBITS
#define NMR_SFBITS(d)
AAC encoder NMR scalefactor coder.
Definition: aaccoder_nmr.h:58
NMR_CWARM
#define NMR_CWARM
Definition: aaccoder_nmr.h:63
b0
static double b0(void *priv, double x, double y)
Definition: vf_xfade.c:2033
FFPsyBand::spread
float spread
Definition: psymodel.h:54
put_bits.h
IndividualChannelStream::group_len
uint8_t group_len[8]
Definition: aacdec.h:175
ff_quantize_band_cost_cache_init
void ff_quantize_band_cost_cache_init(struct AACEncContext *s)
Definition: aacenc.c:373
aacenc.h