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.

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