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