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 Libav.
9 * Libav 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 * Libav 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 Libav; 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 uint16_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 static void adjust_frame_size(AC3EncodeContext *s)
182 while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
183 s->bits_written -= s->bit_rate;
184 s->samples_written -= s->sample_rate;
186 s->frame_size = s->frame_size_min +
187 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
188 s->bits_written += s->frame_size * 8;
189 s->samples_written += AC3_FRAME_SIZE;
193 static void compute_coupling_strategy(AC3EncodeContext *s)
198 /* set coupling use flags for each block/channel */
199 /* TODO: turn coupling on/off and adjust start band based on bit usage */
200 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
201 AC3Block *block = &s->blocks[blk];
202 for (ch = 1; ch <= s->fbw_channels; ch++)
203 block->channel_in_cpl[ch] = s->cpl_on;
206 /* enable coupling for each block if at least 2 channels have coupling
207 enabled for that block */
209 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
210 AC3Block *block = &s->blocks[blk];
211 block->num_cpl_channels = 0;
212 for (ch = 1; ch <= s->fbw_channels; ch++)
213 block->num_cpl_channels += block->channel_in_cpl[ch];
214 block->cpl_in_use = block->num_cpl_channels > 1;
215 if (!block->cpl_in_use) {
216 block->num_cpl_channels = 0;
217 for (ch = 1; ch <= s->fbw_channels; ch++)
218 block->channel_in_cpl[ch] = 0;
221 block->new_cpl_strategy = !blk;
223 for (ch = 1; ch <= s->fbw_channels; ch++) {
224 if (block->channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]) {
225 block->new_cpl_strategy = 1;
230 block->new_cpl_leak = block->new_cpl_strategy;
232 if (!blk || (block->cpl_in_use && !got_cpl_snr)) {
233 block->new_snr_offsets = 1;
234 if (block->cpl_in_use)
237 block->new_snr_offsets = 0;
241 /* set bandwidth for each channel */
242 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
243 AC3Block *block = &s->blocks[blk];
244 for (ch = 1; ch <= s->fbw_channels; ch++) {
245 if (block->channel_in_cpl[ch])
246 block->end_freq[ch] = s->start_freq[CPL_CH];
248 block->end_freq[ch] = s->bandwidth_code * 3 + 73;
255 * Apply stereo rematrixing to coefficients based on rematrixing flags.
257 static void apply_rematrixing(AC3EncodeContext *s)
264 if (!s->rematrixing_enabled)
267 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
268 AC3Block *block = &s->blocks[blk];
269 if (block->new_rematrixing_strategy)
270 flags = block->rematrixing_flags;
271 nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
272 for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {
274 start = ff_ac3_rematrix_band_tab[bnd];
275 end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
276 for (i = start; i < end; i++) {
277 int32_t lt = block->fixed_coef[1][i];
278 int32_t rt = block->fixed_coef[2][i];
279 block->fixed_coef[1][i] = (lt + rt) >> 1;
280 block->fixed_coef[2][i] = (lt - rt) >> 1;
289 * Initialize exponent tables.
291 static av_cold void exponent_init(AC3EncodeContext *s)
293 int expstr, i, grpsize;
295 for (expstr = EXP_D15-1; expstr <= EXP_D45-1; expstr++) {
296 grpsize = 3 << expstr;
297 for (i = 12; i < 256; i++) {
298 exponent_group_tab[0][expstr][i] = (i + grpsize - 4) / grpsize;
299 exponent_group_tab[1][expstr][i] = (i ) / grpsize;
303 exponent_group_tab[0][0][7] = 2;
308 * Extract exponents from the MDCT coefficients.
309 * This takes into account the normalization that was done to the input samples
310 * by adjusting the exponents by the exponent shift values.
312 static void extract_exponents(AC3EncodeContext *s)
315 int chan_size = AC3_MAX_COEFS * AC3_MAX_BLOCKS * (s->channels - ch + 1);
316 AC3Block *block = &s->blocks[0];
318 s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch], chan_size);
323 * Exponent Difference Threshold.
324 * New exponents are sent if their SAD exceed this number.
326 #define EXP_DIFF_THRESHOLD 500
330 * Calculate exponent strategies for all channels.
331 * Array arrangement is reversed to simplify the per-channel calculation.
333 static void compute_exp_strategy(AC3EncodeContext *s)
337 for (ch = !s->cpl_on; ch <= s->fbw_channels; ch++) {
338 uint8_t *exp_strategy = s->exp_strategy[ch];
339 uint8_t *exp = s->blocks[0].exp[ch];
342 /* estimate if the exponent variation & decide if they should be
343 reused in the next frame */
344 exp_strategy[0] = EXP_NEW;
345 exp += AC3_MAX_COEFS;
346 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++, exp += AC3_MAX_COEFS) {
347 if ((ch == CPL_CH && (!s->blocks[blk].cpl_in_use || !s->blocks[blk-1].cpl_in_use)) ||
348 (ch > CPL_CH && (s->blocks[blk].channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]))) {
349 exp_strategy[blk] = EXP_NEW;
352 exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
353 exp_strategy[blk] = EXP_REUSE;
354 if (ch == CPL_CH && exp_diff > (EXP_DIFF_THRESHOLD * (s->blocks[blk].end_freq[ch] - s->start_freq[ch]) / AC3_MAX_COEFS))
355 exp_strategy[blk] = EXP_NEW;
356 else if (ch > CPL_CH && exp_diff > EXP_DIFF_THRESHOLD)
357 exp_strategy[blk] = EXP_NEW;
360 /* now select the encoding strategy type : if exponents are often
361 recoded, we use a coarse encoding */
363 while (blk < AC3_MAX_BLOCKS) {
365 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
367 switch (blk1 - blk) {
368 case 1: exp_strategy[blk] = EXP_D45; break;
370 case 3: exp_strategy[blk] = EXP_D25; break;
371 default: exp_strategy[blk] = EXP_D15; break;
378 s->exp_strategy[ch][0] = EXP_D15;
379 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
380 s->exp_strategy[ch][blk] = EXP_REUSE;
386 * Update the exponents so that they are the ones the decoder will decode.
388 static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy,
393 nb_groups = exponent_group_tab[cpl][exp_strategy-1][nb_exps] * 3;
395 /* for each group, compute the minimum exponent */
396 switch(exp_strategy) {
398 for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
399 uint8_t exp_min = exp[k];
400 if (exp[k+1] < exp_min)
402 exp[i-cpl] = exp_min;
407 for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
408 uint8_t exp_min = exp[k];
409 if (exp[k+1] < exp_min)
411 if (exp[k+2] < exp_min)
413 if (exp[k+3] < exp_min)
415 exp[i-cpl] = exp_min;
421 /* constraint for DC exponent */
422 if (!cpl && exp[0] > 15)
425 /* decrease the delta between each groups to within 2 so that they can be
426 differentially encoded */
427 for (i = 1; i <= nb_groups; i++)
428 exp[i] = FFMIN(exp[i], exp[i-1] + 2);
431 exp[i] = FFMIN(exp[i], exp[i+1] + 2);
434 exp[-1] = exp[0] & ~1;
436 /* now we have the exponent values the decoder will see */
437 switch (exp_strategy) {
439 for (i = nb_groups, k = (nb_groups * 2)-cpl; i > 0; i--) {
440 uint8_t exp1 = exp[i-cpl];
446 for (i = nb_groups, k = (nb_groups * 4)-cpl; i > 0; i--) {
447 exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i-cpl];
456 * Encode exponents from original extracted form to what the decoder will see.
457 * This copies and groups exponents based on exponent strategy and reduces
458 * deltas between adjacent exponent groups so that they can be differentially
461 static void encode_exponents(AC3EncodeContext *s)
463 int blk, blk1, ch, cpl;
464 uint8_t *exp, *exp_strategy;
465 int nb_coefs, num_reuse_blocks;
467 for (ch = !s->cpl_on; ch <= s->channels; ch++) {
468 exp = s->blocks[0].exp[ch] + s->start_freq[ch];
469 exp_strategy = s->exp_strategy[ch];
471 cpl = (ch == CPL_CH);
473 while (blk < AC3_MAX_BLOCKS) {
474 AC3Block *block = &s->blocks[blk];
475 if (cpl && !block->cpl_in_use) {
476 exp += AC3_MAX_COEFS;
480 nb_coefs = block->end_freq[ch] - s->start_freq[ch];
483 /* count the number of EXP_REUSE blocks after the current block
484 and set exponent reference block numbers */
485 s->exp_ref_block[ch][blk] = blk;
486 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
487 s->exp_ref_block[ch][blk1] = blk;
490 num_reuse_blocks = blk1 - blk - 1;
492 /* for the EXP_REUSE case we select the min of the exponents */
493 s->ac3dsp.ac3_exponent_min(exp-s->start_freq[ch], num_reuse_blocks,
496 encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk], cpl);
498 exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
503 /* reference block numbers have been changed, so reset ref_bap_set */
510 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
511 * varies depending on exponent strategy and bandwidth.
513 static void group_exponents(AC3EncodeContext *s)
516 int group_size, nb_groups, bit_count;
518 int delta0, delta1, delta2;
522 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
523 AC3Block *block = &s->blocks[blk];
524 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
525 int exp_strategy = s->exp_strategy[ch][blk];
526 if (exp_strategy == EXP_REUSE)
528 cpl = (ch == CPL_CH);
529 group_size = exp_strategy + (exp_strategy == EXP_D45);
530 nb_groups = exponent_group_tab[cpl][exp_strategy-1][block->end_freq[ch]-s->start_freq[ch]];
531 bit_count += 4 + (nb_groups * 7);
532 p = block->exp[ch] + s->start_freq[ch] - cpl;
536 block->grouped_exp[ch][0] = exp1;
538 /* remaining exponents are delta encoded */
539 for (i = 1; i <= nb_groups; i++) {
540 /* merge three delta in one code */
544 delta0 = exp1 - exp0 + 2;
545 av_assert2(delta0 >= 0 && delta0 <= 4);
550 delta1 = exp1 - exp0 + 2;
551 av_assert2(delta1 >= 0 && delta1 <= 4);
556 delta2 = exp1 - exp0 + 2;
557 av_assert2(delta2 >= 0 && delta2 <= 4);
559 block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
564 s->exponent_bits = bit_count;
569 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
570 * Extract exponents from MDCT coefficients, calculate exponent strategies,
571 * and encode final exponents.
573 static void process_exponents(AC3EncodeContext *s)
575 extract_exponents(s);
577 compute_exp_strategy(s);
588 * Count frame bits that are based solely on fixed parameters.
589 * This only has to be run once when the encoder is initialized.
591 static void count_frame_bits_fixed(AC3EncodeContext *s)
593 static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
598 * no dynamic range codes
599 * bit allocation parameters do not change between blocks
600 * no delta bit allocation
607 frame_bits = 16; /* sync info */
609 /* bitstream info header */
611 frame_bits += 1 + 1 + 1;
612 /* audio frame header */
615 /* exponent strategy */
616 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
617 frame_bits += 2 * s->fbw_channels + s->lfe_on;
618 /* converter exponent strategy */
619 frame_bits += s->fbw_channels * 5;
622 /* block start info */
626 frame_bits += frame_bits_inc[s->channel_mode];
630 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
632 /* block switch flags */
633 frame_bits += s->fbw_channels;
636 frame_bits += s->fbw_channels;
642 /* spectral extension */
647 /* exponent strategy */
648 frame_bits += 2 * s->fbw_channels;
652 /* bit allocation params */
655 frame_bits += 2 + 2 + 2 + 2 + 3;
658 /* converter snr offset */
663 /* delta bit allocation */
675 frame_bits += 1 + 16;
677 s->frame_bits_fixed = frame_bits;
682 * Initialize bit allocation.
683 * Set default parameter codes and calculate parameter values.
685 static void bit_alloc_init(AC3EncodeContext *s)
689 /* init default parameters */
690 s->slow_decay_code = 2;
691 s->fast_decay_code = 1;
692 s->slow_gain_code = 1;
693 s->db_per_bit_code = s->eac3 ? 2 : 3;
695 for (ch = 0; ch <= s->channels; ch++)
696 s->fast_gain_code[ch] = 4;
698 /* initial snr offset */
699 s->coarse_snr_offset = 40;
701 /* compute real values */
702 /* currently none of these values change during encoding, so we can just
703 set them once at initialization */
704 s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
705 s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
706 s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
707 s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
708 s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
709 s->bit_alloc.cpl_fast_leak = 0;
710 s->bit_alloc.cpl_slow_leak = 0;
712 count_frame_bits_fixed(s);
717 * Count the bits used to encode the frame, minus exponents and mantissas.
718 * Bits based on fixed parameters have already been counted, so now we just
719 * have to add the bits based on parameters that change during encoding.
721 static void count_frame_bits(AC3EncodeContext *s)
723 AC3EncOptions *opt = &s->options;
730 if (s->channel_mode > AC3_CHMODE_MONO) {
732 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
733 AC3Block *block = &s->blocks[blk];
735 if (block->new_cpl_strategy)
739 /* coupling exponent strategy */
740 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
741 frame_bits += 2 * s->blocks[blk].cpl_in_use;
743 if (opt->audio_production_info)
745 if (s->bitstream_id == 6) {
746 if (opt->extended_bsi_1)
748 if (opt->extended_bsi_2)
754 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
755 AC3Block *block = &s->blocks[blk];
757 /* coupling strategy */
760 if (block->new_cpl_strategy) {
763 if (block->cpl_in_use) {
766 if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO)
767 frame_bits += s->fbw_channels;
768 if (s->channel_mode == AC3_CHMODE_STEREO)
774 frame_bits += s->num_cpl_subbands - 1;
778 /* coupling coordinates */
779 if (block->cpl_in_use) {
780 for (ch = 1; ch <= s->fbw_channels; ch++) {
781 if (block->channel_in_cpl[ch]) {
782 if (!s->eac3 || block->new_cpl_coords != 2)
784 if (block->new_cpl_coords) {
786 frame_bits += (4 + 4) * s->num_cpl_bands;
792 /* stereo rematrixing */
793 if (s->channel_mode == AC3_CHMODE_STEREO) {
794 if (!s->eac3 || blk > 0)
796 if (s->blocks[blk].new_rematrixing_strategy)
797 frame_bits += block->num_rematrixing_bands;
800 /* bandwidth codes & gain range */
801 for (ch = 1; ch <= s->fbw_channels; ch++) {
802 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
803 if (!block->channel_in_cpl[ch])
809 /* coupling exponent strategy */
810 if (!s->eac3 && block->cpl_in_use)
813 /* snr offsets and fast gain codes */
816 if (block->new_snr_offsets)
817 frame_bits += 6 + (s->channels + block->cpl_in_use) * (4 + 3);
820 /* coupling leak info */
821 if (block->cpl_in_use) {
822 if (!s->eac3 || block->new_cpl_leak != 2)
824 if (block->new_cpl_leak)
829 s->frame_bits = s->frame_bits_fixed + frame_bits;
834 * Calculate masking curve based on the final exponents.
835 * Also calculate the power spectral densities to use in future calculations.
837 static void bit_alloc_masking(AC3EncodeContext *s)
841 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
842 AC3Block *block = &s->blocks[blk];
843 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
844 /* We only need psd and mask for calculating bap.
845 Since we currently do not calculate bap when exponent
846 strategy is EXP_REUSE we do not need to calculate psd or mask. */
847 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
848 ff_ac3_bit_alloc_calc_psd(block->exp[ch], s->start_freq[ch],
849 block->end_freq[ch], block->psd[ch],
850 block->band_psd[ch]);
851 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
852 s->start_freq[ch], block->end_freq[ch],
853 ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
854 ch == s->lfe_channel,
855 DBA_NONE, 0, NULL, NULL, NULL,
864 * Ensure that bap for each block and channel point to the current bap_buffer.
865 * They may have been switched during the bit allocation search.
867 static void reset_block_bap(AC3EncodeContext *s)
872 if (s->ref_bap[0][0] == s->bap_buffer && s->ref_bap_set)
875 ref_bap = s->bap_buffer;
876 for (ch = 0; ch <= s->channels; ch++) {
877 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
878 s->ref_bap[ch][blk] = ref_bap + AC3_MAX_COEFS * s->exp_ref_block[ch][blk];
879 ref_bap += AC3_MAX_COEFS * AC3_MAX_BLOCKS;
886 * Initialize mantissa counts.
887 * These are set so that they are padded to the next whole group size when bits
888 * are counted in compute_mantissa_size.
890 static void count_mantissa_bits_init(uint16_t mant_cnt[AC3_MAX_BLOCKS][16])
894 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
895 memset(mant_cnt[blk], 0, sizeof(mant_cnt[blk]));
896 mant_cnt[blk][1] = mant_cnt[blk][2] = 2;
897 mant_cnt[blk][4] = 1;
903 * Update mantissa bit counts for all blocks in 1 channel in a given bandwidth
906 static void count_mantissa_bits_update_ch(AC3EncodeContext *s, int ch,
907 uint16_t mant_cnt[AC3_MAX_BLOCKS][16],
912 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
913 AC3Block *block = &s->blocks[blk];
914 if (ch == CPL_CH && !block->cpl_in_use)
916 s->ac3dsp.update_bap_counts(mant_cnt[blk],
917 s->ref_bap[ch][blk] + start,
918 FFMIN(end, block->end_freq[ch]) - start);
924 * Count the number of mantissa bits in the frame based on the bap values.
926 static int count_mantissa_bits(AC3EncodeContext *s)
928 int ch, max_end_freq;
929 LOCAL_ALIGNED_16(uint16_t, mant_cnt, [AC3_MAX_BLOCKS], [16]);
931 count_mantissa_bits_init(mant_cnt);
933 max_end_freq = s->bandwidth_code * 3 + 73;
934 for (ch = !s->cpl_enabled; ch <= s->channels; ch++)
935 count_mantissa_bits_update_ch(s, ch, mant_cnt, s->start_freq[ch],
938 return s->ac3dsp.compute_mantissa_size(mant_cnt);
943 * Run the bit allocation with a given SNR offset.
944 * This calculates the bit allocation pointers that will be used to determine
945 * the quantization of each mantissa.
946 * @return the number of bits needed for mantissas if the given SNR offset is
949 static int bit_alloc(AC3EncodeContext *s, int snr_offset)
953 snr_offset = (snr_offset - 240) << 2;
956 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
957 AC3Block *block = &s->blocks[blk];
959 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
960 /* Currently the only bit allocation parameters which vary across
961 blocks within a frame are the exponent values. We can take
962 advantage of that by reusing the bit allocation pointers
963 whenever we reuse exponents. */
964 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
965 s->ac3dsp.bit_alloc_calc_bap(block->mask[ch], block->psd[ch],
966 s->start_freq[ch], block->end_freq[ch],
967 snr_offset, s->bit_alloc.floor,
968 ff_ac3_bap_tab, s->ref_bap[ch][blk]);
972 return count_mantissa_bits(s);
977 * Constant bitrate bit allocation search.
978 * Find the largest SNR offset that will allow data to fit in the frame.
980 static int cbr_bit_allocation(AC3EncodeContext *s)
984 int snr_offset, snr_incr;
986 bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
988 return AVERROR(EINVAL);
990 snr_offset = s->coarse_snr_offset << 4;
992 /* if previous frame SNR offset was 1023, check if current frame can also
993 use SNR offset of 1023. if so, skip the search. */
994 if ((snr_offset | s->fine_snr_offset[1]) == 1023) {
995 if (bit_alloc(s, 1023) <= bits_left)
999 while (snr_offset >= 0 &&
1000 bit_alloc(s, snr_offset) > bits_left) {
1004 return AVERROR(EINVAL);
1006 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1007 for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1008 while (snr_offset + snr_incr <= 1023 &&
1009 bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1010 snr_offset += snr_incr;
1011 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1014 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1017 s->coarse_snr_offset = snr_offset >> 4;
1018 for (ch = !s->cpl_on; ch <= s->channels; ch++)
1019 s->fine_snr_offset[ch] = snr_offset & 0xF;
1026 * Downgrade exponent strategies to reduce the bits used by the exponents.
1027 * This is a fallback for when bit allocation fails with the normal exponent
1028 * strategies. Each time this function is run it only downgrades the
1029 * strategy in 1 channel of 1 block.
1030 * @return non-zero if downgrade was unsuccessful
1032 static int downgrade_exponents(AC3EncodeContext *s)
1036 for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1037 for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
1038 if (s->exp_strategy[ch][blk] == EXP_D15) {
1039 s->exp_strategy[ch][blk] = EXP_D25;
1044 for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1045 for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
1046 if (s->exp_strategy[ch][blk] == EXP_D25) {
1047 s->exp_strategy[ch][blk] = EXP_D45;
1052 /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
1053 the block number > 0 */
1054 for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
1055 for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
1056 if (s->exp_strategy[ch][blk] > EXP_REUSE) {
1057 s->exp_strategy[ch][blk] = EXP_REUSE;
1067 * Perform bit allocation search.
1068 * Finds the SNR offset value that maximizes quality and fits in the specified
1069 * frame size. Output is the SNR offset and a set of bit allocation pointers
1070 * used to quantize the mantissas.
1072 static int compute_bit_allocation(AC3EncodeContext *s)
1076 count_frame_bits(s);
1078 bit_alloc_masking(s);
1080 ret = cbr_bit_allocation(s);
1082 /* fallback 1: disable channel coupling */
1085 compute_coupling_strategy(s);
1086 s->compute_rematrixing_strategy(s);
1087 apply_rematrixing(s);
1088 process_exponents(s);
1089 ret = compute_bit_allocation(s);
1093 /* fallback 2: downgrade exponents */
1094 if (!downgrade_exponents(s)) {
1095 extract_exponents(s);
1096 encode_exponents(s);
1098 ret = compute_bit_allocation(s);
1102 /* fallbacks were not enough... */
1111 * Symmetric quantization on 'levels' levels.
1113 static inline int sym_quant(int c, int e, int levels)
1115 int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1116 av_assert2(v >= 0 && v < levels);
1122 * Asymmetric quantization on 2^qbits levels.
1124 static inline int asym_quant(int c, int e, int qbits)
1128 lshift = e + qbits - 24;
1135 m = (1 << (qbits-1));
1138 av_assert2(v >= -m);
1139 return v & ((1 << qbits)-1);
1144 * Quantize a set of mantissas for a single channel in a single block.
1146 static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1147 uint8_t *exp, uint8_t *bap,
1148 uint16_t *qmant, int start_freq,
1153 for (i = start_freq; i < end_freq; i++) {
1155 int c = fixed_coef[i];
1163 v = sym_quant(c, e, 3);
1164 switch (s->mant1_cnt) {
1166 s->qmant1_ptr = &qmant[i];
1171 *s->qmant1_ptr += 3 * v;
1176 *s->qmant1_ptr += v;
1183 v = sym_quant(c, e, 5);
1184 switch (s->mant2_cnt) {
1186 s->qmant2_ptr = &qmant[i];
1191 *s->qmant2_ptr += 5 * v;
1196 *s->qmant2_ptr += v;
1203 v = sym_quant(c, e, 7);
1206 v = sym_quant(c, e, 11);
1207 switch (s->mant4_cnt) {
1209 s->qmant4_ptr = &qmant[i];
1214 *s->qmant4_ptr += v;
1221 v = sym_quant(c, e, 15);
1224 v = asym_quant(c, e, 14);
1227 v = asym_quant(c, e, 16);
1230 v = asym_quant(c, e, b - 1);
1239 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1241 static void quantize_mantissas(AC3EncodeContext *s)
1243 int blk, ch, ch0=0, got_cpl;
1245 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1246 AC3Block *block = &s->blocks[blk];
1249 got_cpl = !block->cpl_in_use;
1250 for (ch = 1; ch <= s->channels; ch++) {
1251 if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1256 quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1257 s->blocks[s->exp_ref_block[ch][blk]].exp[ch],
1258 s->ref_bap[ch][blk], block->qmant[ch],
1259 s->start_freq[ch], block->end_freq[ch]);
1268 * Write the AC-3 frame header to the output bitstream.
1270 static void ac3_output_frame_header(AC3EncodeContext *s)
1272 AC3EncOptions *opt = &s->options;
1274 put_bits(&s->pb, 16, 0x0b77); /* frame header */
1275 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
1276 put_bits(&s->pb, 2, s->bit_alloc.sr_code);
1277 put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1278 put_bits(&s->pb, 5, s->bitstream_id);
1279 put_bits(&s->pb, 3, s->bitstream_mode);
1280 put_bits(&s->pb, 3, s->channel_mode);
1281 if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1282 put_bits(&s->pb, 2, s->center_mix_level);
1283 if (s->channel_mode & 0x04)
1284 put_bits(&s->pb, 2, s->surround_mix_level);
1285 if (s->channel_mode == AC3_CHMODE_STEREO)
1286 put_bits(&s->pb, 2, opt->dolby_surround_mode);
1287 put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1288 put_bits(&s->pb, 5, -opt->dialogue_level);
1289 put_bits(&s->pb, 1, 0); /* no compression control word */
1290 put_bits(&s->pb, 1, 0); /* no lang code */
1291 put_bits(&s->pb, 1, opt->audio_production_info);
1292 if (opt->audio_production_info) {
1293 put_bits(&s->pb, 5, opt->mixing_level - 80);
1294 put_bits(&s->pb, 2, opt->room_type);
1296 put_bits(&s->pb, 1, opt->copyright);
1297 put_bits(&s->pb, 1, opt->original);
1298 if (s->bitstream_id == 6) {
1299 /* alternate bit stream syntax */
1300 put_bits(&s->pb, 1, opt->extended_bsi_1);
1301 if (opt->extended_bsi_1) {
1302 put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1303 put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1304 put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1305 put_bits(&s->pb, 3, s->loro_center_mix_level);
1306 put_bits(&s->pb, 3, s->loro_surround_mix_level);
1308 put_bits(&s->pb, 1, opt->extended_bsi_2);
1309 if (opt->extended_bsi_2) {
1310 put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1311 put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1312 put_bits(&s->pb, 1, opt->ad_converter_type);
1313 put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
1316 put_bits(&s->pb, 1, 0); /* no time code 1 */
1317 put_bits(&s->pb, 1, 0); /* no time code 2 */
1319 put_bits(&s->pb, 1, 0); /* no additional bit stream info */
1324 * Write one audio block to the output bitstream.
1326 static void output_audio_block(AC3EncodeContext *s, int blk)
1328 int ch, i, baie, bnd, got_cpl;
1330 AC3Block *block = &s->blocks[blk];
1332 /* block switching */
1334 for (ch = 0; ch < s->fbw_channels; ch++)
1335 put_bits(&s->pb, 1, 0);
1340 for (ch = 0; ch < s->fbw_channels; ch++)
1341 put_bits(&s->pb, 1, 1);
1344 /* dynamic range codes */
1345 put_bits(&s->pb, 1, 0);
1347 /* spectral extension */
1349 put_bits(&s->pb, 1, 0);
1351 /* channel coupling */
1353 put_bits(&s->pb, 1, block->new_cpl_strategy);
1354 if (block->new_cpl_strategy) {
1356 put_bits(&s->pb, 1, block->cpl_in_use);
1357 if (block->cpl_in_use) {
1358 int start_sub, end_sub;
1360 put_bits(&s->pb, 1, 0); /* enhanced coupling */
1361 if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO) {
1362 for (ch = 1; ch <= s->fbw_channels; ch++)
1363 put_bits(&s->pb, 1, block->channel_in_cpl[ch]);
1365 if (s->channel_mode == AC3_CHMODE_STEREO)
1366 put_bits(&s->pb, 1, 0); /* phase flags in use */
1367 start_sub = (s->start_freq[CPL_CH] - 37) / 12;
1368 end_sub = (s->cpl_end_freq - 37) / 12;
1369 put_bits(&s->pb, 4, start_sub);
1370 put_bits(&s->pb, 4, end_sub - 3);
1371 /* coupling band structure */
1373 put_bits(&s->pb, 1, 0); /* use default */
1375 for (bnd = start_sub+1; bnd < end_sub; bnd++)
1376 put_bits(&s->pb, 1, ff_eac3_default_cpl_band_struct[bnd]);
1381 /* coupling coordinates */
1382 if (block->cpl_in_use) {
1383 for (ch = 1; ch <= s->fbw_channels; ch++) {
1384 if (block->channel_in_cpl[ch]) {
1385 if (!s->eac3 || block->new_cpl_coords != 2)
1386 put_bits(&s->pb, 1, block->new_cpl_coords);
1387 if (block->new_cpl_coords) {
1388 put_bits(&s->pb, 2, block->cpl_master_exp[ch]);
1389 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
1390 put_bits(&s->pb, 4, block->cpl_coord_exp [ch][bnd]);
1391 put_bits(&s->pb, 4, block->cpl_coord_mant[ch][bnd]);
1398 /* stereo rematrixing */
1399 if (s->channel_mode == AC3_CHMODE_STEREO) {
1400 if (!s->eac3 || blk > 0)
1401 put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1402 if (block->new_rematrixing_strategy) {
1403 /* rematrixing flags */
1404 for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++)
1405 put_bits(&s->pb, 1, block->rematrixing_flags[bnd]);
1409 /* exponent strategy */
1411 for (ch = !block->cpl_in_use; ch <= s->fbw_channels; ch++)
1412 put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1414 put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1418 for (ch = 1; ch <= s->fbw_channels; ch++) {
1419 if (s->exp_strategy[ch][blk] != EXP_REUSE && !block->channel_in_cpl[ch])
1420 put_bits(&s->pb, 6, s->bandwidth_code);
1424 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1426 int cpl = (ch == CPL_CH);
1428 if (s->exp_strategy[ch][blk] == EXP_REUSE)
1432 put_bits(&s->pb, 4, block->grouped_exp[ch][0] >> cpl);
1434 /* exponent groups */
1435 nb_groups = exponent_group_tab[cpl][s->exp_strategy[ch][blk]-1][block->end_freq[ch]-s->start_freq[ch]];
1436 for (i = 1; i <= nb_groups; i++)
1437 put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1439 /* gain range info */
1440 if (ch != s->lfe_channel && !cpl)
1441 put_bits(&s->pb, 2, 0);
1444 /* bit allocation info */
1447 put_bits(&s->pb, 1, baie);
1449 put_bits(&s->pb, 2, s->slow_decay_code);
1450 put_bits(&s->pb, 2, s->fast_decay_code);
1451 put_bits(&s->pb, 2, s->slow_gain_code);
1452 put_bits(&s->pb, 2, s->db_per_bit_code);
1453 put_bits(&s->pb, 3, s->floor_code);
1459 put_bits(&s->pb, 1, block->new_snr_offsets);
1460 if (block->new_snr_offsets) {
1461 put_bits(&s->pb, 6, s->coarse_snr_offset);
1462 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1463 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1464 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1468 put_bits(&s->pb, 1, 0); /* no converter snr offset */
1472 if (block->cpl_in_use) {
1473 if (!s->eac3 || block->new_cpl_leak != 2)
1474 put_bits(&s->pb, 1, block->new_cpl_leak);
1475 if (block->new_cpl_leak) {
1476 put_bits(&s->pb, 3, s->bit_alloc.cpl_fast_leak);
1477 put_bits(&s->pb, 3, s->bit_alloc.cpl_slow_leak);
1482 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1483 put_bits(&s->pb, 1, 0); /* no data to skip */
1487 got_cpl = !block->cpl_in_use;
1488 for (ch = 1; ch <= s->channels; ch++) {
1491 if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1496 for (i = s->start_freq[ch]; i < block->end_freq[ch]; i++) {
1497 q = block->qmant[ch][i];
1498 b = s->ref_bap[ch][blk][i];
1501 case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
1502 case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
1503 case 3: put_bits(&s->pb, 3, q); break;
1504 case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
1505 case 14: put_bits(&s->pb, 14, q); break;
1506 case 15: put_bits(&s->pb, 16, q); break;
1507 default: put_bits(&s->pb, b-1, q); break;
1516 /** CRC-16 Polynomial */
1517 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1520 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1537 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1543 r = mul_poly(r, a, poly);
1544 a = mul_poly(a, a, poly);
1552 * Fill the end of the frame with 0's and compute the two CRCs.
1554 static void output_frame_end(AC3EncodeContext *s)
1556 const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1557 int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1560 frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1562 /* pad the remainder of the frame with zeros */
1563 av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1564 flush_put_bits(&s->pb);
1566 pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1567 av_assert2(pad_bytes >= 0);
1569 memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1573 crc2_partial = av_crc(crc_ctx, 0, frame + 2, s->frame_size - 5);
1576 /* this is not so easy because it is at the beginning of the data... */
1577 crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1578 crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1579 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1580 AV_WB16(frame + 2, crc1);
1583 crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1584 s->frame_size - frame_size_58 - 3);
1586 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1587 /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1588 if (crc2 == 0x770B) {
1589 frame[s->frame_size - 3] ^= 0x1;
1590 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1592 crc2 = av_bswap16(crc2);
1593 AV_WB16(frame + s->frame_size - 2, crc2);
1598 * Write the frame to the output bitstream.
1600 static void output_frame(AC3EncodeContext *s, unsigned char *frame)
1604 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1606 s->output_frame_header(s);
1608 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1609 output_audio_block(s, blk);
1611 output_frame_end(s);
1615 static void dprint_options(AVCodecContext *avctx)
1618 AC3EncodeContext *s = avctx->priv_data;
1619 AC3EncOptions *opt = &s->options;
1622 switch (s->bitstream_id) {
1623 case 6: av_strlcpy(strbuf, "AC-3 (alt syntax)", 32); break;
1624 case 8: av_strlcpy(strbuf, "AC-3 (standard)", 32); break;
1625 case 9: av_strlcpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
1626 case 10: av_strlcpy(strbuf, "AC-3 (dnet quater-rate)", 32); break;
1627 case 16: av_strlcpy(strbuf, "E-AC-3 (enhanced)", 32); break;
1628 default: snprintf(strbuf, 32, "ERROR");
1630 av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
1631 av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
1632 av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
1633 av_dlog(avctx, "channel_layout: %s\n", strbuf);
1634 av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
1635 av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
1637 av_dlog(avctx, "cutoff: %d\n", s->cutoff);
1639 av_dlog(avctx, "per_frame_metadata: %s\n",
1640 opt->allow_per_frame_metadata?"on":"off");
1642 av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
1643 s->center_mix_level);
1645 av_dlog(avctx, "center_mixlev: {not written}\n");
1646 if (s->has_surround)
1647 av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
1648 s->surround_mix_level);
1650 av_dlog(avctx, "surround_mixlev: {not written}\n");
1651 if (opt->audio_production_info) {
1652 av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
1653 switch (opt->room_type) {
1654 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1655 case 1: av_strlcpy(strbuf, "large", 32); break;
1656 case 2: av_strlcpy(strbuf, "small", 32); break;
1657 default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
1659 av_dlog(avctx, "room_type: %s\n", strbuf);
1661 av_dlog(avctx, "mixing_level: {not written}\n");
1662 av_dlog(avctx, "room_type: {not written}\n");
1664 av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
1665 av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
1666 if (s->channel_mode == AC3_CHMODE_STEREO) {
1667 switch (opt->dolby_surround_mode) {
1668 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1669 case 1: av_strlcpy(strbuf, "on", 32); break;
1670 case 2: av_strlcpy(strbuf, "off", 32); break;
1671 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
1673 av_dlog(avctx, "dsur_mode: %s\n", strbuf);
1675 av_dlog(avctx, "dsur_mode: {not written}\n");
1677 av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
1679 if (s->bitstream_id == 6) {
1680 if (opt->extended_bsi_1) {
1681 switch (opt->preferred_stereo_downmix) {
1682 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1683 case 1: av_strlcpy(strbuf, "ltrt", 32); break;
1684 case 2: av_strlcpy(strbuf, "loro", 32); break;
1685 default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
1687 av_dlog(avctx, "dmix_mode: %s\n", strbuf);
1688 av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
1689 opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
1690 av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
1691 opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
1692 av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
1693 opt->loro_center_mix_level, s->loro_center_mix_level);
1694 av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
1695 opt->loro_surround_mix_level, s->loro_surround_mix_level);
1697 av_dlog(avctx, "extended bitstream info 1: {not written}\n");
1699 if (opt->extended_bsi_2) {
1700 switch (opt->dolby_surround_ex_mode) {
1701 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1702 case 1: av_strlcpy(strbuf, "on", 32); break;
1703 case 2: av_strlcpy(strbuf, "off", 32); break;
1704 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
1706 av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
1707 switch (opt->dolby_headphone_mode) {
1708 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1709 case 1: av_strlcpy(strbuf, "on", 32); break;
1710 case 2: av_strlcpy(strbuf, "off", 32); break;
1711 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
1713 av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
1715 switch (opt->ad_converter_type) {
1716 case 0: av_strlcpy(strbuf, "standard", 32); break;
1717 case 1: av_strlcpy(strbuf, "hdcd", 32); break;
1718 default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
1720 av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
1722 av_dlog(avctx, "extended bitstream info 2: {not written}\n");
1729 #define FLT_OPTION_THRESHOLD 0.01
1731 static int validate_float_option(float v, const float *v_list, int v_list_size)
1735 for (i = 0; i < v_list_size; i++) {
1736 if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
1737 v > (v_list[i] - FLT_OPTION_THRESHOLD))
1740 if (i == v_list_size)
1747 static void validate_mix_level(void *log_ctx, const char *opt_name,
1748 float *opt_param, const float *list,
1749 int list_size, int default_value, int min_value,
1752 int mixlev = validate_float_option(*opt_param, list, list_size);
1753 if (mixlev < min_value) {
1754 mixlev = default_value;
1755 if (*opt_param >= 0.0) {
1756 av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
1757 "default value: %0.3f\n", opt_name, list[mixlev]);
1760 *opt_param = list[mixlev];
1761 *ctx_param = mixlev;
1766 * Validate metadata options as set by AVOption system.
1767 * These values can optionally be changed per-frame.
1769 static int validate_metadata(AVCodecContext *avctx)
1771 AC3EncodeContext *s = avctx->priv_data;
1772 AC3EncOptions *opt = &s->options;
1774 /* validate mixing levels */
1775 if (s->has_center) {
1776 validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
1777 cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
1778 &s->center_mix_level);
1780 if (s->has_surround) {
1781 validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
1782 surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
1783 &s->surround_mix_level);
1786 /* set audio production info flag */
1787 if (opt->mixing_level >= 0 || opt->room_type >= 0) {
1788 if (opt->mixing_level < 0) {
1789 av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
1790 "room_type is set\n");
1791 return AVERROR(EINVAL);
1793 if (opt->mixing_level < 80) {
1794 av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
1795 "80dB and 111dB\n");
1796 return AVERROR(EINVAL);
1798 /* default room type */
1799 if (opt->room_type < 0)
1801 opt->audio_production_info = 1;
1803 opt->audio_production_info = 0;
1806 /* set extended bsi 1 flag */
1807 if ((s->has_center || s->has_surround) &&
1808 (opt->preferred_stereo_downmix >= 0 ||
1809 opt->ltrt_center_mix_level >= 0 ||
1810 opt->ltrt_surround_mix_level >= 0 ||
1811 opt->loro_center_mix_level >= 0 ||
1812 opt->loro_surround_mix_level >= 0)) {
1813 /* default preferred stereo downmix */
1814 if (opt->preferred_stereo_downmix < 0)
1815 opt->preferred_stereo_downmix = 0;
1816 /* validate Lt/Rt center mix level */
1817 validate_mix_level(avctx, "ltrt_center_mix_level",
1818 &opt->ltrt_center_mix_level, extmixlev_options,
1819 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1820 &s->ltrt_center_mix_level);
1821 /* validate Lt/Rt surround mix level */
1822 validate_mix_level(avctx, "ltrt_surround_mix_level",
1823 &opt->ltrt_surround_mix_level, extmixlev_options,
1824 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1825 &s->ltrt_surround_mix_level);
1826 /* validate Lo/Ro center mix level */
1827 validate_mix_level(avctx, "loro_center_mix_level",
1828 &opt->loro_center_mix_level, extmixlev_options,
1829 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1830 &s->loro_center_mix_level);
1831 /* validate Lo/Ro surround mix level */
1832 validate_mix_level(avctx, "loro_surround_mix_level",
1833 &opt->loro_surround_mix_level, extmixlev_options,
1834 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1835 &s->loro_surround_mix_level);
1836 opt->extended_bsi_1 = 1;
1838 opt->extended_bsi_1 = 0;
1841 /* set extended bsi 2 flag */
1842 if (opt->dolby_surround_ex_mode >= 0 ||
1843 opt->dolby_headphone_mode >= 0 ||
1844 opt->ad_converter_type >= 0) {
1845 /* default dolby surround ex mode */
1846 if (opt->dolby_surround_ex_mode < 0)
1847 opt->dolby_surround_ex_mode = 0;
1848 /* default dolby headphone mode */
1849 if (opt->dolby_headphone_mode < 0)
1850 opt->dolby_headphone_mode = 0;
1851 /* default A/D converter type */
1852 if (opt->ad_converter_type < 0)
1853 opt->ad_converter_type = 0;
1854 opt->extended_bsi_2 = 1;
1856 opt->extended_bsi_2 = 0;
1859 /* set bitstream id for alternate bitstream syntax */
1860 if (opt->extended_bsi_1 || opt->extended_bsi_2) {
1861 if (s->bitstream_id > 8 && s->bitstream_id < 11) {
1862 static int warn_once = 1;
1864 av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
1865 "not compatible with reduced samplerates. writing of "
1866 "extended bitstream information will be disabled.\n");
1870 s->bitstream_id = 6;
1879 * Encode a single AC-3 frame.
1881 int ff_ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
1882 int buf_size, void *data)
1884 AC3EncodeContext *s = avctx->priv_data;
1885 const SampleType *samples = data;
1888 if (!s->eac3 && s->options.allow_per_frame_metadata) {
1889 ret = validate_metadata(avctx);
1894 if (s->bit_alloc.sr_code == 1 || s->eac3)
1895 adjust_frame_size(s);
1897 s->deinterleave_input_samples(s, samples);
1901 s->scale_coefficients(s);
1903 s->cpl_on = s->cpl_enabled;
1904 compute_coupling_strategy(s);
1907 s->apply_channel_coupling(s);
1909 s->compute_rematrixing_strategy(s);
1911 apply_rematrixing(s);
1913 process_exponents(s);
1915 ret = compute_bit_allocation(s);
1917 av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1921 quantize_mantissas(s);
1923 output_frame(s, frame);
1925 return s->frame_size;
1930 * Finalize encoding and free any memory allocated by the encoder.
1932 av_cold int ff_ac3_encode_close(AVCodecContext *avctx)
1935 AC3EncodeContext *s = avctx->priv_data;
1937 av_freep(&s->windowed_samples);
1938 for (ch = 0; ch < s->channels; ch++)
1939 av_freep(&s->planar_samples[ch]);
1940 av_freep(&s->planar_samples);
1941 av_freep(&s->bap_buffer);
1942 av_freep(&s->bap1_buffer);
1943 av_freep(&s->mdct_coef_buffer);
1944 av_freep(&s->fixed_coef_buffer);
1945 av_freep(&s->exp_buffer);
1946 av_freep(&s->grouped_exp_buffer);
1947 av_freep(&s->psd_buffer);
1948 av_freep(&s->band_psd_buffer);
1949 av_freep(&s->mask_buffer);
1950 av_freep(&s->qmant_buffer);
1951 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1952 AC3Block *block = &s->blocks[blk];
1953 av_freep(&block->mdct_coef);
1954 av_freep(&block->fixed_coef);
1955 av_freep(&block->exp);
1956 av_freep(&block->grouped_exp);
1957 av_freep(&block->psd);
1958 av_freep(&block->band_psd);
1959 av_freep(&block->mask);
1960 av_freep(&block->qmant);
1963 s->mdct_end(s->mdct);
1966 av_freep(&avctx->coded_frame);
1972 * Set channel information during initialization.
1974 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1975 int64_t *channel_layout)
1979 if (channels < 1 || channels > AC3_MAX_CHANNELS)
1980 return AVERROR(EINVAL);
1981 if ((uint64_t)*channel_layout > 0x7FF)
1982 return AVERROR(EINVAL);
1983 ch_layout = *channel_layout;
1985 ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1987 s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1988 s->channels = channels;
1989 s->fbw_channels = channels - s->lfe_on;
1990 s->lfe_channel = s->lfe_on ? s->fbw_channels + 1 : -1;
1992 ch_layout -= AV_CH_LOW_FREQUENCY;
1994 switch (ch_layout) {
1995 case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
1996 case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
1997 case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
1998 case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
1999 case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
2000 case AV_CH_LAYOUT_QUAD:
2001 case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
2002 case AV_CH_LAYOUT_5POINT0:
2003 case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
2005 return AVERROR(EINVAL);
2007 s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
2008 s->has_surround = s->channel_mode & 0x04;
2010 s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
2011 *channel_layout = ch_layout;
2013 *channel_layout |= AV_CH_LOW_FREQUENCY;
2019 static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
2023 /* validate channel layout */
2024 if (!avctx->channel_layout) {
2025 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
2026 "encoder will guess the layout, but it "
2027 "might be incorrect.\n");
2029 ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
2031 av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
2035 /* validate sample rate */
2036 /* note: max_sr could be changed from 2 to 5 for E-AC-3 once we find a
2037 decoder that supports half sample rate so we can validate that
2038 the generated files are correct. */
2039 max_sr = s->eac3 ? 2 : 8;
2040 for (i = 0; i <= max_sr; i++) {
2041 if ((ff_ac3_sample_rate_tab[i % 3] >> (i / 3)) == avctx->sample_rate)
2045 av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
2046 return AVERROR(EINVAL);
2048 s->sample_rate = avctx->sample_rate;
2049 s->bit_alloc.sr_shift = i / 3;
2050 s->bit_alloc.sr_code = i % 3;
2051 s->bitstream_id = s->eac3 ? 16 : 8 + s->bit_alloc.sr_shift;
2053 /* validate bit rate */
2055 int max_br, min_br, wpf, min_br_dist, min_br_code;
2057 /* calculate min/max bitrate */
2058 max_br = 2048 * s->sample_rate / AC3_FRAME_SIZE * 16;
2059 min_br = ((s->sample_rate + (AC3_FRAME_SIZE-1)) / AC3_FRAME_SIZE) * 16;
2060 if (avctx->bit_rate < min_br || avctx->bit_rate > max_br) {
2061 av_log(avctx, AV_LOG_ERROR, "invalid bit rate. must be %d to %d "
2062 "for this sample rate\n", min_br, max_br);
2063 return AVERROR(EINVAL);
2066 /* calculate words-per-frame for the selected bitrate */
2067 wpf = (avctx->bit_rate / 16) * AC3_FRAME_SIZE / s->sample_rate;
2068 av_assert1(wpf > 0 && wpf <= 2048);
2070 /* find the closest AC-3 bitrate code to the selected bitrate.
2071 this is needed for lookup tables for bandwidth and coupling
2072 parameter selection */
2074 min_br_dist = INT_MAX;
2075 for (i = 0; i < 19; i++) {
2076 int br_dist = abs(ff_ac3_bitrate_tab[i] * 1000 - avctx->bit_rate);
2077 if (br_dist < min_br_dist) {
2078 min_br_dist = br_dist;
2083 /* make sure the minimum frame size is below the average frame size */
2084 s->frame_size_code = min_br_code << 1;
2085 while (wpf > 1 && wpf * s->sample_rate / AC3_FRAME_SIZE * 16 > avctx->bit_rate)
2087 s->frame_size_min = 2 * wpf;
2089 for (i = 0; i < 19; i++) {
2090 if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
2094 av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2095 return AVERROR(EINVAL);
2097 s->frame_size_code = i << 1;
2098 s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2100 s->bit_rate = avctx->bit_rate;
2101 s->frame_size = s->frame_size_min;
2103 /* validate cutoff */
2104 if (avctx->cutoff < 0) {
2105 av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2106 return AVERROR(EINVAL);
2108 s->cutoff = avctx->cutoff;
2109 if (s->cutoff > (s->sample_rate >> 1))
2110 s->cutoff = s->sample_rate >> 1;
2112 /* validate audio service type / channels combination */
2113 if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
2114 avctx->channels == 1) ||
2115 ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
2116 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
2117 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
2118 && avctx->channels > 1)) {
2119 av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
2120 "specified number of channels\n");
2121 return AVERROR(EINVAL);
2125 ret = validate_metadata(avctx);
2130 s->rematrixing_enabled = s->options.stereo_rematrixing &&
2131 (s->channel_mode == AC3_CHMODE_STEREO);
2133 s->cpl_enabled = s->options.channel_coupling &&
2134 s->channel_mode >= AC3_CHMODE_STEREO && !s->fixed_point;
2141 * Set bandwidth for all channels.
2142 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2143 * default value will be used.
2145 static av_cold void set_bandwidth(AC3EncodeContext *s)
2148 int av_uninit(cpl_start);
2151 /* calculate bandwidth based on user-specified cutoff frequency */
2153 fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2154 s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2156 /* use default bandwidth setting */
2157 s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2160 /* set number of coefficients for each channel */
2161 for (ch = 1; ch <= s->fbw_channels; ch++) {
2162 s->start_freq[ch] = 0;
2163 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2164 s->blocks[blk].end_freq[ch] = s->bandwidth_code * 3 + 73;
2166 /* LFE channel always has 7 coefs */
2168 s->start_freq[s->lfe_channel] = 0;
2169 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2170 s->blocks[blk].end_freq[ch] = 7;
2173 /* initialize coupling strategy */
2174 if (s->cpl_enabled) {
2175 if (s->options.cpl_start >= 0) {
2176 cpl_start = s->options.cpl_start;
2178 cpl_start = ac3_coupling_start_tab[s->channel_mode-2][s->bit_alloc.sr_code][s->frame_size_code/2];
2183 if (s->cpl_enabled) {
2184 int i, cpl_start_band, cpl_end_band;
2185 uint8_t *cpl_band_sizes = s->cpl_band_sizes;
2187 cpl_end_band = s->bandwidth_code / 4 + 3;
2188 cpl_start_band = av_clip(cpl_start, 0, FFMIN(cpl_end_band-1, 15));
2190 s->num_cpl_subbands = cpl_end_band - cpl_start_band;
2192 s->num_cpl_bands = 1;
2193 *cpl_band_sizes = 12;
2194 for (i = cpl_start_band + 1; i < cpl_end_band; i++) {
2195 if (ff_eac3_default_cpl_band_struct[i]) {
2196 *cpl_band_sizes += 12;
2200 *cpl_band_sizes = 12;
2204 s->start_freq[CPL_CH] = cpl_start_band * 12 + 37;
2205 s->cpl_end_freq = cpl_end_band * 12 + 37;
2206 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2207 s->blocks[blk].end_freq[CPL_CH] = s->cpl_end_freq;
2212 static av_cold int allocate_buffers(AVCodecContext *avctx)
2215 AC3EncodeContext *s = avctx->priv_data;
2216 int channels = s->channels + 1; /* includes coupling channel */
2218 FF_ALLOC_OR_GOTO(avctx, s->windowed_samples, AC3_WINDOW_SIZE *
2219 sizeof(*s->windowed_samples), alloc_fail);
2220 FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
2222 for (ch = 0; ch < s->channels; ch++) {
2223 FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
2224 (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
2227 FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * channels *
2228 AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
2229 FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * channels *
2230 AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
2231 FF_ALLOCZ_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * channels *
2232 AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
2233 FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * channels *
2234 AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
2235 FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * channels *
2236 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
2237 FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * channels *
2238 AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
2239 FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * channels *
2240 64 * sizeof(*s->band_psd_buffer), alloc_fail);
2241 FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * channels *
2242 64 * sizeof(*s->mask_buffer), alloc_fail);
2243 FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * channels *
2244 AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
2245 if (s->cpl_enabled) {
2246 FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_exp_buffer, AC3_MAX_BLOCKS * channels *
2247 16 * sizeof(*s->cpl_coord_exp_buffer), alloc_fail);
2248 FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_mant_buffer, AC3_MAX_BLOCKS * channels *
2249 16 * sizeof(*s->cpl_coord_mant_buffer), alloc_fail);
2251 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2252 AC3Block *block = &s->blocks[blk];
2253 FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, channels * sizeof(*block->mdct_coef),
2255 FF_ALLOCZ_OR_GOTO(avctx, block->exp, channels * sizeof(*block->exp),
2257 FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, channels * sizeof(*block->grouped_exp),
2259 FF_ALLOCZ_OR_GOTO(avctx, block->psd, channels * sizeof(*block->psd),
2261 FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, channels * sizeof(*block->band_psd),
2263 FF_ALLOCZ_OR_GOTO(avctx, block->mask, channels * sizeof(*block->mask),
2265 FF_ALLOCZ_OR_GOTO(avctx, block->qmant, channels * sizeof(*block->qmant),
2267 if (s->cpl_enabled) {
2268 FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_exp, channels * sizeof(*block->cpl_coord_exp),
2270 FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_mant, channels * sizeof(*block->cpl_coord_mant),
2274 for (ch = 0; ch < channels; ch++) {
2275 /* arrangement: block, channel, coeff */
2276 block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * channels + ch)];
2277 block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
2278 block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * channels + ch)];
2279 block->mask[ch] = &s->mask_buffer [64 * (blk * channels + ch)];
2280 block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
2281 if (s->cpl_enabled) {
2282 block->cpl_coord_exp[ch] = &s->cpl_coord_exp_buffer [16 * (blk * channels + ch)];
2283 block->cpl_coord_mant[ch] = &s->cpl_coord_mant_buffer[16 * (blk * channels + ch)];
2286 /* arrangement: channel, block, coeff */
2287 block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2288 block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2292 if (!s->fixed_point) {
2293 FF_ALLOCZ_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * channels *
2294 AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
2295 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2296 AC3Block *block = &s->blocks[blk];
2297 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2298 sizeof(*block->fixed_coef), alloc_fail);
2299 for (ch = 0; ch < channels; ch++)
2300 block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2303 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2304 AC3Block *block = &s->blocks[blk];
2305 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2306 sizeof(*block->fixed_coef), alloc_fail);
2307 for (ch = 0; ch < channels; ch++)
2308 block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2314 return AVERROR(ENOMEM);
2319 * Initialize the encoder.
2321 av_cold int ff_ac3_encode_init(AVCodecContext *avctx)
2323 AC3EncodeContext *s = avctx->priv_data;
2324 int ret, frame_size_58;
2326 s->eac3 = avctx->codec_id == CODEC_ID_EAC3;
2328 avctx->frame_size = AC3_FRAME_SIZE;
2330 ff_ac3_common_init();
2332 ret = validate_options(avctx, s);
2336 s->bitstream_mode = avctx->audio_service_type;
2337 if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2338 s->bitstream_mode = 0x7;
2340 s->bits_written = 0;
2341 s->samples_written = 0;
2343 /* calculate crc_inv for both possible frame sizes */
2344 frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
2345 s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2346 if (s->bit_alloc.sr_code == 1) {
2347 frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2348 s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2351 /* set function pointers */
2352 if (CONFIG_AC3_FIXED_ENCODER && s->fixed_point) {
2353 s->mdct_end = ff_ac3_fixed_mdct_end;
2354 s->mdct_init = ff_ac3_fixed_mdct_init;
2355 s->apply_window = ff_ac3_fixed_apply_window;
2356 s->normalize_samples = ff_ac3_fixed_normalize_samples;
2357 s->scale_coefficients = ff_ac3_fixed_scale_coefficients;
2358 s->deinterleave_input_samples = ff_ac3_fixed_deinterleave_input_samples;
2359 s->apply_mdct = ff_ac3_fixed_apply_mdct;
2360 s->apply_channel_coupling = ff_ac3_fixed_apply_channel_coupling;
2361 s->compute_rematrixing_strategy = ff_ac3_fixed_compute_rematrixing_strategy;
2362 } else if (CONFIG_AC3_ENCODER || CONFIG_EAC3_ENCODER) {
2363 s->mdct_end = ff_ac3_float_mdct_end;
2364 s->mdct_init = ff_ac3_float_mdct_init;
2365 s->apply_window = ff_ac3_float_apply_window;
2366 s->normalize_samples = ff_ac3_float_normalize_samples;
2367 s->scale_coefficients = ff_ac3_float_scale_coefficients;
2368 s->deinterleave_input_samples = ff_ac3_float_deinterleave_input_samples;
2369 s->apply_mdct = ff_ac3_float_apply_mdct;
2370 s->apply_channel_coupling = ff_ac3_float_apply_channel_coupling;
2371 s->compute_rematrixing_strategy = ff_ac3_float_compute_rematrixing_strategy;
2373 if (CONFIG_EAC3_ENCODER && s->eac3)
2374 s->output_frame_header = ff_eac3_output_frame_header;
2376 s->output_frame_header = ac3_output_frame_header;
2384 FF_ALLOCZ_OR_GOTO(avctx, s->mdct, sizeof(AC3MDCTContext), init_fail);
2385 ret = s->mdct_init(avctx, s->mdct, 9);
2389 ret = allocate_buffers(avctx);
2393 avctx->coded_frame= avcodec_alloc_frame();
2395 dsputil_init(&s->dsp, avctx);
2396 ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2398 dprint_options(avctx);
2402 ff_ac3_encode_close(avctx);