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 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++) {
1167 int c = fixed_coef[i];
1175 v = sym_quant(c, e, 3);
1176 switch (s->mant1_cnt) {
1178 s->qmant1_ptr = &qmant[i];
1183 *s->qmant1_ptr += 3 * v;
1188 *s->qmant1_ptr += v;
1195 v = sym_quant(c, e, 5);
1196 switch (s->mant2_cnt) {
1198 s->qmant2_ptr = &qmant[i];
1203 *s->qmant2_ptr += 5 * v;
1208 *s->qmant2_ptr += v;
1215 v = sym_quant(c, e, 7);
1218 v = sym_quant(c, e, 11);
1219 switch (s->mant4_cnt) {
1221 s->qmant4_ptr = &qmant[i];
1226 *s->qmant4_ptr += v;
1233 v = sym_quant(c, e, 15);
1236 v = asym_quant(c, e, 14);
1239 v = asym_quant(c, e, 16);
1242 v = asym_quant(c, e, b - 1);
1251 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1253 void ff_ac3_quantize_mantissas(AC3EncodeContext *s)
1255 int blk, ch, ch0=0, got_cpl;
1257 for (blk = 0; blk < s->num_blocks; blk++) {
1258 AC3Block *block = &s->blocks[blk];
1261 got_cpl = !block->cpl_in_use;
1262 for (ch = 1; ch <= s->channels; ch++) {
1263 if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1268 quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1269 s->blocks[s->exp_ref_block[ch][blk]].exp[ch],
1270 s->ref_bap[ch][blk], block->qmant[ch],
1271 s->start_freq[ch], block->end_freq[ch]);
1280 * Write the AC-3 frame header to the output bitstream.
1282 static void ac3_output_frame_header(AC3EncodeContext *s)
1284 AC3EncOptions *opt = &s->options;
1286 put_bits(&s->pb, 16, 0x0b77); /* frame header */
1287 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
1288 put_bits(&s->pb, 2, s->bit_alloc.sr_code);
1289 put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1290 put_bits(&s->pb, 5, s->bitstream_id);
1291 put_bits(&s->pb, 3, s->bitstream_mode);
1292 put_bits(&s->pb, 3, s->channel_mode);
1293 if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1294 put_bits(&s->pb, 2, s->center_mix_level);
1295 if (s->channel_mode & 0x04)
1296 put_bits(&s->pb, 2, s->surround_mix_level);
1297 if (s->channel_mode == AC3_CHMODE_STEREO)
1298 put_bits(&s->pb, 2, opt->dolby_surround_mode);
1299 put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1300 put_bits(&s->pb, 5, -opt->dialogue_level);
1301 put_bits(&s->pb, 1, 0); /* no compression control word */
1302 put_bits(&s->pb, 1, 0); /* no lang code */
1303 put_bits(&s->pb, 1, opt->audio_production_info);
1304 if (opt->audio_production_info) {
1305 put_bits(&s->pb, 5, opt->mixing_level - 80);
1306 put_bits(&s->pb, 2, opt->room_type);
1308 put_bits(&s->pb, 1, opt->copyright);
1309 put_bits(&s->pb, 1, opt->original);
1310 if (s->bitstream_id == 6) {
1311 /* alternate bit stream syntax */
1312 put_bits(&s->pb, 1, opt->extended_bsi_1);
1313 if (opt->extended_bsi_1) {
1314 put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1315 put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1316 put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1317 put_bits(&s->pb, 3, s->loro_center_mix_level);
1318 put_bits(&s->pb, 3, s->loro_surround_mix_level);
1320 put_bits(&s->pb, 1, opt->extended_bsi_2);
1321 if (opt->extended_bsi_2) {
1322 put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1323 put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1324 put_bits(&s->pb, 1, opt->ad_converter_type);
1325 put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
1328 put_bits(&s->pb, 1, 0); /* no time code 1 */
1329 put_bits(&s->pb, 1, 0); /* no time code 2 */
1331 put_bits(&s->pb, 1, 0); /* no additional bit stream info */
1336 * Write one audio block to the output bitstream.
1338 static void output_audio_block(AC3EncodeContext *s, int blk)
1340 int ch, i, baie, bnd, got_cpl;
1342 AC3Block *block = &s->blocks[blk];
1344 /* block switching */
1346 for (ch = 0; ch < s->fbw_channels; ch++)
1347 put_bits(&s->pb, 1, 0);
1352 for (ch = 0; ch < s->fbw_channels; ch++)
1353 put_bits(&s->pb, 1, 1);
1356 /* dynamic range codes */
1357 put_bits(&s->pb, 1, 0);
1359 /* spectral extension */
1361 put_bits(&s->pb, 1, 0);
1363 /* channel coupling */
1365 put_bits(&s->pb, 1, block->new_cpl_strategy);
1366 if (block->new_cpl_strategy) {
1368 put_bits(&s->pb, 1, block->cpl_in_use);
1369 if (block->cpl_in_use) {
1370 int start_sub, end_sub;
1372 put_bits(&s->pb, 1, 0); /* enhanced coupling */
1373 if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO) {
1374 for (ch = 1; ch <= s->fbw_channels; ch++)
1375 put_bits(&s->pb, 1, block->channel_in_cpl[ch]);
1377 if (s->channel_mode == AC3_CHMODE_STEREO)
1378 put_bits(&s->pb, 1, 0); /* phase flags in use */
1379 start_sub = (s->start_freq[CPL_CH] - 37) / 12;
1380 end_sub = (s->cpl_end_freq - 37) / 12;
1381 put_bits(&s->pb, 4, start_sub);
1382 put_bits(&s->pb, 4, end_sub - 3);
1383 /* coupling band structure */
1385 put_bits(&s->pb, 1, 0); /* use default */
1387 for (bnd = start_sub+1; bnd < end_sub; bnd++)
1388 put_bits(&s->pb, 1, ff_eac3_default_cpl_band_struct[bnd]);
1393 /* coupling coordinates */
1394 if (block->cpl_in_use) {
1395 for (ch = 1; ch <= s->fbw_channels; ch++) {
1396 if (block->channel_in_cpl[ch]) {
1397 if (!s->eac3 || block->new_cpl_coords[ch] != 2)
1398 put_bits(&s->pb, 1, block->new_cpl_coords[ch]);
1399 if (block->new_cpl_coords[ch]) {
1400 put_bits(&s->pb, 2, block->cpl_master_exp[ch]);
1401 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
1402 put_bits(&s->pb, 4, block->cpl_coord_exp [ch][bnd]);
1403 put_bits(&s->pb, 4, block->cpl_coord_mant[ch][bnd]);
1410 /* stereo rematrixing */
1411 if (s->channel_mode == AC3_CHMODE_STEREO) {
1412 if (!s->eac3 || blk > 0)
1413 put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1414 if (block->new_rematrixing_strategy) {
1415 /* rematrixing flags */
1416 for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++)
1417 put_bits(&s->pb, 1, block->rematrixing_flags[bnd]);
1421 /* exponent strategy */
1423 for (ch = !block->cpl_in_use; ch <= s->fbw_channels; ch++)
1424 put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1426 put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1430 for (ch = 1; ch <= s->fbw_channels; ch++) {
1431 if (s->exp_strategy[ch][blk] != EXP_REUSE && !block->channel_in_cpl[ch])
1432 put_bits(&s->pb, 6, s->bandwidth_code);
1436 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1438 int cpl = (ch == CPL_CH);
1440 if (s->exp_strategy[ch][blk] == EXP_REUSE)
1444 put_bits(&s->pb, 4, block->grouped_exp[ch][0] >> cpl);
1446 /* exponent groups */
1447 nb_groups = exponent_group_tab[cpl][s->exp_strategy[ch][blk]-1][block->end_freq[ch]-s->start_freq[ch]];
1448 for (i = 1; i <= nb_groups; i++)
1449 put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1451 /* gain range info */
1452 if (ch != s->lfe_channel && !cpl)
1453 put_bits(&s->pb, 2, 0);
1456 /* bit allocation info */
1459 put_bits(&s->pb, 1, baie);
1461 put_bits(&s->pb, 2, s->slow_decay_code);
1462 put_bits(&s->pb, 2, s->fast_decay_code);
1463 put_bits(&s->pb, 2, s->slow_gain_code);
1464 put_bits(&s->pb, 2, s->db_per_bit_code);
1465 put_bits(&s->pb, 3, s->floor_code);
1471 put_bits(&s->pb, 1, block->new_snr_offsets);
1472 if (block->new_snr_offsets) {
1473 put_bits(&s->pb, 6, s->coarse_snr_offset);
1474 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1475 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1476 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1480 put_bits(&s->pb, 1, 0); /* no converter snr offset */
1484 if (block->cpl_in_use) {
1485 if (!s->eac3 || block->new_cpl_leak != 2)
1486 put_bits(&s->pb, 1, block->new_cpl_leak);
1487 if (block->new_cpl_leak) {
1488 put_bits(&s->pb, 3, s->bit_alloc.cpl_fast_leak);
1489 put_bits(&s->pb, 3, s->bit_alloc.cpl_slow_leak);
1494 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1495 put_bits(&s->pb, 1, 0); /* no data to skip */
1499 got_cpl = !block->cpl_in_use;
1500 for (ch = 1; ch <= s->channels; ch++) {
1503 if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1508 for (i = s->start_freq[ch]; i < block->end_freq[ch]; i++) {
1509 q = block->qmant[ch][i];
1510 b = s->ref_bap[ch][blk][i];
1513 case 1: if (q != 128) put_bits (&s->pb, 5, q); break;
1514 case 2: if (q != 128) put_bits (&s->pb, 7, q); break;
1515 case 3: put_sbits(&s->pb, 3, q); break;
1516 case 4: if (q != 128) put_bits (&s->pb, 7, q); break;
1517 case 14: put_sbits(&s->pb, 14, q); break;
1518 case 15: put_sbits(&s->pb, 16, q); break;
1519 default: put_sbits(&s->pb, b-1, q); break;
1528 /** CRC-16 Polynomial */
1529 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1532 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1549 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1555 r = mul_poly(r, a, poly);
1556 a = mul_poly(a, a, poly);
1564 * Fill the end of the frame with 0's and compute the two CRCs.
1566 static void output_frame_end(AC3EncodeContext *s)
1568 const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1569 int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1572 frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1574 /* pad the remainder of the frame with zeros */
1575 av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1576 flush_put_bits(&s->pb);
1578 pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1579 av_assert2(pad_bytes >= 0);
1581 memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1585 crc2_partial = av_crc(crc_ctx, 0, frame + 2, s->frame_size - 5);
1588 /* this is not so easy because it is at the beginning of the data... */
1589 crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1590 crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1591 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1592 AV_WB16(frame + 2, crc1);
1595 crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1596 s->frame_size - frame_size_58 - 3);
1598 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1599 /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1600 if (crc2 == 0x770B) {
1601 frame[s->frame_size - 3] ^= 0x1;
1602 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1604 crc2 = av_bswap16(crc2);
1605 AV_WB16(frame + s->frame_size - 2, crc2);
1610 * Write the frame to the output bitstream.
1612 void ff_ac3_output_frame(AC3EncodeContext *s, unsigned char *frame)
1616 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1618 s->output_frame_header(s);
1620 for (blk = 0; blk < s->num_blocks; blk++)
1621 output_audio_block(s, blk);
1623 output_frame_end(s);
1627 static void dprint_options(AC3EncodeContext *s)
1630 AVCodecContext *avctx = s->avctx;
1631 AC3EncOptions *opt = &s->options;
1634 switch (s->bitstream_id) {
1635 case 6: av_strlcpy(strbuf, "AC-3 (alt syntax)", 32); break;
1636 case 8: av_strlcpy(strbuf, "AC-3 (standard)", 32); break;
1637 case 9: av_strlcpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
1638 case 10: av_strlcpy(strbuf, "AC-3 (dnet quater-rate)", 32); break;
1639 case 16: av_strlcpy(strbuf, "E-AC-3 (enhanced)", 32); break;
1640 default: snprintf(strbuf, 32, "ERROR");
1642 av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
1643 av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
1644 av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
1645 av_dlog(avctx, "channel_layout: %s\n", strbuf);
1646 av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
1647 av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
1648 av_dlog(avctx, "blocks/frame: %d (code=%d)\n", s->num_blocks, s->num_blks_code);
1650 av_dlog(avctx, "cutoff: %d\n", s->cutoff);
1652 av_dlog(avctx, "per_frame_metadata: %s\n",
1653 opt->allow_per_frame_metadata?"on":"off");
1655 av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
1656 s->center_mix_level);
1658 av_dlog(avctx, "center_mixlev: {not written}\n");
1659 if (s->has_surround)
1660 av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
1661 s->surround_mix_level);
1663 av_dlog(avctx, "surround_mixlev: {not written}\n");
1664 if (opt->audio_production_info) {
1665 av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
1666 switch (opt->room_type) {
1667 case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1668 case AC3ENC_OPT_LARGE_ROOM: av_strlcpy(strbuf, "large", 32); break;
1669 case AC3ENC_OPT_SMALL_ROOM: av_strlcpy(strbuf, "small", 32); break;
1670 default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
1672 av_dlog(avctx, "room_type: %s\n", strbuf);
1674 av_dlog(avctx, "mixing_level: {not written}\n");
1675 av_dlog(avctx, "room_type: {not written}\n");
1677 av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
1678 av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
1679 if (s->channel_mode == AC3_CHMODE_STEREO) {
1680 switch (opt->dolby_surround_mode) {
1681 case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1682 case AC3ENC_OPT_MODE_ON: av_strlcpy(strbuf, "on", 32); break;
1683 case AC3ENC_OPT_MODE_OFF: av_strlcpy(strbuf, "off", 32); break;
1684 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
1686 av_dlog(avctx, "dsur_mode: %s\n", strbuf);
1688 av_dlog(avctx, "dsur_mode: {not written}\n");
1690 av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
1692 if (s->bitstream_id == 6) {
1693 if (opt->extended_bsi_1) {
1694 switch (opt->preferred_stereo_downmix) {
1695 case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1696 case AC3ENC_OPT_DOWNMIX_LTRT: av_strlcpy(strbuf, "ltrt", 32); break;
1697 case AC3ENC_OPT_DOWNMIX_LORO: av_strlcpy(strbuf, "loro", 32); break;
1698 default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
1700 av_dlog(avctx, "dmix_mode: %s\n", strbuf);
1701 av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
1702 opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
1703 av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
1704 opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
1705 av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
1706 opt->loro_center_mix_level, s->loro_center_mix_level);
1707 av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
1708 opt->loro_surround_mix_level, s->loro_surround_mix_level);
1710 av_dlog(avctx, "extended bitstream info 1: {not written}\n");
1712 if (opt->extended_bsi_2) {
1713 switch (opt->dolby_surround_ex_mode) {
1714 case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1715 case AC3ENC_OPT_MODE_ON: av_strlcpy(strbuf, "on", 32); break;
1716 case AC3ENC_OPT_MODE_OFF: av_strlcpy(strbuf, "off", 32); break;
1717 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
1719 av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
1720 switch (opt->dolby_headphone_mode) {
1721 case AC3ENC_OPT_NOT_INDICATED: av_strlcpy(strbuf, "notindicated", 32); break;
1722 case AC3ENC_OPT_MODE_ON: av_strlcpy(strbuf, "on", 32); break;
1723 case AC3ENC_OPT_MODE_OFF: av_strlcpy(strbuf, "off", 32); break;
1724 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
1726 av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
1728 switch (opt->ad_converter_type) {
1729 case AC3ENC_OPT_ADCONV_STANDARD: av_strlcpy(strbuf, "standard", 32); break;
1730 case AC3ENC_OPT_ADCONV_HDCD: av_strlcpy(strbuf, "hdcd", 32); break;
1731 default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
1733 av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
1735 av_dlog(avctx, "extended bitstream info 2: {not written}\n");
1742 #define FLT_OPTION_THRESHOLD 0.01
1744 static int validate_float_option(float v, const float *v_list, int v_list_size)
1748 for (i = 0; i < v_list_size; i++) {
1749 if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
1750 v > (v_list[i] - FLT_OPTION_THRESHOLD))
1753 if (i == v_list_size)
1760 static void validate_mix_level(void *log_ctx, const char *opt_name,
1761 float *opt_param, const float *list,
1762 int list_size, int default_value, int min_value,
1765 int mixlev = validate_float_option(*opt_param, list, list_size);
1766 if (mixlev < min_value) {
1767 mixlev = default_value;
1768 if (*opt_param >= 0.0) {
1769 av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
1770 "default value: %0.3f\n", opt_name, list[mixlev]);
1773 *opt_param = list[mixlev];
1774 *ctx_param = mixlev;
1779 * Validate metadata options as set by AVOption system.
1780 * These values can optionally be changed per-frame.
1782 int ff_ac3_validate_metadata(AC3EncodeContext *s)
1784 AVCodecContext *avctx = s->avctx;
1785 AC3EncOptions *opt = &s->options;
1787 opt->audio_production_info = 0;
1788 opt->extended_bsi_1 = 0;
1789 opt->extended_bsi_2 = 0;
1790 opt->eac3_mixing_metadata = 0;
1791 opt->eac3_info_metadata = 0;
1793 /* determine mixing metadata / xbsi1 use */
1794 if (s->channel_mode > AC3_CHMODE_STEREO && opt->preferred_stereo_downmix != AC3ENC_OPT_NONE) {
1795 opt->extended_bsi_1 = 1;
1796 opt->eac3_mixing_metadata = 1;
1798 if (s->has_center &&
1799 (opt->ltrt_center_mix_level >= 0 || opt->loro_center_mix_level >= 0)) {
1800 opt->extended_bsi_1 = 1;
1801 opt->eac3_mixing_metadata = 1;
1803 if (s->has_surround &&
1804 (opt->ltrt_surround_mix_level >= 0 || opt->loro_surround_mix_level >= 0)) {
1805 opt->extended_bsi_1 = 1;
1806 opt->eac3_mixing_metadata = 1;
1810 /* determine info metadata use */
1811 if (avctx->audio_service_type != AV_AUDIO_SERVICE_TYPE_MAIN)
1812 opt->eac3_info_metadata = 1;
1813 if (opt->copyright != AC3ENC_OPT_NONE || opt->original != AC3ENC_OPT_NONE)
1814 opt->eac3_info_metadata = 1;
1815 if (s->channel_mode == AC3_CHMODE_STEREO &&
1816 (opt->dolby_headphone_mode != AC3ENC_OPT_NONE || opt->dolby_surround_mode != AC3ENC_OPT_NONE))
1817 opt->eac3_info_metadata = 1;
1818 if (s->channel_mode >= AC3_CHMODE_2F2R && opt->dolby_surround_ex_mode != AC3ENC_OPT_NONE)
1819 opt->eac3_info_metadata = 1;
1820 if (opt->mixing_level != AC3ENC_OPT_NONE || opt->room_type != AC3ENC_OPT_NONE ||
1821 opt->ad_converter_type != AC3ENC_OPT_NONE) {
1822 opt->audio_production_info = 1;
1823 opt->eac3_info_metadata = 1;
1826 /* determine audio production info use */
1827 if (opt->mixing_level != AC3ENC_OPT_NONE || opt->room_type != AC3ENC_OPT_NONE)
1828 opt->audio_production_info = 1;
1830 /* determine xbsi2 use */
1831 if (s->channel_mode >= AC3_CHMODE_2F2R && opt->dolby_surround_ex_mode != AC3ENC_OPT_NONE)
1832 opt->extended_bsi_2 = 1;
1833 if (s->channel_mode == AC3_CHMODE_STEREO && opt->dolby_headphone_mode != AC3ENC_OPT_NONE)
1834 opt->extended_bsi_2 = 1;
1835 if (opt->ad_converter_type != AC3ENC_OPT_NONE)
1836 opt->extended_bsi_2 = 1;
1839 /* validate AC-3 mixing levels */
1841 if (s->has_center) {
1842 validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
1843 cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
1844 &s->center_mix_level);
1846 if (s->has_surround) {
1847 validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
1848 surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
1849 &s->surround_mix_level);
1853 /* validate extended bsi 1 / mixing metadata */
1854 if (opt->extended_bsi_1 || opt->eac3_mixing_metadata) {
1855 /* default preferred stereo downmix */
1856 if (opt->preferred_stereo_downmix == AC3ENC_OPT_NONE)
1857 opt->preferred_stereo_downmix = AC3ENC_OPT_NOT_INDICATED;
1858 if (!s->eac3 || s->has_center) {
1859 /* validate Lt/Rt center mix level */
1860 validate_mix_level(avctx, "ltrt_center_mix_level",
1861 &opt->ltrt_center_mix_level, extmixlev_options,
1862 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1863 &s->ltrt_center_mix_level);
1864 /* validate Lo/Ro center mix level */
1865 validate_mix_level(avctx, "loro_center_mix_level",
1866 &opt->loro_center_mix_level, extmixlev_options,
1867 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1868 &s->loro_center_mix_level);
1870 if (!s->eac3 || s->has_surround) {
1871 /* validate Lt/Rt surround mix level */
1872 validate_mix_level(avctx, "ltrt_surround_mix_level",
1873 &opt->ltrt_surround_mix_level, extmixlev_options,
1874 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1875 &s->ltrt_surround_mix_level);
1876 /* validate Lo/Ro surround mix level */
1877 validate_mix_level(avctx, "loro_surround_mix_level",
1878 &opt->loro_surround_mix_level, extmixlev_options,
1879 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1880 &s->loro_surround_mix_level);
1884 /* validate audio service type / channels combination */
1885 if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
1886 avctx->channels == 1) ||
1887 ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
1888 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
1889 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
1890 && avctx->channels > 1)) {
1891 av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
1892 "specified number of channels\n");
1893 return AVERROR(EINVAL);
1896 /* validate extended bsi 2 / info metadata */
1897 if (opt->extended_bsi_2 || opt->eac3_info_metadata) {
1898 /* default dolby headphone mode */
1899 if (opt->dolby_headphone_mode == AC3ENC_OPT_NONE)
1900 opt->dolby_headphone_mode = AC3ENC_OPT_NOT_INDICATED;
1901 /* default dolby surround ex mode */
1902 if (opt->dolby_surround_ex_mode == AC3ENC_OPT_NONE)
1903 opt->dolby_surround_ex_mode = AC3ENC_OPT_NOT_INDICATED;
1904 /* default A/D converter type */
1905 if (opt->ad_converter_type == AC3ENC_OPT_NONE)
1906 opt->ad_converter_type = AC3ENC_OPT_ADCONV_STANDARD;
1909 /* copyright & original defaults */
1910 if (!s->eac3 || opt->eac3_info_metadata) {
1911 /* default copyright */
1912 if (opt->copyright == AC3ENC_OPT_NONE)
1913 opt->copyright = AC3ENC_OPT_OFF;
1914 /* default original */
1915 if (opt->original == AC3ENC_OPT_NONE)
1916 opt->original = AC3ENC_OPT_ON;
1919 /* dolby surround mode default */
1920 if (!s->eac3 || opt->eac3_info_metadata) {
1921 if (opt->dolby_surround_mode == AC3ENC_OPT_NONE)
1922 opt->dolby_surround_mode = AC3ENC_OPT_NOT_INDICATED;
1925 /* validate audio production info */
1926 if (opt->audio_production_info) {
1927 if (opt->mixing_level == AC3ENC_OPT_NONE) {
1928 av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
1929 "room_type is set\n");
1930 return AVERROR(EINVAL);
1932 if (opt->mixing_level < 80) {
1933 av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
1934 "80dB and 111dB\n");
1935 return AVERROR(EINVAL);
1937 /* default room type */
1938 if (opt->room_type == AC3ENC_OPT_NONE)
1939 opt->room_type = AC3ENC_OPT_NOT_INDICATED;
1942 /* set bitstream id for alternate bitstream syntax */
1943 if (!s->eac3 && (opt->extended_bsi_1 || opt->extended_bsi_2)) {
1944 if (s->bitstream_id > 8 && s->bitstream_id < 11) {
1945 static int warn_once = 1;
1947 av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
1948 "not compatible with reduced samplerates. writing of "
1949 "extended bitstream information will be disabled.\n");
1953 s->bitstream_id = 6;
1962 * Finalize encoding and free any memory allocated by the encoder.
1964 av_cold int ff_ac3_encode_close(AVCodecContext *avctx)
1967 AC3EncodeContext *s = avctx->priv_data;
1969 av_freep(&s->windowed_samples);
1970 for (ch = 0; ch < s->channels; ch++)
1971 av_freep(&s->planar_samples[ch]);
1972 av_freep(&s->planar_samples);
1973 av_freep(&s->bap_buffer);
1974 av_freep(&s->bap1_buffer);
1975 av_freep(&s->mdct_coef_buffer);
1976 av_freep(&s->fixed_coef_buffer);
1977 av_freep(&s->exp_buffer);
1978 av_freep(&s->grouped_exp_buffer);
1979 av_freep(&s->psd_buffer);
1980 av_freep(&s->band_psd_buffer);
1981 av_freep(&s->mask_buffer);
1982 av_freep(&s->qmant_buffer);
1983 av_freep(&s->cpl_coord_exp_buffer);
1984 av_freep(&s->cpl_coord_mant_buffer);
1985 for (blk = 0; blk < s->num_blocks; blk++) {
1986 AC3Block *block = &s->blocks[blk];
1987 av_freep(&block->mdct_coef);
1988 av_freep(&block->fixed_coef);
1989 av_freep(&block->exp);
1990 av_freep(&block->grouped_exp);
1991 av_freep(&block->psd);
1992 av_freep(&block->band_psd);
1993 av_freep(&block->mask);
1994 av_freep(&block->qmant);
1995 av_freep(&block->cpl_coord_exp);
1996 av_freep(&block->cpl_coord_mant);
2001 av_freep(&avctx->coded_frame);
2007 * Set channel information during initialization.
2009 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
2010 int64_t *channel_layout)
2014 if (channels < 1 || channels > AC3_MAX_CHANNELS)
2015 return AVERROR(EINVAL);
2016 if ((uint64_t)*channel_layout > 0x7FF)
2017 return AVERROR(EINVAL);
2018 ch_layout = *channel_layout;
2020 ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
2022 s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
2023 s->channels = channels;
2024 s->fbw_channels = channels - s->lfe_on;
2025 s->lfe_channel = s->lfe_on ? s->fbw_channels + 1 : -1;
2027 ch_layout -= AV_CH_LOW_FREQUENCY;
2029 switch (ch_layout) {
2030 case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
2031 case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
2032 case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
2033 case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
2034 case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
2035 case AV_CH_LAYOUT_QUAD:
2036 case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
2037 case AV_CH_LAYOUT_5POINT0:
2038 case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
2040 return AVERROR(EINVAL);
2042 s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
2043 s->has_surround = s->channel_mode & 0x04;
2045 s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
2046 *channel_layout = ch_layout;
2048 *channel_layout |= AV_CH_LOW_FREQUENCY;
2054 static av_cold int validate_options(AC3EncodeContext *s)
2056 AVCodecContext *avctx = s->avctx;
2059 /* validate channel layout */
2060 if (!avctx->channel_layout) {
2061 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
2062 "encoder will guess the layout, but it "
2063 "might be incorrect.\n");
2065 ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
2067 av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
2071 /* validate sample rate */
2072 /* note: max_sr could be changed from 2 to 5 for E-AC-3 once we find a
2073 decoder that supports half sample rate so we can validate that
2074 the generated files are correct. */
2075 max_sr = s->eac3 ? 2 : 8;
2076 for (i = 0; i <= max_sr; i++) {
2077 if ((ff_ac3_sample_rate_tab[i % 3] >> (i / 3)) == avctx->sample_rate)
2081 av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
2082 return AVERROR(EINVAL);
2084 s->sample_rate = avctx->sample_rate;
2085 s->bit_alloc.sr_shift = i / 3;
2086 s->bit_alloc.sr_code = i % 3;
2087 s->bitstream_id = s->eac3 ? 16 : 8 + s->bit_alloc.sr_shift;
2089 /* validate bit rate */
2091 int max_br, min_br, wpf, min_br_dist, min_br_code;
2092 int num_blks_code, num_blocks, frame_samples;
2094 /* calculate min/max bitrate */
2095 /* TODO: More testing with 3 and 2 blocks. All E-AC-3 samples I've
2096 found use either 6 blocks or 1 block, even though 2 or 3 blocks
2097 would work as far as the bit rate is concerned. */
2098 for (num_blks_code = 3; num_blks_code >= 0; num_blks_code--) {
2099 num_blocks = ((int[]){ 1, 2, 3, 6 })[num_blks_code];
2100 frame_samples = AC3_BLOCK_SIZE * num_blocks;
2101 max_br = 2048 * s->sample_rate / frame_samples * 16;
2102 min_br = ((s->sample_rate + (frame_samples-1)) / frame_samples) * 16;
2103 if (avctx->bit_rate <= max_br)
2106 if (avctx->bit_rate < min_br || avctx->bit_rate > max_br) {
2107 av_log(avctx, AV_LOG_ERROR, "invalid bit rate. must be %d to %d "
2108 "for this sample rate\n", min_br, max_br);
2109 return AVERROR(EINVAL);
2111 s->num_blks_code = num_blks_code;
2112 s->num_blocks = num_blocks;
2114 /* calculate words-per-frame for the selected bitrate */
2115 wpf = (avctx->bit_rate / 16) * frame_samples / s->sample_rate;
2116 av_assert1(wpf > 0 && wpf <= 2048);
2118 /* find the closest AC-3 bitrate code to the selected bitrate.
2119 this is needed for lookup tables for bandwidth and coupling
2120 parameter selection */
2122 min_br_dist = INT_MAX;
2123 for (i = 0; i < 19; i++) {
2124 int br_dist = abs(ff_ac3_bitrate_tab[i] * 1000 - avctx->bit_rate);
2125 if (br_dist < min_br_dist) {
2126 min_br_dist = br_dist;
2131 /* make sure the minimum frame size is below the average frame size */
2132 s->frame_size_code = min_br_code << 1;
2133 while (wpf > 1 && wpf * s->sample_rate / AC3_FRAME_SIZE * 16 > avctx->bit_rate)
2135 s->frame_size_min = 2 * wpf;
2137 for (i = 0; i < 19; i++) {
2138 if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
2142 av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2143 return AVERROR(EINVAL);
2145 s->frame_size_code = i << 1;
2146 s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2147 s->num_blks_code = 0x3;
2150 s->bit_rate = avctx->bit_rate;
2151 s->frame_size = s->frame_size_min;
2153 /* validate cutoff */
2154 if (avctx->cutoff < 0) {
2155 av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2156 return AVERROR(EINVAL);
2158 s->cutoff = avctx->cutoff;
2159 if (s->cutoff > (s->sample_rate >> 1))
2160 s->cutoff = s->sample_rate >> 1;
2162 ret = ff_ac3_validate_metadata(s);
2166 s->rematrixing_enabled = s->options.stereo_rematrixing &&
2167 (s->channel_mode == AC3_CHMODE_STEREO);
2169 s->cpl_enabled = s->options.channel_coupling &&
2170 s->channel_mode >= AC3_CHMODE_STEREO;
2177 * Set bandwidth for all channels.
2178 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2179 * default value will be used.
2181 static av_cold void set_bandwidth(AC3EncodeContext *s)
2184 int av_uninit(cpl_start);
2187 /* calculate bandwidth based on user-specified cutoff frequency */
2189 fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2190 s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2192 /* use default bandwidth setting */
2193 s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2196 /* set number of coefficients for each channel */
2197 for (ch = 1; ch <= s->fbw_channels; ch++) {
2198 s->start_freq[ch] = 0;
2199 for (blk = 0; blk < s->num_blocks; blk++)
2200 s->blocks[blk].end_freq[ch] = s->bandwidth_code * 3 + 73;
2202 /* LFE channel always has 7 coefs */
2204 s->start_freq[s->lfe_channel] = 0;
2205 for (blk = 0; blk < s->num_blocks; blk++)
2206 s->blocks[blk].end_freq[ch] = 7;
2209 /* initialize coupling strategy */
2210 if (s->cpl_enabled) {
2211 if (s->options.cpl_start != AC3ENC_OPT_AUTO) {
2212 cpl_start = s->options.cpl_start;
2214 cpl_start = ac3_coupling_start_tab[s->channel_mode-2][s->bit_alloc.sr_code][s->frame_size_code/2];
2215 if (cpl_start < 0) {
2216 if (s->options.channel_coupling == AC3ENC_OPT_AUTO)
2223 if (s->cpl_enabled) {
2224 int i, cpl_start_band, cpl_end_band;
2225 uint8_t *cpl_band_sizes = s->cpl_band_sizes;
2227 cpl_end_band = s->bandwidth_code / 4 + 3;
2228 cpl_start_band = av_clip(cpl_start, 0, FFMIN(cpl_end_band-1, 15));
2230 s->num_cpl_subbands = cpl_end_band - cpl_start_band;
2232 s->num_cpl_bands = 1;
2233 *cpl_band_sizes = 12;
2234 for (i = cpl_start_band + 1; i < cpl_end_band; i++) {
2235 if (ff_eac3_default_cpl_band_struct[i]) {
2236 *cpl_band_sizes += 12;
2240 *cpl_band_sizes = 12;
2244 s->start_freq[CPL_CH] = cpl_start_band * 12 + 37;
2245 s->cpl_end_freq = cpl_end_band * 12 + 37;
2246 for (blk = 0; blk < s->num_blocks; blk++)
2247 s->blocks[blk].end_freq[CPL_CH] = s->cpl_end_freq;
2252 static av_cold int allocate_buffers(AC3EncodeContext *s)
2254 AVCodecContext *avctx = s->avctx;
2256 int channels = s->channels + 1; /* includes coupling channel */
2257 int channel_blocks = channels * s->num_blocks;
2258 int total_coefs = AC3_MAX_COEFS * channel_blocks;
2260 if (s->allocate_sample_buffers(s))
2263 FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, total_coefs *
2264 sizeof(*s->bap_buffer), alloc_fail);
2265 FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, total_coefs *
2266 sizeof(*s->bap1_buffer), alloc_fail);
2267 FF_ALLOCZ_OR_GOTO(avctx, s->mdct_coef_buffer, total_coefs *
2268 sizeof(*s->mdct_coef_buffer), alloc_fail);
2269 FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, total_coefs *
2270 sizeof(*s->exp_buffer), alloc_fail);
2271 FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, channel_blocks * 128 *
2272 sizeof(*s->grouped_exp_buffer), alloc_fail);
2273 FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, total_coefs *
2274 sizeof(*s->psd_buffer), alloc_fail);
2275 FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, channel_blocks * 64 *
2276 sizeof(*s->band_psd_buffer), alloc_fail);
2277 FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, channel_blocks * 64 *
2278 sizeof(*s->mask_buffer), alloc_fail);
2279 FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, total_coefs *
2280 sizeof(*s->qmant_buffer), alloc_fail);
2281 if (s->cpl_enabled) {
2282 FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_exp_buffer, channel_blocks * 16 *
2283 sizeof(*s->cpl_coord_exp_buffer), alloc_fail);
2284 FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_mant_buffer, channel_blocks * 16 *
2285 sizeof(*s->cpl_coord_mant_buffer), alloc_fail);
2287 for (blk = 0; blk < s->num_blocks; blk++) {
2288 AC3Block *block = &s->blocks[blk];
2289 FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, channels * sizeof(*block->mdct_coef),
2291 FF_ALLOCZ_OR_GOTO(avctx, block->exp, channels * sizeof(*block->exp),
2293 FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, channels * sizeof(*block->grouped_exp),
2295 FF_ALLOCZ_OR_GOTO(avctx, block->psd, channels * sizeof(*block->psd),
2297 FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, channels * sizeof(*block->band_psd),
2299 FF_ALLOCZ_OR_GOTO(avctx, block->mask, channels * sizeof(*block->mask),
2301 FF_ALLOCZ_OR_GOTO(avctx, block->qmant, channels * sizeof(*block->qmant),
2303 if (s->cpl_enabled) {
2304 FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_exp, channels * sizeof(*block->cpl_coord_exp),
2306 FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_mant, channels * sizeof(*block->cpl_coord_mant),
2310 for (ch = 0; ch < channels; ch++) {
2311 /* arrangement: block, channel, coeff */
2312 block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * channels + ch)];
2313 block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
2314 block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * channels + ch)];
2315 block->mask[ch] = &s->mask_buffer [64 * (blk * channels + ch)];
2316 block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
2317 if (s->cpl_enabled) {
2318 block->cpl_coord_exp[ch] = &s->cpl_coord_exp_buffer [16 * (blk * channels + ch)];
2319 block->cpl_coord_mant[ch] = &s->cpl_coord_mant_buffer[16 * (blk * channels + ch)];
2322 /* arrangement: channel, block, coeff */
2323 block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
2324 block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
2328 if (!s->fixed_point) {
2329 FF_ALLOCZ_OR_GOTO(avctx, s->fixed_coef_buffer, total_coefs *
2330 sizeof(*s->fixed_coef_buffer), alloc_fail);
2331 for (blk = 0; blk < s->num_blocks; blk++) {
2332 AC3Block *block = &s->blocks[blk];
2333 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2334 sizeof(*block->fixed_coef), alloc_fail);
2335 for (ch = 0; ch < channels; ch++)
2336 block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (s->num_blocks * ch + blk)];
2339 for (blk = 0; blk < s->num_blocks; blk++) {
2340 AC3Block *block = &s->blocks[blk];
2341 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2342 sizeof(*block->fixed_coef), alloc_fail);
2343 for (ch = 0; ch < channels; ch++)
2344 block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2350 return AVERROR(ENOMEM);
2355 * Initialize the encoder.
2357 av_cold int ff_ac3_encode_init(AVCodecContext *avctx)
2359 AC3EncodeContext *s = avctx->priv_data;
2360 int ret, frame_size_58;
2364 s->eac3 = avctx->codec_id == CODEC_ID_EAC3;
2366 ff_ac3_common_init();
2368 ret = validate_options(s);
2372 avctx->frame_size = AC3_BLOCK_SIZE * s->num_blocks;
2374 s->bitstream_mode = avctx->audio_service_type;
2375 if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2376 s->bitstream_mode = 0x7;
2378 s->bits_written = 0;
2379 s->samples_written = 0;
2381 /* calculate crc_inv for both possible frame sizes */
2382 frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
2383 s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2384 if (s->bit_alloc.sr_code == 1) {
2385 frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2386 s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2389 /* set function pointers */
2390 if (CONFIG_AC3_FIXED_ENCODER && s->fixed_point) {
2391 s->mdct_end = ff_ac3_fixed_mdct_end;
2392 s->mdct_init = ff_ac3_fixed_mdct_init;
2393 s->allocate_sample_buffers = ff_ac3_fixed_allocate_sample_buffers;
2394 } else if (CONFIG_AC3_ENCODER || CONFIG_EAC3_ENCODER) {
2395 s->mdct_end = ff_ac3_float_mdct_end;
2396 s->mdct_init = ff_ac3_float_mdct_init;
2397 s->allocate_sample_buffers = ff_ac3_float_allocate_sample_buffers;
2399 if (CONFIG_EAC3_ENCODER && s->eac3)
2400 s->output_frame_header = ff_eac3_output_frame_header;
2402 s->output_frame_header = ac3_output_frame_header;
2410 ret = s->mdct_init(s);
2414 ret = allocate_buffers(s);
2418 avctx->coded_frame= avcodec_alloc_frame();
2420 dsputil_init(&s->dsp, avctx);
2421 ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2427 ff_ac3_encode_close(avctx);