Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ e0b33d47

History | View | Annotate | Download (77.6 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/crc.h"
37
#include "libavutil/opt.h"
38
#include "avcodec.h"
39
#include "put_bits.h"
40
#include "dsputil.h"
41
#include "ac3dsp.h"
42
#include "ac3.h"
43
#include "audioconvert.h"
44
#include "fft.h"
45

    
46

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

    
51

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
223

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

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

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

    
280

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

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

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

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

    
291
static int normalize_samples(AC3EncodeContext *s);
292

    
293
static void scale_coefficients(AC3EncodeContext *s);
294

    
295

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

    
302

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

    
328

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

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

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

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

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

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

    
358

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

    
375

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

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

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

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

    
404

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

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

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

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

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

    
429

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

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

    
442
    s->num_rematrixing_bands = 4;
443

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

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

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

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

    
483

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

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

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

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

    
518

    
519
/**
520
 * Initialize exponent tables.
521
 */
522
static av_cold void exponent_init(AC3EncodeContext *s)
523
{
524
    int i;
525
    for (i = 73; i < 256; i++) {
526
        exponent_group_tab[0][i] = (i - 1) /  3;
527
        exponent_group_tab[1][i] = (i + 2) /  6;
528
        exponent_group_tab[2][i] = (i + 8) / 12;
529
    }
530
    /* LFE */
531
    exponent_group_tab[0][7] = 2;
532
}
533

    
534

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

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

    
553

    
554
/**
555
 * Exponent Difference Threshold.
556
 * New exponents are sent if their SAD exceed this number.
557
 */
558
#define EXP_DIFF_THRESHOLD 500
559

    
560

    
561
/**
562
 * Calculate exponent strategies for all blocks in a single channel.
563
 */
564
static void compute_exp_strategy_ch(AC3EncodeContext *s, uint8_t *exp_strategy,
565
                                    uint8_t *exp)
566
{
567
    int blk, blk1;
568
    int exp_diff;
569

    
570
    /* estimate if the exponent variation & decide if they should be
571
       reused in the next frame */
572
    exp_strategy[0] = EXP_NEW;
573
    exp += AC3_MAX_COEFS;
574
    for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
575
        exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
576
        if (exp_diff > EXP_DIFF_THRESHOLD)
577
            exp_strategy[blk] = EXP_NEW;
578
        else
579
            exp_strategy[blk] = EXP_REUSE;
580
        exp += AC3_MAX_COEFS;
581
    }
582

    
583
    /* now select the encoding strategy type : if exponents are often
584
       recoded, we use a coarse encoding */
585
    blk = 0;
586
    while (blk < AC3_MAX_BLOCKS) {
587
        blk1 = blk + 1;
588
        while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
589
            blk1++;
590
        switch (blk1 - blk) {
591
        case 1:  exp_strategy[blk] = EXP_D45; break;
592
        case 2:
593
        case 3:  exp_strategy[blk] = EXP_D25; break;
594
        default: exp_strategy[blk] = EXP_D15; break;
595
        }
596
        blk = blk1;
597
    }
598
}
599

    
600

    
601
/**
602
 * Calculate exponent strategies for all channels.
603
 * Array arrangement is reversed to simplify the per-channel calculation.
604
 */
605
static void compute_exp_strategy(AC3EncodeContext *s)
606
{
607
    int ch, blk;
608

    
609
    for (ch = 0; ch < s->fbw_channels; ch++) {
610
        compute_exp_strategy_ch(s, s->exp_strategy[ch], s->blocks[0].exp[ch]);
611
    }
612
    if (s->lfe_on) {
613
        ch = s->lfe_channel;
614
        s->exp_strategy[ch][0] = EXP_D15;
615
        for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
616
            s->exp_strategy[ch][blk] = EXP_REUSE;
617
    }
618
}
619

    
620

    
621
/**
622
 * Update the exponents so that they are the ones the decoder will decode.
623
 */
624
static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy)
625
{
626
    int nb_groups, i, k;
627

    
628
    nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
629

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

    
656
    /* constraint for DC exponent */
657
    if (exp[0] > 15)
658
        exp[0] = 15;
659

    
660
    /* decrease the delta between each groups to within 2 so that they can be
661
       differentially encoded */
662
    for (i = 1; i <= nb_groups; i++)
663
        exp[i] = FFMIN(exp[i], exp[i-1] + 2);
664
    i--;
665
    while (--i >= 0)
666
        exp[i] = FFMIN(exp[i], exp[i+1] + 2);
667

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

    
686

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

    
699
    for (ch = 0; ch < s->channels; ch++) {
700
        exp          = s->blocks[0].exp[ch];
701
        exp_strategy = s->exp_strategy[ch];
702
        nb_coefs     = s->nb_coefs[ch];
703

    
704
        blk = 0;
705
        while (blk < AC3_MAX_BLOCKS) {
706
            blk1 = blk + 1;
707

    
708
            /* count the number of EXP_REUSE blocks after the current block
709
               and set exponent reference block pointers */
710
            s->blocks[blk].exp_ref_block[ch] = &s->blocks[blk];
711
            while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
712
                s->blocks[blk1].exp_ref_block[ch] = &s->blocks[blk];
713
                blk1++;
714
            }
715
            num_reuse_blocks = blk1 - blk - 1;
716

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

    
720
            encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk]);
721

    
722
            exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
723
            blk = blk1;
724
        }
725
    }
726
}
727

    
728

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

    
742
    bit_count = 0;
743
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
744
        AC3Block *block = &s->blocks[blk];
