Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ 4d7a4215

History | View | Annotate | Download (77.5 KB)

1
/*
2
 * The simplest AC-3 encoder
3
 * Copyright (c) 2000 Fabrice Bellard
4
 * Copyright (c) 2006-2010 Justin Ruggles <justin.ruggles@gmail.com>
5
 * Copyright (c) 2006-2010 Prakash Punnoor <prakash@punnoor.de>
6
 *
7
 * This file is part of Libav.
8
 *
9
 * Libav is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU Lesser General Public
11
 * License as published by the Free Software Foundation; either
12
 * version 2.1 of the License, or (at your option) any later version.
13
 *
14
 * Libav is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17
 * Lesser General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU Lesser General Public
20
 * License along with Libav; if not, write to the Free Software
21
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22
 */
23

    
24
/**
25
 * @file
26
 * The simplest AC-3 encoder.
27
 */
28

    
29
//#define DEBUG
30
//#define ASSERT_LEVEL 2
31

    
32
#include <stdint.h>
33

    
34
#include "libavutil/audioconvert.h"
35
#include "libavutil/avassert.h"
36
#include "libavutil/avstring.h"
37
#include "libavutil/crc.h"
38
#include "libavutil/opt.h"
39
#include "avcodec.h"
40
#include "put_bits.h"
41
#include "dsputil.h"
42
#include "ac3dsp.h"
43
#include "ac3.h"
44
#include "audioconvert.h"
45
#include "fft.h"
46

    
47

    
48
#ifndef CONFIG_AC3ENC_FLOAT
49
#define CONFIG_AC3ENC_FLOAT 0
50
#endif
51

    
52

    
53
/** Maximum number of exponent groups. +1 for separate DC exponent. */
54
#define AC3_MAX_EXP_GROUPS 85
55

    
56
#if CONFIG_AC3ENC_FLOAT
57
#define MAC_COEF(d,a,b) ((d)+=(a)*(b))
58
typedef float SampleType;
59
typedef float CoefType;
60
typedef float CoefSumType;
61
#else
62
#define MAC_COEF(d,a,b) MAC64(d,a,b)
63
typedef int16_t SampleType;
64
typedef int32_t CoefType;
65
typedef int64_t CoefSumType;
66
#endif
67

    
68
typedef struct AC3MDCTContext {
69
    const SampleType *window;           ///< MDCT window function
70
    FFTContext fft;                     ///< FFT context for MDCT calculation
71
} AC3MDCTContext;
72

    
73
/**
74
 * Encoding Options used by AVOption.
75
 */
76
typedef struct AC3EncOptions {
77
    /* AC-3 metadata options*/
78
    int dialogue_level;
79
    int bitstream_mode;
80
    float center_mix_level;
81
    float surround_mix_level;
82
    int dolby_surround_mode;
83
    int audio_production_info;
84
    int mixing_level;
85
    int room_type;
86
    int copyright;
87
    int original;
88
    int extended_bsi_1;
89
    int preferred_stereo_downmix;
90
    float ltrt_center_mix_level;
91
    float ltrt_surround_mix_level;
92
    float loro_center_mix_level;
93
    float loro_surround_mix_level;
94
    int extended_bsi_2;
95
    int dolby_surround_ex_mode;
96
    int dolby_headphone_mode;
97
    int ad_converter_type;
98

    
99
    /* other encoding options */
100
    int allow_per_frame_metadata;
101
    int stereo_rematrixing;
102
} AC3EncOptions;
103

    
104
/**
105
 * Data for a single audio block.
106
 */
107
typedef struct AC3Block {
108
    uint8_t  **bap;                             ///< bit allocation pointers (bap)
109
    CoefType **mdct_coef;                       ///< MDCT coefficients
110
    int32_t  **fixed_coef;                      ///< fixed-point MDCT coefficients
111
    uint8_t  **exp;                             ///< original exponents
112
    uint8_t  **grouped_exp;                     ///< grouped exponents
113
    int16_t  **psd;                             ///< psd per frequency bin
114
    int16_t  **band_psd;                        ///< psd per critical band
115
    int16_t  **mask;                            ///< masking curve
116
    uint16_t **qmant;                           ///< quantized mantissas
117
    uint8_t  coeff_shift[AC3_MAX_CHANNELS];     ///< fixed-point coefficient shift values
118
    uint8_t  new_rematrixing_strategy;          ///< send new rematrixing flags in this block
119
    uint8_t  rematrixing_flags[4];              ///< rematrixing flags
120
    struct AC3Block *exp_ref_block[AC3_MAX_CHANNELS]; ///< reference blocks for EXP_REUSE
121
} AC3Block;
122

    
123
/**
124
 * AC-3 encoder private context.
125
 */
126
typedef struct AC3EncodeContext {
127
    AVClass *av_class;                      ///< AVClass used for AVOption
128
    AC3EncOptions options;                  ///< encoding options
129
    PutBitContext pb;                       ///< bitstream writer context
130
    DSPContext dsp;
131
    AC3DSPContext ac3dsp;                   ///< AC-3 optimized functions
132
    AC3MDCTContext mdct;                    ///< MDCT context
133

    
134
    AC3Block blocks[AC3_MAX_BLOCKS];        ///< per-block info
135

    
136
    int bitstream_id;                       ///< bitstream id                           (bsid)
137
    int bitstream_mode;                     ///< bitstream mode                         (bsmod)
138

    
139
    int bit_rate;                           ///< target bit rate, in bits-per-second
140
    int sample_rate;                        ///< sampling frequency, in Hz
141

    
142
    int frame_size_min;                     ///< minimum frame size in case rounding is necessary
143
    int frame_size;                         ///< current frame size in bytes
144
    int frame_size_code;                    ///< frame size code                        (frmsizecod)
145
    uint16_t crc_inv[2];
146
    int bits_written;                       ///< bit count    (used to avg. bitrate)
147
    int samples_written;                    ///< sample count (used to avg. bitrate)
148

    
149
    int fbw_channels;                       ///< number of full-bandwidth channels      (nfchans)
150
    int channels;                           ///< total number of channels               (nchans)
151
    int lfe_on;                             ///< indicates if there is an LFE channel   (lfeon)
152
    int lfe_channel;                        ///< channel index of the LFE channel
153
    int has_center;                         ///< indicates if there is a center channel
154
    int has_surround;                       ///< indicates if there are one or more surround channels
155
    int channel_mode;                       ///< channel mode                           (acmod)
156
    const uint8_t *channel_map;             ///< channel map used to reorder channels
157

    
158
    int center_mix_level;                   ///< center mix level code
159
    int surround_mix_level;                 ///< surround mix level code
160
    int ltrt_center_mix_level;              ///< Lt/Rt center mix level code
161
    int ltrt_surround_mix_level;            ///< Lt/Rt surround mix level code
162
    int loro_center_mix_level;              ///< Lo/Ro center mix level code
163
    int loro_surround_mix_level;            ///< Lo/Ro surround mix level code
164

    
165
    int cutoff;                             ///< user-specified cutoff frequency, in Hz
166
    int bandwidth_code;                     ///< bandwidth code (0 to 60)               (chbwcod)
167
    int nb_coefs[AC3_MAX_CHANNELS];
168

    
169
    int rematrixing_enabled;                ///< stereo rematrixing enabled
170
    int num_rematrixing_bands;              ///< number of rematrixing bands
171

    
172
    /* bitrate allocation control */
173
    int slow_gain_code;                     ///< slow gain code                         (sgaincod)
174
    int slow_decay_code;                    ///< slow decay code                        (sdcycod)
175
    int fast_decay_code;                    ///< fast decay code                        (fdcycod)
176
    int db_per_bit_code;                    ///< dB/bit code                            (dbpbcod)
177
    int floor_code;                         ///< floor code                             (floorcod)
178
    AC3BitAllocParameters bit_alloc;        ///< bit allocation parameters
179
    int coarse_snr_offset;                  ///< coarse SNR offsets                     (csnroffst)
180
    int fast_gain_code[AC3_MAX_CHANNELS];   ///< fast gain codes (signal-to-mask ratio) (fgaincod)
181
    int fine_snr_offset[AC3_MAX_CHANNELS];  ///< fine SNR offsets                       (fsnroffst)
182
    int frame_bits_fixed;                   ///< number of non-coefficient bits for fixed parameters
183
    int frame_bits;                         ///< all frame bits except exponents and mantissas
184
    int exponent_bits;                      ///< number of bits used for exponents
185

    
186
    SampleType **planar_samples;
187
    uint8_t *bap_buffer;
188
    uint8_t *bap1_buffer;
189
    CoefType *mdct_coef_buffer;
190
    int32_t *fixed_coef_buffer;
191
    uint8_t *exp_buffer;
192
    uint8_t *grouped_exp_buffer;
193
    int16_t *psd_buffer;
194
    int16_t *band_psd_buffer;
195
    int16_t *mask_buffer;
196
    uint16_t *qmant_buffer;
197

    
198
    uint8_t exp_strategy[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< exponent strategies
199

    
200
    DECLARE_ALIGNED(32, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
201
} AC3EncodeContext;
202

    
203
typedef struct AC3Mant {
204
    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
205
    int mant1_cnt, mant2_cnt, mant4_cnt;    ///< mantissa counts for bap=1,2,4
206
} AC3Mant;
207

    
208
#define CMIXLEV_NUM_OPTIONS 3
209
static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
210
    LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
211
};
212

    
213
#define SURMIXLEV_NUM_OPTIONS 3
214
static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
215
    LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
216
};
217

    
218
#define EXTMIXLEV_NUM_OPTIONS 8
219
static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
220
    LEVEL_PLUS_3DB,  LEVEL_PLUS_1POINT5DB,  LEVEL_ONE,       LEVEL_MINUS_4POINT5DB,
221
    LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
