2 * The simplest AC-3 encoder
3 * Copyright (c) 2000 Fabrice Bellard
4 * Copyright (c) 2006-2010 Justin Ruggles <justin.ruggles@gmail.com>
5 * Copyright (c) 2006-2010 Prakash Punnoor <prakash@punnoor.de>
7 * This file is part of Libav.
9 * Libav is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * Libav is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with Libav; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 * The simplest AC-3 encoder.
30 //#define ASSERT_LEVEL 2
34 #include "libavutil/audioconvert.h"
35 #include "libavutil/avassert.h"
36 #include "libavutil/avstring.h"
37 #include "libavutil/crc.h"
38 #include "libavutil/opt.h"
44 #include "audioconvert.h"
48 #ifndef CONFIG_AC3ENC_FLOAT
49 #define CONFIG_AC3ENC_FLOAT 0
53 /** Maximum number of exponent groups. +1 for separate DC exponent. */
54 #define AC3_MAX_EXP_GROUPS 85
56 #if CONFIG_AC3ENC_FLOAT
57 #define MAC_COEF(d,a,b) ((d)+=(a)*(b))
58 typedef float SampleType;
59 typedef float CoefType;
60 typedef float CoefSumType;
62 #define MAC_COEF(d,a,b) MAC64(d,a,b)
63 typedef int16_t SampleType;
64 typedef int32_t CoefType;
65 typedef int64_t CoefSumType;
68 typedef struct AC3MDCTContext {
69 const SampleType *window; ///< MDCT window function
70 FFTContext fft; ///< FFT context for MDCT calculation
74 * Encoding Options used by AVOption.
76 typedef struct AC3EncOptions {
77 /* AC-3 metadata options*/
80 float center_mix_level;
81 float surround_mix_level;
82 int dolby_surround_mode;
83 int audio_production_info;
89 int preferred_stereo_downmix;
90 float ltrt_center_mix_level;
91 float ltrt_surround_mix_level;
92 float loro_center_mix_level;
93 float loro_surround_mix_level;
95 int dolby_surround_ex_mode;
96 int dolby_headphone_mode;
97 int ad_converter_type;
99 /* other encoding options */
100 int allow_per_frame_metadata;
101 int stereo_rematrixing;
102 int channel_coupling;
107 * Data for a single audio block.
109 typedef struct AC3Block {
110 uint8_t **bap; ///< bit allocation pointers (bap)
111 CoefType **mdct_coef; ///< MDCT coefficients
112 int32_t **fixed_coef; ///< fixed-point MDCT coefficients
113 uint8_t **exp; ///< original exponents
114 uint8_t **grouped_exp; ///< grouped exponents
115 int16_t **psd; ///< psd per frequency bin
116 int16_t **band_psd; ///< psd per critical band
117 int16_t **mask; ///< masking curve
118 uint16_t **qmant; ///< quantized mantissas
119 uint8_t **cpl_coord_exp; ///< coupling coord exponents (cplcoexp)
120 uint8_t **cpl_coord_mant; ///< coupling coord mantissas (cplcomant)
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 int num_rematrixing_bands; ///< number of rematrixing bands
124 uint8_t rematrixing_flags[4]; ///< rematrixing flags
125 struct AC3Block *exp_ref_block[AC3_MAX_CHANNELS]; ///< reference blocks for EXP_REUSE
126 int new_cpl_strategy; ///< send new coupling strategy
127 int cpl_in_use; ///< coupling in use for this block (cplinu)
128 uint8_t channel_in_cpl[AC3_MAX_CHANNELS]; ///< channel in coupling (chincpl)
129 int num_cpl_channels; ///< number of channels in coupling
130 uint8_t new_cpl_coords; ///< send new coupling coordinates (cplcoe)
131 uint8_t cpl_master_exp[AC3_MAX_CHANNELS]; ///< coupling coord master exponents (mstrcplco)
132 int new_snr_offsets; ///< send new SNR offsets
133 int new_cpl_leak; ///< send new coupling leak info
134 int end_freq[AC3_MAX_CHANNELS]; ///< end frequency bin (endmant)
138 * AC-3 encoder private context.
140 typedef struct AC3EncodeContext {
141 AVClass *av_class; ///< AVClass used for AVOption
142 AC3EncOptions options; ///< encoding options
143 PutBitContext pb; ///< bitstream writer context
145 AC3DSPContext ac3dsp; ///< AC-3 optimized functions
146 AC3MDCTContext mdct; ///< MDCT context
148 AC3Block blocks[AC3_MAX_BLOCKS]; ///< per-block info
150 int bitstream_id; ///< bitstream id (bsid)
151 int bitstream_mode; ///< bitstream mode (bsmod)
153 int bit_rate; ///< target bit rate, in bits-per-second
154 int sample_rate; ///< sampling frequency, in Hz
156 int frame_size_min; ///< minimum frame size in case rounding is necessary
157 int frame_size; ///< current frame size in bytes
158 int frame_size_code; ///< frame size code (frmsizecod)
160 int bits_written; ///< bit count (used to avg. bitrate)
161 int samples_written; ///< sample count (used to avg. bitrate)
163 int fbw_channels; ///< number of full-bandwidth channels (nfchans)
164 int channels; ///< total number of channels (nchans)
165 int lfe_on; ///< indicates if there is an LFE channel (lfeon)
166 int lfe_channel; ///< channel index of the LFE channel
167 int has_center; ///< indicates if there is a center channel
168 int has_surround; ///< indicates if there are one or more surround channels
169 int channel_mode; ///< channel mode (acmod)
170 const uint8_t *channel_map; ///< channel map used to reorder channels
172 int center_mix_level; ///< center mix level code
173 int surround_mix_level; ///< surround mix level code
174 int ltrt_center_mix_level; ///< Lt/Rt center mix level code
175 int ltrt_surround_mix_level; ///< Lt/Rt surround mix level code
176 int loro_center_mix_level; ///< Lo/Ro center mix level code
177 int loro_surround_mix_level; ///< Lo/Ro surround mix level code
179 int cutoff; ///< user-specified cutoff frequency, in Hz
180 int bandwidth_code; ///< bandwidth code (0 to 60) (chbwcod)
181 int start_freq[AC3_MAX_CHANNELS]; ///< start frequency bin (strtmant)
182 int cpl_end_freq; ///< coupling channel end frequency bin
184 int cpl_on; ///< coupling turned on for this frame
185 int cpl_enabled; ///< coupling enabled for all frames
186 int num_cpl_subbands; ///< number of coupling subbands (ncplsubnd)
187 int num_cpl_bands; ///< number of coupling bands (ncplbnd)
188 uint8_t cpl_band_sizes[AC3_MAX_CPL_BANDS]; ///< number of coeffs in each coupling band
190 int rematrixing_enabled; ///< stereo rematrixing enabled
192 /* bitrate allocation control */
193 int slow_gain_code; ///< slow gain code (sgaincod)
194 int slow_decay_code; ///< slow decay code (sdcycod)
195 int fast_decay_code; ///< fast decay code (fdcycod)
196 int db_per_bit_code; ///< dB/bit code (dbpbcod)
197 int floor_code; ///< floor code (floorcod)
198 AC3BitAllocParameters bit_alloc; ///< bit allocation parameters
199 int coarse_snr_offset; ///< coarse SNR offsets (csnroffst)
200 int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signal-to-mask ratio) (fgaincod)
201 int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst)
202 int frame_bits_fixed; ///< number of non-coefficient bits for fixed parameters
203 int frame_bits; ///< all frame bits except exponents and mantissas
204 int exponent_bits; ///< number of bits used for exponents
206 SampleType **planar_samples;
208 uint8_t *bap1_buffer;
209 CoefType *mdct_coef_buffer;
210 int32_t *fixed_coef_buffer;
212 uint8_t *grouped_exp_buffer;
214 int16_t *band_psd_buffer;
215 int16_t *mask_buffer;
216 uint16_t *qmant_buffer;
217 uint8_t *cpl_coord_exp_buffer;
218 uint8_t *cpl_coord_mant_buffer;
220 uint8_t exp_strategy[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< exponent strategies
222 DECLARE_ALIGNED(32, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
225 typedef struct AC3Mant {
226 uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
227 int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
230 #define CMIXLEV_NUM_OPTIONS 3
231 static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
232 LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
235 #define SURMIXLEV_NUM_OPTIONS 3
236 static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
237 LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
240 #define EXTMIXLEV_NUM_OPTIONS 8
241 static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
242 LEVEL_PLUS_3DB, LEVEL_PLUS_1POINT5DB, LEVEL_ONE, LEVEL_MINUS_4POINT5DB,
243 LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
247 #define OFFSET(param) offsetof(AC3EncodeContext, options.param)
248 #define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
250 static const AVOption options[] = {
251 /* Metadata Options */
252 {"per_frame_metadata", "Allow Changing Metadata Per-Frame", OFFSET(allow_per_frame_metadata), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 1, AC3ENC_PARAM},
254 {"center_mixlev", "Center Mix Level", OFFSET(center_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = LEVEL_MINUS_4POINT5DB }, 0.0, 1.0, AC3ENC_PARAM},
255 {"surround_mixlev", "Surround Mix Level", OFFSET(surround_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = LEVEL_MINUS_6DB }, 0.0, 1.0, AC3ENC_PARAM},
256 /* audio production information */
257 {"mixing_level", "Mixing Level", OFFSET(mixing_level), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 111, AC3ENC_PARAM},
258 {"room_type", "Room Type", OFFSET(room_type), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "room_type"},
259 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
260 {"large", "Large Room", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
261 {"small", "Small Room", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
262 /* other metadata options */
263 {"copyright", "Copyright Bit", OFFSET(copyright), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 1, AC3ENC_PARAM},
264 {"dialnorm", "Dialogue Level (dB)", OFFSET(dialogue_level), FF_OPT_TYPE_INT, {.dbl = -31 }, -31, -1, AC3ENC_PARAM},
265 {"dsur_mode", "Dolby Surround Mode", OFFSET(dolby_surround_mode), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 2, AC3ENC_PARAM, "dsur_mode"},
266 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
267 {"on", "Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
268 {"off", "Not Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
269 {"original", "Original Bit Stream", OFFSET(original), FF_OPT_TYPE_INT, {.dbl = 1 }, 0, 1, AC3ENC_PARAM},
270 /* extended bitstream information */
271 {"dmix_mode", "Preferred Stereo Downmix Mode", OFFSET(preferred_stereo_downmix), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dmix_mode"},
272 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
273 {"ltrt", "Lt/Rt Downmix Preferred", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
274 {"loro", "Lo/Ro Downmix Preferred", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
275 {"ltrt_cmixlev", "Lt/Rt Center Mix Level", OFFSET(ltrt_center_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
276 {"ltrt_surmixlev", "Lt/Rt Surround Mix Level", OFFSET(ltrt_surround_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
277 {"loro_cmixlev", "Lo/Ro Center Mix Level", OFFSET(loro_center_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
278 {"loro_surmixlev", "Lo/Ro Surround Mix Level", OFFSET(loro_surround_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
279 {"dsurex_mode", "Dolby Surround EX Mode", OFFSET(dolby_surround_ex_mode), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dsurex_mode"},
280 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
281 {"on", "Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
282 {"off", "Not Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
283 {"dheadphone_mode", "Dolby Headphone Mode", OFFSET(dolby_headphone_mode), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dheadphone_mode"},
284 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
285 {"on", "Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
286 {"off", "Not Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
287 {"ad_conv_type", "A/D Converter Type", OFFSET(ad_converter_type), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 1, AC3ENC_PARAM, "ad_conv_type"},
288 {"standard", "Standard (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
289 {"hdcd", "HDCD", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
290 /* Other Encoding Options */
291 {"stereo_rematrixing", "Stereo Rematrixing", OFFSET(stereo_rematrixing), FF_OPT_TYPE_INT, {.dbl = 1 }, 0, 1, AC3ENC_PARAM},
292 #if CONFIG_AC3ENC_FLOAT
293 {"channel_coupling", "Channel Coupling", OFFSET(channel_coupling), FF_OPT_TYPE_INT, {.dbl = 1 }, 0, 1, AC3ENC_PARAM, "channel_coupling"},
294 {"auto", "Selected by the Encoder", 0, FF_OPT_TYPE_CONST, {.dbl = -1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "channel_coupling"},
295 {"cpl_start_band", "Coupling Start Band", OFFSET(cpl_start), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 15, AC3ENC_PARAM, "cpl_start_band"},
296 {"auto", "Selected by the Encoder", 0, FF_OPT_TYPE_CONST, {.dbl = -1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "cpl_start_band"},
301 #if CONFIG_AC3ENC_FLOAT
302 static AVClass ac3enc_class = { "AC-3 Encoder", av_default_item_name,
303 options, LIBAVUTIL_VERSION_INT };
305 static AVClass ac3enc_class = { "Fixed-Point AC-3 Encoder", av_default_item_name,
306 options, LIBAVUTIL_VERSION_INT };
310 /* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
312 static av_cold void mdct_end(AC3MDCTContext *mdct);
314 static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
317 static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
318 const SampleType *window, unsigned int len);
320 static int normalize_samples(AC3EncodeContext *s);
322 static void scale_coefficients(AC3EncodeContext *s);
326 * LUT for number of exponent groups.
327 * exponent_group_tab[coupling][exponent strategy-1][number of coefficients]
329 static uint8_t exponent_group_tab[2][3][256];
333 * List of supported channel layouts.
335 static const int64_t ac3_channel_layouts[] = {
339 AV_CH_LAYOUT_SURROUND,
342 AV_CH_LAYOUT_4POINT0,
343 AV_CH_LAYOUT_5POINT0,
344 AV_CH_LAYOUT_5POINT0_BACK,
345 (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
346 (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
347 (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
348 (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
349 (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
350 (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
351 (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
352 AV_CH_LAYOUT_5POINT1,
353 AV_CH_LAYOUT_5POINT1_BACK,
359 * LUT to select the bandwidth code based on the bit rate, sample rate, and
360 * number of full-bandwidth channels.
361 * bandwidth_tab[fbw_channels-1][sample rate code][bit rate code]
363 static const uint8_t ac3_bandwidth_tab[5][3][19] = {
364 // 32 40 48 56 64 80 96 112 128 160 192 224 256 320 384 448 512 576 640
366 { { 0, 0, 0, 12, 16, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
367 { 0, 0, 0, 16, 20, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
368 { 0, 0, 0, 32, 40, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
370 { { 0, 0, 0, 0, 0, 0, 0, 20, 24, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
371 { 0, 0, 0, 0, 0, 0, 4, 24, 28, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
372 { 0, 0, 0, 0, 0, 0, 20, 44, 52, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
374 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 24, 32, 40, 48, 48, 48, 48, 48, 48 },
375 { 0, 0, 0, 0, 0, 0, 0, 0, 4, 20, 28, 36, 44, 56, 56, 56, 56, 56, 56 },
376 { 0, 0, 0, 0, 0, 0, 0, 0, 20, 40, 48, 60, 60, 60, 60, 60, 60, 60, 60 } },
378 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 32, 48, 48, 48, 48, 48, 48 },
379 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 28, 36, 56, 56, 56, 56, 56, 56 },
380 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 48, 60, 60, 60, 60, 60, 60, 60 } },
382 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 20, 32, 40, 48, 48, 48, 48 },
383 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 36, 44, 56, 56, 56, 56 },
384 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 44, 60, 60, 60, 60, 60, 60 } }
389 * LUT to select the coupling start band based on the bit rate, sample rate, and
390 * number of full-bandwidth channels. -1 = coupling off
391 * ac3_coupling_start_tab[channel_mode-2][sample rate code][bit rate code]
393 * TODO: more testing for optimal parameters.
394 * multi-channel tests at 44.1kHz and 32kHz.
396 static const int8_t ac3_coupling_start_tab[6][3][19] = {
397 // 32 40 48 56 64 80 96 112 128 160 192 224 256 320 384 448 512 576 640
400 { { 0, 0, 0, 0, 0, 0, 0, 1, 1, 7, 8, 11, 12, -1, -1, -1, -1, -1, -1 },
401 { 0, 0, 0, 0, 0, 0, 1, 3, 5, 7, 10, 12, 13, -1, -1, -1, -1, -1, -1 },
402 { 0, 0, 0, 0, 1, 2, 2, 9, 13, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
405 { { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
406 { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
407 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
410 { { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
411 { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
412 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
415 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
416 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
417 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
420 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
421 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
422 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
425 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 8, 11, 12, 12, -1, -1 },
426 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 8, 11, 12, 12, -1, -1 },
427 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
432 * Adjust the frame size to make the average bit rate match the target bit rate.
433 * This is only needed for 11025, 22050, and 44100 sample rates.
435 static void adjust_frame_size(AC3EncodeContext *s)
437 while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
438 s->bits_written -= s->bit_rate;
439 s->samples_written -= s->sample_rate;
441 s->frame_size = s->frame_size_min +
442 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
443 s->bits_written += s->frame_size * 8;
444 s->samples_written += AC3_FRAME_SIZE;
449 * Deinterleave input samples.
450 * Channels are reordered from Libav's default order to AC-3 order.
452 static void deinterleave_input_samples(AC3EncodeContext *s,
453 const SampleType *samples)
457 /* deinterleave and remap input samples */
458 for (ch = 0; ch < s->channels; ch++) {
459 const SampleType *sptr;
462 /* copy last 256 samples of previous frame to the start of the current frame */
463 memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
464 AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
468 sptr = samples + s->channel_map[ch];
469 for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
470 s->planar_samples[ch][i] = *sptr;
478 * Apply the MDCT to input samples to generate frequency coefficients.
479 * This applies the KBD window and normalizes the input to reduce precision
480 * loss due to fixed-point calculations.
482 static void apply_mdct(AC3EncodeContext *s)
486 for (ch = 0; ch < s->channels; ch++) {
487 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
488 AC3Block *block = &s->blocks[blk];
489 const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
491 apply_window(&s->dsp, s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
493 block->coeff_shift[ch+1] = normalize_samples(s);
495 s->mdct.fft.mdct_calcw(&s->mdct.fft, block->mdct_coef[ch+1],
496 s->windowed_samples);
502 static void compute_coupling_strategy(AC3EncodeContext *s)
507 /* set coupling use flags for each block/channel */
508 /* TODO: turn coupling on/off and adjust start band based on bit usage */
509 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
510 AC3Block *block = &s->blocks[blk];
511 for (ch = 1; ch <= s->fbw_channels; ch++)
512 block->channel_in_cpl[ch] = s->cpl_on;
515 /* enable coupling for each block if at least 2 channels have coupling
516 enabled for that block */
518 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
519 AC3Block *block = &s->blocks[blk];
520 block->num_cpl_channels = 0;
521 for (ch = 1; ch <= s->fbw_channels; ch++)
522 block->num_cpl_channels += block->channel_in_cpl[ch];
523 block->cpl_in_use = block->num_cpl_channels > 1;
524 if (!block->cpl_in_use) {
525 block->num_cpl_channels = 0;
526 for (ch = 1; ch <= s->fbw_channels; ch++)
527 block->channel_in_cpl[ch] = 0;
530 block->new_cpl_strategy = !blk;
532 for (ch = 1; ch <= s->fbw_channels; ch++) {
533 if (block->channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]) {
534 block->new_cpl_strategy = 1;
539 block->new_cpl_leak = block->new_cpl_strategy;
541 if (!blk || (block->cpl_in_use && !got_cpl_snr)) {
542 block->new_snr_offsets = 1;
543 if (block->cpl_in_use)
546 block->new_snr_offsets = 0;
550 /* set bandwidth for each channel */
551 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
552 AC3Block *block = &s->blocks[blk];
553 for (ch = 1; ch <= s->fbw_channels; ch++) {
554 if (block->channel_in_cpl[ch])
555 block->end_freq[ch] = s->start_freq[CPL_CH];
557 block->end_freq[ch] = s->bandwidth_code * 3 + 73;
564 * Calculate a single coupling coordinate.
566 static inline float calc_cpl_coord(float energy_ch, float energy_cpl)
570 coord *= sqrtf(energy_ch / energy_cpl);
576 * Calculate coupling channel and coupling coordinates.
577 * TODO: Currently this is only used for the floating-point encoder. I was
578 * able to make it work for the fixed-point encoder, but quality was
579 * generally lower in most cases than not using coupling. If a more
580 * adaptive coupling strategy were to be implemented it might be useful
581 * at that time to use coupling for the fixed-point encoder as well.
583 static void apply_channel_coupling(AC3EncodeContext *s)
585 #if CONFIG_AC3ENC_FLOAT
586 DECLARE_ALIGNED(16, float, cpl_coords) [AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][16] = {{{0}}};
587 DECLARE_ALIGNED(16, int32_t, fixed_cpl_coords)[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][16] = {{{0}}};
588 int blk, ch, bnd, i, j;
589 CoefSumType energy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][16] = {{{0}}};
590 int num_cpl_coefs = s->num_cpl_subbands * 12;
592 /* calculate coupling channel from fbw channels */
593 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
594 AC3Block *block = &s->blocks[blk];
595 CoefType *cpl_coef = &block->mdct_coef[CPL_CH][s->start_freq[CPL_CH]];
596 if (!block->cpl_in_use)
598 memset(cpl_coef-1, 0, (num_cpl_coefs+4) * sizeof(*cpl_coef));
599 for (ch = 1; ch <= s->fbw_channels; ch++) {
600 CoefType *ch_coef = &block->mdct_coef[ch][s->start_freq[CPL_CH]];
601 if (!block->channel_in_cpl[ch])
603 for (i = 0; i < num_cpl_coefs; i++)
604 cpl_coef[i] += ch_coef[i];
606 /* note: coupling start bin % 4 will always be 1 and num_cpl_coefs
607 will always be a multiple of 12, so we need to subtract 1 from
608 the start and add 4 to the length when using optimized
609 functions which require 16-byte alignment. */
611 /* coefficients must be clipped to +/- 1.0 in order to be encoded */
612 s->dsp.vector_clipf(cpl_coef-1, cpl_coef-1, -1.0f, 1.0f, num_cpl_coefs+4);
614 /* scale coupling coefficients from float to 24-bit fixed-point */
615 s->ac3dsp.float_to_fixed24(&block->fixed_coef[CPL_CH][s->start_freq[CPL_CH]-1],
616 cpl_coef-1, num_cpl_coefs+4);
619 /* calculate energy in each band in coupling channel and each fbw channel */
620 /* TODO: possibly use SIMD to speed up energy calculation */
622 i = s->start_freq[CPL_CH];
623 while (i < s->cpl_end_freq) {
624 int band_size = s->cpl_band_sizes[bnd];
625 for (ch = CPL_CH; ch <= s->fbw_channels; ch++) {
626 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
627 AC3Block *block = &s->blocks[blk];
628 if (!block->cpl_in_use || (ch > CPL_CH && !block->channel_in_cpl[ch]))
630 for (j = 0; j < band_size; j++) {
631 CoefType v = block->mdct_coef[ch][i+j];
632 MAC_COEF(energy[blk][ch][bnd], v, v);
640 /* determine which blocks to send new coupling coordinates for */
641 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
642 AC3Block *block = &s->blocks[blk];
643 AC3Block *block0 = blk ? &s->blocks[blk-1] : NULL;
645 CoefSumType coord_diff[AC3_MAX_CHANNELS] = {0,};
647 if (block->cpl_in_use) {
648 /* calculate coupling coordinates for all blocks and calculate the
649 average difference between coordinates in successive blocks */
650 for (ch = 1; ch <= s->fbw_channels; ch++) {
651 if (!block->channel_in_cpl[ch])
654 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
655 cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy[blk][ch][bnd],
656 energy[blk][CPL_CH][bnd]);
657 if (blk > 0 && block0->cpl_in_use &&
658 block0->channel_in_cpl[ch]) {
659 coord_diff[ch] += fabs(cpl_coords[blk-1][ch][bnd] -
660 cpl_coords[blk ][ch][bnd]);
663 coord_diff[ch] /= s->num_cpl_bands;
666 /* send new coordinates if this is the first block, if previous
667 * block did not use coupling but this block does, the channels
668 * using coupling has changed from the previous block, or the
669 * coordinate difference from the last block for any channel is
670 * greater than a threshold value. */
673 } else if (!block0->cpl_in_use) {
676 for (ch = 1; ch <= s->fbw_channels; ch++) {
677 if (block->channel_in_cpl[ch] && !block0->channel_in_cpl[ch]) {
683 for (ch = 1; ch <= s->fbw_channels; ch++) {
684 if (block->channel_in_cpl[ch] && coord_diff[ch] > 0.04) {
692 block->new_cpl_coords = new_coords;
695 /* calculate final coupling coordinates, taking into account reusing of
696 coordinates in successive blocks */
697 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
699 while (blk < AC3_MAX_BLOCKS) {
701 CoefSumType energy_cpl;
702 AC3Block *block = &s->blocks[blk];
704 if (!block->cpl_in_use) {
709 energy_cpl = energy[blk][CPL_CH][bnd];
711 while (!s->blocks[blk1].new_cpl_coords && blk1 < AC3_MAX_BLOCKS) {
712 if (s->blocks[blk1].cpl_in_use)
713 energy_cpl += energy[blk1][CPL_CH][bnd];
717 for (ch = 1; ch <= s->fbw_channels; ch++) {
719 if (!block->channel_in_cpl[ch])
721 energy_ch = energy[blk][ch][bnd];
723 while (!s->blocks[blk1].new_cpl_coords && blk1 < AC3_MAX_BLOCKS) {
724 if (s->blocks[blk1].cpl_in_use)
725 energy_ch += energy[blk1][ch][bnd];
728 cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy_ch, energy_cpl);
734 /* calculate exponents/mantissas for coupling coordinates */
735 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
736 AC3Block *block = &s->blocks[blk];
737 if (!block->cpl_in_use || !block->new_cpl_coords)
740 s->ac3dsp.float_to_fixed24(fixed_cpl_coords[blk][1],
742 s->fbw_channels * 16);
743 s->ac3dsp.extract_exponents(block->cpl_coord_exp[1],
744 fixed_cpl_coords[blk][1],
745 s->fbw_channels * 16);
747 for (ch = 1; ch <= s->fbw_channels; ch++) {
748 int bnd, min_exp, max_exp, master_exp;
750 /* determine master exponent */
751 min_exp = max_exp = block->cpl_coord_exp[ch][0];
752 for (bnd = 1; bnd < s->num_cpl_bands; bnd++) {
753 int exp = block->cpl_coord_exp[ch][bnd];
754 min_exp = FFMIN(exp, min_exp);
755 max_exp = FFMAX(exp, max_exp);
757 master_exp = ((max_exp - 15) + 2) / 3;
758 master_exp = FFMAX(master_exp, 0);
759 while (min_exp < master_exp * 3)
761 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
762 block->cpl_coord_exp[ch][bnd] = av_clip(block->cpl_coord_exp[ch][bnd] -
763 master_exp * 3, 0, 15);
765 block->cpl_master_exp[ch] = master_exp;
767 /* quantize mantissas */
768 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
769 int cpl_exp = block->cpl_coord_exp[ch][bnd];
770 int cpl_mant = (fixed_cpl_coords[blk][ch][bnd] << (5 + cpl_exp + master_exp * 3)) >> 24;
776 block->cpl_coord_mant[ch][bnd] = cpl_mant;
780 #endif /* CONFIG_AC3ENC_FLOAT */
785 * Determine rematrixing flags for each block and band.
787 static void compute_rematrixing_strategy(AC3EncodeContext *s)
791 AC3Block *block, *block0;
793 if (s->channel_mode != AC3_CHMODE_STEREO)
796 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
797 block = &s->blocks[blk];
798 block->new_rematrixing_strategy = !blk;
800 if (!s->rematrixing_enabled) {
805 block->num_rematrixing_bands = 4;
806 if (block->cpl_in_use) {
807 block->num_rematrixing_bands -= (s->start_freq[CPL_CH] <= 61);
808 block->num_rematrixing_bands -= (s->start_freq[CPL_CH] == 37);
809 if (blk && block->num_rematrixing_bands != block0->num_rematrixing_bands)
810 block->new_rematrixing_strategy = 1;
812 nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
814 for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {
815 /* calculate calculate sum of squared coeffs for one band in one block */
816 int start = ff_ac3_rematrix_band_tab[bnd];
817 int end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
818 CoefSumType sum[4] = {0,};
819 for (i = start; i < end; i++) {
820 CoefType lt = block->mdct_coef[1][i];
821 CoefType rt = block->mdct_coef[2][i];
822 CoefType md = lt + rt;
823 CoefType sd = lt - rt;
824 MAC_COEF(sum[0], lt, lt);
825 MAC_COEF(sum[1], rt, rt);
826 MAC_COEF(sum[2], md, md);
827 MAC_COEF(sum[3], sd, sd);
830 /* compare sums to determine if rematrixing will be used for this band */
831 if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
832 block->rematrixing_flags[bnd] = 1;
834 block->rematrixing_flags[bnd] = 0;
836 /* determine if new rematrixing flags will be sent */
838 block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
839 block->new_rematrixing_strategy = 1;
848 * Apply stereo rematrixing to coefficients based on rematrixing flags.
850 static void apply_rematrixing(AC3EncodeContext *s)
857 if (!s->rematrixing_enabled)
860 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
861 AC3Block *block = &s->blocks[blk];
862 if (block->new_rematrixing_strategy)
863 flags = block->rematrixing_flags;
864 nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
865 for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {
867 start = ff_ac3_rematrix_band_tab[bnd];
868 end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
869 for (i = start; i < end; i++) {
870 int32_t lt = block->fixed_coef[1][i];
871 int32_t rt = block->fixed_coef[2][i];
872 block->fixed_coef[1][i] = (lt + rt) >> 1;
873 block->fixed_coef[2][i] = (lt - rt) >> 1;
882 * Initialize exponent tables.
884 static av_cold void exponent_init(AC3EncodeContext *s)
886 int expstr, i, grpsize;
888 for (expstr = EXP_D15-1; expstr <= EXP_D45-1; expstr++) {
889 grpsize = 3 << expstr;
890 for (i = 12; i < 256; i++) {
891 exponent_group_tab[0][expstr][i] = (i + grpsize - 4) / grpsize;
892 exponent_group_tab[1][expstr][i] = (i ) / grpsize;
896 exponent_group_tab[0][0][7] = 2;
901 * Extract exponents from the MDCT coefficients.
902 * This takes into account the normalization that was done to the input samples
903 * by adjusting the exponents by the exponent shift values.
905 static void extract_exponents(AC3EncodeContext *s)
909 for (ch = !s->cpl_on; ch <= s->channels; ch++) {
910 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
911 AC3Block *block = &s->blocks[blk];
912 s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch],
920 * Exponent Difference Threshold.
921 * New exponents are sent if their SAD exceed this number.
923 #define EXP_DIFF_THRESHOLD 500
927 * Calculate exponent strategies for all channels.
928 * Array arrangement is reversed to simplify the per-channel calculation.
930 static void compute_exp_strategy(AC3EncodeContext *s)
934 for (ch = !s->cpl_on; ch <= s->fbw_channels; ch++) {
935 uint8_t *exp_strategy = s->exp_strategy[ch];
936 uint8_t *exp = s->blocks[0].exp[ch];
939 /* estimate if the exponent variation & decide if they should be
940 reused in the next frame */
941 exp_strategy[0] = EXP_NEW;
942 exp += AC3_MAX_COEFS;
943 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++, exp += AC3_MAX_COEFS) {
944 if ((ch == CPL_CH && (!s->blocks[blk].cpl_in_use || !s->blocks[blk-1].cpl_in_use)) ||
945 (ch > CPL_CH && (s->blocks[blk].channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]))) {
946 exp_strategy[blk] = EXP_NEW;
949 exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
950 exp_strategy[blk] = EXP_REUSE;
951 if (ch == CPL_CH && exp_diff > (EXP_DIFF_THRESHOLD * (s->blocks[blk].end_freq[ch] - s->start_freq[ch]) / AC3_MAX_COEFS))
952 exp_strategy[blk] = EXP_NEW;
953 else if (ch > CPL_CH && exp_diff > EXP_DIFF_THRESHOLD)
954 exp_strategy[blk] = EXP_NEW;
957 /* now select the encoding strategy type : if exponents are often
958 recoded, we use a coarse encoding */
960 while (blk < AC3_MAX_BLOCKS) {
962 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
964 switch (blk1 - blk) {
965 case 1: exp_strategy[blk] = EXP_D45; break;
967 case 3: exp_strategy[blk] = EXP_D25; break;
968 default: exp_strategy[blk] = EXP_D15; break;
975 s->exp_strategy[ch][0] = EXP_D15;
976 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
977 s->exp_strategy[ch][blk] = EXP_REUSE;
983 * Update the exponents so that they are the ones the decoder will decode.
985 static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy,
990 nb_groups = exponent_group_tab[cpl][exp_strategy-1][nb_exps] * 3;
992 /* for each group, compute the minimum exponent */
993 switch(exp_strategy) {
995 for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
996 uint8_t exp_min = exp[k];
997 if (exp[k+1] < exp_min)
999 exp[i-cpl] = exp_min;
1004 for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
1005 uint8_t exp_min = exp[k];
1006 if (exp[k+1] < exp_min)
1008 if (exp[k+2] < exp_min)
1010 if (exp[k+3] < exp_min)
1012 exp[i-cpl] = exp_min;
1018 /* constraint for DC exponent */
1019 if (!cpl && exp[0] > 15)
1022 /* decrease the delta between each groups to within 2 so that they can be
1023 differentially encoded */
1024 for (i = 1; i <= nb_groups; i++)
1025 exp[i] = FFMIN(exp[i], exp[i-1] + 2);
1028 exp[i] = FFMIN(exp[i], exp[i+1] + 2);
1031 exp[-1] = exp[0] & ~1;
1033 /* now we have the exponent values the decoder will see */
1034 switch (exp_strategy) {
1036 for (i = nb_groups, k = (nb_groups * 2)-cpl; i > 0; i--) {
1037 uint8_t exp1 = exp[i-cpl];
1043 for (i = nb_groups, k = (nb_groups * 4)-cpl; i > 0; i--) {
1044 exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i-cpl];
1053 * Encode exponents from original extracted form to what the decoder will see.
1054 * This copies and groups exponents based on exponent strategy and reduces
1055 * deltas between adjacent exponent groups so that they can be differentially
1058 static void encode_exponents(AC3EncodeContext *s)
1060 int blk, blk1, ch, cpl;
1061 uint8_t *exp, *exp_strategy;
1062 int nb_coefs, num_reuse_blocks;
1064 for (ch = !s->cpl_on; ch <= s->channels; ch++) {
1065 exp = s->blocks[0].exp[ch] + s->start_freq[ch];
1066 exp_strategy = s->exp_strategy[ch];
1068 cpl = (ch == CPL_CH);
1070 while (blk < AC3_MAX_BLOCKS) {
1071 AC3Block *block = &s->blocks[blk];
1072 if (cpl && !block->cpl_in_use) {
1073 exp += AC3_MAX_COEFS;
1077 nb_coefs = block->end_freq[ch] - s->start_freq[ch];
1080 /* count the number of EXP_REUSE blocks after the current block
1081 and set exponent reference block pointers */
1082 block->exp_ref_block[ch] = block;
1083 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
1084 s->blocks[blk1].exp_ref_block[ch] = block;
1087 num_reuse_blocks = blk1 - blk - 1;
1089 /* for the EXP_REUSE case we select the min of the exponents */
1090 s->ac3dsp.ac3_exponent_min(exp-s->start_freq[ch], num_reuse_blocks,
1093 encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk], cpl);
1095 exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
1104 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
1105 * varies depending on exponent strategy and bandwidth.
1107 static void group_exponents(AC3EncodeContext *s)
1109 int blk, ch, i, cpl;
1110 int group_size, nb_groups, bit_count;
1112 int delta0, delta1, delta2;
1116 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1117 AC3Block *block = &s->blocks[blk];
1118 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1119 int exp_strategy = s->exp_strategy[ch][blk];
1120 if (exp_strategy == EXP_REUSE)
1122 cpl = (ch == CPL_CH);
1123 group_size = exp_strategy + (exp_strategy == EXP_D45);
1124 nb_groups = exponent_group_tab[cpl][exp_strategy-1][block->end_freq[ch]-s->start_freq[ch]];
1125 bit_count += 4 + (nb_groups * 7);
1126 p = block->exp[ch] + s->start_freq[ch] - cpl;
1130 block->grouped_exp[ch][0] = exp1;
1132 /* remaining exponents are delta encoded */
1133 for (i = 1; i <= nb_groups; i++) {
1134 /* merge three delta in one code */
1138 delta0 = exp1 - exp0 + 2;
1139 av_assert2(delta0 >= 0 && delta0 <= 4);
1144 delta1 = exp1 - exp0 + 2;
1145 av_assert2(delta1 >= 0 && delta1 <= 4);
1150 delta2 = exp1 - exp0 + 2;
1151 av_assert2(delta2 >= 0 && delta2 <= 4);
1153 block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
1158 s->exponent_bits = bit_count;
1163 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
1164 * Extract exponents from MDCT coefficients, calculate exponent strategies,
1165 * and encode final exponents.
1167 static void process_exponents(AC3EncodeContext *s)
1169 extract_exponents(s);
1171 compute_exp_strategy(s);
1173 encode_exponents(s);
1182 * Count frame bits that are based solely on fixed parameters.
1183 * This only has to be run once when the encoder is initialized.
1185 static void count_frame_bits_fixed(AC3EncodeContext *s)
1187 static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
1192 * no dynamic range codes
1193 * bit allocation parameters do not change between blocks
1194 * no delta bit allocation
1196 * no auxilliary data
1201 frame_bits += frame_bits_inc[s->channel_mode];
1204 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1205 /* block switch flags */
1206 frame_bits += s->fbw_channels;
1209 frame_bits += s->fbw_channels;
1214 /* exponent strategy */
1215 frame_bits += 2 * s->fbw_channels;
1219 /* bit allocation params */
1222 frame_bits += 2 + 2 + 2 + 2 + 3;
1224 /* delta bit allocation */
1231 /* auxiliary data */
1235 frame_bits += 1 + 16;
1237 s->frame_bits_fixed = frame_bits;
1242 * Initialize bit allocation.
1243 * Set default parameter codes and calculate parameter values.
1245 static void bit_alloc_init(AC3EncodeContext *s)
1249 /* init default parameters */
1250 s->slow_decay_code = 2;
1251 s->fast_decay_code = 1;
1252 s->slow_gain_code = 1;
1253 s->db_per_bit_code = 3;
1255 for (ch = 0; ch <= s->channels; ch++)
1256 s->fast_gain_code[ch] = 4;
1258 /* initial snr offset */
1259 s->coarse_snr_offset = 40;
1261 /* compute real values */
1262 /* currently none of these values change during encoding, so we can just
1263 set them once at initialization */
1264 s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
1265 s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
1266 s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
1267 s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
1268 s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
1269 s->bit_alloc.cpl_fast_leak = 0;
1270 s->bit_alloc.cpl_slow_leak = 0;
1272 count_frame_bits_fixed(s);
1277 * Count the bits used to encode the frame, minus exponents and mantissas.
1278 * Bits based on fixed parameters have already been counted, so now we just
1279 * have to add the bits based on parameters that change during encoding.
1281 static void count_frame_bits(AC3EncodeContext *s)
1283 AC3EncOptions *opt = &s->options;
1288 if (opt->audio_production_info)
1290 if (s->bitstream_id == 6) {
1291 if (opt->extended_bsi_1)
1293 if (opt->extended_bsi_2)
1298 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1299 AC3Block *block = &s->blocks[blk];
1301 /* coupling strategy */
1303 if (block->new_cpl_strategy) {
1305 if (block->cpl_in_use) {
1306 frame_bits += s->fbw_channels;
1307 if (s->channel_mode == AC3_CHMODE_STEREO)
1309 frame_bits += 4 + 4;
1310 frame_bits += s->num_cpl_subbands - 1;
1314 /* coupling coordinates */
1315 if (block->cpl_in_use) {
1316 for (ch = 1; ch <= s->fbw_channels; ch++) {
1317 if (block->channel_in_cpl[ch]) {
1319 if (block->new_cpl_coords) {
1321 frame_bits += (4 + 4) * s->num_cpl_bands;
1327 /* stereo rematrixing */
1328 if (s->channel_mode == AC3_CHMODE_STEREO) {
1330 if (s->blocks[blk].new_rematrixing_strategy)
1331 frame_bits += block->num_rematrixing_bands;
1334 /* bandwidth codes & gain range */
1335 for (ch = 1; ch <= s->fbw_channels; ch++) {
1336 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1337 if (!block->channel_in_cpl[ch])
1343 /* coupling exponent strategy */
1344 if (block->cpl_in_use)
1347 /* snr offsets and fast gain codes */
1349 if (block->new_snr_offsets)
1350 frame_bits += 6 + (s->channels + block->cpl_in_use) * (4 + 3);
1352 /* coupling leak info */
1353 if (block->cpl_in_use) {
1355 if (block->new_cpl_leak)
1356 frame_bits += 3 + 3;
1360 s->frame_bits = s->frame_bits_fixed + frame_bits;
1365 * Finalize the mantissa bit count by adding in the grouped mantissas.
1367 static int compute_mantissa_size_final(int mant_cnt[5])
1369 // bap=1 : 3 mantissas in 5 bits
1370 int bits = (mant_cnt[1] / 3) * 5;
1371 // bap=2 : 3 mantissas in 7 bits
1372 // bap=4 : 2 mantissas in 7 bits
1373 bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
1374 // bap=3 : each mantissa is 3 bits
1375 bits += mant_cnt[3] * 3;
1381 * Calculate masking curve based on the final exponents.
1382 * Also calculate the power spectral densities to use in future calculations.
1384 static void bit_alloc_masking(AC3EncodeContext *s)
1388 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1389 AC3Block *block = &s->blocks[blk];
1390 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1391 /* We only need psd and mask for calculating bap.
1392 Since we currently do not calculate bap when exponent
1393 strategy is EXP_REUSE we do not need to calculate psd or mask. */
1394 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1395 ff_ac3_bit_alloc_calc_psd(block->exp[ch], s->start_freq[ch],
1396 block->end_freq[ch], block->psd[ch],
1397 block->band_psd[ch]);
1398 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
1399 s->start_freq[ch], block->end_freq[ch],
1400 ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
1401 ch == s->lfe_channel,
1402 DBA_NONE, 0, NULL, NULL, NULL,
1411 * Ensure that bap for each block and channel point to the current bap_buffer.
1412 * They may have been switched during the bit allocation search.
1414 static void reset_block_bap(AC3EncodeContext *s)
1417 int channels = s->channels + 1;
1418 if (s->blocks[0].bap[0] == s->bap_buffer)
1420 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1421 for (ch = 0; ch < channels; ch++) {
1422 s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * channels + ch)];
1429 * Run the bit allocation with a given SNR offset.
1430 * This calculates the bit allocation pointers that will be used to determine
1431 * the quantization of each mantissa.
1432 * @return the number of bits needed for mantissas if the given SNR offset is
1435 static int bit_alloc(AC3EncodeContext *s, int snr_offset)
1441 snr_offset = (snr_offset - 240) << 2;
1445 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1446 AC3Block *block = &s->blocks[blk];
1447 AC3Block *ref_block;
1449 int got_cpl = !block->cpl_in_use;
1450 // initialize grouped mantissa counts. these are set so that they are
1451 // padded to the next whole group size when bits are counted in
1452 // compute_mantissa_size_final
1453 mant_cnt[0] = mant_cnt[3] = 0;
1454 mant_cnt[1] = mant_cnt[2] = 2;
1456 for (ch = 1; ch <= s->channels; ch++) {
1457 if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1463 /* Currently the only bit allocation parameters which vary across
1464 blocks within a frame are the exponent values. We can take
1465 advantage of that by reusing the bit allocation pointers
1466 whenever we reuse exponents. */
1467 ref_block = block->exp_ref_block[ch];
1468 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1469 s->ac3dsp.bit_alloc_calc_bap(ref_block->mask[ch], ref_block->psd[ch],
1470 s->start_freq[ch], block->end_freq[ch],
1471 snr_offset, s->bit_alloc.floor,
1472 ff_ac3_bap_tab, ref_block->bap[ch]);
1474 mantissa_bits += s->ac3dsp.compute_mantissa_size(mant_cnt,
1475 ref_block->bap[ch]+s->start_freq[ch],
1476 block->end_freq[ch]-s->start_freq[ch]);
1480 mantissa_bits += compute_mantissa_size_final(mant_cnt);
1482 return mantissa_bits;
1487 * Constant bitrate bit allocation search.
1488 * Find the largest SNR offset that will allow data to fit in the frame.
1490 static int cbr_bit_allocation(AC3EncodeContext *s)
1494 int snr_offset, snr_incr;
1496 bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1498 return AVERROR(EINVAL);
1500 snr_offset = s->coarse_snr_offset << 4;
1502 /* if previous frame SNR offset was 1023, check if current frame can also
1503 use SNR offset of 1023. if so, skip the search. */
1504 if ((snr_offset | s->fine_snr_offset[1]) == 1023) {
1505 if (bit_alloc(s, 1023) <= bits_left)
1509 while (snr_offset >= 0 &&
1510 bit_alloc(s, snr_offset) > bits_left) {
1514 return AVERROR(EINVAL);
1516 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1517 for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1518 while (snr_offset + snr_incr <= 1023 &&
1519 bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1520 snr_offset += snr_incr;
1521 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1524 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1527 s->coarse_snr_offset = snr_offset >> 4;
1528 for (ch = !s->cpl_on; ch <= s->channels; ch++)
1529 s->fine_snr_offset[ch] = snr_offset & 0xF;
1536 * Downgrade exponent strategies to reduce the bits used by the exponents.
1537 * This is a fallback for when bit allocation fails with the normal exponent
1538 * strategies. Each time this function is run it only downgrades the
1539 * strategy in 1 channel of 1 block.
1540 * @return non-zero if downgrade was unsuccessful
1542 static int downgrade_exponents(AC3EncodeContext *s)
1546 for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1547 for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
1548 if (s->exp_strategy[ch][blk] == EXP_D15) {
1549 s->exp_strategy[ch][blk] = EXP_D25;
1554 for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1555 for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
1556 if (s->exp_strategy[ch][blk] == EXP_D25) {
1557 s->exp_strategy[ch][blk] = EXP_D45;
1562 /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
1563 the block number > 0 */
1564 for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
1565 for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
1566 if (s->exp_strategy[ch][blk] > EXP_REUSE) {
1567 s->exp_strategy[ch][blk] = EXP_REUSE;
1577 * Perform bit allocation search.
1578 * Finds the SNR offset value that maximizes quality and fits in the specified
1579 * frame size. Output is the SNR offset and a set of bit allocation pointers
1580 * used to quantize the mantissas.
1582 static int compute_bit_allocation(AC3EncodeContext *s)
1586 count_frame_bits(s);
1588 bit_alloc_masking(s);
1590 ret = cbr_bit_allocation(s);
1592 /* fallback 1: disable channel coupling */
1595 compute_coupling_strategy(s);
1596 compute_rematrixing_strategy(s);
1597 apply_rematrixing(s);
1598 process_exponents(s);
1599 ret = compute_bit_allocation(s);
1603 /* fallback 2: downgrade exponents */
1604 if (!downgrade_exponents(s)) {
1605 extract_exponents(s);
1606 encode_exponents(s);
1608 ret = compute_bit_allocation(s);
1612 /* fallbacks were not enough... */
1621 * Symmetric quantization on 'levels' levels.
1623 static inline int sym_quant(int c, int e, int levels)
1625 int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1626 av_assert2(v >= 0 && v < levels);
1632 * Asymmetric quantization on 2^qbits levels.
1634 static inline int asym_quant(int c, int e, int qbits)
1638 lshift = e + qbits - 24;
1645 m = (1 << (qbits-1));
1648 av_assert2(v >= -m);
1649 return v & ((1 << qbits)-1);
1654 * Quantize a set of mantissas for a single channel in a single block.
1656 static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1657 uint8_t *exp, uint8_t *bap,
1658 uint16_t *qmant, int start_freq,
1663 for (i = start_freq; i < end_freq; i++) {
1665 int c = fixed_coef[i];
1673 v = sym_quant(c, e, 3);
1674 switch (s->mant1_cnt) {
1676 s->qmant1_ptr = &qmant[i];
1681 *s->qmant1_ptr += 3 * v;
1686 *s->qmant1_ptr += v;
1693 v = sym_quant(c, e, 5);
1694 switch (s->mant2_cnt) {
1696 s->qmant2_ptr = &qmant[i];
1701 *s->qmant2_ptr += 5 * v;
1706 *s->qmant2_ptr += v;
1713 v = sym_quant(c, e, 7);
1716 v = sym_quant(c, e, 11);
1717 switch (s->mant4_cnt) {
1719 s->qmant4_ptr = &qmant[i];
1724 *s->qmant4_ptr += v;
1731 v = sym_quant(c, e, 15);
1734 v = asym_quant(c, e, 14);
1737 v = asym_quant(c, e, 16);
1740 v = asym_quant(c, e, b - 1);
1749 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1751 static void quantize_mantissas(AC3EncodeContext *s)
1753 int blk, ch, ch0=0, got_cpl;
1755 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1756 AC3Block *block = &s->blocks[blk];
1757 AC3Block *ref_block;
1760 got_cpl = !block->cpl_in_use;
1761 for (ch = 1; ch <= s->channels; ch++) {
1762 if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1767 ref_block = block->exp_ref_block[ch];
1768 quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1770 ref_block->bap[ch], block->qmant[ch],
1771 s->start_freq[ch], block->end_freq[ch]);
1780 * Write the AC-3 frame header to the output bitstream.
1782 static void output_frame_header(AC3EncodeContext *s)
1784 AC3EncOptions *opt = &s->options;
1786 put_bits(&s->pb, 16, 0x0b77); /* frame header */
1787 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
1788 put_bits(&s->pb, 2, s->bit_alloc.sr_code);
1789 put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1790 put_bits(&s->pb, 5, s->bitstream_id);
1791 put_bits(&s->pb, 3, s->bitstream_mode);
1792 put_bits(&s->pb, 3, s->channel_mode);
1793 if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1794 put_bits(&s->pb, 2, s->center_mix_level);
1795 if (s->channel_mode & 0x04)
1796 put_bits(&s->pb, 2, s->surround_mix_level);
1797 if (s->channel_mode == AC3_CHMODE_STEREO)
1798 put_bits(&s->pb, 2, opt->dolby_surround_mode);
1799 put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1800 put_bits(&s->pb, 5, -opt->dialogue_level);
1801 put_bits(&s->pb, 1, 0); /* no compression control word */
1802 put_bits(&s->pb, 1, 0); /* no lang code */
1803 put_bits(&s->pb, 1, opt->audio_production_info);
1804 if (opt->audio_production_info) {
1805 put_bits(&s->pb, 5, opt->mixing_level - 80);
1806 put_bits(&s->pb, 2, opt->room_type);
1808 put_bits(&s->pb, 1, opt->copyright);
1809 put_bits(&s->pb, 1, opt->original);
1810 if (s->bitstream_id == 6) {
1811 /* alternate bit stream syntax */
1812 put_bits(&s->pb, 1, opt->extended_bsi_1);
1813 if (opt->extended_bsi_1) {
1814 put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1815 put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1816 put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1817 put_bits(&s->pb, 3, s->loro_center_mix_level);
1818 put_bits(&s->pb, 3, s->loro_surround_mix_level);
1820 put_bits(&s->pb, 1, opt->extended_bsi_2);
1821 if (opt->extended_bsi_2) {
1822 put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1823 put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1824 put_bits(&s->pb, 1, opt->ad_converter_type);
1825 put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
1828 put_bits(&s->pb, 1, 0); /* no time code 1 */
1829 put_bits(&s->pb, 1, 0); /* no time code 2 */
1831 put_bits(&s->pb, 1, 0); /* no additional bit stream info */
1836 * Write one audio block to the output bitstream.
1838 static void output_audio_block(AC3EncodeContext *s, int blk)
1840 int ch, i, baie, bnd, got_cpl;
1842 AC3Block *block = &s->blocks[blk];
1844 /* block switching */
1845 for (ch = 0; ch < s->fbw_channels; ch++)
1846 put_bits(&s->pb, 1, 0);
1849 for (ch = 0; ch < s->fbw_channels; ch++)
1850 put_bits(&s->pb, 1, 1);
1852 /* dynamic range codes */
1853 put_bits(&s->pb, 1, 0);
1855 /* channel coupling */
1856 put_bits(&s->pb, 1, block->new_cpl_strategy);
1857 if (block->new_cpl_strategy) {
1858 put_bits(&s->pb, 1, block->cpl_in_use);
1859 if (block->cpl_in_use) {
1860 int start_sub, end_sub;
1861 for (ch = 1; ch <= s->fbw_channels; ch++)
1862 put_bits(&s->pb, 1, block->channel_in_cpl[ch]);
1863 if (s->channel_mode == AC3_CHMODE_STEREO)
1864 put_bits(&s->pb, 1, 0); /* phase flags in use */
1865 start_sub = (s->start_freq[CPL_CH] - 37) / 12;
1866 end_sub = (s->cpl_end_freq - 37) / 12;
1867 put_bits(&s->pb, 4, start_sub);
1868 put_bits(&s->pb, 4, end_sub - 3);
1869 for (bnd = start_sub+1; bnd < end_sub; bnd++)
1870 put_bits(&s->pb, 1, ff_eac3_default_cpl_band_struct[bnd]);
1874 /* coupling coordinates */
1875 if (block->cpl_in_use) {
1876 for (ch = 1; ch <= s->fbw_channels; ch++) {
1877 if (block->channel_in_cpl[ch]) {
1878 put_bits(&s->pb, 1, block->new_cpl_coords);
1879 if (block->new_cpl_coords) {
1880 put_bits(&s->pb, 2, block->cpl_master_exp[ch]);
1881 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
1882 put_bits(&s->pb, 4, block->cpl_coord_exp [ch][bnd]);
1883 put_bits(&s->pb, 4, block->cpl_coord_mant[ch][bnd]);
1890 /* stereo rematrixing */
1891 if (s->channel_mode == AC3_CHMODE_STEREO) {
1892 put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1893 if (block->new_rematrixing_strategy) {
1894 /* rematrixing flags */
1895 for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++)
1896 put_bits(&s->pb, 1, block->rematrixing_flags[bnd]);
1900 /* exponent strategy */
1901 for (ch = !block->cpl_in_use; ch <= s->fbw_channels; ch++)
1902 put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1904 put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1907 for (ch = 1; ch <= s->fbw_channels; ch++) {
1908 if (s->exp_strategy[ch][blk] != EXP_REUSE && !block->channel_in_cpl[ch])
1909 put_bits(&s->pb, 6, s->bandwidth_code);
1913 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1915 int cpl = (ch == CPL_CH);
1917 if (s->exp_strategy[ch][blk] == EXP_REUSE)
1921 put_bits(&s->pb, 4, block->grouped_exp[ch][0] >> cpl);
1923 /* exponent groups */
1924 nb_groups = exponent_group_tab[cpl][s->exp_strategy[ch][blk]-1][block->end_freq[ch]-s->start_freq[ch]];
1925 for (i = 1; i <= nb_groups; i++)
1926 put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1928 /* gain range info */
1929 if (ch != s->lfe_channel && !cpl)
1930 put_bits(&s->pb, 2, 0);
1933 /* bit allocation info */
1935 put_bits(&s->pb, 1, baie);
1937 put_bits(&s->pb, 2, s->slow_decay_code);
1938 put_bits(&s->pb, 2, s->fast_decay_code);
1939 put_bits(&s->pb, 2, s->slow_gain_code);
1940 put_bits(&s->pb, 2, s->db_per_bit_code);
1941 put_bits(&s->pb, 3, s->floor_code);
1945 put_bits(&s->pb, 1, block->new_snr_offsets);
1946 if (block->new_snr_offsets) {
1947 put_bits(&s->pb, 6, s->coarse_snr_offset);
1948 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1949 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1950 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1955 if (block->cpl_in_use) {
1956 put_bits(&s->pb, 1, block->new_cpl_leak);
1957 if (block->new_cpl_leak) {
1958 put_bits(&s->pb, 3, s->bit_alloc.cpl_fast_leak);
1959 put_bits(&s->pb, 3, s->bit_alloc.cpl_slow_leak);
1963 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1964 put_bits(&s->pb, 1, 0); /* no data to skip */
1967 got_cpl = !block->cpl_in_use;
1968 for (ch = 1; ch <= s->channels; ch++) {
1970 AC3Block *ref_block;
1972 if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1977 ref_block = block->exp_ref_block[ch];
1978 for (i = s->start_freq[ch]; i < block->end_freq[ch]; i++) {
1979 q = block->qmant[ch][i];
1980 b = ref_block->bap[ch][i];
1983 case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
1984 case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
1985 case 3: put_bits(&s->pb, 3, q); break;
1986 case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
1987 case 14: put_bits(&s->pb, 14, q); break;
1988 case 15: put_bits(&s->pb, 16, q); break;
1989 default: put_bits(&s->pb, b-1, q); break;
1998 /** CRC-16 Polynomial */
1999 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
2002 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
2019 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
2025 r = mul_poly(r, a, poly);
2026 a = mul_poly(a, a, poly);
2034 * Fill the end of the frame with 0's and compute the two CRCs.
2036 static void output_frame_end(AC3EncodeContext *s)
2038 const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
2039 int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
2042 frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
2044 /* pad the remainder of the frame with zeros */
2045 av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
2046 flush_put_bits(&s->pb);
2048 pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
2049 av_assert2(pad_bytes >= 0);
2051 memset(put_bits_ptr(&s->pb), 0, pad_bytes);
2054 /* this is not so easy because it is at the beginning of the data... */
2055 crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
2056 crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
2057 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
2058 AV_WB16(frame + 2, crc1);
2061 crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
2062 s->frame_size - frame_size_58 - 3);
2063 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
2064 /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
2065 if (crc2 == 0x770B) {
2066 frame[s->frame_size - 3] ^= 0x1;
2067 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
2069 crc2 = av_bswap16(crc2);
2070 AV_WB16(frame + s->frame_size - 2, crc2);
2075 * Write the frame to the output bitstream.
2077 static void output_frame(AC3EncodeContext *s, unsigned char *frame)
2081 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
2083 output_frame_header(s);
2085 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2086 output_audio_block(s, blk);
2088 output_frame_end(s);
2092 static void dprint_options(AVCodecContext *avctx)
2095 AC3EncodeContext *s = avctx->priv_data;
2096 AC3EncOptions *opt = &s->options;
2099 switch (s->bitstream_id) {
2100 case 6: av_strlcpy(strbuf, "AC-3 (alt syntax)", 32); break;
2101 case 8: av_strlcpy(strbuf, "AC-3 (standard)", 32); break;
2102 case 9: av_strlcpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
2103 case 10: av_strlcpy(strbuf, "AC-3 (dnet quater-rate", 32); break;
2104 default: snprintf(strbuf, 32, "ERROR");
2106 av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
2107 av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
2108 av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
2109 av_dlog(avctx, "channel_layout: %s\n", strbuf);
2110 av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
2111 av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
2113 av_dlog(avctx, "cutoff: %d\n", s->cutoff);
2115 av_dlog(avctx, "per_frame_metadata: %s\n",
2116 opt->allow_per_frame_metadata?"on":"off");
2118 av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
2119 s->center_mix_level);
2121 av_dlog(avctx, "center_mixlev: {not written}\n");
2122 if (s->has_surround)
2123 av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
2124 s->surround_mix_level);
2126 av_dlog(avctx, "surround_mixlev: {not written}\n");
2127 if (opt->audio_production_info) {
2128 av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
2129 switch (opt->room_type) {
2130 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
2131 case 1: av_strlcpy(strbuf, "large", 32); break;
2132 case 2: av_strlcpy(strbuf, "small", 32); break;
2133 default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
2135 av_dlog(avctx, "room_type: %s\n", strbuf);
2137 av_dlog(avctx, "mixing_level: {not written}\n");
2138 av_dlog(avctx, "room_type: {not written}\n");
2140 av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
2141 av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
2142 if (s->channel_mode == AC3_CHMODE_STEREO) {
2143 switch (opt->dolby_surround_mode) {
2144 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
2145 case 1: av_strlcpy(strbuf, "on", 32); break;
2146 case 2: av_strlcpy(strbuf, "off", 32); break;
2147 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
2149 av_dlog(avctx, "dsur_mode: %s\n", strbuf);
2151 av_dlog(avctx, "dsur_mode: {not written}\n");
2153 av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
2155 if (s->bitstream_id == 6) {
2156 if (opt->extended_bsi_1) {
2157 switch (opt->preferred_stereo_downmix) {
2158 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
2159 case 1: av_strlcpy(strbuf, "ltrt", 32); break;
2160 case 2: av_strlcpy(strbuf, "loro", 32); break;
2161 default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
2163 av_dlog(avctx, "dmix_mode: %s\n", strbuf);
2164 av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
2165 opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
2166 av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
2167 opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
2168 av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
2169 opt->loro_center_mix_level, s->loro_center_mix_level);
2170 av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
2171 opt->loro_surround_mix_level, s->loro_surround_mix_level);
2173 av_dlog(avctx, "extended bitstream info 1: {not written}\n");
2175 if (opt->extended_bsi_2) {
2176 switch (opt->dolby_surround_ex_mode) {
2177 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
2178 case 1: av_strlcpy(strbuf, "on", 32); break;
2179 case 2: av_strlcpy(strbuf, "off", 32); break;
2180 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
2182 av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
2183 switch (opt->dolby_headphone_mode) {
2184 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
2185 case 1: av_strlcpy(strbuf, "on", 32); break;
2186 case 2: av_strlcpy(strbuf, "off", 32); break;
2187 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
2189 av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
2191 switch (opt->ad_converter_type) {
2192 case 0: av_strlcpy(strbuf, "standard", 32); break;
2193 case 1: av_strlcpy(strbuf, "hdcd", 32); break;
2194 default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
2196 av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
2198 av_dlog(avctx, "extended bitstream info 2: {not written}\n");
2205 #define FLT_OPTION_THRESHOLD 0.01
2207 static int validate_float_option(float v, const float *v_list, int v_list_size)
2211 for (i = 0; i < v_list_size; i++) {
2212 if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
2213 v > (v_list[i] - FLT_OPTION_THRESHOLD))
2216 if (i == v_list_size)
2223 static void validate_mix_level(void *log_ctx, const char *opt_name,
2224 float *opt_param, const float *list,
2225 int list_size, int default_value, int min_value,
2228 int mixlev = validate_float_option(*opt_param, list, list_size);
2229 if (mixlev < min_value) {
2230 mixlev = default_value;
2231 if (*opt_param >= 0.0) {
2232 av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
2233 "default value: %0.3f\n", opt_name, list[mixlev]);
2236 *opt_param = list[mixlev];
2237 *ctx_param = mixlev;
2242 * Validate metadata options as set by AVOption system.
2243 * These values can optionally be changed per-frame.
2245 static int validate_metadata(AVCodecContext *avctx)
2247 AC3EncodeContext *s = avctx->priv_data;
2248 AC3EncOptions *opt = &s->options;
2250 /* validate mixing levels */
2251 if (s->has_center) {
2252 validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
2253 cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
2254 &s->center_mix_level);
2256 if (s->has_surround) {
2257 validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
2258 surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
2259 &s->surround_mix_level);
2262 /* set audio production info flag */
2263 if (opt->mixing_level >= 0 || opt->room_type >= 0) {
2264 if (opt->mixing_level < 0) {
2265 av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
2266 "room_type is set\n");
2267 return AVERROR(EINVAL);
2269 if (opt->mixing_level < 80) {
2270 av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
2271 "80dB and 111dB\n");
2272 return AVERROR(EINVAL);
2274 /* default room type */
2275 if (opt->room_type < 0)
2277 opt->audio_production_info = 1;
2279 opt->audio_production_info = 0;
2282 /* set extended bsi 1 flag */
2283 if ((s->has_center || s->has_surround) &&
2284 (opt->preferred_stereo_downmix >= 0 ||
2285 opt->ltrt_center_mix_level >= 0 ||
2286 opt->ltrt_surround_mix_level >= 0 ||
2287 opt->loro_center_mix_level >= 0 ||
2288 opt->loro_surround_mix_level >= 0)) {
2289 /* default preferred stereo downmix */
2290 if (opt->preferred_stereo_downmix < 0)
2291 opt->preferred_stereo_downmix = 0;
2292 /* validate Lt/Rt center mix level */
2293 validate_mix_level(avctx, "ltrt_center_mix_level",
2294 &opt->ltrt_center_mix_level, extmixlev_options,
2295 EXTMIXLEV_NUM_OPTIONS, 5, 0,
2296 &s->ltrt_center_mix_level);
2297 /* validate Lt/Rt surround mix level */
2298 validate_mix_level(avctx, "ltrt_surround_mix_level",
2299 &opt->ltrt_surround_mix_level, extmixlev_options,
2300 EXTMIXLEV_NUM_OPTIONS, 6, 3,
2301 &s->ltrt_surround_mix_level);
2302 /* validate Lo/Ro center mix level */
2303 validate_mix_level(avctx, "loro_center_mix_level",
2304 &opt->loro_center_mix_level, extmixlev_options,
2305 EXTMIXLEV_NUM_OPTIONS, 5, 0,
2306 &s->loro_center_mix_level);
2307 /* validate Lo/Ro surround mix level */
2308 validate_mix_level(avctx, "loro_surround_mix_level",
2309 &opt->loro_surround_mix_level, extmixlev_options,
2310 EXTMIXLEV_NUM_OPTIONS, 6, 3,
2311 &s->loro_surround_mix_level);
2312 opt->extended_bsi_1 = 1;
2314 opt->extended_bsi_1 = 0;
2317 /* set extended bsi 2 flag */
2318 if (opt->dolby_surround_ex_mode >= 0 ||
2319 opt->dolby_headphone_mode >= 0 ||
2320 opt->ad_converter_type >= 0) {
2321 /* default dolby surround ex mode */
2322 if (opt->dolby_surround_ex_mode < 0)
2323 opt->dolby_surround_ex_mode = 0;
2324 /* default dolby headphone mode */
2325 if (opt->dolby_headphone_mode < 0)
2326 opt->dolby_headphone_mode = 0;
2327 /* default A/D converter type */
2328 if (opt->ad_converter_type < 0)
2329 opt->ad_converter_type = 0;
2330 opt->extended_bsi_2 = 1;
2332 opt->extended_bsi_2 = 0;
2335 /* set bitstream id for alternate bitstream syntax */
2336 if (opt->extended_bsi_1 || opt->extended_bsi_2) {
2337 if (s->bitstream_id > 8 && s->bitstream_id < 11) {
2338 static int warn_once = 1;
2340 av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
2341 "not compatible with reduced samplerates. writing of "
2342 "extended bitstream information will be disabled.\n");
2346 s->bitstream_id = 6;
2355 * Encode a single AC-3 frame.
2357 static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
2358 int buf_size, void *data)
2360 AC3EncodeContext *s = avctx->priv_data;
2361 const SampleType *samples = data;
2364 if (s->options.allow_per_frame_metadata) {
2365 ret = validate_metadata(avctx);
2370 if (s->bit_alloc.sr_code == 1)
2371 adjust_frame_size(s);
2373 deinterleave_input_samples(s, samples);
2377 scale_coefficients(s);
2379 s->cpl_on = s->cpl_enabled;
2380 compute_coupling_strategy(s);
2383 apply_channel_coupling(s);
2385 compute_rematrixing_strategy(s);
2387 apply_rematrixing(s);
2389 process_exponents(s);
2391 ret = compute_bit_allocation(s);
2393 av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
2397 quantize_mantissas(s);
2399 output_frame(s, frame);
2401 return s->frame_size;
2406 * Finalize encoding and free any memory allocated by the encoder.
2408 static av_cold int ac3_encode_close(AVCodecContext *avctx)
2411 AC3EncodeContext *s = avctx->priv_data;
2413 for (ch = 0; ch < s->channels; ch++)
2414 av_freep(&s->planar_samples[ch]);
2415 av_freep(&s->planar_samples);
2416 av_freep(&s->bap_buffer);
2417 av_freep(&s->bap1_buffer);
2418 av_freep(&s->mdct_coef_buffer);
2419 av_freep(&s->fixed_coef_buffer);
2420 av_freep(&s->exp_buffer);
2421 av_freep(&s->grouped_exp_buffer);
2422 av_freep(&s->psd_buffer);
2423 av_freep(&s->band_psd_buffer);
2424 av_freep(&s->mask_buffer);
2425 av_freep(&s->qmant_buffer);
2426 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2427 AC3Block *block = &s->blocks[blk];
2428 av_freep(&block->bap);
2429 av_freep(&block->mdct_coef);
2430 av_freep(&block->fixed_coef);
2431 av_freep(&block->exp);
2432 av_freep(&block->grouped_exp);
2433 av_freep(&block->psd);
2434 av_freep(&block->band_psd);
2435 av_freep(&block->mask);
2436 av_freep(&block->qmant);
2441 av_freep(&avctx->coded_frame);
2447 * Set channel information during initialization.
2449 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
2450 int64_t *channel_layout)
2454 if (channels < 1 || channels > AC3_MAX_CHANNELS)
2455 return AVERROR(EINVAL);
2456 if ((uint64_t)*channel_layout > 0x7FF)
2457 return AVERROR(EINVAL);
2458 ch_layout = *channel_layout;
2460 ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
2462 s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
2463 s->channels = channels;
2464 s->fbw_channels = channels - s->lfe_on;
2465 s->lfe_channel = s->lfe_on ? s->fbw_channels + 1 : -1;
2467 ch_layout -= AV_CH_LOW_FREQUENCY;
2469 switch (ch_layout) {
2470 case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
2471 case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
2472 case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
2473 case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
2474 case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
2475 case AV_CH_LAYOUT_QUAD:
2476 case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
2477 case AV_CH_LAYOUT_5POINT0:
2478 case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
2480 return AVERROR(EINVAL);
2482 s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
2483 s->has_surround = s->channel_mode & 0x04;
2485 s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
2486 *channel_layout = ch_layout;
2488 *channel_layout |= AV_CH_LOW_FREQUENCY;
2494 static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
2498 /* validate channel layout */
2499 if (!avctx->channel_layout) {
2500 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
2501 "encoder will guess the layout, but it "
2502 "might be incorrect.\n");
2504 ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
2506 av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
2510 /* validate sample rate */
2511 for (i = 0; i < 9; i++) {
2512 if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
2516 av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
2517 return AVERROR(EINVAL);
2519 s->sample_rate = avctx->sample_rate;
2520 s->bit_alloc.sr_shift = i % 3;
2521 s->bit_alloc.sr_code = i / 3;
2522 s->bitstream_id = 8 + s->bit_alloc.sr_shift;
2524 /* validate bit rate */
2525 for (i = 0; i < 19; i++) {
2526 if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
2530 av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2531 return AVERROR(EINVAL);
2533 s->bit_rate = avctx->bit_rate;
2534 s->frame_size_code = i << 1;
2536 /* validate cutoff */
2537 if (avctx->cutoff < 0) {
2538 av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2539 return AVERROR(EINVAL);
2541 s->cutoff = avctx->cutoff;
2542 if (s->cutoff > (s->sample_rate >> 1))
2543 s->cutoff = s->sample_rate >> 1;
2545 /* validate audio service type / channels combination */
2546 if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
2547 avctx->channels == 1) ||
2548 ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
2549 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
2550 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
2551 && avctx->channels > 1)) {
2552 av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
2553 "specified number of channels\n");
2554 return AVERROR(EINVAL);
2557 ret = validate_metadata(avctx);
2561 s->rematrixing_enabled = s->options.stereo_rematrixing &&
2562 (s->channel_mode == AC3_CHMODE_STEREO);
2564 s->cpl_enabled = s->options.channel_coupling &&
2565 s->channel_mode >= AC3_CHMODE_STEREO &&
2566 CONFIG_AC3ENC_FLOAT;
2573 * Set bandwidth for all channels.
2574 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2575 * default value will be used.
2577 static av_cold void set_bandwidth(AC3EncodeContext *s)
2580 int av_uninit(cpl_start);
2583 /* calculate bandwidth based on user-specified cutoff frequency */
2585 fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2586 s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2588 /* use default bandwidth setting */
2589 s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2592 /* set number of coefficients for each channel */
2593 for (ch = 1; ch <= s->fbw_channels; ch++) {
2594 s->start_freq[ch] = 0;
2595 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2596 s->blocks[blk].end_freq[ch] = s->bandwidth_code * 3 + 73;
2598 /* LFE channel always has 7 coefs */
2600 s->start_freq[s->lfe_channel] = 0;
2601 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2602 s->blocks[blk].end_freq[ch] = 7;
2605 /* initialize coupling strategy */
2606 if (s->cpl_enabled) {
2607 if (s->options.cpl_start >= 0) {
2608 cpl_start = s->options.cpl_start;
2610 cpl_start = ac3_coupling_start_tab[s->channel_mode-2][s->bit_alloc.sr_code][s->frame_size_code/2];
2615 if (s->cpl_enabled) {
2616 int i, cpl_start_band, cpl_end_band;
2617 uint8_t *cpl_band_sizes = s->cpl_band_sizes;
2619 cpl_end_band = s->bandwidth_code / 4 + 3;
2620 cpl_start_band = av_clip(cpl_start, 0, FFMIN(cpl_end_band-1, 15));
2622 s->num_cpl_subbands = cpl_end_band - cpl_start_band;
2624 s->num_cpl_bands = 1;
2625 *cpl_band_sizes = 12;
2626 for (i = cpl_start_band + 1; i < cpl_end_band; i++) {
2627 if (ff_eac3_default_cpl_band_struct[i]) {
2628 *cpl_band_sizes += 12;
2632 *cpl_band_sizes = 12;
2636 s->start_freq[CPL_CH] = cpl_start_band * 12 + 37;
2637 s->cpl_end_freq = cpl_end_band * 12 + 37;
2638 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2639 s->blocks[blk].end_freq[CPL_CH] = s->cpl_end_freq;
2644 static av_cold int allocate_buffers(AVCodecContext *avctx)
2647 AC3EncodeContext *s = avctx->priv_data;
2648 int channels = s->channels + 1; /* includes coupling channel */
2650 FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
2652 for (ch = 0; ch < s->channels; ch++) {
2653 FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
2654 (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
2657 FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * channels *
2658 AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
2659 FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * channels *
2660 AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
2661 FF_ALLOCZ_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * channels *
2662 AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
2663 FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * channels *
2664 AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
2665 FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * channels *
2666 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
2667 FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * channels *
2668 AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
2669 FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * channels *
2670 64 * sizeof(*s->band_psd_buffer), alloc_fail);
2671 FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * channels *
2672 64 * sizeof(*s->mask_buffer), alloc_fail);
2673 FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * channels *
2674 AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
2675 if (s->cpl_enabled) {
2676 FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_exp_buffer, AC3_MAX_BLOCKS * channels *
2677 16 * sizeof(*s->cpl_coord_exp_buffer), alloc_fail);
2678 FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_mant_buffer, AC3_MAX_BLOCKS * channels *
2679 16 * sizeof(*s->cpl_coord_mant_buffer), alloc_fail);
2681 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2682 AC3Block *block = &s->blocks[blk];
2683 FF_ALLOC_OR_GOTO(avctx, block->bap, channels * sizeof(*block->bap),
2685 FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, channels * sizeof(*block->mdct_coef),
2687 FF_ALLOCZ_OR_GOTO(avctx, block->exp, channels * sizeof(*block->exp),
2689 FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, channels * sizeof(*block->grouped_exp),
2691 FF_ALLOCZ_OR_GOTO(avctx, block->psd, channels * sizeof(*block->psd),
2693 FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, channels * sizeof(*block->band_psd),
2695 FF_ALLOCZ_OR_GOTO(avctx, block->mask, channels * sizeof(*block->mask),
2697 FF_ALLOCZ_OR_GOTO(avctx, block->qmant, channels * sizeof(*block->qmant),
2699 if (s->cpl_enabled) {
2700 FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_exp, channels * sizeof(*block->cpl_coord_exp),
2702 FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_mant, channels * sizeof(*block->cpl_coord_mant),
2706 for (ch = 0; ch < channels; ch++) {
2707 /* arrangement: block, channel, coeff */
2708 block->bap[ch] = &s->bap_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
2709 block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * channels + ch)];
2710 block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
2711 block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * channels + ch)];
2712 block->mask[ch] = &s->mask_buffer [64 * (blk * channels + ch)];
2713 block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
2714 if (s->cpl_enabled) {
2715 block->cpl_coord_exp[ch] = &s->cpl_coord_exp_buffer [16 * (blk * channels + ch)];
2716 block->cpl_coord_mant[ch] = &s->cpl_coord_mant_buffer[16 * (blk * channels + ch)];
2719 /* arrangement: channel, block, coeff */
2720 block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2721 block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2725 if (CONFIG_AC3ENC_FLOAT) {
2726 FF_ALLOCZ_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * channels *
2727 AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
2728 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2729 AC3Block *block = &s->blocks[blk];
2730 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2731 sizeof(*block->fixed_coef), alloc_fail);
2732 for (ch = 0; ch < channels; ch++)
2733 block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2736 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2737 AC3Block *block = &s->blocks[blk];
2738 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2739 sizeof(*block->fixed_coef), alloc_fail);
2740 for (ch = 0; ch < channels; ch++)
2741 block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2747 return AVERROR(ENOMEM);
2752 * Initialize the encoder.
2754 static av_cold int ac3_encode_init(AVCodecContext *avctx)
2756 AC3EncodeContext *s = avctx->priv_data;
2757 int ret, frame_size_58;
2759 avctx->frame_size = AC3_FRAME_SIZE;
2761 ff_ac3_common_init();
2763 ret = validate_options(avctx, s);
2767 s->bitstream_mode = avctx->audio_service_type;
2768 if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2769 s->bitstream_mode = 0x7;
2771 s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2772 s->bits_written = 0;
2773 s->samples_written = 0;
2774 s->frame_size = s->frame_size_min;
2776 /* calculate crc_inv for both possible frame sizes */
2777 frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
2778 s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2779 if (s->bit_alloc.sr_code == 1) {
2780 frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2781 s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2790 ret = mdct_init(avctx, &s->mdct, 9);
2794 ret = allocate_buffers(avctx);
2798 avctx->coded_frame= avcodec_alloc_frame();
2800 dsputil_init(&s->dsp, avctx);
2801 ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2803 dprint_options(avctx);
2807 ac3_encode_close(avctx);