745
        for (ch = 0; ch < s->channels; ch++) {
746
            int exp_strategy = s->exp_strategy[ch][blk];
747
            if (exp_strategy == EXP_REUSE)
748
                continue;
749
            group_size = exp_strategy + (exp_strategy == EXP_D45);
750
            nb_groups = exponent_group_tab[exp_strategy-1][s->nb_coefs[ch]];
751
            bit_count += 4 + (nb_groups * 7);
752
            p = block->exp[ch];
753

    
754
            /* DC exponent */
755
            exp1 = *p++;
756
            block->grouped_exp[ch][0] = exp1;
757

    
758
            /* remaining exponents are delta encoded */
759
            for (i = 1; i <= nb_groups; i++) {
760
                /* merge three delta in one code */
761
                exp0   = exp1;
762
                exp1   = p[0];
763
                p     += group_size;
764
                delta0 = exp1 - exp0 + 2;
765
                av_assert2(delta0 >= 0 && delta0 <= 4);
766

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

    
773
                exp0   = exp1;
774
                exp1   = p[0];
775
                p     += group_size;
776
                delta2 = exp1 - exp0 + 2;
777
                av_assert2(delta2 >= 0 && delta2 <= 4);
778

    
779
                block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
780
            }
781
        }
782
    }
783

    
784
    s->exponent_bits = bit_count;
785
}
786

    
787

    
788
/**
789
 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
790
 * Extract exponents from MDCT coefficients, calculate exponent strategies,
791
 * and encode final exponents.
792
 */
793
static void process_exponents(AC3EncodeContext *s)
794
{
795
    extract_exponents(s);
796

    
797
    compute_exp_strategy(s);
798

    
799
    encode_exponents(s);
800

    
801
    group_exponents(s);
802

    
803
    emms_c();
804
}
805

    
806

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

    
817
    /* assumptions:
818
     *   no dynamic range codes
819
     *   no channel coupling
820
     *   bit allocation parameters do not change between blocks
821
     *   SNR offsets do not change between blocks
822
     *   no delta bit allocation
823
     *   no skipped data
824
     *   no auxilliary data
825
     */
826

    
827
    /* header size */
828
    frame_bits = 65;
829
    frame_bits += frame_bits_inc[s->channel_mode];
830

    
831
    /* audio blocks */
832
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
833
        frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
834
        if (s->channel_mode == AC3_CHMODE_STEREO) {
835
            frame_bits++; /* rematstr */
836
        }
837
        frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
838
        if (s->lfe_on)
839
            frame_bits++; /* lfeexpstr */
840
        frame_bits++; /* baie */
841
        frame_bits++; /* snr */
842
        frame_bits += 2; /* delta / skip */
843
    }
844
    frame_bits++; /* cplinu for block 0 */
845
    /* bit alloc info */
846
    /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
847
    /* csnroffset[6] */
848
    /* (fsnoffset[4] + fgaincod[4]) * c */
849
    frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
850

    
851
    /* auxdatae, crcrsv */
852
    frame_bits += 2;
853

    
854
    /* CRC */
855
    frame_bits += 16;
856

    
857
    s->frame_bits_fixed = frame_bits;
858
}
859

    
860

    
861
/**
862
 * Initialize bit allocation.
863
 * Set default parameter codes and calculate parameter values.
864
 */
865
static void bit_alloc_init(AC3EncodeContext *s)
866
{
867
    int ch;
868

    
869
    /* init default parameters */
870
    s->slow_decay_code = 2;
871
    s->fast_decay_code = 1;
872
    s->slow_gain_code  = 1;
873
    s->db_per_bit_code = 3;
874
    s->floor_code      = 7;
875
    for (ch = 0; ch < s->channels; ch++)
876
        s->fast_gain_code[ch] = 4;
877

    
878
    /* initial snr offset */
879
    s->coarse_snr_offset = 40;
880

    
881
    /* compute real values */
882
    /* currently none of these values change during encoding, so we can just
883
       set them once at initialization */
884
    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
885
    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
886
    s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
887
    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
888
    s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
889

    
890
    count_frame_bits_fixed(s);
891
}
892

    
893

    
894
/**
895
 * Count the bits used to encode the frame, minus exponents and mantissas.
896
 * Bits based on fixed parameters have already been counted, so now we just
897
 * have to add the bits based on parameters that change during encoding.
898
 */
899
static void count_frame_bits(AC3EncodeContext *s)
900
{
901
    AC3EncOptions *opt = &s->options;
902
    int blk, ch;
903
    int frame_bits = 0;
904

    
905
    if (opt->audio_production_info)
906
        frame_bits += 7;
907
    if (s->bitstream_id == 6) {
908
        if (opt->extended_bsi_1)
909
            frame_bits += 14;
910
        if (opt->extended_bsi_2)
911
            frame_bits += 14;
912
    }
913

    
914
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
915
        /* stereo rematrixing */
916
        if (s->channel_mode == AC3_CHMODE_STEREO &&
917
            s->blocks[blk].new_rematrixing_strategy) {
918
            frame_bits += s->num_rematrixing_bands;
919
        }
920

    
921
        for (ch = 0; ch < s->fbw_channels; ch++) {
922
            if (s->exp_strategy[ch][blk] != EXP_REUSE)
923
                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
924
        }
925
    }
926
    s->frame_bits = s->frame_bits_fixed + frame_bits;
927
}
928

    
929

    
930
/**
931
 * Finalize the mantissa bit count by adding in the grouped mantissas.
932
 */
