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.
30 //#define ASSERT_LEVEL 2
34 #include "libavutil/audioconvert.h"
35 #include "libavutil/avassert.h"
36 #include "libavutil/crc.h"
37 #include "libavutil/opt.h"
43 #include "audioconvert.h"
47 #ifndef CONFIG_AC3ENC_FLOAT
48 #define CONFIG_AC3ENC_FLOAT 0
52 /** Maximum number of exponent groups. +1 for separate DC exponent. */
53 #define AC3_MAX_EXP_GROUPS 85
55 #if CONFIG_AC3ENC_FLOAT
56 #define MAC_COEF(d,a,b) ((d)+=(a)*(b))
57 typedef float SampleType;
58 typedef float CoefType;
59 typedef float CoefSumType;
61 #define MAC_COEF(d,a,b) MAC64(d,a,b)
62 typedef int16_t SampleType;
63 typedef int32_t CoefType;
64 typedef int64_t CoefSumType;
67 typedef struct AC3MDCTContext {
68 const SampleType *window; ///< MDCT window function
69 FFTContext fft; ///< FFT context for MDCT calculation
73 * Data for a single audio block.
75 typedef struct AC3Block {
76 uint8_t **bap; ///< bit allocation pointers (bap)
77 CoefType **mdct_coef; ///< MDCT coefficients
78 int32_t **fixed_coef; ///< fixed-point MDCT coefficients
79 uint8_t **exp; ///< original exponents
80 uint8_t **grouped_exp; ///< grouped exponents
81 int16_t **psd; ///< psd per frequency bin
82 int16_t **band_psd; ///< psd per critical band
83 int16_t **mask; ///< masking curve
84 uint16_t **qmant; ///< quantized mantissas
85 uint8_t coeff_shift[AC3_MAX_CHANNELS]; ///< fixed-point coefficient shift values
86 uint8_t new_rematrixing_strategy; ///< send new rematrixing flags in this block
87 uint8_t rematrixing_flags[4]; ///< rematrixing flags
88 struct AC3Block *exp_ref_block[AC3_MAX_CHANNELS]; ///< reference blocks for EXP_REUSE
92 * AC-3 encoder private context.
94 typedef struct AC3EncodeContext {
95 AVClass *av_class; ///< AVClass used for AVOption
96 AC3EncOptions options; ///< encoding options
97 PutBitContext pb; ///< bitstream writer context
99 AC3DSPContext ac3dsp; ///< AC-3 optimized functions
100 AC3MDCTContext mdct; ///< MDCT context
102 AC3Block blocks[AC3_MAX_BLOCKS]; ///< per-block info
104 int bitstream_id; ///< bitstream id (bsid)
105 int bitstream_mode; ///< bitstream mode (bsmod)
107 int bit_rate; ///< target bit rate, in bits-per-second
108 int sample_rate; ///< sampling frequency, in Hz
110 int frame_size_min; ///< minimum frame size in case rounding is necessary
111 int frame_size; ///< current frame size in bytes
112 int frame_size_code; ///< frame size code (frmsizecod)
114 int bits_written; ///< bit count (used to avg. bitrate)
115 int samples_written; ///< sample count (used to avg. bitrate)
117 int fbw_channels; ///< number of full-bandwidth channels (nfchans)
118 int channels; ///< total number of channels (nchans)
119 int lfe_on; ///< indicates if there is an LFE channel (lfeon)
120 int lfe_channel; ///< channel index of the LFE channel
121 int has_center; ///< indicates if there is a center channel
122 int has_surround; ///< indicates if there are one or more surround channels
123 int channel_mode; ///< channel mode (acmod)
124 const uint8_t *channel_map; ///< channel map used to reorder channels
126 int center_mix_level; ///< center mix level code
127 int surround_mix_level; ///< surround mix level code
128 int ltrt_center_mix_level; ///< Lt/Rt center mix level code
129 int ltrt_surround_mix_level; ///< Lt/Rt surround mix level code
130 int loro_center_mix_level; ///< Lo/Ro center mix level code
131 int loro_surround_mix_level; ///< Lo/Ro surround mix level code
133 int cutoff; ///< user-specified cutoff frequency, in Hz
134 int bandwidth_code; ///< bandwidth code (0 to 60) (chbwcod)
135 int nb_coefs[AC3_MAX_CHANNELS];
137 int rematrixing_enabled; ///< stereo rematrixing enabled
138 int num_rematrixing_bands; ///< number of rematrixing bands
140 /* bitrate allocation control */
141 int slow_gain_code; ///< slow gain code (sgaincod)
142 int slow_decay_code; ///< slow decay code (sdcycod)
143 int fast_decay_code; ///< fast decay code (fdcycod)
144 int db_per_bit_code; ///< dB/bit code (dbpbcod)
145 int floor_code; ///< floor code (floorcod)
146 AC3BitAllocParameters bit_alloc; ///< bit allocation parameters
147 int coarse_snr_offset; ///< coarse SNR offsets (csnroffst)
148 int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signal-to-mask ratio) (fgaincod)
149 int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst)
150 int frame_bits_fixed; ///< number of non-coefficient bits for fixed parameters
151 int frame_bits; ///< all frame bits except exponents and mantissas
152 int exponent_bits; ///< number of bits used for exponents
154 SampleType **planar_samples;
156 uint8_t *bap1_buffer;
157 CoefType *mdct_coef_buffer;
158 int32_t *fixed_coef_buffer;
160 uint8_t *grouped_exp_buffer;
162 int16_t *band_psd_buffer;
163 int16_t *mask_buffer;
164 uint16_t *qmant_buffer;
166 uint8_t exp_strategy[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< exponent strategies
168 DECLARE_ALIGNED(32, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
171 typedef struct AC3Mant {
172 uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
173 int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
176 #define CMIXLEV_NUM_OPTIONS 3
177 static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
178 LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
181 #define SURMIXLEV_NUM_OPTIONS 3
182 static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
183 LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
186 #define EXTMIXLEV_NUM_OPTIONS 8
187 static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
188 LEVEL_PLUS_3DB, LEVEL_PLUS_1POINT5DB, LEVEL_ONE, LEVEL_MINUS_4POINT5DB,
189 LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
193 #define OFFSET(param) offsetof(AC3EncodeContext, options.param)
194 #define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
196 #if CONFIG_AC3ENC_FLOAT || !CONFIG_AC3_FLOAT_ENCODER //we need this exactly once compiled in
197 const AVOption ff_ac3_options[] = {
198 /* Metadata Options */
199 {"per_frame_metadata", "Allow Changing Metadata Per-Frame", OFFSET(allow_per_frame_metadata), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 1, AC3ENC_PARAM},
201 {"center_mixlev", "Center Mix Level", OFFSET(center_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = LEVEL_MINUS_4POINT5DB }, 0.0, 1.0, AC3ENC_PARAM},
202 {"surround_mixlev", "Surround Mix Level", OFFSET(surround_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = LEVEL_MINUS_6DB }, 0.0, 1.0, AC3ENC_PARAM},
203 /* audio production information */
204 {"mixing_level", "Mixing Level", OFFSET(mixing_level), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 111, AC3ENC_PARAM},
205 {"room_type", "Room Type", OFFSET(room_type), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "room_type"},
206 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
207 {"large", "Large Room", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
208 {"small", "Small Room", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
209 /* other metadata options */
210 {"copyright", "Copyright Bit", OFFSET(copyright), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 1, AC3ENC_PARAM},
211 {"dialnorm", "Dialogue Level (dB)", OFFSET(dialogue_level), FF_OPT_TYPE_INT, {.dbl = -31 }, -31, -1, AC3ENC_PARAM},
212 {"dsur_mode", "Dolby Surround Mode", OFFSET(dolby_surround_mode), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 2, AC3ENC_PARAM, "dsur_mode"},
213 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
214 {"on", "Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
215 {"off", "Not Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
216 {"original", "Original Bit Stream", OFFSET(original), FF_OPT_TYPE_INT, {.dbl = 1 }, 0, 1, AC3ENC_PARAM},
217 /* extended bitstream information */
218 {"dmix_mode", "Preferred Stereo Downmix Mode", OFFSET(preferred_stereo_downmix), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dmix_mode"},
219 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
220 {"ltrt", "Lt/Rt Downmix Preferred", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
221 {"loro", "Lo/Ro Downmix Preferred", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
222 {"ltrt_cmixlev", "Lt/Rt Center Mix Level", OFFSET(ltrt_center_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
223 {"ltrt_surmixlev", "Lt/Rt Surround Mix Level", OFFSET(ltrt_surround_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
224 {"loro_cmixlev", "Lo/Ro Center Mix Level", OFFSET(loro_center_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
225 {"loro_surmixlev", "Lo/Ro Surround Mix Level", OFFSET(loro_surround_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
226 {"dsurex_mode", "Dolby Surround EX Mode", OFFSET(dolby_surround_ex_mode), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dsurex_mode"},
227 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
228 {"on", "Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
229 {"off", "Not Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
230 {"dheadphone_mode", "Dolby Headphone Mode", OFFSET(dolby_headphone_mode), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dheadphone_mode"},
231 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
232 {"on", "Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
233 {"off", "Not Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
234 {"ad_conv_type", "A/D Converter Type", OFFSET(ad_converter_type), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 1, AC3ENC_PARAM, "ad_conv_type"},
235 {"standard", "Standard (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
236 {"hdcd", "HDCD", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
237 /* Other Encoding Options */
238 {"stereo_rematrixing", "Stereo Rematrixing", OFFSET(stereo_rematrixing), FF_OPT_TYPE_INT, {.dbl = 1 }, 0, 1, AC3ENC_PARAM},
243 #if CONFIG_AC3ENC_FLOAT
244 static AVClass ac3enc_class = { "AC-3 Encoder", av_default_item_name,
245 ff_ac3_options, LIBAVUTIL_VERSION_INT };
247 static AVClass ac3enc_class = { "Fixed-Point AC-3 Encoder", av_default_item_name,
248 ff_ac3_options, LIBAVUTIL_VERSION_INT };
252 /* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
254 static av_cold void mdct_end(AC3MDCTContext *mdct);
256 static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
259 static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
260 const SampleType *window, unsigned int len);
262 static int normalize_samples(AC3EncodeContext *s);
264 static void scale_coefficients(AC3EncodeContext *s);
268 * LUT for number of exponent groups.
269 * exponent_group_tab[exponent strategy-1][number of coefficients]
271 static uint8_t exponent_group_tab[3][256];
275 * List of supported channel layouts.
277 #if CONFIG_AC3ENC_FLOAT || !CONFIG_AC3_FLOAT_ENCODER //we need this exactly once compiled in
278 const int64_t ff_ac3_channel_layouts[] = {
282 AV_CH_LAYOUT_SURROUND,
285 AV_CH_LAYOUT_4POINT0,
286 AV_CH_LAYOUT_5POINT0,
287 AV_CH_LAYOUT_5POINT0_BACK,
288 (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
289 (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
290 (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
291 (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
292 (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
293 (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
294 (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
295 AV_CH_LAYOUT_5POINT1,
296 AV_CH_LAYOUT_5POINT1_BACK,
303 * LUT to select the bandwidth code based on the bit rate, sample rate, and
304 * number of full-bandwidth channels.
305 * bandwidth_tab[fbw_channels-1][sample rate code][bit rate code]
307 static const uint8_t ac3_bandwidth_tab[5][3][19] = {
308 // 32 40 48 56 64 80 96 112 128 160 192 224 256 320 384 448 512 576 640
310 { { 0, 0, 0, 12, 16, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
311 { 0, 0, 0, 16, 20, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
312 { 0, 0, 0, 32, 40, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
314 { { 0, 0, 0, 0, 0, 0, 0, 20, 24, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
315 { 0, 0, 0, 0, 0, 0, 4, 24, 28, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
316 { 0, 0, 0, 0, 0, 0, 20, 44, 52, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
318 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 24, 32, 40, 48, 48, 48, 48, 48, 48 },
319 { 0, 0, 0, 0, 0, 0, 0, 0, 4, 20, 28, 36, 44, 56, 56, 56, 56, 56, 56 },
320 { 0, 0, 0, 0, 0, 0, 0, 0, 20, 40, 48, 60, 60, 60, 60, 60, 60, 60, 60 } },
322 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 32, 48, 48, 48, 48, 48, 48 },
323 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 28, 36, 56, 56, 56, 56, 56, 56 },
324 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 48, 60, 60, 60, 60, 60, 60, 60 } },
326 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 20, 32, 40, 48, 48, 48, 48 },
327 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 36, 44, 56, 56, 56, 56 },
328 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 44, 60, 60, 60, 60, 60, 60 } }
333 * Adjust the frame size to make the average bit rate match the target bit rate.
334 * This is only needed for 11025, 22050, and 44100 sample rates.
336 static void adjust_frame_size(AC3EncodeContext *s)
338 while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
339 s->bits_written -= s->bit_rate;
340 s->samples_written -= s->sample_rate;
342 s->frame_size = s->frame_size_min +
343 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
344 s->bits_written += s->frame_size * 8;
345 s->samples_written += AC3_FRAME_SIZE;
350 * Deinterleave input samples.
351 * Channels are reordered from FFmpeg's default order to AC-3 order.
353 static void deinterleave_input_samples(AC3EncodeContext *s,
354 const SampleType *samples)
358 /* deinterleave and remap input samples */
359 for (ch = 0; ch < s->channels; ch++) {
360 const SampleType *sptr;
363 /* copy last 256 samples of previous frame to the start of the current frame */
364 memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
365 AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
369 sptr = samples + s->channel_map[ch];
370 for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
371 s->planar_samples[ch][i] = *sptr;
379 * Apply the MDCT to input samples to generate frequency coefficients.
380 * This applies the KBD window and normalizes the input to reduce precision
381 * loss due to fixed-point calculations.
383 static void apply_mdct(AC3EncodeContext *s)
387 for (ch = 0; ch < s->channels; ch++) {
388 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
389 AC3Block *block = &s->blocks[blk];
390 const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
392 apply_window(&s->dsp, s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
394 block->coeff_shift[ch] = normalize_samples(s);
396 s->mdct.fft.mdct_calcw(&s->mdct.fft, block->mdct_coef[ch],
397 s->windowed_samples);
404 * Determine rematrixing flags for each block and band.
406 static void compute_rematrixing_strategy(AC3EncodeContext *s)
410 AC3Block *block, *block0;
412 if (s->channel_mode != AC3_CHMODE_STEREO)
415 s->num_rematrixing_bands = 4;
417 nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
419 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
420 block = &s->blocks[blk];
421 block->new_rematrixing_strategy = !blk;
422 if (!s->rematrixing_enabled)
424 for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
425 /* calculate calculate sum of squared coeffs for one band in one block */
426 int start = ff_ac3_rematrix_band_tab[bnd];
427 int end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
428 CoefSumType sum[4] = {0,};
429 for (i = start; i < end; i++) {
430 CoefType lt = block->mdct_coef[0][i];
431 CoefType rt = block->mdct_coef[1][i];
432 CoefType md = lt + rt;
433 CoefType sd = lt - rt;
434 MAC_COEF(sum[0], lt, lt);
435 MAC_COEF(sum[1], rt, rt);
436 MAC_COEF(sum[2], md, md);
437 MAC_COEF(sum[3], sd, sd);
440 /* compare sums to determine if rematrixing will be used for this band */
441 if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
442 block->rematrixing_flags[bnd] = 1;
444 block->rematrixing_flags[bnd] = 0;
446 /* determine if new rematrixing flags will be sent */
448 block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
449 block->new_rematrixing_strategy = 1;
458 * Apply stereo rematrixing to coefficients based on rematrixing flags.
460 static void apply_rematrixing(AC3EncodeContext *s)
467 if (!s->rematrixing_enabled)
470 nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
472 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
473 AC3Block *block = &s->blocks[blk];
474 if (block->new_rematrixing_strategy)
475 flags = block->rematrixing_flags;
476 for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
478 start = ff_ac3_rematrix_band_tab[bnd];
479 end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
480 for (i = start; i < end; i++) {
481 int32_t lt = block->fixed_coef[0][i];
482 int32_t rt = block->fixed_coef[1][i];
483 block->fixed_coef[0][i] = (lt + rt) >> 1;
484 block->fixed_coef[1][i] = (lt - rt) >> 1;
493 * Initialize exponent tables.
495 static av_cold void exponent_init(AC3EncodeContext *s)
497 int expstr, i, grpsize;
499 for (expstr = EXP_D15-1; expstr <= EXP_D45-1; expstr++) {
500 grpsize = 3 << expstr;
501 for (i = 73; i < 256; i++) {
502 exponent_group_tab[expstr][i] = (i + grpsize - 4) / grpsize;
506 exponent_group_tab[0][7] = 2;
511 * Extract exponents from the MDCT coefficients.
512 * This takes into account the normalization that was done to the input samples
513 * by adjusting the exponents by the exponent shift values.
515 static void extract_exponents(AC3EncodeContext *s)
519 for (ch = 0; ch < s->channels; ch++) {
520 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
521 AC3Block *block = &s->blocks[blk];
522 s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch],
530 * Exponent Difference Threshold.
531 * New exponents are sent if their SAD exceed this number.
533 #define EXP_DIFF_THRESHOLD 500
537 * Calculate exponent strategies for all channels.
538 * Array arrangement is reversed to simplify the per-channel calculation.
540 static void compute_exp_strategy(AC3EncodeContext *s)
544 for (ch = 0; ch < s->fbw_channels; ch++) {
545 uint8_t *exp_strategy = s->exp_strategy[ch];
546 uint8_t *exp = s->blocks[0].exp[ch];
549 /* estimate if the exponent variation & decide if they should be
550 reused in the next frame */
551 exp_strategy[0] = EXP_NEW;
552 exp += AC3_MAX_COEFS;
553 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
554 exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
555 if (exp_diff > EXP_DIFF_THRESHOLD)
556 exp_strategy[blk] = EXP_NEW;
558 exp_strategy[blk] = EXP_REUSE;
559 exp += AC3_MAX_COEFS;
562 /* now select the encoding strategy type : if exponents are often
563 recoded, we use a coarse encoding */
565 while (blk < AC3_MAX_BLOCKS) {
567 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
569 switch (blk1 - blk) {
570 case 1: exp_strategy[blk] = EXP_D45; break;
572 case 3: exp_strategy[blk] = EXP_D25; break;
573 default: exp_strategy[blk] = EXP_D15; break;
580 s->exp_strategy[ch][0] = EXP_D15;
581 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
582 s->exp_strategy[ch][blk] = EXP_REUSE;
588 * Update the exponents so that they are the ones the decoder will decode.
590 static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy)
594 nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
596 /* for each group, compute the minimum exponent */
597 switch(exp_strategy) {
599 for (i = 1, k = 1; i <= nb_groups; i++) {
600 uint8_t exp_min = exp[k];
601 if (exp[k+1] < exp_min)
608 for (i = 1, k = 1; i <= nb_groups; i++) {
609 uint8_t exp_min = exp[k];
610 if (exp[k+1] < exp_min)
612 if (exp[k+2] < exp_min)
614 if (exp[k+3] < exp_min)
622 /* constraint for DC exponent */
626 /* decrease the delta between each groups to within 2 so that they can be
627 differentially encoded */
628 for (i = 1; i <= nb_groups; i++)
629 exp[i] = FFMIN(exp[i], exp[i-1] + 2);
632 exp[i] = FFMIN(exp[i], exp[i+1] + 2);
634 /* now we have the exponent values the decoder will see */
635 switch (exp_strategy) {
637 for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
638 uint8_t exp1 = exp[i];
644 for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
645 exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
654 * Encode exponents from original extracted form to what the decoder will see.
655 * This copies and groups exponents based on exponent strategy and reduces
656 * deltas between adjacent exponent groups so that they can be differentially
659 static void encode_exponents(AC3EncodeContext *s)
662 uint8_t *exp, *exp_strategy;
663 int nb_coefs, num_reuse_blocks;
665 for (ch = 0; ch < s->channels; ch++) {
666 exp = s->blocks[0].exp[ch];
667 exp_strategy = s->exp_strategy[ch];
668 nb_coefs = s->nb_coefs[ch];
671 while (blk < AC3_MAX_BLOCKS) {
674 /* count the number of EXP_REUSE blocks after the current block
675 and set exponent reference block pointers */
676 s->blocks[blk].exp_ref_block[ch] = &s->blocks[blk];
677 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
678 s->blocks[blk1].exp_ref_block[ch] = &s->blocks[blk];
681 num_reuse_blocks = blk1 - blk - 1;
683 /* for the EXP_REUSE case we select the min of the exponents */
684 s->ac3dsp.ac3_exponent_min(exp, num_reuse_blocks, nb_coefs);
686 encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk]);
688 exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
697 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
698 * varies depending on exponent strategy and bandwidth.
700 static void group_exponents(AC3EncodeContext *s)
703 int group_size, nb_groups, bit_count;
705 int delta0, delta1, delta2;
709 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
710 AC3Block *block = &s->blocks[blk];
711 for (ch = 0; ch < s->channels; ch++) {
712 int exp_strategy = s->exp_strategy[ch][blk];
713 if (exp_strategy == EXP_REUSE)
715 group_size = exp_strategy + (exp_strategy == EXP_D45);
716 nb_groups = exponent_group_tab[exp_strategy-1][s->nb_coefs[ch]];
717 bit_count += 4 + (nb_groups * 7);
722 block->grouped_exp[ch][0] = exp1;
724 /* remaining exponents are delta encoded */
725 for (i = 1; i <= nb_groups; i++) {
726 /* merge three delta in one code */
730 delta0 = exp1 - exp0 + 2;
731 av_assert2(delta0 >= 0 && delta0 <= 4);
736 delta1 = exp1 - exp0 + 2;
737 av_assert2(delta1 >= 0 && delta1 <= 4);
742 delta2 = exp1 - exp0 + 2;
743 av_assert2(delta2 >= 0 && delta2 <= 4);
745 block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
750 s->exponent_bits = bit_count;
755 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
756 * Extract exponents from MDCT coefficients, calculate exponent strategies,
757 * and encode final exponents.
759 static void process_exponents(AC3EncodeContext *s)
761 extract_exponents(s);
763 compute_exp_strategy(s);
774 * Count frame bits that are based solely on fixed parameters.
775 * This only has to be run once when the encoder is initialized.
777 static void count_frame_bits_fixed(AC3EncodeContext *s)
779 static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
784 * no dynamic range codes
785 * no channel coupling
786 * bit allocation parameters do not change between blocks
787 * SNR offsets do not change between blocks
788 * no delta bit allocation
795 frame_bits += frame_bits_inc[s->channel_mode];
798 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
799 frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
800 if (s->channel_mode == AC3_CHMODE_STEREO) {
801 frame_bits++; /* rematstr */
803 frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
805 frame_bits++; /* lfeexpstr */
806 frame_bits++; /* baie */
807 frame_bits++; /* snr */
808 frame_bits += 2; /* delta / skip */
810 frame_bits++; /* cplinu for block 0 */
812 /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
814 /* (fsnoffset[4] + fgaincod[4]) * c */
815 frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
817 /* auxdatae, crcrsv */
823 s->frame_bits_fixed = frame_bits;
828 * Initialize bit allocation.
829 * Set default parameter codes and calculate parameter values.
831 static void bit_alloc_init(AC3EncodeContext *s)
835 /* init default parameters */
836 s->slow_decay_code = 2;
837 s->fast_decay_code = 1;
838 s->slow_gain_code = 1;
839 s->db_per_bit_code = 3;
841 for (ch = 0; ch < s->channels; ch++)
842 s->fast_gain_code[ch] = 4;
844 /* initial snr offset */
845 s->coarse_snr_offset = 40;
847 /* compute real values */
848 /* currently none of these values change during encoding, so we can just
849 set them once at initialization */
850 s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
851 s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
852 s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
853 s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
854 s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
856 count_frame_bits_fixed(s);
861 * Count the bits used to encode the frame, minus exponents and mantissas.
862 * Bits based on fixed parameters have already been counted, so now we just
863 * have to add the bits based on parameters that change during encoding.
865 static void count_frame_bits(AC3EncodeContext *s)
867 AC3EncOptions *opt = &s->options;
871 if (opt->audio_production_info)
873 if (s->bitstream_id == 6) {
874 if (opt->extended_bsi_1)
876 if (opt->extended_bsi_2)
880 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
881 /* stereo rematrixing */
882 if (s->channel_mode == AC3_CHMODE_STEREO &&
883 s->blocks[blk].new_rematrixing_strategy) {
884 frame_bits += s->num_rematrixing_bands;
887 for (ch = 0; ch < s->fbw_channels; ch++) {
888 if (s->exp_strategy[ch][blk] != EXP_REUSE)
889 frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
892 s->frame_bits = s->frame_bits_fixed + frame_bits;
897 * Finalize the mantissa bit count by adding in the grouped mantissas.
899 static int compute_mantissa_size_final(int mant_cnt[5])
901 // bap=1 : 3 mantissas in 5 bits
902 int bits = (mant_cnt[1] / 3) * 5;
903 // bap=2 : 3 mantissas in 7 bits
904 // bap=4 : 2 mantissas in 7 bits
905 bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
906 // bap=3 : each mantissa is 3 bits
907 bits += mant_cnt[3] * 3;
913 * Calculate masking curve based on the final exponents.
914 * Also calculate the power spectral densities to use in future calculations.
916 static void bit_alloc_masking(AC3EncodeContext *s)
920 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
921 AC3Block *block = &s->blocks[blk];
922 for (ch = 0; ch < s->channels; ch++) {
923 /* We only need psd and mask for calculating bap.
924 Since we currently do not calculate bap when exponent
925 strategy is EXP_REUSE we do not need to calculate psd or mask. */
926 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
927 ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
929 block->psd[ch], block->band_psd[ch]);
930 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
932 ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
933 ch == s->lfe_channel,
934 DBA_NONE, 0, NULL, NULL, NULL,
943 * Ensure that bap for each block and channel point to the current bap_buffer.
944 * They may have been switched during the bit allocation search.
946 static void reset_block_bap(AC3EncodeContext *s)
949 if (s->blocks[0].bap[0] == s->bap_buffer)
951 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
952 for (ch = 0; ch < s->channels; ch++) {
953 s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
960 * Run the bit allocation with a given SNR offset.
961 * This calculates the bit allocation pointers that will be used to determine
962 * the quantization of each mantissa.
963 * @return the number of bits needed for mantissas if the given SNR offset is
966 static int bit_alloc(AC3EncodeContext *s, int snr_offset)
972 snr_offset = (snr_offset - 240) << 2;
976 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
977 AC3Block *block = &s->blocks[blk];
979 // initialize grouped mantissa counts. these are set so that they are
980 // padded to the next whole group size when bits are counted in
981 // compute_mantissa_size_final
982 mant_cnt[0] = mant_cnt[3] = 0;
983 mant_cnt[1] = mant_cnt[2] = 2;
985 for (ch = 0; ch < s->channels; ch++) {
986 /* Currently the only bit allocation parameters which vary across
987 blocks within a frame are the exponent values. We can take
988 advantage of that by reusing the bit allocation pointers
989 whenever we reuse exponents. */
990 ref_block = block->exp_ref_block[ch];
991 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
992 s->ac3dsp.bit_alloc_calc_bap(ref_block->mask[ch],
993 ref_block->psd[ch], 0,
994 s->nb_coefs[ch], snr_offset,
995 s->bit_alloc.floor, ff_ac3_bap_tab,
998 mantissa_bits += s->ac3dsp.compute_mantissa_size(mant_cnt,
1002 mantissa_bits += compute_mantissa_size_final(mant_cnt);
1004 return mantissa_bits;
1009 * Constant bitrate bit allocation search.
1010 * Find the largest SNR offset that will allow data to fit in the frame.
1012 static int cbr_bit_allocation(AC3EncodeContext *s)
1016 int snr_offset, snr_incr;
1018 bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1020 return AVERROR(EINVAL);
1022 snr_offset = s->coarse_snr_offset << 4;
1024 /* if previous frame SNR offset was 1023, check if current frame can also
1025 use SNR offset of 1023. if so, skip the search. */
1026 if ((snr_offset | s->fine_snr_offset[0]) == 1023) {
1027 if (bit_alloc(s, 1023) <= bits_left)
1031 while (snr_offset >= 0 &&
1032 bit_alloc(s, snr_offset) > bits_left) {
1036 return AVERROR(EINVAL);
1038 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1039 for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1040 while (snr_offset + snr_incr <= 1023 &&
1041 bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1042 snr_offset += snr_incr;
1043 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1046 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1049 s->coarse_snr_offset = snr_offset >> 4;
1050 for (ch = 0; ch < s->channels; ch++)
1051 s->fine_snr_offset[ch] = snr_offset & 0xF;
1058 * Downgrade exponent strategies to reduce the bits used by the exponents.
1059 * This is a fallback for when bit allocation fails with the normal exponent
1060 * strategies. Each time this function is run it only downgrades the
1061 * strategy in 1 channel of 1 block.
1062 * @return non-zero if downgrade was unsuccessful
1064 static int downgrade_exponents(AC3EncodeContext *s)
1068 for (ch = 0; ch < s->fbw_channels; ch++) {
1069 for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1070 if (s->exp_strategy[ch][blk] == EXP_D15) {
1071 s->exp_strategy[ch][blk] = EXP_D25;
1076 for (ch = 0; ch < s->fbw_channels; ch++) {
1077 for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1078 if (s->exp_strategy[ch][blk] == EXP_D25) {
1079 s->exp_strategy[ch][blk] = EXP_D45;
1084 for (ch = 0; ch < s->fbw_channels; ch++) {
1085 /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
1086 the block number > 0 */
1087 for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
1088 if (s->exp_strategy[ch][blk] > EXP_REUSE) {
1089 s->exp_strategy[ch][blk] = EXP_REUSE;
1099 * Perform bit allocation search.
1100 * Finds the SNR offset value that maximizes quality and fits in the specified
1101 * frame size. Output is the SNR offset and a set of bit allocation pointers
1102 * used to quantize the mantissas.
1104 static int compute_bit_allocation(AC3EncodeContext *s)
1108 count_frame_bits(s);
1110 bit_alloc_masking(s);
1112 ret = cbr_bit_allocation(s);
1114 /* fallback 1: downgrade exponents */
1115 if (!downgrade_exponents(s)) {
1116 extract_exponents(s);
1117 encode_exponents(s);
1119 ret = compute_bit_allocation(s);
1123 /* fallbacks were not enough... */
1132 * Symmetric quantization on 'levels' levels.
1134 static inline int sym_quant(int c, int e, int levels)
1136 int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1137 av_assert2(v >= 0 && v < levels);
1143 * Asymmetric quantization on 2^qbits levels.
1145 static inline int asym_quant(int c, int e, int qbits)
1149 lshift = e + qbits - 24;
1156 m = (1 << (qbits-1));
1159 av_assert2(v >= -m);
1160 return v & ((1 << qbits)-1);
1165 * Quantize a set of mantissas for a single channel in a single block.
1167 static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1169 uint8_t *bap, uint16_t *qmant, int n)
1173 for (i = 0; i < n; i++) {
1175 int c = fixed_coef[i];
1183 v = sym_quant(c, e, 3);
1184 switch (s->mant1_cnt) {
1186 s->qmant1_ptr = &qmant[i];
1191 *s->qmant1_ptr += 3 * v;
1196 *s->qmant1_ptr += v;
1203 v = sym_quant(c, e, 5);
1204 switch (s->mant2_cnt) {
1206 s->qmant2_ptr = &qmant[i];
1211 *s->qmant2_ptr += 5 * v;
1216 *s->qmant2_ptr += v;
1223 v = sym_quant(c, e, 7);
1226 v = sym_quant(c, e, 11);
1227 switch (s->mant4_cnt) {
1229 s->qmant4_ptr = &qmant[i];
1234 *s->qmant4_ptr += v;
1241 v = sym_quant(c, e, 15);
1244 v = asym_quant(c, e, 14);
1247 v = asym_quant(c, e, 16);
1250 v = asym_quant(c, e, b - 1);
1259 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1261 static void quantize_mantissas(AC3EncodeContext *s)
1266 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1267 AC3Block *block = &s->blocks[blk];
1268 AC3Block *ref_block;
1271 for (ch = 0; ch < s->channels; ch++) {
1272 ref_block = block->exp_ref_block[ch];
1273 quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1274 ref_block->exp[ch], ref_block->bap[ch],
1275 block->qmant[ch], s->nb_coefs[ch]);
1282 * Write the AC-3 frame header to the output bitstream.
1284 static void output_frame_header(AC3EncodeContext *s)
1286 AC3EncOptions *opt = &s->options;
1288 put_bits(&s->pb, 16, 0x0b77); /* frame header */
1289 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
1290 put_bits(&s->pb, 2, s->bit_alloc.sr_code);
1291 put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1292 put_bits(&s->pb, 5, s->bitstream_id);
1293 put_bits(&s->pb, 3, s->bitstream_mode);
1294 put_bits(&s->pb, 3, s->channel_mode);
1295 if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1296 put_bits(&s->pb, 2, s->center_mix_level);
1297 if (s->channel_mode & 0x04)
1298 put_bits(&s->pb, 2, s->surround_mix_level);
1299 if (s->channel_mode == AC3_CHMODE_STEREO)
1300 put_bits(&s->pb, 2, opt->dolby_surround_mode);
1301 put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1302 put_bits(&s->pb, 5, -opt->dialogue_level);
1303 put_bits(&s->pb, 1, 0); /* no compression control word */
1304 put_bits(&s->pb, 1, 0); /* no lang code */
1305 put_bits(&s->pb, 1, opt->audio_production_info);
1306 if (opt->audio_production_info) {
1307 put_bits(&s->pb, 5, opt->mixing_level - 80);
1308 put_bits(&s->pb, 2, opt->room_type);
1310 put_bits(&s->pb, 1, opt->copyright);
1311 put_bits(&s->pb, 1, opt->original);
1312 if (s->bitstream_id == 6) {
1313 /* alternate bit stream syntax */
1314 put_bits(&s->pb, 1, opt->extended_bsi_1);
1315 if (opt->extended_bsi_1) {
1316 put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1317 put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1318 put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1319 put_bits(&s->pb, 3, s->loro_center_mix_level);
1320 put_bits(&s->pb, 3, s->loro_surround_mix_level);
1322 put_bits(&s->pb, 1, opt->extended_bsi_2);
1323 if (opt->extended_bsi_2) {
1324 put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1325 put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1326 put_bits(&s->pb, 1, opt->ad_converter_type);
1327 put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
1330 put_bits(&s->pb, 1, 0); /* no time code 1 */
1331 put_bits(&s->pb, 1, 0); /* no time code 2 */
1333 put_bits(&s->pb, 1, 0); /* no additional bit stream info */
1338 * Write one audio block to the output bitstream.
1340 static void output_audio_block(AC3EncodeContext *s, int blk)
1342 int ch, i, baie, rbnd;
1343 AC3Block *block = &s->blocks[blk];
1345 /* block switching */
1346 for (ch = 0; ch < s->fbw_channels; ch++)
1347 put_bits(&s->pb, 1, 0);
1350 for (ch = 0; ch < s->fbw_channels; ch++)
1351 put_bits(&s->pb, 1, 1);
1353 /* dynamic range codes */
1354 put_bits(&s->pb, 1, 0);
1356 /* channel coupling */
1358 put_bits(&s->pb, 1, 1); /* coupling strategy present */
1359 put_bits(&s->pb, 1, 0); /* no coupling strategy */
1361 put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1364 /* stereo rematrixing */
1365 if (s->channel_mode == AC3_CHMODE_STEREO) {
1366 put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1367 if (block->new_rematrixing_strategy) {
1368 /* rematrixing flags */
1369 for (rbnd = 0; rbnd < s->num_rematrixing_bands; rbnd++)
1370 put_bits(&s->pb, 1, block->rematrixing_flags[rbnd]);
1374 /* exponent strategy */
1375 for (ch = 0; ch < s->fbw_channels; ch++)
1376 put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1378 put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1381 for (ch = 0; ch < s->fbw_channels; ch++) {
1382 if (s->exp_strategy[ch][blk] != EXP_REUSE)
1383 put_bits(&s->pb, 6, s->bandwidth_code);
1387 for (ch = 0; ch < s->channels; ch++) {
1390 if (s->exp_strategy[ch][blk] == EXP_REUSE)
1394 put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1396 /* exponent groups */
1397 nb_groups = exponent_group_tab[s->exp_strategy[ch][blk]-1][s->nb_coefs[ch]];
1398 for (i = 1; i <= nb_groups; i++)
1399 put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1401 /* gain range info */
1402 if (ch != s->lfe_channel)
1403 put_bits(&s->pb, 2, 0);
1406 /* bit allocation info */
1408 put_bits(&s->pb, 1, baie);
1410 put_bits(&s->pb, 2, s->slow_decay_code);
1411 put_bits(&s->pb, 2, s->fast_decay_code);
1412 put_bits(&s->pb, 2, s->slow_gain_code);
1413 put_bits(&s->pb, 2, s->db_per_bit_code);
1414 put_bits(&s->pb, 3, s->floor_code);
1418 put_bits(&s->pb, 1, baie);
1420 put_bits(&s->pb, 6, s->coarse_snr_offset);
1421 for (ch = 0; ch < s->channels; ch++) {
1422 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1423 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1427 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1428 put_bits(&s->pb, 1, 0); /* no data to skip */
1431 for (ch = 0; ch < s->channels; ch++) {
1433 AC3Block *ref_block = block->exp_ref_block[ch];
1434 for (i = 0; i < s->nb_coefs[ch]; i++) {
1435 q = block->qmant[ch][i];
1436 b = ref_block->bap[ch][i];
1439 case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
1440 case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
1441 case 3: put_bits(&s->pb, 3, q); break;
1442 case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
1443 case 14: put_bits(&s->pb, 14, q); break;
1444 case 15: put_bits(&s->pb, 16, q); break;
1445 default: put_bits(&s->pb, b-1, q); break;
1452 /** CRC-16 Polynomial */
1453 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1456 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1473 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1479 r = mul_poly(r, a, poly);
1480 a = mul_poly(a, a, poly);
1488 * Fill the end of the frame with 0's and compute the two CRCs.
1490 static void output_frame_end(AC3EncodeContext *s)
1492 const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1493 int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1496 frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1498 /* pad the remainder of the frame with zeros */
1499 av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1500 flush_put_bits(&s->pb);
1502 pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1503 av_assert2(pad_bytes >= 0);
1505 memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1508 /* this is not so easy because it is at the beginning of the data... */
1509 crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1510 crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1511 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1512 AV_WB16(frame + 2, crc1);
1515 crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1516 s->frame_size - frame_size_58 - 3);
1517 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1518 /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1519 if (crc2 == 0x770B) {
1520 frame[s->frame_size - 3] ^= 0x1;
1521 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1523 crc2 = av_bswap16(crc2);
1524 AV_WB16(frame + s->frame_size - 2, crc2);
1529 * Write the frame to the output bitstream.
1531 static void output_frame(AC3EncodeContext *s, unsigned char *frame)
1535 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1537 output_frame_header(s);
1539 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1540 output_audio_block(s, blk);
1542 output_frame_end(s);
1546 static void dprint_options(AVCodecContext *avctx)
1549 AC3EncodeContext *s = avctx->priv_data;
1550 AC3EncOptions *opt = &s->options;
1553 switch (s->bitstream_id) {
1554 case 6: strncpy(strbuf, "AC-3 (alt syntax)", 32); break;
1555 case 8: strncpy(strbuf, "AC-3 (standard)", 32); break;
1556 case 9: strncpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
1557 case 10: strncpy(strbuf, "AC-3 (dnet quater-rate", 32); break;
1558 default: snprintf(strbuf, 32, "ERROR");
1560 av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
1561 av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
1562 av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
1563 av_dlog(avctx, "channel_layout: %s\n", strbuf);
1564 av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
1565 av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
1567 av_dlog(avctx, "cutoff: %d\n", s->cutoff);
1569 av_dlog(avctx, "per_frame_metadata: %s\n",
1570 opt->allow_per_frame_metadata?"on":"off");
1572 av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
1573 s->center_mix_level);
1575 av_dlog(avctx, "center_mixlev: {not written}\n");
1576 if (s->has_surround)
1577 av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
1578 s->surround_mix_level);
1580 av_dlog(avctx, "surround_mixlev: {not written}\n");
1581 if (opt->audio_production_info) {
1582 av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
1583 switch (opt->room_type) {
1584 case 0: strncpy(strbuf, "notindicated", 32); break;
1585 case 1: strncpy(strbuf, "large", 32); break;
1586 case 2: strncpy(strbuf, "small", 32); break;
1587 default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
1589 av_dlog(avctx, "room_type: %s\n", strbuf);
1591 av_dlog(avctx, "mixing_level: {not written}\n");
1592 av_dlog(avctx, "room_type: {not written}\n");
1594 av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
1595 av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
1596 if (s->channel_mode == AC3_CHMODE_STEREO) {
1597 switch (opt->dolby_surround_mode) {
1598 case 0: strncpy(strbuf, "notindicated", 32); break;
1599 case 1: strncpy(strbuf, "on", 32); break;
1600 case 2: strncpy(strbuf, "off", 32); break;
1601 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
1603 av_dlog(avctx, "dsur_mode: %s\n", strbuf);
1605 av_dlog(avctx, "dsur_mode: {not written}\n");
1607 av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
1609 if (s->bitstream_id == 6) {
1610 if (opt->extended_bsi_1) {
1611 switch (opt->preferred_stereo_downmix) {
1612 case 0: strncpy(strbuf, "notindicated", 32); break;
1613 case 1: strncpy(strbuf, "ltrt", 32); break;
1614 case 2: strncpy(strbuf, "loro", 32); break;
1615 default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
1617 av_dlog(avctx, "dmix_mode: %s\n", strbuf);
1618 av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
1619 opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
1620 av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
1621 opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
1622 av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
1623 opt->loro_center_mix_level, s->loro_center_mix_level);
1624 av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
1625 opt->loro_surround_mix_level, s->loro_surround_mix_level);
1627 av_dlog(avctx, "extended bitstream info 1: {not written}\n");
1629 if (opt->extended_bsi_2) {
1630 switch (opt->dolby_surround_ex_mode) {
1631 case 0: strncpy(strbuf, "notindicated", 32); break;
1632 case 1: strncpy(strbuf, "on", 32); break;
1633 case 2: strncpy(strbuf, "off", 32); break;
1634 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
1636 av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
1637 switch (opt->dolby_headphone_mode) {
1638 case 0: strncpy(strbuf, "notindicated", 32); break;
1639 case 1: strncpy(strbuf, "on", 32); break;
1640 case 2: strncpy(strbuf, "off", 32); break;
1641 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
1643 av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
1645 switch (opt->ad_converter_type) {
1646 case 0: strncpy(strbuf, "standard", 32); break;
1647 case 1: strncpy(strbuf, "hdcd", 32); break;
1648 default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
1650 av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
1652 av_dlog(avctx, "extended bitstream info 2: {not written}\n");
1659 #define FLT_OPTION_THRESHOLD 0.01
1661 static int validate_float_option(float v, const float *v_list, int v_list_size)
1665 for (i = 0; i < v_list_size; i++) {
1666 if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
1667 v > (v_list[i] - FLT_OPTION_THRESHOLD))
1670 if (i == v_list_size)
1677 static void validate_mix_level(void *log_ctx, const char *opt_name,
1678 float *opt_param, const float *list,
1679 int list_size, int default_value, int min_value,
1682 int mixlev = validate_float_option(*opt_param, list, list_size);
1683 if (mixlev < min_value) {
1684 mixlev = default_value;
1685 if (*opt_param >= 0.0) {
1686 av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
1687 "default value: %0.3f\n", opt_name, list[mixlev]);
1690 *opt_param = list[mixlev];
1691 *ctx_param = mixlev;
1696 * Validate metadata options as set by AVOption system.
1697 * These values can optionally be changed per-frame.
1699 static int validate_metadata(AVCodecContext *avctx)
1701 AC3EncodeContext *s = avctx->priv_data;
1702 AC3EncOptions *opt = &s->options;
1704 /* validate mixing levels */
1705 if (s->has_center) {
1706 validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
1707 cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
1708 &s->center_mix_level);
1710 if (s->has_surround) {
1711 validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
1712 surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
1713 &s->surround_mix_level);
1716 /* set audio production info flag */
1717 if (opt->mixing_level >= 0 || opt->room_type >= 0) {
1718 if (opt->mixing_level < 0) {
1719 av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
1720 "room_type is set\n");
1721 return AVERROR(EINVAL);
1723 if (opt->mixing_level < 80) {
1724 av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
1725 "80dB and 111dB\n");
1726 return AVERROR(EINVAL);
1728 /* default room type */
1729 if (opt->room_type < 0)
1731 opt->audio_production_info = 1;
1733 opt->audio_production_info = 0;
1736 /* set extended bsi 1 flag */
1737 if ((s->has_center || s->has_surround) &&
1738 (opt->preferred_stereo_downmix >= 0 ||
1739 opt->ltrt_center_mix_level >= 0 ||
1740 opt->ltrt_surround_mix_level >= 0 ||
1741 opt->loro_center_mix_level >= 0 ||
1742 opt->loro_surround_mix_level >= 0)) {
1743 /* default preferred stereo downmix */
1744 if (opt->preferred_stereo_downmix < 0)
1745 opt->preferred_stereo_downmix = 0;
1746 /* validate Lt/Rt center mix level */
1747 validate_mix_level(avctx, "ltrt_center_mix_level",
1748 &opt->ltrt_center_mix_level, extmixlev_options,
1749 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1750 &s->ltrt_center_mix_level);
1751 /* validate Lt/Rt surround mix level */
1752 validate_mix_level(avctx, "ltrt_surround_mix_level",
1753 &opt->ltrt_surround_mix_level, extmixlev_options,
1754 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1755 &s->ltrt_surround_mix_level);
1756 /* validate Lo/Ro center mix level */
1757 validate_mix_level(avctx, "loro_center_mix_level",
1758 &opt->loro_center_mix_level, extmixlev_options,
1759 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1760 &s->loro_center_mix_level);
1761 /* validate Lo/Ro surround mix level */
1762 validate_mix_level(avctx, "loro_surround_mix_level",
1763 &opt->loro_surround_mix_level, extmixlev_options,
1764 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1765 &s->loro_surround_mix_level);
1766 opt->extended_bsi_1 = 1;
1768 opt->extended_bsi_1 = 0;
1771 /* set extended bsi 2 flag */
1772 if (opt->dolby_surround_ex_mode >= 0 ||
1773 opt->dolby_headphone_mode >= 0 ||
1774 opt->ad_converter_type >= 0) {
1775 /* default dolby surround ex mode */
1776 if (opt->dolby_surround_ex_mode < 0)
1777 opt->dolby_surround_ex_mode = 0;
1778 /* default dolby headphone mode */
1779 if (opt->dolby_headphone_mode < 0)
1780 opt->dolby_headphone_mode = 0;
1781 /* default A/D converter type */
1782 if (opt->ad_converter_type < 0)
1783 opt->ad_converter_type = 0;
1784 opt->extended_bsi_2 = 1;
1786 opt->extended_bsi_2 = 0;
1789 /* set bitstream id for alternate bitstream syntax */
1790 if (opt->extended_bsi_1 || opt->extended_bsi_2) {
1791 if (s->bitstream_id > 8 && s->bitstream_id < 11) {
1792 static int warn_once = 1;
1794 av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
1795 "not compatible with reduced samplerates. writing of "
1796 "extended bitstream information will be disabled.\n");
1800 s->bitstream_id = 6;
1809 * Encode a single AC-3 frame.
1811 static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
1812 int buf_size, void *data)
1814 AC3EncodeContext *s = avctx->priv_data;
1815 const SampleType *samples = data;
1818 if (s->options.allow_per_frame_metadata) {
1819 ret = validate_metadata(avctx);
1824 if (s->bit_alloc.sr_code == 1)
1825 adjust_frame_size(s);
1827 deinterleave_input_samples(s, samples);
1831 scale_coefficients(s);
1833 compute_rematrixing_strategy(s);
1835 apply_rematrixing(s);
1837 process_exponents(s);
1839 ret = compute_bit_allocation(s);
1841 av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1845 quantize_mantissas(s);
1847 output_frame(s, frame);
1849 return s->frame_size;
1854 * Finalize encoding and free any memory allocated by the encoder.
1856 static av_cold int ac3_encode_close(AVCodecContext *avctx)
1859 AC3EncodeContext *s = avctx->priv_data;
1861 for (ch = 0; ch < s->channels; ch++)
1862 av_freep(&s->planar_samples[ch]);
1863 av_freep(&s->planar_samples);
1864 av_freep(&s->bap_buffer);
1865 av_freep(&s->bap1_buffer);
1866 av_freep(&s->mdct_coef_buffer);
1867 av_freep(&s->fixed_coef_buffer);
1868 av_freep(&s->exp_buffer);
1869 av_freep(&s->grouped_exp_buffer);
1870 av_freep(&s->psd_buffer);
1871 av_freep(&s->band_psd_buffer);
1872 av_freep(&s->mask_buffer);
1873 av_freep(&s->qmant_buffer);
1874 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1875 AC3Block *block = &s->blocks[blk];
1876 av_freep(&block->bap);
1877 av_freep(&block->mdct_coef);
1878 av_freep(&block->fixed_coef);
1879 av_freep(&block->exp);
1880 av_freep(&block->grouped_exp);
1881 av_freep(&block->psd);
1882 av_freep(&block->band_psd);
1883 av_freep(&block->mask);
1884 av_freep(&block->qmant);
1889 av_freep(&avctx->coded_frame);
1895 * Set channel information during initialization.
1897 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1898 int64_t *channel_layout)
1902 if (channels < 1 || channels > AC3_MAX_CHANNELS)
1903 return AVERROR(EINVAL);
1904 if ((uint64_t)*channel_layout > 0x7FF)
1905 return AVERROR(EINVAL);
1906 ch_layout = *channel_layout;
1908 ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1910 s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1911 s->channels = channels;
1912 s->fbw_channels = channels - s->lfe_on;
1913 s->lfe_channel = s->lfe_on ? s->fbw_channels : -1;
1915 ch_layout -= AV_CH_LOW_FREQUENCY;
1917 switch (ch_layout) {
1918 case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
1919 case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
1920 case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
1921 case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
1922 case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
1923 case AV_CH_LAYOUT_QUAD:
1924 case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
1925 case AV_CH_LAYOUT_5POINT0:
1926 case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
1928 return AVERROR(EINVAL);
1930 s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
1931 s->has_surround = s->channel_mode & 0x04;
1933 s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1934 *channel_layout = ch_layout;
1936 *channel_layout |= AV_CH_LOW_FREQUENCY;
1942 static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1946 /* validate channel layout */
1947 if (!avctx->channel_layout) {
1948 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1949 "encoder will guess the layout, but it "
1950 "might be incorrect.\n");
1952 ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1954 av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1958 /* validate sample rate */
1959 for (i = 0; i < 9; i++) {
1960 if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
1964 av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1965 return AVERROR(EINVAL);
1967 s->sample_rate = avctx->sample_rate;
1968 s->bit_alloc.sr_shift = i % 3;
1969 s->bit_alloc.sr_code = i / 3;
1970 s->bitstream_id = 8 + s->bit_alloc.sr_shift;
1972 /* validate bit rate */
1973 for (i = 0; i < 19; i++) {
1974 if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
1978 av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
1979 return AVERROR(EINVAL);
1981 s->bit_rate = avctx->bit_rate;
1982 s->frame_size_code = i << 1;
1984 /* validate cutoff */
1985 if (avctx->cutoff < 0) {
1986 av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
1987 return AVERROR(EINVAL);
1989 s->cutoff = avctx->cutoff;
1990 if (s->cutoff > (s->sample_rate >> 1))
1991 s->cutoff = s->sample_rate >> 1;
1993 /* validate audio service type / channels combination */
1994 if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
1995 avctx->channels == 1) ||
1996 ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
1997 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
1998 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
1999 && avctx->channels > 1)) {
2000 av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
2001 "specified number of channels\n");
2002 return AVERROR(EINVAL);
2005 ret = validate_metadata(avctx);
2009 s->rematrixing_enabled = s->options.stereo_rematrixing &&
2010 (s->channel_mode == AC3_CHMODE_STEREO);
2017 * Set bandwidth for all channels.
2018 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2019 * default value will be used.
2021 static av_cold void set_bandwidth(AC3EncodeContext *s)
2026 /* calculate bandwidth based on user-specified cutoff frequency */
2028 fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2029 s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2031 /* use default bandwidth setting */
2032 s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2035 /* set number of coefficients for each channel */
2036 for (ch = 0; ch < s->fbw_channels; ch++) {
2037 s->nb_coefs[ch] = s->bandwidth_code * 3 + 73;
2040 s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
2044 static av_cold int allocate_buffers(AVCodecContext *avctx)
2047 AC3EncodeContext *s = avctx->priv_data;
2049 FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
2051 for (ch = 0; ch < s->channels; ch++) {
2052 FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
2053 (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
2056 FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * s->channels *
2057 AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
2058 FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
2059 AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
2060 FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
2061 AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
2062 FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
2063 AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
2064 FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
2065 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
2066 FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
2067 AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
2068 FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
2069 64 * sizeof(*s->band_psd_buffer), alloc_fail);
2070 FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
2071 64 * sizeof(*s->mask_buffer), alloc_fail);
2072 FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
2073 AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
2074 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2075 AC3Block *block = &s->blocks[blk];
2076 FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
2078 FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
2080 FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
2082 FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
2084 FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
2086 FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
2088 FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
2090 FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
2093 for (ch = 0; ch < s->channels; ch++) {
2094 /* arrangement: block, channel, coeff */
2095 block->bap[ch] = &s->bap_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2096 block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2097 block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * s->channels + ch)];
2098 block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2099 block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * s->channels + ch)];
2100 block->mask[ch] = &s->mask_buffer [64 * (blk * s->channels + ch)];
2101 block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2103 /* arrangement: channel, block, coeff */
2104 block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2108 if (CONFIG_AC3ENC_FLOAT) {
2109 FF_ALLOC_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * s->channels *
2110 AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
2111 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2112 AC3Block *block = &s->blocks[blk];
2113 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2114 sizeof(*block->fixed_coef), alloc_fail);
2115 for (ch = 0; ch < s->channels; ch++)
2116 block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
2119 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2120 AC3Block *block = &s->blocks[blk];
2121 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2122 sizeof(*block->fixed_coef), alloc_fail);
2123 for (ch = 0; ch < s->channels; ch++)
2124 block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2130 return AVERROR(ENOMEM);
2135 * Initialize the encoder.
2137 static av_cold int ac3_encode_init(AVCodecContext *avctx)
2139 AC3EncodeContext *s = avctx->priv_data;
2140 int ret, frame_size_58;
2142 avctx->frame_size = AC3_FRAME_SIZE;
2144 ff_ac3_common_init();
2146 ret = validate_options(avctx, s);
2150 s->bitstream_mode = avctx->audio_service_type;
2151 if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2152 s->bitstream_mode = 0x7;
2154 s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2155 s->bits_written = 0;
2156 s->samples_written = 0;
2157 s->frame_size = s->frame_size_min;
2159 /* calculate crc_inv for both possible frame sizes */
2160 frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
2161 s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2162 if (s->bit_alloc.sr_code == 1) {
2163 frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2164 s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2173 ret = mdct_init(avctx, &s->mdct, 9);
2177 ret = allocate_buffers(avctx);
2181 avctx->coded_frame= avcodec_alloc_frame();
2183 dsputil_init(&s->dsp, avctx);
2184 ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2186 dprint_options(avctx);
2190 ac3_encode_close(avctx);