222
};
223

    
224

    
225
#define OFFSET(param) offsetof(AC3EncodeContext, options.param)
226
#define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
227

    
228
static const AVOption options[] = {
229
/* Metadata Options */
230
{"per_frame_metadata", "Allow Changing Metadata Per-Frame", OFFSET(allow_per_frame_metadata), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 1, AC3ENC_PARAM},
231
/* downmix levels */
232
{"center_mixlev", "Center Mix Level", OFFSET(center_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = LEVEL_MINUS_4POINT5DB }, 0.0, 1.0, AC3ENC_PARAM},
233
{"surround_mixlev", "Surround Mix Level", OFFSET(surround_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = LEVEL_MINUS_6DB }, 0.0, 1.0, AC3ENC_PARAM},
234
/* audio production information */
235
{"mixing_level", "Mixing Level", OFFSET(mixing_level), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 111, AC3ENC_PARAM},
236
{"room_type", "Room Type", OFFSET(room_type), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "room_type"},
237
    {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
238
    {"large",        "Large Room",              0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
239
    {"small",        "Small Room",              0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
240
/* other metadata options */
241
{"copyright", "Copyright Bit", OFFSET(copyright), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 1, AC3ENC_PARAM},
242
{"dialnorm", "Dialogue Level (dB)", OFFSET(dialogue_level), FF_OPT_TYPE_INT, {.dbl = -31 }, -31, -1, AC3ENC_PARAM},
243
{"dsur_mode", "Dolby Surround Mode", OFFSET(dolby_surround_mode), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, 2, AC3ENC_PARAM, "dsur_mode"},
244
    {"notindicated", "Not Indicated (default)",    0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
245
    {"on",           "Dolby Surround Encoded",     0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
246
    {"off",          "Not Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
247
{"original", "Original Bit Stream", OFFSET(original), FF_OPT_TYPE_INT,   {.dbl = 1 }, 0, 1, AC3ENC_PARAM},
248
/* extended bitstream information */
249
{"dmix_mode", "Preferred Stereo Downmix Mode", OFFSET(preferred_stereo_downmix), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dmix_mode"},
250
    {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
251
    {"ltrt", "Lt/Rt Downmix Preferred",         0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
252
    {"loro", "Lo/Ro Downmix Preferred",         0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
253
{"ltrt_cmixlev", "Lt/Rt Center Mix Level", OFFSET(ltrt_center_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
254
{"ltrt_surmixlev", "Lt/Rt Surround Mix Level", OFFSET(ltrt_surround_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
255
{"loro_cmixlev", "Lo/Ro Center Mix Level", OFFSET(loro_center_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
256
{"loro_surmixlev", "Lo/Ro Surround Mix Level", OFFSET(loro_surround_mix_level), FF_OPT_TYPE_FLOAT, {.dbl = -1.0 }, -1.0, 2.0, AC3ENC_PARAM},
257
{"dsurex_mode", "Dolby Surround EX Mode", OFFSET(dolby_surround_ex_mode), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dsurex_mode"},
258
    {"notindicated", "Not Indicated (default)",       0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
259
    {"on",           "Dolby Surround EX Encoded",     0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
260
    {"off",          "Not Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
261
{"dheadphone_mode", "Dolby Headphone Mode", OFFSET(dolby_headphone_mode), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 2, AC3ENC_PARAM, "dheadphone_mode"},
262
    {"notindicated", "Not Indicated (default)",     0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
263
    {"on",           "Dolby Headphone Encoded",     0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
264
    {"off",          "Not Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, {.dbl = 2 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
265
{"ad_conv_type", "A/D Converter Type", OFFSET(ad_converter_type), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, 1, AC3ENC_PARAM, "ad_conv_type"},
266
    {"standard", "Standard (default)", 0, FF_OPT_TYPE_CONST, {.dbl = 0 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
267
    {"hdcd",     "HDCD",               0, FF_OPT_TYPE_CONST, {.dbl = 1 }, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
268
/* Other Encoding Options */
269
{"stereo_rematrixing", "Stereo Rematrixing", OFFSET(stereo_rematrixing), FF_OPT_TYPE_INT, {.dbl = 1 }, 0, 1, AC3ENC_PARAM},
270
{NULL}
271
};
272

    
273
#if CONFIG_AC3ENC_FLOAT
274
static AVClass ac3enc_class = { "AC-3 Encoder", av_default_item_name,
275
                                options, LIBAVUTIL_VERSION_INT };
276
#else
277
static AVClass ac3enc_class = { "Fixed-Point AC-3 Encoder", av_default_item_name,
278
                                options, LIBAVUTIL_VERSION_INT };
279
#endif
280

    
281

    
282
/* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
283

    
284
static av_cold void mdct_end(AC3MDCTContext *mdct);
285

    
286
static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
287
                             int nbits);
288

    
289
static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
290
                         const SampleType *window, unsigned int len);
291

    
292
static int normalize_samples(AC3EncodeContext *s);
293

    
294
static void scale_coefficients(AC3EncodeContext *s);
295

    
296

    
297
/**
298
 * LUT for number of exponent groups.
299
 * exponent_group_tab[exponent strategy-1][number of coefficients]
300
 */
301
static uint8_t exponent_group_tab[3][256];
302

    
303

    
304
/**
305
 * List of supported channel layouts.
306
 */
307
static const int64_t ac3_channel_layouts[] = {
308
     AV_CH_LAYOUT_MONO,
309
     AV_CH_LAYOUT_STEREO,
310
     AV_CH_LAYOUT_2_1,
311
     AV_CH_LAYOUT_SURROUND,
312
     AV_CH_LAYOUT_2_2,
313
     AV_CH_LAYOUT_QUAD,
314
     AV_CH_LAYOUT_4POINT0,
315
     AV_CH_LAYOUT_5POINT0,
316
     AV_CH_LAYOUT_5POINT0_BACK,
317
    (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
318
    (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
319
    (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
320
    (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
321
    (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
322
    (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
323
    (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
324
     AV_CH_LAYOUT_5POINT1,
325
     AV_CH_LAYOUT_5POINT1_BACK,
326
     0
327
};
328

    
329

    
330
/**
331
 * LUT to select the bandwidth code based on the bit rate, sample rate, and
332
 * number of full-bandwidth channels.
333
 * bandwidth_tab[fbw_channels-1][sample rate code][bit rate code]
334
 */
335
static const uint8_t ac3_bandwidth_tab[5][3][19] = {
336
//      32  40  48  56  64  80  96 112 128 160 192 224 256 320 384 448 512 576 640
337

    
338
    { {  0,  0,  0, 12, 16, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
339
      {  0,  0,  0, 16, 20, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
340
      {  0,  0,  0, 32, 40, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
341

    
342
    { {  0,  0,  0,  0,  0,  0,  0, 20, 24, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
343
      {  0,  0,  0,  0,  0,  0,  4, 24, 28, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
344
      {  0,  0,  0,  0,  0,  0, 20, 44, 52, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
345

    
346
    { {  0,  0,  0,  0,  0,  0,  0,  0,  0, 16, 24, 32, 40, 48, 48, 48, 48, 48, 48 },
347
      {  0,  0,  0,  0,  0,  0,  0,  0,  4, 20, 28, 36, 44, 56, 56, 56, 56, 56, 56 },
348
      {  0,  0,  0,  0,  0,  0,  0,  0, 20, 40, 48, 60, 60, 60, 60, 60, 60, 60, 60 } },
349

    
350
    { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 12, 24, 32, 48, 48, 48, 48, 48, 48 },
351
      {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 16, 28, 36, 56, 56, 56, 56, 56, 56 },
352
      {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 32, 48, 60, 60, 60, 60, 60, 60, 60 } },
353

    
354
    { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  8, 20, 32, 40, 48, 48, 48, 48 },
355
      {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 12, 24, 36, 44, 56, 56, 56, 56 },
356
      {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 28, 44, 60, 60, 60, 60, 60, 60 } }
357
};
358

    
359

    
360
/**
361
 * Adjust the frame size to make the average bit rate match the target bit rate.
362
 * This is only needed for 11025, 22050, and 44100 sample rates.
363
 */
364
static void adjust_frame_size(AC3EncodeContext *s)
365
{
366
    while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
367
        s->bits_written    -= s->bit_rate;
368
        s->samples_written -= s->sample_rate;
369
    }
370
    s->frame_size = s->frame_size_min +
371
                    2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
372
    s->bits_written    += s->frame_size * 8;
373
    s->samples_written += AC3_FRAME_SIZE;
374
}
375

    
376

    
377
/**
378
 * Deinterleave input samples.
379
 * Channels are reordered from Libav's default order to AC-3 order.
380
 */
381
static void deinterleave_input_samples(AC3EncodeContext *s,
382
                                       const SampleType *samples)
383
{
384
    int ch, i;
385

    
386
    /* deinterleave and remap input samples */
387
    for (ch = 0; ch < s->channels; ch++) {
388
        const SampleType *sptr;
389
        int sinc;
390

    
391
        /* copy last 256 samples of previous frame to the start of the current frame */
392
        memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
393
               AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
394

    
395
        /* deinterleave */
396
        sinc = s->channels;
397
        sptr = samples + s->channel_map[ch];
398
        for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
399
            s->planar_samples[ch][i] = *sptr;
400
            sptr += sinc;
401
        }
402
    }
403
}
404

    
405

    
406
/**
407
 * Apply the MDCT to input samples to generate frequency coefficients.
408
 * This applies the KBD window and normalizes the input to reduce precision
409
 * loss due to fixed-point calculations.
410
 */
411
static void apply_mdct(AC3EncodeContext *s)
412
{
413
    int blk, ch;
414

    
415
    for (ch = 0; ch < s->channels; ch++) {
416
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
417
            AC3Block *block = &s->blocks[blk];
418
            const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
419

    
420
            apply_window(&s->dsp, s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
421

    
422
            block->coeff_shift[ch] = normalize_samples(s);
423

    
424
            s->mdct.fft.mdct_calcw(&s->mdct.fft, block->mdct_coef[ch],
425
                                   s->windowed_samples);
426
        }
427
    }
428
}
429

    
430

    
431
/**
432
 * Determine rematrixing flags for each block and band.
433
 */
434
static void compute_rematrixing_strategy(AC3EncodeContext *s)
435
{
436
    int nb_coefs;
437
    int blk, bnd, i;
438
    AC3Block *block, *block0;
439

    
440
    if (s->channel_mode != AC3_CHMODE_STEREO)
441
        return;
442

    
443
    s->num_rematrixing_bands = 4;
444

    
445
    nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
446

    
447
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
448
        block = &s->blocks[blk];
449
        block->new_rematrixing_strategy = !blk;
450
        if (!s->rematrixing_enabled)
451
            continue;
452
        for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
453
            /* calculate calculate sum of squared coeffs for one band in one block */
454
            int start = ff_ac3_rematrix_band_tab[bnd];
455
            int end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
456
            CoefSumType sum[4] = {0,};
457
            for (i = start; i < end; i++) {
458
                CoefType lt = block->mdct_coef[0][i];
459
                CoefType rt = block->mdct_coef[1][i];
460
                CoefType md = lt + rt;
461
                CoefType sd = lt - rt;
462
                MAC_COEF(sum[0], lt, lt);
463
                MAC_COEF(sum[1], rt, rt);
464
                MAC_COEF(sum[2], md, md);
465
                MAC_COEF(sum[3], sd, sd);
466
            }
467

    
468
            /* compare sums to determine if rematrixing will be used for this band */
469
            if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
470
                block->rematrixing_flags[bnd] = 1;
471
            else
472
                block->rematrixing_flags[bnd] = 0;
473

    
474
            /* determine if new rematrixing flags will be sent */
475
            if (blk &&
476
                block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
477
                block->new_rematrixing_strategy = 1;
478
            }
479
        }
480
        block0 = block;
481
    }
482
}
483

    
484

    
485
/**
486
 * Apply stereo rematrixing to coefficients based on rematrixing flags.
487
 */
488
static void apply_rematrixing(AC3EncodeContext *s)
489
{
490
    int nb_coefs;
491
    int blk, bnd, i;
492
    int start, end;
493
    uint8_t *flags;
494

    
495
    if (!s->rematrixing_enabled)
496
        return;
497

    
498
    nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
499

    
500
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
501
        AC3Block *block = &s->blocks[blk];
502
        if (block->new_rematrixing_strategy)
503
            flags = block->rematrixing_flags;
504
        for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
505
            if (flags[bnd]) {
506
                start = ff_ac3_rematrix_band_tab[bnd];
507
                end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
508
                for (i = start; i < end; i++) {
509
                    int32_t lt = block->fixed_coef[0][i];
510
                    int32_t rt = block->fixed_coef[1][i];
511
                    block->fixed_coef[0][i] = (lt + rt) >> 1;
512
                    block->fixed_coef[1][i] = (lt - rt) >> 1;
513
                }
514
            }
515
        }
516
    }
517
}
518

    
519

    
520
/**
521
 * Initialize exponent tables.
522
 */
523
static av_cold void exponent_init(AC3EncodeContext *s)
524
{
525
    int expstr, i, grpsize;
526

    
527
    for (expstr = EXP_D15-1; expstr <= EXP_D45-1; expstr++) {
528
        grpsize = 3 << expstr;
529
        for (i = 73; i < 256; i++) {
530
            exponent_group_tab[expstr][i] = (i + grpsize - 4) / grpsize;
531
        }
532
    }
533
    /* LFE */
534
    exponent_group_tab[0][7] = 2;
535
}
536

    
537

    
538
/**
539
 * Extract exponents from the MDCT coefficients.
540
 * This takes into account the normalization that was done to the input samples
541
 * by adjusting the exponents by the exponent shift values.
542
 */
543
static void extract_exponents(AC3EncodeContext *s)
544
{
545
    int blk, ch;
546

    
547
    for (ch = 0; ch < s->channels; ch++) {
548
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
549
            AC3Block *block = &s->blocks[blk];
550
            s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch],
551
                                        AC3_MAX_COEFS);
552
        }
553
    }
554
}
555

    
556

    
557
/**
558
 * Exponent Difference Threshold.
559
 * New exponents are sent if their SAD exceed this number.
560
 */
561
#define EXP_DIFF_THRESHOLD 500
562

    
563

    
564
/**
565
 * Calculate exponent strategies for all channels.
566
 * Array arrangement is reversed to simplify the per-channel calculation.
567
 */
568
static void compute_exp_strategy(AC3EncodeContext *s)
569
{
570
    int ch, blk, blk1;
571

    
572
    for (ch = 0; ch < s->fbw_channels; ch++) {
573
        uint8_t *exp_strategy = s->exp_strategy[ch];
574
        uint8_t *exp          = s->blocks[0].exp[ch];
575
        int exp_diff;
576

    
577
        /* estimate if the exponent variation & decide if they should be
578
           reused in the next frame */
579
        exp_strategy[0] = EXP_NEW;
580
        exp += AC3_MAX_COEFS;
581
        for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
582
            exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
583
            if (exp_diff > EXP_DIFF_THRESHOLD)
584
                exp_strategy[blk] = EXP_NEW;
585
            else
586
                exp_strategy[blk] = EXP_REUSE;
587
            exp += AC3_MAX_COEFS;
588
        }
589

    
590
        /* now select the encoding strategy type : if exponents are often
591
           recoded, we use a coarse encoding */
592
        blk = 0;
593
        while (blk < AC3_MAX_BLOCKS) {
594
            blk1 = blk + 1;
595
            while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
596
                blk1++;
597
            switch (blk1 - blk) {
598
            case 1:  exp_strategy[blk] = EXP_D45; break;
599
            case 2:
600
            case 3:  exp_strategy[blk] = EXP_D25; break;
601
            default: exp_strategy[blk] = EXP_D15; break;
602
            }
603
            blk = blk1;
604
        }
605
    }
606
    if (s->lfe_on) {
607
        ch = s->lfe_channel;
608
        s->exp_strategy[ch][0] = EXP_D15;
609
        for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
610
            s->exp_strategy[ch][blk] = EXP_REUSE;
611
    }
612
}
613

    
614

    
615
/**
616
 * Update the exponents so that they are the ones the decoder will decode.
617
 */
618
static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy)
619
{
620
    int nb_groups, i, k;
621

    
622
    nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
623

    
624
    /* for each group, compute the minimum exponent */
625
    switch(exp_strategy) {
626
    case EXP_D25:
627
        for (i = 1, k = 1; i <= nb_groups; i++) {
628
            uint8_t exp_min = exp[k];
629
            if (exp[k+1] < exp_min)
630
                exp_min = exp[k+1];
631
            exp[i] = exp_min;
632
            k += 2;
633
        }
634
        break;
635
    case EXP_D45:
636
        for (i = 1, k = 1; i <= nb_groups; i++) {
637
            uint8_t exp_min = exp[k];
638
            if (exp[k+1] < exp_min)
639
                exp_min = exp[k+1];
640
            if (exp[k+2] < exp_min)
641
                exp_min = exp[k+2];
642
            if (exp[k+3] < exp_min)
643
                exp_min = exp[k+3];
644
            exp[i] = exp_min;
645
            k += 4;
646
        }
647
        break;
648
    }
649

    
650
    /* constraint for DC exponent */
651
    if (exp[0] > 15)
652
        exp[0] = 15;
653

    
654
    /* decrease the delta between each groups to within 2 so that they can be
655
       differentially encoded */
656
    for (i = 1; i <= nb_groups; i++)
657
        exp[i] = FFMIN(exp[i], exp[i-1] + 2);
658
    i--;
659
    while (--i >= 0)
660
        exp[i] = FFMIN(exp[i], exp[i+1] + 2);
661

    
662
    /* now we have the exponent values the decoder will see */
663
    switch (exp_strategy) {
664
    case EXP_D25:
665
        for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
666
            uint8_t exp1 = exp[i];
667
            exp[k--] = exp1;
668
            exp[k--] = exp1;
669
        }
670
        break;
671
    case EXP_D45:
672
        for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
673
            exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
674
            k -= 4;
675
        }
676
        break;
677
    }
678
}
679

    
680

    
681
/**
682
 * Encode exponents from original extracted form to what the decoder will see.
683
 * This copies and groups exponents based on exponent strategy and reduces
684
 * deltas between adjacent exponent groups so that they can be differentially
685
 * encoded.
686
 */
687
static void encode_exponents(AC3EncodeContext *s)
688
{
689
    int blk, blk1, ch;
690
    uint8_t *exp, *exp_strategy;
691
    int nb_coefs, num_reuse_blocks;
692

    
693
    for (ch = 0; ch < s->channels; ch++) {
694
        exp          = s->blocks[0].exp[ch];
695
        exp_strategy = s->exp_strategy[ch];
696
        nb_coefs     = s->nb_coefs[ch];
697

    
698
        blk = 0;
699
        while (blk < AC3_MAX_BLOCKS) {
700
            blk1 = blk + 1;
701

    
702
            /* count the number of EXP_REUSE blocks after the current block
703
               and set exponent reference block pointers */
704
            s->blocks[blk].exp_ref_block[ch] = &s->blocks[blk];
705
            while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
706
                s->blocks[blk1].exp_ref_block[ch] = &s->blocks[blk];
707
                blk1++;
708
            }
709
            num_reuse_blocks = blk1 - blk - 1;
710

    
711
            /* for the EXP_REUSE case we select the min of the exponents */
712
            s->ac3dsp.ac3_exponent_min(exp, num_reuse_blocks, nb_coefs);
713

    
714
            encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk]);
715

    
716
            exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
717
            blk = blk1;
718
        }
719
    }
720
}
721

    
722

    
723
/**
724
 * Group exponents.
725
 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
726
 * varies depending on exponent strategy and bandwidth.
727
 */
728
static void group_exponents(AC3EncodeContext *s)
729
{
730
    int blk, ch, i;
731
    int group_size, nb_groups, bit_count;
732
    uint8_t *p;
733
    int delta0, delta1, delta2;
734
    int exp0, exp1;
735

    
736
    bit_count = 0;
737
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
738
        AC3Block *block = &s->blocks[blk];
739
        for (ch = 0; ch < s->channels; ch++) {
740
            int exp_strategy = s->exp_strategy[ch][blk];
741
            if (exp_strategy == EXP_REUSE)
742
                continue;
743
            group_size = exp_strategy + (exp_strategy == EXP_D45);
744
            nb_groups = exponent_group_tab[exp_strategy-1][s->nb_coefs[ch]];
745
            bit_count += 4 + (nb_groups * 7);
746
            p = block->exp[ch];
747

    
748
            /* DC exponent */
749
            exp1 = *p++;
750
            block->grouped_exp[ch][0] = exp1;
751

    
752
            /* remaining exponents are delta encoded */
753
            for (i = 1; i <= nb_groups; i++) {
754
                /* merge three delta in one code */
755
                exp0   = exp1;
756
                exp1   = p[0];
757
                p     += group_size;
758
                delta0 = exp1 - exp0 + 2;
759
                av_assert2(delta0 >= 0 && delta0 <= 4);
760

    
761
                exp0   = exp1;
762
                exp1   = p[0];
763
                p     += group_size;
764
                delta1 = exp1 - exp0 + 2;
765
                av_assert2(delta1 >= 0 && delta1 <= 4);
766

    
767
                exp0   = exp1;
768
                exp1   = p[0];
769
                p     += group_size;
770
                delta2 = exp1 - exp0 + 2;
771
                av_assert2(delta2 >= 0 && delta2 <= 4);
772

    
773
                block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
774
            }
775
        }
776
    }
777

    
778
    s->exponent_bits = bit_count;
779
}
780

    
781

    
782
/**
783
 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
784
 * Extract exponents from MDCT coefficients, calculate exponent strategies,
785
 * and encode final exponents.
786
 */
787
static void process_exponents(AC3EncodeContext *s)
788
{
789
    extract_exponents(s);
790

    
791
    compute_exp_strategy(s);
792

    
793
    encode_exponents(s);
794

    
795
    group_exponents(s);
796

    
797
    emms_c();
798
}
799

    
800

    
801
/**
802
 * Count frame bits that are based solely on fixed parameters.
803
 * This only has to be run once when the encoder is initialized.
804
 */
805
static void count_frame_bits_fixed(AC3EncodeContext *s)
806
{
807
    static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
808
    int blk;
809
    int frame_bits;
810

    
811
    /* assumptions:
812
     *   no dynamic range codes
813
     *   no channel coupling
814
     *   bit allocation parameters do not change between blocks
815
     *   SNR offsets do not change between blocks
816
     *   no delta bit allocation
817
     *   no skipped data
818
     *   no auxilliary data
819
     */
820

    
821
    /* header */
822
    frame_bits = 65;
823
    frame_bits += frame_bits_inc[s->channel_mode];
824

    
825
    /* audio blocks */
826
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
827
        /* block switch flags */
828
        frame_bits += s->fbw_channels;
829

    
830
        /* dither flags */
831
        frame_bits += s->fbw_channels;
832

    
833
        /* dynamic range */
834
        frame_bits++;
835

    
836
        /* coupling strategy */
837
        frame_bits++;
838
        if (!blk)
839
            frame_bits++;
840

    
841
        /* exponent strategy */
842
        frame_bits += 2 * s->fbw_channels;
843
        if (s->lfe_on)
844
            frame_bits++;
845

    
846
        /* bit allocation params */
847
        frame_bits++;
848
        if (!blk)
849
            frame_bits += 2 + 2 + 2 + 2 + 3;
850

    
851
        /* snr offsets and fast gain codes */
852
        frame_bits++;
853
        if (!blk)
854
            frame_bits += 6 + s->channels * (4 + 3);
855

    
856
        /* delta bit allocation */
857
        frame_bits++;
858

    
859
        /* skipped data */
860
        frame_bits++;
861
    }
862

    
863
    /* auxiliary data */
864
    frame_bits++;
865

    
866
    /* CRC */
867
    frame_bits += 1 + 16;
868

    
869
    s->frame_bits_fixed = frame_bits;
870
}
871

    
872

    
873
/**
874
 * Initialize bit allocation.
875
 * Set default parameter codes and calculate parameter values.
876
 */
877
static void bit_alloc_init(AC3EncodeContext *s)
878
{
879
    int ch;
880

    
881
    /* init default parameters */
882
    s->slow_decay_code = 2;
883
    s->fast_decay_code = 1;
884
    s->slow_gain_code  = 1;
885
    s->db_per_bit_code = 3;
886
    s->floor_code      = 7;
887
    for (ch = 0; ch < s->channels; ch++)
888
        s->fast_gain_code[ch] = 4;
889

    
890
    /* initial snr offset */
891
    s->coarse_snr_offset = 40;
892

    
893
    /* compute real values */
894
    /* currently none of these values change during encoding, so we can just
895
       set them once at initialization */
896
    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
897
    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
898
    s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
899
    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
900
    s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
901

    
902
    count_frame_bits_fixed(s);
903
}
904

    
905

    
906
/**
907
 * Count the bits used to encode the frame, minus exponents and mantissas.
908
 * Bits based on fixed parameters have already been counted, so now we just
909
 * have to add the bits based on parameters that change during encoding.
910
 */
911
static void count_frame_bits(AC3EncodeContext *s)
912
{
913
    AC3EncOptions *opt = &s->options;
914
    int blk, ch;
915
    int frame_bits = 0;
916

    
917
    /* header */
918
    if (opt->audio_production_info)
919
        frame_bits += 7;
920
    if (s->bitstream_id == 6) {
921
        if (opt->extended_bsi_1)
922
            frame_bits += 14;
923
        if (opt->extended_bsi_2)
924
            frame_bits += 14;
925
    }
926

    
927
    /* audio blocks */
928
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
929
        /* stereo rematrixing */
930
        if (s->channel_mode == AC3_CHMODE_STEREO) {
931
            frame_bits++;
932
            if (s->blocks[blk].new_rematrixing_strategy)
933
                frame_bits += s->num_rematrixing_bands;
934
        }
935

    
936
        /* bandwidth codes & gain range */
937
        for (ch = 0; ch < s->fbw_channels; ch++) {
938
            if (s->exp_strategy[ch][blk] != EXP_REUSE)
939
                frame_bits += 6 + 2;
940
        }
941
    }
942

    
943
    s->frame_bits = s->frame_bits_fixed + frame_bits;
944
}
945

    
946

    
947
/**
948
 * Finalize the mantissa bit count by adding in the grouped mantissas.
949
 */
950
static int compute_mantissa_size_final(int mant_cnt[5])
951
{
952
    // bap=1 : 3 mantissas in 5 bits
953
    int bits = (mant_cnt[1] / 3) * 5;
954
    // bap=2 : 3 mantissas in 7 bits
955
    // bap=4 : 2 mantissas in 7 bits
956
    bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
957
    // bap=3 : each mantissa is 3 bits
958
    bits += mant_cnt[3] * 3;
959
    return bits;
960
}
961

    
962

    
963
/**
964
 * Calculate masking curve based on the final exponents.
965
 * Also calculate the power spectral densities to use in future calculations.
966
 */
967
static void bit_alloc_masking(AC3EncodeContext *s)
968
{
969
    int blk, ch;
970

    
971
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
972
        AC3Block *block = &s->blocks[blk];
973
        for (ch = 0; ch < s->channels; ch++) {
974
            /* We only need psd and mask for calculating bap.
975
               Since we currently do not calculate bap when exponent
976
               strategy is EXP_REUSE we do not need to calculate psd or mask. */
977
            if (s->exp_strategy[ch][blk] != EXP_REUSE) {
978
                ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
979
                                          s->nb_coefs[ch],
980
                                          block->psd[ch], block->band_psd[ch]);
981
                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
982
                                           0, s->nb_coefs[ch],
983
                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
984
                                           ch == s->lfe_channel,
985
                                           DBA_NONE, 0, NULL, NULL, NULL,
986
                                           block->mask[ch]);
987
            }
988
        }
989
    }
990
}
991

    
992

    
993
/**
994
 * Ensure that bap for each block and channel point to the current bap_buffer.
995
 * They may have been switched during the bit allocation search.
996
 */
997
static void reset_block_bap(AC3EncodeContext *s)
998
{
999
    int blk, ch;
1000
    if (s->blocks[0].bap[0] == s->bap_buffer)
1001
        return;
1002
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1003
        for (ch = 0; ch < s->channels; ch++) {
1004
            s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
1005
        }
1006
    }
1007
}
1008

    
1009

    
1010
/**
1011
 * Run the bit allocation with a given SNR offset.
1012
 * This calculates the bit allocation pointers that will be used to determine
1013
 * the quantization of each mantissa.
1014
 * @return the number of bits needed for mantissas if the given SNR offset is
1015
 *         is used.
1016
 */
1017
static int bit_alloc(AC3EncodeContext *s, int snr_offset)
1018
{
1019
    int blk, ch;
1020
    int mantissa_bits;
1021
    int mant_cnt[5];
1022

    
1023
    snr_offset = (snr_offset - 240) << 2;
1024

    
1025
    reset_block_bap(s);
1026
    mantissa_bits = 0;
1027
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1028
        AC3Block *block = &s->blocks[blk];
1029
        AC3Block *ref_block;
1030
        // initialize grouped mantissa counts. these are set so that they are
1031
        // padded to the next whole group size when bits are counted in
1032
        // compute_mantissa_size_final
1033
        mant_cnt[0] = mant_cnt[3] = 0;
1034
        mant_cnt[1] = mant_cnt[2] = 2;
1035
        mant_cnt[4] = 1;
1036
        for (ch = 0; ch < s->channels; ch++) {
1037
            /* Currently the only bit allocation parameters which vary across
1038
               blocks within a frame are the exponent values.  We can take
1039
               advantage of that by reusing the bit allocation pointers
1040
               whenever we reuse exponents. */
1041
            ref_block = block->exp_ref_block[ch];
1042
            if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1043
                s->ac3dsp.bit_alloc_calc_bap(ref_block->mask[ch],
1044
                                             ref_block->psd[ch], 0,
1045
                                             s->nb_coefs[ch], snr_offset,
1046
                                             s->bit_alloc.floor, ff_ac3_bap_tab,
1047
                                             ref_block->bap[ch]);
1048
            }
1049
            mantissa_bits += s->ac3dsp.compute_mantissa_size(mant_cnt,
1050
                                                             ref_block->bap[ch],
1051
                                                             s->nb_coefs[ch]);
1052
        }
1053
        mantissa_bits += compute_mantissa_size_final(mant_cnt);
1054
    }
1055
    return mantissa_bits;
1056
}
1057

    
1058

    
1059
/**
1060
 * Constant bitrate bit allocation search.
1061
 * Find the largest SNR offset that will allow data to fit in the frame.
1062
 */
1063
static int cbr_bit_allocation(AC3EncodeContext *s)
1064
{
1065
    int ch;
1066
    int bits_left;
1067
    int snr_offset, snr_incr;
1068

    
1069
    bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1070
    if (bits_left < 0)
1071
        return AVERROR(EINVAL);
1072

    
1073
    snr_offset = s->coarse_snr_offset << 4;
1074

    
1075
    /* if previous frame SNR offset was 1023, check if current frame can also
1076
       use SNR offset of 1023. if so, skip the search. */
1077
    if ((snr_offset | s->fine_snr_offset[0]) == 1023) {
1078
        if (bit_alloc(s, 1023) <= bits_left)
1079
            return 0;
1080
    }
1081

    
1082
    while (snr_offset >= 0 &&
1083
           bit_alloc(s, snr_offset) > bits_left) {
1084
        snr_offset -= 64;
1085
    }
1086
    if (snr_offset < 0)
1087
        return AVERROR(EINVAL);
1088

    
1089
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1090
    for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1091
        while (snr_offset + snr_incr <= 1023 &&
1092
               bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1093
            snr_offset += snr_incr;
1094
            FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1095
        }
1096
    }
1097
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1098
    reset_block_bap(s);
1099

    
1100
    s->coarse_snr_offset = snr_offset >> 4;
1101
    for (ch = 0; ch < s->channels; ch++)
1102
        s->fine_snr_offset[ch] = snr_offset & 0xF;
1103

    
1104
    return 0;
1105
}
1106

    
1107

    
1108
/**
1109
 * Downgrade exponent strategies to reduce the bits used by the exponents.
1110
 * This is a fallback for when bit allocation fails with the normal exponent
1111
 * strategies.  Each time this function is run it only downgrades the
1112
 * strategy in 1 channel of 1 block.
1113
 * @return non-zero if downgrade was unsuccessful
1114
 */
1115
static int downgrade_exponents(AC3EncodeContext *s)
1116
{
1117
    int ch, blk;
1118

    
1119
    for (ch = 0; ch < s->fbw_channels; ch++) {
1120
        for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1121
            if (s->exp_strategy[ch][blk] == EXP_D15) {
1122
                s->exp_strategy[ch][blk] = EXP_D25;
1123
                return 0;
1124
            }
1125
        }
1126
    }
1127
    for (ch = 0; ch < s->fbw_channels; ch++) {
1128
        for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1129
            if (s->exp_strategy[ch][blk] == EXP_D25) {
1130
                s->exp_strategy[ch][blk] = EXP_D45;
1131
                return 0;
1132
            }
1133
        }
1134
    }
1135
    for (ch = 0; ch < s->fbw_channels; ch++) {
1136
        /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
1137
           the block number > 0 */
1138
        for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
1139
            if (s->exp_strategy[ch][blk] > EXP_REUSE) {
1140
                s->exp_strategy[ch][blk] = EXP_REUSE;
1141
                return 0;
1142
            }
1143
        }
1144
    }
1145
    return -1;
1146
}
1147

    
1148

    
1149
/**
1150
 * Perform bit allocation search.
1151
 * Finds the SNR offset value that maximizes quality and fits in the specified
1152
 * frame size.  Output is the SNR offset and a set of bit allocation pointers
1153
 * used to quantize the mantissas.
1154
 */
1155
static int compute_bit_allocation(AC3EncodeContext *s)
1156
{
1157
    int ret;
1158

    
1159
    count_frame_bits(s);
1160

    
1161
    bit_alloc_masking(s);
1162

    
1163
    ret = cbr_bit_allocation(s);
1164
    while (ret) {
1165
        /* fallback 1: downgrade exponents */
1166
        if (!downgrade_exponents(s)) {
1167
            extract_exponents(s);
1168
            encode_exponents(s);
1169
            group_exponents(s);
1170
            ret = compute_bit_allocation(s);
1171
            continue;
1172
        }
1173

    
1174
        /* fallbacks were not enough... */
1175
        break;
1176
    }
1177

    
1178
    return ret;
1179
}
1180

    
1181

    
1182
/**
1183
 * Symmetric quantization on 'levels' levels.
1184
 */
1185
static inline int sym_quant(int c, int e, int levels)
1186
{
1187
    int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1188
    av_assert2(v >= 0 && v < levels);
1189
    return v;
1190
}
1191

    
1192

    
1193
/**
1194
 * Asymmetric quantization on 2^qbits levels.
1195
 */
1196
static inline int asym_quant(int c, int e, int qbits)
1197
{
1198
    int lshift, m, v;
1199

    
1200
    lshift = e + qbits - 24;
1201
    if (lshift >= 0)
1202
        v = c << lshift;
1203
    else
1204
        v = c >> (-lshift);
1205
    /* rounding */
1206
    v = (v + 1) >> 1;
1207
    m = (1 << (qbits-1));
1208
    if (v >= m)
1209
        v = m - 1;
1210
    av_assert2(v >= -m);
1211
    return v & ((1 << qbits)-1);
1212
}
1213

    
1214

    
1215
/**
1216
 * Quantize a set of mantissas for a single channel in a single block.
1217
 */
1218
static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1219
                                      uint8_t *exp,
1220
                                      uint8_t *bap, uint16_t *qmant, int n)
1221
{
1222
    int i;
1223

    
1224
    for (i = 0; i < n; i++) {
1225
        int v;
1226
        int c = fixed_coef[i];
1227
        int e = exp[i];
1228
        int b = bap[i];
1229
        switch (b) {
1230
        case 0:
1231
            v = 0;
1232
            break;
1233
        case 1:
1234
            v = sym_quant(c, e, 3);
1235
            switch (s->mant1_cnt) {
1236
            case 0:
1237
                s->qmant1_ptr = &qmant[i];
1238
                v = 9 * v;
1239
                s->mant1_cnt = 1;
1240
                break;
1241
            case 1:
1242
                *s->qmant1_ptr += 3 * v;
1243
                s->mant1_cnt = 2;
1244
                v = 128;
1245
                break;
1246
            default:
1247
                *s->qmant1_ptr += v;
1248
                s->mant1_cnt = 0;
1249
                v = 128;
1250
                break;
1251
            }
1252
            break;
1253
        case 2:
1254
            v = sym_quant(c, e, 5);
1255
            switch (s->mant2_cnt) {
1256
            case 0:
1257
                s->qmant2_ptr = &qmant[i];
1258
                v = 25 * v;
1259
                s->mant2_cnt = 1;
1260
                break;
1261
            case 1:
1262
                *s->qmant2_ptr += 5 * v;
1263
                s->mant2_cnt = 2;
1264
                v = 128;
1265
                break;
1266
            default:
1267
                *s->qmant2_ptr += v;
1268
                s->mant2_cnt = 0;
1269
                v = 128;
1270
                break;
1271
            }
1272
            break;
1273
        case 3:
1274
            v = sym_quant(c, e, 7);
1275
            break;
1276
        case 4:
1277
            v = sym_quant(c, e, 11);
1278
            switch (s->mant4_cnt) {
1279
            case 0:
1280
                s->qmant4_ptr = &qmant[i];
1281
                v = 11 * v;
1282
                s->mant4_cnt = 1;
1283
                break;
1284
            default:
1285
                *s->qmant4_ptr += v;
1286
                s->mant4_cnt = 0;
1287
                v = 128;
1288
                break;
1289
            }
1290
            break;
1291
        case 5:
1292
            v = sym_quant(c, e, 15);
1293
            break;
1294
        case 14:
1295
            v = asym_quant(c, e, 14);
1296
            break;
1297
        case 15:
1298
            v = asym_quant(c, e, 16);
1299
            break;
1300
        default:
1301
            v = asym_quant(c, e, b - 1);
1302
            break;
1303
        }
1304
        qmant[i] = v;
1305
    }
1306
}
1307

    
1308

    
1309
/**
1310
 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1311
 */
1312
static void quantize_mantissas(AC3EncodeContext *s)
1313
{
1314
    int blk, ch;
1315

    
1316

    
1317
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1318
        AC3Block *block = &s->blocks[blk];
1319
        AC3Block *ref_block;
1320
        AC3Mant m = { 0 };
1321

    
1322
        for (ch = 0; ch < s->channels; ch++) {
1323
            ref_block = block->exp_ref_block[ch];
1324
            quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1325
                                      ref_block->exp[ch], ref_block->bap[ch],
1326
                                      block->qmant[ch], s->nb_coefs[ch]);
1327
        }
1328
    }
1329
}
1330

    
1331

    
1332
/**
1333
 * Write the AC-3 frame header to the output bitstream.
1334
 */
1335
static void output_frame_header(AC3EncodeContext *s)
1336
{
1337
    AC3EncOptions *opt = &s->options;
1338

    
1339
    put_bits(&s->pb, 16, 0x0b77);   /* frame header */
1340
    put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
1341
    put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
1342
    put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1343
    put_bits(&s->pb, 5,  s->bitstream_id);
1344
    put_bits(&s->pb, 3,  s->bitstream_mode);
1345
    put_bits(&s->pb, 3,  s->channel_mode);
1346
    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1347
        put_bits(&s->pb, 2, s->center_mix_level);
1348
    if (s->channel_mode & 0x04)
1349
        put_bits(&s->pb, 2, s->surround_mix_level);
1350
    if (s->channel_mode == AC3_CHMODE_STEREO)
1351
        put_bits(&s->pb, 2, opt->dolby_surround_mode);
1352
    put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1353
    put_bits(&s->pb, 5, -opt->dialogue_level);
1354
    put_bits(&s->pb, 1, 0);         /* no compression control word */
1355
    put_bits(&s->pb, 1, 0);         /* no lang code */
1356
    put_bits(&s->pb, 1, opt->audio_production_info);
1357
    if (opt->audio_production_info) {
1358
        put_bits(&s->pb, 5, opt->mixing_level - 80);
1359
        put_bits(&s->pb, 2, opt->room_type);
1360
    }
1361
    put_bits(&s->pb, 1, opt->copyright);
1362
    put_bits(&s->pb, 1, opt->original);
1363
    if (s->bitstream_id == 6) {
1364
        /* alternate bit stream syntax */
1365
        put_bits(&s->pb, 1, opt->extended_bsi_1);
1366
        if (opt->extended_bsi_1) {
1367
            put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1368
            put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1369
            put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1370
            put_bits(&s->pb, 3, s->loro_center_mix_level);
1371
            put_bits(&s->pb, 3, s->loro_surround_mix_level);
1372
        }
1373
        put_bits(&s->pb, 1, opt->extended_bsi_2);
1374
        if (opt->extended_bsi_2) {
1375
            put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1376
            put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1377
            put_bits(&s->pb, 1, opt->ad_converter_type);
1378
            put_bits(&s->pb, 9, 0);     /* xbsi2 and encinfo : reserved */
1379
        }
1380
    } else {
1381
    put_bits(&s->pb, 1, 0);         /* no time code 1 */
1382
    put_bits(&s->pb, 1, 0);         /* no time code 2 */
1383
    }
1384
    put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
1385
}
1386

    
1387

    
1388
/**
1389
 * Write one audio block to the output bitstream.
1390
 */
1391
static void output_audio_block(AC3EncodeContext *s, int blk)
1392
{
1393
    int ch, i, baie, rbnd;
1394
    AC3Block *block = &s->blocks[blk];
1395

    
1396
    /* block switching */
1397
    for (ch = 0; ch < s->fbw_channels; ch++)
1398
        put_bits(&s->pb, 1, 0);
1399

    
1400
    /* dither flags */
1401
    for (ch = 0; ch < s->fbw_channels; ch++)
1402
        put_bits(&s->pb, 1, 1);
1403

    
1404
    /* dynamic range codes */
1405
    put_bits(&s->pb, 1, 0);
1406

    
1407
    /* channel coupling */
1408
    if (!blk) {
1409
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
1410
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
1411
    } else {
1412
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1413
    }
1414

    
1415
    /* stereo rematrixing */
1416
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1417
        put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1418
        if (block->new_rematrixing_strategy) {
1419
            /* rematrixing flags */
1420
            for (rbnd = 0; rbnd < s->num_rematrixing_bands; rbnd++)
1421
                put_bits(&s->pb, 1, block->rematrixing_flags[rbnd]);
1422
        }
1423
    }
1424

    
1425
    /* exponent strategy */
1426
    for (ch = 0; ch < s->fbw_channels; ch++)
1427
        put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1428
    if (s->lfe_on)
1429
        put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1430

    
1431
    /* bandwidth */
1432
    for (ch = 0; ch < s->fbw_channels; ch++) {
1433
        if (s->exp_strategy[ch][blk] != EXP_REUSE)
1434
            put_bits(&s->pb, 6, s->bandwidth_code);
1435
    }
1436

    
1437
    /* exponents */
1438
    for (ch = 0; ch < s->channels; ch++) {
1439
        int nb_groups;
1440

    
1441
        if (s->exp_strategy[ch][blk] == EXP_REUSE)
1442
            continue;
1443

    
1444
        /* DC exponent */
1445
        put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1446

    
1447
        /* exponent groups */
1448
        nb_groups = exponent_group_tab[s->exp_strategy[ch][blk]-1][s->nb_coefs[ch]];
1449
        for (i = 1; i <= nb_groups; i++)
1450
            put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1451

    
1452
        /* gain range info */
1453
        if (ch != s->lfe_channel)
1454
            put_bits(&s->pb, 2, 0);
1455
    }
1456

    
1457
    /* bit allocation info */
1458
    baie = (blk == 0);
1459
    put_bits(&s->pb, 1, baie);
1460
    if (baie) {
1461
        put_bits(&s->pb, 2, s->slow_decay_code);
1462
        put_bits(&s->pb, 2, s->fast_decay_code);
1463
        put_bits(&s->pb, 2, s->slow_gain_code);
1464
        put_bits(&s->pb, 2, s->db_per_bit_code);
1465
        put_bits(&s->pb, 3, s->floor_code);
1466
    }
1467

    
1468
    /* snr offset */
1469
    put_bits(&s->pb, 1, baie);
1470
    if (baie) {
1471
        put_bits(&s->pb, 6, s->coarse_snr_offset);
1472
        for (ch = 0; ch < s->channels; ch++) {
1473
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1474
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1475
        }
1476
    }
1477

    
1478
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1479
    put_bits(&s->pb, 1, 0); /* no data to skip */
1480

    
1481
    /* mantissas */
1482
    for (ch = 0; ch < s->channels; ch++) {
1483
        int b, q;
1484
        AC3Block *ref_block = block->exp_ref_block[ch];
1485
        for (i = 0; i < s->nb_coefs[ch]; i++) {
1486
            q = block->qmant[ch][i];
1487
            b = ref_block->bap[ch][i];
1488
            switch (b) {
1489
            case 0:                                         break;
1490
            case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
1491
            case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
1492
            case 3:               put_bits(&s->pb,   3, q); break;
1493
            case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
1494
            case 14:              put_bits(&s->pb,  14, q); break;
1495
            case 15:              put_bits(&s->pb,  16, q); break;
1496
            default:              put_bits(&s->pb, b-1, q); break;
1497
            }
1498
        }
1499
    }
1500
}
1501

    
1502

    
1503
/** CRC-16 Polynomial */
1504
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1505

    
1506

    
1507
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1508
{
1509
    unsigned int c;
1510

    
1511
    c = 0;
1512
    while (a) {
1513
        if (a & 1)
1514
            c ^= b;
1515
        a = a >> 1;
1516
        b = b << 1;
1517
        if (b & (1 << 16))
1518
            b ^= poly;
1519
    }
1520
    return c;
1521
}
1522

    
1523

    
1524
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1525
{
1526
    unsigned int r;
1527
    r = 1;
1528
    while (n) {
1529
        if (n & 1)
1530
            r = mul_poly(r, a, poly);
1531
        a = mul_poly(a, a, poly);
1532
        n >>= 1;
1533
    }
1534
    return r;
1535
}
1536

    
1537

    
1538
/**
1539
 * Fill the end of the frame with 0's and compute the two CRCs.
1540
 */
1541
static void output_frame_end(AC3EncodeContext *s)
1542
{
1543
    const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1544
    int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1545
    uint8_t *frame;
1546

    
1547
    frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1548

    
1549
    /* pad the remainder of the frame with zeros */
1550
    av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1551
    flush_put_bits(&s->pb);
1552
    frame = s->pb.buf;
1553
    pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1554
    av_assert2(pad_bytes >= 0);
1555
    if (pad_bytes > 0)
1556
        memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1557

    
1558
    /* compute crc1 */
1559
    /* this is not so easy because it is at the beginning of the data... */
1560
    crc1    = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1561
    crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1562
    crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1563
    AV_WB16(frame + 2, crc1);
1564

    
1565
    /* compute crc2 */
1566
    crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1567
                          s->frame_size - frame_size_58 - 3);
1568
    crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1569
    /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1570
    if (crc2 == 0x770B) {
1571
        frame[s->frame_size - 3] ^= 0x1;
1572
        crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1573
    }
1574
    crc2 = av_bswap16(crc2);
1575
    AV_WB16(frame + s->frame_size - 2, crc2);
1576
}
1577

    
1578

    
1579
/**
1580
 * Write the frame to the output bitstream.
1581
 */
1582
static void output_frame(AC3EncodeContext *s, unsigned char *frame)
1583
{
1584
    int blk;
1585

    
1586
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1587

    
1588
    output_frame_header(s);
1589

    
1590
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1591
        output_audio_block(s, blk);
1592

    
1593
    output_frame_end(s);
1594
}
1595

    
1596

    
1597
static void dprint_options(AVCodecContext *avctx)
1598
{
1599
#ifdef DEBUG
1600
    AC3EncodeContext *s = avctx->priv_data;
1601
    AC3EncOptions *opt = &s->options;
1602
    char strbuf[32];
1603

    
1604
    switch (s->bitstream_id) {
1605
    case  6:  av_strlcpy(strbuf, "AC-3 (alt syntax)", 32);      break;
1606
    case  8:  av_strlcpy(strbuf, "AC-3 (standard)", 32);        break;
1607
    case  9:  av_strlcpy(strbuf, "AC-3 (dnet half-rate)", 32);  break;
1608
    case 10:  av_strlcpy(strbuf, "AC-3 (dnet quater-rate", 32); break;
1609
    default: snprintf(strbuf, 32, "ERROR");
1610
    }
1611
    av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
1612
    av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
1613
    av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
1614
    av_dlog(avctx, "channel_layout: %s\n", strbuf);
1615
    av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
1616
    av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
1617
    if (s->cutoff)
1618
        av_dlog(avctx, "cutoff: %d\n", s->cutoff);
1619

    
1620
    av_dlog(avctx, "per_frame_metadata: %s\n",
1621
            opt->allow_per_frame_metadata?"on":"off");
1622
    if (s->has_center)
1623
        av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
1624
                s->center_mix_level);
1625
    else
1626
        av_dlog(avctx, "center_mixlev: {not written}\n");
1627
    if (s->has_surround)
1628
        av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
1629
                s->surround_mix_level);
1630
    else
1631
        av_dlog(avctx, "surround_mixlev: {not written}\n");
1632
    if (opt->audio_production_info) {
1633
        av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
1634
        switch (opt->room_type) {
1635
        case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
1636
        case 1:  av_strlcpy(strbuf, "large", 32);        break;
1637
        case 2:  av_strlcpy(strbuf, "small", 32);        break;
1638
        default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
1639
        }
1640
        av_dlog(avctx, "room_type: %s\n", strbuf);
1641
    } else {
1642
        av_dlog(avctx, "mixing_level: {not written}\n");
1643
        av_dlog(avctx, "room_type: {not written}\n");
1644
    }
1645
    av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
1646
    av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
1647
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1648
        switch (opt->dolby_surround_mode) {
1649
        case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
1650
        case 1:  av_strlcpy(strbuf, "on", 32);           break;
1651
        case 2:  av_strlcpy(strbuf, "off", 32);          break;
1652
        default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
1653
        }
1654
        av_dlog(avctx, "dsur_mode: %s\n", strbuf);
1655
    } else {
1656
        av_dlog(avctx, "dsur_mode: {not written}\n");
1657
    }
1658
    av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
1659

    
1660
    if (s->bitstream_id == 6) {
1661
        if (opt->extended_bsi_1) {
1662
            switch (opt->preferred_stereo_downmix) {
1663
            case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
1664
            case 1:  av_strlcpy(strbuf, "ltrt", 32);         break;
1665
            case 2:  av_strlcpy(strbuf, "loro", 32);         break;
1666
            default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
1667
            }
1668
            av_dlog(avctx, "dmix_mode: %s\n", strbuf);
1669
            av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
1670
                    opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
1671
            av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
1672
                    opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
1673
            av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
1674
                    opt->loro_center_mix_level, s->loro_center_mix_level);
1675
            av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
1676
                    opt->loro_surround_mix_level, s->loro_surround_mix_level);
1677
        } else {
1678
            av_dlog(avctx, "extended bitstream info 1: {not written}\n");
1679
        }
1680
        if (opt->extended_bsi_2) {
1681
            switch (opt->dolby_surround_ex_mode) {
1682
            case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
1683
            case 1:  av_strlcpy(strbuf, "on", 32);           break;
1684
            case 2:  av_strlcpy(strbuf, "off", 32);          break;
1685
            default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
1686
            }
1687
            av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
1688
            switch (opt->dolby_headphone_mode) {
1689
            case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
1690
            case 1:  av_strlcpy(strbuf, "on", 32);           break;
1691
            case 2:  av_strlcpy(strbuf, "off", 32);          break;
1692
            default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
1693
            }
1694
            av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
1695

    
1696
            switch (opt->ad_converter_type) {
1697
            case 0:  av_strlcpy(strbuf, "standard", 32); break;
1698
            case 1:  av_strlcpy(strbuf, "hdcd", 32);     break;
1699
            default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
1700
            }
1701
            av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
1702
        } else {
1703
            av_dlog(avctx, "extended bitstream info 2: {not written}\n");
1704
        }
1705
    }
1706
#endif
1707
}
1708

    
1709

    
1710
#define FLT_OPTION_THRESHOLD 0.01
1711

    
1712
static int validate_float_option(float v, const float *v_list, int v_list_size)
1713
{
1714
    int i;
1715

    
1716
    for (i = 0; i < v_list_size; i++) {
1717
        if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
1718
            v > (v_list[i] - FLT_OPTION_THRESHOLD))
1719
            break;
1720
    }
