]> git.sesse.net Git - ffmpeg/blob - libavcodec/ac3enc.c
Merge remote branch 'qatar/master'
[ffmpeg] / libavcodec / ac3enc.c
1 /*
2  * The simplest AC-3 encoder
3  * Copyright (c) 2000 Fabrice Bellard
4  * Copyright (c) 2006-2010 Justin Ruggles <justin.ruggles@gmail.com>
5  * Copyright (c) 2006-2010 Prakash Punnoor <prakash@punnoor.de>
6  *
7  * This file is part of FFmpeg.
8  *
9  * FFmpeg is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * FFmpeg is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with FFmpeg; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 /**
25  * @file
26  * The simplest AC-3 encoder.
27  */
28
29 //#define DEBUG
30 //#define ASSERT_LEVEL 2
31
32 #include <stdint.h>
33
34 #include "libavutil/audioconvert.h"
35 #include "libavutil/avassert.h"
36 #include "libavutil/avstring.h"
37 #include "libavutil/crc.h"
38 #include "libavutil/opt.h"
39 #include "avcodec.h"
40 #include "put_bits.h"
41 #include "dsputil.h"
42 #include "ac3dsp.h"
43 #include "ac3.h"
44 #include "audioconvert.h"
45 #include "fft.h"
46
47
48 #ifndef CONFIG_AC3ENC_FLOAT
49 #define CONFIG_AC3ENC_FLOAT 0
50 #endif
51
52
53 /** Maximum number of exponent groups. +1 for separate DC exponent. */
54 #define AC3_MAX_EXP_GROUPS 85
55
56 #if CONFIG_AC3ENC_FLOAT
57 #define MAC_COEF(d,a,b) ((d)+=(a)*(b))
58 typedef float SampleType;
59 typedef float CoefType;
60 typedef float CoefSumType;
61 #else
62 #define MAC_COEF(d,a,b) MAC64(d,a,b)
63 typedef int16_t SampleType;
64 typedef int32_t CoefType;
65 typedef int64_t CoefSumType;
66 #endif
67
68 typedef struct AC3MDCTContext {
69     const SampleType *window;           ///< MDCT window function
70     FFTContext fft;                     ///< FFT context for MDCT calculation
71 } AC3MDCTContext;
72
73 /**
74  * Data for a single audio block.
75  */
76 typedef struct AC3Block {
77     uint8_t  **bap;                             ///< bit allocation pointers (bap)
78     CoefType **mdct_coef;                       ///< MDCT coefficients
79     int32_t  **fixed_coef;                      ///< fixed-point MDCT coefficients
80     uint8_t  **exp;                             ///< original exponents
81     uint8_t  **grouped_exp;                     ///< grouped exponents
82     int16_t  **psd;                             ///< psd per frequency bin
83     int16_t  **band_psd;                        ///< psd per critical band
84     int16_t  **mask;                            ///< masking curve
85     uint16_t **qmant;                           ///< quantized mantissas
86     uint8_t  coeff_shift[AC3_MAX_CHANNELS];     ///< fixed-point coefficient shift values
87     uint8_t  new_rematrixing_strategy;          ///< send new rematrixing flags in this block
88     uint8_t  rematrixing_flags[4];              ///< rematrixing flags
89     struct AC3Block *exp_ref_block[AC3_MAX_CHANNELS]; ///< reference blocks for EXP_REUSE
90 } AC3Block;
91
92 /**
93  * AC-3 encoder private context.
94  */
95 typedef struct AC3EncodeContext {
96     AVClass *av_class;                      ///< AVClass used for AVOption
97     AC3EncOptions options;                  ///< encoding options
98     PutBitContext pb;                       ///< bitstream writer context
99     DSPContext dsp;
100     AC3DSPContext ac3dsp;                   ///< AC-3 optimized functions
101     AC3MDCTContext mdct;                    ///< MDCT context
102
103     AC3Block blocks[AC3_MAX_BLOCKS];        ///< per-block info
104
105     int bitstream_id;                       ///< bitstream id                           (bsid)
106     int bitstream_mode;                     ///< bitstream mode                         (bsmod)
107
108     int bit_rate;                           ///< target bit rate, in bits-per-second
109     int sample_rate;                        ///< sampling frequency, in Hz
110
111     int frame_size_min;                     ///< minimum frame size in case rounding is necessary
112     int frame_size;                         ///< current frame size in bytes
113     int frame_size_code;                    ///< frame size code                        (frmsizecod)
114     uint16_t crc_inv[2];
115     int bits_written;                       ///< bit count    (used to avg. bitrate)
116     int samples_written;                    ///< sample count (used to avg. bitrate)
117
118     int fbw_channels;                       ///< number of full-bandwidth channels      (nfchans)
119     int channels;                           ///< total number of channels               (nchans)
120     int lfe_on;                             ///< indicates if there is an LFE channel   (lfeon)
121     int lfe_channel;                        ///< channel index of the LFE channel
122     int has_center;                         ///< indicates if there is a center channel
123     int has_surround;                       ///< indicates if there are one or more surround channels
124     int channel_mode;                       ///< channel mode                           (acmod)
125     const uint8_t *channel_map;             ///< channel map used to reorder channels
126
127     int center_mix_level;                   ///< center mix level code
128     int surround_mix_level;                 ///< surround mix level code
129     int ltrt_center_mix_level;              ///< Lt/Rt center mix level code
130     int ltrt_surround_mix_level;            ///< Lt/Rt surround mix level code
131     int loro_center_mix_level;              ///< Lo/Ro center mix level code
132     int loro_surround_mix_level;            ///< Lo/Ro surround mix level code
133
134     int cutoff;                             ///< user-specified cutoff frequency, in Hz
135     int bandwidth_code;                     ///< bandwidth code (0 to 60)               (chbwcod)
136     int nb_coefs[AC3_MAX_CHANNELS];
137
138     int rematrixing_enabled;                ///< stereo rematrixing enabled
139     int num_rematrixing_bands;              ///< number of rematrixing bands
140
141     /* bitrate allocation control */
142     int slow_gain_code;                     ///< slow gain code                         (sgaincod)
143     int slow_decay_code;                    ///< slow decay code                        (sdcycod)
144     int fast_decay_code;                    ///< fast decay code                        (fdcycod)
145     int db_per_bit_code;                    ///< dB/bit code                            (dbpbcod)
146     int floor_code;                         ///< floor code                             (floorcod)
147     AC3BitAllocParameters bit_alloc;        ///< bit allocation parameters
148     int coarse_snr_offset;                  ///< coarse SNR offsets                     (csnroffst)
149     int fast_gain_code[AC3_MAX_CHANNELS];   ///< fast gain codes (signal-to-mask ratio) (fgaincod)
150     int fine_snr_offset[AC3_MAX_CHANNELS];  ///< fine SNR offsets                       (fsnroffst)
151     int frame_bits_fixed;                   ///< number of non-coefficient bits for fixed parameters
152     int frame_bits;                         ///< all frame bits except exponents and mantissas
153     int exponent_bits;                      ///< number of bits used for exponents
154
155     SampleType **planar_samples;
156     uint8_t *bap_buffer;
157     uint8_t *bap1_buffer;
158     CoefType *mdct_coef_buffer;
159     int32_t *fixed_coef_buffer;
160     uint8_t *exp_buffer;
161     uint8_t *grouped_exp_buffer;
162     int16_t *psd_buffer;
163     int16_t *band_psd_buffer;
164     int16_t *mask_buffer;
165     uint16_t *qmant_buffer;
166
167     uint8_t exp_strategy[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< exponent strategies
168
169     DECLARE_ALIGNED(32, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
170 } AC3EncodeContext;
171
172 typedef struct AC3Mant {
173     uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
174     int mant1_cnt, mant2_cnt, mant4_cnt;    ///< mantissa counts for bap=1,2,4
175 } AC3Mant;
176
177 #define CMIXLEV_NUM_OPTIONS 3
178 static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
179     LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
180 };
181
182 #define SURMIXLEV_NUM_OPTIONS 3
183 static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
184     LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
185 };
186
187 #define EXTMIXLEV_NUM_OPTIONS 8
188 static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
189     LEVEL_PLUS_3DB,  LEVEL_PLUS_1POINT5DB,  LEVEL_ONE,       LEVEL_MINUS_4POINT5DB,
190     LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
191 };
192
193
194 #define OFFSET(param) offsetof(AC3EncodeContext, options.param)
195 #define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
196
197 #if CONFIG_AC3ENC_FLOAT || !CONFIG_AC3_FLOAT_ENCODER //we need this exactly once compiled in
198 const AVOption ff_ac3_options[] = {
199 /* Metadata Options */
200 {"per_frame_metadata", "Allow Changing Metadata Per-Frame", OFFSET(allow_per_frame_metadata), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 1, AC3ENC_PARAM},
201 /* downmix levels */
202 {"center_mixlev", "Center Mix Level", OFFSET(center_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = LEVEL_MINUS_4POINT5DB }, 0.0, 1.0, AC3ENC_PARAM},
203 {"surround_mixlev", "Surround Mix Level", OFFSET(surround_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = LEVEL_MINUS_6DB }, 0.0, 1.0, AC3ENC_PARAM},
204 /* audio production information */
205 {"mixing_level", "Mixing Level", OFFSET(mixing_level), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 111, AC3ENC_PARAM},
206 {"room_type", "Room Type", OFFSET(room_type), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "room_type"},
207     {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
208     {"large",        "Large Room",              0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
209     {"small",        "Small Room",              0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
210 /* other metadata options */
211 {"copyright", "Copyright Bit", OFFSET(copyright), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 1, AC3ENC_PARAM},
212 {"dialnorm", "Dialogue Level (dB)", OFFSET(dialogue_level), FF_OPT_TYPE_INT, {.dbl = -31 }, -31, -1, AC3ENC_PARAM},
213 {"dsur_mode", "Dolby Surround Mode", OFFSET(dolby_surround_mode), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 2, AC3ENC_PARAM, "dsur_mode"},
214     {"notindicated", "Not Indicated (default)",    0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
215     {"on",           "Dolby Surround Encoded",     0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
216     {"off",          "Not Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
217 {"original", "Original Bit Stream", OFFSET(original), FF_OPT_TYPE_INT,   {.dbl = 1 }, 0, 1, AC3ENC_PARAM},
218 /* extended bitstream information */
219 {"dmix_mode", "Preferred Stereo Downmix Mode", OFFSET(preferred_stereo_downmix), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dmix_mode"},
220     {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
221     {"ltrt", "Lt/Rt Downmix Preferred",         0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
222     {"loro", "Lo/Ro Downmix Preferred",         0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
223 {"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},
224 {"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},
225 {"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},
226 {"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},
227 {"dsurex_mode", "Dolby Surround EX Mode", OFFSET(dolby_surround_ex_mode), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dsurex_mode"},
228     {"notindicated", "Not Indicated (default)",       0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
229     {"on",           "Dolby Surround EX Encoded",     0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
230     {"off",          "Not Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
231 {"dheadphone_mode", "Dolby Headphone Mode", OFFSET(dolby_headphone_mode), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dheadphone_mode"},
232     {"notindicated", "Not Indicated (default)",     0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
233     {"on",           "Dolby Headphone Encoded",     0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
234     {"off",          "Not Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
235 {"ad_conv_type", "A/D Converter Type", OFFSET(ad_converter_type), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 1, AC3ENC_PARAM, "ad_conv_type"},
236     {"standard", "Standard (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
237     {"hdcd",     "HDCD",               0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
238 /* Other Encoding Options */
239 {"stereo_rematrixing", "Stereo Rematrixing", OFFSET(stereo_rematrixing), FF_OPT_TYPE_INT, {.dbl = 1 }, 0, 1, AC3ENC_PARAM},
240 {NULL}
241 };
242 #endif
243
244 #if CONFIG_AC3ENC_FLOAT
245 static AVClass ac3enc_class = { "AC-3 Encoder", av_default_item_name,
246                                 ff_ac3_options, LIBAVUTIL_VERSION_INT };
247 #else
248 static AVClass ac3enc_class = { "Fixed-Point AC-3 Encoder", av_default_item_name,
249                                 ff_ac3_options, LIBAVUTIL_VERSION_INT };
250 #endif
251
252
253 /* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
254
255 static av_cold void mdct_end(AC3MDCTContext *mdct);
256
257 static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
258                              int nbits);
259
260 static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
261                          const SampleType *window, unsigned int len);
262
263 static int normalize_samples(AC3EncodeContext *s);
264
265 static void scale_coefficients(AC3EncodeContext *s);
266
267
268 /**
269  * LUT for number of exponent groups.
270  * exponent_group_tab[exponent strategy-1][number of coefficients]
271  */
272 static uint8_t exponent_group_tab[3][256];
273
274
275 /**
276  * List of supported channel layouts.
277  */
278 #if CONFIG_AC3ENC_FLOAT || !CONFIG_AC3_FLOAT_ENCODER //we need this exactly once compiled in
279 const int64_t ff_ac3_channel_layouts[] = {
280      AV_CH_LAYOUT_MONO,
281      AV_CH_LAYOUT_STEREO,
282      AV_CH_LAYOUT_2_1,
283      AV_CH_LAYOUT_SURROUND,
284      AV_CH_LAYOUT_2_2,
285      AV_CH_LAYOUT_QUAD,
286      AV_CH_LAYOUT_4POINT0,
287      AV_CH_LAYOUT_5POINT0,
288      AV_CH_LAYOUT_5POINT0_BACK,
289     (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
290     (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
291     (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
292     (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
293     (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
294     (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
295     (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
296      AV_CH_LAYOUT_5POINT1,
297      AV_CH_LAYOUT_5POINT1_BACK,
298      0
299 };
300 #endif
301
302
303 /**
304  * LUT to select the bandwidth code based on the bit rate, sample rate, and
305  * number of full-bandwidth channels.
306  * bandwidth_tab[fbw_channels-1][sample rate code][bit rate code]
307  */
308 static const uint8_t ac3_bandwidth_tab[5][3][19] = {
309 //      32  40  48  56  64  80  96 112 128 160 192 224 256 320 384 448 512 576 640
310
311     { {  0,  0,  0, 12, 16, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
312       {  0,  0,  0, 16, 20, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
313       {  0,  0,  0, 32, 40, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
314
315     { {  0,  0,  0,  0,  0,  0,  0, 20, 24, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
316       {  0,  0,  0,  0,  0,  0,  4, 24, 28, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
317       {  0,  0,  0,  0,  0,  0, 20, 44, 52, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
318
319     { {  0,  0,  0,  0,  0,  0,  0,  0,  0, 16, 24, 32, 40, 48, 48, 48, 48, 48, 48 },
320       {  0,  0,  0,  0,  0,  0,  0,  0,  4, 20, 28, 36, 44, 56, 56, 56, 56, 56, 56 },
321       {  0,  0,  0,  0,  0,  0,  0,  0, 20, 40, 48, 60, 60, 60, 60, 60, 60, 60, 60 } },
322
323     { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 12, 24, 32, 48, 48, 48, 48, 48, 48 },
324       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 16, 28, 36, 56, 56, 56, 56, 56, 56 },
325       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 32, 48, 60, 60, 60, 60, 60, 60, 60 } },
326
327     { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  8, 20, 32, 40, 48, 48, 48, 48 },
328       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 12, 24, 36, 44, 56, 56, 56, 56 },
329       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 28, 44, 60, 60, 60, 60, 60, 60 } }
330 };
331
332
333 /**
334  * Adjust the frame size to make the average bit rate match the target bit rate.
335  * This is only needed for 11025, 22050, and 44100 sample rates.
336  */
337 static void adjust_frame_size(AC3EncodeContext *s)
338 {
339     while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
340         s->bits_written    -= s->bit_rate;
341         s->samples_written -= s->sample_rate;
342     }
343     s->frame_size = s->frame_size_min +
344                     2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
345     s->bits_written    += s->frame_size * 8;
346     s->samples_written += AC3_FRAME_SIZE;
347 }
348
349
350 /**
351  * Deinterleave input samples.
352  * Channels are reordered from FFmpeg's default order to AC-3 order.
353  */
354 static void deinterleave_input_samples(AC3EncodeContext *s,
355                                        const SampleType *samples)
356 {
357     int ch, i;
358
359     /* deinterleave and remap input samples */
360     for (ch = 0; ch < s->channels; ch++) {
361         const SampleType *sptr;
362         int sinc;
363
364         /* copy last 256 samples of previous frame to the start of the current frame */
365         memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
366                AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
367
368         /* deinterleave */
369         sinc = s->channels;
370         sptr = samples + s->channel_map[ch];
371         for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
372             s->planar_samples[ch][i] = *sptr;
373             sptr += sinc;
374         }
375     }
376 }
377
378
379 /**
380  * Apply the MDCT to input samples to generate frequency coefficients.
381  * This applies the KBD window and normalizes the input to reduce precision
382  * loss due to fixed-point calculations.
383  */
384 static void apply_mdct(AC3EncodeContext *s)
385 {
386     int blk, ch;
387
388     for (ch = 0; ch < s->channels; ch++) {
389         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
390             AC3Block *block = &s->blocks[blk];
391             const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
392
393             apply_window(&s->dsp, s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
394
395             block->coeff_shift[ch] = normalize_samples(s);
396
397             s->mdct.fft.mdct_calcw(&s->mdct.fft, block->mdct_coef[ch],
398                                    s->windowed_samples);
399         }
400     }
401 }
402
403
404 /**
405  * Determine rematrixing flags for each block and band.
406  */
407 static void compute_rematrixing_strategy(AC3EncodeContext *s)
408 {
409     int nb_coefs;
410     int blk, bnd, i;
411     AC3Block *block, *block0;
412
413     if (s->channel_mode != AC3_CHMODE_STEREO)
414         return;
415
416     s->num_rematrixing_bands = 4;
417
418     nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
419
420     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
421         block = &s->blocks[blk];
422         block->new_rematrixing_strategy = !blk;
423         if (!s->rematrixing_enabled)
424             continue;
425         for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
426             /* calculate calculate sum of squared coeffs for one band in one block */
427             int start = ff_ac3_rematrix_band_tab[bnd];
428             int end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
429             CoefSumType sum[4] = {0,};
430             for (i = start; i < end; i++) {
431                 CoefType lt = block->mdct_coef[0][i];
432                 CoefType rt = block->mdct_coef[1][i];
433                 CoefType md = lt + rt;
434                 CoefType sd = lt - rt;
435                 MAC_COEF(sum[0], lt, lt);
436                 MAC_COEF(sum[1], rt, rt);
437                 MAC_COEF(sum[2], md, md);
438                 MAC_COEF(sum[3], sd, sd);
439             }
440
441             /* compare sums to determine if rematrixing will be used for this band */
442             if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
443                 block->rematrixing_flags[bnd] = 1;
444             else
445                 block->rematrixing_flags[bnd] = 0;
446
447             /* determine if new rematrixing flags will be sent */
448             if (blk &&
449                 block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
450                 block->new_rematrixing_strategy = 1;
451             }
452         }
453         block0 = block;
454     }
455 }
456
457
458 /**
459  * Apply stereo rematrixing to coefficients based on rematrixing flags.
460  */
461 static void apply_rematrixing(AC3EncodeContext *s)
462 {
463     int nb_coefs;
464     int blk, bnd, i;
465     int start, end;
466     uint8_t *flags;
467
468     if (!s->rematrixing_enabled)
469         return;
470
471     nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
472
473     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
474         AC3Block *block = &s->blocks[blk];
475         if (block->new_rematrixing_strategy)
476             flags = block->rematrixing_flags;
477         for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
478             if (flags[bnd]) {
479                 start = ff_ac3_rematrix_band_tab[bnd];
480                 end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
481                 for (i = start; i < end; i++) {
482                     int32_t lt = block->fixed_coef[0][i];
483                     int32_t rt = block->fixed_coef[1][i];
484                     block->fixed_coef[0][i] = (lt + rt) >> 1;
485                     block->fixed_coef[1][i] = (lt - rt) >> 1;
486                 }
487             }
488         }
489     }
490 }
491
492
493 /**
494  * Initialize exponent tables.
495  */
496 static av_cold void exponent_init(AC3EncodeContext *s)
497 {
498     int expstr, i, grpsize;
499
500     for (expstr = EXP_D15-1; expstr <= EXP_D45-1; expstr++) {
501         grpsize = 3 << expstr;
502         for (i = 73; i < 256; i++) {
503             exponent_group_tab[expstr][i] = (i + grpsize - 4) / grpsize;
504         }
505     }
506     /* LFE */
507     exponent_group_tab[0][7] = 2;
508 }
509
510
511 /**
512  * Extract exponents from the MDCT coefficients.
513  * This takes into account the normalization that was done to the input samples
514  * by adjusting the exponents by the exponent shift values.
515  */
516 static void extract_exponents(AC3EncodeContext *s)
517 {
518     int blk, ch;
519
520     for (ch = 0; ch < s->channels; ch++) {
521         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
522             AC3Block *block = &s->blocks[blk];
523             s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch],
524                                         AC3_MAX_COEFS);
525         }
526     }
527 }
528
529
530 /**
531  * Exponent Difference Threshold.
532  * New exponents are sent if their SAD exceed this number.
533  */
534 #define EXP_DIFF_THRESHOLD 500
535
536
537 /**
538  * Calculate exponent strategies for all channels.
539  * Array arrangement is reversed to simplify the per-channel calculation.
540  */
541 static void compute_exp_strategy(AC3EncodeContext *s)
542 {
543     int ch, blk, blk1;
544
545     for (ch = 0; ch < s->fbw_channels; ch++) {
546         uint8_t *exp_strategy = s->exp_strategy[ch];
547         uint8_t *exp          = s->blocks[0].exp[ch];
548         int exp_diff;
549
550         /* estimate if the exponent variation & decide if they should be
551            reused in the next frame */
552         exp_strategy[0] = EXP_NEW;
553         exp += AC3_MAX_COEFS;
554         for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
555             exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
556             if (exp_diff > EXP_DIFF_THRESHOLD)
557                 exp_strategy[blk] = EXP_NEW;
558             else
559                 exp_strategy[blk] = EXP_REUSE;
560             exp += AC3_MAX_COEFS;
561         }
562
563         /* now select the encoding strategy type : if exponents are often
564            recoded, we use a coarse encoding */
565         blk = 0;
566         while (blk < AC3_MAX_BLOCKS) {
567             blk1 = blk + 1;
568             while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
569                 blk1++;
570             switch (blk1 - blk) {
571             case 1:  exp_strategy[blk] = EXP_D45; break;
572             case 2:
573             case 3:  exp_strategy[blk] = EXP_D25; break;
574             default: exp_strategy[blk] = EXP_D15; break;
575             }
576             blk = blk1;
577         }
578     }
579     if (s->lfe_on) {
580         ch = s->lfe_channel;
581         s->exp_strategy[ch][0] = EXP_D15;
582         for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
583             s->exp_strategy[ch][blk] = EXP_REUSE;
584     }
585 }
586
587
588 /**
589  * Update the exponents so that they are the ones the decoder will decode.
590  */
591 static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy)
592 {
593     int nb_groups, i, k;
594
595     nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
596
597     /* for each group, compute the minimum exponent */
598     switch(exp_strategy) {
599     case EXP_D25:
600         for (i = 1, k = 1; i <= nb_groups; i++) {
601             uint8_t exp_min = exp[k];
602             if (exp[k+1] < exp_min)
603                 exp_min = exp[k+1];
604             exp[i] = exp_min;
605             k += 2;
606         }
607         break;
608     case EXP_D45:
609         for (i = 1, k = 1; i <= nb_groups; i++) {
610             uint8_t exp_min = exp[k];
611             if (exp[k+1] < exp_min)
612                 exp_min = exp[k+1];
613             if (exp[k+2] < exp_min)
614                 exp_min = exp[k+2];
615             if (exp[k+3] < exp_min)
616                 exp_min = exp[k+3];
617             exp[i] = exp_min;
618             k += 4;
619         }
620         break;
621     }
622
623     /* constraint for DC exponent */
624     if (exp[0] > 15)
625         exp[0] = 15;
626
627     /* decrease the delta between each groups to within 2 so that they can be
628        differentially encoded */
629     for (i = 1; i <= nb_groups; i++)
630         exp[i] = FFMIN(exp[i], exp[i-1] + 2);
631     i--;
632     while (--i >= 0)
633         exp[i] = FFMIN(exp[i], exp[i+1] + 2);
634
635     /* now we have the exponent values the decoder will see */
636     switch (exp_strategy) {
637     case EXP_D25:
638         for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
639             uint8_t exp1 = exp[i];
640             exp[k--] = exp1;
641             exp[k--] = exp1;
642         }
643         break;
644     case EXP_D45:
645         for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
646             exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
647             k -= 4;
648         }
649         break;
650     }
651 }
652
653
654 /**
655  * Encode exponents from original extracted form to what the decoder will see.
656  * This copies and groups exponents based on exponent strategy and reduces
657  * deltas between adjacent exponent groups so that they can be differentially
658  * encoded.
659  */
660 static void encode_exponents(AC3EncodeContext *s)
661 {
662     int blk, blk1, ch;
663     uint8_t *exp, *exp_strategy;
664     int nb_coefs, num_reuse_blocks;
665
666     for (ch = 0; ch < s->channels; ch++) {
667         exp          = s->blocks[0].exp[ch];
668         exp_strategy = s->exp_strategy[ch];
669         nb_coefs     = s->nb_coefs[ch];
670
671         blk = 0;
672         while (blk < AC3_MAX_BLOCKS) {
673             blk1 = blk + 1;
674
675             /* count the number of EXP_REUSE blocks after the current block
676                and set exponent reference block pointers */
677             s->blocks[blk].exp_ref_block[ch] = &s->blocks[blk];
678             while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
679                 s->blocks[blk1].exp_ref_block[ch] = &s->blocks[blk];
680                 blk1++;
681             }
682             num_reuse_blocks = blk1 - blk - 1;
683
684             /* for the EXP_REUSE case we select the min of the exponents */
685             s->ac3dsp.ac3_exponent_min(exp, num_reuse_blocks, nb_coefs);
686
687             encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk]);
688
689             exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
690             blk = blk1;
691         }
692     }
693 }
694
695
696 /**
697  * Group exponents.
698  * 3 delta-encoded exponents are in each 7-bit group. The number of groups
699  * varies depending on exponent strategy and bandwidth.
700  */
701 static void group_exponents(AC3EncodeContext *s)
702 {
703     int blk, ch, i;
704     int group_size, nb_groups, bit_count;
705     uint8_t *p;
706     int delta0, delta1, delta2;
707     int exp0, exp1;
708
709     bit_count = 0;
710     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
711         AC3Block *block = &s->blocks[blk];
712         for (ch = 0; ch < s->channels; ch++) {
713             int exp_strategy = s->exp_strategy[ch][blk];
714             if (exp_strategy == EXP_REUSE)
715                 continue;
716             group_size = exp_strategy + (exp_strategy == EXP_D45);
717             nb_groups = exponent_group_tab[exp_strategy-1][s->nb_coefs[ch]];
718             bit_count += 4 + (nb_groups * 7);
719             p = block->exp[ch];
720
721             /* DC exponent */
722             exp1 = *p++;
723             block->grouped_exp[ch][0] = exp1;
724
725             /* remaining exponents are delta encoded */
726             for (i = 1; i <= nb_groups; i++) {
727                 /* merge three delta in one code */
728                 exp0   = exp1;
729                 exp1   = p[0];
730                 p     += group_size;
731                 delta0 = exp1 - exp0 + 2;
732                 av_assert2(delta0 >= 0 && delta0 <= 4);
733
734                 exp0   = exp1;
735                 exp1   = p[0];
736                 p     += group_size;
737                 delta1 = exp1 - exp0 + 2;
738                 av_assert2(delta1 >= 0 && delta1 <= 4);
739
740                 exp0   = exp1;
741                 exp1   = p[0];
742                 p     += group_size;
743                 delta2 = exp1 - exp0 + 2;
744                 av_assert2(delta2 >= 0 && delta2 <= 4);
745
746                 block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
747             }
748         }
749     }
750
751     s->exponent_bits = bit_count;
752 }
753
754
755 /**
756  * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
757  * Extract exponents from MDCT coefficients, calculate exponent strategies,
758  * and encode final exponents.
759  */
760 static void process_exponents(AC3EncodeContext *s)
761 {
762     extract_exponents(s);
763
764     compute_exp_strategy(s);
765
766     encode_exponents(s);
767
768     group_exponents(s);
769
770     emms_c();
771 }
772
773
774 /**
775  * Count frame bits that are based solely on fixed parameters.
776  * This only has to be run once when the encoder is initialized.
777  */
778 static void count_frame_bits_fixed(AC3EncodeContext *s)
779 {
780     static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
781     int blk;
782     int frame_bits;
783
784     /* assumptions:
785      *   no dynamic range codes
786      *   no channel coupling
787      *   bit allocation parameters do not change between blocks
788      *   SNR offsets do not change between blocks
789      *   no delta bit allocation
790      *   no skipped data
791      *   no auxilliary data
792      */
793
794     /* header size */
795     frame_bits = 65;
796     frame_bits += frame_bits_inc[s->channel_mode];
797
798     /* audio blocks */
799     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
800         frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
801         if (s->channel_mode == AC3_CHMODE_STEREO) {
802             frame_bits++; /* rematstr */
803         }
804         frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
805         if (s->lfe_on)
806             frame_bits++; /* lfeexpstr */
807         frame_bits++; /* baie */
808         frame_bits++; /* snr */
809         frame_bits += 2; /* delta / skip */
810     }
811     frame_bits++; /* cplinu for block 0 */
812     /* bit alloc info */
813     /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
814     /* csnroffset[6] */
815     /* (fsnoffset[4] + fgaincod[4]) * c */
816     frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
817
818     /* auxdatae, crcrsv */
819     frame_bits += 2;
820
821     /* CRC */
822     frame_bits += 16;
823
824     s->frame_bits_fixed = frame_bits;
825 }
826
827
828 /**
829  * Initialize bit allocation.
830  * Set default parameter codes and calculate parameter values.
831  */
832 static void bit_alloc_init(AC3EncodeContext *s)
833 {
834     int ch;
835
836     /* init default parameters */
837     s->slow_decay_code = 2;
838     s->fast_decay_code = 1;
839     s->slow_gain_code  = 1;
840     s->db_per_bit_code = 3;
841     s->floor_code      = 7;
842     for (ch = 0; ch < s->channels; ch++)
843         s->fast_gain_code[ch] = 4;
844
845     /* initial snr offset */
846     s->coarse_snr_offset = 40;
847
848     /* compute real values */
849     /* currently none of these values change during encoding, so we can just
850        set them once at initialization */
851     s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
852     s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
853     s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
854     s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
855     s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
856
857     count_frame_bits_fixed(s);
858 }
859
860
861 /**
862  * Count the bits used to encode the frame, minus exponents and mantissas.
863  * Bits based on fixed parameters have already been counted, so now we just
864  * have to add the bits based on parameters that change during encoding.
865  */
866 static void count_frame_bits(AC3EncodeContext *s)
867 {
868     AC3EncOptions *opt = &s->options;
869     int blk, ch;
870     int frame_bits = 0;
871
872     if (opt->audio_production_info)
873         frame_bits += 7;
874     if (s->bitstream_id == 6) {
875         if (opt->extended_bsi_1)
876             frame_bits += 14;
877         if (opt->extended_bsi_2)
878             frame_bits += 14;
879     }
880
881     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
882         /* stereo rematrixing */
883         if (s->channel_mode == AC3_CHMODE_STEREO &&
884             s->blocks[blk].new_rematrixing_strategy) {
885             frame_bits += s->num_rematrixing_bands;
886         }
887
888         for (ch = 0; ch < s->fbw_channels; ch++) {
889             if (s->exp_strategy[ch][blk] != EXP_REUSE)
890                 frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
891         }
892     }
893     s->frame_bits = s->frame_bits_fixed + frame_bits;
894 }
895
896
897 /**
898  * Finalize the mantissa bit count by adding in the grouped mantissas.
899  */
900 static int compute_mantissa_size_final(int mant_cnt[5])
901 {
902     // bap=1 : 3 mantissas in 5 bits
903     int bits = (mant_cnt[1] / 3) * 5;
904     // bap=2 : 3 mantissas in 7 bits
905     // bap=4 : 2 mantissas in 7 bits
906     bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
907     // bap=3 : each mantissa is 3 bits
908     bits += mant_cnt[3] * 3;
909     return bits;
910 }
911
912
913 /**
914  * Calculate masking curve based on the final exponents.
915  * Also calculate the power spectral densities to use in future calculations.
916  */
917 static void bit_alloc_masking(AC3EncodeContext *s)
918 {
919     int blk, ch;
920
921     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
922         AC3Block *block = &s->blocks[blk];
923         for (ch = 0; ch < s->channels; ch++) {
924             /* We only need psd and mask for calculating bap.
925                Since we currently do not calculate bap when exponent
926                strategy is EXP_REUSE we do not need to calculate psd or mask. */
927             if (s->exp_strategy[ch][blk] != EXP_REUSE) {
928                 ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
929                                           s->nb_coefs[ch],
930                                           block->psd[ch], block->band_psd[ch]);
931                 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
932                                            0, s->nb_coefs[ch],
933                                            ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
934                                            ch == s->lfe_channel,
935                                            DBA_NONE, 0, NULL, NULL, NULL,
936                                            block->mask[ch]);
937             }
938         }
939     }
940 }
941
942
943 /**
944  * Ensure that bap for each block and channel point to the current bap_buffer.
945  * They may have been switched during the bit allocation search.
946  */
947 static void reset_block_bap(AC3EncodeContext *s)
948 {
949     int blk, ch;
950     if (s->blocks[0].bap[0] == s->bap_buffer)
951         return;
952     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
953         for (ch = 0; ch < s->channels; ch++) {
954             s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
955         }
956     }
957 }
958
959
960 /**
961  * Run the bit allocation with a given SNR offset.
962  * This calculates the bit allocation pointers that will be used to determine
963  * the quantization of each mantissa.
964  * @return the number of bits needed for mantissas if the given SNR offset is
965  *         is used.
966  */
967 static int bit_alloc(AC3EncodeContext *s, int snr_offset)
968 {
969     int blk, ch;
970     int mantissa_bits;
971     int mant_cnt[5];
972
973     snr_offset = (snr_offset - 240) << 2;
974
975     reset_block_bap(s);
976     mantissa_bits = 0;
977     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
978         AC3Block *block = &s->blocks[blk];
979         AC3Block *ref_block;
980         // initialize grouped mantissa counts. these are set so that they are
981         // padded to the next whole group size when bits are counted in
982         // compute_mantissa_size_final
983         mant_cnt[0] = mant_cnt[3] = 0;
984         mant_cnt[1] = mant_cnt[2] = 2;
985         mant_cnt[4] = 1;
986         for (ch = 0; ch < s->channels; ch++) {
987             /* Currently the only bit allocation parameters which vary across
988                blocks within a frame are the exponent values.  We can take
989                advantage of that by reusing the bit allocation pointers
990                whenever we reuse exponents. */
991             ref_block = block->exp_ref_block[ch];
992             if (s->exp_strategy[ch][blk] != EXP_REUSE) {
993                 s->ac3dsp.bit_alloc_calc_bap(ref_block->mask[ch],
994                                              ref_block->psd[ch], 0,
995                                              s->nb_coefs[ch], snr_offset,
996                                              s->bit_alloc.floor, ff_ac3_bap_tab,
997                                              ref_block->bap[ch]);
998             }
999             mantissa_bits += s->ac3dsp.compute_mantissa_size(mant_cnt,
1000                                                              ref_block->bap[ch],
1001                                                              s->nb_coefs[ch]);
1002         }
1003         mantissa_bits += compute_mantissa_size_final(mant_cnt);
1004     }
1005     return mantissa_bits;
1006 }
1007
1008
1009 /**
1010  * Constant bitrate bit allocation search.
1011  * Find the largest SNR offset that will allow data to fit in the frame.
1012  */
1013 static int cbr_bit_allocation(AC3EncodeContext *s)
1014 {
1015     int ch;
1016     int bits_left;
1017     int snr_offset, snr_incr;
1018
1019     bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1020     if (bits_left < 0)
1021         return AVERROR(EINVAL);
1022
1023     snr_offset = s->coarse_snr_offset << 4;
1024
1025     /* if previous frame SNR offset was 1023, check if current frame can also
1026        use SNR offset of 1023. if so, skip the search. */
1027     if ((snr_offset | s->fine_snr_offset[0]) == 1023) {
1028         if (bit_alloc(s, 1023) <= bits_left)
1029             return 0;
1030     }
1031
1032     while (snr_offset >= 0 &&
1033            bit_alloc(s, snr_offset) > bits_left) {
1034         snr_offset -= 64;
1035     }
1036     if (snr_offset < 0)
1037         return AVERROR(EINVAL);
1038
1039     FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1040     for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1041         while (snr_offset + snr_incr <= 1023 &&
1042                bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1043             snr_offset += snr_incr;
1044             FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1045         }
1046     }
1047     FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1048     reset_block_bap(s);
1049
1050     s->coarse_snr_offset = snr_offset >> 4;
1051     for (ch = 0; ch < s->channels; ch++)
1052         s->fine_snr_offset[ch] = snr_offset & 0xF;
1053
1054     return 0;
1055 }
1056
1057
1058 /**
1059  * Downgrade exponent strategies to reduce the bits used by the exponents.
1060  * This is a fallback for when bit allocation fails with the normal exponent
1061  * strategies.  Each time this function is run it only downgrades the
1062  * strategy in 1 channel of 1 block.
1063  * @return non-zero if downgrade was unsuccessful
1064  */
1065 static int downgrade_exponents(AC3EncodeContext *s)
1066 {
1067     int ch, blk;
1068
1069     for (ch = 0; ch < s->fbw_channels; ch++) {
1070         for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1071             if (s->exp_strategy[ch][blk] == EXP_D15) {
1072                 s->exp_strategy[ch][blk] = EXP_D25;
1073                 return 0;
1074             }
1075         }
1076     }
1077     for (ch = 0; ch < s->fbw_channels; ch++) {
1078         for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1079             if (s->exp_strategy[ch][blk] == EXP_D25) {
1080                 s->exp_strategy[ch][blk] = EXP_D45;
1081                 return 0;
1082             }
1083         }
1084     }
1085     for (ch = 0; ch < s->fbw_channels; ch++) {
1086         /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
1087            the block number > 0 */
1088         for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
1089             if (s->exp_strategy[ch][blk] > EXP_REUSE) {
1090                 s->exp_strategy[ch][blk] = EXP_REUSE;
1091                 return 0;
1092             }
1093         }
1094     }
1095     return -1;
1096 }
1097
1098
1099 /**
1100  * Perform bit allocation search.
1101  * Finds the SNR offset value that maximizes quality and fits in the specified
1102  * frame size.  Output is the SNR offset and a set of bit allocation pointers
1103  * used to quantize the mantissas.
1104  */
1105 static int compute_bit_allocation(AC3EncodeContext *s)
1106 {
1107     int ret;
1108
1109     count_frame_bits(s);
1110
1111     bit_alloc_masking(s);
1112
1113     ret = cbr_bit_allocation(s);
1114     while (ret) {
1115         /* fallback 1: downgrade exponents */
1116         if (!downgrade_exponents(s)) {
1117             extract_exponents(s);
1118             encode_exponents(s);
1119             group_exponents(s);
1120             ret = compute_bit_allocation(s);
1121             continue;
1122         }
1123
1124         /* fallbacks were not enough... */
1125         break;
1126     }
1127
1128     return ret;
1129 }
1130
1131
1132 /**
1133  * Symmetric quantization on 'levels' levels.
1134  */
1135 static inline int sym_quant(int c, int e, int levels)
1136 {
1137     int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1138     av_assert2(v >= 0 && v < levels);
1139     return v;
1140 }
1141
1142
1143 /**
1144  * Asymmetric quantization on 2^qbits levels.
1145  */
1146 static inline int asym_quant(int c, int e, int qbits)
1147 {
1148     int lshift, m, v;
1149
1150     lshift = e + qbits - 24;
1151     if (lshift >= 0)
1152         v = c << lshift;
1153     else
1154         v = c >> (-lshift);
1155     /* rounding */
1156     v = (v + 1) >> 1;
1157     m = (1 << (qbits-1));
1158     if (v >= m)
1159         v = m - 1;
1160     av_assert2(v >= -m);
1161     return v & ((1 << qbits)-1);
1162 }
1163
1164
1165 /**
1166  * Quantize a set of mantissas for a single channel in a single block.
1167  */
1168 static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1169                                       uint8_t *exp,
1170                                       uint8_t *bap, uint16_t *qmant, int n)
1171 {
1172     int i;
1173
1174     for (i = 0; i < n; i++) {
1175         int v;
1176         int c = fixed_coef[i];
1177         int e = exp[i];
1178         int b = bap[i];
1179         switch (b) {
1180         case 0:
1181             v = 0;
1182             break;
1183         case 1:
1184             v = sym_quant(c, e, 3);
1185             switch (s->mant1_cnt) {
1186             case 0:
1187                 s->qmant1_ptr = &qmant[i];
1188                 v = 9 * v;
1189                 s->mant1_cnt = 1;
1190                 break;
1191             case 1:
1192                 *s->qmant1_ptr += 3 * v;
1193                 s->mant1_cnt = 2;
1194                 v = 128;
1195                 break;
1196             default:
1197                 *s->qmant1_ptr += v;
1198                 s->mant1_cnt = 0;
1199                 v = 128;
1200                 break;
1201             }
1202             break;
1203         case 2:
1204             v = sym_quant(c, e, 5);
1205             switch (s->mant2_cnt) {
1206             case 0:
1207                 s->qmant2_ptr = &qmant[i];
1208                 v = 25 * v;
1209                 s->mant2_cnt = 1;
1210                 break;
1211             case 1:
1212                 *s->qmant2_ptr += 5 * v;
1213                 s->mant2_cnt = 2;
1214                 v = 128;
1215                 break;
1216             default:
1217                 *s->qmant2_ptr += v;
1218                 s->mant2_cnt = 0;
1219                 v = 128;
1220                 break;
1221             }
1222             break;
1223         case 3:
1224             v = sym_quant(c, e, 7);
1225             break;
1226         case 4:
1227             v = sym_quant(c, e, 11);
1228             switch (s->mant4_cnt) {
1229             case 0:
1230                 s->qmant4_ptr = &qmant[i];
1231                 v = 11 * v;
1232                 s->mant4_cnt = 1;
1233                 break;
1234             default:
1235                 *s->qmant4_ptr += v;
1236                 s->mant4_cnt = 0;
1237                 v = 128;
1238                 break;
1239             }
1240             break;
1241         case 5:
1242             v = sym_quant(c, e, 15);
1243             break;
1244         case 14:
1245             v = asym_quant(c, e, 14);
1246             break;
1247         case 15:
1248             v = asym_quant(c, e, 16);
1249             break;
1250         default:
1251             v = asym_quant(c, e, b - 1);
1252             break;
1253         }
1254         qmant[i] = v;
1255     }
1256 }
1257
1258
1259 /**
1260  * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1261  */
1262 static void quantize_mantissas(AC3EncodeContext *s)
1263 {
1264     int blk, ch;
1265
1266
1267     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1268         AC3Block *block = &s->blocks[blk];
1269         AC3Block *ref_block;
1270         AC3Mant m = { 0 };
1271
1272         for (ch = 0; ch < s->channels; ch++) {
1273             ref_block = block->exp_ref_block[ch];
1274             quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1275                                       ref_block->exp[ch], ref_block->bap[ch],
1276                                       block->qmant[ch], s->nb_coefs[ch]);
1277         }
1278     }
1279 }
1280
1281
1282 /**
1283  * Write the AC-3 frame header to the output bitstream.
1284  */
1285 static void output_frame_header(AC3EncodeContext *s)
1286 {
1287     AC3EncOptions *opt = &s->options;
1288
1289     put_bits(&s->pb, 16, 0x0b77);   /* frame header */
1290     put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
1291     put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
1292     put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1293     put_bits(&s->pb, 5,  s->bitstream_id);
1294     put_bits(&s->pb, 3,  s->bitstream_mode);
1295     put_bits(&s->pb, 3,  s->channel_mode);
1296     if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1297         put_bits(&s->pb, 2, s->center_mix_level);
1298     if (s->channel_mode & 0x04)
1299         put_bits(&s->pb, 2, s->surround_mix_level);
1300     if (s->channel_mode == AC3_CHMODE_STEREO)
1301         put_bits(&s->pb, 2, opt->dolby_surround_mode);
1302     put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1303     put_bits(&s->pb, 5, -opt->dialogue_level);
1304     put_bits(&s->pb, 1, 0);         /* no compression control word */
1305     put_bits(&s->pb, 1, 0);         /* no lang code */
1306     put_bits(&s->pb, 1, opt->audio_production_info);
1307     if (opt->audio_production_info) {
1308         put_bits(&s->pb, 5, opt->mixing_level - 80);
1309         put_bits(&s->pb, 2, opt->room_type);
1310     }
1311     put_bits(&s->pb, 1, opt->copyright);
1312     put_bits(&s->pb, 1, opt->original);
1313     if (s->bitstream_id == 6) {
1314         /* alternate bit stream syntax */
1315         put_bits(&s->pb, 1, opt->extended_bsi_1);
1316         if (opt->extended_bsi_1) {
1317             put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1318             put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1319             put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1320             put_bits(&s->pb, 3, s->loro_center_mix_level);
1321             put_bits(&s->pb, 3, s->loro_surround_mix_level);
1322         }
1323         put_bits(&s->pb, 1, opt->extended_bsi_2);
1324         if (opt->extended_bsi_2) {
1325             put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1326             put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1327             put_bits(&s->pb, 1, opt->ad_converter_type);
1328             put_bits(&s->pb, 9, 0);     /* xbsi2 and encinfo : reserved */
1329         }
1330     } else {
1331     put_bits(&s->pb, 1, 0);         /* no time code 1 */
1332     put_bits(&s->pb, 1, 0);         /* no time code 2 */
1333     }
1334     put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
1335 }
1336
1337
1338 /**
1339  * Write one audio block to the output bitstream.
1340  */
1341 static void output_audio_block(AC3EncodeContext *s, int blk)
1342 {
1343     int ch, i, baie, rbnd;
1344     AC3Block *block = &s->blocks[blk];
1345
1346     /* block switching */
1347     for (ch = 0; ch < s->fbw_channels; ch++)
1348         put_bits(&s->pb, 1, 0);
1349
1350     /* dither flags */
1351     for (ch = 0; ch < s->fbw_channels; ch++)
1352         put_bits(&s->pb, 1, 1);
1353
1354     /* dynamic range codes */
1355     put_bits(&s->pb, 1, 0);
1356
1357     /* channel coupling */
1358     if (!blk) {
1359         put_bits(&s->pb, 1, 1); /* coupling strategy present */
1360         put_bits(&s->pb, 1, 0); /* no coupling strategy */
1361     } else {
1362         put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1363     }
1364
1365     /* stereo rematrixing */
1366     if (s->channel_mode == AC3_CHMODE_STEREO) {
1367         put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1368         if (block->new_rematrixing_strategy) {
1369             /* rematrixing flags */
1370             for (rbnd = 0; rbnd < s->num_rematrixing_bands; rbnd++)
1371                 put_bits(&s->pb, 1, block->rematrixing_flags[rbnd]);
1372         }
1373     }
1374
1375     /* exponent strategy */
1376     for (ch = 0; ch < s->fbw_channels; ch++)
1377         put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1378     if (s->lfe_on)
1379         put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1380
1381     /* bandwidth */
1382     for (ch = 0; ch < s->fbw_channels; ch++) {
1383         if (s->exp_strategy[ch][blk] != EXP_REUSE)
1384             put_bits(&s->pb, 6, s->bandwidth_code);
1385     }
1386
1387     /* exponents */
1388     for (ch = 0; ch < s->channels; ch++) {
1389         int nb_groups;
1390
1391         if (s->exp_strategy[ch][blk] == EXP_REUSE)
1392             continue;
1393
1394         /* DC exponent */
1395         put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1396
1397         /* exponent groups */
1398         nb_groups = exponent_group_tab[s->exp_strategy[ch][blk]-1][s->nb_coefs[ch]];
1399         for (i = 1; i <= nb_groups; i++)
1400             put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1401
1402         /* gain range info */
1403         if (ch != s->lfe_channel)
1404             put_bits(&s->pb, 2, 0);
1405     }
1406
1407     /* bit allocation info */
1408     baie = (blk == 0);
1409     put_bits(&s->pb, 1, baie);
1410     if (baie) {
1411         put_bits(&s->pb, 2, s->slow_decay_code);
1412         put_bits(&s->pb, 2, s->fast_decay_code);
1413         put_bits(&s->pb, 2, s->slow_gain_code);
1414         put_bits(&s->pb, 2, s->db_per_bit_code);
1415         put_bits(&s->pb, 3, s->floor_code);
1416     }
1417
1418     /* snr offset */
1419     put_bits(&s->pb, 1, baie);
1420     if (baie) {
1421         put_bits(&s->pb, 6, s->coarse_snr_offset);
1422         for (ch = 0; ch < s->channels; ch++) {
1423             put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1424             put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1425         }
1426     }
1427
1428     put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1429     put_bits(&s->pb, 1, 0); /* no data to skip */
1430
1431     /* mantissas */
1432     for (ch = 0; ch < s->channels; ch++) {
1433         int b, q;
1434         AC3Block *ref_block = block->exp_ref_block[ch];
1435         for (i = 0; i < s->nb_coefs[ch]; i++) {
1436             q = block->qmant[ch][i];
1437             b = ref_block->bap[ch][i];
1438             switch (b) {
1439             case 0:                                         break;
1440             case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
1441             case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
1442             case 3:               put_bits(&s->pb,   3, q); break;
1443             case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
1444             case 14:              put_bits(&s->pb,  14, q); break;
1445             case 15:              put_bits(&s->pb,  16, q); break;
1446             default:              put_bits(&s->pb, b-1, q); break;
1447             }
1448         }
1449     }
1450 }
1451
1452
1453 /** CRC-16 Polynomial */
1454 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1455
1456
1457 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1458 {
1459     unsigned int c;
1460
1461     c = 0;
1462     while (a) {
1463         if (a & 1)
1464             c ^= b;
1465         a = a >> 1;
1466         b = b << 1;
1467         if (b & (1 << 16))
1468             b ^= poly;
1469     }
1470     return c;
1471 }
1472
1473
1474 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1475 {
1476     unsigned int r;
1477     r = 1;
1478     while (n) {
1479         if (n & 1)
1480             r = mul_poly(r, a, poly);
1481         a = mul_poly(a, a, poly);
1482         n >>= 1;
1483     }
1484     return r;
1485 }
1486
1487
1488 /**
1489  * Fill the end of the frame with 0's and compute the two CRCs.
1490  */
1491 static void output_frame_end(AC3EncodeContext *s)
1492 {
1493     const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1494     int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1495     uint8_t *frame;
1496
1497     frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1498
1499     /* pad the remainder of the frame with zeros */
1500     av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1501     flush_put_bits(&s->pb);
1502     frame = s->pb.buf;
1503     pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1504     av_assert2(pad_bytes >= 0);
1505     if (pad_bytes > 0)
1506         memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1507
1508     /* compute crc1 */
1509     /* this is not so easy because it is at the beginning of the data... */
1510     crc1    = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1511     crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1512     crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1513     AV_WB16(frame + 2, crc1);
1514
1515     /* compute crc2 */
1516     crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1517                           s->frame_size - frame_size_58 - 3);
1518     crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1519     /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1520     if (crc2 == 0x770B) {
1521         frame[s->frame_size - 3] ^= 0x1;
1522         crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1523     }
1524     crc2 = av_bswap16(crc2);
1525     AV_WB16(frame + s->frame_size - 2, crc2);
1526 }
1527
1528
1529 /**
1530  * Write the frame to the output bitstream.
1531  */
1532 static void output_frame(AC3EncodeContext *s, unsigned char *frame)
1533 {
1534     int blk;
1535
1536     init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1537
1538     output_frame_header(s);
1539
1540     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1541         output_audio_block(s, blk);
1542
1543     output_frame_end(s);
1544 }
1545
1546
1547 static void dprint_options(AVCodecContext *avctx)
1548 {
1549 #ifdef DEBUG
1550     AC3EncodeContext *s = avctx->priv_data;
1551     AC3EncOptions *opt = &s->options;
1552     char strbuf[32];
1553
1554     switch (s->bitstream_id) {
1555     case  6:  av_strlcpy(strbuf, "AC-3 (alt syntax)", 32);      break;
1556     case  8:  av_strlcpy(strbuf, "AC-3 (standard)", 32);        break;
1557     case  9:  av_strlcpy(strbuf, "AC-3 (dnet half-rate)", 32);  break;
1558     case 10:  av_strlcpy(strbuf, "AC-3 (dnet quater-rate", 32); break;
1559     default: snprintf(strbuf, 32, "ERROR");
1560     }
1561     av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
1562     av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
1563     av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
1564     av_dlog(avctx, "channel_layout: %s\n", strbuf);
1565     av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
1566     av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
1567     if (s->cutoff)
1568         av_dlog(avctx, "cutoff: %d\n", s->cutoff);
1569
1570     av_dlog(avctx, "per_frame_metadata: %s\n",
1571             opt->allow_per_frame_metadata?"on":"off");
1572     if (s->has_center)
1573         av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
1574                 s->center_mix_level);
1575     else
1576         av_dlog(avctx, "center_mixlev: {not written}\n");
1577     if (s->has_surround)
1578         av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
1579                 s->surround_mix_level);
1580     else
1581         av_dlog(avctx, "surround_mixlev: {not written}\n");
1582     if (opt->audio_production_info) {
1583         av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
1584         switch (opt->room_type) {
1585         case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
1586         case 1:  av_strlcpy(strbuf, "large", 32);        break;
1587         case 2:  av_strlcpy(strbuf, "small", 32);        break;
1588         default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
1589         }
1590         av_dlog(avctx, "room_type: %s\n", strbuf);
1591     } else {
1592         av_dlog(avctx, "mixing_level: {not written}\n");
1593         av_dlog(avctx, "room_type: {not written}\n");
1594     }
1595     av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
1596     av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
1597     if (s->channel_mode == AC3_CHMODE_STEREO) {
1598         switch (opt->dolby_surround_mode) {
1599         case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
1600         case 1:  av_strlcpy(strbuf, "on", 32);           break;
1601         case 2:  av_strlcpy(strbuf, "off", 32);          break;
1602         default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
1603         }
1604         av_dlog(avctx, "dsur_mode: %s\n", strbuf);
1605     } else {
1606         av_dlog(avctx, "dsur_mode: {not written}\n");
1607     }
1608     av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
1609
1610     if (s->bitstream_id == 6) {
1611         if (opt->extended_bsi_1) {
1612             switch (opt->preferred_stereo_downmix) {
1613             case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
1614             case 1:  av_strlcpy(strbuf, "ltrt", 32);         break;
1615             case 2:  av_strlcpy(strbuf, "loro", 32);         break;
1616             default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
1617             }
1618             av_dlog(avctx, "dmix_mode: %s\n", strbuf);
1619             av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
1620                     opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
1621             av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
1622                     opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
1623             av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
1624                     opt->loro_center_mix_level, s->loro_center_mix_level);
1625             av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
1626                     opt->loro_surround_mix_level, s->loro_surround_mix_level);
1627         } else {
1628             av_dlog(avctx, "extended bitstream info 1: {not written}\n");
1629         }
1630         if (opt->extended_bsi_2) {
1631             switch (opt->dolby_surround_ex_mode) {
1632             case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
1633             case 1:  av_strlcpy(strbuf, "on", 32);           break;
1634             case 2:  av_strlcpy(strbuf, "off", 32);          break;
1635             default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
1636             }
1637             av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
1638             switch (opt->dolby_headphone_mode) {
1639             case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
1640             case 1:  av_strlcpy(strbuf, "on", 32);           break;
1641             case 2:  av_strlcpy(strbuf, "off", 32);          break;
1642             default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
1643             }
1644             av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
1645
1646             switch (opt->ad_converter_type) {
1647             case 0:  av_strlcpy(strbuf, "standard", 32); break;
1648             case 1:  av_strlcpy(strbuf, "hdcd", 32);     break;
1649             default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
1650             }
1651             av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
1652         } else {
1653             av_dlog(avctx, "extended bitstream info 2: {not written}\n");
1654         }
1655     }
1656 #endif
1657 }
1658
1659
1660 #define FLT_OPTION_THRESHOLD 0.01
1661
1662 static int validate_float_option(float v, const float *v_list, int v_list_size)
1663 {
1664     int i;
1665
1666     for (i = 0; i < v_list_size; i++) {
1667         if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
1668             v > (v_list[i] - FLT_OPTION_THRESHOLD))
1669             break;
1670     }
1671     if (i == v_list_size)
1672         return -1;
1673
1674     return i;
1675 }
1676
1677
1678 static void validate_mix_level(void *log_ctx, const char *opt_name,
1679                                float *opt_param, const float *list,
1680                                int list_size, int default_value, int min_value,
1681                                int *ctx_param)
1682 {
1683     int mixlev = validate_float_option(*opt_param, list, list_size);
1684     if (mixlev < min_value) {
1685         mixlev = default_value;
1686         if (*opt_param >= 0.0) {
1687             av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
1688                    "default value: %0.3f\n", opt_name, list[mixlev]);
1689         }
1690     }
1691     *opt_param = list[mixlev];
1692     *ctx_param = mixlev;
1693 }
1694
1695
1696 /**
1697  * Validate metadata options as set by AVOption system.
1698  * These values can optionally be changed per-frame.
1699  */
1700 static int validate_metadata(AVCodecContext *avctx)
1701 {
1702     AC3EncodeContext *s = avctx->priv_data;
1703     AC3EncOptions *opt = &s->options;
1704
1705     /* validate mixing levels */
1706     if (s->has_center) {
1707         validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
1708                            cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
1709                            &s->center_mix_level);
1710     }
1711     if (s->has_surround) {
1712         validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
1713                            surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
1714                            &s->surround_mix_level);
1715     }
1716
1717     /* set audio production info flag */
1718     if (opt->mixing_level >= 0 || opt->room_type >= 0) {
1719         if (opt->mixing_level < 0) {
1720             av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
1721                    "room_type is set\n");
1722             return AVERROR(EINVAL);
1723         }
1724         if (opt->mixing_level < 80) {
1725             av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
1726                    "80dB and 111dB\n");
1727             return AVERROR(EINVAL);
1728         }
1729         /* default room type */
1730         if (opt->room_type < 0)
1731             opt->room_type = 0;
1732         opt->audio_production_info = 1;
1733     } else {
1734         opt->audio_production_info = 0;
1735     }
1736
1737     /* set extended bsi 1 flag */
1738     if ((s->has_center || s->has_surround) &&
1739         (opt->preferred_stereo_downmix >= 0 ||
1740          opt->ltrt_center_mix_level   >= 0 ||
1741          opt->ltrt_surround_mix_level >= 0 ||
1742          opt->loro_center_mix_level   >= 0 ||
1743          opt->loro_surround_mix_level >= 0)) {
1744         /* default preferred stereo downmix */
1745         if (opt->preferred_stereo_downmix < 0)
1746             opt->preferred_stereo_downmix = 0;
1747         /* validate Lt/Rt center mix level */
1748         validate_mix_level(avctx, "ltrt_center_mix_level",
1749                            &opt->ltrt_center_mix_level, extmixlev_options,
1750                            EXTMIXLEV_NUM_OPTIONS, 5, 0,
1751                            &s->ltrt_center_mix_level);
1752         /* validate Lt/Rt surround mix level */
1753         validate_mix_level(avctx, "ltrt_surround_mix_level",
1754                            &opt->ltrt_surround_mix_level, extmixlev_options,
1755                            EXTMIXLEV_NUM_OPTIONS, 6, 3,
1756                            &s->ltrt_surround_mix_level);
1757         /* validate Lo/Ro center mix level */
1758         validate_mix_level(avctx, "loro_center_mix_level",
1759                            &opt->loro_center_mix_level, extmixlev_options,
1760                            EXTMIXLEV_NUM_OPTIONS, 5, 0,
1761                            &s->loro_center_mix_level);
1762         /* validate Lo/Ro surround mix level */
1763         validate_mix_level(avctx, "loro_surround_mix_level",
1764                            &opt->loro_surround_mix_level, extmixlev_options,
1765                            EXTMIXLEV_NUM_OPTIONS, 6, 3,
1766                            &s->loro_surround_mix_level);
1767         opt->extended_bsi_1 = 1;
1768     } else {
1769         opt->extended_bsi_1 = 0;
1770     }
1771
1772     /* set extended bsi 2 flag */
1773     if (opt->dolby_surround_ex_mode >= 0 ||
1774         opt->dolby_headphone_mode   >= 0 ||
1775         opt->ad_converter_type      >= 0) {
1776         /* default dolby surround ex mode */
1777         if (opt->dolby_surround_ex_mode < 0)
1778             opt->dolby_surround_ex_mode = 0;
1779         /* default dolby headphone mode */
1780         if (opt->dolby_headphone_mode < 0)
1781             opt->dolby_headphone_mode = 0;
1782         /* default A/D converter type */
1783         if (opt->ad_converter_type < 0)
1784             opt->ad_converter_type = 0;
1785         opt->extended_bsi_2 = 1;
1786     } else {
1787         opt->extended_bsi_2 = 0;
1788     }
1789
1790     /* set bitstream id for alternate bitstream syntax */
1791     if (opt->extended_bsi_1 || opt->extended_bsi_2) {
1792         if (s->bitstream_id > 8 && s->bitstream_id < 11) {
1793             static int warn_once = 1;
1794             if (warn_once) {
1795                 av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
1796                        "not compatible with reduced samplerates. writing of "
1797                        "extended bitstream information will be disabled.\n");
1798                 warn_once = 0;
1799             }
1800         } else {
1801             s->bitstream_id = 6;
1802         }
1803     }
1804
1805     return 0;
1806 }
1807
1808
1809 /**
1810  * Encode a single AC-3 frame.
1811  */
1812 static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
1813                             int buf_size, void *data)
1814 {
1815     AC3EncodeContext *s = avctx->priv_data;
1816     const SampleType *samples = data;
1817     int ret;
1818
1819     if (s->options.allow_per_frame_metadata) {
1820         ret = validate_metadata(avctx);
1821         if (ret)
1822             return ret;
1823     }
1824
1825     if (s->bit_alloc.sr_code == 1)
1826         adjust_frame_size(s);
1827
1828     deinterleave_input_samples(s, samples);
1829
1830     apply_mdct(s);
1831
1832     scale_coefficients(s);
1833
1834     compute_rematrixing_strategy(s);
1835
1836     apply_rematrixing(s);
1837
1838     process_exponents(s);
1839
1840     ret = compute_bit_allocation(s);
1841     if (ret) {
1842         av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1843         return ret;
1844     }
1845
1846     quantize_mantissas(s);
1847
1848     output_frame(s, frame);
1849
1850     return s->frame_size;
1851 }
1852
1853
1854 /**
1855  * Finalize encoding and free any memory allocated by the encoder.
1856  */
1857 static av_cold int ac3_encode_close(AVCodecContext *avctx)
1858 {
1859     int blk, ch;
1860     AC3EncodeContext *s = avctx->priv_data;
1861
1862     for (ch = 0; ch < s->channels; ch++)
1863         av_freep(&s->planar_samples[ch]);
1864     av_freep(&s->planar_samples);
1865     av_freep(&s->bap_buffer);
1866     av_freep(&s->bap1_buffer);
1867     av_freep(&s->mdct_coef_buffer);
1868     av_freep(&s->fixed_coef_buffer);
1869     av_freep(&s->exp_buffer);
1870     av_freep(&s->grouped_exp_buffer);
1871     av_freep(&s->psd_buffer);
1872     av_freep(&s->band_psd_buffer);
1873     av_freep(&s->mask_buffer);
1874     av_freep(&s->qmant_buffer);
1875     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1876         AC3Block *block = &s->blocks[blk];
1877         av_freep(&block->bap);
1878         av_freep(&block->mdct_coef);
1879         av_freep(&block->fixed_coef);
1880         av_freep(&block->exp);
1881         av_freep(&block->grouped_exp);
1882         av_freep(&block->psd);
1883         av_freep(&block->band_psd);
1884         av_freep(&block->mask);
1885         av_freep(&block->qmant);
1886     }
1887
1888     mdct_end(&s->mdct);
1889
1890     av_freep(&avctx->coded_frame);
1891     return 0;
1892 }
1893
1894
1895 /**
1896  * Set channel information during initialization.
1897  */
1898 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1899                                     int64_t *channel_layout)
1900 {
1901     int ch_layout;
1902
1903     if (channels < 1 || channels > AC3_MAX_CHANNELS)
1904         return AVERROR(EINVAL);
1905     if ((uint64_t)*channel_layout > 0x7FF)
1906         return AVERROR(EINVAL);
1907     ch_layout = *channel_layout;
1908     if (!ch_layout)
1909         ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1910
1911     s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1912     s->channels     = channels;
1913     s->fbw_channels = channels - s->lfe_on;
1914     s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
1915     if (s->lfe_on)
1916         ch_layout -= AV_CH_LOW_FREQUENCY;
1917
1918     switch (ch_layout) {
1919     case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
1920     case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
1921     case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
1922     case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
1923     case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
1924     case AV_CH_LAYOUT_QUAD:
1925     case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
1926     case AV_CH_LAYOUT_5POINT0:
1927     case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
1928     default:
1929         return AVERROR(EINVAL);
1930     }
1931     s->has_center   = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
1932     s->has_surround =  s->channel_mode & 0x04;
1933
1934     s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1935     *channel_layout = ch_layout;
1936     if (s->lfe_on)
1937         *channel_layout |= AV_CH_LOW_FREQUENCY;
1938
1939     return 0;
1940 }
1941
1942
1943 static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1944 {
1945     int i, ret;
1946
1947     /* validate channel layout */
1948     if (!avctx->channel_layout) {
1949         av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1950                                       "encoder will guess the layout, but it "
1951                                       "might be incorrect.\n");
1952     }
1953     ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1954     if (ret) {
1955         av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1956         return ret;
1957     }
1958
1959     /* validate sample rate */
1960     for (i = 0; i < 9; i++) {
1961         if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
1962             break;
1963     }
1964     if (i == 9) {
1965         av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1966         return AVERROR(EINVAL);
1967     }
1968     s->sample_rate        = avctx->sample_rate;
1969     s->bit_alloc.sr_shift = i % 3;
1970     s->bit_alloc.sr_code  = i / 3;
1971     s->bitstream_id       = 8 + s->bit_alloc.sr_shift;
1972
1973     /* validate bit rate */
1974     for (i = 0; i < 19; i++) {
1975         if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
1976             break;
1977     }
1978     if (i == 19) {
1979         av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
1980         return AVERROR(EINVAL);
1981     }
1982     s->bit_rate        = avctx->bit_rate;
1983     s->frame_size_code = i << 1;
1984
1985     /* validate cutoff */
1986     if (avctx->cutoff < 0) {
1987         av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
1988         return AVERROR(EINVAL);
1989     }
1990     s->cutoff = avctx->cutoff;
1991     if (s->cutoff > (s->sample_rate >> 1))
1992         s->cutoff = s->sample_rate >> 1;
1993
1994     /* validate audio service type / channels combination */
1995     if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
1996          avctx->channels == 1) ||
1997         ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
1998           avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY  ||
1999           avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
2000          && avctx->channels > 1)) {
2001         av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
2002                                     "specified number of channels\n");
2003         return AVERROR(EINVAL);
2004     }
2005
2006     ret = validate_metadata(avctx);
2007     if (ret)
2008         return ret;
2009
2010     s->rematrixing_enabled = s->options.stereo_rematrixing &&
2011                              (s->channel_mode == AC3_CHMODE_STEREO);
2012
2013     return 0;
2014 }
2015
2016
2017 /**
2018  * Set bandwidth for all channels.
2019  * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2020  * default value will be used.
2021  */
2022 static av_cold void set_bandwidth(AC3EncodeContext *s)
2023 {
2024     int ch;
2025
2026     if (s->cutoff) {
2027         /* calculate bandwidth based on user-specified cutoff frequency */
2028         int fbw_coeffs;
2029         fbw_coeffs     = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2030         s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2031     } else {
2032         /* use default bandwidth setting */
2033         s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2034     }
2035
2036     /* set number of coefficients for each channel */
2037     for (ch = 0; ch < s->fbw_channels; ch++) {
2038         s->nb_coefs[ch] = s->bandwidth_code * 3 + 73;
2039     }
2040     if (s->lfe_on)
2041         s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
2042 }
2043
2044
2045 static av_cold int allocate_buffers(AVCodecContext *avctx)
2046 {
2047     int blk, ch;
2048     AC3EncodeContext *s = avctx->priv_data;
2049
2050     FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
2051                      alloc_fail);
2052     for (ch = 0; ch < s->channels; ch++) {
2053         FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
2054                           (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
2055                           alloc_fail);
2056     }
2057     FF_ALLOC_OR_GOTO(avctx, s->bap_buffer,  AC3_MAX_BLOCKS * s->channels *
2058                      AC3_MAX_COEFS * sizeof(*s->bap_buffer),  alloc_fail);
2059     FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
2060                      AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
2061     FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
2062                      AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
2063     FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
2064                      AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
2065     FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
2066                      128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
2067     FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
2068                      AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
2069     FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
2070                      64 * sizeof(*s->band_psd_buffer), alloc_fail);
2071     FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
2072                      64 * sizeof(*s->mask_buffer), alloc_fail);
2073     FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
2074                      AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
2075     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2076         AC3Block *block = &s->blocks[blk];
2077         FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
2078                          alloc_fail);
2079         FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
2080                           alloc_fail);
2081         FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
2082                           alloc_fail);
2083         FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
2084                           alloc_fail);
2085         FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
2086                           alloc_fail);
2087         FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
2088                           alloc_fail);
2089         FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
2090                           alloc_fail);
2091         FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
2092                           alloc_fail);
2093
2094         for (ch = 0; ch < s->channels; ch++) {
2095             /* arrangement: block, channel, coeff */
2096             block->bap[ch]         = &s->bap_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
2097             block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (blk * s->channels + ch)];
2098             block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * s->channels + ch)];
2099             block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
2100             block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * s->channels + ch)];
2101             block->mask[ch]        = &s->mask_buffer       [64            * (blk * s->channels + ch)];
2102             block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * s->channels + ch)];
2103
2104             /* arrangement: channel, block, coeff */
2105             block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2106         }
2107     }
2108
2109     if (CONFIG_AC3ENC_FLOAT) {
2110         FF_ALLOC_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * s->channels *
2111                          AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
2112         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2113             AC3Block *block = &s->blocks[blk];
2114             FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2115                               sizeof(*block->fixed_coef), alloc_fail);
2116             for (ch = 0; ch < s->channels; ch++)
2117                 block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
2118         }
2119     } else {
2120         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2121             AC3Block *block = &s->blocks[blk];
2122             FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2123                               sizeof(*block->fixed_coef), alloc_fail);
2124             for (ch = 0; ch < s->channels; ch++)
2125                 block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2126         }
2127     }
2128
2129     return 0;
2130 alloc_fail:
2131     return AVERROR(ENOMEM);
2132 }
2133
2134
2135 /**
2136  * Initialize the encoder.
2137  */
2138 static av_cold int ac3_encode_init(AVCodecContext *avctx)
2139 {
2140     AC3EncodeContext *s = avctx->priv_data;
2141     int ret, frame_size_58;
2142
2143     avctx->frame_size = AC3_FRAME_SIZE;
2144
2145     ff_ac3_common_init();
2146
2147     ret = validate_options(avctx, s);
2148     if (ret)
2149         return ret;
2150
2151     s->bitstream_mode = avctx->audio_service_type;
2152     if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2153         s->bitstream_mode = 0x7;
2154
2155     s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2156     s->bits_written    = 0;
2157     s->samples_written = 0;
2158     s->frame_size      = s->frame_size_min;
2159
2160     /* calculate crc_inv for both possible frame sizes */
2161     frame_size_58 = (( s->frame_size    >> 2) + ( s->frame_size    >> 4)) << 1;
2162     s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2163     if (s->bit_alloc.sr_code == 1) {
2164         frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2165         s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2166     }
2167
2168     set_bandwidth(s);
2169
2170     exponent_init(s);
2171
2172     bit_alloc_init(s);
2173
2174     ret = mdct_init(avctx, &s->mdct, 9);
2175     if (ret)
2176         goto init_fail;
2177
2178     ret = allocate_buffers(avctx);
2179     if (ret)
2180         goto init_fail;
2181
2182     avctx->coded_frame= avcodec_alloc_frame();
2183
2184     dsputil_init(&s->dsp, avctx);
2185     ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2186
2187     dprint_options(avctx);
2188
2189     return 0;
2190 init_fail:
2191     ac3_encode_close(avctx);
2192     return ret;
2193 }