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.

1731 lines
54KB

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