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 */
530 * Count exponent bits based on bandwidth, coupling, and exponent strategies.
532 static int count_exponent_bits(AC3EncodeContext *s)
535 int nb_groups, bit_count;
538 for (blk = 0; blk < s->num_blocks; blk++) {
539 AC3Block *block = &s->blocks[blk];
540 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
541 int exp_strategy = s->exp_strategy[ch][blk];
542 int cpl = (ch == CPL_CH);
543 int nb_coefs = block->end_freq[ch] - s->start_freq[ch];
545 if (exp_strategy == EXP_REUSE)
548 nb_groups = exponent_group_tab[cpl][exp_strategy-1][nb_coefs];
549 bit_count += 4 + (nb_groups * 7);
559 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
560 * varies depending on exponent strategy and bandwidth.
562 void ff_ac3_group_exponents(AC3EncodeContext *s)
565 int group_size, nb_groups;
567 int delta0, delta1, delta2;
570 for (blk = 0; blk < s->num_blocks; blk++) {
571 AC3Block *block = &s->blocks[blk];
572 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
573 int exp_strategy = s->exp_strategy[ch][blk];
574 if (exp_strategy == EXP_REUSE)
576 cpl = (ch == CPL_CH);
577 group_size = exp_strategy + (exp_strategy == EXP_D45);
578 nb_groups = exponent_group_tab[cpl][exp_strategy-1][block->end_freq[ch]-s->start_freq[ch]];
579 p = block->exp[ch] + s->start_freq[ch] - cpl;
583 block->grouped_exp[ch][0] = exp1;
585 /* remaining exponents are delta encoded */
586 for (i = 1; i <= nb_groups; i++) {
587 /* merge three delta in one code */
591 delta0 = exp1 - exp0 + 2;
592 av_assert2(delta0 >= 0 && delta0 <= 4);
597 delta1 = exp1 - exp0 + 2;
598 av_assert2(delta1 >= 0 && delta1 <= 4);
603 delta2 = exp1 - exp0 + 2;
604 av_assert2(delta2 >= 0 && delta2 <= 4);
606 block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
614 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
615 * Extract exponents from MDCT coefficients, calculate exponent strategies,
616 * and encode final exponents.
618 void ff_ac3_process_exponents(AC3EncodeContext *s)
620 extract_exponents(s);
622 compute_exp_strategy(s);
631 * Count frame bits that are based solely on fixed parameters.
632 * This only has to be run once when the encoder is initialized.
634 static void count_frame_bits_fixed(AC3EncodeContext *s)
636 static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
641 * no dynamic range codes
642 * bit allocation parameters do not change between blocks
643 * no delta bit allocation
650 frame_bits = 16; /* sync info */
652 /* bitstream info header */
655 if (s->num_blocks != 0x6)
658 /* audio frame header */
659 if (s->num_blocks == 6)
662 /* exponent strategy */
663 if (s->use_frame_exp_strategy)
664 frame_bits += 5 * s->fbw_channels;
666 frame_bits += s->num_blocks * 2 * s->fbw_channels;
668 frame_bits += s->num_blocks;
669 /* converter exponent strategy */
670 if (s->num_blks_code != 0x3)
673 frame_bits += s->fbw_channels * 5;
676 /* block start info */
677 if (s->num_blocks != 1)
681 frame_bits += frame_bits_inc[s->channel_mode];
685 for (blk = 0; blk < s->num_blocks; blk++) {
687 /* block switch flags */
688 frame_bits += s->fbw_channels;
691 frame_bits += s->fbw_channels;
697 /* spectral extension */
702 /* exponent strategy */
703 frame_bits += 2 * s->fbw_channels;
707 /* bit allocation params */
710 frame_bits += 2 + 2 + 2 + 2 + 3;
713 /* converter snr offset */
718 /* delta bit allocation */
730 frame_bits += 1 + 16;
732 s->frame_bits_fixed = frame_bits;
737 * Initialize bit allocation.
738 * Set default parameter codes and calculate parameter values.
740 static void bit_alloc_init(AC3EncodeContext *s)
744 /* init default parameters */
745 s->slow_decay_code = 2;
746 s->fast_decay_code = 1;
747 s->slow_gain_code = 1;
748 s->db_per_bit_code = s->eac3 ? 2 : 3;
750 for (ch = 0; ch <= s->channels; ch++)
751 s->fast_gain_code[ch] = 4;
753 /* initial snr offset */
754 s->coarse_snr_offset = 40;
756 /* compute real values */
757 /* currently none of these values change during encoding, so we can just
758 set them once at initialization */
759 s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
760 s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
761 s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
762 s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
763 s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
764 s->bit_alloc.cpl_fast_leak = 0;
765 s->bit_alloc.cpl_slow_leak = 0;
767 count_frame_bits_fixed(s);
772 * Count the bits used to encode the frame, minus exponents and mantissas.
773 * Bits based on fixed parameters have already been counted, so now we just
774 * have to add the bits based on parameters that change during encoding.
776 static void count_frame_bits(AC3EncodeContext *s)
778 AC3EncOptions *opt = &s->options;
784 if (opt->eac3_mixing_metadata) {
785 if (s->channel_mode > AC3_CHMODE_STEREO)
791 frame_bits += s->lfe_on;
792 frame_bits += 1 + 1 + 2;
793 if (s->channel_mode < AC3_CHMODE_STEREO)
797 if (opt->eac3_info_metadata) {
798 frame_bits += 3 + 1 + 1;
799 if (s->channel_mode == AC3_CHMODE_STEREO)
801 if (s->channel_mode >= AC3_CHMODE_2F2R)
804 if (opt->audio_production_info)
805 frame_bits += 5 + 2 + 1;
809 if (s->channel_mode > AC3_CHMODE_MONO) {
811 for (blk = 1; blk < s->num_blocks; blk++) {
812 AC3Block *block = &s->blocks[blk];
814 if (block->new_cpl_strategy)
818 /* coupling exponent strategy */
820 if (s->use_frame_exp_strategy) {
821 frame_bits += 5 * s->cpl_on;
823 for (blk = 0; blk < s->num_blocks; blk++)
824 frame_bits += 2 * s->blocks[blk].cpl_in_use;
828 if (opt->audio_production_info)
830 if (s->bitstream_id == 6) {
831 if (opt->extended_bsi_1)
833 if (opt->extended_bsi_2)
839 for (blk = 0; blk < s->num_blocks; blk++) {
840 AC3Block *block = &s->blocks[blk];
842 /* coupling strategy */
845 if (block->new_cpl_strategy) {
848 if (block->cpl_in_use) {
851 if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO)
852 frame_bits += s->fbw_channels;
853 if (s->channel_mode == AC3_CHMODE_STEREO)
859 frame_bits += s->num_cpl_subbands - 1;
863 /* coupling coordinates */
864 if (block->cpl_in_use) {
865 for (ch = 1; ch <= s->fbw_channels; ch++) {
866 if (block->channel_in_cpl[ch]) {
867 if (!s->eac3 || block->new_cpl_coords[ch] != 2)
869 if (block->new_cpl_coords[ch]) {
871 frame_bits += (4 + 4) * s->num_cpl_bands;
877 /* stereo rematrixing */
878 if (s->channel_mode == AC3_CHMODE_STEREO) {
879 if (!s->eac3 || blk > 0)
881 if (s->blocks[blk].new_rematrixing_strategy)
882 frame_bits += block->num_rematrixing_bands;
885 /* bandwidth codes & gain range */
886 for (ch = 1; ch <= s->fbw_channels; ch++) {
887 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
888 if (!block->channel_in_cpl[ch])
894 /* coupling exponent strategy */
895 if (!s->eac3 && block->cpl_in_use)
898 /* snr offsets and fast gain codes */
901 if (block->new_snr_offsets)
902 frame_bits += 6 + (s->channels + block->cpl_in_use) * (4 + 3);
905 /* coupling leak info */
906 if (block->cpl_in_use) {
907 if (!s->eac3 || block->new_cpl_leak != 2)
909 if (block->new_cpl_leak)
914 s->frame_bits = s->frame_bits_fixed + frame_bits;
919 * Calculate masking curve based on the final exponents.
920 * Also calculate the power spectral densities to use in future calculations.
922 static void bit_alloc_masking(AC3EncodeContext *s)
926 for (blk = 0; blk < s->num_blocks; blk++) {
927 AC3Block *block = &s->blocks[blk];
928 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
929 /* We only need psd and mask for calculating bap.
930 Since we currently do not calculate bap when exponent
931 strategy is EXP_REUSE we do not need to calculate psd or mask. */
932 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
933 ff_ac3_bit_alloc_calc_psd(block->exp[ch], s->start_freq[ch],
934 block->end_freq[ch], block->psd[ch],
935 block->band_psd[ch]);
936 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
937 s->start_freq[ch], block->end_freq[ch],
938 ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
939 ch == s->lfe_channel,
940 DBA_NONE, 0, NULL, NULL, NULL,
949 * Ensure that bap for each block and channel point to the current bap_buffer.
950 * They may have been switched during the bit allocation search.
952 static void reset_block_bap(AC3EncodeContext *s)
957 if (s->ref_bap[0][0] == s->bap_buffer && s->ref_bap_set)
960 ref_bap = s->bap_buffer;
961 for (ch = 0; ch <= s->channels; ch++) {
962 for (blk = 0; blk < s->num_blocks; blk++)
963 s->ref_bap[ch][blk] = ref_bap + AC3_MAX_COEFS * s->exp_ref_block[ch][blk];
964 ref_bap += AC3_MAX_COEFS * s->num_blocks;
971 * Initialize mantissa counts.
972 * These are set so that they are padded to the next whole group size when bits
973 * are counted in compute_mantissa_size.
975 static void count_mantissa_bits_init(uint16_t mant_cnt[AC3_MAX_BLOCKS][16])
979 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
980 memset(mant_cnt[blk], 0, sizeof(mant_cnt[blk]));
981 mant_cnt[blk][1] = mant_cnt[blk][2] = 2;
982 mant_cnt[blk][4] = 1;
988 * Update mantissa bit counts for all blocks in 1 channel in a given bandwidth
991 static void count_mantissa_bits_update_ch(AC3EncodeContext *s, int ch,
992 uint16_t mant_cnt[AC3_MAX_BLOCKS][16],
997 for (blk = 0; blk < s->num_blocks; blk++) {
998 AC3Block *block = &s->blocks[blk];
999 if (ch == CPL_CH && !block->cpl_in_use)
1001 s->ac3dsp.update_bap_counts(mant_cnt[blk],
1002 s->ref_bap[ch][blk] + start,
1003 FFMIN(end, block->end_freq[ch]) - start);
1009 * Count the number of mantissa bits in the frame based on the bap values.
1011 static int count_mantissa_bits(AC3EncodeContext *s)
1013 int ch, max_end_freq;
1014 LOCAL_ALIGNED_16(uint16_t, mant_cnt, [AC3_MAX_BLOCKS], [16]);
1016 count_mantissa_bits_init(mant_cnt);
1018 max_end_freq = s->bandwidth_code * 3 + 73;
1019 for (ch = !s->cpl_enabled; ch <= s->channels; ch++)
1020 count_mantissa_bits_update_ch(s, ch, mant_cnt, s->start_freq[ch],
1023 return s->ac3dsp.compute_mantissa_size(mant_cnt);
1028 * Run the bit allocation with a given SNR offset.
1029 * This calculates the bit allocation pointers that will be used to determine
1030 * the quantization of each mantissa.
1031 * @return the number of bits needed for mantissas if the given SNR offset is
1034 static int bit_alloc(AC3EncodeContext *s, int snr_offset)
1038 snr_offset = (snr_offset - 240) << 2;
1041 for (blk = 0; blk < s->num_blocks; blk++) {
1042 AC3Block *block = &s->blocks[blk];
1044 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1045 /* Currently the only bit allocation parameters which vary across
1046 blocks within a frame are the exponent values. We can take
1047 advantage of that by reusing the bit allocation pointers
1048 whenever we reuse exponents. */
1049 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1050 s->ac3dsp.bit_alloc_calc_bap(block->mask[ch], block->psd[ch],
1051 s->start_freq[ch], block->end_freq[ch],
1052 snr_offset, s->bit_alloc.floor,
1053 ff_ac3_bap_tab, s->ref_bap[ch][blk]);
1057 return count_mantissa_bits(s);
1062 * Constant bitrate bit allocation search.
1063 * Find the largest SNR offset that will allow data to fit in the frame.
1065 static int cbr_bit_allocation(AC3EncodeContext *s)
1069 int snr_offset, snr_incr;
1071 bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1073 return AVERROR(EINVAL);
1075 snr_offset = s->coarse_snr_offset << 4;
1077 /* if previous frame SNR offset was 1023, check if current frame can also
1078 use SNR offset of 1023. if so, skip the search. */
1079 if ((snr_offset | s->fine_snr_offset[1]) == 1023) {
1080 if (bit_alloc(s, 1023) <= bits_left)
1084 while (snr_offset >= 0 &&
1085 bit_alloc(s, snr_offset) > bits_left) {
1089 return AVERROR(EINVAL);
1091 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1092 for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1093 while (snr_offset + snr_incr <= 1023 &&
1094 bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1095 snr_offset += snr_incr;
1096 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1099 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1102 s->coarse_snr_offset = snr_offset >> 4;
1103 for (ch = !s->cpl_on; ch <= s->channels; ch++)
1104 s->fine_snr_offset[ch] = snr_offset & 0xF;
1111 * Perform bit allocation search.
1112 * Finds the SNR offset value that maximizes quality and fits in the specified
1113 * frame size. Output is the SNR offset and a set of bit allocation pointers
1114 * used to quantize the mantissas.
1116 int ff_ac3_compute_bit_allocation(AC3EncodeContext *s)
1118 count_frame_bits(s);
1120 s->exponent_bits = count_exponent_bits(s);
1122 bit_alloc_masking(s);
1124 return cbr_bit_allocation(s);
1129 * Symmetric quantization on 'levels' levels.
1131 static inline int sym_quant(int c, int e, int levels)
1133 int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1134 av_assert2(v >= 0 && v < levels);
1140 * Asymmetric quantization on 2^qbits levels.
1142 static inline int asym_quant(int c, int e, int qbits)
1146 c = (((c << e) >> (24 - qbits)) + 1) >> 1;
1147 m = (1 << (qbits-1));
1150 av_assert2(c >= -m);
1156 * Quantize a set of mantissas for a single channel in a single block.
1158 static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1159 uint8_t *exp, uint8_t *bap,
1160 int16_t *qmant, int start_freq,
1165 for (i = start_freq; i < end_freq; i++) {
1166 int c = fixed_coef[i];
1172 v = sym_quant(c, e, 3);
1173 switch (s->mant1_cnt) {
1175 s->qmant1_ptr = &qmant[i];
1180 *s->qmant1_ptr += 3 * v;
1185 *s->qmant1_ptr += v;
1192 v = sym_quant(c, e, 5);
1193 switch (s->mant2_cnt) {
1195 s->qmant2_ptr = &qmant[i];
1200 *s->qmant2_ptr += 5 * v;
1205 *s->qmant2_ptr += v;
1212 v = sym_quant(c, e, 7);
1215 v = sym_quant(c, e, 11);
1216 switch (s->mant4_cnt) {
1218 s->qmant4_ptr = &qmant[i];
1223 *s->qmant4_ptr += v;
1230 v = sym_quant(c, e, 15);
1233 v = asym_quant(c, e, 14);
1236 v = asym_quant(c, e, 16);
1239 v = asym_quant(c, e, v - 1);
1248 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1250 void ff_ac3_quantize_mantissas(AC3EncodeContext *s)
1252 int blk, ch, ch0=0, got_cpl;
1254 for (blk = 0; blk < s->num_blocks; blk++) {
1255 AC3Block *block = &s->blocks[blk];
1258 got_cpl = !block->cpl_in_use;
1259 for (ch = 1; ch <= s->channels; ch++) {
1260 if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1265 quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1266 s->blocks[s->exp_ref_block[ch][blk]].exp[ch],
1267 s->ref_bap[ch][blk], block->qmant[ch],
1268 s->start_freq[ch], block->end_freq[ch]);
1277 * Write the AC-3 frame header to the output bitstream.
1279 static void ac3_output_frame_header(AC3EncodeContext *s)
1281 AC3EncOptions *opt = &s->options;
1283 put_bits(&s->pb, 16, 0x0b77); /* frame header */
1284 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
1285 put_bits(&s->pb, 2, s->bit_alloc.sr_code);
1286 put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1287 put_bits(&s->pb, 5, s->bitstream_id);
1288 put_bits(&s->pb, 3, s->bitstream_mode);
1289 put_bits(&s->pb, 3, s->channel_mode);
1290 if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1291 put_bits(&s->pb, 2, s->center_mix_level);
1292 if (s->channel_mode & 0x04)
1293 put_bits(&s->pb, 2, s->surround_mix_level);
1294 if (s->channel_mode == AC3_CHMODE_STEREO)
1295 put_bits(&s->pb, 2, opt->dolby_surround_mode);
1296 put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1297 put_bits(&s->pb, 5, -opt->dialogue_level);
1298 put_bits(&s->pb, 1, 0); /* no compression control word */
1299 put_bits(&s->pb, 1, 0); /* no lang code */
1300 put_bits(&s->pb, 1, opt->audio_production_info);
1301 if (opt->audio_production_info) {
1302 put_bits(&s->pb, 5, opt->mixing_level - 80);
1303 put_bits(&s->pb, 2, opt->room_type);
1305 put_bits(&s->pb, 1, opt->copyright);
1306 put_bits(&s->pb, 1, opt->original);
1307 if (s->bitstream_id == 6) {
1308 /* alternate bit stream syntax */
1309 put_bits(&s->pb, 1, opt->extended_bsi_1);
1310 if (opt->extended_bsi_1) {
1311 put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1312 put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1313 put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1314 put_bits(&s->pb, 3, s->loro_center_mix_level);
1315 put_bits(&s->pb, 3, s->loro_surround_mix_level);
1317 put_bits(&s->pb, 1, opt->extended_bsi_2);
1318 if (opt->extended_bsi_2) {
1319 put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1320 put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1321 put_bits(&s->pb, 1, opt->ad_converter_type);
1322 put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
1325 put_bits(&s->pb, 1, 0); /* no time code 1 */
1326 put_bits(&s->pb, 1, 0); /* no time code 2 */
1328 put_bits(&s->pb, 1, 0); /* no additional bit stream info */
1333 * Write one audio block to the output bitstream.
1335 static void output_audio_block(AC3EncodeContext *s, int blk)
1337 int ch, i, baie, bnd, got_cpl;
1339 AC3Block *block = &s->blocks[blk];
1341 /* block switching */
1343 for (ch = 0; ch < s->fbw_channels; ch++)
1344 put_bits(&s->pb, 1, 0);
1349 for (ch = 0; ch < s->fbw_channels; ch++)
1350 put_bits(&s->pb, 1, 1);
1353 /* dynamic range codes */
1354 put_bits(&s->pb, 1, 0);
1356 /* spectral extension */
1358 put_bits(&s->pb, 1, 0);
1360 /* channel coupling */
1362 put_bits(&s->pb, 1, block->new_cpl_strategy);
1363 if (block->new_cpl_strategy) {
1365 put_bits(&s->pb, 1, block->cpl_in_use);
1366 if (block->cpl_in_use) {
1367 int start_sub, end_sub;
1369 put_bits(&s->pb, 1, 0); /* enhanced coupling */
1370 if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO) {
1371 for (ch = 1; ch <= s->fbw_channels; ch++)
1372 put_bits(&s->pb, 1, block->channel_in_cpl[ch]);
1374 if (s->channel_mode == AC3_CHMODE_STEREO)
1375 put_bits(&s->pb, 1, 0); /* phase flags in use */
1376 start_sub = (s->start_freq[CPL_CH] - 37) / 12;
1377 end_sub = (s->cpl_end_freq - 37) / 12;
1378 put_bits(&s->pb, 4, start_sub);
1379 put_bits(&s->pb, 4, end_sub - 3);
1380 /* coupling band structure */
1382 put_bits(&s->pb, 1, 0); /* use default */
1384 for (bnd = start_sub+1; bnd < end_sub; bnd++)
1385 put_bits(&s->pb, 1, ff_eac3_default_cpl_band_struct[bnd]);
1390 /* coupling coordinates */
1391 if (block->cpl_in_use) {
1392 for (ch = 1; ch <= s->fbw_channels; ch++) {
1393 if (block->channel_in_cpl[ch]) {
1394 if (!s->eac3 || block->new_cpl_coords[ch] != 2)
1395 put_bits(&s->pb, 1, block->new_cpl_coords[ch]);
1396 if (block->new_cpl_coords[ch]) {
1397 put_bits(&s->pb, 2, block->cpl_master_exp[ch]);
1398 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
1399 put_bits(&s->pb, 4, block->cpl_coord_exp [ch][bnd]);
1400 put_bits(&s->pb, 4, block->cpl_coord_mant[ch][bnd]);
1407 /* stereo rematrixing */
1408 if (s->channel_mode == AC3_CHMODE_STEREO) {
1409 if (!s->eac3 || blk > 0)
1410 put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1411 if (block->new_rematrixing_strategy) {
1412 /* rematrixing flags */
1413 for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++)
1414 put_bits(&s->pb, 1, block->rematrixing_flags[bnd]);
1418 /* exponent strategy */
1420 for (ch = !block->cpl_in_use; ch <= s->fbw_channels; ch++)
1421 put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1423 put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1427 for (ch = 1; ch <= s->fbw_channels; ch++) {
1428 if (s->exp_strategy[ch][blk] != EXP_REUSE && !block->channel_in_cpl[ch])
1429 put_bits(&s->pb, 6, s->bandwidth_code);
1433 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1435 int cpl = (ch == CPL_CH);
1437 if (s->exp_strategy[ch][blk] == EXP_REUSE)
1441 put_bits(&s->pb, 4, block->grouped_exp[ch][0] >> cpl);
1443 /* exponent groups */
1444 nb_groups = exponent_group_tab[cpl][s->exp_strategy[ch][blk]-1][block->end_freq[ch]-s->start_freq[ch]];
1445 for (i = 1; i <= nb_groups; i++)
1446 put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1448 /* gain range info */
1449 if (ch != s->lfe_channel && !cpl)
1450 put_bits(&s->pb, 2, 0);
1453 /* bit allocation info */
1456 put_bits(&s->pb, 1, baie);
1458 put_bits(&s->pb, 2, s->slow_decay_code);
1459 put_bits(&s->pb, 2, s->fast_decay_code);
1460 put_bits(&s->pb, 2, s->slow_gain_code);
1461 put_bits(&s->pb, 2, s->db_per_bit_code);
1462 put_bits(&s->pb, 3, s->floor_code);
1468 put_bits(&s->pb, 1, block->new_snr_offsets);
1469 if (block->new_snr_offsets) {
1470 put_bits(&s->pb, 6, s->coarse_snr_offset);
1471 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1472 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1473 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1477 put_bits(&s->pb, 1, 0); /* no converter snr offset */
1481 if (block->cpl_in_use) {
1482 if (!s->eac3 || block->new_cpl_leak != 2)
1483 put_bits(&s->pb, 1, block->new_cpl_leak);
1484 if (block->new_cpl_leak) {
1485 put_bits(&s->pb, 3, s->bit_alloc.cpl_fast_leak);
1486 put_bits(&s->pb, 3, s->bit_alloc.cpl_slow_leak);
1491 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1492 put_bits(&s->pb, 1, 0); /* no data to skip */
1496 got_cpl = !block->cpl_in_use;
1497 for (ch = 1; ch <= s->channels; ch++) {
1500 if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1505 for (i = s->start_freq[ch]; i < block->end_freq[ch]; i++) {
1506 q = block->qmant[ch][i];
1507 b = s->ref_bap[ch][blk][i];
1510 case 1: if (q != 128) put_bits (&s->pb, 5, q); break;
1511 case 2: if (q != 128) put_bits (&s->pb, 7, q); break;
1512 case 3: put_sbits(&s->pb, 3, q); break;
1513 case 4: if (q != 128) put_bits (&s->pb, 7, q); break;
1514 case 14: put_sbits(&s->pb, 14, q); break;
1515 case 15: put_sbits(&s->pb, 16, q); break;
1516 default: put_sbits(&s->pb, b-1, q); break;
1525 /** CRC-16 Polynomial */
1526 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1529 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1546 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1552 r = mul_poly(r, a, poly);
1553 a = mul_poly(a, a, poly);
1561 * Fill the end of the frame with 0's and compute the two CRCs.
1563 static void output_frame_end(AC3EncodeContext *s)
1565 const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1566 int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1569 frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1571 /* pad the remainder of the frame with zeros */
1572 av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1573 flush_put_bits(&s->pb);
1575 pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1576 av_assert2(pad_bytes >= 0);
1578 memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1582 crc2_partial = av_crc(crc_ctx, 0, frame + 2, s->frame_size - 5);
1585 /* this is not so easy because it is at the beginning of the data... */
1586 crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1587 crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1588 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1589 AV_WB16(frame + 2, crc1);
1592 crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1593 s->frame_size - frame_size_58 - 3);
1595 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1596 /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1597 if (crc2 == 0x770B) {
1598 frame[s->frame_size - 3] ^= 0x1;
1599 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1601 crc2 = av_bswap16(crc2);
1602 AV_WB16(frame + s->frame_size - 2, crc2);
1607 * Write the frame to the output bitstream.
1609 void ff_ac3_output_frame(AC3EncodeContext *s, unsigned char *frame)
1613 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1615 s->output_frame_header(s);
1617 for (blk = 0; blk < s->num_blocks; blk++)
1618 output_audio_block(s, blk);
1620 output_frame_end(s);
1624 static void dprint_options(AC3EncodeContext *s)
1627 AVCodecContext *avctx = s->avctx;
1628 AC3EncOptions *opt = &s->options;
1631 switch (s->bitstream_id) {
1632 case 6: av_strlcpy(strbuf, "AC-3 (alt syntax)", 32); break;
1633 case 8: av_strlcpy(strbuf, "AC-3 (standard)", 32); break;
1634 case 9: av_strlcpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
1635 case 10: av_strlcpy(strbuf, "AC-3 (dnet quater-rate)", 32); break;
1636 case 16: av_strlcpy(strbuf, "E-AC-3 (enhanced)", 32); break;
1637 default: snprintf(strbuf, 32, "ERROR");
1639 av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
1640 av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
1641 av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
1642 av_dlog(avctx, "channel_layout: %s\n", strbuf);
1643 av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
1644 av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
1645 av_dlog(avctx, "blocks/frame: %d (code=%d)\n", s->num_blocks, s->num_blks_code);
1647 av_dlog(avctx, "cutoff: %d\n", s->cutoff);
1649 av_dlog(avctx, "per_frame_metadata: %s\n",
1650 opt->allow_per_frame_metadata?"on":"off");
1652 av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
1653 s->center_mix_level);
1655 av_dlog(avctx, "center_mixlev: {not written}\n");
1656 if (s->has_surround)
1657 av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
1658 s->surround_mix_level);
1660 av_dlog(avctx, "surround_mixlev: {not written}\n");
1661 if (opt->audio_production_info) {
1662 av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
1663 switch (opt->room_type) {
1664 case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1665 case AC3ENC_OPT_LARGE_ROOM: av_strlcpy(strbuf, "large", 32); break;
1666 case AC3ENC_OPT_SMALL_ROOM: av_strlcpy(strbuf, "small", 32); break;
1667 default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
1669 av_dlog(avctx, "room_type: %s\n", strbuf);
1671 av_dlog(avctx, "mixing_level: {not written}\n");
1672 av_dlog(avctx, "room_type: {not written}\n");
1674 av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
1675 av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
1676 if (s->channel_mode == AC3_CHMODE_STEREO) {
1677 switch (opt->dolby_surround_mode) {
1678 case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1679 case AC3ENC_OPT_MODE_ON: av_strlcpy(strbuf, "on", 32); break;
1680 case AC3ENC_OPT_MODE_OFF: av_strlcpy(strbuf, "off", 32); break;
1681 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
1683 av_dlog(avctx, "dsur_mode: %s\n", strbuf);
1685 av_dlog(avctx, "dsur_mode: {not written}\n");
1687 av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
1689 if (s->bitstream_id == 6) {
1690 if (opt->extended_bsi_1) {
1691 switch (opt->preferred_stereo_downmix) {
1692 case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1693 case AC3ENC_OPT_DOWNMIX_LTRT: av_strlcpy(strbuf, "ltrt", 32); break;
1694 case AC3ENC_OPT_DOWNMIX_LORO: av_strlcpy(strbuf, "loro", 32); break;
1695 default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
1697 av_dlog(avctx, "dmix_mode: %s\n", strbuf);
1698 av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
1699 opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
1700 av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
1701 opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
1702 av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
1703 opt->loro_center_mix_level, s->loro_center_mix_level);
1704 av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
1705 opt->loro_surround_mix_level, s->loro_surround_mix_level);
1707 av_dlog(avctx, "extended bitstream info 1: {not written}\n");
1709 if (opt->extended_bsi_2) {
1710 switch (opt->dolby_surround_ex_mode) {
1711 case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1712 case AC3ENC_OPT_MODE_ON: av_strlcpy(strbuf, "on", 32); break;
1713 case AC3ENC_OPT_MODE_OFF: av_strlcpy(strbuf, "off", 32); break;
1714 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
1716 av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
1717 switch (opt->dolby_headphone_mode) {
1718 case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1719 case AC3ENC_OPT_MODE_ON: av_strlcpy(strbuf, "on", 32); break;
1720 case AC3ENC_OPT_MODE_OFF: av_strlcpy(strbuf, "off", 32); break;
1721 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
1723 av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
1725 switch (opt->ad_converter_type) {
1726 case AC3ENC_OPT_ADCONV_STANDARD: av_strlcpy(strbuf, "standard", 32); break;
1727 case AC3ENC_OPT_ADCONV_HDCD: av_strlcpy(strbuf, "hdcd", 32); break;
1728 default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
1730 av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
1732 av_dlog(avctx, "extended bitstream info 2: {not written}\n");
1739 #define FLT_OPTION_THRESHOLD 0.01
1741 static int validate_float_option(float v, const float *v_list, int v_list_size)
1745 for (i = 0; i < v_list_size; i++) {
1746 if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
1747 v > (v_list[i] - FLT_OPTION_THRESHOLD))
1750 if (i == v_list_size)
1757 static void validate_mix_level(void *log_ctx, const char *opt_name,
1758 float *opt_param, const float *list,
1759 int list_size, int default_value, int min_value,
1762 int mixlev = validate_float_option(*opt_param, list, list_size);
1763 if (mixlev < min_value) {
1764 mixlev = default_value;
1765 if (*opt_param >= 0.0) {
1766 av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
1767 "default value: %0.3f\n", opt_name, list[mixlev]);
1770 *opt_param = list[mixlev];
1771 *ctx_param = mixlev;
1776 * Validate metadata options as set by AVOption system.
1777 * These values can optionally be changed per-frame.
1779 int ff_ac3_validate_metadata(AC3EncodeContext *s)
1781 AVCodecContext *avctx = s->avctx;
1782 AC3EncOptions *opt = &s->options;
1784 opt->audio_production_info = 0;
1785 opt->extended_bsi_1 = 0;
1786 opt->extended_bsi_2 = 0;
1787 opt->eac3_mixing_metadata = 0;
1788 opt->eac3_info_metadata = 0;
1790 /* determine mixing metadata / xbsi1 use */
1791 if (s->channel_mode > AC3_CHMODE_STEREO && opt->preferred_stereo_downmix != AC3ENC_OPT_NONE) {
1792 opt->extended_bsi_1 = 1;
1793 opt->eac3_mixing_metadata = 1;
1795 if (s->has_center &&
1796 (opt->ltrt_center_mix_level >= 0 || opt->loro_center_mix_level >= 0)) {
1797 opt->extended_bsi_1 = 1;
1798 opt->eac3_mixing_metadata = 1;
1800 if (s->has_surround &&
1801 (opt->ltrt_surround_mix_level >= 0 || opt->loro_surround_mix_level >= 0)) {
1802 opt->extended_bsi_1 = 1;
1803 opt->eac3_mixing_metadata = 1;
1807 /* determine info metadata use */
1808 if (avctx->audio_service_type != AV_AUDIO_SERVICE_TYPE_MAIN)
1809 opt->eac3_info_metadata = 1;
1810 if (opt->copyright != AC3ENC_OPT_NONE || opt->original != AC3ENC_OPT_NONE)
1811 opt->eac3_info_metadata = 1;
1812 if (s->channel_mode == AC3_CHMODE_STEREO &&
1813 (opt->dolby_headphone_mode != AC3ENC_OPT_NONE || opt->dolby_surround_mode != AC3ENC_OPT_NONE))
1814 opt->eac3_info_metadata = 1;
1815 if (s->channel_mode >= AC3_CHMODE_2F2R && opt->dolby_surround_ex_mode != AC3ENC_OPT_NONE)
1816 opt->eac3_info_metadata = 1;
1817 if (opt->mixing_level != AC3ENC_OPT_NONE || opt->room_type != AC3ENC_OPT_NONE ||
1818 opt->ad_converter_type != AC3ENC_OPT_NONE) {
1819 opt->audio_production_info = 1;
1820 opt->eac3_info_metadata = 1;
1823 /* determine audio production info use */
1824 if (opt->mixing_level != AC3ENC_OPT_NONE || opt->room_type != AC3ENC_OPT_NONE)
1825 opt->audio_production_info = 1;
1827 /* determine xbsi2 use */
1828 if (s->channel_mode >= AC3_CHMODE_2F2R && opt->dolby_surround_ex_mode != AC3ENC_OPT_NONE)
1829 opt->extended_bsi_2 = 1;
1830 if (s->channel_mode == AC3_CHMODE_STEREO && opt->dolby_headphone_mode != AC3ENC_OPT_NONE)
1831 opt->extended_bsi_2 = 1;
1832 if (opt->ad_converter_type != AC3ENC_OPT_NONE)
1833 opt->extended_bsi_2 = 1;
1836 /* validate AC-3 mixing levels */
1838 if (s->has_center) {
1839 validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
1840 cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
1841 &s->center_mix_level);
1843 if (s->has_surround) {
1844 validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
1845 surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
1846 &s->surround_mix_level);
1850 /* validate extended bsi 1 / mixing metadata */
1851 if (opt->extended_bsi_1 || opt->eac3_mixing_metadata) {
1852 /* default preferred stereo downmix */
1853 if (opt->preferred_stereo_downmix == AC3ENC_OPT_NONE)
1854 opt->preferred_stereo_downmix = AC3ENC_OPT_NOT_INDICATED;
1855 if (!s->eac3 || s->has_center) {
1856 /* validate Lt/Rt center mix level */
1857 validate_mix_level(avctx, "ltrt_center_mix_level",
1858 &opt->ltrt_center_mix_level, extmixlev_options,
1859 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1860 &s->ltrt_center_mix_level);
1861 /* validate Lo/Ro center mix level */
1862 validate_mix_level(avctx, "loro_center_mix_level",
1863 &opt->loro_center_mix_level, extmixlev_options,
1864 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1865 &s->loro_center_mix_level);
1867 if (!s->eac3 || s->has_surround) {
1868 /* validate Lt/Rt surround mix level */
1869 validate_mix_level(avctx, "ltrt_surround_mix_level",
1870 &opt->ltrt_surround_mix_level, extmixlev_options,
1871 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1872 &s->ltrt_surround_mix_level);
1873 /* validate Lo/Ro surround mix level */
1874 validate_mix_level(avctx, "loro_surround_mix_level",
1875 &opt->loro_surround_mix_level, extmixlev_options,
1876 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1877 &s->loro_surround_mix_level);
1881 /* validate audio service type / channels combination */
1882 if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
1883 avctx->channels == 1) ||
1884 ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
1885 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
1886 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
1887 && avctx->channels > 1)) {
1888 av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
1889 "specified number of channels\n");
1890 return AVERROR(EINVAL);
1893 /* validate extended bsi 2 / info metadata */
1894 if (opt->extended_bsi_2 || opt->eac3_info_metadata) {
1895 /* default dolby headphone mode */
1896 if (opt->dolby_headphone_mode == AC3ENC_OPT_NONE)
1897 opt->dolby_headphone_mode = AC3ENC_OPT_NOT_INDICATED;
1898 /* default dolby surround ex mode */
1899 if (opt->dolby_surround_ex_mode == AC3ENC_OPT_NONE)
1900 opt->dolby_surround_ex_mode = AC3ENC_OPT_NOT_INDICATED;
1901 /* default A/D converter type */
1902 if (opt->ad_converter_type == AC3ENC_OPT_NONE)
1903 opt->ad_converter_type = AC3ENC_OPT_ADCONV_STANDARD;
1906 /* copyright & original defaults */
1907 if (!s->eac3 || opt->eac3_info_metadata) {
1908 /* default copyright */
1909 if (opt->copyright == AC3ENC_OPT_NONE)
1910 opt->copyright = AC3ENC_OPT_OFF;
1911 /* default original */
1912 if (opt->original == AC3ENC_OPT_NONE)
1913 opt->original = AC3ENC_OPT_ON;
1916 /* dolby surround mode default */
1917 if (!s->eac3 || opt->eac3_info_metadata) {
1918 if (opt->dolby_surround_mode == AC3ENC_OPT_NONE)
1919 opt->dolby_surround_mode = AC3ENC_OPT_NOT_INDICATED;
1922 /* validate audio production info */
1923 if (opt->audio_production_info) {
1924 if (opt->mixing_level == AC3ENC_OPT_NONE) {
1925 av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
1926 "room_type is set\n");
1927 return AVERROR(EINVAL);
1929 if (opt->mixing_level < 80) {
1930 av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
1931 "80dB and 111dB\n");
1932 return AVERROR(EINVAL);
1934 /* default room type */
1935 if (opt->room_type == AC3ENC_OPT_NONE)
1936 opt->room_type = AC3ENC_OPT_NOT_INDICATED;
1939 /* set bitstream id for alternate bitstream syntax */
1940 if (!s->eac3 && (opt->extended_bsi_1 || opt->extended_bsi_2)) {
1941 if (s->bitstream_id > 8 && s->bitstream_id < 11) {
1942 static int warn_once = 1;
1944 av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
1945 "not compatible with reduced samplerates. writing of "
1946 "extended bitstream information will be disabled.\n");
1950 s->bitstream_id = 6;
1959 * Finalize encoding and free any memory allocated by the encoder.
1961 av_cold int ff_ac3_encode_close(AVCodecContext *avctx)
1964 AC3EncodeContext *s = avctx->priv_data;
1966 av_freep(&s->windowed_samples);
1967 for (ch = 0; ch < s->channels; ch++)
1968 av_freep(&s->planar_samples[ch]);
1969 av_freep(&s->planar_samples);
1970 av_freep(&s->bap_buffer);
1971 av_freep(&s->bap1_buffer);
1972 av_freep(&s->mdct_coef_buffer);
1973 av_freep(&s->fixed_coef_buffer);
1974 av_freep(&s->exp_buffer);
1975 av_freep(&s->grouped_exp_buffer);
1976 av_freep(&s->psd_buffer);
1977 av_freep(&s->band_psd_buffer);
1978 av_freep(&s->mask_buffer);
1979 av_freep(&s->qmant_buffer);
1980 av_freep(&s->cpl_coord_exp_buffer);
1981 av_freep(&s->cpl_coord_mant_buffer);
1982 for (blk = 0; blk < s->num_blocks; blk++) {
1983 AC3Block *block = &s->blocks[blk];
1984 av_freep(&block->mdct_coef);
1985 av_freep(&block->fixed_coef);
1986 av_freep(&block->exp);
1987 av_freep(&block->grouped_exp);
1988 av_freep(&block->psd);
1989 av_freep(&block->band_psd);
1990 av_freep(&block->mask);
1991 av_freep(&block->qmant);
1992 av_freep(&block->cpl_coord_exp);
1993 av_freep(&block->cpl_coord_mant);
1998 av_freep(&avctx->coded_frame);
2004 * Set channel information during initialization.
2006 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
2007 int64_t *channel_layout)
2011 if (channels < 1 || channels > AC3_MAX_CHANNELS)
2012 return AVERROR(EINVAL);
2013 if ((uint64_t)*channel_layout > 0x7FF)
2014 return AVERROR(EINVAL);
2015 ch_layout = *channel_layout;
2017 ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
2019 s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
2020 s->channels = channels;
2021 s->fbw_channels = channels - s->lfe_on;
2022 s->lfe_channel = s->lfe_on ? s->fbw_channels + 1 : -1;
2024 ch_layout -= AV_CH_LOW_FREQUENCY;
2026 switch (ch_layout) {
2027 case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
2028 case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
2029 case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
2030 case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
2031 case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
2032 case AV_CH_LAYOUT_QUAD:
2033 case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
2034 case AV_CH_LAYOUT_5POINT0:
2035 case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
2037 return AVERROR(EINVAL);
2039 s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
2040 s->has_surround = s->channel_mode & 0x04;
2042 s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
2043 *channel_layout = ch_layout;
2045 *channel_layout |= AV_CH_LOW_FREQUENCY;
2051 static av_cold int validate_options(AC3EncodeContext *s)
2053 AVCodecContext *avctx = s->avctx;
2056 /* validate channel layout */
2057 if (!avctx->channel_layout) {
2058 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
2059 "encoder will guess the layout, but it "
2060 "might be incorrect.\n");
2062 ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
2064 av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
2068 /* validate sample rate */
2069 /* note: max_sr could be changed from 2 to 5 for E-AC-3 once we find a
2070 decoder that supports half sample rate so we can validate that
2071 the generated files are correct. */
2072 max_sr = s->eac3 ? 2 : 8;
2073 for (i = 0; i <= max_sr; i++) {
2074 if ((ff_ac3_sample_rate_tab[i % 3] >> (i / 3)) == avctx->sample_rate)
2078 av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
2079 return AVERROR(EINVAL);
2081 s->sample_rate = avctx->sample_rate;
2082 s->bit_alloc.sr_shift = i / 3;
2083 s->bit_alloc.sr_code = i % 3;
2084 s->bitstream_id = s->eac3 ? 16 : 8 + s->bit_alloc.sr_shift;
2086 /* validate bit rate */
2088 int max_br, min_br, wpf, min_br_dist, min_br_code;
2089 int num_blks_code, num_blocks, frame_samples;
2091 /* calculate min/max bitrate */
2092 /* TODO: More testing with 3 and 2 blocks. All E-AC-3 samples I've
2093 found use either 6 blocks or 1 block, even though 2 or 3 blocks
2094 would work as far as the bit rate is concerned. */
2095 for (num_blks_code = 3; num_blks_code >= 0; num_blks_code--) {
2096 num_blocks = ((int[]){ 1, 2, 3, 6 })[num_blks_code];
2097 frame_samples = AC3_BLOCK_SIZE * num_blocks;
2098 max_br = 2048 * s->sample_rate / frame_samples * 16;
2099 min_br = ((s->sample_rate + (frame_samples-1)) / frame_samples) * 16;
2100 if (avctx->bit_rate <= max_br)
2103 if (avctx->bit_rate < min_br || avctx->bit_rate > max_br) {
2104 av_log(avctx, AV_LOG_ERROR, "invalid bit rate. must be %d to %d "
2105 "for this sample rate\n", min_br, max_br);
2106 return AVERROR(EINVAL);
2108 s->num_blks_code = num_blks_code;
2109 s->num_blocks = num_blocks;
2111 /* calculate words-per-frame for the selected bitrate */
2112 wpf = (avctx->bit_rate / 16) * frame_samples / s->sample_rate;
2113 av_assert1(wpf > 0 && wpf <= 2048);
2115 /* find the closest AC-3 bitrate code to the selected bitrate.
2116 this is needed for lookup tables for bandwidth and coupling
2117 parameter selection */
2119 min_br_dist = INT_MAX;
2120 for (i = 0; i < 19; i++) {
2121 int br_dist = abs(ff_ac3_bitrate_tab[i] * 1000 - avctx->bit_rate);
2122 if (br_dist < min_br_dist) {
2123 min_br_dist = br_dist;
2128 /* make sure the minimum frame size is below the average frame size */
2129 s->frame_size_code = min_br_code << 1;
2130 while (wpf > 1 && wpf * s->sample_rate / AC3_FRAME_SIZE * 16 > avctx->bit_rate)
2132 s->frame_size_min = 2 * wpf;
2134 for (i = 0; i < 19; i++) {
2135 if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
2139 av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2140 return AVERROR(EINVAL);
2142 s->frame_size_code = i << 1;
2143 s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2144 s->num_blks_code = 0x3;
2147 s->bit_rate = avctx->bit_rate;
2148 s->frame_size = s->frame_size_min;
2150 /* validate cutoff */
2151 if (avctx->cutoff < 0) {
2152 av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2153 return AVERROR(EINVAL);
2155 s->cutoff = avctx->cutoff;
2156 if (s->cutoff > (s->sample_rate >> 1))
2157 s->cutoff = s->sample_rate >> 1;
2159 ret = ff_ac3_validate_metadata(s);
2163 s->rematrixing_enabled = s->options.stereo_rematrixing &&
2164 (s->channel_mode == AC3_CHMODE_STEREO);
2166 s->cpl_enabled = s->options.channel_coupling &&
2167 s->channel_mode >= AC3_CHMODE_STEREO;
2174 * Set bandwidth for all channels.
2175 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2176 * default value will be used.
2178 static av_cold void set_bandwidth(AC3EncodeContext *s)
2181 int av_uninit(cpl_start);
2184 /* calculate bandwidth based on user-specified cutoff frequency */
2186 fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2187 s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2189 /* use default bandwidth setting */
2190 s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2193 /* set number of coefficients for each channel */
2194 for (ch = 1; ch <= s->fbw_channels; ch++) {
2195 s->start_freq[ch] = 0;
2196 for (blk = 0; blk < s->num_blocks; blk++)
2197 s->blocks[blk].end_freq[ch] = s->bandwidth_code * 3 + 73;
2199 /* LFE channel always has 7 coefs */
2201 s->start_freq[s->lfe_channel] = 0;
2202 for (blk = 0; blk < s->num_blocks; blk++)
2203 s->blocks[blk].end_freq[ch] = 7;
2206 /* initialize coupling strategy */
2207 if (s->cpl_enabled) {
2208 if (s->options.cpl_start != AC3ENC_OPT_AUTO) {
2209 cpl_start = s->options.cpl_start;
2211 cpl_start = ac3_coupling_start_tab[s->channel_mode-2][s->bit_alloc.sr_code][s->frame_size_code/2];
2212 if (cpl_start < 0) {
2213 if (s->options.channel_coupling == AC3ENC_OPT_AUTO)
2220 if (s->cpl_enabled) {
2221 int i, cpl_start_band, cpl_end_band;
2222 uint8_t *cpl_band_sizes = s->cpl_band_sizes;
2224 cpl_end_band = s->bandwidth_code / 4 + 3;
2225 cpl_start_band = av_clip(cpl_start, 0, FFMIN(cpl_end_band-1, 15));
2227 s->num_cpl_subbands = cpl_end_band - cpl_start_band;
2229 s->num_cpl_bands = 1;
2230 *cpl_band_sizes = 12;
2231 for (i = cpl_start_band + 1; i < cpl_end_band; i++) {
2232 if (ff_eac3_default_cpl_band_struct[i]) {
2233 *cpl_band_sizes += 12;
2237 *cpl_band_sizes = 12;
2241 s->start_freq[CPL_CH] = cpl_start_band * 12 + 37;
2242 s->cpl_end_freq = cpl_end_band * 12 + 37;
2243 for (blk = 0; blk < s->num_blocks; blk++)
2244 s->blocks[blk].end_freq[CPL_CH] = s->cpl_end_freq;
2249 static av_cold int allocate_buffers(AC3EncodeContext *s)
2251 AVCodecContext *avctx = s->avctx;
2253 int channels = s->channels + 1; /* includes coupling channel */
2254 int channel_blocks = channels * s->num_blocks;
2255 int total_coefs = AC3_MAX_COEFS * channel_blocks;
2257 if (s->allocate_sample_buffers(s))
2260 FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, total_coefs *
2261 sizeof(*s->bap_buffer), alloc_fail);
2262 FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, total_coefs *
2263 sizeof(*s->bap1_buffer), alloc_fail);
2264 FF_ALLOCZ_OR_GOTO(avctx, s->mdct_coef_buffer, total_coefs *
2265 sizeof(*s->mdct_coef_buffer), alloc_fail);
2266 FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, total_coefs *
2267 sizeof(*s->exp_buffer), alloc_fail);
2268 FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, channel_blocks * 128 *
2269 sizeof(*s->grouped_exp_buffer), alloc_fail);
2270 FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, total_coefs *
2271 sizeof(*s->psd_buffer), alloc_fail);
2272 FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, channel_blocks * 64 *
2273 sizeof(*s->band_psd_buffer), alloc_fail);
2274 FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, channel_blocks * 64 *
2275 sizeof(*s->mask_buffer), alloc_fail);
2276 FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, total_coefs *
2277 sizeof(*s->qmant_buffer), alloc_fail);
2278 if (s->cpl_enabled) {
2279 FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_exp_buffer, channel_blocks * 16 *
2280 sizeof(*s->cpl_coord_exp_buffer), alloc_fail);
2281 FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_mant_buffer, channel_blocks * 16 *
2282 sizeof(*s->cpl_coord_mant_buffer), alloc_fail);
2284 for (blk = 0; blk < s->num_blocks; blk++) {
2285 AC3Block *block = &s->blocks[blk];
2286 FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, channels * sizeof(*block->mdct_coef),
2288 FF_ALLOCZ_OR_GOTO(avctx, block->exp, channels * sizeof(*block->exp),
2290 FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, channels * sizeof(*block->grouped_exp),
2292 FF_ALLOCZ_OR_GOTO(avctx, block->psd, channels * sizeof(*block->psd),
2294 FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, channels * sizeof(*block->band_psd),
2296 FF_ALLOCZ_OR_GOTO(avctx, block->mask, channels * sizeof(*block->mask),
2298 FF_ALLOCZ_OR_GOTO(avctx, block->qmant, channels * sizeof(*block->qmant),
2300 if (s->cpl_enabled) {
2301 FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_exp, channels * sizeof(*block->cpl_coord_exp),
2303 FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_mant, channels * sizeof(*block->cpl_coord_mant),
2307 for (ch = 0; ch < channels; ch++) {
2308 /* arrangement: block, channel, coeff */
2309 block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * channels + ch)];
2310 block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
2311 block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * channels + ch)];
2312 block->mask[ch] = &s->mask_buffer [64 * (blk * channels + ch)];
2313 block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
2314 if (s->cpl_enabled) {
2315 block->cpl_coord_exp[ch] = &s->cpl_coord_exp_buffer [16 * (blk * channels + ch)];
2316 block->cpl_coord_mant[ch] = &s->cpl_coord_mant_buffer[16 * (blk * channels + ch)];
2319 /* arrangement: channel, block, coeff */
2320 block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
2321 block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
2325 if (!s->fixed_point) {
2326 FF_ALLOCZ_OR_GOTO(avctx, s->fixed_coef_buffer, total_coefs *
2327 sizeof(*s->fixed_coef_buffer), alloc_fail);
2328 for (blk = 0; blk < s->num_blocks; blk++) {
2329 AC3Block *block = &s->blocks[blk];
2330 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2331 sizeof(*block->fixed_coef), alloc_fail);
2332 for (ch = 0; ch < channels; ch++)
2333 block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
2336 for (blk = 0; blk < s->num_blocks; blk++) {
2337 AC3Block *block = &s->blocks[blk];
2338 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2339 sizeof(*block->fixed_coef), alloc_fail);
2340 for (ch = 0; ch < channels; ch++)
2341 block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2347 return AVERROR(ENOMEM);
2352 * Initialize the encoder.
2354 av_cold int ff_ac3_encode_init(AVCodecContext *avctx)
2356 AC3EncodeContext *s = avctx->priv_data;
2357 int ret, frame_size_58;
2361 s->eac3 = avctx->codec_id == CODEC_ID_EAC3;
2363 ff_ac3_common_init();
2365 ret = validate_options(s);
2369 avctx->frame_size = AC3_BLOCK_SIZE * s->num_blocks;
2371 s->bitstream_mode = avctx->audio_service_type;
2372 if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2373 s->bitstream_mode = 0x7;
2375 s->bits_written = 0;
2376 s->samples_written = 0;
2378 /* calculate crc_inv for both possible frame sizes */
2379 frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
2380 s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2381 if (s->bit_alloc.sr_code == 1) {
2382 frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2383 s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2386 /* set function pointers */
2387 if (CONFIG_AC3_FIXED_ENCODER && s->fixed_point) {
2388 s->mdct_end = ff_ac3_fixed_mdct_end;
2389 s->mdct_init = ff_ac3_fixed_mdct_init;
2390 s->allocate_sample_buffers = ff_ac3_fixed_allocate_sample_buffers;
2391 } else if (CONFIG_AC3_ENCODER || CONFIG_EAC3_ENCODER) {
2392 s->mdct_end = ff_ac3_float_mdct_end;
2393 s->mdct_init = ff_ac3_float_mdct_init;
2394 s->allocate_sample_buffers = ff_ac3_float_allocate_sample_buffers;
2396 if (CONFIG_EAC3_ENCODER && s->eac3)
2397 s->output_frame_header = ff_eac3_output_frame_header;
2399 s->output_frame_header = ac3_output_frame_header;
2407 ret = s->mdct_init(s);
2411 ret = allocate_buffers(s);
2415 avctx->coded_frame= avcodec_alloc_frame();
2417 dsputil_init(&s->dsp, avctx);
2418 ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2424 ff_ac3_encode_close(avctx);