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.

1843 lines
58KB

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