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.

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