1721
    if (i == v_list_size)
1722
        return -1;
1723

    
1724
    return i;
1725
}
1726

    
1727

    
1728
static void validate_mix_level(void *log_ctx, const char *opt_name,
1729
                               float *opt_param, const float *list,
1730
                               int list_size, int default_value, int min_value,
1731
                               int *ctx_param)
1732
{
1733
    int mixlev = validate_float_option(*opt_param, list, list_size);
1734
    if (mixlev < min_value) {
1735
        mixlev = default_value;
1736
        if (*opt_param >= 0.0) {
1737
            av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
1738
                   "default value: %0.3f\n", opt_name, list[mixlev]);
1739
        }
1740
    }
1741
    *opt_param = list[mixlev];
1742
    *ctx_param = mixlev;
1743
}
1744

    
1745

    
1746
/**
1747
 * Validate metadata options as set by AVOption system.
1748
 * These values can optionally be changed per-frame.
1749
 */
1750
static int validate_metadata(AVCodecContext *avctx)
1751
{
1752
    AC3EncodeContext *s = avctx->priv_data;
1753
    AC3EncOptions *opt = &s->options;
1754

    
1755
    /* validate mixing levels */
1756
    if (s->has_center) {
1757
        validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
1758
                           cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
1759
                           &s->center_mix_level);
1760
    }
