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_BLOCK_SIZE * s->num_blocks;
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 < s->num_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 < s->num_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 < s->num_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 < s->num_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 * s->num_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
335 * Table used to select exponent strategy based on exponent reuse block interval.
337 static const uint8_t exp_strategy_reuse_tab[4][6] = {
338 { EXP_D15, EXP_D15, EXP_D15, EXP_D15, EXP_D15, EXP_D15 },
339 { EXP_D15, EXP_D15, EXP_D15, EXP_D15, EXP_D15, EXP_D15 },
340 { EXP_D25, EXP_D25, EXP_D15, EXP_D15, EXP_D15, EXP_D15 },
341 { EXP_D45, EXP_D25, EXP_D25, EXP_D15, EXP_D15, EXP_D15 }
345 * Calculate exponent strategies for all channels.
346 * Array arrangement is reversed to simplify the per-channel calculation.
348 static void compute_exp_strategy(AC3EncodeContext *s)
352 for (ch = !s->cpl_on; ch <= s->fbw_channels; ch++) {
353 uint8_t *exp_strategy = s->exp_strategy[ch];
354 uint8_t *exp = s->blocks[0].exp[ch];
357 /* estimate if the exponent variation & decide if they should be
358 reused in the next frame */
359 exp_strategy[0] = EXP_NEW;
360 exp += AC3_MAX_COEFS;
361 for (blk = 1; blk < s->num_blocks; blk++, exp += AC3_MAX_COEFS) {
363 if (!s->blocks[blk-1].cpl_in_use) {
364 exp_strategy[blk] = EXP_NEW;
366 } else if (!s->blocks[blk].cpl_in_use) {
367 exp_strategy[blk] = EXP_REUSE;
370 } else if (s->blocks[blk].channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]) {
371 exp_strategy[blk] = EXP_NEW;
374 exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
375 exp_strategy[blk] = EXP_REUSE;
376 if (ch == CPL_CH && exp_diff > (EXP_DIFF_THRESHOLD * (s->blocks[blk].end_freq[ch] - s->start_freq[ch]) / AC3_MAX_COEFS))
377 exp_strategy[blk] = EXP_NEW;
378 else if (ch > CPL_CH && exp_diff > EXP_DIFF_THRESHOLD)
379 exp_strategy[blk] = EXP_NEW;
382 /* now select the encoding strategy type : if exponents are often
383 recoded, we use a coarse encoding */
385 while (blk < s->num_blocks) {
387 while (blk1 < s->num_blocks && exp_strategy[blk1] == EXP_REUSE)
389 exp_strategy[blk] = exp_strategy_reuse_tab[s->num_blks_code][blk1-blk-1];
395 s->exp_strategy[ch][0] = EXP_D15;
396 for (blk = 1; blk < s->num_blocks; blk++)
397 s->exp_strategy[ch][blk] = EXP_REUSE;
400 /* for E-AC-3, determine frame exponent strategy */
401 if (CONFIG_EAC3_ENCODER && s->eac3)
402 ff_eac3_get_frame_exp_strategy(s);
407 * Update the exponents so that they are the ones the decoder will decode.
409 static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy,
414 nb_groups = exponent_group_tab[cpl][exp_strategy-1][nb_exps] * 3;
416 /* for each group, compute the minimum exponent */
417 switch(exp_strategy) {
419 for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
420 uint8_t exp_min = exp[k];
421 if (exp[k+1] < exp_min)
423 exp[i-cpl] = exp_min;
428 for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
429 uint8_t exp_min = exp[k];
430 if (exp[k+1] < exp_min)
432 if (exp[k+2] < exp_min)
434 if (exp[k+3] < exp_min)
436 exp[i-cpl] = exp_min;
442 /* constraint for DC exponent */
443 if (!cpl && exp[0] > 15)
446 /* decrease the delta between each groups to within 2 so that they can be
447 differentially encoded */
448 for (i = 1; i <= nb_groups; i++)
449 exp[i] = FFMIN(exp[i], exp[i-1] + 2);
452 exp[i] = FFMIN(exp[i], exp[i+1] + 2);
455 exp[-1] = exp[0] & ~1;
457 /* now we have the exponent values the decoder will see */
458 switch (exp_strategy) {
460 for (i = nb_groups, k = (nb_groups * 2)-cpl; i > 0; i--) {
461 uint8_t exp1 = exp[i-cpl];
467 for (i = nb_groups, k = (nb_groups * 4)-cpl; i > 0; i--) {
468 exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i-cpl];
477 * Encode exponents from original extracted form to what the decoder will see.
478 * This copies and groups exponents based on exponent strategy and reduces
479 * deltas between adjacent exponent groups so that they can be differentially
482 static void encode_exponents(AC3EncodeContext *s)
484 int blk, blk1, ch, cpl;
485 uint8_t *exp, *exp_strategy;
486 int nb_coefs, num_reuse_blocks;
488 for (ch = !s->cpl_on; ch <= s->channels; ch++) {
489 exp = s->blocks[0].exp[ch] + s->start_freq[ch];
490 exp_strategy = s->exp_strategy[ch];
492 cpl = (ch == CPL_CH);
494 while (blk < s->num_blocks) {
495 AC3Block *block = &s->blocks[blk];
496 if (cpl && !block->cpl_in_use) {
497 exp += AC3_MAX_COEFS;
501 nb_coefs = block->end_freq[ch] - s->start_freq[ch];
504 /* count the number of EXP_REUSE blocks after the current block
505 and set exponent reference block numbers */
506 s->exp_ref_block[ch][blk] = blk;
507 while (blk1 < s->num_blocks && exp_strategy[blk1] == EXP_REUSE) {
508 s->exp_ref_block[ch][blk1] = blk;
511 num_reuse_blocks = blk1 - blk - 1;
513 /* for the EXP_REUSE case we select the min of the exponents */
514 s->ac3dsp.ac3_exponent_min(exp-s->start_freq[ch], num_reuse_blocks,
517 encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk], cpl);
519 exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
524 /* reference block numbers have been changed, so reset ref_bap_set */
531 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
532 * varies depending on exponent strategy and bandwidth.
534 static void group_exponents(AC3EncodeContext *s)
537 int group_size, nb_groups, bit_count;
539 int delta0, delta1, delta2;
543 for (blk = 0; blk < s->num_blocks; blk++) {
544 AC3Block *block = &s->blocks[blk];
545 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
546 int exp_strategy = s->exp_strategy[ch][blk];
547 if (exp_strategy == EXP_REUSE)
549 cpl = (ch == CPL_CH);
550 group_size = exp_strategy + (exp_strategy == EXP_D45);
551 nb_groups = exponent_group_tab[cpl][exp_strategy-1][block->end_freq[ch]-s->start_freq[ch]];
552 bit_count += 4 + (nb_groups * 7);
553 p = block->exp[ch] + s->start_freq[ch] - cpl;
557 block->grouped_exp[ch][0] = exp1;
559 /* remaining exponents are delta encoded */
560 for (i = 1; i <= nb_groups; i++) {
561 /* merge three delta in one code */
565 delta0 = exp1 - exp0 + 2;
566 av_assert2(delta0 >= 0 && delta0 <= 4);
571 delta1 = exp1 - exp0 + 2;
572 av_assert2(delta1 >= 0 && delta1 <= 4);
577 delta2 = exp1 - exp0 + 2;
578 av_assert2(delta2 >= 0 && delta2 <= 4);
580 block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
585 s->exponent_bits = bit_count;
590 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
591 * Extract exponents from MDCT coefficients, calculate exponent strategies,
592 * and encode final exponents.
594 void ff_ac3_process_exponents(AC3EncodeContext *s)
596 extract_exponents(s);
598 compute_exp_strategy(s);
609 * Count frame bits that are based solely on fixed parameters.
610 * This only has to be run once when the encoder is initialized.
612 static void count_frame_bits_fixed(AC3EncodeContext *s)
614 static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
619 * no dynamic range codes
620 * bit allocation parameters do not change between blocks
621 * no delta bit allocation
628 frame_bits = 16; /* sync info */
630 /* bitstream info header */
633 if (s->num_blocks != 0x6)
636 /* audio frame header */
637 if (s->num_blocks == 6)
640 /* exponent strategy */
641 if (s->use_frame_exp_strategy)
642 frame_bits += 5 * s->fbw_channels;
644 frame_bits += s->num_blocks * 2 * s->fbw_channels;
646 frame_bits += s->num_blocks;
647 /* converter exponent strategy */
648 if (s->num_blks_code != 0x3)
651 frame_bits += s->fbw_channels * 5;
654 /* block start info */
655 if (s->num_blocks != 1)
659 frame_bits += frame_bits_inc[s->channel_mode];
663 for (blk = 0; blk < s->num_blocks; blk++) {
665 /* block switch flags */
666 frame_bits += s->fbw_channels;
669 frame_bits += s->fbw_channels;
675 /* spectral extension */
680 /* exponent strategy */
681 frame_bits += 2 * s->fbw_channels;
685 /* bit allocation params */
688 frame_bits += 2 + 2 + 2 + 2 + 3;
691 /* converter snr offset */
696 /* delta bit allocation */
708 frame_bits += 1 + 16;
710 s->frame_bits_fixed = frame_bits;
715 * Initialize bit allocation.
716 * Set default parameter codes and calculate parameter values.
718 static void bit_alloc_init(AC3EncodeContext *s)
722 /* init default parameters */
723 s->slow_decay_code = 2;
724 s->fast_decay_code = 1;
725 s->slow_gain_code = 1;
726 s->db_per_bit_code = s->eac3 ? 2 : 3;
728 for (ch = 0; ch <= s->channels; ch++)
729 s->fast_gain_code[ch] = 4;
731 /* initial snr offset */
732 s->coarse_snr_offset = 40;
734 /* compute real values */
735 /* currently none of these values change during encoding, so we can just
736 set them once at initialization */
737 s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
738 s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
739 s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
740 s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
741 s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
742 s->bit_alloc.cpl_fast_leak = 0;
743 s->bit_alloc.cpl_slow_leak = 0;
745 count_frame_bits_fixed(s);
750 * Count the bits used to encode the frame, minus exponents and mantissas.
751 * Bits based on fixed parameters have already been counted, so now we just
752 * have to add the bits based on parameters that change during encoding.
754 static void count_frame_bits(AC3EncodeContext *s)
756 AC3EncOptions *opt = &s->options;
762 if (opt->eac3_mixing_metadata) {
763 if (s->channel_mode > AC3_CHMODE_STEREO)
769 frame_bits += s->lfe_on;
770 frame_bits += 1 + 1 + 2;
771 if (s->channel_mode < AC3_CHMODE_STEREO)
775 if (opt->eac3_info_metadata) {
776 frame_bits += 3 + 1 + 1;
777 if (s->channel_mode == AC3_CHMODE_STEREO)
779 if (s->channel_mode >= AC3_CHMODE_2F2R)
782 if (opt->audio_production_info)
783 frame_bits += 5 + 2 + 1;
787 if (s->channel_mode > AC3_CHMODE_MONO) {
789 for (blk = 1; blk < s->num_blocks; blk++) {
790 AC3Block *block = &s->blocks[blk];
792 if (block->new_cpl_strategy)
796 /* coupling exponent strategy */
798 if (s->use_frame_exp_strategy) {
799 frame_bits += 5 * s->cpl_on;
801 for (blk = 0; blk < s->num_blocks; blk++)
802 frame_bits += 2 * s->blocks[blk].cpl_in_use;
806 if (opt->audio_production_info)
808 if (s->bitstream_id == 6) {
809 if (opt->extended_bsi_1)
811 if (opt->extended_bsi_2)
817 for (blk = 0; blk < s->num_blocks; blk++) {
818 AC3Block *block = &s->blocks[blk];
820 /* coupling strategy */
823 if (block->new_cpl_strategy) {
826 if (block->cpl_in_use) {
829 if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO)
830 frame_bits += s->fbw_channels;
831 if (s->channel_mode == AC3_CHMODE_STEREO)
837 frame_bits += s->num_cpl_subbands - 1;
841 /* coupling coordinates */
842 if (block->cpl_in_use) {
843 for (ch = 1; ch <= s->fbw_channels; ch++) {
844 if (block->channel_in_cpl[ch]) {
845 if (!s->eac3 || block->new_cpl_coords != 2)
847 if (block->new_cpl_coords) {
849 frame_bits += (4 + 4) * s->num_cpl_bands;
855 /* stereo rematrixing */
856 if (s->channel_mode == AC3_CHMODE_STEREO) {
857 if (!s->eac3 || blk > 0)
859 if (s->blocks[blk].new_rematrixing_strategy)
860 frame_bits += block->num_rematrixing_bands;
863 /* bandwidth codes & gain range */
864 for (ch = 1; ch <= s->fbw_channels; ch++) {
865 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
866 if (!block->channel_in_cpl[ch])
872 /* coupling exponent strategy */
873 if (!s->eac3 && block->cpl_in_use)
876 /* snr offsets and fast gain codes */
879 if (block->new_snr_offsets)
880 frame_bits += 6 + (s->channels + block->cpl_in_use) * (4 + 3);
883 /* coupling leak info */
884 if (block->cpl_in_use) {
885 if (!s->eac3 || block->new_cpl_leak != 2)
887 if (block->new_cpl_leak)
892 s->frame_bits = s->frame_bits_fixed + frame_bits;
897 * Calculate masking curve based on the final exponents.
898 * Also calculate the power spectral densities to use in future calculations.
900 static void bit_alloc_masking(AC3EncodeContext *s)
904 for (blk = 0; blk < s->num_blocks; blk++) {
905 AC3Block *block = &s->blocks[blk];
906 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
907 /* We only need psd and mask for calculating bap.
908 Since we currently do not calculate bap when exponent
909 strategy is EXP_REUSE we do not need to calculate psd or mask. */
910 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
911 ff_ac3_bit_alloc_calc_psd(block->exp[ch], s->start_freq[ch],
912 block->end_freq[ch], block->psd[ch],
913 block->band_psd[ch]);
914 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
915 s->start_freq[ch], block->end_freq[ch],
916 ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
917 ch == s->lfe_channel,
918 DBA_NONE, 0, NULL, NULL, NULL,
927 * Ensure that bap for each block and channel point to the current bap_buffer.
928 * They may have been switched during the bit allocation search.
930 static void reset_block_bap(AC3EncodeContext *s)
935 if (s->ref_bap[0][0] == s->bap_buffer && s->ref_bap_set)
938 ref_bap = s->bap_buffer;
939 for (ch = 0; ch <= s->channels; ch++) {
940 for (blk = 0; blk < s->num_blocks; blk++)
941 s->ref_bap[ch][blk] = ref_bap + AC3_MAX_COEFS * s->exp_ref_block[ch][blk];
942 ref_bap += AC3_MAX_COEFS * s->num_blocks;
949 * Initialize mantissa counts.
950 * These are set so that they are padded to the next whole group size when bits
951 * are counted in compute_mantissa_size.
953 static void count_mantissa_bits_init(uint16_t mant_cnt[AC3_MAX_BLOCKS][16])
957 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
958 memset(mant_cnt[blk], 0, sizeof(mant_cnt[blk]));
959 mant_cnt[blk][1] = mant_cnt[blk][2] = 2;
960 mant_cnt[blk][4] = 1;
966 * Update mantissa bit counts for all blocks in 1 channel in a given bandwidth
969 static void count_mantissa_bits_update_ch(AC3EncodeContext *s, int ch,
970 uint16_t mant_cnt[AC3_MAX_BLOCKS][16],
975 for (blk = 0; blk < s->num_blocks; blk++) {
976 AC3Block *block = &s->blocks[blk];
977 if (ch == CPL_CH && !block->cpl_in_use)
979 s->ac3dsp.update_bap_counts(mant_cnt[blk],
980 s->ref_bap[ch][blk] + start,
981 FFMIN(end, block->end_freq[ch]) - start);
987 * Count the number of mantissa bits in the frame based on the bap values.
989 static int count_mantissa_bits(AC3EncodeContext *s)
991 int ch, max_end_freq;
992 LOCAL_ALIGNED_16(uint16_t, mant_cnt, [AC3_MAX_BLOCKS], [16]);
994 count_mantissa_bits_init(mant_cnt);
996 max_end_freq = s->bandwidth_code * 3 + 73;
997 for (ch = !s->cpl_enabled; ch <= s->channels; ch++)
998 count_mantissa_bits_update_ch(s, ch, mant_cnt, s->start_freq[ch],
1001 return s->ac3dsp.compute_mantissa_size(mant_cnt);
1006 * Run the bit allocation with a given SNR offset.
1007 * This calculates the bit allocation pointers that will be used to determine
1008 * the quantization of each mantissa.
1009 * @return the number of bits needed for mantissas if the given SNR offset is
1012 static int bit_alloc(AC3EncodeContext *s, int snr_offset)
1016 snr_offset = (snr_offset - 240) << 2;
1019 for (blk = 0; blk < s->num_blocks; blk++) {
1020 AC3Block *block = &s->blocks[blk];
1022 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1023 /* Currently the only bit allocation parameters which vary across
1024 blocks within a frame are the exponent values. We can take
1025 advantage of that by reusing the bit allocation pointers
1026 whenever we reuse exponents. */
1027 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1028 s->ac3dsp.bit_alloc_calc_bap(block->mask[ch], block->psd[ch],
1029 s->start_freq[ch], block->end_freq[ch],
1030 snr_offset, s->bit_alloc.floor,
1031 ff_ac3_bap_tab, s->ref_bap[ch][blk]);
1035 return count_mantissa_bits(s);
1040 * Constant bitrate bit allocation search.
1041 * Find the largest SNR offset that will allow data to fit in the frame.
1043 static int cbr_bit_allocation(AC3EncodeContext *s)
1047 int snr_offset, snr_incr;
1049 bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1051 return AVERROR(EINVAL);
1053 snr_offset = s->coarse_snr_offset << 4;
1055 /* if previous frame SNR offset was 1023, check if current frame can also
1056 use SNR offset of 1023. if so, skip the search. */
1057 if ((snr_offset | s->fine_snr_offset[1]) == 1023) {
1058 if (bit_alloc(s, 1023) <= bits_left)
1062 while (snr_offset >= 0 &&
1063 bit_alloc(s, snr_offset) > bits_left) {
1067 return AVERROR(EINVAL);
1069 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1070 for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1071 while (snr_offset + snr_incr <= 1023 &&
1072 bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1073 snr_offset += snr_incr;
1074 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1077 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1080 s->coarse_snr_offset = snr_offset >> 4;
1081 for (ch = !s->cpl_on; ch <= s->channels; ch++)
1082 s->fine_snr_offset[ch] = snr_offset & 0xF;
1089 * Perform bit allocation search.
1090 * Finds the SNR offset value that maximizes quality and fits in the specified
1091 * frame size. Output is the SNR offset and a set of bit allocation pointers
1092 * used to quantize the mantissas.
1094 int ff_ac3_compute_bit_allocation(AC3EncodeContext *s)
1096 count_frame_bits(s);
1098 bit_alloc_masking(s);
1100 return cbr_bit_allocation(s);
1105 * Symmetric quantization on 'levels' levels.
1107 static inline int sym_quant(int c, int e, int levels)
1109 int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1110 av_assert2(v >= 0 && v < levels);
1116 * Asymmetric quantization on 2^qbits levels.
1118 static inline int asym_quant(int c, int e, int qbits)
1122 c = (((c << e) >> (24 - qbits)) + 1) >> 1;
1123 m = (1 << (qbits-1));
1126 av_assert2(c >= -m);
1132 * Quantize a set of mantissas for a single channel in a single block.
1134 static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1135 uint8_t *exp, uint8_t *bap,
1136 int16_t *qmant, int start_freq,
1141 for (i = start_freq; i < end_freq; i++) {
1143 int c = fixed_coef[i];
1151 v = sym_quant(c, e, 3);
1152 switch (s->mant1_cnt) {
1154 s->qmant1_ptr = &qmant[i];
1159 *s->qmant1_ptr += 3 * v;
1164 *s->qmant1_ptr += v;
1171 v = sym_quant(c, e, 5);
1172 switch (s->mant2_cnt) {
1174 s->qmant2_ptr = &qmant[i];
1179 *s->qmant2_ptr += 5 * v;
1184 *s->qmant2_ptr += v;
1191 v = sym_quant(c, e, 7);
1194 v = sym_quant(c, e, 11);
1195 switch (s->mant4_cnt) {
1197 s->qmant4_ptr = &qmant[i];
1202 *s->qmant4_ptr += v;
1209 v = sym_quant(c, e, 15);
1212 v = asym_quant(c, e, 14);
1215 v = asym_quant(c, e, 16);
1218 v = asym_quant(c, e, b - 1);
1227 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1229 void ff_ac3_quantize_mantissas(AC3EncodeContext *s)
1231 int blk, ch, ch0=0, got_cpl;
1233 for (blk = 0; blk < s->num_blocks; blk++) {
1234 AC3Block *block = &s->blocks[blk];
1237 got_cpl = !block->cpl_in_use;
1238 for (ch = 1; ch <= s->channels; ch++) {
1239 if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1244 quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1245 s->blocks[s->exp_ref_block[ch][blk]].exp[ch],
1246 s->ref_bap[ch][blk], block->qmant[ch],
1247 s->start_freq[ch], block->end_freq[ch]);
1256 * Write the AC-3 frame header to the output bitstream.
1258 static void ac3_output_frame_header(AC3EncodeContext *s)
1260 AC3EncOptions *opt = &s->options;
1262 put_bits(&s->pb, 16, 0x0b77); /* frame header */
1263 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
1264 put_bits(&s->pb, 2, s->bit_alloc.sr_code);
1265 put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1266 put_bits(&s->pb, 5, s->bitstream_id);
1267 put_bits(&s->pb, 3, s->bitstream_mode);
1268 put_bits(&s->pb, 3, s->channel_mode);
1269 if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1270 put_bits(&s->pb, 2, s->center_mix_level);
1271 if (s->channel_mode & 0x04)
1272 put_bits(&s->pb, 2, s->surround_mix_level);
1273 if (s->channel_mode == AC3_CHMODE_STEREO)
1274 put_bits(&s->pb, 2, opt->dolby_surround_mode);
1275 put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1276 put_bits(&s->pb, 5, -opt->dialogue_level);
1277 put_bits(&s->pb, 1, 0); /* no compression control word */
1278 put_bits(&s->pb, 1, 0); /* no lang code */
1279 put_bits(&s->pb, 1, opt->audio_production_info);
1280 if (opt->audio_production_info) {
1281 put_bits(&s->pb, 5, opt->mixing_level - 80);
1282 put_bits(&s->pb, 2, opt->room_type);
1284 put_bits(&s->pb, 1, opt->copyright);
1285 put_bits(&s->pb, 1, opt->original);
1286 if (s->bitstream_id == 6) {
1287 /* alternate bit stream syntax */
1288 put_bits(&s->pb, 1, opt->extended_bsi_1);
1289 if (opt->extended_bsi_1) {
1290 put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1291 put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1292 put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1293 put_bits(&s->pb, 3, s->loro_center_mix_level);
1294 put_bits(&s->pb, 3, s->loro_surround_mix_level);
1296 put_bits(&s->pb, 1, opt->extended_bsi_2);
1297 if (opt->extended_bsi_2) {
1298 put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1299 put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1300 put_bits(&s->pb, 1, opt->ad_converter_type);
1301 put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
1304 put_bits(&s->pb, 1, 0); /* no time code 1 */
1305 put_bits(&s->pb, 1, 0); /* no time code 2 */
1307 put_bits(&s->pb, 1, 0); /* no additional bit stream info */
1312 * Write one audio block to the output bitstream.
1314 static void output_audio_block(AC3EncodeContext *s, int blk)
1316 int ch, i, baie, bnd, got_cpl;
1318 AC3Block *block = &s->blocks[blk];
1320 /* block switching */
1322 for (ch = 0; ch < s->fbw_channels; ch++)
1323 put_bits(&s->pb, 1, 0);
1328 for (ch = 0; ch < s->fbw_channels; ch++)
1329 put_bits(&s->pb, 1, 1);
1332 /* dynamic range codes */
1333 put_bits(&s->pb, 1, 0);
1335 /* spectral extension */
1337 put_bits(&s->pb, 1, 0);
1339 /* channel coupling */
1341 put_bits(&s->pb, 1, block->new_cpl_strategy);
1342 if (block->new_cpl_strategy) {
1344 put_bits(&s->pb, 1, block->cpl_in_use);
1345 if (block->cpl_in_use) {
1346 int start_sub, end_sub;
1348 put_bits(&s->pb, 1, 0); /* enhanced coupling */
1349 if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO) {
1350 for (ch = 1; ch <= s->fbw_channels; ch++)
1351 put_bits(&s->pb, 1, block->channel_in_cpl[ch]);
1353 if (s->channel_mode == AC3_CHMODE_STEREO)
1354 put_bits(&s->pb, 1, 0); /* phase flags in use */
1355 start_sub = (s->start_freq[CPL_CH] - 37) / 12;
1356 end_sub = (s->cpl_end_freq - 37) / 12;
1357 put_bits(&s->pb, 4, start_sub);
1358 put_bits(&s->pb, 4, end_sub - 3);
1359 /* coupling band structure */
1361 put_bits(&s->pb, 1, 0); /* use default */
1363 for (bnd = start_sub+1; bnd < end_sub; bnd++)
1364 put_bits(&s->pb, 1, ff_eac3_default_cpl_band_struct[bnd]);
1369 /* coupling coordinates */
1370 if (block->cpl_in_use) {
1371 for (ch = 1; ch <= s->fbw_channels; ch++) {
1372 if (block->channel_in_cpl[ch]) {
1373 if (!s->eac3 || block->new_cpl_coords != 2)
1374 put_bits(&s->pb, 1, block->new_cpl_coords);
1375 if (block->new_cpl_coords) {
1376 put_bits(&s->pb, 2, block->cpl_master_exp[ch]);
1377 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
1378 put_bits(&s->pb, 4, block->cpl_coord_exp [ch][bnd]);
1379 put_bits(&s->pb, 4, block->cpl_coord_mant[ch][bnd]);
1386 /* stereo rematrixing */
1387 if (s->channel_mode == AC3_CHMODE_STEREO) {
1388 if (!s->eac3 || blk > 0)
1389 put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1390 if (block->new_rematrixing_strategy) {
1391 /* rematrixing flags */
1392 for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++)
1393 put_bits(&s->pb, 1, block->rematrixing_flags[bnd]);
1397 /* exponent strategy */
1399 for (ch = !block->cpl_in_use; ch <= s->fbw_channels; ch++)
1400 put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1402 put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1406 for (ch = 1; ch <= s->fbw_channels; ch++) {
1407 if (s->exp_strategy[ch][blk] != EXP_REUSE && !block->channel_in_cpl[ch])
1408 put_bits(&s->pb, 6, s->bandwidth_code);
1412 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1414 int cpl = (ch == CPL_CH);
1416 if (s->exp_strategy[ch][blk] == EXP_REUSE)
1420 put_bits(&s->pb, 4, block->grouped_exp[ch][0] >> cpl);
1422 /* exponent groups */
1423 nb_groups = exponent_group_tab[cpl][s->exp_strategy[ch][blk]-1][block->end_freq[ch]-s->start_freq[ch]];
1424 for (i = 1; i <= nb_groups; i++)
1425 put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1427 /* gain range info */
1428 if (ch != s->lfe_channel && !cpl)
1429 put_bits(&s->pb, 2, 0);
1432 /* bit allocation info */
1435 put_bits(&s->pb, 1, baie);
1437 put_bits(&s->pb, 2, s->slow_decay_code);
1438 put_bits(&s->pb, 2, s->fast_decay_code);
1439 put_bits(&s->pb, 2, s->slow_gain_code);
1440 put_bits(&s->pb, 2, s->db_per_bit_code);
1441 put_bits(&s->pb, 3, s->floor_code);
1447 put_bits(&s->pb, 1, block->new_snr_offsets);
1448 if (block->new_snr_offsets) {
1449 put_bits(&s->pb, 6, s->coarse_snr_offset);
1450 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1451 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1452 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1456 put_bits(&s->pb, 1, 0); /* no converter snr offset */
1460 if (block->cpl_in_use) {
1461 if (!s->eac3 || block->new_cpl_leak != 2)
1462 put_bits(&s->pb, 1, block->new_cpl_leak);
1463 if (block->new_cpl_leak) {
1464 put_bits(&s->pb, 3, s->bit_alloc.cpl_fast_leak);
1465 put_bits(&s->pb, 3, s->bit_alloc.cpl_slow_leak);
1470 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1471 put_bits(&s->pb, 1, 0); /* no data to skip */
1475 got_cpl = !block->cpl_in_use;
1476 for (ch = 1; ch <= s->channels; ch++) {
1479 if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1484 for (i = s->start_freq[ch]; i < block->end_freq[ch]; i++) {
1485 q = block->qmant[ch][i];
1486 b = s->ref_bap[ch][blk][i];
1489 case 1: if (q != 128) put_bits (&s->pb, 5, q); break;
1490 case 2: if (q != 128) put_bits (&s->pb, 7, q); break;
1491 case 3: put_sbits(&s->pb, 3, q); break;
1492 case 4: if (q != 128) put_bits (&s->pb, 7, q); break;
1493 case 14: put_sbits(&s->pb, 14, q); break;
1494 case 15: put_sbits(&s->pb, 16, q); break;
1495 default: put_sbits(&s->pb, b-1, q); break;
1504 /** CRC-16 Polynomial */
1505 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1508 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1525 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1531 r = mul_poly(r, a, poly);
1532 a = mul_poly(a, a, poly);
1540 * Fill the end of the frame with 0's and compute the two CRCs.
1542 static void output_frame_end(AC3EncodeContext *s)
1544 const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1545 int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1548 frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1550 /* pad the remainder of the frame with zeros */
1551 av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1552 flush_put_bits(&s->pb);
1554 pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1555 av_assert2(pad_bytes >= 0);
1557 memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1561 crc2_partial = av_crc(crc_ctx, 0, frame + 2, s->frame_size - 5);
1564 /* this is not so easy because it is at the beginning of the data... */
1565 crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1566 crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1567 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1568 AV_WB16(frame + 2, crc1);
1571 crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1572 s->frame_size - frame_size_58 - 3);
1574 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1575 /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1576 if (crc2 == 0x770B) {
1577 frame[s->frame_size - 3] ^= 0x1;
1578 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1580 crc2 = av_bswap16(crc2);
1581 AV_WB16(frame + s->frame_size - 2, crc2);
1586 * Write the frame to the output bitstream.
1588 void ff_ac3_output_frame(AC3EncodeContext *s, unsigned char *frame)
1592 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1594 s->output_frame_header(s);
1596 for (blk = 0; blk < s->num_blocks; blk++)
1597 output_audio_block(s, blk);
1599 output_frame_end(s);
1603 static void dprint_options(AC3EncodeContext *s)
1606 AVCodecContext *avctx = s->avctx;
1607 AC3EncOptions *opt = &s->options;
1610 switch (s->bitstream_id) {
1611 case 6: av_strlcpy(strbuf, "AC-3 (alt syntax)", 32); break;
1612 case 8: av_strlcpy(strbuf, "AC-3 (standard)", 32); break;
1613 case 9: av_strlcpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
1614 case 10: av_strlcpy(strbuf, "AC-3 (dnet quater-rate)", 32); break;
1615 case 16: av_strlcpy(strbuf, "E-AC-3 (enhanced)", 32); break;
1616 default: snprintf(strbuf, 32, "ERROR");
1618 av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
1619 av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
1620 av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
1621 av_dlog(avctx, "channel_layout: %s\n", strbuf);
1622 av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
1623 av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
1624 av_dlog(avctx, "blocks/frame: %d (code=%d)\n", s->num_blocks, s->num_blks_code);
1626 av_dlog(avctx, "cutoff: %d\n", s->cutoff);
1628 av_dlog(avctx, "per_frame_metadata: %s\n",
1629 opt->allow_per_frame_metadata?"on":"off");
1631 av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
1632 s->center_mix_level);
1634 av_dlog(avctx, "center_mixlev: {not written}\n");
1635 if (s->has_surround)
1636 av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
1637 s->surround_mix_level);
1639 av_dlog(avctx, "surround_mixlev: {not written}\n");
1640 if (opt->audio_production_info) {
1641 av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
1642 switch (opt->room_type) {
1643 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1644 case 1: av_strlcpy(strbuf, "large", 32); break;
1645 case 2: av_strlcpy(strbuf, "small", 32); break;
1646 default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
1648 av_dlog(avctx, "room_type: %s\n", strbuf);
1650 av_dlog(avctx, "mixing_level: {not written}\n");
1651 av_dlog(avctx, "room_type: {not written}\n");
1653 av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
1654 av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
1655 if (s->channel_mode == AC3_CHMODE_STEREO) {
1656 switch (opt->dolby_surround_mode) {
1657 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1658 case 1: av_strlcpy(strbuf, "on", 32); break;
1659 case 2: av_strlcpy(strbuf, "off", 32); break;
1660 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
1662 av_dlog(avctx, "dsur_mode: %s\n", strbuf);
1664 av_dlog(avctx, "dsur_mode: {not written}\n");
1666 av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
1668 if (s->bitstream_id == 6) {
1669 if (opt->extended_bsi_1) {
1670 switch (opt->preferred_stereo_downmix) {
1671 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1672 case 1: av_strlcpy(strbuf, "ltrt", 32); break;
1673 case 2: av_strlcpy(strbuf, "loro", 32); break;
1674 default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
1676 av_dlog(avctx, "dmix_mode: %s\n", strbuf);
1677 av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
1678 opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
1679 av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
1680 opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
1681 av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
1682 opt->loro_center_mix_level, s->loro_center_mix_level);
1683 av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
1684 opt->loro_surround_mix_level, s->loro_surround_mix_level);
1686 av_dlog(avctx, "extended bitstream info 1: {not written}\n");
1688 if (opt->extended_bsi_2) {
1689 switch (opt->dolby_surround_ex_mode) {
1690 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1691 case 1: av_strlcpy(strbuf, "on", 32); break;
1692 case 2: av_strlcpy(strbuf, "off", 32); break;
1693 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
1695 av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
1696 switch (opt->dolby_headphone_mode) {
1697 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1698 case 1: av_strlcpy(strbuf, "on", 32); break;
1699 case 2: av_strlcpy(strbuf, "off", 32); break;
1700 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
1702 av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
1704 switch (opt->ad_converter_type) {
1705 case 0: av_strlcpy(strbuf, "standard", 32); break;
1706 case 1: av_strlcpy(strbuf, "hdcd", 32); break;
1707 default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
1709 av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
1711 av_dlog(avctx, "extended bitstream info 2: {not written}\n");
1718 #define FLT_OPTION_THRESHOLD 0.01
1720 static int validate_float_option(float v, const float *v_list, int v_list_size)
1724 for (i = 0; i < v_list_size; i++) {
1725 if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
1726 v > (v_list[i] - FLT_OPTION_THRESHOLD))
1729 if (i == v_list_size)
1736 static void validate_mix_level(void *log_ctx, const char *opt_name,
1737 float *opt_param, const float *list,
1738 int list_size, int default_value, int min_value,
1741 int mixlev = validate_float_option(*opt_param, list, list_size);
1742 if (mixlev < min_value) {
1743 mixlev = default_value;
1744 if (*opt_param >= 0.0) {
1745 av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
1746 "default value: %0.3f\n", opt_name, list[mixlev]);
1749 *opt_param = list[mixlev];
1750 *ctx_param = mixlev;
1755 * Validate metadata options as set by AVOption system.
1756 * These values can optionally be changed per-frame.
1758 int ff_ac3_validate_metadata(AC3EncodeContext *s)
1760 AVCodecContext *avctx = s->avctx;
1761 AC3EncOptions *opt = &s->options;
1763 opt->audio_production_info = 0;
1764 opt->extended_bsi_1 = 0;
1765 opt->extended_bsi_2 = 0;
1766 opt->eac3_mixing_metadata = 0;
1767 opt->eac3_info_metadata = 0;
1769 /* determine mixing metadata / xbsi1 use */
1770 if (s->channel_mode > AC3_CHMODE_STEREO && opt->preferred_stereo_downmix >= 0) {
1771 opt->extended_bsi_1 = 1;
1772 opt->eac3_mixing_metadata = 1;
1774 if (s->has_center &&
1775 (opt->ltrt_center_mix_level >= 0 || opt->loro_center_mix_level >= 0)) {
1776 opt->extended_bsi_1 = 1;
1777 opt->eac3_mixing_metadata = 1;
1779 if (s->has_surround &&
1780 (opt->ltrt_surround_mix_level >= 0 || opt->loro_surround_mix_level >= 0)) {
1781 opt->extended_bsi_1 = 1;
1782 opt->eac3_mixing_metadata = 1;
1786 /* determine info metadata use */
1787 if (avctx->audio_service_type != AV_AUDIO_SERVICE_TYPE_MAIN)
1788 opt->eac3_info_metadata = 1;
1789 if (opt->copyright >= 0 || opt->original >= 0)
1790 opt->eac3_info_metadata = 1;
1791 if (s->channel_mode == AC3_CHMODE_STEREO &&
1792 (opt->dolby_headphone_mode >= 0 || opt->dolby_surround_mode >= 0))
1793 opt->eac3_info_metadata = 1;
1794 if (s->channel_mode >= AC3_CHMODE_2F2R && opt->dolby_surround_ex_mode >= 0)
1795 opt->eac3_info_metadata = 1;
1796 if (opt->mixing_level >= 0 || opt->room_type >= 0 || opt->ad_converter_type >= 0) {
1797 opt->audio_production_info = 1;
1798 opt->eac3_info_metadata = 1;
1801 /* determine audio production info use */
1802 if (opt->mixing_level >= 0 || opt->room_type >= 0)
1803 opt->audio_production_info = 1;
1805 /* determine xbsi2 use */
1806 if (s->channel_mode >= AC3_CHMODE_2F2R && opt->dolby_surround_ex_mode >= 0)
1807 opt->extended_bsi_2 = 1;
1808 if (s->channel_mode == AC3_CHMODE_STEREO && opt->dolby_headphone_mode >= 0)
1809 opt->extended_bsi_2 = 1;
1810 if (opt->ad_converter_type >= 0)
1811 opt->extended_bsi_2 = 1;
1814 /* validate AC-3 mixing levels */
1816 if (s->has_center) {
1817 validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
1818 cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
1819 &s->center_mix_level);
1821 if (s->has_surround) {
1822 validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
1823 surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
1824 &s->surround_mix_level);
1828 /* validate extended bsi 1 / mixing metadata */
1829 if (opt->extended_bsi_1 || opt->eac3_mixing_metadata) {
1830 /* default preferred stereo downmix */
1831 if (opt->preferred_stereo_downmix < 0)
1832 opt->preferred_stereo_downmix = 0;
1833 if (!s->eac3 || s->has_center) {
1834 /* validate Lt/Rt center mix level */
1835 validate_mix_level(avctx, "ltrt_center_mix_level",
1836 &opt->ltrt_center_mix_level, extmixlev_options,
1837 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1838 &s->ltrt_center_mix_level);
1839 /* validate Lo/Ro center mix level */
1840 validate_mix_level(avctx, "loro_center_mix_level",
1841 &opt->loro_center_mix_level, extmixlev_options,
1842 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1843 &s->loro_center_mix_level);
1845 if (!s->eac3 || s->has_surround) {
1846 /* validate Lt/Rt surround mix level */
1847 validate_mix_level(avctx, "ltrt_surround_mix_level",
1848 &opt->ltrt_surround_mix_level, extmixlev_options,
1849 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1850 &s->ltrt_surround_mix_level);
1851 /* validate Lo/Ro surround mix level */
1852 validate_mix_level(avctx, "loro_surround_mix_level",
1853 &opt->loro_surround_mix_level, extmixlev_options,
1854 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1855 &s->loro_surround_mix_level);
1859 /* validate audio service type / channels combination */
1860 if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
1861 avctx->channels == 1) ||
1862 ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
1863 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
1864 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
1865 && avctx->channels > 1)) {
1866 av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
1867 "specified number of channels\n");
1868 return AVERROR(EINVAL);
1871 /* validate extended bsi 2 / info metadata */
1872 if (opt->extended_bsi_2 || opt->eac3_info_metadata) {
1873 /* default dolby headphone mode */
1874 if (opt->dolby_headphone_mode < 0)
1875 opt->dolby_headphone_mode = 0;
1876 /* default dolby surround ex mode */
1877 if (opt->dolby_surround_ex_mode < 0)
1878 opt->dolby_surround_ex_mode = 0;
1879 /* default A/D converter type */
1880 if (opt->ad_converter_type < 0)
1881 opt->ad_converter_type = 0;
1884 /* copyright & original defaults */
1885 if (!s->eac3 || opt->eac3_info_metadata) {
1886 /* default copyright */
1887 if (opt->copyright < 0)
1889 /* default original */
1890 if (opt->original < 0)
1894 /* dolby surround mode default */
1895 if (!s->eac3 || opt->eac3_info_metadata) {
1896 if (opt->dolby_surround_mode < 0)
1897 opt->dolby_surround_mode = 0;
1900 /* validate audio production info */
1901 if (opt->audio_production_info) {
1902 if (opt->mixing_level < 0) {
1903 av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
1904 "room_type is set\n");
1905 return AVERROR(EINVAL);
1907 if (opt->mixing_level < 80) {
1908 av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
1909 "80dB and 111dB\n");
1910 return AVERROR(EINVAL);
1912 /* default room type */
1913 if (opt->room_type < 0)
1917 /* set bitstream id for alternate bitstream syntax */
1918 if (!s->eac3 && (opt->extended_bsi_1 || opt->extended_bsi_2)) {
1919 if (s->bitstream_id > 8 && s->bitstream_id < 11) {
1920 static int warn_once = 1;
1922 av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
1923 "not compatible with reduced samplerates. writing of "
1924 "extended bitstream information will be disabled.\n");
1928 s->bitstream_id = 6;
1937 * Finalize encoding and free any memory allocated by the encoder.
1939 av_cold int ff_ac3_encode_close(AVCodecContext *avctx)
1942 AC3EncodeContext *s = avctx->priv_data;
1944 av_freep(&s->windowed_samples);
1945 for (ch = 0; ch < s->channels; ch++)
1946 av_freep(&s->planar_samples[ch]);
1947 av_freep(&s->planar_samples);
1948 av_freep(&s->bap_buffer);
1949 av_freep(&s->bap1_buffer);
1950 av_freep(&s->mdct_coef_buffer);
1951 av_freep(&s->fixed_coef_buffer);
1952 av_freep(&s->exp_buffer);
1953 av_freep(&s->grouped_exp_buffer);
1954 av_freep(&s->psd_buffer);
1955 av_freep(&s->band_psd_buffer);
1956 av_freep(&s->mask_buffer);
1957 av_freep(&s->qmant_buffer);
1958 av_freep(&s->cpl_coord_exp_buffer);
1959 av_freep(&s->cpl_coord_mant_buffer);
1960 for (blk = 0; blk < s->num_blocks; blk++) {
1961 AC3Block *block = &s->blocks[blk];
1962 av_freep(&block->mdct_coef);
1963 av_freep(&block->fixed_coef);
1964 av_freep(&block->exp);
1965 av_freep(&block->grouped_exp);
1966 av_freep(&block->psd);
1967 av_freep(&block->band_psd);
1968 av_freep(&block->mask);
1969 av_freep(&block->qmant);
1970 av_freep(&block->cpl_coord_exp);
1971 av_freep(&block->cpl_coord_mant);
1976 av_freep(&avctx->coded_frame);
1982 * Set channel information during initialization.
1984 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1985 int64_t *channel_layout)
1989 if (channels < 1 || channels > AC3_MAX_CHANNELS)
1990 return AVERROR(EINVAL);
1991 if ((uint64_t)*channel_layout > 0x7FF)
1992 return AVERROR(EINVAL);
1993 ch_layout = *channel_layout;
1995 ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1997 s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1998 s->channels = channels;
1999 s->fbw_channels = channels - s->lfe_on;
2000 s->lfe_channel = s->lfe_on ? s->fbw_channels + 1 : -1;
2002 ch_layout -= AV_CH_LOW_FREQUENCY;
2004 switch (ch_layout) {
2005 case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
2006 case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
2007 case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
2008 case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
2009 case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
2010 case AV_CH_LAYOUT_QUAD:
2011 case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
2012 case AV_CH_LAYOUT_5POINT0:
2013 case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
2015 return AVERROR(EINVAL);
2017 s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
2018 s->has_surround = s->channel_mode & 0x04;
2020 s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
2021 *channel_layout = ch_layout;
2023 *channel_layout |= AV_CH_LOW_FREQUENCY;
2029 static av_cold int validate_options(AC3EncodeContext *s)
2031 AVCodecContext *avctx = s->avctx;
2034 /* validate channel layout */
2035 if (!avctx->channel_layout) {
2036 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
2037 "encoder will guess the layout, but it "
2038 "might be incorrect.\n");
2040 ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
2042 av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
2046 /* validate sample rate */
2047 /* note: max_sr could be changed from 2 to 5 for E-AC-3 once we find a
2048 decoder that supports half sample rate so we can validate that
2049 the generated files are correct. */
2050 max_sr = s->eac3 ? 2 : 8;
2051 for (i = 0; i <= max_sr; i++) {
2052 if ((ff_ac3_sample_rate_tab[i % 3] >> (i / 3)) == avctx->sample_rate)
2056 av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
2057 return AVERROR(EINVAL);
2059 s->sample_rate = avctx->sample_rate;
2060 s->bit_alloc.sr_shift = i / 3;
2061 s->bit_alloc.sr_code = i % 3;
2062 s->bitstream_id = s->eac3 ? 16 : 8 + s->bit_alloc.sr_shift;
2064 /* validate bit rate */
2066 int max_br, min_br, wpf, min_br_dist, min_br_code;
2067 int num_blks_code, num_blocks, frame_samples;
2069 /* calculate min/max bitrate */
2070 /* TODO: More testing with 3 and 2 blocks. All E-AC-3 samples I've
2071 found use either 6 blocks or 1 block, even though 2 or 3 blocks
2072 would work as far as the bit rate is concerned. */
2073 for (num_blks_code = 3; num_blks_code >= 0; num_blks_code--) {
2074 num_blocks = ((int[]){ 1, 2, 3, 6 })[num_blks_code];
2075 frame_samples = AC3_BLOCK_SIZE * num_blocks;
2076 max_br = 2048 * s->sample_rate / frame_samples * 16;
2077 min_br = ((s->sample_rate + (frame_samples-1)) / frame_samples) * 16;
2078 if (avctx->bit_rate <= max_br)
2081 if (avctx->bit_rate < min_br || avctx->bit_rate > max_br) {
2082 av_log(avctx, AV_LOG_ERROR, "invalid bit rate. must be %d to %d "
2083 "for this sample rate\n", min_br, max_br);
2084 return AVERROR(EINVAL);
2086 s->num_blks_code = num_blks_code;
2087 s->num_blocks = num_blocks;
2089 /* calculate words-per-frame for the selected bitrate */
2090 wpf = (avctx->bit_rate / 16) * frame_samples / s->sample_rate;
2091 av_assert1(wpf > 0 && wpf <= 2048);
2093 /* find the closest AC-3 bitrate code to the selected bitrate.
2094 this is needed for lookup tables for bandwidth and coupling
2095 parameter selection */
2097 min_br_dist = INT_MAX;
2098 for (i = 0; i < 19; i++) {
2099 int br_dist = abs(ff_ac3_bitrate_tab[i] * 1000 - avctx->bit_rate);
2100 if (br_dist < min_br_dist) {
2101 min_br_dist = br_dist;
2106 /* make sure the minimum frame size is below the average frame size */
2107 s->frame_size_code = min_br_code << 1;
2108 while (wpf > 1 && wpf * s->sample_rate / AC3_FRAME_SIZE * 16 > avctx->bit_rate)
2110 s->frame_size_min = 2 * wpf;
2112 for (i = 0; i < 19; i++) {
2113 if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
2117 av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2118 return AVERROR(EINVAL);
2120 s->frame_size_code = i << 1;
2121 s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2122 s->num_blks_code = 0x3;
2125 s->bit_rate = avctx->bit_rate;
2126 s->frame_size = s->frame_size_min;
2128 /* validate cutoff */
2129 if (avctx->cutoff < 0) {
2130 av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2131 return AVERROR(EINVAL);
2133 s->cutoff = avctx->cutoff;
2134 if (s->cutoff > (s->sample_rate >> 1))
2135 s->cutoff = s->sample_rate >> 1;
2137 ret = ff_ac3_validate_metadata(s);
2141 s->rematrixing_enabled = s->options.stereo_rematrixing &&
2142 (s->channel_mode == AC3_CHMODE_STEREO);
2144 s->cpl_enabled = s->options.channel_coupling &&
2145 s->channel_mode >= AC3_CHMODE_STEREO && !s->fixed_point;
2152 * Set bandwidth for all channels.
2153 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2154 * default value will be used.
2156 static av_cold void set_bandwidth(AC3EncodeContext *s)
2159 int av_uninit(cpl_start);
2162 /* calculate bandwidth based on user-specified cutoff frequency */
2164 fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2165 s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2167 /* use default bandwidth setting */
2168 s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2171 /* set number of coefficients for each channel */
2172 for (ch = 1; ch <= s->fbw_channels; ch++) {
2173 s->start_freq[ch] = 0;
2174 for (blk = 0; blk < s->num_blocks; blk++)
2175 s->blocks[blk].end_freq[ch] = s->bandwidth_code * 3 + 73;
2177 /* LFE channel always has 7 coefs */
2179 s->start_freq[s->lfe_channel] = 0;
2180 for (blk = 0; blk < s->num_blocks; blk++)
2181 s->blocks[blk].end_freq[ch] = 7;
2184 /* initialize coupling strategy */
2185 if (s->cpl_enabled) {
2186 if (s->options.cpl_start >= 0) {
2187 cpl_start = s->options.cpl_start;
2189 cpl_start = ac3_coupling_start_tab[s->channel_mode-2][s->bit_alloc.sr_code][s->frame_size_code/2];
2194 if (s->cpl_enabled) {
2195 int i, cpl_start_band, cpl_end_band;
2196 uint8_t *cpl_band_sizes = s->cpl_band_sizes;
2198 cpl_end_band = s->bandwidth_code / 4 + 3;
2199 cpl_start_band = av_clip(cpl_start, 0, FFMIN(cpl_end_band-1, 15));
2201 s->num_cpl_subbands = cpl_end_band - cpl_start_band;
2203 s->num_cpl_bands = 1;
2204 *cpl_band_sizes = 12;
2205 for (i = cpl_start_band + 1; i < cpl_end_band; i++) {
2206 if (ff_eac3_default_cpl_band_struct[i]) {
2207 *cpl_band_sizes += 12;
2211 *cpl_band_sizes = 12;
2215 s->start_freq[CPL_CH] = cpl_start_band * 12 + 37;
2216 s->cpl_end_freq = cpl_end_band * 12 + 37;
2217 for (blk = 0; blk < s->num_blocks; blk++)
2218 s->blocks[blk].end_freq[CPL_CH] = s->cpl_end_freq;
2223 static av_cold int allocate_buffers(AC3EncodeContext *s)
2225 AVCodecContext *avctx = s->avctx;
2227 int channels = s->channels + 1; /* includes coupling channel */
2228 int channel_blocks = channels * s->num_blocks;
2229 int total_coefs = AC3_MAX_COEFS * channel_blocks;
2231 if (s->allocate_sample_buffers(s))
2234 FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, total_coefs *
2235 sizeof(*s->bap_buffer), alloc_fail);
2236 FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, total_coefs *
2237 sizeof(*s->bap1_buffer), alloc_fail);
2238 FF_ALLOCZ_OR_GOTO(avctx, s->mdct_coef_buffer, total_coefs *
2239 sizeof(*s->mdct_coef_buffer), alloc_fail);
2240 FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, total_coefs *
2241 sizeof(*s->exp_buffer), alloc_fail);
2242 FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, channel_blocks * 128 *
2243 sizeof(*s->grouped_exp_buffer), alloc_fail);
2244 FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, total_coefs *
2245 sizeof(*s->psd_buffer), alloc_fail);
2246 FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, channel_blocks * 64 *
2247 sizeof(*s->band_psd_buffer), alloc_fail);
2248 FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, channel_blocks * 64 *
2249 sizeof(*s->mask_buffer), alloc_fail);
2250 FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, total_coefs *
2251 sizeof(*s->qmant_buffer), alloc_fail);
2252 if (s->cpl_enabled) {
2253 FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_exp_buffer, channel_blocks * 16 *
2254 sizeof(*s->cpl_coord_exp_buffer), alloc_fail);
2255 FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_mant_buffer, channel_blocks * 16 *
2256 sizeof(*s->cpl_coord_mant_buffer), alloc_fail);
2258 for (blk = 0; blk < s->num_blocks; blk++) {
2259 AC3Block *block = &s->blocks[blk];
2260 FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, channels * sizeof(*block->mdct_coef),
2262 FF_ALLOCZ_OR_GOTO(avctx, block->exp, channels * sizeof(*block->exp),
2264 FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, channels * sizeof(*block->grouped_exp),
2266 FF_ALLOCZ_OR_GOTO(avctx, block->psd, channels * sizeof(*block->psd),
2268 FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, channels * sizeof(*block->band_psd),
2270 FF_ALLOCZ_OR_GOTO(avctx, block->mask, channels * sizeof(*block->mask),
2272 FF_ALLOCZ_OR_GOTO(avctx, block->qmant, channels * sizeof(*block->qmant),
2274 if (s->cpl_enabled) {
2275 FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_exp, channels * sizeof(*block->cpl_coord_exp),
2277 FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_mant, channels * sizeof(*block->cpl_coord_mant),
2281 for (ch = 0; ch < channels; ch++) {
2282 /* arrangement: block, channel, coeff */
2283 block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * channels + ch)];
2284 block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
2285 block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * channels + ch)];
2286 block->mask[ch] = &s->mask_buffer [64 * (blk * channels + ch)];
2287 block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
2288 if (s->cpl_enabled) {
2289 block->cpl_coord_exp[ch] = &s->cpl_coord_exp_buffer [16 * (blk * channels + ch)];
2290 block->cpl_coord_mant[ch] = &s->cpl_coord_mant_buffer[16 * (blk * channels + ch)];
2293 /* arrangement: channel, block, coeff */
2294 block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
2295 block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
2299 if (!s->fixed_point) {
2300 FF_ALLOCZ_OR_GOTO(avctx, s->fixed_coef_buffer, total_coefs *
2301 sizeof(*s->fixed_coef_buffer), alloc_fail);
2302 for (blk = 0; blk < s->num_blocks; blk++) {
2303 AC3Block *block = &s->blocks[blk];
2304 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2305 sizeof(*block->fixed_coef), alloc_fail);
2306 for (ch = 0; ch < channels; ch++)
2307 block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
2310 for (blk = 0; blk < s->num_blocks; blk++) {
2311 AC3Block *block = &s->blocks[blk];
2312 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2313 sizeof(*block->fixed_coef), alloc_fail);
2314 for (ch = 0; ch < channels; ch++)
2315 block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2321 return AVERROR(ENOMEM);
2326 * Initialize the encoder.
2328 av_cold int ff_ac3_encode_init(AVCodecContext *avctx)
2330 AC3EncodeContext *s = avctx->priv_data;
2331 int ret, frame_size_58;
2335 s->eac3 = avctx->codec_id == CODEC_ID_EAC3;
2337 ff_ac3_common_init();
2339 ret = validate_options(s);
2343 avctx->frame_size = AC3_BLOCK_SIZE * s->num_blocks;
2345 s->bitstream_mode = avctx->audio_service_type;
2346 if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2347 s->bitstream_mode = 0x7;
2349 s->bits_written = 0;
2350 s->samples_written = 0;
2352 /* calculate crc_inv for both possible frame sizes */
2353 frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
2354 s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2355 if (s->bit_alloc.sr_code == 1) {
2356 frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2357 s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2360 /* set function pointers */
2361 if (CONFIG_AC3_FIXED_ENCODER && s->fixed_point) {
2362 s->mdct_end = ff_ac3_fixed_mdct_end;
2363 s->mdct_init = ff_ac3_fixed_mdct_init;
2364 s->allocate_sample_buffers = ff_ac3_fixed_allocate_sample_buffers;
2365 } else if (CONFIG_AC3_ENCODER || CONFIG_EAC3_ENCODER) {
2366 s->mdct_end = ff_ac3_float_mdct_end;
2367 s->mdct_init = ff_ac3_float_mdct_init;
2368 s->allocate_sample_buffers = ff_ac3_float_allocate_sample_buffers;
2370 if (CONFIG_EAC3_ENCODER && s->eac3)
2371 s->output_frame_header = ff_eac3_output_frame_header;
2373 s->output_frame_header = ac3_output_frame_header;
2381 ret = s->mdct_init(s);
2385 ret = allocate_buffers(s);
2389 avctx->coded_frame= avcodec_alloc_frame();
2391 dsputil_init(&s->dsp, avctx);
2392 ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2398 ff_ac3_encode_close(avctx);