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>
7 * This file is part of FFmpeg.
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.
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.
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
26 * The simplest AC-3 encoder.
29 //#define ASSERT_LEVEL 2
33 #include "libavutil/audioconvert.h"
34 #include "libavutil/avassert.h"
35 #include "libavutil/avstring.h"
36 #include "libavutil/crc.h"
37 #include "libavutil/opt.h"
43 #include "audioconvert.h"
48 typedef struct AC3Mant {
49 int16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
50 int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
53 #define CMIXLEV_NUM_OPTIONS 3
54 static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
55 LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
58 #define SURMIXLEV_NUM_OPTIONS 3
59 static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
60 LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
63 #define EXTMIXLEV_NUM_OPTIONS 8
64 static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
65 LEVEL_PLUS_3DB, LEVEL_PLUS_1POINT5DB, LEVEL_ONE, LEVEL_MINUS_4POINT5DB,
66 LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
71 * LUT for number of exponent groups.
72 * exponent_group_tab[coupling][exponent strategy-1][number of coefficients]
74 static uint8_t exponent_group_tab[2][3][256];
78 * List of supported channel layouts.
80 const int64_t ff_ac3_channel_layouts[19] = {
84 AV_CH_LAYOUT_SURROUND,
89 AV_CH_LAYOUT_5POINT0_BACK,
90 (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
91 (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
92 (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
93 (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
94 (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
95 (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
96 (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
98 AV_CH_LAYOUT_5POINT1_BACK,
104 * LUT to select the bandwidth code based on the bit rate, sample rate, and
105 * number of full-bandwidth channels.
106 * bandwidth_tab[fbw_channels-1][sample rate code][bit rate code]
108 static const uint8_t ac3_bandwidth_tab[5][3][19] = {
109 // 32 40 48 56 64 80 96 112 128 160 192 224 256 320 384 448 512 576 640
111 { { 0, 0, 0, 12, 16, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
112 { 0, 0, 0, 16, 20, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
113 { 0, 0, 0, 32, 40, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
115 { { 0, 0, 0, 0, 0, 0, 0, 20, 24, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
116 { 0, 0, 0, 0, 0, 0, 4, 24, 28, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
117 { 0, 0, 0, 0, 0, 0, 20, 44, 52, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
119 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 24, 32, 40, 48, 48, 48, 48, 48, 48 },
120 { 0, 0, 0, 0, 0, 0, 0, 0, 4, 20, 28, 36, 44, 56, 56, 56, 56, 56, 56 },
121 { 0, 0, 0, 0, 0, 0, 0, 0, 20, 40, 48, 60, 60, 60, 60, 60, 60, 60, 60 } },
123 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 32, 48, 48, 48, 48, 48, 48 },
124 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 28, 36, 56, 56, 56, 56, 56, 56 },
125 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 48, 60, 60, 60, 60, 60, 60, 60 } },
127 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 20, 32, 40, 48, 48, 48, 48 },
128 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 36, 44, 56, 56, 56, 56 },
129 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 44, 60, 60, 60, 60, 60, 60 } }
134 * LUT to select the coupling start band based on the bit rate, sample rate, and
135 * number of full-bandwidth channels. -1 = coupling off
136 * ac3_coupling_start_tab[channel_mode-2][sample rate code][bit rate code]
138 * TODO: more testing for optimal parameters.
139 * multi-channel tests at 44.1kHz and 32kHz.
141 static const int8_t ac3_coupling_start_tab[6][3][19] = {
142 // 32 40 48 56 64 80 96 112 128 160 192 224 256 320 384 448 512 576 640
145 { { 0, 0, 0, 0, 0, 0, 0, 1, 1, 7, 8, 11, 12, -1, -1, -1, -1, -1, -1 },
146 { 0, 0, 0, 0, 0, 0, 1, 3, 5, 7, 10, 12, 13, -1, -1, -1, -1, -1, -1 },
147 { 0, 0, 0, 0, 1, 2, 2, 9, 13, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
150 { { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
151 { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
152 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
155 { { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
156 { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
157 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
160 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
161 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
162 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
165 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
166 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
167 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
170 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 8, 11, 12, 12, -1, -1 },
171 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 8, 11, 12, 12, -1, -1 },
172 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
177 * Adjust the frame size to make the average bit rate match the target bit rate.
178 * This is only needed for 11025, 22050, and 44100 sample rates or any E-AC-3.
180 void ff_ac3_adjust_frame_size(AC3EncodeContext *s)
182 while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
183 s->bits_written -= s->bit_rate;
184 s->samples_written -= s->sample_rate;
186 s->frame_size = s->frame_size_min +
187 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
188 s->bits_written += s->frame_size * 8;
189 s->samples_written += AC3_FRAME_SIZE;
193 void ff_ac3_compute_coupling_strategy(AC3EncodeContext *s)
198 /* set coupling use flags for each block/channel */
199 /* TODO: turn coupling on/off and adjust start band based on bit usage */
200 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
201 AC3Block *block = &s->blocks[blk];
202 for (ch = 1; ch <= s->fbw_channels; ch++)
203 block->channel_in_cpl[ch] = s->cpl_on;
206 /* enable coupling for each block if at least 2 channels have coupling
207 enabled for that block */
209 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
210 AC3Block *block = &s->blocks[blk];
211 block->num_cpl_channels = 0;
212 for (ch = 1; ch <= s->fbw_channels; ch++)
213 block->num_cpl_channels += block->channel_in_cpl[ch];
214 block->cpl_in_use = block->num_cpl_channels > 1;
215 if (!block->cpl_in_use) {
216 block->num_cpl_channels = 0;
217 for (ch = 1; ch <= s->fbw_channels; ch++)
218 block->channel_in_cpl[ch] = 0;
221 block->new_cpl_strategy = !blk;
223 for (ch = 1; ch <= s->fbw_channels; ch++) {
224 if (block->channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]) {
225 block->new_cpl_strategy = 1;
230 block->new_cpl_leak = block->new_cpl_strategy;
232 if (!blk || (block->cpl_in_use && !got_cpl_snr)) {
233 block->new_snr_offsets = 1;
234 if (block->cpl_in_use)
237 block->new_snr_offsets = 0;
241 /* set bandwidth for each channel */
242 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
243 AC3Block *block = &s->blocks[blk];
244 for (ch = 1; ch <= s->fbw_channels; ch++) {
245 if (block->channel_in_cpl[ch])
246 block->end_freq[ch] = s->start_freq[CPL_CH];
248 block->end_freq[ch] = s->bandwidth_code * 3 + 73;
255 * Apply stereo rematrixing to coefficients based on rematrixing flags.
257 void ff_ac3_apply_rematrixing(AC3EncodeContext *s)
264 if (!s->rematrixing_enabled)
267 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
268 AC3Block *block = &s->blocks[blk];
269 if (block->new_rematrixing_strategy)
270 flags = block->rematrixing_flags;
271 nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
272 for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {
274 start = ff_ac3_rematrix_band_tab[bnd];
275 end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
276 for (i = start; i < end; i++) {
277 int32_t lt = block->fixed_coef[1][i];
278 int32_t rt = block->fixed_coef[2][i];
279 block->fixed_coef[1][i] = (lt + rt) >> 1;
280 block->fixed_coef[2][i] = (lt - rt) >> 1;
289 * Initialize exponent tables.
291 static av_cold void exponent_init(AC3EncodeContext *s)
293 int expstr, i, grpsize;
295 for (expstr = EXP_D15-1; expstr <= EXP_D45-1; expstr++) {
296 grpsize = 3 << expstr;
297 for (i = 12; i < 256; i++) {
298 exponent_group_tab[0][expstr][i] = (i + grpsize - 4) / grpsize;
299 exponent_group_tab[1][expstr][i] = (i ) / grpsize;
303 exponent_group_tab[0][0][7] = 2;
308 * Extract exponents from the MDCT coefficients.
310 static void extract_exponents(AC3EncodeContext *s)
313 int chan_size = AC3_MAX_COEFS * AC3_MAX_BLOCKS * (s->channels - ch + 1);
314 AC3Block *block = &s->blocks[0];
316 s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch], chan_size);
321 * Exponent Difference Threshold.
322 * New exponents are sent if their SAD exceed this number.
324 #define EXP_DIFF_THRESHOLD 500
328 * Calculate exponent strategies for all channels.
329 * Array arrangement is reversed to simplify the per-channel calculation.
331 static void compute_exp_strategy(AC3EncodeContext *s)
335 for (ch = !s->cpl_on; ch <= s->fbw_channels; ch++) {
336 uint8_t *exp_strategy = s->exp_strategy[ch];
337 uint8_t *exp = s->blocks[0].exp[ch];
340 /* estimate if the exponent variation & decide if they should be
341 reused in the next frame */
342 exp_strategy[0] = EXP_NEW;
343 exp += AC3_MAX_COEFS;
344 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++, exp += AC3_MAX_COEFS) {
345 if ((ch == CPL_CH && (!s->blocks[blk].cpl_in_use || !s->blocks[blk-1].cpl_in_use)) ||
346 (ch > CPL_CH && (s->blocks[blk].channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]))) {
347 exp_strategy[blk] = EXP_NEW;
350 exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
351 exp_strategy[blk] = EXP_REUSE;
352 if (ch == CPL_CH && exp_diff > (EXP_DIFF_THRESHOLD * (s->blocks[blk].end_freq[ch] - s->start_freq[ch]) / AC3_MAX_COEFS))
353 exp_strategy[blk] = EXP_NEW;
354 else if (ch > CPL_CH && exp_diff > EXP_DIFF_THRESHOLD)
355 exp_strategy[blk] = EXP_NEW;
358 /* now select the encoding strategy type : if exponents are often
359 recoded, we use a coarse encoding */
361 while (blk < AC3_MAX_BLOCKS) {
363 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
365 switch (blk1 - blk) {
366 case 1: exp_strategy[blk] = EXP_D45; break;
368 case 3: exp_strategy[blk] = EXP_D25; break;
369 default: exp_strategy[blk] = EXP_D15; break;
376 s->exp_strategy[ch][0] = EXP_D15;
377 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
378 s->exp_strategy[ch][blk] = EXP_REUSE;
384 * Update the exponents so that they are the ones the decoder will decode.
386 static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy,
391 nb_groups = exponent_group_tab[cpl][exp_strategy-1][nb_exps] * 3;
393 /* for each group, compute the minimum exponent */
394 switch(exp_strategy) {
396 for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
397 uint8_t exp_min = exp[k];
398 if (exp[k+1] < exp_min)
400 exp[i-cpl] = exp_min;
405 for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
406 uint8_t exp_min = exp[k];
407 if (exp[k+1] < exp_min)
409 if (exp[k+2] < exp_min)
411 if (exp[k+3] < exp_min)
413 exp[i-cpl] = exp_min;
419 /* constraint for DC exponent */
420 if (!cpl && exp[0] > 15)
423 /* decrease the delta between each groups to within 2 so that they can be
424 differentially encoded */
425 for (i = 1; i <= nb_groups; i++)
426 exp[i] = FFMIN(exp[i], exp[i-1] + 2);
429 exp[i] = FFMIN(exp[i], exp[i+1] + 2);
432 exp[-1] = exp[0] & ~1;
434 /* now we have the exponent values the decoder will see */
435 switch (exp_strategy) {
437 for (i = nb_groups, k = (nb_groups * 2)-cpl; i > 0; i--) {
438 uint8_t exp1 = exp[i-cpl];
444 for (i = nb_groups, k = (nb_groups * 4)-cpl; i > 0; i--) {
445 exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i-cpl];
454 * Encode exponents from original extracted form to what the decoder will see.
455 * This copies and groups exponents based on exponent strategy and reduces
456 * deltas between adjacent exponent groups so that they can be differentially
459 static void encode_exponents(AC3EncodeContext *s)
461 int blk, blk1, ch, cpl;
462 uint8_t *exp, *exp_strategy;
463 int nb_coefs, num_reuse_blocks;
465 for (ch = !s->cpl_on; ch <= s->channels; ch++) {
466 exp = s->blocks[0].exp[ch] + s->start_freq[ch];
467 exp_strategy = s->exp_strategy[ch];
469 cpl = (ch == CPL_CH);
471 while (blk < AC3_MAX_BLOCKS) {
472 AC3Block *block = &s->blocks[blk];
473 if (cpl && !block->cpl_in_use) {
474 exp += AC3_MAX_COEFS;
478 nb_coefs = block->end_freq[ch] - s->start_freq[ch];
481 /* count the number of EXP_REUSE blocks after the current block
482 and set exponent reference block numbers */
483 s->exp_ref_block[ch][blk] = blk;
484 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
485 s->exp_ref_block[ch][blk1] = blk;
488 num_reuse_blocks = blk1 - blk - 1;
490 /* for the EXP_REUSE case we select the min of the exponents */
491 s->ac3dsp.ac3_exponent_min(exp-s->start_freq[ch], num_reuse_blocks,
494 encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk], cpl);
496 exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
501 /* reference block numbers have been changed, so reset ref_bap_set */
508 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
509 * varies depending on exponent strategy and bandwidth.
511 static void group_exponents(AC3EncodeContext *s)
514 int group_size, nb_groups, bit_count;
516 int delta0, delta1, delta2;
520 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
521 AC3Block *block = &s->blocks[blk];
522 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
523 int exp_strategy = s->exp_strategy[ch][blk];
524 if (exp_strategy == EXP_REUSE)
526 cpl = (ch == CPL_CH);
527 group_size = exp_strategy + (exp_strategy == EXP_D45);
528 nb_groups = exponent_group_tab[cpl][exp_strategy-1][block->end_freq[ch]-s->start_freq[ch]];
529 bit_count += 4 + (nb_groups * 7);
530 p = block->exp[ch] + s->start_freq[ch] - cpl;
534 block->grouped_exp[ch][0] = exp1;
536 /* remaining exponents are delta encoded */
537 for (i = 1; i <= nb_groups; i++) {
538 /* merge three delta in one code */
542 delta0 = exp1 - exp0 + 2;
543 av_assert2(delta0 >= 0 && delta0 <= 4);
548 delta1 = exp1 - exp0 + 2;
549 av_assert2(delta1 >= 0 && delta1 <= 4);
554 delta2 = exp1 - exp0 + 2;
555 av_assert2(delta2 >= 0 && delta2 <= 4);
557 block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
562 s->exponent_bits = bit_count;
567 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
568 * Extract exponents from MDCT coefficients, calculate exponent strategies,
569 * and encode final exponents.
571 void ff_ac3_process_exponents(AC3EncodeContext *s)
573 extract_exponents(s);
575 compute_exp_strategy(s);
586 * Count frame bits that are based solely on fixed parameters.
587 * This only has to be run once when the encoder is initialized.
589 static void count_frame_bits_fixed(AC3EncodeContext *s)
591 static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
596 * no dynamic range codes
597 * bit allocation parameters do not change between blocks
598 * no delta bit allocation
605 frame_bits = 16; /* sync info */
607 /* bitstream info header */
609 frame_bits += 1 + 1 + 1;
610 /* audio frame header */
613 /* exponent strategy */
614 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
615 frame_bits += 2 * s->fbw_channels + s->lfe_on;
616 /* converter exponent strategy */
617 frame_bits += s->fbw_channels * 5;
620 /* block start info */
624 frame_bits += frame_bits_inc[s->channel_mode];
628 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
630 /* block switch flags */
631 frame_bits += s->fbw_channels;
634 frame_bits += s->fbw_channels;
640 /* spectral extension */
645 /* exponent strategy */
646 frame_bits += 2 * s->fbw_channels;
650 /* bit allocation params */
653 frame_bits += 2 + 2 + 2 + 2 + 3;
656 /* converter snr offset */
661 /* delta bit allocation */
673 frame_bits += 1 + 16;
675 s->frame_bits_fixed = frame_bits;
680 * Initialize bit allocation.
681 * Set default parameter codes and calculate parameter values.
683 static void bit_alloc_init(AC3EncodeContext *s)
687 /* init default parameters */
688 s->slow_decay_code = 2;
689 s->fast_decay_code = 1;
690 s->slow_gain_code = 1;
691 s->db_per_bit_code = s->eac3 ? 2 : 3;
693 for (ch = 0; ch <= s->channels; ch++)
694 s->fast_gain_code[ch] = 4;
696 /* initial snr offset */
697 s->coarse_snr_offset = 40;
699 /* compute real values */
700 /* currently none of these values change during encoding, so we can just
701 set them once at initialization */
702 s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
703 s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
704 s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
705 s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
706 s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
707 s->bit_alloc.cpl_fast_leak = 0;
708 s->bit_alloc.cpl_slow_leak = 0;
710 count_frame_bits_fixed(s);
715 * Count the bits used to encode the frame, minus exponents and mantissas.
716 * Bits based on fixed parameters have already been counted, so now we just
717 * have to add the bits based on parameters that change during encoding.
719 static void count_frame_bits(AC3EncodeContext *s)
721 AC3EncOptions *opt = &s->options;
728 if (s->channel_mode > AC3_CHMODE_MONO) {
730 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
731 AC3Block *block = &s->blocks[blk];
733 if (block->new_cpl_strategy)
737 /* coupling exponent strategy */
738 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
739 frame_bits += 2 * s->blocks[blk].cpl_in_use;
741 if (opt->audio_production_info)
743 if (s->bitstream_id == 6) {
744 if (opt->extended_bsi_1)
746 if (opt->extended_bsi_2)
752 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
753 AC3Block *block = &s->blocks[blk];
755 /* coupling strategy */
758 if (block->new_cpl_strategy) {
761 if (block->cpl_in_use) {
764 if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO)
765 frame_bits += s->fbw_channels;
766 if (s->channel_mode == AC3_CHMODE_STEREO)
772 frame_bits += s->num_cpl_subbands - 1;
776 /* coupling coordinates */
777 if (block->cpl_in_use) {
778 for (ch = 1; ch <= s->fbw_channels; ch++) {
779 if (block->channel_in_cpl[ch]) {
780 if (!s->eac3 || block->new_cpl_coords != 2)
782 if (block->new_cpl_coords) {
784 frame_bits += (4 + 4) * s->num_cpl_bands;
790 /* stereo rematrixing */
791 if (s->channel_mode == AC3_CHMODE_STEREO) {
792 if (!s->eac3 || blk > 0)
794 if (s->blocks[blk].new_rematrixing_strategy)
795 frame_bits += block->num_rematrixing_bands;
798 /* bandwidth codes & gain range */
799 for (ch = 1; ch <= s->fbw_channels; ch++) {
800 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
801 if (!block->channel_in_cpl[ch])
807 /* coupling exponent strategy */
808 if (!s->eac3 && block->cpl_in_use)
811 /* snr offsets and fast gain codes */
814 if (block->new_snr_offsets)
815 frame_bits += 6 + (s->channels + block->cpl_in_use) * (4 + 3);
818 /* coupling leak info */
819 if (block->cpl_in_use) {
820 if (!s->eac3 || block->new_cpl_leak != 2)
822 if (block->new_cpl_leak)
827 s->frame_bits = s->frame_bits_fixed + frame_bits;
832 * Calculate masking curve based on the final exponents.
833 * Also calculate the power spectral densities to use in future calculations.
835 static void bit_alloc_masking(AC3EncodeContext *s)
839 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
840 AC3Block *block = &s->blocks[blk];
841 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
842 /* We only need psd and mask for calculating bap.
843 Since we currently do not calculate bap when exponent
844 strategy is EXP_REUSE we do not need to calculate psd or mask. */
845 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
846 ff_ac3_bit_alloc_calc_psd(block->exp[ch], s->start_freq[ch],
847 block->end_freq[ch], block->psd[ch],
848 block->band_psd[ch]);
849 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
850 s->start_freq[ch], block->end_freq[ch],
851 ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
852 ch == s->lfe_channel,
853 DBA_NONE, 0, NULL, NULL, NULL,
862 * Ensure that bap for each block and channel point to the current bap_buffer.
863 * They may have been switched during the bit allocation search.
865 static void reset_block_bap(AC3EncodeContext *s)
870 if (s->ref_bap[0][0] == s->bap_buffer && s->ref_bap_set)
873 ref_bap = s->bap_buffer;
874 for (ch = 0; ch <= s->channels; ch++) {
875 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
876 s->ref_bap[ch][blk] = ref_bap + AC3_MAX_COEFS * s->exp_ref_block[ch][blk];
877 ref_bap += AC3_MAX_COEFS * AC3_MAX_BLOCKS;
884 * Initialize mantissa counts.
885 * These are set so that they are padded to the next whole group size when bits
886 * are counted in compute_mantissa_size.
888 static void count_mantissa_bits_init(uint16_t mant_cnt[AC3_MAX_BLOCKS][16])
892 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
893 memset(mant_cnt[blk], 0, sizeof(mant_cnt[blk]));
894 mant_cnt[blk][1] = mant_cnt[blk][2] = 2;
895 mant_cnt[blk][4] = 1;
901 * Update mantissa bit counts for all blocks in 1 channel in a given bandwidth
904 static void count_mantissa_bits_update_ch(AC3EncodeContext *s, int ch,
905 uint16_t mant_cnt[AC3_MAX_BLOCKS][16],
910 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
911 AC3Block *block = &s->blocks[blk];
912 if (ch == CPL_CH && !block->cpl_in_use)
914 s->ac3dsp.update_bap_counts(mant_cnt[blk],
915 s->ref_bap[ch][blk] + start,
916 FFMIN(end, block->end_freq[ch]) - start);
922 * Count the number of mantissa bits in the frame based on the bap values.
924 static int count_mantissa_bits(AC3EncodeContext *s)
926 int ch, max_end_freq;
927 LOCAL_ALIGNED_16(uint16_t, mant_cnt, [AC3_MAX_BLOCKS], [16]);
929 count_mantissa_bits_init(mant_cnt);
931 max_end_freq = s->bandwidth_code * 3 + 73;
932 for (ch = !s->cpl_enabled; ch <= s->channels; ch++)
933 count_mantissa_bits_update_ch(s, ch, mant_cnt, s->start_freq[ch],
936 return s->ac3dsp.compute_mantissa_size(mant_cnt);
941 * Run the bit allocation with a given SNR offset.
942 * This calculates the bit allocation pointers that will be used to determine
943 * the quantization of each mantissa.
944 * @return the number of bits needed for mantissas if the given SNR offset is
947 static int bit_alloc(AC3EncodeContext *s, int snr_offset)
951 snr_offset = (snr_offset - 240) << 2;
954 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
955 AC3Block *block = &s->blocks[blk];
957 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
958 /* Currently the only bit allocation parameters which vary across
959 blocks within a frame are the exponent values. We can take
960 advantage of that by reusing the bit allocation pointers
961 whenever we reuse exponents. */
962 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
963 s->ac3dsp.bit_alloc_calc_bap(block->mask[ch], block->psd[ch],
964 s->start_freq[ch], block->end_freq[ch],
965 snr_offset, s->bit_alloc.floor,
966 ff_ac3_bap_tab, s->ref_bap[ch][blk]);
970 return count_mantissa_bits(s);
975 * Constant bitrate bit allocation search.
976 * Find the largest SNR offset that will allow data to fit in the frame.
978 static int cbr_bit_allocation(AC3EncodeContext *s)
982 int snr_offset, snr_incr;
984 bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
986 return AVERROR(EINVAL);
988 snr_offset = s->coarse_snr_offset << 4;
990 /* if previous frame SNR offset was 1023, check if current frame can also
991 use SNR offset of 1023. if so, skip the search. */
992 if ((snr_offset | s->fine_snr_offset[1]) == 1023) {
993 if (bit_alloc(s, 1023) <= bits_left)
997 while (snr_offset >= 0 &&
998 bit_alloc(s, snr_offset) > bits_left) {
1002 return AVERROR(EINVAL);
1004 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1005 for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1006 while (snr_offset + snr_incr <= 1023 &&
1007 bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1008 snr_offset += snr_incr;
1009 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1012 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1015 s->coarse_snr_offset = snr_offset >> 4;
1016 for (ch = !s->cpl_on; ch <= s->channels; ch++)
1017 s->fine_snr_offset[ch] = snr_offset & 0xF;
1024 * Perform bit allocation search.
1025 * Finds the SNR offset value that maximizes quality and fits in the specified
1026 * frame size. Output is the SNR offset and a set of bit allocation pointers
1027 * used to quantize the mantissas.
1029 int ff_ac3_compute_bit_allocation(AC3EncodeContext *s)
1031 count_frame_bits(s);
1033 bit_alloc_masking(s);
1035 return cbr_bit_allocation(s);
1040 * Symmetric quantization on 'levels' levels.
1042 static inline int sym_quant(int c, int e, int levels)
1044 int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1045 av_assert2(v >= 0 && v < levels);
1051 * Asymmetric quantization on 2^qbits levels.
1053 static inline int asym_quant(int c, int e, int qbits)
1057 c = (((c << e) >> (24 - qbits)) + 1) >> 1;
1058 m = (1 << (qbits-1));
1061 av_assert2(c >= -m);
1067 * Quantize a set of mantissas for a single channel in a single block.
1069 static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1070 uint8_t *exp, uint8_t *bap,
1071 int16_t *qmant, int start_freq,
1076 for (i = start_freq; i < end_freq; i++) {
1078 int c = fixed_coef[i];
1086 v = sym_quant(c, e, 3);
1087 switch (s->mant1_cnt) {
1089 s->qmant1_ptr = &qmant[i];
1094 *s->qmant1_ptr += 3 * v;
1099 *s->qmant1_ptr += v;
1106 v = sym_quant(c, e, 5);
1107 switch (s->mant2_cnt) {
1109 s->qmant2_ptr = &qmant[i];
1114 *s->qmant2_ptr += 5 * v;
1119 *s->qmant2_ptr += v;
1126 v = sym_quant(c, e, 7);
1129 v = sym_quant(c, e, 11);
1130 switch (s->mant4_cnt) {
1132 s->qmant4_ptr = &qmant[i];
1137 *s->qmant4_ptr += v;
1144 v = sym_quant(c, e, 15);
1147 v = asym_quant(c, e, 14);
1150 v = asym_quant(c, e, 16);
1153 v = asym_quant(c, e, b - 1);
1162 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1164 void ff_ac3_quantize_mantissas(AC3EncodeContext *s)
1166 int blk, ch, ch0=0, got_cpl;
1168 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1169 AC3Block *block = &s->blocks[blk];
1172 got_cpl = !block->cpl_in_use;
1173 for (ch = 1; ch <= s->channels; ch++) {
1174 if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1179 quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1180 s->blocks[s->exp_ref_block[ch][blk]].exp[ch],
1181 s->ref_bap[ch][blk], block->qmant[ch],
1182 s->start_freq[ch], block->end_freq[ch]);
1191 * Write the AC-3 frame header to the output bitstream.
1193 static void ac3_output_frame_header(AC3EncodeContext *s)
1195 AC3EncOptions *opt = &s->options;
1197 put_bits(&s->pb, 16, 0x0b77); /* frame header */
1198 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
1199 put_bits(&s->pb, 2, s->bit_alloc.sr_code);
1200 put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1201 put_bits(&s->pb, 5, s->bitstream_id);
1202 put_bits(&s->pb, 3, s->bitstream_mode);
1203 put_bits(&s->pb, 3, s->channel_mode);
1204 if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1205 put_bits(&s->pb, 2, s->center_mix_level);
1206 if (s->channel_mode & 0x04)
1207 put_bits(&s->pb, 2, s->surround_mix_level);
1208 if (s->channel_mode == AC3_CHMODE_STEREO)
1209 put_bits(&s->pb, 2, opt->dolby_surround_mode);
1210 put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1211 put_bits(&s->pb, 5, -opt->dialogue_level);
1212 put_bits(&s->pb, 1, 0); /* no compression control word */
1213 put_bits(&s->pb, 1, 0); /* no lang code */
1214 put_bits(&s->pb, 1, opt->audio_production_info);
1215 if (opt->audio_production_info) {
1216 put_bits(&s->pb, 5, opt->mixing_level - 80);
1217 put_bits(&s->pb, 2, opt->room_type);
1219 put_bits(&s->pb, 1, opt->copyright);
1220 put_bits(&s->pb, 1, opt->original);
1221 if (s->bitstream_id == 6) {
1222 /* alternate bit stream syntax */
1223 put_bits(&s->pb, 1, opt->extended_bsi_1);
1224 if (opt->extended_bsi_1) {
1225 put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1226 put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1227 put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1228 put_bits(&s->pb, 3, s->loro_center_mix_level);
1229 put_bits(&s->pb, 3, s->loro_surround_mix_level);
1231 put_bits(&s->pb, 1, opt->extended_bsi_2);
1232 if (opt->extended_bsi_2) {
1233 put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1234 put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1235 put_bits(&s->pb, 1, opt->ad_converter_type);
1236 put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
1239 put_bits(&s->pb, 1, 0); /* no time code 1 */
1240 put_bits(&s->pb, 1, 0); /* no time code 2 */
1242 put_bits(&s->pb, 1, 0); /* no additional bit stream info */
1247 * Write one audio block to the output bitstream.
1249 static void output_audio_block(AC3EncodeContext *s, int blk)
1251 int ch, i, baie, bnd, got_cpl;
1253 AC3Block *block = &s->blocks[blk];
1255 /* block switching */
1257 for (ch = 0; ch < s->fbw_channels; ch++)
1258 put_bits(&s->pb, 1, 0);
1263 for (ch = 0; ch < s->fbw_channels; ch++)
1264 put_bits(&s->pb, 1, 1);
1267 /* dynamic range codes */
1268 put_bits(&s->pb, 1, 0);
1270 /* spectral extension */
1272 put_bits(&s->pb, 1, 0);
1274 /* channel coupling */
1276 put_bits(&s->pb, 1, block->new_cpl_strategy);
1277 if (block->new_cpl_strategy) {
1279 put_bits(&s->pb, 1, block->cpl_in_use);
1280 if (block->cpl_in_use) {
1281 int start_sub, end_sub;
1283 put_bits(&s->pb, 1, 0); /* enhanced coupling */
1284 if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO) {
1285 for (ch = 1; ch <= s->fbw_channels; ch++)
1286 put_bits(&s->pb, 1, block->channel_in_cpl[ch]);
1288 if (s->channel_mode == AC3_CHMODE_STEREO)
1289 put_bits(&s->pb, 1, 0); /* phase flags in use */
1290 start_sub = (s->start_freq[CPL_CH] - 37) / 12;
1291 end_sub = (s->cpl_end_freq - 37) / 12;
1292 put_bits(&s->pb, 4, start_sub);
1293 put_bits(&s->pb, 4, end_sub - 3);
1294 /* coupling band structure */
1296 put_bits(&s->pb, 1, 0); /* use default */
1298 for (bnd = start_sub+1; bnd < end_sub; bnd++)
1299 put_bits(&s->pb, 1, ff_eac3_default_cpl_band_struct[bnd]);
1304 /* coupling coordinates */
1305 if (block->cpl_in_use) {
1306 for (ch = 1; ch <= s->fbw_channels; ch++) {
1307 if (block->channel_in_cpl[ch]) {
1308 if (!s->eac3 || block->new_cpl_coords != 2)
1309 put_bits(&s->pb, 1, block->new_cpl_coords);
1310 if (block->new_cpl_coords) {
1311 put_bits(&s->pb, 2, block->cpl_master_exp[ch]);
1312 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
1313 put_bits(&s->pb, 4, block->cpl_coord_exp [ch][bnd]);
1314 put_bits(&s->pb, 4, block->cpl_coord_mant[ch][bnd]);
1321 /* stereo rematrixing */
1322 if (s->channel_mode == AC3_CHMODE_STEREO) {
1323 if (!s->eac3 || blk > 0)
1324 put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1325 if (block->new_rematrixing_strategy) {
1326 /* rematrixing flags */
1327 for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++)
1328 put_bits(&s->pb, 1, block->rematrixing_flags[bnd]);
1332 /* exponent strategy */
1334 for (ch = !block->cpl_in_use; ch <= s->fbw_channels; ch++)
1335 put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1337 put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1341 for (ch = 1; ch <= s->fbw_channels; ch++) {
1342 if (s->exp_strategy[ch][blk] != EXP_REUSE && !block->channel_in_cpl[ch])
1343 put_bits(&s->pb, 6, s->bandwidth_code);
1347 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1349 int cpl = (ch == CPL_CH);
1351 if (s->exp_strategy[ch][blk] == EXP_REUSE)
1355 put_bits(&s->pb, 4, block->grouped_exp[ch][0] >> cpl);
1357 /* exponent groups */
1358 nb_groups = exponent_group_tab[cpl][s->exp_strategy[ch][blk]-1][block->end_freq[ch]-s->start_freq[ch]];
1359 for (i = 1; i <= nb_groups; i++)
1360 put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1362 /* gain range info */
1363 if (ch != s->lfe_channel && !cpl)
1364 put_bits(&s->pb, 2, 0);
1367 /* bit allocation info */
1370 put_bits(&s->pb, 1, baie);
1372 put_bits(&s->pb, 2, s->slow_decay_code);
1373 put_bits(&s->pb, 2, s->fast_decay_code);
1374 put_bits(&s->pb, 2, s->slow_gain_code);
1375 put_bits(&s->pb, 2, s->db_per_bit_code);
1376 put_bits(&s->pb, 3, s->floor_code);
1382 put_bits(&s->pb, 1, block->new_snr_offsets);
1383 if (block->new_snr_offsets) {
1384 put_bits(&s->pb, 6, s->coarse_snr_offset);
1385 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1386 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1387 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1391 put_bits(&s->pb, 1, 0); /* no converter snr offset */
1395 if (block->cpl_in_use) {
1396 if (!s->eac3 || block->new_cpl_leak != 2)
1397 put_bits(&s->pb, 1, block->new_cpl_leak);
1398 if (block->new_cpl_leak) {
1399 put_bits(&s->pb, 3, s->bit_alloc.cpl_fast_leak);
1400 put_bits(&s->pb, 3, s->bit_alloc.cpl_slow_leak);
1405 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1406 put_bits(&s->pb, 1, 0); /* no data to skip */
1410 got_cpl = !block->cpl_in_use;
1411 for (ch = 1; ch <= s->channels; ch++) {
1414 if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1419 for (i = s->start_freq[ch]; i < block->end_freq[ch]; i++) {
1420 q = block->qmant[ch][i];
1421 b = s->ref_bap[ch][blk][i];
1424 case 1: if (q != 128) put_bits (&s->pb, 5, q); break;
1425 case 2: if (q != 128) put_bits (&s->pb, 7, q); break;
1426 case 3: put_sbits(&s->pb, 3, q); break;
1427 case 4: if (q != 128) put_bits (&s->pb, 7, q); break;
1428 case 14: put_sbits(&s->pb, 14, q); break;
1429 case 15: put_sbits(&s->pb, 16, q); break;
1430 default: put_sbits(&s->pb, b-1, q); break;
1439 /** CRC-16 Polynomial */
1440 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1443 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1460 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1466 r = mul_poly(r, a, poly);
1467 a = mul_poly(a, a, poly);
1475 * Fill the end of the frame with 0's and compute the two CRCs.
1477 static void output_frame_end(AC3EncodeContext *s)
1479 const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1480 int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1483 frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1485 /* pad the remainder of the frame with zeros */
1486 av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1487 flush_put_bits(&s->pb);
1489 pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1490 av_assert2(pad_bytes >= 0);
1492 memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1496 crc2_partial = av_crc(crc_ctx, 0, frame + 2, s->frame_size - 5);
1499 /* this is not so easy because it is at the beginning of the data... */
1500 crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1501 crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1502 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1503 AV_WB16(frame + 2, crc1);
1506 crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1507 s->frame_size - frame_size_58 - 3);
1509 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1510 /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1511 if (crc2 == 0x770B) {
1512 frame[s->frame_size - 3] ^= 0x1;
1513 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1515 crc2 = av_bswap16(crc2);
1516 AV_WB16(frame + s->frame_size - 2, crc2);
1521 * Write the frame to the output bitstream.
1523 void ff_ac3_output_frame(AC3EncodeContext *s, unsigned char *frame)
1527 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1529 s->output_frame_header(s);
1531 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1532 output_audio_block(s, blk);
1534 output_frame_end(s);
1538 static void dprint_options(AVCodecContext *avctx)
1541 AC3EncodeContext *s = avctx->priv_data;
1542 AC3EncOptions *opt = &s->options;
1545 switch (s->bitstream_id) {
1546 case 6: av_strlcpy(strbuf, "AC-3 (alt syntax)", 32); break;
1547 case 8: av_strlcpy(strbuf, "AC-3 (standard)", 32); break;
1548 case 9: av_strlcpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
1549 case 10: av_strlcpy(strbuf, "AC-3 (dnet quater-rate)", 32); break;
1550 case 16: av_strlcpy(strbuf, "E-AC-3 (enhanced)", 32); break;
1551 default: snprintf(strbuf, 32, "ERROR");
1553 av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
1554 av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
1555 av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
1556 av_dlog(avctx, "channel_layout: %s\n", strbuf);
1557 av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
1558 av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
1560 av_dlog(avctx, "cutoff: %d\n", s->cutoff);
1562 av_dlog(avctx, "per_frame_metadata: %s\n",
1563 opt->allow_per_frame_metadata?"on":"off");
1565 av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
1566 s->center_mix_level);
1568 av_dlog(avctx, "center_mixlev: {not written}\n");
1569 if (s->has_surround)
1570 av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
1571 s->surround_mix_level);
1573 av_dlog(avctx, "surround_mixlev: {not written}\n");
1574 if (opt->audio_production_info) {
1575 av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
1576 switch (opt->room_type) {
1577 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1578 case 1: av_strlcpy(strbuf, "large", 32); break;
1579 case 2: av_strlcpy(strbuf, "small", 32); break;
1580 default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
1582 av_dlog(avctx, "room_type: %s\n", strbuf);
1584 av_dlog(avctx, "mixing_level: {not written}\n");
1585 av_dlog(avctx, "room_type: {not written}\n");
1587 av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
1588 av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
1589 if (s->channel_mode == AC3_CHMODE_STEREO) {
1590 switch (opt->dolby_surround_mode) {
1591 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1592 case 1: av_strlcpy(strbuf, "on", 32); break;
1593 case 2: av_strlcpy(strbuf, "off", 32); break;
1594 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
1596 av_dlog(avctx, "dsur_mode: %s\n", strbuf);
1598 av_dlog(avctx, "dsur_mode: {not written}\n");
1600 av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
1602 if (s->bitstream_id == 6) {
1603 if (opt->extended_bsi_1) {
1604 switch (opt->preferred_stereo_downmix) {
1605 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1606 case 1: av_strlcpy(strbuf, "ltrt", 32); break;
1607 case 2: av_strlcpy(strbuf, "loro", 32); break;
1608 default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
1610 av_dlog(avctx, "dmix_mode: %s\n", strbuf);
1611 av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
1612 opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
1613 av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
1614 opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
1615 av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
1616 opt->loro_center_mix_level, s->loro_center_mix_level);
1617 av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
1618 opt->loro_surround_mix_level, s->loro_surround_mix_level);
1620 av_dlog(avctx, "extended bitstream info 1: {not written}\n");
1622 if (opt->extended_bsi_2) {
1623 switch (opt->dolby_surround_ex_mode) {
1624 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1625 case 1: av_strlcpy(strbuf, "on", 32); break;
1626 case 2: av_strlcpy(strbuf, "off", 32); break;
1627 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
1629 av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
1630 switch (opt->dolby_headphone_mode) {
1631 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1632 case 1: av_strlcpy(strbuf, "on", 32); break;
1633 case 2: av_strlcpy(strbuf, "off", 32); break;
1634 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
1636 av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
1638 switch (opt->ad_converter_type) {
1639 case 0: av_strlcpy(strbuf, "standard", 32); break;
1640 case 1: av_strlcpy(strbuf, "hdcd", 32); break;
1641 default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
1643 av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
1645 av_dlog(avctx, "extended bitstream info 2: {not written}\n");
1652 #define FLT_OPTION_THRESHOLD 0.01
1654 static int validate_float_option(float v, const float *v_list, int v_list_size)
1658 for (i = 0; i < v_list_size; i++) {
1659 if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
1660 v > (v_list[i] - FLT_OPTION_THRESHOLD))
1663 if (i == v_list_size)
1670 static void validate_mix_level(void *log_ctx, const char *opt_name,
1671 float *opt_param, const float *list,
1672 int list_size, int default_value, int min_value,
1675 int mixlev = validate_float_option(*opt_param, list, list_size);
1676 if (mixlev < min_value) {
1677 mixlev = default_value;
1678 if (*opt_param >= 0.0) {
1679 av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
1680 "default value: %0.3f\n", opt_name, list[mixlev]);
1683 *opt_param = list[mixlev];
1684 *ctx_param = mixlev;
1689 * Validate metadata options as set by AVOption system.
1690 * These values can optionally be changed per-frame.
1692 int ff_ac3_validate_metadata(AVCodecContext *avctx)
1694 AC3EncodeContext *s = avctx->priv_data;
1695 AC3EncOptions *opt = &s->options;
1697 /* validate mixing levels */
1698 if (s->has_center) {
1699 validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
1700 cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
1701 &s->center_mix_level);
1703 if (s->has_surround) {
1704 validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
1705 surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
1706 &s->surround_mix_level);
1709 /* set audio production info flag */
1710 if (opt->mixing_level >= 0 || opt->room_type >= 0) {
1711 if (opt->mixing_level < 0) {
1712 av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
1713 "room_type is set\n");
1714 return AVERROR(EINVAL);
1716 if (opt->mixing_level < 80) {
1717 av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
1718 "80dB and 111dB\n");
1719 return AVERROR(EINVAL);
1721 /* default room type */
1722 if (opt->room_type < 0)
1724 opt->audio_production_info = 1;
1726 opt->audio_production_info = 0;
1729 /* set extended bsi 1 flag */
1730 if ((s->has_center || s->has_surround) &&
1731 (opt->preferred_stereo_downmix >= 0 ||
1732 opt->ltrt_center_mix_level >= 0 ||
1733 opt->ltrt_surround_mix_level >= 0 ||
1734 opt->loro_center_mix_level >= 0 ||
1735 opt->loro_surround_mix_level >= 0)) {
1736 /* default preferred stereo downmix */
1737 if (opt->preferred_stereo_downmix < 0)
1738 opt->preferred_stereo_downmix = 0;
1739 /* validate Lt/Rt center mix level */
1740 validate_mix_level(avctx, "ltrt_center_mix_level",
1741 &opt->ltrt_center_mix_level, extmixlev_options,
1742 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1743 &s->ltrt_center_mix_level);
1744 /* validate Lt/Rt surround mix level */
1745 validate_mix_level(avctx, "ltrt_surround_mix_level",
1746 &opt->ltrt_surround_mix_level, extmixlev_options,
1747 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1748 &s->ltrt_surround_mix_level);
1749 /* validate Lo/Ro center mix level */
1750 validate_mix_level(avctx, "loro_center_mix_level",
1751 &opt->loro_center_mix_level, extmixlev_options,
1752 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1753 &s->loro_center_mix_level);
1754 /* validate Lo/Ro surround mix level */
1755 validate_mix_level(avctx, "loro_surround_mix_level",
1756 &opt->loro_surround_mix_level, extmixlev_options,
1757 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1758 &s->loro_surround_mix_level);
1759 opt->extended_bsi_1 = 1;
1761 opt->extended_bsi_1 = 0;
1764 /* set extended bsi 2 flag */
1765 if (opt->dolby_surround_ex_mode >= 0 ||
1766 opt->dolby_headphone_mode >= 0 ||
1767 opt->ad_converter_type >= 0) {
1768 /* default dolby surround ex mode */
1769 if (opt->dolby_surround_ex_mode < 0)
1770 opt->dolby_surround_ex_mode = 0;
1771 /* default dolby headphone mode */
1772 if (opt->dolby_headphone_mode < 0)
1773 opt->dolby_headphone_mode = 0;
1774 /* default A/D converter type */
1775 if (opt->ad_converter_type < 0)
1776 opt->ad_converter_type = 0;
1777 opt->extended_bsi_2 = 1;
1779 opt->extended_bsi_2 = 0;
1782 /* set bitstream id for alternate bitstream syntax */
1783 if (opt->extended_bsi_1 || opt->extended_bsi_2) {
1784 if (s->bitstream_id > 8 && s->bitstream_id < 11) {
1785 static int warn_once = 1;
1787 av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
1788 "not compatible with reduced samplerates. writing of "
1789 "extended bitstream information will be disabled.\n");
1793 s->bitstream_id = 6;
1802 * Finalize encoding and free any memory allocated by the encoder.
1804 av_cold int ff_ac3_encode_close(AVCodecContext *avctx)
1807 AC3EncodeContext *s = avctx->priv_data;
1809 av_freep(&s->windowed_samples);
1810 for (ch = 0; ch < s->channels; ch++)
1811 av_freep(&s->planar_samples[ch]);
1812 av_freep(&s->planar_samples);
1813 av_freep(&s->bap_buffer);
1814 av_freep(&s->bap1_buffer);
1815 av_freep(&s->mdct_coef_buffer);
1816 av_freep(&s->fixed_coef_buffer);
1817 av_freep(&s->exp_buffer);
1818 av_freep(&s->grouped_exp_buffer);
1819 av_freep(&s->psd_buffer);
1820 av_freep(&s->band_psd_buffer);
1821 av_freep(&s->mask_buffer);
1822 av_freep(&s->qmant_buffer);
1823 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1824 AC3Block *block = &s->blocks[blk];
1825 av_freep(&block->mdct_coef);
1826 av_freep(&block->fixed_coef);
1827 av_freep(&block->exp);
1828 av_freep(&block->grouped_exp);
1829 av_freep(&block->psd);
1830 av_freep(&block->band_psd);
1831 av_freep(&block->mask);
1832 av_freep(&block->qmant);
1835 s->mdct_end(s->mdct);
1838 av_freep(&avctx->coded_frame);
1844 * Set channel information during initialization.
1846 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1847 int64_t *channel_layout)
1851 if (channels < 1 || channels > AC3_MAX_CHANNELS)
1852 return AVERROR(EINVAL);
1853 if ((uint64_t)*channel_layout > 0x7FF)
1854 return AVERROR(EINVAL);
1855 ch_layout = *channel_layout;
1857 ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1859 s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1860 s->channels = channels;
1861 s->fbw_channels = channels - s->lfe_on;
1862 s->lfe_channel = s->lfe_on ? s->fbw_channels + 1 : -1;
1864 ch_layout -= AV_CH_LOW_FREQUENCY;
1866 switch (ch_layout) {
1867 case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
1868 case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
1869 case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
1870 case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
1871 case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
1872 case AV_CH_LAYOUT_QUAD:
1873 case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
1874 case AV_CH_LAYOUT_5POINT0:
1875 case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
1877 return AVERROR(EINVAL);
1879 s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
1880 s->has_surround = s->channel_mode & 0x04;
1882 s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1883 *channel_layout = ch_layout;
1885 *channel_layout |= AV_CH_LOW_FREQUENCY;
1891 static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1895 /* validate channel layout */
1896 if (!avctx->channel_layout) {
1897 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1898 "encoder will guess the layout, but it "
1899 "might be incorrect.\n");
1901 ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1903 av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1907 /* validate sample rate */
1908 /* note: max_sr could be changed from 2 to 5 for E-AC-3 once we find a
1909 decoder that supports half sample rate so we can validate that
1910 the generated files are correct. */
1911 max_sr = s->eac3 ? 2 : 8;
1912 for (i = 0; i <= max_sr; i++) {
1913 if ((ff_ac3_sample_rate_tab[i % 3] >> (i / 3)) == avctx->sample_rate)
1917 av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1918 return AVERROR(EINVAL);
1920 s->sample_rate = avctx->sample_rate;
1921 s->bit_alloc.sr_shift = i / 3;
1922 s->bit_alloc.sr_code = i % 3;
1923 s->bitstream_id = s->eac3 ? 16 : 8 + s->bit_alloc.sr_shift;
1925 /* validate bit rate */
1927 int max_br, min_br, wpf, min_br_dist, min_br_code;
1929 /* calculate min/max bitrate */
1930 max_br = 2048 * s->sample_rate / AC3_FRAME_SIZE * 16;
1931 min_br = ((s->sample_rate + (AC3_FRAME_SIZE-1)) / AC3_FRAME_SIZE) * 16;
1932 if (avctx->bit_rate < min_br || avctx->bit_rate > max_br) {
1933 av_log(avctx, AV_LOG_ERROR, "invalid bit rate. must be %d to %d "
1934 "for this sample rate\n", min_br, max_br);
1935 return AVERROR(EINVAL);
1938 /* calculate words-per-frame for the selected bitrate */
1939 wpf = (avctx->bit_rate / 16) * AC3_FRAME_SIZE / s->sample_rate;
1940 av_assert1(wpf > 0 && wpf <= 2048);
1942 /* find the closest AC-3 bitrate code to the selected bitrate.
1943 this is needed for lookup tables for bandwidth and coupling
1944 parameter selection */
1946 min_br_dist = INT_MAX;
1947 for (i = 0; i < 19; i++) {
1948 int br_dist = abs(ff_ac3_bitrate_tab[i] * 1000 - avctx->bit_rate);
1949 if (br_dist < min_br_dist) {
1950 min_br_dist = br_dist;
1955 /* make sure the minimum frame size is below the average frame size */
1956 s->frame_size_code = min_br_code << 1;
1957 while (wpf > 1 && wpf * s->sample_rate / AC3_FRAME_SIZE * 16 > avctx->bit_rate)
1959 s->frame_size_min = 2 * wpf;
1961 for (i = 0; i < 19; i++) {
1962 if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
1966 av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
1967 return AVERROR(EINVAL);
1969 s->frame_size_code = i << 1;
1970 s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
1972 s->bit_rate = avctx->bit_rate;
1973 s->frame_size = s->frame_size_min;
1975 /* validate cutoff */
1976 if (avctx->cutoff < 0) {
1977 av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
1978 return AVERROR(EINVAL);
1980 s->cutoff = avctx->cutoff;
1981 if (s->cutoff > (s->sample_rate >> 1))
1982 s->cutoff = s->sample_rate >> 1;
1984 /* validate audio service type / channels combination */
1985 if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
1986 avctx->channels == 1) ||
1987 ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
1988 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
1989 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
1990 && avctx->channels > 1)) {
1991 av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
1992 "specified number of channels\n");
1993 return AVERROR(EINVAL);
1997 ret = ff_ac3_validate_metadata(avctx);
2002 s->rematrixing_enabled = s->options.stereo_rematrixing &&
2003 (s->channel_mode == AC3_CHMODE_STEREO);
2005 s->cpl_enabled = s->options.channel_coupling &&
2006 s->channel_mode >= AC3_CHMODE_STEREO && !s->fixed_point;
2013 * Set bandwidth for all channels.
2014 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2015 * default value will be used.
2017 static av_cold void set_bandwidth(AC3EncodeContext *s)
2020 int av_uninit(cpl_start);
2023 /* calculate bandwidth based on user-specified cutoff frequency */
2025 fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2026 s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2028 /* use default bandwidth setting */
2029 s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2032 /* set number of coefficients for each channel */
2033 for (ch = 1; ch <= s->fbw_channels; ch++) {
2034 s->start_freq[ch] = 0;
2035 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2036 s->blocks[blk].end_freq[ch] = s->bandwidth_code * 3 + 73;
2038 /* LFE channel always has 7 coefs */
2040 s->start_freq[s->lfe_channel] = 0;
2041 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2042 s->blocks[blk].end_freq[ch] = 7;
2045 /* initialize coupling strategy */
2046 if (s->cpl_enabled) {
2047 if (s->options.cpl_start >= 0) {
2048 cpl_start = s->options.cpl_start;
2050 cpl_start = ac3_coupling_start_tab[s->channel_mode-2][s->bit_alloc.sr_code][s->frame_size_code/2];
2055 if (s->cpl_enabled) {
2056 int i, cpl_start_band, cpl_end_band;
2057 uint8_t *cpl_band_sizes = s->cpl_band_sizes;
2059 cpl_end_band = s->bandwidth_code / 4 + 3;
2060 cpl_start_band = av_clip(cpl_start, 0, FFMIN(cpl_end_band-1, 15));
2062 s->num_cpl_subbands = cpl_end_band - cpl_start_band;
2064 s->num_cpl_bands = 1;
2065 *cpl_band_sizes = 12;
2066 for (i = cpl_start_band + 1; i < cpl_end_band; i++) {
2067 if (ff_eac3_default_cpl_band_struct[i]) {
2068 *cpl_band_sizes += 12;
2072 *cpl_band_sizes = 12;
2076 s->start_freq[CPL_CH] = cpl_start_band * 12 + 37;
2077 s->cpl_end_freq = cpl_end_band * 12 + 37;
2078 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2079 s->blocks[blk].end_freq[CPL_CH] = s->cpl_end_freq;
2084 static av_cold int allocate_buffers(AVCodecContext *avctx)
2087 AC3EncodeContext *s = avctx->priv_data;
2088 int channels = s->channels + 1; /* includes coupling channel */
2090 if (s->allocate_sample_buffers(s))
2093 FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * channels *
2094 AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
2095 FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * channels *
2096 AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
2097 FF_ALLOCZ_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * channels *
2098 AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
2099 FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * channels *
2100 AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
2101 FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * channels *
2102 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
2103 FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * channels *
2104 AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
2105 FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * channels *
2106 64 * sizeof(*s->band_psd_buffer), alloc_fail);
2107 FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * channels *
2108 64 * sizeof(*s->mask_buffer), alloc_fail);
2109 FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * channels *
2110 AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
2111 if (s->cpl_enabled) {
2112 FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_exp_buffer, AC3_MAX_BLOCKS * channels *
2113 16 * sizeof(*s->cpl_coord_exp_buffer), alloc_fail);
2114 FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_mant_buffer, AC3_MAX_BLOCKS * channels *
2115 16 * sizeof(*s->cpl_coord_mant_buffer), alloc_fail);
2117 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2118 AC3Block *block = &s->blocks[blk];
2119 FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, channels * sizeof(*block->mdct_coef),
2121 FF_ALLOCZ_OR_GOTO(avctx, block->exp, channels * sizeof(*block->exp),
2123 FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, channels * sizeof(*block->grouped_exp),
2125 FF_ALLOCZ_OR_GOTO(avctx, block->psd, channels * sizeof(*block->psd),
2127 FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, channels * sizeof(*block->band_psd),
2129 FF_ALLOCZ_OR_GOTO(avctx, block->mask, channels * sizeof(*block->mask),
2131 FF_ALLOCZ_OR_GOTO(avctx, block->qmant, channels * sizeof(*block->qmant),
2133 if (s->cpl_enabled) {
2134 FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_exp, channels * sizeof(*block->cpl_coord_exp),
2136 FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_mant, channels * sizeof(*block->cpl_coord_mant),
2140 for (ch = 0; ch < channels; ch++) {
2141 /* arrangement: block, channel, coeff */
2142 block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * channels + ch)];
2143 block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
2144 block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * channels + ch)];
2145 block->mask[ch] = &s->mask_buffer [64 * (blk * channels + ch)];
2146 block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
2147 if (s->cpl_enabled) {
2148 block->cpl_coord_exp[ch] = &s->cpl_coord_exp_buffer [16 * (blk * channels + ch)];
2149 block->cpl_coord_mant[ch] = &s->cpl_coord_mant_buffer[16 * (blk * channels + ch)];
2152 /* arrangement: channel, block, coeff */
2153 block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2154 block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2158 if (!s->fixed_point) {
2159 FF_ALLOCZ_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * channels *
2160 AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
2161 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2162 AC3Block *block = &s->blocks[blk];
2163 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2164 sizeof(*block->fixed_coef), alloc_fail);
2165 for (ch = 0; ch < channels; ch++)
2166 block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2169 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2170 AC3Block *block = &s->blocks[blk];
2171 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2172 sizeof(*block->fixed_coef), alloc_fail);
2173 for (ch = 0; ch < channels; ch++)
2174 block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2180 return AVERROR(ENOMEM);
2185 * Initialize the encoder.
2187 av_cold int ff_ac3_encode_init(AVCodecContext *avctx)
2189 AC3EncodeContext *s = avctx->priv_data;
2190 int ret, frame_size_58;
2194 s->eac3 = avctx->codec_id == CODEC_ID_EAC3;
2196 avctx->frame_size = AC3_FRAME_SIZE;
2198 ff_ac3_common_init();
2200 ret = validate_options(avctx, s);
2204 s->bitstream_mode = avctx->audio_service_type;
2205 if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2206 s->bitstream_mode = 0x7;
2208 s->bits_written = 0;
2209 s->samples_written = 0;
2211 /* calculate crc_inv for both possible frame sizes */
2212 frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
2213 s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2214 if (s->bit_alloc.sr_code == 1) {
2215 frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2216 s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2219 /* set function pointers */
2220 if (CONFIG_AC3_FIXED_ENCODER && s->fixed_point) {
2221 s->mdct_end = ff_ac3_fixed_mdct_end;
2222 s->mdct_init = ff_ac3_fixed_mdct_init;
2223 s->allocate_sample_buffers = ff_ac3_fixed_allocate_sample_buffers;
2224 } else if (CONFIG_AC3_ENCODER || CONFIG_EAC3_ENCODER) {
2225 s->mdct_end = ff_ac3_float_mdct_end;
2226 s->mdct_init = ff_ac3_float_mdct_init;
2227 s->allocate_sample_buffers = ff_ac3_float_allocate_sample_buffers;
2229 if (CONFIG_EAC3_ENCODER && s->eac3)
2230 s->output_frame_header = ff_eac3_output_frame_header;
2232 s->output_frame_header = ac3_output_frame_header;
2240 FF_ALLOCZ_OR_GOTO(avctx, s->mdct, sizeof(AC3MDCTContext), init_fail);
2241 ret = s->mdct_init(avctx, s->mdct, 9);
2245 ret = allocate_buffers(avctx);
2249 avctx->coded_frame= avcodec_alloc_frame();
2251 dsputil_init(&s->dsp, avctx);
2252 ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2254 dprint_options(avctx);
2258 ff_ac3_encode_close(avctx);