1761
    if (s->has_surround) {
1762
        validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
1763
                           surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
1764
                           &s->surround_mix_level);
1765
    }
1766

    
1767
    /* set audio production info flag */
1768
    if (opt->mixing_level >= 0 || opt->room_type >= 0) {
1769
        if (opt->mixing_level < 0) {
1770
            av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
1771
                   "room_type is set\n");
1772
            return AVERROR(EINVAL);
1773
        }
1774
        if (opt->mixing_level < 80) {
1775
            av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
1776
                   "80dB and 111dB\n");
1777
            return AVERROR(EINVAL);
1778
        }
1779
        /* default room type */
1780
        if (opt->room_type < 0)
1781
            opt->room_type = 0;
1782
        opt->audio_production_info = 1;
1783
    } else {
1784
        opt->audio_production_info = 0;
1785
    }
1786

    
1787
    /* set extended bsi 1 flag */
1788
    if ((s->has_center || s->has_surround) &&
1789
        (opt->preferred_stereo_downmix >= 0 ||
1790
         opt->ltrt_center_mix_level   >= 0 ||
1791
         opt->ltrt_surround_mix_level >= 0 ||
1792
         opt->loro_center_mix_level   >= 0 ||
1793
         opt->loro_surround_mix_level >= 0)) {
1794
        /* default preferred stereo downmix */
1795
        if (opt->preferred_stereo_downmix < 0)
1796
            opt->preferred_stereo_downmix = 0;
1797
        /* validate Lt/Rt center mix level */
1798
        validate_mix_level(avctx, "ltrt_center_mix_level",
1799
                           &opt->ltrt_center_mix_level, extmixlev_options,
1800
                           EXTMIXLEV_NUM_OPTIONS, 5, 0,
1801
                           &s->ltrt_center_mix_level);
1802
        /* validate Lt/Rt surround mix level */
1803
        validate_mix_level(avctx, "ltrt_surround_mix_level",
1804
                           &opt->ltrt_surround_mix_level, extmixlev_options,
1805
                           EXTMIXLEV_NUM_OPTIONS, 6, 3,
1806
                           &s->ltrt_surround_mix_level);
1807
        /* validate Lo/Ro center mix level */
1808
        validate_mix_level(avctx, "loro_center_mix_level",
1809
                           &opt->loro_center_mix_level, extmixlev_options,
1810
                           EXTMIXLEV_NUM_OPTIONS, 5, 0,
1811
                           &s->loro_center_mix_level);
1812
        /* validate Lo/Ro surround mix level */
1813
        validate_mix_level(avctx, "loro_surround_mix_level",
1814
                           &opt->loro_surround_mix_level, extmixlev_options,
1815
                           EXTMIXLEV_NUM_OPTIONS, 6, 3,
1816
                           &s->loro_surround_mix_level);
1817
        opt->extended_bsi_1 = 1;
1818
    } else {
1819
        opt->extended_bsi_1 = 0;
1820
    }
