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.

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