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/avstring.h"
37 #include "libavutil/crc.h"
38 #include "libavutil/opt.h"
44 #include "audioconvert.h"
48 #ifndef CONFIG_AC3ENC_FLOAT
49 #define CONFIG_AC3ENC_FLOAT 0
53 /** Maximum number of exponent groups. +1 for separate DC exponent. */
54 #define AC3_MAX_EXP_GROUPS 85
56 #if CONFIG_AC3ENC_FLOAT
57 #define MAC_COEF(d,a,b) ((d)+=(a)*(b))
58 typedef float SampleType;
59 typedef float CoefType;
60 typedef float CoefSumType;
62 #define MAC_COEF(d,a,b) MAC64(d,a,b)
63 typedef int16_t SampleType;
64 typedef int32_t CoefType;
65 typedef int64_t CoefSumType;
68 typedef struct AC3MDCTContext {
69 const SampleType *window; ///< MDCT window function
70 FFTContext fft; ///< FFT context for MDCT calculation
74 * Data for a single audio block.
76 typedef struct AC3Block {
77 uint8_t **bap; ///< bit allocation pointers (bap)
78 CoefType **mdct_coef; ///< MDCT coefficients
79 int32_t **fixed_coef; ///< fixed-point MDCT coefficients
80 uint8_t **exp; ///< original exponents
81 uint8_t **grouped_exp; ///< grouped exponents
82 int16_t **psd; ///< psd per frequency bin
83 int16_t **band_psd; ///< psd per critical band
84 int16_t **mask; ///< masking curve
85 uint16_t **qmant; ///< quantized mantissas
86 uint8_t coeff_shift[AC3_MAX_CHANNELS]; ///< fixed-point coefficient shift values
87 uint8_t new_rematrixing_strategy; ///< send new rematrixing flags in this block
88 uint8_t rematrixing_flags[4]; ///< rematrixing flags
89 struct AC3Block *exp_ref_block[AC3_MAX_CHANNELS]; ///< reference blocks for EXP_REUSE
93 * AC-3 encoder private context.
95 typedef struct AC3EncodeContext {
96 AVClass *av_class; ///< AVClass used for AVOption
97 AC3EncOptions options; ///< encoding options
98 PutBitContext pb; ///< bitstream writer context
100 AC3DSPContext ac3dsp; ///< AC-3 optimized functions
101 AC3MDCTContext mdct; ///< MDCT context
103 AC3Block blocks[AC3_MAX_BLOCKS]; ///< per-block info
105 int bitstream_id; ///< bitstream id (bsid)
106 int bitstream_mode; ///< bitstream mode (bsmod)
108 int bit_rate; ///< target bit rate, in bits-per-second
109 int sample_rate; ///< sampling frequency, in Hz
111 int frame_size_min; ///< minimum frame size in case rounding is necessary
112 int frame_size; ///< current frame size in bytes
113 int frame_size_code; ///< frame size code (frmsizecod)
115 int bits_written; ///< bit count (used to avg. bitrate)
116 int samples_written; ///< sample count (used to avg. bitrate)
118 int fbw_channels; ///< number of full-bandwidth channels (nfchans)
119 int channels; ///< total number of channels (nchans)
120 int lfe_on; ///< indicates if there is an LFE channel (lfeon)
121 int lfe_channel; ///< channel index of the LFE channel
122 int has_center; ///< indicates if there is a center channel
123 int has_surround; ///< indicates if there are one or more surround channels
124 int channel_mode; ///< channel mode (acmod)
125 const uint8_t *channel_map; ///< channel map used to reorder channels
127 int center_mix_level; ///< center mix level code
128 int surround_mix_level; ///< surround mix level code
129 int ltrt_center_mix_level; ///< Lt/Rt center mix level code
130 int ltrt_surround_mix_level; ///< Lt/Rt surround mix level code
131 int loro_center_mix_level; ///< Lo/Ro center mix level code
132 int loro_surround_mix_level; ///< Lo/Ro surround mix level code
134 int cutoff; ///< user-specified cutoff frequency, in Hz
135 int bandwidth_code; ///< bandwidth code (0 to 60) (chbwcod)
136 int nb_coefs[AC3_MAX_CHANNELS];
138 int rematrixing_enabled; ///< stereo rematrixing enabled
139 int num_rematrixing_bands; ///< number of rematrixing bands
141 /* bitrate allocation control */
142 int slow_gain_code; ///< slow gain code (sgaincod)
143 int slow_decay_code; ///< slow decay code (sdcycod)
144 int fast_decay_code; ///< fast decay code (fdcycod)
145 int db_per_bit_code; ///< dB/bit code (dbpbcod)
146 int floor_code; ///< floor code (floorcod)
147 AC3BitAllocParameters bit_alloc; ///< bit allocation parameters
148 int coarse_snr_offset; ///< coarse SNR offsets (csnroffst)
149 int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signal-to-mask ratio) (fgaincod)
150 int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst)
151 int frame_bits_fixed; ///< number of non-coefficient bits for fixed parameters
152 int frame_bits; ///< all frame bits except exponents and mantissas
153 int exponent_bits; ///< number of bits used for exponents
155 SampleType **planar_samples;
157 uint8_t *bap1_buffer;
158 CoefType *mdct_coef_buffer;
159 int32_t *fixed_coef_buffer;
161 uint8_t *grouped_exp_buffer;
163 int16_t *band_psd_buffer;
164 int16_t *mask_buffer;
165 uint16_t *qmant_buffer;
167 uint8_t exp_strategy[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< exponent strategies
169 DECLARE_ALIGNED(32, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
172 typedef struct AC3Mant {
173 uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
174 int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
177 #define CMIXLEV_NUM_OPTIONS 3
178 static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
179 LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
182 #define SURMIXLEV_NUM_OPTIONS 3
183 static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
184 LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
187 #define EXTMIXLEV_NUM_OPTIONS 8
188 static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
189 LEVEL_PLUS_3DB, LEVEL_PLUS_1POINT5DB, LEVEL_ONE, LEVEL_MINUS_4POINT5DB,
190 LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
194 #define OFFSET(param) offsetof(AC3EncodeContext, options.param)
195 #define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
197 #if CONFIG_AC3ENC_FLOAT || !CONFIG_AC3_FLOAT_ENCODER //we need this exactly once compiled in
198 const AVOption ff_ac3_options[] = {
199 /* Metadata Options */
200 {"per_frame_metadata", "Allow Changing Metadata Per-Frame", OFFSET(allow_per_frame_metadata), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 1, AC3ENC_PARAM},
202 {"center_mixlev", "Center Mix Level", OFFSET(center_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = LEVEL_MINUS_4POINT5DB }, 0.0, 1.0, AC3ENC_PARAM},
203 {"surround_mixlev", "Surround Mix Level", OFFSET(surround_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = LEVEL_MINUS_6DB }, 0.0, 1.0, AC3ENC_PARAM},
204 /* audio production information */
205 {"mixing_level", "Mixing Level", OFFSET(mixing_level), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 111, AC3ENC_PARAM},
206 {"room_type", "Room Type", OFFSET(room_type), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "room_type"},
207 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
208 {"large", "Large Room", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
209 {"small", "Small Room", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
210 /* other metadata options */
211 {"copyright", "Copyright Bit", OFFSET(copyright), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 1, AC3ENC_PARAM},
212 {"dialnorm", "Dialogue Level (dB)", OFFSET(dialogue_level), FF_OPT_TYPE_INT, {.dbl = -31 }, -31, -1, AC3ENC_PARAM},
213 {"dsur_mode", "Dolby Surround Mode", OFFSET(dolby_surround_mode), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 2, AC3ENC_PARAM, "dsur_mode"},
214 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
215 {"on", "Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
216 {"off", "Not Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
217 {"original", "Original Bit Stream", OFFSET(original), FF_OPT_TYPE_INT, {.dbl = 1 }, 0, 1, AC3ENC_PARAM},
218 /* extended bitstream information */
219 {"dmix_mode", "Preferred Stereo Downmix Mode", OFFSET(preferred_stereo_downmix), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dmix_mode"},
220 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
221 {"ltrt", "Lt/Rt Downmix Preferred", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
222 {"loro", "Lo/Ro Downmix Preferred", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
223 {"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},
224 {"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},
225 {"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},
226 {"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},
227 {"dsurex_mode", "Dolby Surround EX Mode", OFFSET(dolby_surround_ex_mode), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dsurex_mode"},
228 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
229 {"on", "Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
230 {"off", "Not Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
231 {"dheadphone_mode", "Dolby Headphone Mode", OFFSET(dolby_headphone_mode), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dheadphone_mode"},
232 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
233 {"on", "Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
234 {"off", "Not Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
235 {"ad_conv_type", "A/D Converter Type", OFFSET(ad_converter_type), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 1, AC3ENC_PARAM, "ad_conv_type"},
236 {"standard", "Standard (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
237 {"hdcd", "HDCD", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
238 /* Other Encoding Options */
239 {"stereo_rematrixing", "Stereo Rematrixing", OFFSET(stereo_rematrixing), FF_OPT_TYPE_INT, {.dbl = 1 }, 0, 1, AC3ENC_PARAM},
244 #if CONFIG_AC3ENC_FLOAT
245 static AVClass ac3enc_class = { "AC-3 Encoder", av_default_item_name,
246 ff_ac3_options, LIBAVUTIL_VERSION_INT };
248 static AVClass ac3enc_class = { "Fixed-Point AC-3 Encoder", av_default_item_name,
249 ff_ac3_options, LIBAVUTIL_VERSION_INT };
253 /* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
255 static av_cold void mdct_end(AC3MDCTContext *mdct);
257 static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
260 static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
261 const SampleType *window, unsigned int len);
263 static int normalize_samples(AC3EncodeContext *s);
265 static void scale_coefficients(AC3EncodeContext *s);
269 * LUT for number of exponent groups.
270 * exponent_group_tab[exponent strategy-1][number of coefficients]
272 static uint8_t exponent_group_tab[3][256];
276 * List of supported channel layouts.
278 #if CONFIG_AC3ENC_FLOAT || !CONFIG_AC3_FLOAT_ENCODER //we need this exactly once compiled in
279 const int64_t ff_ac3_channel_layouts[] = {
283 AV_CH_LAYOUT_SURROUND,
286 AV_CH_LAYOUT_4POINT0,
287 AV_CH_LAYOUT_5POINT0,
288 AV_CH_LAYOUT_5POINT0_BACK,
289 (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
290 (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
291 (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
292 (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
293 (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
294 (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
295 (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
296 AV_CH_LAYOUT_5POINT1,
297 AV_CH_LAYOUT_5POINT1_BACK,
304 * LUT to select the bandwidth code based on the bit rate, sample rate, and
305 * number of full-bandwidth channels.
306 * bandwidth_tab[fbw_channels-1][sample rate code][bit rate code]
308 static const uint8_t ac3_bandwidth_tab[5][3][19] = {
309 // 32 40 48 56 64 80 96 112 128 160 192 224 256 320 384 448 512 576 640
311 { { 0, 0, 0, 12, 16, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
312 { 0, 0, 0, 16, 20, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
313 { 0, 0, 0, 32, 40, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
315 { { 0, 0, 0, 0, 0, 0, 0, 20, 24, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
316 { 0, 0, 0, 0, 0, 0, 4, 24, 28, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
317 { 0, 0, 0, 0, 0, 0, 20, 44, 52, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
319 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 24, 32, 40, 48, 48, 48, 48, 48, 48 },
320 { 0, 0, 0, 0, 0, 0, 0, 0, 4, 20, 28, 36, 44, 56, 56, 56, 56, 56, 56 },
321 { 0, 0, 0, 0, 0, 0, 0, 0, 20, 40, 48, 60, 60, 60, 60, 60, 60, 60, 60 } },
323 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 32, 48, 48, 48, 48, 48, 48 },
324 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 28, 36, 56, 56, 56, 56, 56, 56 },
325 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 48, 60, 60, 60, 60, 60, 60, 60 } },
327 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 20, 32, 40, 48, 48, 48, 48 },
328 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 36, 44, 56, 56, 56, 56 },
329 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 44, 60, 60, 60, 60, 60, 60 } }
334 * Adjust the frame size to make the average bit rate match the target bit rate.
335 * This is only needed for 11025, 22050, and 44100 sample rates.
337 static void adjust_frame_size(AC3EncodeContext *s)
339 while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
340 s->bits_written -= s->bit_rate;
341 s->samples_written -= s->sample_rate;
343 s->frame_size = s->frame_size_min +
344 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
345 s->bits_written += s->frame_size * 8;
346 s->samples_written += AC3_FRAME_SIZE;
351 * Deinterleave input samples.
352 * Channels are reordered from FFmpeg's default order to AC-3 order.
354 static void deinterleave_input_samples(AC3EncodeContext *s,
355 const SampleType *samples)
359 /* deinterleave and remap input samples */
360 for (ch = 0; ch < s->channels; ch++) {
361 const SampleType *sptr;
364 /* copy last 256 samples of previous frame to the start of the current frame */
365 memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
366 AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
370 sptr = samples + s->channel_map[ch];
371 for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
372 s->planar_samples[ch][i] = *sptr;
380 * Apply the MDCT to input samples to generate frequency coefficients.
381 * This applies the KBD window and normalizes the input to reduce precision
382 * loss due to fixed-point calculations.
384 static void apply_mdct(AC3EncodeContext *s)
388 for (ch = 0; ch < s->channels; ch++) {
389 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
390 AC3Block *block = &s->blocks[blk];
391 const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
393 apply_window(&s->dsp, s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
395 block->coeff_shift[ch] = normalize_samples(s);
397 s->mdct.fft.mdct_calcw(&s->mdct.fft, block->mdct_coef[ch],
398 s->windowed_samples);
405 * Determine rematrixing flags for each block and band.
407 static void compute_rematrixing_strategy(AC3EncodeContext *s)
411 AC3Block *block, *block0;
413 if (s->channel_mode != AC3_CHMODE_STEREO)
416 s->num_rematrixing_bands = 4;
418 nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
420 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
421 block = &s->blocks[blk];
422 block->new_rematrixing_strategy = !blk;
423 if (!s->rematrixing_enabled)
425 for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
426 /* calculate calculate sum of squared coeffs for one band in one block */
427 int start = ff_ac3_rematrix_band_tab[bnd];
428 int end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
429 CoefSumType sum[4] = {0,};
430 for (i = start; i < end; i++) {
431 CoefType lt = block->mdct_coef[0][i];
432 CoefType rt = block->mdct_coef[1][i];
433 CoefType md = lt + rt;
434 CoefType sd = lt - rt;
435 MAC_COEF(sum[0], lt, lt);
436 MAC_COEF(sum[1], rt, rt);
437 MAC_COEF(sum[2], md, md);
438 MAC_COEF(sum[3], sd, sd);
441 /* compare sums to determine if rematrixing will be used for this band */
442 if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
443 block->rematrixing_flags[bnd] = 1;
445 block->rematrixing_flags[bnd] = 0;
447 /* determine if new rematrixing flags will be sent */
449 block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
450 block->new_rematrixing_strategy = 1;
459 * Apply stereo rematrixing to coefficients based on rematrixing flags.
461 static void apply_rematrixing(AC3EncodeContext *s)
468 if (!s->rematrixing_enabled)
471 nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
473 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
474 AC3Block *block = &s->blocks[blk];
475 if (block->new_rematrixing_strategy)
476 flags = block->rematrixing_flags;
477 for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
479 start = ff_ac3_rematrix_band_tab[bnd];
480 end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
481 for (i = start; i < end; i++) {
482 int32_t lt = block->fixed_coef[0][i];
483 int32_t rt = block->fixed_coef[1][i];
484 block->fixed_coef[0][i] = (lt + rt) >> 1;
485 block->fixed_coef[1][i] = (lt - rt) >> 1;
494 * Initialize exponent tables.
496 static av_cold void exponent_init(AC3EncodeContext *s)
498 int expstr, i, grpsize;
500 for (expstr = EXP_D15-1; expstr <= EXP_D45-1; expstr++) {
501 grpsize = 3 << expstr;
502 for (i = 73; i < 256; i++) {
503 exponent_group_tab[expstr][i] = (i + grpsize - 4) / grpsize;
507 exponent_group_tab[0][7] = 2;
512 * Extract exponents from the MDCT coefficients.
513 * This takes into account the normalization that was done to the input samples
514 * by adjusting the exponents by the exponent shift values.
516 static void extract_exponents(AC3EncodeContext *s)
520 for (ch = 0; ch < s->channels; ch++) {
521 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
522 AC3Block *block = &s->blocks[blk];
523 s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch],
531 * Exponent Difference Threshold.
532 * New exponents are sent if their SAD exceed this number.
534 #define EXP_DIFF_THRESHOLD 500
538 * Calculate exponent strategies for all channels.
539 * Array arrangement is reversed to simplify the per-channel calculation.
541 static void compute_exp_strategy(AC3EncodeContext *s)
545 for (ch = 0; ch < s->fbw_channels; ch++) {
546 uint8_t *exp_strategy = s->exp_strategy[ch];
547 uint8_t *exp = s->blocks[0].exp[ch];
550 /* estimate if the exponent variation & decide if they should be
551 reused in the next frame */
552 exp_strategy[0] = EXP_NEW;
553 exp += AC3_MAX_COEFS;
554 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
555 exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
556 if (exp_diff > EXP_DIFF_THRESHOLD)
557 exp_strategy[blk] = EXP_NEW;
559 exp_strategy[blk] = EXP_REUSE;
560 exp += AC3_MAX_COEFS;
563 /* now select the encoding strategy type : if exponents are often
564 recoded, we use a coarse encoding */
566 while (blk < AC3_MAX_BLOCKS) {
568 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
570 switch (blk1 - blk) {
571 case 1: exp_strategy[blk] = EXP_D45; break;
573 case 3: exp_strategy[blk] = EXP_D25; break;
574 default: exp_strategy[blk] = EXP_D15; break;
581 s->exp_strategy[ch][0] = EXP_D15;
582 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
583 s->exp_strategy[ch][blk] = EXP_REUSE;
589 * Update the exponents so that they are the ones the decoder will decode.
591 static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy)
595 nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
597 /* for each group, compute the minimum exponent */
598 switch(exp_strategy) {
600 for (i = 1, k = 1; i <= nb_groups; i++) {
601 uint8_t exp_min = exp[k];
602 if (exp[k+1] < exp_min)
609 for (i = 1, k = 1; i <= nb_groups; i++) {
610 uint8_t exp_min = exp[k];
611 if (exp[k+1] < exp_min)
613 if (exp[k+2] < exp_min)
615 if (exp[k+3] < exp_min)
623 /* constraint for DC exponent */
627 /* decrease the delta between each groups to within 2 so that they can be
628 differentially encoded */
629 for (i = 1; i <= nb_groups; i++)
630 exp[i] = FFMIN(exp[i], exp[i-1] + 2);
633 exp[i] = FFMIN(exp[i], exp[i+1] + 2);
635 /* now we have the exponent values the decoder will see */
636 switch (exp_strategy) {
638 for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
639 uint8_t exp1 = exp[i];
645 for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
646 exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
655 * Encode exponents from original extracted form to what the decoder will see.
656 * This copies and groups exponents based on exponent strategy and reduces
657 * deltas between adjacent exponent groups so that they can be differentially
660 static void encode_exponents(AC3EncodeContext *s)
663 uint8_t *exp, *exp_strategy;
664 int nb_coefs, num_reuse_blocks;
666 for (ch = 0; ch < s->channels; ch++) {
667 exp = s->blocks[0].exp[ch];
668 exp_strategy = s->exp_strategy[ch];
669 nb_coefs = s->nb_coefs[ch];
672 while (blk < AC3_MAX_BLOCKS) {
675 /* count the number of EXP_REUSE blocks after the current block
676 and set exponent reference block pointers */
677 s->blocks[blk].exp_ref_block[ch] = &s->blocks[blk];
678 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
679 s->blocks[blk1].exp_ref_block[ch] = &s->blocks[blk];
682 num_reuse_blocks = blk1 - blk - 1;
684 /* for the EXP_REUSE case we select the min of the exponents */
685 s->ac3dsp.ac3_exponent_min(exp, num_reuse_blocks, nb_coefs);
687 encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk]);
689 exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
698 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
699 * varies depending on exponent strategy and bandwidth.
701 static void group_exponents(AC3EncodeContext *s)
704 int group_size, nb_groups, bit_count;
706 int delta0, delta1, delta2;
710 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
711 AC3Block *block = &s->blocks[blk];
712 for (ch = 0; ch < s->channels; ch++) {
713 int exp_strategy = s->exp_strategy[ch][blk];
714 if (exp_strategy == EXP_REUSE)
716 group_size = exp_strategy + (exp_strategy == EXP_D45);
717 nb_groups = exponent_group_tab[exp_strategy-1][s->nb_coefs[ch]];
718 bit_count += 4 + (nb_groups * 7);
723 block->grouped_exp[ch][0] = exp1;
725 /* remaining exponents are delta encoded */
726 for (i = 1; i <= nb_groups; i++) {
727 /* merge three delta in one code */
731 delta0 = exp1 - exp0 + 2;
732 av_assert2(delta0 >= 0 && delta0 <= 4);
737 delta1 = exp1 - exp0 + 2;
738 av_assert2(delta1 >= 0 && delta1 <= 4);
743 delta2 = exp1 - exp0 + 2;
744 av_assert2(delta2 >= 0 && delta2 <= 4);
746 block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
751 s->exponent_bits = bit_count;
756 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
757 * Extract exponents from MDCT coefficients, calculate exponent strategies,
758 * and encode final exponents.
760 static void process_exponents(AC3EncodeContext *s)
762 extract_exponents(s);
764 compute_exp_strategy(s);
775 * Count frame bits that are based solely on fixed parameters.
776 * This only has to be run once when the encoder is initialized.
778 static void count_frame_bits_fixed(AC3EncodeContext *s)
780 static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
785 * no dynamic range codes
786 * no channel coupling
787 * bit allocation parameters do not change between blocks
788 * SNR offsets do not change between blocks
789 * no delta bit allocation
796 frame_bits += frame_bits_inc[s->channel_mode];
799 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
800 frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
801 if (s->channel_mode == AC3_CHMODE_STEREO) {
802 frame_bits++; /* rematstr */
804 frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
806 frame_bits++; /* lfeexpstr */
807 frame_bits++; /* baie */
808 frame_bits++; /* snr */
809 frame_bits += 2; /* delta / skip */
811 frame_bits++; /* cplinu for block 0 */
813 /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
815 /* (fsnoffset[4] + fgaincod[4]) * c */
816 frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
818 /* auxdatae, crcrsv */
824 s->frame_bits_fixed = frame_bits;
829 * Initialize bit allocation.
830 * Set default parameter codes and calculate parameter values.
832 static void bit_alloc_init(AC3EncodeContext *s)
836 /* init default parameters */
837 s->slow_decay_code = 2;
838 s->fast_decay_code = 1;
839 s->slow_gain_code = 1;
840 s->db_per_bit_code = 3;
842 for (ch = 0; ch < s->channels; ch++)
843 s->fast_gain_code[ch] = 4;
845 /* initial snr offset */
846 s->coarse_snr_offset = 40;
848 /* compute real values */
849 /* currently none of these values change during encoding, so we can just
850 set them once at initialization */
851 s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
852 s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
853 s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
854 s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
855 s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
857 count_frame_bits_fixed(s);
862 * Count the bits used to encode the frame, minus exponents and mantissas.
863 * Bits based on fixed parameters have already been counted, so now we just
864 * have to add the bits based on parameters that change during encoding.
866 static void count_frame_bits(AC3EncodeContext *s)
868 AC3EncOptions *opt = &s->options;
872 if (opt->audio_production_info)
874 if (s->bitstream_id == 6) {
875 if (opt->extended_bsi_1)
877 if (opt->extended_bsi_2)
881 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
882 /* stereo rematrixing */
883 if (s->channel_mode == AC3_CHMODE_STEREO &&
884 s->blocks[blk].new_rematrixing_strategy) {
885 frame_bits += s->num_rematrixing_bands;
888 for (ch = 0; ch < s->fbw_channels; ch++) {
889 if (s->exp_strategy[ch][blk] != EXP_REUSE)
890 frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
893 s->frame_bits = s->frame_bits_fixed + frame_bits;
898 * Finalize the mantissa bit count by adding in the grouped mantissas.
900 static int compute_mantissa_size_final(int mant_cnt[5])
902 // bap=1 : 3 mantissas in 5 bits
903 int bits = (mant_cnt[1] / 3) * 5;
904 // bap=2 : 3 mantissas in 7 bits
905 // bap=4 : 2 mantissas in 7 bits
906 bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
907 // bap=3 : each mantissa is 3 bits
908 bits += mant_cnt[3] * 3;
914 * Calculate masking curve based on the final exponents.
915 * Also calculate the power spectral densities to use in future calculations.
917 static void bit_alloc_masking(AC3EncodeContext *s)
921 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
922 AC3Block *block = &s->blocks[blk];
923 for (ch = 0; ch < s->channels; ch++) {
924 /* We only need psd and mask for calculating bap.
925 Since we currently do not calculate bap when exponent
926 strategy is EXP_REUSE we do not need to calculate psd or mask. */
927 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
928 ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
930 block->psd[ch], block->band_psd[ch]);
931 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
933 ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
934 ch == s->lfe_channel,
935 DBA_NONE, 0, NULL, NULL, NULL,
944 * Ensure that bap for each block and channel point to the current bap_buffer.
945 * They may have been switched during the bit allocation search.
947 static void reset_block_bap(AC3EncodeContext *s)
950 if (s->blocks[0].bap[0] == s->bap_buffer)
952 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
953 for (ch = 0; ch < s->channels; ch++) {
954 s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
961 * Run the bit allocation with a given SNR offset.
962 * This calculates the bit allocation pointers that will be used to determine
963 * the quantization of each mantissa.
964 * @return the number of bits needed for mantissas if the given SNR offset is
967 static int bit_alloc(AC3EncodeContext *s, int snr_offset)
973 snr_offset = (snr_offset - 240) << 2;
977 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
978 AC3Block *block = &s->blocks[blk];
980 // initialize grouped mantissa counts. these are set so that they are
981 // padded to the next whole group size when bits are counted in
982 // compute_mantissa_size_final
983 mant_cnt[0] = mant_cnt[3] = 0;
984 mant_cnt[1] = mant_cnt[2] = 2;
986 for (ch = 0; ch < s->channels; ch++) {
987 /* Currently the only bit allocation parameters which vary across
988 blocks within a frame are the exponent values. We can take
989 advantage of that by reusing the bit allocation pointers
990 whenever we reuse exponents. */
991 ref_block = block->exp_ref_block[ch];
992 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
993 s->ac3dsp.bit_alloc_calc_bap(ref_block->mask[ch],
994 ref_block->psd[ch], 0,
995 s->nb_coefs[ch], snr_offset,
996 s->bit_alloc.floor, ff_ac3_bap_tab,
999 mantissa_bits += s->ac3dsp.compute_mantissa_size(mant_cnt,
1003 mantissa_bits += compute_mantissa_size_final(mant_cnt);
1005 return mantissa_bits;
1010 * Constant bitrate bit allocation search.
1011 * Find the largest SNR offset that will allow data to fit in the frame.
1013 static int cbr_bit_allocation(AC3EncodeContext *s)
1017 int snr_offset, snr_incr;
1019 bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1021 return AVERROR(EINVAL);
1023 snr_offset = s->coarse_snr_offset << 4;
1025 /* if previous frame SNR offset was 1023, check if current frame can also
1026 use SNR offset of 1023. if so, skip the search. */
1027 if ((snr_offset | s->fine_snr_offset[0]) == 1023) {
1028 if (bit_alloc(s, 1023) <= bits_left)
1032 while (snr_offset >= 0 &&
1033 bit_alloc(s, snr_offset) > bits_left) {
1037 return AVERROR(EINVAL);
1039 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1040 for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1041 while (snr_offset + snr_incr <= 1023 &&
1042 bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1043 snr_offset += snr_incr;
1044 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1047 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1050 s->coarse_snr_offset = snr_offset >> 4;
1051 for (ch = 0; ch < s->channels; ch++)
1052 s->fine_snr_offset[ch] = snr_offset & 0xF;
1059 * Downgrade exponent strategies to reduce the bits used by the exponents.
1060 * This is a fallback for when bit allocation fails with the normal exponent
1061 * strategies. Each time this function is run it only downgrades the
1062 * strategy in 1 channel of 1 block.
1063 * @return non-zero if downgrade was unsuccessful
1065 static int downgrade_exponents(AC3EncodeContext *s)
1069 for (ch = 0; ch < s->fbw_channels; ch++) {
1070 for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1071 if (s->exp_strategy[ch][blk] == EXP_D15) {
1072 s->exp_strategy[ch][blk] = EXP_D25;
1077 for (ch = 0; ch < s->fbw_channels; ch++) {
1078 for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1079 if (s->exp_strategy[ch][blk] == EXP_D25) {
1080 s->exp_strategy[ch][blk] = EXP_D45;
1085 for (ch = 0; ch < s->fbw_channels; ch++) {
1086 /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
1087 the block number > 0 */
1088 for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
1089 if (s->exp_strategy[ch][blk] > EXP_REUSE) {
1090 s->exp_strategy[ch][blk] = EXP_REUSE;
1100 * Perform bit allocation search.
1101 * Finds the SNR offset value that maximizes quality and fits in the specified
1102 * frame size. Output is the SNR offset and a set of bit allocation pointers
1103 * used to quantize the mantissas.
1105 static int compute_bit_allocation(AC3EncodeContext *s)
1109 count_frame_bits(s);
1111 bit_alloc_masking(s);
1113 ret = cbr_bit_allocation(s);
1115 /* fallback 1: downgrade exponents */
1116 if (!downgrade_exponents(s)) {
1117 extract_exponents(s);
1118 encode_exponents(s);
1120 ret = compute_bit_allocation(s);
1124 /* fallbacks were not enough... */
1133 * Symmetric quantization on 'levels' levels.
1135 static inline int sym_quant(int c, int e, int levels)
1137 int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1138 av_assert2(v >= 0 && v < levels);
1144 * Asymmetric quantization on 2^qbits levels.
1146 static inline int asym_quant(int c, int e, int qbits)
1150 lshift = e + qbits - 24;
1157 m = (1 << (qbits-1));
1160 av_assert2(v >= -m);
1161 return v & ((1 << qbits)-1);
1166 * Quantize a set of mantissas for a single channel in a single block.
1168 static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1170 uint8_t *bap, uint16_t *qmant, int n)
1174 for (i = 0; i < n; i++) {
1176 int c = fixed_coef[i];
1184 v = sym_quant(c, e, 3);
1185 switch (s->mant1_cnt) {
1187 s->qmant1_ptr = &qmant[i];
1192 *s->qmant1_ptr += 3 * v;
1197 *s->qmant1_ptr += v;
1204 v = sym_quant(c, e, 5);
1205 switch (s->mant2_cnt) {
1207 s->qmant2_ptr = &qmant[i];
1212 *s->qmant2_ptr += 5 * v;
1217 *s->qmant2_ptr += v;
1224 v = sym_quant(c, e, 7);
1227 v = sym_quant(c, e, 11);
1228 switch (s->mant4_cnt) {
1230 s->qmant4_ptr = &qmant[i];
1235 *s->qmant4_ptr += v;
1242 v = sym_quant(c, e, 15);
1245 v = asym_quant(c, e, 14);
1248 v = asym_quant(c, e, 16);
1251 v = asym_quant(c, e, b - 1);
1260 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1262 static void quantize_mantissas(AC3EncodeContext *s)
1267 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1268 AC3Block *block = &s->blocks[blk];
1269 AC3Block *ref_block;
1272 for (ch = 0; ch < s->channels; ch++) {
1273 ref_block = block->exp_ref_block[ch];
1274 quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1275 ref_block->exp[ch], ref_block->bap[ch],
1276 block->qmant[ch], s->nb_coefs[ch]);
1283 * Write the AC-3 frame header to the output bitstream.
1285 static void output_frame_header(AC3EncodeContext *s)
1287 AC3EncOptions *opt = &s->options;
1289 put_bits(&s->pb, 16, 0x0b77); /* frame header */
1290 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
1291 put_bits(&s->pb, 2, s->bit_alloc.sr_code);
1292 put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1293 put_bits(&s->pb, 5, s->bitstream_id);
1294 put_bits(&s->pb, 3, s->bitstream_mode);
1295 put_bits(&s->pb, 3, s->channel_mode);
1296 if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1297 put_bits(&s->pb, 2, s->center_mix_level);
1298 if (s->channel_mode & 0x04)
1299 put_bits(&s->pb, 2, s->surround_mix_level);
1300 if (s->channel_mode == AC3_CHMODE_STEREO)
1301 put_bits(&s->pb, 2, opt->dolby_surround_mode);
1302 put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1303 put_bits(&s->pb, 5, -opt->dialogue_level);
1304 put_bits(&s->pb, 1, 0); /* no compression control word */
1305 put_bits(&s->pb, 1, 0); /* no lang code */
1306 put_bits(&s->pb, 1, opt->audio_production_info);
1307 if (opt->audio_production_info) {
1308 put_bits(&s->pb, 5, opt->mixing_level - 80);
1309 put_bits(&s->pb, 2, opt->room_type);
1311 put_bits(&s->pb, 1, opt->copyright);
1312 put_bits(&s->pb, 1, opt->original);
1313 if (s->bitstream_id == 6) {
1314 /* alternate bit stream syntax */
1315 put_bits(&s->pb, 1, opt->extended_bsi_1);
1316 if (opt->extended_bsi_1) {
1317 put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1318 put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1319 put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1320 put_bits(&s->pb, 3, s->loro_center_mix_level);
1321 put_bits(&s->pb, 3, s->loro_surround_mix_level);
1323 put_bits(&s->pb, 1, opt->extended_bsi_2);
1324 if (opt->extended_bsi_2) {
1325 put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1326 put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1327 put_bits(&s->pb, 1, opt->ad_converter_type);
1328 put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
1331 put_bits(&s->pb, 1, 0); /* no time code 1 */
1332 put_bits(&s->pb, 1, 0); /* no time code 2 */
1334 put_bits(&s->pb, 1, 0); /* no additional bit stream info */
1339 * Write one audio block to the output bitstream.
1341 static void output_audio_block(AC3EncodeContext *s, int blk)
1343 int ch, i, baie, rbnd;
1344 AC3Block *block = &s->blocks[blk];
1346 /* block switching */
1347 for (ch = 0; ch < s->fbw_channels; ch++)
1348 put_bits(&s->pb, 1, 0);
1351 for (ch = 0; ch < s->fbw_channels; ch++)
1352 put_bits(&s->pb, 1, 1);
1354 /* dynamic range codes */
1355 put_bits(&s->pb, 1, 0);
1357 /* channel coupling */
1359 put_bits(&s->pb, 1, 1); /* coupling strategy present */
1360 put_bits(&s->pb, 1, 0); /* no coupling strategy */
1362 put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1365 /* stereo rematrixing */
1366 if (s->channel_mode == AC3_CHMODE_STEREO) {
1367 put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1368 if (block->new_rematrixing_strategy) {
1369 /* rematrixing flags */
1370 for (rbnd = 0; rbnd < s->num_rematrixing_bands; rbnd++)
1371 put_bits(&s->pb, 1, block->rematrixing_flags[rbnd]);
1375 /* exponent strategy */
1376 for (ch = 0; ch < s->fbw_channels; ch++)
1377 put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1379 put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1382 for (ch = 0; ch < s->fbw_channels; ch++) {
1383 if (s->exp_strategy[ch][blk] != EXP_REUSE)
1384 put_bits(&s->pb, 6, s->bandwidth_code);
1388 for (ch = 0; ch < s->channels; ch++) {
1391 if (s->exp_strategy[ch][blk] == EXP_REUSE)
1395 put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1397 /* exponent groups */
1398 nb_groups = exponent_group_tab[s->exp_strategy[ch][blk]-1][s->nb_coefs[ch]];
1399 for (i = 1; i <= nb_groups; i++)
1400 put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1402 /* gain range info */
1403 if (ch != s->lfe_channel)
1404 put_bits(&s->pb, 2, 0);
1407 /* bit allocation info */
1409 put_bits(&s->pb, 1, baie);
1411 put_bits(&s->pb, 2, s->slow_decay_code);
1412 put_bits(&s->pb, 2, s->fast_decay_code);
1413 put_bits(&s->pb, 2, s->slow_gain_code);
1414 put_bits(&s->pb, 2, s->db_per_bit_code);
1415 put_bits(&s->pb, 3, s->floor_code);
1419 put_bits(&s->pb, 1, baie);
1421 put_bits(&s->pb, 6, s->coarse_snr_offset);
1422 for (ch = 0; ch < s->channels; ch++) {
1423 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1424 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1428 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1429 put_bits(&s->pb, 1, 0); /* no data to skip */
1432 for (ch = 0; ch < s->channels; ch++) {
1434 AC3Block *ref_block = block->exp_ref_block[ch];
1435 for (i = 0; i < s->nb_coefs[ch]; i++) {
1436 q = block->qmant[ch][i];
1437 b = ref_block->bap[ch][i];
1440 case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
1441 case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
1442 case 3: put_bits(&s->pb, 3, q); break;
1443 case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
1444 case 14: put_bits(&s->pb, 14, q); break;
1445 case 15: put_bits(&s->pb, 16, q); break;
1446 default: put_bits(&s->pb, b-1, q); break;
1453 /** CRC-16 Polynomial */
1454 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1457 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1474 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1480 r = mul_poly(r, a, poly);
1481 a = mul_poly(a, a, poly);
1489 * Fill the end of the frame with 0's and compute the two CRCs.
1491 static void output_frame_end(AC3EncodeContext *s)
1493 const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1494 int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1497 frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1499 /* pad the remainder of the frame with zeros */
1500 av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1501 flush_put_bits(&s->pb);
1503 pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1504 av_assert2(pad_bytes >= 0);
1506 memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1509 /* this is not so easy because it is at the beginning of the data... */
1510 crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1511 crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1512 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1513 AV_WB16(frame + 2, crc1);
1516 crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1517 s->frame_size - frame_size_58 - 3);
1518 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1519 /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1520 if (crc2 == 0x770B) {
1521 frame[s->frame_size - 3] ^= 0x1;
1522 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1524 crc2 = av_bswap16(crc2);
1525 AV_WB16(frame + s->frame_size - 2, crc2);
1530 * Write the frame to the output bitstream.
1532 static void output_frame(AC3EncodeContext *s, unsigned char *frame)
1536 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1538 output_frame_header(s);
1540 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1541 output_audio_block(s, blk);
1543 output_frame_end(s);
1547 static void dprint_options(AVCodecContext *avctx)
1550 AC3EncodeContext *s = avctx->priv_data;
1551 AC3EncOptions *opt = &s->options;
1554 switch (s->bitstream_id) {
1555 case 6: av_strlcpy(strbuf, "AC-3 (alt syntax)", 32); break;
1556 case 8: av_strlcpy(strbuf, "AC-3 (standard)", 32); break;
1557 case 9: av_strlcpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
1558 case 10: av_strlcpy(strbuf, "AC-3 (dnet quater-rate", 32); break;
1559 default: snprintf(strbuf, 32, "ERROR");
1561 av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
1562 av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
1563 av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
1564 av_dlog(avctx, "channel_layout: %s\n", strbuf);
1565 av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
1566 av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
1568 av_dlog(avctx, "cutoff: %d\n", s->cutoff);
1570 av_dlog(avctx, "per_frame_metadata: %s\n",
1571 opt->allow_per_frame_metadata?"on":"off");
1573 av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
1574 s->center_mix_level);
1576 av_dlog(avctx, "center_mixlev: {not written}\n");
1577 if (s->has_surround)
1578 av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
1579 s->surround_mix_level);
1581 av_dlog(avctx, "surround_mixlev: {not written}\n");
1582 if (opt->audio_production_info) {
1583 av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
1584 switch (opt->room_type) {
1585 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1586 case 1: av_strlcpy(strbuf, "large", 32); break;
1587 case 2: av_strlcpy(strbuf, "small", 32); break;
1588 default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
1590 av_dlog(avctx, "room_type: %s\n", strbuf);
1592 av_dlog(avctx, "mixing_level: {not written}\n");
1593 av_dlog(avctx, "room_type: {not written}\n");
1595 av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
1596 av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
1597 if (s->channel_mode == AC3_CHMODE_STEREO) {
1598 switch (opt->dolby_surround_mode) {
1599 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1600 case 1: av_strlcpy(strbuf, "on", 32); break;
1601 case 2: av_strlcpy(strbuf, "off", 32); break;
1602 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
1604 av_dlog(avctx, "dsur_mode: %s\n", strbuf);
1606 av_dlog(avctx, "dsur_mode: {not written}\n");
1608 av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
1610 if (s->bitstream_id == 6) {
1611 if (opt->extended_bsi_1) {
1612 switch (opt->preferred_stereo_downmix) {
1613 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1614 case 1: av_strlcpy(strbuf, "ltrt", 32); break;
1615 case 2: av_strlcpy(strbuf, "loro", 32); break;
1616 default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
1618 av_dlog(avctx, "dmix_mode: %s\n", strbuf);
1619 av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
1620 opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
1621 av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
1622 opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
1623 av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
1624 opt->loro_center_mix_level, s->loro_center_mix_level);
1625 av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
1626 opt->loro_surround_mix_level, s->loro_surround_mix_level);
1628 av_dlog(avctx, "extended bitstream info 1: {not written}\n");
1630 if (opt->extended_bsi_2) {
1631 switch (opt->dolby_surround_ex_mode) {
1632 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1633 case 1: av_strlcpy(strbuf, "on", 32); break;
1634 case 2: av_strlcpy(strbuf, "off", 32); break;
1635 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
1637 av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
1638 switch (opt->dolby_headphone_mode) {
1639 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1640 case 1: av_strlcpy(strbuf, "on", 32); break;
1641 case 2: av_strlcpy(strbuf, "off", 32); break;
1642 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
1644 av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
1646 switch (opt->ad_converter_type) {
1647 case 0: av_strlcpy(strbuf, "standard", 32); break;
1648 case 1: av_strlcpy(strbuf, "hdcd", 32); break;
1649 default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
1651 av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
1653 av_dlog(avctx, "extended bitstream info 2: {not written}\n");
1660 #define FLT_OPTION_THRESHOLD 0.01
1662 static int validate_float_option(float v, const float *v_list, int v_list_size)
1666 for (i = 0; i < v_list_size; i++) {
1667 if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
1668 v > (v_list[i] - FLT_OPTION_THRESHOLD))
1671 if (i == v_list_size)
1678 static void validate_mix_level(void *log_ctx, const char *opt_name,
1679 float *opt_param, const float *list,
1680 int list_size, int default_value, int min_value,
1683 int mixlev = validate_float_option(*opt_param, list, list_size);
1684 if (mixlev < min_value) {
1685 mixlev = default_value;
1686 if (*opt_param >= 0.0) {
1687 av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
1688 "default value: %0.3f\n", opt_name, list[mixlev]);
1691 *opt_param = list[mixlev];
1692 *ctx_param = mixlev;
1697 * Validate metadata options as set by AVOption system.
1698 * These values can optionally be changed per-frame.
1700 static int validate_metadata(AVCodecContext *avctx)
1702 AC3EncodeContext *s = avctx->priv_data;
1703 AC3EncOptions *opt = &s->options;
1705 /* validate mixing levels */
1706 if (s->has_center) {
1707 validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
1708 cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
1709 &s->center_mix_level);
1711 if (s->has_surround) {
1712 validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
1713 surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
1714 &s->surround_mix_level);
1717 /* set audio production info flag */
1718 if (opt->mixing_level >= 0 || opt->room_type >= 0) {
1719 if (opt->mixing_level < 0) {
1720 av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
1721 "room_type is set\n");
1722 return AVERROR(EINVAL);
1724 if (opt->mixing_level < 80) {
1725 av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
1726 "80dB and 111dB\n");
1727 return AVERROR(EINVAL);
1729 /* default room type */
1730 if (opt->room_type < 0)
1732 opt->audio_production_info = 1;
1734 opt->audio_production_info = 0;
1737 /* set extended bsi 1 flag */
1738 if ((s->has_center || s->has_surround) &&
1739 (opt->preferred_stereo_downmix >= 0 ||
1740 opt->ltrt_center_mix_level >= 0 ||
1741 opt->ltrt_surround_mix_level >= 0 ||
1742 opt->loro_center_mix_level >= 0 ||
1743 opt->loro_surround_mix_level >= 0)) {
1744 /* default preferred stereo downmix */
1745 if (opt->preferred_stereo_downmix < 0)
1746 opt->preferred_stereo_downmix = 0;
1747 /* validate Lt/Rt center mix level */
1748 validate_mix_level(avctx, "ltrt_center_mix_level",
1749 &opt->ltrt_center_mix_level, extmixlev_options,
1750 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1751 &s->ltrt_center_mix_level);
1752 /* validate Lt/Rt surround mix level */
1753 validate_mix_level(avctx, "ltrt_surround_mix_level",
1754 &opt->ltrt_surround_mix_level, extmixlev_options,
1755 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1756 &s->ltrt_surround_mix_level);
1757 /* validate Lo/Ro center mix level */
1758 validate_mix_level(avctx, "loro_center_mix_level",
1759 &opt->loro_center_mix_level, extmixlev_options,
1760 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1761 &s->loro_center_mix_level);
1762 /* validate Lo/Ro surround mix level */
1763 validate_mix_level(avctx, "loro_surround_mix_level",
1764 &opt->loro_surround_mix_level, extmixlev_options,
1765 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1766 &s->loro_surround_mix_level);
1767 opt->extended_bsi_1 = 1;
1769 opt->extended_bsi_1 = 0;
1772 /* set extended bsi 2 flag */
1773 if (opt->dolby_surround_ex_mode >= 0 ||
1774 opt->dolby_headphone_mode >= 0 ||
1775 opt->ad_converter_type >= 0) {
1776 /* default dolby surround ex mode */
1777 if (opt->dolby_surround_ex_mode < 0)
1778 opt->dolby_surround_ex_mode = 0;
1779 /* default dolby headphone mode */
1780 if (opt->dolby_headphone_mode < 0)
1781 opt->dolby_headphone_mode = 0;
1782 /* default A/D converter type */
1783 if (opt->ad_converter_type < 0)
1784 opt->ad_converter_type = 0;
1785 opt->extended_bsi_2 = 1;
1787 opt->extended_bsi_2 = 0;
1790 /* set bitstream id for alternate bitstream syntax */
1791 if (opt->extended_bsi_1 || opt->extended_bsi_2) {
1792 if (s->bitstream_id > 8 && s->bitstream_id < 11) {
1793 static int warn_once = 1;
1795 av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
1796 "not compatible with reduced samplerates. writing of "
1797 "extended bitstream information will be disabled.\n");
1801 s->bitstream_id = 6;
1810 * Encode a single AC-3 frame.
1812 static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
1813 int buf_size, void *data)
1815 AC3EncodeContext *s = avctx->priv_data;
1816 const SampleType *samples = data;
1819 if (s->options.allow_per_frame_metadata) {
1820 ret = validate_metadata(avctx);
1825 if (s->bit_alloc.sr_code == 1)
1826 adjust_frame_size(s);
1828 deinterleave_input_samples(s, samples);
1832 scale_coefficients(s);
1834 compute_rematrixing_strategy(s);
1836 apply_rematrixing(s);
1838 process_exponents(s);
1840 ret = compute_bit_allocation(s);
1842 av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1846 quantize_mantissas(s);
1848 output_frame(s, frame);
1850 return s->frame_size;
1855 * Finalize encoding and free any memory allocated by the encoder.
1857 static av_cold int ac3_encode_close(AVCodecContext *avctx)
1860 AC3EncodeContext *s = avctx->priv_data;
1862 for (ch = 0; ch < s->channels; ch++)
1863 av_freep(&s->planar_samples[ch]);
1864 av_freep(&s->planar_samples);
1865 av_freep(&s->bap_buffer);
1866 av_freep(&s->bap1_buffer);
1867 av_freep(&s->mdct_coef_buffer);
1868 av_freep(&s->fixed_coef_buffer);
1869 av_freep(&s->exp_buffer);
1870 av_freep(&s->grouped_exp_buffer);
1871 av_freep(&s->psd_buffer);
1872 av_freep(&s->band_psd_buffer);
1873 av_freep(&s->mask_buffer);
1874 av_freep(&s->qmant_buffer);
1875 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1876 AC3Block *block = &s->blocks[blk];
1877 av_freep(&block->bap);
1878 av_freep(&block->mdct_coef);
1879 av_freep(&block->fixed_coef);
1880 av_freep(&block->exp);
1881 av_freep(&block->grouped_exp);
1882 av_freep(&block->psd);
1883 av_freep(&block->band_psd);
1884 av_freep(&block->mask);
1885 av_freep(&block->qmant);
1890 av_freep(&avctx->coded_frame);
1896 * Set channel information during initialization.
1898 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1899 int64_t *channel_layout)
1903 if (channels < 1 || channels > AC3_MAX_CHANNELS)
1904 return AVERROR(EINVAL);
1905 if ((uint64_t)*channel_layout > 0x7FF)
1906 return AVERROR(EINVAL);
1907 ch_layout = *channel_layout;
1909 ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1911 s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1912 s->channels = channels;
1913 s->fbw_channels = channels - s->lfe_on;
1914 s->lfe_channel = s->lfe_on ? s->fbw_channels : -1;
1916 ch_layout -= AV_CH_LOW_FREQUENCY;
1918 switch (ch_layout) {
1919 case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
1920 case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
1921 case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
1922 case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
1923 case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
1924 case AV_CH_LAYOUT_QUAD:
1925 case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
1926 case AV_CH_LAYOUT_5POINT0:
1927 case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
1929 return AVERROR(EINVAL);
1931 s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
1932 s->has_surround = s->channel_mode & 0x04;
1934 s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1935 *channel_layout = ch_layout;
1937 *channel_layout |= AV_CH_LOW_FREQUENCY;
1943 static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1947 /* validate channel layout */
1948 if (!avctx->channel_layout) {
1949 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1950 "encoder will guess the layout, but it "
1951 "might be incorrect.\n");
1953 ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1955 av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1959 /* validate sample rate */
1960 for (i = 0; i < 9; i++) {
1961 if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
1965 av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1966 return AVERROR(EINVAL);
1968 s->sample_rate = avctx->sample_rate;
1969 s->bit_alloc.sr_shift = i % 3;
1970 s->bit_alloc.sr_code = i / 3;
1971 s->bitstream_id = 8 + s->bit_alloc.sr_shift;
1973 /* validate bit rate */
1974 for (i = 0; i < 19; i++) {
1975 if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
1979 av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
1980 return AVERROR(EINVAL);
1982 s->bit_rate = avctx->bit_rate;
1983 s->frame_size_code = i << 1;
1985 /* validate cutoff */
1986 if (avctx->cutoff < 0) {
1987 av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
1988 return AVERROR(EINVAL);
1990 s->cutoff = avctx->cutoff;
1991 if (s->cutoff > (s->sample_rate >> 1))
1992 s->cutoff = s->sample_rate >> 1;
1994 /* validate audio service type / channels combination */
1995 if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
1996 avctx->channels == 1) ||
1997 ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
1998 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
1999 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
2000 && avctx->channels > 1)) {
2001 av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
2002 "specified number of channels\n");
2003 return AVERROR(EINVAL);
2006 ret = validate_metadata(avctx);
2010 s->rematrixing_enabled = s->options.stereo_rematrixing &&
2011 (s->channel_mode == AC3_CHMODE_STEREO);
2018 * Set bandwidth for all channels.
2019 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2020 * default value will be used.
2022 static av_cold void set_bandwidth(AC3EncodeContext *s)
2027 /* calculate bandwidth based on user-specified cutoff frequency */
2029 fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2030 s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2032 /* use default bandwidth setting */
2033 s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2036 /* set number of coefficients for each channel */
2037 for (ch = 0; ch < s->fbw_channels; ch++) {
2038 s->nb_coefs[ch] = s->bandwidth_code * 3 + 73;
2041 s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
2045 static av_cold int allocate_buffers(AVCodecContext *avctx)
2048 AC3EncodeContext *s = avctx->priv_data;
2050 FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
2052 for (ch = 0; ch < s->channels; ch++) {
2053 FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
2054 (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
2057 FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * s->channels *
2058 AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
2059 FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
2060 AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
2061 FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
2062 AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
2063 FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
2064 AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
2065 FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
2066 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
2067 FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
2068 AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
2069 FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
2070 64 * sizeof(*s->band_psd_buffer), alloc_fail);
2071 FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
2072 64 * sizeof(*s->mask_buffer), alloc_fail);
2073 FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
2074 AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
2075 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2076 AC3Block *block = &s->blocks[blk];
2077 FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
2079 FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
2081 FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
2083 FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
2085 FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
2087 FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
2089 FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
2091 FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
2094 for (ch = 0; ch < s->channels; ch++) {
2095 /* arrangement: block, channel, coeff */
2096 block->bap[ch] = &s->bap_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2097 block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2098 block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * s->channels + ch)];
2099 block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2100 block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * s->channels + ch)];
2101 block->mask[ch] = &s->mask_buffer [64 * (blk * s->channels + ch)];
2102 block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2104 /* arrangement: channel, block, coeff */
2105 block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2109 if (CONFIG_AC3ENC_FLOAT) {
2110 FF_ALLOC_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * s->channels *
2111 AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
2112 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2113 AC3Block *block = &s->blocks[blk];
2114 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2115 sizeof(*block->fixed_coef), alloc_fail);
2116 for (ch = 0; ch < s->channels; ch++)
2117 block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
2120 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2121 AC3Block *block = &s->blocks[blk];
2122 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2123 sizeof(*block->fixed_coef), alloc_fail);
2124 for (ch = 0; ch < s->channels; ch++)
2125 block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2131 return AVERROR(ENOMEM);
2136 * Initialize the encoder.
2138 static av_cold int ac3_encode_init(AVCodecContext *avctx)
2140 AC3EncodeContext *s = avctx->priv_data;
2141 int ret, frame_size_58;
2143 avctx->frame_size = AC3_FRAME_SIZE;
2145 ff_ac3_common_init();
2147 ret = validate_options(avctx, s);
2151 s->bitstream_mode = avctx->audio_service_type;
2152 if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2153 s->bitstream_mode = 0x7;
2155 s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2156 s->bits_written = 0;
2157 s->samples_written = 0;
2158 s->frame_size = s->frame_size_min;
2160 /* calculate crc_inv for both possible frame sizes */
2161 frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
2162 s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2163 if (s->bit_alloc.sr_code == 1) {
2164 frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2165 s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2174 ret = mdct_init(avctx, &s->mdct, 9);
2178 ret = allocate_buffers(avctx);
2182 avctx->coded_frame= avcodec_alloc_frame();
2184 dsputil_init(&s->dsp, avctx);
2185 ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2187 dprint_options(avctx);
2191 ac3_encode_close(avctx);