1821

    
1822
    /* set extended bsi 2 flag */
1823
    if (opt->dolby_surround_ex_mode >= 0 ||
1824
        opt->dolby_headphone_mode   >= 0 ||
1825
        opt->ad_converter_type      >= 0) {
1826
        /* default dolby surround ex mode */
1827
        if (opt->dolby_surround_ex_mode < 0)
1828
            opt->dolby_surround_ex_mode = 0;
1829
        /* default dolby headphone mode */
1830
        if (opt->dolby_headphone_mode < 0)
1831
            opt->dolby_headphone_mode = 0;
1832
        /* default A/D converter type */
1833
        if (opt->ad_converter_type < 0)
1834
            opt->ad_converter_type = 0;
1835
        opt->extended_bsi_2 = 1;
1836
    } else {
1837
        opt->extended_bsi_2 = 0;
1838
    }
1839

    
1840
    /* set bitstream id for alternate bitstream syntax */
1841
    if (opt->extended_bsi_1 || opt->extended_bsi_2) {
1842
        if (s->bitstream_id > 8 && s->bitstream_id < 11) {
1843
            static int warn_once = 1;
1844
            if (warn_once) {
1845
                av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
1846
                       "not compatible with reduced samplerates. writing of "
1847
                       "extended bitstream information will be disabled.\n");
1848
                warn_once = 0;
1849
            }
1850
        } else {
1851
            s->bitstream_id = 6;
1852
        }
