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