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