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)
199 /* set coupling use flags for each block/channel */
200 /* TODO: turn coupling on/off and adjust start band based on bit usage */
201 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
202 AC3Block *block = &s->blocks[blk];
203 for (ch = 1; ch <= s->fbw_channels; ch++)
204 block->channel_in_cpl[ch] = s->cpl_on;
207 /* enable coupling for each block if at least 2 channels have coupling
208 enabled for that block */
211 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
212 AC3Block *block = &s->blocks[blk];
213 block->num_cpl_channels = 0;
214 for (ch = 1; ch <= s->fbw_channels; ch++)
215 block->num_cpl_channels += block->channel_in_cpl[ch];
216 block->cpl_in_use = block->num_cpl_channels > 1;
217 num_cpl_blocks += block->cpl_in_use;
218 if (!block->cpl_in_use) {
219 block->num_cpl_channels = 0;
220 for (ch = 1; ch <= s->fbw_channels; ch++)
221 block->channel_in_cpl[ch] = 0;
224 block->new_cpl_strategy = !blk;
226 for (ch = 1; ch <= s->fbw_channels; ch++) {
227 if (block->channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]) {
228 block->new_cpl_strategy = 1;
233 block->new_cpl_leak = block->new_cpl_strategy;
235 if (!blk || (block->cpl_in_use && !got_cpl_snr)) {
236 block->new_snr_offsets = 1;
237 if (block->cpl_in_use)
240 block->new_snr_offsets = 0;
246 /* set bandwidth for each channel */
247 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
248 AC3Block *block = &s->blocks[blk];
249 for (ch = 1; ch <= s->fbw_channels; ch++) {
250 if (block->channel_in_cpl[ch])
251 block->end_freq[ch] = s->start_freq[CPL_CH];
253 block->end_freq[ch] = s->bandwidth_code * 3 + 73;
260 * Apply stereo rematrixing to coefficients based on rematrixing flags.
262 void ff_ac3_apply_rematrixing(AC3EncodeContext *s)
269 if (!s->rematrixing_enabled)
272 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
273 AC3Block *block = &s->blocks[blk];
274 if (block->new_rematrixing_strategy)
275 flags = block->rematrixing_flags;
276 nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
277 for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {
279 start = ff_ac3_rematrix_band_tab[bnd];
280 end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
281 for (i = start; i < end; i++) {
282 int32_t lt = block->fixed_coef[1][i];
283 int32_t rt = block->fixed_coef[2][i];
284 block->fixed_coef[1][i] = (lt + rt) >> 1;
285 block->fixed_coef[2][i] = (lt - rt) >> 1;
294 * Initialize exponent tables.
296 static av_cold void exponent_init(AC3EncodeContext *s)
298 int expstr, i, grpsize;
300 for (expstr = EXP_D15-1; expstr <= EXP_D45-1; expstr++) {
301 grpsize = 3 << expstr;
302 for (i = 12; i < 256; i++) {
303 exponent_group_tab[0][expstr][i] = (i + grpsize - 4) / grpsize;
304 exponent_group_tab[1][expstr][i] = (i ) / grpsize;
308 exponent_group_tab[0][0][7] = 2;
310 if (CONFIG_EAC3_ENCODER && s->eac3)
311 ff_eac3_exponent_init();
316 * Extract exponents from the MDCT coefficients.
318 static void extract_exponents(AC3EncodeContext *s)
321 int chan_size = AC3_MAX_COEFS * AC3_MAX_BLOCKS * (s->channels - ch + 1);
322 AC3Block *block = &s->blocks[0];
324 s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch], chan_size);
329 * Exponent Difference Threshold.
330 * New exponents are sent if their SAD exceed this number.
332 #define EXP_DIFF_THRESHOLD 500
336 * Calculate exponent strategies for all channels.
337 * Array arrangement is reversed to simplify the per-channel calculation.
339 static void compute_exp_strategy(AC3EncodeContext *s)
343 for (ch = !s->cpl_on; ch <= s->fbw_channels; ch++) {
344 uint8_t *exp_strategy = s->exp_strategy[ch];
345 uint8_t *exp = s->blocks[0].exp[ch];
348 /* estimate if the exponent variation & decide if they should be
349 reused in the next frame */
350 exp_strategy[0] = EXP_NEW;
351 exp += AC3_MAX_COEFS;
352 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++, exp += AC3_MAX_COEFS) {
354 if (!s->blocks[blk-1].cpl_in_use) {
355 exp_strategy[blk] = EXP_NEW;
357 } else if (!s->blocks[blk].cpl_in_use) {
358 exp_strategy[blk] = EXP_REUSE;
361 } else if (s->blocks[blk].channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]) {
362 exp_strategy[blk] = EXP_NEW;
365 exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
366 exp_strategy[blk] = EXP_REUSE;
367 if (ch == CPL_CH && exp_diff > (EXP_DIFF_THRESHOLD * (s->blocks[blk].end_freq[ch] - s->start_freq[ch]) / AC3_MAX_COEFS))
368 exp_strategy[blk] = EXP_NEW;
369 else if (ch > CPL_CH && exp_diff > EXP_DIFF_THRESHOLD)
370 exp_strategy[blk] = EXP_NEW;
373 /* now select the encoding strategy type : if exponents are often
374 recoded, we use a coarse encoding */
376 while (blk < AC3_MAX_BLOCKS) {
378 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
380 switch (blk1 - blk) {
381 case 1: exp_strategy[blk] = EXP_D45; break;
383 case 3: exp_strategy[blk] = EXP_D25; break;
384 default: exp_strategy[blk] = EXP_D15; break;
391 s->exp_strategy[ch][0] = EXP_D15;
392 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
393 s->exp_strategy[ch][blk] = EXP_REUSE;
396 /* for E-AC-3, determine frame exponent strategy */
397 if (CONFIG_EAC3_ENCODER && s->eac3)
398 ff_eac3_get_frame_exp_strategy(s);
403 * Update the exponents so that they are the ones the decoder will decode.
405 static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy,
410 nb_groups = exponent_group_tab[cpl][exp_strategy-1][nb_exps] * 3;
412 /* for each group, compute the minimum exponent */
413 switch(exp_strategy) {
415 for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
416 uint8_t exp_min = exp[k];
417 if (exp[k+1] < exp_min)
419 exp[i-cpl] = exp_min;
424 for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
425 uint8_t exp_min = exp[k];
426 if (exp[k+1] < exp_min)
428 if (exp[k+2] < exp_min)
430 if (exp[k+3] < exp_min)
432 exp[i-cpl] = exp_min;
438 /* constraint for DC exponent */
439 if (!cpl && exp[0] > 15)
442 /* decrease the delta between each groups to within 2 so that they can be
443 differentially encoded */
444 for (i = 1; i <= nb_groups; i++)
445 exp[i] = FFMIN(exp[i], exp[i-1] + 2);
448 exp[i] = FFMIN(exp[i], exp[i+1] + 2);
451 exp[-1] = exp[0] & ~1;
453 /* now we have the exponent values the decoder will see */
454 switch (exp_strategy) {
456 for (i = nb_groups, k = (nb_groups * 2)-cpl; i > 0; i--) {
457 uint8_t exp1 = exp[i-cpl];
463 for (i = nb_groups, k = (nb_groups * 4)-cpl; i > 0; i--) {
464 exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i-cpl];
473 * Encode exponents from original extracted form to what the decoder will see.
474 * This copies and groups exponents based on exponent strategy and reduces
475 * deltas between adjacent exponent groups so that they can be differentially
478 static void encode_exponents(AC3EncodeContext *s)
480 int blk, blk1, ch, cpl;
481 uint8_t *exp, *exp_strategy;
482 int nb_coefs, num_reuse_blocks;
484 for (ch = !s->cpl_on; ch <= s->channels; ch++) {
485 exp = s->blocks[0].exp[ch] + s->start_freq[ch];
486 exp_strategy = s->exp_strategy[ch];
488 cpl = (ch == CPL_CH);
490 while (blk < AC3_MAX_BLOCKS) {
491 AC3Block *block = &s->blocks[blk];
492 if (cpl && !block->cpl_in_use) {
493 exp += AC3_MAX_COEFS;
497 nb_coefs = block->end_freq[ch] - s->start_freq[ch];
500 /* count the number of EXP_REUSE blocks after the current block
501 and set exponent reference block numbers */
502 s->exp_ref_block[ch][blk] = blk;
503 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
504 s->exp_ref_block[ch][blk1] = blk;
507 num_reuse_blocks = blk1 - blk - 1;
509 /* for the EXP_REUSE case we select the min of the exponents */
510 s->ac3dsp.ac3_exponent_min(exp-s->start_freq[ch], num_reuse_blocks,
513 encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk], cpl);
515 exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
520 /* reference block numbers have been changed, so reset ref_bap_set */
527 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
528 * varies depending on exponent strategy and bandwidth.
530 static void group_exponents(AC3EncodeContext *s)
533 int group_size, nb_groups, bit_count;
535 int delta0, delta1, delta2;
539 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
540 AC3Block *block = &s->blocks[blk];
541 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
542 int exp_strategy = s->exp_strategy[ch][blk];
543 if (exp_strategy == EXP_REUSE)
545 cpl = (ch == CPL_CH);
546 group_size = exp_strategy + (exp_strategy == EXP_D45);
547 nb_groups = exponent_group_tab[cpl][exp_strategy-1][block->end_freq[ch]-s->start_freq[ch]];
548 bit_count += 4 + (nb_groups * 7);
549 p = block->exp[ch] + s->start_freq[ch] - cpl;
553 block->grouped_exp[ch][0] = exp1;
555 /* remaining exponents are delta encoded */
556 for (i = 1; i <= nb_groups; i++) {
557 /* merge three delta in one code */
561 delta0 = exp1 - exp0 + 2;
562 av_assert2(delta0 >= 0 && delta0 <= 4);
567 delta1 = exp1 - exp0 + 2;
568 av_assert2(delta1 >= 0 && delta1 <= 4);
573 delta2 = exp1 - exp0 + 2;
574 av_assert2(delta2 >= 0 && delta2 <= 4);
576 block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
581 s->exponent_bits = bit_count;
586 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
587 * Extract exponents from MDCT coefficients, calculate exponent strategies,
588 * and encode final exponents.
590 void ff_ac3_process_exponents(AC3EncodeContext *s)
592 extract_exponents(s);
594 compute_exp_strategy(s);
605 * Count frame bits that are based solely on fixed parameters.
606 * This only has to be run once when the encoder is initialized.
608 static void count_frame_bits_fixed(AC3EncodeContext *s)
610 static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
615 * no dynamic range codes
616 * bit allocation parameters do not change between blocks
617 * no delta bit allocation
624 frame_bits = 16; /* sync info */
626 /* bitstream info header */
628 frame_bits += 1 + 1 + 1;
629 /* audio frame header */
632 /* exponent strategy */
633 if (s->use_frame_exp_strategy)
634 frame_bits += 5 * s->fbw_channels;
636 frame_bits += AC3_MAX_BLOCKS * 2 * s->fbw_channels;
638 frame_bits += AC3_MAX_BLOCKS;
639 /* converter exponent strategy */
640 frame_bits += s->fbw_channels * 5;
643 /* block start info */
647 frame_bits += frame_bits_inc[s->channel_mode];
651 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
653 /* block switch flags */
654 frame_bits += s->fbw_channels;
657 frame_bits += s->fbw_channels;
663 /* spectral extension */
668 /* exponent strategy */
669 frame_bits += 2 * s->fbw_channels;
673 /* bit allocation params */
676 frame_bits += 2 + 2 + 2 + 2 + 3;
679 /* converter snr offset */
684 /* delta bit allocation */
696 frame_bits += 1 + 16;
698 s->frame_bits_fixed = frame_bits;
703 * Initialize bit allocation.
704 * Set default parameter codes and calculate parameter values.
706 static void bit_alloc_init(AC3EncodeContext *s)
710 /* init default parameters */
711 s->slow_decay_code = 2;
712 s->fast_decay_code = 1;
713 s->slow_gain_code = 1;
714 s->db_per_bit_code = s->eac3 ? 2 : 3;
716 for (ch = 0; ch <= s->channels; ch++)
717 s->fast_gain_code[ch] = 4;
719 /* initial snr offset */
720 s->coarse_snr_offset = 40;
722 /* compute real values */
723 /* currently none of these values change during encoding, so we can just
724 set them once at initialization */
725 s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
726 s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
727 s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
728 s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
729 s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
730 s->bit_alloc.cpl_fast_leak = 0;
731 s->bit_alloc.cpl_slow_leak = 0;
733 count_frame_bits_fixed(s);
738 * Count the bits used to encode the frame, minus exponents and mantissas.
739 * Bits based on fixed parameters have already been counted, so now we just
740 * have to add the bits based on parameters that change during encoding.
742 static void count_frame_bits(AC3EncodeContext *s)
744 AC3EncOptions *opt = &s->options;
751 if (s->channel_mode > AC3_CHMODE_MONO) {
753 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
754 AC3Block *block = &s->blocks[blk];
756 if (block->new_cpl_strategy)
760 /* coupling exponent strategy */
762 if (s->use_frame_exp_strategy) {
763 frame_bits += 5 * s->cpl_on;
765 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
766 frame_bits += 2 * s->blocks[blk].cpl_in_use;
770 if (opt->audio_production_info)
772 if (s->bitstream_id == 6) {
773 if (opt->extended_bsi_1)
775 if (opt->extended_bsi_2)
781 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
782 AC3Block *block = &s->blocks[blk];
784 /* coupling strategy */
787 if (block->new_cpl_strategy) {
790 if (block->cpl_in_use) {
793 if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO)
794 frame_bits += s->fbw_channels;
795 if (s->channel_mode == AC3_CHMODE_STEREO)
801 frame_bits += s->num_cpl_subbands - 1;
805 /* coupling coordinates */
806 if (block->cpl_in_use) {
807 for (ch = 1; ch <= s->fbw_channels; ch++) {
808 if (block->channel_in_cpl[ch]) {
809 if (!s->eac3 || block->new_cpl_coords != 2)
811 if (block->new_cpl_coords) {
813 frame_bits += (4 + 4) * s->num_cpl_bands;
819 /* stereo rematrixing */
820 if (s->channel_mode == AC3_CHMODE_STEREO) {
821 if (!s->eac3 || blk > 0)
823 if (s->blocks[blk].new_rematrixing_strategy)
824 frame_bits += block->num_rematrixing_bands;
827 /* bandwidth codes & gain range */
828 for (ch = 1; ch <= s->fbw_channels; ch++) {
829 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
830 if (!block->channel_in_cpl[ch])
836 /* coupling exponent strategy */
837 if (!s->eac3 && block->cpl_in_use)
840 /* snr offsets and fast gain codes */
843 if (block->new_snr_offsets)
844 frame_bits += 6 + (s->channels + block->cpl_in_use) * (4 + 3);
847 /* coupling leak info */
848 if (block->cpl_in_use) {
849 if (!s->eac3 || block->new_cpl_leak != 2)
851 if (block->new_cpl_leak)
856 s->frame_bits = s->frame_bits_fixed + frame_bits;
861 * Calculate masking curve based on the final exponents.
862 * Also calculate the power spectral densities to use in future calculations.
864 static void bit_alloc_masking(AC3EncodeContext *s)
868 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
869 AC3Block *block = &s->blocks[blk];
870 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
871 /* We only need psd and mask for calculating bap.
872 Since we currently do not calculate bap when exponent
873 strategy is EXP_REUSE we do not need to calculate psd or mask. */
874 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
875 ff_ac3_bit_alloc_calc_psd(block->exp[ch], s->start_freq[ch],
876 block->end_freq[ch], block->psd[ch],
877 block->band_psd[ch]);
878 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
879 s->start_freq[ch], block->end_freq[ch],
880 ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
881 ch == s->lfe_channel,
882 DBA_NONE, 0, NULL, NULL, NULL,
891 * Ensure that bap for each block and channel point to the current bap_buffer.
892 * They may have been switched during the bit allocation search.
894 static void reset_block_bap(AC3EncodeContext *s)
899 if (s->ref_bap[0][0] == s->bap_buffer && s->ref_bap_set)
902 ref_bap = s->bap_buffer;
903 for (ch = 0; ch <= s->channels; ch++) {
904 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
905 s->ref_bap[ch][blk] = ref_bap + AC3_MAX_COEFS * s->exp_ref_block[ch][blk];
906 ref_bap += AC3_MAX_COEFS * AC3_MAX_BLOCKS;
913 * Initialize mantissa counts.
914 * These are set so that they are padded to the next whole group size when bits
915 * are counted in compute_mantissa_size.
917 static void count_mantissa_bits_init(uint16_t mant_cnt[AC3_MAX_BLOCKS][16])
921 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
922 memset(mant_cnt[blk], 0, sizeof(mant_cnt[blk]));
923 mant_cnt[blk][1] = mant_cnt[blk][2] = 2;
924 mant_cnt[blk][4] = 1;
930 * Update mantissa bit counts for all blocks in 1 channel in a given bandwidth
933 static void count_mantissa_bits_update_ch(AC3EncodeContext *s, int ch,
934 uint16_t mant_cnt[AC3_MAX_BLOCKS][16],
939 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
940 AC3Block *block = &s->blocks[blk];
941 if (ch == CPL_CH && !block->cpl_in_use)
943 s->ac3dsp.update_bap_counts(mant_cnt[blk],
944 s->ref_bap[ch][blk] + start,
945 FFMIN(end, block->end_freq[ch]) - start);
951 * Count the number of mantissa bits in the frame based on the bap values.
953 static int count_mantissa_bits(AC3EncodeContext *s)
955 int ch, max_end_freq;
956 LOCAL_ALIGNED_16(uint16_t, mant_cnt, [AC3_MAX_BLOCKS], [16]);
958 count_mantissa_bits_init(mant_cnt);
960 max_end_freq = s->bandwidth_code * 3 + 73;
961 for (ch = !s->cpl_enabled; ch <= s->channels; ch++)
962 count_mantissa_bits_update_ch(s, ch, mant_cnt, s->start_freq[ch],
965 return s->ac3dsp.compute_mantissa_size(mant_cnt);
970 * Run the bit allocation with a given SNR offset.
971 * This calculates the bit allocation pointers that will be used to determine
972 * the quantization of each mantissa.
973 * @return the number of bits needed for mantissas if the given SNR offset is
976 static int bit_alloc(AC3EncodeContext *s, int snr_offset)
980 snr_offset = (snr_offset - 240) << 2;
983 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
984 AC3Block *block = &s->blocks[blk];
986 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
987 /* Currently the only bit allocation parameters which vary across
988 blocks within a frame are the exponent values. We can take
989 advantage of that by reusing the bit allocation pointers
990 whenever we reuse exponents. */
991 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
992 s->ac3dsp.bit_alloc_calc_bap(block->mask[ch], block->psd[ch],
993 s->start_freq[ch], block->end_freq[ch],
994 snr_offset, s->bit_alloc.floor,
995 ff_ac3_bap_tab, s->ref_bap[ch][blk]);
999 return count_mantissa_bits(s);
1004 * Constant bitrate bit allocation search.
1005 * Find the largest SNR offset that will allow data to fit in the frame.
1007 static int cbr_bit_allocation(AC3EncodeContext *s)
1011 int snr_offset, snr_incr;
1013 bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1015 return AVERROR(EINVAL);
1017 snr_offset = s->coarse_snr_offset << 4;
1019 /* if previous frame SNR offset was 1023, check if current frame can also
1020 use SNR offset of 1023. if so, skip the search. */
1021 if ((snr_offset | s->fine_snr_offset[1]) == 1023) {
1022 if (bit_alloc(s, 1023) <= bits_left)
1026 while (snr_offset >= 0 &&
1027 bit_alloc(s, snr_offset) > bits_left) {
1031 return AVERROR(EINVAL);
1033 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1034 for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1035 while (snr_offset + snr_incr <= 1023 &&
1036 bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1037 snr_offset += snr_incr;
1038 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1041 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1044 s->coarse_snr_offset = snr_offset >> 4;
1045 for (ch = !s->cpl_on; ch <= s->channels; ch++)
1046 s->fine_snr_offset[ch] = snr_offset & 0xF;
1053 * Perform bit allocation search.
1054 * Finds the SNR offset value that maximizes quality and fits in the specified
1055 * frame size. Output is the SNR offset and a set of bit allocation pointers
1056 * used to quantize the mantissas.
1058 int ff_ac3_compute_bit_allocation(AC3EncodeContext *s)
1060 count_frame_bits(s);
1062 bit_alloc_masking(s);
1064 return cbr_bit_allocation(s);
1069 * Symmetric quantization on 'levels' levels.
1071 static inline int sym_quant(int c, int e, int levels)
1073 int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1074 av_assert2(v >= 0 && v < levels);
1080 * Asymmetric quantization on 2^qbits levels.
1082 static inline int asym_quant(int c, int e, int qbits)
1086 c = (((c << e) >> (24 - qbits)) + 1) >> 1;
1087 m = (1 << (qbits-1));
1090 av_assert2(c >= -m);
1096 * Quantize a set of mantissas for a single channel in a single block.
1098 static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1099 uint8_t *exp, uint8_t *bap,
1100 int16_t *qmant, int start_freq,
1105 for (i = start_freq; i < end_freq; i++) {
1107 int c = fixed_coef[i];
1115 v = sym_quant(c, e, 3);
1116 switch (s->mant1_cnt) {
1118 s->qmant1_ptr = &qmant[i];
1123 *s->qmant1_ptr += 3 * v;
1128 *s->qmant1_ptr += v;
1135 v = sym_quant(c, e, 5);
1136 switch (s->mant2_cnt) {
1138 s->qmant2_ptr = &qmant[i];
1143 *s->qmant2_ptr += 5 * v;
1148 *s->qmant2_ptr += v;
1155 v = sym_quant(c, e, 7);
1158 v = sym_quant(c, e, 11);
1159 switch (s->mant4_cnt) {
1161 s->qmant4_ptr = &qmant[i];
1166 *s->qmant4_ptr += v;
1173 v = sym_quant(c, e, 15);
1176 v = asym_quant(c, e, 14);
1179 v = asym_quant(c, e, 16);
1182 v = asym_quant(c, e, b - 1);
1191 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1193 void ff_ac3_quantize_mantissas(AC3EncodeContext *s)
1195 int blk, ch, ch0=0, got_cpl;
1197 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1198 AC3Block *block = &s->blocks[blk];
1201 got_cpl = !block->cpl_in_use;
1202 for (ch = 1; ch <= s->channels; ch++) {
1203 if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1208 quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1209 s->blocks[s->exp_ref_block[ch][blk]].exp[ch],
1210 s->ref_bap[ch][blk], block->qmant[ch],
1211 s->start_freq[ch], block->end_freq[ch]);
1220 * Write the AC-3 frame header to the output bitstream.
1222 static void ac3_output_frame_header(AC3EncodeContext *s)
1224 AC3EncOptions *opt = &s->options;
1226 put_bits(&s->pb, 16, 0x0b77); /* frame header */
1227 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
1228 put_bits(&s->pb, 2, s->bit_alloc.sr_code);
1229 put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1230 put_bits(&s->pb, 5, s->bitstream_id);
1231 put_bits(&s->pb, 3, s->bitstream_mode);
1232 put_bits(&s->pb, 3, s->channel_mode);
1233 if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1234 put_bits(&s->pb, 2, s->center_mix_level);
1235 if (s->channel_mode & 0x04)
1236 put_bits(&s->pb, 2, s->surround_mix_level);
1237 if (s->channel_mode == AC3_CHMODE_STEREO)
1238 put_bits(&s->pb, 2, opt->dolby_surround_mode);
1239 put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1240 put_bits(&s->pb, 5, -opt->dialogue_level);
1241 put_bits(&s->pb, 1, 0); /* no compression control word */
1242 put_bits(&s->pb, 1, 0); /* no lang code */
1243 put_bits(&s->pb, 1, opt->audio_production_info);
1244 if (opt->audio_production_info) {
1245 put_bits(&s->pb, 5, opt->mixing_level - 80);
1246 put_bits(&s->pb, 2, opt->room_type);
1248 put_bits(&s->pb, 1, opt->copyright);
1249 put_bits(&s->pb, 1, opt->original);
1250 if (s->bitstream_id == 6) {
1251 /* alternate bit stream syntax */
1252 put_bits(&s->pb, 1, opt->extended_bsi_1);
1253 if (opt->extended_bsi_1) {
1254 put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1255 put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1256 put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1257 put_bits(&s->pb, 3, s->loro_center_mix_level);
1258 put_bits(&s->pb, 3, s->loro_surround_mix_level);
1260 put_bits(&s->pb, 1, opt->extended_bsi_2);
1261 if (opt->extended_bsi_2) {
1262 put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1263 put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1264 put_bits(&s->pb, 1, opt->ad_converter_type);
1265 put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
1268 put_bits(&s->pb, 1, 0); /* no time code 1 */
1269 put_bits(&s->pb, 1, 0); /* no time code 2 */
1271 put_bits(&s->pb, 1, 0); /* no additional bit stream info */
1276 * Write one audio block to the output bitstream.
1278 static void output_audio_block(AC3EncodeContext *s, int blk)
1280 int ch, i, baie, bnd, got_cpl;
1282 AC3Block *block = &s->blocks[blk];
1284 /* block switching */
1286 for (ch = 0; ch < s->fbw_channels; ch++)
1287 put_bits(&s->pb, 1, 0);
1292 for (ch = 0; ch < s->fbw_channels; ch++)
1293 put_bits(&s->pb, 1, 1);
1296 /* dynamic range codes */
1297 put_bits(&s->pb, 1, 0);
1299 /* spectral extension */
1301 put_bits(&s->pb, 1, 0);
1303 /* channel coupling */
1305 put_bits(&s->pb, 1, block->new_cpl_strategy);
1306 if (block->new_cpl_strategy) {
1308 put_bits(&s->pb, 1, block->cpl_in_use);
1309 if (block->cpl_in_use) {
1310 int start_sub, end_sub;
1312 put_bits(&s->pb, 1, 0); /* enhanced coupling */
1313 if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO) {
1314 for (ch = 1; ch <= s->fbw_channels; ch++)
1315 put_bits(&s->pb, 1, block->channel_in_cpl[ch]);
1317 if (s->channel_mode == AC3_CHMODE_STEREO)
1318 put_bits(&s->pb, 1, 0); /* phase flags in use */
1319 start_sub = (s->start_freq[CPL_CH] - 37) / 12;
1320 end_sub = (s->cpl_end_freq - 37) / 12;
1321 put_bits(&s->pb, 4, start_sub);
1322 put_bits(&s->pb, 4, end_sub - 3);
1323 /* coupling band structure */
1325 put_bits(&s->pb, 1, 0); /* use default */
1327 for (bnd = start_sub+1; bnd < end_sub; bnd++)
1328 put_bits(&s->pb, 1, ff_eac3_default_cpl_band_struct[bnd]);
1333 /* coupling coordinates */
1334 if (block->cpl_in_use) {
1335 for (ch = 1; ch <= s->fbw_channels; ch++) {
1336 if (block->channel_in_cpl[ch]) {
1337 if (!s->eac3 || block->new_cpl_coords != 2)
1338 put_bits(&s->pb, 1, block->new_cpl_coords);
1339 if (block->new_cpl_coords) {
1340 put_bits(&s->pb, 2, block->cpl_master_exp[ch]);
1341 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
1342 put_bits(&s->pb, 4, block->cpl_coord_exp [ch][bnd]);
1343 put_bits(&s->pb, 4, block->cpl_coord_mant[ch][bnd]);
1350 /* stereo rematrixing */
1351 if (s->channel_mode == AC3_CHMODE_STEREO) {
1352 if (!s->eac3 || blk > 0)
1353 put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1354 if (block->new_rematrixing_strategy) {
1355 /* rematrixing flags */
1356 for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++)
1357 put_bits(&s->pb, 1, block->rematrixing_flags[bnd]);
1361 /* exponent strategy */
1363 for (ch = !block->cpl_in_use; ch <= s->fbw_channels; ch++)
1364 put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1366 put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1370 for (ch = 1; ch <= s->fbw_channels; ch++) {
1371 if (s->exp_strategy[ch][blk] != EXP_REUSE && !block->channel_in_cpl[ch])
1372 put_bits(&s->pb, 6, s->bandwidth_code);
1376 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1378 int cpl = (ch == CPL_CH);
1380 if (s->exp_strategy[ch][blk] == EXP_REUSE)
1384 put_bits(&s->pb, 4, block->grouped_exp[ch][0] >> cpl);
1386 /* exponent groups */
1387 nb_groups = exponent_group_tab[cpl][s->exp_strategy[ch][blk]-1][block->end_freq[ch]-s->start_freq[ch]];
1388 for (i = 1; i <= nb_groups; i++)
1389 put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1391 /* gain range info */
1392 if (ch != s->lfe_channel && !cpl)
1393 put_bits(&s->pb, 2, 0);
1396 /* bit allocation info */
1399 put_bits(&s->pb, 1, baie);
1401 put_bits(&s->pb, 2, s->slow_decay_code);
1402 put_bits(&s->pb, 2, s->fast_decay_code);
1403 put_bits(&s->pb, 2, s->slow_gain_code);
1404 put_bits(&s->pb, 2, s->db_per_bit_code);
1405 put_bits(&s->pb, 3, s->floor_code);
1411 put_bits(&s->pb, 1, block->new_snr_offsets);
1412 if (block->new_snr_offsets) {
1413 put_bits(&s->pb, 6, s->coarse_snr_offset);
1414 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1415 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1416 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1420 put_bits(&s->pb, 1, 0); /* no converter snr offset */
1424 if (block->cpl_in_use) {
1425 if (!s->eac3 || block->new_cpl_leak != 2)
1426 put_bits(&s->pb, 1, block->new_cpl_leak);
1427 if (block->new_cpl_leak) {
1428 put_bits(&s->pb, 3, s->bit_alloc.cpl_fast_leak);
1429 put_bits(&s->pb, 3, s->bit_alloc.cpl_slow_leak);
1434 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1435 put_bits(&s->pb, 1, 0); /* no data to skip */
1439 got_cpl = !block->cpl_in_use;
1440 for (ch = 1; ch <= s->channels; ch++) {
1443 if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1448 for (i = s->start_freq[ch]; i < block->end_freq[ch]; i++) {
1449 q = block->qmant[ch][i];
1450 b = s->ref_bap[ch][blk][i];
1453 case 1: if (q != 128) put_bits (&s->pb, 5, q); break;
1454 case 2: if (q != 128) put_bits (&s->pb, 7, q); break;
1455 case 3: put_sbits(&s->pb, 3, q); break;
1456 case 4: if (q != 128) put_bits (&s->pb, 7, q); break;
1457 case 14: put_sbits(&s->pb, 14, q); break;
1458 case 15: put_sbits(&s->pb, 16, q); break;
1459 default: put_sbits(&s->pb, b-1, q); break;
1468 /** CRC-16 Polynomial */
1469 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1472 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1489 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1495 r = mul_poly(r, a, poly);
1496 a = mul_poly(a, a, poly);
1504 * Fill the end of the frame with 0's and compute the two CRCs.
1506 static void output_frame_end(AC3EncodeContext *s)
1508 const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1509 int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1512 frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1514 /* pad the remainder of the frame with zeros */
1515 av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1516 flush_put_bits(&s->pb);
1518 pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1519 av_assert2(pad_bytes >= 0);
1521 memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1525 crc2_partial = av_crc(crc_ctx, 0, frame + 2, s->frame_size - 5);
1528 /* this is not so easy because it is at the beginning of the data... */
1529 crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1530 crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1531 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1532 AV_WB16(frame + 2, crc1);
1535 crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1536 s->frame_size - frame_size_58 - 3);
1538 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1539 /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1540 if (crc2 == 0x770B) {
1541 frame[s->frame_size - 3] ^= 0x1;
1542 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1544 crc2 = av_bswap16(crc2);
1545 AV_WB16(frame + s->frame_size - 2, crc2);
1550 * Write the frame to the output bitstream.
1552 void ff_ac3_output_frame(AC3EncodeContext *s, unsigned char *frame)
1556 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1558 s->output_frame_header(s);
1560 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1561 output_audio_block(s, blk);
1563 output_frame_end(s);
1567 static void dprint_options(AC3EncodeContext *s)
1570 AVCodecContext *avctx = s->avctx;
1571 AC3EncOptions *opt = &s->options;
1574 switch (s->bitstream_id) {
1575 case 6: av_strlcpy(strbuf, "AC-3 (alt syntax)", 32); break;
1576 case 8: av_strlcpy(strbuf, "AC-3 (standard)", 32); break;
1577 case 9: av_strlcpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
1578 case 10: av_strlcpy(strbuf, "AC-3 (dnet quater-rate)", 32); break;
1579 case 16: av_strlcpy(strbuf, "E-AC-3 (enhanced)", 32); break;
1580 default: snprintf(strbuf, 32, "ERROR");
1582 av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
1583 av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
1584 av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
1585 av_dlog(avctx, "channel_layout: %s\n", strbuf);
1586 av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
1587 av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
1589 av_dlog(avctx, "cutoff: %d\n", s->cutoff);
1591 av_dlog(avctx, "per_frame_metadata: %s\n",
1592 opt->allow_per_frame_metadata?"on":"off");
1594 av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
1595 s->center_mix_level);
1597 av_dlog(avctx, "center_mixlev: {not written}\n");
1598 if (s->has_surround)
1599 av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
1600 s->surround_mix_level);
1602 av_dlog(avctx, "surround_mixlev: {not written}\n");
1603 if (opt->audio_production_info) {
1604 av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
1605 switch (opt->room_type) {
1606 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1607 case 1: av_strlcpy(strbuf, "large", 32); break;
1608 case 2: av_strlcpy(strbuf, "small", 32); break;
1609 default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
1611 av_dlog(avctx, "room_type: %s\n", strbuf);
1613 av_dlog(avctx, "mixing_level: {not written}\n");
1614 av_dlog(avctx, "room_type: {not written}\n");
1616 av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
1617 av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
1618 if (s->channel_mode == AC3_CHMODE_STEREO) {
1619 switch (opt->dolby_surround_mode) {
1620 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1621 case 1: av_strlcpy(strbuf, "on", 32); break;
1622 case 2: av_strlcpy(strbuf, "off", 32); break;
1623 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
1625 av_dlog(avctx, "dsur_mode: %s\n", strbuf);
1627 av_dlog(avctx, "dsur_mode: {not written}\n");
1629 av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
1631 if (s->bitstream_id == 6) {
1632 if (opt->extended_bsi_1) {
1633 switch (opt->preferred_stereo_downmix) {
1634 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1635 case 1: av_strlcpy(strbuf, "ltrt", 32); break;
1636 case 2: av_strlcpy(strbuf, "loro", 32); break;
1637 default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
1639 av_dlog(avctx, "dmix_mode: %s\n", strbuf);
1640 av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
1641 opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
1642 av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
1643 opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
1644 av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
1645 opt->loro_center_mix_level, s->loro_center_mix_level);
1646 av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
1647 opt->loro_surround_mix_level, s->loro_surround_mix_level);
1649 av_dlog(avctx, "extended bitstream info 1: {not written}\n");
1651 if (opt->extended_bsi_2) {
1652 switch (opt->dolby_surround_ex_mode) {
1653 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1654 case 1: av_strlcpy(strbuf, "on", 32); break;
1655 case 2: av_strlcpy(strbuf, "off", 32); break;
1656 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
1658 av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
1659 switch (opt->dolby_headphone_mode) {
1660 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1661 case 1: av_strlcpy(strbuf, "on", 32); break;
1662 case 2: av_strlcpy(strbuf, "off", 32); break;
1663 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
1665 av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
1667 switch (opt->ad_converter_type) {
1668 case 0: av_strlcpy(strbuf, "standard", 32); break;
1669 case 1: av_strlcpy(strbuf, "hdcd", 32); break;
1670 default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
1672 av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
1674 av_dlog(avctx, "extended bitstream info 2: {not written}\n");
1681 #define FLT_OPTION_THRESHOLD 0.01
1683 static int validate_float_option(float v, const float *v_list, int v_list_size)
1687 for (i = 0; i < v_list_size; i++) {
1688 if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
1689 v > (v_list[i] - FLT_OPTION_THRESHOLD))
1692 if (i == v_list_size)
1699 static void validate_mix_level(void *log_ctx, const char *opt_name,
1700 float *opt_param, const float *list,
1701 int list_size, int default_value, int min_value,
1704 int mixlev = validate_float_option(*opt_param, list, list_size);
1705 if (mixlev < min_value) {
1706 mixlev = default_value;
1707 if (*opt_param >= 0.0) {
1708 av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
1709 "default value: %0.3f\n", opt_name, list[mixlev]);
1712 *opt_param = list[mixlev];
1713 *ctx_param = mixlev;
1718 * Validate metadata options as set by AVOption system.
1719 * These values can optionally be changed per-frame.
1721 int ff_ac3_validate_metadata(AC3EncodeContext *s)
1723 AVCodecContext *avctx = s->avctx;
1724 AC3EncOptions *opt = &s->options;
1726 /* validate mixing levels */
1727 if (s->has_center) {
1728 validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
1729 cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
1730 &s->center_mix_level);
1732 if (s->has_surround) {
1733 validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
1734 surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
1735 &s->surround_mix_level);
1738 /* set audio production info flag */
1739 if (opt->mixing_level >= 0 || opt->room_type >= 0) {
1740 if (opt->mixing_level < 0) {
1741 av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
1742 "room_type is set\n");
1743 return AVERROR(EINVAL);
1745 if (opt->mixing_level < 80) {
1746 av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
1747 "80dB and 111dB\n");
1748 return AVERROR(EINVAL);
1750 /* default room type */
1751 if (opt->room_type < 0)
1753 opt->audio_production_info = 1;
1755 opt->audio_production_info = 0;
1758 /* set extended bsi 1 flag */
1759 if ((s->has_center || s->has_surround) &&
1760 (opt->preferred_stereo_downmix >= 0 ||
1761 opt->ltrt_center_mix_level >= 0 ||
1762 opt->ltrt_surround_mix_level >= 0 ||
1763 opt->loro_center_mix_level >= 0 ||
1764 opt->loro_surround_mix_level >= 0)) {
1765 /* default preferred stereo downmix */
1766 if (opt->preferred_stereo_downmix < 0)
1767 opt->preferred_stereo_downmix = 0;
1768 /* validate Lt/Rt center mix level */
1769 validate_mix_level(avctx, "ltrt_center_mix_level",
1770 &opt->ltrt_center_mix_level, extmixlev_options,
1771 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1772 &s->ltrt_center_mix_level);
1773 /* validate Lt/Rt surround mix level */
1774 validate_mix_level(avctx, "ltrt_surround_mix_level",
1775 &opt->ltrt_surround_mix_level, extmixlev_options,
1776 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1777 &s->ltrt_surround_mix_level);
1778 /* validate Lo/Ro center mix level */
1779 validate_mix_level(avctx, "loro_center_mix_level",
1780 &opt->loro_center_mix_level, extmixlev_options,
1781 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1782 &s->loro_center_mix_level);
1783 /* validate Lo/Ro surround mix level */
1784 validate_mix_level(avctx, "loro_surround_mix_level",
1785 &opt->loro_surround_mix_level, extmixlev_options,
1786 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1787 &s->loro_surround_mix_level);
1788 opt->extended_bsi_1 = 1;
1790 opt->extended_bsi_1 = 0;
1793 /* set extended bsi 2 flag */
1794 if (opt->dolby_surround_ex_mode >= 0 ||
1795 opt->dolby_headphone_mode >= 0 ||
1796 opt->ad_converter_type >= 0) {
1797 /* default dolby surround ex mode */
1798 if (opt->dolby_surround_ex_mode < 0)
1799 opt->dolby_surround_ex_mode = 0;
1800 /* default dolby headphone mode */
1801 if (opt->dolby_headphone_mode < 0)
1802 opt->dolby_headphone_mode = 0;
1803 /* default A/D converter type */
1804 if (opt->ad_converter_type < 0)
1805 opt->ad_converter_type = 0;
1806 opt->extended_bsi_2 = 1;
1808 opt->extended_bsi_2 = 0;
1811 /* set bitstream id for alternate bitstream syntax */
1812 if (opt->extended_bsi_1 || opt->extended_bsi_2) {
1813 if (s->bitstream_id > 8 && s->bitstream_id < 11) {
1814 static int warn_once = 1;
1816 av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
1817 "not compatible with reduced samplerates. writing of "
1818 "extended bitstream information will be disabled.\n");
1822 s->bitstream_id = 6;
1831 * Finalize encoding and free any memory allocated by the encoder.
1833 av_cold int ff_ac3_encode_close(AVCodecContext *avctx)
1836 AC3EncodeContext *s = avctx->priv_data;
1838 av_freep(&s->windowed_samples);
1839 for (ch = 0; ch < s->channels; ch++)
1840 av_freep(&s->planar_samples[ch]);
1841 av_freep(&s->planar_samples);
1842 av_freep(&s->bap_buffer);
1843 av_freep(&s->bap1_buffer);
1844 av_freep(&s->mdct_coef_buffer);
1845 av_freep(&s->fixed_coef_buffer);
1846 av_freep(&s->exp_buffer);
1847 av_freep(&s->grouped_exp_buffer);
1848 av_freep(&s->psd_buffer);
1849 av_freep(&s->band_psd_buffer);
1850 av_freep(&s->mask_buffer);
1851 av_freep(&s->qmant_buffer);
1852 av_freep(&s->cpl_coord_exp_buffer);
1853 av_freep(&s->cpl_coord_mant_buffer);
1854 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1855 AC3Block *block = &s->blocks[blk];
1856 av_freep(&block->mdct_coef);
1857 av_freep(&block->fixed_coef);
1858 av_freep(&block->exp);
1859 av_freep(&block->grouped_exp);
1860 av_freep(&block->psd);
1861 av_freep(&block->band_psd);
1862 av_freep(&block->mask);
1863 av_freep(&block->qmant);
1864 av_freep(&block->cpl_coord_exp);
1865 av_freep(&block->cpl_coord_mant);
1870 av_freep(&avctx->coded_frame);
1876 * Set channel information during initialization.
1878 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1879 int64_t *channel_layout)
1883 if (channels < 1 || channels > AC3_MAX_CHANNELS)
1884 return AVERROR(EINVAL);
1885 if ((uint64_t)*channel_layout > 0x7FF)
1886 return AVERROR(EINVAL);
1887 ch_layout = *channel_layout;
1889 ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1891 s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1892 s->channels = channels;
1893 s->fbw_channels = channels - s->lfe_on;
1894 s->lfe_channel = s->lfe_on ? s->fbw_channels + 1 : -1;
1896 ch_layout -= AV_CH_LOW_FREQUENCY;
1898 switch (ch_layout) {
1899 case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
1900 case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
1901 case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
1902 case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
1903 case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
1904 case AV_CH_LAYOUT_QUAD:
1905 case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
1906 case AV_CH_LAYOUT_5POINT0:
1907 case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
1909 return AVERROR(EINVAL);
1911 s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
1912 s->has_surround = s->channel_mode & 0x04;
1914 s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1915 *channel_layout = ch_layout;
1917 *channel_layout |= AV_CH_LOW_FREQUENCY;
1923 static av_cold int validate_options(AC3EncodeContext *s)
1925 AVCodecContext *avctx = s->avctx;
1928 /* validate channel layout */
1929 if (!avctx->channel_layout) {
1930 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1931 "encoder will guess the layout, but it "
1932 "might be incorrect.\n");
1934 ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1936 av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1940 /* validate sample rate */
1941 /* note: max_sr could be changed from 2 to 5 for E-AC-3 once we find a
1942 decoder that supports half sample rate so we can validate that
1943 the generated files are correct. */
1944 max_sr = s->eac3 ? 2 : 8;
1945 for (i = 0; i <= max_sr; i++) {
1946 if ((ff_ac3_sample_rate_tab[i % 3] >> (i / 3)) == avctx->sample_rate)
1950 av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1951 return AVERROR(EINVAL);
1953 s->sample_rate = avctx->sample_rate;
1954 s->bit_alloc.sr_shift = i / 3;
1955 s->bit_alloc.sr_code = i % 3;
1956 s->bitstream_id = s->eac3 ? 16 : 8 + s->bit_alloc.sr_shift;
1958 /* validate bit rate */
1960 int max_br, min_br, wpf, min_br_dist, min_br_code;
1962 /* calculate min/max bitrate */
1963 max_br = 2048 * s->sample_rate / AC3_FRAME_SIZE * 16;
1964 min_br = ((s->sample_rate + (AC3_FRAME_SIZE-1)) / AC3_FRAME_SIZE) * 16;
1965 if (avctx->bit_rate < min_br || avctx->bit_rate > max_br) {
1966 av_log(avctx, AV_LOG_ERROR, "invalid bit rate. must be %d to %d "
1967 "for this sample rate\n", min_br, max_br);
1968 return AVERROR(EINVAL);
1971 /* calculate words-per-frame for the selected bitrate */
1972 wpf = (avctx->bit_rate / 16) * AC3_FRAME_SIZE / s->sample_rate;
1973 av_assert1(wpf > 0 && wpf <= 2048);
1975 /* find the closest AC-3 bitrate code to the selected bitrate.
1976 this is needed for lookup tables for bandwidth and coupling
1977 parameter selection */
1979 min_br_dist = INT_MAX;
1980 for (i = 0; i < 19; i++) {
1981 int br_dist = abs(ff_ac3_bitrate_tab[i] * 1000 - avctx->bit_rate);
1982 if (br_dist < min_br_dist) {
1983 min_br_dist = br_dist;
1988 /* make sure the minimum frame size is below the average frame size */
1989 s->frame_size_code = min_br_code << 1;
1990 while (wpf > 1 && wpf * s->sample_rate / AC3_FRAME_SIZE * 16 > avctx->bit_rate)
1992 s->frame_size_min = 2 * wpf;
1994 for (i = 0; i < 19; i++) {
1995 if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
1999 av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2000 return AVERROR(EINVAL);
2002 s->frame_size_code = i << 1;
2003 s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2005 s->bit_rate = avctx->bit_rate;
2006 s->frame_size = s->frame_size_min;
2008 /* validate cutoff */
2009 if (avctx->cutoff < 0) {
2010 av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2011 return AVERROR(EINVAL);
2013 s->cutoff = avctx->cutoff;
2014 if (s->cutoff > (s->sample_rate >> 1))
2015 s->cutoff = s->sample_rate >> 1;
2017 /* validate audio service type / channels combination */
2018 if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
2019 avctx->channels == 1) ||
2020 ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
2021 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
2022 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
2023 && avctx->channels > 1)) {
2024 av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
2025 "specified number of channels\n");
2026 return AVERROR(EINVAL);
2030 ret = ff_ac3_validate_metadata(s);
2035 s->rematrixing_enabled = s->options.stereo_rematrixing &&
2036 (s->channel_mode == AC3_CHMODE_STEREO);
2038 s->cpl_enabled = s->options.channel_coupling &&
2039 s->channel_mode >= AC3_CHMODE_STEREO && !s->fixed_point;
2046 * Set bandwidth for all channels.
2047 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2048 * default value will be used.
2050 static av_cold void set_bandwidth(AC3EncodeContext *s)
2053 int av_uninit(cpl_start);
2056 /* calculate bandwidth based on user-specified cutoff frequency */
2058 fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2059 s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2061 /* use default bandwidth setting */
2062 s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2065 /* set number of coefficients for each channel */
2066 for (ch = 1; ch <= s->fbw_channels; ch++) {
2067 s->start_freq[ch] = 0;
2068 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2069 s->blocks[blk].end_freq[ch] = s->bandwidth_code * 3 + 73;
2071 /* LFE channel always has 7 coefs */
2073 s->start_freq[s->lfe_channel] = 0;
2074 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2075 s->blocks[blk].end_freq[ch] = 7;
2078 /* initialize coupling strategy */
2079 if (s->cpl_enabled) {
2080 if (s->options.cpl_start >= 0) {
2081 cpl_start = s->options.cpl_start;
2083 cpl_start = ac3_coupling_start_tab[s->channel_mode-2][s->bit_alloc.sr_code][s->frame_size_code/2];
2088 if (s->cpl_enabled) {
2089 int i, cpl_start_band, cpl_end_band;
2090 uint8_t *cpl_band_sizes = s->cpl_band_sizes;
2092 cpl_end_band = s->bandwidth_code / 4 + 3;
2093 cpl_start_band = av_clip(cpl_start, 0, FFMIN(cpl_end_band-1, 15));
2095 s->num_cpl_subbands = cpl_end_band - cpl_start_band;
2097 s->num_cpl_bands = 1;
2098 *cpl_band_sizes = 12;
2099 for (i = cpl_start_band + 1; i < cpl_end_band; i++) {
2100 if (ff_eac3_default_cpl_band_struct[i]) {
2101 *cpl_band_sizes += 12;
2105 *cpl_band_sizes = 12;
2109 s->start_freq[CPL_CH] = cpl_start_band * 12 + 37;
2110 s->cpl_end_freq = cpl_end_band * 12 + 37;
2111 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2112 s->blocks[blk].end_freq[CPL_CH] = s->cpl_end_freq;
2117 static av_cold int allocate_buffers(AC3EncodeContext *s)
2119 AVCodecContext *avctx = s->avctx;
2121 int channels = s->channels + 1; /* includes coupling channel */
2123 if (s->allocate_sample_buffers(s))
2126 FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * channels *
2127 AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
2128 FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * channels *
2129 AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
2130 FF_ALLOCZ_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * channels *
2131 AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
2132 FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * channels *
2133 AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
2134 FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * channels *
2135 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
2136 FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * channels *
2137 AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
2138 FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * channels *
2139 64 * sizeof(*s->band_psd_buffer), alloc_fail);
2140 FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * channels *
2141 64 * sizeof(*s->mask_buffer), alloc_fail);
2142 FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * channels *
2143 AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
2144 if (s->cpl_enabled) {
2145 FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_exp_buffer, AC3_MAX_BLOCKS * channels *
2146 16 * sizeof(*s->cpl_coord_exp_buffer), alloc_fail);
2147 FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_mant_buffer, AC3_MAX_BLOCKS * channels *
2148 16 * sizeof(*s->cpl_coord_mant_buffer), alloc_fail);
2150 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2151 AC3Block *block = &s->blocks[blk];
2152 FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, channels * sizeof(*block->mdct_coef),
2154 FF_ALLOCZ_OR_GOTO(avctx, block->exp, channels * sizeof(*block->exp),
2156 FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, channels * sizeof(*block->grouped_exp),
2158 FF_ALLOCZ_OR_GOTO(avctx, block->psd, channels * sizeof(*block->psd),
2160 FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, channels * sizeof(*block->band_psd),
2162 FF_ALLOCZ_OR_GOTO(avctx, block->mask, channels * sizeof(*block->mask),
2164 FF_ALLOCZ_OR_GOTO(avctx, block->qmant, channels * sizeof(*block->qmant),
2166 if (s->cpl_enabled) {
2167 FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_exp, channels * sizeof(*block->cpl_coord_exp),
2169 FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_mant, channels * sizeof(*block->cpl_coord_mant),
2173 for (ch = 0; ch < channels; ch++) {
2174 /* arrangement: block, channel, coeff */
2175 block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * channels + ch)];
2176 block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
2177 block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * channels + ch)];
2178 block->mask[ch] = &s->mask_buffer [64 * (blk * channels + ch)];
2179 block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
2180 if (s->cpl_enabled) {
2181 block->cpl_coord_exp[ch] = &s->cpl_coord_exp_buffer [16 * (blk * channels + ch)];
2182 block->cpl_coord_mant[ch] = &s->cpl_coord_mant_buffer[16 * (blk * channels + ch)];
2185 /* arrangement: channel, block, coeff */
2186 block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2187 block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2191 if (!s->fixed_point) {
2192 FF_ALLOCZ_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * channels *
2193 AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
2194 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2195 AC3Block *block = &s->blocks[blk];
2196 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2197 sizeof(*block->fixed_coef), alloc_fail);
2198 for (ch = 0; ch < channels; ch++)
2199 block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2202 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2203 AC3Block *block = &s->blocks[blk];
2204 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2205 sizeof(*block->fixed_coef), alloc_fail);
2206 for (ch = 0; ch < channels; ch++)
2207 block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2213 return AVERROR(ENOMEM);
2218 * Initialize the encoder.
2220 av_cold int ff_ac3_encode_init(AVCodecContext *avctx)
2222 AC3EncodeContext *s = avctx->priv_data;
2223 int ret, frame_size_58;
2227 s->eac3 = avctx->codec_id == CODEC_ID_EAC3;
2229 avctx->frame_size = AC3_FRAME_SIZE;
2231 ff_ac3_common_init();
2233 ret = validate_options(s);
2237 s->bitstream_mode = avctx->audio_service_type;
2238 if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2239 s->bitstream_mode = 0x7;
2241 s->bits_written = 0;
2242 s->samples_written = 0;
2244 /* calculate crc_inv for both possible frame sizes */
2245 frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
2246 s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2247 if (s->bit_alloc.sr_code == 1) {
2248 frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2249 s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2252 /* set function pointers */
2253 if (CONFIG_AC3_FIXED_ENCODER && s->fixed_point) {
2254 s->mdct_end = ff_ac3_fixed_mdct_end;
2255 s->mdct_init = ff_ac3_fixed_mdct_init;
2256 s->allocate_sample_buffers = ff_ac3_fixed_allocate_sample_buffers;
2257 } else if (CONFIG_AC3_ENCODER || CONFIG_EAC3_ENCODER) {
2258 s->mdct_end = ff_ac3_float_mdct_end;
2259 s->mdct_init = ff_ac3_float_mdct_init;
2260 s->allocate_sample_buffers = ff_ac3_float_allocate_sample_buffers;
2262 if (CONFIG_EAC3_ENCODER && s->eac3)
2263 s->output_frame_header = ff_eac3_output_frame_header;
2265 s->output_frame_header = ac3_output_frame_header;
2273 ret = s->mdct_init(s);
2277 ret = allocate_buffers(s);
2281 avctx->coded_frame= avcodec_alloc_frame();
2283 dsputil_init(&s->dsp, avctx);
2284 ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2290 ff_ac3_encode_close(avctx);