1853
    }
1854

    
1855
    return 0;
1856
}
1857

    
1858

    
1859
/**
1860
 * Encode a single AC-3 frame.
1861
 */
1862
static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
1863
                            int buf_size, void *data)
1864
{
1865
    AC3EncodeContext *s = avctx->priv_data;
1866
    const SampleType *samples = data;
1867
    int ret;
1868

    
1869
    if (s->options.allow_per_frame_metadata) {
1870
        ret = validate_metadata(avctx);
1871
        if (ret)
1872
            return ret;
1873
    }
1874

    
1875
    if (s->bit_alloc.sr_code == 1)
1876
        adjust_frame_size(s);
1877

    
1878
    deinterleave_input_samples(s, samples);
1879

    
1880
    apply_mdct(s);
1881

    
1882
    scale_coefficients(s);
1883

    
1884
    compute_rematrixing_strategy(s);
1885

    
1886
    apply_rematrixing(s);
1887

    
1888
    process_exponents(s);
1889

    
1890
    ret = compute_bit_allocation(s);
1891
    if (ret) {
1892
        av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1893
        return ret;
1894
    }
1895

    
1896
    quantize_mantissas(s);
1897

    
1898
    output_frame(s, frame);
1899

    
1900
    return s->frame_size;
1901
}
1902

    
1903

    
1904
/**
1905
 * Finalize encoding and free any memory allocated by the encoder.
1906
 */
