]> git.sesse.net Git - ffmpeg/blob - libavcodec/ac3enc.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavcodec / ac3enc.c
1 /*
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>
6  *
7  * This file is part of FFmpeg.
8  *
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.
13  *
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.
18  *
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
22  */
23
24 /**
25  * @file
26  * The simplest AC-3 encoder.
27  */
28
29 //#define DEBUG
30 //#define ASSERT_LEVEL 2
31
32 #include <stdint.h>
33
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"
39 #include "avcodec.h"
40 #include "put_bits.h"
41 #include "dsputil.h"
42 #include "ac3dsp.h"
43 #include "ac3.h"
44 #include "audioconvert.h"
45 #include "fft.h"
46
47
48 #ifndef CONFIG_AC3ENC_FLOAT
49 #define CONFIG_AC3ENC_FLOAT 0
50 #endif
51
52
53 /** Maximum number of exponent groups. +1 for separate DC exponent. */
54 #define AC3_MAX_EXP_GROUPS 85
55
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;
61 #else
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;
66 #endif
67
68 typedef struct AC3MDCTContext {
69     const SampleType *window;           ///< MDCT window function
70     FFTContext fft;                     ///< FFT context for MDCT calculation
71 } AC3MDCTContext;
72
73
74 /**
75  * Data for a single audio block.
76  */
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)
103 } AC3Block;
104
105 /**
106  * AC-3 encoder private context.
107  */
108 typedef struct AC3EncodeContext {
109     AVClass *av_class;                      ///< AVClass used for AVOption
110     AC3EncOptions options;                  ///< encoding options
111     PutBitContext pb;                       ///< bitstream writer context
112     DSPContext dsp;
113     AC3DSPContext ac3dsp;                   ///< AC-3 optimized functions
114     AC3MDCTContext mdct;                    ///< MDCT context
115
116     AC3Block blocks[AC3_MAX_BLOCKS];        ///< per-block info
117
118     int bitstream_id;                       ///< bitstream id                           (bsid)
119     int bitstream_mode;                     ///< bitstream mode                         (bsmod)
120
121     int bit_rate;                           ///< target bit rate, in bits-per-second
122     int sample_rate;                        ///< sampling frequency, in Hz
123
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)
127     uint16_t crc_inv[2];
128     int bits_written;                       ///< bit count    (used to avg. bitrate)
129     int samples_written;                    ///< sample count (used to avg. bitrate)
130
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
139
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
146
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
151
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
157
158     int rematrixing_enabled;                ///< stereo rematrixing enabled
159
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
173
174     SampleType **planar_samples;
175     uint8_t *bap_buffer;
176     uint8_t *bap1_buffer;
177     CoefType *mdct_coef_buffer;
178     int32_t *fixed_coef_buffer;
179     uint8_t *exp_buffer;
180     uint8_t *grouped_exp_buffer;
181     int16_t *psd_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;
187
188     uint8_t exp_strategy[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< exponent strategies
189
190     DECLARE_ALIGNED(32, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
191 } AC3EncodeContext;
192
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
196 } AC3Mant;
197
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
201 };
202
203 #define SURMIXLEV_NUM_OPTIONS 3
204 static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
205     LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
206 };
207
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
212 };
213
214
215 #define OFFSET(param) offsetof(AC3EncodeContext, options.param)
216 #define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
217
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},
222 /* downmix levels */
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"},
266 #endif
267 {NULL}
268 };
269 #endif
270
271 #if CONFIG_AC3ENC_FLOAT
272 static AVClass ac3enc_class = { "AC-3 Encoder", av_default_item_name,
273                                 ff_ac3_options, LIBAVUTIL_VERSION_INT };
274 #else
275 static AVClass ac3enc_class = { "Fixed-Point AC-3 Encoder", av_default_item_name,
276                                 ff_ac3_options, LIBAVUTIL_VERSION_INT };
277 #endif
278
279
280 /* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
281
282 static av_cold void mdct_end(AC3MDCTContext *mdct);
283
284 static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
285                              int nbits);
286
287 static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
288                          const SampleType *window, unsigned int len);
289
290 static int normalize_samples(AC3EncodeContext *s);
291
292 static void scale_coefficients(AC3EncodeContext *s);
293
294
295 /**
296  * LUT for number of exponent groups.
297  * exponent_group_tab[coupling][exponent strategy-1][number of coefficients]
298  */
299 static uint8_t exponent_group_tab[2][3][256];
300
301
302 /**
303  * List of supported channel layouts.
304  */
305 #if CONFIG_AC3ENC_FLOAT || !CONFIG_AC3_FLOAT_ENCODER //we need this exactly once compiled in
306 const int64_t ff_ac3_channel_layouts[] = {
307      AV_CH_LAYOUT_MONO,
308      AV_CH_LAYOUT_STEREO,
309      AV_CH_LAYOUT_2_1,
310      AV_CH_LAYOUT_SURROUND,
311      AV_CH_LAYOUT_2_2,
312      AV_CH_LAYOUT_QUAD,
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,
325      0
326 };
327 #endif
328
329
330 /**
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]
334  */
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
337
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 } },
341
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 } },
345
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 } },
349
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 } },
353
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 } }
357 };
358
359
360 /**
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]
364  *
365  * TODO: more testing for optimal parameters.
366  *       multi-channel tests at 44.1kHz and 32kHz.
367  */
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
370
371     // 2/0
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 } },
375
376     // 3/0
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 } },
380
381     // 2/1 - untested
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 } },
385
386     // 3/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 } },
390
391     // 2/2 - untested
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 } },
395
396     // 3/2
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 } },
400 };
401
402
403 /**
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.
406  */
407 static void adjust_frame_size(AC3EncodeContext *s)
408 {
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;
412     }
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;
417 }
418
419
420 /**
421  * Deinterleave input samples.
422  * Channels are reordered from FFmpeg's default order to AC-3 order.
423  */
424 static void deinterleave_input_samples(AC3EncodeContext *s,
425                                        const SampleType *samples)
426 {
427     int ch, i;
428
429     /* deinterleave and remap input samples */
430     for (ch = 0; ch < s->channels; ch++) {
431         const SampleType *sptr;
432         int sinc;
433
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]));
437
438         /* deinterleave */
439         sinc = s->channels;
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;
443             sptr += sinc;
444         }
445     }
446 }
447
448
449 /**
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.
453  */
454 static void apply_mdct(AC3EncodeContext *s)
455 {
456     int blk, ch;
457
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];
462
463             apply_window(&s->dsp, s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
464
465             block->coeff_shift[ch+1] = normalize_samples(s);
466
467             s->mdct.fft.mdct_calcw(&s->mdct.fft, block->mdct_coef[ch+1],
468                                    s->windowed_samples);
469         }
470     }
471 }
472
473
474 static void compute_coupling_strategy(AC3EncodeContext *s)
475 {
476     int blk, ch;
477     int got_cpl_snr;
478
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;
485     }
486
487     /* enable coupling for each block if at least 2 channels have coupling
488        enabled for that block */
489     got_cpl_snr = 0;
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;
500         }
501
502         block->new_cpl_strategy = !blk;
503         if (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;
507                     break;
508                 }
509             }
510         }
511         block->new_cpl_leak = block->new_cpl_strategy;
512
513         if (!blk || (block->cpl_in_use && !got_cpl_snr)) {
514             block->new_snr_offsets = 1;
515             if (block->cpl_in_use)
516                 got_cpl_snr = 1;
517         } else {
518             block->new_snr_offsets = 0;
519         }
520     }
521
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];
528             else
529                 block->end_freq[ch] = s->bandwidth_code * 3 + 73;
530         }
531     }
532 }
533
534
535 /**
536  * Calculate a single coupling coordinate.
537  */
538 static inline float calc_cpl_coord(float energy_ch, float energy_cpl)
539 {
540     float coord = 0.125;
541     if (energy_cpl > 0)
542         coord *= sqrtf(energy_ch / energy_cpl);
543     return coord;
544 }
545
546
547 /**
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.
554  */
555 static void apply_channel_coupling(AC3EncodeContext *s)
556 {
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;
563
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)
569             continue;
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])
574                 continue;
575             for (i = 0; i < num_cpl_coefs; i++)
576                 cpl_coef[i] += ch_coef[i];
577         }
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. */
582
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);
585
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);
589     }
590
591     /* calculate energy in each band in coupling channel and each fbw channel */
592     /* TODO: possibly use SIMD to speed up energy calculation */
593     bnd = 0;
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]))
601                     continue;
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);
605                 }
606             }
607         }
608         i += band_size;
609         bnd++;
610     }
611
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;
616         int new_coords = 0;
617         CoefSumType coord_diff[AC3_MAX_CHANNELS] = {0,};
618
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])
624                     continue;
625
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]);
633                     }
634                 }
635                 coord_diff[ch] /= s->num_cpl_bands;
636             }
637
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. */
643             if (blk == 0) {
644                 new_coords = 1;
645             } else if (!block0->cpl_in_use) {
646                 new_coords = 1;
647             } else {
648                 for (ch = 1; ch <= s->fbw_channels; ch++) {
649                     if (block->channel_in_cpl[ch] && !block0->channel_in_cpl[ch]) {
650                         new_coords = 1;
651                         break;
652                     }
653                 }
654                 if (!new_coords) {
655                     for (ch = 1; ch <= s->fbw_channels; ch++) {
656                         if (block->channel_in_cpl[ch] && coord_diff[ch] > 0.04) {
657                             new_coords = 1;
658                             break;
659                         }
660                     }
661                 }
662             }
663         }
664         block->new_cpl_coords = new_coords;
665     }
666
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++) {
670         blk = 0;
671         while (blk < AC3_MAX_BLOCKS) {
672             int blk1;
673             CoefSumType energy_cpl;
674             AC3Block *block  = &s->blocks[blk];
675
676             if (!block->cpl_in_use) {
677                 blk++;
678                 continue;
679             }
680
681             energy_cpl = energy[blk][CPL_CH][bnd];
682             blk1 = blk+1;
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];
686                 blk1++;
687             }
688
689             for (ch = 1; ch <= s->fbw_channels; ch++) {
690                 CoefType energy_ch;
691                 if (!block->channel_in_cpl[ch])
692                     continue;
693                 energy_ch = energy[blk][ch][bnd];
694                 blk1 = blk+1;
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];
698                     blk1++;
699                 }
700                 cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy_ch, energy_cpl);
701             }
702             blk = blk1;
703         }
704     }
705
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)
710             continue;
711
712         s->ac3dsp.float_to_fixed24(fixed_cpl_coords[blk][1],
713                                    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);
718
719         for (ch = 1; ch <= s->fbw_channels; ch++) {
720             int bnd, min_exp, max_exp, master_exp;
721
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);
728             }
729             master_exp = ((max_exp - 15) + 2) / 3;
730             master_exp = FFMAX(master_exp, 0);
731             while (min_exp < master_exp * 3)
732                 master_exp--;
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);
736             }
737             block->cpl_master_exp[ch] = master_exp;
738
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;
743                 if (cpl_exp == 15)
744                     cpl_mant >>= 1;
745                 else
746                     cpl_mant -= 16;
747
748                 block->cpl_coord_mant[ch][bnd] = cpl_mant;
749             }
750         }
751     }
752 #endif /* CONFIG_AC3ENC_FLOAT */
753 }
754
755
756 /**
757  * Determine rematrixing flags for each block and band.
758  */
759 static void compute_rematrixing_strategy(AC3EncodeContext *s)
760 {
761     int nb_coefs;
762     int blk, bnd, i;
763     AC3Block *block, *block0;
764
765     if (s->channel_mode != AC3_CHMODE_STEREO)
766         return;
767
768     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
769         block = &s->blocks[blk];
770         block->new_rematrixing_strategy = !blk;
771
772         if (!s->rematrixing_enabled) {
773             block0 = block;
774             continue;
775         }
776
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;
783         }
784         nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
785
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);
800             }
801
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;
805             else
806                 block->rematrixing_flags[bnd] = 0;
807
808             /* determine if new rematrixing flags will be sent */
809             if (blk &&
810                 block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
811                 block->new_rematrixing_strategy = 1;
812             }
813         }
814         block0 = block;
815     }
816 }
817
818
819 /**
820  * Apply stereo rematrixing to coefficients based on rematrixing flags.
821  */
822 static void apply_rematrixing(AC3EncodeContext *s)
823 {
824     int nb_coefs;
825     int blk, bnd, i;
826     int start, end;
827     uint8_t *flags;
828
829     if (!s->rematrixing_enabled)
830         return;
831
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++) {
838             if (flags[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;
846                 }
847             }
848         }
849     }
850 }
851
852
853 /**
854  * Initialize exponent tables.
855  */
856 static av_cold void exponent_init(AC3EncodeContext *s)
857 {
858     int expstr, i, grpsize;
859
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;
865         }
866     }
867     /* LFE */
868     exponent_group_tab[0][0][7] = 2;
869 }
870
871
872 /**
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.
876  */
877 static void extract_exponents(AC3EncodeContext *s)
878 {
879     int blk, ch;
880
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],
885                                         AC3_MAX_COEFS);
886         }
887     }
888 }
889
890
891 /**
892  * Exponent Difference Threshold.
893  * New exponents are sent if their SAD exceed this number.
894  */
895 #define EXP_DIFF_THRESHOLD 500
896
897
898 /**
899  * Calculate exponent strategies for all channels.
900  * Array arrangement is reversed to simplify the per-channel calculation.
901  */
902 static void compute_exp_strategy(AC3EncodeContext *s)
903 {
904     int ch, blk, blk1;
905
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];
909         int exp_diff;
910
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;
919                 continue;
920             }
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;
927         }
928
929         /* now select the encoding strategy type : if exponents are often
930            recoded, we use a coarse encoding */
931         blk = 0;
932         while (blk < AC3_MAX_BLOCKS) {
933             blk1 = blk + 1;
934             while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
935                 blk1++;
936             switch (blk1 - blk) {
937             case 1:  exp_strategy[blk] = EXP_D45; break;
938             case 2:
939             case 3:  exp_strategy[blk] = EXP_D25; break;
940             default: exp_strategy[blk] = EXP_D15; break;
941             }
942             blk = blk1;
943         }
944     }
945     if (s->lfe_on) {
946         ch = s->lfe_channel;
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;
950     }
951 }
952
953
954 /**
955  * Update the exponents so that they are the ones the decoder will decode.
956  */
957 static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy,
958                                     int cpl)
959 {
960     int nb_groups, i, k;
961
962     nb_groups = exponent_group_tab[cpl][exp_strategy-1][nb_exps] * 3;
963
964     /* for each group, compute the minimum exponent */
965     switch(exp_strategy) {
966     case EXP_D25:
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)
970                 exp_min = exp[k+1];
971             exp[i-cpl] = exp_min;
972             k += 2;
973         }
974         break;
975     case EXP_D45:
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)
979                 exp_min = exp[k+1];
980             if (exp[k+2] < exp_min)
981                 exp_min = exp[k+2];
982             if (exp[k+3] < exp_min)
983                 exp_min = exp[k+3];
984             exp[i-cpl] = exp_min;
985             k += 4;
986         }
987         break;
988     }
989
990     /* constraint for DC exponent */
991     if (!cpl && exp[0] > 15)
992         exp[0] = 15;
993
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);
998     i--;
999     while (--i >= 0)
1000         exp[i] = FFMIN(exp[i], exp[i+1] + 2);
1001
1002     if (cpl)
1003         exp[-1] = exp[0] & ~1;
1004
1005     /* now we have the exponent values the decoder will see */
1006     switch (exp_strategy) {
1007     case EXP_D25:
1008         for (i = nb_groups, k = (nb_groups * 2)-cpl; i > 0; i--) {
1009             uint8_t exp1 = exp[i-cpl];
1010             exp[k--] = exp1;
1011             exp[k--] = exp1;
1012         }
1013         break;
1014     case EXP_D45:
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];
1017             k -= 4;
1018         }
1019         break;
1020     }
1021 }
1022
1023
1024 /**
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
1028  * encoded.
1029  */
1030 static void encode_exponents(AC3EncodeContext *s)
1031 {
1032     int blk, blk1, ch, cpl;
1033     uint8_t *exp, *exp_strategy;
1034     int nb_coefs, num_reuse_blocks;
1035
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];
1039
1040         cpl = (ch == CPL_CH);
1041         blk = 0;
1042         while (blk < AC3_MAX_BLOCKS) {
1043             AC3Block *block = &s->blocks[blk];
1044             if (cpl && !block->cpl_in_use) {
1045                 exp += AC3_MAX_COEFS;
1046                 blk++;
1047                 continue;
1048             }
1049             nb_coefs = block->end_freq[ch] - s->start_freq[ch];
1050             blk1 = blk + 1;
1051
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;
1057                 blk1++;
1058             }
1059             num_reuse_blocks = blk1 - blk - 1;
1060
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,
1063                                        AC3_MAX_COEFS);
1064
1065             encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk], cpl);
1066
1067             exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
1068             blk = blk1;
1069         }
1070     }
1071 }
1072
1073
1074 /**
1075  * Group exponents.
1076  * 3 delta-encoded exponents are in each 7-bit group. The number of groups
1077  * varies depending on exponent strategy and bandwidth.
1078  */
1079 static void group_exponents(AC3EncodeContext *s)
1080 {
1081     int blk, ch, i, cpl;
1082     int group_size, nb_groups, bit_count;
1083     uint8_t *p;
1084     int delta0, delta1, delta2;
1085     int exp0, exp1;
1086
1087     bit_count = 0;
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)
1093                 continue;
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;
1099
1100             /* DC exponent */
1101             exp1 = *p++;
1102             block->grouped_exp[ch][0] = exp1;
1103
1104             /* remaining exponents are delta encoded */
1105             for (i = 1; i <= nb_groups; i++) {
1106                 /* merge three delta in one code */
1107                 exp0   = exp1;
1108                 exp1   = p[0];
1109                 p     += group_size;
1110                 delta0 = exp1 - exp0 + 2;
1111                 av_assert2(delta0 >= 0 && delta0 <= 4);
1112
1113                 exp0   = exp1;
1114                 exp1   = p[0];
1115                 p     += group_size;
1116                 delta1 = exp1 - exp0 + 2;
1117                 av_assert2(delta1 >= 0 && delta1 <= 4);
1118
1119                 exp0   = exp1;
1120                 exp1   = p[0];
1121                 p     += group_size;
1122                 delta2 = exp1 - exp0 + 2;
1123                 av_assert2(delta2 >= 0 && delta2 <= 4);
1124
1125                 block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
1126             }
1127         }
1128     }
1129
1130     s->exponent_bits = bit_count;
1131 }
1132
1133
1134 /**
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.
1138  */
1139 static void process_exponents(AC3EncodeContext *s)
1140 {
1141     extract_exponents(s);
1142
1143     compute_exp_strategy(s);
1144
1145     encode_exponents(s);
1146
1147     group_exponents(s);
1148
1149     emms_c();
1150 }
1151
1152
1153 /**
1154  * Count frame bits that are based solely on fixed parameters.
1155  * This only has to be run once when the encoder is initialized.
1156  */
1157 static void count_frame_bits_fixed(AC3EncodeContext *s)
1158 {
1159     static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
1160     int blk;
1161     int frame_bits;
1162
1163     /* assumptions:
1164      *   no dynamic range codes
1165      *   bit allocation parameters do not change between blocks
1166      *   no delta bit allocation
1167      *   no skipped data
1168      *   no auxilliary data
1169      */
1170
1171     /* header */
1172     frame_bits = 65;
1173     frame_bits += frame_bits_inc[s->channel_mode];
1174
1175     /* audio blocks */
1176     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1177         /* block switch flags */
1178         frame_bits += s->fbw_channels;
1179
1180         /* dither flags */
1181         frame_bits += s->fbw_channels;
1182
1183         /* dynamic range */
1184         frame_bits++;
1185
1186         /* exponent strategy */
1187         frame_bits += 2 * s->fbw_channels;
1188         if (s->lfe_on)
1189             frame_bits++;
1190
1191         /* bit allocation params */
1192         frame_bits++;
1193         if (!blk)
1194             frame_bits += 2 + 2 + 2 + 2 + 3;
1195
1196         /* delta bit allocation */
1197         frame_bits++;
1198
1199         /* skipped data */
1200         frame_bits++;
1201     }
1202
1203     /* auxiliary data */
1204     frame_bits++;
1205
1206     /* CRC */
1207     frame_bits += 1 + 16;
1208
1209     s->frame_bits_fixed = frame_bits;
1210 }
1211
1212
1213 /**
1214  * Initialize bit allocation.
1215  * Set default parameter codes and calculate parameter values.
1216  */
1217 static void bit_alloc_init(AC3EncodeContext *s)
1218 {
1219     int ch;
1220
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;
1226     s->floor_code      = 7;
1227     for (ch = 0; ch <= s->channels; ch++)
1228         s->fast_gain_code[ch] = 4;
1229
1230     /* initial snr offset */
1231     s->coarse_snr_offset = 40;
1232
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;
1243
1244     count_frame_bits_fixed(s);
1245 }
1246
1247
1248 /**
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.
1252  */
1253 static void count_frame_bits(AC3EncodeContext *s)
1254 {
1255     AC3EncOptions *opt = &s->options;
1256     int blk, ch;
1257     int frame_bits = 0;
1258
1259     /* header */
1260     if (opt->audio_production_info)
1261         frame_bits += 7;
1262     if (s->bitstream_id == 6) {
1263         if (opt->extended_bsi_1)
1264             frame_bits += 14;
1265         if (opt->extended_bsi_2)
1266             frame_bits += 14;
1267     }
1268
1269     /* audio blocks */
1270     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1271         AC3Block *block = &s->blocks[blk];
1272
1273         /* coupling strategy */
1274         frame_bits++;
1275         if (block->new_cpl_strategy) {
1276             frame_bits++;
1277             if (block->cpl_in_use) {
1278                 frame_bits += s->fbw_channels;
1279                 if (s->channel_mode == AC3_CHMODE_STEREO)
1280                     frame_bits++;
1281                 frame_bits += 4 + 4;
1282                 frame_bits += s->num_cpl_subbands - 1;
1283             }
1284         }
1285
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]) {
1290                     frame_bits++;
1291                     if (block->new_cpl_coords) {
1292                         frame_bits += 2;
1293                         frame_bits += (4 + 4) * s->num_cpl_bands;
1294                     }
1295                 }
1296             }
1297         }
1298
1299         /* stereo rematrixing */
1300         if (s->channel_mode == AC3_CHMODE_STEREO) {
1301             frame_bits++;
1302             if (s->blocks[blk].new_rematrixing_strategy)
1303                 frame_bits += block->num_rematrixing_bands;
1304         }
1305
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])
1310                     frame_bits += 6;
1311                 frame_bits += 2;
1312             }
1313         }
1314
1315         /* coupling exponent strategy */
1316         if (block->cpl_in_use)
1317             frame_bits += 2;
1318
1319         /* snr offsets and fast gain codes */
1320         frame_bits++;
1321         if (block->new_snr_offsets)
1322             frame_bits += 6 + (s->channels + block->cpl_in_use) * (4 + 3);
1323
1324         /* coupling leak info */
1325         if (block->cpl_in_use) {
1326             frame_bits++;
1327             if (block->new_cpl_leak)
1328                 frame_bits += 3 + 3;
1329         }
1330     }
1331
1332     s->frame_bits = s->frame_bits_fixed + frame_bits;
1333 }
1334
1335
1336 /**
1337  * Finalize the mantissa bit count by adding in the grouped mantissas.
1338  */
1339 static int compute_mantissa_size_final(int mant_cnt[5])
1340 {
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;
1348     return bits;
1349 }
1350
1351
1352 /**
1353  * Calculate masking curve based on the final exponents.
1354  * Also calculate the power spectral densities to use in future calculations.
1355  */
1356 static void bit_alloc_masking(AC3EncodeContext *s)
1357 {
1358     int blk, ch;
1359
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,
1375                                            block->mask[ch]);
1376             }
1377         }
1378     }
1379 }
1380
1381
1382 /**
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.
1385  */
1386 static void reset_block_bap(AC3EncodeContext *s)
1387 {
1388     int blk, ch;
1389     int channels = s->channels + 1;
1390     if (s->blocks[0].bap[0] == s->bap_buffer)
1391         return;
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)];
1395         }
1396     }
1397 }
1398
1399
1400 /**
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
1405  *         is used.
1406  */
1407 static int bit_alloc(AC3EncodeContext *s, int snr_offset)
1408 {
1409     int blk, ch;
1410     int mantissa_bits;
1411     int mant_cnt[5];
1412
1413     snr_offset = (snr_offset - 240) << 2;
1414
1415     reset_block_bap(s);
1416     mantissa_bits = 0;
1417     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1418         AC3Block *block = &s->blocks[blk];
1419         AC3Block *ref_block;
1420         int av_uninit(ch0);
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;
1427         mant_cnt[4] = 1;
1428         for (ch = 1; ch <= s->channels; ch++) {
1429             if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1430                 ch0     = ch - 1;
1431                 ch      = CPL_CH;
1432                 got_cpl = 1;
1433             }
1434
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]);
1445             }
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]);
1449             if (ch == CPL_CH)
1450                 ch = ch0;
1451         }
1452         mantissa_bits += compute_mantissa_size_final(mant_cnt);
1453     }
1454     return mantissa_bits;
1455 }
1456
1457
1458 /**
1459  * Constant bitrate bit allocation search.
1460  * Find the largest SNR offset that will allow data to fit in the frame.
1461  */
1462 static int cbr_bit_allocation(AC3EncodeContext *s)
1463 {
1464     int ch;
1465     int bits_left;
1466     int snr_offset, snr_incr;
1467
1468     bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1469     if (bits_left < 0)
1470         return AVERROR(EINVAL);
1471
1472     snr_offset = s->coarse_snr_offset << 4;
1473
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)
1478             return 0;
1479     }
1480
1481     while (snr_offset >= 0 &&
1482            bit_alloc(s, snr_offset) > bits_left) {
1483         snr_offset -= 64;
1484     }
1485     if (snr_offset < 0)
1486         return AVERROR(EINVAL);
1487
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);
1494         }
1495     }
1496     FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1497     reset_block_bap(s);
1498
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;
1502
1503     return 0;
1504 }
1505
1506
1507 /**
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
1513  */
1514 static int downgrade_exponents(AC3EncodeContext *s)
1515 {
1516     int ch, blk;
1517
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;
1522                 return 0;
1523             }
1524         }
1525     }
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;
1530                 return 0;
1531             }
1532         }
1533     }
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;
1540                 return 0;
1541             }
1542         }
1543     }
1544     return -1;
1545 }
1546
1547
1548 /**
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.
1553  */
1554 static int compute_bit_allocation(AC3EncodeContext *s)
1555 {
1556     int ret;
1557
1558     count_frame_bits(s);
1559
1560     bit_alloc_masking(s);
1561
1562     ret = cbr_bit_allocation(s);
1563     while (ret) {
1564         /* fallback 1: disable channel coupling */
1565         if (s->cpl_on) {
1566             s->cpl_on = 0;
1567             compute_coupling_strategy(s);
1568             compute_rematrixing_strategy(s);
1569             apply_rematrixing(s);
1570             process_exponents(s);
1571             ret = compute_bit_allocation(s);
1572             continue;
1573         }
1574
1575         /* fallback 2: downgrade exponents */
1576         if (!downgrade_exponents(s)) {
1577             extract_exponents(s);
1578             encode_exponents(s);
1579             group_exponents(s);
1580             ret = compute_bit_allocation(s);
1581             continue;
1582         }
1583
1584         /* fallbacks were not enough... */
1585         break;
1586     }
1587
1588     return ret;
1589 }
1590
1591
1592 /**
1593  * Symmetric quantization on 'levels' levels.
1594  */
1595 static inline int sym_quant(int c, int e, int levels)
1596 {
1597     int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1598     av_assert2(v >= 0 && v < levels);
1599     return v;
1600 }
1601
1602
1603 /**
1604  * Asymmetric quantization on 2^qbits levels.
1605  */
1606 static inline int asym_quant(int c, int e, int qbits)
1607 {
1608     int lshift, m, v;
1609
1610     lshift = e + qbits - 24;
1611     if (lshift >= 0)
1612         v = c << lshift;
1613     else
1614         v = c >> (-lshift);
1615     /* rounding */
1616     v = (v + 1) >> 1;
1617     m = (1 << (qbits-1));
1618     if (v >= m)
1619         v = m - 1;
1620     av_assert2(v >= -m);
1621     return v & ((1 << qbits)-1);
1622 }
1623
1624
1625 /**
1626  * Quantize a set of mantissas for a single channel in a single block.
1627  */
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,
1631                                       int end_freq)
1632 {
1633     int i;
1634
1635     for (i = start_freq; i < end_freq; i++) {
1636         int v;
1637         int c = fixed_coef[i];
1638         int e = exp[i];
1639         int b = bap[i];
1640         switch (b) {
1641         case 0:
1642             v = 0;
1643             break;
1644         case 1:
1645             v = sym_quant(c, e, 3);
1646             switch (s->mant1_cnt) {
1647             case 0:
1648                 s->qmant1_ptr = &qmant[i];
1649                 v = 9 * v;
1650                 s->mant1_cnt = 1;
1651                 break;
1652             case 1:
1653                 *s->qmant1_ptr += 3 * v;
1654                 s->mant1_cnt = 2;
1655                 v = 128;
1656                 break;
1657             default:
1658                 *s->qmant1_ptr += v;
1659                 s->mant1_cnt = 0;
1660                 v = 128;
1661                 break;
1662             }
1663             break;
1664         case 2:
1665             v = sym_quant(c, e, 5);
1666             switch (s->mant2_cnt) {
1667             case 0:
1668                 s->qmant2_ptr = &qmant[i];
1669                 v = 25 * v;
1670                 s->mant2_cnt = 1;
1671                 break;
1672             case 1:
1673                 *s->qmant2_ptr += 5 * v;
1674                 s->mant2_cnt = 2;
1675                 v = 128;
1676                 break;
1677             default:
1678                 *s->qmant2_ptr += v;
1679                 s->mant2_cnt = 0;
1680                 v = 128;
1681                 break;
1682             }
1683             break;
1684         case 3:
1685             v = sym_quant(c, e, 7);
1686             break;
1687         case 4:
1688             v = sym_quant(c, e, 11);
1689             switch (s->mant4_cnt) {
1690             case 0:
1691                 s->qmant4_ptr = &qmant[i];
1692                 v = 11 * v;
1693                 s->mant4_cnt = 1;
1694                 break;
1695             default:
1696                 *s->qmant4_ptr += v;
1697                 s->mant4_cnt = 0;
1698                 v = 128;
1699                 break;
1700             }
1701             break;
1702         case 5:
1703             v = sym_quant(c, e, 15);
1704             break;
1705         case 14:
1706             v = asym_quant(c, e, 14);
1707             break;
1708         case 15:
1709             v = asym_quant(c, e, 16);
1710             break;
1711         default:
1712             v = asym_quant(c, e, b - 1);
1713             break;
1714         }
1715         qmant[i] = v;
1716     }
1717 }
1718
1719
1720 /**
1721  * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1722  */
1723 static void quantize_mantissas(AC3EncodeContext *s)
1724 {
1725     int blk, ch, ch0=0, got_cpl;
1726
1727     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1728         AC3Block *block = &s->blocks[blk];
1729         AC3Block *ref_block;
1730         AC3Mant m = { 0 };
1731
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]) {
1735                 ch0     = ch - 1;
1736                 ch      = CPL_CH;
1737                 got_cpl = 1;
1738             }
1739             ref_block = block->exp_ref_block[ch];
1740             quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1741                                       ref_block->exp[ch],
1742                                       ref_block->bap[ch], block->qmant[ch],
1743                                       s->start_freq[ch], block->end_freq[ch]);
1744             if (ch == CPL_CH)
1745                 ch = ch0;
1746         }
1747     }
1748 }
1749
1750
1751 /**
1752  * Write the AC-3 frame header to the output bitstream.
1753  */
1754 static void output_frame_header(AC3EncodeContext *s)
1755 {
1756     AC3EncOptions *opt = &s->options;
1757
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);
1779     }
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);
1791         }
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 */
1798         }
1799     } else {
1800     put_bits(&s->pb, 1, 0);         /* no time code 1 */
1801     put_bits(&s->pb, 1, 0);         /* no time code 2 */
1802     }
1803     put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
1804 }
1805
1806
1807 /**
1808  * Write one audio block to the output bitstream.
1809  */
1810 static void output_audio_block(AC3EncodeContext *s, int blk)
1811 {
1812     int ch, i, baie, bnd, got_cpl;
1813     int av_uninit(ch0);
1814     AC3Block *block = &s->blocks[blk];
1815
1816     /* block switching */
1817     for (ch = 0; ch < s->fbw_channels; ch++)
1818         put_bits(&s->pb, 1, 0);
1819
1820     /* dither flags */
1821     for (ch = 0; ch < s->fbw_channels; ch++)
1822         put_bits(&s->pb, 1, 1);
1823
1824     /* dynamic range codes */
1825     put_bits(&s->pb, 1, 0);
1826
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]);
1843         }
1844     }
1845
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]);
1856                     }
1857                 }
1858             }
1859         }
1860     }
1861
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]);
1869         }
1870     }
1871
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]);
1875     if (s->lfe_on)
1876         put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1877
1878     /* bandwidth */
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);
1882     }
1883
1884     /* exponents */
1885     for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1886         int nb_groups;
1887         int cpl = (ch == CPL_CH);
1888
1889         if (s->exp_strategy[ch][blk] == EXP_REUSE)
1890             continue;
1891
1892         /* DC exponent */
1893         put_bits(&s->pb, 4, block->grouped_exp[ch][0] >> cpl);
1894
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]);
1899
1900         /* gain range info */
1901         if (ch != s->lfe_channel && !cpl)
1902             put_bits(&s->pb, 2, 0);
1903     }
1904
1905     /* bit allocation info */
1906     baie = (blk == 0);
1907     put_bits(&s->pb, 1, baie);
1908     if (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);
1914     }
1915
1916     /* snr offset */
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]);
1923         }
1924     }
1925
1926     /* coupling leak */
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);
1932         }
1933     }
1934
1935     put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1936     put_bits(&s->pb, 1, 0); /* no data to skip */
1937
1938     /* mantissas */
1939     got_cpl = !block->cpl_in_use;
1940     for (ch = 1; ch <= s->channels; ch++) {
1941         int b, q;
1942         AC3Block *ref_block;
1943
1944         if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1945             ch0     = ch - 1;
1946             ch      = CPL_CH;
1947             got_cpl = 1;
1948         }
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];
1953             switch (b) {
1954             case 0:                                         break;
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;
1962             }
1963         }
1964         if (ch == CPL_CH)
1965             ch = ch0;
1966     }
1967 }
1968
1969
1970 /** CRC-16 Polynomial */
1971 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1972
1973
1974 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1975 {
1976     unsigned int c;
1977
1978     c = 0;
1979     while (a) {
1980         if (a & 1)
1981             c ^= b;
1982         a = a >> 1;
1983         b = b << 1;
1984         if (b & (1 << 16))
1985             b ^= poly;
1986     }
1987     return c;
1988 }
1989
1990
1991 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1992 {
1993     unsigned int r;
1994     r = 1;
1995     while (n) {
1996         if (n & 1)
1997             r = mul_poly(r, a, poly);
1998         a = mul_poly(a, a, poly);
1999         n >>= 1;
2000     }
2001     return r;
2002 }
2003
2004
2005 /**
2006  * Fill the end of the frame with 0's and compute the two CRCs.
2007  */
2008 static void output_frame_end(AC3EncodeContext *s)
2009 {
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;
2012     uint8_t *frame;
2013
2014     frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
2015
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);
2019     frame = s->pb.buf;
2020     pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
2021     av_assert2(pad_bytes >= 0);
2022     if (pad_bytes > 0)
2023         memset(put_bits_ptr(&s->pb), 0, pad_bytes);
2024
2025     /* compute crc1 */
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);
2031
2032     /* compute crc2 */
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);
2040     }
2041     crc2 = av_bswap16(crc2);
2042     AV_WB16(frame + s->frame_size - 2, crc2);
2043 }
2044
2045
2046 /**
2047  * Write the frame to the output bitstream.
2048  */
2049 static void output_frame(AC3EncodeContext *s, unsigned char *frame)
2050 {
2051     int blk;
2052
2053     init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
2054
2055     output_frame_header(s);
2056
2057     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2058         output_audio_block(s, blk);
2059
2060     output_frame_end(s);
2061 }
2062
2063
2064 static void dprint_options(AVCodecContext *avctx)
2065 {
2066 #ifdef DEBUG
2067     AC3EncodeContext *s = avctx->priv_data;
2068     AC3EncOptions *opt = &s->options;
2069     char strbuf[32];
2070
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");
2077     }
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);
2084     if (s->cutoff)
2085         av_dlog(avctx, "cutoff: %d\n", s->cutoff);
2086
2087     av_dlog(avctx, "per_frame_metadata: %s\n",
2088             opt->allow_per_frame_metadata?"on":"off");
2089     if (s->has_center)
2090         av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
2091                 s->center_mix_level);
2092     else
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);
2097     else
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);
2106         }
2107         av_dlog(avctx, "room_type: %s\n", strbuf);
2108     } else {
2109         av_dlog(avctx, "mixing_level: {not written}\n");
2110         av_dlog(avctx, "room_type: {not written}\n");
2111     }
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);
2120         }
2121         av_dlog(avctx, "dsur_mode: %s\n", strbuf);
2122     } else {
2123         av_dlog(avctx, "dsur_mode: {not written}\n");
2124     }
2125     av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
2126
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);
2134             }
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);
2144         } else {
2145             av_dlog(avctx, "extended bitstream info 1: {not written}\n");
2146         }
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);
2153             }
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);
2160             }
2161             av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
2162
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);
2167             }
2168             av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
2169         } else {
2170             av_dlog(avctx, "extended bitstream info 2: {not written}\n");
2171         }
2172     }
2173 #endif
2174 }
2175
2176
2177 #define FLT_OPTION_THRESHOLD 0.01
2178
2179 static int validate_float_option(float v, const float *v_list, int v_list_size)
2180 {
2181     int i;
2182
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))
2186             break;
2187     }
2188     if (i == v_list_size)
2189         return -1;
2190
2191     return i;
2192 }
2193
2194
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,
2198                                int *ctx_param)
2199 {
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]);
2206         }
2207     }
2208     *opt_param = list[mixlev];
2209     *ctx_param = mixlev;
2210 }
2211
2212
2213 /**
2214  * Validate metadata options as set by AVOption system.
2215  * These values can optionally be changed per-frame.
2216  */
2217 static int validate_metadata(AVCodecContext *avctx)
2218 {
2219     AC3EncodeContext *s = avctx->priv_data;
2220     AC3EncOptions *opt = &s->options;
2221
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);
2227     }
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);
2232     }
2233
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);
2240         }
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);
2245         }
2246         /* default room type */
2247         if (opt->room_type < 0)
2248             opt->room_type = 0;
2249         opt->audio_production_info = 1;
2250     } else {
2251         opt->audio_production_info = 0;
2252     }
2253
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;
2285     } else {
2286         opt->extended_bsi_1 = 0;
2287     }
2288
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;
2303     } else {
2304         opt->extended_bsi_2 = 0;
2305     }
2306
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;
2311             if (warn_once) {
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");
2315                 warn_once = 0;
2316             }
2317         } else {
2318             s->bitstream_id = 6;
2319         }
2320     }
2321
2322     return 0;
2323 }
2324
2325
2326 /**
2327  * Encode a single AC-3 frame.
2328  */
2329 static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
2330                             int buf_size, void *data)
2331 {
2332     AC3EncodeContext *s = avctx->priv_data;
2333     const SampleType *samples = data;
2334     int ret;
2335
2336     if (s->options.allow_per_frame_metadata) {
2337         ret = validate_metadata(avctx);
2338         if (ret)
2339             return ret;
2340     }
2341
2342     if (s->bit_alloc.sr_code == 1)
2343         adjust_frame_size(s);
2344
2345     deinterleave_input_samples(s, samples);
2346
2347     apply_mdct(s);
2348
2349     scale_coefficients(s);
2350
2351     s->cpl_on = s->cpl_enabled;
2352     compute_coupling_strategy(s);
2353
2354     if (s->cpl_on)
2355         apply_channel_coupling(s);
2356
2357     compute_rematrixing_strategy(s);
2358
2359     apply_rematrixing(s);
2360
2361     process_exponents(s);
2362
2363     ret = compute_bit_allocation(s);
2364     if (ret) {
2365         av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
2366         return ret;
2367     }
2368
2369     quantize_mantissas(s);
2370
2371     output_frame(s, frame);
2372
2373     return s->frame_size;
2374 }
2375
2376
2377 /**
2378  * Finalize encoding and free any memory allocated by the encoder.
2379  */
2380 static av_cold int ac3_encode_close(AVCodecContext *avctx)
2381 {
2382     int blk, ch;
2383     AC3EncodeContext *s = avctx->priv_data;
2384
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);
2409     }
2410
2411     mdct_end(&s->mdct);
2412
2413     av_freep(&avctx->coded_frame);
2414     return 0;
2415 }
2416
2417
2418 /**
2419  * Set channel information during initialization.
2420  */
2421 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
2422                                     int64_t *channel_layout)
2423 {
2424     int ch_layout;
2425
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;
2431     if (!ch_layout)
2432         ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
2433
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;
2438     if (s->lfe_on)
2439         ch_layout -= AV_CH_LOW_FREQUENCY;
2440
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;
2451     default:
2452         return AVERROR(EINVAL);
2453     }
2454     s->has_center   = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
2455     s->has_surround =  s->channel_mode & 0x04;
2456
2457     s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
2458     *channel_layout = ch_layout;
2459     if (s->lfe_on)
2460         *channel_layout |= AV_CH_LOW_FREQUENCY;
2461
2462     return 0;
2463 }
2464
2465
2466 static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
2467 {
2468     int i, ret;
2469
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");
2475     }
2476     ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
2477     if (ret) {
2478         av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
2479         return ret;
2480     }
2481
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)
2485             break;
2486     }
2487     if (i == 9) {
2488         av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
2489         return AVERROR(EINVAL);
2490     }
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;
2495
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)
2499             break;
2500     }
2501     if (i == 19) {
2502         av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2503         return AVERROR(EINVAL);
2504     }
2505     s->bit_rate        = avctx->bit_rate;
2506     s->frame_size_code = i << 1;
2507
2508     /* validate cutoff */
2509     if (avctx->cutoff < 0) {
2510         av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2511         return AVERROR(EINVAL);
2512     }
2513     s->cutoff = avctx->cutoff;
2514     if (s->cutoff > (s->sample_rate >> 1))
2515         s->cutoff = s->sample_rate >> 1;
2516
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);
2527     }
2528
2529     ret = validate_metadata(avctx);
2530     if (ret)
2531         return ret;
2532
2533     s->rematrixing_enabled = s->options.stereo_rematrixing &&
2534                              (s->channel_mode == AC3_CHMODE_STEREO);
2535
2536     s->cpl_enabled = s->options.channel_coupling &&
2537                      s->channel_mode >= AC3_CHMODE_STEREO &&
2538                      CONFIG_AC3ENC_FLOAT;
2539
2540     return 0;
2541 }
2542
2543
2544 /**
2545  * Set bandwidth for all channels.
2546  * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2547  * default value will be used.
2548  */
2549 static av_cold void set_bandwidth(AC3EncodeContext *s)
2550 {
2551     int blk, ch;
2552     int av_uninit(cpl_start);
2553
2554     if (s->cutoff) {
2555         /* calculate bandwidth based on user-specified cutoff frequency */
2556         int fbw_coeffs;
2557         fbw_coeffs     = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2558         s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2559     } else {
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];
2562     }
2563
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;
2569     }
2570     /* LFE channel always has 7 coefs */
2571     if (s->lfe_on) {
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;
2575     }
2576
2577     /* initialize coupling strategy */
2578     if (s->cpl_enabled) {
2579         if (s->options.cpl_start >= 0) {
2580             cpl_start = s->options.cpl_start;
2581         } else {
2582             cpl_start = ac3_coupling_start_tab[s->channel_mode-2][s->bit_alloc.sr_code][s->frame_size_code/2];
2583             if (cpl_start < 0)
2584                 s->cpl_enabled = 0;
2585         }
2586     }
2587     if (s->cpl_enabled) {
2588         int i, cpl_start_band, cpl_end_band;
2589         uint8_t *cpl_band_sizes = s->cpl_band_sizes;
2590
2591         cpl_end_band   = s->bandwidth_code / 4 + 3;
2592         cpl_start_band = av_clip(cpl_start, 0, FFMIN(cpl_end_band-1, 15));
2593
2594         s->num_cpl_subbands = cpl_end_band - cpl_start_band;
2595
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;
2601             } else {
2602                 s->num_cpl_bands++;
2603                 cpl_band_sizes++;
2604                 *cpl_band_sizes = 12;
2605             }
2606         }
2607
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;
2612     }
2613 }
2614
2615
2616 static av_cold int allocate_buffers(AVCodecContext *avctx)
2617 {
2618     int blk, ch;
2619     AC3EncodeContext *s = avctx->priv_data;
2620     int channels = s->channels + 1; /* includes coupling channel */
2621
2622     FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
2623                      alloc_fail);
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),
2627                           alloc_fail);
2628     }
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);
2652     }
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),
2656                          alloc_fail);
2657         FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, channels * sizeof(*block->mdct_coef),
2658                           alloc_fail);
2659         FF_ALLOCZ_OR_GOTO(avctx, block->exp, channels * sizeof(*block->exp),
2660                           alloc_fail);
2661         FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, channels * sizeof(*block->grouped_exp),
2662                           alloc_fail);
2663         FF_ALLOCZ_OR_GOTO(avctx, block->psd, channels * sizeof(*block->psd),
2664                           alloc_fail);
2665         FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, channels * sizeof(*block->band_psd),
2666                           alloc_fail);
2667         FF_ALLOCZ_OR_GOTO(avctx, block->mask, channels * sizeof(*block->mask),
2668                           alloc_fail);
2669         FF_ALLOCZ_OR_GOTO(avctx, block->qmant, channels * sizeof(*block->qmant),
2670                           alloc_fail);
2671         if (s->cpl_enabled) {
2672             FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_exp, channels * sizeof(*block->cpl_coord_exp),
2673                               alloc_fail);
2674             FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_mant, channels * sizeof(*block->cpl_coord_mant),
2675                               alloc_fail);
2676         }
2677
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)];
2689             }
2690
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)];
2694         }
2695     }
2696
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)];
2706         }
2707     } else {
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];
2714         }
2715     }
2716
2717     return 0;
2718 alloc_fail:
2719     return AVERROR(ENOMEM);
2720 }
2721
2722
2723 /**
2724  * Initialize the encoder.
2725  */
2726 static av_cold int ac3_encode_init(AVCodecContext *avctx)
2727 {
2728     AC3EncodeContext *s = avctx->priv_data;
2729     int ret, frame_size_58;
2730
2731     avctx->frame_size = AC3_FRAME_SIZE;
2732
2733     ff_ac3_common_init();
2734
2735     ret = validate_options(avctx, s);
2736     if (ret)
2737         return ret;
2738
2739     s->bitstream_mode = avctx->audio_service_type;
2740     if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2741         s->bitstream_mode = 0x7;
2742
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;
2747
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);
2754     }
2755
2756     set_bandwidth(s);
2757
2758     exponent_init(s);
2759
2760     bit_alloc_init(s);
2761
2762     ret = mdct_init(avctx, &s->mdct, 9);
2763     if (ret)
2764         goto init_fail;
2765
2766     ret = allocate_buffers(avctx);
2767     if (ret)
2768         goto init_fail;
2769
2770     avctx->coded_frame= avcodec_alloc_frame();
2771
2772     dsputil_init(&s->dsp, avctx);
2773     ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2774
2775     dprint_options(avctx);
2776
2777     return 0;
2778 init_fail:
2779     ac3_encode_close(avctx);
2780     return ret;
2781 }