2 * The simplest AC-3 encoder
3 * Copyright (c) 2000 Fabrice Bellard
4 * Copyright (c) 2006-2010 Justin Ruggles <justin.ruggles@gmail.com>
5 * Copyright (c) 2006-2010 Prakash Punnoor <prakash@punnoor.de>
7 * This file is part of FFmpeg.
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 * The simplest AC-3 encoder.
30 //#define ASSERT_LEVEL 2
34 #include "libavutil/audioconvert.h"
35 #include "libavutil/avassert.h"
36 #include "libavutil/avstring.h"
37 #include "libavutil/crc.h"
38 #include "libavutil/opt.h"
44 #include "audioconvert.h"
48 #ifndef CONFIG_AC3ENC_FLOAT
49 #define CONFIG_AC3ENC_FLOAT 0
53 /** Maximum number of exponent groups. +1 for separate DC exponent. */
54 #define AC3_MAX_EXP_GROUPS 85
56 #if CONFIG_AC3ENC_FLOAT
57 #define MAC_COEF(d,a,b) ((d)+=(a)*(b))
58 typedef float SampleType;
59 typedef float CoefType;
60 typedef float CoefSumType;
62 #define MAC_COEF(d,a,b) MAC64(d,a,b)
63 typedef int16_t SampleType;
64 typedef int32_t CoefType;
65 typedef int64_t CoefSumType;
68 typedef struct AC3MDCTContext {
69 const SampleType *window; ///< MDCT window function
70 FFTContext fft; ///< FFT context for MDCT calculation
75 * Data for a single audio block.
77 typedef struct AC3Block {
78 uint8_t **bap; ///< bit allocation pointers (bap)
79 CoefType **mdct_coef; ///< MDCT coefficients
80 int32_t **fixed_coef; ///< fixed-point MDCT coefficients
81 uint8_t **exp; ///< original exponents
82 uint8_t **grouped_exp; ///< grouped exponents
83 int16_t **psd; ///< psd per frequency bin
84 int16_t **band_psd; ///< psd per critical band
85 int16_t **mask; ///< masking curve
86 uint16_t **qmant; ///< quantized mantissas
87 uint8_t **cpl_coord_exp; ///< coupling coord exponents (cplcoexp)
88 uint8_t **cpl_coord_mant; ///< coupling coord mantissas (cplcomant)
89 uint8_t coeff_shift[AC3_MAX_CHANNELS]; ///< fixed-point coefficient shift values
90 uint8_t new_rematrixing_strategy; ///< send new rematrixing flags in this block
91 int num_rematrixing_bands; ///< number of rematrixing bands
92 uint8_t rematrixing_flags[4]; ///< rematrixing flags
93 struct AC3Block *exp_ref_block[AC3_MAX_CHANNELS]; ///< reference blocks for EXP_REUSE
94 int new_cpl_strategy; ///< send new coupling strategy
95 int cpl_in_use; ///< coupling in use for this block (cplinu)
96 uint8_t channel_in_cpl[AC3_MAX_CHANNELS]; ///< channel in coupling (chincpl)
97 int num_cpl_channels; ///< number of channels in coupling
98 uint8_t new_cpl_coords; ///< send new coupling coordinates (cplcoe)
99 uint8_t cpl_master_exp[AC3_MAX_CHANNELS]; ///< coupling coord master exponents (mstrcplco)
100 int new_snr_offsets; ///< send new SNR offsets
101 int new_cpl_leak; ///< send new coupling leak info
102 int end_freq[AC3_MAX_CHANNELS]; ///< end frequency bin (endmant)
106 * AC-3 encoder private context.
108 typedef struct AC3EncodeContext {
109 AVClass *av_class; ///< AVClass used for AVOption
110 AC3EncOptions options; ///< encoding options
111 PutBitContext pb; ///< bitstream writer context
113 AC3DSPContext ac3dsp; ///< AC-3 optimized functions
114 AC3MDCTContext mdct; ///< MDCT context
116 AC3Block blocks[AC3_MAX_BLOCKS]; ///< per-block info
118 int bitstream_id; ///< bitstream id (bsid)
119 int bitstream_mode; ///< bitstream mode (bsmod)
121 int bit_rate; ///< target bit rate, in bits-per-second
122 int sample_rate; ///< sampling frequency, in Hz
124 int frame_size_min; ///< minimum frame size in case rounding is necessary
125 int frame_size; ///< current frame size in bytes
126 int frame_size_code; ///< frame size code (frmsizecod)
128 int bits_written; ///< bit count (used to avg. bitrate)
129 int samples_written; ///< sample count (used to avg. bitrate)
131 int fbw_channels; ///< number of full-bandwidth channels (nfchans)
132 int channels; ///< total number of channels (nchans)
133 int lfe_on; ///< indicates if there is an LFE channel (lfeon)
134 int lfe_channel; ///< channel index of the LFE channel
135 int has_center; ///< indicates if there is a center channel
136 int has_surround; ///< indicates if there are one or more surround channels
137 int channel_mode; ///< channel mode (acmod)
138 const uint8_t *channel_map; ///< channel map used to reorder channels
140 int center_mix_level; ///< center mix level code
141 int surround_mix_level; ///< surround mix level code
142 int ltrt_center_mix_level; ///< Lt/Rt center mix level code
143 int ltrt_surround_mix_level; ///< Lt/Rt surround mix level code
144 int loro_center_mix_level; ///< Lo/Ro center mix level code
145 int loro_surround_mix_level; ///< Lo/Ro surround mix level code
147 int cutoff; ///< user-specified cutoff frequency, in Hz
148 int bandwidth_code; ///< bandwidth code (0 to 60) (chbwcod)
149 int start_freq[AC3_MAX_CHANNELS]; ///< start frequency bin (strtmant)
150 int cpl_end_freq; ///< coupling channel end frequency bin
152 int cpl_on; ///< coupling turned on for this frame
153 int cpl_enabled; ///< coupling enabled for all frames
154 int num_cpl_subbands; ///< number of coupling subbands (ncplsubnd)
155 int num_cpl_bands; ///< number of coupling bands (ncplbnd)
156 uint8_t cpl_band_sizes[AC3_MAX_CPL_BANDS]; ///< number of coeffs in each coupling band
158 int rematrixing_enabled; ///< stereo rematrixing enabled
160 /* bitrate allocation control */
161 int slow_gain_code; ///< slow gain code (sgaincod)
162 int slow_decay_code; ///< slow decay code (sdcycod)
163 int fast_decay_code; ///< fast decay code (fdcycod)
164 int db_per_bit_code; ///< dB/bit code (dbpbcod)
165 int floor_code; ///< floor code (floorcod)
166 AC3BitAllocParameters bit_alloc; ///< bit allocation parameters
167 int coarse_snr_offset; ///< coarse SNR offsets (csnroffst)
168 int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signal-to-mask ratio) (fgaincod)
169 int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst)
170 int frame_bits_fixed; ///< number of non-coefficient bits for fixed parameters
171 int frame_bits; ///< all frame bits except exponents and mantissas
172 int exponent_bits; ///< number of bits used for exponents
174 SampleType **planar_samples;
176 uint8_t *bap1_buffer;
177 CoefType *mdct_coef_buffer;
178 int32_t *fixed_coef_buffer;
180 uint8_t *grouped_exp_buffer;
182 int16_t *band_psd_buffer;
183 int16_t *mask_buffer;
184 uint16_t *qmant_buffer;
185 uint8_t *cpl_coord_exp_buffer;
186 uint8_t *cpl_coord_mant_buffer;
188 uint8_t exp_strategy[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< exponent strategies
190 DECLARE_ALIGNED(32, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
193 typedef struct AC3Mant {
194 uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
195 int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
198 #define CMIXLEV_NUM_OPTIONS 3
199 static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
200 LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
203 #define SURMIXLEV_NUM_OPTIONS 3
204 static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
205 LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
208 #define EXTMIXLEV_NUM_OPTIONS 8
209 static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
210 LEVEL_PLUS_3DB, LEVEL_PLUS_1POINT5DB, LEVEL_ONE, LEVEL_MINUS_4POINT5DB,
211 LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
215 #define OFFSET(param) offsetof(AC3EncodeContext, options.param)
216 #define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
218 #if CONFIG_AC3ENC_FLOAT || !CONFIG_AC3_FLOAT_ENCODER //we need this exactly once compiled in
219 const AVOption ff_ac3_options[] = {
220 /* Metadata Options */
221 {"per_frame_metadata", "Allow Changing Metadata Per-Frame", OFFSET(allow_per_frame_metadata), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 1, AC3ENC_PARAM},
223 {"center_mixlev", "Center Mix Level", OFFSET(center_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = LEVEL_MINUS_4POINT5DB }, 0.0, 1.0, AC3ENC_PARAM},
224 {"surround_mixlev", "Surround Mix Level", OFFSET(surround_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = LEVEL_MINUS_6DB }, 0.0, 1.0, AC3ENC_PARAM},
225 /* audio production information */
226 {"mixing_level", "Mixing Level", OFFSET(mixing_level), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 111, AC3ENC_PARAM},
227 {"room_type", "Room Type", OFFSET(room_type), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "room_type"},
228 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
229 {"large", "Large Room", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
230 {"small", "Small Room", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
231 /* other metadata options */
232 {"copyright", "Copyright Bit", OFFSET(copyright), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 1, AC3ENC_PARAM},
233 {"dialnorm", "Dialogue Level (dB)", OFFSET(dialogue_level), FF_OPT_TYPE_INT, {.dbl = -31 }, -31, -1, AC3ENC_PARAM},
234 {"dsur_mode", "Dolby Surround Mode", OFFSET(dolby_surround_mode), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 2, AC3ENC_PARAM, "dsur_mode"},
235 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
236 {"on", "Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
237 {"off", "Not Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
238 {"original", "Original Bit Stream", OFFSET(original), FF_OPT_TYPE_INT, {.dbl = 1 }, 0, 1, AC3ENC_PARAM},
239 /* extended bitstream information */
240 {"dmix_mode", "Preferred Stereo Downmix Mode", OFFSET(preferred_stereo_downmix), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dmix_mode"},
241 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
242 {"ltrt", "Lt/Rt Downmix Preferred", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
243 {"loro", "Lo/Ro Downmix Preferred", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
244 {"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},
245 {"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},
246 {"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},
247 {"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},
248 {"dsurex_mode", "Dolby Surround EX Mode", OFFSET(dolby_surround_ex_mode), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dsurex_mode"},
249 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
250 {"on", "Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
251 {"off", "Not Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
252 {"dheadphone_mode", "Dolby Headphone Mode", OFFSET(dolby_headphone_mode), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dheadphone_mode"},
253 {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
254 {"on", "Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
255 {"off", "Not Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
256 {"ad_conv_type", "A/D Converter Type", OFFSET(ad_converter_type), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 1, AC3ENC_PARAM, "ad_conv_type"},
257 {"standard", "Standard (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
258 {"hdcd", "HDCD", 0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
259 /* Other Encoding Options */
260 {"stereo_rematrixing", "Stereo Rematrixing", OFFSET(stereo_rematrixing), FF_OPT_TYPE_INT, {.dbl = 1 }, 0, 1, AC3ENC_PARAM},
261 #if CONFIG_AC3ENC_FLOAT
262 {"channel_coupling", "Channel Coupling", OFFSET(channel_coupling), FF_OPT_TYPE_INT, {.dbl = 1 }, 0, 1, AC3ENC_PARAM, "channel_coupling"},
263 {"auto", "Selected by the Encoder", 0, FF_OPT_TYPE_CONST, {.dbl = -1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "channel_coupling"},
264 {"cpl_start_band", "Coupling Start Band", OFFSET(cpl_start), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 15, AC3ENC_PARAM, "cpl_start_band"},
265 {"auto", "Selected by the Encoder", 0, FF_OPT_TYPE_CONST, {.dbl = -1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "cpl_start_band"},
271 #if CONFIG_AC3ENC_FLOAT
272 static AVClass ac3enc_class = { "AC-3 Encoder", av_default_item_name,
273 ff_ac3_options, LIBAVUTIL_VERSION_INT };
275 static AVClass ac3enc_class = { "Fixed-Point AC-3 Encoder", av_default_item_name,
276 ff_ac3_options, LIBAVUTIL_VERSION_INT };
280 /* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
282 static av_cold void mdct_end(AC3MDCTContext *mdct);
284 static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
287 static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
288 const SampleType *window, unsigned int len);
290 static int normalize_samples(AC3EncodeContext *s);
292 static void scale_coefficients(AC3EncodeContext *s);
296 * LUT for number of exponent groups.
297 * exponent_group_tab[coupling][exponent strategy-1][number of coefficients]
299 static uint8_t exponent_group_tab[2][3][256];
303 * List of supported channel layouts.
305 #if CONFIG_AC3ENC_FLOAT || !CONFIG_AC3_FLOAT_ENCODER //we need this exactly once compiled in
306 const int64_t ff_ac3_channel_layouts[] = {
310 AV_CH_LAYOUT_SURROUND,
313 AV_CH_LAYOUT_4POINT0,
314 AV_CH_LAYOUT_5POINT0,
315 AV_CH_LAYOUT_5POINT0_BACK,
316 (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
317 (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
318 (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
319 (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
320 (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
321 (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
322 (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
323 AV_CH_LAYOUT_5POINT1,
324 AV_CH_LAYOUT_5POINT1_BACK,
331 * LUT to select the bandwidth code based on the bit rate, sample rate, and
332 * number of full-bandwidth channels.
333 * bandwidth_tab[fbw_channels-1][sample rate code][bit rate code]
335 static const uint8_t ac3_bandwidth_tab[5][3][19] = {
336 // 32 40 48 56 64 80 96 112 128 160 192 224 256 320 384 448 512 576 640
338 { { 0, 0, 0, 12, 16, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
339 { 0, 0, 0, 16, 20, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
340 { 0, 0, 0, 32, 40, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
342 { { 0, 0, 0, 0, 0, 0, 0, 20, 24, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
343 { 0, 0, 0, 0, 0, 0, 4, 24, 28, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
344 { 0, 0, 0, 0, 0, 0, 20, 44, 52, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
346 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 24, 32, 40, 48, 48, 48, 48, 48, 48 },
347 { 0, 0, 0, 0, 0, 0, 0, 0, 4, 20, 28, 36, 44, 56, 56, 56, 56, 56, 56 },
348 { 0, 0, 0, 0, 0, 0, 0, 0, 20, 40, 48, 60, 60, 60, 60, 60, 60, 60, 60 } },
350 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 32, 48, 48, 48, 48, 48, 48 },
351 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 28, 36, 56, 56, 56, 56, 56, 56 },
352 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 48, 60, 60, 60, 60, 60, 60, 60 } },
354 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 20, 32, 40, 48, 48, 48, 48 },
355 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 36, 44, 56, 56, 56, 56 },
356 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 44, 60, 60, 60, 60, 60, 60 } }
361 * LUT to select the coupling start band based on the bit rate, sample rate, and
362 * number of full-bandwidth channels. -1 = coupling off
363 * ac3_coupling_start_tab[channel_mode-2][sample rate code][bit rate code]
365 * TODO: more testing for optimal parameters.
366 * multi-channel tests at 44.1kHz and 32kHz.
368 static const int8_t ac3_coupling_start_tab[6][3][19] = {
369 // 32 40 48 56 64 80 96 112 128 160 192 224 256 320 384 448 512 576 640
372 { { 0, 0, 0, 0, 0, 0, 0, 1, 1, 7, 8, 11, 12, -1, -1, -1, -1, -1, -1 },
373 { 0, 0, 0, 0, 0, 0, 1, 3, 5, 7, 10, 12, 13, -1, -1, -1, -1, -1, -1 },
374 { 0, 0, 0, 0, 1, 2, 2, 9, 13, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
377 { { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
378 { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
379 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
382 { { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
383 { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
384 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
387 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
388 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
389 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
392 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
393 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
394 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
397 { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 8, 11, 12, 12, -1, -1 },
398 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 8, 11, 12, 12, -1, -1 },
399 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
404 * Adjust the frame size to make the average bit rate match the target bit rate.
405 * This is only needed for 11025, 22050, and 44100 sample rates.
407 static void adjust_frame_size(AC3EncodeContext *s)
409 while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
410 s->bits_written -= s->bit_rate;
411 s->samples_written -= s->sample_rate;
413 s->frame_size = s->frame_size_min +
414 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
415 s->bits_written += s->frame_size * 8;
416 s->samples_written += AC3_FRAME_SIZE;
421 * Deinterleave input samples.
422 * Channels are reordered from FFmpeg's default order to AC-3 order.
424 static void deinterleave_input_samples(AC3EncodeContext *s,
425 const SampleType *samples)
429 /* deinterleave and remap input samples */
430 for (ch = 0; ch < s->channels; ch++) {
431 const SampleType *sptr;
434 /* copy last 256 samples of previous frame to the start of the current frame */
435 memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
436 AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
440 sptr = samples + s->channel_map[ch];
441 for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
442 s->planar_samples[ch][i] = *sptr;
450 * Apply the MDCT to input samples to generate frequency coefficients.
451 * This applies the KBD window and normalizes the input to reduce precision
452 * loss due to fixed-point calculations.
454 static void apply_mdct(AC3EncodeContext *s)
458 for (ch = 0; ch < s->channels; ch++) {
459 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
460 AC3Block *block = &s->blocks[blk];
461 const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
463 apply_window(&s->dsp, s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
465 block->coeff_shift[ch+1] = normalize_samples(s);
467 s->mdct.fft.mdct_calcw(&s->mdct.fft, block->mdct_coef[ch+1],
468 s->windowed_samples);
474 static void compute_coupling_strategy(AC3EncodeContext *s)
479 /* set coupling use flags for each block/channel */
480 /* TODO: turn coupling on/off and adjust start band based on bit usage */
481 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
482 AC3Block *block = &s->blocks[blk];
483 for (ch = 1; ch <= s->fbw_channels; ch++)
484 block->channel_in_cpl[ch] = s->cpl_on;
487 /* enable coupling for each block if at least 2 channels have coupling
488 enabled for that block */
490 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
491 AC3Block *block = &s->blocks[blk];
492 block->num_cpl_channels = 0;
493 for (ch = 1; ch <= s->fbw_channels; ch++)
494 block->num_cpl_channels += block->channel_in_cpl[ch];
495 block->cpl_in_use = block->num_cpl_channels > 1;
496 if (!block->cpl_in_use) {
497 block->num_cpl_channels = 0;
498 for (ch = 1; ch <= s->fbw_channels; ch++)
499 block->channel_in_cpl[ch] = 0;
502 block->new_cpl_strategy = !blk;
504 for (ch = 1; ch <= s->fbw_channels; ch++) {
505 if (block->channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]) {
506 block->new_cpl_strategy = 1;
511 block->new_cpl_leak = block->new_cpl_strategy;
513 if (!blk || (block->cpl_in_use && !got_cpl_snr)) {
514 block->new_snr_offsets = 1;
515 if (block->cpl_in_use)
518 block->new_snr_offsets = 0;
522 /* set bandwidth for each channel */
523 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
524 AC3Block *block = &s->blocks[blk];
525 for (ch = 1; ch <= s->fbw_channels; ch++) {
526 if (block->channel_in_cpl[ch])
527 block->end_freq[ch] = s->start_freq[CPL_CH];
529 block->end_freq[ch] = s->bandwidth_code * 3 + 73;
536 * Calculate a single coupling coordinate.
538 static inline float calc_cpl_coord(float energy_ch, float energy_cpl)
542 coord *= sqrtf(energy_ch / energy_cpl);
548 * Calculate coupling channel and coupling coordinates.
549 * TODO: Currently this is only used for the floating-point encoder. I was
550 * able to make it work for the fixed-point encoder, but quality was
551 * generally lower in most cases than not using coupling. If a more
552 * adaptive coupling strategy were to be implemented it might be useful
553 * at that time to use coupling for the fixed-point encoder as well.
555 static void apply_channel_coupling(AC3EncodeContext *s)
557 #if CONFIG_AC3ENC_FLOAT
558 DECLARE_ALIGNED(16, float, cpl_coords) [AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][16] = {{{0}}};
559 DECLARE_ALIGNED(16, int32_t, fixed_cpl_coords)[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][16] = {{{0}}};
560 int blk, ch, bnd, i, j;
561 CoefSumType energy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][16] = {{{0}}};
562 int num_cpl_coefs = s->num_cpl_subbands * 12;
564 /* calculate coupling channel from fbw channels */
565 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
566 AC3Block *block = &s->blocks[blk];
567 CoefType *cpl_coef = &block->mdct_coef[CPL_CH][s->start_freq[CPL_CH]];
568 if (!block->cpl_in_use)
570 memset(cpl_coef-1, 0, (num_cpl_coefs+4) * sizeof(*cpl_coef));
571 for (ch = 1; ch <= s->fbw_channels; ch++) {
572 CoefType *ch_coef = &block->mdct_coef[ch][s->start_freq[CPL_CH]];
573 if (!block->channel_in_cpl[ch])
575 for (i = 0; i < num_cpl_coefs; i++)
576 cpl_coef[i] += ch_coef[i];
578 /* note: coupling start bin % 4 will always be 1 and num_cpl_coefs
579 will always be a multiple of 12, so we need to subtract 1 from
580 the start and add 4 to the length when using optimized
581 functions which require 16-byte alignment. */
583 /* coefficients must be clipped to +/- 1.0 in order to be encoded */
584 s->dsp.vector_clipf(cpl_coef-1, cpl_coef-1, -1.0f, 1.0f, num_cpl_coefs+4);
586 /* scale coupling coefficients from float to 24-bit fixed-point */
587 s->ac3dsp.float_to_fixed24(&block->fixed_coef[CPL_CH][s->start_freq[CPL_CH]-1],
588 cpl_coef-1, num_cpl_coefs+4);
591 /* calculate energy in each band in coupling channel and each fbw channel */
592 /* TODO: possibly use SIMD to speed up energy calculation */
594 i = s->start_freq[CPL_CH];
595 while (i < s->cpl_end_freq) {
596 int band_size = s->cpl_band_sizes[bnd];
597 for (ch = CPL_CH; ch <= s->fbw_channels; ch++) {
598 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
599 AC3Block *block = &s->blocks[blk];
600 if (!block->cpl_in_use || (ch > CPL_CH && !block->channel_in_cpl[ch]))
602 for (j = 0; j < band_size; j++) {
603 CoefType v = block->mdct_coef[ch][i+j];
604 MAC_COEF(energy[blk][ch][bnd], v, v);
612 /* determine which blocks to send new coupling coordinates for */
613 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
614 AC3Block *block = &s->blocks[blk];
615 AC3Block *block0 = blk ? &s->blocks[blk-1] : NULL;
617 CoefSumType coord_diff[AC3_MAX_CHANNELS] = {0,};
619 if (block->cpl_in_use) {
620 /* calculate coupling coordinates for all blocks and calculate the
621 average difference between coordinates in successive blocks */
622 for (ch = 1; ch <= s->fbw_channels; ch++) {
623 if (!block->channel_in_cpl[ch])
626 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
627 cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy[blk][ch][bnd],
628 energy[blk][CPL_CH][bnd]);
629 if (blk > 0 && block0->cpl_in_use &&
630 block0->channel_in_cpl[ch]) {
631 coord_diff[ch] += fabs(cpl_coords[blk-1][ch][bnd] -
632 cpl_coords[blk ][ch][bnd]);
635 coord_diff[ch] /= s->num_cpl_bands;
638 /* send new coordinates if this is the first block, if previous
639 * block did not use coupling but this block does, the channels
640 * using coupling has changed from the previous block, or the
641 * coordinate difference from the last block for any channel is
642 * greater than a threshold value. */
645 } else if (!block0->cpl_in_use) {
648 for (ch = 1; ch <= s->fbw_channels; ch++) {
649 if (block->channel_in_cpl[ch] && !block0->channel_in_cpl[ch]) {
655 for (ch = 1; ch <= s->fbw_channels; ch++) {
656 if (block->channel_in_cpl[ch] && coord_diff[ch] > 0.04) {
664 block->new_cpl_coords = new_coords;
667 /* calculate final coupling coordinates, taking into account reusing of
668 coordinates in successive blocks */
669 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
671 while (blk < AC3_MAX_BLOCKS) {
673 CoefSumType energy_cpl;
674 AC3Block *block = &s->blocks[blk];
676 if (!block->cpl_in_use) {
681 energy_cpl = energy[blk][CPL_CH][bnd];
683 while (!s->blocks[blk1].new_cpl_coords && blk1 < AC3_MAX_BLOCKS) {
684 if (s->blocks[blk1].cpl_in_use)
685 energy_cpl += energy[blk1][CPL_CH][bnd];
689 for (ch = 1; ch <= s->fbw_channels; ch++) {
691 if (!block->channel_in_cpl[ch])
693 energy_ch = energy[blk][ch][bnd];
695 while (!s->blocks[blk1].new_cpl_coords && blk1 < AC3_MAX_BLOCKS) {
696 if (s->blocks[blk1].cpl_in_use)
697 energy_ch += energy[blk1][ch][bnd];
700 cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy_ch, energy_cpl);
706 /* calculate exponents/mantissas for coupling coordinates */
707 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
708 AC3Block *block = &s->blocks[blk];
709 if (!block->cpl_in_use || !block->new_cpl_coords)
712 s->ac3dsp.float_to_fixed24(fixed_cpl_coords[blk][1],
714 s->fbw_channels * 16);
715 s->ac3dsp.extract_exponents(block->cpl_coord_exp[1],
716 fixed_cpl_coords[blk][1],
717 s->fbw_channels * 16);
719 for (ch = 1; ch <= s->fbw_channels; ch++) {
720 int bnd, min_exp, max_exp, master_exp;
722 /* determine master exponent */
723 min_exp = max_exp = block->cpl_coord_exp[ch][0];
724 for (bnd = 1; bnd < s->num_cpl_bands; bnd++) {
725 int exp = block->cpl_coord_exp[ch][bnd];
726 min_exp = FFMIN(exp, min_exp);
727 max_exp = FFMAX(exp, max_exp);
729 master_exp = ((max_exp - 15) + 2) / 3;
730 master_exp = FFMAX(master_exp, 0);
731 while (min_exp < master_exp * 3)
733 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
734 block->cpl_coord_exp[ch][bnd] = av_clip(block->cpl_coord_exp[ch][bnd] -
735 master_exp * 3, 0, 15);
737 block->cpl_master_exp[ch] = master_exp;
739 /* quantize mantissas */
740 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
741 int cpl_exp = block->cpl_coord_exp[ch][bnd];
742 int cpl_mant = (fixed_cpl_coords[blk][ch][bnd] << (5 + cpl_exp + master_exp * 3)) >> 24;
748 block->cpl_coord_mant[ch][bnd] = cpl_mant;
752 #endif /* CONFIG_AC3ENC_FLOAT */
757 * Determine rematrixing flags for each block and band.
759 static void compute_rematrixing_strategy(AC3EncodeContext *s)
763 AC3Block *block, *block0;
765 if (s->channel_mode != AC3_CHMODE_STEREO)
768 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
769 block = &s->blocks[blk];
770 block->new_rematrixing_strategy = !blk;
772 if (!s->rematrixing_enabled) {
777 block->num_rematrixing_bands = 4;
778 if (block->cpl_in_use) {
779 block->num_rematrixing_bands -= (s->start_freq[CPL_CH] <= 61);
780 block->num_rematrixing_bands -= (s->start_freq[CPL_CH] == 37);
781 if (blk && block->num_rematrixing_bands != block0->num_rematrixing_bands)
782 block->new_rematrixing_strategy = 1;
784 nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
786 for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {
787 /* calculate calculate sum of squared coeffs for one band in one block */
788 int start = ff_ac3_rematrix_band_tab[bnd];
789 int end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
790 CoefSumType sum[4] = {0,};
791 for (i = start; i < end; i++) {
792 CoefType lt = block->mdct_coef[1][i];
793 CoefType rt = block->mdct_coef[2][i];
794 CoefType md = lt + rt;
795 CoefType sd = lt - rt;
796 MAC_COEF(sum[0], lt, lt);
797 MAC_COEF(sum[1], rt, rt);
798 MAC_COEF(sum[2], md, md);
799 MAC_COEF(sum[3], sd, sd);
802 /* compare sums to determine if rematrixing will be used for this band */
803 if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
804 block->rematrixing_flags[bnd] = 1;
806 block->rematrixing_flags[bnd] = 0;
808 /* determine if new rematrixing flags will be sent */
810 block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
811 block->new_rematrixing_strategy = 1;
820 * Apply stereo rematrixing to coefficients based on rematrixing flags.
822 static void apply_rematrixing(AC3EncodeContext *s)
829 if (!s->rematrixing_enabled)
832 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
833 AC3Block *block = &s->blocks[blk];
834 if (block->new_rematrixing_strategy)
835 flags = block->rematrixing_flags;
836 nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
837 for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {
839 start = ff_ac3_rematrix_band_tab[bnd];
840 end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
841 for (i = start; i < end; i++) {
842 int32_t lt = block->fixed_coef[1][i];
843 int32_t rt = block->fixed_coef[2][i];
844 block->fixed_coef[1][i] = (lt + rt) >> 1;
845 block->fixed_coef[2][i] = (lt - rt) >> 1;
854 * Initialize exponent tables.
856 static av_cold void exponent_init(AC3EncodeContext *s)
858 int expstr, i, grpsize;
860 for (expstr = EXP_D15-1; expstr <= EXP_D45-1; expstr++) {
861 grpsize = 3 << expstr;
862 for (i = 12; i < 256; i++) {
863 exponent_group_tab[0][expstr][i] = (i + grpsize - 4) / grpsize;
864 exponent_group_tab[1][expstr][i] = (i ) / grpsize;
868 exponent_group_tab[0][0][7] = 2;
873 * Extract exponents from the MDCT coefficients.
874 * This takes into account the normalization that was done to the input samples
875 * by adjusting the exponents by the exponent shift values.
877 static void extract_exponents(AC3EncodeContext *s)
881 for (ch = !s->cpl_on; ch <= s->channels; ch++) {
882 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
883 AC3Block *block = &s->blocks[blk];
884 s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch],
892 * Exponent Difference Threshold.
893 * New exponents are sent if their SAD exceed this number.
895 #define EXP_DIFF_THRESHOLD 500
899 * Calculate exponent strategies for all channels.
900 * Array arrangement is reversed to simplify the per-channel calculation.
902 static void compute_exp_strategy(AC3EncodeContext *s)
906 for (ch = !s->cpl_on; ch <= s->fbw_channels; ch++) {
907 uint8_t *exp_strategy = s->exp_strategy[ch];
908 uint8_t *exp = s->blocks[0].exp[ch];
911 /* estimate if the exponent variation & decide if they should be
912 reused in the next frame */
913 exp_strategy[0] = EXP_NEW;
914 exp += AC3_MAX_COEFS;
915 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++, exp += AC3_MAX_COEFS) {
916 if ((ch == CPL_CH && (!s->blocks[blk].cpl_in_use || !s->blocks[blk-1].cpl_in_use)) ||
917 (ch > CPL_CH && (s->blocks[blk].channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]))) {
918 exp_strategy[blk] = EXP_NEW;
921 exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
922 exp_strategy[blk] = EXP_REUSE;
923 if (ch == CPL_CH && exp_diff > (EXP_DIFF_THRESHOLD * (s->blocks[blk].end_freq[ch] - s->start_freq[ch]) / AC3_MAX_COEFS))
924 exp_strategy[blk] = EXP_NEW;
925 else if (ch > CPL_CH && exp_diff > EXP_DIFF_THRESHOLD)
926 exp_strategy[blk] = EXP_NEW;
929 /* now select the encoding strategy type : if exponents are often
930 recoded, we use a coarse encoding */
932 while (blk < AC3_MAX_BLOCKS) {
934 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
936 switch (blk1 - blk) {
937 case 1: exp_strategy[blk] = EXP_D45; break;
939 case 3: exp_strategy[blk] = EXP_D25; break;
940 default: exp_strategy[blk] = EXP_D15; break;
947 s->exp_strategy[ch][0] = EXP_D15;
948 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
949 s->exp_strategy[ch][blk] = EXP_REUSE;
955 * Update the exponents so that they are the ones the decoder will decode.
957 static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy,
962 nb_groups = exponent_group_tab[cpl][exp_strategy-1][nb_exps] * 3;
964 /* for each group, compute the minimum exponent */
965 switch(exp_strategy) {
967 for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
968 uint8_t exp_min = exp[k];
969 if (exp[k+1] < exp_min)
971 exp[i-cpl] = exp_min;
976 for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
977 uint8_t exp_min = exp[k];
978 if (exp[k+1] < exp_min)
980 if (exp[k+2] < exp_min)
982 if (exp[k+3] < exp_min)
984 exp[i-cpl] = exp_min;
990 /* constraint for DC exponent */
991 if (!cpl && exp[0] > 15)
994 /* decrease the delta between each groups to within 2 so that they can be
995 differentially encoded */
996 for (i = 1; i <= nb_groups; i++)
997 exp[i] = FFMIN(exp[i], exp[i-1] + 2);
1000 exp[i] = FFMIN(exp[i], exp[i+1] + 2);
1003 exp[-1] = exp[0] & ~1;
1005 /* now we have the exponent values the decoder will see */
1006 switch (exp_strategy) {
1008 for (i = nb_groups, k = (nb_groups * 2)-cpl; i > 0; i--) {
1009 uint8_t exp1 = exp[i-cpl];
1015 for (i = nb_groups, k = (nb_groups * 4)-cpl; i > 0; i--) {
1016 exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i-cpl];
1025 * Encode exponents from original extracted form to what the decoder will see.
1026 * This copies and groups exponents based on exponent strategy and reduces
1027 * deltas between adjacent exponent groups so that they can be differentially
1030 static void encode_exponents(AC3EncodeContext *s)
1032 int blk, blk1, ch, cpl;
1033 uint8_t *exp, *exp_strategy;
1034 int nb_coefs, num_reuse_blocks;
1036 for (ch = !s->cpl_on; ch <= s->channels; ch++) {
1037 exp = s->blocks[0].exp[ch] + s->start_freq[ch];
1038 exp_strategy = s->exp_strategy[ch];
1040 cpl = (ch == CPL_CH);
1042 while (blk < AC3_MAX_BLOCKS) {
1043 AC3Block *block = &s->blocks[blk];
1044 if (cpl && !block->cpl_in_use) {
1045 exp += AC3_MAX_COEFS;
1049 nb_coefs = block->end_freq[ch] - s->start_freq[ch];
1052 /* count the number of EXP_REUSE blocks after the current block
1053 and set exponent reference block pointers */
1054 block->exp_ref_block[ch] = block;
1055 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
1056 s->blocks[blk1].exp_ref_block[ch] = block;
1059 num_reuse_blocks = blk1 - blk - 1;
1061 /* for the EXP_REUSE case we select the min of the exponents */
1062 s->ac3dsp.ac3_exponent_min(exp-s->start_freq[ch], num_reuse_blocks,
1065 encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk], cpl);
1067 exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
1076 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
1077 * varies depending on exponent strategy and bandwidth.
1079 static void group_exponents(AC3EncodeContext *s)
1081 int blk, ch, i, cpl;
1082 int group_size, nb_groups, bit_count;
1084 int delta0, delta1, delta2;
1088 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1089 AC3Block *block = &s->blocks[blk];
1090 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1091 int exp_strategy = s->exp_strategy[ch][blk];
1092 if (exp_strategy == EXP_REUSE)
1094 cpl = (ch == CPL_CH);
1095 group_size = exp_strategy + (exp_strategy == EXP_D45);
1096 nb_groups = exponent_group_tab[cpl][exp_strategy-1][block->end_freq[ch]-s->start_freq[ch]];
1097 bit_count += 4 + (nb_groups * 7);
1098 p = block->exp[ch] + s->start_freq[ch] - cpl;
1102 block->grouped_exp[ch][0] = exp1;
1104 /* remaining exponents are delta encoded */
1105 for (i = 1; i <= nb_groups; i++) {
1106 /* merge three delta in one code */
1110 delta0 = exp1 - exp0 + 2;
1111 av_assert2(delta0 >= 0 && delta0 <= 4);
1116 delta1 = exp1 - exp0 + 2;
1117 av_assert2(delta1 >= 0 && delta1 <= 4);
1122 delta2 = exp1 - exp0 + 2;
1123 av_assert2(delta2 >= 0 && delta2 <= 4);
1125 block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
1130 s->exponent_bits = bit_count;
1135 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
1136 * Extract exponents from MDCT coefficients, calculate exponent strategies,
1137 * and encode final exponents.
1139 static void process_exponents(AC3EncodeContext *s)
1141 extract_exponents(s);
1143 compute_exp_strategy(s);
1145 encode_exponents(s);
1154 * Count frame bits that are based solely on fixed parameters.
1155 * This only has to be run once when the encoder is initialized.
1157 static void count_frame_bits_fixed(AC3EncodeContext *s)
1159 static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
1164 * no dynamic range codes
1165 * bit allocation parameters do not change between blocks
1166 * no delta bit allocation
1168 * no auxilliary data
1173 frame_bits += frame_bits_inc[s->channel_mode];
1176 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1177 /* block switch flags */
1178 frame_bits += s->fbw_channels;
1181 frame_bits += s->fbw_channels;
1186 /* exponent strategy */
1187 frame_bits += 2 * s->fbw_channels;
1191 /* bit allocation params */
1194 frame_bits += 2 + 2 + 2 + 2 + 3;
1196 /* delta bit allocation */
1203 /* auxiliary data */
1207 frame_bits += 1 + 16;
1209 s->frame_bits_fixed = frame_bits;
1214 * Initialize bit allocation.
1215 * Set default parameter codes and calculate parameter values.
1217 static void bit_alloc_init(AC3EncodeContext *s)
1221 /* init default parameters */
1222 s->slow_decay_code = 2;
1223 s->fast_decay_code = 1;
1224 s->slow_gain_code = 1;
1225 s->db_per_bit_code = 3;
1227 for (ch = 0; ch <= s->channels; ch++)
1228 s->fast_gain_code[ch] = 4;
1230 /* initial snr offset */
1231 s->coarse_snr_offset = 40;
1233 /* compute real values */
1234 /* currently none of these values change during encoding, so we can just
1235 set them once at initialization */
1236 s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
1237 s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
1238 s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
1239 s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
1240 s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
1241 s->bit_alloc.cpl_fast_leak = 0;
1242 s->bit_alloc.cpl_slow_leak = 0;
1244 count_frame_bits_fixed(s);
1249 * Count the bits used to encode the frame, minus exponents and mantissas.
1250 * Bits based on fixed parameters have already been counted, so now we just
1251 * have to add the bits based on parameters that change during encoding.
1253 static void count_frame_bits(AC3EncodeContext *s)
1255 AC3EncOptions *opt = &s->options;
1260 if (opt->audio_production_info)
1262 if (s->bitstream_id == 6) {
1263 if (opt->extended_bsi_1)
1265 if (opt->extended_bsi_2)
1270 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1271 AC3Block *block = &s->blocks[blk];
1273 /* coupling strategy */
1275 if (block->new_cpl_strategy) {
1277 if (block->cpl_in_use) {
1278 frame_bits += s->fbw_channels;
1279 if (s->channel_mode == AC3_CHMODE_STEREO)
1281 frame_bits += 4 + 4;
1282 frame_bits += s->num_cpl_subbands - 1;
1286 /* coupling coordinates */
1287 if (block->cpl_in_use) {
1288 for (ch = 1; ch <= s->fbw_channels; ch++) {
1289 if (block->channel_in_cpl[ch]) {
1291 if (block->new_cpl_coords) {
1293 frame_bits += (4 + 4) * s->num_cpl_bands;
1299 /* stereo rematrixing */
1300 if (s->channel_mode == AC3_CHMODE_STEREO) {
1302 if (s->blocks[blk].new_rematrixing_strategy)
1303 frame_bits += block->num_rematrixing_bands;
1306 /* bandwidth codes & gain range */
1307 for (ch = 1; ch <= s->fbw_channels; ch++) {
1308 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1309 if (!block->channel_in_cpl[ch])
1315 /* coupling exponent strategy */
1316 if (block->cpl_in_use)
1319 /* snr offsets and fast gain codes */
1321 if (block->new_snr_offsets)
1322 frame_bits += 6 + (s->channels + block->cpl_in_use) * (4 + 3);
1324 /* coupling leak info */
1325 if (block->cpl_in_use) {
1327 if (block->new_cpl_leak)
1328 frame_bits += 3 + 3;
1332 s->frame_bits = s->frame_bits_fixed + frame_bits;
1337 * Finalize the mantissa bit count by adding in the grouped mantissas.
1339 static int compute_mantissa_size_final(int mant_cnt[5])
1341 // bap=1 : 3 mantissas in 5 bits
1342 int bits = (mant_cnt[1] / 3) * 5;
1343 // bap=2 : 3 mantissas in 7 bits
1344 // bap=4 : 2 mantissas in 7 bits
1345 bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
1346 // bap=3 : each mantissa is 3 bits
1347 bits += mant_cnt[3] * 3;
1353 * Calculate masking curve based on the final exponents.
1354 * Also calculate the power spectral densities to use in future calculations.
1356 static void bit_alloc_masking(AC3EncodeContext *s)
1360 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1361 AC3Block *block = &s->blocks[blk];
1362 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1363 /* We only need psd and mask for calculating bap.
1364 Since we currently do not calculate bap when exponent
1365 strategy is EXP_REUSE we do not need to calculate psd or mask. */
1366 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1367 ff_ac3_bit_alloc_calc_psd(block->exp[ch], s->start_freq[ch],
1368 block->end_freq[ch], block->psd[ch],
1369 block->band_psd[ch]);
1370 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
1371 s->start_freq[ch], block->end_freq[ch],
1372 ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
1373 ch == s->lfe_channel,
1374 DBA_NONE, 0, NULL, NULL, NULL,
1383 * Ensure that bap for each block and channel point to the current bap_buffer.
1384 * They may have been switched during the bit allocation search.
1386 static void reset_block_bap(AC3EncodeContext *s)
1389 int channels = s->channels + 1;
1390 if (s->blocks[0].bap[0] == s->bap_buffer)
1392 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1393 for (ch = 0; ch < channels; ch++) {
1394 s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * channels + ch)];
1401 * Run the bit allocation with a given SNR offset.
1402 * This calculates the bit allocation pointers that will be used to determine
1403 * the quantization of each mantissa.
1404 * @return the number of bits needed for mantissas if the given SNR offset is
1407 static int bit_alloc(AC3EncodeContext *s, int snr_offset)
1413 snr_offset = (snr_offset - 240) << 2;
1417 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1418 AC3Block *block = &s->blocks[blk];
1419 AC3Block *ref_block;
1421 int got_cpl = !block->cpl_in_use;
1422 // initialize grouped mantissa counts. these are set so that they are
1423 // padded to the next whole group size when bits are counted in
1424 // compute_mantissa_size_final
1425 mant_cnt[0] = mant_cnt[3] = 0;
1426 mant_cnt[1] = mant_cnt[2] = 2;
1428 for (ch = 1; ch <= s->channels; ch++) {
1429 if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1435 /* Currently the only bit allocation parameters which vary across
1436 blocks within a frame are the exponent values. We can take
1437 advantage of that by reusing the bit allocation pointers
1438 whenever we reuse exponents. */
1439 ref_block = block->exp_ref_block[ch];
1440 if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1441 s->ac3dsp.bit_alloc_calc_bap(ref_block->mask[ch], ref_block->psd[ch],
1442 s->start_freq[ch], block->end_freq[ch],
1443 snr_offset, s->bit_alloc.floor,
1444 ff_ac3_bap_tab, ref_block->bap[ch]);
1446 mantissa_bits += s->ac3dsp.compute_mantissa_size(mant_cnt,
1447 ref_block->bap[ch]+s->start_freq[ch],
1448 block->end_freq[ch]-s->start_freq[ch]);
1452 mantissa_bits += compute_mantissa_size_final(mant_cnt);
1454 return mantissa_bits;
1459 * Constant bitrate bit allocation search.
1460 * Find the largest SNR offset that will allow data to fit in the frame.
1462 static int cbr_bit_allocation(AC3EncodeContext *s)
1466 int snr_offset, snr_incr;
1468 bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1470 return AVERROR(EINVAL);
1472 snr_offset = s->coarse_snr_offset << 4;
1474 /* if previous frame SNR offset was 1023, check if current frame can also
1475 use SNR offset of 1023. if so, skip the search. */
1476 if ((snr_offset | s->fine_snr_offset[1]) == 1023) {
1477 if (bit_alloc(s, 1023) <= bits_left)
1481 while (snr_offset >= 0 &&
1482 bit_alloc(s, snr_offset) > bits_left) {
1486 return AVERROR(EINVAL);
1488 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1489 for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1490 while (snr_offset + snr_incr <= 1023 &&
1491 bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1492 snr_offset += snr_incr;
1493 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1496 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1499 s->coarse_snr_offset = snr_offset >> 4;
1500 for (ch = !s->cpl_on; ch <= s->channels; ch++)
1501 s->fine_snr_offset[ch] = snr_offset & 0xF;
1508 * Downgrade exponent strategies to reduce the bits used by the exponents.
1509 * This is a fallback for when bit allocation fails with the normal exponent
1510 * strategies. Each time this function is run it only downgrades the
1511 * strategy in 1 channel of 1 block.
1512 * @return non-zero if downgrade was unsuccessful
1514 static int downgrade_exponents(AC3EncodeContext *s)
1518 for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1519 for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
1520 if (s->exp_strategy[ch][blk] == EXP_D15) {
1521 s->exp_strategy[ch][blk] = EXP_D25;
1526 for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1527 for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
1528 if (s->exp_strategy[ch][blk] == EXP_D25) {
1529 s->exp_strategy[ch][blk] = EXP_D45;
1534 /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
1535 the block number > 0 */
1536 for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
1537 for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
1538 if (s->exp_strategy[ch][blk] > EXP_REUSE) {
1539 s->exp_strategy[ch][blk] = EXP_REUSE;
1549 * Perform bit allocation search.
1550 * Finds the SNR offset value that maximizes quality and fits in the specified
1551 * frame size. Output is the SNR offset and a set of bit allocation pointers
1552 * used to quantize the mantissas.
1554 static int compute_bit_allocation(AC3EncodeContext *s)
1558 count_frame_bits(s);
1560 bit_alloc_masking(s);
1562 ret = cbr_bit_allocation(s);
1564 /* fallback 1: disable channel coupling */
1567 compute_coupling_strategy(s);
1568 compute_rematrixing_strategy(s);
1569 apply_rematrixing(s);
1570 process_exponents(s);
1571 ret = compute_bit_allocation(s);
1575 /* fallback 2: downgrade exponents */
1576 if (!downgrade_exponents(s)) {
1577 extract_exponents(s);
1578 encode_exponents(s);
1580 ret = compute_bit_allocation(s);
1584 /* fallbacks were not enough... */
1593 * Symmetric quantization on 'levels' levels.
1595 static inline int sym_quant(int c, int e, int levels)
1597 int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1598 av_assert2(v >= 0 && v < levels);
1604 * Asymmetric quantization on 2^qbits levels.
1606 static inline int asym_quant(int c, int e, int qbits)
1610 lshift = e + qbits - 24;
1617 m = (1 << (qbits-1));
1620 av_assert2(v >= -m);
1621 return v & ((1 << qbits)-1);
1626 * Quantize a set of mantissas for a single channel in a single block.
1628 static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1629 uint8_t *exp, uint8_t *bap,
1630 uint16_t *qmant, int start_freq,
1635 for (i = start_freq; i < end_freq; i++) {
1637 int c = fixed_coef[i];
1645 v = sym_quant(c, e, 3);
1646 switch (s->mant1_cnt) {
1648 s->qmant1_ptr = &qmant[i];
1653 *s->qmant1_ptr += 3 * v;
1658 *s->qmant1_ptr += v;
1665 v = sym_quant(c, e, 5);
1666 switch (s->mant2_cnt) {
1668 s->qmant2_ptr = &qmant[i];
1673 *s->qmant2_ptr += 5 * v;
1678 *s->qmant2_ptr += v;
1685 v = sym_quant(c, e, 7);
1688 v = sym_quant(c, e, 11);
1689 switch (s->mant4_cnt) {
1691 s->qmant4_ptr = &qmant[i];
1696 *s->qmant4_ptr += v;
1703 v = sym_quant(c, e, 15);
1706 v = asym_quant(c, e, 14);
1709 v = asym_quant(c, e, 16);
1712 v = asym_quant(c, e, b - 1);
1721 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1723 static void quantize_mantissas(AC3EncodeContext *s)
1725 int blk, ch, ch0=0, got_cpl;
1727 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1728 AC3Block *block = &s->blocks[blk];
1729 AC3Block *ref_block;
1732 got_cpl = !block->cpl_in_use;
1733 for (ch = 1; ch <= s->channels; ch++) {
1734 if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1739 ref_block = block->exp_ref_block[ch];
1740 quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1742 ref_block->bap[ch], block->qmant[ch],
1743 s->start_freq[ch], block->end_freq[ch]);
1752 * Write the AC-3 frame header to the output bitstream.
1754 static void output_frame_header(AC3EncodeContext *s)
1756 AC3EncOptions *opt = &s->options;
1758 put_bits(&s->pb, 16, 0x0b77); /* frame header */
1759 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
1760 put_bits(&s->pb, 2, s->bit_alloc.sr_code);
1761 put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1762 put_bits(&s->pb, 5, s->bitstream_id);
1763 put_bits(&s->pb, 3, s->bitstream_mode);
1764 put_bits(&s->pb, 3, s->channel_mode);
1765 if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1766 put_bits(&s->pb, 2, s->center_mix_level);
1767 if (s->channel_mode & 0x04)
1768 put_bits(&s->pb, 2, s->surround_mix_level);
1769 if (s->channel_mode == AC3_CHMODE_STEREO)
1770 put_bits(&s->pb, 2, opt->dolby_surround_mode);
1771 put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1772 put_bits(&s->pb, 5, -opt->dialogue_level);
1773 put_bits(&s->pb, 1, 0); /* no compression control word */
1774 put_bits(&s->pb, 1, 0); /* no lang code */
1775 put_bits(&s->pb, 1, opt->audio_production_info);
1776 if (opt->audio_production_info) {
1777 put_bits(&s->pb, 5, opt->mixing_level - 80);
1778 put_bits(&s->pb, 2, opt->room_type);
1780 put_bits(&s->pb, 1, opt->copyright);
1781 put_bits(&s->pb, 1, opt->original);
1782 if (s->bitstream_id == 6) {
1783 /* alternate bit stream syntax */
1784 put_bits(&s->pb, 1, opt->extended_bsi_1);
1785 if (opt->extended_bsi_1) {
1786 put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1787 put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1788 put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1789 put_bits(&s->pb, 3, s->loro_center_mix_level);
1790 put_bits(&s->pb, 3, s->loro_surround_mix_level);
1792 put_bits(&s->pb, 1, opt->extended_bsi_2);
1793 if (opt->extended_bsi_2) {
1794 put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1795 put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1796 put_bits(&s->pb, 1, opt->ad_converter_type);
1797 put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
1800 put_bits(&s->pb, 1, 0); /* no time code 1 */
1801 put_bits(&s->pb, 1, 0); /* no time code 2 */
1803 put_bits(&s->pb, 1, 0); /* no additional bit stream info */
1808 * Write one audio block to the output bitstream.
1810 static void output_audio_block(AC3EncodeContext *s, int blk)
1812 int ch, i, baie, bnd, got_cpl;
1814 AC3Block *block = &s->blocks[blk];
1816 /* block switching */
1817 for (ch = 0; ch < s->fbw_channels; ch++)
1818 put_bits(&s->pb, 1, 0);
1821 for (ch = 0; ch < s->fbw_channels; ch++)
1822 put_bits(&s->pb, 1, 1);
1824 /* dynamic range codes */
1825 put_bits(&s->pb, 1, 0);
1827 /* channel coupling */
1828 put_bits(&s->pb, 1, block->new_cpl_strategy);
1829 if (block->new_cpl_strategy) {
1830 put_bits(&s->pb, 1, block->cpl_in_use);
1831 if (block->cpl_in_use) {
1832 int start_sub, end_sub;
1833 for (ch = 1; ch <= s->fbw_channels; ch++)
1834 put_bits(&s->pb, 1, block->channel_in_cpl[ch]);
1835 if (s->channel_mode == AC3_CHMODE_STEREO)
1836 put_bits(&s->pb, 1, 0); /* phase flags in use */
1837 start_sub = (s->start_freq[CPL_CH] - 37) / 12;
1838 end_sub = (s->cpl_end_freq - 37) / 12;
1839 put_bits(&s->pb, 4, start_sub);
1840 put_bits(&s->pb, 4, end_sub - 3);
1841 for (bnd = start_sub+1; bnd < end_sub; bnd++)
1842 put_bits(&s->pb, 1, ff_eac3_default_cpl_band_struct[bnd]);
1846 /* coupling coordinates */
1847 if (block->cpl_in_use) {
1848 for (ch = 1; ch <= s->fbw_channels; ch++) {
1849 if (block->channel_in_cpl[ch]) {
1850 put_bits(&s->pb, 1, block->new_cpl_coords);
1851 if (block->new_cpl_coords) {
1852 put_bits(&s->pb, 2, block->cpl_master_exp[ch]);
1853 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
1854 put_bits(&s->pb, 4, block->cpl_coord_exp [ch][bnd]);
1855 put_bits(&s->pb, 4, block->cpl_coord_mant[ch][bnd]);
1862 /* stereo rematrixing */
1863 if (s->channel_mode == AC3_CHMODE_STEREO) {
1864 put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1865 if (block->new_rematrixing_strategy) {
1866 /* rematrixing flags */
1867 for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++)
1868 put_bits(&s->pb, 1, block->rematrixing_flags[bnd]);
1872 /* exponent strategy */
1873 for (ch = !block->cpl_in_use; ch <= s->fbw_channels; ch++)
1874 put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1876 put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1879 for (ch = 1; ch <= s->fbw_channels; ch++) {
1880 if (s->exp_strategy[ch][blk] != EXP_REUSE && !block->channel_in_cpl[ch])
1881 put_bits(&s->pb, 6, s->bandwidth_code);
1885 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1887 int cpl = (ch == CPL_CH);
1889 if (s->exp_strategy[ch][blk] == EXP_REUSE)
1893 put_bits(&s->pb, 4, block->grouped_exp[ch][0] >> cpl);
1895 /* exponent groups */
1896 nb_groups = exponent_group_tab[cpl][s->exp_strategy[ch][blk]-1][block->end_freq[ch]-s->start_freq[ch]];
1897 for (i = 1; i <= nb_groups; i++)
1898 put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1900 /* gain range info */
1901 if (ch != s->lfe_channel && !cpl)
1902 put_bits(&s->pb, 2, 0);
1905 /* bit allocation info */
1907 put_bits(&s->pb, 1, baie);
1909 put_bits(&s->pb, 2, s->slow_decay_code);
1910 put_bits(&s->pb, 2, s->fast_decay_code);
1911 put_bits(&s->pb, 2, s->slow_gain_code);
1912 put_bits(&s->pb, 2, s->db_per_bit_code);
1913 put_bits(&s->pb, 3, s->floor_code);
1917 put_bits(&s->pb, 1, block->new_snr_offsets);
1918 if (block->new_snr_offsets) {
1919 put_bits(&s->pb, 6, s->coarse_snr_offset);
1920 for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1921 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1922 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1927 if (block->cpl_in_use) {
1928 put_bits(&s->pb, 1, block->new_cpl_leak);
1929 if (block->new_cpl_leak) {
1930 put_bits(&s->pb, 3, s->bit_alloc.cpl_fast_leak);
1931 put_bits(&s->pb, 3, s->bit_alloc.cpl_slow_leak);
1935 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1936 put_bits(&s->pb, 1, 0); /* no data to skip */
1939 got_cpl = !block->cpl_in_use;
1940 for (ch = 1; ch <= s->channels; ch++) {
1942 AC3Block *ref_block;
1944 if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1949 ref_block = block->exp_ref_block[ch];
1950 for (i = s->start_freq[ch]; i < block->end_freq[ch]; i++) {
1951 q = block->qmant[ch][i];
1952 b = ref_block->bap[ch][i];
1955 case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
1956 case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
1957 case 3: put_bits(&s->pb, 3, q); break;
1958 case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
1959 case 14: put_bits(&s->pb, 14, q); break;
1960 case 15: put_bits(&s->pb, 16, q); break;
1961 default: put_bits(&s->pb, b-1, q); break;
1970 /** CRC-16 Polynomial */
1971 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1974 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1991 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1997 r = mul_poly(r, a, poly);
1998 a = mul_poly(a, a, poly);
2006 * Fill the end of the frame with 0's and compute the two CRCs.
2008 static void output_frame_end(AC3EncodeContext *s)
2010 const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
2011 int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
2014 frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
2016 /* pad the remainder of the frame with zeros */
2017 av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
2018 flush_put_bits(&s->pb);
2020 pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
2021 av_assert2(pad_bytes >= 0);
2023 memset(put_bits_ptr(&s->pb), 0, pad_bytes);
2026 /* this is not so easy because it is at the beginning of the data... */
2027 crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
2028 crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
2029 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
2030 AV_WB16(frame + 2, crc1);
2033 crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
2034 s->frame_size - frame_size_58 - 3);
2035 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
2036 /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
2037 if (crc2 == 0x770B) {
2038 frame[s->frame_size - 3] ^= 0x1;
2039 crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
2041 crc2 = av_bswap16(crc2);
2042 AV_WB16(frame + s->frame_size - 2, crc2);
2047 * Write the frame to the output bitstream.
2049 static void output_frame(AC3EncodeContext *s, unsigned char *frame)
2053 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
2055 output_frame_header(s);
2057 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2058 output_audio_block(s, blk);
2060 output_frame_end(s);
2064 static void dprint_options(AVCodecContext *avctx)
2067 AC3EncodeContext *s = avctx->priv_data;
2068 AC3EncOptions *opt = &s->options;
2071 switch (s->bitstream_id) {
2072 case 6: av_strlcpy(strbuf, "AC-3 (alt syntax)", 32); break;
2073 case 8: av_strlcpy(strbuf, "AC-3 (standard)", 32); break;
2074 case 9: av_strlcpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
2075 case 10: av_strlcpy(strbuf, "AC-3 (dnet quater-rate", 32); break;
2076 default: snprintf(strbuf, 32, "ERROR");
2078 av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
2079 av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
2080 av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
2081 av_dlog(avctx, "channel_layout: %s\n", strbuf);
2082 av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
2083 av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
2085 av_dlog(avctx, "cutoff: %d\n", s->cutoff);
2087 av_dlog(avctx, "per_frame_metadata: %s\n",
2088 opt->allow_per_frame_metadata?"on":"off");
2090 av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
2091 s->center_mix_level);
2093 av_dlog(avctx, "center_mixlev: {not written}\n");
2094 if (s->has_surround)
2095 av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
2096 s->surround_mix_level);
2098 av_dlog(avctx, "surround_mixlev: {not written}\n");
2099 if (opt->audio_production_info) {
2100 av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
2101 switch (opt->room_type) {
2102 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
2103 case 1: av_strlcpy(strbuf, "large", 32); break;
2104 case 2: av_strlcpy(strbuf, "small", 32); break;
2105 default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
2107 av_dlog(avctx, "room_type: %s\n", strbuf);
2109 av_dlog(avctx, "mixing_level: {not written}\n");
2110 av_dlog(avctx, "room_type: {not written}\n");
2112 av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
2113 av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
2114 if (s->channel_mode == AC3_CHMODE_STEREO) {
2115 switch (opt->dolby_surround_mode) {
2116 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
2117 case 1: av_strlcpy(strbuf, "on", 32); break;
2118 case 2: av_strlcpy(strbuf, "off", 32); break;
2119 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
2121 av_dlog(avctx, "dsur_mode: %s\n", strbuf);
2123 av_dlog(avctx, "dsur_mode: {not written}\n");
2125 av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
2127 if (s->bitstream_id == 6) {
2128 if (opt->extended_bsi_1) {
2129 switch (opt->preferred_stereo_downmix) {
2130 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
2131 case 1: av_strlcpy(strbuf, "ltrt", 32); break;
2132 case 2: av_strlcpy(strbuf, "loro", 32); break;
2133 default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
2135 av_dlog(avctx, "dmix_mode: %s\n", strbuf);
2136 av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
2137 opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
2138 av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
2139 opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
2140 av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
2141 opt->loro_center_mix_level, s->loro_center_mix_level);
2142 av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
2143 opt->loro_surround_mix_level, s->loro_surround_mix_level);
2145 av_dlog(avctx, "extended bitstream info 1: {not written}\n");
2147 if (opt->extended_bsi_2) {
2148 switch (opt->dolby_surround_ex_mode) {
2149 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
2150 case 1: av_strlcpy(strbuf, "on", 32); break;
2151 case 2: av_strlcpy(strbuf, "off", 32); break;
2152 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
2154 av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
2155 switch (opt->dolby_headphone_mode) {
2156 case 0: av_strlcpy(strbuf, "notindicated", 32); break;
2157 case 1: av_strlcpy(strbuf, "on", 32); break;
2158 case 2: av_strlcpy(strbuf, "off", 32); break;
2159 default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
2161 av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
2163 switch (opt->ad_converter_type) {
2164 case 0: av_strlcpy(strbuf, "standard", 32); break;
2165 case 1: av_strlcpy(strbuf, "hdcd", 32); break;
2166 default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
2168 av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
2170 av_dlog(avctx, "extended bitstream info 2: {not written}\n");
2177 #define FLT_OPTION_THRESHOLD 0.01
2179 static int validate_float_option(float v, const float *v_list, int v_list_size)
2183 for (i = 0; i < v_list_size; i++) {
2184 if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
2185 v > (v_list[i] - FLT_OPTION_THRESHOLD))
2188 if (i == v_list_size)
2195 static void validate_mix_level(void *log_ctx, const char *opt_name,
2196 float *opt_param, const float *list,
2197 int list_size, int default_value, int min_value,
2200 int mixlev = validate_float_option(*opt_param, list, list_size);
2201 if (mixlev < min_value) {
2202 mixlev = default_value;
2203 if (*opt_param >= 0.0) {
2204 av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
2205 "default value: %0.3f\n", opt_name, list[mixlev]);
2208 *opt_param = list[mixlev];
2209 *ctx_param = mixlev;
2214 * Validate metadata options as set by AVOption system.
2215 * These values can optionally be changed per-frame.
2217 static int validate_metadata(AVCodecContext *avctx)
2219 AC3EncodeContext *s = avctx->priv_data;
2220 AC3EncOptions *opt = &s->options;
2222 /* validate mixing levels */
2223 if (s->has_center) {
2224 validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
2225 cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
2226 &s->center_mix_level);
2228 if (s->has_surround) {
2229 validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
2230 surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
2231 &s->surround_mix_level);
2234 /* set audio production info flag */
2235 if (opt->mixing_level >= 0 || opt->room_type >= 0) {
2236 if (opt->mixing_level < 0) {
2237 av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
2238 "room_type is set\n");
2239 return AVERROR(EINVAL);
2241 if (opt->mixing_level < 80) {
2242 av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
2243 "80dB and 111dB\n");
2244 return AVERROR(EINVAL);
2246 /* default room type */
2247 if (opt->room_type < 0)
2249 opt->audio_production_info = 1;
2251 opt->audio_production_info = 0;
2254 /* set extended bsi 1 flag */
2255 if ((s->has_center || s->has_surround) &&
2256 (opt->preferred_stereo_downmix >= 0 ||
2257 opt->ltrt_center_mix_level >= 0 ||
2258 opt->ltrt_surround_mix_level >= 0 ||
2259 opt->loro_center_mix_level >= 0 ||
2260 opt->loro_surround_mix_level >= 0)) {
2261 /* default preferred stereo downmix */
2262 if (opt->preferred_stereo_downmix < 0)
2263 opt->preferred_stereo_downmix = 0;
2264 /* validate Lt/Rt center mix level */
2265 validate_mix_level(avctx, "ltrt_center_mix_level",
2266 &opt->ltrt_center_mix_level, extmixlev_options,
2267 EXTMIXLEV_NUM_OPTIONS, 5, 0,
2268 &s->ltrt_center_mix_level);
2269 /* validate Lt/Rt surround mix level */
2270 validate_mix_level(avctx, "ltrt_surround_mix_level",
2271 &opt->ltrt_surround_mix_level, extmixlev_options,
2272 EXTMIXLEV_NUM_OPTIONS, 6, 3,
2273 &s->ltrt_surround_mix_level);
2274 /* validate Lo/Ro center mix level */
2275 validate_mix_level(avctx, "loro_center_mix_level",
2276 &opt->loro_center_mix_level, extmixlev_options,
2277 EXTMIXLEV_NUM_OPTIONS, 5, 0,
2278 &s->loro_center_mix_level);
2279 /* validate Lo/Ro surround mix level */
2280 validate_mix_level(avctx, "loro_surround_mix_level",
2281 &opt->loro_surround_mix_level, extmixlev_options,
2282 EXTMIXLEV_NUM_OPTIONS, 6, 3,
2283 &s->loro_surround_mix_level);
2284 opt->extended_bsi_1 = 1;
2286 opt->extended_bsi_1 = 0;
2289 /* set extended bsi 2 flag */
2290 if (opt->dolby_surround_ex_mode >= 0 ||
2291 opt->dolby_headphone_mode >= 0 ||
2292 opt->ad_converter_type >= 0) {
2293 /* default dolby surround ex mode */
2294 if (opt->dolby_surround_ex_mode < 0)
2295 opt->dolby_surround_ex_mode = 0;
2296 /* default dolby headphone mode */
2297 if (opt->dolby_headphone_mode < 0)
2298 opt->dolby_headphone_mode = 0;
2299 /* default A/D converter type */
2300 if (opt->ad_converter_type < 0)
2301 opt->ad_converter_type = 0;
2302 opt->extended_bsi_2 = 1;
2304 opt->extended_bsi_2 = 0;
2307 /* set bitstream id for alternate bitstream syntax */
2308 if (opt->extended_bsi_1 || opt->extended_bsi_2) {
2309 if (s->bitstream_id > 8 && s->bitstream_id < 11) {
2310 static int warn_once = 1;
2312 av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
2313 "not compatible with reduced samplerates. writing of "
2314 "extended bitstream information will be disabled.\n");
2318 s->bitstream_id = 6;
2327 * Encode a single AC-3 frame.
2329 static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
2330 int buf_size, void *data)
2332 AC3EncodeContext *s = avctx->priv_data;
2333 const SampleType *samples = data;
2336 if (s->options.allow_per_frame_metadata) {
2337 ret = validate_metadata(avctx);
2342 if (s->bit_alloc.sr_code == 1)
2343 adjust_frame_size(s);
2345 deinterleave_input_samples(s, samples);
2349 scale_coefficients(s);
2351 s->cpl_on = s->cpl_enabled;
2352 compute_coupling_strategy(s);
2355 apply_channel_coupling(s);
2357 compute_rematrixing_strategy(s);
2359 apply_rematrixing(s);
2361 process_exponents(s);
2363 ret = compute_bit_allocation(s);
2365 av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
2369 quantize_mantissas(s);
2371 output_frame(s, frame);
2373 return s->frame_size;
2378 * Finalize encoding and free any memory allocated by the encoder.
2380 static av_cold int ac3_encode_close(AVCodecContext *avctx)
2383 AC3EncodeContext *s = avctx->priv_data;
2385 for (ch = 0; ch < s->channels; ch++)
2386 av_freep(&s->planar_samples[ch]);
2387 av_freep(&s->planar_samples);
2388 av_freep(&s->bap_buffer);
2389 av_freep(&s->bap1_buffer);
2390 av_freep(&s->mdct_coef_buffer);
2391 av_freep(&s->fixed_coef_buffer);
2392 av_freep(&s->exp_buffer);
2393 av_freep(&s->grouped_exp_buffer);
2394 av_freep(&s->psd_buffer);
2395 av_freep(&s->band_psd_buffer);
2396 av_freep(&s->mask_buffer);
2397 av_freep(&s->qmant_buffer);
2398 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2399 AC3Block *block = &s->blocks[blk];
2400 av_freep(&block->bap);
2401 av_freep(&block->mdct_coef);
2402 av_freep(&block->fixed_coef);
2403 av_freep(&block->exp);
2404 av_freep(&block->grouped_exp);
2405 av_freep(&block->psd);
2406 av_freep(&block->band_psd);
2407 av_freep(&block->mask);
2408 av_freep(&block->qmant);
2413 av_freep(&avctx->coded_frame);
2419 * Set channel information during initialization.
2421 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
2422 int64_t *channel_layout)
2426 if (channels < 1 || channels > AC3_MAX_CHANNELS)
2427 return AVERROR(EINVAL);
2428 if ((uint64_t)*channel_layout > 0x7FF)
2429 return AVERROR(EINVAL);
2430 ch_layout = *channel_layout;
2432 ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
2434 s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
2435 s->channels = channels;
2436 s->fbw_channels = channels - s->lfe_on;
2437 s->lfe_channel = s->lfe_on ? s->fbw_channels + 1 : -1;
2439 ch_layout -= AV_CH_LOW_FREQUENCY;
2441 switch (ch_layout) {
2442 case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
2443 case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
2444 case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
2445 case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
2446 case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
2447 case AV_CH_LAYOUT_QUAD:
2448 case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
2449 case AV_CH_LAYOUT_5POINT0:
2450 case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
2452 return AVERROR(EINVAL);
2454 s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
2455 s->has_surround = s->channel_mode & 0x04;
2457 s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
2458 *channel_layout = ch_layout;
2460 *channel_layout |= AV_CH_LOW_FREQUENCY;
2466 static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
2470 /* validate channel layout */
2471 if (!avctx->channel_layout) {
2472 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
2473 "encoder will guess the layout, but it "
2474 "might be incorrect.\n");
2476 ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
2478 av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
2482 /* validate sample rate */
2483 for (i = 0; i < 9; i++) {
2484 if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
2488 av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
2489 return AVERROR(EINVAL);
2491 s->sample_rate = avctx->sample_rate;
2492 s->bit_alloc.sr_shift = i % 3;
2493 s->bit_alloc.sr_code = i / 3;
2494 s->bitstream_id = 8 + s->bit_alloc.sr_shift;
2496 /* validate bit rate */
2497 for (i = 0; i < 19; i++) {
2498 if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
2502 av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2503 return AVERROR(EINVAL);
2505 s->bit_rate = avctx->bit_rate;
2506 s->frame_size_code = i << 1;
2508 /* validate cutoff */
2509 if (avctx->cutoff < 0) {
2510 av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2511 return AVERROR(EINVAL);
2513 s->cutoff = avctx->cutoff;
2514 if (s->cutoff > (s->sample_rate >> 1))
2515 s->cutoff = s->sample_rate >> 1;
2517 /* validate audio service type / channels combination */
2518 if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
2519 avctx->channels == 1) ||
2520 ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
2521 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
2522 avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
2523 && avctx->channels > 1)) {
2524 av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
2525 "specified number of channels\n");
2526 return AVERROR(EINVAL);
2529 ret = validate_metadata(avctx);
2533 s->rematrixing_enabled = s->options.stereo_rematrixing &&
2534 (s->channel_mode == AC3_CHMODE_STEREO);
2536 s->cpl_enabled = s->options.channel_coupling &&
2537 s->channel_mode >= AC3_CHMODE_STEREO &&
2538 CONFIG_AC3ENC_FLOAT;
2545 * Set bandwidth for all channels.
2546 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2547 * default value will be used.
2549 static av_cold void set_bandwidth(AC3EncodeContext *s)
2552 int av_uninit(cpl_start);
2555 /* calculate bandwidth based on user-specified cutoff frequency */
2557 fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2558 s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2560 /* use default bandwidth setting */
2561 s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2564 /* set number of coefficients for each channel */
2565 for (ch = 1; ch <= s->fbw_channels; ch++) {
2566 s->start_freq[ch] = 0;
2567 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2568 s->blocks[blk].end_freq[ch] = s->bandwidth_code * 3 + 73;
2570 /* LFE channel always has 7 coefs */
2572 s->start_freq[s->lfe_channel] = 0;
2573 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2574 s->blocks[blk].end_freq[ch] = 7;
2577 /* initialize coupling strategy */
2578 if (s->cpl_enabled) {
2579 if (s->options.cpl_start >= 0) {
2580 cpl_start = s->options.cpl_start;
2582 cpl_start = ac3_coupling_start_tab[s->channel_mode-2][s->bit_alloc.sr_code][s->frame_size_code/2];
2587 if (s->cpl_enabled) {
2588 int i, cpl_start_band, cpl_end_band;
2589 uint8_t *cpl_band_sizes = s->cpl_band_sizes;
2591 cpl_end_band = s->bandwidth_code / 4 + 3;
2592 cpl_start_band = av_clip(cpl_start, 0, FFMIN(cpl_end_band-1, 15));
2594 s->num_cpl_subbands = cpl_end_band - cpl_start_band;
2596 s->num_cpl_bands = 1;
2597 *cpl_band_sizes = 12;
2598 for (i = cpl_start_band + 1; i < cpl_end_band; i++) {
2599 if (ff_eac3_default_cpl_band_struct[i]) {
2600 *cpl_band_sizes += 12;
2604 *cpl_band_sizes = 12;
2608 s->start_freq[CPL_CH] = cpl_start_band * 12 + 37;
2609 s->cpl_end_freq = cpl_end_band * 12 + 37;
2610 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2611 s->blocks[blk].end_freq[CPL_CH] = s->cpl_end_freq;
2616 static av_cold int allocate_buffers(AVCodecContext *avctx)
2619 AC3EncodeContext *s = avctx->priv_data;
2620 int channels = s->channels + 1; /* includes coupling channel */
2622 FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
2624 for (ch = 0; ch < s->channels; ch++) {
2625 FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
2626 (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
2629 FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * channels *
2630 AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
2631 FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * channels *
2632 AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
2633 FF_ALLOCZ_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * channels *
2634 AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
2635 FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * channels *
2636 AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
2637 FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * channels *
2638 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
2639 FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * channels *
2640 AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
2641 FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * channels *
2642 64 * sizeof(*s->band_psd_buffer), alloc_fail);
2643 FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * channels *
2644 64 * sizeof(*s->mask_buffer), alloc_fail);
2645 FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * channels *
2646 AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
2647 if (s->cpl_enabled) {
2648 FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_exp_buffer, AC3_MAX_BLOCKS * channels *
2649 16 * sizeof(*s->cpl_coord_exp_buffer), alloc_fail);
2650 FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_mant_buffer, AC3_MAX_BLOCKS * channels *
2651 16 * sizeof(*s->cpl_coord_mant_buffer), alloc_fail);
2653 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2654 AC3Block *block = &s->blocks[blk];
2655 FF_ALLOC_OR_GOTO(avctx, block->bap, channels * sizeof(*block->bap),
2657 FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, channels * sizeof(*block->mdct_coef),
2659 FF_ALLOCZ_OR_GOTO(avctx, block->exp, channels * sizeof(*block->exp),
2661 FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, channels * sizeof(*block->grouped_exp),
2663 FF_ALLOCZ_OR_GOTO(avctx, block->psd, channels * sizeof(*block->psd),
2665 FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, channels * sizeof(*block->band_psd),
2667 FF_ALLOCZ_OR_GOTO(avctx, block->mask, channels * sizeof(*block->mask),
2669 FF_ALLOCZ_OR_GOTO(avctx, block->qmant, channels * sizeof(*block->qmant),
2671 if (s->cpl_enabled) {
2672 FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_exp, channels * sizeof(*block->cpl_coord_exp),
2674 FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_mant, channels * sizeof(*block->cpl_coord_mant),
2678 for (ch = 0; ch < channels; ch++) {
2679 /* arrangement: block, channel, coeff */
2680 block->bap[ch] = &s->bap_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
2681 block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * channels + ch)];
2682 block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
2683 block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * channels + ch)];
2684 block->mask[ch] = &s->mask_buffer [64 * (blk * channels + ch)];
2685 block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
2686 if (s->cpl_enabled) {
2687 block->cpl_coord_exp[ch] = &s->cpl_coord_exp_buffer [16 * (blk * channels + ch)];
2688 block->cpl_coord_mant[ch] = &s->cpl_coord_mant_buffer[16 * (blk * channels + ch)];
2691 /* arrangement: channel, block, coeff */
2692 block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2693 block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2697 if (CONFIG_AC3ENC_FLOAT) {
2698 FF_ALLOCZ_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * channels *
2699 AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
2700 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2701 AC3Block *block = &s->blocks[blk];
2702 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2703 sizeof(*block->fixed_coef), alloc_fail);
2704 for (ch = 0; ch < channels; ch++)
2705 block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2708 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2709 AC3Block *block = &s->blocks[blk];
2710 FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2711 sizeof(*block->fixed_coef), alloc_fail);
2712 for (ch = 0; ch < channels; ch++)
2713 block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2719 return AVERROR(ENOMEM);
2724 * Initialize the encoder.
2726 static av_cold int ac3_encode_init(AVCodecContext *avctx)
2728 AC3EncodeContext *s = avctx->priv_data;
2729 int ret, frame_size_58;
2731 avctx->frame_size = AC3_FRAME_SIZE;
2733 ff_ac3_common_init();
2735 ret = validate_options(avctx, s);
2739 s->bitstream_mode = avctx->audio_service_type;
2740 if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2741 s->bitstream_mode = 0x7;
2743 s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2744 s->bits_written = 0;
2745 s->samples_written = 0;
2746 s->frame_size = s->frame_size_min;
2748 /* calculate crc_inv for both possible frame sizes */
2749 frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
2750 s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2751 if (s->bit_alloc.sr_code == 1) {
2752 frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2753 s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2762 ret = mdct_init(avctx, &s->mdct, 9);
2766 ret = allocate_buffers(avctx);
2770 avctx->coded_frame= avcodec_alloc_frame();
2772 dsputil_init(&s->dsp, avctx);
2773 ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2775 dprint_options(avctx);
2779 ac3_encode_close(avctx);