933
static int compute_mantissa_size_final(int mant_cnt[5])
934
{
935
    // bap=1 : 3 mantissas in 5 bits
936
    int bits = (mant_cnt[1] / 3) * 5;
937
    // bap=2 : 3 mantissas in 7 bits
938
    // bap=4 : 2 mantissas in 7 bits
939
    bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
940
    // bap=3 : each mantissa is 3 bits
941
    bits += mant_cnt[3] * 3;
942
    return bits;
943
}
944

    
945

    
946
/**
947
 * Calculate masking curve based on the final exponents.
948
 * Also calculate the power spectral densities to use in future calculations.
949
 */
950
static void bit_alloc_masking(AC3EncodeContext *s)
951
{
952
    int blk, ch;
953

    
954
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
955
        AC3Block *block = &s->blocks[blk];
956
        for (ch = 0; ch < s->channels; ch++) {
957
            /* We only need psd and mask for calculating bap.
958
               Since we currently do not calculate bap when exponent
959
               strategy is EXP_REUSE we do not need to calculate psd or mask. */
960
            if (s->exp_strategy[ch][blk] != EXP_REUSE) {
961
                ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
962
                                          s->nb_coefs[ch],
963
                                          block->psd[ch], block->band_psd[ch]);
964
                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
965
                                           0, s->nb_coefs[ch],
966
                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
967
                                           ch == s->lfe_channel,
968
                                           DBA_NONE, 0, NULL, NULL, NULL,
969
                                           block->mask[ch]);
970
            }
971
        }
972
    }
973
}
974

    
975

    
976
/**
977
 * Ensure that bap for each block and channel point to the current bap_buffer.
978
 * They may have been switched during the bit allocation search.
979
 */
980
static void reset_block_bap(AC3EncodeContext *s)
981
{
982
    int blk, ch;
983
    if (s->blocks[0].bap[0] == s->bap_buffer)
984
        return;
985
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
986
        for (ch = 0; ch < s->channels; ch++) {
987
            s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
988
        }
989
    }
990
}
991

    
992

    
993
/**
994
 * Run the bit allocation with a given SNR offset.
995
 * This calculates the bit allocation pointers that will be used to determine
996
 * the quantization of each mantissa.
997
 * @return the number of bits needed for mantissas if the given SNR offset is
998
 *         is used.
999
 */
1000
static int bit_alloc(AC3EncodeContext *s, int snr_offset)
1001
{
1002
    int blk, ch;
1003
    int mantissa_bits;
1004
    int mant_cnt[5];
1005

    
1006
    snr_offset = (snr_offset - 240) << 2;
1007

    
1008
    reset_block_bap(s);
1009
    mantissa_bits = 0;
1010
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1011
        AC3Block *block;
1012
        // initialize grouped mantissa counts. these are set so that they are
1013
        // padded to the next whole group size when bits are counted in
1014
        // compute_mantissa_size_final
1015
        mant_cnt[0] = mant_cnt[3] = 0;
1016
        mant_cnt[1] = mant_cnt[2] = 2;
1017
        mant_cnt[4] = 1;
1018
        for (ch = 0; ch < s->channels; ch++) {
1019
            /* Currently the only bit allocation parameters which vary across
1020
               blocks within a frame are the exponent values.  We can take
1021
               advantage of that by reusing the bit allocation pointers
1022
               whenever we reuse exponents. */
1023
            block = s->blocks[blk].exp_ref_block[ch];
1024
            if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1025
                s->ac3dsp.bit_alloc_calc_bap(block->mask[ch], block->psd[ch], 0,
1026
                                          s->nb_coefs[ch], snr_offset,
1027
                                          s->bit_alloc.floor, ff_ac3_bap_tab,
1028
                                          block->bap[ch]);
1029
            }
1030
            mantissa_bits += s->ac3dsp.compute_mantissa_size(mant_cnt, block->bap[ch], s->nb_coefs[ch]);
1031
        }
1032
        mantissa_bits += compute_mantissa_size_final(mant_cnt);
1033
    }
1034
    return mantissa_bits;
1035
}
1036

    
1037

    
1038
/**
1039
 * Constant bitrate bit allocation search.
1040
 * Find the largest SNR offset that will allow data to fit in the frame.
1041
 */
1042
static int cbr_bit_allocation(AC3EncodeContext *s)
1043
{
1044
    int ch;
1045
    int bits_left;
1046
    int snr_offset, snr_incr;
1047

    
1048
    bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1049
    av_assert2(bits_left >= 0);
1050

    
1051
    snr_offset = s->coarse_snr_offset << 4;
1052

    
1053
    /* if previous frame SNR offset was 1023, check if current frame can also
1054
       use SNR offset of 1023. if so, skip the search. */
1055
    if ((snr_offset | s->fine_snr_offset[0]) == 1023) {
1056
        if (bit_alloc(s, 1023) <= bits_left)
1057
            return 0;
1058
    }
1059

    
1060
    while (snr_offset >= 0 &&
1061
           bit_alloc(s, snr_offset) > bits_left) {
1062
        snr_offset -= 64;
1063
    }
1064
    if (snr_offset < 0)
1065
        return AVERROR(EINVAL);
1066

    
1067
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1068
    for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1069
        while (snr_offset + snr_incr <= 1023 &&
1070
               bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1071
            snr_offset += snr_incr;
1072
            FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1073
        }
1074
    }
1075
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1076
    reset_block_bap(s);
1077

    
1078
    s->coarse_snr_offset = snr_offset >> 4;
1079
    for (ch = 0; ch < s->channels; ch++)
1080
        s->fine_snr_offset[ch] = snr_offset & 0xF;
