You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

963 lines
36KB

  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. * @file
  23. * AAC encoder psychoacoustic model
  24. */
  25. #include "libavutil/libm.h"
  26. #include "avcodec.h"
  27. #include "aactab.h"
  28. #include "psymodel.h"
  29. /***********************************
  30. * TODOs:
  31. * try other bitrate controlling mechanism (maybe use ratecontrol.c?)
  32. * control quality for quality-based output
  33. **********************************/
  34. /**
  35. * constants for 3GPP AAC psychoacoustic model
  36. * @{
  37. */
  38. #define PSY_3GPP_THR_SPREAD_HI 1.5f // spreading factor for low-to-hi threshold spreading (15 dB/Bark)
  39. #define PSY_3GPP_THR_SPREAD_LOW 3.0f // spreading factor for hi-to-low threshold spreading (30 dB/Bark)
  40. /* spreading factor for low-to-hi energy spreading, long block, > 22kbps/channel (20dB/Bark) */
  41. #define PSY_3GPP_EN_SPREAD_HI_L1 2.0f
  42. /* spreading factor for low-to-hi energy spreading, long block, <= 22kbps/channel (15dB/Bark) */
  43. #define PSY_3GPP_EN_SPREAD_HI_L2 1.5f
  44. /* spreading factor for low-to-hi energy spreading, short block (15 dB/Bark) */
  45. #define PSY_3GPP_EN_SPREAD_HI_S 1.5f
  46. /* spreading factor for hi-to-low energy spreading, long block (30dB/Bark) */
  47. #define PSY_3GPP_EN_SPREAD_LOW_L 3.0f
  48. /* spreading factor for hi-to-low energy spreading, short block (20dB/Bark) */
  49. #define PSY_3GPP_EN_SPREAD_LOW_S 2.0f
  50. #define PSY_3GPP_RPEMIN 0.01f
  51. #define PSY_3GPP_RPELEV 2.0f
  52. #define PSY_3GPP_C1 3.0f /* log2(8) */
  53. #define PSY_3GPP_C2 1.3219281f /* log2(2.5) */
  54. #define PSY_3GPP_C3 0.55935729f /* 1 - C2 / C1 */
  55. #define PSY_SNR_1DB 7.9432821e-1f /* -1dB */
  56. #define PSY_SNR_25DB 3.1622776e-3f /* -25dB */
  57. #define PSY_3GPP_SAVE_SLOPE_L -0.46666667f
  58. #define PSY_3GPP_SAVE_SLOPE_S -0.36363637f
  59. #define PSY_3GPP_SAVE_ADD_L -0.84285712f
  60. #define PSY_3GPP_SAVE_ADD_S -0.75f
  61. #define PSY_3GPP_SPEND_SLOPE_L 0.66666669f
  62. #define PSY_3GPP_SPEND_SLOPE_S 0.81818181f
  63. #define PSY_3GPP_SPEND_ADD_L -0.35f
  64. #define PSY_3GPP_SPEND_ADD_S -0.26111111f
  65. #define PSY_3GPP_CLIP_LO_L 0.2f
  66. #define PSY_3GPP_CLIP_LO_S 0.2f
  67. #define PSY_3GPP_CLIP_HI_L 0.95f
  68. #define PSY_3GPP_CLIP_HI_S 0.75f
  69. #define PSY_3GPP_AH_THR_LONG 0.5f
  70. #define PSY_3GPP_AH_THR_SHORT 0.63f
  71. enum {
  72. PSY_3GPP_AH_NONE,
  73. PSY_3GPP_AH_INACTIVE,
  74. PSY_3GPP_AH_ACTIVE
  75. };
  76. #define PSY_3GPP_BITS_TO_PE(bits) ((bits) * 1.18f)
  77. /* LAME psy model constants */
  78. #define PSY_LAME_FIR_LEN 21 ///< LAME psy model FIR order
  79. #define AAC_BLOCK_SIZE_LONG 1024 ///< long block size
  80. #define AAC_BLOCK_SIZE_SHORT 128 ///< short block size
  81. #define AAC_NUM_BLOCKS_SHORT 8 ///< number of blocks in a short sequence
  82. #define PSY_LAME_NUM_SUBBLOCKS 3 ///< Number of sub-blocks in each short block
  83. /**
  84. * @}
  85. */
  86. /**
  87. * information for single band used by 3GPP TS26.403-inspired psychoacoustic model
  88. */
  89. typedef struct AacPsyBand{
  90. float energy; ///< band energy
  91. float thr; ///< energy threshold
  92. float thr_quiet; ///< threshold in quiet
  93. float nz_lines; ///< number of non-zero spectral lines
  94. float active_lines; ///< number of active spectral lines
  95. float pe; ///< perceptual entropy
  96. float pe_const; ///< constant part of the PE calculation
  97. float norm_fac; ///< normalization factor for linearization
  98. int avoid_holes; ///< hole avoidance flag
  99. }AacPsyBand;
  100. /**
  101. * single/pair channel context for psychoacoustic model
  102. */
  103. typedef struct AacPsyChannel{
  104. AacPsyBand band[128]; ///< bands information
  105. AacPsyBand prev_band[128]; ///< bands information from the previous frame
  106. float win_energy; ///< sliding average of channel energy
  107. float iir_state[2]; ///< hi-pass IIR filter state
  108. uint8_t next_grouping; ///< stored grouping scheme for the next frame (in case of 8 short window sequence)
  109. enum WindowSequence next_window_seq; ///< window sequence to be used in the next frame
  110. /* LAME psy model specific members */
  111. float attack_threshold; ///< attack threshold for this channel
  112. float prev_energy_subshort[AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS];
  113. int prev_attack; ///< attack value for the last short block in the previous sequence
  114. }AacPsyChannel;
  115. /**
  116. * psychoacoustic model frame type-dependent coefficients
  117. */
  118. typedef struct AacPsyCoeffs{
  119. float ath; ///< absolute threshold of hearing per bands
  120. float barks; ///< Bark value for each spectral band in long frame
  121. float spread_low[2]; ///< spreading factor for low-to-high threshold spreading in long frame
  122. float spread_hi [2]; ///< spreading factor for high-to-low threshold spreading in long frame
  123. float min_snr; ///< minimal SNR
  124. }AacPsyCoeffs;
  125. /**
  126. * 3GPP TS26.403-inspired psychoacoustic model specific data
  127. */
  128. typedef struct AacPsyContext{
  129. int chan_bitrate; ///< bitrate per channel
  130. int frame_bits; ///< average bits per frame
  131. int fill_level; ///< bit reservoir fill level
  132. struct {
  133. float min; ///< minimum allowed PE for bit factor calculation
  134. float max; ///< maximum allowed PE for bit factor calculation
  135. float previous; ///< allowed PE of the previous frame
  136. float correction; ///< PE correction factor
  137. } pe;
  138. AacPsyCoeffs psy_coef[2][64];
  139. AacPsyChannel *ch;
  140. }AacPsyContext;
  141. /**
  142. * LAME psy model preset struct
  143. */
  144. typedef struct {
  145. int quality; ///< Quality to map the rest of the vaules to.
  146. /* This is overloaded to be both kbps per channel in ABR mode, and
  147. * requested quality in constant quality mode.
  148. */
  149. float st_lrm; ///< short threshold for L, R, and M channels
  150. } PsyLamePreset;
  151. /**
  152. * LAME psy model preset table for ABR
  153. */
  154. static const PsyLamePreset psy_abr_map[] = {
  155. /* TODO: Tuning. These were taken from LAME. */
  156. /* kbps/ch st_lrm */
  157. { 8, 6.60},
  158. { 16, 6.60},
  159. { 24, 6.60},
  160. { 32, 6.60},
  161. { 40, 6.60},
  162. { 48, 6.60},
  163. { 56, 6.60},
  164. { 64, 6.40},
  165. { 80, 6.00},
  166. { 96, 5.60},
  167. {112, 5.20},
  168. {128, 5.20},
  169. {160, 5.20}
  170. };
  171. /**
  172. * LAME psy model preset table for constant quality
  173. */
  174. static const PsyLamePreset psy_vbr_map[] = {
  175. /* vbr_q st_lrm */
  176. { 0, 4.20},
  177. { 1, 4.20},
  178. { 2, 4.20},
  179. { 3, 4.20},
  180. { 4, 4.20},
  181. { 5, 4.20},
  182. { 6, 4.20},
  183. { 7, 4.20},
  184. { 8, 4.20},
  185. { 9, 4.20},
  186. {10, 4.20}
  187. };
  188. /**
  189. * LAME psy model FIR coefficient table
  190. */
  191. static const float psy_fir_coeffs[] = {
  192. -8.65163e-18 * 2, -0.00851586 * 2, -6.74764e-18 * 2, 0.0209036 * 2,
  193. -3.36639e-17 * 2, -0.0438162 * 2, -1.54175e-17 * 2, 0.0931738 * 2,
  194. -5.52212e-17 * 2, -0.313819 * 2
  195. };
  196. #if ARCH_MIPS
  197. # include "mips/aacpsy_mips.h"
  198. #endif /* ARCH_MIPS */
  199. /**
  200. * Calculate the ABR attack threshold from the above LAME psymodel table.
  201. */
  202. static float lame_calc_attack_threshold(int bitrate)
  203. {
  204. /* Assume max bitrate to start with */
  205. int lower_range = 12, upper_range = 12;
  206. int lower_range_kbps = psy_abr_map[12].quality;
  207. int upper_range_kbps = psy_abr_map[12].quality;
  208. int i;
  209. /* Determine which bitrates the value specified falls between.
  210. * If the loop ends without breaking our above assumption of 320kbps was correct.
  211. */
  212. for (i = 1; i < 13; i++) {
  213. if (FFMAX(bitrate, psy_abr_map[i].quality) != bitrate) {
  214. upper_range = i;
  215. upper_range_kbps = psy_abr_map[i ].quality;
  216. lower_range = i - 1;
  217. lower_range_kbps = psy_abr_map[i - 1].quality;
  218. break; /* Upper range found */
  219. }
  220. }
  221. /* Determine which range the value specified is closer to */
  222. if ((upper_range_kbps - bitrate) > (bitrate - lower_range_kbps))
  223. return psy_abr_map[lower_range].st_lrm;
  224. return psy_abr_map[upper_range].st_lrm;
  225. }
  226. /**
  227. * LAME psy model specific initialization
  228. */
  229. static void lame_window_init(AacPsyContext *ctx, AVCodecContext *avctx) {
  230. int i, j;
  231. for (i = 0; i < avctx->channels; i++) {
  232. AacPsyChannel *pch = &ctx->ch[i];
  233. if (avctx->flags & CODEC_FLAG_QSCALE)
  234. pch->attack_threshold = psy_vbr_map[avctx->global_quality / FF_QP2LAMBDA].st_lrm;
  235. else
  236. pch->attack_threshold = lame_calc_attack_threshold(avctx->bit_rate / avctx->channels / 1000);
  237. for (j = 0; j < AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS; j++)
  238. pch->prev_energy_subshort[j] = 10.0f;
  239. }
  240. }
  241. /**
  242. * Calculate Bark value for given line.
  243. */
  244. static av_cold float calc_bark(float f)
  245. {
  246. return 13.3f * atanf(0.00076f * f) + 3.5f * atanf((f / 7500.0f) * (f / 7500.0f));
  247. }
  248. #define ATH_ADD 4
  249. /**
  250. * Calculate ATH value for given frequency.
  251. * Borrowed from Lame.
  252. */
  253. static av_cold float ath(float f, float add)
  254. {
  255. f /= 1000.0f;
  256. return 3.64 * pow(f, -0.8)
  257. - 6.8 * exp(-0.6 * (f - 3.4) * (f - 3.4))
  258. + 6.0 * exp(-0.15 * (f - 8.7) * (f - 8.7))
  259. + (0.6 + 0.04 * add) * 0.001 * f * f * f * f;
  260. }
  261. static av_cold int psy_3gpp_init(FFPsyContext *ctx) {
  262. AacPsyContext *pctx;
  263. float bark;
  264. int i, j, g, start;
  265. float prev, minscale, minath, minsnr, pe_min;
  266. const int chan_bitrate = ctx->avctx->bit_rate / ctx->avctx->channels;
  267. const int bandwidth = ctx->avctx->cutoff ? ctx->avctx->cutoff : AAC_CUTOFF(ctx->avctx);
  268. const float num_bark = calc_bark((float)bandwidth);
  269. ctx->model_priv_data = av_mallocz(sizeof(AacPsyContext));
  270. pctx = (AacPsyContext*) ctx->model_priv_data;
  271. pctx->chan_bitrate = chan_bitrate;
  272. pctx->frame_bits = chan_bitrate * AAC_BLOCK_SIZE_LONG / ctx->avctx->sample_rate;
  273. pctx->pe.min = 8.0f * AAC_BLOCK_SIZE_LONG * bandwidth / (ctx->avctx->sample_rate * 2.0f);
  274. pctx->pe.max = 12.0f * AAC_BLOCK_SIZE_LONG * bandwidth / (ctx->avctx->sample_rate * 2.0f);
  275. ctx->bitres.size = 6144 - pctx->frame_bits;
  276. ctx->bitres.size -= ctx->bitres.size % 8;
  277. pctx->fill_level = ctx->bitres.size;
  278. minath = ath(3410, ATH_ADD);
  279. for (j = 0; j < 2; j++) {
  280. AacPsyCoeffs *coeffs = pctx->psy_coef[j];
  281. const uint8_t *band_sizes = ctx->bands[j];
  282. float line_to_frequency = ctx->avctx->sample_rate / (j ? 256.f : 2048.0f);
  283. float avg_chan_bits = chan_bitrate / ctx->avctx->sample_rate * (j ? 128.0f : 1024.0f);
  284. /* reference encoder uses 2.4% here instead of 60% like the spec says */
  285. float bark_pe = 0.024f * PSY_3GPP_BITS_TO_PE(avg_chan_bits) / num_bark;
  286. float en_spread_low = j ? PSY_3GPP_EN_SPREAD_LOW_S : PSY_3GPP_EN_SPREAD_LOW_L;
  287. /* High energy spreading for long blocks <= 22kbps/channel and short blocks are the same. */
  288. float en_spread_hi = (j || (chan_bitrate <= 22.0f)) ? PSY_3GPP_EN_SPREAD_HI_S : PSY_3GPP_EN_SPREAD_HI_L1;
  289. i = 0;
  290. prev = 0.0;
  291. for (g = 0; g < ctx->num_bands[j]; g++) {
  292. i += band_sizes[g];
  293. bark = calc_bark((i-1) * line_to_frequency);
  294. coeffs[g].barks = (bark + prev) / 2.0;
  295. prev = bark;
  296. }
  297. for (g = 0; g < ctx->num_bands[j] - 1; g++) {
  298. AacPsyCoeffs *coeff = &coeffs[g];
  299. float bark_width = coeffs[g+1].barks - coeffs->barks;
  300. coeff->spread_low[0] = pow(10.0, -bark_width * PSY_3GPP_THR_SPREAD_LOW);
  301. coeff->spread_hi [0] = pow(10.0, -bark_width * PSY_3GPP_THR_SPREAD_HI);
  302. coeff->spread_low[1] = pow(10.0, -bark_width * en_spread_low);
  303. coeff->spread_hi [1] = pow(10.0, -bark_width * en_spread_hi);
  304. pe_min = bark_pe * bark_width;
  305. minsnr = exp2(pe_min / band_sizes[g]) - 1.5f;
  306. coeff->min_snr = av_clipf(1.0f / minsnr, PSY_SNR_25DB, PSY_SNR_1DB);
  307. }
  308. start = 0;
  309. for (g = 0; g < ctx->num_bands[j]; g++) {
  310. minscale = ath(start * line_to_frequency, ATH_ADD);
  311. for (i = 1; i < band_sizes[g]; i++)
  312. minscale = FFMIN(minscale, ath((start + i) * line_to_frequency, ATH_ADD));
  313. coeffs[g].ath = minscale - minath;
  314. start += band_sizes[g];
  315. }
  316. }
  317. pctx->ch = av_mallocz(sizeof(AacPsyChannel) * ctx->avctx->channels);
  318. lame_window_init(pctx, ctx->avctx);
  319. return 0;
  320. }
  321. /**
  322. * IIR filter used in block switching decision
  323. */
  324. static float iir_filter(int in, float state[2])
  325. {
  326. float ret;
  327. ret = 0.7548f * (in - state[0]) + 0.5095f * state[1];
  328. state[0] = in;
  329. state[1] = ret;
  330. return ret;
  331. }
  332. /**
  333. * window grouping information stored as bits (0 - new group, 1 - group continues)
  334. */
  335. static const uint8_t window_grouping[9] = {
  336. 0xB6, 0x6C, 0xD8, 0xB2, 0x66, 0xC6, 0x96, 0x36, 0x36
  337. };
  338. /**
  339. * Tell encoder which window types to use.
  340. * @see 3GPP TS26.403 5.4.1 "Blockswitching"
  341. */
  342. static av_unused FFPsyWindowInfo psy_3gpp_window(FFPsyContext *ctx,
  343. const int16_t *audio,
  344. const int16_t *la,
  345. int channel, int prev_type)
  346. {
  347. int i, j;
  348. int br = ctx->avctx->bit_rate / ctx->avctx->channels;
  349. int attack_ratio = br <= 16000 ? 18 : 10;
  350. AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
  351. AacPsyChannel *pch = &pctx->ch[channel];
  352. uint8_t grouping = 0;
  353. int next_type = pch->next_window_seq;
  354. FFPsyWindowInfo wi = { { 0 } };
  355. if (la) {
  356. float s[8], v;
  357. int switch_to_eight = 0;
  358. float sum = 0.0, sum2 = 0.0;
  359. int attack_n = 0;
  360. int stay_short = 0;
  361. for (i = 0; i < 8; i++) {
  362. for (j = 0; j < 128; j++) {
  363. v = iir_filter(la[i*128+j], pch->iir_state);
  364. sum += v*v;
  365. }
  366. s[i] = sum;
  367. sum2 += sum;
  368. }
  369. for (i = 0; i < 8; i++) {
  370. if (s[i] > pch->win_energy * attack_ratio) {
  371. attack_n = i + 1;
  372. switch_to_eight = 1;
  373. break;
  374. }
  375. }
  376. pch->win_energy = pch->win_energy*7/8 + sum2/64;
  377. wi.window_type[1] = prev_type;
  378. switch (prev_type) {
  379. case ONLY_LONG_SEQUENCE:
  380. wi.window_type[0] = switch_to_eight ? LONG_START_SEQUENCE : ONLY_LONG_SEQUENCE;
  381. next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : ONLY_LONG_SEQUENCE;
  382. break;
  383. case LONG_START_SEQUENCE:
  384. wi.window_type[0] = EIGHT_SHORT_SEQUENCE;
  385. grouping = pch->next_grouping;
  386. next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : LONG_STOP_SEQUENCE;
  387. break;
  388. case LONG_STOP_SEQUENCE:
  389. wi.window_type[0] = switch_to_eight ? LONG_START_SEQUENCE : ONLY_LONG_SEQUENCE;
  390. next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : ONLY_LONG_SEQUENCE;
  391. break;
  392. case EIGHT_SHORT_SEQUENCE:
  393. stay_short = next_type == EIGHT_SHORT_SEQUENCE || switch_to_eight;
  394. wi.window_type[0] = stay_short ? EIGHT_SHORT_SEQUENCE : LONG_STOP_SEQUENCE;
  395. grouping = next_type == EIGHT_SHORT_SEQUENCE ? pch->next_grouping : 0;
  396. next_type = switch_to_eight ? EIGHT_SHORT_SEQUENCE : LONG_STOP_SEQUENCE;
  397. break;
  398. }
  399. pch->next_grouping = window_grouping[attack_n];
  400. pch->next_window_seq = next_type;
  401. } else {
  402. for (i = 0; i < 3; i++)
  403. wi.window_type[i] = prev_type;
  404. grouping = (prev_type == EIGHT_SHORT_SEQUENCE) ? window_grouping[0] : 0;
  405. }
  406. wi.window_shape = 1;
  407. if (wi.window_type[0] != EIGHT_SHORT_SEQUENCE) {
  408. wi.num_windows = 1;
  409. wi.grouping[0] = 1;
  410. } else {
  411. int lastgrp = 0;
  412. wi.num_windows = 8;
  413. for (i = 0; i < 8; i++) {
  414. if (!((grouping >> i) & 1))
  415. lastgrp = i;
  416. wi.grouping[lastgrp]++;
  417. }
  418. }
  419. return wi;
  420. }
  421. /* 5.6.1.2 "Calculation of Bit Demand" */
  422. static int calc_bit_demand(AacPsyContext *ctx, float pe, int bits, int size,
  423. int short_window)
  424. {
  425. const float bitsave_slope = short_window ? PSY_3GPP_SAVE_SLOPE_S : PSY_3GPP_SAVE_SLOPE_L;
  426. const float bitsave_add = short_window ? PSY_3GPP_SAVE_ADD_S : PSY_3GPP_SAVE_ADD_L;
  427. const float bitspend_slope = short_window ? PSY_3GPP_SPEND_SLOPE_S : PSY_3GPP_SPEND_SLOPE_L;
  428. const float bitspend_add = short_window ? PSY_3GPP_SPEND_ADD_S : PSY_3GPP_SPEND_ADD_L;
  429. const float clip_low = short_window ? PSY_3GPP_CLIP_LO_S : PSY_3GPP_CLIP_LO_L;
  430. const float clip_high = short_window ? PSY_3GPP_CLIP_HI_S : PSY_3GPP_CLIP_HI_L;
  431. float clipped_pe, bit_save, bit_spend, bit_factor, fill_level;
  432. ctx->fill_level += ctx->frame_bits - bits;
  433. ctx->fill_level = av_clip(ctx->fill_level, 0, size);
  434. fill_level = av_clipf((float)ctx->fill_level / size, clip_low, clip_high);
  435. clipped_pe = av_clipf(pe, ctx->pe.min, ctx->pe.max);
  436. bit_save = (fill_level + bitsave_add) * bitsave_slope;
  437. assert(bit_save <= 0.3f && bit_save >= -0.05000001f);
  438. bit_spend = (fill_level + bitspend_add) * bitspend_slope;
  439. assert(bit_spend <= 0.5f && bit_spend >= -0.1f);
  440. /* The bit factor graph in the spec is obviously incorrect.
  441. * bit_spend + ((bit_spend - bit_spend))...
  442. * The reference encoder subtracts everything from 1, but also seems incorrect.
  443. * 1 - bit_save + ((bit_spend + bit_save))...
  444. * Hopefully below is correct.
  445. */
  446. bit_factor = 1.0f - bit_save + ((bit_spend - bit_save) / (ctx->pe.max - ctx->pe.min)) * (clipped_pe - ctx->pe.min);
  447. /* NOTE: The reference encoder attempts to center pe max/min around the current pe. */
  448. ctx->pe.max = FFMAX(pe, ctx->pe.max);
  449. ctx->pe.min = FFMIN(pe, ctx->pe.min);
  450. return FFMIN(ctx->frame_bits * bit_factor, ctx->frame_bits + size - bits);
  451. }
  452. static float calc_pe_3gpp(AacPsyBand *band)
  453. {
  454. float pe, a;
  455. band->pe = 0.0f;
  456. band->pe_const = 0.0f;
  457. band->active_lines = 0.0f;
  458. if (band->energy > band->thr) {
  459. a = log2f(band->energy);
  460. pe = a - log2f(band->thr);
  461. band->active_lines = band->nz_lines;
  462. if (pe < PSY_3GPP_C1) {
  463. pe = pe * PSY_3GPP_C3 + PSY_3GPP_C2;
  464. a = a * PSY_3GPP_C3 + PSY_3GPP_C2;
  465. band->active_lines *= PSY_3GPP_C3;
  466. }
  467. band->pe = pe * band->nz_lines;
  468. band->pe_const = a * band->nz_lines;
  469. }
  470. return band->pe;
  471. }
  472. static float calc_reduction_3gpp(float a, float desired_pe, float pe,
  473. float active_lines)
  474. {
  475. float thr_avg, reduction;
  476. if(active_lines == 0.0)
  477. return 0;
  478. thr_avg = exp2f((a - pe) / (4.0f * active_lines));
  479. reduction = exp2f((a - desired_pe) / (4.0f * active_lines)) - thr_avg;
  480. return FFMAX(reduction, 0.0f);
  481. }
  482. static float calc_reduced_thr_3gpp(AacPsyBand *band, float min_snr,
  483. float reduction)
  484. {
  485. float thr = band->thr;
  486. if (band->energy > thr) {
  487. thr = sqrtf(thr);
  488. thr = sqrtf(thr) + reduction;
  489. thr *= thr;
  490. thr *= thr;
  491. /* This deviates from the 3GPP spec to match the reference encoder.
  492. * It performs min(thr_reduced, max(thr, energy/min_snr)) only for bands
  493. * that have hole avoidance on (active or inactive). It always reduces the
  494. * threshold of bands with hole avoidance off.
  495. */
  496. if (thr > band->energy * min_snr && band->avoid_holes != PSY_3GPP_AH_NONE) {
  497. thr = FFMAX(band->thr, band->energy * min_snr);
  498. band->avoid_holes = PSY_3GPP_AH_ACTIVE;
  499. }
  500. }
  501. return thr;
  502. }
  503. #ifndef calc_thr_3gpp
  504. static void calc_thr_3gpp(const FFPsyWindowInfo *wi, const int num_bands, AacPsyChannel *pch,
  505. const uint8_t *band_sizes, const float *coefs)
  506. {
  507. int i, w, g;
  508. int start = 0;
  509. for (w = 0; w < wi->num_windows*16; w += 16) {
  510. for (g = 0; g < num_bands; g++) {
  511. AacPsyBand *band = &pch->band[w+g];
  512. float form_factor = 0.0f;
  513. float Temp;
  514. band->energy = 0.0f;
  515. for (i = 0; i < band_sizes[g]; i++) {
  516. band->energy += coefs[start+i] * coefs[start+i];
  517. form_factor += sqrtf(fabs(coefs[start+i]));
  518. }
  519. Temp = band->energy > 0 ? sqrtf((float)band_sizes[g] / band->energy) : 0;
  520. band->thr = band->energy * 0.001258925f;
  521. band->nz_lines = form_factor * sqrtf(Temp);
  522. start += band_sizes[g];
  523. }
  524. }
  525. }
  526. #endif /* calc_thr_3gpp */
  527. #ifndef psy_hp_filter
  528. static void psy_hp_filter(const float *firbuf, float *hpfsmpl, const float *psy_fir_coeffs)
  529. {
  530. int i, j;
  531. for (i = 0; i < AAC_BLOCK_SIZE_LONG; i++) {
  532. float sum1, sum2;
  533. sum1 = firbuf[i + (PSY_LAME_FIR_LEN - 1) / 2];
  534. sum2 = 0.0;
  535. for (j = 0; j < ((PSY_LAME_FIR_LEN - 1) / 2) - 1; j += 2) {
  536. sum1 += psy_fir_coeffs[j] * (firbuf[i + j] + firbuf[i + PSY_LAME_FIR_LEN - j]);
  537. sum2 += psy_fir_coeffs[j + 1] * (firbuf[i + j + 1] + firbuf[i + PSY_LAME_FIR_LEN - j - 1]);
  538. }
  539. /* NOTE: The LAME psymodel expects it's input in the range -32768 to 32768. Tuning this for normalized floats would be difficult. */
  540. hpfsmpl[i] = (sum1 + sum2) * 32768.0f;
  541. }
  542. }
  543. #endif /* psy_hp_filter */
  544. /**
  545. * Calculate band thresholds as suggested in 3GPP TS26.403
  546. */
  547. static void psy_3gpp_analyze_channel(FFPsyContext *ctx, int channel,
  548. const float *coefs, const FFPsyWindowInfo *wi)
  549. {
  550. AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
  551. AacPsyChannel *pch = &pctx->ch[channel];
  552. int i, w, g;
  553. float desired_bits, desired_pe, delta_pe, reduction= NAN, spread_en[128] = {0};
  554. float a = 0.0f, active_lines = 0.0f, norm_fac = 0.0f;
  555. float pe = pctx->chan_bitrate > 32000 ? 0.0f : FFMAX(50.0f, 100.0f - pctx->chan_bitrate * 100.0f / 32000.0f);
  556. const int num_bands = ctx->num_bands[wi->num_windows == 8];
  557. const uint8_t *band_sizes = ctx->bands[wi->num_windows == 8];
  558. AacPsyCoeffs *coeffs = pctx->psy_coef[wi->num_windows == 8];
  559. const float avoid_hole_thr = wi->num_windows == 8 ? PSY_3GPP_AH_THR_SHORT : PSY_3GPP_AH_THR_LONG;
  560. //calculate energies, initial thresholds and related values - 5.4.2 "Threshold Calculation"
  561. calc_thr_3gpp(wi, num_bands, pch, band_sizes, coefs);
  562. //modify thresholds and energies - spread, threshold in quiet, pre-echo control
  563. for (w = 0; w < wi->num_windows*16; w += 16) {
  564. AacPsyBand *bands = &pch->band[w];
  565. /* 5.4.2.3 "Spreading" & 5.4.3 "Spread Energy Calculation" */
  566. spread_en[0] = bands[0].energy;
  567. for (g = 1; g < num_bands; g++) {
  568. bands[g].thr = FFMAX(bands[g].thr, bands[g-1].thr * coeffs[g].spread_hi[0]);
  569. spread_en[w+g] = FFMAX(bands[g].energy, spread_en[w+g-1] * coeffs[g].spread_hi[1]);
  570. }
  571. for (g = num_bands - 2; g >= 0; g--) {
  572. bands[g].thr = FFMAX(bands[g].thr, bands[g+1].thr * coeffs[g].spread_low[0]);
  573. spread_en[w+g] = FFMAX(spread_en[w+g], spread_en[w+g+1] * coeffs[g].spread_low[1]);
  574. }
  575. //5.4.2.4 "Threshold in quiet"
  576. for (g = 0; g < num_bands; g++) {
  577. AacPsyBand *band = &bands[g];
  578. band->thr_quiet = band->thr = FFMAX(band->thr, coeffs[g].ath);
  579. //5.4.2.5 "Pre-echo control"
  580. if (!(wi->window_type[0] == LONG_STOP_SEQUENCE || (wi->window_type[1] == LONG_START_SEQUENCE && !w)))
  581. band->thr = FFMAX(PSY_3GPP_RPEMIN*band->thr, FFMIN(band->thr,
  582. PSY_3GPP_RPELEV*pch->prev_band[w+g].thr_quiet));
  583. /* 5.6.1.3.1 "Preparatory steps of the perceptual entropy calculation" */
  584. pe += calc_pe_3gpp(band);
  585. a += band->pe_const;
  586. active_lines += band->active_lines;
  587. /* 5.6.1.3.3 "Selection of the bands for avoidance of holes" */
  588. if (spread_en[w+g] * avoid_hole_thr > band->energy || coeffs[g].min_snr > 1.0f)
  589. band->avoid_holes = PSY_3GPP_AH_NONE;
  590. else
  591. band->avoid_holes = PSY_3GPP_AH_INACTIVE;
  592. }
  593. }
  594. /* 5.6.1.3.2 "Calculation of the desired perceptual entropy" */
  595. ctx->ch[channel].entropy = pe;
  596. desired_bits = calc_bit_demand(pctx, pe, ctx->bitres.bits, ctx->bitres.size, wi->num_windows == 8);
  597. desired_pe = PSY_3GPP_BITS_TO_PE(desired_bits);
  598. /* NOTE: PE correction is kept simple. During initial testing it had very
  599. * little effect on the final bitrate. Probably a good idea to come
  600. * back and do more testing later.
  601. */
  602. if (ctx->bitres.bits > 0)
  603. desired_pe *= av_clipf(pctx->pe.previous / PSY_3GPP_BITS_TO_PE(ctx->bitres.bits),
  604. 0.85f, 1.15f);
  605. pctx->pe.previous = PSY_3GPP_BITS_TO_PE(desired_bits);
  606. if (desired_pe < pe) {
  607. /* 5.6.1.3.4 "First Estimation of the reduction value" */
  608. for (w = 0; w < wi->num_windows*16; w += 16) {
  609. reduction = calc_reduction_3gpp(a, desired_pe, pe, active_lines);
  610. pe = 0.0f;
  611. a = 0.0f;
  612. active_lines = 0.0f;
  613. for (g = 0; g < num_bands; g++) {
  614. AacPsyBand *band = &pch->band[w+g];
  615. band->thr = calc_reduced_thr_3gpp(band, coeffs[g].min_snr, reduction);
  616. /* recalculate PE */
  617. pe += calc_pe_3gpp(band);
  618. a += band->pe_const;
  619. active_lines += band->active_lines;
  620. }
  621. }
  622. /* 5.6.1.3.5 "Second Estimation of the reduction value" */
  623. for (i = 0; i < 2; i++) {
  624. float pe_no_ah = 0.0f, desired_pe_no_ah;
  625. active_lines = a = 0.0f;
  626. for (w = 0; w < wi->num_windows*16; w += 16) {
  627. for (g = 0; g < num_bands; g++) {
  628. AacPsyBand *band = &pch->band[w+g];
  629. if (band->avoid_holes != PSY_3GPP_AH_ACTIVE) {
  630. pe_no_ah += band->pe;
  631. a += band->pe_const;
  632. active_lines += band->active_lines;
  633. }
  634. }
  635. }
  636. desired_pe_no_ah = FFMAX(desired_pe - (pe - pe_no_ah), 0.0f);
  637. if (active_lines > 0.0f)
  638. reduction += calc_reduction_3gpp(a, desired_pe_no_ah, pe_no_ah, active_lines);
  639. pe = 0.0f;
  640. for (w = 0; w < wi->num_windows*16; w += 16) {
  641. for (g = 0; g < num_bands; g++) {
  642. AacPsyBand *band = &pch->band[w+g];
  643. if (active_lines > 0.0f)
  644. band->thr = calc_reduced_thr_3gpp(band, coeffs[g].min_snr, reduction);
  645. pe += calc_pe_3gpp(band);
  646. band->norm_fac = band->active_lines / band->thr;
  647. norm_fac += band->norm_fac;
  648. }
  649. }
  650. delta_pe = desired_pe - pe;
  651. if (fabs(delta_pe) > 0.05f * desired_pe)
  652. break;
  653. }
  654. if (pe < 1.15f * desired_pe) {
  655. /* 6.6.1.3.6 "Final threshold modification by linearization" */
  656. norm_fac = 1.0f / norm_fac;
  657. for (w = 0; w < wi->num_windows*16; w += 16) {
  658. for (g = 0; g < num_bands; g++) {
  659. AacPsyBand *band = &pch->band[w+g];
  660. if (band->active_lines > 0.5f) {
  661. float delta_sfb_pe = band->norm_fac * norm_fac * delta_pe;
  662. float thr = band->thr;
  663. thr *= exp2f(delta_sfb_pe / band->active_lines);
  664. if (thr > coeffs[g].min_snr * band->energy && band->avoid_holes == PSY_3GPP_AH_INACTIVE)
  665. thr = FFMAX(band->thr, coeffs[g].min_snr * band->energy);
  666. band->thr = thr;
  667. }
  668. }
  669. }
  670. } else {
  671. /* 5.6.1.3.7 "Further perceptual entropy reduction" */
  672. g = num_bands;
  673. while (pe > desired_pe && g--) {
  674. for (w = 0; w < wi->num_windows*16; w+= 16) {
  675. AacPsyBand *band = &pch->band[w+g];
  676. if (band->avoid_holes != PSY_3GPP_AH_NONE && coeffs[g].min_snr < PSY_SNR_1DB) {
  677. coeffs[g].min_snr = PSY_SNR_1DB;
  678. band->thr = band->energy * PSY_SNR_1DB;
  679. pe += band->active_lines * 1.5f - band->pe;
  680. }
  681. }
  682. }
  683. /* TODO: allow more holes (unused without mid/side) */
  684. }
  685. }
  686. for (w = 0; w < wi->num_windows*16; w += 16) {
  687. for (g = 0; g < num_bands; g++) {
  688. AacPsyBand *band = &pch->band[w+g];
  689. FFPsyBand *psy_band = &ctx->ch[channel].psy_bands[w+g];
  690. psy_band->threshold = band->thr;
  691. psy_band->energy = band->energy;
  692. }
  693. }
  694. memcpy(pch->prev_band, pch->band, sizeof(pch->band));
  695. }
  696. static void psy_3gpp_analyze(FFPsyContext *ctx, int channel,
  697. const float **coeffs, const FFPsyWindowInfo *wi)
  698. {
  699. int ch;
  700. FFPsyChannelGroup *group = ff_psy_find_group(ctx, channel);
  701. for (ch = 0; ch < group->num_ch; ch++)
  702. psy_3gpp_analyze_channel(ctx, channel + ch, coeffs[ch], &wi[ch]);
  703. }
  704. static av_cold void psy_3gpp_end(FFPsyContext *apc)
  705. {
  706. AacPsyContext *pctx = (AacPsyContext*) apc->model_priv_data;
  707. av_freep(&pctx->ch);
  708. av_freep(&apc->model_priv_data);
  709. }
  710. static void lame_apply_block_type(AacPsyChannel *ctx, FFPsyWindowInfo *wi, int uselongblock)
  711. {
  712. int blocktype = ONLY_LONG_SEQUENCE;
  713. if (uselongblock) {
  714. if (ctx->next_window_seq == EIGHT_SHORT_SEQUENCE)
  715. blocktype = LONG_STOP_SEQUENCE;
  716. } else {
  717. blocktype = EIGHT_SHORT_SEQUENCE;
  718. if (ctx->next_window_seq == ONLY_LONG_SEQUENCE)
  719. ctx->next_window_seq = LONG_START_SEQUENCE;
  720. if (ctx->next_window_seq == LONG_STOP_SEQUENCE)
  721. ctx->next_window_seq = EIGHT_SHORT_SEQUENCE;
  722. }
  723. wi->window_type[0] = ctx->next_window_seq;
  724. ctx->next_window_seq = blocktype;
  725. }
  726. static FFPsyWindowInfo psy_lame_window(FFPsyContext *ctx, const float *audio,
  727. const float *la, int channel, int prev_type)
  728. {
  729. AacPsyContext *pctx = (AacPsyContext*) ctx->model_priv_data;
  730. AacPsyChannel *pch = &pctx->ch[channel];
  731. int grouping = 0;
  732. int uselongblock = 1;
  733. int attacks[AAC_NUM_BLOCKS_SHORT + 1] = { 0 };
  734. int i;
  735. FFPsyWindowInfo wi = { { 0 } };
  736. if (la) {
  737. float hpfsmpl[AAC_BLOCK_SIZE_LONG];
  738. float const *pf = hpfsmpl;
  739. float attack_intensity[(AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS];
  740. float energy_subshort[(AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS];
  741. float energy_short[AAC_NUM_BLOCKS_SHORT + 1] = { 0 };
  742. const float *firbuf = la + (AAC_BLOCK_SIZE_SHORT/4 - PSY_LAME_FIR_LEN);
  743. int att_sum = 0;
  744. /* LAME comment: apply high pass filter of fs/4 */
  745. psy_hp_filter(firbuf, hpfsmpl, psy_fir_coeffs);
  746. /* Calculate the energies of each sub-shortblock */
  747. for (i = 0; i < PSY_LAME_NUM_SUBBLOCKS; i++) {
  748. energy_subshort[i] = pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 1) * PSY_LAME_NUM_SUBBLOCKS)];
  749. assert(pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 2) * PSY_LAME_NUM_SUBBLOCKS + 1)] > 0);
  750. attack_intensity[i] = energy_subshort[i] / pch->prev_energy_subshort[i + ((AAC_NUM_BLOCKS_SHORT - 2) * PSY_LAME_NUM_SUBBLOCKS + 1)];
  751. energy_short[0] += energy_subshort[i];
  752. }
  753. for (i = 0; i < AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS; i++) {
  754. float const *const pfe = pf + AAC_BLOCK_SIZE_LONG / (AAC_NUM_BLOCKS_SHORT * PSY_LAME_NUM_SUBBLOCKS);
  755. float p = 1.0f;
  756. for (; pf < pfe; pf++)
  757. p = FFMAX(p, fabsf(*pf));
  758. pch->prev_energy_subshort[i] = energy_subshort[i + PSY_LAME_NUM_SUBBLOCKS] = p;
  759. energy_short[1 + i / PSY_LAME_NUM_SUBBLOCKS] += p;
  760. /* NOTE: The indexes below are [i + 3 - 2] in the LAME source.
  761. * Obviously the 3 and 2 have some significance, or this would be just [i + 1]
  762. * (which is what we use here). What the 3 stands for is ambiguous, as it is both
  763. * number of short blocks, and the number of sub-short blocks.
  764. * It seems that LAME is comparing each sub-block to sub-block + 1 in the
  765. * previous block.
  766. */
  767. if (p > energy_subshort[i + 1])
  768. p = p / energy_subshort[i + 1];
  769. else if (energy_subshort[i + 1] > p * 10.0f)
  770. p = energy_subshort[i + 1] / (p * 10.0f);
  771. else
  772. p = 0.0;
  773. attack_intensity[i + PSY_LAME_NUM_SUBBLOCKS] = p;
  774. }
  775. /* compare energy between sub-short blocks */
  776. for (i = 0; i < (AAC_NUM_BLOCKS_SHORT + 1) * PSY_LAME_NUM_SUBBLOCKS; i++)
  777. if (!attacks[i / PSY_LAME_NUM_SUBBLOCKS])
  778. if (attack_intensity[i] > pch->attack_threshold)
  779. attacks[i / PSY_LAME_NUM_SUBBLOCKS] = (i % PSY_LAME_NUM_SUBBLOCKS) + 1;
  780. /* should have energy change between short blocks, in order to avoid periodic signals */
  781. /* Good samples to show the effect are Trumpet test songs */
  782. /* GB: tuned (1) to avoid too many short blocks for test sample TRUMPET */
  783. /* RH: tuned (2) to let enough short blocks through for test sample FSOL and SNAPS */
  784. for (i = 1; i < AAC_NUM_BLOCKS_SHORT + 1; i++) {
  785. float const u = energy_short[i - 1];
  786. float const v = energy_short[i];
  787. float const m = FFMAX(u, v);
  788. if (m < 40000) { /* (2) */
  789. if (u < 1.7f * v && v < 1.7f * u) { /* (1) */
  790. if (i == 1 && attacks[0] < attacks[i])
  791. attacks[0] = 0;
  792. attacks[i] = 0;
  793. }
  794. }
  795. att_sum += attacks[i];
  796. }
  797. if (attacks[0] <= pch->prev_attack)
  798. attacks[0] = 0;
  799. att_sum += attacks[0];
  800. /* 3 below indicates the previous attack happened in the last sub-block of the previous sequence */
  801. if (pch->prev_attack == 3 || att_sum) {
  802. uselongblock = 0;
  803. for (i = 1; i < AAC_NUM_BLOCKS_SHORT + 1; i++)
  804. if (attacks[i] && attacks[i-1])
  805. attacks[i] = 0;
  806. }
  807. } else {
  808. /* We have no lookahead info, so just use same type as the previous sequence. */
  809. uselongblock = !(prev_type == EIGHT_SHORT_SEQUENCE);
  810. }
  811. lame_apply_block_type(pch, &wi, uselongblock);
  812. wi.window_type[1] = prev_type;
  813. if (wi.window_type[0] != EIGHT_SHORT_SEQUENCE) {
  814. wi.num_windows = 1;
  815. wi.grouping[0] = 1;
  816. if (wi.window_type[0] == LONG_START_SEQUENCE)
  817. wi.window_shape = 0;
  818. else
  819. wi.window_shape = 1;
  820. } else {
  821. int lastgrp = 0;
  822. wi.num_windows = 8;
  823. wi.window_shape = 0;
  824. for (i = 0; i < 8; i++) {
  825. if (!((pch->next_grouping >> i) & 1))
  826. lastgrp = i;
  827. wi.grouping[lastgrp]++;
  828. }
  829. }
  830. /* Determine grouping, based on the location of the first attack, and save for
  831. * the next frame.
  832. * FIXME: Move this to analysis.
  833. * TODO: Tune groupings depending on attack location
  834. * TODO: Handle more than one attack in a group
  835. */
  836. for (i = 0; i < 9; i++) {
  837. if (attacks[i]) {
  838. grouping = i;
  839. break;
  840. }
  841. }
  842. pch->next_grouping = window_grouping[grouping];
  843. pch->prev_attack = attacks[8];
  844. return wi;
  845. }
  846. const FFPsyModel ff_aac_psy_model =
  847. {
  848. .name = "3GPP TS 26.403-inspired model",
  849. .init = psy_3gpp_init,
  850. .window = psy_lame_window,
  851. .analyze = psy_3gpp_analyze,
  852. .end = psy_3gpp_end,
  853. };