2 * The simplest AC-3 encoder
3 * Copyright (c) 2000 Fabrice Bellard
4 * Copyright (c) 2006-2010 Justin Ruggles <justin.ruggles@gmail.com>
5 * Copyright (c) 2006-2010 Prakash Punnoor <prakash@punnoor.de>
7 * This file is part of FFmpeg.
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 * The simplest AC-3 encoder.
30 //#define ASSERT_LEVEL 2
32 #include "libavutil/audioconvert.h"
33 #include "libavutil/avassert.h"
34 #include "libavutil/crc.h"
35 #include "libavutil/opt.h"
41 #include "audioconvert.h"
44 #ifndef CONFIG_AC3ENC_FLOAT
45 #define CONFIG_AC3ENC_FLOAT 0
49 /** Maximum number of exponent groups. +1 for separate DC exponent. */
50 #define AC3_MAX_EXP_GROUPS 85
52 /* stereo rematrixing algorithms */
53 #define AC3_REMATRIXING_IS_STATIC 0x1
54 #define AC3_REMATRIXING_SUMS 0
55 #define AC3_REMATRIXING_NONE 1
56 #define AC3_REMATRIXING_ALWAYS 3
58 /** Scale a float value by 2^bits and convert to an integer. */
59 #define SCALE_FLOAT(a, bits) lrintf((a) * (float)(1 << (bits)))
62 #if CONFIG_AC3ENC_FLOAT
63 #include "ac3enc_float.h"
65 #include "ac3enc_fixed.h"
70 * Encoding Options used by AVOption.
72 typedef struct AC3EncOptions {
73 /* AC-3 metadata options*/
76 float center_mix_level;
77 float surround_mix_level;
78 int dolby_surround_mode;
79 int audio_production_info;
85 int preferred_stereo_downmix;
86 float ltrt_center_mix_level;
87 float ltrt_surround_mix_level;
88 float loro_center_mix_level;
89 float loro_surround_mix_level;
91 int dolby_surround_ex_mode;
92 int dolby_headphone_mode;
93 int ad_converter_type;
95 /* other encoding options */
96 int allow_per_frame_metadata;
100 * Data for a single audio block.
102 typedef struct AC3Block {
103 uint8_t **bap; ///< bit allocation pointers (bap)
104 CoefType **mdct_coef; ///< MDCT coefficients
105 int32_t **fixed_coef; ///< fixed-point MDCT coefficients
106 uint8_t **exp; ///< original exponents
107 uint8_t **grouped_exp; ///< grouped exponents
108 int16_t **psd; ///< psd per frequency bin
109 int16_t **band_psd; ///< psd per critical band
110 int16_t **mask; ///< masking curve
111 uint16_t **qmant; ///< quantized mantissas
112 uint8_t coeff_shift[AC3_MAX_CHANNELS]; ///< fixed-point coefficient shift values
113 uint8_t new_rematrixing_strategy; ///< send new rematrixing flags in this block
114 uint8_t rematrixing_flags[4]; ///< rematrixing flags
115 struct AC3Block *exp_ref_block[AC3_MAX_CHANNELS]; ///< reference blocks for EXP_REUSE
119 * AC-3 encoder private context.
121 typedef struct AC3EncodeContext {
122 AVClass *av_class; ///< AVClass used for AVOption
123 AC3EncOptions options; ///< encoding options
124 PutBitContext pb; ///< bitstream writer context
126 AC3DSPContext ac3dsp; ///< AC-3 optimized functions
127 AC3MDCTContext mdct; ///< MDCT context
129 AC3Block blocks[AC3_MAX_BLOCKS]; ///< per-block info
131 int bitstream_id; ///< bitstream id (bsid)
132 int bitstream_mode; ///< bitstream mode (bsmod)
134 int bit_rate; ///< target bit rate, in bits-per-second
135 int sample_rate; ///< sampling frequency, in Hz
137 int frame_size_min; ///< minimum frame size in case rounding is necessary
138 int frame_size; ///< current frame size in bytes
139 int frame_size_code; ///< frame size code (frmsizecod)
141 int bits_written; ///< bit count (used to avg. bitrate)
142 int samples_written; ///< sample count (used to avg. bitrate)
144 int fbw_channels; ///< number of full-bandwidth channels (nfchans)
145 int channels; ///< total number of channels (nchans)
146 int lfe_on; ///< indicates if there is an LFE channel (lfeon)
147 int lfe_channel; ///< channel index of the LFE channel
148 int has_center; ///< indicates if there is a center channel
149 int has_surround; ///< indicates if there are one or more surround channels
150 int channel_mode; ///< channel mode (acmod)
151 const uint8_t *channel_map; ///< channel map used to reorder channels
153 int center_mix_level; ///< center mix level code
154 int surround_mix_level; ///< surround mix level code
155 int ltrt_center_mix_level; ///< Lt/Rt center mix level code
156 int ltrt_surround_mix_level; ///< Lt/Rt surround mix level code
157 int loro_center_mix_level; ///< Lo/Ro center mix level code
158 int loro_surround_mix_level; ///< Lo/Ro surround mix level code
160 int cutoff; ///< user-specified cutoff frequency, in Hz
161 int bandwidth_code[AC3_MAX_CHANNELS]; ///< bandwidth code (0 to 60) (chbwcod)
162 int nb_coefs[AC3_MAX_CHANNELS];
164 int rematrixing; ///< determines how rematrixing strategy is calculated
165 int num_rematrixing_bands; ///< number of rematrixing bands
167 /* bitrate allocation control */
168 int slow_gain_code; ///< slow gain code (sgaincod)
169 int slow_decay_code; ///< slow decay code (sdcycod)
170 int fast_decay_code; ///< fast decay code (fdcycod)
171 int db_per_bit_code; ///< dB/bit code (dbpbcod)
172 int floor_code; ///< floor code (floorcod)
173 AC3BitAllocParameters bit_alloc; ///< bit allocation parameters
174 int coarse_snr_offset; ///< coarse SNR offsets (csnroffst)
175 int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signal-to-mask ratio) (fgaincod)
176 int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst)
177 int frame_bits_fixed; ///< number of non-coefficient bits for fixed parameters
178 int frame_bits; ///< all frame bits except exponents and mantissas
179 int exponent_bits; ///< number of bits used for exponents
181 SampleType **planar_samples;
183 uint8_t *bap1_buffer;
184 CoefType *mdct_coef_buffer;
185 int32_t *fixed_coef_buffer;
187 uint8_t *grouped_exp_buffer;
189 int16_t *band_psd_buffer;
190 int16_t *mask_buffer;
191 uint16_t *qmant_buffer;
193 uint8_t exp_strategy[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< exponent strategies
195 DECLARE_ALIGNED(16, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
198 typedef struct AC3Mant {
199 uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
200 int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
203 #define CMIXLEV_NUM_OPTIONS 3
204 static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
205 LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
208 #define SURMIXLEV_NUM_OPTIONS 3
209 static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
210 LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
213 #define EXTMIXLEV_NUM_OPTIONS 8
214 static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
215 LEVEL_PLUS_3DB, LEVEL_PLUS_1POINT5DB, LEVEL_ONE, LEVEL_MINUS_4POINT5DB,
216 LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
220 #define OFFSET(param) offsetof(AC3EncodeContext, options.param)
221 #define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
223 static const AVOption options[] = {
224 /* Metadata Options */
225 {"per_frame_metadata", "Allow Changing Metadata Per-Frame", OFFSET(allow_per_frame_metadata), FF_OPT_TYPE_INT, 0, 0, 1, AC3ENC_PARAM},
227 {"center_mixlev", "Center Mix Level", OFFSET(center_mix_level), FF_OPT_TYPE_FLOAT, LEVEL_MINUS_4POINT5DB, 0.0, 1.0, AC3ENC_PARAM},
228 {"surround_mixlev", "Surround Mix Level", OFFSET(surround_mix_level), FF_OPT_TYPE_FLOAT, LEVEL_MINUS_6DB, 0.0, 1.0, AC3ENC_PARAM},
229 /* audio production information */
230 {"mixing_level", "Mixing Level", OFFSET(mixing_level), FF_OPT_TYPE_INT, -1, -1, 111, AC3ENC_PARAM},
231 {"room_type", "Room Type", OFFSET(room_type), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "room_type"},
232 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
233 {"large", "Large Room", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
234 {"small", "Small Room", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
235 /* other metadata options */
236 {"copyright", "Copyright Bit", OFFSET(copyright), FF_OPT_TYPE_INT, 0, 0, 1, AC3ENC_PARAM},
237 {"dialnorm", "Dialogue Level (dB)", OFFSET(dialogue_level), FF_OPT_TYPE_INT, -31, -31, -1, AC3ENC_PARAM},
238 {"dsur_mode", "Dolby Surround Mode", OFFSET(dolby_surround_mode), FF_OPT_TYPE_INT, 0, 0, 2, AC3ENC_PARAM, "dsur_mode"},
239 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
240 {"on", "Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
241 {"off", "Not Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
242 {"original", "Original Bit Stream", OFFSET(original), FF_OPT_TYPE_INT, 1, 0, 1, AC3ENC_PARAM},
243 /* extended bitstream information */
244 {"dmix_mode", "Preferred Stereo Downmix Mode", OFFSET(preferred_stereo_downmix), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "dmix_mode"},
245 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
246 {"ltrt", "Lt/Rt Downmix Preferred", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
247 {"loro", "Lo/Ro Downmix Preferred", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
248 {"ltrt_cmixlev", "Lt/Rt Center Mix Level", OFFSET(ltrt_center_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
249 {"ltrt_surmixlev", "Lt/Rt Surround Mix Level", OFFSET(ltrt_surround_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
250 {"loro_cmixlev", "Lo/Ro Center Mix Level", OFFSET(loro_center_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
251 {"loro_surmixlev", "Lo/Ro Surround Mix Level", OFFSET(loro_surround_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
252 {"dsurex_mode", "Dolby Surround EX Mode", OFFSET(dolby_surround_ex_mode), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "dsurex_mode"},
253 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
254 {"on", "Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
255 {"off", "Not Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
256 {"dheadphone_mode", "Dolby Headphone Mode", OFFSET(dolby_headphone_mode), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "dheadphone_mode"},
257 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
258 {"on", "Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
259 {"off", "Not Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
260 {"ad_conv_type", "A/D Converter Type", OFFSET(ad_converter_type), FF_OPT_TYPE_INT, -1, -1, 1, AC3ENC_PARAM, "ad_conv_type"},
261 {"standard", "Standard (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
262 {"hdcd", "HDCD", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
266 #if CONFIG_AC3ENC_FLOAT
267 static AVClass ac3enc_class = { "AC-3 Encoder", av_default_item_name,
268 options, LIBAVUTIL_VERSION_INT };
270 static AVClass ac3enc_class = { "Fixed-Point AC-3 Encoder", av_default_item_name,
271 options, LIBAVUTIL_VERSION_INT };
275 /* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
277 static av_cold void mdct_end(AC3MDCTContext *mdct);
279 static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
282 static void mdct512(AC3MDCTContext *mdct, CoefType *out, SampleType *in);
284 static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
285 const SampleType *window, unsigned int len);
287 static int normalize_samples(AC3EncodeContext *s);
289 static void scale_coefficients(AC3EncodeContext *s);
293 * LUT for number of exponent groups.
294 * exponent_group_tab[exponent strategy-1][number of coefficients]
296 static uint8_t exponent_group_tab[3][256];
300 * List of supported channel layouts.
302 static const int64_t ac3_channel_layouts[] = {
306 AV_CH_LAYOUT_SURROUND,
309 AV_CH_LAYOUT_4POINT0,
310 AV_CH_LAYOUT_5POINT0,
311 AV_CH_LAYOUT_5POINT0_BACK,
312 (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
313 (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
314 (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
315 (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
316 (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
317 (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
318 (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
319 AV_CH_LAYOUT_5POINT1,
320 AV_CH_LAYOUT_5POINT1_BACK,
326 * Adjust the frame size to make the average bit rate match the target bit rate.
327 * This is only needed for 11025, 22050, and 44100 sample rates.
329 static void adjust_frame_size(AC3EncodeContext *s)
331 while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
332 s->bits_written -= s->bit_rate;
333 s->samples_written -= s->sample_rate;
335 s->frame_size = s->frame_size_min +
336 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
337 s->bits_written += s->frame_size * 8;
338 s->samples_written += AC3_FRAME_SIZE;
343 * Deinterleave input samples.
344 * Channels are reordered from FFmpeg's default order to AC-3 order.
346 static void deinterleave_input_samples(AC3EncodeContext *s,
347 const SampleType *samples)
351 /* deinterleave and remap input samples */
352 for (ch = 0; ch < s->channels; ch++) {
353 const SampleType *sptr;
356 /* copy last 256 samples of previous frame to the start of the current frame */
357 memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
358 AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
362 sptr = samples + s->channel_map[ch];
363 for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
364 s->planar_samples[ch][i] = *sptr;
372 * Apply the MDCT to input samples to generate frequency coefficients.
373 * This applies the KBD window and normalizes the input to reduce precision
374 * loss due to fixed-point calculations.
376 static void apply_mdct(AC3EncodeContext *s)
380 for (ch = 0; ch < s->channels; ch++) {
381 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
382 AC3Block *block = &s->blocks[blk];
383 const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
385 apply_window(&s->dsp, s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
387 block->coeff_shift[ch] = normalize_samples(s);
389 mdct512(&s->mdct, block->mdct_coef[ch], s->windowed_samples);
396 * Initialize stereo rematrixing.
397 * If the strategy does not change for each frame, set the rematrixing flags.
399 static void rematrixing_init(AC3EncodeContext *s)
401 if (s->channel_mode == AC3_CHMODE_STEREO)
402 s->rematrixing = AC3_REMATRIXING_SUMS;
404 s->rematrixing = AC3_REMATRIXING_NONE;
405 /* NOTE: AC3_REMATRIXING_ALWAYS might be used in
406 the future in conjunction with channel coupling. */
408 if (s->rematrixing & AC3_REMATRIXING_IS_STATIC) {
409 int flag = (s->rematrixing == AC3_REMATRIXING_ALWAYS);
410 s->blocks[0].new_rematrixing_strategy = 1;
411 memset(s->blocks[0].rematrixing_flags, flag,
412 sizeof(s->blocks[0].rematrixing_flags));
418 * Determine rematrixing flags for each block and band.
420 static void compute_rematrixing_strategy(AC3EncodeContext *s)
424 AC3Block *block, *block0;
426 s->num_rematrixing_bands = 4;
428 if (s->rematrixing & AC3_REMATRIXING_IS_STATIC)
431 nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
433 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
434 block = &s->blocks[blk];
435 block->new_rematrixing_strategy = !blk;
436 for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
437 /* calculate calculate sum of squared coeffs for one band in one block */
438 int start = ff_ac3_rematrix_band_tab[bnd];
439 int end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
440 CoefSumType sum[4] = {0,};
441 for (i = start; i < end; i++) {
442 CoefType lt = block->mdct_coef[0][i];
443 CoefType rt = block->mdct_coef[1][i];
444 CoefType md = lt + rt;
445 CoefType sd = lt - rt;
446 MAC_COEF(sum[0], lt, lt);
447 MAC_COEF(sum[1], rt, rt);
448 MAC_COEF(sum[2], md, md);
449 MAC_COEF(sum[3], sd, sd);
452 /* compare sums to determine if rematrixing will be used for this band */
453 if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
454 block->rematrixing_flags[bnd] = 1;
456 block->rematrixing_flags[bnd] = 0;
458 /* determine if new rematrixing flags will be sent */
460 block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
461 block->new_rematrixing_strategy = 1;
470 * Apply stereo rematrixing to coefficients based on rematrixing flags.
472 static void apply_rematrixing(AC3EncodeContext *s)
479 if (s->rematrixing == AC3_REMATRIXING_NONE)
482 nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
484 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
485 AC3Block *block = &s->blocks[blk];
486 if (block->new_rematrixing_strategy)
487 flags = block->rematrixing_flags;
488 for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
490 start = ff_ac3_rematrix_band_tab[bnd];
491 end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
492 for (i = start; i < end; i++) {
493 int32_t lt = block->fixed_coef[0][i];
494 int32_t rt = block->fixed_coef[1][i];
495 block->fixed_coef[0][i] = (lt + rt) >> 1;
496 block->fixed_coef[1][i] = (lt - rt) >> 1;
505 * Initialize exponent tables.
507 static av_cold void exponent_init(AC3EncodeContext *s)
510 for (i = 73; i < 256; i++) {
511 exponent_group_tab[0][i] = (i - 1) / 3;
512 exponent_group_tab[1][i] = (i + 2) / 6;
513 exponent_group_tab[2][i] = (i + 8) / 12;
516 exponent_group_tab[0][7] = 2;
521 * Extract exponents from the MDCT coefficients.
522 * This takes into account the normalization that was done to the input samples
523 * by adjusting the exponents by the exponent shift values.
525 static void extract_exponents(AC3EncodeContext *s)
529 for (ch = 0; ch < s->channels; ch++) {
530 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
531 AC3Block *block = &s->blocks[blk];
532 uint8_t *exp = block->exp[ch];
533 int32_t *coef = block->fixed_coef[ch];
534 for (i = 0; i < AC3_MAX_COEFS; i++) {
536 int v = abs(coef[i]);
555 * Exponent Difference Threshold.
556 * New exponents are sent if their SAD exceed this number.
558 #define EXP_DIFF_THRESHOLD 500
562 * Calculate exponent strategies for all blocks in a single channel.
564 static void compute_exp_strategy_ch(AC3EncodeContext *s, uint8_t *exp_strategy,
570 /* estimate if the exponent variation & decide if they should be
571 reused in the next frame */
572 exp_strategy[0] = EXP_NEW;
573 exp += AC3_MAX_COEFS;
574 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
575 exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
576 if (exp_diff > EXP_DIFF_THRESHOLD)
577 exp_strategy[blk] = EXP_NEW;
579 exp_strategy[blk] = EXP_REUSE;
580 exp += AC3_MAX_COEFS;
583 /* now select the encoding strategy type : if exponents are often
584 recoded, we use a coarse encoding */
586 while (blk < AC3_MAX_BLOCKS) {
588 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
590 switch (blk1 - blk) {
591 case 1: exp_strategy[blk] = EXP_D45; break;
593 case 3: exp_strategy[blk] = EXP_D25; break;
594 default: exp_strategy[blk] = EXP_D15; break;
602 * Calculate exponent strategies for all channels.
603 * Array arrangement is reversed to simplify the per-channel calculation.
605 static void compute_exp_strategy(AC3EncodeContext *s)
609 for (ch = 0; ch < s->fbw_channels; ch++) {
610 compute_exp_strategy_ch(s, s->exp_strategy[ch], s->blocks[0].exp[ch]);
614 s->exp_strategy[ch][0] = EXP_D15;
615 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
616 s->exp_strategy[ch][blk] = EXP_REUSE;
622 * Update the exponents so that they are the ones the decoder will decode.
624 static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy)
628 nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
630 /* for each group, compute the minimum exponent */
631 switch(exp_strategy) {
633 for (i = 1, k = 1; i <= nb_groups; i++) {
634 uint8_t exp_min = exp[k];
635 if (exp[k+1] < exp_min)
642 for (i = 1, k = 1; i <= nb_groups; i++) {
643 uint8_t exp_min = exp[k];
644 if (exp[k+1] < exp_min)
646 if (exp[k+2] < exp_min)
648 if (exp[k+3] < exp_min)
656 /* constraint for DC exponent */
660 /* decrease the delta between each groups to within 2 so that they can be
661 differentially encoded */
662 for (i = 1; i <= nb_groups; i++)
663 exp[i] = FFMIN(exp[i], exp[i-1] + 2);
666 exp[i] = FFMIN(exp[i], exp[i+1] + 2);
668 /* now we have the exponent values the decoder will see */
669 switch (exp_strategy) {
671 for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
672 uint8_t exp1 = exp[i];
678 for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
679 exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
688 * Encode exponents from original extracted form to what the decoder will see.
689 * This copies and groups exponents based on exponent strategy and reduces
690 * deltas between adjacent exponent groups so that they can be differentially
693 static void encode_exponents(AC3EncodeContext *s)
696 uint8_t *exp, *exp_strategy;
697 int nb_coefs, num_reuse_blocks;
699 for (ch = 0; ch < s->channels; ch++) {
700 exp = s->blocks[0].exp[ch];
701 exp_strategy = s->exp_strategy[ch];
702 nb_coefs = s->nb_coefs[ch];
705 while (blk < AC3_MAX_BLOCKS) {
708 /* count the number of EXP_REUSE blocks after the current block
709 and set exponent reference block pointers */
710 s->blocks[blk].exp_ref_block[ch] = &s->blocks[blk];
711 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
712 s->blocks[blk1].exp_ref_block[ch] = &s->blocks[blk];
715 num_reuse_blocks = blk1 - blk - 1;
717 /* for the EXP_REUSE case we select the min of the exponents */
718 s->ac3dsp.ac3_exponent_min(exp, num_reuse_blocks, nb_coefs);
720 encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk]);
722 exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
731 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
732 * varies depending on exponent strategy and bandwidth.
734 static void group_exponents(AC3EncodeContext *s)
737 int group_size, nb_groups, bit_count;
739 int delta0, delta1, delta2;
743 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
744 AC3Block *block = &s->blocks[blk];
745 for (ch = 0; ch < s->channels; ch++) {
746 int exp_strategy = s->exp_strategy[ch][blk];
747 if (exp_strategy == EXP_REUSE)
749 group_size = exp_strategy + (exp_strategy == EXP_D45);
750 nb_groups = exponent_group_tab[exp_strategy-1][s->nb_coefs[ch]];
751 bit_count += 4 + (nb_groups * 7);
756 block->grouped_exp[ch][0] = exp1;
758 /* remaining exponents are delta encoded */
759 for (i = 1; i <= nb_groups; i++) {
760 /* merge three delta in one code */
764 delta0 = exp1 - exp0 + 2;
765 av_assert2(delta0 >= 0 && delta0 <= 4);
770 delta1 = exp1 - exp0 + 2;
771 av_assert2(delta1 >= 0 && delta1 <= 4);
776 delta2 = exp1 - exp0 + 2;
777 av_assert2(delta2 >= 0 && delta2 <= 4);
779 block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
784 s->exponent_bits = bit_count;
789 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
790 * Extract exponents from MDCT coefficients, calculate exponent strategies,
791 * and encode final exponents.
793 static void process_exponents(AC3EncodeContext *s)
795 extract_exponents(s);
797 compute_exp_strategy(s);
808 * Count frame bits that are based solely on fixed parameters.
809 * This only has to be run once when the encoder is initialized.
811 static void count_frame_bits_fixed(AC3EncodeContext *s)
813 static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
818 * no dynamic range codes
819 * no channel coupling
820 * bit allocation parameters do not change between blocks
821 * SNR offsets do not change between blocks
822 * no delta bit allocation
829 frame_bits += frame_bits_inc[s->channel_mode];
832 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
833 frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
834 if (s->channel_mode == AC3_CHMODE_STEREO) {
835 frame_bits++; /* rematstr */
837 frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
839 frame_bits++; /* lfeexpstr */
840 frame_bits++; /* baie */
841 frame_bits++; /* snr */
842 frame_bits += 2; /* delta / skip */
844 frame_bits++; /* cplinu for block 0 */
846 /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
848 /* (fsnoffset[4] + fgaincod[4]) * c */
849 frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
851 /* auxdatae, crcrsv */
857 s->frame_bits_fixed = frame_bits;
862 * Initialize bit allocation.
863 * Set default parameter codes and calculate parameter values.
865 static void bit_alloc_init(AC3EncodeContext *s)
869 /* init default parameters */
870 s->slow_decay_code = 2;
871 s->fast_decay_code = 1;
872 s->slow_gain_code = 1;
873 s->db_per_bit_code = 3;
875 for (ch = 0; ch < s->channels; ch++)
876 s->fast_gain_code[ch] = 4;
878 /* initial snr offset */
879 s->coarse_snr_offset = 40;
881 /* compute real values */
882 /* currently none of these values change during encoding, so we can just
883 set them once at initialization */
884 s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
885 s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
886 s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
887 s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
888 s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
890 count_frame_bits_fixed(s);
895 * Count the bits used to encode the frame, minus exponents and mantissas.
896 * Bits based on fixed parameters have already been counted, so now we just
897 * have to add the bits based on parameters that change during encoding.
899 static void count_frame_bits(AC3EncodeContext *s)
901 AC3EncOptions *opt = &s->options;
905 if (opt->audio_production_info)
907 if (s->bitstream_id == 6) {
908 if (opt->extended_bsi_1)
910 if (opt->extended_bsi_2)
914 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
915 /* stereo rematrixing */
916 if (s->channel_mode == AC3_CHMODE_STEREO &&
917 s->blocks[blk].new_rematrixing_strategy) {
918 frame_bits += s->num_rematrixing_bands;
921 for (ch = 0; ch < s->fbw_channels; ch++) {
922 if (s->exp_strategy[ch][blk] != EXP_REUSE)
923 frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
926 s->frame_bits = s->frame_bits_fixed + frame_bits;
931 * Finalize the mantissa bit count by adding in the grouped mantissas.
933 static int compute_mantissa_size_final(int mant_cnt[5])
935 // bap=1 : 3 mantissas in 5 bits
936 int bits = (mant_cnt[1] / 3) * 5;
937 // bap=2 : 3 mantissas in 7 bits
938 // bap=4 : 2 mantissas in 7 bits
939 bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
940 // bap=3 : each mantissa is 3 bits
941 bits += mant_cnt[3] * 3;
947 * Calculate masking curve based on the final exponents.
948 * Also calculate the power spectral densities to use in future calculations.
950 static void bit_alloc_masking(AC3EncodeContext *s)
954 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
955 AC3Block *block = &s->blocks[blk];
956 for (ch = 0; ch < s->channels; ch++) {
957 /* We only need psd and mask for calculating bap.
958 Since we currently do not calculate bap when exponent
959 strategy is EXP_REUSE we do not need to calculate psd or mask. */
960 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
961 ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
963 block->psd[ch], block->band_psd[ch]);
964 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
966 ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
967 ch == s->lfe_channel,
968 DBA_NONE, 0, NULL, NULL, NULL,
977 * Ensure that bap for each block and channel point to the current bap_buffer.
978 * They may have been switched during the bit allocation search.
980 static void reset_block_bap(AC3EncodeContext *s)
983 if (s->blocks[0].bap[0] == s->bap_buffer)
985 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
986 for (ch = 0; ch < s->channels; ch++) {
987 s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
994 * Run the bit allocation with a given SNR offset.
995 * This calculates the bit allocation pointers that will be used to determine
996 * the quantization of each mantissa.
997 * @return the number of bits needed for mantissas if the given SNR offset is
1000 static int bit_alloc(AC3EncodeContext *s, int snr_offset)
1006 snr_offset = (snr_offset - 240) << 2;
1010 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1012 // initialize grouped mantissa counts. these are set so that they are
1013 // padded to the next whole group size when bits are counted in
1014 // compute_mantissa_size_final
1015 mant_cnt[0] = mant_cnt[3] = 0;
1016 mant_cnt[1] = mant_cnt[2] = 2;
1018 for (ch = 0; ch < s->channels; ch++) {
1019 /* Currently the only bit allocation parameters which vary across
1020 blocks within a frame are the exponent values. We can take
1021 advantage of that by reusing the bit allocation pointers
1022 whenever we reuse exponents. */
1023 block = s->blocks[blk].exp_ref_block[ch];
1024 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1025 s->ac3dsp.bit_alloc_calc_bap(block->mask[ch], block->psd[ch], 0,
1026 s->nb_coefs[ch], snr_offset,
1027 s->bit_alloc.floor, ff_ac3_bap_tab,
1030 mantissa_bits += s->ac3dsp.compute_mantissa_size(mant_cnt, block->bap[ch], s->nb_coefs[ch]);
1032 mantissa_bits += compute_mantissa_size_final(mant_cnt);
1034 return mantissa_bits;
1039 * Constant bitrate bit allocation search.
1040 * Find the largest SNR offset that will allow data to fit in the frame.
1042 static int cbr_bit_allocation(AC3EncodeContext *s)
1046 int snr_offset, snr_incr;
1048 bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1049 av_assert2(bits_left >= 0);
1051 snr_offset = s->coarse_snr_offset << 4;
1053 /* if previous frame SNR offset was 1023, check if current frame can also
1054 use SNR offset of 1023. if so, skip the search. */
1055 if ((snr_offset | s->fine_snr_offset[0]) == 1023) {
1056 if (bit_alloc(s, 1023) <= bits_left)
1060 while (snr_offset >= 0 &&
1061 bit_alloc(s, snr_offset) > bits_left) {
1065 return AVERROR(EINVAL);
1067 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1068 for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1069 while (snr_offset + snr_incr <= 1023 &&
1070 bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1071 snr_offset += snr_incr;
1072 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1075 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1078 s->coarse_snr_offset = snr_offset >> 4;
1079 for (ch = 0; ch < s->channels; ch++)
1080 s->fine_snr_offset[ch] = snr_offset & 0xF;
1087 * Downgrade exponent strategies to reduce the bits used by the exponents.
1088 * This is a fallback for when bit allocation fails with the normal exponent
1089 * strategies. Each time this function is run it only downgrades the
1090 * strategy in 1 channel of 1 block.
1091 * @return non-zero if downgrade was unsuccessful
1093 static int downgrade_exponents(AC3EncodeContext *s)
1097 for (ch = 0; ch < s->fbw_channels; ch++) {
1098 for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1099 if (s->exp_strategy[ch][blk] == EXP_D15) {
1100 s->exp_strategy[ch][blk] = EXP_D25;
1105 for (ch = 0; ch < s->fbw_channels; ch++) {
1106 for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1107 if (s->exp_strategy[ch][blk] == EXP_D25) {
1108 s->exp_strategy[ch][blk] = EXP_D45;
1113 for (ch = 0; ch < s->fbw_channels; ch++) {
1114 /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
1115 the block number > 0 */
1116 for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
1117 if (s->exp_strategy[ch][blk] > EXP_REUSE) {
1118 s->exp_strategy[ch][blk] = EXP_REUSE;
1128 * Reduce the bandwidth to reduce the number of bits used for a given SNR offset.
1129 * This is a second fallback for when bit allocation still fails after exponents
1130 * have been downgraded.
1131 * @return non-zero if bandwidth reduction was unsuccessful
1133 static int reduce_bandwidth(AC3EncodeContext *s, int min_bw_code)
1137 if (s->bandwidth_code[0] > min_bw_code) {
1138 for (ch = 0; ch < s->fbw_channels; ch++) {
1139 s->bandwidth_code[ch]--;
1140 s->nb_coefs[ch] = s->bandwidth_code[ch] * 3 + 73;
1149 * Perform bit allocation search.
1150 * Finds the SNR offset value that maximizes quality and fits in the specified
1151 * frame size. Output is the SNR offset and a set of bit allocation pointers
1152 * used to quantize the mantissas.
1154 static int compute_bit_allocation(AC3EncodeContext *s)
1158 count_frame_bits(s);
1160 bit_alloc_masking(s);
1162 ret = cbr_bit_allocation(s);
1164 /* fallback 1: downgrade exponents */
1165 if (!downgrade_exponents(s)) {
1166 extract_exponents(s);
1167 encode_exponents(s);
1169 ret = compute_bit_allocation(s);
1173 /* fallback 2: reduce bandwidth */
1174 /* only do this if the user has not specified a specific cutoff
1176 if (!s->cutoff && !reduce_bandwidth(s, 0)) {
1177 process_exponents(s);
1178 ret = compute_bit_allocation(s);
1182 /* fallbacks were not enough... */
1191 * Symmetric quantization on 'levels' levels.
1193 static inline int sym_quant(int c, int e, int levels)
1195 int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1196 av_assert2(v >= 0 && v < levels);
1202 * Asymmetric quantization on 2^qbits levels.
1204 static inline int asym_quant(int c, int e, int qbits)
1208 lshift = e + qbits - 24;
1215 m = (1 << (qbits-1));
1218 av_assert2(v >= -m);
1219 return v & ((1 << qbits)-1);
1224 * Quantize a set of mantissas for a single channel in a single block.
1226 static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1228 uint8_t *bap, uint16_t *qmant, int n)
1232 for (i = 0; i < n; i++) {
1234 int c = fixed_coef[i];
1242 v = sym_quant(c, e, 3);
1243 switch (s->mant1_cnt) {
1245 s->qmant1_ptr = &qmant[i];
1250 *s->qmant1_ptr += 3 * v;
1255 *s->qmant1_ptr += v;
1262 v = sym_quant(c, e, 5);
1263 switch (s->mant2_cnt) {
1265 s->qmant2_ptr = &qmant[i];
1270 *s->qmant2_ptr += 5 * v;
1275 *s->qmant2_ptr += v;
1282 v = sym_quant(c, e, 7);
1285 v = sym_quant(c, e, 11);
1286 switch (s->mant4_cnt) {
1288 s->qmant4_ptr = &qmant[i];
1293 *s->qmant4_ptr += v;
1300 v = sym_quant(c, e, 15);
1303 v = asym_quant(c, e, 14);
1306 v = asym_quant(c, e, 16);
1309 v = asym_quant(c, e, b - 1);
1318 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1320 static void quantize_mantissas(AC3EncodeContext *s)
1325 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1326 AC3Block *block = &s->blocks[blk];
1327 AC3Block *ref_block;
1330 for (ch = 0; ch < s->channels; ch++) {
1331 ref_block = block->exp_ref_block[ch];
1332 quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1333 ref_block->exp[ch], ref_block->bap[ch],
1334 block->qmant[ch], s->nb_coefs[ch]);
1341 * Write the AC-3 frame header to the output bitstream.
1343 static void output_frame_header(AC3EncodeContext *s)
1345 AC3EncOptions *opt = &s->options;
1347 put_bits(&s->pb, 16, 0x0b77); /* frame header */
1348 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
1349 put_bits(&s->pb, 2, s->bit_alloc.sr_code);
1350 put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1351 put_bits(&s->pb, 5, s->bitstream_id);
1352 put_bits(&s->pb, 3, s->bitstream_mode);
1353 put_bits(&s->pb, 3, s->channel_mode);
1354 if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1355 put_bits(&s->pb, 2, s->center_mix_level);
1356 if (s->channel_mode & 0x04)
1357 put_bits(&s->pb, 2, s->surround_mix_level);
1358 if (s->channel_mode == AC3_CHMODE_STEREO)
1359 put_bits(&s->pb, 2, opt->dolby_surround_mode);
1360 put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1361 put_bits(&s->pb, 5, -opt->dialogue_level);
1362 put_bits(&s->pb, 1, 0); /* no compression control word */
1363 put_bits(&s->pb, 1, 0); /* no lang code */
1364 put_bits(&s->pb, 1, opt->audio_production_info);
1365 if (opt->audio_production_info) {
1366 put_bits(&s->pb, 5, opt->mixing_level - 80);
1367 put_bits(&s->pb, 2, opt->room_type);
1369 put_bits(&s->pb, 1, opt->copyright);
1370 put_bits(&s->pb, 1, opt->original);
1371 if (s->bitstream_id == 6) {
1372 /* alternate bit stream syntax */
1373 put_bits(&s->pb, 1, opt->extended_bsi_1);
1374 if (opt->extended_bsi_1) {
1375 put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1376 put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1377 put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1378 put_bits(&s->pb, 3, s->loro_center_mix_level);
1379 put_bits(&s->pb, 3, s->loro_surround_mix_level);
1381 put_bits(&s->pb, 1, opt->extended_bsi_2);
1382 if (opt->extended_bsi_2) {
1383 put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1384 put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1385 put_bits(&s->pb, 1, opt->ad_converter_type);
1386 put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
1389 put_bits(&s->pb, 1, 0); /* no time code 1 */
1390 put_bits(&s->pb, 1, 0); /* no time code 2 */
1392 put_bits(&s->pb, 1, 0); /* no additional bit stream info */
1397 * Write one audio block to the output bitstream.
1399 static void output_audio_block(AC3EncodeContext *s, int blk)
1401 int ch, i, baie, rbnd;
1402 AC3Block *block = &s->blocks[blk];
1404 /* block switching */
1405 for (ch = 0; ch < s->fbw_channels; ch++)
1406 put_bits(&s->pb, 1, 0);
1409 for (ch = 0; ch < s->fbw_channels; ch++)
1410 put_bits(&s->pb, 1, 1);
1412 /* dynamic range codes */
1413 put_bits(&s->pb, 1, 0);
1415 /* channel coupling */
1417 put_bits(&s->pb, 1, 1); /* coupling strategy present */
1418 put_bits(&s->pb, 1, 0); /* no coupling strategy */
1420 put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1423 /* stereo rematrixing */
1424 if (s->channel_mode == AC3_CHMODE_STEREO) {
1425 put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1426 if (block->new_rematrixing_strategy) {
1427 /* rematrixing flags */
1428 for (rbnd = 0; rbnd < s->num_rematrixing_bands; rbnd++)
1429 put_bits(&s->pb, 1, block->rematrixing_flags[rbnd]);
1433 /* exponent strategy */
1434 for (ch = 0; ch < s->fbw_channels; ch++)
1435 put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1437 put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1440 for (ch = 0; ch < s->fbw_channels; ch++) {
1441 if (s->exp_strategy[ch][blk] != EXP_REUSE)
1442 put_bits(&s->pb, 6, s->bandwidth_code[ch]);
1446 for (ch = 0; ch < s->channels; ch++) {
1449 if (s->exp_strategy[ch][blk] == EXP_REUSE)
1453 put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1455 /* exponent groups */
1456 nb_groups = exponent_group_tab[s->exp_strategy[ch][blk]-1][s->nb_coefs[ch]];
1457 for (i = 1; i <= nb_groups; i++)
1458 put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1460 /* gain range info */
1461 if (ch != s->lfe_channel)
1462 put_bits(&s->pb, 2, 0);
1465 /* bit allocation info */
1467 put_bits(&s->pb, 1, baie);
1469 put_bits(&s->pb, 2, s->slow_decay_code);
1470 put_bits(&s->pb, 2, s->fast_decay_code);
1471 put_bits(&s->pb, 2, s->slow_gain_code);
1472 put_bits(&s->pb, 2, s->db_per_bit_code);
1473 put_bits(&s->pb, 3, s->floor_code);
1477 put_bits(&s->pb, 1, baie);
1479 put_bits(&s->pb, 6, s->coarse_snr_offset);
1480 for (ch = 0; ch < s->channels; ch++) {
1481 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1482 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1486 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1487 put_bits(&s->pb, 1, 0); /* no data to skip */
1490 for (ch = 0; ch < s->channels; ch++) {
1492 AC3Block *ref_block = block->exp_ref_block[ch];
1493 for (i = 0; i < s->nb_coefs[ch]; i++) {
1494 q = block->qmant[ch][i];
1495 b = ref_block->bap[ch][i];
1498 case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
1499 case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
1500 case 3: put_bits(&s->pb, 3, q); break;
1501 case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
1502 case 14: put_bits(&s->pb, 14, q); break;
1503 case 15: put_bits(&s->pb, 16, q); break;
1504 default: put_bits(&s->pb, b-1, q); break;
1511 /** CRC-16 Polynomial */
1512 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1515 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1532 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1538 r = mul_poly(r, a, poly);
1539 a = mul_poly(a, a, poly);
1547 * Fill the end of the frame with 0's and compute the two CRCs.
1549 static void output_frame_end(AC3EncodeContext *s)
1551 const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1552 int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1555 frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1557 /* pad the remainder of the frame with zeros */
1558 av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1559 flush_put_bits(&s->pb);
1561 pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1562 av_assert2(pad_bytes >= 0);
1564 memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1567 /* this is not so easy because it is at the beginning of the data... */
1568 crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1569 crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1570 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1571 AV_WB16(frame + 2, crc1);
1574 crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1575 s->frame_size - frame_size_58 - 3);
1576 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1577 /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1578 if (crc2 == 0x770B) {
1579 frame[s->frame_size - 3] ^= 0x1;
1580 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1582 crc2 = av_bswap16(crc2);
1583 AV_WB16(frame + s->frame_size - 2, crc2);
1588 * Write the frame to the output bitstream.
1590 static void output_frame(AC3EncodeContext *s, unsigned char *frame)
1594 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1596 output_frame_header(s);
1598 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1599 output_audio_block(s, blk);
1601 output_frame_end(s);
1605 static void dprint_options(AVCodecContext *avctx)
1608 AC3EncodeContext *s = avctx->priv_data;
1609 AC3EncOptions *opt = &s->options;
1612 switch (s->bitstream_id) {
1613 case 6: strncpy(strbuf, "AC-3 (alt syntax)", 32); break;
1614 case 8: strncpy(strbuf, "AC-3 (standard)", 32); break;
1615 case 9: strncpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
1616 case 10: strncpy(strbuf, "AC-3 (dnet quater-rate", 32); break;
1617 default: snprintf(strbuf, 32, "ERROR");
1619 av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
1620 av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
1621 av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
1622 av_dlog(avctx, "channel_layout: %s\n", strbuf);
1623 av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
1624 av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
1626 av_dlog(avctx, "cutoff: %d\n", s->cutoff);
1628 av_dlog(avctx, "per_frame_metadata: %s\n",
1629 opt->allow_per_frame_metadata?"on":"off");
1631 av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
1632 s->center_mix_level);
1634 av_dlog(avctx, "center_mixlev: {not written}\n");
1635 if (s->has_surround)
1636 av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
1637 s->surround_mix_level);
1639 av_dlog(avctx, "surround_mixlev: {not written}\n");
1640 if (opt->audio_production_info) {
1641 av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
1642 switch (opt->room_type) {
1643 case 0: strncpy(strbuf, "notindicated", 32); break;
1644 case 1: strncpy(strbuf, "large", 32); break;
1645 case 2: strncpy(strbuf, "small", 32); break;
1646 default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
1648 av_dlog(avctx, "room_type: %s\n", strbuf);
1650 av_dlog(avctx, "mixing_level: {not written}\n");
1651 av_dlog(avctx, "room_type: {not written}\n");
1653 av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
1654 av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
1655 if (s->channel_mode == AC3_CHMODE_STEREO) {
1656 switch (opt->dolby_surround_mode) {
1657 case 0: strncpy(strbuf, "notindicated", 32); break;
1658 case 1: strncpy(strbuf, "on", 32); break;
1659 case 2: strncpy(strbuf, "off", 32); break;
1660 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
1662 av_dlog(avctx, "dsur_mode: %s\n", strbuf);
1664 av_dlog(avctx, "dsur_mode: {not written}\n");
1666 av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
1668 if (s->bitstream_id == 6) {
1669 if (opt->extended_bsi_1) {
1670 switch (opt->preferred_stereo_downmix) {
1671 case 0: strncpy(strbuf, "notindicated", 32); break;
1672 case 1: strncpy(strbuf, "ltrt", 32); break;
1673 case 2: strncpy(strbuf, "loro", 32); break;
1674 default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
1676 av_dlog(avctx, "dmix_mode: %s\n", strbuf);
1677 av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
1678 opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
1679 av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
1680 opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
1681 av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
1682 opt->loro_center_mix_level, s->loro_center_mix_level);
1683 av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
1684 opt->loro_surround_mix_level, s->loro_surround_mix_level);
1686 av_dlog(avctx, "extended bitstream info 1: {not written}\n");
1688 if (opt->extended_bsi_2) {
1689 switch (opt->dolby_surround_ex_mode) {
1690 case 0: strncpy(strbuf, "notindicated", 32); break;
1691 case 1: strncpy(strbuf, "on", 32); break;
1692 case 2: strncpy(strbuf, "off", 32); break;
1693 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
1695 av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
1696 switch (opt->dolby_headphone_mode) {
1697 case 0: strncpy(strbuf, "notindicated", 32); break;
1698 case 1: strncpy(strbuf, "on", 32); break;
1699 case 2: strncpy(strbuf, "off", 32); break;
1700 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
1702 av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
1704 switch (opt->ad_converter_type) {
1705 case 0: strncpy(strbuf, "standard", 32); break;
1706 case 1: strncpy(strbuf, "hdcd", 32); break;
1707 default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
1709 av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
1711 av_dlog(avctx, "extended bitstream info 2: {not written}\n");
1718 #define FLT_OPTION_THRESHOLD 0.01
1720 static int validate_float_option(float v, const float *v_list, int v_list_size)
1724 for (i = 0; i < v_list_size; i++) {
1725 if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
1726 v > (v_list[i] - FLT_OPTION_THRESHOLD))
1729 if (i == v_list_size)
1736 static void validate_mix_level(void *log_ctx, const char *opt_name,
1737 float *opt_param, const float *list,
1738 int list_size, int default_value, int min_value,
1741 int mixlev = validate_float_option(*opt_param, list, list_size);
1742 if (mixlev < min_value) {
1743 mixlev = default_value;
1744 if (*opt_param >= 0.0) {
1745 av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
1746 "default value: %0.3f\n", opt_name, list[mixlev]);
1749 *opt_param = list[mixlev];
1750 *ctx_param = mixlev;
1755 * Validate metadata options as set by AVOption system.
1756 * These values can optionally be changed per-frame.
1758 static int validate_metadata(AVCodecContext *avctx)
1760 AC3EncodeContext *s = avctx->priv_data;
1761 AC3EncOptions *opt = &s->options;
1763 /* validate mixing levels */
1764 if (s->has_center) {
1765 validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
1766 cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
1767 &s->center_mix_level);
1769 if (s->has_surround) {
1770 validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
1771 surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
1772 &s->surround_mix_level);
1775 /* set audio production info flag */
1776 if (opt->mixing_level >= 0 || opt->room_type >= 0) {
1777 if (opt->mixing_level < 0) {
1778 av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
1779 "room_type is set\n");
1780 return AVERROR(EINVAL);
1782 if (opt->mixing_level < 80) {
1783 av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
1784 "80dB and 111dB\n");
1785 return AVERROR(EINVAL);
1787 /* default room type */
1788 if (opt->room_type < 0)
1790 opt->audio_production_info = 1;
1792 opt->audio_production_info = 0;
1795 /* set extended bsi 1 flag */
1796 if ((s->has_center || s->has_surround) &&
1797 (opt->preferred_stereo_downmix >= 0 ||
1798 opt->ltrt_center_mix_level >= 0 ||
1799 opt->ltrt_surround_mix_level >= 0 ||
1800 opt->loro_center_mix_level >= 0 ||
1801 opt->loro_surround_mix_level >= 0)) {
1802 /* default preferred stereo downmix */
1803 if (opt->preferred_stereo_downmix < 0)
1804 opt->preferred_stereo_downmix = 0;
1805 /* validate Lt/Rt center mix level */
1806 validate_mix_level(avctx, "ltrt_center_mix_level",
1807 &opt->ltrt_center_mix_level, extmixlev_options,
1808 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1809 &s->ltrt_center_mix_level);
1810 /* validate Lt/Rt surround mix level */
1811 validate_mix_level(avctx, "ltrt_surround_mix_level",
1812 &opt->ltrt_surround_mix_level, extmixlev_options,
1813 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1814 &s->ltrt_surround_mix_level);
1815 /* validate Lo/Ro center mix level */
1816 validate_mix_level(avctx, "loro_center_mix_level",
1817 &opt->loro_center_mix_level, extmixlev_options,
1818 EXTMIXLEV_NUM_OPTIONS, 5, 0,
1819 &s->loro_center_mix_level);
1820 /* validate Lo/Ro surround mix level */
1821 validate_mix_level(avctx, "loro_surround_mix_level",
1822 &opt->loro_surround_mix_level, extmixlev_options,
1823 EXTMIXLEV_NUM_OPTIONS, 6, 3,
1824 &s->loro_surround_mix_level);
1825 opt->extended_bsi_1 = 1;
1827 opt->extended_bsi_1 = 0;
1830 /* set extended bsi 2 flag */
1831 if (opt->dolby_surround_ex_mode >= 0 ||
1832 opt->dolby_headphone_mode >= 0 ||
1833 opt->ad_converter_type >= 0) {
1834 /* default dolby surround ex mode */
1835 if (opt->dolby_surround_ex_mode < 0)
1836 opt->dolby_surround_ex_mode = 0;
1837 /* default dolby headphone mode */
1838 if (opt->dolby_headphone_mode < 0)
1839 opt->dolby_headphone_mode = 0;
1840 /* default A/D converter type */
1841 if (opt->ad_converter_type < 0)
1842 opt->ad_converter_type = 0;
1843 opt->extended_bsi_2 = 1;
1845 opt->extended_bsi_2 = 0;
1848 /* set bitstream id for alternate bitstream syntax */
1849 if (opt->extended_bsi_1 || opt->extended_bsi_2) {
1850 if (s->bitstream_id > 8 && s->bitstream_id < 11) {
1851 static int warn_once = 1;
1853 av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
1854 "not compatible with reduced samplerates. writing of "
1855 "extended bitstream information will be disabled.\n");
1859 s->bitstream_id = 6;
1868 * Encode a single AC-3 frame.
1870 static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
1871 int buf_size, void *data)
1873 AC3EncodeContext *s = avctx->priv_data;
1874 const SampleType *samples = data;
1877 if (s->options.allow_per_frame_metadata) {
1878 ret = validate_metadata(avctx);
1883 if (s->bit_alloc.sr_code == 1)
1884 adjust_frame_size(s);
1886 deinterleave_input_samples(s, samples);
1890 scale_coefficients(s);
1892 compute_rematrixing_strategy(s);
1894 apply_rematrixing(s);
1896 process_exponents(s);
1898 ret = compute_bit_allocation(s);
1900 av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1904 quantize_mantissas(s);
1906 output_frame(s, frame);
1908 return s->frame_size;
1913 * Finalize encoding and free any memory allocated by the encoder.
1915 static av_cold int ac3_encode_close(AVCodecContext *avctx)
1918 AC3EncodeContext *s = avctx->priv_data;
1920 for (ch = 0; ch < s->channels; ch++)
1921 av_freep(&s->planar_samples[ch]);
1922 av_freep(&s->planar_samples);
1923 av_freep(&s->bap_buffer);
1924 av_freep(&s->bap1_buffer);
1925 av_freep(&s->mdct_coef_buffer);
1926 av_freep(&s->fixed_coef_buffer);
1927 av_freep(&s->exp_buffer);
1928 av_freep(&s->grouped_exp_buffer);
1929 av_freep(&s->psd_buffer);
1930 av_freep(&s->band_psd_buffer);
1931 av_freep(&s->mask_buffer);
1932 av_freep(&s->qmant_buffer);
1933 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1934 AC3Block *block = &s->blocks[blk];
1935 av_freep(&block->bap);
1936 av_freep(&block->mdct_coef);
1937 av_freep(&block->fixed_coef);
1938 av_freep(&block->exp);
1939 av_freep(&block->grouped_exp);
1940 av_freep(&block->psd);
1941 av_freep(&block->band_psd);
1942 av_freep(&block->mask);
1943 av_freep(&block->qmant);
1948 av_freep(&avctx->coded_frame);
1954 * Set channel information during initialization.
1956 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1957 int64_t *channel_layout)
1961 if (channels < 1 || channels > AC3_MAX_CHANNELS)
1962 return AVERROR(EINVAL);
1963 if ((uint64_t)*channel_layout > 0x7FF)
1964 return AVERROR(EINVAL);
1965 ch_layout = *channel_layout;
1967 ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1968 if (av_get_channel_layout_nb_channels(ch_layout) != channels)
1969 return AVERROR(EINVAL);
1971 s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1972 s->channels = channels;
1973 s->fbw_channels = channels - s->lfe_on;
1974 s->lfe_channel = s->lfe_on ? s->fbw_channels : -1;
1976 ch_layout -= AV_CH_LOW_FREQUENCY;
1978 switch (ch_layout) {
1979 case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
1980 case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
1981 case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
1982 case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
1983 case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
1984 case AV_CH_LAYOUT_QUAD:
1985 case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
1986 case AV_CH_LAYOUT_5POINT0:
1987 case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
1989 return AVERROR(EINVAL);
1991 s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
1992 s->has_surround = s->channel_mode & 0x04;
1994 s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1995 *channel_layout = ch_layout;
1997 *channel_layout |= AV_CH_LOW_FREQUENCY;
2003 static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
2007 /* validate channel layout */
2008 if (!avctx->channel_layout) {
2009 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
2010 "encoder will guess the layout, but it "
2011 "might be incorrect.\n");
2013 ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
2015 av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
2019 /* validate sample rate */
2020 for (i = 0; i < 9; i++) {
2021 if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
2025 av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
2026 return AVERROR(EINVAL);
2028 s->sample_rate = avctx->sample_rate;
2029 s->bit_alloc.sr_shift = i % 3;
2030 s->bit_alloc.sr_code = i / 3;
2031 s->bitstream_id = 8 + s->bit_alloc.sr_shift;
2033 /* validate bit rate */
2034 for (i = 0; i < 19; i++) {
2035 if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
2039 av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2040 return AVERROR(EINVAL);
2042 s->bit_rate = avctx->bit_rate;
2043 s->frame_size_code = i << 1;
2045 /* validate cutoff */
2046 if (avctx->cutoff < 0) {
2047 av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2048 return AVERROR(EINVAL);
2050 s->cutoff = avctx->cutoff;
2051 if (s->cutoff > (s->sample_rate >> 1))
2052 s->cutoff = s->sample_rate >> 1;
2054 /* validate audio service type / channels combination */
2055 if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
2056 avctx->channels == 1) ||
2057 ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
2058 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
2059 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
2060 && avctx->channels > 1)) {
2061 av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
2062 "specified number of channels\n");
2063 return AVERROR(EINVAL);
2066 ret = validate_metadata(avctx);
2075 * Set bandwidth for all channels.
2076 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2077 * default value will be used.
2079 static av_cold void set_bandwidth(AC3EncodeContext *s)
2084 /* calculate bandwidth based on user-specified cutoff frequency */
2086 fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2087 bw_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2089 /* use default bandwidth setting */
2090 /* XXX: should compute the bandwidth according to the frame
2091 size, so that we avoid annoying high frequency artifacts */
2095 /* set number of coefficients for each channel */
2096 for (ch = 0; ch < s->fbw_channels; ch++) {
2097 s->bandwidth_code[ch] = bw_code;
2098 s->nb_coefs[ch] = bw_code * 3 + 73;
2101 s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
2105 static av_cold int allocate_buffers(AVCodecContext *avctx)
2108 AC3EncodeContext *s = avctx->priv_data;
2110 FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
2112 for (ch = 0; ch < s->channels; ch++) {
2113 FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
2114 (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
2117 FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * s->channels *
2118 AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
2119 FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
2120 AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
2121 FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
2122 AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
2123 FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
2124 AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
2125 FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
2126 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
2127 FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
2128 AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
2129 FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
2130 64 * sizeof(*s->band_psd_buffer), alloc_fail);
2131 FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
2132 64 * sizeof(*s->mask_buffer), alloc_fail);
2133 FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
2134 AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
2135 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2136 AC3Block *block = &s->blocks[blk];
2137 FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
2139 FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
2141 FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
2143 FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
2145 FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
2147 FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
2149 FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
2151 FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
2154 for (ch = 0; ch < s->channels; ch++) {
2155 /* arrangement: block, channel, coeff */
2156 block->bap[ch] = &s->bap_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2157 block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2158 block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * s->channels + ch)];
2159 block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2160 block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * s->channels + ch)];
2161 block->mask[ch] = &s->mask_buffer [64 * (blk * s->channels + ch)];
2162 block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
2164 /* arrangement: channel, block, coeff */
2165 block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2169 if (CONFIG_AC3ENC_FLOAT) {
2170 FF_ALLOC_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * s->channels *
2171 AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
2172 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2173 AC3Block *block = &s->blocks[blk];
2174 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2175 sizeof(*block->fixed_coef), alloc_fail);
2176 for (ch = 0; ch < s->channels; ch++)
2177 block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
2180 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2181 AC3Block *block = &s->blocks[blk];
2182 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2183 sizeof(*block->fixed_coef), alloc_fail);
2184 for (ch = 0; ch < s->channels; ch++)
2185 block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2191 return AVERROR(ENOMEM);
2196 * Initialize the encoder.
2198 static av_cold int ac3_encode_init(AVCodecContext *avctx)
2200 AC3EncodeContext *s = avctx->priv_data;
2201 int ret, frame_size_58;
2203 avctx->frame_size = AC3_FRAME_SIZE;
2205 ff_ac3_common_init();
2207 ret = validate_options(avctx, s);
2211 s->bitstream_mode = avctx->audio_service_type;
2212 if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2213 s->bitstream_mode = 0x7;
2215 s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2216 s->bits_written = 0;
2217 s->samples_written = 0;
2218 s->frame_size = s->frame_size_min;
2220 /* calculate crc_inv for both possible frame sizes */
2221 frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
2222 s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2223 if (s->bit_alloc.sr_code == 1) {
2224 frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2225 s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2230 rematrixing_init(s);
2236 ret = mdct_init(avctx, &s->mdct, 9);
2240 ret = allocate_buffers(avctx);
2244 avctx->coded_frame= avcodec_alloc_frame();
2246 dsputil_init(&s->dsp, avctx);
2247 ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2249 dprint_options(avctx);
2253 ac3_encode_close(avctx);