aacpsy.c 35 KB

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