]> git.sesse.net Git - ffmpeg/blob - libavcodec/ac3enc.c
ac3enc: initialize all coefficients to zero.
[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 Libav.
8  *
9  * Libav is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * Libav is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with Libav; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
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  * Encoding Options used by AVOption.
75  */
76 typedef struct AC3EncOptions {
77     /* AC-3 metadata options*/
78     int dialogue_level;
79     int bitstream_mode;
80     float center_mix_level;
81     float surround_mix_level;
82     int dolby_surround_mode;
83     int audio_production_info;
84     int mixing_level;
85     int room_type;
86     int copyright;
87     int original;
88     int extended_bsi_1;
89     int preferred_stereo_downmix;
90     float ltrt_center_mix_level;
91     float ltrt_surround_mix_level;
92     float loro_center_mix_level;
93     float loro_surround_mix_level;
94     int extended_bsi_2;
95     int dolby_surround_ex_mode;
96     int dolby_headphone_mode;
97     int ad_converter_type;
98
99     /* other encoding options */
100     int allow_per_frame_metadata;
101     int stereo_rematrixing;
102     int channel_coupling;
103     int cpl_start;
104 } AC3EncOptions;
105
106 /**
107  * Data for a single audio block.
108  */
109 typedef struct AC3Block {
110     uint8_t  **bap;                             ///< bit allocation pointers (bap)
111     CoefType **mdct_coef;                       ///< MDCT coefficients
112     int32_t  **fixed_coef;                      ///< fixed-point MDCT coefficients
113     uint8_t  **exp;                             ///< original exponents
114     uint8_t  **grouped_exp;                     ///< grouped exponents
115     int16_t  **psd;                             ///< psd per frequency bin
116     int16_t  **band_psd;                        ///< psd per critical band
117     int16_t  **mask;                            ///< masking curve
118     uint16_t **qmant;                           ///< quantized mantissas
119     uint8_t  **cpl_coord_exp;                   ///< coupling coord exponents           (cplcoexp)
120     uint8_t  **cpl_coord_mant;                  ///< coupling coord mantissas           (cplcomant)
121     uint8_t  coeff_shift[AC3_MAX_CHANNELS];     ///< fixed-point coefficient shift values
122     uint8_t  new_rematrixing_strategy;          ///< send new rematrixing flags in this block
123     int      num_rematrixing_bands;             ///< number of rematrixing bands
124     uint8_t  rematrixing_flags[4];              ///< rematrixing flags
125     struct AC3Block *exp_ref_block[AC3_MAX_CHANNELS]; ///< reference blocks for EXP_REUSE
126     int      new_cpl_strategy;                  ///< send new coupling strategy
127     int      cpl_in_use;                        ///< coupling in use for this block     (cplinu)
128     uint8_t  channel_in_cpl[AC3_MAX_CHANNELS];  ///< channel in coupling                (chincpl)
129     int      num_cpl_channels;                  ///< number of channels in coupling
130     uint8_t  new_cpl_coords;                    ///< send new coupling coordinates      (cplcoe)
131     uint8_t  cpl_master_exp[AC3_MAX_CHANNELS];  ///< coupling coord master exponents    (mstrcplco)
132     int      new_snr_offsets;                   ///< send new SNR offsets
133     int      new_cpl_leak;                      ///< send new coupling leak info
134     int      end_freq[AC3_MAX_CHANNELS];        ///< end frequency bin                  (endmant)
135 } AC3Block;
136
137 /**
138  * AC-3 encoder private context.
139  */
140 typedef struct AC3EncodeContext {
141     AVClass *av_class;                      ///< AVClass used for AVOption
142     AC3EncOptions options;                  ///< encoding options
143     PutBitContext pb;                       ///< bitstream writer context
144     DSPContext dsp;
145     AC3DSPContext ac3dsp;                   ///< AC-3 optimized functions
146     AC3MDCTContext mdct;                    ///< MDCT context
147
148     AC3Block blocks[AC3_MAX_BLOCKS];        ///< per-block info
149
150     int bitstream_id;                       ///< bitstream id                           (bsid)
151     int bitstream_mode;                     ///< bitstream mode                         (bsmod)
152
153     int bit_rate;                           ///< target bit rate, in bits-per-second
154     int sample_rate;                        ///< sampling frequency, in Hz
155
156     int frame_size_min;                     ///< minimum frame size in case rounding is necessary
157     int frame_size;                         ///< current frame size in bytes
158     int frame_size_code;                    ///< frame size code                        (frmsizecod)
159     uint16_t crc_inv[2];
160     int bits_written;                       ///< bit count    (used to avg. bitrate)
161     int samples_written;                    ///< sample count (used to avg. bitrate)
162
163     int fbw_channels;                       ///< number of full-bandwidth channels      (nfchans)
164     int channels;                           ///< total number of channels               (nchans)
165     int lfe_on;                             ///< indicates if there is an LFE channel   (lfeon)
166     int lfe_channel;                        ///< channel index of the LFE channel
167     int has_center;                         ///< indicates if there is a center channel
168     int has_surround;                       ///< indicates if there are one or more surround channels
169     int channel_mode;                       ///< channel mode                           (acmod)
170     const uint8_t *channel_map;             ///< channel map used to reorder channels
171
172     int center_mix_level;                   ///< center mix level code
173     int surround_mix_level;                 ///< surround mix level code
174     int ltrt_center_mix_level;              ///< Lt/Rt center mix level code
175     int ltrt_surround_mix_level;            ///< Lt/Rt surround mix level code
176     int loro_center_mix_level;              ///< Lo/Ro center mix level code
177     int loro_surround_mix_level;            ///< Lo/Ro surround mix level code
178
179     int cutoff;                             ///< user-specified cutoff frequency, in Hz
180     int bandwidth_code;                     ///< bandwidth code (0 to 60)               (chbwcod)
181     int start_freq[AC3_MAX_CHANNELS];       ///< start frequency bin                    (strtmant)
182     int cpl_end_freq;                       ///< coupling channel end frequency bin
183
184     int cpl_on;                             ///< coupling turned on for this frame
185     int cpl_enabled;                        ///< coupling enabled for all frames
186     int num_cpl_subbands;                   ///< number of coupling subbands            (ncplsubnd)
187     int num_cpl_bands;                      ///< number of coupling bands               (ncplbnd)
188     uint8_t cpl_band_sizes[AC3_MAX_CPL_BANDS];  ///< number of coeffs in each coupling band
189
190     int rematrixing_enabled;                ///< stereo rematrixing enabled
191
192     /* bitrate allocation control */
193     int slow_gain_code;                     ///< slow gain code                         (sgaincod)
194     int slow_decay_code;                    ///< slow decay code                        (sdcycod)
195     int fast_decay_code;                    ///< fast decay code                        (fdcycod)
196     int db_per_bit_code;                    ///< dB/bit code                            (dbpbcod)
197     int floor_code;                         ///< floor code                             (floorcod)
198     AC3BitAllocParameters bit_alloc;        ///< bit allocation parameters
199     int coarse_snr_offset;                  ///< coarse SNR offsets                     (csnroffst)
200     int fast_gain_code[AC3_MAX_CHANNELS];   ///< fast gain codes (signal-to-mask ratio) (fgaincod)
201     int fine_snr_offset[AC3_MAX_CHANNELS];  ///< fine SNR offsets                       (fsnroffst)
202     int frame_bits_fixed;                   ///< number of non-coefficient bits for fixed parameters
203     int frame_bits;                         ///< all frame bits except exponents and mantissas
204     int exponent_bits;                      ///< number of bits used for exponents
205
206     SampleType **planar_samples;
207     uint8_t *bap_buffer;
208     uint8_t *bap1_buffer;
209     CoefType *mdct_coef_buffer;
210     int32_t *fixed_coef_buffer;
211     uint8_t *exp_buffer;
212     uint8_t *grouped_exp_buffer;
213     int16_t *psd_buffer;
214     int16_t *band_psd_buffer;
215     int16_t *mask_buffer;
216     uint16_t *qmant_buffer;
217     uint8_t *cpl_coord_exp_buffer;
218     uint8_t *cpl_coord_mant_buffer;
219
220     uint8_t exp_strategy[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< exponent strategies
221
222     DECLARE_ALIGNED(32, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
223 } AC3EncodeContext;
224
225 typedef struct AC3Mant {
226     uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
227     int mant1_cnt, mant2_cnt, mant4_cnt;    ///< mantissa counts for bap=1,2,4
228 } AC3Mant;
229
230 #define CMIXLEV_NUM_OPTIONS 3
231 static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
232     LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
233 };
234
235 #define SURMIXLEV_NUM_OPTIONS 3
236 static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
237     LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
238 };
239
240 #define EXTMIXLEV_NUM_OPTIONS 8
241 static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
242     LEVEL_PLUS_3DB,  LEVEL_PLUS_1POINT5DB,  LEVEL_ONE,       LEVEL_MINUS_4POINT5DB,
243     LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
244 };
245
246
247 #define OFFSET(param) offsetof(AC3EncodeContext, options.param)
248 #define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
249
250 static const AVOption options[] = {
251 /* Metadata Options */
252 {"per_frame_metadata", "Allow Changing Metadata Per-Frame", OFFSET(allow_per_frame_metadata), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 1, AC3ENC_PARAM},
253 /* downmix levels */
254 {"center_mixlev", "Center Mix Level", OFFSET(center_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = LEVEL_MINUS_4POINT5DB }, 0.0, 1.0, AC3ENC_PARAM},
255 {"surround_mixlev", "Surround Mix Level", OFFSET(surround_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = LEVEL_MINUS_6DB }, 0.0, 1.0, AC3ENC_PARAM},
256 /* audio production information */
257 {"mixing_level", "Mixing Level", OFFSET(mixing_level), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 111, AC3ENC_PARAM},
258 {"room_type", "Room Type", OFFSET(room_type), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "room_type"},
259     {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
260     {"large",        "Large Room",              0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
261     {"small",        "Small Room",              0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
262 /* other metadata options */
263 {"copyright", "Copyright Bit", OFFSET(copyright), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 1, AC3ENC_PARAM},
264 {"dialnorm", "Dialogue Level (dB)", OFFSET(dialogue_level), FF_OPT_TYPE_INT, {.dbl = -31 }, -31, -1, AC3ENC_PARAM},
265 {"dsur_mode", "Dolby Surround Mode", OFFSET(dolby_surround_mode), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 2, AC3ENC_PARAM, "dsur_mode"},
266     {"notindicated", "Not Indicated (default)",    0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
267     {"on",           "Dolby Surround Encoded",     0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
268     {"off",          "Not Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
269 {"original", "Original Bit Stream", OFFSET(original), FF_OPT_TYPE_INT,   {.dbl = 1 }, 0, 1, AC3ENC_PARAM},
270 /* extended bitstream information */
271 {"dmix_mode", "Preferred Stereo Downmix Mode", OFFSET(preferred_stereo_downmix), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dmix_mode"},
272     {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
273     {"ltrt", "Lt/Rt Downmix Preferred",         0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
274     {"loro", "Lo/Ro Downmix Preferred",         0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
275 {"ltrt_cmixlev", "Lt/Rt Center Mix Level", OFFSET(ltrt_center_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
276 {"ltrt_surmixlev", "Lt/Rt Surround Mix Level", OFFSET(ltrt_surround_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
277 {"loro_cmixlev", "Lo/Ro Center Mix Level", OFFSET(loro_center_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
278 {"loro_surmixlev", "Lo/Ro Surround Mix Level", OFFSET(loro_surround_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
279 {"dsurex_mode", "Dolby Surround EX Mode", OFFSET(dolby_surround_ex_mode), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dsurex_mode"},
280     {"notindicated", "Not Indicated (default)",       0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
281     {"on",           "Dolby Surround EX Encoded",     0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
282     {"off",          "Not Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
283 {"dheadphone_mode", "Dolby Headphone Mode", OFFSET(dolby_headphone_mode), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dheadphone_mode"},
284     {"notindicated", "Not Indicated (default)",     0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
285     {"on",           "Dolby Headphone Encoded",     0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
286     {"off",          "Not Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
287 {"ad_conv_type", "A/D Converter Type", OFFSET(ad_converter_type), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 1, AC3ENC_PARAM, "ad_conv_type"},
288     {"standard", "Standard (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
289     {"hdcd",     "HDCD",               0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
290 /* Other Encoding Options */
291 {"stereo_rematrixing", "Stereo Rematrixing", OFFSET(stereo_rematrixing), FF_OPT_TYPE_INT, {.dbl = 1 }, 0, 1, AC3ENC_PARAM},
292 #if CONFIG_AC3ENC_FLOAT
293 {"channel_coupling",   "Channel Coupling",   OFFSET(channel_coupling),   FF_OPT_TYPE_INT, {.dbl = 1 }, 0, 1, AC3ENC_PARAM, "channel_coupling"},
294     {"auto", "Selected by the Encoder", 0, FF_OPT_TYPE_CONST, {.dbl = -1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "channel_coupling"},
295 {"cpl_start_band", "Coupling Start Band", OFFSET(cpl_start), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 15, AC3ENC_PARAM, "cpl_start_band"},
296     {"auto", "Selected by the Encoder", 0, FF_OPT_TYPE_CONST, {.dbl = -1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "cpl_start_band"},
297 #endif
298 {NULL}
299 };
300
301 #if CONFIG_AC3ENC_FLOAT
302 static AVClass ac3enc_class = { "AC-3 Encoder", av_default_item_name,
303                                 options, LIBAVUTIL_VERSION_INT };
304 #else
305 static AVClass ac3enc_class = { "Fixed-Point AC-3 Encoder", av_default_item_name,
306                                 options, LIBAVUTIL_VERSION_INT };
307 #endif
308
309
310 /* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
311
312 static av_cold void mdct_end(AC3MDCTContext *mdct);
313
314 static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
315                              int nbits);
316
317 static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
318                          const SampleType *window, unsigned int len);
319
320 static int normalize_samples(AC3EncodeContext *s);
321
322 static void scale_coefficients(AC3EncodeContext *s);
323
324
325 /**
326  * LUT for number of exponent groups.
327  * exponent_group_tab[coupling][exponent strategy-1][number of coefficients]
328  */
329 static uint8_t exponent_group_tab[2][3][256];
330
331
332 /**
333  * List of supported channel layouts.
334  */
335 static const int64_t ac3_channel_layouts[] = {
336      AV_CH_LAYOUT_MONO,
337      AV_CH_LAYOUT_STEREO,
338      AV_CH_LAYOUT_2_1,
339      AV_CH_LAYOUT_SURROUND,
340      AV_CH_LAYOUT_2_2,
341      AV_CH_LAYOUT_QUAD,
342      AV_CH_LAYOUT_4POINT0,
343      AV_CH_LAYOUT_5POINT0,
344      AV_CH_LAYOUT_5POINT0_BACK,
345     (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
346     (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
347     (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
348     (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
349     (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
350     (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
351     (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
352      AV_CH_LAYOUT_5POINT1,
353      AV_CH_LAYOUT_5POINT1_BACK,
354      0
355 };
356
357
358 /**
359  * LUT to select the bandwidth code based on the bit rate, sample rate, and
360  * number of full-bandwidth channels.
361  * bandwidth_tab[fbw_channels-1][sample rate code][bit rate code]
362  */
363 static const uint8_t ac3_bandwidth_tab[5][3][19] = {
364 //      32  40  48  56  64  80  96 112 128 160 192 224 256 320 384 448 512 576 640
365
366     { {  0,  0,  0, 12, 16, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
367       {  0,  0,  0, 16, 20, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
368       {  0,  0,  0, 32, 40, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
369
370     { {  0,  0,  0,  0,  0,  0,  0, 20, 24, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
371       {  0,  0,  0,  0,  0,  0,  4, 24, 28, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
372       {  0,  0,  0,  0,  0,  0, 20, 44, 52, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
373
374     { {  0,  0,  0,  0,  0,  0,  0,  0,  0, 16, 24, 32, 40, 48, 48, 48, 48, 48, 48 },
375       {  0,  0,  0,  0,  0,  0,  0,  0,  4, 20, 28, 36, 44, 56, 56, 56, 56, 56, 56 },
376       {  0,  0,  0,  0,  0,  0,  0,  0, 20, 40, 48, 60, 60, 60, 60, 60, 60, 60, 60 } },
377
378     { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 12, 24, 32, 48, 48, 48, 48, 48, 48 },
379       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 16, 28, 36, 56, 56, 56, 56, 56, 56 },
380       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 32, 48, 60, 60, 60, 60, 60, 60, 60 } },
381
382     { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  8, 20, 32, 40, 48, 48, 48, 48 },
383       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 12, 24, 36, 44, 56, 56, 56, 56 },
384       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 28, 44, 60, 60, 60, 60, 60, 60 } }
385 };
386
387
388 /**
389  * LUT to select the coupling start band based on the bit rate, sample rate, and
390  * number of full-bandwidth channels. -1 = coupling off
391  * ac3_coupling_start_tab[channel_mode-2][sample rate code][bit rate code]
392  *
393  * TODO: more testing for optimal parameters.
394  *       multi-channel tests at 44.1kHz and 32kHz.
395  */
396 static const int8_t ac3_coupling_start_tab[6][3][19] = {
397 //      32  40  48  56  64  80  96 112 128 160 192 224 256 320 384 448 512 576 640
398
399     // 2/0
400     { {  0,  0,  0,  0,  0,  0,  0,  1,  1,  7,  8, 11, 12, -1, -1, -1, -1, -1, -1 },
401       {  0,  0,  0,  0,  0,  0,  1,  3,  5,  7, 10, 12, 13, -1, -1, -1, -1, -1, -1 },
402       {  0,  0,  0,  0,  1,  2,  2,  9, 13, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
403
404     // 3/0
405     { {  0,  0,  0,  0,  0,  0,  0,  0,  2,  2,  6,  9, 11, 12, 13, -1, -1, -1, -1 },
406       {  0,  0,  0,  0,  0,  0,  0,  0,  2,  2,  6,  9, 11, 12, 13, -1, -1, -1, -1 },
407       { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
408
409     // 2/1 - untested
410     { {  0,  0,  0,  0,  0,  0,  0,  0,  2,  2,  6,  9, 11, 12, 13, -1, -1, -1, -1 },
411       {  0,  0,  0,  0,  0,  0,  0,  0,  2,  2,  6,  9, 11, 12, 13, -1, -1, -1, -1 },
412       { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
413
414     // 3/1
415     { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3,  2, 10, 11, 11, 12, 12, 14, -1 },
416       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3,  2, 10, 11, 11, 12, 12, 14, -1 },
417       { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
418
419     // 2/2 - untested
420     { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3,  2, 10, 11, 11, 12, 12, 14, -1 },
421       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3,  2, 10, 11, 11, 12, 12, 14, -1 },
422       { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
423
424     // 3/2
425     { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  6,  8, 11, 12, 12, -1, -1 },
426       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  6,  8, 11, 12, 12, -1, -1 },
427       { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
428 };
429
430
431 /**
432  * Adjust the frame size to make the average bit rate match the target bit rate.
433  * This is only needed for 11025, 22050, and 44100 sample rates.
434  */
435 static void adjust_frame_size(AC3EncodeContext *s)
436 {
437     while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
438         s->bits_written    -= s->bit_rate;
439         s->samples_written -= s->sample_rate;
440     }
441     s->frame_size = s->frame_size_min +
442                     2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
443     s->bits_written    += s->frame_size * 8;
444     s->samples_written += AC3_FRAME_SIZE;
445 }
446
447
448 /**
449  * Deinterleave input samples.
450  * Channels are reordered from Libav's default order to AC-3 order.
451  */
452 static void deinterleave_input_samples(AC3EncodeContext *s,
453                                        const SampleType *samples)
454 {
455     int ch, i;
456
457     /* deinterleave and remap input samples */
458     for (ch = 0; ch < s->channels; ch++) {
459         const SampleType *sptr;
460         int sinc;
461
462         /* copy last 256 samples of previous frame to the start of the current frame */
463         memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
464                AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
465
466         /* deinterleave */
467         sinc = s->channels;
468         sptr = samples + s->channel_map[ch];
469         for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
470             s->planar_samples[ch][i] = *sptr;
471             sptr += sinc;
472         }
473     }
474 }
475
476
477 /**
478  * Apply the MDCT to input samples to generate frequency coefficients.
479  * This applies the KBD window and normalizes the input to reduce precision
480  * loss due to fixed-point calculations.
481  */
482 static void apply_mdct(AC3EncodeContext *s)
483 {
484     int blk, ch;
485
486     for (ch = 0; ch < s->channels; ch++) {
487         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
488             AC3Block *block = &s->blocks[blk];
489             const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
490
491             apply_window(&s->dsp, s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
492
493             block->coeff_shift[ch+1] = normalize_samples(s);
494
495             s->mdct.fft.mdct_calcw(&s->mdct.fft, block->mdct_coef[ch+1],
496                                    s->windowed_samples);
497         }
498     }
499 }
500
501
502 static void compute_coupling_strategy(AC3EncodeContext *s)
503 {
504     int blk, ch;
505     int got_cpl_snr;
506
507     /* set coupling use flags for each block/channel */
508     /* TODO: turn coupling on/off and adjust start band based on bit usage */
509     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
510         AC3Block *block = &s->blocks[blk];
511         for (ch = 1; ch <= s->fbw_channels; ch++)
512             block->channel_in_cpl[ch] = s->cpl_on;
513     }
514
515     /* enable coupling for each block if at least 2 channels have coupling
516        enabled for that block */
517     got_cpl_snr = 0;
518     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
519         AC3Block *block = &s->blocks[blk];
520         block->num_cpl_channels = 0;
521         for (ch = 1; ch <= s->fbw_channels; ch++)
522             block->num_cpl_channels += block->channel_in_cpl[ch];
523         block->cpl_in_use = block->num_cpl_channels > 1;
524         if (!block->cpl_in_use) {
525             block->num_cpl_channels = 0;
526             for (ch = 1; ch <= s->fbw_channels; ch++)
527                 block->channel_in_cpl[ch] = 0;
528         }
529
530         block->new_cpl_strategy = !blk;
531         if (blk) {
532             for (ch = 1; ch <= s->fbw_channels; ch++) {
533                 if (block->channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]) {
534                     block->new_cpl_strategy = 1;
535                     break;
536                 }
537             }
538         }
539         block->new_cpl_leak = block->new_cpl_strategy;
540
541         if (!blk || (block->cpl_in_use && !got_cpl_snr)) {
542             block->new_snr_offsets = 1;
543             if (block->cpl_in_use)
544                 got_cpl_snr = 1;
545         } else {
546             block->new_snr_offsets = 0;
547         }
548     }
549
550     /* set bandwidth for each channel */
551     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
552         AC3Block *block = &s->blocks[blk];
553         for (ch = 1; ch <= s->fbw_channels; ch++) {
554             if (block->channel_in_cpl[ch])
555                 block->end_freq[ch] = s->start_freq[CPL_CH];
556             else
557                 block->end_freq[ch] = s->bandwidth_code * 3 + 73;
558         }
559     }
560 }
561
562
563 /**
564  * Calculate a single coupling coordinate.
565  */
566 static inline float calc_cpl_coord(float energy_ch, float energy_cpl)
567 {
568     float coord = 0.125;
569     if (energy_cpl > 0)
570         coord *= sqrtf(energy_ch / energy_cpl);
571     return coord;
572 }
573
574
575 /**
576  * Calculate coupling channel and coupling coordinates.
577  * TODO: Currently this is only used for the floating-point encoder. I was
578  *       able to make it work for the fixed-point encoder, but quality was
579  *       generally lower in most cases than not using coupling. If a more
580  *       adaptive coupling strategy were to be implemented it might be useful
581  *       at that time to use coupling for the fixed-point encoder as well.
582  */
583 static void apply_channel_coupling(AC3EncodeContext *s)
584 {
585 #if CONFIG_AC3ENC_FLOAT
586     DECLARE_ALIGNED(16, float,   cpl_coords)      [AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][16] = {{{0}}};
587     DECLARE_ALIGNED(16, int32_t, fixed_cpl_coords)[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][16] = {{{0}}};
588     int blk, ch, bnd, i, j;
589     CoefSumType energy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][16] = {{{0}}};
590     int num_cpl_coefs = s->num_cpl_subbands * 12;
591
592     /* calculate coupling channel from fbw channels */
593     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
594         AC3Block *block = &s->blocks[blk];
595         CoefType *cpl_coef = &block->mdct_coef[CPL_CH][s->start_freq[CPL_CH]];
596         if (!block->cpl_in_use)
597             continue;
598         memset(cpl_coef-1, 0, (num_cpl_coefs+4) * sizeof(*cpl_coef));
599         for (ch = 1; ch <= s->fbw_channels; ch++) {
600             CoefType *ch_coef = &block->mdct_coef[ch][s->start_freq[CPL_CH]];
601             if (!block->channel_in_cpl[ch])
602                 continue;
603             for (i = 0; i < num_cpl_coefs; i++)
604                 cpl_coef[i] += ch_coef[i];
605         }
606         /* note: coupling start bin % 4 will always be 1 and num_cpl_coefs
607                  will always be a multiple of 12, so we need to subtract 1 from
608                  the start and add 4 to the length when using optimized
609                  functions which require 16-byte alignment. */
610
611         /* coefficients must be clipped to +/- 1.0 in order to be encoded */
612         s->dsp.vector_clipf(cpl_coef-1, cpl_coef-1, -1.0f, 1.0f, num_cpl_coefs+4);
613
614         /* scale coupling coefficients from float to 24-bit fixed-point */
615         s->ac3dsp.float_to_fixed24(&block->fixed_coef[CPL_CH][s->start_freq[CPL_CH]-1],
616                                    cpl_coef-1, num_cpl_coefs+4);
617     }
618
619     /* calculate energy in each band in coupling channel and each fbw channel */
620     /* TODO: possibly use SIMD to speed up energy calculation */
621     bnd = 0;
622     i = s->start_freq[CPL_CH];
623     while (i < s->cpl_end_freq) {
624         int band_size = s->cpl_band_sizes[bnd];
625         for (ch = CPL_CH; ch <= s->fbw_channels; ch++) {
626             for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
627                 AC3Block *block = &s->blocks[blk];
628                 if (!block->cpl_in_use || (ch > CPL_CH && !block->channel_in_cpl[ch]))
629                     continue;
630                 for (j = 0; j < band_size; j++) {
631                     CoefType v = block->mdct_coef[ch][i+j];
632                     MAC_COEF(energy[blk][ch][bnd], v, v);
633                 }
634             }
635         }
636         i += band_size;
637         bnd++;
638     }
639
640     /* determine which blocks to send new coupling coordinates for */
641     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
642         AC3Block *block  = &s->blocks[blk];
643         AC3Block *block0 = blk ? &s->blocks[blk-1] : NULL;
644         int new_coords = 0;
645         CoefSumType coord_diff[AC3_MAX_CHANNELS] = {0,};
646
647         if (block->cpl_in_use) {
648             /* calculate coupling coordinates for all blocks and calculate the
649                average difference between coordinates in successive blocks */
650             for (ch = 1; ch <= s->fbw_channels; ch++) {
651                 if (!block->channel_in_cpl[ch])
652                     continue;
653
654                 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
655                     cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy[blk][ch][bnd],
656                                                               energy[blk][CPL_CH][bnd]);
657                     if (blk > 0 && block0->cpl_in_use &&
658                         block0->channel_in_cpl[ch]) {
659                         coord_diff[ch] += fabs(cpl_coords[blk-1][ch][bnd] -
660                                                cpl_coords[blk  ][ch][bnd]);
661                     }
662                 }
663                 coord_diff[ch] /= s->num_cpl_bands;
664             }
665
666             /* send new coordinates if this is the first block, if previous
667              * block did not use coupling but this block does, the channels
668              * using coupling has changed from the previous block, or the
669              * coordinate difference from the last block for any channel is
670              * greater than a threshold value. */
671             if (blk == 0) {
672                 new_coords = 1;
673             } else if (!block0->cpl_in_use) {
674                 new_coords = 1;
675             } else {
676                 for (ch = 1; ch <= s->fbw_channels; ch++) {
677                     if (block->channel_in_cpl[ch] && !block0->channel_in_cpl[ch]) {
678                         new_coords = 1;
679                         break;
680                     }
681                 }
682                 if (!new_coords) {
683                     for (ch = 1; ch <= s->fbw_channels; ch++) {
684                         if (block->channel_in_cpl[ch] && coord_diff[ch] > 0.04) {
685                             new_coords = 1;
686                             break;
687                         }
688                     }
689                 }
690             }
691         }
692         block->new_cpl_coords = new_coords;
693     }
694
695     /* calculate final coupling coordinates, taking into account reusing of
696        coordinates in successive blocks */
697     for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
698         blk = 0;
699         while (blk < AC3_MAX_BLOCKS) {
700             int blk1;
701             CoefSumType energy_cpl;
702             AC3Block *block  = &s->blocks[blk];
703
704             if (!block->cpl_in_use) {
705                 blk++;
706                 continue;
707             }
708
709             energy_cpl = energy[blk][CPL_CH][bnd];
710             blk1 = blk+1;
711             while (!s->blocks[blk1].new_cpl_coords && blk1 < AC3_MAX_BLOCKS) {
712                 if (s->blocks[blk1].cpl_in_use)
713                     energy_cpl += energy[blk1][CPL_CH][bnd];
714                 blk1++;
715             }
716
717             for (ch = 1; ch <= s->fbw_channels; ch++) {
718                 CoefType energy_ch;
719                 if (!block->channel_in_cpl[ch])
720                     continue;
721                 energy_ch = energy[blk][ch][bnd];
722                 blk1 = blk+1;
723                 while (!s->blocks[blk1].new_cpl_coords && blk1 < AC3_MAX_BLOCKS) {
724                     if (s->blocks[blk1].cpl_in_use)
725                         energy_ch += energy[blk1][ch][bnd];
726                     blk1++;
727                 }
728                 cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy_ch, energy_cpl);
729             }
730             blk = blk1;
731         }
732     }
733
734     /* calculate exponents/mantissas for coupling coordinates */
735     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
736         AC3Block *block = &s->blocks[blk];
737         if (!block->cpl_in_use || !block->new_cpl_coords)
738             continue;
739
740         s->ac3dsp.float_to_fixed24(fixed_cpl_coords[blk][1],
741                                    cpl_coords[blk][1],
742                                    s->fbw_channels * 16);
743         s->ac3dsp.extract_exponents(block->cpl_coord_exp[1],
744                                     fixed_cpl_coords[blk][1],
745                                     s->fbw_channels * 16);
746
747         for (ch = 1; ch <= s->fbw_channels; ch++) {
748             int bnd, min_exp, max_exp, master_exp;
749
750             /* determine master exponent */
751             min_exp = max_exp = block->cpl_coord_exp[ch][0];
752             for (bnd = 1; bnd < s->num_cpl_bands; bnd++) {
753                 int exp = block->cpl_coord_exp[ch][bnd];
754                 min_exp = FFMIN(exp, min_exp);
755                 max_exp = FFMAX(exp, max_exp);
756             }
757             master_exp = ((max_exp - 15) + 2) / 3;
758             master_exp = FFMAX(master_exp, 0);
759             while (min_exp < master_exp * 3)
760                 master_exp--;
761             for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
762                 block->cpl_coord_exp[ch][bnd] = av_clip(block->cpl_coord_exp[ch][bnd] -
763                                                         master_exp * 3, 0, 15);
764             }
765             block->cpl_master_exp[ch] = master_exp;
766
767             /* quantize mantissas */
768             for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
769                 int cpl_exp  = block->cpl_coord_exp[ch][bnd];
770                 int cpl_mant = (fixed_cpl_coords[blk][ch][bnd] << (5 + cpl_exp + master_exp * 3)) >> 24;
771                 if (cpl_exp == 15)
772                     cpl_mant >>= 1;
773                 else
774                     cpl_mant -= 16;
775
776                 block->cpl_coord_mant[ch][bnd] = cpl_mant;
777             }
778         }
779     }
780 #endif /* CONFIG_AC3ENC_FLOAT */
781 }
782
783
784 /**
785  * Determine rematrixing flags for each block and band.
786  */
787 static void compute_rematrixing_strategy(AC3EncodeContext *s)
788 {
789     int nb_coefs;
790     int blk, bnd, i;
791     AC3Block *block, *block0;
792
793     if (s->channel_mode != AC3_CHMODE_STEREO)
794         return;
795
796     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
797         block = &s->blocks[blk];
798         block->new_rematrixing_strategy = !blk;
799
800         if (!s->rematrixing_enabled) {
801             block0 = block;
802             continue;
803         }
804
805         block->num_rematrixing_bands = 4;
806         if (block->cpl_in_use) {
807             block->num_rematrixing_bands -= (s->start_freq[CPL_CH] <= 61);
808             block->num_rematrixing_bands -= (s->start_freq[CPL_CH] == 37);
809             if (blk && block->num_rematrixing_bands != block0->num_rematrixing_bands)
810                 block->new_rematrixing_strategy = 1;
811         }
812         nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
813
814         for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {
815             /* calculate calculate sum of squared coeffs for one band in one block */
816             int start = ff_ac3_rematrix_band_tab[bnd];
817             int end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
818             CoefSumType sum[4] = {0,};
819             for (i = start; i < end; i++) {
820                 CoefType lt = block->mdct_coef[1][i];
821                 CoefType rt = block->mdct_coef[2][i];
822                 CoefType md = lt + rt;
823                 CoefType sd = lt - rt;
824                 MAC_COEF(sum[0], lt, lt);
825                 MAC_COEF(sum[1], rt, rt);
826                 MAC_COEF(sum[2], md, md);
827                 MAC_COEF(sum[3], sd, sd);
828             }
829
830             /* compare sums to determine if rematrixing will be used for this band */
831             if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
832                 block->rematrixing_flags[bnd] = 1;
833             else
834                 block->rematrixing_flags[bnd] = 0;
835
836             /* determine if new rematrixing flags will be sent */
837             if (blk &&
838                 block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
839                 block->new_rematrixing_strategy = 1;
840             }
841         }
842         block0 = block;
843     }
844 }
845
846
847 /**
848  * Apply stereo rematrixing to coefficients based on rematrixing flags.
849  */
850 static void apply_rematrixing(AC3EncodeContext *s)
851 {
852     int nb_coefs;
853     int blk, bnd, i;
854     int start, end;
855     uint8_t *flags;
856
857     if (!s->rematrixing_enabled)
858         return;
859
860     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
861         AC3Block *block = &s->blocks[blk];
862         if (block->new_rematrixing_strategy)
863             flags = block->rematrixing_flags;
864         nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
865         for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {
866             if (flags[bnd]) {
867                 start = ff_ac3_rematrix_band_tab[bnd];
868                 end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
869                 for (i = start; i < end; i++) {
870                     int32_t lt = block->fixed_coef[1][i];
871                     int32_t rt = block->fixed_coef[2][i];
872                     block->fixed_coef[1][i] = (lt + rt) >> 1;
873                     block->fixed_coef[2][i] = (lt - rt) >> 1;
874                 }
875             }
876         }
877     }
878 }
879
880
881 /**
882  * Initialize exponent tables.
883  */
884 static av_cold void exponent_init(AC3EncodeContext *s)
885 {
886     int expstr, i, grpsize;
887
888     for (expstr = EXP_D15-1; expstr <= EXP_D45-1; expstr++) {
889         grpsize = 3 << expstr;
890         for (i = 12; i < 256; i++) {
891             exponent_group_tab[0][expstr][i] = (i + grpsize - 4) / grpsize;
892             exponent_group_tab[1][expstr][i] = (i              ) / grpsize;
893         }
894     }
895     /* LFE */
896     exponent_group_tab[0][0][7] = 2;
897 }
898
899
900 /**
901  * Extract exponents from the MDCT coefficients.
902  * This takes into account the normalization that was done to the input samples
903  * by adjusting the exponents by the exponent shift values.
904  */
905 static void extract_exponents(AC3EncodeContext *s)
906 {
907     int blk, ch;
908
909     for (ch = !s->cpl_on; ch <= s->channels; ch++) {
910         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
911             AC3Block *block = &s->blocks[blk];
912             s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch],
913                                         AC3_MAX_COEFS);
914         }
915     }
916 }
917
918
919 /**
920  * Exponent Difference Threshold.
921  * New exponents are sent if their SAD exceed this number.
922  */
923 #define EXP_DIFF_THRESHOLD 500
924
925
926 /**
927  * Calculate exponent strategies for all channels.
928  * Array arrangement is reversed to simplify the per-channel calculation.
929  */
930 static void compute_exp_strategy(AC3EncodeContext *s)
931 {
932     int ch, blk, blk1;
933
934     for (ch = !s->cpl_on; ch <= s->fbw_channels; ch++) {
935         uint8_t *exp_strategy = s->exp_strategy[ch];
936         uint8_t *exp          = s->blocks[0].exp[ch];
937         int exp_diff;
938
939         /* estimate if the exponent variation & decide if they should be
940            reused in the next frame */
941         exp_strategy[0] = EXP_NEW;
942         exp += AC3_MAX_COEFS;
943         for (blk = 1; blk < AC3_MAX_BLOCKS; blk++, exp += AC3_MAX_COEFS) {
944             if ((ch == CPL_CH && (!s->blocks[blk].cpl_in_use || !s->blocks[blk-1].cpl_in_use)) ||
945                 (ch  > CPL_CH && (s->blocks[blk].channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]))) {
946                 exp_strategy[blk] = EXP_NEW;
947                 continue;
948             }
949             exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
950             exp_strategy[blk] = EXP_REUSE;
951             if (ch == CPL_CH && exp_diff > (EXP_DIFF_THRESHOLD * (s->blocks[blk].end_freq[ch] - s->start_freq[ch]) / AC3_MAX_COEFS))
952                 exp_strategy[blk] = EXP_NEW;
953             else if (ch > CPL_CH && exp_diff > EXP_DIFF_THRESHOLD)
954                 exp_strategy[blk] = EXP_NEW;
955         }
956
957         /* now select the encoding strategy type : if exponents are often
958            recoded, we use a coarse encoding */
959         blk = 0;
960         while (blk < AC3_MAX_BLOCKS) {
961             blk1 = blk + 1;
962             while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
963                 blk1++;
964             switch (blk1 - blk) {
965             case 1:  exp_strategy[blk] = EXP_D45; break;
966             case 2:
967             case 3:  exp_strategy[blk] = EXP_D25; break;
968             default: exp_strategy[blk] = EXP_D15; break;
969             }
970             blk = blk1;
971         }
972     }
973     if (s->lfe_on) {
974         ch = s->lfe_channel;
975         s->exp_strategy[ch][0] = EXP_D15;
976         for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
977             s->exp_strategy[ch][blk] = EXP_REUSE;
978     }
979 }
980
981
982 /**
983  * Update the exponents so that they are the ones the decoder will decode.
984  */
985 static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy,
986                                     int cpl)
987 {
988     int nb_groups, i, k;
989
990     nb_groups = exponent_group_tab[cpl][exp_strategy-1][nb_exps] * 3;
991
992     /* for each group, compute the minimum exponent */
993     switch(exp_strategy) {
994     case EXP_D25:
995         for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
996             uint8_t exp_min = exp[k];
997             if (exp[k+1] < exp_min)
998                 exp_min = exp[k+1];
999             exp[i-cpl] = exp_min;
1000             k += 2;
1001         }
1002         break;
1003     case EXP_D45:
1004         for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
1005             uint8_t exp_min = exp[k];
1006             if (exp[k+1] < exp_min)
1007                 exp_min = exp[k+1];
1008             if (exp[k+2] < exp_min)
1009                 exp_min = exp[k+2];
1010             if (exp[k+3] < exp_min)
1011                 exp_min = exp[k+3];
1012             exp[i-cpl] = exp_min;
1013             k += 4;
1014         }
1015         break;
1016     }
1017
1018     /* constraint for DC exponent */
1019     if (!cpl && exp[0] > 15)
1020         exp[0] = 15;
1021
1022     /* decrease the delta between each groups to within 2 so that they can be
1023        differentially encoded */
1024     for (i = 1; i <= nb_groups; i++)
1025         exp[i] = FFMIN(exp[i], exp[i-1] + 2);
1026     i--;
1027     while (--i >= 0)
1028         exp[i] = FFMIN(exp[i], exp[i+1] + 2);
1029
1030     if (cpl)
1031         exp[-1] = exp[0] & ~1;
1032
1033     /* now we have the exponent values the decoder will see */
1034     switch (exp_strategy) {
1035     case EXP_D25:
1036         for (i = nb_groups, k = (nb_groups * 2)-cpl; i > 0; i--) {
1037             uint8_t exp1 = exp[i-cpl];
1038             exp[k--] = exp1;
1039             exp[k--] = exp1;
1040         }
1041         break;
1042     case EXP_D45:
1043         for (i = nb_groups, k = (nb_groups * 4)-cpl; i > 0; i--) {
1044             exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i-cpl];
1045             k -= 4;
1046         }
1047         break;
1048     }
1049 }
1050
1051
1052 /**
1053  * Encode exponents from original extracted form to what the decoder will see.
1054  * This copies and groups exponents based on exponent strategy and reduces
1055  * deltas between adjacent exponent groups so that they can be differentially
1056  * encoded.
1057  */
1058 static void encode_exponents(AC3EncodeContext *s)
1059 {
1060     int blk, blk1, ch, cpl;
1061     uint8_t *exp, *exp_strategy;
1062     int nb_coefs, num_reuse_blocks;
1063
1064     for (ch = !s->cpl_on; ch <= s->channels; ch++) {
1065         exp          = s->blocks[0].exp[ch] + s->start_freq[ch];
1066         exp_strategy = s->exp_strategy[ch];
1067
1068         cpl = (ch == CPL_CH);
1069         blk = 0;
1070         while (blk < AC3_MAX_BLOCKS) {
1071             AC3Block *block = &s->blocks[blk];
1072             if (cpl && !block->cpl_in_use) {
1073                 exp += AC3_MAX_COEFS;
1074                 blk++;
1075                 continue;
1076             }
1077             nb_coefs = block->end_freq[ch] - s->start_freq[ch];
1078             blk1 = blk + 1;
1079
1080             /* count the number of EXP_REUSE blocks after the current block
1081                and set exponent reference block pointers */
1082             block->exp_ref_block[ch] = block;
1083             while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
1084                 s->blocks[blk1].exp_ref_block[ch] = block;
1085                 blk1++;
1086             }
1087             num_reuse_blocks = blk1 - blk - 1;
1088
1089             /* for the EXP_REUSE case we select the min of the exponents */
1090             s->ac3dsp.ac3_exponent_min(exp-s->start_freq[ch], num_reuse_blocks,
1091                                        AC3_MAX_COEFS);
1092
1093             encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk], cpl);
1094
1095             exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
1096             blk = blk1;
1097         }
1098     }
1099 }
1100
1101
1102 /**
1103  * Group exponents.
1104  * 3 delta-encoded exponents are in each 7-bit group. The number of groups
1105  * varies depending on exponent strategy and bandwidth.
1106  */
1107 static void group_exponents(AC3EncodeContext *s)
1108 {
1109     int blk, ch, i, cpl;
1110     int group_size, nb_groups, bit_count;
1111     uint8_t *p;
1112     int delta0, delta1, delta2;
1113     int exp0, exp1;
1114
1115     bit_count = 0;
1116     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1117         AC3Block *block = &s->blocks[blk];
1118         for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1119             int exp_strategy = s->exp_strategy[ch][blk];
1120             if (exp_strategy == EXP_REUSE)
1121                 continue;
1122             cpl = (ch == CPL_CH);
1123             group_size = exp_strategy + (exp_strategy == EXP_D45);
1124             nb_groups = exponent_group_tab[cpl][exp_strategy-1][block->end_freq[ch]-s->start_freq[ch]];
1125             bit_count += 4 + (nb_groups * 7);
1126             p = block->exp[ch] + s->start_freq[ch] - cpl;
1127
1128             /* DC exponent */
1129             exp1 = *p++;
1130             block->grouped_exp[ch][0] = exp1;
1131
1132             /* remaining exponents are delta encoded */
1133             for (i = 1; i <= nb_groups; i++) {
1134                 /* merge three delta in one code */
1135                 exp0   = exp1;
1136                 exp1   = p[0];
1137                 p     += group_size;
1138                 delta0 = exp1 - exp0 + 2;
1139                 av_assert2(delta0 >= 0 && delta0 <= 4);
1140
1141                 exp0   = exp1;
1142                 exp1   = p[0];
1143                 p     += group_size;
1144                 delta1 = exp1 - exp0 + 2;
1145                 av_assert2(delta1 >= 0 && delta1 <= 4);
1146
1147                 exp0   = exp1;
1148                 exp1   = p[0];
1149                 p     += group_size;
1150                 delta2 = exp1 - exp0 + 2;
1151                 av_assert2(delta2 >= 0 && delta2 <= 4);
1152
1153                 block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
1154             }
1155         }
1156     }
1157
1158     s->exponent_bits = bit_count;
1159 }
1160
1161
1162 /**
1163  * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
1164  * Extract exponents from MDCT coefficients, calculate exponent strategies,
1165  * and encode final exponents.
1166  */
1167 static void process_exponents(AC3EncodeContext *s)
1168 {
1169     extract_exponents(s);
1170
1171     compute_exp_strategy(s);
1172
1173     encode_exponents(s);
1174
1175     group_exponents(s);
1176
1177     emms_c();
1178 }
1179
1180
1181 /**
1182  * Count frame bits that are based solely on fixed parameters.
1183  * This only has to be run once when the encoder is initialized.
1184  */
1185 static void count_frame_bits_fixed(AC3EncodeContext *s)
1186 {
1187     static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
1188     int blk;
1189     int frame_bits;
1190
1191     /* assumptions:
1192      *   no dynamic range codes
1193      *   bit allocation parameters do not change between blocks
1194      *   no delta bit allocation
1195      *   no skipped data
1196      *   no auxilliary data
1197      */
1198
1199     /* header */
1200     frame_bits = 65;
1201     frame_bits += frame_bits_inc[s->channel_mode];
1202
1203     /* audio blocks */
1204     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1205         /* block switch flags */
1206         frame_bits += s->fbw_channels;
1207
1208         /* dither flags */
1209         frame_bits += s->fbw_channels;
1210
1211         /* dynamic range */
1212         frame_bits++;
1213
1214         /* exponent strategy */
1215         frame_bits += 2 * s->fbw_channels;
1216         if (s->lfe_on)
1217             frame_bits++;
1218
1219         /* bit allocation params */
1220         frame_bits++;
1221         if (!blk)
1222             frame_bits += 2 + 2 + 2 + 2 + 3;
1223
1224         /* delta bit allocation */
1225         frame_bits++;
1226
1227         /* skipped data */
1228         frame_bits++;
1229     }
1230
1231     /* auxiliary data */
1232     frame_bits++;
1233
1234     /* CRC */
1235     frame_bits += 1 + 16;
1236
1237     s->frame_bits_fixed = frame_bits;
1238 }
1239
1240
1241 /**
1242  * Initialize bit allocation.
1243  * Set default parameter codes and calculate parameter values.
1244  */
1245 static void bit_alloc_init(AC3EncodeContext *s)
1246 {
1247     int ch;
1248
1249     /* init default parameters */
1250     s->slow_decay_code = 2;
1251     s->fast_decay_code = 1;
1252     s->slow_gain_code  = 1;
1253     s->db_per_bit_code = 3;
1254     s->floor_code      = 7;
1255     for (ch = 0; ch <= s->channels; ch++)
1256         s->fast_gain_code[ch] = 4;
1257
1258     /* initial snr offset */
1259     s->coarse_snr_offset = 40;
1260
1261     /* compute real values */
1262     /* currently none of these values change during encoding, so we can just
1263        set them once at initialization */
1264     s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
1265     s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
1266     s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
1267     s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
1268     s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
1269     s->bit_alloc.cpl_fast_leak = 0;
1270     s->bit_alloc.cpl_slow_leak = 0;
1271
1272     count_frame_bits_fixed(s);
1273 }
1274
1275
1276 /**
1277  * Count the bits used to encode the frame, minus exponents and mantissas.
1278  * Bits based on fixed parameters have already been counted, so now we just
1279  * have to add the bits based on parameters that change during encoding.
1280  */
1281 static void count_frame_bits(AC3EncodeContext *s)
1282 {
1283     AC3EncOptions *opt = &s->options;
1284     int blk, ch;
1285     int frame_bits = 0;
1286
1287     /* header */
1288     if (opt->audio_production_info)
1289         frame_bits += 7;
1290     if (s->bitstream_id == 6) {
1291         if (opt->extended_bsi_1)
1292             frame_bits += 14;
1293         if (opt->extended_bsi_2)
1294             frame_bits += 14;
1295     }
1296
1297     /* audio blocks */
1298     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1299         AC3Block *block = &s->blocks[blk];
1300
1301         /* coupling strategy */
1302         frame_bits++;
1303         if (block->new_cpl_strategy) {
1304             frame_bits++;
1305             if (block->cpl_in_use) {
1306                 frame_bits += s->fbw_channels;
1307                 if (s->channel_mode == AC3_CHMODE_STEREO)
1308                     frame_bits++;
1309                 frame_bits += 4 + 4;
1310                 frame_bits += s->num_cpl_subbands - 1;
1311             }
1312         }
1313
1314         /* coupling coordinates */
1315         if (block->cpl_in_use) {
1316             for (ch = 1; ch <= s->fbw_channels; ch++) {
1317                 if (block->channel_in_cpl[ch]) {
1318                     frame_bits++;
1319                     if (block->new_cpl_coords) {
1320                         frame_bits += 2;
1321                         frame_bits += (4 + 4) * s->num_cpl_bands;
1322                     }
1323                 }
1324             }
1325         }
1326
1327         /* stereo rematrixing */
1328         if (s->channel_mode == AC3_CHMODE_STEREO) {
1329             frame_bits++;
1330             if (s->blocks[blk].new_rematrixing_strategy)
1331                 frame_bits += block->num_rematrixing_bands;
1332         }
1333
1334         /* bandwidth codes & gain range */
1335         for (ch = 1; ch <= s->fbw_channels; ch++) {
1336             if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1337                 if (!block->channel_in_cpl[ch])
1338                     frame_bits += 6;
1339                 frame_bits += 2;
1340             }
1341         }
1342
1343         /* coupling exponent strategy */
1344         if (block->cpl_in_use)
1345             frame_bits += 2;
1346
1347         /* snr offsets and fast gain codes */
1348         frame_bits++;
1349         if (block->new_snr_offsets)
1350             frame_bits += 6 + (s->channels + block->cpl_in_use) * (4 + 3);
1351
1352         /* coupling leak info */
1353         if (block->cpl_in_use) {
1354             frame_bits++;
1355             if (block->new_cpl_leak)
1356                 frame_bits += 3 + 3;
1357         }
1358     }
1359
1360     s->frame_bits = s->frame_bits_fixed + frame_bits;
1361 }
1362
1363
1364 /**
1365  * Finalize the mantissa bit count by adding in the grouped mantissas.
1366  */
1367 static int compute_mantissa_size_final(int mant_cnt[5])
1368 {
1369     // bap=1 : 3 mantissas in 5 bits
1370     int bits = (mant_cnt[1] / 3) * 5;
1371     // bap=2 : 3 mantissas in 7 bits
1372     // bap=4 : 2 mantissas in 7 bits
1373     bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
1374     // bap=3 : each mantissa is 3 bits
1375     bits += mant_cnt[3] * 3;
1376     return bits;
1377 }
1378
1379
1380 /**
1381  * Calculate masking curve based on the final exponents.
1382  * Also calculate the power spectral densities to use in future calculations.
1383  */
1384 static void bit_alloc_masking(AC3EncodeContext *s)
1385 {
1386     int blk, ch;
1387
1388     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1389         AC3Block *block = &s->blocks[blk];
1390         for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1391             /* We only need psd and mask for calculating bap.
1392                Since we currently do not calculate bap when exponent
1393                strategy is EXP_REUSE we do not need to calculate psd or mask. */
1394             if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1395                 ff_ac3_bit_alloc_calc_psd(block->exp[ch], s->start_freq[ch],
1396                                           block->end_freq[ch], block->psd[ch],
1397                                           block->band_psd[ch]);
1398                 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
1399                                            s->start_freq[ch], block->end_freq[ch],
1400                                            ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
1401                                            ch == s->lfe_channel,
1402                                            DBA_NONE, 0, NULL, NULL, NULL,
1403                                            block->mask[ch]);
1404             }
1405         }
1406     }
1407 }
1408
1409
1410 /**
1411  * Ensure that bap for each block and channel point to the current bap_buffer.
1412  * They may have been switched during the bit allocation search.
1413  */
1414 static void reset_block_bap(AC3EncodeContext *s)
1415 {
1416     int blk, ch;
1417     int channels = s->channels + 1;
1418     if (s->blocks[0].bap[0] == s->bap_buffer)
1419         return;
1420     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1421         for (ch = 0; ch < channels; ch++) {
1422             s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * channels + ch)];
1423         }
1424     }
1425 }
1426
1427
1428 /**
1429  * Run the bit allocation with a given SNR offset.
1430  * This calculates the bit allocation pointers that will be used to determine
1431  * the quantization of each mantissa.
1432  * @return the number of bits needed for mantissas if the given SNR offset is
1433  *         is used.
1434  */
1435 static int bit_alloc(AC3EncodeContext *s, int snr_offset)
1436 {
1437     int blk, ch;
1438     int mantissa_bits;
1439     int mant_cnt[5];
1440
1441     snr_offset = (snr_offset - 240) << 2;
1442
1443     reset_block_bap(s);
1444     mantissa_bits = 0;
1445     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1446         AC3Block *block = &s->blocks[blk];
1447         AC3Block *ref_block;
1448         int av_uninit(ch0);
1449         int got_cpl = !block->cpl_in_use;
1450         // initialize grouped mantissa counts. these are set so that they are
1451         // padded to the next whole group size when bits are counted in
1452         // compute_mantissa_size_final
1453         mant_cnt[0] = mant_cnt[3] = 0;
1454         mant_cnt[1] = mant_cnt[2] = 2;
1455         mant_cnt[4] = 1;
1456         for (ch = 1; ch <= s->channels; ch++) {
1457             if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1458                 ch0     = ch - 1;
1459                 ch      = CPL_CH;
1460                 got_cpl = 1;
1461             }
1462
1463             /* Currently the only bit allocation parameters which vary across
1464                blocks within a frame are the exponent values.  We can take
1465                advantage of that by reusing the bit allocation pointers
1466                whenever we reuse exponents. */
1467             ref_block = block->exp_ref_block[ch];
1468             if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1469                 s->ac3dsp.bit_alloc_calc_bap(ref_block->mask[ch], ref_block->psd[ch],
1470                                              s->start_freq[ch], block->end_freq[ch],
1471                                              snr_offset, s->bit_alloc.floor,
1472                                              ff_ac3_bap_tab, ref_block->bap[ch]);
1473             }
1474             mantissa_bits += s->ac3dsp.compute_mantissa_size(mant_cnt,
1475                                                              ref_block->bap[ch]+s->start_freq[ch],
1476                                                              block->end_freq[ch]-s->start_freq[ch]);
1477             if (ch == CPL_CH)
1478                 ch = ch0;
1479         }
1480         mantissa_bits += compute_mantissa_size_final(mant_cnt);
1481     }
1482     return mantissa_bits;
1483 }
1484
1485
1486 /**
1487  * Constant bitrate bit allocation search.
1488  * Find the largest SNR offset that will allow data to fit in the frame.
1489  */
1490 static int cbr_bit_allocation(AC3EncodeContext *s)
1491 {
1492     int ch;
1493     int bits_left;
1494     int snr_offset, snr_incr;
1495
1496     bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1497     if (bits_left < 0)
1498         return AVERROR(EINVAL);
1499
1500     snr_offset = s->coarse_snr_offset << 4;
1501
1502     /* if previous frame SNR offset was 1023, check if current frame can also
1503        use SNR offset of 1023. if so, skip the search. */
1504     if ((snr_offset | s->fine_snr_offset[1]) == 1023) {
1505         if (bit_alloc(s, 1023) <= bits_left)
1506             return 0;
1507     }
1508
1509     while (snr_offset >= 0 &&
1510            bit_alloc(s, snr_offset) > bits_left) {
1511         snr_offset -= 64;
1512     }
1513     if (snr_offset < 0)
1514         return AVERROR(EINVAL);
1515
1516     FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1517     for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1518         while (snr_offset + snr_incr <= 1023 &&
1519                bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1520             snr_offset += snr_incr;
1521             FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1522         }
1523     }
1524     FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1525     reset_block_bap(s);
1526
1527     s->coarse_snr_offset = snr_offset >> 4;
1528     for (ch = !s->cpl_on; ch <= s->channels; ch++)
1529         s->fine_snr_offset[ch] = snr_offset & 0xF;
1530
1531     return 0;
1532 }
1533
1534
1535 /**
1536  * Downgrade exponent strategies to reduce the bits used by the exponents.
1537  * This is a fallback for when bit allocation fails with the normal exponent
1538  * strategies.  Each time this function is run it only downgrades the
1539  * strategy in 1 channel of 1 block.
1540  * @return non-zero if downgrade was unsuccessful
1541  */
1542 static int downgrade_exponents(AC3EncodeContext *s)
1543 {
1544     int ch, blk;
1545
1546     for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1547         for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
1548             if (s->exp_strategy[ch][blk] == EXP_D15) {
1549                 s->exp_strategy[ch][blk] = EXP_D25;
1550                 return 0;
1551             }
1552         }
1553     }
1554     for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1555         for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
1556             if (s->exp_strategy[ch][blk] == EXP_D25) {
1557                 s->exp_strategy[ch][blk] = EXP_D45;
1558                 return 0;
1559             }
1560         }
1561     }
1562     /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
1563        the block number > 0 */
1564     for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
1565         for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
1566             if (s->exp_strategy[ch][blk] > EXP_REUSE) {
1567                 s->exp_strategy[ch][blk] = EXP_REUSE;
1568                 return 0;
1569             }
1570         }
1571     }
1572     return -1;
1573 }
1574
1575
1576 /**
1577  * Perform bit allocation search.
1578  * Finds the SNR offset value that maximizes quality and fits in the specified
1579  * frame size.  Output is the SNR offset and a set of bit allocation pointers
1580  * used to quantize the mantissas.
1581  */
1582 static int compute_bit_allocation(AC3EncodeContext *s)
1583 {
1584     int ret;
1585
1586     count_frame_bits(s);
1587
1588     bit_alloc_masking(s);
1589
1590     ret = cbr_bit_allocation(s);
1591     while (ret) {
1592         /* fallback 1: disable channel coupling */
1593         if (s->cpl_on) {
1594             s->cpl_on = 0;
1595             compute_coupling_strategy(s);
1596             compute_rematrixing_strategy(s);
1597             apply_rematrixing(s);
1598             process_exponents(s);
1599             ret = compute_bit_allocation(s);
1600             continue;
1601         }
1602
1603         /* fallback 2: downgrade exponents */
1604         if (!downgrade_exponents(s)) {
1605             extract_exponents(s);
1606             encode_exponents(s);
1607             group_exponents(s);
1608             ret = compute_bit_allocation(s);
1609             continue;
1610         }
1611
1612         /* fallbacks were not enough... */
1613         break;
1614     }
1615
1616     return ret;
1617 }
1618
1619
1620 /**
1621  * Symmetric quantization on 'levels' levels.
1622  */
1623 static inline int sym_quant(int c, int e, int levels)
1624 {
1625     int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1626     av_assert2(v >= 0 && v < levels);
1627     return v;
1628 }
1629
1630
1631 /**
1632  * Asymmetric quantization on 2^qbits levels.
1633  */
1634 static inline int asym_quant(int c, int e, int qbits)
1635 {
1636     int lshift, m, v;
1637
1638     lshift = e + qbits - 24;
1639     if (lshift >= 0)
1640         v = c << lshift;
1641     else
1642         v = c >> (-lshift);
1643     /* rounding */
1644     v = (v + 1) >> 1;
1645     m = (1 << (qbits-1));
1646     if (v >= m)
1647         v = m - 1;
1648     av_assert2(v >= -m);
1649     return v & ((1 << qbits)-1);
1650 }
1651
1652
1653 /**
1654  * Quantize a set of mantissas for a single channel in a single block.
1655  */
1656 static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1657                                       uint8_t *exp, uint8_t *bap,
1658                                       uint16_t *qmant, int start_freq,
1659                                       int end_freq)
1660 {
1661     int i;
1662
1663     for (i = start_freq; i < end_freq; i++) {
1664         int v;
1665         int c = fixed_coef[i];
1666         int e = exp[i];
1667         int b = bap[i];
1668         switch (b) {
1669         case 0:
1670             v = 0;
1671             break;
1672         case 1:
1673             v = sym_quant(c, e, 3);
1674             switch (s->mant1_cnt) {
1675             case 0:
1676                 s->qmant1_ptr = &qmant[i];
1677                 v = 9 * v;
1678                 s->mant1_cnt = 1;
1679                 break;
1680             case 1:
1681                 *s->qmant1_ptr += 3 * v;
1682                 s->mant1_cnt = 2;
1683                 v = 128;
1684                 break;
1685             default:
1686                 *s->qmant1_ptr += v;
1687                 s->mant1_cnt = 0;
1688                 v = 128;
1689                 break;
1690             }
1691             break;
1692         case 2:
1693             v = sym_quant(c, e, 5);
1694             switch (s->mant2_cnt) {
1695             case 0:
1696                 s->qmant2_ptr = &qmant[i];
1697                 v = 25 * v;
1698                 s->mant2_cnt = 1;
1699                 break;
1700             case 1:
1701                 *s->qmant2_ptr += 5 * v;
1702                 s->mant2_cnt = 2;
1703                 v = 128;
1704                 break;
1705             default:
1706                 *s->qmant2_ptr += v;
1707                 s->mant2_cnt = 0;
1708                 v = 128;
1709                 break;
1710             }
1711             break;
1712         case 3:
1713             v = sym_quant(c, e, 7);
1714             break;
1715         case 4:
1716             v = sym_quant(c, e, 11);
1717             switch (s->mant4_cnt) {
1718             case 0:
1719                 s->qmant4_ptr = &qmant[i];
1720                 v = 11 * v;
1721                 s->mant4_cnt = 1;
1722                 break;
1723             default:
1724                 *s->qmant4_ptr += v;
1725                 s->mant4_cnt = 0;
1726                 v = 128;
1727                 break;
1728             }
1729             break;
1730         case 5:
1731             v = sym_quant(c, e, 15);
1732             break;
1733         case 14:
1734             v = asym_quant(c, e, 14);
1735             break;
1736         case 15:
1737             v = asym_quant(c, e, 16);
1738             break;
1739         default:
1740             v = asym_quant(c, e, b - 1);
1741             break;
1742         }
1743         qmant[i] = v;
1744     }
1745 }
1746
1747
1748 /**
1749  * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1750  */
1751 static void quantize_mantissas(AC3EncodeContext *s)
1752 {
1753     int blk, ch, ch0=0, got_cpl;
1754
1755     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1756         AC3Block *block = &s->blocks[blk];
1757         AC3Block *ref_block;
1758         AC3Mant m = { 0 };
1759
1760         got_cpl = !block->cpl_in_use;
1761         for (ch = 1; ch <= s->channels; ch++) {
1762             if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1763                 ch0     = ch - 1;
1764                 ch      = CPL_CH;
1765                 got_cpl = 1;
1766             }
1767             ref_block = block->exp_ref_block[ch];
1768             quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1769                                       ref_block->exp[ch],
1770                                       ref_block->bap[ch], block->qmant[ch],
1771                                       s->start_freq[ch], block->end_freq[ch]);
1772             if (ch == CPL_CH)
1773                 ch = ch0;
1774         }
1775     }
1776 }
1777
1778
1779 /**
1780  * Write the AC-3 frame header to the output bitstream.
1781  */
1782 static void output_frame_header(AC3EncodeContext *s)
1783 {
1784     AC3EncOptions *opt = &s->options;
1785
1786     put_bits(&s->pb, 16, 0x0b77);   /* frame header */
1787     put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
1788     put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
1789     put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1790     put_bits(&s->pb, 5,  s->bitstream_id);
1791     put_bits(&s->pb, 3,  s->bitstream_mode);
1792     put_bits(&s->pb, 3,  s->channel_mode);
1793     if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1794         put_bits(&s->pb, 2, s->center_mix_level);
1795     if (s->channel_mode & 0x04)
1796         put_bits(&s->pb, 2, s->surround_mix_level);
1797     if (s->channel_mode == AC3_CHMODE_STEREO)
1798         put_bits(&s->pb, 2, opt->dolby_surround_mode);
1799     put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1800     put_bits(&s->pb, 5, -opt->dialogue_level);
1801     put_bits(&s->pb, 1, 0);         /* no compression control word */
1802     put_bits(&s->pb, 1, 0);         /* no lang code */
1803     put_bits(&s->pb, 1, opt->audio_production_info);
1804     if (opt->audio_production_info) {
1805         put_bits(&s->pb, 5, opt->mixing_level - 80);
1806         put_bits(&s->pb, 2, opt->room_type);
1807     }
1808     put_bits(&s->pb, 1, opt->copyright);
1809     put_bits(&s->pb, 1, opt->original);
1810     if (s->bitstream_id == 6) {
1811         /* alternate bit stream syntax */
1812         put_bits(&s->pb, 1, opt->extended_bsi_1);
1813         if (opt->extended_bsi_1) {
1814             put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1815             put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1816             put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1817             put_bits(&s->pb, 3, s->loro_center_mix_level);
1818             put_bits(&s->pb, 3, s->loro_surround_mix_level);
1819         }
1820         put_bits(&s->pb, 1, opt->extended_bsi_2);
1821         if (opt->extended_bsi_2) {
1822             put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1823             put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1824             put_bits(&s->pb, 1, opt->ad_converter_type);
1825             put_bits(&s->pb, 9, 0);     /* xbsi2 and encinfo : reserved */
1826         }
1827     } else {
1828     put_bits(&s->pb, 1, 0);         /* no time code 1 */
1829     put_bits(&s->pb, 1, 0);         /* no time code 2 */
1830     }
1831     put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
1832 }
1833
1834
1835 /**
1836  * Write one audio block to the output bitstream.
1837  */
1838 static void output_audio_block(AC3EncodeContext *s, int blk)
1839 {
1840     int ch, i, baie, bnd, got_cpl;
1841     int av_uninit(ch0);
1842     AC3Block *block = &s->blocks[blk];
1843
1844     /* block switching */
1845     for (ch = 0; ch < s->fbw_channels; ch++)
1846         put_bits(&s->pb, 1, 0);
1847
1848     /* dither flags */
1849     for (ch = 0; ch < s->fbw_channels; ch++)
1850         put_bits(&s->pb, 1, 1);
1851
1852     /* dynamic range codes */
1853     put_bits(&s->pb, 1, 0);
1854
1855     /* channel coupling */
1856     put_bits(&s->pb, 1, block->new_cpl_strategy);
1857     if (block->new_cpl_strategy) {
1858         put_bits(&s->pb, 1, block->cpl_in_use);
1859         if (block->cpl_in_use) {
1860             int start_sub, end_sub;
1861             for (ch = 1; ch <= s->fbw_channels; ch++)
1862                 put_bits(&s->pb, 1, block->channel_in_cpl[ch]);
1863             if (s->channel_mode == AC3_CHMODE_STEREO)
1864                 put_bits(&s->pb, 1, 0); /* phase flags in use */
1865             start_sub = (s->start_freq[CPL_CH] - 37) / 12;
1866             end_sub   = (s->cpl_end_freq       - 37) / 12;
1867             put_bits(&s->pb, 4, start_sub);
1868             put_bits(&s->pb, 4, end_sub - 3);
1869             for (bnd = start_sub+1; bnd < end_sub; bnd++)
1870                 put_bits(&s->pb, 1, ff_eac3_default_cpl_band_struct[bnd]);
1871         }
1872     }
1873
1874     /* coupling coordinates */
1875     if (block->cpl_in_use) {
1876         for (ch = 1; ch <= s->fbw_channels; ch++) {
1877             if (block->channel_in_cpl[ch]) {
1878                 put_bits(&s->pb, 1, block->new_cpl_coords);
1879                 if (block->new_cpl_coords) {
1880                     put_bits(&s->pb, 2, block->cpl_master_exp[ch]);
1881                     for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
1882                         put_bits(&s->pb, 4, block->cpl_coord_exp [ch][bnd]);
1883                         put_bits(&s->pb, 4, block->cpl_coord_mant[ch][bnd]);
1884                     }
1885                 }
1886             }
1887         }
1888     }
1889
1890     /* stereo rematrixing */
1891     if (s->channel_mode == AC3_CHMODE_STEREO) {
1892         put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1893         if (block->new_rematrixing_strategy) {
1894             /* rematrixing flags */
1895             for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++)
1896                 put_bits(&s->pb, 1, block->rematrixing_flags[bnd]);
1897         }
1898     }
1899
1900     /* exponent strategy */
1901     for (ch = !block->cpl_in_use; ch <= s->fbw_channels; ch++)
1902         put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1903     if (s->lfe_on)
1904         put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1905
1906     /* bandwidth */
1907     for (ch = 1; ch <= s->fbw_channels; ch++) {
1908         if (s->exp_strategy[ch][blk] != EXP_REUSE && !block->channel_in_cpl[ch])
1909             put_bits(&s->pb, 6, s->bandwidth_code);
1910     }
1911
1912     /* exponents */
1913     for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1914         int nb_groups;
1915         int cpl = (ch == CPL_CH);
1916
1917         if (s->exp_strategy[ch][blk] == EXP_REUSE)
1918             continue;
1919
1920         /* DC exponent */
1921         put_bits(&s->pb, 4, block->grouped_exp[ch][0] >> cpl);
1922
1923         /* exponent groups */
1924         nb_groups = exponent_group_tab[cpl][s->exp_strategy[ch][blk]-1][block->end_freq[ch]-s->start_freq[ch]];
1925         for (i = 1; i <= nb_groups; i++)
1926             put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1927
1928         /* gain range info */
1929         if (ch != s->lfe_channel && !cpl)
1930             put_bits(&s->pb, 2, 0);
1931     }
1932
1933     /* bit allocation info */
1934     baie = (blk == 0);
1935     put_bits(&s->pb, 1, baie);
1936     if (baie) {
1937         put_bits(&s->pb, 2, s->slow_decay_code);
1938         put_bits(&s->pb, 2, s->fast_decay_code);
1939         put_bits(&s->pb, 2, s->slow_gain_code);
1940         put_bits(&s->pb, 2, s->db_per_bit_code);
1941         put_bits(&s->pb, 3, s->floor_code);
1942     }
1943
1944     /* snr offset */
1945     put_bits(&s->pb, 1, block->new_snr_offsets);
1946     if (block->new_snr_offsets) {
1947         put_bits(&s->pb, 6, s->coarse_snr_offset);
1948         for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1949             put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1950             put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1951         }
1952     }
1953
1954     /* coupling leak */
1955     if (block->cpl_in_use) {
1956         put_bits(&s->pb, 1, block->new_cpl_leak);
1957         if (block->new_cpl_leak) {
1958             put_bits(&s->pb, 3, s->bit_alloc.cpl_fast_leak);
1959             put_bits(&s->pb, 3, s->bit_alloc.cpl_slow_leak);
1960         }
1961     }
1962
1963     put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1964     put_bits(&s->pb, 1, 0); /* no data to skip */
1965
1966     /* mantissas */
1967     got_cpl = !block->cpl_in_use;
1968     for (ch = 1; ch <= s->channels; ch++) {
1969         int b, q;
1970         AC3Block *ref_block;
1971
1972         if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1973             ch0     = ch - 1;
1974             ch      = CPL_CH;
1975             got_cpl = 1;
1976         }
1977         ref_block = block->exp_ref_block[ch];
1978         for (i = s->start_freq[ch]; i < block->end_freq[ch]; i++) {
1979             q = block->qmant[ch][i];
1980             b = ref_block->bap[ch][i];
1981             switch (b) {
1982             case 0:                                         break;
1983             case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
1984             case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
1985             case 3:               put_bits(&s->pb,   3, q); break;
1986             case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
1987             case 14:              put_bits(&s->pb,  14, q); break;
1988             case 15:              put_bits(&s->pb,  16, q); break;
1989             default:              put_bits(&s->pb, b-1, q); break;
1990             }
1991         }
1992         if (ch == CPL_CH)
1993             ch = ch0;
1994     }
1995 }
1996
1997
1998 /** CRC-16 Polynomial */
1999 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
2000
2001
2002 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
2003 {
2004     unsigned int c;
2005
2006     c = 0;
2007     while (a) {
2008         if (a & 1)
2009             c ^= b;
2010         a = a >> 1;
2011         b = b << 1;
2012         if (b & (1 << 16))
2013             b ^= poly;
2014     }
2015     return c;
2016 }
2017
2018
2019 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
2020 {
2021     unsigned int r;
2022     r = 1;
2023     while (n) {
2024         if (n & 1)
2025             r = mul_poly(r, a, poly);
2026         a = mul_poly(a, a, poly);
2027         n >>= 1;
2028     }
2029     return r;
2030 }
2031
2032
2033 /**
2034  * Fill the end of the frame with 0's and compute the two CRCs.
2035  */
2036 static void output_frame_end(AC3EncodeContext *s)
2037 {
2038     const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
2039     int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
2040     uint8_t *frame;
2041
2042     frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
2043
2044     /* pad the remainder of the frame with zeros */
2045     av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
2046     flush_put_bits(&s->pb);
2047     frame = s->pb.buf;
2048     pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
2049     av_assert2(pad_bytes >= 0);
2050     if (pad_bytes > 0)
2051         memset(put_bits_ptr(&s->pb), 0, pad_bytes);
2052
2053     /* compute crc1 */
2054     /* this is not so easy because it is at the beginning of the data... */
2055     crc1    = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
2056     crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
2057     crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
2058     AV_WB16(frame + 2, crc1);
2059
2060     /* compute crc2 */
2061     crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
2062                           s->frame_size - frame_size_58 - 3);
2063     crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
2064     /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
2065     if (crc2 == 0x770B) {
2066         frame[s->frame_size - 3] ^= 0x1;
2067         crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
2068     }
2069     crc2 = av_bswap16(crc2);
2070     AV_WB16(frame + s->frame_size - 2, crc2);
2071 }
2072
2073
2074 /**
2075  * Write the frame to the output bitstream.
2076  */
2077 static void output_frame(AC3EncodeContext *s, unsigned char *frame)
2078 {
2079     int blk;
2080
2081     init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
2082
2083     output_frame_header(s);
2084
2085     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2086         output_audio_block(s, blk);
2087
2088     output_frame_end(s);
2089 }
2090
2091
2092 static void dprint_options(AVCodecContext *avctx)
2093 {
2094 #ifdef DEBUG
2095     AC3EncodeContext *s = avctx->priv_data;
2096     AC3EncOptions *opt = &s->options;
2097     char strbuf[32];
2098
2099     switch (s->bitstream_id) {
2100     case  6:  av_strlcpy(strbuf, "AC-3 (alt syntax)", 32);      break;
2101     case  8:  av_strlcpy(strbuf, "AC-3 (standard)", 32);        break;
2102     case  9:  av_strlcpy(strbuf, "AC-3 (dnet half-rate)", 32);  break;
2103     case 10:  av_strlcpy(strbuf, "AC-3 (dnet quater-rate", 32); break;
2104     default: snprintf(strbuf, 32, "ERROR");
2105     }
2106     av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
2107     av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
2108     av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
2109     av_dlog(avctx, "channel_layout: %s\n", strbuf);
2110     av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
2111     av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
2112     if (s->cutoff)
2113         av_dlog(avctx, "cutoff: %d\n", s->cutoff);
2114
2115     av_dlog(avctx, "per_frame_metadata: %s\n",
2116             opt->allow_per_frame_metadata?"on":"off");
2117     if (s->has_center)
2118         av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
2119                 s->center_mix_level);
2120     else
2121         av_dlog(avctx, "center_mixlev: {not written}\n");
2122     if (s->has_surround)
2123         av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
2124                 s->surround_mix_level);
2125     else
2126         av_dlog(avctx, "surround_mixlev: {not written}\n");
2127     if (opt->audio_production_info) {
2128         av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
2129         switch (opt->room_type) {
2130         case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
2131         case 1:  av_strlcpy(strbuf, "large", 32);        break;
2132         case 2:  av_strlcpy(strbuf, "small", 32);        break;
2133         default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
2134         }
2135         av_dlog(avctx, "room_type: %s\n", strbuf);
2136     } else {
2137         av_dlog(avctx, "mixing_level: {not written}\n");
2138         av_dlog(avctx, "room_type: {not written}\n");
2139     }
2140     av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
2141     av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
2142     if (s->channel_mode == AC3_CHMODE_STEREO) {
2143         switch (opt->dolby_surround_mode) {
2144         case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
2145         case 1:  av_strlcpy(strbuf, "on", 32);           break;
2146         case 2:  av_strlcpy(strbuf, "off", 32);          break;
2147         default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
2148         }
2149         av_dlog(avctx, "dsur_mode: %s\n", strbuf);
2150     } else {
2151         av_dlog(avctx, "dsur_mode: {not written}\n");
2152     }
2153     av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
2154
2155     if (s->bitstream_id == 6) {
2156         if (opt->extended_bsi_1) {
2157             switch (opt->preferred_stereo_downmix) {
2158             case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
2159             case 1:  av_strlcpy(strbuf, "ltrt", 32);         break;
2160             case 2:  av_strlcpy(strbuf, "loro", 32);         break;
2161             default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
2162             }
2163             av_dlog(avctx, "dmix_mode: %s\n", strbuf);
2164             av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
2165                     opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
2166             av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
2167                     opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
2168             av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
2169                     opt->loro_center_mix_level, s->loro_center_mix_level);
2170             av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
2171                     opt->loro_surround_mix_level, s->loro_surround_mix_level);
2172         } else {
2173             av_dlog(avctx, "extended bitstream info 1: {not written}\n");
2174         }
2175         if (opt->extended_bsi_2) {
2176             switch (opt->dolby_surround_ex_mode) {
2177             case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
2178             case 1:  av_strlcpy(strbuf, "on", 32);           break;
2179             case 2:  av_strlcpy(strbuf, "off", 32);          break;
2180             default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
2181             }
2182             av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
2183             switch (opt->dolby_headphone_mode) {
2184             case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
2185             case 1:  av_strlcpy(strbuf, "on", 32);           break;
2186             case 2:  av_strlcpy(strbuf, "off", 32);          break;
2187             default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
2188             }
2189             av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
2190
2191             switch (opt->ad_converter_type) {
2192             case 0:  av_strlcpy(strbuf, "standard", 32); break;
2193             case 1:  av_strlcpy(strbuf, "hdcd", 32);     break;
2194             default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
2195             }
2196             av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
2197         } else {
2198             av_dlog(avctx, "extended bitstream info 2: {not written}\n");
2199         }
2200     }
2201 #endif
2202 }
2203
2204
2205 #define FLT_OPTION_THRESHOLD 0.01
2206
2207 static int validate_float_option(float v, const float *v_list, int v_list_size)
2208 {
2209     int i;
2210
2211     for (i = 0; i < v_list_size; i++) {
2212         if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
2213             v > (v_list[i] - FLT_OPTION_THRESHOLD))
2214             break;
2215     }
2216     if (i == v_list_size)
2217         return -1;
2218
2219     return i;
2220 }
2221
2222
2223 static void validate_mix_level(void *log_ctx, const char *opt_name,
2224                                float *opt_param, const float *list,
2225                                int list_size, int default_value, int min_value,
2226                                int *ctx_param)
2227 {
2228     int mixlev = validate_float_option(*opt_param, list, list_size);
2229     if (mixlev < min_value) {
2230         mixlev = default_value;
2231         if (*opt_param >= 0.0) {
2232             av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
2233                    "default value: %0.3f\n", opt_name, list[mixlev]);
2234         }
2235     }
2236     *opt_param = list[mixlev];
2237     *ctx_param = mixlev;
2238 }
2239
2240
2241 /**
2242  * Validate metadata options as set by AVOption system.
2243  * These values can optionally be changed per-frame.
2244  */
2245 static int validate_metadata(AVCodecContext *avctx)
2246 {
2247     AC3EncodeContext *s = avctx->priv_data;
2248     AC3EncOptions *opt = &s->options;
2249
2250     /* validate mixing levels */
2251     if (s->has_center) {
2252         validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
2253                            cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
2254                            &s->center_mix_level);
2255     }
2256     if (s->has_surround) {
2257         validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
2258                            surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
2259                            &s->surround_mix_level);
2260     }
2261
2262     /* set audio production info flag */
2263     if (opt->mixing_level >= 0 || opt->room_type >= 0) {
2264         if (opt->mixing_level < 0) {
2265             av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
2266                    "room_type is set\n");
2267             return AVERROR(EINVAL);
2268         }
2269         if (opt->mixing_level < 80) {
2270             av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
2271                    "80dB and 111dB\n");
2272             return AVERROR(EINVAL);
2273         }
2274         /* default room type */
2275         if (opt->room_type < 0)
2276             opt->room_type = 0;
2277         opt->audio_production_info = 1;
2278     } else {
2279         opt->audio_production_info = 0;
2280     }
2281
2282     /* set extended bsi 1 flag */
2283     if ((s->has_center || s->has_surround) &&
2284         (opt->preferred_stereo_downmix >= 0 ||
2285          opt->ltrt_center_mix_level   >= 0 ||
2286          opt->ltrt_surround_mix_level >= 0 ||
2287          opt->loro_center_mix_level   >= 0 ||
2288          opt->loro_surround_mix_level >= 0)) {
2289         /* default preferred stereo downmix */
2290         if (opt->preferred_stereo_downmix < 0)
2291             opt->preferred_stereo_downmix = 0;
2292         /* validate Lt/Rt center mix level */
2293         validate_mix_level(avctx, "ltrt_center_mix_level",
2294                            &opt->ltrt_center_mix_level, extmixlev_options,
2295                            EXTMIXLEV_NUM_OPTIONS, 5, 0,
2296                            &s->ltrt_center_mix_level);
2297         /* validate Lt/Rt surround mix level */
2298         validate_mix_level(avctx, "ltrt_surround_mix_level",
2299                            &opt->ltrt_surround_mix_level, extmixlev_options,
2300                            EXTMIXLEV_NUM_OPTIONS, 6, 3,
2301                            &s->ltrt_surround_mix_level);
2302         /* validate Lo/Ro center mix level */
2303         validate_mix_level(avctx, "loro_center_mix_level",
2304                            &opt->loro_center_mix_level, extmixlev_options,
2305                            EXTMIXLEV_NUM_OPTIONS, 5, 0,
2306                            &s->loro_center_mix_level);
2307         /* validate Lo/Ro surround mix level */
2308         validate_mix_level(avctx, "loro_surround_mix_level",
2309                            &opt->loro_surround_mix_level, extmixlev_options,
2310                            EXTMIXLEV_NUM_OPTIONS, 6, 3,
2311                            &s->loro_surround_mix_level);
2312         opt->extended_bsi_1 = 1;
2313     } else {
2314         opt->extended_bsi_1 = 0;
2315     }
2316
2317     /* set extended bsi 2 flag */
2318     if (opt->dolby_surround_ex_mode >= 0 ||
2319         opt->dolby_headphone_mode   >= 0 ||
2320         opt->ad_converter_type      >= 0) {
2321         /* default dolby surround ex mode */
2322         if (opt->dolby_surround_ex_mode < 0)
2323             opt->dolby_surround_ex_mode = 0;
2324         /* default dolby headphone mode */
2325         if (opt->dolby_headphone_mode < 0)
2326             opt->dolby_headphone_mode = 0;
2327         /* default A/D converter type */
2328         if (opt->ad_converter_type < 0)
2329             opt->ad_converter_type = 0;
2330         opt->extended_bsi_2 = 1;
2331     } else {
2332         opt->extended_bsi_2 = 0;
2333     }
2334
2335     /* set bitstream id for alternate bitstream syntax */
2336     if (opt->extended_bsi_1 || opt->extended_bsi_2) {
2337         if (s->bitstream_id > 8 && s->bitstream_id < 11) {
2338             static int warn_once = 1;
2339             if (warn_once) {
2340                 av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
2341                        "not compatible with reduced samplerates. writing of "
2342                        "extended bitstream information will be disabled.\n");
2343                 warn_once = 0;
2344             }
2345         } else {
2346             s->bitstream_id = 6;
2347         }
2348     }
2349
2350     return 0;
2351 }
2352
2353
2354 /**
2355  * Encode a single AC-3 frame.
2356  */
2357 static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
2358                             int buf_size, void *data)
2359 {
2360     AC3EncodeContext *s = avctx->priv_data;
2361     const SampleType *samples = data;
2362     int ret;
2363
2364     if (s->options.allow_per_frame_metadata) {
2365         ret = validate_metadata(avctx);
2366         if (ret)
2367             return ret;
2368     }
2369
2370     if (s->bit_alloc.sr_code == 1)
2371         adjust_frame_size(s);
2372
2373     deinterleave_input_samples(s, samples);
2374
2375     apply_mdct(s);
2376
2377     scale_coefficients(s);
2378
2379     s->cpl_on = s->cpl_enabled;
2380     compute_coupling_strategy(s);
2381
2382     if (s->cpl_on)
2383         apply_channel_coupling(s);
2384
2385     compute_rematrixing_strategy(s);
2386
2387     apply_rematrixing(s);
2388
2389     process_exponents(s);
2390
2391     ret = compute_bit_allocation(s);
2392     if (ret) {
2393         av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
2394         return ret;
2395     }
2396
2397     quantize_mantissas(s);
2398
2399     output_frame(s, frame);
2400
2401     return s->frame_size;
2402 }
2403
2404
2405 /**
2406  * Finalize encoding and free any memory allocated by the encoder.
2407  */
2408 static av_cold int ac3_encode_close(AVCodecContext *avctx)
2409 {
2410     int blk, ch;
2411     AC3EncodeContext *s = avctx->priv_data;
2412
2413     for (ch = 0; ch < s->channels; ch++)
2414         av_freep(&s->planar_samples[ch]);
2415     av_freep(&s->planar_samples);
2416     av_freep(&s->bap_buffer);
2417     av_freep(&s->bap1_buffer);
2418     av_freep(&s->mdct_coef_buffer);
2419     av_freep(&s->fixed_coef_buffer);
2420     av_freep(&s->exp_buffer);
2421     av_freep(&s->grouped_exp_buffer);
2422     av_freep(&s->psd_buffer);
2423     av_freep(&s->band_psd_buffer);
2424     av_freep(&s->mask_buffer);
2425     av_freep(&s->qmant_buffer);
2426     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2427         AC3Block *block = &s->blocks[blk];
2428         av_freep(&block->bap);
2429         av_freep(&block->mdct_coef);
2430         av_freep(&block->fixed_coef);
2431         av_freep(&block->exp);
2432         av_freep(&block->grouped_exp);
2433         av_freep(&block->psd);
2434         av_freep(&block->band_psd);
2435         av_freep(&block->mask);
2436         av_freep(&block->qmant);
2437     }
2438
2439     mdct_end(&s->mdct);
2440
2441     av_freep(&avctx->coded_frame);
2442     return 0;
2443 }
2444
2445
2446 /**
2447  * Set channel information during initialization.
2448  */
2449 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
2450                                     int64_t *channel_layout)
2451 {
2452     int ch_layout;
2453
2454     if (channels < 1 || channels > AC3_MAX_CHANNELS)
2455         return AVERROR(EINVAL);
2456     if ((uint64_t)*channel_layout > 0x7FF)
2457         return AVERROR(EINVAL);
2458     ch_layout = *channel_layout;
2459     if (!ch_layout)
2460         ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
2461
2462     s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
2463     s->channels     = channels;
2464     s->fbw_channels = channels - s->lfe_on;
2465     s->lfe_channel  = s->lfe_on ? s->fbw_channels + 1 : -1;
2466     if (s->lfe_on)
2467         ch_layout -= AV_CH_LOW_FREQUENCY;
2468
2469     switch (ch_layout) {
2470     case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
2471     case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
2472     case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
2473     case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
2474     case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
2475     case AV_CH_LAYOUT_QUAD:
2476     case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
2477     case AV_CH_LAYOUT_5POINT0:
2478     case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
2479     default:
2480         return AVERROR(EINVAL);
2481     }
2482     s->has_center   = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
2483     s->has_surround =  s->channel_mode & 0x04;
2484
2485     s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
2486     *channel_layout = ch_layout;
2487     if (s->lfe_on)
2488         *channel_layout |= AV_CH_LOW_FREQUENCY;
2489
2490     return 0;
2491 }
2492
2493
2494 static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
2495 {
2496     int i, ret;
2497
2498     /* validate channel layout */
2499     if (!avctx->channel_layout) {
2500         av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
2501                                       "encoder will guess the layout, but it "
2502                                       "might be incorrect.\n");
2503     }
2504     ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
2505     if (ret) {
2506         av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
2507         return ret;
2508     }
2509
2510     /* validate sample rate */
2511     for (i = 0; i < 9; i++) {
2512         if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
2513             break;
2514     }
2515     if (i == 9) {
2516         av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
2517         return AVERROR(EINVAL);
2518     }
2519     s->sample_rate        = avctx->sample_rate;
2520     s->bit_alloc.sr_shift = i % 3;
2521     s->bit_alloc.sr_code  = i / 3;
2522     s->bitstream_id       = 8 + s->bit_alloc.sr_shift;
2523
2524     /* validate bit rate */
2525     for (i = 0; i < 19; i++) {
2526         if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
2527             break;
2528     }
2529     if (i == 19) {
2530         av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2531         return AVERROR(EINVAL);
2532     }
2533     s->bit_rate        = avctx->bit_rate;
2534     s->frame_size_code = i << 1;
2535
2536     /* validate cutoff */
2537     if (avctx->cutoff < 0) {
2538         av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2539         return AVERROR(EINVAL);
2540     }
2541     s->cutoff = avctx->cutoff;
2542     if (s->cutoff > (s->sample_rate >> 1))
2543         s->cutoff = s->sample_rate >> 1;
2544
2545     /* validate audio service type / channels combination */
2546     if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
2547          avctx->channels == 1) ||
2548         ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
2549           avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY  ||
2550           avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
2551          && avctx->channels > 1)) {
2552         av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
2553                                     "specified number of channels\n");
2554         return AVERROR(EINVAL);
2555     }
2556
2557     ret = validate_metadata(avctx);
2558     if (ret)
2559         return ret;
2560
2561     s->rematrixing_enabled = s->options.stereo_rematrixing &&
2562                              (s->channel_mode == AC3_CHMODE_STEREO);
2563
2564     s->cpl_enabled = s->options.channel_coupling &&
2565                      s->channel_mode >= AC3_CHMODE_STEREO &&
2566                      CONFIG_AC3ENC_FLOAT;
2567
2568     return 0;
2569 }
2570
2571
2572 /**
2573  * Set bandwidth for all channels.
2574  * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2575  * default value will be used.
2576  */
2577 static av_cold void set_bandwidth(AC3EncodeContext *s)
2578 {
2579     int blk, ch;
2580     int av_uninit(cpl_start);
2581
2582     if (s->cutoff) {
2583         /* calculate bandwidth based on user-specified cutoff frequency */
2584         int fbw_coeffs;
2585         fbw_coeffs     = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2586         s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2587     } else {
2588         /* use default bandwidth setting */
2589         s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2590     }
2591
2592     /* set number of coefficients for each channel */
2593     for (ch = 1; ch <= s->fbw_channels; ch++) {
2594         s->start_freq[ch] = 0;
2595         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2596             s->blocks[blk].end_freq[ch] = s->bandwidth_code * 3 + 73;
2597     }
2598     /* LFE channel always has 7 coefs */
2599     if (s->lfe_on) {
2600         s->start_freq[s->lfe_channel] = 0;
2601         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2602             s->blocks[blk].end_freq[ch] = 7;
2603     }
2604
2605     /* initialize coupling strategy */
2606     if (s->cpl_enabled) {
2607         if (s->options.cpl_start >= 0) {
2608             cpl_start = s->options.cpl_start;
2609         } else {
2610             cpl_start = ac3_coupling_start_tab[s->channel_mode-2][s->bit_alloc.sr_code][s->frame_size_code/2];
2611             if (cpl_start < 0)
2612                 s->cpl_enabled = 0;
2613         }
2614     }
2615     if (s->cpl_enabled) {
2616         int i, cpl_start_band, cpl_end_band;
2617         uint8_t *cpl_band_sizes = s->cpl_band_sizes;
2618
2619         cpl_end_band   = s->bandwidth_code / 4 + 3;
2620         cpl_start_band = av_clip(cpl_start, 0, FFMIN(cpl_end_band-1, 15));
2621
2622         s->num_cpl_subbands = cpl_end_band - cpl_start_band;
2623
2624         s->num_cpl_bands = 1;
2625         *cpl_band_sizes  = 12;
2626         for (i = cpl_start_band + 1; i < cpl_end_band; i++) {
2627             if (ff_eac3_default_cpl_band_struct[i]) {
2628                 *cpl_band_sizes += 12;
2629             } else {
2630                 s->num_cpl_bands++;
2631                 cpl_band_sizes++;
2632                 *cpl_band_sizes = 12;
2633             }
2634         }
2635
2636         s->start_freq[CPL_CH] = cpl_start_band * 12 + 37;
2637         s->cpl_end_freq       = cpl_end_band   * 12 + 37;
2638         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2639             s->blocks[blk].end_freq[CPL_CH] = s->cpl_end_freq;
2640     }
2641 }
2642
2643
2644 static av_cold int allocate_buffers(AVCodecContext *avctx)
2645 {
2646     int blk, ch;
2647     AC3EncodeContext *s = avctx->priv_data;
2648     int channels = s->channels + 1; /* includes coupling channel */
2649
2650     FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
2651                      alloc_fail);
2652     for (ch = 0; ch < s->channels; ch++) {
2653         FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
2654                           (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
2655                           alloc_fail);
2656     }
2657     FF_ALLOC_OR_GOTO(avctx, s->bap_buffer,  AC3_MAX_BLOCKS * channels *
2658                      AC3_MAX_COEFS * sizeof(*s->bap_buffer),  alloc_fail);
2659     FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * channels *
2660                      AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
2661     FF_ALLOCZ_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * channels *
2662                       AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
2663     FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * channels *
2664                      AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
2665     FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * channels *
2666                      128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
2667     FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * channels *
2668                      AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
2669     FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * channels *
2670                      64 * sizeof(*s->band_psd_buffer), alloc_fail);
2671     FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * channels *
2672                      64 * sizeof(*s->mask_buffer), alloc_fail);
2673     FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * channels *
2674                      AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
2675     if (s->cpl_enabled) {
2676         FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_exp_buffer, AC3_MAX_BLOCKS * channels *
2677                          16 * sizeof(*s->cpl_coord_exp_buffer), alloc_fail);
2678         FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_mant_buffer, AC3_MAX_BLOCKS * channels *
2679                          16 * sizeof(*s->cpl_coord_mant_buffer), alloc_fail);
2680     }
2681     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2682         AC3Block *block = &s->blocks[blk];
2683         FF_ALLOC_OR_GOTO(avctx, block->bap, channels * sizeof(*block->bap),
2684                          alloc_fail);
2685         FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, channels * sizeof(*block->mdct_coef),
2686                           alloc_fail);
2687         FF_ALLOCZ_OR_GOTO(avctx, block->exp, channels * sizeof(*block->exp),
2688                           alloc_fail);
2689         FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, channels * sizeof(*block->grouped_exp),
2690                           alloc_fail);
2691         FF_ALLOCZ_OR_GOTO(avctx, block->psd, channels * sizeof(*block->psd),
2692                           alloc_fail);
2693         FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, channels * sizeof(*block->band_psd),
2694                           alloc_fail);
2695         FF_ALLOCZ_OR_GOTO(avctx, block->mask, channels * sizeof(*block->mask),
2696                           alloc_fail);
2697         FF_ALLOCZ_OR_GOTO(avctx, block->qmant, channels * sizeof(*block->qmant),
2698                           alloc_fail);
2699         if (s->cpl_enabled) {
2700             FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_exp, channels * sizeof(*block->cpl_coord_exp),
2701                               alloc_fail);
2702             FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_mant, channels * sizeof(*block->cpl_coord_mant),
2703                               alloc_fail);
2704         }
2705
2706         for (ch = 0; ch < channels; ch++) {
2707             /* arrangement: block, channel, coeff */
2708             block->bap[ch]         = &s->bap_buffer        [AC3_MAX_COEFS * (blk * channels + ch)];
2709             block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * channels + ch)];
2710             block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * channels + ch)];
2711             block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * channels + ch)];
2712             block->mask[ch]        = &s->mask_buffer       [64            * (blk * channels + ch)];
2713             block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * channels + ch)];
2714             if (s->cpl_enabled) {
2715                 block->cpl_coord_exp[ch]  = &s->cpl_coord_exp_buffer [16  * (blk * channels + ch)];
2716                 block->cpl_coord_mant[ch] = &s->cpl_coord_mant_buffer[16  * (blk * channels + ch)];
2717             }
2718
2719             /* arrangement: channel, block, coeff */
2720             block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2721             block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2722         }
2723     }
2724
2725     if (CONFIG_AC3ENC_FLOAT) {
2726         FF_ALLOCZ_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * channels *
2727                           AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
2728         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2729             AC3Block *block = &s->blocks[blk];
2730             FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2731                               sizeof(*block->fixed_coef), alloc_fail);
2732             for (ch = 0; ch < channels; ch++)
2733                 block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2734         }
2735     } else {
2736         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2737             AC3Block *block = &s->blocks[blk];
2738             FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2739                               sizeof(*block->fixed_coef), alloc_fail);
2740             for (ch = 0; ch < channels; ch++)
2741                 block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2742         }
2743     }
2744
2745     return 0;
2746 alloc_fail:
2747     return AVERROR(ENOMEM);
2748 }
2749
2750
2751 /**
2752  * Initialize the encoder.
2753  */
2754 static av_cold int ac3_encode_init(AVCodecContext *avctx)
2755 {
2756     AC3EncodeContext *s = avctx->priv_data;
2757     int ret, frame_size_58;
2758
2759     avctx->frame_size = AC3_FRAME_SIZE;
2760
2761     ff_ac3_common_init();
2762
2763     ret = validate_options(avctx, s);
2764     if (ret)
2765         return ret;
2766
2767     s->bitstream_mode = avctx->audio_service_type;
2768     if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2769         s->bitstream_mode = 0x7;
2770
2771     s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2772     s->bits_written    = 0;
2773     s->samples_written = 0;
2774     s->frame_size      = s->frame_size_min;
2775
2776     /* calculate crc_inv for both possible frame sizes */
2777     frame_size_58 = (( s->frame_size    >> 2) + ( s->frame_size    >> 4)) << 1;
2778     s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2779     if (s->bit_alloc.sr_code == 1) {
2780         frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2781         s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2782     }
2783
2784     set_bandwidth(s);
2785
2786     exponent_init(s);
2787
2788     bit_alloc_init(s);
2789
2790     ret = mdct_init(avctx, &s->mdct, 9);
2791     if (ret)
2792         goto init_fail;
2793
2794     ret = allocate_buffers(avctx);
2795     if (ret)
2796         goto init_fail;
2797
2798     avctx->coded_frame= avcodec_alloc_frame();
2799
2800     dsputil_init(&s->dsp, avctx);
2801     ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2802
2803     dprint_options(avctx);
2804
2805     return 0;
2806 init_fail:
2807     ac3_encode_close(avctx);
2808     return ret;
2809 }