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/crc.h"
37 #include "libavutil/opt.h"
43 #include "audioconvert.h"
47 #ifndef CONFIG_AC3ENC_FLOAT
48 #define CONFIG_AC3ENC_FLOAT 0
52 /** Maximum number of exponent groups. +1 for separate DC exponent. */
53 #define AC3_MAX_EXP_GROUPS 85
55 /* stereo rematrixing algorithms */
56 #define AC3_REMATRIXING_IS_STATIC 0x1
57 #define AC3_REMATRIXING_SUMS 0
58 #define AC3_REMATRIXING_NONE 1
59 #define AC3_REMATRIXING_ALWAYS 3
61 #if CONFIG_AC3ENC_FLOAT
62 #define MAC_COEF(d,a,b) ((d)+=(a)*(b))
63 typedef float SampleType;
64 typedef float CoefType;
65 typedef float CoefSumType;
67 #define MAC_COEF(d,a,b) MAC64(d,a,b)
68 typedef int16_t SampleType;
69 typedef int32_t CoefType;
70 typedef int64_t CoefSumType;
73 typedef struct AC3MDCTContext {
74 const SampleType *window; ///< MDCT window function
75 FFTContext fft; ///< FFT context for MDCT calculation
79 * Encoding Options used by AVOption.
81 typedef struct AC3EncOptions {
82 /* AC-3 metadata options*/
85 float center_mix_level;
86 float surround_mix_level;
87 int dolby_surround_mode;
88 int audio_production_info;
94 int preferred_stereo_downmix;
95 float ltrt_center_mix_level;
96 float ltrt_surround_mix_level;
97 float loro_center_mix_level;
98 float loro_surround_mix_level;
100 int dolby_surround_ex_mode;
101 int dolby_headphone_mode;
102 int ad_converter_type;
104 /* other encoding options */
105 int allow_per_frame_metadata;
109 * Data for a single audio block.
111 typedef struct AC3Block {
112 uint8_t **bap; ///< bit allocation pointers (bap)
113 CoefType **mdct_coef; ///< MDCT coefficients
114 int32_t **fixed_coef; ///< fixed-point MDCT coefficients
115 uint8_t **exp; ///< original exponents
116 uint8_t **grouped_exp; ///< grouped exponents
117 int16_t **psd; ///< psd per frequency bin
118 int16_t **band_psd; ///< psd per critical band
119 int16_t **mask; ///< masking curve
120 uint16_t **qmant; ///< quantized mantissas
121 uint8_t coeff_shift[AC3_MAX_CHANNELS]; ///< fixed-point coefficient shift values
122 uint8_t new_rematrixing_strategy; ///< send new rematrixing flags in this block
123 uint8_t rematrixing_flags[4]; ///< rematrixing flags
124 struct AC3Block *exp_ref_block[AC3_MAX_CHANNELS]; ///< reference blocks for EXP_REUSE
128 * AC-3 encoder private context.
130 typedef struct AC3EncodeContext {
131 AVClass *av_class; ///< AVClass used for AVOption
132 AC3EncOptions options; ///< encoding options
133 PutBitContext pb; ///< bitstream writer context
135 AC3DSPContext ac3dsp; ///< AC-3 optimized functions
136 AC3MDCTContext mdct; ///< MDCT context
138 AC3Block blocks[AC3_MAX_BLOCKS]; ///< per-block info
140 int bitstream_id; ///< bitstream id (bsid)
141 int bitstream_mode; ///< bitstream mode (bsmod)
143 int bit_rate; ///< target bit rate, in bits-per-second
144 int sample_rate; ///< sampling frequency, in Hz
146 int frame_size_min; ///< minimum frame size in case rounding is necessary
147 int frame_size; ///< current frame size in bytes
148 int frame_size_code; ///< frame size code (frmsizecod)
150 int bits_written; ///< bit count (used to avg. bitrate)
151 int samples_written; ///< sample count (used to avg. bitrate)
153 int fbw_channels; ///< number of full-bandwidth channels (nfchans)
154 int channels; ///< total number of channels (nchans)
155 int lfe_on; ///< indicates if there is an LFE channel (lfeon)
156 int lfe_channel; ///< channel index of the LFE channel
157 int has_center; ///< indicates if there is a center channel
158 int has_surround; ///< indicates if there are one or more surround channels
159 int channel_mode; ///< channel mode (acmod)
160 const uint8_t *channel_map; ///< channel map used to reorder channels
162 int center_mix_level; ///< center mix level code
163 int surround_mix_level; ///< surround mix level code
164 int ltrt_center_mix_level; ///< Lt/Rt center mix level code
165 int ltrt_surround_mix_level; ///< Lt/Rt surround mix level code
166 int loro_center_mix_level; ///< Lo/Ro center mix level code
167 int loro_surround_mix_level; ///< Lo/Ro surround mix level code
169 int cutoff; ///< user-specified cutoff frequency, in Hz
170 int bandwidth_code[AC3_MAX_CHANNELS]; ///< bandwidth code (0 to 60) (chbwcod)
171 int nb_coefs[AC3_MAX_CHANNELS];
173 int rematrixing; ///< determines how rematrixing strategy is calculated
174 int num_rematrixing_bands; ///< number of rematrixing bands
176 /* bitrate allocation control */
177 int slow_gain_code; ///< slow gain code (sgaincod)
178 int slow_decay_code; ///< slow decay code (sdcycod)
179 int fast_decay_code; ///< fast decay code (fdcycod)
180 int db_per_bit_code; ///< dB/bit code (dbpbcod)
181 int floor_code; ///< floor code (floorcod)
182 AC3BitAllocParameters bit_alloc; ///< bit allocation parameters
183 int coarse_snr_offset; ///< coarse SNR offsets (csnroffst)
184 int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signal-to-mask ratio) (fgaincod)
185 int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst)
186 int frame_bits_fixed; ///< number of non-coefficient bits for fixed parameters
187 int frame_bits; ///< all frame bits except exponents and mantissas
188 int exponent_bits; ///< number of bits used for exponents
190 SampleType **planar_samples;
192 uint8_t *bap1_buffer;
193 CoefType *mdct_coef_buffer;
194 int32_t *fixed_coef_buffer;
196 uint8_t *grouped_exp_buffer;
198 int16_t *band_psd_buffer;
199 int16_t *mask_buffer;
200 uint16_t *qmant_buffer;
202 uint8_t exp_strategy[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< exponent strategies
204 DECLARE_ALIGNED(32, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
207 typedef struct AC3Mant {
208 uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
209 int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
212 #define CMIXLEV_NUM_OPTIONS 3
213 static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
214 LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
217 #define SURMIXLEV_NUM_OPTIONS 3
218 static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
219 LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
222 #define EXTMIXLEV_NUM_OPTIONS 8
223 static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
224 LEVEL_PLUS_3DB, LEVEL_PLUS_1POINT5DB, LEVEL_ONE, LEVEL_MINUS_4POINT5DB,
225 LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
229 #define OFFSET(param) offsetof(AC3EncodeContext, options.param)
230 #define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
232 static const AVOption options[] = {
233 /* Metadata Options */
234 {"per_frame_metadata", "Allow Changing Metadata Per-Frame", OFFSET(allow_per_frame_metadata), FF_OPT_TYPE_INT, 0, 0, 1, AC3ENC_PARAM},
236 {"center_mixlev", "Center Mix Level", OFFSET(center_mix_level), FF_OPT_TYPE_FLOAT, LEVEL_MINUS_4POINT5DB, 0.0, 1.0, AC3ENC_PARAM},
237 {"surround_mixlev", "Surround Mix Level", OFFSET(surround_mix_level), FF_OPT_TYPE_FLOAT, LEVEL_MINUS_6DB, 0.0, 1.0, AC3ENC_PARAM},
238 /* audio production information */
239 {"mixing_level", "Mixing Level", OFFSET(mixing_level), FF_OPT_TYPE_INT, -1, -1, 111, AC3ENC_PARAM},
240 {"room_type", "Room Type", OFFSET(room_type), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "room_type"},
241 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
242 {"large", "Large Room", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
243 {"small", "Small Room", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
244 /* other metadata options */
245 {"copyright", "Copyright Bit", OFFSET(copyright), FF_OPT_TYPE_INT, 0, 0, 1, AC3ENC_PARAM},
246 {"dialnorm", "Dialogue Level (dB)", OFFSET(dialogue_level), FF_OPT_TYPE_INT, -31, -31, -1, AC3ENC_PARAM},
247 {"dsur_mode", "Dolby Surround Mode", OFFSET(dolby_surround_mode), FF_OPT_TYPE_INT, 0, 0, 2, AC3ENC_PARAM, "dsur_mode"},
248 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
249 {"on", "Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
250 {"off", "Not Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
251 {"original", "Original Bit Stream", OFFSET(original), FF_OPT_TYPE_INT, 1, 0, 1, AC3ENC_PARAM},
252 /* extended bitstream information */
253 {"dmix_mode", "Preferred Stereo Downmix Mode", OFFSET(preferred_stereo_downmix), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "dmix_mode"},
254 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
255 {"ltrt", "Lt/Rt Downmix Preferred", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
256 {"loro", "Lo/Ro Downmix Preferred", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
257 {"ltrt_cmixlev", "Lt/Rt Center Mix Level", OFFSET(ltrt_center_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
258 {"ltrt_surmixlev", "Lt/Rt Surround Mix Level", OFFSET(ltrt_surround_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
259 {"loro_cmixlev", "Lo/Ro Center Mix Level", OFFSET(loro_center_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
260 {"loro_surmixlev", "Lo/Ro Surround Mix Level", OFFSET(loro_surround_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
261 {"dsurex_mode", "Dolby Surround EX Mode", OFFSET(dolby_surround_ex_mode), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "dsurex_mode"},
262 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
263 {"on", "Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
264 {"off", "Not Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
265 {"dheadphone_mode", "Dolby Headphone Mode", OFFSET(dolby_headphone_mode), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "dheadphone_mode"},
266 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
267 {"on", "Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
268 {"off", "Not Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
269 {"ad_conv_type", "A/D Converter Type", OFFSET(ad_converter_type), FF_OPT_TYPE_INT, -1, -1, 1, AC3ENC_PARAM, "ad_conv_type"},
270 {"standard", "Standard (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
271 {"hdcd", "HDCD", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
275 #if CONFIG_AC3ENC_FLOAT
276 static AVClass ac3enc_class = { "AC-3 Encoder", av_default_item_name,
277 options, LIBAVUTIL_VERSION_INT };
279 static AVClass ac3enc_class = { "Fixed-Point AC-3 Encoder", av_default_item_name,
280 options, LIBAVUTIL_VERSION_INT };
284 /* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
286 static av_cold void mdct_end(AC3MDCTContext *mdct);
288 static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
291 static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
292 const SampleType *window, unsigned int len);
294 static int normalize_samples(AC3EncodeContext *s);
296 static void scale_coefficients(AC3EncodeContext *s);
300 * LUT for number of exponent groups.
301 * exponent_group_tab[exponent strategy-1][number of coefficients]
303 static uint8_t exponent_group_tab[3][256];
307 * List of supported channel layouts.
309 static const int64_t ac3_channel_layouts[] = {
313 AV_CH_LAYOUT_SURROUND,
316 AV_CH_LAYOUT_4POINT0,
317 AV_CH_LAYOUT_5POINT0,
318 AV_CH_LAYOUT_5POINT0_BACK,
319 (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
320 (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
321 (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
322 (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
323 (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
324 (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
325 (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
326 AV_CH_LAYOUT_5POINT1,
327 AV_CH_LAYOUT_5POINT1_BACK,
333 * LUT to select the bandwidth code based on the bit rate, sample rate, and
334 * number of full-bandwidth channels.
335 * bandwidth_tab[fbw_channels-1][sample rate code][bit rate code]
337 static const uint8_t ac3_bandwidth_tab[5][3][19] = {
338 // 32 40 48 56 64 80 96 112 128 160 192 224 256 320 384 448 512 576 640
340 { { 0, 0, 0, 12, 16, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
341 { 0, 0, 0, 16, 20, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
342 { 0, 0, 0, 32, 40, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
344 { { 0, 0, 0, 0, 0, 0, 0, 20, 24, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
345 { 0, 0, 0, 0, 0, 0, 4, 24, 28, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
346 { 0, 0, 0, 0, 0, 0, 20, 44, 52, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
348 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 24, 32, 40, 48, 48, 48, 48, 48, 48 },
349 { 0, 0, 0, 0, 0, 0, 0, 0, 4, 20, 28, 36, 44, 56, 56, 56, 56, 56, 56 },
350 { 0, 0, 0, 0, 0, 0, 0, 0, 20, 40, 48, 60, 60, 60, 60, 60, 60, 60, 60 } },
352 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 32, 48, 48, 48, 48, 48, 48 },
353 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 28, 36, 56, 56, 56, 56, 56, 56 },
354 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 48, 60, 60, 60, 60, 60, 60, 60 } },
356 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 20, 32, 40, 48, 48, 48, 48 },
357 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 36, 44, 56, 56, 56, 56 },
358 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 44, 60, 60, 60, 60, 60, 60 } }
363 * Adjust the frame size to make the average bit rate match the target bit rate.
364 * This is only needed for 11025, 22050, and 44100 sample rates.
366 static void adjust_frame_size(AC3EncodeContext *s)
368 while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
369 s->bits_written -= s->bit_rate;
370 s->samples_written -= s->sample_rate;
372 s->frame_size = s->frame_size_min +
373 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
374 s->bits_written += s->frame_size * 8;
375 s->samples_written += AC3_FRAME_SIZE;
380 * Deinterleave input samples.
381 * Channels are reordered from Libav's default order to AC-3 order.
383 static void deinterleave_input_samples(AC3EncodeContext *s,
384 const SampleType *samples)
388 /* deinterleave and remap input samples */
389 for (ch = 0; ch < s->channels; ch++) {
390 const SampleType *sptr;
393 /* copy last 256 samples of previous frame to the start of the current frame */
394 memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
395 AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
399 sptr = samples + s->channel_map[ch];
400 for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
401 s->planar_samples[ch][i] = *sptr;
409 * Apply the MDCT to input samples to generate frequency coefficients.
410 * This applies the KBD window and normalizes the input to reduce precision
411 * loss due to fixed-point calculations.
413 static void apply_mdct(AC3EncodeContext *s)
417 for (ch = 0; ch < s->channels; ch++) {
418 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
419 AC3Block *block = &s->blocks[blk];
420 const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
422 apply_window(&s->dsp, s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
424 block->coeff_shift[ch] = normalize_samples(s);
426 s->mdct.fft.mdct_calcw(&s->mdct.fft, block->mdct_coef[ch],
427 s->windowed_samples);
434 * Initialize stereo rematrixing.
435 * If the strategy does not change for each frame, set the rematrixing flags.
437 static void rematrixing_init(AC3EncodeContext *s)
439 if (s->channel_mode == AC3_CHMODE_STEREO)
440 s->rematrixing = AC3_REMATRIXING_SUMS;
442 s->rematrixing = AC3_REMATRIXING_NONE;
443 /* NOTE: AC3_REMATRIXING_ALWAYS might be used in
444 the future in conjunction with channel coupling. */
446 if (s->rematrixing & AC3_REMATRIXING_IS_STATIC) {
447 int flag = (s->rematrixing == AC3_REMATRIXING_ALWAYS);
448 s->blocks[0].new_rematrixing_strategy = 1;
449 memset(s->blocks[0].rematrixing_flags, flag,
450 sizeof(s->blocks[0].rematrixing_flags));
456 * Determine rematrixing flags for each block and band.
458 static void compute_rematrixing_strategy(AC3EncodeContext *s)
462 AC3Block *block, *block0;
464 s->num_rematrixing_bands = 4;
466 if (s->rematrixing & AC3_REMATRIXING_IS_STATIC)
469 nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
471 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
472 block = &s->blocks[blk];
473 block->new_rematrixing_strategy = !blk;
474 for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
475 /* calculate calculate sum of squared coeffs for one band in one block */
476 int start = ff_ac3_rematrix_band_tab[bnd];
477 int end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
478 CoefSumType sum[4] = {0,};
479 for (i = start; i < end; i++) {
480 CoefType lt = block->mdct_coef[0][i];
481 CoefType rt = block->mdct_coef[1][i];
482 CoefType md = lt + rt;
483 CoefType sd = lt - rt;
484 MAC_COEF(sum[0], lt, lt);
485 MAC_COEF(sum[1], rt, rt);
486 MAC_COEF(sum[2], md, md);
487 MAC_COEF(sum[3], sd, sd);
490 /* compare sums to determine if rematrixing will be used for this band */
491 if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
492 block->rematrixing_flags[bnd] = 1;
494 block->rematrixing_flags[bnd] = 0;
496 /* determine if new rematrixing flags will be sent */
498 block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
499 block->new_rematrixing_strategy = 1;
508 * Apply stereo rematrixing to coefficients based on rematrixing flags.
510 static void apply_rematrixing(AC3EncodeContext *s)
517 if (s->rematrixing == AC3_REMATRIXING_NONE)
520 nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
522 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
523 AC3Block *block = &s->blocks[blk];
524 if (block->new_rematrixing_strategy)
525 flags = block->rematrixing_flags;
526 for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
528 start = ff_ac3_rematrix_band_tab[bnd];
529 end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
530 for (i = start; i < end; i++) {
531 int32_t lt = block->fixed_coef[0][i];
532 int32_t rt = block->fixed_coef[1][i];
533 block->fixed_coef[0][i] = (lt + rt) >> 1;
534 block->fixed_coef[1][i] = (lt - rt) >> 1;
543 * Initialize exponent tables.
545 static av_cold void exponent_init(AC3EncodeContext *s)
548 for (i = 73; i < 256; i++) {
549 exponent_group_tab[0][i] = (i - 1) / 3;
550 exponent_group_tab[1][i] = (i + 2) / 6;
551 exponent_group_tab[2][i] = (i + 8) / 12;
554 exponent_group_tab[0][7] = 2;
559 * Extract exponents from the MDCT coefficients.
560 * This takes into account the normalization that was done to the input samples
561 * by adjusting the exponents by the exponent shift values.
563 static void extract_exponents(AC3EncodeContext *s)
567 for (ch = 0; ch < s->channels; ch++) {
568 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
569 AC3Block *block = &s->blocks[blk];
570 s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch],
578 * Exponent Difference Threshold.
579 * New exponents are sent if their SAD exceed this number.
581 #define EXP_DIFF_THRESHOLD 500
585 * Calculate exponent strategies for all blocks in a single channel.
587 static void compute_exp_strategy_ch(AC3EncodeContext *s, uint8_t *exp_strategy,
593 /* estimate if the exponent variation & decide if they should be
594 reused in the next frame */
595 exp_strategy[0] = EXP_NEW;
596 exp += AC3_MAX_COEFS;
597 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
598 exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
599 if (exp_diff > EXP_DIFF_THRESHOLD)
600 exp_strategy[blk] = EXP_NEW;
602 exp_strategy[blk] = EXP_REUSE;
603 exp += AC3_MAX_COEFS;
606 /* now select the encoding strategy type : if exponents are often
607 recoded, we use a coarse encoding */
609 while (blk < AC3_MAX_BLOCKS) {
611 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
613 switch (blk1 - blk) {
614 case 1: exp_strategy[blk] = EXP_D45; break;
616 case 3: exp_strategy[blk] = EXP_D25; break;
617 default: exp_strategy[blk] = EXP_D15; break;
625 * Calculate exponent strategies for all channels.
626 * Array arrangement is reversed to simplify the per-channel calculation.
628 static void compute_exp_strategy(AC3EncodeContext *s)
632 for (ch = 0; ch < s->fbw_channels; ch++) {
633 compute_exp_strategy_ch(s, s->exp_strategy[ch], s->blocks[0].exp[ch]);
637 s->exp_strategy[ch][0] = EXP_D15;
638 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
639 s->exp_strategy[ch][blk] = EXP_REUSE;
645 * Update the exponents so that they are the ones the decoder will decode.
647 static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy)
651 nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
653 /* for each group, compute the minimum exponent */
654 switch(exp_strategy) {
656 for (i = 1, k = 1; i <= nb_groups; i++) {
657 uint8_t exp_min = exp[k];
658 if (exp[k+1] < exp_min)
665 for (i = 1, k = 1; i <= nb_groups; i++) {
666 uint8_t exp_min = exp[k];
667 if (exp[k+1] < exp_min)
669 if (exp[k+2] < exp_min)
671 if (exp[k+3] < exp_min)
679 /* constraint for DC exponent */
683 /* decrease the delta between each groups to within 2 so that they can be
684 differentially encoded */
685 for (i = 1; i <= nb_groups; i++)
686 exp[i] = FFMIN(exp[i], exp[i-1] + 2);
689 exp[i] = FFMIN(exp[i], exp[i+1] + 2);
691 /* now we have the exponent values the decoder will see */
692 switch (exp_strategy) {
694 for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
695 uint8_t exp1 = exp[i];
701 for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
702 exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
711 * Encode exponents from original extracted form to what the decoder will see.
712 * This copies and groups exponents based on exponent strategy and reduces
713 * deltas between adjacent exponent groups so that they can be differentially
716 static void encode_exponents(AC3EncodeContext *s)
719 uint8_t *exp, *exp_strategy;
720 int nb_coefs, num_reuse_blocks;
722 for (ch = 0; ch < s->channels; ch++) {
723 exp = s->blocks[0].exp[ch];
724 exp_strategy = s->exp_strategy[ch];
725 nb_coefs = s->nb_coefs[ch];
728 while (blk < AC3_MAX_BLOCKS) {
731 /* count the number of EXP_REUSE blocks after the current block
732 and set exponent reference block pointers */
733 s->blocks[blk].exp_ref_block[ch] = &s->blocks[blk];
734 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
735 s->blocks[blk1].exp_ref_block[ch] = &s->blocks[blk];
738 num_reuse_blocks = blk1 - blk - 1;
740 /* for the EXP_REUSE case we select the min of the exponents */
741 s->ac3dsp.ac3_exponent_min(exp, num_reuse_blocks, nb_coefs);
743 encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk]);
745 exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
754 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
755 * varies depending on exponent strategy and bandwidth.
757 static void group_exponents(AC3EncodeContext *s)
760 int group_size, nb_groups, bit_count;
762 int delta0, delta1, delta2;
766 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
767 AC3Block *block = &s->blocks[blk];
768 for (ch = 0; ch < s->channels; ch++) {
769 int exp_strategy = s->exp_strategy[ch][blk];
770 if (exp_strategy == EXP_REUSE)
772 group_size = exp_strategy + (exp_strategy == EXP_D45);
773 nb_groups = exponent_group_tab[exp_strategy-1][s->nb_coefs[ch]];
774 bit_count += 4 + (nb_groups * 7);
779 block->grouped_exp[ch][0] = exp1;
781 /* remaining exponents are delta encoded */
782 for (i = 1; i <= nb_groups; i++) {
783 /* merge three delta in one code */
787 delta0 = exp1 - exp0 + 2;
788 av_assert2(delta0 >= 0 && delta0 <= 4);
793 delta1 = exp1 - exp0 + 2;
794 av_assert2(delta1 >= 0 && delta1 <= 4);
799 delta2 = exp1 - exp0 + 2;
800 av_assert2(delta2 >= 0 && delta2 <= 4);
802 block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
807 s->exponent_bits = bit_count;
812 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
813 * Extract exponents from MDCT coefficients, calculate exponent strategies,
814 * and encode final exponents.
816 static void process_exponents(AC3EncodeContext *s)
818 extract_exponents(s);
820 compute_exp_strategy(s);
831 * Count frame bits that are based solely on fixed parameters.
832 * This only has to be run once when the encoder is initialized.
834 static void count_frame_bits_fixed(AC3EncodeContext *s)
836 static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
841 * no dynamic range codes
842 * no channel coupling
843 * bit allocation parameters do not change between blocks
844 * SNR offsets do not change between blocks
845 * no delta bit allocation
852 frame_bits += frame_bits_inc[s->channel_mode];
855 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
856 frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
857 if (s->channel_mode == AC3_CHMODE_STEREO) {
858 frame_bits++; /* rematstr */
860 frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
862 frame_bits++; /* lfeexpstr */
863 frame_bits++; /* baie */
864 frame_bits++; /* snr */
865 frame_bits += 2; /* delta / skip */
867 frame_bits++; /* cplinu for block 0 */
869 /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
871 /* (fsnoffset[4] + fgaincod[4]) * c */
872 frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
874 /* auxdatae, crcrsv */
880 s->frame_bits_fixed = frame_bits;
885 * Initialize bit allocation.
886 * Set default parameter codes and calculate parameter values.
888 static void bit_alloc_init(AC3EncodeContext *s)
892 /* init default parameters */
893 s->slow_decay_code = 2;
894 s->fast_decay_code = 1;
895 s->slow_gain_code = 1;
896 s->db_per_bit_code = 3;
898 for (ch = 0; ch < s->channels; ch++)
899 s->fast_gain_code[ch] = 4;
901 /* initial snr offset */
902 s->coarse_snr_offset = 40;
904 /* compute real values */
905 /* currently none of these values change during encoding, so we can just
906 set them once at initialization */
907 s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
908 s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
909 s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
910 s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
911 s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
913 count_frame_bits_fixed(s);
918 * Count the bits used to encode the frame, minus exponents and mantissas.
919 * Bits based on fixed parameters have already been counted, so now we just
920 * have to add the bits based on parameters that change during encoding.
922 static void count_frame_bits(AC3EncodeContext *s)
924 AC3EncOptions *opt = &s->options;
928 if (opt->audio_production_info)
930 if (s->bitstream_id == 6) {
931 if (opt->extended_bsi_1)
933 if (opt->extended_bsi_2)
937 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
938 /* stereo rematrixing */
939 if (s->channel_mode == AC3_CHMODE_STEREO &&
940 s->blocks[blk].new_rematrixing_strategy) {
941 frame_bits += s->num_rematrixing_bands;
944 for (ch = 0; ch < s->fbw_channels; ch++) {
945 if (s->exp_strategy[ch][blk] != EXP_REUSE)
946 frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
949 s->frame_bits = s->frame_bits_fixed + frame_bits;
954 * Finalize the mantissa bit count by adding in the grouped mantissas.
956 static int compute_mantissa_size_final(int mant_cnt[5])
958 // bap=1 : 3 mantissas in 5 bits
959 int bits = (mant_cnt[1] / 3) * 5;
960 // bap=2 : 3 mantissas in 7 bits
961 // bap=4 : 2 mantissas in 7 bits
962 bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
963 // bap=3 : each mantissa is 3 bits
964 bits += mant_cnt[3] * 3;
970 * Calculate masking curve based on the final exponents.
971 * Also calculate the power spectral densities to use in future calculations.
973 static void bit_alloc_masking(AC3EncodeContext *s)
977 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
978 AC3Block *block = &s->blocks[blk];
979 for (ch = 0; ch < s->channels; ch++) {
980 /* We only need psd and mask for calculating bap.
981 Since we currently do not calculate bap when exponent
982 strategy is EXP_REUSE we do not need to calculate psd or mask. */
983 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
984 ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
986 block->psd[ch], block->band_psd[ch]);
987 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
989 ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
990 ch == s->lfe_channel,
991 DBA_NONE, 0, NULL, NULL, NULL,
1000 * Ensure that bap for each block and channel point to the current bap_buffer.
1001 * They may have been switched during the bit allocation search.
1003 static void reset_block_bap(AC3EncodeContext *s)
1006 if (s->blocks[0].bap[0] == s->bap_buffer)
1008 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1009 for (ch = 0; ch < s->channels; ch++) {
1010 s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
1017 * Run the bit allocation with a given SNR offset.
1018 * This calculates the bit allocation pointers that will be used to determine
1019 * the quantization of each mantissa.
1020 * @return the number of bits needed for mantissas if the given SNR offset is
1023 static int bit_alloc(AC3EncodeContext *s, int snr_offset)
1029 snr_offset = (snr_offset - 240) << 2;
1033 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1035 // initialize grouped mantissa counts. these are set so that they are
1036 // padded to the next whole group size when bits are counted in
1037 // compute_mantissa_size_final
1038 mant_cnt[0] = mant_cnt[3] = 0;
1039 mant_cnt[1] = mant_cnt[2] = 2;
1041 for (ch = 0; ch < s->channels; ch++) {
1042 /* Currently the only bit allocation parameters which vary across
1043 blocks within a frame are the exponent values. We can take
1044 advantage of that by reusing the bit allocation pointers
1045 whenever we reuse exponents. */
1046 block = s->blocks[blk].exp_ref_block[ch];
1047 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1048 s->ac3dsp.bit_alloc_calc_bap(block->mask[ch], block->psd[ch], 0,
1049 s->nb_coefs[ch], snr_offset,
1050 s->bit_alloc.floor, ff_ac3_bap_tab,
1053 mantissa_bits += s->ac3dsp.compute_mantissa_size(mant_cnt, block->bap[ch], s->nb_coefs[ch]);
1055 mantissa_bits += compute_mantissa_size_final(mant_cnt);
1057 return mantissa_bits;
1062 * Constant bitrate bit allocation search.
1063 * Find the largest SNR offset that will allow data to fit in the frame.
1065 static int cbr_bit_allocation(AC3EncodeContext *s)
1069 int snr_offset, snr_incr;
1071 bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1072 av_assert2(bits_left >= 0);
1074 snr_offset = s->coarse_snr_offset << 4;
1076 /* if previous frame SNR offset was 1023, check if current frame can also
1077 use SNR offset of 1023. if so, skip the search. */
1078 if ((snr_offset | s->fine_snr_offset[0]) == 1023) {
1079 if (bit_alloc(s, 1023) <= bits_left)
1083 while (snr_offset >= 0 &&
1084 bit_alloc(s, snr_offset) > bits_left) {
1088 return AVERROR(EINVAL);
1090 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1091 for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1092 while (snr_offset + snr_incr <= 1023 &&
1093 bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1094 snr_offset += snr_incr;
1095 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1098 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1101 s->coarse_snr_offset = snr_offset >> 4;
1102 for (ch = 0; ch < s->channels; ch++)
1103 s->fine_snr_offset[ch] = snr_offset & 0xF;
1110 * Downgrade exponent strategies to reduce the bits used by the exponents.
1111 * This is a fallback for when bit allocation fails with the normal exponent
1112 * strategies. Each time this function is run it only downgrades the
1113 * strategy in 1 channel of 1 block.
1114 * @return non-zero if downgrade was unsuccessful
1116 static int downgrade_exponents(AC3EncodeContext *s)
1120 for (ch = 0; ch < s->fbw_channels; ch++) {
1121 for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1122 if (s->exp_strategy[ch][blk] == EXP_D15) {
1123 s->exp_strategy[ch][blk] = EXP_D25;
1128 for (ch = 0; ch < s->fbw_channels; ch++) {
1129 for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1130 if (s->exp_strategy[ch][blk] == EXP_D25) {
1131 s->exp_strategy[ch][blk] = EXP_D45;
1136 for (ch = 0; ch < s->fbw_channels; ch++) {
1137 /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
1138 the block number > 0 */
1139 for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
1140 if (s->exp_strategy[ch][blk] > EXP_REUSE) {
1141 s->exp_strategy[ch][blk] = EXP_REUSE;
1151 * Reduce the bandwidth to reduce the number of bits used for a given SNR offset.
1152 * This is a second fallback for when bit allocation still fails after exponents
1153 * have been downgraded.
1154 * @return non-zero if bandwidth reduction was unsuccessful
1156 static int reduce_bandwidth(AC3EncodeContext *s, int min_bw_code)
1160 if (s->bandwidth_code[0] > min_bw_code) {
1161 for (ch = 0; ch < s->fbw_channels; ch++) {
1162 s->bandwidth_code[ch]--;
1163 s->nb_coefs[ch] = s->bandwidth_code[ch] * 3 + 73;
1172 * Perform bit allocation search.
1173 * Finds the SNR offset value that maximizes quality and fits in the specified
1174 * frame size. Output is the SNR offset and a set of bit allocation pointers
1175 * used to quantize the mantissas.
1177 static int compute_bit_allocation(AC3EncodeContext *s)
1181 count_frame_bits(s);
1183 bit_alloc_masking(s);
1185 ret = cbr_bit_allocation(s);
1187 /* fallback 1: downgrade exponents */
1188 if (!downgrade_exponents(s)) {
1189 extract_exponents(s);
1190 encode_exponents(s);
1192 ret = compute_bit_allocation(s);
1196 /* fallback 2: reduce bandwidth */
1197 /* only do this if the user has not specified a specific cutoff
1199 if (!s->cutoff && !reduce_bandwidth(s, 0)) {
1200 process_exponents(s);
1201 ret = compute_bit_allocation(s);
1205 /* fallbacks were not enough... */
1214 * Symmetric quantization on 'levels' levels.
1216 static inline int sym_quant(int c, int e, int levels)
1218 int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1219 av_assert2(v >= 0 && v < levels);
1225 * Asymmetric quantization on 2^qbits levels.
1227 static inline int asym_quant(int c, int e, int qbits)
1231 lshift = e + qbits - 24;
1238 m = (1 << (qbits-1));
1241 av_assert2(v >= -m);
1242 return v & ((1 << qbits)-1);
1247 * Quantize a set of mantissas for a single channel in a single block.
1249 static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1251 uint8_t *bap, uint16_t *qmant, int n)
1255 for (i = 0; i < n; i++) {
1257 int c = fixed_coef[i];
1265 v = sym_quant(c, e, 3);
1266 switch (s->mant1_cnt) {
1268 s->qmant1_ptr = &qmant[i];
1273 *s->qmant1_ptr += 3 * v;
1278 *s->qmant1_ptr += v;
1285 v = sym_quant(c, e, 5);
1286 switch (s->mant2_cnt) {
1288 s->qmant2_ptr = &qmant[i];
1293 *s->qmant2_ptr += 5 * v;
1298 *s->qmant2_ptr += v;
1305 v = sym_quant(c, e, 7);
1308 v = sym_quant(c, e, 11);
1309 switch (s->mant4_cnt) {
1311 s->qmant4_ptr = &qmant[i];
1316 *s->qmant4_ptr += v;
1323 v = sym_quant(c, e, 15);
1326 v = asym_quant(c, e, 14);
1329 v = asym_quant(c, e, 16);
1332 v = asym_quant(c, e, b - 1);
1341 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1343 static void quantize_mantissas(AC3EncodeContext *s)
1348 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1349 AC3Block *block = &s->blocks[blk];
1350 AC3Block *ref_block;
1353 for (ch = 0; ch < s->channels; ch++) {
1354 ref_block = block->exp_ref_block[ch];
1355 quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1356 ref_block->exp[ch], ref_block->bap[ch],
1357 block->qmant[ch], s->nb_coefs[ch]);
1364 * Write the AC-3 frame header to the output bitstream.
1366 static void output_frame_header(AC3EncodeContext *s)
1368 AC3EncOptions *opt = &s->options;
1370 put_bits(&s->pb, 16, 0x0b77); /* frame header */
1371 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
1372 put_bits(&s->pb, 2, s->bit_alloc.sr_code);
1373 put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1374 put_bits(&s->pb, 5, s->bitstream_id);
1375 put_bits(&s->pb, 3, s->bitstream_mode);
1376 put_bits(&s->pb, 3, s->channel_mode);
1377 if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1378 put_bits(&s->pb, 2, s->center_mix_level);
1379 if (s->channel_mode & 0x04)
1380 put_bits(&s->pb, 2, s->surround_mix_level);
1381 if (s->channel_mode == AC3_CHMODE_STEREO)
1382 put_bits(&s->pb, 2, opt->dolby_surround_mode);
1383 put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1384 put_bits(&s->pb, 5, -opt->dialogue_level);
1385 put_bits(&s->pb, 1, 0); /* no compression control word */
1386 put_bits(&s->pb, 1, 0); /* no lang code */
1387 put_bits(&s->pb, 1, opt->audio_production_info);
1388 if (opt->audio_production_info) {
1389 put_bits(&s->pb, 5, opt->mixing_level - 80);
1390 put_bits(&s->pb, 2, opt->room_type);
1392 put_bits(&s->pb, 1, opt->copyright);
1393 put_bits(&s->pb, 1, opt->original);
1394 if (s->bitstream_id == 6) {
1395 /* alternate bit stream syntax */
1396 put_bits(&s->pb, 1, opt->extended_bsi_1);
1397 if (opt->extended_bsi_1) {
1398 put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1399 put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1400 put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1401 put_bits(&s->pb, 3, s->loro_center_mix_level);
1402 put_bits(&s->pb, 3, s->loro_surround_mix_level);
1404 put_bits(&s->pb, 1, opt->extended_bsi_2);
1405 if (opt->extended_bsi_2) {
1406 put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1407 put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1408 put_bits(&s->pb, 1, opt->ad_converter_type);
1409 put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
1412 put_bits(&s->pb, 1, 0); /* no time code 1 */
1413 put_bits(&s->pb, 1, 0); /* no time code 2 */
1415 put_bits(&s->pb, 1, 0); /* no additional bit stream info */
1420 * Write one audio block to the output bitstream.
1422 static void output_audio_block(AC3EncodeContext *s, int blk)
1424 int ch, i, baie, rbnd;
1425 AC3Block *block = &s->blocks[blk];
1427 /* block switching */
1428 for (ch = 0; ch < s->fbw_channels; ch++)
1429 put_bits(&s->pb, 1, 0);
1432 for (ch = 0; ch < s->fbw_channels; ch++)
1433 put_bits(&s->pb, 1, 1);
1435 /* dynamic range codes */
1436 put_bits(&s->pb, 1, 0);
1438 /* channel coupling */
1440 put_bits(&s->pb, 1, 1); /* coupling strategy present */
1441 put_bits(&s->pb, 1, 0); /* no coupling strategy */
1443 put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1446 /* stereo rematrixing */
1447 if (s->channel_mode == AC3_CHMODE_STEREO) {
1448 put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1449 if (block->new_rematrixing_strategy) {
1450 /* rematrixing flags */
1451 for (rbnd = 0; rbnd < s->num_rematrixing_bands; rbnd++)
1452 put_bits(&s->pb, 1, block->rematrixing_flags[rbnd]);
1456 /* exponent strategy */
1457 for (ch = 0; ch < s->fbw_channels; ch++)
1458 put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1460 put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1463 for (ch = 0; ch < s->fbw_channels; ch++) {
1464 if (s->exp_strategy[ch][blk] != EXP_REUSE)
1465 put_bits(&s->pb, 6, s->bandwidth_code[ch]);
1469 for (ch = 0; ch < s->channels; ch++) {
1472 if (s->exp_strategy[ch][blk] == EXP_REUSE)
1476 put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1478 /* exponent groups */
1479 nb_groups = exponent_group_tab[s->exp_strategy[ch][blk]-1][s->nb_coefs[ch]];
1480 for (i = 1; i <= nb_groups; i++)
1481 put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1483 /* gain range info */
1484 if (ch != s->lfe_channel)
1485 put_bits(&s->pb, 2, 0);
1488 /* bit allocation info */
1490 put_bits(&s->pb, 1, baie);
1492 put_bits(&s->pb, 2, s->slow_decay_code);
1493 put_bits(&s->pb, 2, s->fast_decay_code);
1494 put_bits(&s->pb, 2, s->slow_gain_code);
1495 put_bits(&s->pb, 2, s->db_per_bit_code);
1496 put_bits(&s->pb, 3, s->floor_code);
1500 put_bits(&s->pb, 1, baie);
1502 put_bits(&s->pb, 6, s->coarse_snr_offset);
1503 for (ch = 0; ch < s->channels; ch++) {
1504 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1505 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1509 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1510 put_bits(&s->pb, 1, 0); /* no data to skip */
1513 for (ch = 0; ch < s->channels; ch++) {
1515 AC3Block *ref_block = block->exp_ref_block[ch];
1516 for (i = 0; i < s->nb_coefs[ch]; i++) {
1517 q = block->qmant[ch][i];
1518 b = ref_block->bap[ch][i];
1521 case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
1522 case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
1523 case 3: put_bits(&s->pb, 3, q); break;
1524 case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
1525 case 14: put_bits(&s->pb, 14, q); break;
1526 case 15: put_bits(&s->pb, 16, q); break;
1527 default: put_bits(&s->pb, b-1, q); break;
1534 /** CRC-16 Polynomial */
1535 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1538 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1555 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1561 r = mul_poly(r, a, poly);
1562 a = mul_poly(a, a, poly);
1570 * Fill the end of the frame with 0's and compute the two CRCs.
1572 static void output_frame_end(AC3EncodeContext *s)
1574 const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1575 int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1578 frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1580 /* pad the remainder of the frame with zeros */
1581 av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1582 flush_put_bits(&s->pb);
1584 pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1585 av_assert2(pad_bytes >= 0);
1587 memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1590 /* this is not so easy because it is at the beginning of the data... */
1591 crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1592 crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1593 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1594 AV_WB16(frame + 2, crc1);
1597 crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1598 s->frame_size - frame_size_58 - 3);
1599 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1600 /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1601 if (crc2 == 0x770B) {
1602 frame[s->frame_size - 3] ^= 0x1;
1603 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1605 crc2 = av_bswap16(crc2);
1606 AV_WB16(frame + s->frame_size - 2, crc2);
1611 * Write the frame to the output bitstream.
1613 static void output_frame(AC3EncodeContext *s, unsigned char *frame)
1617 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1619 output_frame_header(s);
1621 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1622 output_audio_block(s, blk);
1624 output_frame_end(s);
1628 static void dprint_options(AVCodecContext *avctx)
1631 AC3EncodeContext *s = avctx->priv_data;
1632 AC3EncOptions *opt = &s->options;
1635 switch (s->bitstream_id) {
1636 case 6: strncpy(strbuf, "AC-3 (alt syntax)", 32); break;
1637 case 8: strncpy(strbuf, "AC-3 (standard)", 32); break;
1638 case 9: strncpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
1639 case 10: strncpy(strbuf, "AC-3 (dnet quater-rate", 32); break;
1640 default: snprintf(strbuf, 32, "ERROR");
1642 av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
1643 av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
1644 av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
1645 av_dlog(avctx, "channel_layout: %s\n", strbuf);
1646 av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
1647 av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
1649 av_dlog(avctx, "cutoff: %d\n", s->cutoff);
1651 av_dlog(avctx, "per_frame_metadata: %s\n",
1652 opt->allow_per_frame_metadata?"on":"off");
1654 av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
1655 s->center_mix_level);
1657 av_dlog(avctx, "center_mixlev: {not written}\n");
1658 if (s->has_surround)
1659 av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
1660 s->surround_mix_level);
1662 av_dlog(avctx, "surround_mixlev: {not written}\n");
1663 if (opt->audio_production_info) {
1664 av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
1665 switch (opt->room_type) {
1666 case 0: strncpy(strbuf, "notindicated", 32); break;
1667 case 1: strncpy(strbuf, "large", 32); break;
1668 case 2: strncpy(strbuf, "small", 32); break;
1669 default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
1671 av_dlog(avctx, "room_type: %s\n", strbuf);
1673 av_dlog(avctx, "mixing_level: {not written}\n");
1674 av_dlog(avctx, "room_type: {not written}\n");
1676 av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
1677 av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
1678 if (s->channel_mode == AC3_CHMODE_STEREO) {
1679 switch (opt->dolby_surround_mode) {
1680 case 0: strncpy(strbuf, "notindicated", 32); break;
1681 case 1: strncpy(strbuf, "on", 32); break;
1682 case 2: strncpy(strbuf, "off", 32); break;
1683 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
1685 av_dlog(avctx, "dsur_mode: %s\n", strbuf);
1687 av_dlog(avctx, "dsur_mode: {not written}\n");
1689 av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
1691 if (s->bitstream_id == 6) {
1692 if (opt->extended_bsi_1) {
1693 switch (opt->preferred_stereo_downmix) {
1694 case 0: strncpy(strbuf, "notindicated", 32); break;
1695 case 1: strncpy(strbuf, "ltrt", 32); break;
1696 case 2: strncpy(strbuf, "loro", 32); break;
1697 default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
1699 av_dlog(avctx, "dmix_mode: %s\n", strbuf);
1700 av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
1701 opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
1702 av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
1703 opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
1704 av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
1705 opt->loro_center_mix_level, s->loro_center_mix_level);
1706 av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
1707 opt->loro_surround_mix_level, s->loro_surround_mix_level);
1709 av_dlog(avctx, "extended bitstream info 1: {not written}\n");
1711 if (opt->extended_bsi_2) {
1712 switch (opt->dolby_surround_ex_mode) {
1713 case 0: strncpy(strbuf, "notindicated", 32); break;
1714 case 1: strncpy(strbuf, "on", 32); break;
1715 case 2: strncpy(strbuf, "off", 32); break;
1716 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
1718 av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
1719 switch (opt->dolby_headphone_mode) {
1720 case 0: strncpy(strbuf, "notindicated", 32); break;
1721 case 1: strncpy(strbuf, "on", 32); break;
1722 case 2: strncpy(strbuf, "off", 32); break;
1723 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
1725 av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
1727 switch (opt->ad_converter_type) {
1728 case 0: strncpy(strbuf, "standard", 32); break;
1729 case 1: strncpy(strbuf, "hdcd", 32); break;
1730 default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
1732 av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
1734 av_dlog(avctx, "extended bitstream info 2: {not written}\n");
1741 #define FLT_OPTION_THRESHOLD 0.01
1743 static int validate_float_option(float v, const float *v_list, int v_list_size)
1747 for (i = 0; i < v_list_size; i++) {
1748 if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
1749 v > (v_list[i] - FLT_OPTION_THRESHOLD))
1752 if (i == v_list_size)
1759 static void validate_mix_level(void *log_ctx, const char *opt_name,
1760 float *opt_param, const float *list,
1761 int list_size, int default_value, int min_value,
1764 int mixlev = validate_float_option(*opt_param, list, list_size);
1765 if (mixlev < min_value) {
1766 mixlev = default_value;
1767 if (*opt_param >= 0.0) {
1768 av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
1769 "default value: %0.3f\n", opt_name, list[mixlev]);
1772 *opt_param = list[mixlev];
1773 *ctx_param = mixlev;
1778 * Validate metadata options as set by AVOption system.
1779 * These values can optionally be changed per-frame.
1781 static int validate_metadata(AVCodecContext *avctx)
1783 AC3EncodeContext *s = avctx->priv_data;
1784 AC3EncOptions *opt = &s->options;
1786 /* validate mixing levels */
1787 if (s->has_center) {
1788 validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
1789 cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
1790 &s->center_mix_level);
1792 if (s->has_surround) {
1793 validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
1794 surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
1795 &s->surround_mix_level);
1798 /* set audio production info flag */
1799 if (opt->mixing_level >= 0 || opt->room_type >= 0) {
1800 if (opt->mixing_level < 0) {
1801 av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
1802 "room_type is set\n");
1803 return AVERROR(EINVAL);
1805 if (opt->mixing_level < 80) {
1806 av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
1807 "80dB and 111dB\n");
1808 return AVERROR(EINVAL);
1810 /* default room type */
1811 if (opt->room_type < 0)
1813 opt->audio_production_info = 1;
1815 opt->audio_production_info = 0;
1818 /* set extended bsi 1 flag */
1819 if ((s->has_center || s->has_surround) &&
1820 (opt->preferred_stereo_downmix >= 0 ||
1821 opt->ltrt_center_mix_level >= 0 ||
1822 opt->ltrt_surround_mix_level >= 0 ||
1823 opt->loro_center_mix_level >= 0 ||
1824 opt->loro_surround_mix_level >= 0)) {
1825 /* default preferred stereo downmix */
1826 if (opt->preferred_stereo_downmix < 0)
1827 opt->preferred_stereo_downmix = 0;
1828 /* validate Lt/Rt center mix level */
1829 validate_mix_level(avctx, "ltrt_center_mix_level",
1830 &opt->ltrt_center_mix_level, extmixlev_options,
1831 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1832 &s->ltrt_center_mix_level);
1833 /* validate Lt/Rt surround mix level */
1834 validate_mix_level(avctx, "ltrt_surround_mix_level",
1835 &opt->ltrt_surround_mix_level, extmixlev_options,
1836 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1837 &s->ltrt_surround_mix_level);
1838 /* validate Lo/Ro center mix level */
1839 validate_mix_level(avctx, "loro_center_mix_level",
1840 &opt->loro_center_mix_level, extmixlev_options,
1841 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1842 &s->loro_center_mix_level);
1843 /* validate Lo/Ro surround mix level */
1844 validate_mix_level(avctx, "loro_surround_mix_level",
1845 &opt->loro_surround_mix_level, extmixlev_options,
1846 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1847 &s->loro_surround_mix_level);
1848 opt->extended_bsi_1 = 1;
1850 opt->extended_bsi_1 = 0;
1853 /* set extended bsi 2 flag */
1854 if (opt->dolby_surround_ex_mode >= 0 ||
1855 opt->dolby_headphone_mode >= 0 ||
1856 opt->ad_converter_type >= 0) {
1857 /* default dolby surround ex mode */
1858 if (opt->dolby_surround_ex_mode < 0)
1859 opt->dolby_surround_ex_mode = 0;
1860 /* default dolby headphone mode */
1861 if (opt->dolby_headphone_mode < 0)
1862 opt->dolby_headphone_mode = 0;
1863 /* default A/D converter type */
1864 if (opt->ad_converter_type < 0)
1865 opt->ad_converter_type = 0;
1866 opt->extended_bsi_2 = 1;
1868 opt->extended_bsi_2 = 0;
1871 /* set bitstream id for alternate bitstream syntax */
1872 if (opt->extended_bsi_1 || opt->extended_bsi_2) {
1873 if (s->bitstream_id > 8 && s->bitstream_id < 11) {
1874 static int warn_once = 1;
1876 av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
1877 "not compatible with reduced samplerates. writing of "
1878 "extended bitstream information will be disabled.\n");
1882 s->bitstream_id = 6;
1891 * Encode a single AC-3 frame.
1893 static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
1894 int buf_size, void *data)
1896 AC3EncodeContext *s = avctx->priv_data;
1897 const SampleType *samples = data;
1900 if (s->options.allow_per_frame_metadata) {
1901 ret = validate_metadata(avctx);
1906 if (s->bit_alloc.sr_code == 1)
1907 adjust_frame_size(s);
1909 deinterleave_input_samples(s, samples);
1913 scale_coefficients(s);
1915 compute_rematrixing_strategy(s);
1917 apply_rematrixing(s);
1919 process_exponents(s);
1921 ret = compute_bit_allocation(s);
1923 av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1927 quantize_mantissas(s);
1929 output_frame(s, frame);
1931 return s->frame_size;
1936 * Finalize encoding and free any memory allocated by the encoder.
1938 static av_cold int ac3_encode_close(AVCodecContext *avctx)
1941 AC3EncodeContext *s = avctx->priv_data;
1943 for (ch = 0; ch < s->channels; ch++)
1944 av_freep(&s->planar_samples[ch]);
1945 av_freep(&s->planar_samples);
1946 av_freep(&s->bap_buffer);
1947 av_freep(&s->bap1_buffer);
1948 av_freep(&s->mdct_coef_buffer);
1949 av_freep(&s->fixed_coef_buffer);
1950 av_freep(&s->exp_buffer);
1951 av_freep(&s->grouped_exp_buffer);
1952 av_freep(&s->psd_buffer);
1953 av_freep(&s->band_psd_buffer);
1954 av_freep(&s->mask_buffer);
1955 av_freep(&s->qmant_buffer);
1956 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1957 AC3Block *block = &s->blocks[blk];
1958 av_freep(&block->bap);
1959 av_freep(&block->mdct_coef);
1960 av_freep(&block->fixed_coef);
1961 av_freep(&block->exp);
1962 av_freep(&block->grouped_exp);
1963 av_freep(&block->psd);
1964 av_freep(&block->band_psd);
1965 av_freep(&block->mask);
1966 av_freep(&block->qmant);
1971 av_freep(&avctx->coded_frame);
1977 * Set channel information during initialization.
1979 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1980 int64_t *channel_layout)
1984 if (channels < 1 || channels > AC3_MAX_CHANNELS)
1985 return AVERROR(EINVAL);
1986 if ((uint64_t)*channel_layout > 0x7FF)
1987 return AVERROR(EINVAL);
1988 ch_layout = *channel_layout;
1990 ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1991 if (av_get_channel_layout_nb_channels(ch_layout) != channels)
1992 return AVERROR(EINVAL);
1994 s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1995 s->channels = channels;
1996 s->fbw_channels = channels - s->lfe_on;
1997 s->lfe_channel = s->lfe_on ? s->fbw_channels : -1;
1999 ch_layout -= AV_CH_LOW_FREQUENCY;
2001 switch (ch_layout) {
2002 case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
2003 case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
2004 case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
2005 case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
2006 case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
2007 case AV_CH_LAYOUT_QUAD:
2008 case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
2009 case AV_CH_LAYOUT_5POINT0:
2010 case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
2012 return AVERROR(EINVAL);
2014 s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
2015 s->has_surround = s->channel_mode & 0x04;
2017 s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
2018 *channel_layout = ch_layout;
2020 *channel_layout |= AV_CH_LOW_FREQUENCY;
2026 static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
2030 /* validate channel layout */
2031 if (!avctx->channel_layout) {
2032 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
2033 "encoder will guess the layout, but it "
2034 "might be incorrect.\n");
2036 ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
2038 av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
2042 /* validate sample rate */
2043 for (i = 0; i < 9; i++) {
2044 if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
2048 av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
2049 return AVERROR(EINVAL);
2051 s->sample_rate = avctx->sample_rate;
2052 s->bit_alloc.sr_shift = i % 3;
2053 s->bit_alloc.sr_code = i / 3;
2054 s->bitstream_id = 8 + s->bit_alloc.sr_shift;
2056 /* validate bit rate */
2057 for (i = 0; i < 19; i++) {
2058 if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
2062 av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2063 return AVERROR(EINVAL);
2065 s->bit_rate = avctx->bit_rate;
2066 s->frame_size_code = i << 1;
2068 /* validate cutoff */
2069 if (avctx->cutoff < 0) {
2070 av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2071 return AVERROR(EINVAL);
2073 s->cutoff = avctx->cutoff;
2074 if (s->cutoff > (s->sample_rate >> 1))
2075 s->cutoff = s->sample_rate >> 1;
2077 /* validate audio service type / channels combination */
2078 if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
2079 avctx->channels == 1) ||
2080 ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
2081 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
2082 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
2083 && avctx->channels > 1)) {
2084 av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
2085 "specified number of channels\n");
2086 return AVERROR(EINVAL);
2089 ret = validate_metadata(avctx);
2098 * Set bandwidth for all channels.
2099 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2100 * default value will be used.
2102 static av_cold void set_bandwidth(AC3EncodeContext *s)
2107 /* calculate bandwidth based on user-specified cutoff frequency */
2109 fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2110 bw_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2112 /* use default bandwidth setting */
2113 bw_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2116 /* set number of coefficients for each channel */
2117 for (ch = 0; ch < s->fbw_channels; ch++) {
2118 s->bandwidth_code[ch] = bw_code;
2119 s->nb_coefs[ch] = bw_code * 3 + 73;
2122 s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
2126 static av_cold int allocate_buffers(AVCodecContext *avctx)
2129 AC3EncodeContext *s = avctx->priv_data;
2131 FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
2133 for (ch = 0; ch < s->channels; ch++) {
2134 FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
2135 (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
2138 FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * s->channels *
2139 AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
2140 FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
2141 AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
2142 FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
2143 AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
2144 FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
2145 AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
2146 FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
2147 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
2148 FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
2149 AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
2150 FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
2151 64 * sizeof(*s->band_psd_buffer), alloc_fail);
2152 FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
2153 64 * sizeof(*s->mask_buffer), alloc_fail);
2154 FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
2155 AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
2156 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2157 AC3Block *block = &s->blocks[blk];
2158 FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
2160 FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
2162 FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
2164 FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
2166 FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
2168 FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
2170 FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
2172 FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
2175 for (ch = 0; ch < s->channels; ch++) {
2176 /* arrangement: block, channel, coeff */
2177 block->bap[ch] = &s->bap_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2178 block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2179 block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * s->channels + ch)];
2180 block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2181 block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * s->channels + ch)];
2182 block->mask[ch] = &s->mask_buffer [64 * (blk * s->channels + ch)];
2183 block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2185 /* arrangement: channel, block, coeff */
2186 block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2190 if (CONFIG_AC3ENC_FLOAT) {
2191 FF_ALLOC_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * s->channels *
2192 AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
2193 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2194 AC3Block *block = &s->blocks[blk];
2195 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2196 sizeof(*block->fixed_coef), alloc_fail);
2197 for (ch = 0; ch < s->channels; ch++)
2198 block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
2201 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2202 AC3Block *block = &s->blocks[blk];
2203 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2204 sizeof(*block->fixed_coef), alloc_fail);
2205 for (ch = 0; ch < s->channels; ch++)
2206 block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2212 return AVERROR(ENOMEM);
2217 * Initialize the encoder.
2219 static av_cold int ac3_encode_init(AVCodecContext *avctx)
2221 AC3EncodeContext *s = avctx->priv_data;
2222 int ret, frame_size_58;
2224 avctx->frame_size = AC3_FRAME_SIZE;
2226 ff_ac3_common_init();
2228 ret = validate_options(avctx, s);
2232 s->bitstream_mode = avctx->audio_service_type;
2233 if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2234 s->bitstream_mode = 0x7;
2236 s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2237 s->bits_written = 0;
2238 s->samples_written = 0;
2239 s->frame_size = s->frame_size_min;
2241 /* calculate crc_inv for both possible frame sizes */
2242 frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
2243 s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2244 if (s->bit_alloc.sr_code == 1) {
2245 frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2246 s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2251 rematrixing_init(s);
2257 ret = mdct_init(avctx, &s->mdct, 9);
2261 ret = allocate_buffers(avctx);
2265 avctx->coded_frame= avcodec_alloc_frame();
2267 dsputil_init(&s->dsp, avctx);
2268 ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2270 dprint_options(avctx);
2274 ac3_encode_close(avctx);