1081

    
1082
    return 0;
1083
}
1084

    
1085

    
1086
/**
1087
 * Downgrade exponent strategies to reduce the bits used by the exponents.
1088
 * This is a fallback for when bit allocation fails with the normal exponent
1089
 * strategies.  Each time this function is run it only downgrades the
1090
 * strategy in 1 channel of 1 block.
1091
 * @return non-zero if downgrade was unsuccessful
1092
 */
1093
static int downgrade_exponents(AC3EncodeContext *s)
1094
{
1095
    int ch, blk;
1096

    
1097
    for (ch = 0; ch < s->fbw_channels; ch++) {
1098
        for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1099
            if (s->exp_strategy[ch][blk] == EXP_D15) {
1100
                s->exp_strategy[ch][blk] = EXP_D25;
1101
                return 0;
1102
            }
1103
        }
1104
    }
1105
    for (ch = 0; ch < s->fbw_channels; ch++) {
1106
        for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1107
            if (s->exp_strategy[ch][blk] == EXP_D25) {
1108
                s->exp_strategy[ch][blk] = EXP_D45;
1109
                return 0;
1110
            }
1111
        }
1112
    }
1113
    for (ch = 0; ch < s->fbw_channels; ch++) {
1114
        /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
1115
           the block number > 0 */
1116
        for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
1117
            if (s->exp_strategy[ch][blk] > EXP_REUSE) {
1118
                s->exp_strategy[ch][blk] = EXP_REUSE;
1119
                return 0;
1120
            }
1121
        }
1122
    }
1123
    return -1;
1124
}
1125

    
1126

    
1127
/**
1128
 * Reduce the bandwidth to reduce the number of bits used for a given SNR offset.
1129
 * This is a second fallback for when bit allocation still fails after exponents
1130
 * have been downgraded.
1131
 * @return non-zero if bandwidth reduction was unsuccessful
1132
 */
1133
static int reduce_bandwidth(AC3EncodeContext *s, int min_bw_code)
1134
{
1135
    int ch;
1136

    
1137
    if (s->bandwidth_code[0] > min_bw_code) {
1138
        for (ch = 0; ch < s->fbw_channels; ch++) {
1139
            s->bandwidth_code[ch]--;
1140
            s->nb_coefs[ch] = s->bandwidth_code[ch] * 3 + 73;
1141
        }
1142
        return 0;
1143
    }
1144
    return -1;
1145
}
1146

    
1147

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

    
1158
    count_frame_bits(s);
1159

    
1160
    bit_alloc_masking(s);
1161

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

    
1173
        /* fallback 2: reduce bandwidth */
1174
        /* only do this if the user has not specified a specific cutoff
1175
           frequency */
1176
        if (!s->cutoff && !reduce_bandwidth(s, 0)) {
1177
            process_exponents(s);
1178
            ret = compute_bit_allocation(s);
1179
            continue;
1180
        }
1181

    
1182
        /* fallbacks were not enough... */
1183
        break;
1184
    }
1185

    
1186
    return ret;
1187
}
1188

    
1189

    
1190
/**
1191
 * Symmetric quantization on 'levels' levels.
1192
 */
1193
static inline int sym_quant(int c, int e, int levels)
1194
{
1195
    int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1196
    av_assert2(v >= 0 && v < levels);
1197
    return v;
1198
}
1199

    
1200

    
1201
/**
1202
 * Asymmetric quantization on 2^qbits levels.
1203
 */
1204
static inline int asym_quant(int c, int e, int qbits)
1205
{
1206
    int lshift, m, v;
1207

    
1208
    lshift = e + qbits - 24;
1209
    if (lshift >= 0)
1210
        v = c << lshift;
1211
    else
1212
        v = c >> (-lshift);
1213
    /* rounding */
1214
    v = (v + 1) >> 1;
1215
    m = (1 << (qbits-1));
1216
    if (v >= m)
1217
        v = m - 1;
1218
    av_assert2(v >= -m);
1219
    return v & ((1 << qbits)-1);
1220
}
1221

    
1222

    
1223
/**
1224
 * Quantize a set of mantissas for a single channel in a single block.
1225
 */
1226
static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1227
                                      uint8_t *exp,
1228
                                      uint8_t *bap, uint16_t *qmant, int n)
1229
{
1230
    int i;
1231

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

    
1316

    
1317
/**
1318
 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1319
 */
1320
static void quantize_mantissas(AC3EncodeContext *s)
1321
{
1322
    int blk, ch;
1323

    
1324

    
1325
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1326
        AC3Block *block = &s->blocks[blk];
1327
        AC3Block *ref_block;
1328
        AC3Mant m = { 0 };
1329

    
1330
        for (ch = 0; ch < s->channels; ch++) {
1331
            ref_block = block->exp_ref_block[ch];
1332
            quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1333
                                      ref_block->exp[ch], ref_block->bap[ch],
1334
                                      block->qmant[ch], s->nb_coefs[ch]);
1335
        }
1336
    }
1337
}
1338

    
1339

    
1340
/**
1341
 * Write the AC-3 frame header to the output bitstream.
1342
 */
