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"
49 typedef struct AC3Mant {
50 uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
51 int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
54 #define CMIXLEV_NUM_OPTIONS 3
55 static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
56 LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
59 #define SURMIXLEV_NUM_OPTIONS 3
60 static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
61 LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
64 #define EXTMIXLEV_NUM_OPTIONS 8
65 static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
66 LEVEL_PLUS_3DB, LEVEL_PLUS_1POINT5DB, LEVEL_ONE, LEVEL_MINUS_4POINT5DB,
67 LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
71 #define OFFSET(param) offsetof(AC3EncodeContext, options.param)
72 #define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
74 #define AC3ENC_TYPE_AC3_FIXED 0
75 #define AC3ENC_TYPE_AC3 1
76 #define AC3ENC_TYPE_EAC3 2
78 #if CONFIG_AC3ENC_FLOAT
79 #define AC3ENC_TYPE AC3ENC_TYPE_AC3
80 #include "ac3enc_opts_template.c"
81 static AVClass ac3enc_class = { "AC-3 Encoder", av_default_item_name,
82 ac3_options, LIBAVUTIL_VERSION_INT };
84 #define AC3ENC_TYPE AC3ENC_TYPE_EAC3
85 #include "ac3enc_opts_template.c"
86 static AVClass eac3enc_class = { "E-AC-3 Encoder", av_default_item_name,
87 eac3_options, LIBAVUTIL_VERSION_INT };
89 #define AC3ENC_TYPE AC3ENC_TYPE_AC3_FIXED
90 #include "ac3enc_opts_template.c"
91 static AVClass ac3enc_class = { "Fixed-Point AC-3 Encoder", av_default_item_name,
92 ac3fixed_options, LIBAVUTIL_VERSION_INT };
96 /* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
98 static av_cold void mdct_end(AC3MDCTContext *mdct);
100 static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
103 static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
104 const SampleType *window, unsigned int len);
106 static int normalize_samples(AC3EncodeContext *s);
108 static void scale_coefficients(AC3EncodeContext *s);
112 * LUT for number of exponent groups.
113 * exponent_group_tab[coupling][exponent strategy-1][number of coefficients]
115 static uint8_t exponent_group_tab[2][3][256];
119 * List of supported channel layouts.
121 #if CONFIG_AC3ENC_FLOAT || !CONFIG_AC3_FLOAT_ENCODER //we need this exactly once compiled in
122 const int64_t ff_ac3_channel_layouts[] = {
126 AV_CH_LAYOUT_SURROUND,
129 AV_CH_LAYOUT_4POINT0,
130 AV_CH_LAYOUT_5POINT0,
131 AV_CH_LAYOUT_5POINT0_BACK,
132 (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
133 (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
134 (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
135 (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
136 (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
137 (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
138 (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
139 AV_CH_LAYOUT_5POINT1,
140 AV_CH_LAYOUT_5POINT1_BACK,
147 * LUT to select the bandwidth code based on the bit rate, sample rate, and
148 * number of full-bandwidth channels.
149 * bandwidth_tab[fbw_channels-1][sample rate code][bit rate code]
151 static const uint8_t ac3_bandwidth_tab[5][3][19] = {
152 // 32 40 48 56 64 80 96 112 128 160 192 224 256 320 384 448 512 576 640
154 { { 0, 0, 0, 12, 16, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
155 { 0, 0, 0, 16, 20, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
156 { 0, 0, 0, 32, 40, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
158 { { 0, 0, 0, 0, 0, 0, 0, 20, 24, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
159 { 0, 0, 0, 0, 0, 0, 4, 24, 28, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
160 { 0, 0, 0, 0, 0, 0, 20, 44, 52, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
162 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 24, 32, 40, 48, 48, 48, 48, 48, 48 },
163 { 0, 0, 0, 0, 0, 0, 0, 0, 4, 20, 28, 36, 44, 56, 56, 56, 56, 56, 56 },
164 { 0, 0, 0, 0, 0, 0, 0, 0, 20, 40, 48, 60, 60, 60, 60, 60, 60, 60, 60 } },
166 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 32, 48, 48, 48, 48, 48, 48 },
167 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 28, 36, 56, 56, 56, 56, 56, 56 },
168 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 48, 60, 60, 60, 60, 60, 60, 60 } },
170 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 20, 32, 40, 48, 48, 48, 48 },
171 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 36, 44, 56, 56, 56, 56 },
172 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 44, 60, 60, 60, 60, 60, 60 } }
177 * LUT to select the coupling start band based on the bit rate, sample rate, and
178 * number of full-bandwidth channels. -1 = coupling off
179 * ac3_coupling_start_tab[channel_mode-2][sample rate code][bit rate code]
181 * TODO: more testing for optimal parameters.
182 * multi-channel tests at 44.1kHz and 32kHz.
184 static const int8_t ac3_coupling_start_tab[6][3][19] = {
185 // 32 40 48 56 64 80 96 112 128 160 192 224 256 320 384 448 512 576 640
188 { { 0, 0, 0, 0, 0, 0, 0, 1, 1, 7, 8, 11, 12, -1, -1, -1, -1, -1, -1 },
189 { 0, 0, 0, 0, 0, 0, 1, 3, 5, 7, 10, 12, 13, -1, -1, -1, -1, -1, -1 },
190 { 0, 0, 0, 0, 1, 2, 2, 9, 13, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
193 { { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
194 { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
195 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
198 { { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
199 { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
200 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
203 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
204 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
205 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
208 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
209 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
210 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
213 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 8, 11, 12, 12, -1, -1 },
214 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 8, 11, 12, 12, -1, -1 },
215 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
220 * Adjust the frame size to make the average bit rate match the target bit rate.
221 * This is only needed for 11025, 22050, and 44100 sample rates or any E-AC-3.
223 static void adjust_frame_size(AC3EncodeContext *s)
225 while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
226 s->bits_written -= s->bit_rate;
227 s->samples_written -= s->sample_rate;
229 s->frame_size = s->frame_size_min +
230 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
231 s->bits_written += s->frame_size * 8;
232 s->samples_written += AC3_FRAME_SIZE;
237 * Deinterleave input samples.
238 * Channels are reordered from FFmpeg's default order to AC-3 order.
240 static void deinterleave_input_samples(AC3EncodeContext *s,
241 const SampleType *samples)
245 /* deinterleave and remap input samples */
246 for (ch = 0; ch < s->channels; ch++) {
247 const SampleType *sptr;
250 /* copy last 256 samples of previous frame to the start of the current frame */
251 memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
252 AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
256 sptr = samples + s->channel_map[ch];
257 for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
258 s->planar_samples[ch][i] = *sptr;
266 * Apply the MDCT to input samples to generate frequency coefficients.
267 * This applies the KBD window and normalizes the input to reduce precision
268 * loss due to fixed-point calculations.
270 static void apply_mdct(AC3EncodeContext *s)
274 for (ch = 0; ch < s->channels; ch++) {
275 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
276 AC3Block *block = &s->blocks[blk];
277 const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
279 apply_window(&s->dsp, s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
281 block->coeff_shift[ch+1] = normalize_samples(s);
283 s->mdct.fft.mdct_calcw(&s->mdct.fft, block->mdct_coef[ch+1],
284 s->windowed_samples);
290 static void compute_coupling_strategy(AC3EncodeContext *s)
295 /* set coupling use flags for each block/channel */
296 /* TODO: turn coupling on/off and adjust start band based on bit usage */
297 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
298 AC3Block *block = &s->blocks[blk];
299 for (ch = 1; ch <= s->fbw_channels; ch++)
300 block->channel_in_cpl[ch] = s->cpl_on;
303 /* enable coupling for each block if at least 2 channels have coupling
304 enabled for that block */
306 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
307 AC3Block *block = &s->blocks[blk];
308 block->num_cpl_channels = 0;
309 for (ch = 1; ch <= s->fbw_channels; ch++)
310 block->num_cpl_channels += block->channel_in_cpl[ch];
311 block->cpl_in_use = block->num_cpl_channels > 1;
312 if (!block->cpl_in_use) {
313 block->num_cpl_channels = 0;
314 for (ch = 1; ch <= s->fbw_channels; ch++)
315 block->channel_in_cpl[ch] = 0;
318 block->new_cpl_strategy = !blk;
320 for (ch = 1; ch <= s->fbw_channels; ch++) {
321 if (block->channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]) {
322 block->new_cpl_strategy = 1;
327 block->new_cpl_leak = block->new_cpl_strategy;
329 if (!blk || (block->cpl_in_use && !got_cpl_snr)) {
330 block->new_snr_offsets = 1;
331 if (block->cpl_in_use)
334 block->new_snr_offsets = 0;
338 /* set bandwidth for each channel */
339 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
340 AC3Block *block = &s->blocks[blk];
341 for (ch = 1; ch <= s->fbw_channels; ch++) {
342 if (block->channel_in_cpl[ch])
343 block->end_freq[ch] = s->start_freq[CPL_CH];
345 block->end_freq[ch] = s->bandwidth_code * 3 + 73;
352 * Calculate a single coupling coordinate.
354 static inline float calc_cpl_coord(float energy_ch, float energy_cpl)
358 coord *= sqrtf(energy_ch / energy_cpl);
364 * Calculate coupling channel and coupling coordinates.
365 * TODO: Currently this is only used for the floating-point encoder. I was
366 * able to make it work for the fixed-point encoder, but quality was
367 * generally lower in most cases than not using coupling. If a more
368 * adaptive coupling strategy were to be implemented it might be useful
369 * at that time to use coupling for the fixed-point encoder as well.
371 static void apply_channel_coupling(AC3EncodeContext *s)
373 #if CONFIG_AC3ENC_FLOAT
374 LOCAL_ALIGNED_16(float, cpl_coords, [AC3_MAX_BLOCKS], [AC3_MAX_CHANNELS][16]);
375 LOCAL_ALIGNED_16(int32_t, fixed_cpl_coords, [AC3_MAX_BLOCKS], [AC3_MAX_CHANNELS][16]);
376 int blk, ch, bnd, i, j;
377 CoefSumType energy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][16] = {{{0}}};
378 int num_cpl_coefs = s->num_cpl_subbands * 12;
380 memset(cpl_coords, 0, AC3_MAX_BLOCKS * sizeof(*cpl_coords));
381 memset(fixed_cpl_coords, 0, AC3_MAX_BLOCKS * sizeof(*fixed_cpl_coords));
383 /* calculate coupling channel from fbw channels */
384 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
385 AC3Block *block = &s->blocks[blk];
386 CoefType *cpl_coef = &block->mdct_coef[CPL_CH][s->start_freq[CPL_CH]];
387 if (!block->cpl_in_use)
389 memset(cpl_coef-1, 0, (num_cpl_coefs+4) * sizeof(*cpl_coef));
390 for (ch = 1; ch <= s->fbw_channels; ch++) {
391 CoefType *ch_coef = &block->mdct_coef[ch][s->start_freq[CPL_CH]];
392 if (!block->channel_in_cpl[ch])
394 for (i = 0; i < num_cpl_coefs; i++)
395 cpl_coef[i] += ch_coef[i];
397 /* note: coupling start bin % 4 will always be 1 and num_cpl_coefs
398 will always be a multiple of 12, so we need to subtract 1 from
399 the start and add 4 to the length when using optimized
400 functions which require 16-byte alignment. */
402 /* coefficients must be clipped to +/- 1.0 in order to be encoded */
403 s->dsp.vector_clipf(cpl_coef-1, cpl_coef-1, -1.0f, 1.0f, num_cpl_coefs+4);
405 /* scale coupling coefficients from float to 24-bit fixed-point */
406 s->ac3dsp.float_to_fixed24(&block->fixed_coef[CPL_CH][s->start_freq[CPL_CH]-1],
407 cpl_coef-1, num_cpl_coefs+4);
410 /* calculate energy in each band in coupling channel and each fbw channel */
411 /* TODO: possibly use SIMD to speed up energy calculation */
413 i = s->start_freq[CPL_CH];
414 while (i < s->cpl_end_freq) {
415 int band_size = s->cpl_band_sizes[bnd];
416 for (ch = CPL_CH; ch <= s->fbw_channels; ch++) {
417 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
418 AC3Block *block = &s->blocks[blk];
419 if (!block->cpl_in_use || (ch > CPL_CH && !block->channel_in_cpl[ch]))
421 for (j = 0; j < band_size; j++) {
422 CoefType v = block->mdct_coef[ch][i+j];
423 MAC_COEF(energy[blk][ch][bnd], v, v);
431 /* determine which blocks to send new coupling coordinates for */
432 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
433 AC3Block *block = &s->blocks[blk];
434 AC3Block *block0 = blk ? &s->blocks[blk-1] : NULL;
436 CoefSumType coord_diff[AC3_MAX_CHANNELS] = {0,};
438 if (block->cpl_in_use) {
439 /* calculate coupling coordinates for all blocks and calculate the
440 average difference between coordinates in successive blocks */
441 for (ch = 1; ch <= s->fbw_channels; ch++) {
442 if (!block->channel_in_cpl[ch])
445 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
446 cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy[blk][ch][bnd],
447 energy[blk][CPL_CH][bnd]);
448 if (blk > 0 && block0->cpl_in_use &&
449 block0->channel_in_cpl[ch]) {
450 coord_diff[ch] += fabs(cpl_coords[blk-1][ch][bnd] -
451 cpl_coords[blk ][ch][bnd]);
454 coord_diff[ch] /= s->num_cpl_bands;
457 /* send new coordinates if this is the first block, if previous
458 * block did not use coupling but this block does, the channels
459 * using coupling has changed from the previous block, or the
460 * coordinate difference from the last block for any channel is
461 * greater than a threshold value. */
464 } else if (!block0->cpl_in_use) {
467 for (ch = 1; ch <= s->fbw_channels; ch++) {
468 if (block->channel_in_cpl[ch] && !block0->channel_in_cpl[ch]) {
474 for (ch = 1; ch <= s->fbw_channels; ch++) {
475 if (block->channel_in_cpl[ch] && coord_diff[ch] > 0.04) {
483 block->new_cpl_coords = new_coords;
486 /* calculate final coupling coordinates, taking into account reusing of
487 coordinates in successive blocks */
488 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
490 while (blk < AC3_MAX_BLOCKS) {
492 CoefSumType energy_cpl;
493 AC3Block *block = &s->blocks[blk];
495 if (!block->cpl_in_use) {
500 energy_cpl = energy[blk][CPL_CH][bnd];
502 while (!s->blocks[blk1].new_cpl_coords && blk1 < AC3_MAX_BLOCKS) {
503 if (s->blocks[blk1].cpl_in_use)
504 energy_cpl += energy[blk1][CPL_CH][bnd];
508 for (ch = 1; ch <= s->fbw_channels; ch++) {
510 if (!block->channel_in_cpl[ch])
512 energy_ch = energy[blk][ch][bnd];
514 while (!s->blocks[blk1].new_cpl_coords && blk1 < AC3_MAX_BLOCKS) {
515 if (s->blocks[blk1].cpl_in_use)
516 energy_ch += energy[blk1][ch][bnd];
519 cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy_ch, energy_cpl);
525 /* calculate exponents/mantissas for coupling coordinates */
526 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
527 AC3Block *block = &s->blocks[blk];
528 if (!block->cpl_in_use || !block->new_cpl_coords)
531 s->ac3dsp.float_to_fixed24(fixed_cpl_coords[blk][1],
533 s->fbw_channels * 16);
534 s->ac3dsp.extract_exponents(block->cpl_coord_exp[1],
535 fixed_cpl_coords[blk][1],
536 s->fbw_channels * 16);
538 for (ch = 1; ch <= s->fbw_channels; ch++) {
539 int bnd, min_exp, max_exp, master_exp;
541 /* determine master exponent */
542 min_exp = max_exp = block->cpl_coord_exp[ch][0];
543 for (bnd = 1; bnd < s->num_cpl_bands; bnd++) {
544 int exp = block->cpl_coord_exp[ch][bnd];
545 min_exp = FFMIN(exp, min_exp);
546 max_exp = FFMAX(exp, max_exp);
548 master_exp = ((max_exp - 15) + 2) / 3;
549 master_exp = FFMAX(master_exp, 0);
550 while (min_exp < master_exp * 3)
552 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
553 block->cpl_coord_exp[ch][bnd] = av_clip(block->cpl_coord_exp[ch][bnd] -
554 master_exp * 3, 0, 15);
556 block->cpl_master_exp[ch] = master_exp;
558 /* quantize mantissas */
559 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
560 int cpl_exp = block->cpl_coord_exp[ch][bnd];
561 int cpl_mant = (fixed_cpl_coords[blk][ch][bnd] << (5 + cpl_exp + master_exp * 3)) >> 24;
567 block->cpl_coord_mant[ch][bnd] = cpl_mant;
572 if (CONFIG_EAC3_ENCODER && s->eac3)
573 ff_eac3_set_cpl_states(s);
574 #endif /* CONFIG_AC3ENC_FLOAT */
579 * Determine rematrixing flags for each block and band.
581 static void compute_rematrixing_strategy(AC3EncodeContext *s)
585 AC3Block *block, *block0;
587 if (s->channel_mode != AC3_CHMODE_STEREO)
590 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
591 block = &s->blocks[blk];
592 block->new_rematrixing_strategy = !blk;
594 if (!s->rematrixing_enabled) {
599 block->num_rematrixing_bands = 4;
600 if (block->cpl_in_use) {
601 block->num_rematrixing_bands -= (s->start_freq[CPL_CH] <= 61);
602 block->num_rematrixing_bands -= (s->start_freq[CPL_CH] == 37);
603 if (blk && block->num_rematrixing_bands != block0->num_rematrixing_bands)
604 block->new_rematrixing_strategy = 1;
606 nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
608 for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {
609 /* calculate calculate sum of squared coeffs for one band in one block */
610 int start = ff_ac3_rematrix_band_tab[bnd];
611 int end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
612 CoefSumType sum[4] = {0,};
613 for (i = start; i < end; i++) {
614 CoefType lt = block->mdct_coef[1][i];
615 CoefType rt = block->mdct_coef[2][i];
616 CoefType md = lt + rt;
617 CoefType sd = lt - rt;
618 MAC_COEF(sum[0], lt, lt);
619 MAC_COEF(sum[1], rt, rt);
620 MAC_COEF(sum[2], md, md);
621 MAC_COEF(sum[3], sd, sd);
624 /* compare sums to determine if rematrixing will be used for this band */
625 if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
626 block->rematrixing_flags[bnd] = 1;
628 block->rematrixing_flags[bnd] = 0;
630 /* determine if new rematrixing flags will be sent */
632 block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
633 block->new_rematrixing_strategy = 1;
642 * Apply stereo rematrixing to coefficients based on rematrixing flags.
644 static void apply_rematrixing(AC3EncodeContext *s)
651 if (!s->rematrixing_enabled)
654 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
655 AC3Block *block = &s->blocks[blk];
656 if (block->new_rematrixing_strategy)
657 flags = block->rematrixing_flags;
658 nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
659 for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {
661 start = ff_ac3_rematrix_band_tab[bnd];
662 end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
663 for (i = start; i < end; i++) {
664 int32_t lt = block->fixed_coef[1][i];
665 int32_t rt = block->fixed_coef[2][i];
666 block->fixed_coef[1][i] = (lt + rt) >> 1;
667 block->fixed_coef[2][i] = (lt - rt) >> 1;
676 * Initialize exponent tables.
678 static av_cold void exponent_init(AC3EncodeContext *s)
680 int expstr, i, grpsize;
682 for (expstr = EXP_D15-1; expstr <= EXP_D45-1; expstr++) {
683 grpsize = 3 << expstr;
684 for (i = 12; i < 256; i++) {
685 exponent_group_tab[0][expstr][i] = (i + grpsize - 4) / grpsize;
686 exponent_group_tab[1][expstr][i] = (i ) / grpsize;
690 exponent_group_tab[0][0][7] = 2;
695 * Extract exponents from the MDCT coefficients.
696 * This takes into account the normalization that was done to the input samples
697 * by adjusting the exponents by the exponent shift values.
699 static void extract_exponents(AC3EncodeContext *s)
702 int chan_size = AC3_MAX_COEFS * AC3_MAX_BLOCKS * (s->channels - ch + 1);
703 AC3Block *block = &s->blocks[0];
705 s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch], chan_size);
710 * Exponent Difference Threshold.
711 * New exponents are sent if their SAD exceed this number.
713 #define EXP_DIFF_THRESHOLD 500
717 * Calculate exponent strategies for all channels.
718 * Array arrangement is reversed to simplify the per-channel calculation.
720 static void compute_exp_strategy(AC3EncodeContext *s)
724 for (ch = !s->cpl_on; ch <= s->fbw_channels; ch++) {
725 uint8_t *exp_strategy = s->exp_strategy[ch];
726 uint8_t *exp = s->blocks[0].exp[ch];
729 /* estimate if the exponent variation & decide if they should be
730 reused in the next frame */
731 exp_strategy[0] = EXP_NEW;
732 exp += AC3_MAX_COEFS;
733 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++, exp += AC3_MAX_COEFS) {
734 if ((ch == CPL_CH && (!s->blocks[blk].cpl_in_use || !s->blocks[blk-1].cpl_in_use)) ||
735 (ch > CPL_CH && (s->blocks[blk].channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]))) {
736 exp_strategy[blk] = EXP_NEW;
739 exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
740 exp_strategy[blk] = EXP_REUSE;
741 if (ch == CPL_CH && exp_diff > (EXP_DIFF_THRESHOLD * (s->blocks[blk].end_freq[ch] - s->start_freq[ch]) / AC3_MAX_COEFS))
742 exp_strategy[blk] = EXP_NEW;
743 else if (ch > CPL_CH && exp_diff > EXP_DIFF_THRESHOLD)
744 exp_strategy[blk] = EXP_NEW;
747 /* now select the encoding strategy type : if exponents are often
748 recoded, we use a coarse encoding */
750 while (blk < AC3_MAX_BLOCKS) {
752 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
754 switch (blk1 - blk) {
755 case 1: exp_strategy[blk] = EXP_D45; break;
757 case 3: exp_strategy[blk] = EXP_D25; break;
758 default: exp_strategy[blk] = EXP_D15; break;
765 s->exp_strategy[ch][0] = EXP_D15;
766 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
767 s->exp_strategy[ch][blk] = EXP_REUSE;
773 * Update the exponents so that they are the ones the decoder will decode.
775 static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy,
780 nb_groups = exponent_group_tab[cpl][exp_strategy-1][nb_exps] * 3;
782 /* for each group, compute the minimum exponent */
783 switch(exp_strategy) {
785 for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
786 uint8_t exp_min = exp[k];
787 if (exp[k+1] < exp_min)
789 exp[i-cpl] = exp_min;
794 for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
795 uint8_t exp_min = exp[k];
796 if (exp[k+1] < exp_min)
798 if (exp[k+2] < exp_min)
800 if (exp[k+3] < exp_min)
802 exp[i-cpl] = exp_min;
808 /* constraint for DC exponent */
809 if (!cpl && exp[0] > 15)
812 /* decrease the delta between each groups to within 2 so that they can be
813 differentially encoded */
814 for (i = 1; i <= nb_groups; i++)
815 exp[i] = FFMIN(exp[i], exp[i-1] + 2);
818 exp[i] = FFMIN(exp[i], exp[i+1] + 2);
821 exp[-1] = exp[0] & ~1;
823 /* now we have the exponent values the decoder will see */
824 switch (exp_strategy) {
826 for (i = nb_groups, k = (nb_groups * 2)-cpl; i > 0; i--) {
827 uint8_t exp1 = exp[i-cpl];
833 for (i = nb_groups, k = (nb_groups * 4)-cpl; i > 0; i--) {
834 exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i-cpl];
843 * Encode exponents from original extracted form to what the decoder will see.
844 * This copies and groups exponents based on exponent strategy and reduces
845 * deltas between adjacent exponent groups so that they can be differentially
848 static void encode_exponents(AC3EncodeContext *s)
850 int blk, blk1, ch, cpl;
851 uint8_t *exp, *exp_strategy;
852 int nb_coefs, num_reuse_blocks;
854 for (ch = !s->cpl_on; ch <= s->channels; ch++) {
855 exp = s->blocks[0].exp[ch] + s->start_freq[ch];
856 exp_strategy = s->exp_strategy[ch];
858 cpl = (ch == CPL_CH);
860 while (blk < AC3_MAX_BLOCKS) {
861 AC3Block *block = &s->blocks[blk];
862 if (cpl && !block->cpl_in_use) {
863 exp += AC3_MAX_COEFS;
867 nb_coefs = block->end_freq[ch] - s->start_freq[ch];
870 /* count the number of EXP_REUSE blocks after the current block
871 and set exponent reference block numbers */
872 s->exp_ref_block[ch][blk] = blk;
873 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
874 s->exp_ref_block[ch][blk1] = blk;
877 num_reuse_blocks = blk1 - blk - 1;
879 /* for the EXP_REUSE case we select the min of the exponents */
880 s->ac3dsp.ac3_exponent_min(exp-s->start_freq[ch], num_reuse_blocks,
883 encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk], cpl);
885 exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
890 /* reference block numbers have been changed, so reset ref_bap_set */
897 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
898 * varies depending on exponent strategy and bandwidth.
900 static void group_exponents(AC3EncodeContext *s)
903 int group_size, nb_groups, bit_count;
905 int delta0, delta1, delta2;
909 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
910 AC3Block *block = &s->blocks[blk];
911 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
912 int exp_strategy = s->exp_strategy[ch][blk];
913 if (exp_strategy == EXP_REUSE)
915 cpl = (ch == CPL_CH);
916 group_size = exp_strategy + (exp_strategy == EXP_D45);
917 nb_groups = exponent_group_tab[cpl][exp_strategy-1][block->end_freq[ch]-s->start_freq[ch]];
918 bit_count += 4 + (nb_groups * 7);
919 p = block->exp[ch] + s->start_freq[ch] - cpl;
923 block->grouped_exp[ch][0] = exp1;
925 /* remaining exponents are delta encoded */
926 for (i = 1; i <= nb_groups; i++) {
927 /* merge three delta in one code */
931 delta0 = exp1 - exp0 + 2;
932 av_assert2(delta0 >= 0 && delta0 <= 4);
937 delta1 = exp1 - exp0 + 2;
938 av_assert2(delta1 >= 0 && delta1 <= 4);
943 delta2 = exp1 - exp0 + 2;
944 av_assert2(delta2 >= 0 && delta2 <= 4);
946 block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
951 s->exponent_bits = bit_count;
956 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
957 * Extract exponents from MDCT coefficients, calculate exponent strategies,
958 * and encode final exponents.
960 static void process_exponents(AC3EncodeContext *s)
962 extract_exponents(s);
964 compute_exp_strategy(s);
975 * Count frame bits that are based solely on fixed parameters.
976 * This only has to be run once when the encoder is initialized.
978 static void count_frame_bits_fixed(AC3EncodeContext *s)
980 static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
985 * no dynamic range codes
986 * bit allocation parameters do not change between blocks
987 * no delta bit allocation
994 frame_bits = 16; /* sync info */
996 /* bitstream info header */
998 frame_bits += 1 + 1 + 1;
999 /* audio frame header */
1002 /* exponent strategy */
1003 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1004 frame_bits += 2 * s->fbw_channels + s->lfe_on;
1005 /* converter exponent strategy */
1006 frame_bits += s->fbw_channels * 5;
1009 /* block start info */
1013 frame_bits += frame_bits_inc[s->channel_mode];
1017 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1019 /* block switch flags */
1020 frame_bits += s->fbw_channels;
1023 frame_bits += s->fbw_channels;
1029 /* spectral extension */
1034 /* exponent strategy */
1035 frame_bits += 2 * s->fbw_channels;
1039 /* bit allocation params */
1042 frame_bits += 2 + 2 + 2 + 2 + 3;
1045 /* converter snr offset */
1050 /* delta bit allocation */
1058 /* auxiliary data */
1062 frame_bits += 1 + 16;
1064 s->frame_bits_fixed = frame_bits;
1069 * Initialize bit allocation.
1070 * Set default parameter codes and calculate parameter values.
1072 static void bit_alloc_init(AC3EncodeContext *s)
1076 /* init default parameters */
1077 s->slow_decay_code = 2;
1078 s->fast_decay_code = 1;
1079 s->slow_gain_code = 1;
1080 s->db_per_bit_code = s->eac3 ? 2 : 3;
1082 for (ch = 0; ch <= s->channels; ch++)
1083 s->fast_gain_code[ch] = 4;
1085 /* initial snr offset */
1086 s->coarse_snr_offset = 40;
1088 /* compute real values */
1089 /* currently none of these values change during encoding, so we can just
1090 set them once at initialization */
1091 s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
1092 s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
1093 s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
1094 s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
1095 s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
1096 s->bit_alloc.cpl_fast_leak = 0;
1097 s->bit_alloc.cpl_slow_leak = 0;
1099 count_frame_bits_fixed(s);
1104 * Count the bits used to encode the frame, minus exponents and mantissas.
1105 * Bits based on fixed parameters have already been counted, so now we just
1106 * have to add the bits based on parameters that change during encoding.
1108 static void count_frame_bits(AC3EncodeContext *s)
1110 AC3EncOptions *opt = &s->options;
1117 if (s->channel_mode > AC3_CHMODE_MONO) {
1119 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
1120 AC3Block *block = &s->blocks[blk];
1122 if (block->new_cpl_strategy)
1126 /* coupling exponent strategy */
1127 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1128 frame_bits += 2 * s->blocks[blk].cpl_in_use;
1130 if (opt->audio_production_info)
1132 if (s->bitstream_id == 6) {
1133 if (opt->extended_bsi_1)
1135 if (opt->extended_bsi_2)
1141 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1142 AC3Block *block = &s->blocks[blk];
1144 /* coupling strategy */
1147 if (block->new_cpl_strategy) {
1150 if (block->cpl_in_use) {
1153 if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO)
1154 frame_bits += s->fbw_channels;
1155 if (s->channel_mode == AC3_CHMODE_STEREO)
1157 frame_bits += 4 + 4;
1161 frame_bits += s->num_cpl_subbands - 1;
1165 /* coupling coordinates */
1166 if (block->cpl_in_use) {
1167 for (ch = 1; ch <= s->fbw_channels; ch++) {
1168 if (block->channel_in_cpl[ch]) {
1169 if (!s->eac3 || block->new_cpl_coords != 2)
1171 if (block->new_cpl_coords) {
1173 frame_bits += (4 + 4) * s->num_cpl_bands;
1179 /* stereo rematrixing */
1180 if (s->channel_mode == AC3_CHMODE_STEREO) {
1181 if (!s->eac3 || blk > 0)
1183 if (s->blocks[blk].new_rematrixing_strategy)
1184 frame_bits += block->num_rematrixing_bands;
1187 /* bandwidth codes & gain range */
1188 for (ch = 1; ch <= s->fbw_channels; ch++) {
1189 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1190 if (!block->channel_in_cpl[ch])
1196 /* coupling exponent strategy */
1197 if (!s->eac3 && block->cpl_in_use)
1200 /* snr offsets and fast gain codes */
1203 if (block->new_snr_offsets)
1204 frame_bits += 6 + (s->channels + block->cpl_in_use) * (4 + 3);
1207 /* coupling leak info */
1208 if (block->cpl_in_use) {
1209 if (!s->eac3 || block->new_cpl_leak != 2)
1211 if (block->new_cpl_leak)
1212 frame_bits += 3 + 3;
1216 s->frame_bits = s->frame_bits_fixed + frame_bits;
1221 * Calculate masking curve based on the final exponents.
1222 * Also calculate the power spectral densities to use in future calculations.
1224 static void bit_alloc_masking(AC3EncodeContext *s)
1228 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1229 AC3Block *block = &s->blocks[blk];
1230 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1231 /* We only need psd and mask for calculating bap.
1232 Since we currently do not calculate bap when exponent
1233 strategy is EXP_REUSE we do not need to calculate psd or mask. */
1234 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1235 ff_ac3_bit_alloc_calc_psd(block->exp[ch], s->start_freq[ch],
1236 block->end_freq[ch], block->psd[ch],
1237 block->band_psd[ch]);
1238 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
1239 s->start_freq[ch], block->end_freq[ch],
1240 ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
1241 ch == s->lfe_channel,
1242 DBA_NONE, 0, NULL, NULL, NULL,
1251 * Ensure that bap for each block and channel point to the current bap_buffer.
1252 * They may have been switched during the bit allocation search.
1254 static void reset_block_bap(AC3EncodeContext *s)
1259 if (s->ref_bap[0][0] == s->bap_buffer && s->ref_bap_set)
1262 ref_bap = s->bap_buffer;
1263 for (ch = 0; ch <= s->channels; ch++) {
1264 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1265 s->ref_bap[ch][blk] = ref_bap + AC3_MAX_COEFS * s->exp_ref_block[ch][blk];
1266 ref_bap += AC3_MAX_COEFS * AC3_MAX_BLOCKS;
1273 * Initialize mantissa counts.
1274 * These are set so that they are padded to the next whole group size when bits
1275 * are counted in compute_mantissa_size.
1277 static void count_mantissa_bits_init(uint16_t mant_cnt[AC3_MAX_BLOCKS][16])
1281 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1282 memset(mant_cnt[blk], 0, sizeof(mant_cnt[blk]));
1283 mant_cnt[blk][1] = mant_cnt[blk][2] = 2;
1284 mant_cnt[blk][4] = 1;
1290 * Update mantissa bit counts for all blocks in 1 channel in a given bandwidth
1293 static void count_mantissa_bits_update_ch(AC3EncodeContext *s, int ch,
1294 uint16_t mant_cnt[AC3_MAX_BLOCKS][16],
1299 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1300 AC3Block *block = &s->blocks[blk];
1301 if (ch == CPL_CH && !block->cpl_in_use)
1303 s->ac3dsp.update_bap_counts(mant_cnt[blk],
1304 s->ref_bap[ch][blk] + start,
1305 FFMIN(end, block->end_freq[ch]) - start);
1311 * Count the number of mantissa bits in the frame based on the bap values.
1313 static int count_mantissa_bits(AC3EncodeContext *s)
1315 int ch, max_end_freq;
1316 LOCAL_ALIGNED_16(uint16_t, mant_cnt, [AC3_MAX_BLOCKS], [16]);
1318 count_mantissa_bits_init(mant_cnt);
1320 max_end_freq = s->bandwidth_code * 3 + 73;
1321 for (ch = !s->cpl_enabled; ch <= s->channels; ch++)
1322 count_mantissa_bits_update_ch(s, ch, mant_cnt, s->start_freq[ch],
1325 return s->ac3dsp.compute_mantissa_size(mant_cnt);
1330 * Run the bit allocation with a given SNR offset.
1331 * This calculates the bit allocation pointers that will be used to determine
1332 * the quantization of each mantissa.
1333 * @return the number of bits needed for mantissas if the given SNR offset is
1336 static int bit_alloc(AC3EncodeContext *s, int snr_offset)
1340 snr_offset = (snr_offset - 240) << 2;
1343 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1344 AC3Block *block = &s->blocks[blk];
1346 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1347 /* Currently the only bit allocation parameters which vary across
1348 blocks within a frame are the exponent values. We can take
1349 advantage of that by reusing the bit allocation pointers
1350 whenever we reuse exponents. */
1351 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1352 s->ac3dsp.bit_alloc_calc_bap(block->mask[ch], block->psd[ch],
1353 s->start_freq[ch], block->end_freq[ch],
1354 snr_offset, s->bit_alloc.floor,
1355 ff_ac3_bap_tab, s->ref_bap[ch][blk]);
1359 return count_mantissa_bits(s);
1364 * Constant bitrate bit allocation search.
1365 * Find the largest SNR offset that will allow data to fit in the frame.
1367 static int cbr_bit_allocation(AC3EncodeContext *s)
1371 int snr_offset, snr_incr;
1373 bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1375 return AVERROR(EINVAL);
1377 snr_offset = s->coarse_snr_offset << 4;
1379 /* if previous frame SNR offset was 1023, check if current frame can also
1380 use SNR offset of 1023. if so, skip the search. */
1381 if ((snr_offset | s->fine_snr_offset[1]) == 1023) {
1382 if (bit_alloc(s, 1023) <= bits_left)
1386 while (snr_offset >= 0 &&
1387 bit_alloc(s, snr_offset) > bits_left) {
1391 return AVERROR(EINVAL);
1393 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1394 for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1395 while (snr_offset + snr_incr <= 1023 &&
1396 bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1397 snr_offset += snr_incr;
1398 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1401 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1404 s->coarse_snr_offset = snr_offset >> 4;
1405 for (ch = !s->cpl_on; ch <= s->channels; ch++)
1406 s->fine_snr_offset[ch] = snr_offset & 0xF;
1413 * Downgrade exponent strategies to reduce the bits used by the exponents.
1414 * This is a fallback for when bit allocation fails with the normal exponent
1415 * strategies. Each time this function is run it only downgrades the
1416 * strategy in 1 channel of 1 block.
1417 * @return non-zero if downgrade was unsuccessful
1419 static int downgrade_exponents(AC3EncodeContext *s)
1423 for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1424 for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
1425 if (s->exp_strategy[ch][blk] == EXP_D15) {
1426 s->exp_strategy[ch][blk] = EXP_D25;
1431 for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1432 for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
1433 if (s->exp_strategy[ch][blk] == EXP_D25) {
1434 s->exp_strategy[ch][blk] = EXP_D45;
1439 /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
1440 the block number > 0 */
1441 for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
1442 for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
1443 if (s->exp_strategy[ch][blk] > EXP_REUSE) {
1444 s->exp_strategy[ch][blk] = EXP_REUSE;
1454 * Perform bit allocation search.
1455 * Finds the SNR offset value that maximizes quality and fits in the specified
1456 * frame size. Output is the SNR offset and a set of bit allocation pointers
1457 * used to quantize the mantissas.
1459 static int compute_bit_allocation(AC3EncodeContext *s)
1463 count_frame_bits(s);
1465 bit_alloc_masking(s);
1467 ret = cbr_bit_allocation(s);
1469 /* fallback 1: disable channel coupling */
1472 compute_coupling_strategy(s);
1473 compute_rematrixing_strategy(s);
1474 apply_rematrixing(s);
1475 process_exponents(s);
1476 ret = compute_bit_allocation(s);
1480 /* fallback 2: downgrade exponents */
1481 if (!downgrade_exponents(s)) {
1482 extract_exponents(s);
1483 encode_exponents(s);
1485 ret = compute_bit_allocation(s);
1489 /* fallbacks were not enough... */
1498 * Symmetric quantization on 'levels' levels.
1500 static inline int sym_quant(int c, int e, int levels)
1502 int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1503 av_assert2(v >= 0 && v < levels);
1509 * Asymmetric quantization on 2^qbits levels.
1511 static inline int asym_quant(int c, int e, int qbits)
1515 lshift = e + qbits - 24;
1522 m = (1 << (qbits-1));
1525 av_assert2(v >= -m);
1526 return v & ((1 << qbits)-1);
1531 * Quantize a set of mantissas for a single channel in a single block.
1533 static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1534 uint8_t *exp, uint8_t *bap,
1535 uint16_t *qmant, int start_freq,
1540 for (i = start_freq; i < end_freq; i++) {
1542 int c = fixed_coef[i];
1550 v = sym_quant(c, e, 3);
1551 switch (s->mant1_cnt) {
1553 s->qmant1_ptr = &qmant[i];
1558 *s->qmant1_ptr += 3 * v;
1563 *s->qmant1_ptr += v;
1570 v = sym_quant(c, e, 5);
1571 switch (s->mant2_cnt) {
1573 s->qmant2_ptr = &qmant[i];
1578 *s->qmant2_ptr += 5 * v;
1583 *s->qmant2_ptr += v;
1590 v = sym_quant(c, e, 7);
1593 v = sym_quant(c, e, 11);
1594 switch (s->mant4_cnt) {
1596 s->qmant4_ptr = &qmant[i];
1601 *s->qmant4_ptr += v;
1608 v = sym_quant(c, e, 15);
1611 v = asym_quant(c, e, 14);
1614 v = asym_quant(c, e, 16);
1617 v = asym_quant(c, e, b - 1);
1626 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1628 static void quantize_mantissas(AC3EncodeContext *s)
1630 int blk, ch, ch0=0, got_cpl;
1632 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1633 AC3Block *block = &s->blocks[blk];
1636 got_cpl = !block->cpl_in_use;
1637 for (ch = 1; ch <= s->channels; ch++) {
1638 if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1643 quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1644 s->blocks[s->exp_ref_block[ch][blk]].exp[ch],
1645 s->ref_bap[ch][blk], block->qmant[ch],
1646 s->start_freq[ch], block->end_freq[ch]);
1655 * Write the AC-3 frame header to the output bitstream.
1657 static void ac3_output_frame_header(AC3EncodeContext *s)
1659 AC3EncOptions *opt = &s->options;
1661 put_bits(&s->pb, 16, 0x0b77); /* frame header */
1662 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
1663 put_bits(&s->pb, 2, s->bit_alloc.sr_code);
1664 put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1665 put_bits(&s->pb, 5, s->bitstream_id);
1666 put_bits(&s->pb, 3, s->bitstream_mode);
1667 put_bits(&s->pb, 3, s->channel_mode);
1668 if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1669 put_bits(&s->pb, 2, s->center_mix_level);
1670 if (s->channel_mode & 0x04)
1671 put_bits(&s->pb, 2, s->surround_mix_level);
1672 if (s->channel_mode == AC3_CHMODE_STEREO)
1673 put_bits(&s->pb, 2, opt->dolby_surround_mode);
1674 put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1675 put_bits(&s->pb, 5, -opt->dialogue_level);
1676 put_bits(&s->pb, 1, 0); /* no compression control word */
1677 put_bits(&s->pb, 1, 0); /* no lang code */
1678 put_bits(&s->pb, 1, opt->audio_production_info);
1679 if (opt->audio_production_info) {
1680 put_bits(&s->pb, 5, opt->mixing_level - 80);
1681 put_bits(&s->pb, 2, opt->room_type);
1683 put_bits(&s->pb, 1, opt->copyright);
1684 put_bits(&s->pb, 1, opt->original);
1685 if (s->bitstream_id == 6) {
1686 /* alternate bit stream syntax */
1687 put_bits(&s->pb, 1, opt->extended_bsi_1);
1688 if (opt->extended_bsi_1) {
1689 put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1690 put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1691 put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1692 put_bits(&s->pb, 3, s->loro_center_mix_level);
1693 put_bits(&s->pb, 3, s->loro_surround_mix_level);
1695 put_bits(&s->pb, 1, opt->extended_bsi_2);
1696 if (opt->extended_bsi_2) {
1697 put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1698 put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1699 put_bits(&s->pb, 1, opt->ad_converter_type);
1700 put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
1703 put_bits(&s->pb, 1, 0); /* no time code 1 */
1704 put_bits(&s->pb, 1, 0); /* no time code 2 */
1706 put_bits(&s->pb, 1, 0); /* no additional bit stream info */
1711 * Write one audio block to the output bitstream.
1713 static void output_audio_block(AC3EncodeContext *s, int blk)
1715 int ch, i, baie, bnd, got_cpl;
1717 AC3Block *block = &s->blocks[blk];
1719 /* block switching */
1721 for (ch = 0; ch < s->fbw_channels; ch++)
1722 put_bits(&s->pb, 1, 0);
1727 for (ch = 0; ch < s->fbw_channels; ch++)
1728 put_bits(&s->pb, 1, 1);
1731 /* dynamic range codes */
1732 put_bits(&s->pb, 1, 0);
1734 /* spectral extension */
1736 put_bits(&s->pb, 1, 0);
1738 /* channel coupling */
1740 put_bits(&s->pb, 1, block->new_cpl_strategy);
1741 if (block->new_cpl_strategy) {
1743 put_bits(&s->pb, 1, block->cpl_in_use);
1744 if (block->cpl_in_use) {
1745 int start_sub, end_sub;
1747 put_bits(&s->pb, 1, 0); /* enhanced coupling */
1748 if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO) {
1749 for (ch = 1; ch <= s->fbw_channels; ch++)
1750 put_bits(&s->pb, 1, block->channel_in_cpl[ch]);
1752 if (s->channel_mode == AC3_CHMODE_STEREO)
1753 put_bits(&s->pb, 1, 0); /* phase flags in use */
1754 start_sub = (s->start_freq[CPL_CH] - 37) / 12;
1755 end_sub = (s->cpl_end_freq - 37) / 12;
1756 put_bits(&s->pb, 4, start_sub);
1757 put_bits(&s->pb, 4, end_sub - 3);
1758 /* coupling band structure */
1760 put_bits(&s->pb, 1, 0); /* use default */
1762 for (bnd = start_sub+1; bnd < end_sub; bnd++)
1763 put_bits(&s->pb, 1, ff_eac3_default_cpl_band_struct[bnd]);
1768 /* coupling coordinates */
1769 if (block->cpl_in_use) {
1770 for (ch = 1; ch <= s->fbw_channels; ch++) {
1771 if (block->channel_in_cpl[ch]) {
1772 if (!s->eac3 || block->new_cpl_coords != 2)
1773 put_bits(&s->pb, 1, block->new_cpl_coords);
1774 if (block->new_cpl_coords) {
1775 put_bits(&s->pb, 2, block->cpl_master_exp[ch]);
1776 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
1777 put_bits(&s->pb, 4, block->cpl_coord_exp [ch][bnd]);
1778 put_bits(&s->pb, 4, block->cpl_coord_mant[ch][bnd]);
1785 /* stereo rematrixing */
1786 if (s->channel_mode == AC3_CHMODE_STEREO) {
1787 if (!s->eac3 || blk > 0)
1788 put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1789 if (block->new_rematrixing_strategy) {
1790 /* rematrixing flags */
1791 for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++)
1792 put_bits(&s->pb, 1, block->rematrixing_flags[bnd]);
1796 /* exponent strategy */
1798 for (ch = !block->cpl_in_use; ch <= s->fbw_channels; ch++)
1799 put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1801 put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1805 for (ch = 1; ch <= s->fbw_channels; ch++) {
1806 if (s->exp_strategy[ch][blk] != EXP_REUSE && !block->channel_in_cpl[ch])
1807 put_bits(&s->pb, 6, s->bandwidth_code);
1811 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1813 int cpl = (ch == CPL_CH);
1815 if (s->exp_strategy[ch][blk] == EXP_REUSE)
1819 put_bits(&s->pb, 4, block->grouped_exp[ch][0] >> cpl);
1821 /* exponent groups */
1822 nb_groups = exponent_group_tab[cpl][s->exp_strategy[ch][blk]-1][block->end_freq[ch]-s->start_freq[ch]];
1823 for (i = 1; i <= nb_groups; i++)
1824 put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1826 /* gain range info */
1827 if (ch != s->lfe_channel && !cpl)
1828 put_bits(&s->pb, 2, 0);
1831 /* bit allocation info */
1834 put_bits(&s->pb, 1, baie);
1836 put_bits(&s->pb, 2, s->slow_decay_code);
1837 put_bits(&s->pb, 2, s->fast_decay_code);
1838 put_bits(&s->pb, 2, s->slow_gain_code);
1839 put_bits(&s->pb, 2, s->db_per_bit_code);
1840 put_bits(&s->pb, 3, s->floor_code);
1846 put_bits(&s->pb, 1, block->new_snr_offsets);
1847 if (block->new_snr_offsets) {
1848 put_bits(&s->pb, 6, s->coarse_snr_offset);
1849 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1850 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1851 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1855 put_bits(&s->pb, 1, 0); /* no converter snr offset */
1859 if (block->cpl_in_use) {
1860 if (!s->eac3 || block->new_cpl_leak != 2)
1861 put_bits(&s->pb, 1, block->new_cpl_leak);
1862 if (block->new_cpl_leak) {
1863 put_bits(&s->pb, 3, s->bit_alloc.cpl_fast_leak);
1864 put_bits(&s->pb, 3, s->bit_alloc.cpl_slow_leak);
1869 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1870 put_bits(&s->pb, 1, 0); /* no data to skip */
1874 got_cpl = !block->cpl_in_use;
1875 for (ch = 1; ch <= s->channels; ch++) {
1878 if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1883 for (i = s->start_freq[ch]; i < block->end_freq[ch]; i++) {
1884 q = block->qmant[ch][i];
1885 b = s->ref_bap[ch][blk][i];
1888 case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
1889 case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
1890 case 3: put_bits(&s->pb, 3, q); break;
1891 case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
1892 case 14: put_bits(&s->pb, 14, q); break;
1893 case 15: put_bits(&s->pb, 16, q); break;
1894 default: put_bits(&s->pb, b-1, q); break;
1903 /** CRC-16 Polynomial */
1904 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1907 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1924 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1930 r = mul_poly(r, a, poly);
1931 a = mul_poly(a, a, poly);
1939 * Fill the end of the frame with 0's and compute the two CRCs.
1941 static void output_frame_end(AC3EncodeContext *s)
1943 const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1944 int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1947 frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1949 /* pad the remainder of the frame with zeros */
1950 av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1951 flush_put_bits(&s->pb);
1953 pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1954 av_assert2(pad_bytes >= 0);
1956 memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1960 crc2_partial = av_crc(crc_ctx, 0, frame + 2, s->frame_size - 5);
1963 /* this is not so easy because it is at the beginning of the data... */
1964 crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1965 crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1966 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1967 AV_WB16(frame + 2, crc1);
1970 crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1971 s->frame_size - frame_size_58 - 3);
1973 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1974 /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1975 if (crc2 == 0x770B) {
1976 frame[s->frame_size - 3] ^= 0x1;
1977 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1979 crc2 = av_bswap16(crc2);
1980 AV_WB16(frame + s->frame_size - 2, crc2);
1985 * Write the frame to the output bitstream.
1987 static void output_frame(AC3EncodeContext *s, unsigned char *frame)
1991 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1993 if (CONFIG_EAC3_ENCODER && s->eac3)
1994 ff_eac3_output_frame_header(s);
1996 ac3_output_frame_header(s);
1998 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1999 output_audio_block(s, blk);
2001 output_frame_end(s);
2005 static void dprint_options(AVCodecContext *avctx)
2008 AC3EncodeContext *s = avctx->priv_data;
2009 AC3EncOptions *opt = &s->options;
2012 switch (s->bitstream_id) {
2013 case 6: av_strlcpy(strbuf, "AC-3 (alt syntax)", 32); break;
2014 case 8: av_strlcpy(strbuf, "AC-3 (standard)", 32); break;
2015 case 9: av_strlcpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
2016 case 10: av_strlcpy(strbuf, "AC-3 (dnet quater-rate)", 32); break;
2017 case 16: av_strlcpy(strbuf, "E-AC-3 (enhanced)", 32); break;
2018 default: snprintf(strbuf, 32, "ERROR");
2020 av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
2021 av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
2022 av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
2023 av_dlog(avctx, "channel_layout: %s\n", strbuf);
2024 av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
2025 av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
2027 av_dlog(avctx, "cutoff: %d\n", s->cutoff);
2029 av_dlog(avctx, "per_frame_metadata: %s\n",
2030 opt->allow_per_frame_metadata?"on":"off");
2032 av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
2033 s->center_mix_level);
2035 av_dlog(avctx, "center_mixlev: {not written}\n");
2036 if (s->has_surround)
2037 av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
2038 s->surround_mix_level);
2040 av_dlog(avctx, "surround_mixlev: {not written}\n");
2041 if (opt->audio_production_info) {
2042 av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
2043 switch (opt->room_type) {
2044 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
2045 case 1: av_strlcpy(strbuf, "large", 32); break;
2046 case 2: av_strlcpy(strbuf, "small", 32); break;
2047 default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
2049 av_dlog(avctx, "room_type: %s\n", strbuf);
2051 av_dlog(avctx, "mixing_level: {not written}\n");
2052 av_dlog(avctx, "room_type: {not written}\n");
2054 av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
2055 av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
2056 if (s->channel_mode == AC3_CHMODE_STEREO) {
2057 switch (opt->dolby_surround_mode) {
2058 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
2059 case 1: av_strlcpy(strbuf, "on", 32); break;
2060 case 2: av_strlcpy(strbuf, "off", 32); break;
2061 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
2063 av_dlog(avctx, "dsur_mode: %s\n", strbuf);
2065 av_dlog(avctx, "dsur_mode: {not written}\n");
2067 av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
2069 if (s->bitstream_id == 6) {
2070 if (opt->extended_bsi_1) {
2071 switch (opt->preferred_stereo_downmix) {
2072 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
2073 case 1: av_strlcpy(strbuf, "ltrt", 32); break;
2074 case 2: av_strlcpy(strbuf, "loro", 32); break;
2075 default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
2077 av_dlog(avctx, "dmix_mode: %s\n", strbuf);
2078 av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
2079 opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
2080 av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
2081 opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
2082 av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
2083 opt->loro_center_mix_level, s->loro_center_mix_level);
2084 av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
2085 opt->loro_surround_mix_level, s->loro_surround_mix_level);
2087 av_dlog(avctx, "extended bitstream info 1: {not written}\n");
2089 if (opt->extended_bsi_2) {
2090 switch (opt->dolby_surround_ex_mode) {
2091 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
2092 case 1: av_strlcpy(strbuf, "on", 32); break;
2093 case 2: av_strlcpy(strbuf, "off", 32); break;
2094 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
2096 av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
2097 switch (opt->dolby_headphone_mode) {
2098 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
2099 case 1: av_strlcpy(strbuf, "on", 32); break;
2100 case 2: av_strlcpy(strbuf, "off", 32); break;
2101 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
2103 av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
2105 switch (opt->ad_converter_type) {
2106 case 0: av_strlcpy(strbuf, "standard", 32); break;
2107 case 1: av_strlcpy(strbuf, "hdcd", 32); break;
2108 default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
2110 av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
2112 av_dlog(avctx, "extended bitstream info 2: {not written}\n");
2119 #define FLT_OPTION_THRESHOLD 0.01
2121 static int validate_float_option(float v, const float *v_list, int v_list_size)
2125 for (i = 0; i < v_list_size; i++) {
2126 if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
2127 v > (v_list[i] - FLT_OPTION_THRESHOLD))
2130 if (i == v_list_size)
2137 static void validate_mix_level(void *log_ctx, const char *opt_name,
2138 float *opt_param, const float *list,
2139 int list_size, int default_value, int min_value,
2142 int mixlev = validate_float_option(*opt_param, list, list_size);
2143 if (mixlev < min_value) {
2144 mixlev = default_value;
2145 if (*opt_param >= 0.0) {
2146 av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
2147 "default value: %0.3f\n", opt_name, list[mixlev]);
2150 *opt_param = list[mixlev];
2151 *ctx_param = mixlev;
2156 * Validate metadata options as set by AVOption system.
2157 * These values can optionally be changed per-frame.
2159 static int validate_metadata(AVCodecContext *avctx)
2161 AC3EncodeContext *s = avctx->priv_data;
2162 AC3EncOptions *opt = &s->options;
2164 /* validate mixing levels */
2165 if (s->has_center) {
2166 validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
2167 cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
2168 &s->center_mix_level);
2170 if (s->has_surround) {
2171 validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
2172 surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
2173 &s->surround_mix_level);
2176 /* set audio production info flag */
2177 if (opt->mixing_level >= 0 || opt->room_type >= 0) {
2178 if (opt->mixing_level < 0) {
2179 av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
2180 "room_type is set\n");
2181 return AVERROR(EINVAL);
2183 if (opt->mixing_level < 80) {
2184 av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
2185 "80dB and 111dB\n");
2186 return AVERROR(EINVAL);
2188 /* default room type */
2189 if (opt->room_type < 0)
2191 opt->audio_production_info = 1;
2193 opt->audio_production_info = 0;
2196 /* set extended bsi 1 flag */
2197 if ((s->has_center || s->has_surround) &&
2198 (opt->preferred_stereo_downmix >= 0 ||
2199 opt->ltrt_center_mix_level >= 0 ||
2200 opt->ltrt_surround_mix_level >= 0 ||
2201 opt->loro_center_mix_level >= 0 ||
2202 opt->loro_surround_mix_level >= 0)) {
2203 /* default preferred stereo downmix */
2204 if (opt->preferred_stereo_downmix < 0)
2205 opt->preferred_stereo_downmix = 0;
2206 /* validate Lt/Rt center mix level */
2207 validate_mix_level(avctx, "ltrt_center_mix_level",
2208 &opt->ltrt_center_mix_level, extmixlev_options,
2209 EXTMIXLEV_NUM_OPTIONS, 5, 0,
2210 &s->ltrt_center_mix_level);
2211 /* validate Lt/Rt surround mix level */
2212 validate_mix_level(avctx, "ltrt_surround_mix_level",
2213 &opt->ltrt_surround_mix_level, extmixlev_options,
2214 EXTMIXLEV_NUM_OPTIONS, 6, 3,
2215 &s->ltrt_surround_mix_level);
2216 /* validate Lo/Ro center mix level */
2217 validate_mix_level(avctx, "loro_center_mix_level",
2218 &opt->loro_center_mix_level, extmixlev_options,
2219 EXTMIXLEV_NUM_OPTIONS, 5, 0,
2220 &s->loro_center_mix_level);
2221 /* validate Lo/Ro surround mix level */
2222 validate_mix_level(avctx, "loro_surround_mix_level",
2223 &opt->loro_surround_mix_level, extmixlev_options,
2224 EXTMIXLEV_NUM_OPTIONS, 6, 3,
2225 &s->loro_surround_mix_level);
2226 opt->extended_bsi_1 = 1;
2228 opt->extended_bsi_1 = 0;
2231 /* set extended bsi 2 flag */
2232 if (opt->dolby_surround_ex_mode >= 0 ||
2233 opt->dolby_headphone_mode >= 0 ||
2234 opt->ad_converter_type >= 0) {
2235 /* default dolby surround ex mode */
2236 if (opt->dolby_surround_ex_mode < 0)
2237 opt->dolby_surround_ex_mode = 0;
2238 /* default dolby headphone mode */
2239 if (opt->dolby_headphone_mode < 0)
2240 opt->dolby_headphone_mode = 0;
2241 /* default A/D converter type */
2242 if (opt->ad_converter_type < 0)
2243 opt->ad_converter_type = 0;
2244 opt->extended_bsi_2 = 1;
2246 opt->extended_bsi_2 = 0;
2249 /* set bitstream id for alternate bitstream syntax */
2250 if (opt->extended_bsi_1 || opt->extended_bsi_2) {
2251 if (s->bitstream_id > 8 && s->bitstream_id < 11) {
2252 static int warn_once = 1;
2254 av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
2255 "not compatible with reduced samplerates. writing of "
2256 "extended bitstream information will be disabled.\n");
2260 s->bitstream_id = 6;
2269 * Encode a single AC-3 frame.
2271 static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
2272 int buf_size, void *data)
2274 AC3EncodeContext *s = avctx->priv_data;
2275 const SampleType *samples = data;
2278 if (!s->eac3 && s->options.allow_per_frame_metadata) {
2279 ret = validate_metadata(avctx);
2284 if (s->bit_alloc.sr_code == 1 || s->eac3)
2285 adjust_frame_size(s);
2287 deinterleave_input_samples(s, samples);
2291 scale_coefficients(s);
2293 s->cpl_on = s->cpl_enabled;
2294 compute_coupling_strategy(s);
2297 apply_channel_coupling(s);
2299 compute_rematrixing_strategy(s);
2301 apply_rematrixing(s);
2303 process_exponents(s);
2305 ret = compute_bit_allocation(s);
2307 av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
2311 quantize_mantissas(s);
2313 output_frame(s, frame);
2315 return s->frame_size;
2320 * Finalize encoding and free any memory allocated by the encoder.
2322 static av_cold int ac3_encode_close(AVCodecContext *avctx)
2325 AC3EncodeContext *s = avctx->priv_data;
2327 for (ch = 0; ch < s->channels; ch++)
2328 av_freep(&s->planar_samples[ch]);
2329 av_freep(&s->planar_samples);
2330 av_freep(&s->bap_buffer);
2331 av_freep(&s->bap1_buffer);
2332 av_freep(&s->mdct_coef_buffer);
2333 av_freep(&s->fixed_coef_buffer);
2334 av_freep(&s->exp_buffer);
2335 av_freep(&s->grouped_exp_buffer);
2336 av_freep(&s->psd_buffer);
2337 av_freep(&s->band_psd_buffer);
2338 av_freep(&s->mask_buffer);
2339 av_freep(&s->qmant_buffer);
2340 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2341 AC3Block *block = &s->blocks[blk];
2342 av_freep(&block->mdct_coef);
2343 av_freep(&block->fixed_coef);
2344 av_freep(&block->exp);
2345 av_freep(&block->grouped_exp);
2346 av_freep(&block->psd);
2347 av_freep(&block->band_psd);
2348 av_freep(&block->mask);
2349 av_freep(&block->qmant);
2354 av_freep(&avctx->coded_frame);
2360 * Set channel information during initialization.
2362 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
2363 int64_t *channel_layout)
2367 if (channels < 1 || channels > AC3_MAX_CHANNELS)
2368 return AVERROR(EINVAL);
2369 if ((uint64_t)*channel_layout > 0x7FF)
2370 return AVERROR(EINVAL);
2371 ch_layout = *channel_layout;
2373 ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
2375 s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
2376 s->channels = channels;
2377 s->fbw_channels = channels - s->lfe_on;
2378 s->lfe_channel = s->lfe_on ? s->fbw_channels + 1 : -1;
2380 ch_layout -= AV_CH_LOW_FREQUENCY;
2382 switch (ch_layout) {
2383 case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
2384 case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
2385 case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
2386 case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
2387 case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
2388 case AV_CH_LAYOUT_QUAD:
2389 case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
2390 case AV_CH_LAYOUT_5POINT0:
2391 case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
2393 return AVERROR(EINVAL);
2395 s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
2396 s->has_surround = s->channel_mode & 0x04;
2398 s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
2399 *channel_layout = ch_layout;
2401 *channel_layout |= AV_CH_LOW_FREQUENCY;
2407 static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
2411 /* validate channel layout */
2412 if (!avctx->channel_layout) {
2413 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
2414 "encoder will guess the layout, but it "
2415 "might be incorrect.\n");
2417 ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
2419 av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
2423 /* validate sample rate */
2424 /* note: max_sr could be changed from 2 to 5 for E-AC-3 once we find a
2425 decoder that supports half sample rate so we can validate that
2426 the generated files are correct. */
2427 max_sr = s->eac3 ? 2 : 8;
2428 for (i = 0; i <= max_sr; i++) {
2429 if ((ff_ac3_sample_rate_tab[i % 3] >> (i / 3)) == avctx->sample_rate)
2433 av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
2434 return AVERROR(EINVAL);
2436 s->sample_rate = avctx->sample_rate;
2437 s->bit_alloc.sr_shift = i / 3;
2438 s->bit_alloc.sr_code = i % 3;
2439 s->bitstream_id = s->eac3 ? 16 : 8 + s->bit_alloc.sr_shift;
2441 /* validate bit rate */
2443 int max_br, min_br, wpf, min_br_dist, min_br_code;
2445 /* calculate min/max bitrate */
2446 max_br = 2048 * s->sample_rate / AC3_FRAME_SIZE * 16;
2447 min_br = ((s->sample_rate + (AC3_FRAME_SIZE-1)) / AC3_FRAME_SIZE) * 16;
2448 if (avctx->bit_rate < min_br || avctx->bit_rate > max_br) {
2449 av_log(avctx, AV_LOG_ERROR, "invalid bit rate. must be %d to %d "
2450 "for this sample rate\n", min_br, max_br);
2451 return AVERROR(EINVAL);
2454 /* calculate words-per-frame for the selected bitrate */
2455 wpf = (avctx->bit_rate / 16) * AC3_FRAME_SIZE / s->sample_rate;
2456 av_assert1(wpf > 0 && wpf <= 2048);
2458 /* find the closest AC-3 bitrate code to the selected bitrate.
2459 this is needed for lookup tables for bandwidth and coupling
2460 parameter selection */
2462 min_br_dist = INT_MAX;
2463 for (i = 0; i < 19; i++) {
2464 int br_dist = abs(ff_ac3_bitrate_tab[i] * 1000 - avctx->bit_rate);
2465 if (br_dist < min_br_dist) {
2466 min_br_dist = br_dist;
2471 /* make sure the minimum frame size is below the average frame size */
2472 s->frame_size_code = min_br_code << 1;
2473 while (wpf > 1 && wpf * s->sample_rate / AC3_FRAME_SIZE * 16 > avctx->bit_rate)
2475 s->frame_size_min = 2 * wpf;
2477 for (i = 0; i < 19; i++) {
2478 if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
2482 av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2483 return AVERROR(EINVAL);
2485 s->frame_size_code = i << 1;
2486 s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2488 s->bit_rate = avctx->bit_rate;
2489 s->frame_size = s->frame_size_min;
2491 /* validate cutoff */
2492 if (avctx->cutoff < 0) {
2493 av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2494 return AVERROR(EINVAL);
2496 s->cutoff = avctx->cutoff;
2497 if (s->cutoff > (s->sample_rate >> 1))
2498 s->cutoff = s->sample_rate >> 1;
2500 /* validate audio service type / channels combination */
2501 if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
2502 avctx->channels == 1) ||
2503 ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
2504 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
2505 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
2506 && avctx->channels > 1)) {
2507 av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
2508 "specified number of channels\n");
2509 return AVERROR(EINVAL);
2513 ret = validate_metadata(avctx);
2518 s->rematrixing_enabled = s->options.stereo_rematrixing &&
2519 (s->channel_mode == AC3_CHMODE_STEREO);
2521 s->cpl_enabled = s->options.channel_coupling &&
2522 s->channel_mode >= AC3_CHMODE_STEREO &&
2523 CONFIG_AC3ENC_FLOAT;
2530 * Set bandwidth for all channels.
2531 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2532 * default value will be used.
2534 static av_cold void set_bandwidth(AC3EncodeContext *s)
2537 int av_uninit(cpl_start);
2540 /* calculate bandwidth based on user-specified cutoff frequency */
2542 fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2543 s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2545 /* use default bandwidth setting */
2546 s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2549 /* set number of coefficients for each channel */
2550 for (ch = 1; ch <= s->fbw_channels; ch++) {
2551 s->start_freq[ch] = 0;
2552 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2553 s->blocks[blk].end_freq[ch] = s->bandwidth_code * 3 + 73;
2555 /* LFE channel always has 7 coefs */
2557 s->start_freq[s->lfe_channel] = 0;
2558 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2559 s->blocks[blk].end_freq[ch] = 7;
2562 /* initialize coupling strategy */
2563 if (s->cpl_enabled) {
2564 if (s->options.cpl_start >= 0) {
2565 cpl_start = s->options.cpl_start;
2567 cpl_start = ac3_coupling_start_tab[s->channel_mode-2][s->bit_alloc.sr_code][s->frame_size_code/2];
2572 if (s->cpl_enabled) {
2573 int i, cpl_start_band, cpl_end_band;
2574 uint8_t *cpl_band_sizes = s->cpl_band_sizes;
2576 cpl_end_band = s->bandwidth_code / 4 + 3;
2577 cpl_start_band = av_clip(cpl_start, 0, FFMIN(cpl_end_band-1, 15));
2579 s->num_cpl_subbands = cpl_end_band - cpl_start_band;
2581 s->num_cpl_bands = 1;
2582 *cpl_band_sizes = 12;
2583 for (i = cpl_start_band + 1; i < cpl_end_band; i++) {
2584 if (ff_eac3_default_cpl_band_struct[i]) {
2585 *cpl_band_sizes += 12;
2589 *cpl_band_sizes = 12;
2593 s->start_freq[CPL_CH] = cpl_start_band * 12 + 37;
2594 s->cpl_end_freq = cpl_end_band * 12 + 37;
2595 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2596 s->blocks[blk].end_freq[CPL_CH] = s->cpl_end_freq;
2601 static av_cold int allocate_buffers(AVCodecContext *avctx)
2604 AC3EncodeContext *s = avctx->priv_data;
2605 int channels = s->channels + 1; /* includes coupling channel */
2607 FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
2609 for (ch = 0; ch < s->channels; ch++) {
2610 FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
2611 (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
2614 FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * channels *
2615 AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
2616 FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * channels *
2617 AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
2618 FF_ALLOCZ_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * channels *
2619 AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
2620 FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * channels *
2621 AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
2622 FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * channels *
2623 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
2624 FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * channels *
2625 AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
2626 FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * channels *
2627 64 * sizeof(*s->band_psd_buffer), alloc_fail);
2628 FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * channels *
2629 64 * sizeof(*s->mask_buffer), alloc_fail);
2630 FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * channels *
2631 AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
2632 if (s->cpl_enabled) {
2633 FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_exp_buffer, AC3_MAX_BLOCKS * channels *
2634 16 * sizeof(*s->cpl_coord_exp_buffer), alloc_fail);
2635 FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_mant_buffer, AC3_MAX_BLOCKS * channels *
2636 16 * sizeof(*s->cpl_coord_mant_buffer), alloc_fail);
2638 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2639 AC3Block *block = &s->blocks[blk];
2640 FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, channels * sizeof(*block->mdct_coef),
2642 FF_ALLOCZ_OR_GOTO(avctx, block->exp, channels * sizeof(*block->exp),
2644 FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, channels * sizeof(*block->grouped_exp),
2646 FF_ALLOCZ_OR_GOTO(avctx, block->psd, channels * sizeof(*block->psd),
2648 FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, channels * sizeof(*block->band_psd),
2650 FF_ALLOCZ_OR_GOTO(avctx, block->mask, channels * sizeof(*block->mask),
2652 FF_ALLOCZ_OR_GOTO(avctx, block->qmant, channels * sizeof(*block->qmant),
2654 if (s->cpl_enabled) {
2655 FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_exp, channels * sizeof(*block->cpl_coord_exp),
2657 FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_mant, channels * sizeof(*block->cpl_coord_mant),
2661 for (ch = 0; ch < channels; ch++) {
2662 /* arrangement: block, channel, coeff */
2663 block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * channels + ch)];
2664 block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
2665 block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * channels + ch)];
2666 block->mask[ch] = &s->mask_buffer [64 * (blk * channels + ch)];
2667 block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
2668 if (s->cpl_enabled) {
2669 block->cpl_coord_exp[ch] = &s->cpl_coord_exp_buffer [16 * (blk * channels + ch)];
2670 block->cpl_coord_mant[ch] = &s->cpl_coord_mant_buffer[16 * (blk * channels + ch)];
2673 /* arrangement: channel, block, coeff */
2674 block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2675 block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2679 if (CONFIG_AC3ENC_FLOAT) {
2680 FF_ALLOCZ_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * channels *
2681 AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
2682 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2683 AC3Block *block = &s->blocks[blk];
2684 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2685 sizeof(*block->fixed_coef), alloc_fail);
2686 for (ch = 0; ch < channels; ch++)
2687 block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2690 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2691 AC3Block *block = &s->blocks[blk];
2692 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2693 sizeof(*block->fixed_coef), alloc_fail);
2694 for (ch = 0; ch < channels; ch++)
2695 block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2701 return AVERROR(ENOMEM);
2706 * Initialize the encoder.
2708 static av_cold int ac3_encode_init(AVCodecContext *avctx)
2710 AC3EncodeContext *s = avctx->priv_data;
2711 int ret, frame_size_58;
2713 s->eac3 = avctx->codec_id == CODEC_ID_EAC3;
2715 avctx->frame_size = AC3_FRAME_SIZE;
2717 ff_ac3_common_init();
2719 ret = validate_options(avctx, s);
2723 s->bitstream_mode = avctx->audio_service_type;
2724 if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2725 s->bitstream_mode = 0x7;
2727 s->bits_written = 0;
2728 s->samples_written = 0;
2730 /* calculate crc_inv for both possible frame sizes */
2731 frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
2732 s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2733 if (s->bit_alloc.sr_code == 1) {
2734 frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2735 s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2744 ret = mdct_init(avctx, &s->mdct, 9);
2748 ret = allocate_buffers(avctx);
2752 avctx->coded_frame= avcodec_alloc_frame();
2754 dsputil_init(&s->dsp, avctx);
2755 ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2757 dprint_options(avctx);
2761 ac3_encode_close(avctx);