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.

1700 lines
53KB

  1. /*
  2. * The simplest AC-3 encoder
  3. * Copyright (c) 2000 Fabrice Bellard
  4. * Copyright (c) 2006-2010 Justin Ruggles <justin.ruggles@gmail.com>
  5. * Copyright (c) 2006-2010 Prakash Punnoor <prakash@punnoor.de>
  6. *
  7. * This file is part of FFmpeg.
  8. *
  9. * FFmpeg is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU Lesser General Public
  11. * License as published by the Free Software Foundation; either
  12. * version 2.1 of the License, or (at your option) any later version.
  13. *
  14. * FFmpeg is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * Lesser General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Lesser General Public
  20. * License along with FFmpeg; if not, write to the Free Software
  21. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  22. */
  23. /**
  24. * @file
  25. * The simplest AC-3 encoder.
  26. */
  27. //#define DEBUG
  28. #include "libavcore/audioconvert.h"
  29. #include "libavutil/crc.h"
  30. #include "avcodec.h"
  31. #include "put_bits.h"
  32. #include "dsputil.h"
  33. #include "ac3.h"
  34. #include "audioconvert.h"
  35. #ifndef CONFIG_AC3ENC_FLOAT
  36. #define CONFIG_AC3ENC_FLOAT 0
  37. #endif
  38. /** Maximum number of exponent groups. +1 for separate DC exponent. */
  39. #define AC3_MAX_EXP_GROUPS 85
  40. /** Scale a float value by 2^bits and convert to an integer. */
  41. #define SCALE_FLOAT(a, bits) lrintf((a) * (float)(1 << (bits)))
  42. #if CONFIG_AC3ENC_FLOAT
  43. #include "ac3enc_float.h"
  44. #else
  45. #include "ac3enc_fixed.h"
  46. #endif
  47. /**
  48. * Data for a single audio block.
  49. */
  50. typedef struct AC3Block {
  51. uint8_t **bap; ///< bit allocation pointers (bap)
  52. CoefType **mdct_coef; ///< MDCT coefficients
  53. uint8_t **exp; ///< original exponents
  54. uint8_t **grouped_exp; ///< grouped exponents
  55. int16_t **psd; ///< psd per frequency bin
  56. int16_t **band_psd; ///< psd per critical band
  57. int16_t **mask; ///< masking curve
  58. uint16_t **qmant; ///< quantized mantissas
  59. uint8_t exp_strategy[AC3_MAX_CHANNELS]; ///< exponent strategies
  60. int8_t exp_shift[AC3_MAX_CHANNELS]; ///< exponent shift values
  61. } AC3Block;
  62. /**
  63. * AC-3 encoder private context.
  64. */
  65. typedef struct AC3EncodeContext {
  66. PutBitContext pb; ///< bitstream writer context
  67. DSPContext dsp;
  68. AC3MDCTContext mdct; ///< MDCT context
  69. AC3Block blocks[AC3_MAX_BLOCKS]; ///< per-block info
  70. int bitstream_id; ///< bitstream id (bsid)
  71. int bitstream_mode; ///< bitstream mode (bsmod)
  72. int bit_rate; ///< target bit rate, in bits-per-second
  73. int sample_rate; ///< sampling frequency, in Hz
  74. int frame_size_min; ///< minimum frame size in case rounding is necessary
  75. int frame_size; ///< current frame size in bytes
  76. int frame_size_code; ///< frame size code (frmsizecod)
  77. uint16_t crc_inv[2];
  78. int bits_written; ///< bit count (used to avg. bitrate)
  79. int samples_written; ///< sample count (used to avg. bitrate)
  80. int fbw_channels; ///< number of full-bandwidth channels (nfchans)
  81. int channels; ///< total number of channels (nchans)
  82. int lfe_on; ///< indicates if there is an LFE channel (lfeon)
  83. int lfe_channel; ///< channel index of the LFE channel
  84. int channel_mode; ///< channel mode (acmod)
  85. const uint8_t *channel_map; ///< channel map used to reorder channels
  86. int cutoff; ///< user-specified cutoff frequency, in Hz
  87. int bandwidth_code[AC3_MAX_CHANNELS]; ///< bandwidth code (0 to 60) (chbwcod)
  88. int nb_coefs[AC3_MAX_CHANNELS];
  89. /* bitrate allocation control */
  90. int slow_gain_code; ///< slow gain code (sgaincod)
  91. int slow_decay_code; ///< slow decay code (sdcycod)
  92. int fast_decay_code; ///< fast decay code (fdcycod)
  93. int db_per_bit_code; ///< dB/bit code (dbpbcod)
  94. int floor_code; ///< floor code (floorcod)
  95. AC3BitAllocParameters bit_alloc; ///< bit allocation parameters
  96. int coarse_snr_offset; ///< coarse SNR offsets (csnroffst)
  97. int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signal-to-mask ratio) (fgaincod)
  98. int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst)
  99. int frame_bits_fixed; ///< number of non-coefficient bits for fixed parameters
  100. int frame_bits; ///< all frame bits except exponents and mantissas
  101. int exponent_bits; ///< number of bits used for exponents
  102. /* mantissa encoding */
  103. int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
  104. uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
  105. SampleType **planar_samples;
  106. uint8_t *bap_buffer;
  107. uint8_t *bap1_buffer;
  108. CoefType *mdct_coef_buffer;
  109. uint8_t *exp_buffer;
  110. uint8_t *grouped_exp_buffer;
  111. int16_t *psd_buffer;
  112. int16_t *band_psd_buffer;
  113. int16_t *mask_buffer;
  114. uint16_t *qmant_buffer;
  115. DECLARE_ALIGNED(16, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
  116. } AC3EncodeContext;
  117. /* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
  118. static av_cold void mdct_end(AC3MDCTContext *mdct);
  119. static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
  120. int nbits);
  121. static void mdct512(AC3MDCTContext *mdct, CoefType *out, SampleType *in);
  122. static void apply_window(SampleType *output, const SampleType *input,
  123. const SampleType *window, int n);
  124. static int normalize_samples(AC3EncodeContext *s);
  125. /**
  126. * LUT for number of exponent groups.
  127. * exponent_group_tab[exponent strategy-1][number of coefficients]
  128. */
  129. static uint8_t exponent_group_tab[3][256];
  130. /**
  131. * List of supported channel layouts.
  132. */
  133. static const int64_t ac3_channel_layouts[] = {
  134. AV_CH_LAYOUT_MONO,
  135. AV_CH_LAYOUT_STEREO,
  136. AV_CH_LAYOUT_2_1,
  137. AV_CH_LAYOUT_SURROUND,
  138. AV_CH_LAYOUT_2_2,
  139. AV_CH_LAYOUT_QUAD,
  140. AV_CH_LAYOUT_4POINT0,
  141. AV_CH_LAYOUT_5POINT0,
  142. AV_CH_LAYOUT_5POINT0_BACK,
  143. (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
  144. (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
  145. (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
  146. (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
  147. (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
  148. (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
  149. (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
  150. AV_CH_LAYOUT_5POINT1,
  151. AV_CH_LAYOUT_5POINT1_BACK,
  152. 0
  153. };
  154. /**
  155. * Adjust the frame size to make the average bit rate match the target bit rate.
  156. * This is only needed for 11025, 22050, and 44100 sample rates.
  157. */
  158. static void adjust_frame_size(AC3EncodeContext *s)
  159. {
  160. while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
  161. s->bits_written -= s->bit_rate;
  162. s->samples_written -= s->sample_rate;
  163. }
  164. s->frame_size = s->frame_size_min +
  165. 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
  166. s->bits_written += s->frame_size * 8;
  167. s->samples_written += AC3_FRAME_SIZE;
  168. }
  169. /**
  170. * Deinterleave input samples.
  171. * Channels are reordered from FFmpeg's default order to AC-3 order.
  172. */
  173. static void deinterleave_input_samples(AC3EncodeContext *s,
  174. const SampleType *samples)
  175. {
  176. int ch, i;
  177. /* deinterleave and remap input samples */
  178. for (ch = 0; ch < s->channels; ch++) {
  179. const SampleType *sptr;
  180. int sinc;
  181. /* copy last 256 samples of previous frame to the start of the current frame */
  182. memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
  183. AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
  184. /* deinterleave */
  185. sinc = s->channels;
  186. sptr = samples + s->channel_map[ch];
  187. for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
  188. s->planar_samples[ch][i] = *sptr;
  189. sptr += sinc;
  190. }
  191. }
  192. }
  193. /**
  194. * Apply the MDCT to input samples to generate frequency coefficients.
  195. * This applies the KBD window and normalizes the input to reduce precision
  196. * loss due to fixed-point calculations.
  197. */
  198. static void apply_mdct(AC3EncodeContext *s)
  199. {
  200. int blk, ch;
  201. for (ch = 0; ch < s->channels; ch++) {
  202. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  203. AC3Block *block = &s->blocks[blk];
  204. const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
  205. apply_window(s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
  206. block->exp_shift[ch] = normalize_samples(s);
  207. mdct512(&s->mdct, block->mdct_coef[ch], s->windowed_samples);
  208. }
  209. }
  210. }
  211. /**
  212. * Initialize exponent tables.
  213. */
  214. static av_cold void exponent_init(AC3EncodeContext *s)
  215. {
  216. int i;
  217. for (i = 73; i < 256; i++) {
  218. exponent_group_tab[0][i] = (i - 1) / 3;
  219. exponent_group_tab[1][i] = (i + 2) / 6;
  220. exponent_group_tab[2][i] = (i + 8) / 12;
  221. }
  222. /* LFE */
  223. exponent_group_tab[0][7] = 2;
  224. }
  225. /**
  226. * Extract exponents from the MDCT coefficients.
  227. * This takes into account the normalization that was done to the input samples
  228. * by adjusting the exponents by the exponent shift values.
  229. */
  230. static void extract_exponents(AC3EncodeContext *s)
  231. {
  232. int blk, ch, i;
  233. for (ch = 0; ch < s->channels; ch++) {
  234. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  235. AC3Block *block = &s->blocks[blk];
  236. for (i = 0; i < AC3_MAX_COEFS; i++) {
  237. int e;
  238. int v = abs(SCALE_COEF(block->mdct_coef[ch][i]));
  239. if (v == 0)
  240. e = 24;
  241. else {
  242. e = 23 - av_log2(v) + block->exp_shift[ch];
  243. if (e >= 24) {
  244. e = 24;
  245. block->mdct_coef[ch][i] = 0;
  246. }
  247. }
  248. block->exp[ch][i] = e;
  249. }
  250. }
  251. }
  252. }
  253. /**
  254. * Exponent Difference Threshold.
  255. * New exponents are sent if their SAD exceed this number.
  256. */
  257. #define EXP_DIFF_THRESHOLD 1000
  258. /**
  259. * Calculate exponent strategies for all blocks in a single channel.
  260. */
  261. static void compute_exp_strategy_ch(AC3EncodeContext *s, uint8_t *exp_strategy,
  262. uint8_t **exp)
  263. {
  264. int blk, blk1;
  265. int exp_diff;
  266. /* estimate if the exponent variation & decide if they should be
  267. reused in the next frame */
  268. exp_strategy[0] = EXP_NEW;
  269. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
  270. exp_diff = s->dsp.sad[0](NULL, exp[blk], exp[blk-1], 16, 16);
  271. if (exp_diff > EXP_DIFF_THRESHOLD)
  272. exp_strategy[blk] = EXP_NEW;
  273. else
  274. exp_strategy[blk] = EXP_REUSE;
  275. }
  276. emms_c();
  277. /* now select the encoding strategy type : if exponents are often
  278. recoded, we use a coarse encoding */
  279. blk = 0;
  280. while (blk < AC3_MAX_BLOCKS) {
  281. blk1 = blk + 1;
  282. while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
  283. blk1++;
  284. switch (blk1 - blk) {
  285. case 1: exp_strategy[blk] = EXP_D45; break;
  286. case 2:
  287. case 3: exp_strategy[blk] = EXP_D25; break;
  288. default: exp_strategy[blk] = EXP_D15; break;
  289. }
  290. blk = blk1;
  291. }
  292. }
  293. /**
  294. * Calculate exponent strategies for all channels.
  295. * Array arrangement is reversed to simplify the per-channel calculation.
  296. */
  297. static void compute_exp_strategy(AC3EncodeContext *s)
  298. {
  299. uint8_t *exp1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
  300. uint8_t exp_str1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
  301. int ch, blk;
  302. for (ch = 0; ch < s->fbw_channels; ch++) {
  303. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  304. exp1[ch][blk] = s->blocks[blk].exp[ch];
  305. exp_str1[ch][blk] = s->blocks[blk].exp_strategy[ch];
  306. }
  307. compute_exp_strategy_ch(s, exp_str1[ch], exp1[ch]);
  308. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  309. s->blocks[blk].exp_strategy[ch] = exp_str1[ch][blk];
  310. }
  311. if (s->lfe_on) {
  312. ch = s->lfe_channel;
  313. s->blocks[0].exp_strategy[ch] = EXP_D15;
  314. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
  315. s->blocks[blk].exp_strategy[ch] = EXP_REUSE;
  316. }
  317. }
  318. /**
  319. * Set each encoded exponent in a block to the minimum of itself and the
  320. * exponent in the same frequency bin of a following block.
  321. * exp[i] = min(exp[i], exp1[i]
  322. */
  323. static void exponent_min(uint8_t *exp, uint8_t *exp1, int n)
  324. {
  325. int i;
  326. for (i = 0; i < n; i++) {
  327. if (exp1[i] < exp[i])
  328. exp[i] = exp1[i];
  329. }
  330. }
  331. /**
  332. * Update the exponents so that they are the ones the decoder will decode.
  333. */
  334. static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy)
  335. {
  336. int nb_groups, i, k;
  337. nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
  338. /* for each group, compute the minimum exponent */
  339. switch(exp_strategy) {
  340. case EXP_D25:
  341. for (i = 1, k = 1; i <= nb_groups; i++) {
  342. uint8_t exp_min = exp[k];
  343. if (exp[k+1] < exp_min)
  344. exp_min = exp[k+1];
  345. exp[i] = exp_min;
  346. k += 2;
  347. }
  348. break;
  349. case EXP_D45:
  350. for (i = 1, k = 1; i <= nb_groups; i++) {
  351. uint8_t exp_min = exp[k];
  352. if (exp[k+1] < exp_min)
  353. exp_min = exp[k+1];
  354. if (exp[k+2] < exp_min)
  355. exp_min = exp[k+2];
  356. if (exp[k+3] < exp_min)
  357. exp_min = exp[k+3];
  358. exp[i] = exp_min;
  359. k += 4;
  360. }
  361. break;
  362. }
  363. /* constraint for DC exponent */
  364. if (exp[0] > 15)
  365. exp[0] = 15;
  366. /* decrease the delta between each groups to within 2 so that they can be
  367. differentially encoded */
  368. for (i = 1; i <= nb_groups; i++)
  369. exp[i] = FFMIN(exp[i], exp[i-1] + 2);
  370. i--;
  371. while (--i >= 0)
  372. exp[i] = FFMIN(exp[i], exp[i+1] + 2);
  373. /* now we have the exponent values the decoder will see */
  374. switch (exp_strategy) {
  375. case EXP_D25:
  376. for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
  377. uint8_t exp1 = exp[i];
  378. exp[k--] = exp1;
  379. exp[k--] = exp1;
  380. }
  381. break;
  382. case EXP_D45:
  383. for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
  384. exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
  385. k -= 4;
  386. }
  387. break;
  388. }
  389. }
  390. /**
  391. * Encode exponents from original extracted form to what the decoder will see.
  392. * This copies and groups exponents based on exponent strategy and reduces
  393. * deltas between adjacent exponent groups so that they can be differentially
  394. * encoded.
  395. */
  396. static void encode_exponents(AC3EncodeContext *s)
  397. {
  398. int blk, blk1, blk2, ch;
  399. AC3Block *block, *block1, *block2;
  400. for (ch = 0; ch < s->channels; ch++) {
  401. blk = 0;
  402. block = &s->blocks[0];
  403. while (blk < AC3_MAX_BLOCKS) {
  404. blk1 = blk + 1;
  405. block1 = block + 1;
  406. /* for the EXP_REUSE case we select the min of the exponents */
  407. while (blk1 < AC3_MAX_BLOCKS && block1->exp_strategy[ch] == EXP_REUSE) {
  408. exponent_min(block->exp[ch], block1->exp[ch], s->nb_coefs[ch]);
  409. blk1++;
  410. block1++;
  411. }
  412. encode_exponents_blk_ch(block->exp[ch], s->nb_coefs[ch],
  413. block->exp_strategy[ch]);
  414. /* copy encoded exponents for reuse case */
  415. block2 = block + 1;
  416. for (blk2 = blk+1; blk2 < blk1; blk2++, block2++) {
  417. memcpy(block2->exp[ch], block->exp[ch],
  418. s->nb_coefs[ch] * sizeof(uint8_t));
  419. }
  420. blk = blk1;
  421. block = block1;
  422. }
  423. }
  424. }
  425. /**
  426. * Group exponents.
  427. * 3 delta-encoded exponents are in each 7-bit group. The number of groups
  428. * varies depending on exponent strategy and bandwidth.
  429. */
  430. static void group_exponents(AC3EncodeContext *s)
  431. {
  432. int blk, ch, i;
  433. int group_size, nb_groups, bit_count;
  434. uint8_t *p;
  435. int delta0, delta1, delta2;
  436. int exp0, exp1;
  437. bit_count = 0;
  438. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  439. AC3Block *block = &s->blocks[blk];
  440. for (ch = 0; ch < s->channels; ch++) {
  441. if (block->exp_strategy[ch] == EXP_REUSE) {
  442. continue;
  443. }
  444. group_size = block->exp_strategy[ch] + (block->exp_strategy[ch] == EXP_D45);
  445. nb_groups = exponent_group_tab[block->exp_strategy[ch]-1][s->nb_coefs[ch]];
  446. bit_count += 4 + (nb_groups * 7);
  447. p = block->exp[ch];
  448. /* DC exponent */
  449. exp1 = *p++;
  450. block->grouped_exp[ch][0] = exp1;
  451. /* remaining exponents are delta encoded */
  452. for (i = 1; i <= nb_groups; i++) {
  453. /* merge three delta in one code */
  454. exp0 = exp1;
  455. exp1 = p[0];
  456. p += group_size;
  457. delta0 = exp1 - exp0 + 2;
  458. exp0 = exp1;
  459. exp1 = p[0];
  460. p += group_size;
  461. delta1 = exp1 - exp0 + 2;
  462. exp0 = exp1;
  463. exp1 = p[0];
  464. p += group_size;
  465. delta2 = exp1 - exp0 + 2;
  466. block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
  467. }
  468. }
  469. }
  470. s->exponent_bits = bit_count;
  471. }
  472. /**
  473. * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
  474. * Extract exponents from MDCT coefficients, calculate exponent strategies,
  475. * and encode final exponents.
  476. */
  477. static void process_exponents(AC3EncodeContext *s)
  478. {
  479. extract_exponents(s);
  480. compute_exp_strategy(s);
  481. encode_exponents(s);
  482. group_exponents(s);
  483. }
  484. /**
  485. * Count frame bits that are based solely on fixed parameters.
  486. * This only has to be run once when the encoder is initialized.
  487. */
  488. static void count_frame_bits_fixed(AC3EncodeContext *s)
  489. {
  490. static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
  491. int blk;
  492. int frame_bits;
  493. /* assumptions:
  494. * no dynamic range codes
  495. * no channel coupling
  496. * no rematrixing
  497. * bit allocation parameters do not change between blocks
  498. * SNR offsets do not change between blocks
  499. * no delta bit allocation
  500. * no skipped data
  501. * no auxilliary data
  502. */
  503. /* header size */
  504. frame_bits = 65;
  505. frame_bits += frame_bits_inc[s->channel_mode];
  506. /* audio blocks */
  507. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  508. frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
  509. if (s->channel_mode == AC3_CHMODE_STEREO) {
  510. frame_bits++; /* rematstr */
  511. if (!blk)
  512. frame_bits += 4;
  513. }
  514. frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
  515. if (s->lfe_on)
  516. frame_bits++; /* lfeexpstr */
  517. frame_bits++; /* baie */
  518. frame_bits++; /* snr */
  519. frame_bits += 2; /* delta / skip */
  520. }
  521. frame_bits++; /* cplinu for block 0 */
  522. /* bit alloc info */
  523. /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
  524. /* csnroffset[6] */
  525. /* (fsnoffset[4] + fgaincod[4]) * c */
  526. frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
  527. /* auxdatae, crcrsv */
  528. frame_bits += 2;
  529. /* CRC */
  530. frame_bits += 16;
  531. s->frame_bits_fixed = frame_bits;
  532. }
  533. /**
  534. * Initialize bit allocation.
  535. * Set default parameter codes and calculate parameter values.
  536. */
  537. static void bit_alloc_init(AC3EncodeContext *s)
  538. {
  539. int ch;
  540. /* init default parameters */
  541. s->slow_decay_code = 2;
  542. s->fast_decay_code = 1;
  543. s->slow_gain_code = 1;
  544. s->db_per_bit_code = 3;
  545. s->floor_code = 4;
  546. for (ch = 0; ch < s->channels; ch++)
  547. s->fast_gain_code[ch] = 4;
  548. /* initial snr offset */
  549. s->coarse_snr_offset = 40;
  550. /* compute real values */
  551. /* currently none of these values change during encoding, so we can just
  552. set them once at initialization */
  553. s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
  554. s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
  555. s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
  556. s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
  557. s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
  558. count_frame_bits_fixed(s);
  559. }
  560. /**
  561. * Count the bits used to encode the frame, minus exponents and mantissas.
  562. * Bits based on fixed parameters have already been counted, so now we just
  563. * have to add the bits based on parameters that change during encoding.
  564. */
  565. static void count_frame_bits(AC3EncodeContext *s)
  566. {
  567. int blk, ch;
  568. int frame_bits = 0;
  569. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  570. uint8_t *exp_strategy = s->blocks[blk].exp_strategy;
  571. for (ch = 0; ch < s->fbw_channels; ch++) {
  572. if (exp_strategy[ch] != EXP_REUSE)
  573. frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
  574. }
  575. }
  576. s->frame_bits = s->frame_bits_fixed + frame_bits;
  577. }
  578. /**
  579. * Calculate the number of bits needed to encode a set of mantissas.
  580. */
  581. static int compute_mantissa_size(int mant_cnt[5], uint8_t *bap, int nb_coefs)
  582. {
  583. int bits, b, i;
  584. bits = 0;
  585. for (i = 0; i < nb_coefs; i++) {
  586. b = bap[i];
  587. if (b <= 4) {
  588. // bap=1 to bap=4 will be counted in compute_mantissa_size_final
  589. mant_cnt[b]++;
  590. } else if (b <= 13) {
  591. // bap=5 to bap=13 use (bap-1) bits
  592. bits += b - 1;
  593. } else {
  594. // bap=14 uses 14 bits and bap=15 uses 16 bits
  595. bits += (b == 14) ? 14 : 16;
  596. }
  597. }
  598. return bits;
  599. }
  600. /**
  601. * Finalize the mantissa bit count by adding in the grouped mantissas.
  602. */
  603. static int compute_mantissa_size_final(int mant_cnt[5])
  604. {
  605. // bap=1 : 3 mantissas in 5 bits
  606. int bits = (mant_cnt[1] / 3) * 5;
  607. // bap=2 : 3 mantissas in 7 bits
  608. // bap=4 : 2 mantissas in 7 bits
  609. bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
  610. // bap=3 : each mantissa is 3 bits
  611. bits += mant_cnt[3] * 3;
  612. return bits;
  613. }
  614. /**
  615. * Calculate masking curve based on the final exponents.
  616. * Also calculate the power spectral densities to use in future calculations.
  617. */
  618. static void bit_alloc_masking(AC3EncodeContext *s)
  619. {
  620. int blk, ch;
  621. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  622. AC3Block *block = &s->blocks[blk];
  623. for (ch = 0; ch < s->channels; ch++) {
  624. /* We only need psd and mask for calculating bap.
  625. Since we currently do not calculate bap when exponent
  626. strategy is EXP_REUSE we do not need to calculate psd or mask. */
  627. if (block->exp_strategy[ch] != EXP_REUSE) {
  628. ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
  629. s->nb_coefs[ch],
  630. block->psd[ch], block->band_psd[ch]);
  631. ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
  632. 0, s->nb_coefs[ch],
  633. ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
  634. ch == s->lfe_channel,
  635. DBA_NONE, 0, NULL, NULL, NULL,
  636. block->mask[ch]);
  637. }
  638. }
  639. }
  640. }
  641. /**
  642. * Ensure that bap for each block and channel point to the current bap_buffer.
  643. * They may have been switched during the bit allocation search.
  644. */
  645. static void reset_block_bap(AC3EncodeContext *s)
  646. {
  647. int blk, ch;
  648. if (s->blocks[0].bap[0] == s->bap_buffer)
  649. return;
  650. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  651. for (ch = 0; ch < s->channels; ch++) {
  652. s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
  653. }
  654. }
  655. }
  656. /**
  657. * Run the bit allocation with a given SNR offset.
  658. * This calculates the bit allocation pointers that will be used to determine
  659. * the quantization of each mantissa.
  660. * @return the number of bits needed for mantissas if the given SNR offset is
  661. * is used.
  662. */
  663. static int bit_alloc(AC3EncodeContext *s, int snr_offset)
  664. {
  665. int blk, ch;
  666. int mantissa_bits;
  667. int mant_cnt[5];
  668. snr_offset = (snr_offset - 240) << 2;
  669. reset_block_bap(s);
  670. mantissa_bits = 0;
  671. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  672. AC3Block *block = &s->blocks[blk];
  673. // initialize grouped mantissa counts. these are set so that they are
  674. // padded to the next whole group size when bits are counted in
  675. // compute_mantissa_size_final
  676. mant_cnt[0] = mant_cnt[3] = 0;
  677. mant_cnt[1] = mant_cnt[2] = 2;
  678. mant_cnt[4] = 1;
  679. for (ch = 0; ch < s->channels; ch++) {
  680. /* Currently the only bit allocation parameters which vary across
  681. blocks within a frame are the exponent values. We can take
  682. advantage of that by reusing the bit allocation pointers
  683. whenever we reuse exponents. */
  684. if (block->exp_strategy[ch] == EXP_REUSE) {
  685. memcpy(block->bap[ch], s->blocks[blk-1].bap[ch], AC3_MAX_COEFS);
  686. } else {
  687. ff_ac3_bit_alloc_calc_bap(block->mask[ch], block->psd[ch], 0,
  688. s->nb_coefs[ch], snr_offset,
  689. s->bit_alloc.floor, ff_ac3_bap_tab,
  690. block->bap[ch]);
  691. }
  692. mantissa_bits += compute_mantissa_size(mant_cnt, block->bap[ch], s->nb_coefs[ch]);
  693. }
  694. mantissa_bits += compute_mantissa_size_final(mant_cnt);
  695. }
  696. return mantissa_bits;
  697. }
  698. /**
  699. * Constant bitrate bit allocation search.
  700. * Find the largest SNR offset that will allow data to fit in the frame.
  701. */
  702. static int cbr_bit_allocation(AC3EncodeContext *s)
  703. {
  704. int ch;
  705. int bits_left;
  706. int snr_offset, snr_incr;
  707. bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
  708. snr_offset = s->coarse_snr_offset << 4;
  709. /* if previous frame SNR offset was 1023, check if current frame can also
  710. use SNR offset of 1023. if so, skip the search. */
  711. if ((snr_offset | s->fine_snr_offset[0]) == 1023) {
  712. if (bit_alloc(s, 1023) <= bits_left)
  713. return 0;
  714. }
  715. while (snr_offset >= 0 &&
  716. bit_alloc(s, snr_offset) > bits_left) {
  717. snr_offset -= 64;
  718. }
  719. if (snr_offset < 0)
  720. return AVERROR(EINVAL);
  721. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  722. for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
  723. while (snr_offset + snr_incr <= 1023 &&
  724. bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
  725. snr_offset += snr_incr;
  726. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  727. }
  728. }
  729. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  730. reset_block_bap(s);
  731. s->coarse_snr_offset = snr_offset >> 4;
  732. for (ch = 0; ch < s->channels; ch++)
  733. s->fine_snr_offset[ch] = snr_offset & 0xF;
  734. return 0;
  735. }
  736. /**
  737. * Downgrade exponent strategies to reduce the bits used by the exponents.
  738. * This is a fallback for when bit allocation fails with the normal exponent
  739. * strategies. Each time this function is run it only downgrades the
  740. * strategy in 1 channel of 1 block.
  741. * @return non-zero if downgrade was unsuccessful
  742. */
  743. static int downgrade_exponents(AC3EncodeContext *s)
  744. {
  745. int ch, blk;
  746. for (ch = 0; ch < s->fbw_channels; ch++) {
  747. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  748. if (s->blocks[blk].exp_strategy[ch] == EXP_D15) {
  749. s->blocks[blk].exp_strategy[ch] = EXP_D25;
  750. return 0;
  751. }
  752. }
  753. }
  754. for (ch = 0; ch < s->fbw_channels; ch++) {
  755. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  756. if (s->blocks[blk].exp_strategy[ch] == EXP_D25) {
  757. s->blocks[blk].exp_strategy[ch] = EXP_D45;
  758. return 0;
  759. }
  760. }
  761. }
  762. for (ch = 0; ch < s->fbw_channels; ch++) {
  763. /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
  764. the block number > 0 */
  765. for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
  766. if (s->blocks[blk].exp_strategy[ch] > EXP_REUSE) {
  767. s->blocks[blk].exp_strategy[ch] = EXP_REUSE;
  768. return 0;
  769. }
  770. }
  771. }
  772. return -1;
  773. }
  774. /**
  775. * Reduce the bandwidth to reduce the number of bits used for a given SNR offset.
  776. * This is a second fallback for when bit allocation still fails after exponents
  777. * have been downgraded.
  778. * @return non-zero if bandwidth reduction was unsuccessful
  779. */
  780. static int reduce_bandwidth(AC3EncodeContext *s, int min_bw_code)
  781. {
  782. int ch;
  783. if (s->bandwidth_code[0] > min_bw_code) {
  784. for (ch = 0; ch < s->fbw_channels; ch++) {
  785. s->bandwidth_code[ch]--;
  786. s->nb_coefs[ch] = s->bandwidth_code[ch] * 3 + 73;
  787. }
  788. return 0;
  789. }
  790. return -1;
  791. }
  792. /**
  793. * Perform bit allocation search.
  794. * Finds the SNR offset value that maximizes quality and fits in the specified
  795. * frame size. Output is the SNR offset and a set of bit allocation pointers
  796. * used to quantize the mantissas.
  797. */
  798. static int compute_bit_allocation(AC3EncodeContext *s)
  799. {
  800. int ret;
  801. count_frame_bits(s);
  802. bit_alloc_masking(s);
  803. ret = cbr_bit_allocation(s);
  804. while (ret) {
  805. /* fallback 1: downgrade exponents */
  806. if (!downgrade_exponents(s)) {
  807. extract_exponents(s);
  808. encode_exponents(s);
  809. group_exponents(s);
  810. ret = compute_bit_allocation(s);
  811. continue;
  812. }
  813. /* fallback 2: reduce bandwidth */
  814. /* only do this if the user has not specified a specific cutoff
  815. frequency */
  816. if (!s->cutoff && !reduce_bandwidth(s, 0)) {
  817. process_exponents(s);
  818. ret = compute_bit_allocation(s);
  819. continue;
  820. }
  821. /* fallbacks were not enough... */
  822. break;
  823. }
  824. return ret;
  825. }
  826. /**
  827. * Symmetric quantization on 'levels' levels.
  828. */
  829. static inline int sym_quant(int c, int e, int levels)
  830. {
  831. int v;
  832. if (c >= 0) {
  833. v = (levels * (c << e)) >> 24;
  834. v = (v + 1) >> 1;
  835. v = (levels >> 1) + v;
  836. } else {
  837. v = (levels * ((-c) << e)) >> 24;
  838. v = (v + 1) >> 1;
  839. v = (levels >> 1) - v;
  840. }
  841. assert(v >= 0 && v < levels);
  842. return v;
  843. }
  844. /**
  845. * Asymmetric quantization on 2^qbits levels.
  846. */
  847. static inline int asym_quant(int c, int e, int qbits)
  848. {
  849. int lshift, m, v;
  850. lshift = e + qbits - 24;
  851. if (lshift >= 0)
  852. v = c << lshift;
  853. else
  854. v = c >> (-lshift);
  855. /* rounding */
  856. v = (v + 1) >> 1;
  857. m = (1 << (qbits-1));
  858. if (v >= m)
  859. v = m - 1;
  860. assert(v >= -m);
  861. return v & ((1 << qbits)-1);
  862. }
  863. /**
  864. * Quantize a set of mantissas for a single channel in a single block.
  865. */
  866. static void quantize_mantissas_blk_ch(AC3EncodeContext *s, CoefType *mdct_coef,
  867. int8_t exp_shift, uint8_t *exp,
  868. uint8_t *bap, uint16_t *qmant, int n)
  869. {
  870. int i;
  871. for (i = 0; i < n; i++) {
  872. int v;
  873. int c = SCALE_COEF(mdct_coef[i]);
  874. int e = exp[i] - exp_shift;
  875. int b = bap[i];
  876. switch (b) {
  877. case 0:
  878. v = 0;
  879. break;
  880. case 1:
  881. v = sym_quant(c, e, 3);
  882. switch (s->mant1_cnt) {
  883. case 0:
  884. s->qmant1_ptr = &qmant[i];
  885. v = 9 * v;
  886. s->mant1_cnt = 1;
  887. break;
  888. case 1:
  889. *s->qmant1_ptr += 3 * v;
  890. s->mant1_cnt = 2;
  891. v = 128;
  892. break;
  893. default:
  894. *s->qmant1_ptr += v;
  895. s->mant1_cnt = 0;
  896. v = 128;
  897. break;
  898. }
  899. break;
  900. case 2:
  901. v = sym_quant(c, e, 5);
  902. switch (s->mant2_cnt) {
  903. case 0:
  904. s->qmant2_ptr = &qmant[i];
  905. v = 25 * v;
  906. s->mant2_cnt = 1;
  907. break;
  908. case 1:
  909. *s->qmant2_ptr += 5 * v;
  910. s->mant2_cnt = 2;
  911. v = 128;
  912. break;
  913. default:
  914. *s->qmant2_ptr += v;
  915. s->mant2_cnt = 0;
  916. v = 128;
  917. break;
  918. }
  919. break;
  920. case 3:
  921. v = sym_quant(c, e, 7);
  922. break;
  923. case 4:
  924. v = sym_quant(c, e, 11);
  925. switch (s->mant4_cnt) {
  926. case 0:
  927. s->qmant4_ptr = &qmant[i];
  928. v = 11 * v;
  929. s->mant4_cnt = 1;
  930. break;
  931. default:
  932. *s->qmant4_ptr += v;
  933. s->mant4_cnt = 0;
  934. v = 128;
  935. break;
  936. }
  937. break;
  938. case 5:
  939. v = sym_quant(c, e, 15);
  940. break;
  941. case 14:
  942. v = asym_quant(c, e, 14);
  943. break;
  944. case 15:
  945. v = asym_quant(c, e, 16);
  946. break;
  947. default:
  948. v = asym_quant(c, e, b - 1);
  949. break;
  950. }
  951. qmant[i] = v;
  952. }
  953. }
  954. /**
  955. * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
  956. */
  957. static void quantize_mantissas(AC3EncodeContext *s)
  958. {
  959. int blk, ch;
  960. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  961. AC3Block *block = &s->blocks[blk];
  962. s->mant1_cnt = s->mant2_cnt = s->mant4_cnt = 0;
  963. s->qmant1_ptr = s->qmant2_ptr = s->qmant4_ptr = NULL;
  964. for (ch = 0; ch < s->channels; ch++) {
  965. quantize_mantissas_blk_ch(s, block->mdct_coef[ch], block->exp_shift[ch],
  966. block->exp[ch], block->bap[ch],
  967. block->qmant[ch], s->nb_coefs[ch]);
  968. }
  969. }
  970. }
  971. /**
  972. * Write the AC-3 frame header to the output bitstream.
  973. */
  974. static void output_frame_header(AC3EncodeContext *s)
  975. {
  976. put_bits(&s->pb, 16, 0x0b77); /* frame header */
  977. put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
  978. put_bits(&s->pb, 2, s->bit_alloc.sr_code);
  979. put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
  980. put_bits(&s->pb, 5, s->bitstream_id);
  981. put_bits(&s->pb, 3, s->bitstream_mode);
  982. put_bits(&s->pb, 3, s->channel_mode);
  983. if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
  984. put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
  985. if (s->channel_mode & 0x04)
  986. put_bits(&s->pb, 2, 1); /* XXX -6 dB */
  987. if (s->channel_mode == AC3_CHMODE_STEREO)
  988. put_bits(&s->pb, 2, 0); /* surround not indicated */
  989. put_bits(&s->pb, 1, s->lfe_on); /* LFE */
  990. put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
  991. put_bits(&s->pb, 1, 0); /* no compression control word */
  992. put_bits(&s->pb, 1, 0); /* no lang code */
  993. put_bits(&s->pb, 1, 0); /* no audio production info */
  994. put_bits(&s->pb, 1, 0); /* no copyright */
  995. put_bits(&s->pb, 1, 1); /* original bitstream */
  996. put_bits(&s->pb, 1, 0); /* no time code 1 */
  997. put_bits(&s->pb, 1, 0); /* no time code 2 */
  998. put_bits(&s->pb, 1, 0); /* no additional bit stream info */
  999. }
  1000. /**
  1001. * Write one audio block to the output bitstream.
  1002. */
  1003. static void output_audio_block(AC3EncodeContext *s, int block_num)
  1004. {
  1005. int ch, i, baie, rbnd;
  1006. AC3Block *block = &s->blocks[block_num];
  1007. /* block switching */
  1008. for (ch = 0; ch < s->fbw_channels; ch++)
  1009. put_bits(&s->pb, 1, 0);
  1010. /* dither flags */
  1011. for (ch = 0; ch < s->fbw_channels; ch++)
  1012. put_bits(&s->pb, 1, 1);
  1013. /* dynamic range codes */
  1014. put_bits(&s->pb, 1, 0);
  1015. /* channel coupling */
  1016. if (!block_num) {
  1017. put_bits(&s->pb, 1, 1); /* coupling strategy present */
  1018. put_bits(&s->pb, 1, 0); /* no coupling strategy */
  1019. } else {
  1020. put_bits(&s->pb, 1, 0); /* no new coupling strategy */
  1021. }
  1022. /* stereo rematrixing */
  1023. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1024. if (!block_num) {
  1025. /* first block must define rematrixing (rematstr) */
  1026. put_bits(&s->pb, 1, 1);
  1027. /* dummy rematrixing rematflg(1:4)=0 */
  1028. for (rbnd = 0; rbnd < 4; rbnd++)
  1029. put_bits(&s->pb, 1, 0);
  1030. } else {
  1031. /* no matrixing (but should be used in the future) */
  1032. put_bits(&s->pb, 1, 0);
  1033. }
  1034. }
  1035. /* exponent strategy */
  1036. for (ch = 0; ch < s->fbw_channels; ch++)
  1037. put_bits(&s->pb, 2, block->exp_strategy[ch]);
  1038. if (s->lfe_on)
  1039. put_bits(&s->pb, 1, block->exp_strategy[s->lfe_channel]);
  1040. /* bandwidth */
  1041. for (ch = 0; ch < s->fbw_channels; ch++) {
  1042. if (block->exp_strategy[ch] != EXP_REUSE)
  1043. put_bits(&s->pb, 6, s->bandwidth_code[ch]);
  1044. }
  1045. /* exponents */
  1046. for (ch = 0; ch < s->channels; ch++) {
  1047. int nb_groups;
  1048. if (block->exp_strategy[ch] == EXP_REUSE)
  1049. continue;
  1050. /* DC exponent */
  1051. put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
  1052. /* exponent groups */
  1053. nb_groups = exponent_group_tab[block->exp_strategy[ch]-1][s->nb_coefs[ch]];
  1054. for (i = 1; i <= nb_groups; i++)
  1055. put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
  1056. /* gain range info */
  1057. if (ch != s->lfe_channel)
  1058. put_bits(&s->pb, 2, 0);
  1059. }
  1060. /* bit allocation info */
  1061. baie = (block_num == 0);
  1062. put_bits(&s->pb, 1, baie);
  1063. if (baie) {
  1064. put_bits(&s->pb, 2, s->slow_decay_code);
  1065. put_bits(&s->pb, 2, s->fast_decay_code);
  1066. put_bits(&s->pb, 2, s->slow_gain_code);
  1067. put_bits(&s->pb, 2, s->db_per_bit_code);
  1068. put_bits(&s->pb, 3, s->floor_code);
  1069. }
  1070. /* snr offset */
  1071. put_bits(&s->pb, 1, baie);
  1072. if (baie) {
  1073. put_bits(&s->pb, 6, s->coarse_snr_offset);
  1074. for (ch = 0; ch < s->channels; ch++) {
  1075. put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
  1076. put_bits(&s->pb, 3, s->fast_gain_code[ch]);
  1077. }
  1078. }
  1079. put_bits(&s->pb, 1, 0); /* no delta bit allocation */
  1080. put_bits(&s->pb, 1, 0); /* no data to skip */
  1081. /* mantissas */
  1082. for (ch = 0; ch < s->channels; ch++) {
  1083. int b, q;
  1084. for (i = 0; i < s->nb_coefs[ch]; i++) {
  1085. q = block->qmant[ch][i];
  1086. b = block->bap[ch][i];
  1087. switch (b) {
  1088. case 0: break;
  1089. case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
  1090. case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
  1091. case 3: put_bits(&s->pb, 3, q); break;
  1092. case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
  1093. case 14: put_bits(&s->pb, 14, q); break;
  1094. case 15: put_bits(&s->pb, 16, q); break;
  1095. default: put_bits(&s->pb, b-1, q); break;
  1096. }
  1097. }
  1098. }
  1099. }
  1100. /** CRC-16 Polynomial */
  1101. #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
  1102. static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
  1103. {
  1104. unsigned int c;
  1105. c = 0;
  1106. while (a) {
  1107. if (a & 1)
  1108. c ^= b;
  1109. a = a >> 1;
  1110. b = b << 1;
  1111. if (b & (1 << 16))
  1112. b ^= poly;
  1113. }
  1114. return c;
  1115. }
  1116. static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
  1117. {
  1118. unsigned int r;
  1119. r = 1;
  1120. while (n) {
  1121. if (n & 1)
  1122. r = mul_poly(r, a, poly);
  1123. a = mul_poly(a, a, poly);
  1124. n >>= 1;
  1125. }
  1126. return r;
  1127. }
  1128. /**
  1129. * Fill the end of the frame with 0's and compute the two CRCs.
  1130. */
  1131. static void output_frame_end(AC3EncodeContext *s)
  1132. {
  1133. const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
  1134. int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
  1135. uint8_t *frame;
  1136. frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
  1137. /* pad the remainder of the frame with zeros */
  1138. flush_put_bits(&s->pb);
  1139. frame = s->pb.buf;
  1140. pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
  1141. assert(pad_bytes >= 0);
  1142. if (pad_bytes > 0)
  1143. memset(put_bits_ptr(&s->pb), 0, pad_bytes);
  1144. /* compute crc1 */
  1145. /* this is not so easy because it is at the beginning of the data... */
  1146. crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
  1147. crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
  1148. crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
  1149. AV_WB16(frame + 2, crc1);
  1150. /* compute crc2 */
  1151. crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
  1152. s->frame_size - frame_size_58 - 3);
  1153. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1154. /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
  1155. if (crc2 == 0x770B) {
  1156. frame[s->frame_size - 3] ^= 0x1;
  1157. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1158. }
  1159. crc2 = av_bswap16(crc2);
  1160. AV_WB16(frame + s->frame_size - 2, crc2);
  1161. }
  1162. /**
  1163. * Write the frame to the output bitstream.
  1164. */
  1165. static void output_frame(AC3EncodeContext *s, unsigned char *frame)
  1166. {
  1167. int blk;
  1168. init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
  1169. output_frame_header(s);
  1170. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1171. output_audio_block(s, blk);
  1172. output_frame_end(s);
  1173. }
  1174. /**
  1175. * Encode a single AC-3 frame.
  1176. */
  1177. static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
  1178. int buf_size, void *data)
  1179. {
  1180. AC3EncodeContext *s = avctx->priv_data;
  1181. const SampleType *samples = data;
  1182. int ret;
  1183. if (s->bit_alloc.sr_code == 1)
  1184. adjust_frame_size(s);
  1185. deinterleave_input_samples(s, samples);
  1186. apply_mdct(s);
  1187. process_exponents(s);
  1188. ret = compute_bit_allocation(s);
  1189. if (ret) {
  1190. av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
  1191. return ret;
  1192. }
  1193. quantize_mantissas(s);
  1194. output_frame(s, frame);
  1195. return s->frame_size;
  1196. }
  1197. /**
  1198. * Finalize encoding and free any memory allocated by the encoder.
  1199. */
  1200. static av_cold int ac3_encode_close(AVCodecContext *avctx)
  1201. {
  1202. int blk, ch;
  1203. AC3EncodeContext *s = avctx->priv_data;
  1204. for (ch = 0; ch < s->channels; ch++)
  1205. av_freep(&s->planar_samples[ch]);
  1206. av_freep(&s->planar_samples);
  1207. av_freep(&s->bap_buffer);
  1208. av_freep(&s->bap1_buffer);
  1209. av_freep(&s->mdct_coef_buffer);
  1210. av_freep(&s->exp_buffer);
  1211. av_freep(&s->grouped_exp_buffer);
  1212. av_freep(&s->psd_buffer);
  1213. av_freep(&s->band_psd_buffer);
  1214. av_freep(&s->mask_buffer);
  1215. av_freep(&s->qmant_buffer);
  1216. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1217. AC3Block *block = &s->blocks[blk];
  1218. av_freep(&block->bap);
  1219. av_freep(&block->mdct_coef);
  1220. av_freep(&block->exp);
  1221. av_freep(&block->grouped_exp);
  1222. av_freep(&block->psd);
  1223. av_freep(&block->band_psd);
  1224. av_freep(&block->mask);
  1225. av_freep(&block->qmant);
  1226. }
  1227. mdct_end(&s->mdct);
  1228. av_freep(&avctx->coded_frame);
  1229. return 0;
  1230. }
  1231. /**
  1232. * Set channel information during initialization.
  1233. */
  1234. static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
  1235. int64_t *channel_layout)
  1236. {
  1237. int ch_layout;
  1238. if (channels < 1 || channels > AC3_MAX_CHANNELS)
  1239. return AVERROR(EINVAL);
  1240. if ((uint64_t)*channel_layout > 0x7FF)
  1241. return AVERROR(EINVAL);
  1242. ch_layout = *channel_layout;
  1243. if (!ch_layout)
  1244. ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
  1245. if (av_get_channel_layout_nb_channels(ch_layout) != channels)
  1246. return AVERROR(EINVAL);
  1247. s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
  1248. s->channels = channels;
  1249. s->fbw_channels = channels - s->lfe_on;
  1250. s->lfe_channel = s->lfe_on ? s->fbw_channels : -1;
  1251. if (s->lfe_on)
  1252. ch_layout -= AV_CH_LOW_FREQUENCY;
  1253. switch (ch_layout) {
  1254. case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
  1255. case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
  1256. case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
  1257. case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
  1258. case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
  1259. case AV_CH_LAYOUT_QUAD:
  1260. case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
  1261. case AV_CH_LAYOUT_5POINT0:
  1262. case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
  1263. default:
  1264. return AVERROR(EINVAL);
  1265. }
  1266. s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
  1267. *channel_layout = ch_layout;
  1268. if (s->lfe_on)
  1269. *channel_layout |= AV_CH_LOW_FREQUENCY;
  1270. return 0;
  1271. }
  1272. static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
  1273. {
  1274. int i, ret;
  1275. /* validate channel layout */
  1276. if (!avctx->channel_layout) {
  1277. av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
  1278. "encoder will guess the layout, but it "
  1279. "might be incorrect.\n");
  1280. }
  1281. ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
  1282. if (ret) {
  1283. av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
  1284. return ret;
  1285. }
  1286. /* validate sample rate */
  1287. for (i = 0; i < 9; i++) {
  1288. if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
  1289. break;
  1290. }
  1291. if (i == 9) {
  1292. av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
  1293. return AVERROR(EINVAL);
  1294. }
  1295. s->sample_rate = avctx->sample_rate;
  1296. s->bit_alloc.sr_shift = i % 3;
  1297. s->bit_alloc.sr_code = i / 3;
  1298. /* validate bit rate */
  1299. for (i = 0; i < 19; i++) {
  1300. if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
  1301. break;
  1302. }
  1303. if (i == 19) {
  1304. av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
  1305. return AVERROR(EINVAL);
  1306. }
  1307. s->bit_rate = avctx->bit_rate;
  1308. s->frame_size_code = i << 1;
  1309. /* validate cutoff */
  1310. if (avctx->cutoff < 0) {
  1311. av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
  1312. return AVERROR(EINVAL);
  1313. }
  1314. s->cutoff = avctx->cutoff;
  1315. if (s->cutoff > (s->sample_rate >> 1))
  1316. s->cutoff = s->sample_rate >> 1;
  1317. return 0;
  1318. }
  1319. /**
  1320. * Set bandwidth for all channels.
  1321. * The user can optionally supply a cutoff frequency. Otherwise an appropriate
  1322. * default value will be used.
  1323. */
  1324. static av_cold void set_bandwidth(AC3EncodeContext *s)
  1325. {
  1326. int ch, bw_code;
  1327. if (s->cutoff) {
  1328. /* calculate bandwidth based on user-specified cutoff frequency */
  1329. int fbw_coeffs;
  1330. fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
  1331. bw_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
  1332. } else {
  1333. /* use default bandwidth setting */
  1334. /* XXX: should compute the bandwidth according to the frame
  1335. size, so that we avoid annoying high frequency artifacts */
  1336. bw_code = 50;
  1337. }
  1338. /* set number of coefficients for each channel */
  1339. for (ch = 0; ch < s->fbw_channels; ch++) {
  1340. s->bandwidth_code[ch] = bw_code;
  1341. s->nb_coefs[ch] = bw_code * 3 + 73;
  1342. }
  1343. if (s->lfe_on)
  1344. s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
  1345. }
  1346. static av_cold int allocate_buffers(AVCodecContext *avctx)
  1347. {
  1348. int blk, ch;
  1349. AC3EncodeContext *s = avctx->priv_data;
  1350. FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
  1351. alloc_fail);
  1352. for (ch = 0; ch < s->channels; ch++) {
  1353. FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
  1354. (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
  1355. alloc_fail);
  1356. }
  1357. FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * s->channels *
  1358. AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
  1359. FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
  1360. AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
  1361. FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
  1362. AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
  1363. FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
  1364. AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
  1365. FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
  1366. 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
  1367. FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
  1368. AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
  1369. FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
  1370. 64 * sizeof(*s->band_psd_buffer), alloc_fail);
  1371. FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
  1372. 64 * sizeof(*s->mask_buffer), alloc_fail);
  1373. FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
  1374. AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
  1375. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1376. AC3Block *block = &s->blocks[blk];
  1377. FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
  1378. alloc_fail);
  1379. FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
  1380. alloc_fail);
  1381. FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
  1382. alloc_fail);
  1383. FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
  1384. alloc_fail);
  1385. FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
  1386. alloc_fail);
  1387. FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
  1388. alloc_fail);
  1389. FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
  1390. alloc_fail);
  1391. FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
  1392. alloc_fail);
  1393. for (ch = 0; ch < s->channels; ch++) {
  1394. block->bap[ch] = &s->bap_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1395. block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1396. block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1397. block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * s->channels + ch)];
  1398. block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1399. block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * s->channels + ch)];
  1400. block->mask[ch] = &s->mask_buffer [64 * (blk * s->channels + ch)];
  1401. block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1402. }
  1403. }
  1404. return 0;
  1405. alloc_fail:
  1406. return AVERROR(ENOMEM);
  1407. }
  1408. /**
  1409. * Initialize the encoder.
  1410. */
  1411. static av_cold int ac3_encode_init(AVCodecContext *avctx)
  1412. {
  1413. AC3EncodeContext *s = avctx->priv_data;
  1414. int ret, frame_size_58;
  1415. avctx->frame_size = AC3_FRAME_SIZE;
  1416. ac3_common_init();
  1417. ret = validate_options(avctx, s);
  1418. if (ret)
  1419. return ret;
  1420. s->bitstream_id = 8 + s->bit_alloc.sr_shift;
  1421. s->bitstream_mode = 0; /* complete main audio service */
  1422. s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
  1423. s->bits_written = 0;
  1424. s->samples_written = 0;
  1425. s->frame_size = s->frame_size_min;
  1426. /* calculate crc_inv for both possible frame sizes */
  1427. frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
  1428. s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  1429. if (s->bit_alloc.sr_code == 1) {
  1430. frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
  1431. s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  1432. }
  1433. set_bandwidth(s);
  1434. exponent_init(s);
  1435. bit_alloc_init(s);
  1436. ret = mdct_init(avctx, &s->mdct, 9);
  1437. if (ret)
  1438. goto init_fail;
  1439. ret = allocate_buffers(avctx);
  1440. if (ret)
  1441. goto init_fail;
  1442. avctx->coded_frame= avcodec_alloc_frame();
  1443. dsputil_init(&s->dsp, avctx);
  1444. return 0;
  1445. init_fail:
  1446. ac3_encode_close(avctx);
  1447. return ret;
  1448. }