1907
static av_cold int ac3_encode_close(AVCodecContext *avctx)
1908
{
1909
    int blk, ch;
1910
    AC3EncodeContext *s = avctx->priv_data;
1911

    
1912
    for (ch = 0; ch < s->channels; ch++)
1913
        av_freep(&s->planar_samples[ch]);
1914
    av_freep(&s->planar_samples);
1915
    av_freep(&s->bap_buffer);
1916
    av_freep(&s->bap1_buffer);
1917
    av_freep(&s->mdct_coef_buffer);
1918
    av_freep(&s->fixed_coef_buffer);
1919
    av_freep(&s->exp_buffer);
1920
    av_freep(&s->grouped_exp_buffer);
1921
    av_freep(&s->psd_buffer);
1922
    av_freep(&s->band_psd_buffer);
1923
    av_freep(&s->mask_buffer);
1924
    av_freep(&s->qmant_buffer);
1925
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1926
        AC3Block *block = &s->blocks[blk];
1927
        av_freep(&block->bap);
1928
        av_freep(&block->mdct_coef);
1929
        av_freep(&block->fixed_coef);
1930
        av_freep(&block->exp);
1931
        av_freep(&block->grouped_exp);
1932
        av_freep(&block->psd);
1933
        av_freep(&block->band_psd);
1934
        av_freep(&block->mask);
1935
        av_freep(&block->qmant);
1936
    }
