FFmpeg
Loading...
Searching...
No Matches
aacpsy.c
Go to the documentation of this file.
1/*
2 * AAC encoder psychoacoustic model
3 * Copyright (C) 2008 Konstantin Shishkov
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 * @file
24 * AAC encoder psychoacoustic model
25 */
26
28#include "libavutil/ffmath.h"
29#include "libavutil/mem.h"
30
31#include "avcodec.h"
32#include "aac.h"
33#include "psymodel.h"
34
35/***********************************
36 * TODOs:
37 * try other bitrate controlling mechanism (maybe use ratecontrol.c?)
38 * control quality for quality-based output
39 **********************************/
40
41/**
42 * constants for 3GPP AAC psychoacoustic model
43 * @{
44 */
45#define PSY_3GPP_THR_SPREAD_HI 1.5f // spreading factor for low-to-hi threshold spreading (15 dB/Bark)
46#define PSY_3GPP_THR_SPREAD_LOW 3.0f // spreading factor for hi-to-low threshold spreading (30 dB/Bark)
47/* spreading factor for low-to-hi energy spreading, long block, > 22kbps/channel (20dB/Bark) */
48#define PSY_3GPP_EN_SPREAD_HI_L1 2.0f
49/* spreading factor for low-to-hi energy spreading, long block, <= 22kbps/channel (15dB/Bark) */
50#define PSY_3GPP_EN_SPREAD_HI_L2 1.5f
51/* spreading factor for low-to-hi energy spreading, short block (15 dB/Bark) */
52#define PSY_3GPP_EN_SPREAD_HI_S 1.5f
53/* spreading factor for hi-to-low energy spreading, long block (30dB/Bark) */
54#define PSY_3GPP_EN_SPREAD_LOW_L 3.0f
55/* spreading factor for hi-to-low energy spreading, short block (20dB/Bark) */
56#define PSY_3GPP_EN_SPREAD_LOW_S 2.0f
57
58#define PSY_3GPP_RPEMIN 0.01f
59#define PSY_3GPP_RPELEV 2.0f
60
61#define PSY_3GPP_C1 3.0f /* log2(8) */
62#define PSY_3GPP_C2 1.3219281f /* log2(2.5) */
63#define PSY_3GPP_C3 0.55935729f /* 1 - C2 / C1 */
64
65#define PSY_SNR_1DB 7.9432821e-1f /* -1dB */
66#define PSY_SNR_25DB 3.1622776e-3f /* -25dB */
67
68#define PSY_3GPP_SAVE_SLOPE_L -0.46666667f
69#define PSY_3GPP_SAVE_SLOPE_S -0.36363637f
70#define PSY_3GPP_SAVE_ADD_L -0.84285712f
71#define PSY_3GPP_SAVE_ADD_S -0.75f
72#define PSY_3GPP_SPEND_SLOPE_L 0.66666669f
73#define PSY_3GPP_SPEND_SLOPE_S 0.81818181f
74#define PSY_3GPP_SPEND_ADD_L -0.35f
75#define PSY_3GPP_SPEND_ADD_S -0.26111111f
76#define PSY_3GPP_CLIP_LO_L 0.2f
77#define PSY_3GPP_CLIP_LO_S 0.2f
78#define PSY_3GPP_CLIP_HI_L 0.95f
79#define PSY_3GPP_CLIP_HI_S 0.75f
80
81/* Floor on how close a coded band's mask may come to the band's own energy.
82 * The two rate-control families want different shapes, and measurably so:
83 * in VBR/ABR the mask IS the rate authority, so a mask that has risen to meet
84 * its band's energy tells the solver the band is free to destroy and it buys
85 * no bits for it - a broadband floor is right there. In CBR the budget is
86 * fixed and the mask only ranks bands against each other, so the same
87 * broadband floor just moves bits around and costs ~2% Zim on random content;
88 * restricted to the top end, where the mask degenerates to within 2 dB of band
89 * energy on every sample measured, it is a clear win. */
90#define PSY_THRFL_QUALITY 10.0f /* VBR/ABR depth, dB, all bands */
91#define PSY_THRFL_CBR 6.0f /* CBR depth, dB */
92#define PSY_THRFL_CBR_KNEE 8000.0f /* CBR: only above this frequency */
93
94/* Strength of the 3GPP bit-demand curve: its deviation from unity is
95 * amplified, since the trellis coder wants far stronger per-frame budget
96 * modulation than the reference encoder's gentle curve provides.
97 * The amplified factor goes negative in high-PE frames on a starved
98 * reservoir (15-30% of CBR frames). The desired PE is then <= 0 and the
99 * reduction raises every threshold as far as the min-SNR and hole rules
100 * allow, so those frames are shaped for constant SNR instead of by the
101 * mask. That regime is load-bearing: flooring the demand at frame_bits/8
102 * costs 3-5% Zimtohrli at 64 kbps stereo. */
103#define PSY_3GPP_DEMAND_SCALE 2.5f
104
105#define PSY_3GPP_AH_THR_LONG 0.5f
106#define PSY_3GPP_AH_THR_SHORT 0.63f
107
108#define PSY_PE_FORGET_SLOPE 511
109
110enum {
114};
115
116#define PSY_3GPP_BITS_TO_PE(bits) ((bits) * 1.18f)
117#define PSY_3GPP_PE_TO_BITS(bits) ((bits) / 1.18f)
118
119/* LAME psy model constants */
120#define PSY_LAME_FIR_LEN 21 ///< LAME psy model FIR order
121#define AAC_BLOCK_SIZE_LONG 1024 ///< long block size
122#define AAC_BLOCK_SIZE_SHORT 128 ///< short block size
123#define AAC_NUM_BLOCKS_SHORT 8 ///< number of blocks in a short sequence
124#define PSY_LAME_NUM_SUBBLOCKS 2 ///< Number of sub-blocks in each short block
125
126/* Pre-echo-aware attack detection: the LAME ratio test misses gentler attacks after a quiet
127 * gap, which then stay long and pre-echo. For an isolated onset (long for PSY_LAME_PE_GAP
128 * frames) whose pre-onset is below PSY_LAME_PE_QUIET of the frame peak, scale the threshold by
129 * PSY_LAME_PE_RED so it switches short; dense-transient content never qualifies. */
130#define PSY_LAME_PE_GAP 12 ///< min consecutive long frames before the relaxation applies
131#define PSY_LAME_PE_QUIET 0.4f ///< pre-onset must be below this fraction of the frame peak
132#define PSY_LAME_PE_RED 0.45f ///< attack-threshold multiplier for a qualifying isolated onset
133
134/* The novelty check must see at least one full period of a pulse train to
135 * recognize its pulses as repeats; 30 sub-blocks reaches down to ~23Hz. */
136#define PSY_LAME_HIST 32 ///< HP sub-block peak history depth
137#define PSY_LAME_NOV_BACK 30 ///< novelty look-back in sub-blocks
138
139/* HF-novelty veto: an attack candidate stays long when its first-difference
140 * envelope is both relatively and absolutely unremarkable, and pre-echo is
141 * masked by what precedes it. */
142#define PSY_LAME_HFN_REL 4.0f ///< max derivative rise over the recent envelope
143#define PSY_LAME_HFN_ABS 2000.0f ///< max absolute derivative peak
144#define PSY_LAME_HFN_PRE 8.0f ///< max candidate rise over the ~5ms pre-attack minimum
145
146/* Gap-onset detection against a decaying program-level peak-hold */
147#define PSY_LAME_GAP_DEPTH 6.0f ///< a gap is this far below the peak-hold
148#define PSY_LAME_GAP_BACK 24 ///< gap look-back in sub-blocks (<= PSY_LAME_HIST)
149#define PSY_LAME_GAP_LEVEL 0.4f ///< candidate must reach this fraction of the peak-hold
150#define PSY_LAME_GAP_FLOOR 4000.0f ///< and this absolute peak
151#define PSY_LAME_GAP_TOWER 4.0f ///< HP tower: rise over the whole look-back
152
153/* Level-homogeneous short-window grouping */
154#define PSY_LAME_GRP_RATIO 2.5f ///< max adjacent-window level ratio inside a group
155#define PSY_LAME_GRP_MAX 4 ///< max windows per group
156
157/**
158 * @}
159 */
160
161/**
162 * information for single band used by 3GPP TS26.403-inspired psychoacoustic model
163 */
164typedef struct AacPsyBand{
165 float energy; ///< band energy
166 float thr; ///< energy threshold
167 float thr_quiet; ///< threshold in quiet
168 float nz_lines; ///< number of non-zero spectral lines
169 float active_lines; ///< number of active spectral lines
170 float pe; ///< perceptual entropy
171 float pe_const; ///< constant part of the PE calculation
172 float norm_fac; ///< normalization factor for linearization
173 int avoid_holes; ///< hole avoidance flag
175
176/**
177 * single/pair channel context for psychoacoustic model
178 */
179typedef struct AacPsyChannel{
180 AacPsyBand band[128]; ///< bands information
181 AacPsyBand prev_band[128]; ///< bands information from the previous frame
182
183 float win_energy; ///< sliding average of channel energy
184 float iir_state[2]; ///< hi-pass IIR filter state
185 uint8_t next_grouping; ///< stored grouping scheme for the next frame (in case of 8 short window sequence)
186 enum WindowSequence next_window_seq; ///< window sequence to be used in the next frame
187 /* LAME psy model specific members */
188 float attack_threshold; ///< attack threshold for this channel
190 float next_win_level[AAC_NUM_BLOCKS_SHORT]; ///< lookahead short-window peak levels (grouping homogeneity)
191 float dif_env_hist[PSY_LAME_HIST]; ///< rolling first-difference sub-block peak envelope (HF novelty)
192 float hp_env_hist[PSY_LAME_HIST]; ///< rolling HP sub-block peak envelope
193 float raw_env_hist[PSY_LAME_HIST]; ///< rolling broadband sub-block peak envelope
194 float gap_wall; ///< decaying broadband peak-hold (gap-onset reference)
195 float gap_wall_hp; ///< decaying HP peak-hold (gap-onset reference)
196 int prev_attack; ///< attack value for the last short block in the previous sequence
197 int next_attack0_zero; ///< whether attack[0] of the next frame is zero
198 int frames_since_short; ///< consecutive long frames (pre-echo-aware isolated-onset gate)
199 float prev_frame_energy; ///< previous frame's full-band lookahead energy (attack veto)
200 int64_t win_count; ///< window() calls so far (frame counter for pair sync)
201 int64_t last_att; ///< win_count value of this channel's last own attack
202
203 /* rate-loop re-analysis rewind state, see psy_3gpp_analyze() */
204 int64_t rc_frame_num; ///< frame this channel last saved rewind state for
205 AacPsyBand rc_prev_band[128]; ///< prev_band as it was entering the frame
207
208/**
209 * psychoacoustic model frame type-dependent coefficients
210 */
211typedef struct AacPsyCoeffs{
212 float ath; ///< absolute threshold of hearing per bands
213 float barks; ///< Bark value for each spectral band in long frame
214 float spread_low[2]; ///< spreading factor for low-to-high threshold spreading in long frame
215 float spread_hi [2]; ///< spreading factor for high-to-low threshold spreading in long frame
216 float min_snr; ///< minimal SNR
218
219/**
220 * 3GPP TS26.403-inspired psychoacoustic model specific data
221 */
222typedef struct AacPsyContext{
223 int chan_bitrate; ///< bitrate per channel
224 int frame_bits; ///< average bits per frame
225 int fill_level; ///< bit reservoir fill level
226 struct {
227 float min; ///< minimum allowed PE for bit factor calculation
228 float max; ///< maximum allowed PE for bit factor calculation
229 float previous; ///< allowed PE of the previous frame
230 float correction; ///< PE correction factor
231 } pe;
234 float global_quality; ///< normalized global quality taken from avctx
235
236 /* rate-loop re-analysis rewind state, see psy_3gpp_analyze() */
237 int64_t rc_frame_num; ///< frame the rewind state was saved for
238 int rc_first_ch; ///< first channel analyzed in that frame
242
243/**
244 * LAME psy model preset struct
245 */
246typedef struct PsyLamePreset {
247 int quality; ///< Quality to map the rest of the values to.
248 /* This is overloaded to be both kbps per channel in ABR mode, and
249 * requested quality in constant quality mode.
250 */
251 float st_lrm; ///< short threshold for L, R, and M channels
253
254/**
255 * LAME psy model preset table for ABR
256 */
257static const PsyLamePreset psy_abr_map[] = {
258/* TODO: Tuning. These were taken from LAME. */
259/* kbps/ch st_lrm */
260 { 8, 7.60},
261 { 16, 7.60},
262 { 24, 7.60},
263 { 32, 7.60},
264 { 40, 7.60},
265 { 48, 7.60},
266 { 56, 7.60},
267 { 64, 7.40},
268 { 80, 7.00},
269 { 96, 6.60},
270 {112, 6.20},
271 {128, 6.20},
272 {160, 6.20}
273};
274
275/**
276* LAME psy model preset table for constant quality
277*/
278static const PsyLamePreset psy_vbr_map[] = {
279/* vbr_q st_lrm */
280 { 0, 4.20},
281 { 1, 4.20},
282 { 2, 4.20},
283 { 3, 4.20},
284 { 4, 4.20},
285 { 5, 4.20},
286 { 6, 4.20},
287 { 7, 4.20},
288 { 8, 4.20},
289 { 9, 4.20},
290 {10, 4.20}
291};
292
293/**
294 * LAME psy model FIR coefficient table
295 */
296static const float psy_fir_coeffs[] = {
297 -8.65163e-18 * 2, -0.00851586 * 2, -6.74764e-18 * 2, 0.0209036 * 2,
298 -3.36639e-17 * 2, -0.0438162 * 2, -1.54175e-17 * 2, 0.0931738 * 2,
299 -5.52212e-17 * 2, -0.313819 * 2
300};
301
302/**
303 * Calculate the ABR attack threshold from the above LAME psymodel table.
304 */
306{
307 /* Assume max bitrate to start with */
308 int lower_range = 12, upper_range = 12;
309 int lower_range_kbps = psy_abr_map[12].quality;
310 int upper_range_kbps = psy_abr_map[12].quality;
311 int i;
312
313 /* Determine which bitrates the value specified falls between.
314 * If the loop ends without breaking our above assumption of 320kbps was correct.
315 */
316 for (i = 1; i < 13; i++) {
318 upper_range = i;
319 upper_range_kbps = psy_abr_map[i ].quality;
320 lower_range = i - 1;
321 lower_range_kbps = psy_abr_map[i - 1].quality;
322 break; /* Upper range found */
323 }
324 }
325
326 /* Determine which range the value specified is closer to */
327 if ((upper_range_kbps - bitrate) > (bitrate - lower_range_kbps))
328 return psy_abr_map[lower_range].st_lrm;
329 return psy_abr_map[upper_range].st_lrm;
330}
331
332/**
333 * LAME psy model specific initialization
334 */
336{
337 int i, j;
338
339 for (i = 0; i < avctx->ch_layout.nb_channels; i++) {
340 AacPsyChannel *pch = &ctx->ch[i];
341
342 if ((avctx->flags & AV_CODEC_FLAG_QSCALE) || fctx->unbounded_pe)
343 /* quality-target coders (VBR and ABR) switch windows for quality,
344 * not rate: use the quality attack map regardless of bit_rate */
345 pch->attack_threshold = psy_vbr_map[av_clip(avctx->global_quality / FF_QP2LAMBDA, 0, 10)].st_lrm;
346 else
348
349 for (j = 0; j < AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS; j++)
350 pch->prev_energy_subshort[j] = 10.0f;
351 for (j = 0; j < PSY_LAME_HIST; j++)
352 pch->hp_env_hist[j] = pch->raw_env_hist[j] = pch->dif_env_hist[j] = 10.0f;
353 pch->gap_wall = pch->gap_wall_hp = 0.0f;
354 }
355}
356
357/**
358 * Calculate Bark value for given line.
359 */
360static av_cold float calc_bark(float f)
361{
362 return 13.3f * atanf(0.00076f * f) + 3.5f * atanf((f / 7500.0f) * (f / 7500.0f));
363}
364
365#define ATH_ADD 4
366/**
367 * Calculate ATH value for given frequency.
368 * Borrowed from Lame.
369 */
370static av_cold float ath(float f, float add)
371{
372 f /= 1000.0f;
373 return 3.64 * pow(f, -0.8)
374 - 6.8 * exp(-0.6 * (f - 3.4) * (f - 3.4))
375 + 6.0 * exp(-0.15 * (f - 8.7) * (f - 8.7))
376 + (0.6 + 0.04 * add) * 0.001 * f * f * f * f;
377}
378
380 AacPsyContext *pctx;
381 float bark;
382 int i, j, g, start;
383 float prev, minscale, minath, minsnr, pe_min;
384 int chan_bitrate = ctx->avctx->bit_rate / ((ctx->avctx->flags & AV_CODEC_FLAG_QSCALE) ? 2.0f : ctx->avctx->ch_layout.nb_channels);
385
386 const int bandwidth = ctx->cutoff ? ctx->cutoff : AAC_CUTOFF(ctx->avctx);
387 const float num_bark = calc_bark((float)bandwidth);
388
389 if (bandwidth <= 0)
390 return AVERROR(EINVAL);
391
392 ctx->model_priv_data = av_mallocz(sizeof(AacPsyContext));
393 if (!ctx->model_priv_data)
394 return AVERROR(ENOMEM);
395 pctx = ctx->model_priv_data;
396 pctx->global_quality = (ctx->avctx->global_quality ? ctx->avctx->global_quality : 120) * 0.01f;
397
398 if (ctx->avctx->flags & AV_CODEC_FLAG_QSCALE) {
399 /* Use the target average bitrate to compute spread parameters */
400 chan_bitrate = (int)(chan_bitrate / 120.0 * (ctx->avctx->global_quality ? ctx->avctx->global_quality : 120));
401 }
402
403 pctx->chan_bitrate = chan_bitrate;
404 pctx->frame_bits = FFMIN(2560, chan_bitrate * AAC_BLOCK_SIZE_LONG / ctx->avctx->sample_rate);
405 pctx->pe.min = 8.0f * AAC_BLOCK_SIZE_LONG * bandwidth / (ctx->avctx->sample_rate * 2.0f);
406 pctx->pe.max = 12.0f * AAC_BLOCK_SIZE_LONG * bandwidth / (ctx->avctx->sample_rate * 2.0f);
407 ctx->bitres.size = 6144 - pctx->frame_bits;
408 ctx->bitres.size -= ctx->bitres.size % 8;
409 pctx->fill_level = ctx->bitres.size;
410 minath = ath(3410 - 0.733 * ATH_ADD, ATH_ADD);
411 for (j = 0; j < 2; j++) {
412 AacPsyCoeffs *coeffs = pctx->psy_coef[j];
413 const uint8_t *band_sizes = ctx->bands[j];
414 float line_to_frequency = ctx->avctx->sample_rate / (j ? 256.f : 2048.0f);
415 float avg_chan_bits = chan_bitrate * (j ? 128.0f : 1024.0f) / ctx->avctx->sample_rate;
416 /* reference encoder uses 2.4% here instead of 60% like the spec says */
417 float bark_pe = 0.024f * PSY_3GPP_BITS_TO_PE(avg_chan_bits) / num_bark;
418 float en_spread_low = j ? PSY_3GPP_EN_SPREAD_LOW_S : PSY_3GPP_EN_SPREAD_LOW_L;
419 /* High energy spreading for long blocks <= 22kbps/channel and short blocks are the same. */
420 float en_spread_hi = (j || (chan_bitrate <= 22.0f)) ? PSY_3GPP_EN_SPREAD_HI_S : PSY_3GPP_EN_SPREAD_HI_L1;
421
422 i = 0;
423 prev = 0.0;
424 for (g = 0; g < ctx->num_bands[j]; g++) {
425 i += band_sizes[g];
426 bark = calc_bark((i-1) * line_to_frequency);
427 coeffs[g].barks = (bark + prev) / 2.0;
428 prev = bark;
429 }
430 for (g = 0; g < ctx->num_bands[j] - 1; g++) {
431 AacPsyCoeffs *coeff = &coeffs[g];
432 float bark_width = coeffs[g+1].barks - coeffs->barks;
433 coeff->spread_low[0] = ff_exp10(-bark_width * PSY_3GPP_THR_SPREAD_LOW);
434 coeff->spread_hi [0] = ff_exp10(-bark_width * PSY_3GPP_THR_SPREAD_HI);
435 coeff->spread_low[1] = ff_exp10(-bark_width * en_spread_low);
436 coeff->spread_hi [1] = ff_exp10(-bark_width * en_spread_hi);
437 pe_min = bark_pe * bark_width;
438 minsnr = exp2(pe_min / band_sizes[g]) - 1.5f;
439 coeff->min_snr = av_clipf(1.0f / minsnr, PSY_SNR_25DB, PSY_SNR_1DB);
440 }
441 start = 0;
442 for (g = 0; g < ctx->num_bands[j]; g++) {
443 minscale = ath(start * line_to_frequency, ATH_ADD);
444 for (i = 1; i < band_sizes[g]; i++)
445 minscale = FFMIN(minscale, ath((start + i) * line_to_frequency, ATH_ADD));
446 coeffs[g].ath = minscale - minath;
447 start += band_sizes[g];
448 }
449 }
450
451 pctx->ch = av_calloc(ctx->avctx->ch_layout.nb_channels, sizeof(*pctx->ch));
452 if (!pctx->ch) {
453 av_freep(&ctx->model_priv_data);
454 return AVERROR(ENOMEM);
455 }
456
457 pctx->rc_frame_num = -1;
458 for (i = 0; i < ctx->avctx->ch_layout.nb_channels; i++)
459 pctx->ch[i].rc_frame_num = -1;
460
461 lame_window_init(ctx, pctx, ctx->avctx);
462
463 return 0;
464}
465
466/**
467 * IIR filter used in block switching decision
468 */
469static float iir_filter(int in, float state[2])
470{
471 float ret;
472
473 ret = 0.7548f * (in - state[0]) + 0.5095f * state[1];
474 state[0] = in;
475 state[1] = ret;
476 return ret;
477}
478
479/**
480 * window grouping information stored as bits (0 - new group, 1 - group continues)
481 */
482static const uint8_t window_grouping[9] = {
483 0xB6, 0x6C, 0xD8, 0xB2, 0x66, 0xC6, 0x96, 0x36, 0x36
484};
485
486/**
487 * Tell encoder which window types to use.
488 * @see 3GPP TS26.403 5.4.1 "Blockswitching"
489 */
491 const int16_t *audio,
492 const int16_t *la,
493 int channel, int prev_type)
494{
495 int i, j;
496 int br = ((AacPsyContext*)ctx->model_priv_data)->chan_bitrate;
497 int attack_ratio = br <= 16000 ? 18 : 10;
498 AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
499 AacPsyChannel *pch = &pctx->ch[channel];
500 uint8_t grouping = 0;
501 int next_type = pch->next_window_seq;
502 FFPsyWindowInfo wi = { { 0 } };
503
504 if (la) {
505 float s[8], v;
506 int switch_to_eight = 0;
507 float sum = 0.0, sum2 = 0.0;
508 int attack_n = 0;
509 int stay_short = 0;
510 for (i = 0; i < 8; i++) {
511 for (j = 0; j < 128; j++) {
512 v = iir_filter(la[i*128+j], pch->iir_state);
513 sum += v*v;
514 }
515 s[i] = sum;
516 sum2 += sum;
517 }
518 for (i = 0; i < 8; i++) {
519 if (s[i] > pch->win_energy * attack_ratio) {
520 attack_n = i + 1;
521 switch_to_eight = 1;
522 break;
523 }
524 }
525 pch->win_energy = pch->win_energy*7/8 + sum2/64;
526
527 wi.window_type[1] = prev_type;
528 switch (prev_type) {
530 wi.window_type[0] = switch_to_eight ? LONG_START_SEQUENCE : ONLY_LONG_SEQUENCE;
531 next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : ONLY_LONG_SEQUENCE;
532 break;
535 grouping = pch->next_grouping;
536 next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : LONG_STOP_SEQUENCE;
537 break;
539 wi.window_type[0] = switch_to_eight ? LONG_START_SEQUENCE : ONLY_LONG_SEQUENCE;
540 next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : ONLY_LONG_SEQUENCE;
541 break;
543 stay_short = next_type == EIGHT_SHORT_SEQUENCE || switch_to_eight;
545 grouping = next_type == EIGHT_SHORT_SEQUENCE ? pch->next_grouping : 0;
546 next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : LONG_STOP_SEQUENCE;
547 break;
548 }
549
550 pch->next_grouping = window_grouping[attack_n];
551 pch->next_window_seq = next_type;
552 } else {
553 for (i = 0; i < 3; i++)
554 wi.window_type[i] = prev_type;
555 grouping = (prev_type == EIGHT_SHORT_SEQUENCE) ? window_grouping[0] : 0;
556 }
557
558 wi.window_shape = 1;
559 if (wi.window_type[0] != EIGHT_SHORT_SEQUENCE) {
560 wi.num_windows = 1;
561 wi.grouping[0] = 1;
562 } else {
563 int lastgrp = 0;
564 wi.num_windows = 8;
565 for (i = 0; i < 8; i++) {
566 if (!((grouping >> i) & 1))
567 lastgrp = i;
568 wi.grouping[lastgrp]++;
569 }
570 }
571
572 return wi;
573}
574
575/* 5.6.1.2 "Calculation of Bit Demand" */
576static int calc_bit_demand(AacPsyContext *ctx, float pe, int bits, int size,
577 int short_window)
578{
579 const float bitsave_slope = short_window ? PSY_3GPP_SAVE_SLOPE_S : PSY_3GPP_SAVE_SLOPE_L;
580 const float bitsave_add = short_window ? PSY_3GPP_SAVE_ADD_S : PSY_3GPP_SAVE_ADD_L;
581 const float bitspend_slope = short_window ? PSY_3GPP_SPEND_SLOPE_S : PSY_3GPP_SPEND_SLOPE_L;
582 const float bitspend_add = short_window ? PSY_3GPP_SPEND_ADD_S : PSY_3GPP_SPEND_ADD_L;
583 const float clip_low = short_window ? PSY_3GPP_CLIP_LO_S : PSY_3GPP_CLIP_LO_L;
584 const float clip_high = short_window ? PSY_3GPP_CLIP_HI_S : PSY_3GPP_CLIP_HI_L;
585 float clipped_pe, bit_save, bit_spend, bit_factor, fill_level, forgetful_min_pe;
586
587 ctx->fill_level += ctx->frame_bits - bits;
588 ctx->fill_level = av_clip(ctx->fill_level, 0, size);
589 fill_level = av_clipf((float)ctx->fill_level / size, clip_low, clip_high);
590 clipped_pe = av_clipf(pe, ctx->pe.min, ctx->pe.max);
591 bit_save = (fill_level + bitsave_add) * bitsave_slope;
592 assert(bit_save <= 0.3f && bit_save >= -0.05000001f);
593 bit_spend = (fill_level + bitspend_add) * bitspend_slope;
594 assert(bit_spend <= 0.5f && bit_spend >= -0.1f);
595 /* The bit factor graph in the spec is obviously incorrect.
596 * bit_spend + ((bit_spend - bit_spend))...
597 * The reference encoder subtracts everything from 1, but also seems incorrect.
598 * 1 - bit_save + ((bit_spend + bit_save))...
599 * Hopefully below is correct.
600 */
601 bit_factor = 1.0f - bit_save + ((bit_spend - bit_save) / (ctx->pe.max - ctx->pe.min)) * (clipped_pe - ctx->pe.min);
602 bit_factor = 1.0f + (bit_factor - 1.0f) * PSY_3GPP_DEMAND_SCALE;
603 /* NOTE: The reference encoder attempts to center pe max/min around the current pe.
604 * Here we do that by slowly forgetting pe.min when pe stays in a range that makes
605 * it unlikely (ie: above the mean)
606 */
607 ctx->pe.max = FFMAX(pe, ctx->pe.max);
608 forgetful_min_pe = ((ctx->pe.min * PSY_PE_FORGET_SLOPE)
609 + FFMAX(ctx->pe.min, pe * (pe / ctx->pe.max))) / (PSY_PE_FORGET_SLOPE + 1);
610 ctx->pe.min = FFMIN(pe, forgetful_min_pe);
611
612 /* NOTE: allocate a minimum of 1/8th average frame bits, to avoid
613 * reservoir starvation from producing zero-bit frames
614 */
615 return FFMIN(
616 ctx->frame_bits * bit_factor,
617 FFMAX(ctx->frame_bits + size - bits, ctx->frame_bits / 8));
618}
619
620static float calc_pe_3gpp(AacPsyBand *band)
621{
622 float pe, a;
623
624 band->pe = 0.0f;
625 band->pe_const = 0.0f;
626 band->active_lines = 0.0f;
627 if (band->energy > band->thr) {
628 a = log2f(band->energy);
629 pe = a - log2f(band->thr);
630 band->active_lines = band->nz_lines;
631 if (pe < PSY_3GPP_C1) {
632 pe = pe * PSY_3GPP_C3 + PSY_3GPP_C2;
634 band->active_lines *= PSY_3GPP_C3;
635 }
636 band->pe = pe * band->nz_lines;
637 band->pe_const = a * band->nz_lines;
638 }
639
640 return band->pe;
641}
642
643static float calc_reduction_3gpp(float a, float desired_pe, float pe,
644 float active_lines)
645{
646 float thr_avg, reduction;
647
648 if(active_lines == 0.0)
649 return 0;
650
651 thr_avg = exp2f((a - pe) / (4.0f * active_lines));
652 reduction = exp2f((a - desired_pe) / (4.0f * active_lines)) - thr_avg;
653
654 return FFMAX(reduction, 0.0f);
655}
656
657static float calc_reduced_thr_3gpp(AacPsyBand *band, float min_snr,
658 float reduction)
659{
660 float thr = band->thr;
661
662 if (band->energy > thr) {
663 thr = sqrtf(thr);
664 thr = sqrtf(thr) + reduction;
665 thr *= thr;
666 thr *= thr;
667
668 /* This deviates from the 3GPP spec to match the reference encoder.
669 * It performs min(thr_reduced, max(thr, energy/min_snr)) only for bands
670 * that have hole avoidance on (active or inactive). It always reduces the
671 * threshold of bands with hole avoidance off.
672 */
673 if (thr > band->energy * min_snr && band->avoid_holes != PSY_3GPP_AH_NONE) {
674 thr = FFMAX(band->thr, band->energy * min_snr);
676 }
677 }
678
679 return thr;
680}
681
682static void calc_thr_3gpp(const FFPsyWindowInfo *wi, const int num_bands, AacPsyChannel *pch,
683 const uint8_t *band_sizes, const float *coefs, const int cutoff)
684{
685 int i, w, g;
686 int start = 0, wstart = 0;
687 for (w = 0; w < wi->num_windows*16; w += 16) {
688 wstart = 0;
689 for (g = 0; g < num_bands; g++) {
690 AacPsyBand *band = &pch->band[w+g];
691
692 float form_factor = 0.0f;
693 float Temp;
694 band->energy = 0.0f;
695 if (wstart < cutoff) {
696 for (i = 0; i < band_sizes[g]; i++) {
697 band->energy += coefs[start+i] * coefs[start+i];
698 form_factor += sqrtf(fabs(coefs[start+i]));
699 }
700 }
701 Temp = band->energy > 0 ? sqrtf((float)band_sizes[g] / band->energy) : 0;
702 band->thr = band->energy * 0.001258925f;
703 band->nz_lines = form_factor * sqrtf(Temp);
704
705 start += band_sizes[g];
706 wstart += band_sizes[g];
707 }
708 }
709}
710
711static void psy_hp_filter(const float *firbuf, float *hpfsmpl, const float *psy_fir_coeffs)
712{
713 int i, j;
714 for (i = 0; i < AAC_BLOCK_SIZE_LONG; i++) {
715 float sum1, sum2;
716 sum1 = firbuf[i + (PSY_LAME_FIR_LEN - 1) / 2];
717 sum2 = 0.0;
718 for (j = 0; j < ((PSY_LAME_FIR_LEN - 1) / 2) - 1; j += 2) {
719 sum1 += psy_fir_coeffs[j] * (firbuf[i + j] + firbuf[i + PSY_LAME_FIR_LEN - j]);
720 sum2 += psy_fir_coeffs[j + 1] * (firbuf[i + j + 1] + firbuf[i + PSY_LAME_FIR_LEN - j - 1]);
721 }
722 /* NOTE: The LAME psymodel expects it's input in the range -32768 to 32768.
723 * Tuning this for normalized floats would be difficult. */
724 hpfsmpl[i] = (sum1 + sum2) * 32768.0f;
725 }
726}
727
728/**
729 * Calculate band thresholds as suggested in 3GPP TS26.403
730 */
732 const float *coefs, const FFPsyWindowInfo *wi)
733{
734 AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
735 AacPsyChannel *pch = &pctx->ch[channel];
736 int i, w, g;
737 float desired_bits, desired_pe, delta_pe, reduction= NAN, spread_en[128] = {0};
738 float a = 0.0f, active_lines = 0.0f, norm_fac = 0.0f;
739 float pe = pctx->chan_bitrate > 32000 ? 0.0f : FFMAX(50.0f, 100.0f - pctx->chan_bitrate * 100.0f / 32000.0f);
740 const int num_bands = ctx->num_bands[wi->num_windows == 8];
741 const uint8_t *band_sizes = ctx->bands[wi->num_windows == 8];
742 uint8_t s2l[16] = {0};
743 int start_after_long = wi->num_windows == 8 &&
745 { /* short->long grid band map for cross-transition pre-echo control */
746 if (start_after_long) {
747 const uint8_t *ls = ctx->bands[0];
748 const int ln = ctx->num_bands[0];
749 const uint8_t *ss = ctx->bands[1];
750 int lacc = 0, sacc = 0, gl = 0;
751 for (int gs = 0; gs < num_bands && gs < 16; gs++) {
752 int center8 = (sacc + ss[gs] / 2) * 8;
753 while (gl < ln - 1 && lacc + ls[gl] <= center8) { lacc += ls[gl]; gl++; }
754 s2l[gs] = gl;
755 sacc += ss[gs];
756 }
757 }
758 }
759 AacPsyCoeffs *coeffs = pctx->psy_coef[wi->num_windows == 8];
760 const float avoid_hole_thr = wi->num_windows == 8 ? PSY_3GPP_AH_THR_SHORT : PSY_3GPP_AH_THR_LONG;
761 const int bandwidth = ctx->cutoff ? ctx->cutoff : AAC_CUTOFF(ctx->avctx);
762 const int cutoff = bandwidth * 2048 / wi->num_windows / ctx->avctx->sample_rate;
763
764 //calculate energies, initial thresholds and related values - 5.4.2 "Threshold Calculation"
765 calc_thr_3gpp(wi, num_bands, pch, band_sizes, coefs, cutoff);
766
767 //modify thresholds and energies - spread, threshold in quiet, pre-echo control
768 for (w = 0; w < wi->num_windows*16; w += 16) {
769 AacPsyBand *bands = &pch->band[w];
770
771 /* 5.4.2.3 "Spreading" & 5.4.3 "Spread Energy Calculation" */
772 spread_en[0] = bands[0].energy;
773 for (g = 1; g < num_bands; g++) {
774 bands[g].thr = FFMAX(bands[g].thr, bands[g-1].thr * coeffs[g].spread_hi[0]);
775 spread_en[w+g] = FFMAX(bands[g].energy, spread_en[w+g-1] * coeffs[g].spread_hi[1]);
776 }
777 for (g = num_bands - 2; g >= 0; g--) {
778 bands[g].thr = FFMAX(bands[g].thr, bands[g+1].thr * coeffs[g].spread_low[0]);
779 spread_en[w+g] = FFMAX(spread_en[w+g], spread_en[w+g+1] * coeffs[g].spread_low[1]);
780 }
781 //5.4.2.4 "Threshold in quiet"
782 for (g = 0; g < num_bands; g++) {
783 AacPsyBand *band = &bands[g];
784
785 band->thr_quiet = band->thr = FFMAX(band->thr, coeffs[g].ath);
786 //5.4.2.5 "Pre-echo control"
787 if (!(wi->window_type[0] == LONG_STOP_SEQUENCE || (!w && wi->window_type[1] == LONG_START_SEQUENCE)))
788 band->thr = FFMAX(PSY_3GPP_RPEMIN*band->thr, FFMIN(band->thr,
790 else if (!w && start_after_long)
791 /* w0 after a START frame: grid-mapped, scaled continuity
792 * clamp instead of the spec's skip (cannot bind on noise
793 * content - see memory - but correct for tonal) */
794 band->thr = FFMAX(PSY_3GPP_RPEMIN*band->thr, FFMIN(band->thr,
795 PSY_3GPP_RPELEV*pch->prev_band[s2l[FFMIN(g,15)]].thr / 8.0f));
796
797 /* 5.6.1.3.1 "Preparatory steps of the perceptual entropy calculation" */
798 pe += calc_pe_3gpp(band);
799 a += band->pe_const;
800 active_lines += band->active_lines;
801
802 /* 5.6.1.3.3 "Selection of the bands for avoidance of holes" */
803 if (spread_en[w+g] * avoid_hole_thr > band->energy || coeffs[g].min_snr > 1.0f)
805 else
807 }
808 }
809
810 /* 5.6.1.3.2 "Calculation of the desired perceptual entropy" */
811 ctx->ch[channel].entropy = pe;
812 if (ctx->unbounded_pe) {
813 /* quality-target coder: run the PE reduction at a FIXED reference
814 * quality so thresholds keep their perceptual shaping but stay
815 * independent of the user's -q:a (the coder's own noise-to-mask
816 * target is the sole quality authority) */
817 desired_pe = pe * 120.0f / (2 * 2.5f * 120.0f);
818 desired_bits = FFMIN(2560, PSY_3GPP_PE_TO_BITS(desired_pe));
819 desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits);
820 pctx->pe.max = FFMAX(pe, pctx->pe.max);
821 pctx->pe.min = FFMIN(pe, pctx->pe.min);
822 } else if (ctx->avctx->flags & AV_CODEC_FLAG_QSCALE) {
823 /* (2.5 * 120) achieves almost transparent rate, and we want to give
824 * ample room downwards, so we make that equivalent to QSCALE=2.4
825 */
826 desired_pe = pe * (ctx->avctx->global_quality ? ctx->avctx->global_quality : 120) / (2 * 2.5f * 120.0f);
827 desired_bits = FFMIN(2560, PSY_3GPP_PE_TO_BITS(desired_pe));
828 desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits); // reflect clipping
829
830 /* PE slope smoothing */
831 if (ctx->bitres.bits > 0) {
832 desired_bits = FFMIN(2560, PSY_3GPP_PE_TO_BITS(desired_pe));
833 desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits); // reflect clipping
834 }
835
836 pctx->pe.max = FFMAX(pe, pctx->pe.max);
837 pctx->pe.min = FFMIN(pe, pctx->pe.min);
838 } else {
839 desired_bits = calc_bit_demand(pctx, pe, ctx->bitres.bits, ctx->bitres.size, wi->num_windows == 8);
840 desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits);
841
842 /* NOTE: PE correction is kept simple. During initial testing it had very
843 * little effect on the final bitrate. Probably a good idea to come
844 * back and do more testing later.
845 */
846 if (ctx->bitres.bits > 0) {
847 /* symmetric in the log domain: a negative previous demand (see
848 * PSY_3GPP_DEMAND_SCALE) sits on the lower bound, and the
849 * asymmetric 0.85 there costs ~2% Zimtohrli at 64 kbps */
850 desired_pe *= av_clipf(pctx->pe.previous / PSY_3GPP_BITS_TO_PE(ctx->bitres.bits),
851 1.0f / 1.15f, 1.15f);
852 }
853 }
854 pctx->pe.previous = PSY_3GPP_BITS_TO_PE(desired_bits);
855 ctx->bitres.alloc = desired_bits;
856
857 if (desired_pe < pe) {
858 /* 5.6.1.3.4 "First Estimation of the reduction value" */
859 for (w = 0; w < wi->num_windows*16; w += 16) {
860 reduction = calc_reduction_3gpp(a, desired_pe, pe, active_lines);
861 pe = 0.0f;
862 a = 0.0f;
863 active_lines = 0.0f;
864 for (g = 0; g < num_bands; g++) {
865 AacPsyBand *band = &pch->band[w+g];
866
867 band->thr = calc_reduced_thr_3gpp(band, coeffs[g].min_snr, reduction);
868 /* recalculate PE */
869 pe += calc_pe_3gpp(band);
870 a += band->pe_const;
871 active_lines += band->active_lines;
872 }
873 }
874
875 /* 5.6.1.3.5 "Second Estimation of the reduction value" */
876 for (i = 0; i < 2; i++) {
877 float pe_no_ah = 0.0f, desired_pe_no_ah;
878 active_lines = a = 0.0f;
879 for (w = 0; w < wi->num_windows*16; w += 16) {
880 for (g = 0; g < num_bands; g++) {
881 AacPsyBand *band = &pch->band[w+g];
882
883 if (band->avoid_holes != PSY_3GPP_AH_ACTIVE) {
884 pe_no_ah += band->pe;
885 a += band->pe_const;
886 active_lines += band->active_lines;
887 }
888 }
889 }
890 desired_pe_no_ah = FFMAX(desired_pe - (pe - pe_no_ah), 0.0f);
891 if (active_lines > 0.0f)
892 reduction = calc_reduction_3gpp(a, desired_pe_no_ah, pe_no_ah, active_lines);
893
894 pe = 0.0f;
895 for (w = 0; w < wi->num_windows*16; w += 16) {
896 for (g = 0; g < num_bands; g++) {
897 AacPsyBand *band = &pch->band[w+g];
898
899 if (active_lines > 0.0f)
900 band->thr = calc_reduced_thr_3gpp(band, coeffs[g].min_snr, reduction);
901 pe += calc_pe_3gpp(band);
902 if (band->thr > 0.0f)
903 band->norm_fac = band->active_lines / band->thr;
904 else
905 band->norm_fac = 0.0f;
906 norm_fac += band->norm_fac;
907 }
908 }
909 delta_pe = desired_pe - pe;
910 if (fabs(delta_pe) > 0.05f * desired_pe)
911 break;
912 }
913
914 if (pe < 1.15f * desired_pe) {
915 /* 6.6.1.3.6 "Final threshold modification by linearization" */
916 norm_fac = norm_fac ? 1.0f / norm_fac : 0;
917 for (w = 0; w < wi->num_windows*16; w += 16) {
918 for (g = 0; g < num_bands; g++) {
919 AacPsyBand *band = &pch->band[w+g];
920
921 if (band->active_lines > 0.5f) {
922 float delta_sfb_pe = band->norm_fac * norm_fac * delta_pe;
923 float thr = band->thr;
924
925 thr *= exp2f(delta_sfb_pe / band->active_lines);
926 if (thr > coeffs[g].min_snr * band->energy && band->avoid_holes == PSY_3GPP_AH_INACTIVE)
927 thr = FFMAX(band->thr, coeffs[g].min_snr * band->energy);
928 band->thr = thr;
929 }
930 }
931 }
932 } else {
933 /* 5.6.1.3.7 "Further perceptual entropy reduction" */
934 g = num_bands;
935 while (pe > desired_pe && g--) {
936 for (w = 0; w < wi->num_windows*16; w+= 16) {
937 AacPsyBand *band = &pch->band[w+g];
938 if (band->avoid_holes != PSY_3GPP_AH_NONE && coeffs[g].min_snr < PSY_SNR_1DB) {
939 coeffs[g].min_snr = PSY_SNR_1DB;
940 band->thr = band->energy * PSY_SNR_1DB;
941 pe += band->active_lines * 1.5f - band->pe;
942 }
943 }
944 }
945 /* TODO: allow more holes (unused without mid/side) */
946 }
947 }
948
949 /* Signal-relative mask ceiling. 5.6.1.3.3 exempts bands that are quiet
950 * relative to the spread energy from the min-SNR floor ("holes allowed
951 * here"), so on spectrally lopsided programme their mask is free to rise
952 * until it meets their own energy - the model then calls a band that
953 * carries real texture inaudible, and every consumer of the mask agrees:
954 * the allocator buys it nothing and the quality-target solver sees a mask
955 * it cannot fail. A band we still choose to code must never be allowed
956 * noise within PSY_THRFL_* dB of its own energy, whatever the hole logic said. */
957 {
958 int qmode = ctx->unbounded_pe || (ctx->avctx->flags & AV_CODEC_FLAG_QSCALE);
959 float lim = qmode ? PSY_THRFL_QUALITY : PSY_THRFL_CBR;
960 float knee = qmode ? 0.0f : PSY_THRFL_CBR_KNEE;
961 float lo = ff_exp10f(-lim / 10.0f);
962 float l2f = ctx->avctx->sample_rate / 2.0f /
963 (wi->num_windows == 1 ? 1024.0f : 128.0f);
964 for (w = 0; w < wi->num_windows*16; w += 16) {
965 int start = 0;
966 for (g = 0; g < num_bands; g++) {
967 AacPsyBand *band = &pch->band[w+g];
968 if (start * l2f >= knee)
969 band->thr = FFMIN(band->thr, band->energy * lo);
970 start += band_sizes[g];
971 }
972 }
973 }
974
975 for (w = 0; w < wi->num_windows*16; w += 16) {
976 for (g = 0; g < num_bands; g++) {
977 AacPsyBand *band = &pch->band[w+g];
978 FFPsyBand *psy_band = &ctx->ch[channel].psy_bands[w+g];
979
980 psy_band->threshold = band->thr;
981 psy_band->energy = band->energy;
982 psy_band->spread = band->active_lines * 2.0f / band_sizes[g];
983 psy_band->bits = PSY_3GPP_PE_TO_BITS(band->pe);
984 }
985 }
986
987 memcpy(pch->prev_band, pch->band, sizeof(pch->band));
988}
989
991 const float **coeffs, const FFPsyWindowInfo *wi)
992{
993 int ch;
995 AacPsyContext *pctx = ctx->model_priv_data;
996
997 /* The encoder's rate-control loop may re-run the analysis for the same
998 * frame; carried state (bit reservoir, PE history, previous-frame
999 * thresholds) must advance exactly once per frame, so save it on the
1000 * frame's first run and rewind on re-runs. */
1001 if (ctx->avctx->frame_num != pctx->rc_frame_num) {
1002 pctx->rc_frame_num = ctx->avctx->frame_num;
1003 pctx->rc_first_ch = channel;
1004 pctx->rc_fill_level = pctx->fill_level;
1005 pctx->rc_pe_min = pctx->pe.min;
1006 pctx->rc_pe_max = pctx->pe.max;
1007 pctx->rc_pe_previous = pctx->pe.previous;
1008 } else if (channel == pctx->rc_first_ch) {
1009 pctx->fill_level = pctx->rc_fill_level;
1010 pctx->pe.min = pctx->rc_pe_min;
1011 pctx->pe.max = pctx->rc_pe_max;
1012 pctx->pe.previous = pctx->rc_pe_previous;
1013 }
1014
1015 for (ch = 0; ch < group->num_ch; ch++) {
1016 AacPsyChannel *pch = &pctx->ch[channel + ch];
1017 if (ctx->avctx->frame_num != pch->rc_frame_num) {
1018 pch->rc_frame_num = ctx->avctx->frame_num;
1019 memcpy(pch->rc_prev_band, pch->prev_band, sizeof(pch->prev_band));
1020 } else {
1021 memcpy(pch->prev_band, pch->rc_prev_band, sizeof(pch->prev_band));
1022 }
1023 psy_3gpp_analyze_channel(ctx, channel + ch, coeffs[ch], &wi[ch]);
1024 }
1025}
1026
1028{
1030 if (pctx)
1031 av_freep(&pctx->ch);
1033}
1034
1035static void lame_apply_block_type(AacPsyChannel *ctx, FFPsyWindowInfo *wi, int uselongblock)
1036{
1037 int blocktype = ONLY_LONG_SEQUENCE;
1038 if (uselongblock) {
1039 if (ctx->next_window_seq == EIGHT_SHORT_SEQUENCE)
1040 blocktype = LONG_STOP_SEQUENCE;
1041 } else {
1042 blocktype = EIGHT_SHORT_SEQUENCE;
1043 if (ctx->next_window_seq == ONLY_LONG_SEQUENCE)
1044 ctx->next_window_seq = LONG_START_SEQUENCE;
1045 if (ctx->next_window_seq == LONG_STOP_SEQUENCE)
1046 ctx->next_window_seq = EIGHT_SHORT_SEQUENCE;
1047 }
1048
1049 wi->window_type[0] = ctx->next_window_seq;
1050 ctx->next_window_seq = blocktype;
1051}
1052
1053/* Attack detection half of the LAME window decision: everything up to (and
1054 * excluding) the block-type state machine. Fills attacks[] and returns the raw
1055 * uselongblock; mutates only the detection history. Split out so a channel
1056 * pair can be detected first and DECIDED together (synced block switching). */
1058 const float *la, int channel, int prev_type,
1059 int attacks[AAC_NUM_BLOCKS_SHORT + 1])
1060{
1061 int uselongblock = 1;
1062 int i;
1063
1064 if (la) {
1065 float hpfsmpl[AAC_BLOCK_SIZE_LONG];
1066 const float *pf = hpfsmpl;
1067 float attack_intensity[(AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS];
1068 float energy_subshort[(AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS];
1069 float energy_short[AAC_NUM_BLOCKS_SHORT + 1] = { 0 };
1070 const float *firbuf = la + (AAC_BLOCK_SIZE_SHORT/4 - PSY_LAME_FIR_LEN);
1071 int att_sum = 0;
1072
1073 /* LAME comment: apply high pass filter of fs/4 */
1074 psy_hp_filter(firbuf, hpfsmpl, psy_fir_coeffs);
1075
1076 /* Calculate the energies of each sub-shortblock */
1077 for (i = 0; i < PSY_LAME_NUM_SUBBLOCKS; i++) {
1078 energy_subshort[i] = pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 1) * PSY_LAME_NUM_SUBBLOCKS)];
1079 assert(pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 1) * PSY_LAME_NUM_SUBBLOCKS - 2)] > 0);
1080 attack_intensity[i] = energy_subshort[i] / pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 1) * PSY_LAME_NUM_SUBBLOCKS - 2)];
1081 energy_short[0] += energy_subshort[i];
1082 }
1083
1084 for (i = 0; i < AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS; i++) {
1085 const float *const pfe = pf + AAC_BLOCK_SIZE_LONG / (AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS);
1086 float p = 1.0f;
1087 for (; pf < pfe; pf++)
1088 p = FFMAX(p, fabsf(*pf));
1089 pch->prev_energy_subshort[i] = energy_subshort[i + PSY_LAME_NUM_SUBBLOCKS] = p;
1090 energy_short[1 + i / PSY_LAME_NUM_SUBBLOCKS] += p;
1091
1092 /* NOTE: The indexes below are [i + 3 - 2] in the LAME source. Compare each sub-block to sub-block - 2 */
1093 if (p > energy_subshort[i + PSY_LAME_NUM_SUBBLOCKS - 2])
1094 p = p / energy_subshort[i + PSY_LAME_NUM_SUBBLOCKS - 2];
1095 else if (energy_subshort[i + PSY_LAME_NUM_SUBBLOCKS - 2] > p * 10.0f)
1096 p = energy_subshort[i + PSY_LAME_NUM_SUBBLOCKS - 2] / (p * 10.0f);
1097 else
1098 p = 0.0;
1099
1100 attack_intensity[i + PSY_LAME_NUM_SUBBLOCKS] = p;
1101 }
1102 for (i = 0; i < AAC_NUM_BLOCKS_SHORT; i++)
1103 pch->next_win_level[i] = energy_short[1 + i];
1104
1105 { /* pre-echo-aware threshold relaxation + periodicity/novelty check
1106 * (a pulse train repeats its peak; a real onset towers) */
1107 float frame_peak = 1.0f;
1110 const float nov_gate = 1.25f;
1111 /* first-difference peak per sub-block: an attack that shorts can
1112 * help has HF novelty; a bass pluck under a long window does not */
1113 memcpy(denv, pch->dif_env_hist, sizeof(pch->dif_env_hist));
1114 {
1116 for (i = 0; i < AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS; i++) {
1117 float p = 0.0f;
1118 for (int j2 = i*sub + 1; j2 < (i+1)*sub; j2++)
1119 p = FFMAX(p, fabsf(la[j2] - la[j2-1]));
1120 denv[PSY_LAME_HIST + i] = FFMAX(p * 32768.0f, 1.0f);
1121 }
1122 }
1124 sizeof(pch->dif_env_hist));
1125 memcpy(env,pch->hp_env_hist, sizeof(pch->hp_env_hist));
1126 memcpy(env + PSY_LAME_HIST, energy_subshort + PSY_LAME_NUM_SUBBLOCKS,
1129 frame_peak = FFMAX(frame_peak, energy_subshort[i]);
1130 for (i = 0; i < (AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS; i++)
1131 if (!attacks[i / PSY_LAME_NUM_SUBBLOCKS]) {
1132 float thr = pch->attack_threshold;
1133 if (i >= PSY_LAME_NUM_SUBBLOCKS &&
1135 energy_subshort[i - PSY_LAME_NUM_SUBBLOCKS] < PSY_LAME_PE_QUIET * frame_peak)
1136 thr *= PSY_LAME_PE_RED;
1137 if (attack_intensity[i] > thr) {
1138 /* An attack must tower over the recent HP envelope:
1139 * within ~12ms always (pitch-rate trains), within
1140 * ~44ms only from steady long-window state (slow
1141 * pulse trains, where an isolated short excursion
1142 * is an audible click). */
1143 if (nov_gate > 0.0f && i >= PSY_LAME_NUM_SUBBLOCKS) {
1144 const int pos = PSY_LAME_HIST + i - PSY_LAME_NUM_SUBBLOCKS;
1145 float nearmax = 1.0f, deepmax = 1.0f;
1146 for (int k = 3; k <= 8; k++)
1147 nearmax = FFMAX(nearmax, env[pos - k]);
1148 for (int k = 3; k <= PSY_LAME_NOV_BACK; k++)
1149 deepmax = FFMAX(deepmax, env[pos - k]);
1150 if (energy_subshort[i] < nov_gate * nearmax ||
1151 (energy_subshort[i] < nov_gate * deepmax &&
1153 continue; /* periodic, not an onset */
1154 }
1155 if (i >= PSY_LAME_NUM_SUBBLOCKS) {
1156 /* no HF novelty: pre-echo is masked by the
1157 * sustained LF itself, and the short excursion
1158 * (HF mute, then the stop frame's noisy HF
1159 * hand-back) is the audible event. Both bars
1160 * must agree: absolutely small AND relatively
1161 * unremarkable - a quiet transient rising out
1162 * of silence has a tiny derivative but maximal
1163 * novelty, and its pre-echo lands on silence */
1164 const int pos = PSY_LAME_HIST + i - PSY_LAME_NUM_SUBBLOCKS;
1165 float dmax = 1.0f, premin = 1e30f;
1166 for (int k = 1; k <= PSY_LAME_NOV_BACK; k++)
1167 dmax = FFMAX(dmax, denv[pos - k]);
1168 /* pre-echo audibility: the veto is only safe
1169 * when the surroundings mask the smear - a deep
1170 * dip right before a LOUD attack (stop-gap
1171 * slams) means the long window's pre-echo lands
1172 * on quiet. Quiet candidates keep the veto:
1173 * their smear is at the noise floor, and shorts
1174 * would only fragment the passage */
1175 for (int k = 1; k <= 4; k++)
1176 premin = FFMIN(premin, env[pos - k]);
1177 if (denv[pos] < PSY_LAME_HFN_REL * dmax &&
1178 denv[pos] < PSY_LAME_HFN_ABS &&
1179 premin * PSY_LAME_HFN_PRE > energy_subshort[i])
1180 continue;
1181 }
1182 attacks[i / PSY_LAME_NUM_SUBBLOCKS] = (i % PSY_LAME_NUM_SUBBLOCKS) + 1;
1183 }
1184 }
1185 }
1186
1187 /* should have energy change between short blocks, in order to avoid periodic signals */
1188 /* Good samples to show the effect are Trumpet test songs */
1189 /* GB: tuned (1) to avoid too many short blocks for test sample TRUMPET */
1190 /* RH: tuned (2) to let enough short blocks through for test sample FSOL and SNAPS */
1191 for (i = 1; i < AAC_NUM_BLOCKS_SHORT + 1; i++) {
1192 const float u = energy_short[i - 1];
1193 const float v = energy_short[i];
1194 const float m = FFMAX(u, v);
1195 if (m < 40000) { /* (2) */
1196 if (u < 2.3f * v && v < 2.3f * u) { /* (1) */
1197 if (i == 1 && attacks[0] < attacks[i])
1198 attacks[0] = 0;
1199 attacks[i] = 0;
1200 }
1201 }
1202 att_sum += attacks[i];
1203 }
1204
1205 { /* Gap-onset detection on the broadband envelope: a slam that ends
1206 * a quiet gap (stop-start riffing, kick after a break) can be
1207 * invisible to the HP path - no content above fs/4, or a rise too
1208 * gradual for the 2-sub-block ratio - yet pre-echo into the gap
1209 * is maximally audible (no forward masking there). Fire when the
1210 * candidate towers over a recent dip. Pulse trains cannot fire:
1211 * their inter-pulse floor never dips far enough below the pulse. */
1213 /* scan both envelopes: broadband (kick+chug slams with LF
1214 * dominance) and HP (events whose gap only exists above the
1215 * sustained bass) */
1217 float *walls[2] = { &pch->gap_wall, &pch->gap_wall_hp };
1218 const float *envs[2] = { renv, henv };
1219 memcpy(renv, pch->raw_env_hist, sizeof(pch->raw_env_hist));
1220 for (i = 0; i < AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS; i++) {
1221 float p = 0.0f;
1222 for (int j2 = 0; j2 < 64; j2++)
1223 p = FFMAX(p, fabsf(la[i*64 + j2]));
1224 renv[PSY_LAME_HIST + i] = FFMAX(p * 32768.0f, 1.0f);
1225 }
1226 memcpy(henv, pch->hp_env_hist, sizeof(pch->hp_env_hist));
1227 memcpy(henv + PSY_LAME_HIST, energy_subshort + PSY_LAME_NUM_SUBBLOCKS,
1229 for (int e = 0; e < 2; e++) {
1230 const float *ev = envs[e];
1231 float wall = *walls[e];
1232 for (i = 0; i < AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS; i++) {
1234 const int pos = PSY_LAME_HIST + i;
1235 const float cand = ev[pos];
1236 const float quiet = wall / PSY_LAME_GAP_DEPTH;
1237 int run = 0, k0 = 0;
1238 /* the gap must end adjacent to the candidate (<= 5
1239 * rising sub-blocks) and hold >= 4 sub-blocks (~6ms).
1240 * A pulse train's inter-pulse floor never drops this
1241 * far below its own running peak, so it cannot fire. */
1242 for (int k = 3; k <= 8; k++)
1243 if (ev[pos - k] < quiet) {
1244 k0 = k;
1245 break;
1246 }
1247 if (k0)
1248 for (int k = k0; k <= PSY_LAME_GAP_BACK && ev[pos - k] < quiet; k++)
1249 run++;
1250 if (e == 1 && !(run >= 4)) {
1251 /* HP tower: an onset rising far above everything
1252 * in the look-back, even without a silent gap
1253 * (cymbal-less slams leave the bass sustaining) */
1254 float dmax = 1.0f;
1255 for (int k = 3; k <= PSY_LAME_GAP_BACK; k++)
1256 dmax = FFMAX(dmax, ev[pos - k]);
1257 if (cand > PSY_LAME_GAP_TOWER * dmax)
1258 run = 4; /* qualify via the same fire path */
1259 }
1260 if (!attacks[b] && run >= 4 && cand > PSY_LAME_GAP_LEVEL * wall &&
1261 cand > PSY_LAME_GAP_FLOOR) {
1262 attacks[b] = (i + PSY_LAME_NUM_SUBBLOCKS) % PSY_LAME_NUM_SUBBLOCKS + 1;
1263 att_sum += attacks[b];
1264 }
1265 wall = FFMAX(wall * 0.996f, cand);
1266 }
1267 *walls[e] = wall;
1268 }
1270 sizeof(pch->raw_env_hist));
1271 }
1272
1273 /* roll the HP sub-block peak history */
1274 memmove(pch->hp_env_hist,
1277 sizeof(*pch->hp_env_hist));
1279 energy_subshort + PSY_LAME_NUM_SUBBLOCKS,
1281
1282 if (pch->next_attack0_zero)
1283 attacks[0] = 0;
1284 pch->next_attack0_zero = !attacks[AAC_NUM_BLOCKS_SHORT];
1285
1286 if (attacks[0] <= pch->prev_attack)
1287 attacks[0] = 0;
1288
1289 att_sum += attacks[0];
1290
1291 /* If the previous attack happened in the last sub-block of the previous sequence,
1292 * or if there's a new attack, use short window */
1293 if (pch->prev_attack == PSY_LAME_NUM_SUBBLOCKS || att_sum) {
1294 uselongblock = 0;
1295
1296 for (i = 1; i < AAC_NUM_BLOCKS_SHORT + 1; i++)
1297 if (attacks[i] && attacks[i-1])
1298 attacks[i] = 0;
1299 }
1300
1301 } else {
1302 /* We have no lookahead info, so just use same type as the previous sequence. */
1303 uselongblock = !(prev_type == EIGHT_SHORT_SEQUENCE);
1304 }
1305 return uselongblock;
1306}
1307
1308/* Decision half: the block-type state machine and window/grouping fill,
1309 * given the (possibly pair-synced) final uselongblock. */
1311 int uselongblock,
1312 const int attacks[AAC_NUM_BLOCKS_SHORT + 1],
1313 int prev_type, int have_la)
1314{
1315 int grouping = 0;
1316 int i;
1317 FFPsyWindowInfo wi = { { 0 } };
1318
1319 if (have_la)
1320 pch->frames_since_short = uselongblock ? pch->frames_since_short + 1 : 0;
1321
1322 lame_apply_block_type(pch, &wi, uselongblock);
1323
1324 wi.window_type[1] = prev_type;
1325 if (wi.window_type[0] != EIGHT_SHORT_SEQUENCE) {
1326
1327 wi.num_windows = 1;
1328 wi.grouping[0] = 1;
1329 if (wi.window_type[0] == LONG_START_SEQUENCE)
1330 wi.window_shape = 0;
1331 else
1332 wi.window_shape = 1;
1333
1334 } else {
1335 int lastgrp = 0;
1336
1337 wi.num_windows = 8;
1338 wi.window_shape = 0;
1339 for (i = 0; i < 8; i++) {
1340 if (!((pch->next_grouping >> i) & 1))
1341 lastgrp = i;
1342 wi.grouping[lastgrp]++;
1343 }
1344 }
1345
1346 /* Determine grouping, based on the location of the first attack, and save for
1347 * the next frame.
1348 * FIXME: Move this to analysis.
1349 * TODO: Tune groupings depending on attack location
1350 * TODO: Handle more than one attack in a group
1351 */
1352 for (i = 0; i < 9; i++) {
1353 if (attacks[i]) {
1354 grouping = i;
1355 break;
1356 }
1357 }
1358 pch->next_grouping = window_grouping[grouping];
1359
1360 {
1361 /* energy-homogeneous grouping: fixed attack-position patterns force
1362 * disparate windows to share scalefactors; regroup on level jumps */
1363 uint8_t bits = 0;
1364 int glen = 1;
1365 for (i = 1; i < AAC_NUM_BLOCKS_SHORT; i++) {
1366 float a = pch->next_win_level[i], b = pch->next_win_level[i-1];
1367 float hi = FFMAX(a, b), lo = FFMAX(FFMIN(a, b), 1.0f);
1368 if (hi <= lo * PSY_LAME_GRP_RATIO && glen < PSY_LAME_GRP_MAX) {
1369 bits |= 1 << i;
1370 glen++;
1371 } else {
1372 glen = 1;
1373 }
1374 }
1375 pch->next_grouping = bits;
1376 }
1377
1378 pch->prev_attack = attacks[AAC_NUM_BLOCKS_SHORT - 1];
1379
1380 return wi;
1381}
1382
1384 const float *la, int channel, int prev_type)
1385{
1386 AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
1387 AacPsyChannel *pch = &pctx->ch[channel];
1388 int attacks[AAC_NUM_BLOCKS_SHORT + 1] = { 0 };
1389 int uselongblock = psy_lame_detect(pctx, pch, la, channel, prev_type, attacks);
1390
1391 return psy_lame_apply(pctx, pch, uselongblock, attacks, prev_type, !!la);
1392}
1393
1394/* Pair-synced block switching: either channel's attack switches both. */
1396 const float *audio0, const float *la0,
1397 const float *audio1, const float *la1,
1398 int channel0, int channel1,
1399 int prev_type0, int prev_type1,
1400 FFPsyWindowInfo wi[2])
1401{
1402 AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
1403 AacPsyChannel *pch0 = &pctx->ch[channel0];
1404 AacPsyChannel *pch1 = &pctx->ch[channel1];
1405 int att0[AAC_NUM_BLOCKS_SHORT + 1] = { 0 };
1406 int att1[AAC_NUM_BLOCKS_SHORT + 1] = { 0 };
1407 int merged[AAC_NUM_BLOCKS_SHORT + 1];
1408 int u0 = psy_lame_detect(pctx, pch0, la0, channel0, prev_type0, att0);
1409 int u1 = psy_lame_detect(pctx, pch1, la1, channel1, prev_type1, att1);
1410 int u = u0 && u1;
1411
1412 if (ctx->pair_decoupled[(channel0 >> 1) & 15]) {
1413 /* Joint tools are dead on this pair (encoder-fed state): each channel
1414 * windows for ITS transients - divergence costs nothing there, while
1415 * union-syncing forces the steady channel short at every event in
1416 * the other. Correlated content keeps the sync. */
1417 wi[0] = psy_lame_apply(pctx, pch0, u0, att0, prev_type0, !!la0);
1418 wi[1] = psy_lame_apply(pctx, pch1, u1, att1, prev_type1, !!la1);
1419 return;
1420 }
1421
1422 /* One merged attack map for both channels: the grouping (and with it
1423 * common_window) must match across the pair, and the group boundary
1424 * should isolate the first attack heard in EITHER channel. */
1425 for (int i = 0; i < AAC_NUM_BLOCKS_SHORT + 1; i++)
1426 merged[i] = att0[i] ? att0[i] : att1[i];
1427
1428 /* grouping must also match across the pair: merge the level maps */
1429 for (int i = 0; i < AAC_NUM_BLOCKS_SHORT; i++)
1430 pch0->next_win_level[i] = pch1->next_win_level[i] =
1431 FFMAX(pch0->next_win_level[i], pch1->next_win_level[i]);
1432
1433 wi[0] = psy_lame_apply(pctx, pch0, u, merged, prev_type0, !!la0);
1434 wi[1] = psy_lame_apply(pctx, pch1, u, merged, prev_type1, !!la1);
1435}
1436
1438{
1439 .name = "3GPP TS 26.403-inspired model",
1440 .init = psy_3gpp_init,
1441 .window = psy_lame_window,
1442 .analyze = psy_3gpp_analyze,
1443 .end = psy_3gpp_end,
1444 .window_pair = psy_lame_window_pair,
1445};
AAC definitions and structures.
WindowSequence
Definition aac.h:63
@ EIGHT_SHORT_SEQUENCE
Definition aac.h:66
@ LONG_STOP_SEQUENCE
Definition aac.h:67
@ ONLY_LONG_SEQUENCE
Definition aac.h:64
@ LONG_START_SEQUENCE
Definition aac.h:65
static float lame_calc_attack_threshold(int bitrate)
Calculate the ABR attack threshold from the above LAME psymodel table.
Definition aacpsy.c:305
#define PSY_LAME_GAP_DEPTH
a gap is this far below the peak-hold
Definition aacpsy.c:147
static av_unused FFPsyWindowInfo psy_3gpp_window(FFPsyContext *ctx, const int16_t *audio, const int16_t *la, int channel, int prev_type)
Tell encoder which window types to use.
Definition aacpsy.c:490
#define PSY_LAME_GRP_RATIO
max adjacent-window level ratio inside a group
Definition aacpsy.c:154
#define PSY_LAME_PE_RED
attack-threshold multiplier for a qualifying isolated onset
Definition aacpsy.c:132
#define PSY_3GPP_SPEND_SLOPE_L
Definition aacpsy.c:72
#define PSY_LAME_GAP_LEVEL
candidate must reach this fraction of the peak-hold
Definition aacpsy.c:149
static void lame_apply_block_type(AacPsyChannel *ctx, FFPsyWindowInfo *wi, int uselongblock)
Definition aacpsy.c:1035
#define PSY_3GPP_CLIP_HI_L
Definition aacpsy.c:78
#define PSY_3GPP_EN_SPREAD_HI_L1
Definition aacpsy.c:48
#define PSY_3GPP_C3
Definition aacpsy.c:63
#define PSY_LAME_PE_QUIET
pre-onset must be below this fraction of the frame peak
Definition aacpsy.c:131
static const PsyLamePreset psy_abr_map[]
LAME psy model preset table for ABR.
Definition aacpsy.c:257
#define PSY_3GPP_CLIP_LO_S
Definition aacpsy.c:77
#define PSY_3GPP_RPELEV
Definition aacpsy.c:59
#define PSY_3GPP_AH_THR_LONG
Definition aacpsy.c:105
static const float psy_fir_coeffs[]
LAME psy model FIR coefficient table.
Definition aacpsy.c:296
static av_cold float calc_bark(float f)
Calculate Bark value for given line.
Definition aacpsy.c:360
static void psy_lame_window_pair(FFPsyContext *ctx, const float *audio0, const float *la0, const float *audio1, const float *la1, int channel0, int channel1, int prev_type0, int prev_type1, FFPsyWindowInfo wi[2])
Definition aacpsy.c:1395
#define PSY_LAME_GAP_BACK
gap look-back in sub-blocks (<= PSY_LAME_HIST)
Definition aacpsy.c:148
#define PSY_3GPP_C1
Definition aacpsy.c:61
static float calc_reduced_thr_3gpp(AacPsyBand *band, float min_snr, float reduction)
Definition aacpsy.c:657
#define PSY_3GPP_PE_TO_BITS(bits)
Definition aacpsy.c:117
#define PSY_3GPP_C2
Definition aacpsy.c:62
#define PSY_3GPP_THR_SPREAD_HI
constants for 3GPP AAC psychoacoustic model
Definition aacpsy.c:45
static int psy_lame_detect(AacPsyContext *pctx, AacPsyChannel *pch, const float *la, int channel, int prev_type, int attacks[AAC_NUM_BLOCKS_SHORT+1])
Definition aacpsy.c:1057
#define PSY_LAME_GAP_FLOOR
and this absolute peak
Definition aacpsy.c:150
static void psy_3gpp_analyze(FFPsyContext *ctx, int channel, const float **coeffs, const FFPsyWindowInfo *wi)
Definition aacpsy.c:990
static float calc_reduction_3gpp(float a, float desired_pe, float pe, float active_lines)
Definition aacpsy.c:643
static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio, const float *la, int channel, int prev_type)
Definition aacpsy.c:1383
#define PSY_3GPP_EN_SPREAD_HI_S
Definition aacpsy.c:52
static void psy_hp_filter(const float *firbuf, float *hpfsmpl, const float *psy_fir_coeffs)
Definition aacpsy.c:711
#define PSY_3GPP_RPEMIN
Definition aacpsy.c:58
static const uint8_t window_grouping[9]
window grouping information stored as bits (0 - new group, 1 - group continues)
Definition aacpsy.c:482
#define PSY_SNR_25DB
Definition aacpsy.c:66
#define PSY_3GPP_THR_SPREAD_LOW
Definition aacpsy.c:46
#define PSY_LAME_HFN_PRE
max candidate rise over the ~5ms pre-attack minimum
Definition aacpsy.c:144
#define PSY_3GPP_EN_SPREAD_LOW_L
Definition aacpsy.c:54
#define PSY_3GPP_SAVE_SLOPE_L
Definition aacpsy.c:68
#define PSY_PE_FORGET_SLOPE
Definition aacpsy.c:108
#define PSY_3GPP_DEMAND_SCALE
Definition aacpsy.c:103
static av_cold void lame_window_init(FFPsyContext *fctx, AacPsyContext *ctx, AVCodecContext *avctx)
LAME psy model specific initialization.
Definition aacpsy.c:335
#define PSY_LAME_HFN_REL
max derivative rise over the recent envelope
Definition aacpsy.c:142
#define AAC_BLOCK_SIZE_LONG
long block size
Definition aacpsy.c:121
#define PSY_3GPP_CLIP_LO_L
Definition aacpsy.c:76
#define PSY_3GPP_BITS_TO_PE(bits)
Definition aacpsy.c:116
#define PSY_3GPP_SAVE_ADD_L
Definition aacpsy.c:70
#define PSY_LAME_HIST
HP sub-block peak history depth.
Definition aacpsy.c:136
#define AAC_BLOCK_SIZE_SHORT
short block size
Definition aacpsy.c:122
static float calc_pe_3gpp(AacPsyBand *band)
Definition aacpsy.c:620
#define PSY_3GPP_AH_THR_SHORT
Definition aacpsy.c:106
#define PSY_LAME_PE_GAP
min consecutive long frames before the relaxation applies
Definition aacpsy.c:130
static const PsyLamePreset psy_vbr_map[]
LAME psy model preset table for constant quality.
Definition aacpsy.c:278
#define PSY_LAME_GRP_MAX
max windows per group
Definition aacpsy.c:155
#define PSY_LAME_NUM_SUBBLOCKS
Number of sub-blocks in each short block.
Definition aacpsy.c:124
static av_cold float ath(float f, float add)
Calculate ATH value for given frequency.
Definition aacpsy.c:370
#define AAC_NUM_BLOCKS_SHORT
number of blocks in a short sequence
Definition aacpsy.c:123
static void psy_3gpp_analyze_channel(FFPsyContext *ctx, int channel, const float *coefs, const FFPsyWindowInfo *wi)
Calculate band thresholds as suggested in 3GPP TS26.403.
Definition aacpsy.c:731
#define PSY_3GPP_SPEND_SLOPE_S
Definition aacpsy.c:73
#define PSY_LAME_HFN_ABS
max absolute derivative peak
Definition aacpsy.c:143
#define PSY_3GPP_EN_SPREAD_LOW_S
Definition aacpsy.c:56
#define PSY_THRFL_CBR
Definition aacpsy.c:91
static int calc_bit_demand(AacPsyContext *ctx, float pe, int bits, int size, int short_window)
Definition aacpsy.c:576
#define PSY_3GPP_CLIP_HI_S
Definition aacpsy.c:79
static FFPsyWindowInfo psy_lame_apply(AacPsyContext *pctx, AacPsyChannel *pch, int uselongblock, const int attacks[AAC_NUM_BLOCKS_SHORT+1], int prev_type, int have_la)
Definition aacpsy.c:1310
#define PSY_LAME_NOV_BACK
novelty look-back in sub-blocks
Definition aacpsy.c:137
#define PSY_THRFL_QUALITY
Definition aacpsy.c:90
@ PSY_3GPP_AH_INACTIVE
Definition aacpsy.c:112
@ PSY_3GPP_AH_NONE
Definition aacpsy.c:111
@ PSY_3GPP_AH_ACTIVE
Definition aacpsy.c:113
#define PSY_SNR_1DB
Definition aacpsy.c:65
#define PSY_3GPP_SPEND_ADD_L
Definition aacpsy.c:74
#define ATH_ADD
Definition aacpsy.c:365
static av_cold int psy_3gpp_init(FFPsyContext *ctx)
Definition aacpsy.c:379
static void calc_thr_3gpp(const FFPsyWindowInfo *wi, const int num_bands, AacPsyChannel *pch, const uint8_t *band_sizes, const float *coefs, const int cutoff)
Definition aacpsy.c:682
#define PSY_3GPP_SAVE_SLOPE_S
Definition aacpsy.c:69
#define PSY_LAME_FIR_LEN
LAME psy model FIR order.
Definition aacpsy.c:120
const FFPsyModel ff_aac_psy_model
Definition aacpsy.c:1437
#define PSY_3GPP_SPEND_ADD_S
Definition aacpsy.c:75
#define PSY_3GPP_SAVE_ADD_S
Definition aacpsy.c:71
#define PSY_LAME_GAP_TOWER
HP tower: rise over the whole look-back.
Definition aacpsy.c:151
static av_cold void psy_3gpp_end(FFPsyContext *apc)
Definition aacpsy.c:1027
#define PSY_THRFL_CBR_KNEE
Definition aacpsy.c:92
static const float bands[]
#define log2f(x)
Definition math.h:27
static AVFormatContext * ctx
Libavcodec external API header.
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define f(width, name)
Definition cbs_vp8.c:236
#define ss(width, name, subs,...)
Definition cbs_vp9.c:202
#define s(width, name)
Definition cbs_vp9.c:198
#define av_clip
Definition common.h:100
#define av_clipf
Definition common.h:145
long long int64_t
Definition coverity.c:34
static __device__ float sqrtf(float a)
static __device__ float fabsf(float a)
static __device__ float fabs(float a)
channel
Use these values when setting the channel map with ebur128_set_channel().
Definition ebur128.h:39
int8_t exp
Definition eval.c:76
static struct @346255127015250356166251341105367306144006377143 state
static const uint8_t bits[8]
Definition fastaudio.c:100
internal math functions header
static av_always_inline float ff_exp10f(float x)
Definition ffmath.h:49
static av_always_inline double ff_exp10(double x)
Compute 10^x for floating point values.
Definition ffmath.h:44
#define iir_filter(fir_coef, iir_coef, src, dest, width)
Perform IIR filtering.
Definition g723_1dec.c:589
#define AV_CODEC_FLAG_QSCALE
Use fixed qscale.
Definition avcodec.h:213
#define FF_QP2LAMBDA
factor to convert from H.263 QP to lambda
Definition avutil.h:226
#define AVERROR(e)
Definition error.h:45
int a
#define b
Definition input.c:43
#define u(width, name, range_min, range_max)
Definition cbs_apv.c:68
Macro definitions for various function/variable attributes.
#define av_unused
Definition attributes.h:164
#define av_cold
Definition attributes.h:117
uint8_t w
Definition llvidencdsp.c:39
#define FFMIN(a, b)
Definition macros.h:49
#define FFMAX(a, b)
Definition macros.h:47
float exp2f(float x)
Definition math.c:49
#define NAN
void * av_calloc(size_t nmemb, size_t size)
Definition mem.c:370
Memory handling functions.
FFPsyChannelGroup * ff_psy_find_group(FFPsyContext *ctx, int channel)
Determine what group a channel belongs to.
Definition psymodel.c:67
#define AAC_CUTOFF(s)
Definition psymodel.h:41
unsigned int pos
Definition spdifenc.c:431
int nb_channels
Number of channels in this layout.
main external API structure.
Definition avcodec.h:443
AVChannelLayout ch_layout
Audio channel layout.
Definition avcodec.h:1055
int global_quality
Global quality for codecs which cannot change it per frame.
Definition avcodec.h:1235
int64_t bit_rate
the average bitrate
Definition avcodec.h:493
int flags
AV_CODEC_FLAG_*.
Definition avcodec.h:500
information for single band used by 3GPP TS26.403-inspired psychoacoustic model
Definition aacpsy.c:164
float thr_quiet
threshold in quiet
Definition aacpsy.c:167
float norm_fac
normalization factor for linearization
Definition aacpsy.c:172
float nz_lines
number of non-zero spectral lines
Definition aacpsy.c:168
float active_lines
number of active spectral lines
Definition aacpsy.c:169
float thr
energy threshold
Definition aacpsy.c:166
int avoid_holes
hole avoidance flag
Definition aacpsy.c:173
float energy
band energy
Definition aacpsy.c:165
float pe
perceptual entropy
Definition aacpsy.c:170
float pe_const
constant part of the PE calculation
Definition aacpsy.c:171
single/pair channel context for psychoacoustic model
Definition aacpsy.c:179
float attack_threshold
attack threshold for this channel
Definition aacpsy.c:188
float raw_env_hist[PSY_LAME_HIST]
rolling broadband sub-block peak envelope
Definition aacpsy.c:193
float gap_wall
decaying broadband peak-hold (gap-onset reference)
Definition aacpsy.c:194
float iir_state[2]
hi-pass IIR filter state
Definition aacpsy.c:184
float dif_env_hist[PSY_LAME_HIST]
rolling first-difference sub-block peak envelope (HF novelty)
Definition aacpsy.c:191
float win_energy
sliding average of channel energy
Definition aacpsy.c:183
int64_t win_count
window() calls so far (frame counter for pair sync)
Definition aacpsy.c:200
int64_t rc_frame_num
frame this channel last saved rewind state for
Definition aacpsy.c:204
int next_attack0_zero
whether attack[0] of the next frame is zero
Definition aacpsy.c:197
int64_t last_att
win_count value of this channel's last own attack
Definition aacpsy.c:201
enum WindowSequence next_window_seq
window sequence to be used in the next frame
Definition aacpsy.c:186
float gap_wall_hp
decaying HP peak-hold (gap-onset reference)
Definition aacpsy.c:195
float prev_energy_subshort[AAC_NUM_BLOCKS_SHORT *PSY_LAME_NUM_SUBBLOCKS]
Definition aacpsy.c:189
AacPsyBand rc_prev_band[128]
prev_band as it was entering the frame
Definition aacpsy.c:205
float hp_env_hist[PSY_LAME_HIST]
rolling HP sub-block peak envelope
Definition aacpsy.c:192
AacPsyBand prev_band[128]
bands information from the previous frame
Definition aacpsy.c:181
int frames_since_short
consecutive long frames (pre-echo-aware isolated-onset gate)
Definition aacpsy.c:198
float next_win_level[AAC_NUM_BLOCKS_SHORT]
lookahead short-window peak levels (grouping homogeneity)
Definition aacpsy.c:190
uint8_t next_grouping
stored grouping scheme for the next frame (in case of 8 short window sequence)
Definition aacpsy.c:185
int prev_attack
attack value for the last short block in the previous sequence
Definition aacpsy.c:196
float prev_frame_energy
previous frame's full-band lookahead energy (attack veto)
Definition aacpsy.c:199
AacPsyBand band[128]
bands information
Definition aacpsy.c:180
psychoacoustic model frame type-dependent coefficients
Definition aacpsy.c:211
float ath
absolute threshold of hearing per bands
Definition aacpsy.c:212
float spread_low[2]
spreading factor for low-to-high threshold spreading in long frame
Definition aacpsy.c:214
float min_snr
minimal SNR
Definition aacpsy.c:216
float barks
Bark value for each spectral band in long frame.
Definition aacpsy.c:213
float spread_hi[2]
spreading factor for high-to-low threshold spreading in long frame
Definition aacpsy.c:215
3GPP TS26.403-inspired psychoacoustic model specific data
Definition aacpsy.c:222
float correction
PE correction factor.
Definition aacpsy.c:230
int rc_first_ch
first channel analyzed in that frame
Definition aacpsy.c:238
int rc_fill_level
Definition aacpsy.c:239
float rc_pe_min
Definition aacpsy.c:240
float rc_pe_max
Definition aacpsy.c:240
int chan_bitrate
bitrate per channel
Definition aacpsy.c:223
struct AacPsyContext::@245330130066201162145177070256170070220205206266 pe
float min
minimum allowed PE for bit factor calculation
Definition aacpsy.c:227
AacPsyCoeffs psy_coef[2][64]
Definition aacpsy.c:232
float global_quality
normalized global quality taken from avctx
Definition aacpsy.c:234
int64_t rc_frame_num
frame the rewind state was saved for
Definition aacpsy.c:237
float previous
allowed PE of the previous frame
Definition aacpsy.c:229
int fill_level
bit reservoir fill level
Definition aacpsy.c:225
float rc_pe_previous
Definition aacpsy.c:240
float max
maximum allowed PE for bit factor calculation
Definition aacpsy.c:228
AacPsyChannel * ch
Definition aacpsy.c:233
int frame_bits
average bits per frame
Definition aacpsy.c:224
single band psychoacoustic information
Definition psymodel.h:50
float spread
Definition psymodel.h:54
int bits
Definition psymodel.h:51
float threshold
Definition psymodel.h:53
float energy
Definition psymodel.h:52
psychoacoustic information for an arbitrary group of channels
Definition psymodel.h:68
uint8_t num_ch
number of channels in this group
Definition psymodel.h:70
context used by psychoacoustic model
Definition psymodel.h:89
void * model_priv_data
psychoacoustic model implementation private data
Definition psymodel.h:109
int unbounded_pe
PE reduction at a fixed reference quality, not the rate (quality-target coder owns the rate)
Definition psymodel.h:97
codec-specific psychoacoustic model implementation
Definition psymodel.h:117
windowing related information
Definition psymodel.h:77
int num_windows
number of windows in a frame
Definition psymodel.h:80
int grouping[8]
window grouping (for e.g. AAC)
Definition psymodel.h:81
int window_shape
window shape (sine/KBD/whatever)
Definition psymodel.h:79
int window_type[3]
window type (short/long/transitional, etc.) - current, previous and next
Definition psymodel.h:78
LAME psy model preset struct.
Definition aacpsy.c:246
float st_lrm
short threshold for L, R, and M channels
Definition aacpsy.c:251
int quality
Quality to map the rest of the values to.
Definition aacpsy.c:247
uint8_t run
Definition svq3.c:207
#define av_mallocz(s)
#define av_freep(p)
int64_t bitrate
Definition av1_levels.c:47
int size
const char * g
Definition vf_curves.c:128
static const double coeff[2][5]
static const uint8_t quality[]
Definition vmixdec.c:58