1343
static void output_frame_header(AC3EncodeContext *s)
1344
{
1345
    AC3EncOptions *opt = &s->options;
1346

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

    
1395

    
1396
/**
1397
 * Write one audio block to the output bitstream.
1398
 */
1399
static void output_audio_block(AC3EncodeContext *s, int blk)
1400
{
1401
    int ch, i, baie, rbnd;
1402
    AC3Block *block = &s->blocks[blk];
1403

    
1404
    /* block switching */
1405
    for (ch = 0; ch < s->fbw_channels; ch++)
1406
        put_bits(&s->pb, 1, 0);
1407

    
1408
    /* dither flags */
1409
    for (ch = 0; ch < s->fbw_channels; ch++)
1410
        put_bits(&s->pb, 1, 1);
1411

    
1412
    /* dynamic range codes */
1413
    put_bits(&s->pb, 1, 0);
1414

    
1415
    /* channel coupling */
1416
    if (!blk) {
1417
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
1418
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
1419
    } else {
1420
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1421
    }
1422

    
1423
    /* stereo rematrixing */
1424
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1425
        put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1426
        if (block->new_rematrixing_strategy) {
1427
            /* rematrixing flags */
1428
            for (rbnd = 0; rbnd < s->num_rematrixing_bands; rbnd++)
1429
                put_bits(&s->pb, 1, block->rematrixing_flags[rbnd]);
1430
        }
1431
    }
1432

    
1433
    /* exponent strategy */
1434
    for (ch = 0; ch < s->fbw_channels; ch++)
1435
        put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1436
    if (s->lfe_on)
1437
        put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1438

    
1439
    /* bandwidth */
1440
    for (ch = 0; ch < s->fbw_channels; ch++) {
1441
        if (s->exp_strategy[ch][blk] != EXP_REUSE)
1442
            put_bits(&s->pb, 6, s->bandwidth_code[ch]);
1443
    }
1444

    
1445
    /* exponents */
1446
    for (ch = 0; ch < s->channels; ch++) {
1447
        int nb_groups;
1448

    
1449
        if (s->exp_strategy[ch][blk] == EXP_REUSE)
1450
            continue;
1451

    
1452
        /* DC exponent */
1453
        put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1454

    
1455
        /* exponent groups */
1456
        nb_groups = exponent_group_tab[s->exp_strategy[ch][blk]-1][s->nb_coefs[ch]];
1457
        for (i = 1; i <= nb_groups; i++)
1458
            put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1459

    
1460
        /* gain range info */
1461
        if (ch != s->lfe_channel)
1462
            put_bits(&s->pb, 2, 0);
1463
    }
1464

    
1465
    /* bit allocation info */
1466
    baie = (blk == 0);
1467
    put_bits(&s->pb, 1, baie);
1468
    if (baie) {
1469
        put_bits(&s->pb, 2, s->slow_decay_code);
1470
        put_bits(&s->pb, 2, s->fast_decay_code);
1471
        put_bits(&s->pb, 2, s->slow_gain_code);
1472
        put_bits(&s->pb, 2, s->db_per_bit_code);
1473
        put_bits(&s->pb, 3, s->floor_code);
1474
    }
1475

    
1476
    /* snr offset */
1477
    put_bits(&s->pb, 1, baie);
1478
    if (baie) {
1479
        put_bits(&s->pb, 6, s->coarse_snr_offset);
1480
        for (ch = 0; ch < s->channels; ch++) {
1481
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1482
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1483
        }
1484
    }
1485

    
1486
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1487
    put_bits(&s->pb, 1, 0); /* no data to skip */
1488

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

    
1510

    
1511
/** CRC-16 Polynomial */
1512
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1513

    
1514

    
1515
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1516
{
1517
    unsigned int c;
1518

    
1519
    c = 0;
1520
    while (a) {
1521
        if (a & 1)
1522
            c ^= b;
1523
        a = a >> 1;
1524
        b = b << 1;
1525
        if (b & (1 << 16))
1526
            b ^= poly;
1527
    }
1528
    return c;
1529
}
1530

    
1531

    
1532
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1533
{
1534
    unsigned int r;
1535
    r = 1;
1536
    while (n) {
1537
        if (n & 1)
1538
            r = mul_poly(r, a, poly);
1539
        a = mul_poly(a, a, poly);
1540
        n >>= 1;
1541
    }
1542
    return r;
1543
}
1544

    
1545

    
1546
/**
1547
 * Fill the end of the frame with 0's and compute the two CRCs.
1548
 */
1549
static void output_frame_end(AC3EncodeContext *s)
1550
{
1551
    const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1552
    int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1553
    uint8_t *frame;
1554

    
1555
    frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1556

    
1557
    /* pad the remainder of the frame with zeros */
1558
    av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1559
    flush_put_bits(&s->pb);
1560
    frame = s->pb.buf;
1561
    pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1562
    av_assert2(pad_bytes >= 0);
1563
    if (pad_bytes > 0)
1564
        memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1565

    
1566
    /* compute crc1 */
1567
    /* this is not so easy because it is at the beginning of the data... */
1568
    crc1    = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1569
    crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1570
    crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1571
    AV_WB16(frame + 2, crc1);
1572

    
1573
    /* compute crc2 */
1574
    crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1575
                          s->frame_size - frame_size_58 - 3);
1576
    crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1577
    /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1578
    if (crc2 == 0x770B) {
1579
        frame[s->frame_size - 3] ^= 0x1;
1580
        crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1581
    }
1582
    crc2 = av_bswap16(crc2);
1583
    AV_WB16(frame + s->frame_size - 2, crc2);
1584
}
1585

    
1586

    
1587
/**
1588
 * Write the frame to the output bitstream.
1589
 */
