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.

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