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.

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