1590
static void output_frame(AC3EncodeContext *s, unsigned char *frame)
1591
{
1592
    int blk;
1593

    
1594
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1595

    
1596
    output_frame_header(s);
1597

    
1598
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1599
        output_audio_block(s, blk);
1600

    
1601
    output_frame_end(s);
1602
}
1603

    
1604

    
1605
static void dprint_options(AVCodecContext *avctx)
1606
{
1607
#ifdef DEBUG
1608
    AC3EncodeContext *s = avctx->priv_data;
1609
    AC3EncOptions *opt = &s->options;
1610
    char strbuf[32];
1611

    
1612
    switch (s->bitstream_id) {
1613
    case  6:  strncpy(strbuf, "AC-3 (alt syntax)", 32);      break;
1614
    case  8:  strncpy(strbuf, "AC-3 (standard)", 32);        break;
1615
    case  9:  strncpy(strbuf, "AC-3 (dnet half-rate)", 32);  break;
1616
    case 10:  strncpy(strbuf, "AC-3 (dnet quater-rate", 32); break;
1617
    default: snprintf(strbuf, 32, "ERROR");
1618
    }
1619
    av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
1620
    av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
1621
    av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
1622
    av_dlog(avctx, "channel_layout: %s\n", strbuf);
1623
    av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
1624
    av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
1625
    if (s->cutoff)
1626
        av_dlog(avctx, "cutoff: %d\n", s->cutoff);
1627

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

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

    
1704
            switch (opt->ad_converter_type) {
1705
            case 0:  strncpy(strbuf, "standard", 32); break;
1706
            case 1:  strncpy(strbuf, "hdcd", 32);     break;
1707
            default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
1708
            }
1709
            av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
1710
        } else {
1711
            av_dlog(avctx, "extended bitstream info 2: {not written}\n");
1712
        }
1713
    }
1714
#endif
1715
}
1716

    
1717

    
1718
#define FLT_OPTION_THRESHOLD 0.01
1719

    
1720
static int validate_float_option(float v, const float *v_list, int v_list_size)
1721
{
1722
    int i;
1723

    
1724
    for (i = 0; i < v_list_size; i++) {
1725
        if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
1726
            v > (v_list[i] - FLT_OPTION_THRESHOLD))
1727
            break;
1728
    }
1729
    if (i == v_list_size)
1730
        return -1;
1731

    
1732
    return i;
1733
}
1734

    
1735

    
1736
static void validate_mix_level(void *log_ctx, const char *opt_name,
1737
                               float *opt_param, const float *list,
1738
                               int list_size, int default_value, int min_value,
1739
                               int *ctx_param)
1740
{
1741
    int mixlev = validate_float_option(*opt_param, list, list_size);
1742
    if (mixlev < min_value) {
1743
        mixlev = default_value;
1744
        if (*opt_param >= 0.0) {
1745
            av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
1746
                   "default value: %0.3f\n", opt_name, list[mixlev]);
1747
        }
1748
    }
1749
    *opt_param = list[mixlev];
1750
    *ctx_param = mixlev;
1751
}
1752

    
1753

    
1754
/**
1755
 * Validate metadata options as set by AVOption system.
1756
 * These values can optionally be changed per-frame.
1757
 */
1758
static int validate_metadata(AVCodecContext *avctx)
1759
{
1760
    AC3EncodeContext *s = avctx->priv_data;
1761
    AC3EncOptions *opt = &s->options;
1762

    
1763
    /* validate mixing levels */
1764
    if (s->has_center) {
1765
        validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
1766
                           cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
1767
                           &s->center_mix_level);
1768
    }
1769
    if (s->has_surround) {
1770
        validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
1771
                           surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
1772
                           &s->surround_mix_level);
1773
    }
1774

    
1775
    /* set audio production info flag */
1776
    if (opt->mixing_level >= 0 || opt->room_type >= 0) {
1777
        if (opt->mixing_level < 0) {
1778
            av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
1779
                   "room_type is set\n");
1780
            return AVERROR(EINVAL);
1781
        }
1782
        if (opt->mixing_level < 80) {
1783
            av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
1784
                   "80dB and 111dB\n");
1785
            return AVERROR(EINVAL);
1786
        }
1787
        /* default room type */
1788
        if (opt->room_type < 0)
1789
            opt->room_type = 0;
1790
        opt->audio_production_info = 1;
1791
    } else {
1792
        opt->audio_production_info = 0;
1793
    }
1794

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

    
1830
    /* set extended bsi 2 flag */
1831
    if (opt->dolby_surround_ex_mode >= 0 ||
1832
        opt->dolby_headphone_mode   >= 0 ||
1833
        opt->ad_converter_type      >= 0) {
1834
        /* default dolby surround ex mode */
1835
        if (opt->dolby_surround_ex_mode < 0)
1836
            opt->dolby_surround_ex_mode = 0;
1837
        /* default dolby headphone mode */
1838
        if (opt->dolby_headphone_mode < 0)
1839
            opt->dolby_headphone_mode = 0;
1840
        /* default A/D converter type */
1841
        if (opt->ad_converter_type < 0)
1842
            opt->ad_converter_type = 0;
1843
        opt->extended_bsi_2 = 1;
1844
    } else {
1845
        opt->extended_bsi_2 = 0;
1846
    }
1847

    
1848
    /* set bitstream id for alternate bitstream syntax */
1849
    if (opt->extended_bsi_1 || opt->extended_bsi_2) {
1850
        if (s->bitstream_id > 8 && s->bitstream_id < 11) {
1851
            static int warn_once = 1;
1852
            if (warn_once) {
1853
                av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
1854
                       "not compatible with reduced samplerates. writing of "
1855
                       "extended bitstream information will be disabled.\n");
1856
                warn_once = 0;
1857
            }
1858
        } else {
1859
            s->bitstream_id = 6;
1860
        }
