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