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;
763 if (s->channel_mode > AC3_CHMODE_MONO) {
765 for (blk = 1; blk < s->num_blocks; blk++) {
766 AC3Block *block = &s->blocks[blk];
768 if (block->new_cpl_strategy)
772 /* coupling exponent strategy */
774 if (s->use_frame_exp_strategy) {
775 frame_bits += 5 * s->cpl_on;
777 for (blk = 0; blk < s->num_blocks; blk++)
778 frame_bits += 2 * s->blocks[blk].cpl_in_use;
782 if (opt->audio_production_info)
784 if (s->bitstream_id == 6) {
785 if (opt->extended_bsi_1)
787 if (opt->extended_bsi_2)
793 for (blk = 0; blk < s->num_blocks; blk++) {
794 AC3Block *block = &s->blocks[blk];
796 /* coupling strategy */
799 if (block->new_cpl_strategy) {
802 if (block->cpl_in_use) {
805 if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO)
806 frame_bits += s->fbw_channels;
807 if (s->channel_mode == AC3_CHMODE_STEREO)
813 frame_bits += s->num_cpl_subbands - 1;
817 /* coupling coordinates */
818 if (block->cpl_in_use) {
819 for (ch = 1; ch <= s->fbw_channels; ch++) {
820 if (block->channel_in_cpl[ch]) {
821 if (!s->eac3 || block->new_cpl_coords != 2)
823 if (block->new_cpl_coords) {
825 frame_bits += (4 + 4) * s->num_cpl_bands;
831 /* stereo rematrixing */
832 if (s->channel_mode == AC3_CHMODE_STEREO) {
833 if (!s->eac3 || blk > 0)
835 if (s->blocks[blk].new_rematrixing_strategy)
836 frame_bits += block->num_rematrixing_bands;
839 /* bandwidth codes & gain range */
840 for (ch = 1; ch <= s->fbw_channels; ch++) {
841 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
842 if (!block->channel_in_cpl[ch])
848 /* coupling exponent strategy */
849 if (!s->eac3 && block->cpl_in_use)
852 /* snr offsets and fast gain codes */
855 if (block->new_snr_offsets)
856 frame_bits += 6 + (s->channels + block->cpl_in_use) * (4 + 3);
859 /* coupling leak info */
860 if (block->cpl_in_use) {
861 if (!s->eac3 || block->new_cpl_leak != 2)
863 if (block->new_cpl_leak)
868 s->frame_bits = s->frame_bits_fixed + frame_bits;
873 * Calculate masking curve based on the final exponents.
874 * Also calculate the power spectral densities to use in future calculations.
876 static void bit_alloc_masking(AC3EncodeContext *s)
880 for (blk = 0; blk < s->num_blocks; blk++) {
881 AC3Block *block = &s->blocks[blk];
882 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
883 /* We only need psd and mask for calculating bap.
884 Since we currently do not calculate bap when exponent
885 strategy is EXP_REUSE we do not need to calculate psd or mask. */
886 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
887 ff_ac3_bit_alloc_calc_psd(block->exp[ch], s->start_freq[ch],
888 block->end_freq[ch], block->psd[ch],
889 block->band_psd[ch]);
890 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
891 s->start_freq[ch], block->end_freq[ch],
892 ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
893 ch == s->lfe_channel,
894 DBA_NONE, 0, NULL, NULL, NULL,
903 * Ensure that bap for each block and channel point to the current bap_buffer.
904 * They may have been switched during the bit allocation search.
906 static void reset_block_bap(AC3EncodeContext *s)
911 if (s->ref_bap[0][0] == s->bap_buffer && s->ref_bap_set)
914 ref_bap = s->bap_buffer;
915 for (ch = 0; ch <= s->channels; ch++) {
916 for (blk = 0; blk < s->num_blocks; blk++)
917 s->ref_bap[ch][blk] = ref_bap + AC3_MAX_COEFS * s->exp_ref_block[ch][blk];
918 ref_bap += AC3_MAX_COEFS * s->num_blocks;
925 * Initialize mantissa counts.
926 * These are set so that they are padded to the next whole group size when bits
927 * are counted in compute_mantissa_size.
929 static void count_mantissa_bits_init(uint16_t mant_cnt[AC3_MAX_BLOCKS][16])
933 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
934 memset(mant_cnt[blk], 0, sizeof(mant_cnt[blk]));
935 mant_cnt[blk][1] = mant_cnt[blk][2] = 2;
936 mant_cnt[blk][4] = 1;
942 * Update mantissa bit counts for all blocks in 1 channel in a given bandwidth
945 static void count_mantissa_bits_update_ch(AC3EncodeContext *s, int ch,
946 uint16_t mant_cnt[AC3_MAX_BLOCKS][16],
951 for (blk = 0; blk < s->num_blocks; blk++) {
952 AC3Block *block = &s->blocks[blk];
953 if (ch == CPL_CH && !block->cpl_in_use)
955 s->ac3dsp.update_bap_counts(mant_cnt[blk],
956 s->ref_bap[ch][blk] + start,
957 FFMIN(end, block->end_freq[ch]) - start);
963 * Count the number of mantissa bits in the frame based on the bap values.
965 static int count_mantissa_bits(AC3EncodeContext *s)
967 int ch, max_end_freq;
968 LOCAL_ALIGNED_16(uint16_t, mant_cnt, [AC3_MAX_BLOCKS], [16]);
970 count_mantissa_bits_init(mant_cnt);
972 max_end_freq = s->bandwidth_code * 3 + 73;
973 for (ch = !s->cpl_enabled; ch <= s->channels; ch++)
974 count_mantissa_bits_update_ch(s, ch, mant_cnt, s->start_freq[ch],
977 return s->ac3dsp.compute_mantissa_size(mant_cnt);
982 * Run the bit allocation with a given SNR offset.
983 * This calculates the bit allocation pointers that will be used to determine
984 * the quantization of each mantissa.
985 * @return the number of bits needed for mantissas if the given SNR offset is
988 static int bit_alloc(AC3EncodeContext *s, int snr_offset)
992 snr_offset = (snr_offset - 240) << 2;
995 for (blk = 0; blk < s->num_blocks; blk++) {
996 AC3Block *block = &s->blocks[blk];
998 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
999 /* Currently the only bit allocation parameters which vary across
1000 blocks within a frame are the exponent values. We can take
1001 advantage of that by reusing the bit allocation pointers
1002 whenever we reuse exponents. */
1003 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1004 s->ac3dsp.bit_alloc_calc_bap(block->mask[ch], block->psd[ch],
1005 s->start_freq[ch], block->end_freq[ch],
1006 snr_offset, s->bit_alloc.floor,
1007 ff_ac3_bap_tab, s->ref_bap[ch][blk]);
1011 return count_mantissa_bits(s);
1016 * Constant bitrate bit allocation search.
1017 * Find the largest SNR offset that will allow data to fit in the frame.
1019 static int cbr_bit_allocation(AC3EncodeContext *s)
1023 int snr_offset, snr_incr;
1025 bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1027 return AVERROR(EINVAL);
1029 snr_offset = s->coarse_snr_offset << 4;
1031 /* if previous frame SNR offset was 1023, check if current frame can also
1032 use SNR offset of 1023. if so, skip the search. */
1033 if ((snr_offset | s->fine_snr_offset[1]) == 1023) {
1034 if (bit_alloc(s, 1023) <= bits_left)
1038 while (snr_offset >= 0 &&
1039 bit_alloc(s, snr_offset) > bits_left) {
1043 return AVERROR(EINVAL);
1045 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1046 for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1047 while (snr_offset + snr_incr <= 1023 &&
1048 bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1049 snr_offset += snr_incr;
1050 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1053 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1056 s->coarse_snr_offset = snr_offset >> 4;
1057 for (ch = !s->cpl_on; ch <= s->channels; ch++)
1058 s->fine_snr_offset[ch] = snr_offset & 0xF;
1065 * Perform bit allocation search.
1066 * Finds the SNR offset value that maximizes quality and fits in the specified
1067 * frame size. Output is the SNR offset and a set of bit allocation pointers
1068 * used to quantize the mantissas.
1070 int ff_ac3_compute_bit_allocation(AC3EncodeContext *s)
1072 count_frame_bits(s);
1074 bit_alloc_masking(s);
1076 return cbr_bit_allocation(s);
1081 * Symmetric quantization on 'levels' levels.
1083 static inline int sym_quant(int c, int e, int levels)
1085 int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1086 av_assert2(v >= 0 && v < levels);
1092 * Asymmetric quantization on 2^qbits levels.
1094 static inline int asym_quant(int c, int e, int qbits)
1098 c = (((c << e) >> (24 - qbits)) + 1) >> 1;
1099 m = (1 << (qbits-1));
1102 av_assert2(c >= -m);
1108 * Quantize a set of mantissas for a single channel in a single block.
1110 static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1111 uint8_t *exp, uint8_t *bap,
1112 int16_t *qmant, int start_freq,
1117 for (i = start_freq; i < end_freq; i++) {
1119 int c = fixed_coef[i];
1127 v = sym_quant(c, e, 3);
1128 switch (s->mant1_cnt) {
1130 s->qmant1_ptr = &qmant[i];
1135 *s->qmant1_ptr += 3 * v;
1140 *s->qmant1_ptr += v;
1147 v = sym_quant(c, e, 5);
1148 switch (s->mant2_cnt) {
1150 s->qmant2_ptr = &qmant[i];
1155 *s->qmant2_ptr += 5 * v;
1160 *s->qmant2_ptr += v;
1167 v = sym_quant(c, e, 7);
1170 v = sym_quant(c, e, 11);
1171 switch (s->mant4_cnt) {
1173 s->qmant4_ptr = &qmant[i];
1178 *s->qmant4_ptr += v;
1185 v = sym_quant(c, e, 15);
1188 v = asym_quant(c, e, 14);
1191 v = asym_quant(c, e, 16);
1194 v = asym_quant(c, e, b - 1);
1203 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1205 void ff_ac3_quantize_mantissas(AC3EncodeContext *s)
1207 int blk, ch, ch0=0, got_cpl;
1209 for (blk = 0; blk < s->num_blocks; blk++) {
1210 AC3Block *block = &s->blocks[blk];
1213 got_cpl = !block->cpl_in_use;
1214 for (ch = 1; ch <= s->channels; ch++) {
1215 if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1220 quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1221 s->blocks[s->exp_ref_block[ch][blk]].exp[ch],
1222 s->ref_bap[ch][blk], block->qmant[ch],
1223 s->start_freq[ch], block->end_freq[ch]);
1232 * Write the AC-3 frame header to the output bitstream.
1234 static void ac3_output_frame_header(AC3EncodeContext *s)
1236 AC3EncOptions *opt = &s->options;
1238 put_bits(&s->pb, 16, 0x0b77); /* frame header */
1239 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
1240 put_bits(&s->pb, 2, s->bit_alloc.sr_code);
1241 put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1242 put_bits(&s->pb, 5, s->bitstream_id);
1243 put_bits(&s->pb, 3, s->bitstream_mode);
1244 put_bits(&s->pb, 3, s->channel_mode);
1245 if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1246 put_bits(&s->pb, 2, s->center_mix_level);
1247 if (s->channel_mode & 0x04)
1248 put_bits(&s->pb, 2, s->surround_mix_level);
1249 if (s->channel_mode == AC3_CHMODE_STEREO)
1250 put_bits(&s->pb, 2, opt->dolby_surround_mode);
1251 put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1252 put_bits(&s->pb, 5, -opt->dialogue_level);
1253 put_bits(&s->pb, 1, 0); /* no compression control word */
1254 put_bits(&s->pb, 1, 0); /* no lang code */
1255 put_bits(&s->pb, 1, opt->audio_production_info);
1256 if (opt->audio_production_info) {
1257 put_bits(&s->pb, 5, opt->mixing_level - 80);
1258 put_bits(&s->pb, 2, opt->room_type);
1260 put_bits(&s->pb, 1, opt->copyright);
1261 put_bits(&s->pb, 1, opt->original);
1262 if (s->bitstream_id == 6) {
1263 /* alternate bit stream syntax */
1264 put_bits(&s->pb, 1, opt->extended_bsi_1);
1265 if (opt->extended_bsi_1) {
1266 put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1267 put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1268 put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1269 put_bits(&s->pb, 3, s->loro_center_mix_level);
1270 put_bits(&s->pb, 3, s->loro_surround_mix_level);
1272 put_bits(&s->pb, 1, opt->extended_bsi_2);
1273 if (opt->extended_bsi_2) {
1274 put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1275 put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1276 put_bits(&s->pb, 1, opt->ad_converter_type);
1277 put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
1280 put_bits(&s->pb, 1, 0); /* no time code 1 */
1281 put_bits(&s->pb, 1, 0); /* no time code 2 */
1283 put_bits(&s->pb, 1, 0); /* no additional bit stream info */
1288 * Write one audio block to the output bitstream.
1290 static void output_audio_block(AC3EncodeContext *s, int blk)
1292 int ch, i, baie, bnd, got_cpl;
1294 AC3Block *block = &s->blocks[blk];
1296 /* block switching */
1298 for (ch = 0; ch < s->fbw_channels; ch++)
1299 put_bits(&s->pb, 1, 0);
1304 for (ch = 0; ch < s->fbw_channels; ch++)
1305 put_bits(&s->pb, 1, 1);
1308 /* dynamic range codes */
1309 put_bits(&s->pb, 1, 0);
1311 /* spectral extension */
1313 put_bits(&s->pb, 1, 0);
1315 /* channel coupling */
1317 put_bits(&s->pb, 1, block->new_cpl_strategy);
1318 if (block->new_cpl_strategy) {
1320 put_bits(&s->pb, 1, block->cpl_in_use);
1321 if (block->cpl_in_use) {
1322 int start_sub, end_sub;
1324 put_bits(&s->pb, 1, 0); /* enhanced coupling */
1325 if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO) {
1326 for (ch = 1; ch <= s->fbw_channels; ch++)
1327 put_bits(&s->pb, 1, block->channel_in_cpl[ch]);
1329 if (s->channel_mode == AC3_CHMODE_STEREO)
1330 put_bits(&s->pb, 1, 0); /* phase flags in use */
1331 start_sub = (s->start_freq[CPL_CH] - 37) / 12;
1332 end_sub = (s->cpl_end_freq - 37) / 12;
1333 put_bits(&s->pb, 4, start_sub);
1334 put_bits(&s->pb, 4, end_sub - 3);
1335 /* coupling band structure */
1337 put_bits(&s->pb, 1, 0); /* use default */
1339 for (bnd = start_sub+1; bnd < end_sub; bnd++)
1340 put_bits(&s->pb, 1, ff_eac3_default_cpl_band_struct[bnd]);
1345 /* coupling coordinates */
1346 if (block->cpl_in_use) {
1347 for (ch = 1; ch <= s->fbw_channels; ch++) {
1348 if (block->channel_in_cpl[ch]) {
1349 if (!s->eac3 || block->new_cpl_coords != 2)
1350 put_bits(&s->pb, 1, block->new_cpl_coords);
1351 if (block->new_cpl_coords) {
1352 put_bits(&s->pb, 2, block->cpl_master_exp[ch]);
1353 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
1354 put_bits(&s->pb, 4, block->cpl_coord_exp [ch][bnd]);
1355 put_bits(&s->pb, 4, block->cpl_coord_mant[ch][bnd]);
1362 /* stereo rematrixing */
1363 if (s->channel_mode == AC3_CHMODE_STEREO) {
1364 if (!s->eac3 || blk > 0)
1365 put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1366 if (block->new_rematrixing_strategy) {
1367 /* rematrixing flags */
1368 for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++)
1369 put_bits(&s->pb, 1, block->rematrixing_flags[bnd]);
1373 /* exponent strategy */
1375 for (ch = !block->cpl_in_use; ch <= s->fbw_channels; ch++)
1376 put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1378 put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1382 for (ch = 1; ch <= s->fbw_channels; ch++) {
1383 if (s->exp_strategy[ch][blk] != EXP_REUSE && !block->channel_in_cpl[ch])
1384 put_bits(&s->pb, 6, s->bandwidth_code);
1388 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1390 int cpl = (ch == CPL_CH);
1392 if (s->exp_strategy[ch][blk] == EXP_REUSE)
1396 put_bits(&s->pb, 4, block->grouped_exp[ch][0] >> cpl);
1398 /* exponent groups */
1399 nb_groups = exponent_group_tab[cpl][s->exp_strategy[ch][blk]-1][block->end_freq[ch]-s->start_freq[ch]];
1400 for (i = 1; i <= nb_groups; i++)
1401 put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1403 /* gain range info */
1404 if (ch != s->lfe_channel && !cpl)
1405 put_bits(&s->pb, 2, 0);
1408 /* bit allocation info */
1411 put_bits(&s->pb, 1, baie);
1413 put_bits(&s->pb, 2, s->slow_decay_code);
1414 put_bits(&s->pb, 2, s->fast_decay_code);
1415 put_bits(&s->pb, 2, s->slow_gain_code);
1416 put_bits(&s->pb, 2, s->db_per_bit_code);
1417 put_bits(&s->pb, 3, s->floor_code);
1423 put_bits(&s->pb, 1, block->new_snr_offsets);
1424 if (block->new_snr_offsets) {
1425 put_bits(&s->pb, 6, s->coarse_snr_offset);
1426 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1427 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1428 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1432 put_bits(&s->pb, 1, 0); /* no converter snr offset */
1436 if (block->cpl_in_use) {
1437 if (!s->eac3 || block->new_cpl_leak != 2)
1438 put_bits(&s->pb, 1, block->new_cpl_leak);
1439 if (block->new_cpl_leak) {
1440 put_bits(&s->pb, 3, s->bit_alloc.cpl_fast_leak);
1441 put_bits(&s->pb, 3, s->bit_alloc.cpl_slow_leak);
1446 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1447 put_bits(&s->pb, 1, 0); /* no data to skip */
1451 got_cpl = !block->cpl_in_use;
1452 for (ch = 1; ch <= s->channels; ch++) {
1455 if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1460 for (i = s->start_freq[ch]; i < block->end_freq[ch]; i++) {
1461 q = block->qmant[ch][i];
1462 b = s->ref_bap[ch][blk][i];
1465 case 1: if (q != 128) put_bits (&s->pb, 5, q); break;
1466 case 2: if (q != 128) put_bits (&s->pb, 7, q); break;
1467 case 3: put_sbits(&s->pb, 3, q); break;
1468 case 4: if (q != 128) put_bits (&s->pb, 7, q); break;
1469 case 14: put_sbits(&s->pb, 14, q); break;
1470 case 15: put_sbits(&s->pb, 16, q); break;
1471 default: put_sbits(&s->pb, b-1, q); break;
1480 /** CRC-16 Polynomial */
1481 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1484 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1501 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1507 r = mul_poly(r, a, poly);
1508 a = mul_poly(a, a, poly);
1516 * Fill the end of the frame with 0's and compute the two CRCs.
1518 static void output_frame_end(AC3EncodeContext *s)
1520 const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1521 int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1524 frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1526 /* pad the remainder of the frame with zeros */
1527 av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1528 flush_put_bits(&s->pb);
1530 pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1531 av_assert2(pad_bytes >= 0);
1533 memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1537 crc2_partial = av_crc(crc_ctx, 0, frame + 2, s->frame_size - 5);
1540 /* this is not so easy because it is at the beginning of the data... */
1541 crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1542 crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1543 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1544 AV_WB16(frame + 2, crc1);
1547 crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1548 s->frame_size - frame_size_58 - 3);
1550 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1551 /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1552 if (crc2 == 0x770B) {
1553 frame[s->frame_size - 3] ^= 0x1;
1554 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1556 crc2 = av_bswap16(crc2);
1557 AV_WB16(frame + s->frame_size - 2, crc2);
1562 * Write the frame to the output bitstream.
1564 void ff_ac3_output_frame(AC3EncodeContext *s, unsigned char *frame)
1568 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1570 s->output_frame_header(s);
1572 for (blk = 0; blk < s->num_blocks; blk++)
1573 output_audio_block(s, blk);
1575 output_frame_end(s);
1579 static void dprint_options(AC3EncodeContext *s)
1582 AVCodecContext *avctx = s->avctx;
1583 AC3EncOptions *opt = &s->options;
1586 switch (s->bitstream_id) {
1587 case 6: av_strlcpy(strbuf, "AC-3 (alt syntax)", 32); break;
1588 case 8: av_strlcpy(strbuf, "AC-3 (standard)", 32); break;
1589 case 9: av_strlcpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
1590 case 10: av_strlcpy(strbuf, "AC-3 (dnet quater-rate)", 32); break;
1591 case 16: av_strlcpy(strbuf, "E-AC-3 (enhanced)", 32); break;
1592 default: snprintf(strbuf, 32, "ERROR");
1594 av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
1595 av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
1596 av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
1597 av_dlog(avctx, "channel_layout: %s\n", strbuf);
1598 av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
1599 av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
1600 av_dlog(avctx, "blocks/frame: %d (code=%d)\n", s->num_blocks, s->num_blks_code);
1602 av_dlog(avctx, "cutoff: %d\n", s->cutoff);
1604 av_dlog(avctx, "per_frame_metadata: %s\n",
1605 opt->allow_per_frame_metadata?"on":"off");
1607 av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
1608 s->center_mix_level);
1610 av_dlog(avctx, "center_mixlev: {not written}\n");
1611 if (s->has_surround)
1612 av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
1613 s->surround_mix_level);
1615 av_dlog(avctx, "surround_mixlev: {not written}\n");
1616 if (opt->audio_production_info) {
1617 av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
1618 switch (opt->room_type) {
1619 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1620 case 1: av_strlcpy(strbuf, "large", 32); break;
1621 case 2: av_strlcpy(strbuf, "small", 32); break;
1622 default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
1624 av_dlog(avctx, "room_type: %s\n", strbuf);
1626 av_dlog(avctx, "mixing_level: {not written}\n");
1627 av_dlog(avctx, "room_type: {not written}\n");
1629 av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
1630 av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
1631 if (s->channel_mode == AC3_CHMODE_STEREO) {
1632 switch (opt->dolby_surround_mode) {
1633 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1634 case 1: av_strlcpy(strbuf, "on", 32); break;
1635 case 2: av_strlcpy(strbuf, "off", 32); break;
1636 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
1638 av_dlog(avctx, "dsur_mode: %s\n", strbuf);
1640 av_dlog(avctx, "dsur_mode: {not written}\n");
1642 av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
1644 if (s->bitstream_id == 6) {
1645 if (opt->extended_bsi_1) {
1646 switch (opt->preferred_stereo_downmix) {
1647 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1648 case 1: av_strlcpy(strbuf, "ltrt", 32); break;
1649 case 2: av_strlcpy(strbuf, "loro", 32); break;
1650 default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
1652 av_dlog(avctx, "dmix_mode: %s\n", strbuf);
1653 av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
1654 opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
1655 av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
1656 opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
1657 av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
1658 opt->loro_center_mix_level, s->loro_center_mix_level);
1659 av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
1660 opt->loro_surround_mix_level, s->loro_surround_mix_level);
1662 av_dlog(avctx, "extended bitstream info 1: {not written}\n");
1664 if (opt->extended_bsi_2) {
1665 switch (opt->dolby_surround_ex_mode) {
1666 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1667 case 1: av_strlcpy(strbuf, "on", 32); break;
1668 case 2: av_strlcpy(strbuf, "off", 32); break;
1669 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
1671 av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
1672 switch (opt->dolby_headphone_mode) {
1673 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1674 case 1: av_strlcpy(strbuf, "on", 32); break;
1675 case 2: av_strlcpy(strbuf, "off", 32); break;
1676 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
1678 av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
1680 switch (opt->ad_converter_type) {
1681 case 0: av_strlcpy(strbuf, "standard", 32); break;
1682 case 1: av_strlcpy(strbuf, "hdcd", 32); break;
1683 default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
1685 av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
1687 av_dlog(avctx, "extended bitstream info 2: {not written}\n");
1694 #define FLT_OPTION_THRESHOLD 0.01
1696 static int validate_float_option(float v, const float *v_list, int v_list_size)
1700 for (i = 0; i < v_list_size; i++) {
1701 if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
1702 v > (v_list[i] - FLT_OPTION_THRESHOLD))
1705 if (i == v_list_size)
1712 static void validate_mix_level(void *log_ctx, const char *opt_name,
1713 float *opt_param, const float *list,
1714 int list_size, int default_value, int min_value,
1717 int mixlev = validate_float_option(*opt_param, list, list_size);
1718 if (mixlev < min_value) {
1719 mixlev = default_value;
1720 if (*opt_param >= 0.0) {
1721 av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
1722 "default value: %0.3f\n", opt_name, list[mixlev]);
1725 *opt_param = list[mixlev];
1726 *ctx_param = mixlev;
1731 * Validate metadata options as set by AVOption system.
1732 * These values can optionally be changed per-frame.
1734 int ff_ac3_validate_metadata(AC3EncodeContext *s)
1736 AVCodecContext *avctx = s->avctx;
1737 AC3EncOptions *opt = &s->options;
1739 /* validate mixing levels */
1740 if (s->has_center) {
1741 validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
1742 cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
1743 &s->center_mix_level);
1745 if (s->has_surround) {
1746 validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
1747 surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
1748 &s->surround_mix_level);
1751 /* set audio production info flag */
1752 if (opt->mixing_level >= 0 || opt->room_type >= 0) {
1753 if (opt->mixing_level < 0) {
1754 av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
1755 "room_type is set\n");
1756 return AVERROR(EINVAL);
1758 if (opt->mixing_level < 80) {
1759 av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
1760 "80dB and 111dB\n");
1761 return AVERROR(EINVAL);
1763 /* default room type */
1764 if (opt->room_type < 0)
1766 opt->audio_production_info = 1;
1768 opt->audio_production_info = 0;
1771 /* set extended bsi 1 flag */
1772 if ((s->has_center || s->has_surround) &&
1773 (opt->preferred_stereo_downmix >= 0 ||
1774 opt->ltrt_center_mix_level >= 0 ||
1775 opt->ltrt_surround_mix_level >= 0 ||
1776 opt->loro_center_mix_level >= 0 ||
1777 opt->loro_surround_mix_level >= 0)) {
1778 /* default preferred stereo downmix */
1779 if (opt->preferred_stereo_downmix < 0)
1780 opt->preferred_stereo_downmix = 0;
1781 /* validate Lt/Rt center mix level */
1782 validate_mix_level(avctx, "ltrt_center_mix_level",
1783 &opt->ltrt_center_mix_level, extmixlev_options,
1784 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1785 &s->ltrt_center_mix_level);
1786 /* validate Lt/Rt surround mix level */
1787 validate_mix_level(avctx, "ltrt_surround_mix_level",
1788 &opt->ltrt_surround_mix_level, extmixlev_options,
1789 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1790 &s->ltrt_surround_mix_level);
1791 /* validate Lo/Ro center mix level */
1792 validate_mix_level(avctx, "loro_center_mix_level",
1793 &opt->loro_center_mix_level, extmixlev_options,
1794 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1795 &s->loro_center_mix_level);
1796 /* validate Lo/Ro surround mix level */
1797 validate_mix_level(avctx, "loro_surround_mix_level",
1798 &opt->loro_surround_mix_level, extmixlev_options,
1799 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1800 &s->loro_surround_mix_level);
1801 opt->extended_bsi_1 = 1;
1803 opt->extended_bsi_1 = 0;
1806 /* set extended bsi 2 flag */
1807 if (opt->dolby_surround_ex_mode >= 0 ||
1808 opt->dolby_headphone_mode >= 0 ||
1809 opt->ad_converter_type >= 0) {
1810 /* default dolby surround ex mode */
1811 if (opt->dolby_surround_ex_mode < 0)
1812 opt->dolby_surround_ex_mode = 0;
1813 /* default dolby headphone mode */
1814 if (opt->dolby_headphone_mode < 0)
1815 opt->dolby_headphone_mode = 0;
1816 /* default A/D converter type */
1817 if (opt->ad_converter_type < 0)
1818 opt->ad_converter_type = 0;
1819 opt->extended_bsi_2 = 1;
1821 opt->extended_bsi_2 = 0;
1824 /* set bitstream id for alternate bitstream syntax */
1825 if (opt->extended_bsi_1 || opt->extended_bsi_2) {
1826 if (s->bitstream_id > 8 && s->bitstream_id < 11) {
1827 static int warn_once = 1;
1829 av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
1830 "not compatible with reduced samplerates. writing of "
1831 "extended bitstream information will be disabled.\n");
1835 s->bitstream_id = 6;
1844 * Finalize encoding and free any memory allocated by the encoder.
1846 av_cold int ff_ac3_encode_close(AVCodecContext *avctx)
1849 AC3EncodeContext *s = avctx->priv_data;
1851 av_freep(&s->windowed_samples);
1852 for (ch = 0; ch < s->channels; ch++)
1853 av_freep(&s->planar_samples[ch]);
1854 av_freep(&s->planar_samples);
1855 av_freep(&s->bap_buffer);
1856 av_freep(&s->bap1_buffer);
1857 av_freep(&s->mdct_coef_buffer);
1858 av_freep(&s->fixed_coef_buffer);
1859 av_freep(&s->exp_buffer);
1860 av_freep(&s->grouped_exp_buffer);
1861 av_freep(&s->psd_buffer);
1862 av_freep(&s->band_psd_buffer);
1863 av_freep(&s->mask_buffer);
1864 av_freep(&s->qmant_buffer);
1865 av_freep(&s->cpl_coord_exp_buffer);
1866 av_freep(&s->cpl_coord_mant_buffer);
1867 for (blk = 0; blk < s->num_blocks; blk++) {
1868 AC3Block *block = &s->blocks[blk];
1869 av_freep(&block->mdct_coef);
1870 av_freep(&block->fixed_coef);
1871 av_freep(&block->exp);
1872 av_freep(&block->grouped_exp);
1873 av_freep(&block->psd);
1874 av_freep(&block->band_psd);
1875 av_freep(&block->mask);
1876 av_freep(&block->qmant);
1877 av_freep(&block->cpl_coord_exp);
1878 av_freep(&block->cpl_coord_mant);
1883 av_freep(&avctx->coded_frame);
1889 * Set channel information during initialization.
1891 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1892 int64_t *channel_layout)
1896 if (channels < 1 || channels > AC3_MAX_CHANNELS)
1897 return AVERROR(EINVAL);
1898 if ((uint64_t)*channel_layout > 0x7FF)
1899 return AVERROR(EINVAL);
1900 ch_layout = *channel_layout;
1902 ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1904 s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1905 s->channels = channels;
1906 s->fbw_channels = channels - s->lfe_on;
1907 s->lfe_channel = s->lfe_on ? s->fbw_channels + 1 : -1;
1909 ch_layout -= AV_CH_LOW_FREQUENCY;
1911 switch (ch_layout) {
1912 case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
1913 case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
1914 case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
1915 case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
1916 case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
1917 case AV_CH_LAYOUT_QUAD:
1918 case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
1919 case AV_CH_LAYOUT_5POINT0:
1920 case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
1922 return AVERROR(EINVAL);
1924 s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
1925 s->has_surround = s->channel_mode & 0x04;
1927 s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1928 *channel_layout = ch_layout;
1930 *channel_layout |= AV_CH_LOW_FREQUENCY;
1936 static av_cold int validate_options(AC3EncodeContext *s)
1938 AVCodecContext *avctx = s->avctx;
1941 /* validate channel layout */
1942 if (!avctx->channel_layout) {
1943 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1944 "encoder will guess the layout, but it "
1945 "might be incorrect.\n");
1947 ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1949 av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1953 /* validate sample rate */
1954 /* note: max_sr could be changed from 2 to 5 for E-AC-3 once we find a
1955 decoder that supports half sample rate so we can validate that
1956 the generated files are correct. */
1957 max_sr = s->eac3 ? 2 : 8;
1958 for (i = 0; i <= max_sr; i++) {
1959 if ((ff_ac3_sample_rate_tab[i % 3] >> (i / 3)) == avctx->sample_rate)
1963 av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1964 return AVERROR(EINVAL);
1966 s->sample_rate = avctx->sample_rate;
1967 s->bit_alloc.sr_shift = i / 3;
1968 s->bit_alloc.sr_code = i % 3;
1969 s->bitstream_id = s->eac3 ? 16 : 8 + s->bit_alloc.sr_shift;
1971 /* validate bit rate */
1973 int max_br, min_br, wpf, min_br_dist, min_br_code;
1974 int num_blks_code, num_blocks, frame_samples;
1976 /* calculate min/max bitrate */
1977 /* TODO: More testing with 3 and 2 blocks. All E-AC-3 samples I've
1978 found use either 6 blocks or 1 block, even though 2 or 3 blocks
1979 would work as far as the bit rate is concerned. */
1980 for (num_blks_code = 3; num_blks_code >= 0; num_blks_code--) {
1981 num_blocks = ((int[]){ 1, 2, 3, 6 })[num_blks_code];
1982 frame_samples = AC3_BLOCK_SIZE * num_blocks;
1983 max_br = 2048 * s->sample_rate / frame_samples * 16;
1984 min_br = ((s->sample_rate + (frame_samples-1)) / frame_samples) * 16;
1985 if (avctx->bit_rate <= max_br)
1988 if (avctx->bit_rate < min_br || avctx->bit_rate > max_br) {
1989 av_log(avctx, AV_LOG_ERROR, "invalid bit rate. must be %d to %d "
1990 "for this sample rate\n", min_br, max_br);
1991 return AVERROR(EINVAL);
1993 s->num_blks_code = num_blks_code;
1994 s->num_blocks = num_blocks;
1996 /* calculate words-per-frame for the selected bitrate */
1997 wpf = (avctx->bit_rate / 16) * frame_samples / s->sample_rate;
1998 av_assert1(wpf > 0 && wpf <= 2048);
2000 /* find the closest AC-3 bitrate code to the selected bitrate.
2001 this is needed for lookup tables for bandwidth and coupling
2002 parameter selection */
2004 min_br_dist = INT_MAX;
2005 for (i = 0; i < 19; i++) {
2006 int br_dist = abs(ff_ac3_bitrate_tab[i] * 1000 - avctx->bit_rate);
2007 if (br_dist < min_br_dist) {
2008 min_br_dist = br_dist;
2013 /* make sure the minimum frame size is below the average frame size */
2014 s->frame_size_code = min_br_code << 1;
2015 while (wpf > 1 && wpf * s->sample_rate / AC3_FRAME_SIZE * 16 > avctx->bit_rate)
2017 s->frame_size_min = 2 * wpf;
2019 for (i = 0; i < 19; i++) {
2020 if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
2024 av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2025 return AVERROR(EINVAL);
2027 s->frame_size_code = i << 1;
2028 s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2029 s->num_blks_code = 0x3;
2032 s->bit_rate = avctx->bit_rate;
2033 s->frame_size = s->frame_size_min;
2035 /* validate cutoff */
2036 if (avctx->cutoff < 0) {
2037 av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2038 return AVERROR(EINVAL);
2040 s->cutoff = avctx->cutoff;
2041 if (s->cutoff > (s->sample_rate >> 1))
2042 s->cutoff = s->sample_rate >> 1;
2044 /* validate audio service type / channels combination */
2045 if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
2046 avctx->channels == 1) ||
2047 ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
2048 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
2049 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
2050 && avctx->channels > 1)) {
2051 av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
2052 "specified number of channels\n");
2053 return AVERROR(EINVAL);
2057 ret = ff_ac3_validate_metadata(s);
2062 s->rematrixing_enabled = s->options.stereo_rematrixing &&
2063 (s->channel_mode == AC3_CHMODE_STEREO);
2065 s->cpl_enabled = s->options.channel_coupling &&
2066 s->channel_mode >= AC3_CHMODE_STEREO && !s->fixed_point;
2073 * Set bandwidth for all channels.
2074 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2075 * default value will be used.
2077 static av_cold void set_bandwidth(AC3EncodeContext *s)
2080 int av_uninit(cpl_start);
2083 /* calculate bandwidth based on user-specified cutoff frequency */
2085 fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2086 s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2088 /* use default bandwidth setting */
2089 s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2092 /* set number of coefficients for each channel */
2093 for (ch = 1; ch <= s->fbw_channels; ch++) {
2094 s->start_freq[ch] = 0;
2095 for (blk = 0; blk < s->num_blocks; blk++)
2096 s->blocks[blk].end_freq[ch] = s->bandwidth_code * 3 + 73;
2098 /* LFE channel always has 7 coefs */
2100 s->start_freq[s->lfe_channel] = 0;
2101 for (blk = 0; blk < s->num_blocks; blk++)
2102 s->blocks[blk].end_freq[ch] = 7;
2105 /* initialize coupling strategy */
2106 if (s->cpl_enabled) {
2107 if (s->options.cpl_start >= 0) {
2108 cpl_start = s->options.cpl_start;
2110 cpl_start = ac3_coupling_start_tab[s->channel_mode-2][s->bit_alloc.sr_code][s->frame_size_code/2];
2115 if (s->cpl_enabled) {
2116 int i, cpl_start_band, cpl_end_band;
2117 uint8_t *cpl_band_sizes = s->cpl_band_sizes;
2119 cpl_end_band = s->bandwidth_code / 4 + 3;
2120 cpl_start_band = av_clip(cpl_start, 0, FFMIN(cpl_end_band-1, 15));
2122 s->num_cpl_subbands = cpl_end_band - cpl_start_band;
2124 s->num_cpl_bands = 1;
2125 *cpl_band_sizes = 12;
2126 for (i = cpl_start_band + 1; i < cpl_end_band; i++) {
2127 if (ff_eac3_default_cpl_band_struct[i]) {
2128 *cpl_band_sizes += 12;
2132 *cpl_band_sizes = 12;
2136 s->start_freq[CPL_CH] = cpl_start_band * 12 + 37;
2137 s->cpl_end_freq = cpl_end_band * 12 + 37;
2138 for (blk = 0; blk < s->num_blocks; blk++)
2139 s->blocks[blk].end_freq[CPL_CH] = s->cpl_end_freq;
2144 static av_cold int allocate_buffers(AC3EncodeContext *s)
2146 AVCodecContext *avctx = s->avctx;
2148 int channels = s->channels + 1; /* includes coupling channel */
2149 int channel_blocks = channels * s->num_blocks;
2150 int total_coefs = AC3_MAX_COEFS * channel_blocks;
2152 if (s->allocate_sample_buffers(s))
2155 FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, total_coefs *
2156 sizeof(*s->bap_buffer), alloc_fail);
2157 FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, total_coefs *
2158 sizeof(*s->bap1_buffer), alloc_fail);
2159 FF_ALLOCZ_OR_GOTO(avctx, s->mdct_coef_buffer, total_coefs *
2160 sizeof(*s->mdct_coef_buffer), alloc_fail);
2161 FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, total_coefs *
2162 sizeof(*s->exp_buffer), alloc_fail);
2163 FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, channel_blocks * 128 *
2164 sizeof(*s->grouped_exp_buffer), alloc_fail);
2165 FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, total_coefs *
2166 sizeof(*s->psd_buffer), alloc_fail);
2167 FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, channel_blocks * 64 *
2168 sizeof(*s->band_psd_buffer), alloc_fail);
2169 FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, channel_blocks * 64 *
2170 sizeof(*s->mask_buffer), alloc_fail);
2171 FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, total_coefs *
2172 sizeof(*s->qmant_buffer), alloc_fail);
2173 if (s->cpl_enabled) {
2174 FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_exp_buffer, channel_blocks * 16 *
2175 sizeof(*s->cpl_coord_exp_buffer), alloc_fail);
2176 FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_mant_buffer, channel_blocks * 16 *
2177 sizeof(*s->cpl_coord_mant_buffer), alloc_fail);
2179 for (blk = 0; blk < s->num_blocks; blk++) {
2180 AC3Block *block = &s->blocks[blk];
2181 FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, channels * sizeof(*block->mdct_coef),
2183 FF_ALLOCZ_OR_GOTO(avctx, block->exp, channels * sizeof(*block->exp),
2185 FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, channels * sizeof(*block->grouped_exp),
2187 FF_ALLOCZ_OR_GOTO(avctx, block->psd, channels * sizeof(*block->psd),
2189 FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, channels * sizeof(*block->band_psd),
2191 FF_ALLOCZ_OR_GOTO(avctx, block->mask, channels * sizeof(*block->mask),
2193 FF_ALLOCZ_OR_GOTO(avctx, block->qmant, channels * sizeof(*block->qmant),
2195 if (s->cpl_enabled) {
2196 FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_exp, channels * sizeof(*block->cpl_coord_exp),
2198 FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_mant, channels * sizeof(*block->cpl_coord_mant),
2202 for (ch = 0; ch < channels; ch++) {
2203 /* arrangement: block, channel, coeff */
2204 block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * channels + ch)];
2205 block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
2206 block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * channels + ch)];
2207 block->mask[ch] = &s->mask_buffer [64 * (blk * channels + ch)];
2208 block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
2209 if (s->cpl_enabled) {
2210 block->cpl_coord_exp[ch] = &s->cpl_coord_exp_buffer [16 * (blk * channels + ch)];
2211 block->cpl_coord_mant[ch] = &s->cpl_coord_mant_buffer[16 * (blk * channels + ch)];
2214 /* arrangement: channel, block, coeff */
2215 block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
2216 block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
2220 if (!s->fixed_point) {
2221 FF_ALLOCZ_OR_GOTO(avctx, s->fixed_coef_buffer, total_coefs *
2222 sizeof(*s->fixed_coef_buffer), alloc_fail);
2223 for (blk = 0; blk < s->num_blocks; blk++) {
2224 AC3Block *block = &s->blocks[blk];
2225 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2226 sizeof(*block->fixed_coef), alloc_fail);
2227 for (ch = 0; ch < channels; ch++)
2228 block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
2231 for (blk = 0; blk < s->num_blocks; blk++) {
2232 AC3Block *block = &s->blocks[blk];
2233 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2234 sizeof(*block->fixed_coef), alloc_fail);
2235 for (ch = 0; ch < channels; ch++)
2236 block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2242 return AVERROR(ENOMEM);
2247 * Initialize the encoder.
2249 av_cold int ff_ac3_encode_init(AVCodecContext *avctx)
2251 AC3EncodeContext *s = avctx->priv_data;
2252 int ret, frame_size_58;
2256 s->eac3 = avctx->codec_id == CODEC_ID_EAC3;
2258 ff_ac3_common_init();
2260 ret = validate_options(s);
2264 avctx->frame_size = AC3_BLOCK_SIZE * s->num_blocks;
2266 s->bitstream_mode = avctx->audio_service_type;
2267 if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2268 s->bitstream_mode = 0x7;
2270 s->bits_written = 0;
2271 s->samples_written = 0;
2273 /* calculate crc_inv for both possible frame sizes */
2274 frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
2275 s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2276 if (s->bit_alloc.sr_code == 1) {
2277 frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2278 s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2281 /* set function pointers */
2282 if (CONFIG_AC3_FIXED_ENCODER && s->fixed_point) {
2283 s->mdct_end = ff_ac3_fixed_mdct_end;
2284 s->mdct_init = ff_ac3_fixed_mdct_init;
2285 s->allocate_sample_buffers = ff_ac3_fixed_allocate_sample_buffers;
2286 } else if (CONFIG_AC3_ENCODER || CONFIG_EAC3_ENCODER) {
2287 s->mdct_end = ff_ac3_float_mdct_end;
2288 s->mdct_init = ff_ac3_float_mdct_init;
2289 s->allocate_sample_buffers = ff_ac3_float_allocate_sample_buffers;
2291 if (CONFIG_EAC3_ENCODER && s->eac3)
2292 s->output_frame_header = ff_eac3_output_frame_header;
2294 s->output_frame_header = ac3_output_frame_header;
2302 ret = s->mdct_init(s);
2306 ret = allocate_buffers(s);
2310 avctx->coded_frame= avcodec_alloc_frame();
2312 dsputil_init(&s->dsp, avctx);
2313 ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2319 ff_ac3_encode_close(avctx);