libavcodec/aaccoder_nmr.h
| Line | Branch | Exec | Source |
|---|---|---|---|
| 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 | /* Hole fill applies at any operating lambda above this (comfortable rates | ||
| 77 | * included): sparse-line renditions of noise are audible at every rate. */ | ||
| 78 | #define NMR_PNS_HOLE_LAM 20.0f | ||
| 79 | |||
| 80 | /* RC servo gain: scale the corridor centre by exp2(-K*fill/R) each frame to hold | ||
| 81 | * the long-run mean rate; without it a bad centre drifts for dozens of frames. */ | ||
| 82 | #define NMR_RC_K_CBR 0.5f | ||
| 83 | |||
| 84 | #define NMR_RC_ITERS 8 /* lambda bisection iters when clamping an over-cap frame */ | ||
| 85 | /* Corridor: bisect within [lam_rc/NMR_RC_CORR, lam_rc*NMR_RC_CORR] so quality stays | ||
| 86 | * smooth while per-frame demand is tracked; 1.5 cuts lambda jitter ~25%. */ | ||
| 87 | #define NMR_RC_CORR 1.5f | ||
| 88 | /* Reservoir-cap re-solve coarsens at most this far past the corridor per | ||
| 89 | * escalation step; the residual overage rides as reservoir debt. */ | ||
| 90 | #define NMR_RC_CAPK 3.0f | ||
| 91 | |||
| 92 | /* Quality-target calibration anchor: the nd set-point of -q:a 1, which lands | ||
| 93 | * near 128-136 kbps stereo on the tuning corpora with the q ladder's own | ||
| 94 | * bandwidth. The ABR servo seeds off the same constant (referenced to 81.5 | ||
| 95 | * kbps/ch, where it measured before the bandwidth retune; the boot corrects | ||
| 96 | * the per-content seed error), so they are one constant. It moved | ||
| 97 | * -2.1 -> -0.75 with the quality-target mask floor (PSY_THRFL_QUALITY), which | ||
| 98 | * lowers thr_real and so lifts the whole statistic. | ||
| 99 | * The reachable-range clamps did NOT move | ||
| 100 | * with it: their floors are set by the stat's -4/band sub-mask clip, which the | ||
| 101 | * mask floor does not touch. Targets below them are asymptotically unreachable | ||
| 102 | * - the bisect rails at the finest lambda, the frame exceeds the decoder buffer | ||
| 103 | * and the outer re-encode loop never converges (the 384k stall). Raising them | ||
| 104 | * with the anchor railed the ABR servo instead: it wanted a finer target to | ||
| 105 | * meet its rate ask on easy content and could not ask for one. */ | ||
| 106 | #define NMR_VBR_ANCHOR (-0.75f) | ||
| 107 | #define NMR_VBR_TMIN (-3.8f) | ||
| 108 | /* ABR set-point range. The coarse end is a quality guard: set-points past it | ||
| 109 | * buy little rate for a lot of quality (2.5 -> 6.0 at a 48k ask: -5% rate, | ||
| 110 | * +32% Zimtohrli), so asks below ~56 kbps stereo land above the ask - CBR | ||
| 111 | * is the mode for those rates. At the fine end, easy content can fall short | ||
| 112 | * of very high asks (no padding). */ | ||
| 113 | #define NMR_ABR_TMIN (-3.0f) | ||
| 114 | #define NMR_ABR_TMAX 2.5f | ||
| 115 | |||
| 116 | /* ABR servo: integrator gain on the log rate error, rate EMA weight after the | ||
| 117 | * boot, set-point step size and minimum frames between steps */ | ||
| 118 | #define NMR_ABR_K 0.003f | ||
| 119 | #define NMR_ABR_EMA 0.0023f | ||
| 120 | #define NMR_ABR_STEP 0.15f | ||
| 121 | #define NMR_ABR_HOLD 120 | ||
| 122 | /* ABR boot: open-loop correction gain over the nominal loop gain, the rate | ||
| 123 | * error that re-arms it, the re-arm budget and the settle time before one */ | ||
| 124 | #define NMR_ABR_BOOT_GAIN 1.2f | ||
| 125 | #define NMR_ABR_TOL 0.02f | ||
| 126 | #define NMR_ABR_BOOTS 6 | ||
| 127 | #define NMR_ABR_SETTLE 100 | ||
| 128 | |||
| 129 | /* VBR shorts: the measured stat inflation counts fully once this share of | ||
| 130 | * the frame's energy sits above 6 kHz */ | ||
| 131 | #define NMR_INFL_HF 0.10f | ||
| 132 | |||
| 133 | /* Reservoir half-window (bits/ch); swept 512/1536/3072, 1536 optimal. */ | ||
| 134 | #define NMR_CBR_BUF 1536 | ||
| 135 | /* Slew limit on the FINAL operating lambda per frame; bits deviate instead, | ||
| 136 | * the reservoir absorbs. See memory: aac-castanets-transient-rc. */ | ||
| 137 | #define NMR_SLEW 1.6f | ||
| 138 | #define NMR_SLEW_RUN 1.15f /* within short runs */ | ||
| 139 | #define NMR_RC_CITERS 3 /* corridor coarse-pass iters */ | ||
| 140 | |||
| 141 | /* Transition premask: an attack cannot mask backwards; clamp a START frame's | ||
| 142 | * thresholds toward the previous long frame's. */ | ||
| 143 | #define NMR_TRANS_PM 2.0f | ||
| 144 | |||
| 145 | /* Zero-decision hysteresis: previously-coded bands need this margin below | ||
| 146 | * threshold to zero (marginal bands flicker audibly otherwise). */ | ||
| 147 | #define NMR_ZERO_STICKY 0.5f | ||
| 148 | |||
| 149 | /* Short-window groups keep a borderline window coded down to this fraction | ||
| 150 | * of its zero threshold rather than muting it inside a coded group. */ | ||
| 151 | #define NMR_GROUP_KEEP 0.25f | ||
| 152 | |||
| 153 | /* HF precision taper: thresholds rise by NMR_HF_TAPER dB per kHz^2 above the | ||
| 154 | * knee (Apple's measured HF precision rolloff). */ | ||
| 155 | #define NMR_HF_TAPER 0.08f | ||
| 156 | #define NMR_HF_TAPER_KNEE 8000.0f | ||
| 157 | |||
| 158 | /* Transient bit-burst: an isolated onset (preceded by >= NMR_BURST_GAP long frames) | ||
| 159 | * is coded NMR_BURST_GAIN x finer, held uniform across the run, repaid from steady stretches. */ | ||
| 160 | #define NMR_BURST_GAP 10 | ||
| 161 | #define NMR_BURST_GAIN 8.0f | ||
| 162 | /* Dense-beat boost: short runs with gap < NMR_BURST_GAP get a budget factor | ||
| 163 | * ramping with the gap (starvation-scaled at the use site). */ | ||
| 164 | #define NMR_SHORT_BOOST 2.0f | ||
| 165 | #define NMR_RC_FITERS 4 /* corridor fine-pass iters */ | ||
| 166 | #define NMR_RC_TRACK 0.1f /* per-frame pull of the corridor centre toward the realized lambda */ | ||
| 167 | |||
| 168 | /* PNS noise-distortion gate: only bands coded well above the masking floor become noise. */ | ||
| 169 | #define NMR_PNS_NDGATE 4.0f | ||
| 170 | |||
| 171 | /* Energy/threshold cap for PNS: loud bands (energy >> mask) yield clipping random peaks; | ||
| 172 | * only near-masked bands are safe substitution targets. */ | ||
| 173 | #define NMR_PNS_MAX_ET 8.0f | ||
| 174 | |||
| 175 | /* Operating-lambda floor for PNS: below it the encoder is not struggling, so | ||
| 176 | * substituting real texture for 9 signalling bits is net-negative. */ | ||
| 177 | #define NMR_PNS_LAM 100.0f | ||
| 178 | |||
| 179 | /* PNS decision hysteresis: enter and leave both cost a margin. */ | ||
| 180 | #define NMR_PNS_ENTER 0.7f | ||
| 181 | #define NMR_PNS_STAY 1.4f | ||
| 182 | /* PNS debounce: enter after NMR_PNS_ON consecutive wants, leave after | ||
| 183 | * NMR_PNS_OFF (chronically marginal bands never qualify). */ | ||
| 184 | #define NMR_PNS_ON 8 | ||
| 185 | #define NMR_PNS_OFF 4 | ||
| 186 | |||
| 187 | /** | ||
| 188 | * Viterbi over the coding sequence act[0..nact-1] (indices into the per-band | ||
| 189 | * curves nd/nb), with lambda binary-searched so the coded size ~ destbits. | ||
| 190 | * Fills chosen[band] for every band referenced by act. Returns the operating | ||
| 191 | * lambda. node cost = dist/threshold + lambda*spectral_bits; | ||
| 192 | * edge cost = lambda*sf_differential_bits; |delta sf| <= SCALE_MAX_DIFF hard. | ||
| 193 | */ | ||
| 194 | 54131 | static float nmr_solve(AACEncContext *s, | |
| 195 | const float (*nd)[NMR_NCAND], const int (*nb)[NMR_NCAND], | ||
| 196 | const int *blo, const int *bnc, int step, | ||
| 197 | const int *act, int nact, int destbits, int *chosen, | ||
| 198 | float lo_l, float hi_l, int iters) | ||
| 199 | { | ||
| 200 | float dp[NMR_NCAND], dpp[NMR_NCAND], node[NMR_NCAND]; | ||
| 201 | float lamsf[2*SCALE_MAX_DIFF + 1]; /* lam*sfdiff bit cost, per lambda */ | ||
| 202 | uint8_t bp[128][NMR_NCAND]; | ||
| 203 | 54131 | float lam = 1.0f; | |
| 204 | |||
| 205 | 54131 | if (nact <= 0) | |
| 206 | ✗ | return lam; | |
| 207 | |||
| 208 | 54131 | for (int it = 0; it < iters; it++) { | |
| 209 | 54131 | lam = sqrtf(lo_l * hi_l); | |
| 210 | 6603982 | for (int i = 0; i <= 2*SCALE_MAX_DIFF; i++) | |
| 211 | 6549851 | lamsf[i] = lam * ff_aac_scalefactor_bits[i]; /* edge cost for this lambda */ | |
| 212 | |||
| 213 | 54131 | int b0 = act[0]; | |
| 214 | 820000 | for (int o = 0; o < bnc[b0]; o++) | |
| 215 | 765869 | dp[o] = nd[b0][o] + lam * nb[b0][o]; /* anchor band node cost */ | |
| 216 | |||
| 217 | 2052689 | for (int k = 1; k < nact; k++) { | |
| 218 | 1998558 | int b = act[k], pb = act[k-1]; | |
| 219 | 1998558 | memcpy(dpp, dp, sizeof(dp)); | |
| 220 | 29872166 | for (int o = 0; o < bnc[b]; o++) | |
| 221 | 27873608 | node[o] = nd[b][o] + lam * nb[b][o]; | |
| 222 | /* dp[o] = node[o] + min_op(dpp[op] + edge cost) */ | ||
| 223 | 1998558 | s->aacdsp.nmr_trellis_step(dp, bp[k], dpp, node, lamsf, | |
| 224 | 1998558 | bnc[b], bnc[pb], blo[b] - blo[pb], step, | |
| 225 | SCALE_MAX_DIFF); | ||
| 226 | } | ||
| 227 | |||
| 228 | /* backtrack */ | ||
| 229 | 54131 | int beo = 0, b = act[nact-1]; | |
| 230 | 54131 | float bec = FLT_MAX; | |
| 231 | 774685 | for (int o = 0; o < bnc[b]; o++) | |
| 232 | 720554 | if (dp[o] < bec) { bec = dp[o]; beo = o; } | |
| 233 | 54131 | chosen[b] = beo; | |
| 234 | 2052689 | for (int k = nact-1; k > 0; k--) | |
| 235 | 1998558 | chosen[act[k-1]] = bp[k][chosen[act[k]]]; | |
| 236 | |||
| 237 | /* calc cost */ | ||
| 238 | 54131 | int total = 0; | |
| 239 | 2106820 | for (int k = 0; k < nact; k++) | |
| 240 | 2052689 | total += nb[act[k]][chosen[act[k]]]; | |
| 241 | 2052689 | for (int k = 1; k < nact; k++) | |
| 242 | 1998558 | total += NMR_SFBITS((blo[act[k]]+chosen[act[k]]*step) - (blo[act[k-1]]+chosen[act[k-1]]*step)); | |
| 243 | |||
| 244 | 54131 | if (it == iters - 1) | |
| 245 | 54131 | break; | |
| 246 | |||
| 247 | /* check if we went over budget, go coarser if we did */ | ||
| 248 | ✗ | if (total > destbits) | |
| 249 | ✗ | lo_l = lam; | |
| 250 | else | ||
| 251 | ✗ | hi_l = lam; | |
| 252 | } | ||
| 253 | 54131 | return lam; | |
| 254 | } | ||
| 255 | |||
| 256 | /* Build one coded band's (dist/threshold, bits) cost curve, candidates sf = lo + o*step | ||
| 257 | * for o in [0,maxn), stopping when the band would drop (cb <= 0). Returns the bit count. */ | ||
| 258 | 249270 | static int nmr_band_curve(AACEncContext *s, SingleChannelElement *sce, int w, int g, | |
| 259 | int start, int lo, int step, int maxn, float invthr, | ||
| 260 | float maxval, float *nd_row, int *nb_row) | ||
| 261 | { | ||
| 262 | 249270 | int ncand = 0; | |
| 263 | 3586283 | for (int o = 0; o < maxn && lo + o*step <= SCALE_MAX_POS; o++) { | |
| 264 | 3509300 | int sf = lo + o*step, btot = 0, cb = find_min_book(maxval, sf); | |
| 265 | 3509300 | float dist = 0.0f; | |
| 266 | 3509300 | if (cb <= 0) | |
| 267 | 172287 | break; | |
| 268 | 7002260 | for (int w2 = 0; w2 < sce->ics.group_len[w]; w2++) { | |
| 269 | int bb; | ||
| 270 | 7330494 | dist += quantize_band_cost_cached(s, w + w2, g, sce->coeffs + start + w2*128, | |
| 271 | 3665247 | s->scoefs + start + w2*128, sce->ics.swb_sizes[g], | |
| 272 | sf, cb, 1.0f, INFINITY, &bb, NULL, 0); | ||
| 273 | 3665247 | btot += bb; | |
| 274 | } | ||
| 275 | 3337013 | nd_row[ncand] = (dist - btot) * invthr; | |
| 276 | 3337013 | nb_row[ncand] = btot; | |
| 277 | 3337013 | ncand++; | |
| 278 | } | ||
| 279 | 249270 | return ncand; | |
| 280 | } | ||
| 281 | |||
| 282 | /* Zero a channel with nothing codeable; stale band_types would resurrect | ||
| 283 | * bands with chain-illegal scalefactors. */ | ||
| 284 | 570 | static void nmr_bail_channel(SingleChannelElement *sce) | |
| 285 | { | ||
| 286 | 73530 | for (int i = 0; i < 128; i++) { | |
| 287 | 72960 | if (sce->band_type[i] == INTENSITY_BT || sce->band_type[i] == INTENSITY_BT2) | |
| 288 | 1800 | continue; | |
| 289 | 71160 | sce->zeroes[i] = 1; | |
| 290 | 71160 | sce->band_type[i] = 0; | |
| 291 | } | ||
| 292 | 570 | } | |
| 293 | |||
| 294 | /* Zero coded band b, subwindow flags included (the group flag is re-derived | ||
| 295 | * by ANDing). */ | ||
| 296 | 213 | static void nmr_drop_band(NMRSlot *t, int b) | |
| 297 | { | ||
| 298 | 512 | for (int w2 = 0; w2 < t->sce->ics.group_len[t->bw[b]]; w2++) | |
| 299 | 299 | t->sce->zeroes[(t->bw[b] + w2)*16 + t->bg[b]] = 1; | |
| 300 | 213 | } | |
| 301 | |||
| 302 | /* Keep the coding sequence act[] scalefactor-chain legal on grid `step`. | ||
| 303 | * A band's candidates only reach up to where it quantizes to zero, so two | ||
| 304 | * neighbours more than SCALE_MAX_DIFF apart leave the trellis without any | ||
| 305 | * legal path: every later state stays FLT_MAX and the backtrack returns the | ||
| 306 | * finest candidates, an oversized frame. Walk the chain tracking the | ||
| 307 | * scalefactor range still reachable from its start, and drop the quieter | ||
| 308 | * band of a pair that cannot connect: within reach it would quantize to | ||
| 309 | * zero anyway. A no-op on a legal chain. */ | ||
| 310 | 3531 | static void nmr_chain_repair(NMRSlot *t, int step) | |
| 311 | { | ||
| 312 | 3531 | int rlo[128], rhi[128], n = 0; | |
| 313 | |||
| 314 | 138552 | for (int k = 0; k < t->nact; k++) { | |
| 315 | 135021 | const int b = t->act[k]; | |
| 316 | 135021 | const int lo = t->blo[b], hi = lo + (t->bnc[b] - 1)*step; | |
| 317 | 135021 | int clo = lo, chi = hi, keep = 1; | |
| 318 | 135021 | while (n) { | |
| 319 | 131490 | const int p = t->act[n - 1]; | |
| 320 | 131490 | clo = FFMAX(lo, rlo[n - 1] - SCALE_MAX_DIFF); | |
| 321 | 131490 | chi = FFMIN(hi, rhi[n - 1] + SCALE_MAX_DIFF); | |
| 322 | 131490 | clo = lo + (clo - lo + step - 1) / step * step; | |
| 323 | 131490 | if (clo <= chi) { | |
| 324 | 131490 | chi = lo + (chi - lo) / step * step; | |
| 325 | 131490 | break; | |
| 326 | } | ||
| 327 | ✗ | if (t->maxvals[t->bidx[p]] > t->maxvals[t->bidx[b]]) { | |
| 328 | ✗ | keep = 0; | |
| 329 | ✗ | break; | |
| 330 | } | ||
| 331 | ✗ | nmr_drop_band(t, p); | |
| 332 | ✗ | n--; | |
| 333 | } | ||
| 334 | 135021 | if (!keep) { | |
| 335 | ✗ | nmr_drop_band(t, b); | |
| 336 | ✗ | continue; | |
| 337 | } | ||
| 338 | 135021 | if (!n) { | |
| 339 | 3531 | clo = lo; | |
| 340 | 3531 | chi = hi; | |
| 341 | } | ||
| 342 | /* n <= k: compacting in place never overwrites an unread entry */ | ||
| 343 | 135021 | t->act[n] = b; | |
| 344 | 135021 | rlo[n] = clo; | |
| 345 | 135021 | rhi[n] = chi; | |
| 346 | 135021 | n++; | |
| 347 | } | ||
| 348 | 3531 | t->nact = n; | |
| 349 | 3531 | } | |
| 350 | |||
| 351 | /* Per-channel setup into slot t: short-block threshold shaping, the | ||
| 352 | * allocation law, zero decisions, and the PASS 1 coarse candidate curves. | ||
| 353 | * Returns the coded-band count; 0 = nothing codeable (caller bails). */ | ||
| 354 | 3867 | static int nmr_setup_channel(AVCodecContext *avctx, AACEncContext *s, | |
| 355 | SingleChannelElement *sce, NMRSlot *t) | ||
| 356 | { | ||
| 357 | 3867 | float (*nd)[NMR_NCAND] = s->nmr->nd[t->si]; | |
| 358 | 3867 | int (*nb)[NMR_NCAND] = s->nmr->nb[t->si]; | |
| 359 | 3867 | const int cstep = NMR_COARSE > 0 ? NMR_COARSE : NMR_STEP; | |
| 360 | 3867 | int allz = 0, cutoff = 1024, nbnd = 0; | |
| 361 | |||
| 362 | 3867 | uint8_t *zprev = s->nmr->zero_prev[s->cur_channel & 15]; | |
| 363 | 3867 | if (s->nmr->zero_nw[s->cur_channel & 15] != sce->ics.num_windows) { | |
| 364 | 503 | memset(zprev, 1, 128); | |
| 365 | 503 | s->nmr->zero_nw[s->cur_channel & 15] = sce->ics.num_windows; | |
| 366 | } | ||
| 367 | |||
| 368 | 3867 | t->sce = sce; | |
| 369 | 3867 | t->cur_ch = s->cur_channel; | |
| 370 | 3867 | t->is8 = sce->ics.window_sequence[0] == EIGHT_SHORT_SEQUENCE; | |
| 371 | 3867 | t->nbnd = t->nact = 0; | |
| 372 | |||
| 373 | /* band cutoff index for this frame's window size; the bandwidth is fixed | ||
| 374 | * at init and shared with the psy model */ | ||
| 375 | 3867 | cutoff = s->bandwidth * 2 * (1024 / sce->ics.num_windows) / avctx->sample_rate; | |
| 376 | |||
| 377 | /* Short-block shaping: temporal premask + per-window threshold flatten. */ | ||
| 378 | 3867 | if (sce->ics.window_sequence[0] == EIGHT_SHORT_SEQUENCE) { | |
| 379 | 218 | const float pm_p1 = 0.1f, pm_p2 = 2.0f, pm_p3 = 4.0f; | |
| 380 | 3270 | for (int g = 0; g < sce->ics.num_swb; g++) { | |
| 381 | 3052 | float t1 = FLT_MAX, t2 = FLT_MAX; /* original thr of w-1, w-2 */ | |
| 382 | 27468 | for (int w = 0; w < sce->ics.num_windows; w++) { | |
| 383 | 24416 | FFPsyBand *b = &s->psy.ch[s->cur_channel].psy_bands[w*16+g]; | |
| 384 | 24416 | float th = b->threshold; | |
| 385 | 24416 | float c = FFMIN(th, FFMIN(t1*pm_p2, t2*pm_p3)); | |
| 386 | 24416 | b->threshold = FFMAX(c, th*pm_p1); | |
| 387 | 24416 | t2 = t1; t1 = th; | |
| 388 | } | ||
| 389 | } | ||
| 390 | { | ||
| 391 | 1962 | for (int w = 0; w < sce->ics.num_windows; w++) { | |
| 392 | 1744 | float sum = 0.0f, esum = 0.0f; int n = 0; | |
| 393 | 26160 | for (int g = 0; g < sce->ics.num_swb; g++) { | |
| 394 | 24416 | FFPsyBand *b = &s->psy.ch[s->cur_channel].psy_bands[w*16+g]; | |
| 395 | 24416 | if (b->energy > b->threshold && b->threshold > 0.0f) { sum += b->threshold; esum += b->energy; n++; } | |
| 396 | } | ||
| 397 | 1744 | if (n > 0) { | |
| 398 | /* keep each window codeable: cap the mean 12dB under the | ||
| 399 | * window's mean audible energy */ | ||
| 400 | 1725 | float mean = FFMIN(sum / n, (esum / n) * expf(-12.0f * (float)M_LN10 / 10.0f)); | |
| 401 | 25875 | for (int g = 0; g < sce->ics.num_swb; g++) { | |
| 402 | 24150 | FFPsyBand *b = &s->psy.ch[s->cur_channel].psy_bands[w*16+g]; | |
| 403 | 24150 | if (b->energy > b->threshold && b->threshold > 0.0f) | |
| 404 | 22224 | b->threshold = FFMIN(mean, b->threshold * 1e9f); | |
| 405 | } | ||
| 406 | } | ||
| 407 | } | ||
| 408 | } | ||
| 409 | } | ||
| 410 | |||
| 411 | /* Allocation law; short frames blend to softer energy exponents under | ||
| 412 | * pressure (roll anti-starvation, see memory). */ | ||
| 413 | /* The Apple-RE constants (0.443/0.111) describe THEIR bit distribution, | ||
| 414 | * not this trellis's optimum: more psy-threshold influence is worth -38% | ||
| 415 | * Zim / +0.06 ViSQOL at 128k stereo and -15% at 64k, flat plateau beyond. */ | ||
| 416 | 3867 | float a_ae = 0.50f, a_at = 0.18f; | |
| 417 | 3867 | if (sce->ics.num_windows == 8 && s->nmr) { | |
| 418 | /* blend to mask-weighted exponents under rate pressure */ | ||
| 419 | 218 | a_ae += (0.35f - a_ae) * s->nmr->press; | |
| 420 | 218 | a_at += (0.3f - a_at) * s->nmr->press; | |
| 421 | } | ||
| 422 | 8005 | for (int w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { | |
| 423 | 4138 | int start = 0; | |
| 424 | 182468 | for (int g = 0; g < sce->ics.num_swb; start += sce->ics.swb_sizes[g++]) { | |
| 425 | 178330 | float uplim = 0.0f, ener = 0.0f, spread = 2.0f; | |
| 426 | 178330 | int nz = 0; | |
| 427 | 178330 | if (sce->band_type[w*16+g] == INTENSITY_BT || | |
| 428 | 164006 | sce->band_type[w*16+g] == INTENSITY_BT2) { | |
| 429 | /* pre-decided intensity band (right channel): keep its | ||
| 430 | * signalling, it is not trellis-coded */ | ||
| 431 | 28680 | for (int w2 = 0; w2 < sce->ics.group_len[w]; w2++) | |
| 432 | 14340 | sce->zeroes[(w+w2)*16+g] = 0; | |
| 433 | 14340 | continue; | |
| 434 | } | ||
| 435 | 163990 | float zthr_mul = zprev[w*16+g] ? 1.0f : NMR_ZERO_STICKY; | |
| 436 | /* M/S side bands: zero-reluctance scaled by side/mid ratio (a tiny | ||
| 437 | * side IS the image; zeroing it flickers). */ | ||
| 438 | 163990 | if ((t->cur_ch & 1) && s->nmr && s->nmr->pair && | |
| 439 | 53633 | s->nmr->smode_band[(t->cur_ch >> 1) & 7][w*16+g] == 1) { | |
| 440 | 29774 | const FFPsyBand *mb = &s->psy.ch[s->cur_channel - 1].psy_bands[w*16+g]; | |
| 441 | 29774 | float ratio = 0.0f; | |
| 442 | 29774 | float eside = 0.0f; | |
| 443 | 63459 | for (int w2 = 0; w2 < sce->ics.group_len[w]; w2++) { | |
| 444 | 33685 | const FFPsyBand *bb = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g]; | |
| 445 | 33685 | eside += bb->energy; | |
| 446 | } | ||
| 447 | 29774 | ratio = eside / FFMAX(mb->energy * sce->ics.group_len[w], 1e-9f); | |
| 448 | 29774 | zthr_mul *= 0.25f + 0.75f * av_clipf(ratio / 0.3f, 0.0f, 1.0f); | |
| 449 | } | ||
| 450 | /* HF precision taper (bitstream RE): at 128k Apple codes | ||
| 451 | * 7.5-12.6k ~6dB coarser and 12.6k+ ~28dB coarser than we do, | ||
| 452 | * funding their LF/mid SNR edge; a quadratic thr rise above the | ||
| 453 | * knee reproduces that rolloff */ | ||
| 454 | float hftdb; | ||
| 455 | { | ||
| 456 | 163990 | float bfreq = start * (avctx->sample_rate * (sce->ics.num_windows == 8 ? 4.0f : 0.5f)) / 1024.0f; | |
| 457 | 163990 | float k = FFMAX(0.0f, bfreq - NMR_HF_TAPER_KNEE) / 1000.0f; | |
| 458 | 163990 | hftdb = NMR_HF_TAPER * k * k; | |
| 459 | } | ||
| 460 | 163990 | t->hftx[w*16+g] = 0; | |
| 461 | 345550 | for (int w2 = 0; w2 < sce->ics.group_len[w]; w2++) { | |
| 462 | 181560 | FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g]; | |
| 463 | 181560 | ener += band->energy; | |
| 464 | 181560 | spread = FFMIN(spread, band->spread); | |
| 465 | 181560 | if (start >= cutoff || band->energy <= band->threshold * zthr_mul || | |
| 466 | 135394 | band->threshold == 0.0f) { | |
| 467 | 46166 | sce->zeroes[(w+w2)*16+g] = 1; | |
| 468 | 46166 | continue; | |
| 469 | } | ||
| 470 | 135394 | uplim += band->threshold; | |
| 471 | 135394 | nz = 1; | |
| 472 | } | ||
| 473 | 163990 | if (nz && sce->ics.group_len[w] > 1) { | |
| 474 | /* a coded group must not mute individual borderline windows: | ||
| 475 | * they share the group's scalefactor (near-free to keep) and | ||
| 476 | * a 3-6ms in-band mute right before an attack reads as a | ||
| 477 | * gated crunch on every beat */ | ||
| 478 | 20527 | for (int w2 = 0; w2 < sce->ics.group_len[w]; w2++) { | |
| 479 | 16204 | FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g]; | |
| 480 | 16204 | if (sce->zeroes[(w+w2)*16+g] && start < cutoff && | |
| 481 | 1661 | band->threshold > 0.0f && | |
| 482 | 1661 | band->energy > band->threshold * zthr_mul * NMR_GROUP_KEEP) { | |
| 483 | 1198 | sce->zeroes[(w+w2)*16+g] = 0; | |
| 484 | 1198 | uplim += band->threshold; | |
| 485 | } | ||
| 486 | } | ||
| 487 | } | ||
| 488 | 163990 | zprev[w*16+g] = !nz; | |
| 489 | 163990 | sce->zeroes[w*16+g] = !nz; | |
| 490 | 163990 | t->thr_real[w*16+g] = uplim; /* real mask, before the allocation law (PNS gate) */ | |
| 491 | 163990 | if (nz && ener > 0.0f && uplim > 0.0f) { /* allocation law */ | |
| 492 | 124635 | uplim = expf(a_ae * logf(ener) + a_at * logf(uplim)); | |
| 493 | 124635 | if (hftdb != 0.0f) { | |
| 494 | 29071 | uplim *= powf(10.0f, hftdb * 0.1f); | |
| 495 | /* a band pushed well past its real mask reads as huge | ||
| 496 | * achieved-nd; keep the deliberate deficit out of the | ||
| 497 | * psy-reliability stat or press ramps into noise-class | ||
| 498 | * RC on clean tonal content */ | ||
| 499 | 29071 | if (hftdb > 2.0f) | |
| 500 | 13519 | t->hftx[w*16+g] = 1; | |
| 501 | } | ||
| 502 | } | ||
| 503 | 163990 | t->thr[w*16+g] = uplim; | |
| 504 | 163990 | t->pener[w*16+g] = ener; | |
| 505 | 163990 | t->pspread[w*16+g] = spread; | |
| 506 | 163990 | allz |= nz; | |
| 507 | } | ||
| 508 | } | ||
| 509 | 3867 | if (!allz) | |
| 510 | 570 | return 0; | |
| 511 | |||
| 512 | /* transition premask (see NMR_TRANS_PM) */ | ||
| 513 | 3297 | if (sce->ics.num_windows == 1) { | |
| 514 | 3081 | int ci = t->cur_ch & 15; | |
| 515 | 3081 | if (sce->ics.window_sequence[0] == LONG_START_SEQUENCE && | |
| 516 | 185 | s->nmr->thr_prev_ok[ci]) { | |
| 517 | 4050 | for (int g = 0; g < sce->ics.num_swb && g < 64; g++) | |
| 518 | 3969 | if (t->thr[g] > 0.0f && s->nmr->thr_prev[ci][g] > 0.0f) | |
| 519 | 3636 | t->thr[g] = FFMIN(t->thr[g], s->nmr->thr_prev[ci][g] * NMR_TRANS_PM); | |
| 520 | } | ||
| 521 | 149910 | for (int g = 0; g < sce->ics.num_swb && g < 64; g++) | |
| 522 | 146829 | s->nmr->thr_prev[ci][g] = t->thr[g]; | |
| 523 | 3081 | s->nmr->thr_prev_ok[ci] = 1; | |
| 524 | } else { | ||
| 525 | 216 | s->nmr->thr_prev_ok[t->cur_ch & 15] = 0; | |
| 526 | } | ||
| 527 | |||
| 528 | 3297 | s->aacdsp.abs_pow34(s->scoefs, sce->coeffs, 1024); | |
| 529 | 3297 | ff_quantize_band_cost_cache_init(s); | |
| 530 | |||
| 531 | /* TNS synthesis gain per band: the decoder re-amplifies residual-domain | ||
| 532 | * quantization noise by the whitening gain (shorts only). */ | ||
| 533 | 425313 | for (int i = 0; i < 128; i++) | |
| 534 | 422016 | t->tnsg[i] = 1.0f; | |
| 535 | 3297 | if (sce->ics.num_windows == 8 && sce->tns.present) { | |
| 536 | ✗ | const int mmm2 = FFMIN(sce->ics.tns_max_bands, sce->ics.max_sfb ? sce->ics.max_sfb : sce->ics.num_swb); | |
| 537 | ✗ | for (int w = 0; w < 8; w++) { | |
| 538 | ✗ | int bottom2 = sce->ics.num_swb; | |
| 539 | ✗ | for (int filt = 0; filt < sce->tns.n_filt[w]; filt++) { | |
| 540 | ✗ | int top2 = bottom2; | |
| 541 | ✗ | bottom2 = FFMAX(0, top2 - sce->tns.length[w][filt]); | |
| 542 | ✗ | if (!sce->tns.order[w][filt]) | |
| 543 | ✗ | continue; | |
| 544 | ✗ | for (int g = FFMIN(bottom2, mmm2); g < FFMIN(top2, mmm2); g++) { | |
| 545 | ✗ | int s0 = sce->ics.swb_offset[g] + w*128; | |
| 546 | ✗ | int s1 = sce->ics.swb_offset[g+1] + w*128; | |
| 547 | ✗ | float eres = 0.0f; | |
| 548 | ✗ | const FFPsyBand *pb = &s->psy.ch[s->cur_channel].psy_bands[w*16+g]; | |
| 549 | ✗ | for (int k = s0; k < s1; k++) | |
| 550 | ✗ | eres += sce->coeffs[k]*sce->coeffs[k]; | |
| 551 | ✗ | t->tnsg[w*16+g] = av_clipf(pb->energy / FFMAX(eres, 1e-12f), 1.0f, 64.0f); | |
| 552 | } | ||
| 553 | } | ||
| 554 | } | ||
| 555 | } | ||
| 556 | |||
| 557 | /* finest codeable scalefactor and max value per band */ | ||
| 558 | 6861 | for (int w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { | |
| 559 | 3564 | int start = w*128; | |
| 560 | 157155 | for (int g = 0; g < sce->ics.num_swb; g++) { | |
| 561 | 153591 | t->maxvals[w*16+g] = find_max_val(sce->ics.group_len[w], sce->ics.swb_sizes[g], s->scoefs + start); | |
| 562 | 153591 | t->minsf[w*16+g] = t->maxvals[w*16+g] > 0 ? coef2minsf(t->maxvals[w*16+g]) : 0; | |
| 563 | 153591 | start += sce->ics.swb_sizes[g]; | |
| 564 | } | ||
| 565 | } | ||
| 566 | |||
| 567 | /* PASS 1: coarse candidate curves per coded band | ||
| 568 | * (the lambda search runs on this cheap grid, PASS 2 refines the winner) */ | ||
| 569 | { | ||
| 570 | 6861 | for (int w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { | |
| 571 | 3564 | int start = w*128; | |
| 572 | 157155 | for (int g = 0; g < sce->ics.num_swb; g++) { | |
| 573 | 153591 | if (!sce->zeroes[w*16+g] && t->maxvals[w*16+g] > 0 && nbnd < 128) { | |
| 574 | 124635 | int lo = av_clip(t->minsf[w*16+g], 0, SCALE_MAX_POS); | |
| 575 | 124635 | float invthr = 1.0f / FFMAX(t->thr[w*16+g], 1e-9f); | |
| 576 | 124635 | int ncand = nmr_band_curve(s, sce, w, g, start, lo, cstep, NMR_NCAND, | |
| 577 | 124635 | invthr, t->maxvals[w*16+g], nd[nbnd], nb[nbnd]); | |
| 578 | 124635 | if (t->tnsg[w*16+g] > 1.0f) | |
| 579 | ✗ | for (int o = 0; o < ncand; o++) | |
| 580 | ✗ | nd[nbnd][o] *= t->tnsg[w*16+g]; | |
| 581 | 124635 | if (ncand == 0) { | |
| 582 | /* nothing codeable: drop the group band incl. subwindow | ||
| 583 | * flags (group flag is re-derived by ANDing) */ | ||
| 584 | ✗ | for (int w2 = 0; w2 < sce->ics.group_len[w]; w2++) | |
| 585 | ✗ | sce->zeroes[(w+w2)*16+g] = 1; | |
| 586 | } else { | ||
| 587 | 124635 | t->bidx[nbnd] = w*16+g; | |
| 588 | 124635 | t->bw[nbnd] = w; | |
| 589 | 124635 | t->bg[nbnd] = g; | |
| 590 | 124635 | t->bst[nbnd] = start; | |
| 591 | 124635 | t->blo[nbnd] = lo; | |
| 592 | 124635 | t->bnc[nbnd] = ncand; | |
| 593 | 124635 | nbnd++; | |
| 594 | } | ||
| 595 | } | ||
| 596 | 153591 | start += sce->ics.swb_sizes[g]; | |
| 597 | } | ||
| 598 | } | ||
| 599 | } | ||
| 600 | 3297 | t->nbnd = nbnd; | |
| 601 | 127932 | for (int b = 0; b < nbnd; b++) { | |
| 602 | 124635 | t->act[b] = b; | |
| 603 | 124635 | t->is_pns[b] = 0; | |
| 604 | } | ||
| 605 | 3297 | t->nact = nbnd; | |
| 606 | /* the fine pass refines around the coarse solve, so a chain legal on | ||
| 607 | * the coarse grid stays legal there */ | ||
| 608 | 3297 | nmr_chain_repair(t, cstep); | |
| 609 | 3297 | return nbnd; | |
| 610 | } | ||
| 611 | |||
| 612 | /* total bits of a slot's current chosen[] on grid `step`, incl. sf deltas */ | ||
| 613 | 63532 | static int nmr_slot_bits(const NMRSlot *t, const int (*nb)[NMR_NCAND], int step) | |
| 614 | { | ||
| 615 | 63532 | int tot = 0; | |
| 616 | 2467223 | for (int k = 0; k < t->nact; k++) | |
| 617 | 2403691 | tot += nb[t->act[k]][t->chosen[t->act[k]]]; | |
| 618 | 2403691 | for (int k = 1; k < t->nact; k++) | |
| 619 | 2340159 | tot += NMR_SFBITS((t->blo[t->act[k]]+t->chosen[t->act[k]]*step) - | |
| 620 | (t->blo[t->act[k-1]]+t->chosen[t->act[k-1]]*step)); | ||
| 621 | 63532 | return tot; | |
| 622 | } | ||
| 623 | |||
| 624 | /* Run every slot's trellis at one fixed lambda; returns the pooled bits. */ | ||
| 625 | 51043 | static int nmr_eval_slots(AACEncContext *s, NMRSlot *const *sl, int nsl, int step, float lam) | |
| 626 | { | ||
| 627 | 51043 | int total = 0; | |
| 628 | 105174 | for (int k = 0; k < nsl; k++) { | |
| 629 | 54131 | NMRSlot *t = sl[k]; | |
| 630 | 54131 | if (!t->nact) | |
| 631 | ✗ | continue; | |
| 632 | 54131 | nmr_solve(s, s->nmr->nd[t->si], s->nmr->nb[t->si], t->blo, t->bnc, step, | |
| 633 | 54131 | t->act, t->nact, 0, t->chosen, lam, lam, 1); | |
| 634 | 54131 | total += nmr_slot_bits(t, s->nmr->nb[t->si], step); | |
| 635 | } | ||
| 636 | 51043 | return total; | |
| 637 | } | ||
| 638 | |||
| 639 | /* Bisect ONE shared lambda across the slots so the POOLED bits meet destbits. | ||
| 640 | * This is the CPE budget pool: bits flow to whichever channel of the pair has | ||
| 641 | * demand at the common operating point, instead of an equal per-channel split. */ | ||
| 642 | 3872 | static float nmr_solve_slots(AACEncContext *s, NMRSlot *const *sl, int nsl, int step, | |
| 643 | int destbits, float lo_l, float hi_l, int iters) | ||
| 644 | { | ||
| 645 | 3872 | float lam = 1.0f; | |
| 646 | 20392 | for (int it = 0; it < iters; it++) { | |
| 647 | 20392 | lam = sqrtf(lo_l * hi_l); | |
| 648 | 20392 | int total = nmr_eval_slots(s, sl, nsl, step, lam); | |
| 649 | 20392 | if (it == iters - 1) | |
| 650 | 3872 | break; | |
| 651 | /* over budget -> go coarser */ | ||
| 652 | 16520 | if (total > destbits) | |
| 653 | 4860 | lo_l = lam; | |
| 654 | else | ||
| 655 | 11660 | hi_l = lam; | |
| 656 | } | ||
| 657 | 3872 | return lam; | |
| 658 | } | ||
| 659 | |||
| 660 | /* Mean log2 achieved dist/real-mask over the active bands of all slots at | ||
| 661 | * their current chosen[] - average dB-distance from the mask (Brandenburg | ||
| 662 | * mean-NMR). Log compression keeps unavoidably-loud bands from swamping the | ||
| 663 | * statistic. NAN when nothing is coded. */ | ||
| 664 | 30916 | static float nmr_nd_stat(AACEncContext *s, NMRSlot *const *sl, int nsl) | |
| 665 | { | ||
| 666 | 30916 | float ndsum = 0.0f; | |
| 667 | 30916 | int n = 0; | |
| 668 | 61832 | for (int k = 0; k < nsl; k++) { | |
| 669 | 30916 | NMRSlot *t = sl[k]; | |
| 670 | 30916 | const float (*ndk)[NMR_NCAND] = (const float (*)[NMR_NCAND])s->nmr->nd[t->si]; | |
| 671 | 1254065 | for (int b_ = 0; b_ < t->nact; b_++) { | |
| 672 | 1223149 | int b = t->act[b_], bi = t->bidx[b]; | |
| 673 | 1223149 | if (t->thr_real[bi] > 0.0f && t->thr[bi] > 0.0f) { | |
| 674 | /* floor the sub-mask credit: a flat sf-chain over-codes | ||
| 675 | * quiet bands and their unbounded negative log2 would let a | ||
| 676 | * COARSER lambda read as a finer statistic */ | ||
| 677 | 1223149 | ndsum += FFMAX(log2f(FFMAX(ndk[b][t->chosen[b]] * t->thr[bi] / | |
| 678 | t->thr_real[bi], 1e-6f)), -4.0f); | ||
| 679 | 1223149 | n++; | |
| 680 | } | ||
| 681 | } | ||
| 682 | } | ||
| 683 | 30916 | return n ? ndsum / n : NAN; | |
| 684 | } | ||
| 685 | |||
| 686 | /* Bisect ONE shared lambda across the slots so the achieved noise-to-mask | ||
| 687 | * statistic meets the target: quality-domain VBR. Monotone: coarser lambda -> | ||
| 688 | * more distortion. */ | ||
| 689 | 3490 | static float nmr_solve_slots_nd(AACEncContext *s, NMRSlot *const *sl, int nsl, | |
| 690 | int step, float target, float lo_l, float hi_l, | ||
| 691 | int iters) | ||
| 692 | { | ||
| 693 | 3490 | float lam = 1.0f; | |
| 694 | 29160 | for (int it = 0; it < iters; it++) { | |
| 695 | float st; | ||
| 696 | 29160 | lam = sqrtf(lo_l * hi_l); | |
| 697 | 29160 | nmr_eval_slots(s, sl, nsl, step, lam); | |
| 698 | 29160 | st = nmr_nd_stat(s, sl, nsl); | |
| 699 | 29160 | if (isnan(st) || it == iters - 1) | |
| 700 | break; | ||
| 701 | 25670 | if (st > target) | |
| 702 | 11331 | hi_l = lam; | |
| 703 | else | ||
| 704 | 14339 | lo_l = lam; | |
| 705 | } | ||
| 706 | 3490 | return lam; | |
| 707 | } | ||
| 708 | |||
| 709 | /* Write a solved slot back into its channel: band types, scalefactors, and the | ||
| 710 | * SCALE_MAX_DIFF legality fixups. Verbatim from the pre-pool single-channel tail. */ | ||
| 711 | 3297 | static void nmr_commit_channel(AACEncContext *s, NMRSlot *t) | |
| 712 | { | ||
| 713 | 3297 | SingleChannelElement *sce = t->sce; | |
| 714 | 3297 | const int (*nb)[NMR_NCAND] = (const int (*)[NMR_NCAND])s->nmr->nb[t->si]; | |
| 715 | |||
| 716 | 127932 | for (int b = 0; b < t->nbnd; b++) { | |
| 717 | 124635 | int bi = t->bidx[b]; | |
| 718 | 124635 | if (t->is_pns[b]) { | |
| 719 | 28 | sce->band_type[bi] = NOISE_BT; | |
| 720 | 28 | sce->zeroes[bi] = 0; | |
| 721 | 28 | sce->pns_ener[bi] = t->pener[bi] * FFMIN(1.0f, t->pspread[bi]*t->pspread[bi]); | |
| 722 | } else { | ||
| 723 | 124607 | sce->sf_idx[bi] = av_clip(t->blo[b] + t->chosen[b]*NMR_STEP, 0, SCALE_MAX_POS); | |
| 724 | } | ||
| 725 | } | ||
| 726 | |||
| 727 | |||
| 728 | /* record the bits this solve accounted for; the encoder compares them | ||
| 729 | * against the channel's real output to keep the budget honest. Only the | ||
| 730 | * surviving active bands are coded: bands shed for legality are not. */ | ||
| 731 | 3297 | s->nmr->counted[t->cur_ch] = nmr_slot_bits(t, nb, NMR_STEP); | |
| 732 | |||
| 733 | /* SCALE_MAX_DIFF condition: | ||
| 734 | * re-clamp, codebook fixup, drop uncodeable, set global gain | ||
| 735 | * NOISE_BT bands keep their own scalefactor chain via set_special_band_scalefactors) */ | ||
| 736 | { | ||
| 737 | uint8_t nextband[128]; | ||
| 738 | 3297 | int prev = -1; | |
| 739 | 3297 | ff_init_nextband_map(sce, nextband); | |
| 740 | 6861 | for (int w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { | |
| 741 | 157155 | for (int g = 0; g < sce->ics.num_swb; g++) { | |
| 742 | 153591 | if (sce->band_type[w*16+g] == NOISE_BT || | |
| 743 | 153563 | sce->band_type[w*16+g] == INTENSITY_BT || | |
| 744 | 141039 | sce->band_type[w*16+g] == INTENSITY_BT2) | |
| 745 | 12568 | continue; | |
| 746 | 141023 | if (sce->zeroes[w*16+g]) { | |
| 747 | 16629 | sce->band_type[w*16+g] = 0; | |
| 748 | 16629 | continue; | |
| 749 | } | ||
| 750 | |||
| 751 | 124394 | if (prev != -1) | |
| 752 | 121097 | sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], prev - SCALE_MAX_DIFF, prev + SCALE_MAX_DIFF); | |
| 753 | 124394 | sce->band_type[w*16+g] = find_min_book(t->maxvals[w*16+g], sce->sf_idx[w*16+g]); | |
| 754 | 124394 | if (sce->band_type[w*16+g] <= 0) { | |
| 755 | ✗ | if (!ff_sfdelta_can_remove_band(sce, nextband, prev, w*16+g)) { | |
| 756 | ✗ | sce->band_type[w*16+g] = 1; | |
| 757 | } else { | ||
| 758 | /* drop subwindow flags too, see the PASS 1 drop above */ | ||
| 759 | ✗ | for (int w2 = 0; w2 < sce->ics.group_len[w]; w2++) | |
| 760 | ✗ | sce->zeroes[(w+w2)*16+g] = 1; | |
| 761 | ✗ | sce->band_type[w*16+g] = 0; | |
| 762 | ✗ | continue; | |
| 763 | } | ||
| 764 | } | ||
| 765 | 124394 | if (prev == -1) | |
| 766 | 3297 | sce->sf_idx[0] = sce->sf_idx[w*16+g]; /* global gain */ | |
| 767 | 124394 | prev = sce->sf_idx[w*16+g]; | |
| 768 | } | ||
| 769 | } | ||
| 770 | |||
| 771 | /* every band must carry a chain-legal scalefactor (re-clamp, codebook | ||
| 772 | * fixup, global gain) */ | ||
| 773 | 3297 | if (prev != -1) { | |
| 774 | 3297 | int last = sce->sf_idx[0]; | |
| 775 | 6861 | for (int w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) { | |
| 776 | 157155 | for (int g = 0; g < sce->ics.num_swb; g++) { | |
| 777 | 153591 | if (!sce->zeroes[w*16+g] && sce->band_type[w*16+g] != NOISE_BT && | |
| 778 | 136934 | sce->band_type[w*16+g] < RESERVED_BT) | |
| 779 | 124394 | last = sce->sf_idx[w*16+g]; | |
| 780 | 29197 | else if (sce->band_type[w*16+g] < RESERVED_BT && (w*16+g) > 0) | |
| 781 | 16529 | sce->sf_idx[w*16+g] = last; | |
| 782 | } | ||
| 783 | } | ||
| 784 | } | ||
| 785 | } | ||
| 786 | 3297 | } | |
| 787 | |||
| 788 | /* Solve one element group (a solo channel, or a CPE pair pooled under one | ||
| 789 | * shared lambda and one pooled budget), then PNS and commit. */ | ||
| 790 | 2936 | static void nmr_solve_group(AVCodecContext *avctx, AACEncContext *s, | |
| 791 | const float lambda, NMRSlot *const *sl, int nsl, | ||
| 792 | int chans, int rc_eligible, int rc_global, | ||
| 793 | int rc_rate_frame, int rc_bmax) | ||
| 794 | { | ||
| 795 | 2936 | const int cstep = NMR_COARSE > 0 ? NMR_COARSE : NMR_STEP; | |
| 796 | 2936 | int bch = ((avctx->flags & AV_CODEC_FLAG_QSCALE) ? 2.0f : avctx->ch_layout.nb_channels); | |
| 797 | 2936 | int destbits = avctx->bit_rate * 1024.0 / avctx->sample_rate / bch * (lambda / 120.f) * chans; | |
| 798 | 2936 | int is8_any = 0; | |
| 799 | float lam; | ||
| 800 | 2936 | float rc_off = 1.0f, lam_dem = 0.0f; | |
| 801 | /* the outer loop's starting lambda: legality caps scale with lambda | ||
| 802 | * relative to it, so they only shrink on a hard-overflow retry */ | ||
| 803 | 2936 | const float lam_ref = (avctx->flags & AV_CODEC_FLAG_QSCALE) && avctx->global_quality > 0 ? | |
| 804 | 3758 | avctx->global_quality : 120.0f; | |
| 805 | |||
| 806 | 6233 | for (int k = 0; k < nsl; k++) | |
| 807 | 3297 | is8_any |= sl[k]->is8; | |
| 808 | |||
| 809 | /* decoupled solo solves keep per-channel slew state: sharing one | ||
| 810 | * lam_slew clamps each channel against the OTHER's operating lambda */ | ||
| 811 | 2936 | float *vslew_st = &s->nmr->lam_slew; | |
| 812 | 2936 | if (nsl == 1 && s->channels > 1) { | |
| 813 | 2055 | vslew_st = &s->nmr->lam_slew_ch[sl[0]->cur_ch & 15]; | |
| 814 | 2055 | if (*vslew_st <= 0.0f) | |
| 815 | 133 | *vslew_st = s->nmr->lam_slew; | |
| 816 | } | ||
| 817 | |||
| 818 | 2936 | if (s->psy.bitres.alloc >= 0) | |
| 819 | 5390 | destbits = s->psy.bitres.alloc * | |
| 820 | 2695 | (lambda / (avctx->global_quality ? avctx->global_quality : 120)) * chans; | |
| 821 | 2936 | if (rc_global && s->psy.bitres.alloc >= 0) { | |
| 822 | /* CBR target: nominal + repayment, bounded +-30%/frame */ | ||
| 823 | 930 | double rr = avctx->bit_rate * 1024.0 / avctx->sample_rate; | |
| 824 | 930 | destbits = (rr + av_clipd(s->nmr->rc_fill / 2.0, -0.3 * rr, 0.3 * rr)) * chans / s->channels; | |
| 825 | 2006 | } else if (rc_eligible && s->psy.bitres.alloc >= 0) { | |
| 826 | /* pre-bootstrap CBR frames: target nominal (psy bitres is cold) */ | ||
| 827 | 121 | destbits = (avctx->bit_rate * 1024.0 / avctx->sample_rate) * chans / s->channels; | |
| 828 | } | ||
| 829 | 2936 | destbits = FFMIN(destbits, 5800 * chans); | |
| 830 | /* honest budget: subtract the measured non-trellis overhead (section data, ICS, | ||
| 831 | * sf/PNS signalling), which is rate-dependent hence adaptive. */ | ||
| 832 | 2936 | if (s->nmr->side_inited) | |
| 833 | 2811 | destbits = av_clip(destbits - (int)(s->nmr->side_ema * chans / s->channels), 64, 5800 * chans); | |
| 834 | |||
| 835 | /* Held transient burst, bank-aware: spend banked bits, never borrow deep | ||
| 836 | * (payback troughs starve the next transient). */ | ||
| 837 | 2936 | if (s->nmr->run_burst > 1.0f) { | |
| 838 | 165 | int extra = destbits * (s->nmr->run_burst - 1.0f); | |
| 839 | 165 | int avail = FFMAX(0, (int)((s->nmr->rc_fill + rc_bmax / 2) * (int64_t)chans / s->channels)); | |
| 840 | 165 | destbits = av_clip(destbits + FFMIN(extra, avail), 64, 6800 * chans); | |
| 841 | } | ||
| 842 | |||
| 843 | 2936 | int vbr = (avctx->flags & AV_CODEC_FLAG_QSCALE) && s->nmr; | |
| 844 | 2936 | int abr = !vbr && s->options.rc == 1 && avctx->bit_rate > 0 && s->nmr; | |
| 845 | 2936 | int vbr_subst = 1; | |
| 846 | 2936 | float vbr_t = 0.0f; | |
| 847 | 2936 | if (abr) { | |
| 848 | /* ABR: same quality-target solve, set-point owned by the rate servo */ | ||
| 849 | 822 | vbr_t = s->nmr->abr_t; | |
| 850 | 822 | vbr = 1; | |
| 851 | 2114 | } else if (vbr) { | |
| 852 | /* nd-target VBR: constant achieved noise-to-mask, bits float. */ | ||
| 853 | /* target in log2(dist/real-mask), anchored so -q:a 1 lands near | ||
| 854 | * 128 kbps stereo on the tuning corpus; higher q is finer, each q | ||
| 855 | * doubling ~ -1.2 */ | ||
| 856 | 822 | vbr_t = FFMAX(NMR_VBR_ANCHOR - 1.2f * log2f(avctx->global_quality > 0 ? | |
| 857 | avctx->global_quality / (float)FF_QP2LAMBDA : 1.0f), | ||
| 858 | NMR_VBR_TMIN); | ||
| 859 | } | ||
| 860 | 2936 | if (vbr && is8_any) { | |
| 861 | /* short frames: the grouped-band statistic is inflated (same reason | ||
| 862 | * nd_ema excludes shorts), so they bisect against an offset target | ||
| 863 | * rather than the long-frame one - and never write solver state | ||
| 864 | * (transient-dense content would otherwise starve the long-frame | ||
| 865 | * warm start of updates). Warm off the surrounding operating point. */ | ||
| 866 | 112 | float lam0 = *vslew_st > 0.0f ? FFMIN(*vslew_st, 1e4f) : 0.0f; | |
| 867 | 112 | float *infl = &s->nmr->vbr_infl[sl[0]->cur_ch & 15]; | |
| 868 | 112 | if (lam0 > 0.0f) { | |
| 869 | /* measured stat offset, decided at shorts-run entry: evaluate | ||
| 870 | * the grouped stat at the long-anchor lambda - continuity says | ||
| 871 | * true quality is on target there, so any excess IS this | ||
| 872 | * content's inflation. Broadband beats (velvet) measure +2..+4, | ||
| 873 | * tonal musical decays measure none; the old fixed +3 picked | ||
| 874 | * one class and audibly damaged the other. Re-measured every | ||
| 875 | * short frame: run-entry-only attribution tars a whole tonal | ||
| 876 | * decay run with its mini-attack entry frame. */ | ||
| 877 | 112 | float st0, ehf = 0.0f, etot = 0.0f, hfw; | |
| 878 | 112 | nmr_eval_slots(s, sl, nsl, cstep, lam0); | |
| 879 | 112 | st0 = nmr_nd_stat(s, sl, nsl); | |
| 880 | /* the stat reads inflated on BOTH classes; audibility does not. | ||
| 881 | * Coarse shorts hide under HF-dominant transients (hats, claps) | ||
| 882 | * and stick out on LF/mid tonal material - weight the offset by | ||
| 883 | * the frame's HF energy share. */ | ||
| 884 | 224 | for (int k = 0; k < nsl; k++) | |
| 885 | 3581 | for (int b_ = 0; b_ < sl[k]->nact; b_++) { | |
| 886 | 3469 | int b = sl[k]->act[b_], bi = sl[k]->bidx[b]; | |
| 887 | 3469 | float en = sl[k]->pener[bi]; | |
| 888 | 3469 | int bin = sl[k]->bst[b] - sl[k]->bw[b]*128; | |
| 889 | 3469 | etot += en; | |
| 890 | 3469 | if (bin * (avctx->sample_rate * 4.0f) / 1024.0f > 6000.0f) | |
| 891 | 1576 | ehf += en; | |
| 892 | } | ||
| 893 | 112 | hfw = etot > 0.0f ? av_clipf(ehf / (etot * NMR_INFL_HF), 0.0f, 1.0f) : 1.0f; | |
| 894 | 112 | *infl = isnan(st0) ? 0.0f : av_clipf(st0 - vbr_t, 0.0f, 4.0f) * hfw; | |
| 895 | } | ||
| 896 | 112 | if (lam0 > 0.0f) | |
| 897 | 112 | lam = nmr_solve_slots_nd(s, sl, nsl, cstep, vbr_t + *infl, | |
| 898 | 112 | lam0/32.0f, FFMIN(lam0*32.0f, 1e4f), NMR_CWARM + 2); | |
| 899 | else | ||
| 900 | ✗ | lam = nmr_solve_slots_nd(s, sl, nsl, cstep, vbr_t, 1e-9f, 1e4f, NMR_ITERS); | |
| 901 | 112 | if (lam0 > 0.0f) { | |
| 902 | /* the offset-bisect assumes isolated transients between long | ||
| 903 | * anchors; on continuous-shorts content the per-frame grouped | ||
| 904 | * stat is bisect noise and lambda careens across decades - | ||
| 905 | * audible as whooshing. Hold shorts to the same near-constant | ||
| 906 | * run slew CBR uses (dives toward finer stay free: transient | ||
| 907 | * bits float by design). */ | ||
| 908 | 112 | float kup = s->nmr->prev_was_short ? NMR_SLEW_RUN : NMR_SLEW; | |
| 909 | 112 | if (lam > lam0 * kup || lam < lam0 / 4.0f) { | |
| 910 | 68 | lam = av_clipf(lam, lam0 / 4.0f, lam0 * kup); | |
| 911 | 68 | nmr_eval_slots(s, sl, nsl, cstep, lam); | |
| 912 | } | ||
| 913 | } | ||
| 914 | 112 | vbr_subst = 0; | |
| 915 | 2824 | } else if (vbr) { | |
| 916 | /* warm-started off the previous frame's lambda */ | ||
| 917 | 1532 | float lam0 = s->nmr->lam[sl[0]->cur_ch]; | |
| 918 | 1532 | lam = 1.0f; | |
| 919 | 1532 | if (lam0 > 0.0f) { | |
| 920 | 1528 | lam0 = FFMIN(lam0, 1e4f); | |
| 921 | 1528 | lam = nmr_solve_slots_nd(s, sl, nsl, cstep, vbr_t, | |
| 922 | 1528 | lam0/32.0f, FFMIN(lam0*32.0f, 1e4f), NMR_CWARM + 2); | |
| 923 | 1528 | if (lam < lam0/16.0f || lam > lam0*16.0f) | |
| 924 | 202 | lam0 = 0.0f; | |
| 925 | } | ||
| 926 | 1532 | if (lam0 <= 0.0f) | |
| 927 | 206 | lam = nmr_solve_slots_nd(s, sl, nsl, cstep, vbr_t, 1e-9f, 1e4f, NMR_ITERS); | |
| 928 | 1292 | } else if (rc_global) { | |
| 929 | /* corridor bisect around the servoed centre; pressure = stateless | ||
| 930 | * rc_off multiplier (folding it into lam_rc winds up) */ | ||
| 931 | 1171 | float R = avctx->bit_rate * 1024.0 / avctx->sample_rate; | |
| 932 | float cen; | ||
| 933 | int tot, hardcap, rc_cap; | ||
| 934 | float lo; | ||
| 935 | 1171 | rc_off = exp2f(-NMR_RC_K_CBR * s->nmr->rc_fill / R); | |
| 936 | 1171 | cen = s->nmr->lam_rc * rc_off; | |
| 937 | 1171 | lo = cen / NMR_RC_CORR; | |
| 938 | /* transient burst: widen the lower bound so the boosted destbits can | ||
| 939 | * actually pour into the onset frame */ | ||
| 940 | 1171 | if (is8_any && s->nmr->run_burst > 1.0f) | |
| 941 | 2 | lo /= s->nmr->run_burst; | |
| 942 | 1171 | lam = nmr_solve_slots(s, sl, nsl, cstep, destbits, | |
| 943 | lo, cen * NMR_RC_CORR, NMR_RC_CITERS); | ||
| 944 | |||
| 945 | 1171 | tot = 0; | |
| 946 | 2703 | for (int k = 0; k < nsl; k++) | |
| 947 | 1532 | tot += nmr_slot_bits(sl[k], s->nmr->nb[sl[k]->si], cstep); | |
| 948 | 1171 | hardcap = av_clip((int)(5800.f * FFMIN(1.f, lambda / 120.f)), 256, 5800) * chans; | |
| 949 | /* legality cap only; no spend-floor (rc_off spends the bank) */ | ||
| 950 | 1171 | rc_cap = FFMIN(hardcap, (s->nmr->rc_fill + rc_rate_frame + rc_bmax) * chans / s->channels); | |
| 951 | 1171 | if (tot > rc_cap) { | |
| 952 | /* reservoir-empty: coarsen, but never past a bounded excursion | ||
| 953 | * of the corridor. The coarse grid's bit curve is steppy: an | ||
| 954 | * unbounded fit here can jump lambda by orders of magnitude and | ||
| 955 | * potato-frame the burst recovery frame (audible LF scratch). | ||
| 956 | * The fine pass works from the bounded lambda, and the reservoir | ||
| 957 | * cap is enforced once more on the fine grid after it, where the | ||
| 958 | * fit only moves lambda as far as the frame really needs. */ | ||
| 959 | 41 | lam = nmr_solve_slots(s, sl, nsl, cstep, rc_cap, lam, lam * NMR_RC_CAPK, NMR_CITERS); | |
| 960 | 41 | tot = 0; | |
| 961 | 83 | for (int k = 0; k < nsl; k++) | |
| 962 | 42 | tot += nmr_slot_bits(sl[k], s->nmr->nb[sl[k]->si], cstep); | |
| 963 | 41 | if (tot > rc_cap && s->nmr->rc_fill <= -(rc_bmax * 9 / 10)) { | |
| 964 | /* the debt ledger clips at -rc_bmax: with no capacity | ||
| 965 | * left, further overage would be silently forgiven and | ||
| 966 | * sustained transient content rides hot forever (a | ||
| 967 | * castanets roll hit 215 kbps for its first second on a | ||
| 968 | * 128k ask). A one-frame hard fit trades that for a | ||
| 969 | * potato frame (audible click); instead the bound | ||
| 970 | * ESCALATES with consecutive saturated frames - chronic | ||
| 971 | * rolls converge within a few frames, isolated bursts | ||
| 972 | * never see more than one escalation step. */ | ||
| 973 | 4 | float ek = NMR_RC_CAPK * (1 + FFMIN(s->nmr->rc_satrun, 8)); | |
| 974 | 4 | lam = nmr_solve_slots(s, sl, nsl, cstep, rc_cap, lam, lam * ek, NMR_CITERS); | |
| 975 | 4 | s->nmr->rc_sat_frame = 1; | |
| 976 | 4 | tot = 0; | |
| 977 | 8 | for (int k = 0; k < nsl; k++) | |
| 978 | 4 | tot += nmr_slot_bits(sl[k], s->nmr->nb[sl[k]->si], cstep); | |
| 979 | } | ||
| 980 | 41 | if (tot > hardcap) /* decoder-buffer legality is absolute */ | |
| 981 | ✗ | lam = nmr_solve_slots(s, sl, nsl, cstep, hardcap, lam, 1e4f, NMR_CITERS); | |
| 982 | } | ||
| 983 | } else { | ||
| 984 | /* per-frame bisection, warm-started off the previous frame's lambda; | ||
| 985 | * a result at the bracket edge means redo the full search */ | ||
| 986 | 121 | float lam0 = s->nmr->lam[sl[0]->cur_ch]; | |
| 987 | 121 | lam = 1.0f; | |
| 988 | 121 | if (NMR_COARSE > 0 && lam0 > 0.0f) { | |
| 989 | ✗ | lam = nmr_solve_slots(s, sl, nsl, cstep, destbits, lam0/32.0f, lam0*32.0f, NMR_CWARM); | |
| 990 | ✗ | if (lam < lam0/16.0f || lam > lam0*16.0f) | |
| 991 | ✗ | lam0 = 0.0f; | |
| 992 | } | ||
| 993 | 121 | if (lam0 <= 0.0f) | |
| 994 | 121 | lam = nmr_solve_slots(s, sl, nsl, cstep, destbits, | |
| 995 | 1e-9f, 1e4f, NMR_COARSE > 0 ? NMR_CITERS : NMR_ITERS); | ||
| 996 | } | ||
| 997 | |||
| 998 | /* PASS 2: | ||
| 999 | * refine each band at full granularity (NMR_STEP) in a +/-cstep window | ||
| 1000 | * around the coarse pick, then re-solve. Recovers single-pass quality while the | ||
| 1001 | * lambda search stayed cheap on the coarse grid. */ | ||
| 1002 | if (NMR_COARSE > 0) { | ||
| 1003 | /* nmr_speed, 0 = slowest/best, higher = faster; see the option docs. */ | ||
| 1004 | 2936 | int win = NMR_COARSE - av_clip(s->options.nmr_speed, 0, 4); | |
| 1005 | 6233 | for (int k = 0; k < nsl; k++) { | |
| 1006 | 3297 | NMRSlot *t = sl[k]; | |
| 1007 | 3297 | float (*ndk)[NMR_NCAND] = s->nmr->nd[t->si]; | |
| 1008 | 3297 | int (*nbk)[NMR_NCAND] = s->nmr->nb[t->si]; | |
| 1009 | 3297 | if (!t->nact) | |
| 1010 | ✗ | continue; | |
| 1011 | /* the pow34 spectrum and the quantize cache are per-channel state */ | ||
| 1012 | 3297 | s->aacdsp.abs_pow34(s->scoefs, t->sce->coeffs, 1024); | |
| 1013 | 3297 | ff_quantize_band_cost_cache_init(s); | |
| 1014 | 127932 | for (int b = 0; b < t->nbnd; b++) { | |
| 1015 | 124635 | int center = t->blo[b] + t->chosen[b]*cstep; | |
| 1016 | 124635 | int flo = av_clip(center - win, av_clip(t->minsf[t->bidx[b]], 0, SCALE_MAX_POS), SCALE_MAX_POS); | |
| 1017 | 124635 | int maxn = FFMIN(NMR_NCAND, 2*win/NMR_STEP + 1); | |
| 1018 | 124635 | float invthr = 1.0f / FFMAX(t->thr[t->bidx[b]], 1e-9f); | |
| 1019 | 124635 | int ncand = nmr_band_curve(s, t->sce, t->bw[b], t->bg[b], t->bst[b], flo, NMR_STEP, maxn, | |
| 1020 | 124635 | invthr, t->maxvals[t->bidx[b]], ndk[b], nbk[b]); | |
| 1021 | 124635 | if (t->tnsg[t->bidx[b]] > 1.0f) | |
| 1022 | ✗ | for (int o = 0; o < ncand; o++) | |
| 1023 | ✗ | ndk[b][o] *= t->tnsg[t->bidx[b]]; | |
| 1024 | 124635 | t->blo[b] = flo; | |
| 1025 | 124635 | t->bnc[b] = FFMAX(1, ncand); | |
| 1026 | } | ||
| 1027 | } | ||
| 1028 | /* fine pass: narrow corridor around the coarse solve */ | ||
| 1029 | 3048 | if (vbr && !vbr_subst) { | |
| 1030 | 112 | float infl2 = is8_any ? s->nmr->vbr_infl[sl[0]->cur_ch & 15] : 0.0f; | |
| 1031 | 112 | lam = nmr_solve_slots_nd(s, sl, nsl, NMR_STEP, vbr_t + infl2, | |
| 1032 | 112 | lam/32.0f, FFMIN(lam*32.0f, 1e4f), NMR_IFINE); | |
| 1033 | 2824 | } else if (vbr) | |
| 1034 | /* wide re-bisect: the fine grid sits systematically finer than | ||
| 1035 | * the coarse grid at equal lambda, well past a 1-octave bracket */ | ||
| 1036 | 1532 | lam = nmr_solve_slots_nd(s, sl, nsl, NMR_STEP, vbr_t, | |
| 1037 | 1532 | lam/32.0f, FFMIN(lam*32.0f, 1e4f), NMR_IFINE); | |
| 1038 | 1292 | else if (rc_global) | |
| 1039 | 1171 | lam = nmr_solve_slots(s, sl, nsl, NMR_STEP, destbits, lam/2.0f, lam*2.0f, NMR_RC_FITERS); | |
| 1040 | else | ||
| 1041 | 121 | lam = nmr_solve_slots(s, sl, nsl, NMR_STEP, destbits, lam/16.0f, lam*16.0f, NMR_IFINE); | |
| 1042 | } | ||
| 1043 | |||
| 1044 | 2936 | lam_dem = lam; /* demand-solved lambda, pre bucket clamp: what content wants */ | |
| 1045 | |||
| 1046 | 2936 | if (vbr) { | |
| 1047 | /* quality slew: lambda moves smoothly, bits follow content (the same | ||
| 1048 | * anti-flutter rule the CBR path uses; unconstrained per-frame lambda | ||
| 1049 | * reads as framerate-rate quality modulation). Low-content frames | ||
| 1050 | * (silence, stop-gaps) rail lambda high legitimately - they must | ||
| 1051 | * neither be clamped nor write back solver state, or every gap | ||
| 1052 | * poisons the slew/warm-start and the solve re-traps at the rail. */ | ||
| 1053 | 1644 | int subst = 0; | |
| 1054 | 1644 | float st_fin = nmr_nd_stat(s, sl, nsl); | |
| 1055 | 3288 | for (int k = 0; k < nsl; k++) | |
| 1056 | 1644 | subst += sl[k]->nact; | |
| 1057 | /* a frame counts as an operating point only if it bisected the | ||
| 1058 | * statistic (not a short frame holding lambda) and the solve | ||
| 1059 | * actually REACHED the target: cheap frames (room tone, gaps) sit | ||
| 1060 | * far below it at any lambda and rail high while costing nothing */ | ||
| 1061 | /* two-sided: a frame railed COARSE (st far above target, e.g. the | ||
| 1062 | * first content frames of a quiet channel bisecting from nothing) | ||
| 1063 | * is no more an operating point than a railed-fine cheap frame - | ||
| 1064 | * writing its rail lambda builds a slew prison the channel then | ||
| 1065 | * climbs out of one rung per frame, muffling the stream head */ | ||
| 1066 | 1532 | subst = vbr_subst && subst >= 8 && !isnan(st_fin) && | |
| 1067 | 3176 | st_fin > vbr_t - 0.5f && st_fin < vbr_t + 0.5f; | |
| 1068 | 1644 | if (subst) { | |
| 1069 | 1482 | if (*vslew_st > 0.0f) { | |
| 1070 | /* only bisected LONG frames land here (shorts run free); on | ||
| 1071 | * steady-tonal content per-frame lambda jitter reads as | ||
| 1072 | * framerate-rate noise modulation (see NMR_RC_CORR) */ | ||
| 1073 | 1480 | if (lam > *vslew_st * NMR_SLEW || lam < *vslew_st / NMR_SLEW) { | |
| 1074 | 663 | lam = av_clipf(lam, *vslew_st / NMR_SLEW, *vslew_st * NMR_SLEW); | |
| 1075 | 663 | nmr_eval_slots(s, sl, nsl, NMR_STEP, lam); | |
| 1076 | } | ||
| 1077 | } | ||
| 1078 | 1482 | *vslew_st = s->nmr->lam_slew = lam; | |
| 1079 | 162 | } else if (is8_any && *vslew_st > 0.0f) { | |
| 1080 | /* short frames: PASS 2 re-bisects the inflated grouped stat on | ||
| 1081 | * a fresh +-32x bracket, undoing any earlier bound - the clamp | ||
| 1082 | * must sit here, after the last solve (love.flac whoosh: lambda | ||
| 1083 | * railed at exactly lam*32 through an all-shorts passage) */ | ||
| 1084 | 112 | float kup = s->nmr->prev_was_short ? NMR_SLEW_RUN : NMR_SLEW; | |
| 1085 | 112 | float lam0 = FFMIN(*vslew_st, 1e4f); | |
| 1086 | 112 | if (lam > lam0 * kup || lam < lam0 / 4.0f) { | |
| 1087 | 70 | lam = av_clipf(lam, lam0 / 4.0f, lam0 * kup); | |
| 1088 | 70 | nmr_eval_slots(s, sl, nsl, NMR_STEP, lam); | |
| 1089 | } | ||
| 1090 | } | ||
| 1091 | 1644 | vbr_subst = subst; | |
| 1092 | } | ||
| 1093 | 2936 | if (vbr) { | |
| 1094 | /* legality only: a frame may never exceed the bit reservoir bound. | ||
| 1095 | * Side bits ride on top of the trellis count; a negative side | ||
| 1096 | * estimate must never enlarge the cap. The cap is the format limit | ||
| 1097 | * at the reference lambda (the -q:a quality itself for VBR) and | ||
| 1098 | * only shrinks on an outer hard-overflow retry, so the retry | ||
| 1099 | * converges. */ | ||
| 1100 | 1644 | int hardcap = av_clip((int)(5800.f * FFMIN(1.f, lambda / lam_ref)), 256, 5800) * chans; | |
| 1101 | 1644 | int tot = 0; | |
| 1102 | 1644 | if (s->nmr->side_inited) | |
| 1103 | 1640 | hardcap = FFMAX(hardcap - (int)(FFMAX(s->nmr->side_ema, 0.0f) * chans / s->channels), 256); | |
| 1104 | 3288 | for (int k = 0; k < nsl; k++) | |
| 1105 | 1644 | tot += nmr_slot_bits(sl[k], s->nmr->nb[sl[k]->si], NMR_STEP); | |
| 1106 | 1644 | if (abr && s->nmr->abr_ema < rc_rate_frame) { | |
| 1107 | /* bits-fill: under the long-run target, top an easy frame up | ||
| 1108 | * toward the ask by moving lambda FINER only - the quality | ||
| 1109 | * target is a floor, never traded away. Spends the rate the | ||
| 1110 | * user asked for on sub-mask margin the nd statistic cannot | ||
| 1111 | * see (it clips at -4/band); without this, stat-transparent | ||
| 1112 | * content caps the rate below any ask. Active from frame one | ||
| 1113 | * (the immature EMA reads as a deficit, so the stream head is | ||
| 1114 | * held near the ask) and fades continuously as the EMA | ||
| 1115 | * converges - a boot-gated fill flips regimes at ~2s, an | ||
| 1116 | * audible quality step. | ||
| 1117 | * The fill target follows the psy PE demand shape: per-frame | ||
| 1118 | * demand carries perceptual information the nd model does not | ||
| 1119 | * (the constant-lambda lesson) - and routing it through the | ||
| 1120 | * fill keeps the quality floor intact. */ | ||
| 1121 | 748 | float dshape = 1.0f; | |
| 1122 | int fill; | ||
| 1123 | 748 | if (s->psy.bitres.alloc > 0) { | |
| 1124 | 748 | float *aema = &s->nmr->abr_alloc_ema; | |
| 1125 | 748 | if (*aema <= 0.0f) *aema = s->psy.bitres.alloc; | |
| 1126 | 747 | else *aema += 0.01f * (s->psy.bitres.alloc - *aema); | |
| 1127 | 748 | dshape = av_clipf(s->psy.bitres.alloc / *aema, 0.6f, 1.7f); | |
| 1128 | } | ||
| 1129 | 748 | fill = (int)((rc_rate_frame + (rc_rate_frame - (int)s->nmr->abr_ema)) * dshape) * | |
| 1130 | 748 | chans / s->channels; | |
| 1131 | 748 | fill = FFMIN3(fill, 3 * rc_rate_frame * chans / s->channels / 2, hardcap); | |
| 1132 | 748 | if (tot < fill) { | |
| 1133 | /* the fill dive is the easy-frame operating point: slew it | ||
| 1134 | * like any other lambda move and let it carry the | ||
| 1135 | * continuity state, or per-frame depth variation reads as | ||
| 1136 | * frame-rate HF wobble */ | ||
| 1137 | 416 | float flo = lam / 64.0f; | |
| 1138 | 416 | if (*vslew_st > 0.0f) | |
| 1139 | 416 | flo = FFMIN(FFMAX(flo, *vslew_st / NMR_SLEW), lam); | |
| 1140 | 416 | lam = nmr_solve_slots(s, sl, nsl, NMR_STEP, fill, flo, lam, NMR_RC_ITERS); | |
| 1141 | 416 | if (!is8_any) | |
| 1142 | 400 | *vslew_st = s->nmr->lam_slew = lam; | |
| 1143 | 416 | tot = 0; | |
| 1144 | 832 | for (int k = 0; k < nsl; k++) | |
| 1145 | 416 | tot += nmr_slot_bits(sl[k], s->nmr->nb[sl[k]->si], NMR_STEP); | |
| 1146 | } | ||
| 1147 | } | ||
| 1148 | 1644 | if (tot > hardcap) { | |
| 1149 | 373 | lam = nmr_solve_slots(s, sl, nsl, NMR_STEP, hardcap, lam, 1e4f, NMR_RC_ITERS); | |
| 1150 | 373 | tot = 0; | |
| 1151 | 746 | for (int k = 0; k < nsl; k++) | |
| 1152 | 373 | tot += nmr_slot_bits(sl[k], s->nmr->nb[sl[k]->si], NMR_STEP); | |
| 1153 | /* dense short frames at high rates can exceed the decoder | ||
| 1154 | * buffer even at the coarsest candidate grid; an illegal frame | ||
| 1155 | * traps the outer re-encode loop forever. Shed the highest | ||
| 1156 | * bands until the frame fits. act[] runs window group by window | ||
| 1157 | * group, so pick the highest band across all groups; the first | ||
| 1158 | * band anchors the scalefactor chain and stays. */ | ||
| 1159 | 586 | while (tot > hardcap) { | |
| 1160 | 213 | int dropped = 0; | |
| 1161 | 426 | for (int k = 0; k < nsl; k++) { | |
| 1162 | 213 | NMRSlot *t = sl[k]; | |
| 1163 | 213 | int hi = 1; | |
| 1164 | 213 | if (t->nact <= 1) | |
| 1165 | ✗ | continue; | |
| 1166 | 9511 | for (int b_ = 2; b_ < t->nact; b_++) | |
| 1167 | 9298 | if (t->bg[t->act[b_]] >= t->bg[t->act[hi]]) | |
| 1168 | 8631 | hi = b_; | |
| 1169 | 213 | nmr_drop_band(t, t->act[hi]); | |
| 1170 | 213 | memmove(&t->act[hi], &t->act[hi + 1], (t->nact - hi - 1) * sizeof(t->act[0])); | |
| 1171 | 213 | t->nact--; | |
| 1172 | /* the dropped band may have bridged its neighbours */ | ||
| 1173 | 213 | nmr_chain_repair(t, NMR_STEP); | |
| 1174 | 213 | dropped = 1; | |
| 1175 | } | ||
| 1176 | 213 | if (!dropped) | |
| 1177 | ✗ | break; | |
| 1178 | 213 | tot = nmr_eval_slots(s, sl, nsl, NMR_STEP, lam); | |
| 1179 | } | ||
| 1180 | } | ||
| 1181 | } | ||
| 1182 | |||
| 1183 | 2936 | if (rc_global) { | |
| 1184 | /* reservoir cap on the fine grid (see the coarse-pass bound above), | ||
| 1185 | * then the quality slew limiter */ | ||
| 1186 | 1171 | int hardcap = av_clip((int)(5800.f * FFMIN(1.f, lambda / 120.f)), 256, 5800) * chans; | |
| 1187 | 1171 | int tot = 0, rc_cap; | |
| 1188 | 2703 | for (int k = 0; k < nsl; k++) | |
| 1189 | 1532 | tot += nmr_slot_bits(sl[k], s->nmr->nb[sl[k]->si], NMR_STEP); | |
| 1190 | 1171 | rc_cap = FFMIN(hardcap, (s->nmr->rc_fill + rc_rate_frame + rc_bmax) * chans / s->channels); | |
| 1191 | 1171 | if (tot > rc_cap) { | |
| 1192 | 12 | lam = nmr_solve_slots(s, sl, nsl, NMR_STEP, rc_cap, lam, 1e4f, NMR_RC_ITERS); | |
| 1193 | } | ||
| 1194 | { /* bucket-full spend floor: bits saved beyond the reservoir's | ||
| 1195 | * remaining headroom are simply lost, so with a full bucket the | ||
| 1196 | * plan must not sit below nominal minus what can still be | ||
| 1197 | * banked. Without this a quiet intro poisons the corridor high | ||
| 1198 | * and the loud entrance rate-limits through it - a muffled | ||
| 1199 | * first second at the exact moment the listener tunes in. */ | ||
| 1200 | 1171 | int headroom = rc_bmax - av_clip(s->nmr->rc_fill, -rc_bmax, rc_bmax); | |
| 1201 | 1171 | int fbits = (rc_rate_frame - headroom) * chans / s->channels; | |
| 1202 | 1171 | if (tot < fbits) { | |
| 1203 | 385 | lam = nmr_solve_slots(s, sl, nsl, NMR_STEP, fbits, lam / 64.0f, lam, NMR_RC_ITERS); | |
| 1204 | 385 | tot = 0; | |
| 1205 | 825 | for (int k = 0; k < nsl; k++) | |
| 1206 | 440 | tot += nmr_slot_bits(sl[k], s->nmr->nb[sl[k]->si], NMR_STEP); | |
| 1207 | } | ||
| 1208 | } | ||
| 1209 | 1171 | if (s->nmr->lam_slew > 0.0f) { | |
| 1210 | float kup, kdn; | ||
| 1211 | /* hold lambda near-constant within short runs; bits follow content */ | ||
| 1212 | 1171 | kup = (is8_any && s->nmr->prev_was_short) ? NMR_SLEW_RUN : NMR_SLEW; | |
| 1213 | /* a deliberate onset burst may dive as far as its widened corridor | ||
| 1214 | * allows; the RECOVERY back up is what must stay gradual */ | ||
| 1215 | 2340 | kdn = (is8_any && s->nmr->run_burst > 1.0f) ? NMR_SLEW * s->nmr->run_burst : | |
| 1216 | 1169 | (is8_any && s->nmr->prev_was_short) ? NMR_SLEW_RUN : NMR_SLEW; | |
| 1217 | 1171 | if (lam > s->nmr->lam_slew * kup || lam < s->nmr->lam_slew / kdn) { | |
| 1218 | 344 | lam = av_clipf(lam, s->nmr->lam_slew / kdn, s->nmr->lam_slew * kup); | |
| 1219 | 344 | tot = nmr_eval_slots(s, sl, nsl, NMR_STEP, lam); | |
| 1220 | /* never at the price of an illegal reservoir excursion */ | ||
| 1221 | 344 | if (tot > rc_cap) { | |
| 1222 | 5 | lam = nmr_solve_slots(s, sl, nsl, NMR_STEP, rc_cap, lam, 1e4f, NMR_RC_ITERS); | |
| 1223 | } | ||
| 1224 | } | ||
| 1225 | } | ||
| 1226 | 1171 | s->nmr->lam_slew = lam; | |
| 1227 | 1765 | } else if (rc_eligible && !vbr) { | |
| 1228 | /* corridor not yet bootstrapped: the same bucket-full floor, so a | ||
| 1229 | * fade-in bootstraps lam_rc at a spending operating point instead | ||
| 1230 | * of memorizing the intro's starvation lambda */ | ||
| 1231 | 121 | int headroom = rc_bmax - av_clip(s->nmr->rc_fill, -rc_bmax, rc_bmax); | |
| 1232 | 121 | int fbits = (rc_rate_frame - headroom) * chans / s->channels; | |
| 1233 | 121 | int tot = 0; | |
| 1234 | 242 | for (int k = 0; k < nsl; k++) | |
| 1235 | 121 | tot += nmr_slot_bits(sl[k], s->nmr->nb[sl[k]->si], NMR_STEP); | |
| 1236 | 121 | if (tot < fbits) | |
| 1237 | 52 | lam = nmr_solve_slots(s, sl, nsl, NMR_STEP, fbits, lam / 64.0f, lam, NMR_RC_ITERS); | |
| 1238 | } | ||
| 1239 | |||
| 1240 | 2936 | if (!vbr || vbr_subst) | |
| 1241 | 5909 | for (int k = 0; k < nsl; k++) | |
| 1242 | 3135 | s->nmr->lam[sl[k]->cur_ch] = lam; /* warm start for the next frame */ | |
| 1243 | { /* nd: mean achieved dist/real-mask (dimensionless starvation + | ||
| 1244 | * noise-class signal) */ | ||
| 1245 | 2936 | float ndsum = 0.0f; int ndn = 0; | |
| 1246 | 6233 | for (int k = 0; k < nsl; k++) { | |
| 1247 | 3297 | NMRSlot *t = sl[k]; | |
| 1248 | 3297 | float (*ndk)[NMR_NCAND] = s->nmr->nd[t->si]; | |
| 1249 | 127719 | for (int b_ = 0; b_ < t->nact; b_++) { | |
| 1250 | 124422 | int b = t->act[b_], bi = t->bidx[b]; | |
| 1251 | 124422 | if (t->thr_real[bi] > 0.0f && t->thr[bi] > 0.0f && !t->hftx[bi]) { | |
| 1252 | 111116 | ndsum += ndk[b][t->chosen[b]] * t->thr[bi] / t->thr_real[bi]; | |
| 1253 | 111116 | ndn++; | |
| 1254 | } | ||
| 1255 | } | ||
| 1256 | } | ||
| 1257 | /* long frames only (short groups inflate the ratio) */ | ||
| 1258 | 2936 | if (ndn >= 8 && !is8_any) { | |
| 1259 | 2672 | float nd = ndsum / ndn; | |
| 1260 | 2672 | s->nmr->nd_ema = s->nmr->nd_ema > 0.0f ? | |
| 1261 | 2672 | 0.95f * s->nmr->nd_ema + 0.05f * nd : nd; | |
| 1262 | } | ||
| 1263 | } | ||
| 1264 | { /* track short vs long operating lambda (dense-beat boost scaling) */ | ||
| 1265 | 2936 | float *ema = is8_any ? &s->nmr->lam_short_ema : &s->nmr->lam_long_ema; | |
| 1266 | 2936 | *ema = *ema > 0.0f ? 0.9f * *ema + 0.1f * lam : lam; | |
| 1267 | /* sustained-strain floor: snaps down at any comfortable moment, | ||
| 1268 | * recovers only slowly, so bursty content cannot bank pressure | ||
| 1269 | * credit between its lambda valleys. */ | ||
| 1270 | 5872 | s->nmr->lam_floor = s->nmr->lam_floor > 0.0f ? | |
| 1271 | 2936 | fminf(s->nmr->lam_floor * 1.02f, lam) : lam; | |
| 1272 | } | ||
| 1273 | { /* shared rate-pressure ramp: lambda vs nd-scaled anchors */ | ||
| 1274 | float scale, ramp; | ||
| 1275 | 2936 | scale = 1.0f + av_clipf(s->nmr->nd_ema / 50.0f, 0.0f, 8.0f); | |
| 1276 | 2 | ramp = s->nmr->lam_long_ema > 0.0f ? | |
| 1277 | 2934 | av_clipf((s->nmr->lam_long_ema - 120.0f * scale) / | |
| 1278 | 2936 | (350.0f * scale - 120.0f * scale), 0.0f, 1.0f) : 0.0f; | |
| 1279 | /* transparency veto: lambda*nd below ~74 = comfortable */ | ||
| 1280 | 2936 | if (s->nmr->nd_ema > 0.0f) | |
| 1281 | 2934 | ramp *= av_clipf((s->nmr->lam_long_ema * s->nmr->nd_ema - 60.0f) / | |
| 1282 | (120.0f - 60.0f), 0.0f, 1.0f); | ||
| 1283 | 2936 | s->nmr->press = ramp; | |
| 1284 | } | ||
| 1285 | 2936 | if (rc_global) { | |
| 1286 | /* track the centre toward the CONTENT lambda (demand-solved, pressure | ||
| 1287 | * divided out); clamped lambda is rate noise, not content */ | ||
| 1288 | 1171 | float c = s->nmr->lam_rc * powf(lam_dem / rc_off / s->nmr->lam_rc, NMR_RC_TRACK); | |
| 1289 | 1171 | s->nmr->lam_rc = av_clipf(c, 1e-6f, 1e4f); | |
| 1290 | 1765 | } else if (rc_eligible) { | |
| 1291 | /* bootstrap the servo off the first substantive frame (silent lead-ins | ||
| 1292 | * have degenerate budgets) */ | ||
| 1293 | 121 | int nbnd_max = 0; | |
| 1294 | 242 | for (int k = 0; k < nsl; k++) | |
| 1295 | 121 | nbnd_max = FFMAX(nbnd_max, sl[k]->nbnd); | |
| 1296 | 121 | if (nbnd_max >= 8) { | |
| 1297 | 111 | s->nmr->lam_rc = av_clipf(lam, 1e-4f, 1e4f); | |
| 1298 | 111 | s->nmr->lam_slew = s->nmr->lam_rc; | |
| 1299 | } | ||
| 1300 | } | ||
| 1301 | |||
| 1302 | { /* PNS, per channel at the group's operating lambda */ | ||
| 1303 | 2936 | const float pns_lam = NMR_PNS_LAM; | |
| 1304 | 2936 | int pns_total = 0; | |
| 1305 | 6233 | for (int k = 0; k < nsl; k++) { | |
| 1306 | 3297 | NMRSlot *t = sl[k]; | |
| 1307 | 3297 | const float (*ndk)[NMR_NCAND] = (const float (*)[NMR_NCAND])s->nmr->nd[t->si]; | |
| 1308 | 3297 | const int (*nbk)[NMR_NCAND] = (const int (*)[NMR_NCAND])s->nmr->nb[t->si]; | |
| 1309 | 3297 | int pns_count = 0; | |
| 1310 | /* band 0 (lowest freq) is kept as the global-gain / sf-chain anchor */ | ||
| 1311 | 124635 | for (int b = 1; b < t->nbnd; b++) { | |
| 1312 | 121338 | int bi = t->bidx[b]; | |
| 1313 | 121338 | float spread = t->pspread[bi]; | |
| 1314 | float nmr_pns, cost_keep, cost_pns, frac; | ||
| 1315 | /* zeroes[] is only set on a coded band when it was shed for | ||
| 1316 | * legality; such a band must not come back as noise */ | ||
| 1317 | 121338 | if (!t->sce->can_pns[bi] || t->sce->zeroes[bi]) | |
| 1318 | 107505 | continue; | |
| 1319 | |||
| 1320 | 13833 | int was = s->nmr->pns_prev[t->cur_ch & 15][bi]; | |
| 1321 | 13833 | float bias = was ? NMR_PNS_STAY : NMR_PNS_ENTER; | |
| 1322 | 13833 | int want = 0, force_exit = 0; | |
| 1323 | |||
| 1324 | /* (can_pns was already checked above; gates below fill `want`) */ | ||
| 1325 | 13833 | if (t->pener[bi] > NMR_PNS_MAX_ET * t->thr_real[bi]) { | |
| 1326 | 5570 | force_exit = 1; /* loud-band guard */ | |
| 1327 | 8263 | } else if (lam > NMR_PNS_HOLE_LAM && | |
| 1328 | 3354 | (frac = ndk[b][t->chosen[b]] * t->thr[bi] / | |
| 1329 | 1677 | FFMAX(t->pener[bi], 1e-9f)) > NMR_PNS_HOLE_FRAC * (was ? 0.7f : 1.0f) && | |
| 1330 | spread > NMR_PNS_HOLE_SPREAD) { | ||
| 1331 | /* Spectral-hole fill: a noise-like band whose chosen | ||
| 1332 | * rendition leaves most of its energy uncoded turns to | ||
| 1333 | * sparse lines - structure damage the NMR objective | ||
| 1334 | * cannot see - at ANY comfortable lambda */ | ||
| 1335 | 201 | want = 1; | |
| 1336 | 8062 | } else if (lam > pns_lam) { | |
| 1337 | 498 | if (ndk[b][t->chosen[b]] * t->thr[bi] > | |
| 1338 | 249 | NMR_PNS_NDGATE * t->thr_real[bi] * (was ? 0.5f : 1.0f)) { | |
| 1339 | /* replace only a band coded audibly badly; cost of | ||
| 1340 | * energy-matched noise = its non-noise-like fraction */ | ||
| 1341 | ✗ | nmr_pns = FFMAX(0.0f, t->pener[bi] * (1.0f - spread*spread)) | |
| 1342 | ✗ | / FFMAX(t->thr[bi], 1e-9f); | |
| 1343 | ✗ | cost_keep = ndk[b][t->chosen[b]] + lam * nbk[b][t->chosen[b]]; | |
| 1344 | ✗ | cost_pns = nmr_pns + lam * NMR_PNS_BITS; | |
| 1345 | ✗ | want = cost_pns < cost_keep * bias; | |
| 1346 | } | ||
| 1347 | } | ||
| 1348 | { /* debounce; near-mask deletion candidates skip entry | ||
| 1349 | * (noise beats the ~silent rendition they'd get) */ | ||
| 1350 | 13833 | uint8_t *ron = &s->nmr->pns_run_on [t->cur_ch & 15][bi]; | |
| 1351 | 13833 | uint8_t *roff = &s->nmr->pns_run_off[t->cur_ch & 15][bi]; | |
| 1352 | 13833 | int near = t->pener[bi] < 2.0f * t->thr_real[bi]; | |
| 1353 | 13833 | if (want) { if (*ron < 255) (*ron)++; *roff = 0; } | |
| 1354 | 13632 | else { if (*roff < 255) (*roff)++; *ron = 0; } | |
| 1355 | 13833 | if (force_exit) | |
| 1356 | 5570 | want = was && *roff < 2; /* tolerate 1-frame loudness blips */ | |
| 1357 | 8263 | else if (!was) | |
| 1358 | 8236 | want = *ron >= (near ? 2 : NMR_PNS_ON); | |
| 1359 | 27 | else if (near) | |
| 1360 | ✗ | want = 1; /* physics-hysteresis: noise until audible */ | |
| 1361 | else | ||
| 1362 | 27 | want = !(*roff >= NMR_PNS_OFF); | |
| 1363 | } | ||
| 1364 | 13833 | if (want) { | |
| 1365 | 28 | t->is_pns[b] = 1; | |
| 1366 | 28 | pns_count++; | |
| 1367 | } | ||
| 1368 | } | ||
| 1369 | 3297 | if (pns_count) { | |
| 1370 | /* filter the active list rather than rebuilding it from | ||
| 1371 | * nbnd: bands shed for legality must stay out */ | ||
| 1372 | 21 | int n = 0; | |
| 1373 | 924 | for (int b_ = 0; b_ < t->nact; b_++) | |
| 1374 | 903 | if (!t->is_pns[t->act[b_]]) | |
| 1375 | 875 | t->act[n++] = t->act[b_]; | |
| 1376 | 21 | t->nact = n; | |
| 1377 | /* noise bands leave the scalefactor chain */ | ||
| 1378 | 21 | nmr_chain_repair(t, NMR_STEP); | |
| 1379 | } | ||
| 1380 | 3297 | pns_total += pns_count; | |
| 1381 | } | ||
| 1382 | 2936 | if (pns_total) { | |
| 1383 | /* re-solve over the survivors: at fixed lambda the allocation is | ||
| 1384 | * the same except for the repaired sf-delta chain; in bisection | ||
| 1385 | * mode re-spend the freed budget */ | ||
| 1386 | 21 | if (rc_global || vbr) | |
| 1387 | 21 | nmr_eval_slots(s, sl, nsl, NMR_STEP, lam); | |
| 1388 | else | ||
| 1389 | ✗ | nmr_solve_slots(s, sl, nsl, NMR_STEP, destbits - pns_total * NMR_PNS_BITS, | |
| 1390 | 1e-9f, 1e4f, NMR_ITERS); | ||
| 1391 | } | ||
| 1392 | } | ||
| 1393 | |||
| 1394 | 6233 | for (int k = 0; k < nsl; k++) { | |
| 1395 | 3297 | NMRSlot *t = sl[k]; | |
| 1396 | 3297 | uint8_t *pp = s->nmr->pns_prev[t->cur_ch & 15]; | |
| 1397 | 3297 | uint8_t now[128] = {0}; | |
| 1398 | 127932 | for (int b = 0; b < t->nbnd; b++) | |
| 1399 | 124635 | if (t->is_pns[b]) | |
| 1400 | 28 | now[t->bidx[b]] = 1; | |
| 1401 | 3297 | memcpy(pp, now, 128); | |
| 1402 | } | ||
| 1403 | 6233 | for (int k = 0; k < nsl; k++) | |
| 1404 | 3297 | nmr_commit_channel(s, sl[k]); | |
| 1405 | |||
| 1406 | 2936 | } | |
| 1407 | |||
| 1408 | 3867 | static void search_for_quantizers_nmr(AVCodecContext *avctx, | |
| 1409 | AACEncContext *s, | ||
| 1410 | SingleChannelElement *sce, | ||
| 1411 | const float lambda) | ||
| 1412 | { | ||
| 1413 | 3867 | AACNMRCurves *n = s->nmr; | |
| 1414 | /* Global-lambda RC: one solve per frame at a servoed centre lambda; the reservoir | ||
| 1415 | * holds the long-run mean rate. Bypassed for VBR (-q:a) and the bootstrap frame. */ | ||
| 1416 | 3045 | int rc_eligible = !(avctx->flags & AV_CODEC_FLAG_QSCALE) && avctx->bit_rate > 0 && | |
| 1417 | 6912 | avctx->bit_rate_tolerance != 0 && s->options.rc == 0; | |
| 1418 | /* Signed reservoir; soft steering (bounded repay + rc_off), hard cap = | ||
| 1419 | * legality only. */ | ||
| 1420 | 3867 | int rc_rate_frame = avctx->bit_rate * 1024.0 / avctx->sample_rate; | |
| 1421 | 3867 | int rc_bmax = FFMIN(FFMAX(6144 * s->channels - rc_rate_frame, 256), NMR_CBR_BUF * s->channels); | |
| 1422 | |||
| 1423 | int rc_global, defer; | ||
| 1424 | NMRSlot *t; | ||
| 1425 | |||
| 1426 | 3867 | s->nmr->counted[s->cur_channel] = 0; | |
| 1427 | |||
| 1428 | 3867 | if (s->options.rc == 1 && !(avctx->flags & AV_CODEC_FLAG_QSCALE) && | |
| 1429 | 822 | avctx->bit_rate > 0 && avctx->frame_num != n->abr_frame_num) { | |
| 1430 | /* ABR servo: integrate the log rate error, but apply it to the nd | ||
| 1431 | * set-point in RARE, DISCRETE steps. The set-point must be | ||
| 1432 | * quasi-static: any drift on content timescales moves lambda, and | ||
| 1433 | * with it band/PNS/scalefactor state - measured 2x worse than a | ||
| 1434 | * fixed target at equal mean rate. Locally this mode IS fixed-target | ||
| 1435 | * VBR; rate honesty converges on the minutes scale. */ | ||
| 1436 | 411 | if (n->abr_frame_num == 0 && n->abr_ema <= 0.0f) { | |
| 1437 | /* seed the set-point from the VBR calibration anchor (see | ||
| 1438 | * NMR_VBR_ANCHOR for the 81.5 kbps/ch reference); the servo | ||
| 1439 | * trims the rest */ | ||
| 1440 | 1 | n->abr_t = av_clipf(NMR_VBR_ANCHOR - 2.5f * log2f(avctx->bit_rate / | |
| 1441 | 1 | (81500.0f * s->channels)), NMR_ABR_TMIN, NMR_ABR_TMAX); | |
| 1442 | 1 | n->abr_ema = rc_rate_frame; | |
| 1443 | 410 | } else if (s->last_frame_pb_count > 0) { | |
| 1444 | /* bootstrap: fast rate measurement for ~2s, then one open-loop | ||
| 1445 | * jump over the measured loop gain (~ -0.24 log2 rate per target | ||
| 1446 | * unit) corrects the seed's per-content error; the quasi-static | ||
| 1447 | * stepper handles drift from there */ | ||
| 1448 | /* seed on-target: an EMA warming up from zero reads as a fake | ||
| 1449 | * deficit and the fill overspends the whole stream head */ | ||
| 1450 | 410 | if (n->abr_ema <= 0.0f) | |
| 1451 | ✗ | n->abr_ema = rc_rate_frame; | |
| 1452 | 410 | n->abr_ema += (n->abr_booted ? NMR_ABR_EMA : 0.02f) * | |
| 1453 | 410 | (s->last_frame_pb_count - n->abr_ema); | |
| 1454 | 410 | n->abr_hold++; | |
| 1455 | 410 | if (!n->abr_booted) { | |
| 1456 | 210 | n->abr_longs += sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE; | |
| 1457 | /* boot only off a REPRESENTATIVE window: an all-transient | ||
| 1458 | * head (castanets roll) reads over-target and would coarsen | ||
| 1459 | * the very content that needs bits. Time out eventually. */ | ||
| 1460 | 210 | if ((n->abr_hold >= 86 && n->abr_longs >= n->abr_hold / 2) || | |
| 1461 | 208 | n->abr_hold >= 400) { | |
| 1462 | /* glide the seed correction in, never step it: a | ||
| 1463 | * one-frame noise-floor jump at a fixed stream time is | ||
| 1464 | * audible against revealing content */ | ||
| 1465 | 2 | n->abr_glide = NMR_ABR_BOOT_GAIN * log2f(n->abr_ema / rc_rate_frame) / 0.24f; | |
| 1466 | 2 | n->abr_booted = 1; | |
| 1467 | 2 | n->abr_boots++; | |
| 1468 | 2 | n->abr_hold = 0; | |
| 1469 | } | ||
| 1470 | } else { | ||
| 1471 | /* Re-arm the open-loop correction while the rate is still | ||
| 1472 | * off. One boot leaves a residual whenever the real loop gain | ||
| 1473 | * differs from the nominal 0.24, and the estimator is biased | ||
| 1474 | * toward the ask by construction (the EMA is seeded ON target | ||
| 1475 | * so a cold start cannot read as a deficit), so it understates | ||
| 1476 | * the error it is correcting. The quasi-static stepper cannot | ||
| 1477 | * drain that inside a track - measured, male_speech ended a | ||
| 1478 | * 774-frame file 23% short and still moving. Re-measuring and | ||
| 1479 | * firing again converges regardless of the gain estimate, and | ||
| 1480 | * keeps the set-point quasi-static: corrections stay rare, | ||
| 1481 | * glided, and bounded in number. */ | ||
| 1482 | 200 | if (n->abr_boots < NMR_ABR_BOOTS && n->abr_glide == 0.0f && | |
| 1483 | 110 | n->abr_hold >= NMR_ABR_SETTLE && | |
| 1484 | 2 | fabsf(log2f(n->abr_ema / rc_rate_frame)) > NMR_ABR_TOL) { | |
| 1485 | /* Re-seed the estimator ON target, exactly as the cold | ||
| 1486 | * start does - never to zero. The value is read again | ||
| 1487 | * before anything re-seeds it: by the integrator below | ||
| 1488 | * (log2f(0) is -inf, which pinned the accumulator at its | ||
| 1489 | * clip) and by the bits-fill later in this same frame | ||
| 1490 | * (a zero EMA reads as a 100% deficit and authorises a | ||
| 1491 | * one-frame overspend). Drop the residual integral with | ||
| 1492 | * it: it describes the regime being left, and the boot | ||
| 1493 | * is about to re-measure that same error open-loop. */ | ||
| 1494 | 2 | n->abr_booted = 0; | |
| 1495 | 2 | n->abr_ema = rc_rate_frame; | |
| 1496 | 2 | n->abr_acc = 0.0f; | |
| 1497 | 2 | n->abr_hold = 0; | |
| 1498 | 2 | n->abr_longs = 0; | |
| 1499 | } else { | ||
| 1500 | 198 | n->abr_acc = av_clipf(n->abr_acc + NMR_ABR_K * log2f(n->abr_ema / rc_rate_frame), | |
| 1501 | -4.0f * NMR_ABR_STEP, 4.0f * NMR_ABR_STEP); | ||
| 1502 | /* step in calm stretches (a set-point move during a transient | ||
| 1503 | * section coarsens exactly what needs the bits) - but dense | ||
| 1504 | * content must not deadlock the servo: after 3x the hold the | ||
| 1505 | * step fires regardless. Large errors step at double size; | ||
| 1506 | * the remainder carries over instead of being discarded. */ | ||
| 1507 | 198 | if (fabsf(n->abr_acc) >= NMR_ABR_STEP && n->abr_hold >= NMR_ABR_HOLD && | |
| 1508 | ✗ | (n->frames_since_short >= 12 || n->abr_hold >= 3 * NMR_ABR_HOLD)) { | |
| 1509 | ✗ | float ms = NMR_ABR_STEP * (fabsf(n->abr_acc) > 3.0f * NMR_ABR_STEP ? 2.0f : 1.0f); | |
| 1510 | ✗ | float step = av_clipf(n->abr_acc, -ms, ms); | |
| 1511 | ✗ | n->abr_glide += step; | |
| 1512 | ✗ | n->abr_acc -= step; | |
| 1513 | ✗ | n->abr_hold = 0; | |
| 1514 | } | ||
| 1515 | } | ||
| 1516 | } | ||
| 1517 | 410 | if (n->abr_glide != 0.0f) { | |
| 1518 | /* drain pending set-point corrections smoothly (~0.5 | ||
| 1519 | * log2-units/s): the decision stays quasi-static and | ||
| 1520 | * calm-gated, only the application glides */ | ||
| 1521 | 92 | float d = av_clipf(n->abr_glide, -0.012f, 0.012f); | |
| 1522 | 92 | n->abr_t = av_clipf(n->abr_t + d, NMR_ABR_TMIN, NMR_ABR_TMAX); | |
| 1523 | 92 | n->abr_glide -= d; | |
| 1524 | 92 | if (fabsf(n->abr_glide) < 1e-4f) | |
| 1525 | 2 | n->abr_glide = 0.0f; | |
| 1526 | } | ||
| 1527 | } | ||
| 1528 | 411 | n->abr_frame_num = avctx->frame_num; | |
| 1529 | } | ||
| 1530 | 3867 | if (rc_eligible && !n->rc_fill_seeded) { | |
| 1531 | /* the decoder bit reservoir starts FULL: seed it so the head may frontload */ | ||
| 1532 | 19 | n->rc_fill = rc_bmax; | |
| 1533 | 19 | n->rc_fill_seeded = 1; | |
| 1534 | } | ||
| 1535 | 3867 | if (rc_eligible && avctx->frame_num != n->rc_frame_num) { | |
| 1536 | 1093 | if (n->rc_frame_num > 0 && n->lam_rc > 0.0f) | |
| 1537 | 716 | n->rc_fill = av_clip(n->rc_fill + rc_rate_frame - s->last_frame_pb_count, | |
| 1538 | -rc_bmax, rc_bmax); | ||
| 1539 | 1093 | n->rc_frame_num = avctx->frame_num; | |
| 1540 | 1093 | n->pending = 0; /* a deferred first channel never crosses a frame */ | |
| 1541 | /* consecutive saturated frames, once per frame across all element | ||
| 1542 | * groups: any frame without a saturated overage ends the run */ | ||
| 1543 | 1093 | n->rc_satrun = n->rc_sat_frame ? n->rc_satrun + 1 : 0; | |
| 1544 | 1093 | n->rc_sat_frame = 0; | |
| 1545 | /* latch the RC mode per frame: a mid-frame bootstrap must not flip | ||
| 1546 | * the CPE defer logic between channels */ | ||
| 1547 | 1093 | n->rc_gl = rc_eligible && n->lam_rc > 0.0f; | |
| 1548 | } | ||
| 1549 | 3867 | if (avctx->frame_num != n->win_frame_num) { | |
| 1550 | /* Window history, once per frame in every rate-control mode (the | ||
| 1551 | * quality-target slew and the ABR servo read it too). | ||
| 1552 | * Transient burst run state: set at run start and held across the run so | ||
| 1553 | * coding stays uniform; repaid from the reservoir's steady stretches. */ | ||
| 1554 | 1921 | int is_short = sce->ics.window_sequence[0] == EIGHT_SHORT_SEQUENCE; | |
| 1555 | 1921 | n->win_frame_num = avctx->frame_num; | |
| 1556 | 1921 | if (is_short) { | |
| 1557 | 72 | if (!n->prev_was_short) { /* run start */ | |
| 1558 | 55 | if (n->frames_since_short >= NMR_BURST_GAP) { | |
| 1559 | 29 | n->run_burst = NMR_BURST_GAIN; | |
| 1560 | } else { | ||
| 1561 | /* dense-beat boost, scaled by measured short-frame starvation */ | ||
| 1562 | 26 | float imb = 0.0f; | |
| 1563 | 26 | if (n->lam_long_ema > 0.0f && n->lam_short_ema > 0.0f) | |
| 1564 | 12 | imb = av_clipf(n->lam_short_ema / n->lam_long_ema - 1.0f, | |
| 1565 | 0.0f, 1.0f); | ||
| 1566 | 26 | n->run_burst = 1.0f + (NMR_SHORT_BOOST - 1.0f) * imb * | |
| 1567 | 26 | n->frames_since_short / (float)NMR_BURST_GAP; | |
| 1568 | } | ||
| 1569 | } | ||
| 1570 | 72 | n->frames_since_short = 0; | |
| 1571 | } else { | ||
| 1572 | /* the frame closing a run (the STOP) absorbs the corridor recoil | ||
| 1573 | * of the boosted shorts; give it half the run's factor so the | ||
| 1574 | * repayment spreads into the steady stretch instead */ | ||
| 1575 | 1849 | n->run_burst = n->prev_was_short ? sqrtf(n->run_burst) : 1.0f; | |
| 1576 | 1849 | n->frames_since_short++; | |
| 1577 | } | ||
| 1578 | 1921 | n->prev_was_short = is_short; | |
| 1579 | } | ||
| 1580 | 3867 | rc_global = rc_eligible && n->rc_gl; | |
| 1581 | |||
| 1582 | /* CPE budget pool: under global-lambda RC, defer the pair's first channel | ||
| 1583 | * and solve both against one pooled budget when the second one arrives. */ | ||
| 1584 | 3867 | defer = n->pair && rc_global; | |
| 1585 | |||
| 1586 | 3867 | t = &n->slot[(defer && n->pending) ? 1 : 0]; | |
| 1587 | 3867 | t->si = (defer && n->pending) ? 1 : 0; | |
| 1588 | |||
| 1589 | 3867 | if (!nmr_setup_channel(avctx, s, sce, t)) { | |
| 1590 | 570 | nmr_bail_channel(sce); | |
| 1591 | 570 | t->nbnd = t->nact = 0; | |
| 1592 | } | ||
| 1593 | |||
| 1594 | 3867 | if (defer && !n->pending) { | |
| 1595 | 461 | n->pending = 1; /* wait for the partner channel */ | |
| 1596 | 461 | return; | |
| 1597 | } | ||
| 1598 | |||
| 1599 | { | ||
| 1600 | NMRSlot *sl[2]; | ||
| 1601 | 3406 | int nsl = 0, chans = 1; | |
| 1602 | 3406 | if (defer) { | |
| 1603 | 461 | n->pending = 0; | |
| 1604 | 461 | chans = 2; | |
| 1605 | 461 | if (n->slot[0].nact) | |
| 1606 | 461 | sl[nsl++] = &n->slot[0]; | |
| 1607 | 461 | if (n->slot[1].nact) | |
| 1608 | 361 | sl[nsl++] = &n->slot[1]; | |
| 1609 | 2945 | } else if (t->nact) { | |
| 1610 | 2475 | sl[nsl++] = t; | |
| 1611 | } | ||
| 1612 | 3406 | if (!nsl) | |
| 1613 | 470 | return; /* nothing codeable in the group */ | |
| 1614 | 2936 | nmr_solve_group(avctx, s, lambda, sl, nsl, chans, | |
| 1615 | rc_eligible, rc_global, rc_rate_frame, rc_bmax); | ||
| 1616 | } | ||
| 1617 | } | ||
| 1618 | |||
| 1619 | #endif /* AVCODEC_AACCODER_NMR_H */ | ||
| 1620 |