1861
    }
1862

    
1863
    return 0;
1864
}
1865

    
1866

    
1867
/**
1868
 * Encode a single AC-3 frame.
1869
 */
1870
static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
1871
                            int buf_size, void *data)
1872
{
1873
    AC3EncodeContext *s = avctx->priv_data;
1874
    const SampleType *samples = data;
1875
    int ret;
1876

    
1877
    if (s->options.allow_per_frame_metadata) {
1878
        ret = validate_metadata(avctx);
1879
        if (ret)
1880
            return ret;
1881
    }
1882

    
1883
    if (s->bit_alloc.sr_code == 1)
1884
        adjust_frame_size(s);
1885

    
1886
    deinterleave_input_samples(s, samples);
1887

    
1888
    apply_mdct(s);
1889

    
1890
    scale_coefficients(s);
1891

    
1892
    compute_rematrixing_strategy(s);
1893

    
1894
    apply_rematrixing(s);
1895

    
1896
    process_exponents(s);
1897

    
1898
    ret = compute_bit_allocation(s);
1899
    if (ret) {
1900
        av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1901
        return ret;
1902
    }
1903

    
1904
    quantize_mantissas(s);
1905

    
1906
    output_frame(s, frame);
1907

    
1908
    return s->frame_size;
1909
}
1910

    
1911

    
1912
/**
1913
 * Finalize encoding and free any memory allocated by the encoder.
1914
 */
1915
static av_cold int ac3_encode_close(AVCodecContext *avctx)
1916
{
1917
    int blk, ch;
1918
    AC3EncodeContext *s = avctx->priv_data;
1919

    
1920
    for (ch = 0; ch < s->channels; ch++)
1921
        av_freep(&s->planar_samples[ch]);
1922
    av_freep(&s->planar_samples);
1923
    av_freep(&s->bap_buffer);
1924
    av_freep(&s->bap1_buffer);
1925
    av_freep(&s->mdct_coef_buffer);
1926
    av_freep(&s->fixed_coef_buffer);
1927
    av_freep(&s->exp_buffer);
1928
    av_freep(&s->grouped_exp_buffer);
1929
    av_freep(&s->psd_buffer);
1930
    av_freep(&s->band_psd_buffer);
1931
    av_freep(&s->mask_buffer);
1932
    av_freep(&s->qmant_buffer);
1933
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1934
        AC3Block *block = &s->blocks[blk];
1935
        av_freep(&block->bap);
1936
        av_freep(&block->mdct_coef);
1937
        av_freep(&block->fixed_coef);
1938
        av_freep(&block->exp);
1939
        av_freep(&block->grouped_exp);
1940
        av_freep(&block->psd);
1941
        av_freep(&block->band_psd);
1942
        av_freep(&block->mask);
1943
        av_freep(&block->qmant);
1944
    }
1945

    
1946
    mdct_end(&s->mdct);
1947

    
1948
    av_freep(&avctx->coded_frame);
1949
    return 0;
1950
}
1951

    
1952

    
1953
/**
1954
 * Set channel information during initialization.
1955
 */
1956
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1957
                                    int64_t *channel_layout)
1958
{
1959
    int ch_layout;
1960

    
1961
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
1962
        return AVERROR(EINVAL);
1963
    if ((uint64_t)*channel_layout > 0x7FF)
1964
        return AVERROR(EINVAL);
1965
    ch_layout = *channel_layout;
1966
    if (!ch_layout)
1967
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1968

    
1969
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1970
    s->channels     = channels;
1971
    s->fbw_channels = channels - s->lfe_on;
1972
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
1973
    if (s->lfe_on)
1974
        ch_layout -= AV_CH_LOW_FREQUENCY;
1975

    
1976
    switch (ch_layout) {
1977
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
1978
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
1979
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
1980
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
1981
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
1982
    case AV_CH_LAYOUT_QUAD:
1983
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
1984
    case AV_CH_LAYOUT_5POINT0:
1985
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
1986
    default:
1987
        return AVERROR(EINVAL);
1988
    }
1989
    s->has_center   = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
1990
    s->has_surround =  s->channel_mode & 0x04;
1991

    
1992
    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1993
    *channel_layout = ch_layout;
1994
    if (s->lfe_on)
1995
        *channel_layout |= AV_CH_LOW_FREQUENCY;
1996

    
1997
    return 0;
1998
}
1999

    
2000

    
2001
static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
2002
{
2003
    int i, ret;
2004

    
2005
    /* validate channel layout */
2006
    if (!avctx->channel_layout) {
2007
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
2008
                                      "encoder will guess the layout, but it "
2009
                                      "might be incorrect.\n");
2010
    }
2011
    ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
2012
    if (ret) {
2013
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
2014
        return ret;
2015
    }
2016

    
2017
    /* validate sample rate */
2018
    for (i = 0; i < 9; i++) {
2019
        if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
2020
            break;
2021
    }
2022
    if (i == 9) {
2023
        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
2024
        return AVERROR(EINVAL);
2025
    }
2026
    s->sample_rate        = avctx->sample_rate;
2027
    s->bit_alloc.sr_shift = i % 3;
2028
    s->bit_alloc.sr_code  = i / 3;
2029
    s->bitstream_id       = 8 + s->bit_alloc.sr_shift;
2030

    
2031
    /* validate bit rate */
2032
    for (i = 0; i < 19; i++) {
2033
        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
2034
            break;
2035
    }
2036
    if (i == 19) {
2037
        av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2038
        return AVERROR(EINVAL);
2039
    }
