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.

1854 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. uint8_t exp_strategy[AC3_MAX_CHANNELS]; ///< exponent strategies
  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. AC3MDCTContext mdct; ///< MDCT context
  77. AC3Block blocks[AC3_MAX_BLOCKS]; ///< per-block info
  78. int bitstream_id; ///< bitstream id (bsid)
  79. int bitstream_mode; ///< bitstream mode (bsmod)
  80. int bit_rate; ///< target bit rate, in bits-per-second
  81. int sample_rate; ///< sampling frequency, in Hz
  82. int frame_size_min; ///< minimum frame size in case rounding is necessary
  83. int frame_size; ///< current frame size in bytes
  84. int frame_size_code; ///< frame size code (frmsizecod)
  85. uint16_t crc_inv[2];
  86. int bits_written; ///< bit count (used to avg. bitrate)
  87. int samples_written; ///< sample count (used to avg. bitrate)
  88. int fbw_channels; ///< number of full-bandwidth channels (nfchans)
  89. int channels; ///< total number of channels (nchans)
  90. int lfe_on; ///< indicates if there is an LFE channel (lfeon)
  91. int lfe_channel; ///< channel index of the LFE channel
  92. int channel_mode; ///< channel mode (acmod)
  93. const uint8_t *channel_map; ///< channel map used to reorder channels
  94. int cutoff; ///< user-specified cutoff frequency, in Hz
  95. int bandwidth_code[AC3_MAX_CHANNELS]; ///< bandwidth code (0 to 60) (chbwcod)
  96. int nb_coefs[AC3_MAX_CHANNELS];
  97. int rematrixing; ///< determines how rematrixing strategy is calculated
  98. /* bitrate allocation control */
  99. int slow_gain_code; ///< slow gain code (sgaincod)
  100. int slow_decay_code; ///< slow decay code (sdcycod)
  101. int fast_decay_code; ///< fast decay code (fdcycod)
  102. int db_per_bit_code; ///< dB/bit code (dbpbcod)
  103. int floor_code; ///< floor code (floorcod)
  104. AC3BitAllocParameters bit_alloc; ///< bit allocation parameters
  105. int coarse_snr_offset; ///< coarse SNR offsets (csnroffst)
  106. int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signal-to-mask ratio) (fgaincod)
  107. int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst)
  108. int frame_bits_fixed; ///< number of non-coefficient bits for fixed parameters
  109. int frame_bits; ///< all frame bits except exponents and mantissas
  110. int exponent_bits; ///< number of bits used for exponents
  111. /* mantissa encoding */
  112. int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
  113. uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
  114. SampleType **planar_samples;
  115. uint8_t *bap_buffer;
  116. uint8_t *bap1_buffer;
  117. CoefType *mdct_coef_buffer;
  118. int32_t *fixed_coef_buffer;
  119. uint8_t *exp_buffer;
  120. uint8_t *grouped_exp_buffer;
  121. int16_t *psd_buffer;
  122. int16_t *band_psd_buffer;
  123. int16_t *mask_buffer;
  124. uint16_t *qmant_buffer;
  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->blocks[blk].exp_strategy[ch];
  413. }
  414. compute_exp_strategy_ch(s, exp_str1[ch], exp1[ch]);
  415. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  416. s->blocks[blk].exp_strategy[ch] = exp_str1[ch][blk];
  417. }
  418. if (s->lfe_on) {
  419. ch = s->lfe_channel;
  420. s->blocks[0].exp_strategy[ch] = EXP_D15;
  421. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
  422. s->blocks[blk].exp_strategy[ch] = 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 && block1->exp_strategy[ch] == 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. block->exp_strategy[ch]);
  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 (block->exp_strategy[ch] == EXP_REUSE) {
  549. continue;
  550. }
  551. group_size = block->exp_strategy[ch] + (block->exp_strategy[ch] == EXP_D45);
  552. nb_groups = exponent_group_tab[block->exp_strategy[ch]-1][s->nb_coefs[ch]];
  553. bit_count += 4 + (nb_groups * 7);
  554. p = block->exp[ch];
  555. /* DC exponent */
  556. exp1 = *p++;
  557. block->grouped_exp[ch][0] = exp1;
  558. /* remaining exponents are delta encoded */
  559. for (i = 1; i <= nb_groups; i++) {
  560. /* merge three delta in one code */
  561. exp0 = exp1;
  562. exp1 = p[0];
  563. p += group_size;
  564. delta0 = exp1 - exp0 + 2;
  565. exp0 = exp1;
  566. exp1 = p[0];
  567. p += group_size;
  568. delta1 = exp1 - exp0 + 2;
  569. exp0 = exp1;
  570. exp1 = p[0];
  571. p += group_size;
  572. delta2 = exp1 - exp0 + 2;
  573. block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
  574. }
  575. }
  576. }
  577. s->exponent_bits = bit_count;
  578. }
  579. /**
  580. * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
  581. * Extract exponents from MDCT coefficients, calculate exponent strategies,
  582. * and encode final exponents.
  583. */
  584. static void process_exponents(AC3EncodeContext *s)
  585. {
  586. extract_exponents(s);
  587. compute_exp_strategy(s);
  588. encode_exponents(s);
  589. group_exponents(s);
  590. }
  591. /**
  592. * Count frame bits that are based solely on fixed parameters.
  593. * This only has to be run once when the encoder is initialized.
  594. */
  595. static void count_frame_bits_fixed(AC3EncodeContext *s)
  596. {
  597. static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
  598. int blk;
  599. int frame_bits;
  600. /* assumptions:
  601. * no dynamic range codes
  602. * no channel coupling
  603. * bit allocation parameters do not change between blocks
  604. * SNR offsets do not change between blocks
  605. * no delta bit allocation
  606. * no skipped data
  607. * no auxilliary data
  608. */
  609. /* header size */
  610. frame_bits = 65;
  611. frame_bits += frame_bits_inc[s->channel_mode];
  612. /* audio blocks */
  613. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  614. frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
  615. if (s->channel_mode == AC3_CHMODE_STEREO) {
  616. frame_bits++; /* rematstr */
  617. }
  618. frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
  619. if (s->lfe_on)
  620. frame_bits++; /* lfeexpstr */
  621. frame_bits++; /* baie */
  622. frame_bits++; /* snr */
  623. frame_bits += 2; /* delta / skip */
  624. }
  625. frame_bits++; /* cplinu for block 0 */
  626. /* bit alloc info */
  627. /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
  628. /* csnroffset[6] */
  629. /* (fsnoffset[4] + fgaincod[4]) * c */
  630. frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
  631. /* auxdatae, crcrsv */
  632. frame_bits += 2;
  633. /* CRC */
  634. frame_bits += 16;
  635. s->frame_bits_fixed = frame_bits;
  636. }
  637. /**
  638. * Initialize bit allocation.
  639. * Set default parameter codes and calculate parameter values.
  640. */
  641. static void bit_alloc_init(AC3EncodeContext *s)
  642. {
  643. int ch;
  644. /* init default parameters */
  645. s->slow_decay_code = 2;
  646. s->fast_decay_code = 1;
  647. s->slow_gain_code = 1;
  648. s->db_per_bit_code = 3;
  649. s->floor_code = 4;
  650. for (ch = 0; ch < s->channels; ch++)
  651. s->fast_gain_code[ch] = 4;
  652. /* initial snr offset */
  653. s->coarse_snr_offset = 40;
  654. /* compute real values */
  655. /* currently none of these values change during encoding, so we can just
  656. set them once at initialization */
  657. s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
  658. s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
  659. s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
  660. s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
  661. s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
  662. count_frame_bits_fixed(s);
  663. }
  664. /**
  665. * Count the bits used to encode the frame, minus exponents and mantissas.
  666. * Bits based on fixed parameters have already been counted, so now we just
  667. * have to add the bits based on parameters that change during encoding.
  668. */
  669. static void count_frame_bits(AC3EncodeContext *s)
  670. {
  671. int blk, ch;
  672. int frame_bits = 0;
  673. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  674. uint8_t *exp_strategy = s->blocks[blk].exp_strategy;
  675. /* stereo rematrixing */
  676. if (s->channel_mode == AC3_CHMODE_STEREO &&
  677. s->blocks[blk].new_rematrixing_strategy) {
  678. frame_bits += 4;
  679. }
  680. for (ch = 0; ch < s->fbw_channels; ch++) {
  681. if (exp_strategy[ch] != EXP_REUSE)
  682. frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
  683. }
  684. }
  685. s->frame_bits = s->frame_bits_fixed + frame_bits;
  686. }
  687. /**
  688. * Calculate the number of bits needed to encode a set of mantissas.
  689. */
  690. static int compute_mantissa_size(int mant_cnt[5], uint8_t *bap, int nb_coefs)
  691. {
  692. int bits, b, i;
  693. bits = 0;
  694. for (i = 0; i < nb_coefs; i++) {
  695. b = bap[i];
  696. if (b <= 4) {
  697. // bap=1 to bap=4 will be counted in compute_mantissa_size_final
  698. mant_cnt[b]++;
  699. } else if (b <= 13) {
  700. // bap=5 to bap=13 use (bap-1) bits
  701. bits += b - 1;
  702. } else {
  703. // bap=14 uses 14 bits and bap=15 uses 16 bits
  704. bits += (b == 14) ? 14 : 16;
  705. }
  706. }
  707. return bits;
  708. }
  709. /**
  710. * Finalize the mantissa bit count by adding in the grouped mantissas.
  711. */
  712. static int compute_mantissa_size_final(int mant_cnt[5])
  713. {
  714. // bap=1 : 3 mantissas in 5 bits
  715. int bits = (mant_cnt[1] / 3) * 5;
  716. // bap=2 : 3 mantissas in 7 bits
  717. // bap=4 : 2 mantissas in 7 bits
  718. bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
  719. // bap=3 : each mantissa is 3 bits
  720. bits += mant_cnt[3] * 3;
  721. return bits;
  722. }
  723. /**
  724. * Calculate masking curve based on the final exponents.
  725. * Also calculate the power spectral densities to use in future calculations.
  726. */
  727. static void bit_alloc_masking(AC3EncodeContext *s)
  728. {
  729. int blk, ch;
  730. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  731. AC3Block *block = &s->blocks[blk];
  732. for (ch = 0; ch < s->channels; ch++) {
  733. /* We only need psd and mask for calculating bap.
  734. Since we currently do not calculate bap when exponent
  735. strategy is EXP_REUSE we do not need to calculate psd or mask. */
  736. if (block->exp_strategy[ch] != EXP_REUSE) {
  737. ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
  738. s->nb_coefs[ch],
  739. block->psd[ch], block->band_psd[ch]);
  740. ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
  741. 0, s->nb_coefs[ch],
  742. ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
  743. ch == s->lfe_channel,
  744. DBA_NONE, 0, NULL, NULL, NULL,
  745. block->mask[ch]);
  746. }
  747. }
  748. }
  749. }
  750. /**
  751. * Ensure that bap for each block and channel point to the current bap_buffer.
  752. * They may have been switched during the bit allocation search.
  753. */
  754. static void reset_block_bap(AC3EncodeContext *s)
  755. {
  756. int blk, ch;
  757. if (s->blocks[0].bap[0] == s->bap_buffer)
  758. return;
  759. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  760. for (ch = 0; ch < s->channels; ch++) {
  761. s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
  762. }
  763. }
  764. }
  765. /**
  766. * Run the bit allocation with a given SNR offset.
  767. * This calculates the bit allocation pointers that will be used to determine
  768. * the quantization of each mantissa.
  769. * @return the number of bits needed for mantissas if the given SNR offset is
  770. * is used.
  771. */
  772. static int bit_alloc(AC3EncodeContext *s, int snr_offset)
  773. {
  774. int blk, ch;
  775. int mantissa_bits;
  776. int mant_cnt[5];
  777. snr_offset = (snr_offset - 240) << 2;
  778. reset_block_bap(s);
  779. mantissa_bits = 0;
  780. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  781. AC3Block *block = &s->blocks[blk];
  782. // initialize grouped mantissa counts. these are set so that they are
  783. // padded to the next whole group size when bits are counted in
  784. // compute_mantissa_size_final
  785. mant_cnt[0] = mant_cnt[3] = 0;
  786. mant_cnt[1] = mant_cnt[2] = 2;
  787. mant_cnt[4] = 1;
  788. for (ch = 0; ch < s->channels; ch++) {
  789. /* Currently the only bit allocation parameters which vary across
  790. blocks within a frame are the exponent values. We can take
  791. advantage of that by reusing the bit allocation pointers
  792. whenever we reuse exponents. */
  793. if (block->exp_strategy[ch] == EXP_REUSE) {
  794. memcpy(block->bap[ch], s->blocks[blk-1].bap[ch], AC3_MAX_COEFS);
  795. } else {
  796. ff_ac3_bit_alloc_calc_bap(block->mask[ch], block->psd[ch], 0,
  797. s->nb_coefs[ch], snr_offset,
  798. s->bit_alloc.floor, ff_ac3_bap_tab,
  799. block->bap[ch]);
  800. }
  801. mantissa_bits += compute_mantissa_size(mant_cnt, block->bap[ch], s->nb_coefs[ch]);
  802. }
  803. mantissa_bits += compute_mantissa_size_final(mant_cnt);
  804. }
  805. return mantissa_bits;
  806. }
  807. /**
  808. * Constant bitrate bit allocation search.
  809. * Find the largest SNR offset that will allow data to fit in the frame.
  810. */
  811. static int cbr_bit_allocation(AC3EncodeContext *s)
  812. {
  813. int ch;
  814. int bits_left;
  815. int snr_offset, snr_incr;
  816. bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
  817. snr_offset = s->coarse_snr_offset << 4;
  818. /* if previous frame SNR offset was 1023, check if current frame can also
  819. use SNR offset of 1023. if so, skip the search. */
  820. if ((snr_offset | s->fine_snr_offset[0]) == 1023) {
  821. if (bit_alloc(s, 1023) <= bits_left)
  822. return 0;
  823. }
  824. while (snr_offset >= 0 &&
  825. bit_alloc(s, snr_offset) > bits_left) {
  826. snr_offset -= 64;
  827. }
  828. if (snr_offset < 0)
  829. return AVERROR(EINVAL);
  830. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  831. for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
  832. while (snr_offset + snr_incr <= 1023 &&
  833. bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
  834. snr_offset += snr_incr;
  835. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  836. }
  837. }
  838. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  839. reset_block_bap(s);
  840. s->coarse_snr_offset = snr_offset >> 4;
  841. for (ch = 0; ch < s->channels; ch++)
  842. s->fine_snr_offset[ch] = snr_offset & 0xF;
  843. return 0;
  844. }
  845. /**
  846. * Downgrade exponent strategies to reduce the bits used by the exponents.
  847. * This is a fallback for when bit allocation fails with the normal exponent
  848. * strategies. Each time this function is run it only downgrades the
  849. * strategy in 1 channel of 1 block.
  850. * @return non-zero if downgrade was unsuccessful
  851. */
  852. static int downgrade_exponents(AC3EncodeContext *s)
  853. {
  854. int ch, blk;
  855. for (ch = 0; ch < s->fbw_channels; ch++) {
  856. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  857. if (s->blocks[blk].exp_strategy[ch] == EXP_D15) {
  858. s->blocks[blk].exp_strategy[ch] = EXP_D25;
  859. return 0;
  860. }
  861. }
  862. }
  863. for (ch = 0; ch < s->fbw_channels; ch++) {
  864. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  865. if (s->blocks[blk].exp_strategy[ch] == EXP_D25) {
  866. s->blocks[blk].exp_strategy[ch] = EXP_D45;
  867. return 0;
  868. }
  869. }
  870. }
  871. for (ch = 0; ch < s->fbw_channels; ch++) {
  872. /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
  873. the block number > 0 */
  874. for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
  875. if (s->blocks[blk].exp_strategy[ch] > EXP_REUSE) {
  876. s->blocks[blk].exp_strategy[ch] = EXP_REUSE;
  877. return 0;
  878. }
  879. }
  880. }
  881. return -1;
  882. }
  883. /**
  884. * Reduce the bandwidth to reduce the number of bits used for a given SNR offset.
  885. * This is a second fallback for when bit allocation still fails after exponents
  886. * have been downgraded.
  887. * @return non-zero if bandwidth reduction was unsuccessful
  888. */
  889. static int reduce_bandwidth(AC3EncodeContext *s, int min_bw_code)
  890. {
  891. int ch;
  892. if (s->bandwidth_code[0] > min_bw_code) {
  893. for (ch = 0; ch < s->fbw_channels; ch++) {
  894. s->bandwidth_code[ch]--;
  895. s->nb_coefs[ch] = s->bandwidth_code[ch] * 3 + 73;
  896. }
  897. return 0;
  898. }
  899. return -1;
  900. }
  901. /**
  902. * Perform bit allocation search.
  903. * Finds the SNR offset value that maximizes quality and fits in the specified
  904. * frame size. Output is the SNR offset and a set of bit allocation pointers
  905. * used to quantize the mantissas.
  906. */
  907. static int compute_bit_allocation(AC3EncodeContext *s)
  908. {
  909. int ret;
  910. count_frame_bits(s);
  911. bit_alloc_masking(s);
  912. ret = cbr_bit_allocation(s);
  913. while (ret) {
  914. /* fallback 1: downgrade exponents */
  915. if (!downgrade_exponents(s)) {
  916. extract_exponents(s);
  917. encode_exponents(s);
  918. group_exponents(s);
  919. ret = compute_bit_allocation(s);
  920. continue;
  921. }
  922. /* fallback 2: reduce bandwidth */
  923. /* only do this if the user has not specified a specific cutoff
  924. frequency */
  925. if (!s->cutoff && !reduce_bandwidth(s, 0)) {
  926. process_exponents(s);
  927. ret = compute_bit_allocation(s);
  928. continue;
  929. }
  930. /* fallbacks were not enough... */
  931. break;
  932. }
  933. return ret;
  934. }
  935. /**
  936. * Symmetric quantization on 'levels' levels.
  937. */
  938. static inline int sym_quant(int c, int e, int levels)
  939. {
  940. int v;
  941. if (c >= 0) {
  942. v = (levels * (c << e)) >> 24;
  943. v = (v + 1) >> 1;
  944. v = (levels >> 1) + v;
  945. } else {
  946. v = (levels * ((-c) << e)) >> 24;
  947. v = (v + 1) >> 1;
  948. v = (levels >> 1) - v;
  949. }
  950. assert(v >= 0 && v < levels);
  951. return v;
  952. }
  953. /**
  954. * Asymmetric quantization on 2^qbits levels.
  955. */
  956. static inline int asym_quant(int c, int e, int qbits)
  957. {
  958. int lshift, m, v;
  959. lshift = e + qbits - 24;
  960. if (lshift >= 0)
  961. v = c << lshift;
  962. else
  963. v = c >> (-lshift);
  964. /* rounding */
  965. v = (v + 1) >> 1;
  966. m = (1 << (qbits-1));
  967. if (v >= m)
  968. v = m - 1;
  969. assert(v >= -m);
  970. return v & ((1 << qbits)-1);
  971. }
  972. /**
  973. * Quantize a set of mantissas for a single channel in a single block.
  974. */
  975. static void quantize_mantissas_blk_ch(AC3EncodeContext *s, int32_t *fixed_coef,
  976. int8_t exp_shift, uint8_t *exp,
  977. uint8_t *bap, uint16_t *qmant, int n)
  978. {
  979. int i;
  980. for (i = 0; i < n; i++) {
  981. int v;
  982. int c = fixed_coef[i];
  983. int e = exp[i] - exp_shift;
  984. int b = bap[i];
  985. switch (b) {
  986. case 0:
  987. v = 0;
  988. break;
  989. case 1:
  990. v = sym_quant(c, e, 3);
  991. switch (s->mant1_cnt) {
  992. case 0:
  993. s->qmant1_ptr = &qmant[i];
  994. v = 9 * v;
  995. s->mant1_cnt = 1;
  996. break;
  997. case 1:
  998. *s->qmant1_ptr += 3 * v;
  999. s->mant1_cnt = 2;
  1000. v = 128;
  1001. break;
  1002. default:
  1003. *s->qmant1_ptr += v;
  1004. s->mant1_cnt = 0;
  1005. v = 128;
  1006. break;
  1007. }
  1008. break;
  1009. case 2:
  1010. v = sym_quant(c, e, 5);
  1011. switch (s->mant2_cnt) {
  1012. case 0:
  1013. s->qmant2_ptr = &qmant[i];
  1014. v = 25 * v;
  1015. s->mant2_cnt = 1;
  1016. break;
  1017. case 1:
  1018. *s->qmant2_ptr += 5 * v;
  1019. s->mant2_cnt = 2;
  1020. v = 128;
  1021. break;
  1022. default:
  1023. *s->qmant2_ptr += v;
  1024. s->mant2_cnt = 0;
  1025. v = 128;
  1026. break;
  1027. }
  1028. break;
  1029. case 3:
  1030. v = sym_quant(c, e, 7);
  1031. break;
  1032. case 4:
  1033. v = sym_quant(c, e, 11);
  1034. switch (s->mant4_cnt) {
  1035. case 0:
  1036. s->qmant4_ptr = &qmant[i];
  1037. v = 11 * v;
  1038. s->mant4_cnt = 1;
  1039. break;
  1040. default:
  1041. *s->qmant4_ptr += v;
  1042. s->mant4_cnt = 0;
  1043. v = 128;
  1044. break;
  1045. }
  1046. break;
  1047. case 5:
  1048. v = sym_quant(c, e, 15);
  1049. break;
  1050. case 14:
  1051. v = asym_quant(c, e, 14);
  1052. break;
  1053. case 15:
  1054. v = asym_quant(c, e, 16);
  1055. break;
  1056. default:
  1057. v = asym_quant(c, e, b - 1);
  1058. break;
  1059. }
  1060. qmant[i] = v;
  1061. }
  1062. }
  1063. /**
  1064. * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
  1065. */
  1066. static void quantize_mantissas(AC3EncodeContext *s)
  1067. {
  1068. int blk, ch;
  1069. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1070. AC3Block *block = &s->blocks[blk];
  1071. s->mant1_cnt = s->mant2_cnt = s->mant4_cnt = 0;
  1072. s->qmant1_ptr = s->qmant2_ptr = s->qmant4_ptr = NULL;
  1073. for (ch = 0; ch < s->channels; ch++) {
  1074. quantize_mantissas_blk_ch(s, block->fixed_coef[ch], block->exp_shift[ch],
  1075. block->exp[ch], block->bap[ch],
  1076. block->qmant[ch], s->nb_coefs[ch]);
  1077. }
  1078. }
  1079. }
  1080. /**
  1081. * Write the AC-3 frame header to the output bitstream.
  1082. */
  1083. static void output_frame_header(AC3EncodeContext *s)
  1084. {
  1085. put_bits(&s->pb, 16, 0x0b77); /* frame header */
  1086. put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
  1087. put_bits(&s->pb, 2, s->bit_alloc.sr_code);
  1088. put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
  1089. put_bits(&s->pb, 5, s->bitstream_id);
  1090. put_bits(&s->pb, 3, s->bitstream_mode);
  1091. put_bits(&s->pb, 3, s->channel_mode);
  1092. if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
  1093. put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
  1094. if (s->channel_mode & 0x04)
  1095. put_bits(&s->pb, 2, 1); /* XXX -6 dB */
  1096. if (s->channel_mode == AC3_CHMODE_STEREO)
  1097. put_bits(&s->pb, 2, 0); /* surround not indicated */
  1098. put_bits(&s->pb, 1, s->lfe_on); /* LFE */
  1099. put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
  1100. put_bits(&s->pb, 1, 0); /* no compression control word */
  1101. put_bits(&s->pb, 1, 0); /* no lang code */
  1102. put_bits(&s->pb, 1, 0); /* no audio production info */
  1103. put_bits(&s->pb, 1, 0); /* no copyright */
  1104. put_bits(&s->pb, 1, 1); /* original bitstream */
  1105. put_bits(&s->pb, 1, 0); /* no time code 1 */
  1106. put_bits(&s->pb, 1, 0); /* no time code 2 */
  1107. put_bits(&s->pb, 1, 0); /* no additional bit stream info */
  1108. }
  1109. /**
  1110. * Write one audio block to the output bitstream.
  1111. */
  1112. static void output_audio_block(AC3EncodeContext *s, int block_num)
  1113. {
  1114. int ch, i, baie, rbnd;
  1115. AC3Block *block = &s->blocks[block_num];
  1116. /* block switching */
  1117. for (ch = 0; ch < s->fbw_channels; ch++)
  1118. put_bits(&s->pb, 1, 0);
  1119. /* dither flags */
  1120. for (ch = 0; ch < s->fbw_channels; ch++)
  1121. put_bits(&s->pb, 1, 1);
  1122. /* dynamic range codes */
  1123. put_bits(&s->pb, 1, 0);
  1124. /* channel coupling */
  1125. if (!block_num) {
  1126. put_bits(&s->pb, 1, 1); /* coupling strategy present */
  1127. put_bits(&s->pb, 1, 0); /* no coupling strategy */
  1128. } else {
  1129. put_bits(&s->pb, 1, 0); /* no new coupling strategy */
  1130. }
  1131. /* stereo rematrixing */
  1132. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1133. put_bits(&s->pb, 1, block->new_rematrixing_strategy);
  1134. if (block->new_rematrixing_strategy) {
  1135. /* rematrixing flags */
  1136. for (rbnd = 0; rbnd < 4; rbnd++)
  1137. put_bits(&s->pb, 1, block->rematrixing_flags[rbnd]);
  1138. }
  1139. }
  1140. /* exponent strategy */
  1141. for (ch = 0; ch < s->fbw_channels; ch++)
  1142. put_bits(&s->pb, 2, block->exp_strategy[ch]);
  1143. if (s->lfe_on)
  1144. put_bits(&s->pb, 1, block->exp_strategy[s->lfe_channel]);
  1145. /* bandwidth */
  1146. for (ch = 0; ch < s->fbw_channels; ch++) {
  1147. if (block->exp_strategy[ch] != EXP_REUSE)
  1148. put_bits(&s->pb, 6, s->bandwidth_code[ch]);
  1149. }
  1150. /* exponents */
  1151. for (ch = 0; ch < s->channels; ch++) {
  1152. int nb_groups;
  1153. if (block->exp_strategy[ch] == EXP_REUSE)
  1154. continue;
  1155. /* DC exponent */
  1156. put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
  1157. /* exponent groups */
  1158. nb_groups = exponent_group_tab[block->exp_strategy[ch]-1][s->nb_coefs[ch]];
  1159. for (i = 1; i <= nb_groups; i++)
  1160. put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
  1161. /* gain range info */
  1162. if (ch != s->lfe_channel)
  1163. put_bits(&s->pb, 2, 0);
  1164. }
  1165. /* bit allocation info */
  1166. baie = (block_num == 0);
  1167. put_bits(&s->pb, 1, baie);
  1168. if (baie) {
  1169. put_bits(&s->pb, 2, s->slow_decay_code);
  1170. put_bits(&s->pb, 2, s->fast_decay_code);
  1171. put_bits(&s->pb, 2, s->slow_gain_code);
  1172. put_bits(&s->pb, 2, s->db_per_bit_code);
  1173. put_bits(&s->pb, 3, s->floor_code);
  1174. }
  1175. /* snr offset */
  1176. put_bits(&s->pb, 1, baie);
  1177. if (baie) {
  1178. put_bits(&s->pb, 6, s->coarse_snr_offset);
  1179. for (ch = 0; ch < s->channels; ch++) {
  1180. put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
  1181. put_bits(&s->pb, 3, s->fast_gain_code[ch]);
  1182. }
  1183. }
  1184. put_bits(&s->pb, 1, 0); /* no delta bit allocation */
  1185. put_bits(&s->pb, 1, 0); /* no data to skip */
  1186. /* mantissas */
  1187. for (ch = 0; ch < s->channels; ch++) {
  1188. int b, q;
  1189. for (i = 0; i < s->nb_coefs[ch]; i++) {
  1190. q = block->qmant[ch][i];
  1191. b = block->bap[ch][i];
  1192. switch (b) {
  1193. case 0: break;
  1194. case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
  1195. case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
  1196. case 3: put_bits(&s->pb, 3, q); break;
  1197. case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
  1198. case 14: put_bits(&s->pb, 14, q); break;
  1199. case 15: put_bits(&s->pb, 16, q); break;
  1200. default: put_bits(&s->pb, b-1, q); break;
  1201. }
  1202. }
  1203. }
  1204. }
  1205. /** CRC-16 Polynomial */
  1206. #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
  1207. static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
  1208. {
  1209. unsigned int c;
  1210. c = 0;
  1211. while (a) {
  1212. if (a & 1)
  1213. c ^= b;
  1214. a = a >> 1;
  1215. b = b << 1;
  1216. if (b & (1 << 16))
  1217. b ^= poly;
  1218. }
  1219. return c;
  1220. }
  1221. static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
  1222. {
  1223. unsigned int r;
  1224. r = 1;
  1225. while (n) {
  1226. if (n & 1)
  1227. r = mul_poly(r, a, poly);
  1228. a = mul_poly(a, a, poly);
  1229. n >>= 1;
  1230. }
  1231. return r;
  1232. }
  1233. /**
  1234. * Fill the end of the frame with 0's and compute the two CRCs.
  1235. */
  1236. static void output_frame_end(AC3EncodeContext *s)
  1237. {
  1238. const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
  1239. int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
  1240. uint8_t *frame;
  1241. frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
  1242. /* pad the remainder of the frame with zeros */
  1243. flush_put_bits(&s->pb);
  1244. frame = s->pb.buf;
  1245. pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
  1246. assert(pad_bytes >= 0);
  1247. if (pad_bytes > 0)
  1248. memset(put_bits_ptr(&s->pb), 0, pad_bytes);
  1249. /* compute crc1 */
  1250. /* this is not so easy because it is at the beginning of the data... */
  1251. crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
  1252. crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
  1253. crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
  1254. AV_WB16(frame + 2, crc1);
  1255. /* compute crc2 */
  1256. crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
  1257. s->frame_size - frame_size_58 - 3);
  1258. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1259. /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
  1260. if (crc2 == 0x770B) {
  1261. frame[s->frame_size - 3] ^= 0x1;
  1262. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1263. }
  1264. crc2 = av_bswap16(crc2);
  1265. AV_WB16(frame + s->frame_size - 2, crc2);
  1266. }
  1267. /**
  1268. * Write the frame to the output bitstream.
  1269. */
  1270. static void output_frame(AC3EncodeContext *s, unsigned char *frame)
  1271. {
  1272. int blk;
  1273. init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
  1274. output_frame_header(s);
  1275. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1276. output_audio_block(s, blk);
  1277. output_frame_end(s);
  1278. }
  1279. /**
  1280. * Encode a single AC-3 frame.
  1281. */
  1282. static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
  1283. int buf_size, void *data)
  1284. {
  1285. AC3EncodeContext *s = avctx->priv_data;
  1286. const SampleType *samples = data;
  1287. int ret;
  1288. if (s->bit_alloc.sr_code == 1)
  1289. adjust_frame_size(s);
  1290. deinterleave_input_samples(s, samples);
  1291. apply_mdct(s);
  1292. compute_rematrixing_strategy(s);
  1293. scale_coefficients(s);
  1294. apply_rematrixing(s);
  1295. process_exponents(s);
  1296. ret = compute_bit_allocation(s);
  1297. if (ret) {
  1298. av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
  1299. return ret;
  1300. }
  1301. quantize_mantissas(s);
  1302. output_frame(s, frame);
  1303. return s->frame_size;
  1304. }
  1305. /**
  1306. * Finalize encoding and free any memory allocated by the encoder.
  1307. */
  1308. static av_cold int ac3_encode_close(AVCodecContext *avctx)
  1309. {
  1310. int blk, ch;
  1311. AC3EncodeContext *s = avctx->priv_data;
  1312. for (ch = 0; ch < s->channels; ch++)
  1313. av_freep(&s->planar_samples[ch]);
  1314. av_freep(&s->planar_samples);
  1315. av_freep(&s->bap_buffer);
  1316. av_freep(&s->bap1_buffer);
  1317. av_freep(&s->mdct_coef_buffer);
  1318. av_freep(&s->fixed_coef_buffer);
  1319. av_freep(&s->exp_buffer);
  1320. av_freep(&s->grouped_exp_buffer);
  1321. av_freep(&s->psd_buffer);
  1322. av_freep(&s->band_psd_buffer);
  1323. av_freep(&s->mask_buffer);
  1324. av_freep(&s->qmant_buffer);
  1325. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1326. AC3Block *block = &s->blocks[blk];
  1327. av_freep(&block->bap);
  1328. av_freep(&block->mdct_coef);
  1329. av_freep(&block->fixed_coef);
  1330. av_freep(&block->exp);
  1331. av_freep(&block->grouped_exp);
  1332. av_freep(&block->psd);
  1333. av_freep(&block->band_psd);
  1334. av_freep(&block->mask);
  1335. av_freep(&block->qmant);
  1336. }
  1337. mdct_end(&s->mdct);
  1338. av_freep(&avctx->coded_frame);
  1339. return 0;
  1340. }
  1341. /**
  1342. * Set channel information during initialization.
  1343. */
  1344. static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
  1345. int64_t *channel_layout)
  1346. {
  1347. int ch_layout;
  1348. if (channels < 1 || channels > AC3_MAX_CHANNELS)
  1349. return AVERROR(EINVAL);
  1350. if ((uint64_t)*channel_layout > 0x7FF)
  1351. return AVERROR(EINVAL);
  1352. ch_layout = *channel_layout;
  1353. if (!ch_layout)
  1354. ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
  1355. if (av_get_channel_layout_nb_channels(ch_layout) != channels)
  1356. return AVERROR(EINVAL);
  1357. s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
  1358. s->channels = channels;
  1359. s->fbw_channels = channels - s->lfe_on;
  1360. s->lfe_channel = s->lfe_on ? s->fbw_channels : -1;
  1361. if (s->lfe_on)
  1362. ch_layout -= AV_CH_LOW_FREQUENCY;
  1363. switch (ch_layout) {
  1364. case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
  1365. case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
  1366. case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
  1367. case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
  1368. case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
  1369. case AV_CH_LAYOUT_QUAD:
  1370. case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
  1371. case AV_CH_LAYOUT_5POINT0:
  1372. case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
  1373. default:
  1374. return AVERROR(EINVAL);
  1375. }
  1376. s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
  1377. *channel_layout = ch_layout;
  1378. if (s->lfe_on)
  1379. *channel_layout |= AV_CH_LOW_FREQUENCY;
  1380. return 0;
  1381. }
  1382. static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
  1383. {
  1384. int i, ret;
  1385. /* validate channel layout */
  1386. if (!avctx->channel_layout) {
  1387. av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
  1388. "encoder will guess the layout, but it "
  1389. "might be incorrect.\n");
  1390. }
  1391. ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
  1392. if (ret) {
  1393. av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
  1394. return ret;
  1395. }
  1396. /* validate sample rate */
  1397. for (i = 0; i < 9; i++) {
  1398. if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
  1399. break;
  1400. }
  1401. if (i == 9) {
  1402. av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
  1403. return AVERROR(EINVAL);
  1404. }
  1405. s->sample_rate = avctx->sample_rate;
  1406. s->bit_alloc.sr_shift = i % 3;
  1407. s->bit_alloc.sr_code = i / 3;
  1408. /* validate bit rate */
  1409. for (i = 0; i < 19; i++) {
  1410. if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
  1411. break;
  1412. }
  1413. if (i == 19) {
  1414. av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
  1415. return AVERROR(EINVAL);
  1416. }
  1417. s->bit_rate = avctx->bit_rate;
  1418. s->frame_size_code = i << 1;
  1419. /* validate cutoff */
  1420. if (avctx->cutoff < 0) {
  1421. av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
  1422. return AVERROR(EINVAL);
  1423. }
  1424. s->cutoff = avctx->cutoff;
  1425. if (s->cutoff > (s->sample_rate >> 1))
  1426. s->cutoff = s->sample_rate >> 1;
  1427. return 0;
  1428. }
  1429. /**
  1430. * Set bandwidth for all channels.
  1431. * The user can optionally supply a cutoff frequency. Otherwise an appropriate
  1432. * default value will be used.
  1433. */
  1434. static av_cold void set_bandwidth(AC3EncodeContext *s)
  1435. {
  1436. int ch, bw_code;
  1437. if (s->cutoff) {
  1438. /* calculate bandwidth based on user-specified cutoff frequency */
  1439. int fbw_coeffs;
  1440. fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
  1441. bw_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
  1442. } else {
  1443. /* use default bandwidth setting */
  1444. /* XXX: should compute the bandwidth according to the frame
  1445. size, so that we avoid annoying high frequency artifacts */
  1446. bw_code = 50;
  1447. }
  1448. /* set number of coefficients for each channel */
  1449. for (ch = 0; ch < s->fbw_channels; ch++) {
  1450. s->bandwidth_code[ch] = bw_code;
  1451. s->nb_coefs[ch] = bw_code * 3 + 73;
  1452. }
  1453. if (s->lfe_on)
  1454. s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
  1455. }
  1456. static av_cold int allocate_buffers(AVCodecContext *avctx)
  1457. {
  1458. int blk, ch;
  1459. AC3EncodeContext *s = avctx->priv_data;
  1460. FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
  1461. alloc_fail);
  1462. for (ch = 0; ch < s->channels; ch++) {
  1463. FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
  1464. (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
  1465. alloc_fail);
  1466. }
  1467. FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * s->channels *
  1468. AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
  1469. FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
  1470. AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
  1471. FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
  1472. AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
  1473. FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
  1474. AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
  1475. FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
  1476. 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
  1477. FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
  1478. AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
  1479. FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
  1480. 64 * sizeof(*s->band_psd_buffer), alloc_fail);
  1481. FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
  1482. 64 * sizeof(*s->mask_buffer), alloc_fail);
  1483. FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
  1484. AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
  1485. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1486. AC3Block *block = &s->blocks[blk];
  1487. FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
  1488. alloc_fail);
  1489. FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
  1490. alloc_fail);
  1491. FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
  1492. alloc_fail);
  1493. FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
  1494. alloc_fail);
  1495. FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
  1496. alloc_fail);
  1497. FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
  1498. alloc_fail);
  1499. FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
  1500. alloc_fail);
  1501. FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
  1502. alloc_fail);
  1503. for (ch = 0; ch < s->channels; ch++) {
  1504. block->bap[ch] = &s->bap_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1505. block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1506. block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1507. block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * s->channels + ch)];
  1508. block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1509. block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * s->channels + ch)];
  1510. block->mask[ch] = &s->mask_buffer [64 * (blk * s->channels + ch)];
  1511. block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  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. }