1937

    
1938
    mdct_end(&s->mdct);
1939

    
1940
    av_freep(&avctx->coded_frame);
1941
    return 0;
1942
}
1943

    
1944

    
1945
/**
1946
 * Set channel information during initialization.
1947
 */
1948
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1949
                                    int64_t *channel_layout)
1950
{
1951
    int ch_layout;
1952

    
1953
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
1954
        return AVERROR(EINVAL);
1955
    if ((uint64_t)*channel_layout > 0x7FF)
1956
        return AVERROR(EINVAL);
1957
    ch_layout = *channel_layout;
1958
    if (!ch_layout)
1959
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1960

    
1961
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1962
    s->channels     = channels;
1963
    s->fbw_channels = channels - s->lfe_on;
1964
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
1965
    if (s->lfe_on)
1966
        ch_layout -= AV_CH_LOW_FREQUENCY;
1967

    
1968
    switch (ch_layout) {
1969
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
1970
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
1971
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
1972
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
1973
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
1974
    case AV_CH_LAYOUT_QUAD:
1975
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
1976
    case AV_CH_LAYOUT_5POINT0:
1977
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
1978
    default:
1979
        return AVERROR(EINVAL);
1980
    }
1981
    s->has_center   = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
1982
    s->has_surround =  s->channel_mode & 0x04;
1983

    
1984
    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1985
    *channel_layout = ch_layout;
1986
    if (s->lfe_on)
1987
        *channel_layout |= AV_CH_LOW_FREQUENCY;
1988

    
1989
    return 0;
1990
}
1991

    
1992

    
1993
static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1994
{
1995
    int i, ret;
1996

    
1997
    /* validate channel layout */
1998
    if (!avctx->channel_layout) {
1999
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
2000
                                      "encoder will guess the layout, but it "
2001
                                      "might be incorrect.\n");
2002
    }
2003
    ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
2004
    if (ret) {
2005
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
2006
        return ret;
2007
    }
2008

    
2009
    /* validate sample rate */
2010
    for (i = 0; i < 9; i++) {
2011
        if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
2012
            break;
2013
    }
2014
    if (i == 9) {
2015
        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
2016
        return AVERROR(EINVAL);
2017
    }
2018
    s->sample_rate        = avctx->sample_rate;
2019
    s->bit_alloc.sr_shift = i % 3;
2020
    s->bit_alloc.sr_code  = i / 3;
2021
    s->bitstream_id       = 8 + s->bit_alloc.sr_shift;
2022

    
2023
    /* validate bit rate */
2024
    for (i = 0; i < 19; i++) {
2025
        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
2026
            break;
2027
    }
2028
    if (i == 19) {
2029
        av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2030
        return AVERROR(EINVAL);
2031
    }
2032
    s->bit_rate        = avctx->bit_rate;
2033
    s->frame_size_code = i << 1;
2034

    
2035
    /* validate cutoff */
2036
    if (avctx->cutoff < 0) {
2037
        av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2038
        return AVERROR(EINVAL);
2039
    }
2040
    s->cutoff = avctx->cutoff;
2041
    if (s->cutoff > (s->sample_rate >> 1))
2042
        s->cutoff = s->sample_rate >> 1;
2043

    
2044
    /* validate audio service type / channels combination */
2045
    if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
2046
         avctx->channels == 1) ||
2047
        ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
2048
          avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY  ||
2049
          avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
2050
         && avctx->channels > 1)) {
2051
        av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
2052
                                    "specified number of channels\n");
2053
        return AVERROR(EINVAL);
2054
    }
2055

    
2056
    ret = validate_metadata(avctx);
2057
    if (ret)
2058
        return ret;
2059

    
2060
    s->rematrixing_enabled = s->options.stereo_rematrixing &&
2061
                             (s->channel_mode == AC3_CHMODE_STEREO);
2062

    
2063
    return 0;
2064
}
2065

    
2066

    
2067
/**
2068
 * Set bandwidth for all channels.
2069
 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2070
 * default value will be used.
2071
 */
2072
static av_cold void set_bandwidth(AC3EncodeContext *s)
2073
{
2074
    int ch;
2075

    
2076
    if (s->cutoff) {
2077
        /* calculate bandwidth based on user-specified cutoff frequency */
2078
        int fbw_coeffs;
2079
        fbw_coeffs     = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2080
        s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2081
    } else {
2082
        /* use default bandwidth setting */
2083
        s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2084
    }
2085

    
2086
    /* set number of coefficients for each channel */
2087
    for (ch = 0; ch < s->fbw_channels; ch++) {
2088
        s->nb_coefs[ch] = s->bandwidth_code * 3 + 73;
2089
    }
2090
    if (s->lfe_on)
2091
        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
2092
}
2093

    
2094

    
2095
static av_cold int allocate_buffers(AVCodecContext *avctx)
2096
{
2097
    int blk, ch;
2098
    AC3EncodeContext *s = avctx->priv_data;
2099

    
2100
    FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
2101
                     alloc_fail);
2102
    for (ch = 0; ch < s->channels; ch++) {
2103
        FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
2104
                          (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
2105
                          alloc_fail);
2106
    }
2107
    FF_ALLOC_OR_GOTO(avctx, s->bap_buffer,  AC3_MAX_BLOCKS * s->channels *
2108
                     AC3_MAX_COEFS * sizeof(*s->bap_buffer),  alloc_fail);
2109
    FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
2110
                     AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
2111
    FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
2112
                     AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
2113
    FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
2114
                     AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
2115
    FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
2116
                     128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
2117
    FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
2118
                     AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
2119
    FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
2120
                     64 * sizeof(*s->band_psd_buffer), alloc_fail);
2121
    FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
2122
                     64 * sizeof(*s->mask_buffer), alloc_fail);
2123
    FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
2124
                     AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
2125
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2126
        AC3Block *block = &s->blocks[blk];
2127
        FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
2128
                         alloc_fail);
2129
        FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
2130
                          alloc_fail);
2131
        FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
2132
                          alloc_fail);
2133
        FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
2134
                          alloc_fail);
2135
        FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
2136
                          alloc_fail);
2137
        FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
2138
                          alloc_fail);
2139
        FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
2140
                          alloc_fail);
2141
        FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
2142
                          alloc_fail);
2143

    
2144
        for (ch = 0; ch < s->channels; ch++) {
2145
            /* arrangement: block, channel, coeff */
2146
            block->bap[ch]         = &s->bap_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
2147
            block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (blk * s->channels + ch)];
2148
            block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * s->channels + ch)];
2149
            block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
2150
            block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * s->channels + ch)];
2151
            block->mask[ch]        = &s->mask_buffer       [64            * (blk * s->channels + ch)];
2152
            block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * s->channels + ch)];
2153

    
2154
            /* arrangement: channel, block, coeff */
2155
            block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2156
        }
2157
    }
2158

    
2159
    if (CONFIG_AC3ENC_FLOAT) {
2160
        FF_ALLOC_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * s->channels *
2161
                         AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
2162
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2163
            AC3Block *block = &s->blocks[blk];
2164
            FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2165
                              sizeof(*block->fixed_coef), alloc_fail);
2166
            for (ch = 0; ch < s->channels; ch++)
2167
                block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
2168
        }
2169
    } else {
2170
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2171
            AC3Block *block = &s->blocks[blk];
2172
            FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2173
                              sizeof(*block->fixed_coef), alloc_fail);
2174
            for (ch = 0; ch < s->channels; ch++)
2175
                block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2176
        }
2177
    }
2178

    
2179
    return 0;
2180
alloc_fail:
2181
    return AVERROR(ENOMEM);
2182
}
2183

    
2184

    
2185
/**
2186
 * Initialize the encoder.
2187
 */
2188
static av_cold int ac3_encode_init(AVCodecContext *avctx)
2189
{
2190
    AC3EncodeContext *s = avctx->priv_data;
2191
    int ret, frame_size_58;
2192

    
2193
    avctx->frame_size = AC3_FRAME_SIZE;
2194

    
2195
    ff_ac3_common_init();
2196

    
2197
    ret = validate_options(avctx, s);
2198
    if (ret)
2199
        return ret;
2200

    
2201
    s->bitstream_mode = avctx->audio_service_type;
2202
    if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2203
        s->bitstream_mode = 0x7;
2204

    
2205
    s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2206
    s->bits_written    = 0;
2207
    s->samples_written = 0;
2208
    s->frame_size      = s->frame_size_min;
2209

    
2210
    /* calculate crc_inv for both possible frame sizes */
2211
    frame_size_58 = (( s->frame_size    >> 2) + ( s->frame_size    >> 4)) << 1;
2212
    s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2213
    if (s->bit_alloc.sr_code == 1) {
2214
        frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2215
        s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2216
    }
2217

    
2218
    set_bandwidth(s);
2219

    
2220
    exponent_init(s);
2221

    
2222
    bit_alloc_init(s);
2223

    
2224
    ret = mdct_init(avctx, &s->mdct, 9);
2225
    if (ret)
2226
        goto init_fail;
2227

    
2228
    ret = allocate_buffers(avctx);
2229
    if (ret)
2230
        goto init_fail;
2231

    
2232
    avctx->coded_frame= avcodec_alloc_frame();
2233

    
2234
    dsputil_init(&s->dsp, avctx);
2235
    ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2236

    
2237
    dprint_options(avctx);
2238

    
2239
    return 0;
2240
init_fail:
2241
    ac3_encode_close(avctx);
2242
    return ret;
2243
}