2040
    s->bit_rate        = avctx->bit_rate;
2041
    s->frame_size_code = i << 1;
2042

    
2043
    /* validate cutoff */
2044
    if (avctx->cutoff < 0) {
2045
        av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2046
        return AVERROR(EINVAL);
2047
    }
2048
    s->cutoff = avctx->cutoff;
2049
    if (s->cutoff > (s->sample_rate >> 1))
2050
        s->cutoff = s->sample_rate >> 1;
2051

    
2052
    /* validate audio service type / channels combination */
2053
    if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
2054
         avctx->channels == 1) ||
2055
        ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
2056
          avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY  ||
2057
          avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
2058
         && avctx->channels > 1)) {
2059
        av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
2060
                                    "specified number of channels\n");
2061
        return AVERROR(EINVAL);
2062
    }
2063

    
2064
    ret = validate_metadata(avctx);
2065
    if (ret)
2066
        return ret;
2067

    
2068
    s->rematrixing_enabled = s->options.stereo_rematrixing &&
2069
                             (s->channel_mode == AC3_CHMODE_STEREO);
2070

    
2071
    return 0;
2072
}
2073

    
2074

    
2075
/**
2076
 * Set bandwidth for all channels.
2077
 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2078
 * default value will be used.
2079
 */
2080
static av_cold void set_bandwidth(AC3EncodeContext *s)
2081
{
2082
    int ch, bw_code;
2083

    
2084
    if (s->cutoff) {
2085
        /* calculate bandwidth based on user-specified cutoff frequency */
2086
        int fbw_coeffs;
2087
        fbw_coeffs     = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2088
        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2089
    } else {
2090
        /* use default bandwidth setting */
2091
        bw_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2092
    }
2093

    
2094
    /* set number of coefficients for each channel */
2095
    for (ch = 0; ch < s->fbw_channels; ch++) {
2096
        s->bandwidth_code[ch] = bw_code;
2097
        s->nb_coefs[ch]       = bw_code * 3 + 73;
2098
    }
2099
    if (s->lfe_on)
2100
        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
2101
}
2102

    
2103

    
2104
static av_cold int allocate_buffers(AVCodecContext *avctx)
2105
{
2106
    int blk, ch;
2107
    AC3EncodeContext *s = avctx->priv_data;
2108

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

    
2153
        for (ch = 0; ch < s->channels; ch++) {
2154
            /* arrangement: block, channel, coeff */
2155
            block->bap[ch]         = &s->bap_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
2156
            block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (blk * s->channels + ch)];
2157
            block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * s->channels + ch)];
2158
            block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
2159
            block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * s->channels + ch)];
2160
            block->mask[ch]        = &s->mask_buffer       [64            * (blk * s->channels + ch)];
2161
            block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * s->channels + ch)];
2162

    
2163
            /* arrangement: channel, block, coeff */
2164
            block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2165
        }
2166
    }
2167

    
2168
    if (CONFIG_AC3ENC_FLOAT) {
2169
        FF_ALLOC_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * s->channels *
2170
                         AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
2171
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2172
            AC3Block *block = &s->blocks[blk];
2173
            FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2174
                              sizeof(*block->fixed_coef), alloc_fail);
2175
            for (ch = 0; ch < s->channels; ch++)
2176
                block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
2177
        }
2178
    } else {
2179
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2180
            AC3Block *block = &s->blocks[blk];
2181
            FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2182
                              sizeof(*block->fixed_coef), alloc_fail);
2183
            for (ch = 0; ch < s->channels; ch++)
2184
                block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2185
        }
2186
    }
2187

    
2188
    return 0;
2189
alloc_fail:
2190
    return AVERROR(ENOMEM);
2191
}
2192

    
2193

    
2194
/**
2195
 * Initialize the encoder.
2196
 */
2197
static av_cold int ac3_encode_init(AVCodecContext *avctx)
2198
{
2199
    AC3EncodeContext *s = avctx->priv_data;
2200
    int ret, frame_size_58;
2201

    
2202
    avctx->frame_size = AC3_FRAME_SIZE;
2203

    
2204
    ff_ac3_common_init();
2205

    
2206
    ret = validate_options(avctx, s);
2207
    if (ret)
2208
        return ret;
2209

    
2210
    s->bitstream_mode = avctx->audio_service_type;
2211
    if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2212
        s->bitstream_mode = 0x7;
2213

    
2214
    s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2215
    s->bits_written    = 0;
2216
    s->samples_written = 0;
2217
    s->frame_size      = s->frame_size_min;
2218

    
2219
    /* calculate crc_inv for both possible frame sizes */
2220
    frame_size_58 = (( s->frame_size    >> 2) + ( s->frame_size    >> 4)) << 1;
2221
    s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2222
    if (s->bit_alloc.sr_code == 1) {
2223
        frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2224
        s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2225
    }
2226

    
2227
    set_bandwidth(s);
2228

    
2229
    exponent_init(s);
2230

    
2231
    bit_alloc_init(s);
2232

    
2233
    ret = mdct_init(avctx, &s->mdct, 9);
2234
    if (ret)
2235
        goto init_fail;
2236

    
2237
    ret = allocate_buffers(avctx);
2238
    if (ret)
2239
        goto init_fail;
2240

    
2241
    avctx->coded_frame= avcodec_alloc_frame();
2242

    
2243
    dsputil_init(&s->dsp, avctx);
2244
    ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2245

    
2246
    dprint_options(avctx);
2247

    
2248
    return 0;
2249
init_fail:
2250
    ac3_encode_close(avctx);
2251
    return ret;
2252
}