2 * The simplest AC-3 encoder
3 * Copyright (c) 2000 Fabrice Bellard
4 * Copyright (c) 2006-2010 Justin Ruggles <justin.ruggles@gmail.com>
5 * Copyright (c) 2006-2010 Prakash Punnoor <prakash@punnoor.de>
7 * This file is part of Libav.
9 * Libav is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * Libav is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with Libav; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 * The simplest AC-3 encoder.
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 * Encoding Options used by AVOption.
76 typedef struct AC3EncOptions {
77 /* AC-3 metadata options*/
80 float center_mix_level;
81 float surround_mix_level;
82 int dolby_surround_mode;
83 int audio_production_info;
89 int preferred_stereo_downmix;
90 float ltrt_center_mix_level;
91 float ltrt_surround_mix_level;
92 float loro_center_mix_level;
93 float loro_surround_mix_level;
95 int dolby_surround_ex_mode;
96 int dolby_headphone_mode;
97 int ad_converter_type;
99 /* other encoding options */
100 int allow_per_frame_metadata;
101 int stereo_rematrixing;
105 * Data for a single audio block.
107 typedef struct AC3Block {
108 uint8_t **bap; ///< bit allocation pointers (bap)
109 CoefType **mdct_coef; ///< MDCT coefficients
110 int32_t **fixed_coef; ///< fixed-point MDCT coefficients
111 uint8_t **exp; ///< original exponents
112 uint8_t **grouped_exp; ///< grouped exponents
113 int16_t **psd; ///< psd per frequency bin
114 int16_t **band_psd; ///< psd per critical band
115 int16_t **mask; ///< masking curve
116 uint16_t **qmant; ///< quantized mantissas
117 uint8_t coeff_shift[AC3_MAX_CHANNELS]; ///< fixed-point coefficient shift values
118 uint8_t new_rematrixing_strategy; ///< send new rematrixing flags in this block
119 uint8_t rematrixing_flags[4]; ///< rematrixing flags
120 struct AC3Block *exp_ref_block[AC3_MAX_CHANNELS]; ///< reference blocks for EXP_REUSE
124 * AC-3 encoder private context.
126 typedef struct AC3EncodeContext {
127 AVClass *av_class; ///< AVClass used for AVOption
128 AC3EncOptions options; ///< encoding options
129 PutBitContext pb; ///< bitstream writer context
131 AC3DSPContext ac3dsp; ///< AC-3 optimized functions
132 AC3MDCTContext mdct; ///< MDCT context
134 AC3Block blocks[AC3_MAX_BLOCKS]; ///< per-block info
136 int bitstream_id; ///< bitstream id (bsid)
137 int bitstream_mode; ///< bitstream mode (bsmod)
139 int bit_rate; ///< target bit rate, in bits-per-second
140 int sample_rate; ///< sampling frequency, in Hz
142 int frame_size_min; ///< minimum frame size in case rounding is necessary
143 int frame_size; ///< current frame size in bytes
144 int frame_size_code; ///< frame size code (frmsizecod)
146 int bits_written; ///< bit count (used to avg. bitrate)
147 int samples_written; ///< sample count (used to avg. bitrate)
149 int fbw_channels; ///< number of full-bandwidth channels (nfchans)
150 int channels; ///< total number of channels (nchans)
151 int lfe_on; ///< indicates if there is an LFE channel (lfeon)
152 int lfe_channel; ///< channel index of the LFE channel
153 int has_center; ///< indicates if there is a center channel
154 int has_surround; ///< indicates if there are one or more surround channels
155 int channel_mode; ///< channel mode (acmod)
156 const uint8_t *channel_map; ///< channel map used to reorder channels
158 int center_mix_level; ///< center mix level code
159 int surround_mix_level; ///< surround mix level code
160 int ltrt_center_mix_level; ///< Lt/Rt center mix level code
161 int ltrt_surround_mix_level; ///< Lt/Rt surround mix level code
162 int loro_center_mix_level; ///< Lo/Ro center mix level code
163 int loro_surround_mix_level; ///< Lo/Ro surround mix level code
165 int cutoff; ///< user-specified cutoff frequency, in Hz
166 int bandwidth_code; ///< bandwidth code (0 to 60) (chbwcod)
167 int nb_coefs[AC3_MAX_CHANNELS];
169 int rematrixing_enabled; ///< stereo rematrixing enabled
170 int num_rematrixing_bands; ///< number of rematrixing bands
172 /* bitrate allocation control */
173 int slow_gain_code; ///< slow gain code (sgaincod)
174 int slow_decay_code; ///< slow decay code (sdcycod)
175 int fast_decay_code; ///< fast decay code (fdcycod)
176 int db_per_bit_code; ///< dB/bit code (dbpbcod)
177 int floor_code; ///< floor code (floorcod)
178 AC3BitAllocParameters bit_alloc; ///< bit allocation parameters
179 int coarse_snr_offset; ///< coarse SNR offsets (csnroffst)
180 int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signal-to-mask ratio) (fgaincod)
181 int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst)
182 int frame_bits_fixed; ///< number of non-coefficient bits for fixed parameters
183 int frame_bits; ///< all frame bits except exponents and mantissas
184 int exponent_bits; ///< number of bits used for exponents
186 SampleType **planar_samples;
188 uint8_t *bap1_buffer;
189 CoefType *mdct_coef_buffer;
190 int32_t *fixed_coef_buffer;
192 uint8_t *grouped_exp_buffer;
194 int16_t *band_psd_buffer;
195 int16_t *mask_buffer;
196 uint16_t *qmant_buffer;
198 uint8_t exp_strategy[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< exponent strategies
200 DECLARE_ALIGNED(32, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
203 typedef struct AC3Mant {
204 uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
205 int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
208 #define CMIXLEV_NUM_OPTIONS 3
209 static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
210 LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
213 #define SURMIXLEV_NUM_OPTIONS 3
214 static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
215 LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
218 #define EXTMIXLEV_NUM_OPTIONS 8
219 static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
220 LEVEL_PLUS_3DB, LEVEL_PLUS_1POINT5DB, LEVEL_ONE, LEVEL_MINUS_4POINT5DB,
221 LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
225 #define OFFSET(param) offsetof(AC3EncodeContext, options.param)
226 #define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
228 static const AVOption options[] = {
229 /* Metadata Options */
230 {"per_frame_metadata", "Allow Changing Metadata Per-Frame", OFFSET(allow_per_frame_metadata), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 1, AC3ENC_PARAM},
232 {"center_mixlev", "Center Mix Level", OFFSET(center_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = LEVEL_MINUS_4POINT5DB }, 0.0, 1.0, AC3ENC_PARAM},
233 {"surround_mixlev", "Surround Mix Level", OFFSET(surround_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = LEVEL_MINUS_6DB }, 0.0, 1.0, AC3ENC_PARAM},
234 /* audio production information */
235 {"mixing_level", "Mixing Level", OFFSET(mixing_level), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 111, AC3ENC_PARAM},
236 {"room_type", "Room Type", OFFSET(room_type), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "room_type"},
237 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
238 {"large", "Large Room", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
239 {"small", "Small Room", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
240 /* other metadata options */
241 {"copyright", "Copyright Bit", OFFSET(copyright), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 1, AC3ENC_PARAM},
242 {"dialnorm", "Dialogue Level (dB)", OFFSET(dialogue_level), FF_OPT_TYPE_INT, {.dbl = -31 }, -31, -1, AC3ENC_PARAM},
243 {"dsur_mode", "Dolby Surround Mode", OFFSET(dolby_surround_mode), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 2, AC3ENC_PARAM, "dsur_mode"},
244 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
245 {"on", "Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
246 {"off", "Not Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
247 {"original", "Original Bit Stream", OFFSET(original), FF_OPT_TYPE_INT, {.dbl = 1 }, 0, 1, AC3ENC_PARAM},
248 /* extended bitstream information */
249 {"dmix_mode", "Preferred Stereo Downmix Mode", OFFSET(preferred_stereo_downmix), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dmix_mode"},
250 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
251 {"ltrt", "Lt/Rt Downmix Preferred", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
252 {"loro", "Lo/Ro Downmix Preferred", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
253 {"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},
254 {"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},
255 {"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},
256 {"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},
257 {"dsurex_mode", "Dolby Surround EX Mode", OFFSET(dolby_surround_ex_mode), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dsurex_mode"},
258 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
259 {"on", "Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
260 {"off", "Not Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
261 {"dheadphone_mode", "Dolby Headphone Mode", OFFSET(dolby_headphone_mode), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dheadphone_mode"},
262 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
263 {"on", "Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
264 {"off", "Not Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
265 {"ad_conv_type", "A/D Converter Type", OFFSET(ad_converter_type), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 1, AC3ENC_PARAM, "ad_conv_type"},
266 {"standard", "Standard (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
267 {"hdcd", "HDCD", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
268 /* Other Encoding Options */
269 {"stereo_rematrixing", "Stereo Rematrixing", OFFSET(stereo_rematrixing), FF_OPT_TYPE_INT, {.dbl = 1 }, 0, 1, AC3ENC_PARAM},
273 #if CONFIG_AC3ENC_FLOAT
274 static AVClass ac3enc_class = { "AC-3 Encoder", av_default_item_name,
275 options, LIBAVUTIL_VERSION_INT };
277 static AVClass ac3enc_class = { "Fixed-Point AC-3 Encoder", av_default_item_name,
278 options, LIBAVUTIL_VERSION_INT };
282 /* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
284 static av_cold void mdct_end(AC3MDCTContext *mdct);
286 static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
289 static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
290 const SampleType *window, unsigned int len);
292 static int normalize_samples(AC3EncodeContext *s);
294 static void scale_coefficients(AC3EncodeContext *s);
298 * LUT for number of exponent groups.
299 * exponent_group_tab[exponent strategy-1][number of coefficients]
301 static uint8_t exponent_group_tab[3][256];
305 * List of supported channel layouts.
307 static const int64_t ac3_channel_layouts[] = {
311 AV_CH_LAYOUT_SURROUND,
314 AV_CH_LAYOUT_4POINT0,
315 AV_CH_LAYOUT_5POINT0,
316 AV_CH_LAYOUT_5POINT0_BACK,
317 (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
318 (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
319 (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
320 (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
321 (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
322 (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
323 (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
324 AV_CH_LAYOUT_5POINT1,
325 AV_CH_LAYOUT_5POINT1_BACK,
331 * LUT to select the bandwidth code based on the bit rate, sample rate, and
332 * number of full-bandwidth channels.
333 * bandwidth_tab[fbw_channels-1][sample rate code][bit rate code]
335 static const uint8_t ac3_bandwidth_tab[5][3][19] = {
336 // 32 40 48 56 64 80 96 112 128 160 192 224 256 320 384 448 512 576 640
338 { { 0, 0, 0, 12, 16, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
339 { 0, 0, 0, 16, 20, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
340 { 0, 0, 0, 32, 40, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
342 { { 0, 0, 0, 0, 0, 0, 0, 20, 24, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
343 { 0, 0, 0, 0, 0, 0, 4, 24, 28, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
344 { 0, 0, 0, 0, 0, 0, 20, 44, 52, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
346 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 24, 32, 40, 48, 48, 48, 48, 48, 48 },
347 { 0, 0, 0, 0, 0, 0, 0, 0, 4, 20, 28, 36, 44, 56, 56, 56, 56, 56, 56 },
348 { 0, 0, 0, 0, 0, 0, 0, 0, 20, 40, 48, 60, 60, 60, 60, 60, 60, 60, 60 } },
350 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 32, 48, 48, 48, 48, 48, 48 },
351 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 28, 36, 56, 56, 56, 56, 56, 56 },
352 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 48, 60, 60, 60, 60, 60, 60, 60 } },
354 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 20, 32, 40, 48, 48, 48, 48 },
355 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 36, 44, 56, 56, 56, 56 },
356 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 44, 60, 60, 60, 60, 60, 60 } }
361 * Adjust the frame size to make the average bit rate match the target bit rate.
362 * This is only needed for 11025, 22050, and 44100 sample rates.
364 static void adjust_frame_size(AC3EncodeContext *s)
366 while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
367 s->bits_written -= s->bit_rate;
368 s->samples_written -= s->sample_rate;
370 s->frame_size = s->frame_size_min +
371 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
372 s->bits_written += s->frame_size * 8;
373 s->samples_written += AC3_FRAME_SIZE;
378 * Deinterleave input samples.
379 * Channels are reordered from Libav's default order to AC-3 order.
381 static void deinterleave_input_samples(AC3EncodeContext *s,
382 const SampleType *samples)
386 /* deinterleave and remap input samples */
387 for (ch = 0; ch < s->channels; ch++) {
388 const SampleType *sptr;
391 /* copy last 256 samples of previous frame to the start of the current frame */
392 memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
393 AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
397 sptr = samples + s->channel_map[ch];
398 for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
399 s->planar_samples[ch][i] = *sptr;
407 * Apply the MDCT to input samples to generate frequency coefficients.
408 * This applies the KBD window and normalizes the input to reduce precision
409 * loss due to fixed-point calculations.
411 static void apply_mdct(AC3EncodeContext *s)
415 for (ch = 0; ch < s->channels; ch++) {
416 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
417 AC3Block *block = &s->blocks[blk];
418 const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
420 apply_window(&s->dsp, s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
422 block->coeff_shift[ch] = normalize_samples(s);
424 s->mdct.fft.mdct_calcw(&s->mdct.fft, block->mdct_coef[ch],
425 s->windowed_samples);
432 * Determine rematrixing flags for each block and band.
434 static void compute_rematrixing_strategy(AC3EncodeContext *s)
438 AC3Block *block, *block0;
440 if (s->channel_mode != AC3_CHMODE_STEREO)
443 s->num_rematrixing_bands = 4;
445 nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
447 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
448 block = &s->blocks[blk];
449 block->new_rematrixing_strategy = !blk;
450 if (!s->rematrixing_enabled)
452 for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
453 /* calculate calculate sum of squared coeffs for one band in one block */
454 int start = ff_ac3_rematrix_band_tab[bnd];
455 int end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
456 CoefSumType sum[4] = {0,};
457 for (i = start; i < end; i++) {
458 CoefType lt = block->mdct_coef[0][i];
459 CoefType rt = block->mdct_coef[1][i];
460 CoefType md = lt + rt;
461 CoefType sd = lt - rt;
462 MAC_COEF(sum[0], lt, lt);
463 MAC_COEF(sum[1], rt, rt);
464 MAC_COEF(sum[2], md, md);
465 MAC_COEF(sum[3], sd, sd);
468 /* compare sums to determine if rematrixing will be used for this band */
469 if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
470 block->rematrixing_flags[bnd] = 1;
472 block->rematrixing_flags[bnd] = 0;
474 /* determine if new rematrixing flags will be sent */
476 block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
477 block->new_rematrixing_strategy = 1;
486 * Apply stereo rematrixing to coefficients based on rematrixing flags.
488 static void apply_rematrixing(AC3EncodeContext *s)
495 if (!s->rematrixing_enabled)
498 nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
500 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
501 AC3Block *block = &s->blocks[blk];
502 if (block->new_rematrixing_strategy)
503 flags = block->rematrixing_flags;
504 for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
506 start = ff_ac3_rematrix_band_tab[bnd];
507 end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
508 for (i = start; i < end; i++) {
509 int32_t lt = block->fixed_coef[0][i];
510 int32_t rt = block->fixed_coef[1][i];
511 block->fixed_coef[0][i] = (lt + rt) >> 1;
512 block->fixed_coef[1][i] = (lt - rt) >> 1;
521 * Initialize exponent tables.
523 static av_cold void exponent_init(AC3EncodeContext *s)
525 int expstr, i, grpsize;
527 for (expstr = EXP_D15-1; expstr <= EXP_D45-1; expstr++) {
528 grpsize = 3 << expstr;
529 for (i = 73; i < 256; i++) {
530 exponent_group_tab[expstr][i] = (i + grpsize - 4) / grpsize;
534 exponent_group_tab[0][7] = 2;
539 * Extract exponents from the MDCT coefficients.
540 * This takes into account the normalization that was done to the input samples
541 * by adjusting the exponents by the exponent shift values.
543 static void extract_exponents(AC3EncodeContext *s)
547 for (ch = 0; ch < s->channels; ch++) {
548 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
549 AC3Block *block = &s->blocks[blk];
550 s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch],
558 * Exponent Difference Threshold.
559 * New exponents are sent if their SAD exceed this number.
561 #define EXP_DIFF_THRESHOLD 500
565 * Calculate exponent strategies for all channels.
566 * Array arrangement is reversed to simplify the per-channel calculation.
568 static void compute_exp_strategy(AC3EncodeContext *s)
572 for (ch = 0; ch < s->fbw_channels; ch++) {
573 uint8_t *exp_strategy = s->exp_strategy[ch];
574 uint8_t *exp = s->blocks[0].exp[ch];
577 /* estimate if the exponent variation & decide if they should be
578 reused in the next frame */
579 exp_strategy[0] = EXP_NEW;
580 exp += AC3_MAX_COEFS;
581 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
582 exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
583 if (exp_diff > EXP_DIFF_THRESHOLD)
584 exp_strategy[blk] = EXP_NEW;
586 exp_strategy[blk] = EXP_REUSE;
587 exp += AC3_MAX_COEFS;
590 /* now select the encoding strategy type : if exponents are often
591 recoded, we use a coarse encoding */
593 while (blk < AC3_MAX_BLOCKS) {
595 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
597 switch (blk1 - blk) {
598 case 1: exp_strategy[blk] = EXP_D45; break;
600 case 3: exp_strategy[blk] = EXP_D25; break;
601 default: exp_strategy[blk] = EXP_D15; break;
608 s->exp_strategy[ch][0] = EXP_D15;
609 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
610 s->exp_strategy[ch][blk] = EXP_REUSE;
616 * Update the exponents so that they are the ones the decoder will decode.
618 static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy)
622 nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
624 /* for each group, compute the minimum exponent */
625 switch(exp_strategy) {
627 for (i = 1, k = 1; i <= nb_groups; i++) {
628 uint8_t exp_min = exp[k];
629 if (exp[k+1] < exp_min)
636 for (i = 1, k = 1; i <= nb_groups; i++) {
637 uint8_t exp_min = exp[k];
638 if (exp[k+1] < exp_min)
640 if (exp[k+2] < exp_min)
642 if (exp[k+3] < exp_min)
650 /* constraint for DC exponent */
654 /* decrease the delta between each groups to within 2 so that they can be
655 differentially encoded */
656 for (i = 1; i <= nb_groups; i++)
657 exp[i] = FFMIN(exp[i], exp[i-1] + 2);
660 exp[i] = FFMIN(exp[i], exp[i+1] + 2);
662 /* now we have the exponent values the decoder will see */
663 switch (exp_strategy) {
665 for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
666 uint8_t exp1 = exp[i];
672 for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
673 exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
682 * Encode exponents from original extracted form to what the decoder will see.
683 * This copies and groups exponents based on exponent strategy and reduces
684 * deltas between adjacent exponent groups so that they can be differentially
687 static void encode_exponents(AC3EncodeContext *s)
690 uint8_t *exp, *exp_strategy;
691 int nb_coefs, num_reuse_blocks;
693 for (ch = 0; ch < s->channels; ch++) {
694 exp = s->blocks[0].exp[ch];
695 exp_strategy = s->exp_strategy[ch];
696 nb_coefs = s->nb_coefs[ch];
699 while (blk < AC3_MAX_BLOCKS) {
702 /* count the number of EXP_REUSE blocks after the current block
703 and set exponent reference block pointers */
704 s->blocks[blk].exp_ref_block[ch] = &s->blocks[blk];
705 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
706 s->blocks[blk1].exp_ref_block[ch] = &s->blocks[blk];
709 num_reuse_blocks = blk1 - blk - 1;
711 /* for the EXP_REUSE case we select the min of the exponents */
712 s->ac3dsp.ac3_exponent_min(exp, num_reuse_blocks, nb_coefs);
714 encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk]);
716 exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
725 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
726 * varies depending on exponent strategy and bandwidth.
728 static void group_exponents(AC3EncodeContext *s)
731 int group_size, nb_groups, bit_count;
733 int delta0, delta1, delta2;
737 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
738 AC3Block *block = &s->blocks[blk];
739 for (ch = 0; ch < s->channels; ch++) {
740 int exp_strategy = s->exp_strategy[ch][blk];
741 if (exp_strategy == EXP_REUSE)
743 group_size = exp_strategy + (exp_strategy == EXP_D45);
744 nb_groups = exponent_group_tab[exp_strategy-1][s->nb_coefs[ch]];
745 bit_count += 4 + (nb_groups * 7);
750 block->grouped_exp[ch][0] = exp1;
752 /* remaining exponents are delta encoded */
753 for (i = 1; i <= nb_groups; i++) {
754 /* merge three delta in one code */
758 delta0 = exp1 - exp0 + 2;
759 av_assert2(delta0 >= 0 && delta0 <= 4);
764 delta1 = exp1 - exp0 + 2;
765 av_assert2(delta1 >= 0 && delta1 <= 4);
770 delta2 = exp1 - exp0 + 2;
771 av_assert2(delta2 >= 0 && delta2 <= 4);
773 block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
778 s->exponent_bits = bit_count;
783 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
784 * Extract exponents from MDCT coefficients, calculate exponent strategies,
785 * and encode final exponents.
787 static void process_exponents(AC3EncodeContext *s)
789 extract_exponents(s);
791 compute_exp_strategy(s);
802 * Count frame bits that are based solely on fixed parameters.
803 * This only has to be run once when the encoder is initialized.
805 static void count_frame_bits_fixed(AC3EncodeContext *s)
807 static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
812 * no dynamic range codes
813 * no channel coupling
814 * bit allocation parameters do not change between blocks
815 * SNR offsets do not change between blocks
816 * no delta bit allocation
823 frame_bits += frame_bits_inc[s->channel_mode];
826 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
827 /* block switch flags */
828 frame_bits += s->fbw_channels;
831 frame_bits += s->fbw_channels;
836 /* coupling strategy */
841 /* stereo rematrixing */
842 if (s->channel_mode == AC3_CHMODE_STEREO)
845 /* exponent strategy */
846 frame_bits += 2 * s->fbw_channels;
850 /* bit allocation params */
853 frame_bits += 2 + 2 + 2 + 2 + 3;
855 /* snr offsets and fast gain codes */
858 frame_bits += 6 + s->channels * (4 + 3);
860 /* delta bit allocation */
871 frame_bits += 1 + 16;
873 s->frame_bits_fixed = frame_bits;
878 * Initialize bit allocation.
879 * Set default parameter codes and calculate parameter values.
881 static void bit_alloc_init(AC3EncodeContext *s)
885 /* init default parameters */
886 s->slow_decay_code = 2;
887 s->fast_decay_code = 1;
888 s->slow_gain_code = 1;
889 s->db_per_bit_code = 3;
891 for (ch = 0; ch < s->channels; ch++)
892 s->fast_gain_code[ch] = 4;
894 /* initial snr offset */
895 s->coarse_snr_offset = 40;
897 /* compute real values */
898 /* currently none of these values change during encoding, so we can just
899 set them once at initialization */
900 s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
901 s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
902 s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
903 s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
904 s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
906 count_frame_bits_fixed(s);
911 * Count the bits used to encode the frame, minus exponents and mantissas.
912 * Bits based on fixed parameters have already been counted, so now we just
913 * have to add the bits based on parameters that change during encoding.
915 static void count_frame_bits(AC3EncodeContext *s)
917 AC3EncOptions *opt = &s->options;
922 if (opt->audio_production_info)
924 if (s->bitstream_id == 6) {
925 if (opt->extended_bsi_1)
927 if (opt->extended_bsi_2)
932 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
933 /* stereo rematrixing */
934 if (s->channel_mode == AC3_CHMODE_STEREO &&
935 s->blocks[blk].new_rematrixing_strategy) {
936 frame_bits += s->num_rematrixing_bands;
939 /* bandwidth codes & gain range */
940 for (ch = 0; ch < s->fbw_channels; ch++) {
941 if (s->exp_strategy[ch][blk] != EXP_REUSE)
946 s->frame_bits = s->frame_bits_fixed + frame_bits;
951 * Finalize the mantissa bit count by adding in the grouped mantissas.
953 static int compute_mantissa_size_final(int mant_cnt[5])
955 // bap=1 : 3 mantissas in 5 bits
956 int bits = (mant_cnt[1] / 3) * 5;
957 // bap=2 : 3 mantissas in 7 bits
958 // bap=4 : 2 mantissas in 7 bits
959 bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
960 // bap=3 : each mantissa is 3 bits
961 bits += mant_cnt[3] * 3;
967 * Calculate masking curve based on the final exponents.
968 * Also calculate the power spectral densities to use in future calculations.
970 static void bit_alloc_masking(AC3EncodeContext *s)
974 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
975 AC3Block *block = &s->blocks[blk];
976 for (ch = 0; ch < s->channels; ch++) {
977 /* We only need psd and mask for calculating bap.
978 Since we currently do not calculate bap when exponent
979 strategy is EXP_REUSE we do not need to calculate psd or mask. */
980 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
981 ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
983 block->psd[ch], block->band_psd[ch]);
984 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
986 ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
987 ch == s->lfe_channel,
988 DBA_NONE, 0, NULL, NULL, NULL,
997 * Ensure that bap for each block and channel point to the current bap_buffer.
998 * They may have been switched during the bit allocation search.
1000 static void reset_block_bap(AC3EncodeContext *s)
1003 if (s->blocks[0].bap[0] == s->bap_buffer)
1005 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1006 for (ch = 0; ch < s->channels; ch++) {
1007 s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
1014 * Run the bit allocation with a given SNR offset.
1015 * This calculates the bit allocation pointers that will be used to determine
1016 * the quantization of each mantissa.
1017 * @return the number of bits needed for mantissas if the given SNR offset is
1020 static int bit_alloc(AC3EncodeContext *s, int snr_offset)
1026 snr_offset = (snr_offset - 240) << 2;
1030 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1031 AC3Block *block = &s->blocks[blk];
1032 AC3Block *ref_block;
1033 // initialize grouped mantissa counts. these are set so that they are
1034 // padded to the next whole group size when bits are counted in
1035 // compute_mantissa_size_final
1036 mant_cnt[0] = mant_cnt[3] = 0;
1037 mant_cnt[1] = mant_cnt[2] = 2;
1039 for (ch = 0; ch < s->channels; ch++) {
1040 /* Currently the only bit allocation parameters which vary across
1041 blocks within a frame are the exponent values. We can take
1042 advantage of that by reusing the bit allocation pointers
1043 whenever we reuse exponents. */
1044 ref_block = block->exp_ref_block[ch];
1045 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1046 s->ac3dsp.bit_alloc_calc_bap(ref_block->mask[ch],
1047 ref_block->psd[ch], 0,
1048 s->nb_coefs[ch], snr_offset,
1049 s->bit_alloc.floor, ff_ac3_bap_tab,
1050 ref_block->bap[ch]);
1052 mantissa_bits += s->ac3dsp.compute_mantissa_size(mant_cnt,
1056 mantissa_bits += compute_mantissa_size_final(mant_cnt);
1058 return mantissa_bits;
1063 * Constant bitrate bit allocation search.
1064 * Find the largest SNR offset that will allow data to fit in the frame.
1066 static int cbr_bit_allocation(AC3EncodeContext *s)
1070 int snr_offset, snr_incr;
1072 bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1074 return AVERROR(EINVAL);
1076 snr_offset = s->coarse_snr_offset << 4;
1078 /* if previous frame SNR offset was 1023, check if current frame can also
1079 use SNR offset of 1023. if so, skip the search. */
1080 if ((snr_offset | s->fine_snr_offset[0]) == 1023) {
1081 if (bit_alloc(s, 1023) <= bits_left)
1085 while (snr_offset >= 0 &&
1086 bit_alloc(s, snr_offset) > bits_left) {
1090 return AVERROR(EINVAL);
1092 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1093 for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1094 while (snr_offset + snr_incr <= 1023 &&
1095 bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1096 snr_offset += snr_incr;
1097 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1100 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1103 s->coarse_snr_offset = snr_offset >> 4;
1104 for (ch = 0; ch < s->channels; ch++)
1105 s->fine_snr_offset[ch] = snr_offset & 0xF;
1112 * Downgrade exponent strategies to reduce the bits used by the exponents.
1113 * This is a fallback for when bit allocation fails with the normal exponent
1114 * strategies. Each time this function is run it only downgrades the
1115 * strategy in 1 channel of 1 block.
1116 * @return non-zero if downgrade was unsuccessful
1118 static int downgrade_exponents(AC3EncodeContext *s)
1122 for (ch = 0; ch < s->fbw_channels; ch++) {
1123 for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1124 if (s->exp_strategy[ch][blk] == EXP_D15) {
1125 s->exp_strategy[ch][blk] = EXP_D25;
1130 for (ch = 0; ch < s->fbw_channels; ch++) {
1131 for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1132 if (s->exp_strategy[ch][blk] == EXP_D25) {
1133 s->exp_strategy[ch][blk] = EXP_D45;
1138 for (ch = 0; ch < s->fbw_channels; ch++) {
1139 /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
1140 the block number > 0 */
1141 for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
1142 if (s->exp_strategy[ch][blk] > EXP_REUSE) {
1143 s->exp_strategy[ch][blk] = EXP_REUSE;
1153 * Perform bit allocation search.
1154 * Finds the SNR offset value that maximizes quality and fits in the specified
1155 * frame size. Output is the SNR offset and a set of bit allocation pointers
1156 * used to quantize the mantissas.
1158 static int compute_bit_allocation(AC3EncodeContext *s)
1162 count_frame_bits(s);
1164 bit_alloc_masking(s);
1166 ret = cbr_bit_allocation(s);
1168 /* fallback 1: downgrade exponents */
1169 if (!downgrade_exponents(s)) {
1170 extract_exponents(s);
1171 encode_exponents(s);
1173 ret = compute_bit_allocation(s);
1177 /* fallbacks were not enough... */
1186 * Symmetric quantization on 'levels' levels.
1188 static inline int sym_quant(int c, int e, int levels)
1190 int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1191 av_assert2(v >= 0 && v < levels);
1197 * Asymmetric quantization on 2^qbits levels.
1199 static inline int asym_quant(int c, int e, int qbits)
1203 lshift = e + qbits - 24;
1210 m = (1 << (qbits-1));
1213 av_assert2(v >= -m);
1214 return v & ((1 << qbits)-1);
1219 * Quantize a set of mantissas for a single channel in a single block.
1221 static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1223 uint8_t *bap, uint16_t *qmant, int n)
1227 for (i = 0; i < n; i++) {
1229 int c = fixed_coef[i];
1237 v = sym_quant(c, e, 3);
1238 switch (s->mant1_cnt) {
1240 s->qmant1_ptr = &qmant[i];
1245 *s->qmant1_ptr += 3 * v;
1250 *s->qmant1_ptr += v;
1257 v = sym_quant(c, e, 5);
1258 switch (s->mant2_cnt) {
1260 s->qmant2_ptr = &qmant[i];
1265 *s->qmant2_ptr += 5 * v;
1270 *s->qmant2_ptr += v;
1277 v = sym_quant(c, e, 7);
1280 v = sym_quant(c, e, 11);
1281 switch (s->mant4_cnt) {
1283 s->qmant4_ptr = &qmant[i];
1288 *s->qmant4_ptr += v;
1295 v = sym_quant(c, e, 15);
1298 v = asym_quant(c, e, 14);
1301 v = asym_quant(c, e, 16);
1304 v = asym_quant(c, e, b - 1);
1313 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1315 static void quantize_mantissas(AC3EncodeContext *s)
1320 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1321 AC3Block *block = &s->blocks[blk];
1322 AC3Block *ref_block;
1325 for (ch = 0; ch < s->channels; ch++) {
1326 ref_block = block->exp_ref_block[ch];
1327 quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1328 ref_block->exp[ch], ref_block->bap[ch],
1329 block->qmant[ch], s->nb_coefs[ch]);
1336 * Write the AC-3 frame header to the output bitstream.
1338 static void output_frame_header(AC3EncodeContext *s)
1340 AC3EncOptions *opt = &s->options;
1342 put_bits(&s->pb, 16, 0x0b77); /* frame header */
1343 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
1344 put_bits(&s->pb, 2, s->bit_alloc.sr_code);
1345 put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1346 put_bits(&s->pb, 5, s->bitstream_id);
1347 put_bits(&s->pb, 3, s->bitstream_mode);
1348 put_bits(&s->pb, 3, s->channel_mode);
1349 if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1350 put_bits(&s->pb, 2, s->center_mix_level);
1351 if (s->channel_mode & 0x04)
1352 put_bits(&s->pb, 2, s->surround_mix_level);
1353 if (s->channel_mode == AC3_CHMODE_STEREO)
1354 put_bits(&s->pb, 2, opt->dolby_surround_mode);
1355 put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1356 put_bits(&s->pb, 5, -opt->dialogue_level);
1357 put_bits(&s->pb, 1, 0); /* no compression control word */
1358 put_bits(&s->pb, 1, 0); /* no lang code */
1359 put_bits(&s->pb, 1, opt->audio_production_info);
1360 if (opt->audio_production_info) {
1361 put_bits(&s->pb, 5, opt->mixing_level - 80);
1362 put_bits(&s->pb, 2, opt->room_type);
1364 put_bits(&s->pb, 1, opt->copyright);
1365 put_bits(&s->pb, 1, opt->original);
1366 if (s->bitstream_id == 6) {
1367 /* alternate bit stream syntax */
1368 put_bits(&s->pb, 1, opt->extended_bsi_1);
1369 if (opt->extended_bsi_1) {
1370 put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1371 put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1372 put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1373 put_bits(&s->pb, 3, s->loro_center_mix_level);
1374 put_bits(&s->pb, 3, s->loro_surround_mix_level);
1376 put_bits(&s->pb, 1, opt->extended_bsi_2);
1377 if (opt->extended_bsi_2) {
1378 put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1379 put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1380 put_bits(&s->pb, 1, opt->ad_converter_type);
1381 put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
1384 put_bits(&s->pb, 1, 0); /* no time code 1 */
1385 put_bits(&s->pb, 1, 0); /* no time code 2 */
1387 put_bits(&s->pb, 1, 0); /* no additional bit stream info */
1392 * Write one audio block to the output bitstream.
1394 static void output_audio_block(AC3EncodeContext *s, int blk)
1396 int ch, i, baie, rbnd;
1397 AC3Block *block = &s->blocks[blk];
1399 /* block switching */
1400 for (ch = 0; ch < s->fbw_channels; ch++)
1401 put_bits(&s->pb, 1, 0);
1404 for (ch = 0; ch < s->fbw_channels; ch++)
1405 put_bits(&s->pb, 1, 1);
1407 /* dynamic range codes */
1408 put_bits(&s->pb, 1, 0);
1410 /* channel coupling */
1412 put_bits(&s->pb, 1, 1); /* coupling strategy present */
1413 put_bits(&s->pb, 1, 0); /* no coupling strategy */
1415 put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1418 /* stereo rematrixing */
1419 if (s->channel_mode == AC3_CHMODE_STEREO) {
1420 put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1421 if (block->new_rematrixing_strategy) {
1422 /* rematrixing flags */
1423 for (rbnd = 0; rbnd < s->num_rematrixing_bands; rbnd++)
1424 put_bits(&s->pb, 1, block->rematrixing_flags[rbnd]);
1428 /* exponent strategy */
1429 for (ch = 0; ch < s->fbw_channels; ch++)
1430 put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1432 put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1435 for (ch = 0; ch < s->fbw_channels; ch++) {
1436 if (s->exp_strategy[ch][blk] != EXP_REUSE)
1437 put_bits(&s->pb, 6, s->bandwidth_code);
1441 for (ch = 0; ch < s->channels; ch++) {
1444 if (s->exp_strategy[ch][blk] == EXP_REUSE)
1448 put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1450 /* exponent groups */
1451 nb_groups = exponent_group_tab[s->exp_strategy[ch][blk]-1][s->nb_coefs[ch]];
1452 for (i = 1; i <= nb_groups; i++)
1453 put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1455 /* gain range info */
1456 if (ch != s->lfe_channel)
1457 put_bits(&s->pb, 2, 0);
1460 /* bit allocation info */
1462 put_bits(&s->pb, 1, baie);
1464 put_bits(&s->pb, 2, s->slow_decay_code);
1465 put_bits(&s->pb, 2, s->fast_decay_code);
1466 put_bits(&s->pb, 2, s->slow_gain_code);
1467 put_bits(&s->pb, 2, s->db_per_bit_code);
1468 put_bits(&s->pb, 3, s->floor_code);
1472 put_bits(&s->pb, 1, baie);
1474 put_bits(&s->pb, 6, s->coarse_snr_offset);
1475 for (ch = 0; ch < s->channels; ch++) {
1476 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1477 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1481 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1482 put_bits(&s->pb, 1, 0); /* no data to skip */
1485 for (ch = 0; ch < s->channels; ch++) {
1487 AC3Block *ref_block = block->exp_ref_block[ch];
1488 for (i = 0; i < s->nb_coefs[ch]; i++) {
1489 q = block->qmant[ch][i];
1490 b = ref_block->bap[ch][i];
1493 case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
1494 case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
1495 case 3: put_bits(&s->pb, 3, q); break;
1496 case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
1497 case 14: put_bits(&s->pb, 14, q); break;
1498 case 15: put_bits(&s->pb, 16, q); break;
1499 default: put_bits(&s->pb, b-1, q); break;
1506 /** CRC-16 Polynomial */
1507 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1510 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1527 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1533 r = mul_poly(r, a, poly);
1534 a = mul_poly(a, a, poly);
1542 * Fill the end of the frame with 0's and compute the two CRCs.
1544 static void output_frame_end(AC3EncodeContext *s)
1546 const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1547 int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1550 frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1552 /* pad the remainder of the frame with zeros */
1553 av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1554 flush_put_bits(&s->pb);
1556 pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1557 av_assert2(pad_bytes >= 0);
1559 memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1562 /* this is not so easy because it is at the beginning of the data... */
1563 crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1564 crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1565 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1566 AV_WB16(frame + 2, crc1);
1569 crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1570 s->frame_size - frame_size_58 - 3);
1571 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1572 /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1573 if (crc2 == 0x770B) {
1574 frame[s->frame_size - 3] ^= 0x1;
1575 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1577 crc2 = av_bswap16(crc2);
1578 AV_WB16(frame + s->frame_size - 2, crc2);
1583 * Write the frame to the output bitstream.
1585 static void output_frame(AC3EncodeContext *s, unsigned char *frame)
1589 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1591 output_frame_header(s);
1593 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1594 output_audio_block(s, blk);
1596 output_frame_end(s);
1600 static void dprint_options(AVCodecContext *avctx)
1603 AC3EncodeContext *s = avctx->priv_data;
1604 AC3EncOptions *opt = &s->options;
1607 switch (s->bitstream_id) {
1608 case 6: av_strlcpy(strbuf, "AC-3 (alt syntax)", 32); break;
1609 case 8: av_strlcpy(strbuf, "AC-3 (standard)", 32); break;
1610 case 9: av_strlcpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
1611 case 10: av_strlcpy(strbuf, "AC-3 (dnet quater-rate", 32); break;
1612 default: snprintf(strbuf, 32, "ERROR");
1614 av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
1615 av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
1616 av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
1617 av_dlog(avctx, "channel_layout: %s\n", strbuf);
1618 av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
1619 av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
1621 av_dlog(avctx, "cutoff: %d\n", s->cutoff);
1623 av_dlog(avctx, "per_frame_metadata: %s\n",
1624 opt->allow_per_frame_metadata?"on":"off");
1626 av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
1627 s->center_mix_level);
1629 av_dlog(avctx, "center_mixlev: {not written}\n");
1630 if (s->has_surround)
1631 av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
1632 s->surround_mix_level);
1634 av_dlog(avctx, "surround_mixlev: {not written}\n");
1635 if (opt->audio_production_info) {
1636 av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
1637 switch (opt->room_type) {
1638 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1639 case 1: av_strlcpy(strbuf, "large", 32); break;
1640 case 2: av_strlcpy(strbuf, "small", 32); break;
1641 default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
1643 av_dlog(avctx, "room_type: %s\n", strbuf);
1645 av_dlog(avctx, "mixing_level: {not written}\n");
1646 av_dlog(avctx, "room_type: {not written}\n");
1648 av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
1649 av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
1650 if (s->channel_mode == AC3_CHMODE_STEREO) {
1651 switch (opt->dolby_surround_mode) {
1652 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1653 case 1: av_strlcpy(strbuf, "on", 32); break;
1654 case 2: av_strlcpy(strbuf, "off", 32); break;
1655 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
1657 av_dlog(avctx, "dsur_mode: %s\n", strbuf);
1659 av_dlog(avctx, "dsur_mode: {not written}\n");
1661 av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
1663 if (s->bitstream_id == 6) {
1664 if (opt->extended_bsi_1) {
1665 switch (opt->preferred_stereo_downmix) {
1666 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1667 case 1: av_strlcpy(strbuf, "ltrt", 32); break;
1668 case 2: av_strlcpy(strbuf, "loro", 32); break;
1669 default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
1671 av_dlog(avctx, "dmix_mode: %s\n", strbuf);
1672 av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
1673 opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
1674 av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
1675 opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
1676 av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
1677 opt->loro_center_mix_level, s->loro_center_mix_level);
1678 av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
1679 opt->loro_surround_mix_level, s->loro_surround_mix_level);
1681 av_dlog(avctx, "extended bitstream info 1: {not written}\n");
1683 if (opt->extended_bsi_2) {
1684 switch (opt->dolby_surround_ex_mode) {
1685 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1686 case 1: av_strlcpy(strbuf, "on", 32); break;
1687 case 2: av_strlcpy(strbuf, "off", 32); break;
1688 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
1690 av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
1691 switch (opt->dolby_headphone_mode) {
1692 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
1693 case 1: av_strlcpy(strbuf, "on", 32); break;
1694 case 2: av_strlcpy(strbuf, "off", 32); break;
1695 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
1697 av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
1699 switch (opt->ad_converter_type) {
1700 case 0: av_strlcpy(strbuf, "standard", 32); break;
1701 case 1: av_strlcpy(strbuf, "hdcd", 32); break;
1702 default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
1704 av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
1706 av_dlog(avctx, "extended bitstream info 2: {not written}\n");
1713 #define FLT_OPTION_THRESHOLD 0.01
1715 static int validate_float_option(float v, const float *v_list, int v_list_size)
1719 for (i = 0; i < v_list_size; i++) {
1720 if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
1721 v > (v_list[i] - FLT_OPTION_THRESHOLD))
1724 if (i == v_list_size)
1731 static void validate_mix_level(void *log_ctx, const char *opt_name,
1732 float *opt_param, const float *list,
1733 int list_size, int default_value, int min_value,
1736 int mixlev = validate_float_option(*opt_param, list, list_size);
1737 if (mixlev < min_value) {
1738 mixlev = default_value;
1739 if (*opt_param >= 0.0) {
1740 av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
1741 "default value: %0.3f\n", opt_name, list[mixlev]);
1744 *opt_param = list[mixlev];
1745 *ctx_param = mixlev;
1750 * Validate metadata options as set by AVOption system.
1751 * These values can optionally be changed per-frame.
1753 static int validate_metadata(AVCodecContext *avctx)
1755 AC3EncodeContext *s = avctx->priv_data;
1756 AC3EncOptions *opt = &s->options;
1758 /* validate mixing levels */
1759 if (s->has_center) {
1760 validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
1761 cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
1762 &s->center_mix_level);
1764 if (s->has_surround) {
1765 validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
1766 surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
1767 &s->surround_mix_level);
1770 /* set audio production info flag */
1771 if (opt->mixing_level >= 0 || opt->room_type >= 0) {
1772 if (opt->mixing_level < 0) {
1773 av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
1774 "room_type is set\n");
1775 return AVERROR(EINVAL);
1777 if (opt->mixing_level < 80) {
1778 av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
1779 "80dB and 111dB\n");
1780 return AVERROR(EINVAL);
1782 /* default room type */
1783 if (opt->room_type < 0)
1785 opt->audio_production_info = 1;
1787 opt->audio_production_info = 0;
1790 /* set extended bsi 1 flag */
1791 if ((s->has_center || s->has_surround) &&
1792 (opt->preferred_stereo_downmix >= 0 ||
1793 opt->ltrt_center_mix_level >= 0 ||
1794 opt->ltrt_surround_mix_level >= 0 ||
1795 opt->loro_center_mix_level >= 0 ||
1796 opt->loro_surround_mix_level >= 0)) {
1797 /* default preferred stereo downmix */
1798 if (opt->preferred_stereo_downmix < 0)
1799 opt->preferred_stereo_downmix = 0;
1800 /* validate Lt/Rt center mix level */
1801 validate_mix_level(avctx, "ltrt_center_mix_level",
1802 &opt->ltrt_center_mix_level, extmixlev_options,
1803 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1804 &s->ltrt_center_mix_level);
1805 /* validate Lt/Rt surround mix level */
1806 validate_mix_level(avctx, "ltrt_surround_mix_level",
1807 &opt->ltrt_surround_mix_level, extmixlev_options,
1808 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1809 &s->ltrt_surround_mix_level);
1810 /* validate Lo/Ro center mix level */
1811 validate_mix_level(avctx, "loro_center_mix_level",
1812 &opt->loro_center_mix_level, extmixlev_options,
1813 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1814 &s->loro_center_mix_level);
1815 /* validate Lo/Ro surround mix level */
1816 validate_mix_level(avctx, "loro_surround_mix_level",
1817 &opt->loro_surround_mix_level, extmixlev_options,
1818 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1819 &s->loro_surround_mix_level);
1820 opt->extended_bsi_1 = 1;
1822 opt->extended_bsi_1 = 0;
1825 /* set extended bsi 2 flag */
1826 if (opt->dolby_surround_ex_mode >= 0 ||
1827 opt->dolby_headphone_mode >= 0 ||
1828 opt->ad_converter_type >= 0) {
1829 /* default dolby surround ex mode */
1830 if (opt->dolby_surround_ex_mode < 0)
1831 opt->dolby_surround_ex_mode = 0;
1832 /* default dolby headphone mode */
1833 if (opt->dolby_headphone_mode < 0)
1834 opt->dolby_headphone_mode = 0;
1835 /* default A/D converter type */
1836 if (opt->ad_converter_type < 0)
1837 opt->ad_converter_type = 0;
1838 opt->extended_bsi_2 = 1;
1840 opt->extended_bsi_2 = 0;
1843 /* set bitstream id for alternate bitstream syntax */
1844 if (opt->extended_bsi_1 || opt->extended_bsi_2) {
1845 if (s->bitstream_id > 8 && s->bitstream_id < 11) {
1846 static int warn_once = 1;
1848 av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
1849 "not compatible with reduced samplerates. writing of "
1850 "extended bitstream information will be disabled.\n");
1854 s->bitstream_id = 6;
1863 * Encode a single AC-3 frame.
1865 static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
1866 int buf_size, void *data)
1868 AC3EncodeContext *s = avctx->priv_data;
1869 const SampleType *samples = data;
1872 if (s->options.allow_per_frame_metadata) {
1873 ret = validate_metadata(avctx);
1878 if (s->bit_alloc.sr_code == 1)
1879 adjust_frame_size(s);
1881 deinterleave_input_samples(s, samples);
1885 scale_coefficients(s);
1887 compute_rematrixing_strategy(s);
1889 apply_rematrixing(s);
1891 process_exponents(s);
1893 ret = compute_bit_allocation(s);
1895 av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1899 quantize_mantissas(s);
1901 output_frame(s, frame);
1903 return s->frame_size;
1908 * Finalize encoding and free any memory allocated by the encoder.
1910 static av_cold int ac3_encode_close(AVCodecContext *avctx)
1913 AC3EncodeContext *s = avctx->priv_data;
1915 for (ch = 0; ch < s->channels; ch++)
1916 av_freep(&s->planar_samples[ch]);
1917 av_freep(&s->planar_samples);
1918 av_freep(&s->bap_buffer);
1919 av_freep(&s->bap1_buffer);
1920 av_freep(&s->mdct_coef_buffer);
1921 av_freep(&s->fixed_coef_buffer);
1922 av_freep(&s->exp_buffer);
1923 av_freep(&s->grouped_exp_buffer);
1924 av_freep(&s->psd_buffer);
1925 av_freep(&s->band_psd_buffer);
1926 av_freep(&s->mask_buffer);
1927 av_freep(&s->qmant_buffer);
1928 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1929 AC3Block *block = &s->blocks[blk];
1930 av_freep(&block->bap);
1931 av_freep(&block->mdct_coef);
1932 av_freep(&block->fixed_coef);
1933 av_freep(&block->exp);
1934 av_freep(&block->grouped_exp);
1935 av_freep(&block->psd);
1936 av_freep(&block->band_psd);
1937 av_freep(&block->mask);
1938 av_freep(&block->qmant);
1943 av_freep(&avctx->coded_frame);
1949 * Set channel information during initialization.
1951 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1952 int64_t *channel_layout)
1956 if (channels < 1 || channels > AC3_MAX_CHANNELS)
1957 return AVERROR(EINVAL);
1958 if ((uint64_t)*channel_layout > 0x7FF)
1959 return AVERROR(EINVAL);
1960 ch_layout = *channel_layout;
1962 ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1964 s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1965 s->channels = channels;
1966 s->fbw_channels = channels - s->lfe_on;
1967 s->lfe_channel = s->lfe_on ? s->fbw_channels : -1;
1969 ch_layout -= AV_CH_LOW_FREQUENCY;
1971 switch (ch_layout) {
1972 case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
1973 case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
1974 case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
1975 case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
1976 case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
1977 case AV_CH_LAYOUT_QUAD:
1978 case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
1979 case AV_CH_LAYOUT_5POINT0:
1980 case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
1982 return AVERROR(EINVAL);
1984 s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
1985 s->has_surround = s->channel_mode & 0x04;
1987 s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1988 *channel_layout = ch_layout;
1990 *channel_layout |= AV_CH_LOW_FREQUENCY;
1996 static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
2000 /* validate channel layout */
2001 if (!avctx->channel_layout) {
2002 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
2003 "encoder will guess the layout, but it "
2004 "might be incorrect.\n");
2006 ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
2008 av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
2012 /* validate sample rate */
2013 for (i = 0; i < 9; i++) {
2014 if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
2018 av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
2019 return AVERROR(EINVAL);
2021 s->sample_rate = avctx->sample_rate;
2022 s->bit_alloc.sr_shift = i % 3;
2023 s->bit_alloc.sr_code = i / 3;
2024 s->bitstream_id = 8 + s->bit_alloc.sr_shift;
2026 /* validate bit rate */
2027 for (i = 0; i < 19; i++) {
2028 if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
2032 av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2033 return AVERROR(EINVAL);
2035 s->bit_rate = avctx->bit_rate;
2036 s->frame_size_code = i << 1;
2038 /* validate cutoff */
2039 if (avctx->cutoff < 0) {
2040 av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2041 return AVERROR(EINVAL);
2043 s->cutoff = avctx->cutoff;
2044 if (s->cutoff > (s->sample_rate >> 1))
2045 s->cutoff = s->sample_rate >> 1;
2047 /* validate audio service type / channels combination */
2048 if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
2049 avctx->channels == 1) ||
2050 ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
2051 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
2052 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
2053 && avctx->channels > 1)) {
2054 av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
2055 "specified number of channels\n");
2056 return AVERROR(EINVAL);
2059 ret = validate_metadata(avctx);
2063 s->rematrixing_enabled = s->options.stereo_rematrixing &&
2064 (s->channel_mode == AC3_CHMODE_STEREO);
2071 * Set bandwidth for all channels.
2072 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2073 * default value will be used.
2075 static av_cold void set_bandwidth(AC3EncodeContext *s)
2080 /* calculate bandwidth based on user-specified cutoff frequency */
2082 fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2083 s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2085 /* use default bandwidth setting */
2086 s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2089 /* set number of coefficients for each channel */
2090 for (ch = 0; ch < s->fbw_channels; ch++) {
2091 s->nb_coefs[ch] = s->bandwidth_code * 3 + 73;
2094 s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
2098 static av_cold int allocate_buffers(AVCodecContext *avctx)
2101 AC3EncodeContext *s = avctx->priv_data;
2103 FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
2105 for (ch = 0; ch < s->channels; ch++) {
2106 FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
2107 (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
2110 FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * s->channels *
2111 AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
2112 FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
2113 AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
2114 FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
2115 AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
2116 FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
2117 AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
2118 FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
2119 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
2120 FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
2121 AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
2122 FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
2123 64 * sizeof(*s->band_psd_buffer), alloc_fail);
2124 FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
2125 64 * sizeof(*s->mask_buffer), alloc_fail);
2126 FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
2127 AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
2128 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2129 AC3Block *block = &s->blocks[blk];
2130 FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
2132 FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
2134 FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
2136 FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
2138 FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
2140 FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
2142 FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
2144 FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
2147 for (ch = 0; ch < s->channels; ch++) {
2148 /* arrangement: block, channel, coeff */
2149 block->bap[ch] = &s->bap_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2150 block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2151 block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * s->channels + ch)];
2152 block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2153 block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * s->channels + ch)];
2154 block->mask[ch] = &s->mask_buffer [64 * (blk * s->channels + ch)];
2155 block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2157 /* arrangement: channel, block, coeff */
2158 block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2162 if (CONFIG_AC3ENC_FLOAT) {
2163 FF_ALLOC_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * s->channels *
2164 AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
2165 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2166 AC3Block *block = &s->blocks[blk];
2167 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2168 sizeof(*block->fixed_coef), alloc_fail);
2169 for (ch = 0; ch < s->channels; ch++)
2170 block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
2173 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2174 AC3Block *block = &s->blocks[blk];
2175 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2176 sizeof(*block->fixed_coef), alloc_fail);
2177 for (ch = 0; ch < s->channels; ch++)
2178 block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2184 return AVERROR(ENOMEM);
2189 * Initialize the encoder.
2191 static av_cold int ac3_encode_init(AVCodecContext *avctx)
2193 AC3EncodeContext *s = avctx->priv_data;
2194 int ret, frame_size_58;
2196 avctx->frame_size = AC3_FRAME_SIZE;
2198 ff_ac3_common_init();
2200 ret = validate_options(avctx, s);
2204 s->bitstream_mode = avctx->audio_service_type;
2205 if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2206 s->bitstream_mode = 0x7;
2208 s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2209 s->bits_written = 0;
2210 s->samples_written = 0;
2211 s->frame_size = s->frame_size_min;
2213 /* calculate crc_inv for both possible frame sizes */
2214 frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
2215 s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2216 if (s->bit_alloc.sr_code == 1) {
2217 frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2218 s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2227 ret = mdct_init(avctx, &s->mdct, 9);
2231 ret = allocate_buffers(avctx);
2235 avctx->coded_frame= avcodec_alloc_frame();
2237 dsputil_init(&s->dsp, avctx);
2238 ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2240 dprint_options(avctx);
2244 ac3_encode_close(avctx);