mirror of
https://git.ffmpeg.org/ffmpeg.git
synced 2026-10-24 02:09:03 +03:00
In psy_3gpp_analyze_channel(), the spread energy of the first band was always stored in spread_en[0] instead of spread_en[w], unlike every other access to spread_en[w+g]. For short windows, windows 1-7 thus started spreading from an unset value instead of their own first band energy. This only affects the hole avoidance decision. Tested: make fate passes (5875 tests). Encoder output was bit-identical before and after on luckynight_2ch_44kHz_s16.wav and on a synthetic transient signal at 24k, 32k, 48k, 64k and 128k, so the practical effect seems small. Found with the help of an AI code review; verified by hand. Signed-off-by: romainhedouin <romain.hedouin@epitech.eu>
1446 lines
62 KiB
C
1446 lines
62 KiB
C
/*
|
|
* AAC encoder psychoacoustic model
|
|
* Copyright (C) 2008 Konstantin Shishkov
|
|
*
|
|
* This file is part of FFmpeg.
|
|
*
|
|
* FFmpeg is free software; you can redistribute it and/or
|
|
* modify it under the terms of the GNU Lesser General Public
|
|
* License as published by the Free Software Foundation; either
|
|
* version 2.1 of the License, or (at your option) any later version.
|
|
*
|
|
* FFmpeg is distributed in the hope that it will be useful,
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
|
* Lesser General Public License for more details.
|
|
*
|
|
* You should have received a copy of the GNU Lesser General Public
|
|
* License along with FFmpeg; if not, write to the Free Software
|
|
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
|
*/
|
|
|
|
/**
|
|
* @file
|
|
* AAC encoder psychoacoustic model
|
|
*/
|
|
|
|
#include "libavutil/attributes.h"
|
|
#include "libavutil/ffmath.h"
|
|
#include "libavutil/mem.h"
|
|
|
|
#include "avcodec.h"
|
|
#include "aac.h"
|
|
#include "psymodel.h"
|
|
|
|
/***********************************
|
|
* TODOs:
|
|
* try other bitrate controlling mechanism (maybe use ratecontrol.c?)
|
|
* control quality for quality-based output
|
|
**********************************/
|
|
|
|
/**
|
|
* constants for 3GPP AAC psychoacoustic model
|
|
* @{
|
|
*/
|
|
#define PSY_3GPP_THR_SPREAD_HI 1.5f // spreading factor for low-to-hi threshold spreading (15 dB/Bark)
|
|
#define PSY_3GPP_THR_SPREAD_LOW 3.0f // spreading factor for hi-to-low threshold spreading (30 dB/Bark)
|
|
/* spreading factor for low-to-hi energy spreading, long block, > 22kbps/channel (20dB/Bark) */
|
|
#define PSY_3GPP_EN_SPREAD_HI_L1 2.0f
|
|
/* spreading factor for low-to-hi energy spreading, long block, <= 22kbps/channel (15dB/Bark) */
|
|
#define PSY_3GPP_EN_SPREAD_HI_L2 1.5f
|
|
/* spreading factor for low-to-hi energy spreading, short block (15 dB/Bark) */
|
|
#define PSY_3GPP_EN_SPREAD_HI_S 1.5f
|
|
/* spreading factor for hi-to-low energy spreading, long block (30dB/Bark) */
|
|
#define PSY_3GPP_EN_SPREAD_LOW_L 3.0f
|
|
/* spreading factor for hi-to-low energy spreading, short block (20dB/Bark) */
|
|
#define PSY_3GPP_EN_SPREAD_LOW_S 2.0f
|
|
|
|
#define PSY_3GPP_RPEMIN 0.01f
|
|
#define PSY_3GPP_RPELEV 2.0f
|
|
|
|
#define PSY_3GPP_C1 3.0f /* log2(8) */
|
|
#define PSY_3GPP_C2 1.3219281f /* log2(2.5) */
|
|
#define PSY_3GPP_C3 0.55935729f /* 1 - C2 / C1 */
|
|
|
|
#define PSY_SNR_1DB 7.9432821e-1f /* -1dB */
|
|
#define PSY_SNR_25DB 3.1622776e-3f /* -25dB */
|
|
|
|
#define PSY_3GPP_SAVE_SLOPE_L -0.46666667f
|
|
#define PSY_3GPP_SAVE_SLOPE_S -0.36363637f
|
|
#define PSY_3GPP_SAVE_ADD_L -0.84285712f
|
|
#define PSY_3GPP_SAVE_ADD_S -0.75f
|
|
#define PSY_3GPP_SPEND_SLOPE_L 0.66666669f
|
|
#define PSY_3GPP_SPEND_SLOPE_S 0.81818181f
|
|
#define PSY_3GPP_SPEND_ADD_L -0.35f
|
|
#define PSY_3GPP_SPEND_ADD_S -0.26111111f
|
|
#define PSY_3GPP_CLIP_LO_L 0.2f
|
|
#define PSY_3GPP_CLIP_LO_S 0.2f
|
|
#define PSY_3GPP_CLIP_HI_L 0.95f
|
|
#define PSY_3GPP_CLIP_HI_S 0.75f
|
|
|
|
/* Floor on how close a coded band's mask may come to the band's own energy.
|
|
* The two rate-control families want different shapes, and measurably so:
|
|
* in VBR/ABR the mask IS the rate authority, so a mask that has risen to meet
|
|
* its band's energy tells the solver the band is free to destroy and it buys
|
|
* no bits for it - a broadband floor is right there. In CBR the budget is
|
|
* fixed and the mask only ranks bands against each other, so the same
|
|
* broadband floor just moves bits around and costs ~2% Zim on random content;
|
|
* restricted to the top end, where the mask degenerates to within 2 dB of band
|
|
* energy on every sample measured, it is a clear win. */
|
|
#define PSY_THRFL_QUALITY 10.0f /* VBR/ABR depth, dB, all bands */
|
|
#define PSY_THRFL_CBR 6.0f /* CBR depth, dB */
|
|
#define PSY_THRFL_CBR_KNEE 8000.0f /* CBR: only above this frequency */
|
|
|
|
/* Strength of the 3GPP bit-demand curve: its deviation from unity is
|
|
* amplified, since the trellis coder wants far stronger per-frame budget
|
|
* modulation than the reference encoder's gentle curve provides.
|
|
* The amplified factor goes negative in high-PE frames on a starved
|
|
* reservoir (15-30% of CBR frames). The desired PE is then <= 0 and the
|
|
* reduction raises every threshold as far as the min-SNR and hole rules
|
|
* allow, so those frames are shaped for constant SNR instead of by the
|
|
* mask. That regime is load-bearing: flooring the demand at frame_bits/8
|
|
* costs 3-5% Zimtohrli at 64 kbps stereo. */
|
|
#define PSY_3GPP_DEMAND_SCALE 2.5f
|
|
|
|
#define PSY_3GPP_AH_THR_LONG 0.5f
|
|
#define PSY_3GPP_AH_THR_SHORT 0.63f
|
|
|
|
#define PSY_PE_FORGET_SLOPE 511
|
|
|
|
enum {
|
|
PSY_3GPP_AH_NONE,
|
|
PSY_3GPP_AH_INACTIVE,
|
|
PSY_3GPP_AH_ACTIVE
|
|
};
|
|
|
|
#define PSY_3GPP_BITS_TO_PE(bits) ((bits) * 1.18f)
|
|
#define PSY_3GPP_PE_TO_BITS(bits) ((bits) / 1.18f)
|
|
|
|
/* LAME psy model constants */
|
|
#define PSY_LAME_FIR_LEN 21 ///< LAME psy model FIR order
|
|
#define AAC_BLOCK_SIZE_LONG 1024 ///< long block size
|
|
#define AAC_BLOCK_SIZE_SHORT 128 ///< short block size
|
|
#define AAC_NUM_BLOCKS_SHORT 8 ///< number of blocks in a short sequence
|
|
#define PSY_LAME_NUM_SUBBLOCKS 2 ///< Number of sub-blocks in each short block
|
|
|
|
/* Pre-echo-aware attack detection: the LAME ratio test misses gentler attacks after a quiet
|
|
* gap, which then stay long and pre-echo. For an isolated onset (long for PSY_LAME_PE_GAP
|
|
* frames) whose pre-onset is below PSY_LAME_PE_QUIET of the frame peak, scale the threshold by
|
|
* PSY_LAME_PE_RED so it switches short; dense-transient content never qualifies. */
|
|
#define PSY_LAME_PE_GAP 12 ///< min consecutive long frames before the relaxation applies
|
|
#define PSY_LAME_PE_QUIET 0.4f ///< pre-onset must be below this fraction of the frame peak
|
|
#define PSY_LAME_PE_RED 0.45f ///< attack-threshold multiplier for a qualifying isolated onset
|
|
|
|
/* The novelty check must see at least one full period of a pulse train to
|
|
* recognize its pulses as repeats; 30 sub-blocks reaches down to ~23Hz. */
|
|
#define PSY_LAME_HIST 32 ///< HP sub-block peak history depth
|
|
#define PSY_LAME_NOV_BACK 30 ///< novelty look-back in sub-blocks
|
|
|
|
/* HF-novelty veto: an attack candidate stays long when its first-difference
|
|
* envelope is both relatively and absolutely unremarkable, and pre-echo is
|
|
* masked by what precedes it. */
|
|
#define PSY_LAME_HFN_REL 4.0f ///< max derivative rise over the recent envelope
|
|
#define PSY_LAME_HFN_ABS 2000.0f ///< max absolute derivative peak
|
|
#define PSY_LAME_HFN_PRE 8.0f ///< max candidate rise over the ~5ms pre-attack minimum
|
|
|
|
/* Gap-onset detection against a decaying program-level peak-hold */
|
|
#define PSY_LAME_GAP_DEPTH 6.0f ///< a gap is this far below the peak-hold
|
|
#define PSY_LAME_GAP_BACK 24 ///< gap look-back in sub-blocks (<= PSY_LAME_HIST)
|
|
#define PSY_LAME_GAP_LEVEL 0.4f ///< candidate must reach this fraction of the peak-hold
|
|
#define PSY_LAME_GAP_FLOOR 4000.0f ///< and this absolute peak
|
|
#define PSY_LAME_GAP_TOWER 4.0f ///< HP tower: rise over the whole look-back
|
|
|
|
/* Level-homogeneous short-window grouping */
|
|
#define PSY_LAME_GRP_RATIO 2.5f ///< max adjacent-window level ratio inside a group
|
|
#define PSY_LAME_GRP_MAX 4 ///< max windows per group
|
|
|
|
/**
|
|
* @}
|
|
*/
|
|
|
|
/**
|
|
* information for single band used by 3GPP TS26.403-inspired psychoacoustic model
|
|
*/
|
|
typedef struct AacPsyBand{
|
|
float energy; ///< band energy
|
|
float thr; ///< energy threshold
|
|
float thr_quiet; ///< threshold in quiet
|
|
float nz_lines; ///< number of non-zero spectral lines
|
|
float active_lines; ///< number of active spectral lines
|
|
float pe; ///< perceptual entropy
|
|
float pe_const; ///< constant part of the PE calculation
|
|
float norm_fac; ///< normalization factor for linearization
|
|
int avoid_holes; ///< hole avoidance flag
|
|
}AacPsyBand;
|
|
|
|
/**
|
|
* single/pair channel context for psychoacoustic model
|
|
*/
|
|
typedef struct AacPsyChannel{
|
|
AacPsyBand band[128]; ///< bands information
|
|
AacPsyBand prev_band[128]; ///< bands information from the previous frame
|
|
|
|
float win_energy; ///< sliding average of channel energy
|
|
float iir_state[2]; ///< hi-pass IIR filter state
|
|
uint8_t next_grouping; ///< stored grouping scheme for the next frame (in case of 8 short window sequence)
|
|
enum WindowSequence next_window_seq; ///< window sequence to be used in the next frame
|
|
/* LAME psy model specific members */
|
|
float attack_threshold; ///< attack threshold for this channel
|
|
float prev_energy_subshort[AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS];
|
|
float next_win_level[AAC_NUM_BLOCKS_SHORT]; ///< lookahead short-window peak levels (grouping homogeneity)
|
|
float dif_env_hist[PSY_LAME_HIST]; ///< rolling first-difference sub-block peak envelope (HF novelty)
|
|
float hp_env_hist[PSY_LAME_HIST]; ///< rolling HP sub-block peak envelope
|
|
float raw_env_hist[PSY_LAME_HIST]; ///< rolling broadband sub-block peak envelope
|
|
float gap_wall; ///< decaying broadband peak-hold (gap-onset reference)
|
|
float gap_wall_hp; ///< decaying HP peak-hold (gap-onset reference)
|
|
int prev_attack; ///< attack value for the last short block in the previous sequence
|
|
int next_attack0_zero; ///< whether attack[0] of the next frame is zero
|
|
int frames_since_short; ///< consecutive long frames (pre-echo-aware isolated-onset gate)
|
|
float prev_frame_energy; ///< previous frame's full-band lookahead energy (attack veto)
|
|
int64_t win_count; ///< window() calls so far (frame counter for pair sync)
|
|
int64_t last_att; ///< win_count value of this channel's last own attack
|
|
|
|
/* rate-loop re-analysis rewind state, see psy_3gpp_analyze() */
|
|
int64_t rc_frame_num; ///< frame this channel last saved rewind state for
|
|
AacPsyBand rc_prev_band[128]; ///< prev_band as it was entering the frame
|
|
}AacPsyChannel;
|
|
|
|
/**
|
|
* psychoacoustic model frame type-dependent coefficients
|
|
*/
|
|
typedef struct AacPsyCoeffs{
|
|
float ath; ///< absolute threshold of hearing per bands
|
|
float barks; ///< Bark value for each spectral band in long frame
|
|
float spread_low[2]; ///< spreading factor for low-to-high threshold spreading in long frame
|
|
float spread_hi [2]; ///< spreading factor for high-to-low threshold spreading in long frame
|
|
float min_snr; ///< minimal SNR
|
|
}AacPsyCoeffs;
|
|
|
|
/**
|
|
* 3GPP TS26.403-inspired psychoacoustic model specific data
|
|
*/
|
|
typedef struct AacPsyContext{
|
|
int chan_bitrate; ///< bitrate per channel
|
|
int frame_bits; ///< average bits per frame
|
|
int fill_level; ///< bit reservoir fill level
|
|
struct {
|
|
float min; ///< minimum allowed PE for bit factor calculation
|
|
float max; ///< maximum allowed PE for bit factor calculation
|
|
float previous; ///< allowed PE of the previous frame
|
|
float correction; ///< PE correction factor
|
|
} pe;
|
|
AacPsyCoeffs psy_coef[2][64];
|
|
AacPsyChannel *ch;
|
|
float global_quality; ///< normalized global quality taken from avctx
|
|
|
|
/* rate-loop re-analysis rewind state, see psy_3gpp_analyze() */
|
|
int64_t rc_frame_num; ///< frame the rewind state was saved for
|
|
int rc_first_ch; ///< first channel analyzed in that frame
|
|
int rc_fill_level;
|
|
float rc_pe_min, rc_pe_max, rc_pe_previous;
|
|
}AacPsyContext;
|
|
|
|
/**
|
|
* LAME psy model preset struct
|
|
*/
|
|
typedef struct PsyLamePreset {
|
|
int quality; ///< Quality to map the rest of the values to.
|
|
/* This is overloaded to be both kbps per channel in ABR mode, and
|
|
* requested quality in constant quality mode.
|
|
*/
|
|
float st_lrm; ///< short threshold for L, R, and M channels
|
|
} PsyLamePreset;
|
|
|
|
/**
|
|
* LAME psy model preset table for ABR
|
|
*/
|
|
static const PsyLamePreset psy_abr_map[] = {
|
|
/* TODO: Tuning. These were taken from LAME. */
|
|
/* kbps/ch st_lrm */
|
|
{ 8, 7.60},
|
|
{ 16, 7.60},
|
|
{ 24, 7.60},
|
|
{ 32, 7.60},
|
|
{ 40, 7.60},
|
|
{ 48, 7.60},
|
|
{ 56, 7.60},
|
|
{ 64, 7.40},
|
|
{ 80, 7.00},
|
|
{ 96, 6.60},
|
|
{112, 6.20},
|
|
{128, 6.20},
|
|
{160, 6.20}
|
|
};
|
|
|
|
/**
|
|
* LAME psy model preset table for constant quality
|
|
*/
|
|
static const PsyLamePreset psy_vbr_map[] = {
|
|
/* vbr_q st_lrm */
|
|
{ 0, 4.20},
|
|
{ 1, 4.20},
|
|
{ 2, 4.20},
|
|
{ 3, 4.20},
|
|
{ 4, 4.20},
|
|
{ 5, 4.20},
|
|
{ 6, 4.20},
|
|
{ 7, 4.20},
|
|
{ 8, 4.20},
|
|
{ 9, 4.20},
|
|
{10, 4.20}
|
|
};
|
|
|
|
/**
|
|
* LAME psy model FIR coefficient table
|
|
*/
|
|
static const float psy_fir_coeffs[] = {
|
|
-8.65163e-18 * 2, -0.00851586 * 2, -6.74764e-18 * 2, 0.0209036 * 2,
|
|
-3.36639e-17 * 2, -0.0438162 * 2, -1.54175e-17 * 2, 0.0931738 * 2,
|
|
-5.52212e-17 * 2, -0.313819 * 2
|
|
};
|
|
|
|
/**
|
|
* Calculate the ABR attack threshold from the above LAME psymodel table.
|
|
*/
|
|
static float lame_calc_attack_threshold(int bitrate)
|
|
{
|
|
/* Assume max bitrate to start with */
|
|
int lower_range = 12, upper_range = 12;
|
|
int lower_range_kbps = psy_abr_map[12].quality;
|
|
int upper_range_kbps = psy_abr_map[12].quality;
|
|
int i;
|
|
|
|
/* Determine which bitrates the value specified falls between.
|
|
* If the loop ends without breaking our above assumption of 320kbps was correct.
|
|
*/
|
|
for (i = 1; i < 13; i++) {
|
|
if (FFMAX(bitrate, psy_abr_map[i].quality) != bitrate) {
|
|
upper_range = i;
|
|
upper_range_kbps = psy_abr_map[i ].quality;
|
|
lower_range = i - 1;
|
|
lower_range_kbps = psy_abr_map[i - 1].quality;
|
|
break; /* Upper range found */
|
|
}
|
|
}
|
|
|
|
/* Determine which range the value specified is closer to */
|
|
if ((upper_range_kbps - bitrate) > (bitrate - lower_range_kbps))
|
|
return psy_abr_map[lower_range].st_lrm;
|
|
return psy_abr_map[upper_range].st_lrm;
|
|
}
|
|
|
|
/**
|
|
* LAME psy model specific initialization
|
|
*/
|
|
static av_cold void lame_window_init(FFPsyContext *fctx, AacPsyContext *ctx, AVCodecContext *avctx)
|
|
{
|
|
int i, j;
|
|
|
|
for (i = 0; i < avctx->ch_layout.nb_channels; i++) {
|
|
AacPsyChannel *pch = &ctx->ch[i];
|
|
|
|
if ((avctx->flags & AV_CODEC_FLAG_QSCALE) || fctx->unbounded_pe)
|
|
/* quality-target coders (VBR and ABR) switch windows for quality,
|
|
* not rate: use the quality attack map regardless of bit_rate */
|
|
pch->attack_threshold = psy_vbr_map[av_clip(avctx->global_quality / FF_QP2LAMBDA, 0, 10)].st_lrm;
|
|
else
|
|
pch->attack_threshold = lame_calc_attack_threshold(avctx->bit_rate / avctx->ch_layout.nb_channels / 1000);
|
|
|
|
for (j = 0; j < AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS; j++)
|
|
pch->prev_energy_subshort[j] = 10.0f;
|
|
for (j = 0; j < PSY_LAME_HIST; j++)
|
|
pch->hp_env_hist[j] = pch->raw_env_hist[j] = pch->dif_env_hist[j] = 10.0f;
|
|
pch->gap_wall = pch->gap_wall_hp = 0.0f;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Calculate Bark value for given line.
|
|
*/
|
|
static av_cold float calc_bark(float f)
|
|
{
|
|
return 13.3f * atanf(0.00076f * f) + 3.5f * atanf((f / 7500.0f) * (f / 7500.0f));
|
|
}
|
|
|
|
#define ATH_ADD 4
|
|
/**
|
|
* Calculate ATH value for given frequency.
|
|
* Borrowed from Lame.
|
|
*/
|
|
static av_cold float ath(float f, float add)
|
|
{
|
|
f /= 1000.0f;
|
|
return 3.64 * pow(f, -0.8)
|
|
- 6.8 * exp(-0.6 * (f - 3.4) * (f - 3.4))
|
|
+ 6.0 * exp(-0.15 * (f - 8.7) * (f - 8.7))
|
|
+ (0.6 + 0.04 * add) * 0.001 * f * f * f * f;
|
|
}
|
|
|
|
static av_cold int psy_3gpp_init(FFPsyContext *ctx) {
|
|
AacPsyContext *pctx;
|
|
float bark;
|
|
int i, j, g, start;
|
|
float prev, minscale, minath, minsnr, pe_min;
|
|
int chan_bitrate = ctx->avctx->bit_rate / ((ctx->avctx->flags & AV_CODEC_FLAG_QSCALE) ? 2.0f : ctx->avctx->ch_layout.nb_channels);
|
|
|
|
const int bandwidth = ctx->cutoff ? ctx->cutoff : AAC_CUTOFF(ctx->avctx);
|
|
const float num_bark = calc_bark((float)bandwidth);
|
|
|
|
if (bandwidth <= 0)
|
|
return AVERROR(EINVAL);
|
|
|
|
ctx->model_priv_data = av_mallocz(sizeof(AacPsyContext));
|
|
if (!ctx->model_priv_data)
|
|
return AVERROR(ENOMEM);
|
|
pctx = ctx->model_priv_data;
|
|
pctx->global_quality = (ctx->avctx->global_quality ? ctx->avctx->global_quality : 120) * 0.01f;
|
|
|
|
if (ctx->avctx->flags & AV_CODEC_FLAG_QSCALE) {
|
|
/* Use the target average bitrate to compute spread parameters */
|
|
chan_bitrate = (int)(chan_bitrate / 120.0 * (ctx->avctx->global_quality ? ctx->avctx->global_quality : 120));
|
|
}
|
|
|
|
pctx->chan_bitrate = chan_bitrate;
|
|
pctx->frame_bits = FFMIN(2560, chan_bitrate * AAC_BLOCK_SIZE_LONG / ctx->avctx->sample_rate);
|
|
pctx->pe.min = 8.0f * AAC_BLOCK_SIZE_LONG * bandwidth / (ctx->avctx->sample_rate * 2.0f);
|
|
pctx->pe.max = 12.0f * AAC_BLOCK_SIZE_LONG * bandwidth / (ctx->avctx->sample_rate * 2.0f);
|
|
ctx->bitres.size = 6144 - pctx->frame_bits;
|
|
ctx->bitres.size -= ctx->bitres.size % 8;
|
|
pctx->fill_level = ctx->bitres.size;
|
|
minath = ath(3410 - 0.733 * ATH_ADD, ATH_ADD);
|
|
for (j = 0; j < 2; j++) {
|
|
AacPsyCoeffs *coeffs = pctx->psy_coef[j];
|
|
const uint8_t *band_sizes = ctx->bands[j];
|
|
float line_to_frequency = ctx->avctx->sample_rate / (j ? 256.f : 2048.0f);
|
|
float avg_chan_bits = chan_bitrate * (j ? 128.0f : 1024.0f) / ctx->avctx->sample_rate;
|
|
/* reference encoder uses 2.4% here instead of 60% like the spec says */
|
|
float bark_pe = 0.024f * PSY_3GPP_BITS_TO_PE(avg_chan_bits) / num_bark;
|
|
float en_spread_low = j ? PSY_3GPP_EN_SPREAD_LOW_S : PSY_3GPP_EN_SPREAD_LOW_L;
|
|
/* High energy spreading for long blocks <= 22kbps/channel and short blocks are the same. */
|
|
float en_spread_hi = (j || (chan_bitrate <= 22.0f)) ? PSY_3GPP_EN_SPREAD_HI_S : PSY_3GPP_EN_SPREAD_HI_L1;
|
|
|
|
i = 0;
|
|
prev = 0.0;
|
|
for (g = 0; g < ctx->num_bands[j]; g++) {
|
|
i += band_sizes[g];
|
|
bark = calc_bark((i-1) * line_to_frequency);
|
|
coeffs[g].barks = (bark + prev) / 2.0;
|
|
prev = bark;
|
|
}
|
|
for (g = 0; g < ctx->num_bands[j] - 1; g++) {
|
|
AacPsyCoeffs *coeff = &coeffs[g];
|
|
float bark_width = coeffs[g+1].barks - coeffs->barks;
|
|
coeff->spread_low[0] = ff_exp10(-bark_width * PSY_3GPP_THR_SPREAD_LOW);
|
|
coeff->spread_hi [0] = ff_exp10(-bark_width * PSY_3GPP_THR_SPREAD_HI);
|
|
coeff->spread_low[1] = ff_exp10(-bark_width * en_spread_low);
|
|
coeff->spread_hi [1] = ff_exp10(-bark_width * en_spread_hi);
|
|
pe_min = bark_pe * bark_width;
|
|
minsnr = exp2(pe_min / band_sizes[g]) - 1.5f;
|
|
coeff->min_snr = av_clipf(1.0f / minsnr, PSY_SNR_25DB, PSY_SNR_1DB);
|
|
}
|
|
start = 0;
|
|
for (g = 0; g < ctx->num_bands[j]; g++) {
|
|
minscale = ath(start * line_to_frequency, ATH_ADD);
|
|
for (i = 1; i < band_sizes[g]; i++)
|
|
minscale = FFMIN(minscale, ath((start + i) * line_to_frequency, ATH_ADD));
|
|
coeffs[g].ath = minscale - minath;
|
|
start += band_sizes[g];
|
|
}
|
|
}
|
|
|
|
pctx->ch = av_calloc(ctx->avctx->ch_layout.nb_channels, sizeof(*pctx->ch));
|
|
if (!pctx->ch) {
|
|
av_freep(&ctx->model_priv_data);
|
|
return AVERROR(ENOMEM);
|
|
}
|
|
|
|
pctx->rc_frame_num = -1;
|
|
for (i = 0; i < ctx->avctx->ch_layout.nb_channels; i++)
|
|
pctx->ch[i].rc_frame_num = -1;
|
|
|
|
lame_window_init(ctx, pctx, ctx->avctx);
|
|
|
|
return 0;
|
|
}
|
|
|
|
/**
|
|
* IIR filter used in block switching decision
|
|
*/
|
|
static float iir_filter(int in, float state[2])
|
|
{
|
|
float ret;
|
|
|
|
ret = 0.7548f * (in - state[0]) + 0.5095f * state[1];
|
|
state[0] = in;
|
|
state[1] = ret;
|
|
return ret;
|
|
}
|
|
|
|
/**
|
|
* window grouping information stored as bits (0 - new group, 1 - group continues)
|
|
*/
|
|
static const uint8_t window_grouping[9] = {
|
|
0xB6, 0x6C, 0xD8, 0xB2, 0x66, 0xC6, 0x96, 0x36, 0x36
|
|
};
|
|
|
|
/**
|
|
* Tell encoder which window types to use.
|
|
* @see 3GPP TS26.403 5.4.1 "Blockswitching"
|
|
*/
|
|
av_unused static FFPsyWindowInfo psy_3gpp_window(FFPsyContext *ctx,
|
|
const int16_t *audio,
|
|
const int16_t *la,
|
|
int channel, int prev_type)
|
|
{
|
|
int i, j;
|
|
int br = ((AacPsyContext*)ctx->model_priv_data)->chan_bitrate;
|
|
int attack_ratio = br <= 16000 ? 18 : 10;
|
|
AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
|
|
AacPsyChannel *pch = &pctx->ch[channel];
|
|
uint8_t grouping = 0;
|
|
int next_type = pch->next_window_seq;
|
|
FFPsyWindowInfo wi = { { 0 } };
|
|
|
|
if (la) {
|
|
float s[8], v;
|
|
int switch_to_eight = 0;
|
|
float sum = 0.0, sum2 = 0.0;
|
|
int attack_n = 0;
|
|
int stay_short = 0;
|
|
for (i = 0; i < 8; i++) {
|
|
for (j = 0; j < 128; j++) {
|
|
v = iir_filter(la[i*128+j], pch->iir_state);
|
|
sum += v*v;
|
|
}
|
|
s[i] = sum;
|
|
sum2 += sum;
|
|
}
|
|
for (i = 0; i < 8; i++) {
|
|
if (s[i] > pch->win_energy * attack_ratio) {
|
|
attack_n = i + 1;
|
|
switch_to_eight = 1;
|
|
break;
|
|
}
|
|
}
|
|
pch->win_energy = pch->win_energy*7/8 + sum2/64;
|
|
|
|
wi.window_type[1] = prev_type;
|
|
switch (prev_type) {
|
|
case ONLY_LONG_SEQUENCE:
|
|
wi.window_type[0] = switch_to_eight ? LONG_START_SEQUENCE : ONLY_LONG_SEQUENCE;
|
|
next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : ONLY_LONG_SEQUENCE;
|
|
break;
|
|
case LONG_START_SEQUENCE:
|
|
wi.window_type[0] = EIGHT_SHORT_SEQUENCE;
|
|
grouping = pch->next_grouping;
|
|
next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : LONG_STOP_SEQUENCE;
|
|
break;
|
|
case LONG_STOP_SEQUENCE:
|
|
wi.window_type[0] = switch_to_eight ? LONG_START_SEQUENCE : ONLY_LONG_SEQUENCE;
|
|
next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : ONLY_LONG_SEQUENCE;
|
|
break;
|
|
case EIGHT_SHORT_SEQUENCE:
|
|
stay_short = next_type == EIGHT_SHORT_SEQUENCE || switch_to_eight;
|
|
wi.window_type[0] = stay_short ? EIGHT_SHORT_SEQUENCE : LONG_STOP_SEQUENCE;
|
|
grouping = next_type == EIGHT_SHORT_SEQUENCE ? pch->next_grouping : 0;
|
|
next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : LONG_STOP_SEQUENCE;
|
|
break;
|
|
}
|
|
|
|
pch->next_grouping = window_grouping[attack_n];
|
|
pch->next_window_seq = next_type;
|
|
} else {
|
|
for (i = 0; i < 3; i++)
|
|
wi.window_type[i] = prev_type;
|
|
grouping = (prev_type == EIGHT_SHORT_SEQUENCE) ? window_grouping[0] : 0;
|
|
}
|
|
|
|
wi.window_shape = 1;
|
|
if (wi.window_type[0] != EIGHT_SHORT_SEQUENCE) {
|
|
wi.num_windows = 1;
|
|
wi.grouping[0] = 1;
|
|
} else {
|
|
int lastgrp = 0;
|
|
wi.num_windows = 8;
|
|
for (i = 0; i < 8; i++) {
|
|
if (!((grouping >> i) & 1))
|
|
lastgrp = i;
|
|
wi.grouping[lastgrp]++;
|
|
}
|
|
}
|
|
|
|
return wi;
|
|
}
|
|
|
|
/* 5.6.1.2 "Calculation of Bit Demand" */
|
|
static int calc_bit_demand(AacPsyContext *ctx, float pe, int bits, int size,
|
|
int short_window)
|
|
{
|
|
const float bitsave_slope = short_window ? PSY_3GPP_SAVE_SLOPE_S : PSY_3GPP_SAVE_SLOPE_L;
|
|
const float bitsave_add = short_window ? PSY_3GPP_SAVE_ADD_S : PSY_3GPP_SAVE_ADD_L;
|
|
const float bitspend_slope = short_window ? PSY_3GPP_SPEND_SLOPE_S : PSY_3GPP_SPEND_SLOPE_L;
|
|
const float bitspend_add = short_window ? PSY_3GPP_SPEND_ADD_S : PSY_3GPP_SPEND_ADD_L;
|
|
const float clip_low = short_window ? PSY_3GPP_CLIP_LO_S : PSY_3GPP_CLIP_LO_L;
|
|
const float clip_high = short_window ? PSY_3GPP_CLIP_HI_S : PSY_3GPP_CLIP_HI_L;
|
|
float clipped_pe, bit_save, bit_spend, bit_factor, fill_level, forgetful_min_pe;
|
|
|
|
ctx->fill_level += ctx->frame_bits - bits;
|
|
ctx->fill_level = av_clip(ctx->fill_level, 0, size);
|
|
fill_level = av_clipf((float)ctx->fill_level / size, clip_low, clip_high);
|
|
clipped_pe = av_clipf(pe, ctx->pe.min, ctx->pe.max);
|
|
bit_save = (fill_level + bitsave_add) * bitsave_slope;
|
|
assert(bit_save <= 0.3f && bit_save >= -0.05000001f);
|
|
bit_spend = (fill_level + bitspend_add) * bitspend_slope;
|
|
assert(bit_spend <= 0.5f && bit_spend >= -0.1f);
|
|
/* The bit factor graph in the spec is obviously incorrect.
|
|
* bit_spend + ((bit_spend - bit_spend))...
|
|
* The reference encoder subtracts everything from 1, but also seems incorrect.
|
|
* 1 - bit_save + ((bit_spend + bit_save))...
|
|
* Hopefully below is correct.
|
|
*/
|
|
bit_factor = 1.0f - bit_save + ((bit_spend - bit_save) / (ctx->pe.max - ctx->pe.min)) * (clipped_pe - ctx->pe.min);
|
|
bit_factor = 1.0f + (bit_factor - 1.0f) * PSY_3GPP_DEMAND_SCALE;
|
|
/* NOTE: The reference encoder attempts to center pe max/min around the current pe.
|
|
* Here we do that by slowly forgetting pe.min when pe stays in a range that makes
|
|
* it unlikely (ie: above the mean)
|
|
*/
|
|
ctx->pe.max = FFMAX(pe, ctx->pe.max);
|
|
forgetful_min_pe = ((ctx->pe.min * PSY_PE_FORGET_SLOPE)
|
|
+ FFMAX(ctx->pe.min, pe * (pe / ctx->pe.max))) / (PSY_PE_FORGET_SLOPE + 1);
|
|
ctx->pe.min = FFMIN(pe, forgetful_min_pe);
|
|
|
|
/* NOTE: allocate a minimum of 1/8th average frame bits, to avoid
|
|
* reservoir starvation from producing zero-bit frames
|
|
*/
|
|
return FFMIN(
|
|
ctx->frame_bits * bit_factor,
|
|
FFMAX(ctx->frame_bits + size - bits, ctx->frame_bits / 8));
|
|
}
|
|
|
|
static float calc_pe_3gpp(AacPsyBand *band)
|
|
{
|
|
float pe, a;
|
|
|
|
band->pe = 0.0f;
|
|
band->pe_const = 0.0f;
|
|
band->active_lines = 0.0f;
|
|
if (band->energy > band->thr) {
|
|
a = log2f(band->energy);
|
|
pe = a - log2f(band->thr);
|
|
band->active_lines = band->nz_lines;
|
|
if (pe < PSY_3GPP_C1) {
|
|
pe = pe * PSY_3GPP_C3 + PSY_3GPP_C2;
|
|
a = a * PSY_3GPP_C3 + PSY_3GPP_C2;
|
|
band->active_lines *= PSY_3GPP_C3;
|
|
}
|
|
band->pe = pe * band->nz_lines;
|
|
band->pe_const = a * band->nz_lines;
|
|
}
|
|
|
|
return band->pe;
|
|
}
|
|
|
|
static float calc_reduction_3gpp(float a, float desired_pe, float pe,
|
|
float active_lines)
|
|
{
|
|
float thr_avg, reduction;
|
|
|
|
if(active_lines == 0.0)
|
|
return 0;
|
|
|
|
thr_avg = exp2f((a - pe) / (4.0f * active_lines));
|
|
reduction = exp2f((a - desired_pe) / (4.0f * active_lines)) - thr_avg;
|
|
|
|
return FFMAX(reduction, 0.0f);
|
|
}
|
|
|
|
static float calc_reduced_thr_3gpp(AacPsyBand *band, float min_snr,
|
|
float reduction)
|
|
{
|
|
float thr = band->thr;
|
|
|
|
if (band->energy > thr) {
|
|
thr = sqrtf(thr);
|
|
thr = sqrtf(thr) + reduction;
|
|
thr *= thr;
|
|
thr *= thr;
|
|
|
|
/* This deviates from the 3GPP spec to match the reference encoder.
|
|
* It performs min(thr_reduced, max(thr, energy/min_snr)) only for bands
|
|
* that have hole avoidance on (active or inactive). It always reduces the
|
|
* threshold of bands with hole avoidance off.
|
|
*/
|
|
if (thr > band->energy * min_snr && band->avoid_holes != PSY_3GPP_AH_NONE) {
|
|
thr = FFMAX(band->thr, band->energy * min_snr);
|
|
band->avoid_holes = PSY_3GPP_AH_ACTIVE;
|
|
}
|
|
}
|
|
|
|
return thr;
|
|
}
|
|
|
|
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)
|
|
{
|
|
int i, w, g;
|
|
int start = 0, wstart = 0;
|
|
for (w = 0; w < wi->num_windows*16; w += 16) {
|
|
wstart = 0;
|
|
for (g = 0; g < num_bands; g++) {
|
|
AacPsyBand *band = &pch->band[w+g];
|
|
|
|
float form_factor = 0.0f;
|
|
float Temp;
|
|
band->energy = 0.0f;
|
|
if (wstart < cutoff) {
|
|
for (i = 0; i < band_sizes[g]; i++) {
|
|
band->energy += coefs[start+i] * coefs[start+i];
|
|
form_factor += sqrtf(fabs(coefs[start+i]));
|
|
}
|
|
}
|
|
Temp = band->energy > 0 ? sqrtf((float)band_sizes[g] / band->energy) : 0;
|
|
band->thr = band->energy * 0.001258925f;
|
|
band->nz_lines = form_factor * sqrtf(Temp);
|
|
|
|
start += band_sizes[g];
|
|
wstart += band_sizes[g];
|
|
}
|
|
}
|
|
}
|
|
|
|
static void psy_hp_filter(const float *firbuf, float *hpfsmpl, const float *psy_fir_coeffs)
|
|
{
|
|
int i, j;
|
|
for (i = 0; i < AAC_BLOCK_SIZE_LONG; i++) {
|
|
float sum1, sum2;
|
|
sum1 = firbuf[i + (PSY_LAME_FIR_LEN - 1) / 2];
|
|
sum2 = 0.0;
|
|
for (j = 0; j < ((PSY_LAME_FIR_LEN - 1) / 2) - 1; j += 2) {
|
|
sum1 += psy_fir_coeffs[j] * (firbuf[i + j] + firbuf[i + PSY_LAME_FIR_LEN - j]);
|
|
sum2 += psy_fir_coeffs[j + 1] * (firbuf[i + j + 1] + firbuf[i + PSY_LAME_FIR_LEN - j - 1]);
|
|
}
|
|
/* NOTE: The LAME psymodel expects it's input in the range -32768 to 32768.
|
|
* Tuning this for normalized floats would be difficult. */
|
|
hpfsmpl[i] = (sum1 + sum2) * 32768.0f;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Calculate band thresholds as suggested in 3GPP TS26.403
|
|
*/
|
|
static void psy_3gpp_analyze_channel(FFPsyContext *ctx, int channel,
|
|
const float *coefs, const FFPsyWindowInfo *wi)
|
|
{
|
|
AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
|
|
AacPsyChannel *pch = &pctx->ch[channel];
|
|
int i, w, g;
|
|
float desired_bits, desired_pe, delta_pe, reduction= NAN, spread_en[128] = {0};
|
|
float a = 0.0f, active_lines = 0.0f, norm_fac = 0.0f;
|
|
float pe = pctx->chan_bitrate > 32000 ? 0.0f : FFMAX(50.0f, 100.0f - pctx->chan_bitrate * 100.0f / 32000.0f);
|
|
const int num_bands = ctx->num_bands[wi->num_windows == 8];
|
|
const uint8_t *band_sizes = ctx->bands[wi->num_windows == 8];
|
|
uint8_t s2l[16] = {0};
|
|
int start_after_long = wi->num_windows == 8 &&
|
|
wi->window_type[1] == LONG_START_SEQUENCE;
|
|
{ /* short->long grid band map for cross-transition pre-echo control */
|
|
if (start_after_long) {
|
|
const uint8_t *ls = ctx->bands[0];
|
|
const int ln = ctx->num_bands[0];
|
|
const uint8_t *ss = ctx->bands[1];
|
|
int lacc = 0, sacc = 0, gl = 0;
|
|
for (int gs = 0; gs < num_bands && gs < 16; gs++) {
|
|
int center8 = (sacc + ss[gs] / 2) * 8;
|
|
while (gl < ln - 1 && lacc + ls[gl] <= center8) { lacc += ls[gl]; gl++; }
|
|
s2l[gs] = gl;
|
|
sacc += ss[gs];
|
|
}
|
|
}
|
|
}
|
|
AacPsyCoeffs *coeffs = pctx->psy_coef[wi->num_windows == 8];
|
|
const float avoid_hole_thr = wi->num_windows == 8 ? PSY_3GPP_AH_THR_SHORT : PSY_3GPP_AH_THR_LONG;
|
|
const int bandwidth = ctx->cutoff ? ctx->cutoff : AAC_CUTOFF(ctx->avctx);
|
|
const int cutoff = bandwidth * 2048 / wi->num_windows / ctx->avctx->sample_rate;
|
|
|
|
//calculate energies, initial thresholds and related values - 5.4.2 "Threshold Calculation"
|
|
calc_thr_3gpp(wi, num_bands, pch, band_sizes, coefs, cutoff);
|
|
|
|
//modify thresholds and energies - spread, threshold in quiet, pre-echo control
|
|
for (w = 0; w < wi->num_windows*16; w += 16) {
|
|
AacPsyBand *bands = &pch->band[w];
|
|
|
|
/* 5.4.2.3 "Spreading" & 5.4.3 "Spread Energy Calculation" */
|
|
spread_en[w] = bands[0].energy;
|
|
for (g = 1; g < num_bands; g++) {
|
|
bands[g].thr = FFMAX(bands[g].thr, bands[g-1].thr * coeffs[g].spread_hi[0]);
|
|
spread_en[w+g] = FFMAX(bands[g].energy, spread_en[w+g-1] * coeffs[g].spread_hi[1]);
|
|
}
|
|
for (g = num_bands - 2; g >= 0; g--) {
|
|
bands[g].thr = FFMAX(bands[g].thr, bands[g+1].thr * coeffs[g].spread_low[0]);
|
|
spread_en[w+g] = FFMAX(spread_en[w+g], spread_en[w+g+1] * coeffs[g].spread_low[1]);
|
|
}
|
|
//5.4.2.4 "Threshold in quiet"
|
|
for (g = 0; g < num_bands; g++) {
|
|
AacPsyBand *band = &bands[g];
|
|
|
|
band->thr_quiet = band->thr = FFMAX(band->thr, coeffs[g].ath);
|
|
//5.4.2.5 "Pre-echo control"
|
|
if (!(wi->window_type[0] == LONG_STOP_SEQUENCE || (!w && wi->window_type[1] == LONG_START_SEQUENCE)))
|
|
band->thr = FFMAX(PSY_3GPP_RPEMIN*band->thr, FFMIN(band->thr,
|
|
PSY_3GPP_RPELEV*pch->prev_band[w+g].thr_quiet));
|
|
else if (!w && start_after_long)
|
|
/* w0 after a START frame: grid-mapped, scaled continuity
|
|
* clamp instead of the spec's skip (cannot bind on noise
|
|
* content - see memory - but correct for tonal) */
|
|
band->thr = FFMAX(PSY_3GPP_RPEMIN*band->thr, FFMIN(band->thr,
|
|
PSY_3GPP_RPELEV*pch->prev_band[s2l[FFMIN(g,15)]].thr / 8.0f));
|
|
|
|
/* 5.6.1.3.1 "Preparatory steps of the perceptual entropy calculation" */
|
|
pe += calc_pe_3gpp(band);
|
|
a += band->pe_const;
|
|
active_lines += band->active_lines;
|
|
|
|
/* 5.6.1.3.3 "Selection of the bands for avoidance of holes" */
|
|
if (spread_en[w+g] * avoid_hole_thr > band->energy || coeffs[g].min_snr > 1.0f)
|
|
band->avoid_holes = PSY_3GPP_AH_NONE;
|
|
else
|
|
band->avoid_holes = PSY_3GPP_AH_INACTIVE;
|
|
}
|
|
}
|
|
|
|
/* 5.6.1.3.2 "Calculation of the desired perceptual entropy" */
|
|
ctx->ch[channel].entropy = pe;
|
|
if (ctx->unbounded_pe) {
|
|
/* quality-target coder: run the PE reduction at a FIXED reference
|
|
* quality so thresholds keep their perceptual shaping but stay
|
|
* independent of the user's -q:a (the coder's own noise-to-mask
|
|
* target is the sole quality authority) */
|
|
desired_pe = pe * 120.0f / (2 * 2.5f * 120.0f);
|
|
desired_bits = FFMIN(2560, PSY_3GPP_PE_TO_BITS(desired_pe));
|
|
desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits);
|
|
pctx->pe.max = FFMAX(pe, pctx->pe.max);
|
|
pctx->pe.min = FFMIN(pe, pctx->pe.min);
|
|
} else if (ctx->avctx->flags & AV_CODEC_FLAG_QSCALE) {
|
|
/* (2.5 * 120) achieves almost transparent rate, and we want to give
|
|
* ample room downwards, so we make that equivalent to QSCALE=2.4
|
|
*/
|
|
desired_pe = pe * (ctx->avctx->global_quality ? ctx->avctx->global_quality : 120) / (2 * 2.5f * 120.0f);
|
|
desired_bits = FFMIN(2560, PSY_3GPP_PE_TO_BITS(desired_pe));
|
|
desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits); // reflect clipping
|
|
|
|
/* PE slope smoothing */
|
|
if (ctx->bitres.bits > 0) {
|
|
desired_bits = FFMIN(2560, PSY_3GPP_PE_TO_BITS(desired_pe));
|
|
desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits); // reflect clipping
|
|
}
|
|
|
|
pctx->pe.max = FFMAX(pe, pctx->pe.max);
|
|
pctx->pe.min = FFMIN(pe, pctx->pe.min);
|
|
} else {
|
|
desired_bits = calc_bit_demand(pctx, pe, ctx->bitres.bits, ctx->bitres.size, wi->num_windows == 8);
|
|
desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits);
|
|
|
|
/* NOTE: PE correction is kept simple. During initial testing it had very
|
|
* little effect on the final bitrate. Probably a good idea to come
|
|
* back and do more testing later.
|
|
*/
|
|
if (ctx->bitres.bits > 0) {
|
|
/* symmetric in the log domain: a negative previous demand (see
|
|
* PSY_3GPP_DEMAND_SCALE) sits on the lower bound, and the
|
|
* asymmetric 0.85 there costs ~2% Zimtohrli at 64 kbps */
|
|
desired_pe *= av_clipf(pctx->pe.previous / PSY_3GPP_BITS_TO_PE(ctx->bitres.bits),
|
|
1.0f / 1.15f, 1.15f);
|
|
}
|
|
}
|
|
pctx->pe.previous = PSY_3GPP_BITS_TO_PE(desired_bits);
|
|
ctx->bitres.alloc = desired_bits;
|
|
|
|
if (desired_pe < pe) {
|
|
/* 5.6.1.3.4 "First Estimation of the reduction value" */
|
|
for (w = 0; w < wi->num_windows*16; w += 16) {
|
|
reduction = calc_reduction_3gpp(a, desired_pe, pe, active_lines);
|
|
pe = 0.0f;
|
|
a = 0.0f;
|
|
active_lines = 0.0f;
|
|
for (g = 0; g < num_bands; g++) {
|
|
AacPsyBand *band = &pch->band[w+g];
|
|
|
|
band->thr = calc_reduced_thr_3gpp(band, coeffs[g].min_snr, reduction);
|
|
/* recalculate PE */
|
|
pe += calc_pe_3gpp(band);
|
|
a += band->pe_const;
|
|
active_lines += band->active_lines;
|
|
}
|
|
}
|
|
|
|
/* 5.6.1.3.5 "Second Estimation of the reduction value" */
|
|
for (i = 0; i < 2; i++) {
|
|
float pe_no_ah = 0.0f, desired_pe_no_ah;
|
|
active_lines = a = 0.0f;
|
|
for (w = 0; w < wi->num_windows*16; w += 16) {
|
|
for (g = 0; g < num_bands; g++) {
|
|
AacPsyBand *band = &pch->band[w+g];
|
|
|
|
if (band->avoid_holes != PSY_3GPP_AH_ACTIVE) {
|
|
pe_no_ah += band->pe;
|
|
a += band->pe_const;
|
|
active_lines += band->active_lines;
|
|
}
|
|
}
|
|
}
|
|
desired_pe_no_ah = FFMAX(desired_pe - (pe - pe_no_ah), 0.0f);
|
|
if (active_lines > 0.0f)
|
|
reduction = calc_reduction_3gpp(a, desired_pe_no_ah, pe_no_ah, active_lines);
|
|
|
|
pe = 0.0f;
|
|
for (w = 0; w < wi->num_windows*16; w += 16) {
|
|
for (g = 0; g < num_bands; g++) {
|
|
AacPsyBand *band = &pch->band[w+g];
|
|
|
|
if (active_lines > 0.0f)
|
|
band->thr = calc_reduced_thr_3gpp(band, coeffs[g].min_snr, reduction);
|
|
pe += calc_pe_3gpp(band);
|
|
if (band->thr > 0.0f)
|
|
band->norm_fac = band->active_lines / band->thr;
|
|
else
|
|
band->norm_fac = 0.0f;
|
|
norm_fac += band->norm_fac;
|
|
}
|
|
}
|
|
delta_pe = desired_pe - pe;
|
|
if (fabs(delta_pe) > 0.05f * desired_pe)
|
|
break;
|
|
}
|
|
|
|
if (pe < 1.15f * desired_pe) {
|
|
/* 6.6.1.3.6 "Final threshold modification by linearization" */
|
|
norm_fac = norm_fac ? 1.0f / norm_fac : 0;
|
|
for (w = 0; w < wi->num_windows*16; w += 16) {
|
|
for (g = 0; g < num_bands; g++) {
|
|
AacPsyBand *band = &pch->band[w+g];
|
|
|
|
if (band->active_lines > 0.5f) {
|
|
float delta_sfb_pe = band->norm_fac * norm_fac * delta_pe;
|
|
float thr = band->thr;
|
|
|
|
thr *= exp2f(delta_sfb_pe / band->active_lines);
|
|
if (thr > coeffs[g].min_snr * band->energy && band->avoid_holes == PSY_3GPP_AH_INACTIVE)
|
|
thr = FFMAX(band->thr, coeffs[g].min_snr * band->energy);
|
|
band->thr = thr;
|
|
}
|
|
}
|
|
}
|
|
} else {
|
|
/* 5.6.1.3.7 "Further perceptual entropy reduction" */
|
|
g = num_bands;
|
|
while (pe > desired_pe && g--) {
|
|
for (w = 0; w < wi->num_windows*16; w+= 16) {
|
|
AacPsyBand *band = &pch->band[w+g];
|
|
if (band->avoid_holes != PSY_3GPP_AH_NONE && coeffs[g].min_snr < PSY_SNR_1DB) {
|
|
coeffs[g].min_snr = PSY_SNR_1DB;
|
|
band->thr = band->energy * PSY_SNR_1DB;
|
|
pe += band->active_lines * 1.5f - band->pe;
|
|
}
|
|
}
|
|
}
|
|
/* TODO: allow more holes (unused without mid/side) */
|
|
}
|
|
}
|
|
|
|
/* Signal-relative mask ceiling. 5.6.1.3.3 exempts bands that are quiet
|
|
* relative to the spread energy from the min-SNR floor ("holes allowed
|
|
* here"), so on spectrally lopsided programme their mask is free to rise
|
|
* until it meets their own energy - the model then calls a band that
|
|
* carries real texture inaudible, and every consumer of the mask agrees:
|
|
* the allocator buys it nothing and the quality-target solver sees a mask
|
|
* it cannot fail. A band we still choose to code must never be allowed
|
|
* noise within PSY_THRFL_* dB of its own energy, whatever the hole logic said. */
|
|
{
|
|
int qmode = ctx->unbounded_pe || (ctx->avctx->flags & AV_CODEC_FLAG_QSCALE);
|
|
float lim = qmode ? PSY_THRFL_QUALITY : PSY_THRFL_CBR;
|
|
float knee = qmode ? 0.0f : PSY_THRFL_CBR_KNEE;
|
|
float lo = ff_exp10f(-lim / 10.0f);
|
|
float l2f = ctx->avctx->sample_rate / 2.0f /
|
|
(wi->num_windows == 1 ? 1024.0f : 128.0f);
|
|
for (w = 0; w < wi->num_windows*16; w += 16) {
|
|
int start = 0;
|
|
for (g = 0; g < num_bands; g++) {
|
|
AacPsyBand *band = &pch->band[w+g];
|
|
if (start * l2f >= knee)
|
|
band->thr = FFMIN(band->thr, band->energy * lo);
|
|
start += band_sizes[g];
|
|
}
|
|
}
|
|
}
|
|
|
|
for (w = 0; w < wi->num_windows*16; w += 16) {
|
|
for (g = 0; g < num_bands; g++) {
|
|
AacPsyBand *band = &pch->band[w+g];
|
|
FFPsyBand *psy_band = &ctx->ch[channel].psy_bands[w+g];
|
|
|
|
psy_band->threshold = band->thr;
|
|
psy_band->energy = band->energy;
|
|
psy_band->spread = band->active_lines * 2.0f / band_sizes[g];
|
|
psy_band->bits = PSY_3GPP_PE_TO_BITS(band->pe);
|
|
}
|
|
}
|
|
|
|
memcpy(pch->prev_band, pch->band, sizeof(pch->band));
|
|
}
|
|
|
|
static void psy_3gpp_analyze(FFPsyContext *ctx, int channel,
|
|
const float **coeffs, const FFPsyWindowInfo *wi)
|
|
{
|
|
int ch;
|
|
FFPsyChannelGroup *group = ff_psy_find_group(ctx, channel);
|
|
AacPsyContext *pctx = ctx->model_priv_data;
|
|
|
|
/* The encoder's rate-control loop may re-run the analysis for the same
|
|
* frame; carried state (bit reservoir, PE history, previous-frame
|
|
* thresholds) must advance exactly once per frame, so save it on the
|
|
* frame's first run and rewind on re-runs. */
|
|
if (ctx->avctx->frame_num != pctx->rc_frame_num) {
|
|
pctx->rc_frame_num = ctx->avctx->frame_num;
|
|
pctx->rc_first_ch = channel;
|
|
pctx->rc_fill_level = pctx->fill_level;
|
|
pctx->rc_pe_min = pctx->pe.min;
|
|
pctx->rc_pe_max = pctx->pe.max;
|
|
pctx->rc_pe_previous = pctx->pe.previous;
|
|
} else if (channel == pctx->rc_first_ch) {
|
|
pctx->fill_level = pctx->rc_fill_level;
|
|
pctx->pe.min = pctx->rc_pe_min;
|
|
pctx->pe.max = pctx->rc_pe_max;
|
|
pctx->pe.previous = pctx->rc_pe_previous;
|
|
}
|
|
|
|
for (ch = 0; ch < group->num_ch; ch++) {
|
|
AacPsyChannel *pch = &pctx->ch[channel + ch];
|
|
if (ctx->avctx->frame_num != pch->rc_frame_num) {
|
|
pch->rc_frame_num = ctx->avctx->frame_num;
|
|
memcpy(pch->rc_prev_band, pch->prev_band, sizeof(pch->prev_band));
|
|
} else {
|
|
memcpy(pch->prev_band, pch->rc_prev_band, sizeof(pch->prev_band));
|
|
}
|
|
psy_3gpp_analyze_channel(ctx, channel + ch, coeffs[ch], &wi[ch]);
|
|
}
|
|
}
|
|
|
|
static av_cold void psy_3gpp_end(FFPsyContext *apc)
|
|
{
|
|
AacPsyContext *pctx = (AacPsyContext*) apc->model_priv_data;
|
|
if (pctx)
|
|
av_freep(&pctx->ch);
|
|
av_freep(&apc->model_priv_data);
|
|
}
|
|
|
|
static void lame_apply_block_type(AacPsyChannel *ctx, FFPsyWindowInfo *wi, int uselongblock)
|
|
{
|
|
int blocktype = ONLY_LONG_SEQUENCE;
|
|
if (uselongblock) {
|
|
if (ctx->next_window_seq == EIGHT_SHORT_SEQUENCE)
|
|
blocktype = LONG_STOP_SEQUENCE;
|
|
} else {
|
|
blocktype = EIGHT_SHORT_SEQUENCE;
|
|
if (ctx->next_window_seq == ONLY_LONG_SEQUENCE)
|
|
ctx->next_window_seq = LONG_START_SEQUENCE;
|
|
if (ctx->next_window_seq == LONG_STOP_SEQUENCE)
|
|
ctx->next_window_seq = EIGHT_SHORT_SEQUENCE;
|
|
}
|
|
|
|
wi->window_type[0] = ctx->next_window_seq;
|
|
ctx->next_window_seq = blocktype;
|
|
}
|
|
|
|
/* Attack detection half of the LAME window decision: everything up to (and
|
|
* excluding) the block-type state machine. Fills attacks[] and returns the raw
|
|
* uselongblock; mutates only the detection history. Split out so a channel
|
|
* pair can be detected first and DECIDED together (synced block switching). */
|
|
static int psy_lame_detect(AacPsyContext *pctx, AacPsyChannel *pch,
|
|
const float *la, int channel, int prev_type,
|
|
int attacks[AAC_NUM_BLOCKS_SHORT + 1])
|
|
{
|
|
int uselongblock = 1;
|
|
int i;
|
|
|
|
if (la) {
|
|
float hpfsmpl[AAC_BLOCK_SIZE_LONG];
|
|
const float *pf = hpfsmpl;
|
|
float attack_intensity[(AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS];
|
|
float energy_subshort[(AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS];
|
|
float energy_short[AAC_NUM_BLOCKS_SHORT + 1] = { 0 };
|
|
const float *firbuf = la + (AAC_BLOCK_SIZE_SHORT/4 - PSY_LAME_FIR_LEN);
|
|
int att_sum = 0;
|
|
|
|
/* LAME comment: apply high pass filter of fs/4 */
|
|
psy_hp_filter(firbuf, hpfsmpl, psy_fir_coeffs);
|
|
|
|
/* Calculate the energies of each sub-shortblock */
|
|
for (i = 0; i < PSY_LAME_NUM_SUBBLOCKS; i++) {
|
|
energy_subshort[i] = pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 1) * PSY_LAME_NUM_SUBBLOCKS)];
|
|
assert(pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 1) * PSY_LAME_NUM_SUBBLOCKS - 2)] > 0);
|
|
attack_intensity[i] = energy_subshort[i] / pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 1) * PSY_LAME_NUM_SUBBLOCKS - 2)];
|
|
energy_short[0] += energy_subshort[i];
|
|
}
|
|
|
|
for (i = 0; i < AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS; i++) {
|
|
const float *const pfe = pf + AAC_BLOCK_SIZE_LONG / (AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS);
|
|
float p = 1.0f;
|
|
for (; pf < pfe; pf++)
|
|
p = FFMAX(p, fabsf(*pf));
|
|
pch->prev_energy_subshort[i] = energy_subshort[i + PSY_LAME_NUM_SUBBLOCKS] = p;
|
|
energy_short[1 + i / PSY_LAME_NUM_SUBBLOCKS] += p;
|
|
|
|
/* NOTE: The indexes below are [i + 3 - 2] in the LAME source. Compare each sub-block to sub-block - 2 */
|
|
if (p > energy_subshort[i + PSY_LAME_NUM_SUBBLOCKS - 2])
|
|
p = p / energy_subshort[i + PSY_LAME_NUM_SUBBLOCKS - 2];
|
|
else if (energy_subshort[i + PSY_LAME_NUM_SUBBLOCKS - 2] > p * 10.0f)
|
|
p = energy_subshort[i + PSY_LAME_NUM_SUBBLOCKS - 2] / (p * 10.0f);
|
|
else
|
|
p = 0.0;
|
|
|
|
attack_intensity[i + PSY_LAME_NUM_SUBBLOCKS] = p;
|
|
}
|
|
for (i = 0; i < AAC_NUM_BLOCKS_SHORT; i++)
|
|
pch->next_win_level[i] = energy_short[1 + i];
|
|
|
|
{ /* pre-echo-aware threshold relaxation + periodicity/novelty check
|
|
* (a pulse train repeats its peak; a real onset towers) */
|
|
float frame_peak = 1.0f;
|
|
float env[PSY_LAME_HIST + AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS];
|
|
float denv[PSY_LAME_HIST + AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS];
|
|
const float nov_gate = 1.25f;
|
|
/* first-difference peak per sub-block: an attack that shorts can
|
|
* help has HF novelty; a bass pluck under a long window does not */
|
|
memcpy(denv, pch->dif_env_hist, sizeof(pch->dif_env_hist));
|
|
{
|
|
const int sub = AAC_BLOCK_SIZE_LONG / (AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS);
|
|
for (i = 0; i < AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS; i++) {
|
|
float p = 0.0f;
|
|
for (int j2 = i*sub + 1; j2 < (i+1)*sub; j2++)
|
|
p = FFMAX(p, fabsf(la[j2] - la[j2-1]));
|
|
denv[PSY_LAME_HIST + i] = FFMAX(p * 32768.0f, 1.0f);
|
|
}
|
|
}
|
|
memcpy(pch->dif_env_hist, denv + AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS,
|
|
sizeof(pch->dif_env_hist));
|
|
memcpy(env,pch->hp_env_hist, sizeof(pch->hp_env_hist));
|
|
memcpy(env + PSY_LAME_HIST, energy_subshort + PSY_LAME_NUM_SUBBLOCKS,
|
|
AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS * sizeof(*env));
|
|
for (i = PSY_LAME_NUM_SUBBLOCKS; i < (AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS; i++)
|
|
frame_peak = FFMAX(frame_peak, energy_subshort[i]);
|
|
for (i = 0; i < (AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS; i++)
|
|
if (!attacks[i / PSY_LAME_NUM_SUBBLOCKS]) {
|
|
float thr = pch->attack_threshold;
|
|
if (i >= PSY_LAME_NUM_SUBBLOCKS &&
|
|
pch->frames_since_short >= PSY_LAME_PE_GAP &&
|
|
energy_subshort[i - PSY_LAME_NUM_SUBBLOCKS] < PSY_LAME_PE_QUIET * frame_peak)
|
|
thr *= PSY_LAME_PE_RED;
|
|
if (attack_intensity[i] > thr) {
|
|
/* An attack must tower over the recent HP envelope:
|
|
* within ~12ms always (pitch-rate trains), within
|
|
* ~44ms only from steady long-window state (slow
|
|
* pulse trains, where an isolated short excursion
|
|
* is an audible click). */
|
|
if (nov_gate > 0.0f && i >= PSY_LAME_NUM_SUBBLOCKS) {
|
|
const int pos = PSY_LAME_HIST + i - PSY_LAME_NUM_SUBBLOCKS;
|
|
float nearmax = 1.0f, deepmax = 1.0f;
|
|
for (int k = 3; k <= 8; k++)
|
|
nearmax = FFMAX(nearmax, env[pos - k]);
|
|
for (int k = 3; k <= PSY_LAME_NOV_BACK; k++)
|
|
deepmax = FFMAX(deepmax, env[pos - k]);
|
|
if (energy_subshort[i] < nov_gate * nearmax ||
|
|
(energy_subshort[i] < nov_gate * deepmax &&
|
|
pch->frames_since_short >= PSY_LAME_PE_GAP))
|
|
continue; /* periodic, not an onset */
|
|
}
|
|
if (i >= PSY_LAME_NUM_SUBBLOCKS) {
|
|
/* no HF novelty: pre-echo is masked by the
|
|
* sustained LF itself, and the short excursion
|
|
* (HF mute, then the stop frame's noisy HF
|
|
* hand-back) is the audible event. Both bars
|
|
* must agree: absolutely small AND relatively
|
|
* unremarkable - a quiet transient rising out
|
|
* of silence has a tiny derivative but maximal
|
|
* novelty, and its pre-echo lands on silence */
|
|
const int pos = PSY_LAME_HIST + i - PSY_LAME_NUM_SUBBLOCKS;
|
|
float dmax = 1.0f, premin = 1e30f;
|
|
for (int k = 1; k <= PSY_LAME_NOV_BACK; k++)
|
|
dmax = FFMAX(dmax, denv[pos - k]);
|
|
/* pre-echo audibility: the veto is only safe
|
|
* when the surroundings mask the smear - a deep
|
|
* dip right before a LOUD attack (stop-gap
|
|
* slams) means the long window's pre-echo lands
|
|
* on quiet. Quiet candidates keep the veto:
|
|
* their smear is at the noise floor, and shorts
|
|
* would only fragment the passage */
|
|
for (int k = 1; k <= 4; k++)
|
|
premin = FFMIN(premin, env[pos - k]);
|
|
if (denv[pos] < PSY_LAME_HFN_REL * dmax &&
|
|
denv[pos] < PSY_LAME_HFN_ABS &&
|
|
premin * PSY_LAME_HFN_PRE > energy_subshort[i])
|
|
continue;
|
|
}
|
|
attacks[i / PSY_LAME_NUM_SUBBLOCKS] = (i % PSY_LAME_NUM_SUBBLOCKS) + 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
/* should have energy change between short blocks, in order to avoid periodic signals */
|
|
/* Good samples to show the effect are Trumpet test songs */
|
|
/* GB: tuned (1) to avoid too many short blocks for test sample TRUMPET */
|
|
/* RH: tuned (2) to let enough short blocks through for test sample FSOL and SNAPS */
|
|
for (i = 1; i < AAC_NUM_BLOCKS_SHORT + 1; i++) {
|
|
const float u = energy_short[i - 1];
|
|
const float v = energy_short[i];
|
|
const float m = FFMAX(u, v);
|
|
if (m < 40000) { /* (2) */
|
|
if (u < 2.3f * v && v < 2.3f * u) { /* (1) */
|
|
if (i == 1 && attacks[0] < attacks[i])
|
|
attacks[0] = 0;
|
|
attacks[i] = 0;
|
|
}
|
|
}
|
|
att_sum += attacks[i];
|
|
}
|
|
|
|
{ /* Gap-onset detection on the broadband envelope: a slam that ends
|
|
* a quiet gap (stop-start riffing, kick after a break) can be
|
|
* invisible to the HP path - no content above fs/4, or a rise too
|
|
* gradual for the 2-sub-block ratio - yet pre-echo into the gap
|
|
* is maximally audible (no forward masking there). Fire when the
|
|
* candidate towers over a recent dip. Pulse trains cannot fire:
|
|
* their inter-pulse floor never dips far enough below the pulse. */
|
|
float renv[PSY_LAME_HIST + AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS];
|
|
/* scan both envelopes: broadband (kick+chug slams with LF
|
|
* dominance) and HP (events whose gap only exists above the
|
|
* sustained bass) */
|
|
float henv[PSY_LAME_HIST + AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS];
|
|
float *walls[2] = { &pch->gap_wall, &pch->gap_wall_hp };
|
|
const float *envs[2] = { renv, henv };
|
|
memcpy(renv, pch->raw_env_hist, sizeof(pch->raw_env_hist));
|
|
for (i = 0; i < AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS; i++) {
|
|
float p = 0.0f;
|
|
for (int j2 = 0; j2 < 64; j2++)
|
|
p = FFMAX(p, fabsf(la[i*64 + j2]));
|
|
renv[PSY_LAME_HIST + i] = FFMAX(p * 32768.0f, 1.0f);
|
|
}
|
|
memcpy(henv, pch->hp_env_hist, sizeof(pch->hp_env_hist));
|
|
memcpy(henv + PSY_LAME_HIST, energy_subshort + PSY_LAME_NUM_SUBBLOCKS,
|
|
AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS * sizeof(*henv));
|
|
for (int e = 0; e < 2; e++) {
|
|
const float *ev = envs[e];
|
|
float wall = *walls[e];
|
|
for (i = 0; i < AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS; i++) {
|
|
const int b = (i + PSY_LAME_NUM_SUBBLOCKS) / PSY_LAME_NUM_SUBBLOCKS;
|
|
const int pos = PSY_LAME_HIST + i;
|
|
const float cand = ev[pos];
|
|
const float quiet = wall / PSY_LAME_GAP_DEPTH;
|
|
int run = 0, k0 = 0;
|
|
/* the gap must end adjacent to the candidate (<= 5
|
|
* rising sub-blocks) and hold >= 4 sub-blocks (~6ms).
|
|
* A pulse train's inter-pulse floor never drops this
|
|
* far below its own running peak, so it cannot fire. */
|
|
for (int k = 3; k <= 8; k++)
|
|
if (ev[pos - k] < quiet) {
|
|
k0 = k;
|
|
break;
|
|
}
|
|
if (k0)
|
|
for (int k = k0; k <= PSY_LAME_GAP_BACK && ev[pos - k] < quiet; k++)
|
|
run++;
|
|
if (e == 1 && !(run >= 4)) {
|
|
/* HP tower: an onset rising far above everything
|
|
* in the look-back, even without a silent gap
|
|
* (cymbal-less slams leave the bass sustaining) */
|
|
float dmax = 1.0f;
|
|
for (int k = 3; k <= PSY_LAME_GAP_BACK; k++)
|
|
dmax = FFMAX(dmax, ev[pos - k]);
|
|
if (cand > PSY_LAME_GAP_TOWER * dmax)
|
|
run = 4; /* qualify via the same fire path */
|
|
}
|
|
if (!attacks[b] && run >= 4 && cand > PSY_LAME_GAP_LEVEL * wall &&
|
|
cand > PSY_LAME_GAP_FLOOR) {
|
|
attacks[b] = (i + PSY_LAME_NUM_SUBBLOCKS) % PSY_LAME_NUM_SUBBLOCKS + 1;
|
|
att_sum += attacks[b];
|
|
}
|
|
wall = FFMAX(wall * 0.996f, cand);
|
|
}
|
|
*walls[e] = wall;
|
|
}
|
|
memcpy(pch->raw_env_hist, renv + AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS,
|
|
sizeof(pch->raw_env_hist));
|
|
}
|
|
|
|
/* roll the HP sub-block peak history */
|
|
memmove(pch->hp_env_hist,
|
|
pch->hp_env_hist + AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS,
|
|
(PSY_LAME_HIST - AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS) *
|
|
sizeof(*pch->hp_env_hist));
|
|
memcpy(pch->hp_env_hist + PSY_LAME_HIST - AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS,
|
|
energy_subshort + PSY_LAME_NUM_SUBBLOCKS,
|
|
AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS * sizeof(*pch->hp_env_hist));
|
|
|
|
if (pch->next_attack0_zero)
|
|
attacks[0] = 0;
|
|
pch->next_attack0_zero = !attacks[AAC_NUM_BLOCKS_SHORT];
|
|
|
|
if (attacks[0] <= pch->prev_attack)
|
|
attacks[0] = 0;
|
|
|
|
att_sum += attacks[0];
|
|
|
|
/* If the previous attack happened in the last sub-block of the previous sequence,
|
|
* or if there's a new attack, use short window */
|
|
if (pch->prev_attack == PSY_LAME_NUM_SUBBLOCKS || att_sum) {
|
|
uselongblock = 0;
|
|
|
|
for (i = 1; i < AAC_NUM_BLOCKS_SHORT + 1; i++)
|
|
if (attacks[i] && attacks[i-1])
|
|
attacks[i] = 0;
|
|
}
|
|
|
|
} else {
|
|
/* We have no lookahead info, so just use same type as the previous sequence. */
|
|
uselongblock = !(prev_type == EIGHT_SHORT_SEQUENCE);
|
|
}
|
|
return uselongblock;
|
|
}
|
|
|
|
/* Decision half: the block-type state machine and window/grouping fill,
|
|
* given the (possibly pair-synced) final uselongblock. */
|
|
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)
|
|
{
|
|
int grouping = 0;
|
|
int i;
|
|
FFPsyWindowInfo wi = { { 0 } };
|
|
|
|
if (have_la)
|
|
pch->frames_since_short = uselongblock ? pch->frames_since_short + 1 : 0;
|
|
|
|
lame_apply_block_type(pch, &wi, uselongblock);
|
|
|
|
wi.window_type[1] = prev_type;
|
|
if (wi.window_type[0] != EIGHT_SHORT_SEQUENCE) {
|
|
|
|
wi.num_windows = 1;
|
|
wi.grouping[0] = 1;
|
|
if (wi.window_type[0] == LONG_START_SEQUENCE)
|
|
wi.window_shape = 0;
|
|
else
|
|
wi.window_shape = 1;
|
|
|
|
} else {
|
|
int lastgrp = 0;
|
|
|
|
wi.num_windows = 8;
|
|
wi.window_shape = 0;
|
|
for (i = 0; i < 8; i++) {
|
|
if (!((pch->next_grouping >> i) & 1))
|
|
lastgrp = i;
|
|
wi.grouping[lastgrp]++;
|
|
}
|
|
}
|
|
|
|
/* Determine grouping, based on the location of the first attack, and save for
|
|
* the next frame.
|
|
* FIXME: Move this to analysis.
|
|
* TODO: Tune groupings depending on attack location
|
|
* TODO: Handle more than one attack in a group
|
|
*/
|
|
for (i = 0; i < 9; i++) {
|
|
if (attacks[i]) {
|
|
grouping = i;
|
|
break;
|
|
}
|
|
}
|
|
pch->next_grouping = window_grouping[grouping];
|
|
|
|
{
|
|
/* energy-homogeneous grouping: fixed attack-position patterns force
|
|
* disparate windows to share scalefactors; regroup on level jumps */
|
|
uint8_t bits = 0;
|
|
int glen = 1;
|
|
for (i = 1; i < AAC_NUM_BLOCKS_SHORT; i++) {
|
|
float a = pch->next_win_level[i], b = pch->next_win_level[i-1];
|
|
float hi = FFMAX(a, b), lo = FFMAX(FFMIN(a, b), 1.0f);
|
|
if (hi <= lo * PSY_LAME_GRP_RATIO && glen < PSY_LAME_GRP_MAX) {
|
|
bits |= 1 << i;
|
|
glen++;
|
|
} else {
|
|
glen = 1;
|
|
}
|
|
}
|
|
pch->next_grouping = bits;
|
|
}
|
|
|
|
pch->prev_attack = attacks[AAC_NUM_BLOCKS_SHORT - 1];
|
|
|
|
return wi;
|
|
}
|
|
|
|
static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio,
|
|
const float *la, int channel, int prev_type)
|
|
{
|
|
AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
|
|
AacPsyChannel *pch = &pctx->ch[channel];
|
|
int attacks[AAC_NUM_BLOCKS_SHORT + 1] = { 0 };
|
|
int uselongblock = psy_lame_detect(pctx, pch, la, channel, prev_type, attacks);
|
|
|
|
return psy_lame_apply(pctx, pch, uselongblock, attacks, prev_type, !!la);
|
|
}
|
|
|
|
/* Pair-synced block switching: either channel's attack switches both. */
|
|
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])
|
|
{
|
|
AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
|
|
AacPsyChannel *pch0 = &pctx->ch[channel0];
|
|
AacPsyChannel *pch1 = &pctx->ch[channel1];
|
|
int att0[AAC_NUM_BLOCKS_SHORT + 1] = { 0 };
|
|
int att1[AAC_NUM_BLOCKS_SHORT + 1] = { 0 };
|
|
int merged[AAC_NUM_BLOCKS_SHORT + 1];
|
|
int u0 = psy_lame_detect(pctx, pch0, la0, channel0, prev_type0, att0);
|
|
int u1 = psy_lame_detect(pctx, pch1, la1, channel1, prev_type1, att1);
|
|
int u = u0 && u1;
|
|
|
|
if (ctx->pair_decoupled[(channel0 >> 1) & 15]) {
|
|
/* Joint tools are dead on this pair (encoder-fed state): each channel
|
|
* windows for ITS transients - divergence costs nothing there, while
|
|
* union-syncing forces the steady channel short at every event in
|
|
* the other. Correlated content keeps the sync. */
|
|
wi[0] = psy_lame_apply(pctx, pch0, u0, att0, prev_type0, !!la0);
|
|
wi[1] = psy_lame_apply(pctx, pch1, u1, att1, prev_type1, !!la1);
|
|
return;
|
|
}
|
|
|
|
/* One merged attack map for both channels: the grouping (and with it
|
|
* common_window) must match across the pair, and the group boundary
|
|
* should isolate the first attack heard in EITHER channel. */
|
|
for (int i = 0; i < AAC_NUM_BLOCKS_SHORT + 1; i++)
|
|
merged[i] = att0[i] ? att0[i] : att1[i];
|
|
|
|
/* grouping must also match across the pair: merge the level maps */
|
|
for (int i = 0; i < AAC_NUM_BLOCKS_SHORT; i++)
|
|
pch0->next_win_level[i] = pch1->next_win_level[i] =
|
|
FFMAX(pch0->next_win_level[i], pch1->next_win_level[i]);
|
|
|
|
wi[0] = psy_lame_apply(pctx, pch0, u, merged, prev_type0, !!la0);
|
|
wi[1] = psy_lame_apply(pctx, pch1, u, merged, prev_type1, !!la1);
|
|
}
|
|
|
|
const FFPsyModel ff_aac_psy_model =
|
|
{
|
|
.name = "3GPP TS 26.403-inspired model",
|
|
.init = psy_3gpp_init,
|
|
.window = psy_lame_window,
|
|
.analyze = psy_3gpp_analyze,
|
|
.end = psy_3gpp_end,
|
|
.window_pair = psy_lame_window_pair,
|
|
};
|