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.

1856 lines
58KB

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