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 /* stereo rematrixing algorithms */
56 #define AC3_REMATRIXING_IS_STATIC 0x1
57 #define AC3_REMATRIXING_SUMS 0
58 #define AC3_REMATRIXING_NONE 1
59 #define AC3_REMATRIXING_ALWAYS 3
61 #if CONFIG_AC3ENC_FLOAT
62 #define MAC_COEF(d,a,b) ((d)+=(a)*(b))
63 typedef float SampleType;
64 typedef float CoefType;
65 typedef float CoefSumType;
67 #define MAC_COEF(d,a,b) MAC64(d,a,b)
68 typedef int16_t SampleType;
69 typedef int32_t CoefType;
70 typedef int64_t CoefSumType;
73 typedef struct AC3MDCTContext {
74 const SampleType *window; ///< MDCT window function
75 FFTContext fft; ///< FFT context for MDCT calculation
79 * Data for a single audio block.
81 typedef struct AC3Block {
82 uint8_t **bap; ///< bit allocation pointers (bap)
83 CoefType **mdct_coef; ///< MDCT coefficients
84 int32_t **fixed_coef; ///< fixed-point MDCT coefficients
85 uint8_t **exp; ///< original exponents
86 uint8_t **grouped_exp; ///< grouped exponents
87 int16_t **psd; ///< psd per frequency bin
88 int16_t **band_psd; ///< psd per critical band
89 int16_t **mask; ///< masking curve
90 uint16_t **qmant; ///< quantized mantissas
91 uint8_t coeff_shift[AC3_MAX_CHANNELS]; ///< fixed-point coefficient shift values
92 uint8_t new_rematrixing_strategy; ///< send new rematrixing flags in this block
93 uint8_t rematrixing_flags[4]; ///< rematrixing flags
94 struct AC3Block *exp_ref_block[AC3_MAX_CHANNELS]; ///< reference blocks for EXP_REUSE
98 * AC-3 encoder private context.
100 typedef struct AC3EncodeContext {
101 AVClass *av_class; ///< AVClass used for AVOption
102 AC3EncOptions options; ///< encoding options
103 PutBitContext pb; ///< bitstream writer context
105 AC3DSPContext ac3dsp; ///< AC-3 optimized functions
106 AC3MDCTContext mdct; ///< MDCT context
108 AC3Block blocks[AC3_MAX_BLOCKS]; ///< per-block info
110 int bitstream_id; ///< bitstream id (bsid)
111 int bitstream_mode; ///< bitstream mode (bsmod)
113 int bit_rate; ///< target bit rate, in bits-per-second
114 int sample_rate; ///< sampling frequency, in Hz
116 int frame_size_min; ///< minimum frame size in case rounding is necessary
117 int frame_size; ///< current frame size in bytes
118 int frame_size_code; ///< frame size code (frmsizecod)
120 int bits_written; ///< bit count (used to avg. bitrate)
121 int samples_written; ///< sample count (used to avg. bitrate)
123 int fbw_channels; ///< number of full-bandwidth channels (nfchans)
124 int channels; ///< total number of channels (nchans)
125 int lfe_on; ///< indicates if there is an LFE channel (lfeon)
126 int lfe_channel; ///< channel index of the LFE channel
127 int has_center; ///< indicates if there is a center channel
128 int has_surround; ///< indicates if there are one or more surround channels
129 int channel_mode; ///< channel mode (acmod)
130 const uint8_t *channel_map; ///< channel map used to reorder channels
132 int center_mix_level; ///< center mix level code
133 int surround_mix_level; ///< surround mix level code
134 int ltrt_center_mix_level; ///< Lt/Rt center mix level code
135 int ltrt_surround_mix_level; ///< Lt/Rt surround mix level code
136 int loro_center_mix_level; ///< Lo/Ro center mix level code
137 int loro_surround_mix_level; ///< Lo/Ro surround mix level code
139 int cutoff; ///< user-specified cutoff frequency, in Hz
140 int bandwidth_code[AC3_MAX_CHANNELS]; ///< bandwidth code (0 to 60) (chbwcod)
141 int nb_coefs[AC3_MAX_CHANNELS];
143 int rematrixing; ///< determines how rematrixing strategy is calculated
144 int num_rematrixing_bands; ///< number of rematrixing bands
146 /* bitrate allocation control */
147 int slow_gain_code; ///< slow gain code (sgaincod)
148 int slow_decay_code; ///< slow decay code (sdcycod)
149 int fast_decay_code; ///< fast decay code (fdcycod)
150 int db_per_bit_code; ///< dB/bit code (dbpbcod)
151 int floor_code; ///< floor code (floorcod)
152 AC3BitAllocParameters bit_alloc; ///< bit allocation parameters
153 int coarse_snr_offset; ///< coarse SNR offsets (csnroffst)
154 int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signal-to-mask ratio) (fgaincod)
155 int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst)
156 int frame_bits_fixed; ///< number of non-coefficient bits for fixed parameters
157 int frame_bits; ///< all frame bits except exponents and mantissas
158 int exponent_bits; ///< number of bits used for exponents
160 SampleType **planar_samples;
162 uint8_t *bap1_buffer;
163 CoefType *mdct_coef_buffer;
164 int32_t *fixed_coef_buffer;
166 uint8_t *grouped_exp_buffer;
168 int16_t *band_psd_buffer;
169 int16_t *mask_buffer;
170 uint16_t *qmant_buffer;
172 uint8_t exp_strategy[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< exponent strategies
174 DECLARE_ALIGNED(16, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
177 typedef struct AC3Mant {
178 uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
179 int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
182 #define CMIXLEV_NUM_OPTIONS 3
183 static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
184 LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
187 #define SURMIXLEV_NUM_OPTIONS 3
188 static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
189 LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
192 #define EXTMIXLEV_NUM_OPTIONS 8
193 static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
194 LEVEL_PLUS_3DB, LEVEL_PLUS_1POINT5DB, LEVEL_ONE, LEVEL_MINUS_4POINT5DB,
195 LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
199 #define OFFSET(param) offsetof(AC3EncodeContext, options.param)
200 #define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
202 #if CONFIG_AC3ENC_FLOAT || !CONFIG_AC3_FLOAT_ENCODER //we need this exactly once compiled in
203 const AVOption ff_ac3_options[] = {
204 /* Metadata Options */
205 {"per_frame_metadata", "Allow Changing Metadata Per-Frame", OFFSET(allow_per_frame_metadata), FF_OPT_TYPE_INT, 0, 0, 1, AC3ENC_PARAM},
207 {"center_mixlev", "Center Mix Level", OFFSET(center_mix_level), FF_OPT_TYPE_FLOAT, LEVEL_MINUS_4POINT5DB, 0.0, 1.0, AC3ENC_PARAM},
208 {"surround_mixlev", "Surround Mix Level", OFFSET(surround_mix_level), FF_OPT_TYPE_FLOAT, LEVEL_MINUS_6DB, 0.0, 1.0, AC3ENC_PARAM},
209 /* audio production information */
210 {"mixing_level", "Mixing Level", OFFSET(mixing_level), FF_OPT_TYPE_INT, -1, -1, 111, AC3ENC_PARAM},
211 {"room_type", "Room Type", OFFSET(room_type), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "room_type"},
212 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
213 {"large", "Large Room", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
214 {"small", "Small Room", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
215 /* other metadata options */
216 {"copyright", "Copyright Bit", OFFSET(copyright), FF_OPT_TYPE_INT, 0, 0, 1, AC3ENC_PARAM},
217 {"dialnorm", "Dialogue Level (dB)", OFFSET(dialogue_level), FF_OPT_TYPE_INT, -31, -31, -1, AC3ENC_PARAM},
218 {"dsur_mode", "Dolby Surround Mode", OFFSET(dolby_surround_mode), FF_OPT_TYPE_INT, 0, 0, 2, AC3ENC_PARAM, "dsur_mode"},
219 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
220 {"on", "Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
221 {"off", "Not Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
222 {"original", "Original Bit Stream", OFFSET(original), FF_OPT_TYPE_INT, 1, 0, 1, AC3ENC_PARAM},
223 /* extended bitstream information */
224 {"dmix_mode", "Preferred Stereo Downmix Mode", OFFSET(preferred_stereo_downmix), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "dmix_mode"},
225 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
226 {"ltrt", "Lt/Rt Downmix Preferred", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
227 {"loro", "Lo/Ro Downmix Preferred", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
228 {"ltrt_cmixlev", "Lt/Rt Center Mix Level", OFFSET(ltrt_center_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
229 {"ltrt_surmixlev", "Lt/Rt Surround Mix Level", OFFSET(ltrt_surround_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
230 {"loro_cmixlev", "Lo/Ro Center Mix Level", OFFSET(loro_center_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
231 {"loro_surmixlev", "Lo/Ro Surround Mix Level", OFFSET(loro_surround_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
232 {"dsurex_mode", "Dolby Surround EX Mode", OFFSET(dolby_surround_ex_mode), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "dsurex_mode"},
233 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
234 {"on", "Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
235 {"off", "Not Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
236 {"dheadphone_mode", "Dolby Headphone Mode", OFFSET(dolby_headphone_mode), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "dheadphone_mode"},
237 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
238 {"on", "Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
239 {"off", "Not Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
240 {"ad_conv_type", "A/D Converter Type", OFFSET(ad_converter_type), FF_OPT_TYPE_INT, -1, -1, 1, AC3ENC_PARAM, "ad_conv_type"},
241 {"standard", "Standard (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
242 {"hdcd", "HDCD", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
247 #if CONFIG_AC3ENC_FLOAT
248 static AVClass ac3enc_class = { "AC-3 Encoder", av_default_item_name,
249 ff_ac3_options, LIBAVUTIL_VERSION_INT };
251 static AVClass ac3enc_class = { "Fixed-Point AC-3 Encoder", av_default_item_name,
252 ff_ac3_options, LIBAVUTIL_VERSION_INT };
256 /* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
258 static av_cold void mdct_end(AC3MDCTContext *mdct);
260 static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
263 static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
264 const SampleType *window, unsigned int len);
266 static int normalize_samples(AC3EncodeContext *s);
268 static void scale_coefficients(AC3EncodeContext *s);
272 * LUT for number of exponent groups.
273 * exponent_group_tab[exponent strategy-1][number of coefficients]
275 static uint8_t exponent_group_tab[3][256];
279 * List of supported channel layouts.
281 #if CONFIG_AC3ENC_FLOAT || !CONFIG_AC3_FLOAT_ENCODER //we need this exactly once compiled in
282 const int64_t ff_ac3_channel_layouts[] = {
286 AV_CH_LAYOUT_SURROUND,
289 AV_CH_LAYOUT_4POINT0,
290 AV_CH_LAYOUT_5POINT0,
291 AV_CH_LAYOUT_5POINT0_BACK,
292 (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
293 (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
294 (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
295 (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
296 (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
297 (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
298 (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
299 AV_CH_LAYOUT_5POINT1,
300 AV_CH_LAYOUT_5POINT1_BACK,
307 * LUT to select the bandwidth code based on the bit rate, sample rate, and
308 * number of full-bandwidth channels.
309 * bandwidth_tab[fbw_channels-1][sample rate code][bit rate code]
311 static const uint8_t ac3_bandwidth_tab[5][3][19] = {
312 // 32 40 48 56 64 80 96 112 128 160 192 224 256 320 384 448 512 576 640
314 { { 0, 0, 0, 12, 16, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
315 { 0, 0, 0, 16, 20, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
316 { 0, 0, 0, 32, 40, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
318 { { 0, 0, 0, 0, 0, 0, 0, 20, 24, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
319 { 0, 0, 0, 0, 0, 0, 4, 24, 28, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
320 { 0, 0, 0, 0, 0, 0, 20, 44, 52, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
322 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 24, 32, 40, 48, 48, 48, 48, 48, 48 },
323 { 0, 0, 0, 0, 0, 0, 0, 0, 4, 20, 28, 36, 44, 56, 56, 56, 56, 56, 56 },
324 { 0, 0, 0, 0, 0, 0, 0, 0, 20, 40, 48, 60, 60, 60, 60, 60, 60, 60, 60 } },
326 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 32, 48, 48, 48, 48, 48, 48 },
327 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 28, 36, 56, 56, 56, 56, 56, 56 },
328 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 48, 60, 60, 60, 60, 60, 60, 60 } },
330 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 20, 32, 40, 48, 48, 48, 48 },
331 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 36, 44, 56, 56, 56, 56 },
332 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 44, 60, 60, 60, 60, 60, 60 } }
337 * Adjust the frame size to make the average bit rate match the target bit rate.
338 * This is only needed for 11025, 22050, and 44100 sample rates.
340 static void adjust_frame_size(AC3EncodeContext *s)
342 while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
343 s->bits_written -= s->bit_rate;
344 s->samples_written -= s->sample_rate;
346 s->frame_size = s->frame_size_min +
347 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
348 s->bits_written += s->frame_size * 8;
349 s->samples_written += AC3_FRAME_SIZE;
354 * Deinterleave input samples.
355 * Channels are reordered from FFmpeg's default order to AC-3 order.
357 static void deinterleave_input_samples(AC3EncodeContext *s,
358 const SampleType *samples)
362 /* deinterleave and remap input samples */
363 for (ch = 0; ch < s->channels; ch++) {
364 const SampleType *sptr;
367 /* copy last 256 samples of previous frame to the start of the current frame */
368 memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
369 AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
373 sptr = samples + s->channel_map[ch];
374 for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
375 s->planar_samples[ch][i] = *sptr;
383 * Apply the MDCT to input samples to generate frequency coefficients.
384 * This applies the KBD window and normalizes the input to reduce precision
385 * loss due to fixed-point calculations.
387 static void apply_mdct(AC3EncodeContext *s)
391 for (ch = 0; ch < s->channels; ch++) {
392 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
393 AC3Block *block = &s->blocks[blk];
394 const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
396 apply_window(&s->dsp, s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
398 block->coeff_shift[ch] = normalize_samples(s);
400 s->mdct.fft.mdct_calcw(&s->mdct.fft, block->mdct_coef[ch],
401 s->windowed_samples);
408 * Initialize stereo rematrixing.
409 * If the strategy does not change for each frame, set the rematrixing flags.
411 static void rematrixing_init(AC3EncodeContext *s)
413 if (s->channel_mode == AC3_CHMODE_STEREO)
414 s->rematrixing = AC3_REMATRIXING_SUMS;
416 s->rematrixing = AC3_REMATRIXING_NONE;
417 /* NOTE: AC3_REMATRIXING_ALWAYS might be used in
418 the future in conjunction with channel coupling. */
420 if (s->rematrixing & AC3_REMATRIXING_IS_STATIC) {
421 int flag = (s->rematrixing == AC3_REMATRIXING_ALWAYS);
422 s->blocks[0].new_rematrixing_strategy = 1;
423 memset(s->blocks[0].rematrixing_flags, flag,
424 sizeof(s->blocks[0].rematrixing_flags));
430 * Determine rematrixing flags for each block and band.
432 static void compute_rematrixing_strategy(AC3EncodeContext *s)
436 AC3Block *block, *block0;
438 s->num_rematrixing_bands = 4;
440 if (s->rematrixing & AC3_REMATRIXING_IS_STATIC)
443 nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
445 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
446 block = &s->blocks[blk];
447 block->new_rematrixing_strategy = !blk;
448 for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
449 /* calculate calculate sum of squared coeffs for one band in one block */
450 int start = ff_ac3_rematrix_band_tab[bnd];
451 int end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
452 CoefSumType sum[4] = {0,};
453 for (i = start; i < end; i++) {
454 CoefType lt = block->mdct_coef[0][i];
455 CoefType rt = block->mdct_coef[1][i];
456 CoefType md = lt + rt;
457 CoefType sd = lt - rt;
458 MAC_COEF(sum[0], lt, lt);
459 MAC_COEF(sum[1], rt, rt);
460 MAC_COEF(sum[2], md, md);
461 MAC_COEF(sum[3], sd, sd);
464 /* compare sums to determine if rematrixing will be used for this band */
465 if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
466 block->rematrixing_flags[bnd] = 1;
468 block->rematrixing_flags[bnd] = 0;
470 /* determine if new rematrixing flags will be sent */
472 block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
473 block->new_rematrixing_strategy = 1;
482 * Apply stereo rematrixing to coefficients based on rematrixing flags.
484 static void apply_rematrixing(AC3EncodeContext *s)
491 if (s->rematrixing == AC3_REMATRIXING_NONE)
494 nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
496 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
497 AC3Block *block = &s->blocks[blk];
498 if (block->new_rematrixing_strategy)
499 flags = block->rematrixing_flags;
500 for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
502 start = ff_ac3_rematrix_band_tab[bnd];
503 end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
504 for (i = start; i < end; i++) {
505 int32_t lt = block->fixed_coef[0][i];
506 int32_t rt = block->fixed_coef[1][i];
507 block->fixed_coef[0][i] = (lt + rt) >> 1;
508 block->fixed_coef[1][i] = (lt - rt) >> 1;
517 * Initialize exponent tables.
519 static av_cold void exponent_init(AC3EncodeContext *s)
522 for (i = 73; i < 256; i++) {
523 exponent_group_tab[0][i] = (i - 1) / 3;
524 exponent_group_tab[1][i] = (i + 2) / 6;
525 exponent_group_tab[2][i] = (i + 8) / 12;
528 exponent_group_tab[0][7] = 2;
533 * Extract exponents from the MDCT coefficients.
534 * This takes into account the normalization that was done to the input samples
535 * by adjusting the exponents by the exponent shift values.
537 static void extract_exponents(AC3EncodeContext *s)
541 for (ch = 0; ch < s->channels; ch++) {
542 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
543 AC3Block *block = &s->blocks[blk];
544 s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch],
552 * Exponent Difference Threshold.
553 * New exponents are sent if their SAD exceed this number.
555 #define EXP_DIFF_THRESHOLD 500
559 * Calculate exponent strategies for all blocks in a single channel.
561 static void compute_exp_strategy_ch(AC3EncodeContext *s, uint8_t *exp_strategy,
567 /* estimate if the exponent variation & decide if they should be
568 reused in the next frame */
569 exp_strategy[0] = EXP_NEW;
570 exp += AC3_MAX_COEFS;
571 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
572 exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
573 if (exp_diff > EXP_DIFF_THRESHOLD)
574 exp_strategy[blk] = EXP_NEW;
576 exp_strategy[blk] = EXP_REUSE;
577 exp += AC3_MAX_COEFS;
580 /* now select the encoding strategy type : if exponents are often
581 recoded, we use a coarse encoding */
583 while (blk < AC3_MAX_BLOCKS) {
585 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
587 switch (blk1 - blk) {
588 case 1: exp_strategy[blk] = EXP_D45; break;
590 case 3: exp_strategy[blk] = EXP_D25; break;
591 default: exp_strategy[blk] = EXP_D15; break;
599 * Calculate exponent strategies for all channels.
600 * Array arrangement is reversed to simplify the per-channel calculation.
602 static void compute_exp_strategy(AC3EncodeContext *s)
606 for (ch = 0; ch < s->fbw_channels; ch++) {
607 compute_exp_strategy_ch(s, s->exp_strategy[ch], s->blocks[0].exp[ch]);
611 s->exp_strategy[ch][0] = EXP_D15;
612 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
613 s->exp_strategy[ch][blk] = EXP_REUSE;
619 * Update the exponents so that they are the ones the decoder will decode.
621 static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy)
625 nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
627 /* for each group, compute the minimum exponent */
628 switch(exp_strategy) {
630 for (i = 1, k = 1; i <= nb_groups; i++) {
631 uint8_t exp_min = exp[k];
632 if (exp[k+1] < exp_min)
639 for (i = 1, k = 1; i <= nb_groups; i++) {
640 uint8_t exp_min = exp[k];
641 if (exp[k+1] < exp_min)
643 if (exp[k+2] < exp_min)
645 if (exp[k+3] < exp_min)
653 /* constraint for DC exponent */
657 /* decrease the delta between each groups to within 2 so that they can be
658 differentially encoded */
659 for (i = 1; i <= nb_groups; i++)
660 exp[i] = FFMIN(exp[i], exp[i-1] + 2);
663 exp[i] = FFMIN(exp[i], exp[i+1] + 2);
665 /* now we have the exponent values the decoder will see */
666 switch (exp_strategy) {
668 for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
669 uint8_t exp1 = exp[i];
675 for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
676 exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
685 * Encode exponents from original extracted form to what the decoder will see.
686 * This copies and groups exponents based on exponent strategy and reduces
687 * deltas between adjacent exponent groups so that they can be differentially
690 static void encode_exponents(AC3EncodeContext *s)
693 uint8_t *exp, *exp_strategy;
694 int nb_coefs, num_reuse_blocks;
696 for (ch = 0; ch < s->channels; ch++) {
697 exp = s->blocks[0].exp[ch];
698 exp_strategy = s->exp_strategy[ch];
699 nb_coefs = s->nb_coefs[ch];
702 while (blk < AC3_MAX_BLOCKS) {
705 /* count the number of EXP_REUSE blocks after the current block
706 and set exponent reference block pointers */
707 s->blocks[blk].exp_ref_block[ch] = &s->blocks[blk];
708 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
709 s->blocks[blk1].exp_ref_block[ch] = &s->blocks[blk];
712 num_reuse_blocks = blk1 - blk - 1;
714 /* for the EXP_REUSE case we select the min of the exponents */
715 s->ac3dsp.ac3_exponent_min(exp, num_reuse_blocks, nb_coefs);
717 encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk]);
719 exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
728 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
729 * varies depending on exponent strategy and bandwidth.
731 static void group_exponents(AC3EncodeContext *s)
734 int group_size, nb_groups, bit_count;
736 int delta0, delta1, delta2;
740 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
741 AC3Block *block = &s->blocks[blk];
742 for (ch = 0; ch < s->channels; ch++) {
743 int exp_strategy = s->exp_strategy[ch][blk];
744 if (exp_strategy == EXP_REUSE)
746 group_size = exp_strategy + (exp_strategy == EXP_D45);
747 nb_groups = exponent_group_tab[exp_strategy-1][s->nb_coefs[ch]];
748 bit_count += 4 + (nb_groups * 7);
753 block->grouped_exp[ch][0] = exp1;
755 /* remaining exponents are delta encoded */
756 for (i = 1; i <= nb_groups; i++) {
757 /* merge three delta in one code */
761 delta0 = exp1 - exp0 + 2;
762 av_assert2(delta0 >= 0 && delta0 <= 4);
767 delta1 = exp1 - exp0 + 2;
768 av_assert2(delta1 >= 0 && delta1 <= 4);
773 delta2 = exp1 - exp0 + 2;
774 av_assert2(delta2 >= 0 && delta2 <= 4);
776 block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
781 s->exponent_bits = bit_count;
786 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
787 * Extract exponents from MDCT coefficients, calculate exponent strategies,
788 * and encode final exponents.
790 static void process_exponents(AC3EncodeContext *s)
792 extract_exponents(s);
794 compute_exp_strategy(s);
805 * Count frame bits that are based solely on fixed parameters.
806 * This only has to be run once when the encoder is initialized.
808 static void count_frame_bits_fixed(AC3EncodeContext *s)
810 static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
815 * no dynamic range codes
816 * no channel coupling
817 * bit allocation parameters do not change between blocks
818 * SNR offsets do not change between blocks
819 * no delta bit allocation
826 frame_bits += frame_bits_inc[s->channel_mode];
829 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
830 frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
831 if (s->channel_mode == AC3_CHMODE_STEREO) {
832 frame_bits++; /* rematstr */
834 frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
836 frame_bits++; /* lfeexpstr */
837 frame_bits++; /* baie */
838 frame_bits++; /* snr */
839 frame_bits += 2; /* delta / skip */
841 frame_bits++; /* cplinu for block 0 */
843 /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
845 /* (fsnoffset[4] + fgaincod[4]) * c */
846 frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
848 /* auxdatae, crcrsv */
854 s->frame_bits_fixed = frame_bits;
859 * Initialize bit allocation.
860 * Set default parameter codes and calculate parameter values.
862 static void bit_alloc_init(AC3EncodeContext *s)
866 /* init default parameters */
867 s->slow_decay_code = 2;
868 s->fast_decay_code = 1;
869 s->slow_gain_code = 1;
870 s->db_per_bit_code = 3;
872 for (ch = 0; ch < s->channels; ch++)
873 s->fast_gain_code[ch] = 4;
875 /* initial snr offset */
876 s->coarse_snr_offset = 40;
878 /* compute real values */
879 /* currently none of these values change during encoding, so we can just
880 set them once at initialization */
881 s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
882 s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
883 s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
884 s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
885 s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
887 count_frame_bits_fixed(s);
892 * Count the bits used to encode the frame, minus exponents and mantissas.
893 * Bits based on fixed parameters have already been counted, so now we just
894 * have to add the bits based on parameters that change during encoding.
896 static void count_frame_bits(AC3EncodeContext *s)
898 AC3EncOptions *opt = &s->options;
902 if (opt->audio_production_info)
904 if (s->bitstream_id == 6) {
905 if (opt->extended_bsi_1)
907 if (opt->extended_bsi_2)
911 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
912 /* stereo rematrixing */
913 if (s->channel_mode == AC3_CHMODE_STEREO &&
914 s->blocks[blk].new_rematrixing_strategy) {
915 frame_bits += s->num_rematrixing_bands;
918 for (ch = 0; ch < s->fbw_channels; ch++) {
919 if (s->exp_strategy[ch][blk] != EXP_REUSE)
920 frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
923 s->frame_bits = s->frame_bits_fixed + frame_bits;
928 * Finalize the mantissa bit count by adding in the grouped mantissas.
930 static int compute_mantissa_size_final(int mant_cnt[5])
932 // bap=1 : 3 mantissas in 5 bits
933 int bits = (mant_cnt[1] / 3) * 5;
934 // bap=2 : 3 mantissas in 7 bits
935 // bap=4 : 2 mantissas in 7 bits
936 bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
937 // bap=3 : each mantissa is 3 bits
938 bits += mant_cnt[3] * 3;
944 * Calculate masking curve based on the final exponents.
945 * Also calculate the power spectral densities to use in future calculations.
947 static void bit_alloc_masking(AC3EncodeContext *s)
951 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
952 AC3Block *block = &s->blocks[blk];
953 for (ch = 0; ch < s->channels; ch++) {
954 /* We only need psd and mask for calculating bap.
955 Since we currently do not calculate bap when exponent
956 strategy is EXP_REUSE we do not need to calculate psd or mask. */
957 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
958 ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
960 block->psd[ch], block->band_psd[ch]);
961 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
963 ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
964 ch == s->lfe_channel,
965 DBA_NONE, 0, NULL, NULL, NULL,
974 * Ensure that bap for each block and channel point to the current bap_buffer.
975 * They may have been switched during the bit allocation search.
977 static void reset_block_bap(AC3EncodeContext *s)
980 if (s->blocks[0].bap[0] == s->bap_buffer)
982 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
983 for (ch = 0; ch < s->channels; ch++) {
984 s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
991 * Run the bit allocation with a given SNR offset.
992 * This calculates the bit allocation pointers that will be used to determine
993 * the quantization of each mantissa.
994 * @return the number of bits needed for mantissas if the given SNR offset is
997 static int bit_alloc(AC3EncodeContext *s, int snr_offset)
1003 snr_offset = (snr_offset - 240) << 2;
1007 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1009 // initialize grouped mantissa counts. these are set so that they are
1010 // padded to the next whole group size when bits are counted in
1011 // compute_mantissa_size_final
1012 mant_cnt[0] = mant_cnt[3] = 0;
1013 mant_cnt[1] = mant_cnt[2] = 2;
1015 for (ch = 0; ch < s->channels; ch++) {
1016 /* Currently the only bit allocation parameters which vary across
1017 blocks within a frame are the exponent values. We can take
1018 advantage of that by reusing the bit allocation pointers
1019 whenever we reuse exponents. */
1020 block = s->blocks[blk].exp_ref_block[ch];
1021 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1022 s->ac3dsp.bit_alloc_calc_bap(block->mask[ch], block->psd[ch], 0,
1023 s->nb_coefs[ch], snr_offset,
1024 s->bit_alloc.floor, ff_ac3_bap_tab,
1027 mantissa_bits += s->ac3dsp.compute_mantissa_size(mant_cnt, block->bap[ch], s->nb_coefs[ch]);
1029 mantissa_bits += compute_mantissa_size_final(mant_cnt);
1031 return mantissa_bits;
1036 * Constant bitrate bit allocation search.
1037 * Find the largest SNR offset that will allow data to fit in the frame.
1039 static int cbr_bit_allocation(AC3EncodeContext *s)
1043 int snr_offset, snr_incr;
1045 bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1046 av_assert2(bits_left >= 0);
1048 snr_offset = s->coarse_snr_offset << 4;
1050 /* if previous frame SNR offset was 1023, check if current frame can also
1051 use SNR offset of 1023. if so, skip the search. */
1052 if ((snr_offset | s->fine_snr_offset[0]) == 1023) {
1053 if (bit_alloc(s, 1023) <= bits_left)
1057 while (snr_offset >= 0 &&
1058 bit_alloc(s, snr_offset) > bits_left) {
1062 return AVERROR(EINVAL);
1064 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1065 for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1066 while (snr_offset + snr_incr <= 1023 &&
1067 bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1068 snr_offset += snr_incr;
1069 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1072 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1075 s->coarse_snr_offset = snr_offset >> 4;
1076 for (ch = 0; ch < s->channels; ch++)
1077 s->fine_snr_offset[ch] = snr_offset & 0xF;
1084 * Downgrade exponent strategies to reduce the bits used by the exponents.
1085 * This is a fallback for when bit allocation fails with the normal exponent
1086 * strategies. Each time this function is run it only downgrades the
1087 * strategy in 1 channel of 1 block.
1088 * @return non-zero if downgrade was unsuccessful
1090 static int downgrade_exponents(AC3EncodeContext *s)
1094 for (ch = 0; ch < s->fbw_channels; ch++) {
1095 for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1096 if (s->exp_strategy[ch][blk] == EXP_D15) {
1097 s->exp_strategy[ch][blk] = EXP_D25;
1102 for (ch = 0; ch < s->fbw_channels; ch++) {
1103 for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1104 if (s->exp_strategy[ch][blk] == EXP_D25) {
1105 s->exp_strategy[ch][blk] = EXP_D45;
1110 for (ch = 0; ch < s->fbw_channels; ch++) {
1111 /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
1112 the block number > 0 */
1113 for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
1114 if (s->exp_strategy[ch][blk] > EXP_REUSE) {
1115 s->exp_strategy[ch][blk] = EXP_REUSE;
1125 * Reduce the bandwidth to reduce the number of bits used for a given SNR offset.
1126 * This is a second fallback for when bit allocation still fails after exponents
1127 * have been downgraded.
1128 * @return non-zero if bandwidth reduction was unsuccessful
1130 static int reduce_bandwidth(AC3EncodeContext *s, int min_bw_code)
1134 if (s->bandwidth_code[0] > min_bw_code) {
1135 for (ch = 0; ch < s->fbw_channels; ch++) {
1136 s->bandwidth_code[ch]--;
1137 s->nb_coefs[ch] = s->bandwidth_code[ch] * 3 + 73;
1146 * Perform bit allocation search.
1147 * Finds the SNR offset value that maximizes quality and fits in the specified
1148 * frame size. Output is the SNR offset and a set of bit allocation pointers
1149 * used to quantize the mantissas.
1151 static int compute_bit_allocation(AC3EncodeContext *s)
1155 count_frame_bits(s);
1157 bit_alloc_masking(s);
1159 ret = cbr_bit_allocation(s);
1161 /* fallback 1: downgrade exponents */
1162 if (!downgrade_exponents(s)) {
1163 extract_exponents(s);
1164 encode_exponents(s);
1166 ret = compute_bit_allocation(s);
1170 /* fallback 2: reduce bandwidth */
1171 /* only do this if the user has not specified a specific cutoff
1173 if (!s->cutoff && !reduce_bandwidth(s, 0)) {
1174 process_exponents(s);
1175 ret = compute_bit_allocation(s);
1179 /* fallbacks were not enough... */
1188 * Symmetric quantization on 'levels' levels.
1190 static inline int sym_quant(int c, int e, int levels)
1192 int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1193 av_assert2(v >= 0 && v < levels);
1199 * Asymmetric quantization on 2^qbits levels.
1201 static inline int asym_quant(int c, int e, int qbits)
1205 lshift = e + qbits - 24;
1212 m = (1 << (qbits-1));
1215 av_assert2(v >= -m);
1216 return v & ((1 << qbits)-1);
1221 * Quantize a set of mantissas for a single channel in a single block.
1223 static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1225 uint8_t *bap, uint16_t *qmant, int n)
1229 for (i = 0; i < n; i++) {
1231 int c = fixed_coef[i];
1239 v = sym_quant(c, e, 3);
1240 switch (s->mant1_cnt) {
1242 s->qmant1_ptr = &qmant[i];
1247 *s->qmant1_ptr += 3 * v;
1252 *s->qmant1_ptr += v;
1259 v = sym_quant(c, e, 5);
1260 switch (s->mant2_cnt) {
1262 s->qmant2_ptr = &qmant[i];
1267 *s->qmant2_ptr += 5 * v;
1272 *s->qmant2_ptr += v;
1279 v = sym_quant(c, e, 7);
1282 v = sym_quant(c, e, 11);
1283 switch (s->mant4_cnt) {
1285 s->qmant4_ptr = &qmant[i];
1290 *s->qmant4_ptr += v;
1297 v = sym_quant(c, e, 15);
1300 v = asym_quant(c, e, 14);
1303 v = asym_quant(c, e, 16);
1306 v = asym_quant(c, e, b - 1);
1315 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1317 static void quantize_mantissas(AC3EncodeContext *s)
1322 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1323 AC3Block *block = &s->blocks[blk];
1324 AC3Block *ref_block;
1327 for (ch = 0; ch < s->channels; ch++) {
1328 ref_block = block->exp_ref_block[ch];
1329 quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1330 ref_block->exp[ch], ref_block->bap[ch],
1331 block->qmant[ch], s->nb_coefs[ch]);
1338 * Write the AC-3 frame header to the output bitstream.
1340 static void output_frame_header(AC3EncodeContext *s)
1342 AC3EncOptions *opt = &s->options;
1344 put_bits(&s->pb, 16, 0x0b77); /* frame header */
1345 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
1346 put_bits(&s->pb, 2, s->bit_alloc.sr_code);
1347 put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1348 put_bits(&s->pb, 5, s->bitstream_id);
1349 put_bits(&s->pb, 3, s->bitstream_mode);
1350 put_bits(&s->pb, 3, s->channel_mode);
1351 if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1352 put_bits(&s->pb, 2, s->center_mix_level);
1353 if (s->channel_mode & 0x04)
1354 put_bits(&s->pb, 2, s->surround_mix_level);
1355 if (s->channel_mode == AC3_CHMODE_STEREO)
1356 put_bits(&s->pb, 2, opt->dolby_surround_mode);
1357 put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1358 put_bits(&s->pb, 5, -opt->dialogue_level);
1359 put_bits(&s->pb, 1, 0); /* no compression control word */
1360 put_bits(&s->pb, 1, 0); /* no lang code */
1361 put_bits(&s->pb, 1, opt->audio_production_info);
1362 if (opt->audio_production_info) {
1363 put_bits(&s->pb, 5, opt->mixing_level - 80);
1364 put_bits(&s->pb, 2, opt->room_type);
1366 put_bits(&s->pb, 1, opt->copyright);
1367 put_bits(&s->pb, 1, opt->original);
1368 if (s->bitstream_id == 6) {
1369 /* alternate bit stream syntax */
1370 put_bits(&s->pb, 1, opt->extended_bsi_1);
1371 if (opt->extended_bsi_1) {
1372 put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1373 put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1374 put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1375 put_bits(&s->pb, 3, s->loro_center_mix_level);
1376 put_bits(&s->pb, 3, s->loro_surround_mix_level);
1378 put_bits(&s->pb, 1, opt->extended_bsi_2);
1379 if (opt->extended_bsi_2) {
1380 put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1381 put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1382 put_bits(&s->pb, 1, opt->ad_converter_type);
1383 put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
1386 put_bits(&s->pb, 1, 0); /* no time code 1 */
1387 put_bits(&s->pb, 1, 0); /* no time code 2 */
1389 put_bits(&s->pb, 1, 0); /* no additional bit stream info */
1394 * Write one audio block to the output bitstream.
1396 static void output_audio_block(AC3EncodeContext *s, int blk)
1398 int ch, i, baie, rbnd;
1399 AC3Block *block = &s->blocks[blk];
1401 /* block switching */
1402 for (ch = 0; ch < s->fbw_channels; ch++)
1403 put_bits(&s->pb, 1, 0);
1406 for (ch = 0; ch < s->fbw_channels; ch++)
1407 put_bits(&s->pb, 1, 1);
1409 /* dynamic range codes */
1410 put_bits(&s->pb, 1, 0);
1412 /* channel coupling */
1414 put_bits(&s->pb, 1, 1); /* coupling strategy present */
1415 put_bits(&s->pb, 1, 0); /* no coupling strategy */
1417 put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1420 /* stereo rematrixing */
1421 if (s->channel_mode == AC3_CHMODE_STEREO) {
1422 put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1423 if (block->new_rematrixing_strategy) {
1424 /* rematrixing flags */
1425 for (rbnd = 0; rbnd < s->num_rematrixing_bands; rbnd++)
1426 put_bits(&s->pb, 1, block->rematrixing_flags[rbnd]);
1430 /* exponent strategy */
1431 for (ch = 0; ch < s->fbw_channels; ch++)
1432 put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1434 put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1437 for (ch = 0; ch < s->fbw_channels; ch++) {
1438 if (s->exp_strategy[ch][blk] != EXP_REUSE)
1439 put_bits(&s->pb, 6, s->bandwidth_code[ch]);
1443 for (ch = 0; ch < s->channels; ch++) {
1446 if (s->exp_strategy[ch][blk] == EXP_REUSE)
1450 put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1452 /* exponent groups */
1453 nb_groups = exponent_group_tab[s->exp_strategy[ch][blk]-1][s->nb_coefs[ch]];
1454 for (i = 1; i <= nb_groups; i++)
1455 put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1457 /* gain range info */
1458 if (ch != s->lfe_channel)
1459 put_bits(&s->pb, 2, 0);
1462 /* bit allocation info */
1464 put_bits(&s->pb, 1, baie);
1466 put_bits(&s->pb, 2, s->slow_decay_code);
1467 put_bits(&s->pb, 2, s->fast_decay_code);
1468 put_bits(&s->pb, 2, s->slow_gain_code);
1469 put_bits(&s->pb, 2, s->db_per_bit_code);
1470 put_bits(&s->pb, 3, s->floor_code);
1474 put_bits(&s->pb, 1, baie);
1476 put_bits(&s->pb, 6, s->coarse_snr_offset);
1477 for (ch = 0; ch < s->channels; ch++) {
1478 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1479 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1483 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1484 put_bits(&s->pb, 1, 0); /* no data to skip */
1487 for (ch = 0; ch < s->channels; ch++) {
1489 AC3Block *ref_block = block->exp_ref_block[ch];
1490 for (i = 0; i < s->nb_coefs[ch]; i++) {
1491 q = block->qmant[ch][i];
1492 b = ref_block->bap[ch][i];
1495 case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
1496 case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
1497 case 3: put_bits(&s->pb, 3, q); break;
1498 case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
1499 case 14: put_bits(&s->pb, 14, q); break;
1500 case 15: put_bits(&s->pb, 16, q); break;
1501 default: put_bits(&s->pb, b-1, q); break;
1508 /** CRC-16 Polynomial */
1509 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1512 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1529 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1535 r = mul_poly(r, a, poly);
1536 a = mul_poly(a, a, poly);
1544 * Fill the end of the frame with 0's and compute the two CRCs.
1546 static void output_frame_end(AC3EncodeContext *s)
1548 const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1549 int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1552 frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1554 /* pad the remainder of the frame with zeros */
1555 av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1556 flush_put_bits(&s->pb);
1558 pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1559 av_assert2(pad_bytes >= 0);
1561 memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1564 /* this is not so easy because it is at the beginning of the data... */
1565 crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1566 crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1567 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1568 AV_WB16(frame + 2, crc1);
1571 crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1572 s->frame_size - frame_size_58 - 3);
1573 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1574 /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1575 if (crc2 == 0x770B) {
1576 frame[s->frame_size - 3] ^= 0x1;
1577 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1579 crc2 = av_bswap16(crc2);
1580 AV_WB16(frame + s->frame_size - 2, crc2);
1585 * Write the frame to the output bitstream.
1587 static void output_frame(AC3EncodeContext *s, unsigned char *frame)
1591 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1593 output_frame_header(s);
1595 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1596 output_audio_block(s, blk);
1598 output_frame_end(s);
1602 static void dprint_options(AVCodecContext *avctx)
1605 AC3EncodeContext *s = avctx->priv_data;
1606 AC3EncOptions *opt = &s->options;
1609 switch (s->bitstream_id) {
1610 case 6: strncpy(strbuf, "AC-3 (alt syntax)", 32); break;
1611 case 8: strncpy(strbuf, "AC-3 (standard)", 32); break;
1612 case 9: strncpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
1613 case 10: strncpy(strbuf, "AC-3 (dnet quater-rate", 32); break;
1614 default: snprintf(strbuf, 32, "ERROR");
1616 av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
1617 av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
1618 av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
1619 av_dlog(avctx, "channel_layout: %s\n", strbuf);
1620 av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
1621 av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
1623 av_dlog(avctx, "cutoff: %d\n", s->cutoff);
1625 av_dlog(avctx, "per_frame_metadata: %s\n",
1626 opt->allow_per_frame_metadata?"on":"off");
1628 av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
1629 s->center_mix_level);
1631 av_dlog(avctx, "center_mixlev: {not written}\n");
1632 if (s->has_surround)
1633 av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
1634 s->surround_mix_level);
1636 av_dlog(avctx, "surround_mixlev: {not written}\n");
1637 if (opt->audio_production_info) {
1638 av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
1639 switch (opt->room_type) {
1640 case 0: strncpy(strbuf, "notindicated", 32); break;
1641 case 1: strncpy(strbuf, "large", 32); break;
1642 case 2: strncpy(strbuf, "small", 32); break;
1643 default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
1645 av_dlog(avctx, "room_type: %s\n", strbuf);
1647 av_dlog(avctx, "mixing_level: {not written}\n");
1648 av_dlog(avctx, "room_type: {not written}\n");
1650 av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
1651 av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
1652 if (s->channel_mode == AC3_CHMODE_STEREO) {
1653 switch (opt->dolby_surround_mode) {
1654 case 0: strncpy(strbuf, "notindicated", 32); break;
1655 case 1: strncpy(strbuf, "on", 32); break;
1656 case 2: strncpy(strbuf, "off", 32); break;
1657 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
1659 av_dlog(avctx, "dsur_mode: %s\n", strbuf);
1661 av_dlog(avctx, "dsur_mode: {not written}\n");
1663 av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
1665 if (s->bitstream_id == 6) {
1666 if (opt->extended_bsi_1) {
1667 switch (opt->preferred_stereo_downmix) {
1668 case 0: strncpy(strbuf, "notindicated", 32); break;
1669 case 1: strncpy(strbuf, "ltrt", 32); break;
1670 case 2: strncpy(strbuf, "loro", 32); break;
1671 default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
1673 av_dlog(avctx, "dmix_mode: %s\n", strbuf);
1674 av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
1675 opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
1676 av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
1677 opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
1678 av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
1679 opt->loro_center_mix_level, s->loro_center_mix_level);
1680 av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
1681 opt->loro_surround_mix_level, s->loro_surround_mix_level);
1683 av_dlog(avctx, "extended bitstream info 1: {not written}\n");
1685 if (opt->extended_bsi_2) {
1686 switch (opt->dolby_surround_ex_mode) {
1687 case 0: strncpy(strbuf, "notindicated", 32); break;
1688 case 1: strncpy(strbuf, "on", 32); break;
1689 case 2: strncpy(strbuf, "off", 32); break;
1690 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
1692 av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
1693 switch (opt->dolby_headphone_mode) {
1694 case 0: strncpy(strbuf, "notindicated", 32); break;
1695 case 1: strncpy(strbuf, "on", 32); break;
1696 case 2: strncpy(strbuf, "off", 32); break;
1697 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
1699 av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
1701 switch (opt->ad_converter_type) {
1702 case 0: strncpy(strbuf, "standard", 32); break;
1703 case 1: strncpy(strbuf, "hdcd", 32); break;
1704 default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
1706 av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
1708 av_dlog(avctx, "extended bitstream info 2: {not written}\n");
1715 #define FLT_OPTION_THRESHOLD 0.01
1717 static int validate_float_option(float v, const float *v_list, int v_list_size)
1721 for (i = 0; i < v_list_size; i++) {
1722 if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
1723 v > (v_list[i] - FLT_OPTION_THRESHOLD))
1726 if (i == v_list_size)
1733 static void validate_mix_level(void *log_ctx, const char *opt_name,
1734 float *opt_param, const float *list,
1735 int list_size, int default_value, int min_value,
1738 int mixlev = validate_float_option(*opt_param, list, list_size);
1739 if (mixlev < min_value) {
1740 mixlev = default_value;
1741 if (*opt_param >= 0.0) {
1742 av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
1743 "default value: %0.3f\n", opt_name, list[mixlev]);
1746 *opt_param = list[mixlev];
1747 *ctx_param = mixlev;
1752 * Validate metadata options as set by AVOption system.
1753 * These values can optionally be changed per-frame.
1755 static int validate_metadata(AVCodecContext *avctx)
1757 AC3EncodeContext *s = avctx->priv_data;
1758 AC3EncOptions *opt = &s->options;
1760 /* validate mixing levels */
1761 if (s->has_center) {
1762 validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
1763 cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
1764 &s->center_mix_level);
1766 if (s->has_surround) {
1767 validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
1768 surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
1769 &s->surround_mix_level);
1772 /* set audio production info flag */
1773 if (opt->mixing_level >= 0 || opt->room_type >= 0) {
1774 if (opt->mixing_level < 0) {
1775 av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
1776 "room_type is set\n");
1777 return AVERROR(EINVAL);
1779 if (opt->mixing_level < 80) {
1780 av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
1781 "80dB and 111dB\n");
1782 return AVERROR(EINVAL);
1784 /* default room type */
1785 if (opt->room_type < 0)
1787 opt->audio_production_info = 1;
1789 opt->audio_production_info = 0;
1792 /* set extended bsi 1 flag */
1793 if ((s->has_center || s->has_surround) &&
1794 (opt->preferred_stereo_downmix >= 0 ||
1795 opt->ltrt_center_mix_level >= 0 ||
1796 opt->ltrt_surround_mix_level >= 0 ||
1797 opt->loro_center_mix_level >= 0 ||
1798 opt->loro_surround_mix_level >= 0)) {
1799 /* default preferred stereo downmix */
1800 if (opt->preferred_stereo_downmix < 0)
1801 opt->preferred_stereo_downmix = 0;
1802 /* validate Lt/Rt center mix level */
1803 validate_mix_level(avctx, "ltrt_center_mix_level",
1804 &opt->ltrt_center_mix_level, extmixlev_options,
1805 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1806 &s->ltrt_center_mix_level);
1807 /* validate Lt/Rt surround mix level */
1808 validate_mix_level(avctx, "ltrt_surround_mix_level",
1809 &opt->ltrt_surround_mix_level, extmixlev_options,
1810 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1811 &s->ltrt_surround_mix_level);
1812 /* validate Lo/Ro center mix level */
1813 validate_mix_level(avctx, "loro_center_mix_level",
1814 &opt->loro_center_mix_level, extmixlev_options,
1815 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1816 &s->loro_center_mix_level);
1817 /* validate Lo/Ro surround mix level */
1818 validate_mix_level(avctx, "loro_surround_mix_level",
1819 &opt->loro_surround_mix_level, extmixlev_options,
1820 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1821 &s->loro_surround_mix_level);
1822 opt->extended_bsi_1 = 1;
1824 opt->extended_bsi_1 = 0;
1827 /* set extended bsi 2 flag */
1828 if (opt->dolby_surround_ex_mode >= 0 ||
1829 opt->dolby_headphone_mode >= 0 ||
1830 opt->ad_converter_type >= 0) {
1831 /* default dolby surround ex mode */
1832 if (opt->dolby_surround_ex_mode < 0)
1833 opt->dolby_surround_ex_mode = 0;
1834 /* default dolby headphone mode */
1835 if (opt->dolby_headphone_mode < 0)
1836 opt->dolby_headphone_mode = 0;
1837 /* default A/D converter type */
1838 if (opt->ad_converter_type < 0)
1839 opt->ad_converter_type = 0;
1840 opt->extended_bsi_2 = 1;
1842 opt->extended_bsi_2 = 0;
1845 /* set bitstream id for alternate bitstream syntax */
1846 if (opt->extended_bsi_1 || opt->extended_bsi_2) {
1847 if (s->bitstream_id > 8 && s->bitstream_id < 11) {
1848 static int warn_once = 1;
1850 av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
1851 "not compatible with reduced samplerates. writing of "
1852 "extended bitstream information will be disabled.\n");
1856 s->bitstream_id = 6;
1865 * Encode a single AC-3 frame.
1867 static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
1868 int buf_size, void *data)
1870 AC3EncodeContext *s = avctx->priv_data;
1871 const SampleType *samples = data;
1874 if (s->options.allow_per_frame_metadata) {
1875 ret = validate_metadata(avctx);
1880 if (s->bit_alloc.sr_code == 1)
1881 adjust_frame_size(s);
1883 deinterleave_input_samples(s, samples);
1887 scale_coefficients(s);
1889 compute_rematrixing_strategy(s);
1891 apply_rematrixing(s);
1893 process_exponents(s);
1895 ret = compute_bit_allocation(s);
1897 av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1901 quantize_mantissas(s);
1903 output_frame(s, frame);
1905 return s->frame_size;
1910 * Finalize encoding and free any memory allocated by the encoder.
1912 static av_cold int ac3_encode_close(AVCodecContext *avctx)
1915 AC3EncodeContext *s = avctx->priv_data;
1917 for (ch = 0; ch < s->channels; ch++)
1918 av_freep(&s->planar_samples[ch]);
1919 av_freep(&s->planar_samples);
1920 av_freep(&s->bap_buffer);
1921 av_freep(&s->bap1_buffer);
1922 av_freep(&s->mdct_coef_buffer);
1923 av_freep(&s->fixed_coef_buffer);
1924 av_freep(&s->exp_buffer);
1925 av_freep(&s->grouped_exp_buffer);
1926 av_freep(&s->psd_buffer);
1927 av_freep(&s->band_psd_buffer);
1928 av_freep(&s->mask_buffer);
1929 av_freep(&s->qmant_buffer);
1930 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1931 AC3Block *block = &s->blocks[blk];
1932 av_freep(&block->bap);
1933 av_freep(&block->mdct_coef);
1934 av_freep(&block->fixed_coef);
1935 av_freep(&block->exp);
1936 av_freep(&block->grouped_exp);
1937 av_freep(&block->psd);
1938 av_freep(&block->band_psd);
1939 av_freep(&block->mask);
1940 av_freep(&block->qmant);
1945 av_freep(&avctx->coded_frame);
1951 * Set channel information during initialization.
1953 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1954 int64_t *channel_layout)
1958 if (channels < 1 || channels > AC3_MAX_CHANNELS)
1959 return AVERROR(EINVAL);
1960 if ((uint64_t)*channel_layout > 0x7FF)
1961 return AVERROR(EINVAL);
1962 ch_layout = *channel_layout;
1964 ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1965 if (av_get_channel_layout_nb_channels(ch_layout) != channels)
1966 return AVERROR(EINVAL);
1968 s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1969 s->channels = channels;
1970 s->fbw_channels = channels - s->lfe_on;
1971 s->lfe_channel = s->lfe_on ? s->fbw_channels : -1;
1973 ch_layout -= AV_CH_LOW_FREQUENCY;
1975 switch (ch_layout) {
1976 case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
1977 case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
1978 case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
1979 case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
1980 case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
1981 case AV_CH_LAYOUT_QUAD:
1982 case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
1983 case AV_CH_LAYOUT_5POINT0:
1984 case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
1986 return AVERROR(EINVAL);
1988 s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
1989 s->has_surround = s->channel_mode & 0x04;
1991 s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1992 *channel_layout = ch_layout;
1994 *channel_layout |= AV_CH_LOW_FREQUENCY;
2000 static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
2004 /* validate channel layout */
2005 if (!avctx->channel_layout) {
2006 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
2007 "encoder will guess the layout, but it "
2008 "might be incorrect.\n");
2010 ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
2012 av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
2016 /* validate sample rate */
2017 for (i = 0; i < 9; i++) {
2018 if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
2022 av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
2023 return AVERROR(EINVAL);
2025 s->sample_rate = avctx->sample_rate;
2026 s->bit_alloc.sr_shift = i % 3;
2027 s->bit_alloc.sr_code = i / 3;
2028 s->bitstream_id = 8 + s->bit_alloc.sr_shift;
2030 /* validate bit rate */
2031 for (i = 0; i < 19; i++) {
2032 if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
2036 av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2037 return AVERROR(EINVAL);
2039 s->bit_rate = avctx->bit_rate;
2040 s->frame_size_code = i << 1;
2042 /* validate cutoff */
2043 if (avctx->cutoff < 0) {
2044 av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2045 return AVERROR(EINVAL);
2047 s->cutoff = avctx->cutoff;
2048 if (s->cutoff > (s->sample_rate >> 1))
2049 s->cutoff = s->sample_rate >> 1;
2051 /* validate audio service type / channels combination */
2052 if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
2053 avctx->channels == 1) ||
2054 ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
2055 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
2056 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
2057 && avctx->channels > 1)) {
2058 av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
2059 "specified number of channels\n");
2060 return AVERROR(EINVAL);
2063 ret = validate_metadata(avctx);
2072 * Set bandwidth for all channels.
2073 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2074 * default value will be used.
2076 static av_cold void set_bandwidth(AC3EncodeContext *s)
2081 /* calculate bandwidth based on user-specified cutoff frequency */
2083 fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2084 bw_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2086 /* use default bandwidth setting */
2087 bw_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2090 /* set number of coefficients for each channel */
2091 for (ch = 0; ch < s->fbw_channels; ch++) {
2092 s->bandwidth_code[ch] = bw_code;
2093 s->nb_coefs[ch] = bw_code * 3 + 73;
2096 s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
2100 static av_cold int allocate_buffers(AVCodecContext *avctx)
2103 AC3EncodeContext *s = avctx->priv_data;
2105 FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
2107 for (ch = 0; ch < s->channels; ch++) {
2108 FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
2109 (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
2112 FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * s->channels *
2113 AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
2114 FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
2115 AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
2116 FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
2117 AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
2118 FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
2119 AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
2120 FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
2121 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
2122 FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
2123 AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
2124 FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
2125 64 * sizeof(*s->band_psd_buffer), alloc_fail);
2126 FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
2127 64 * sizeof(*s->mask_buffer), alloc_fail);
2128 FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
2129 AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
2130 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2131 AC3Block *block = &s->blocks[blk];
2132 FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
2134 FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
2136 FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
2138 FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
2140 FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
2142 FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
2144 FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
2146 FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
2149 for (ch = 0; ch < s->channels; ch++) {
2150 /* arrangement: block, channel, coeff */
2151 block->bap[ch] = &s->bap_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2152 block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2153 block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * s->channels + ch)];
2154 block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2155 block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * s->channels + ch)];
2156 block->mask[ch] = &s->mask_buffer [64 * (blk * s->channels + ch)];
2157 block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2159 /* arrangement: channel, block, coeff */
2160 block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2164 if (CONFIG_AC3ENC_FLOAT) {
2165 FF_ALLOC_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * s->channels *
2166 AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
2167 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2168 AC3Block *block = &s->blocks[blk];
2169 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2170 sizeof(*block->fixed_coef), alloc_fail);
2171 for (ch = 0; ch < s->channels; ch++)
2172 block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
2175 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2176 AC3Block *block = &s->blocks[blk];
2177 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2178 sizeof(*block->fixed_coef), alloc_fail);
2179 for (ch = 0; ch < s->channels; ch++)
2180 block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2186 return AVERROR(ENOMEM);
2191 * Initialize the encoder.
2193 static av_cold int ac3_encode_init(AVCodecContext *avctx)
2195 AC3EncodeContext *s = avctx->priv_data;
2196 int ret, frame_size_58;
2198 avctx->frame_size = AC3_FRAME_SIZE;
2200 ff_ac3_common_init();
2202 ret = validate_options(avctx, s);
2206 s->bitstream_mode = avctx->audio_service_type;
2207 if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2208 s->bitstream_mode = 0x7;
2210 s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2211 s->bits_written = 0;
2212 s->samples_written = 0;
2213 s->frame_size = s->frame_size_min;
2215 /* calculate crc_inv for both possible frame sizes */
2216 frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
2217 s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2218 if (s->bit_alloc.sr_code == 1) {
2219 frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2220 s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2225 rematrixing_init(s);
2231 ret = mdct_init(avctx, &s->mdct, 9);
2235 ret = allocate_buffers(avctx);
2239 avctx->coded_frame= avcodec_alloc_frame();
2241 dsputil_init(&s->dsp, avctx);
2242 ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2244 dprint_options(avctx);
2248 ac3_encode_close(avctx);