Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ 6f718471

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 "libavutil/audioconvert.h"
33
#include "libavutil/avassert.h"
34
#include "libavutil/crc.h"
35
#include "libavutil/opt.h"
36
#include "avcodec.h"
37
#include "put_bits.h"
38
#include "dsputil.h"
39
#include "ac3dsp.h"
40
#include "ac3.h"
41
#include "audioconvert.h"
42

    
43

    
44
#ifndef CONFIG_AC3ENC_FLOAT
45
#define CONFIG_AC3ENC_FLOAT 0
46
#endif
47

    
48

    
49
/** Maximum number of exponent groups. +1 for separate DC exponent. */
50
#define AC3_MAX_EXP_GROUPS 85
51

    
52
/* stereo rematrixing algorithms */
53
#define AC3_REMATRIXING_IS_STATIC 0x1
54
#define AC3_REMATRIXING_SUMS    0
55
#define AC3_REMATRIXING_NONE    1
56
#define AC3_REMATRIXING_ALWAYS  3
57

    
58
/** Scale a float value by 2^bits and convert to an integer. */
59
#define SCALE_FLOAT(a, bits) lrintf((a) * (float)(1 << (bits)))
60

    
61

    
62
#if CONFIG_AC3ENC_FLOAT
63
#include "ac3enc_float.h"
64
#else
65
#include "ac3enc_fixed.h"
66
#endif
67

    
68

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

    
95
    /* other encoding options */
96
    int allow_per_frame_metadata;
97
} AC3EncOptions;
98

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

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

    
129
    AC3Block blocks[AC3_MAX_BLOCKS];        ///< per-block info
130

    
131
    int bitstream_id;                       ///< bitstream id                           (bsid)
132
    int bitstream_mode;                     ///< bitstream mode                         (bsmod)
133

    
134
    int bit_rate;                           ///< target bit rate, in bits-per-second
135
    int sample_rate;                        ///< sampling frequency, in Hz
136

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

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

    
153
    int center_mix_level;                   ///< center mix level code
154
    int surround_mix_level;                 ///< surround mix level code
155
    int ltrt_center_mix_level;              ///< Lt/Rt center mix level code
156
    int ltrt_surround_mix_level;            ///< Lt/Rt surround mix level code
157
    int loro_center_mix_level;              ///< Lo/Ro center mix level code
158
    int loro_surround_mix_level;            ///< Lo/Ro surround mix level code
159

    
160
    int cutoff;                             ///< user-specified cutoff frequency, in Hz
161
    int bandwidth_code[AC3_MAX_CHANNELS];   ///< bandwidth code (0 to 60)               (chbwcod)
162
    int nb_coefs[AC3_MAX_CHANNELS];
163

    
164
    int rematrixing;                        ///< determines how rematrixing strategy is calculated
165
    int num_rematrixing_bands;              ///< number of rematrixing bands
166

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

    
181
    SampleType **planar_samples;
182
    uint8_t *bap_buffer;
183
    uint8_t *bap1_buffer;
184
    CoefType *mdct_coef_buffer;
185
    int32_t *fixed_coef_buffer;
186
    uint8_t *exp_buffer;
187
    uint8_t *grouped_exp_buffer;
188
    int16_t *psd_buffer;
189
    int16_t *band_psd_buffer;
190
    int16_t *mask_buffer;
191
    uint16_t *qmant_buffer;
192

    
193
    uint8_t exp_strategy[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< exponent strategies
194

    
195
    DECLARE_ALIGNED(16, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
196
} AC3EncodeContext;
197

    
198
typedef struct AC3Mant {
199
    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
200
    int mant1_cnt, mant2_cnt, mant4_cnt;    ///< mantissa counts for bap=1,2,4
201
} AC3Mant;
202

    
203
#define CMIXLEV_NUM_OPTIONS 3
204
static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
205
    LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
206
};
207

    
208
#define SURMIXLEV_NUM_OPTIONS 3
209
static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
210
    LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
211
};
212

    
213
#define EXTMIXLEV_NUM_OPTIONS 8
214
static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
215
    LEVEL_PLUS_3DB,  LEVEL_PLUS_1POINT5DB,  LEVEL_ONE,       LEVEL_MINUS_4POINT5DB,
216
    LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
217
};
218

    
219

    
220
#define OFFSET(param) offsetof(AC3EncodeContext, options.param)
221
#define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
222

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

    
266
#if CONFIG_AC3ENC_FLOAT
267
static AVClass ac3enc_class = { "AC-3 Encoder", av_default_item_name,
268
                                options, LIBAVUTIL_VERSION_INT };
269
#else
270
static AVClass ac3enc_class = { "Fixed-Point AC-3 Encoder", av_default_item_name,
271
                                options, LIBAVUTIL_VERSION_INT };
272
#endif
273

    
274

    
275
/* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
276

    
277
static av_cold void mdct_end(AC3MDCTContext *mdct);
278

    
279
static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
280
                             int nbits);
281

    
282
static void mdct512(AC3MDCTContext *mdct, CoefType *out, SampleType *in);
283

    
284
static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
285
                         const SampleType *window, unsigned int len);
286

    
287
static int normalize_samples(AC3EncodeContext *s);
288

    
289
static void scale_coefficients(AC3EncodeContext *s);
290

    
291

    
292
/**
293
 * LUT for number of exponent groups.
294
 * exponent_group_tab[exponent strategy-1][number of coefficients]
295
 */
296
static uint8_t exponent_group_tab[3][256];
297

    
298

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

    
324

    
325
/**
326
 * Adjust the frame size to make the average bit rate match the target bit rate.
327
 * This is only needed for 11025, 22050, and 44100 sample rates.
328
 */
329
static void adjust_frame_size(AC3EncodeContext *s)
330
{
331
    while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
332
        s->bits_written    -= s->bit_rate;
333
        s->samples_written -= s->sample_rate;
334
    }
335
    s->frame_size = s->frame_size_min +
336
                    2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
337
    s->bits_written    += s->frame_size * 8;
338
    s->samples_written += AC3_FRAME_SIZE;
339
}
340

    
341

    
342
/**
343
 * Deinterleave input samples.
344
 * Channels are reordered from Libav's default order to AC-3 order.
345
 */
346
static void deinterleave_input_samples(AC3EncodeContext *s,
347
                                       const SampleType *samples)
348
{
349
    int ch, i;
350

    
351
    /* deinterleave and remap input samples */
352
    for (ch = 0; ch < s->channels; ch++) {
353
        const SampleType *sptr;
354
        int sinc;
355

    
356
        /* copy last 256 samples of previous frame to the start of the current frame */
357
        memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
358
               AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
359

    
360
        /* deinterleave */
361
        sinc = s->channels;
362
        sptr = samples + s->channel_map[ch];
363
        for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
364
            s->planar_samples[ch][i] = *sptr;
365
            sptr += sinc;
366
        }
367
    }
368
}
369

    
370

    
371
/**
372
 * Apply the MDCT to input samples to generate frequency coefficients.
373
 * This applies the KBD window and normalizes the input to reduce precision
374
 * loss due to fixed-point calculations.
375
 */
376
static void apply_mdct(AC3EncodeContext *s)
377
{
378
    int blk, ch;
379

    
380
    for (ch = 0; ch < s->channels; ch++) {
381
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
382
            AC3Block *block = &s->blocks[blk];
383
            const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
384

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

    
387
            block->coeff_shift[ch] = normalize_samples(s);
388

    
389
            mdct512(&s->mdct, block->mdct_coef[ch], s->windowed_samples);
390
        }
391
    }
392
}
393

    
394

    
395
/**
396
 * Initialize stereo rematrixing.
397
 * If the strategy does not change for each frame, set the rematrixing flags.
398
 */
399
static void rematrixing_init(AC3EncodeContext *s)
400
{
401
    if (s->channel_mode == AC3_CHMODE_STEREO)
402
        s->rematrixing = AC3_REMATRIXING_SUMS;
403
    else
404
        s->rematrixing = AC3_REMATRIXING_NONE;
405
    /* NOTE: AC3_REMATRIXING_ALWAYS might be used in
406
             the future in conjunction with channel coupling. */
407

    
408
    if (s->rematrixing & AC3_REMATRIXING_IS_STATIC) {
409
        int flag = (s->rematrixing == AC3_REMATRIXING_ALWAYS);
410
        s->blocks[0].new_rematrixing_strategy = 1;
411
        memset(s->blocks[0].rematrixing_flags, flag,
412
               sizeof(s->blocks[0].rematrixing_flags));
413
    }
414
}
415

    
416

    
417
/**
418
 * Determine rematrixing flags for each block and band.
419
 */
420
static void compute_rematrixing_strategy(AC3EncodeContext *s)
421
{
422
    int nb_coefs;
423
    int blk, bnd, i;
424
    AC3Block *block, *block0;
425

    
426
    s->num_rematrixing_bands = 4;
427

    
428
    if (s->rematrixing & AC3_REMATRIXING_IS_STATIC)
429
        return;
430

    
431
    nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
432

    
433
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
434
        block = &s->blocks[blk];
435
        block->new_rematrixing_strategy = !blk;
436
        for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
437
            /* calculate calculate sum of squared coeffs for one band in one block */
438
            int start = ff_ac3_rematrix_band_tab[bnd];
439
            int end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
440
            CoefSumType sum[4] = {0,};
441
            for (i = start; i < end; i++) {
442
                CoefType lt = block->mdct_coef[0][i];
443
                CoefType rt = block->mdct_coef[1][i];
444
                CoefType md = lt + rt;
445
                CoefType sd = lt - rt;
446
                MAC_COEF(sum[0], lt, lt);
447
                MAC_COEF(sum[1], rt, rt);
448
                MAC_COEF(sum[2], md, md);
449
                MAC_COEF(sum[3], sd, sd);
450
            }
451

    
452
            /* compare sums to determine if rematrixing will be used for this band */
453
            if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
454
                block->rematrixing_flags[bnd] = 1;
455
            else
456
                block->rematrixing_flags[bnd] = 0;
457

    
458
            /* determine if new rematrixing flags will be sent */
459
            if (blk &&
460
                block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
461
                block->new_rematrixing_strategy = 1;
462
            }
463
        }
464
        block0 = block;
465
    }
466
}
467

    
468

    
469
/**
470
 * Apply stereo rematrixing to coefficients based on rematrixing flags.
471
 */
472
static void apply_rematrixing(AC3EncodeContext *s)
473
{
474
    int nb_coefs;
475
    int blk, bnd, i;
476
    int start, end;
477
    uint8_t *flags;
478

    
479
    if (s->rematrixing == AC3_REMATRIXING_NONE)
480
        return;
481

    
482
    nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
483

    
484
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
485
        AC3Block *block = &s->blocks[blk];
486
        if (block->new_rematrixing_strategy)
487
            flags = block->rematrixing_flags;
488
        for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
489
            if (flags[bnd]) {
490
                start = ff_ac3_rematrix_band_tab[bnd];
491
                end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
492
                for (i = start; i < end; i++) {
493
                    int32_t lt = block->fixed_coef[0][i];
494
                    int32_t rt = block->fixed_coef[1][i];
495
                    block->fixed_coef[0][i] = (lt + rt) >> 1;
496
                    block->fixed_coef[1][i] = (lt - rt) >> 1;
497
                }
498
            }
499
        }
500
    }
501
}
502

    
503

    
504
/**
505
 * Initialize exponent tables.
506
 */
507
static av_cold void exponent_init(AC3EncodeContext *s)
508
{
509
    int i;
510
    for (i = 73; i < 256; i++) {
511
        exponent_group_tab[0][i] = (i - 1) /  3;
512
        exponent_group_tab[1][i] = (i + 2) /  6;
513
        exponent_group_tab[2][i] = (i + 8) / 12;
514
    }
515
    /* LFE */
516
    exponent_group_tab[0][7] = 2;
517
}
518

    
519

    
520
/**
521
 * Extract exponents from the MDCT coefficients.
522
 * This takes into account the normalization that was done to the input samples
523
 * by adjusting the exponents by the exponent shift values.
524
 */
525
static void extract_exponents(AC3EncodeContext *s)
526
{
527
    int blk, ch, i;
528

    
529
    for (ch = 0; ch < s->channels; ch++) {
530
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
531
            AC3Block *block = &s->blocks[blk];
532
            uint8_t *exp   = block->exp[ch];
533
            int32_t *coef = block->fixed_coef[ch];
534
            for (i = 0; i < AC3_MAX_COEFS; i++) {
535
                int e;
536
                int v = abs(coef[i]);
537
                if (v == 0)
538
                    e = 24;
539
                else {
540
                    e = 23 - av_log2(v);
541
                    if (e >= 24) {
542
                        e = 24;
543
                        coef[i] = 0;
544
                    }
545
                    av_assert2(e >= 0);
546
                }
547
                exp[i] = e;
548
            }
549
        }
550
    }
551
}
552

    
553

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

    
560

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

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

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

    
600

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

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

    
620

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

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

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

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

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

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

    
686

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

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

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

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

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

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

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

    
728

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

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

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

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

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

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

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

    
784
    s->exponent_bits = bit_count;
785
}
786

    
787

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

    
797
    compute_exp_strategy(s);
798

    
799
    encode_exponents(s);
800

    
801
    group_exponents(s);
802

    
803
    emms_c();
804
}
805

    
806

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

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

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

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

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

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

    
857
    s->frame_bits_fixed = frame_bits;
858
}
859

    
860

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

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

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

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

    
890
    count_frame_bits_fixed(s);
891
}
892

    
893

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

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

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

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

    
929

    
930
/**
931
 * Calculate the number of bits needed to encode a set of mantissas.
932
 */
933
static int compute_mantissa_size(int mant_cnt[5], uint8_t *bap, int nb_coefs)
934
{
935
    int bits, b, i;
936

    
937
    bits = 0;
938
    for (i = 0; i < nb_coefs; i++) {
939
        b = bap[i];
940
        if (b <= 4) {
941
            // bap=1 to bap=4 will be counted in compute_mantissa_size_final
942
            mant_cnt[b]++;
943
        } else if (b <= 13) {
944
            // bap=5 to bap=13 use (bap-1) bits
945
            bits += b - 1;
946
        } else {
947
            // bap=14 uses 14 bits and bap=15 uses 16 bits
948
            bits += (b == 14) ? 14 : 16;
949
        }
950
    }
951
    return bits;
952
}
953

    
954

    
955
/**
956
 * Finalize the mantissa bit count by adding in the grouped mantissas.
957
 */
958
static int compute_mantissa_size_final(int mant_cnt[5])
959
{
960
    // bap=1 : 3 mantissas in 5 bits
961
    int bits = (mant_cnt[1] / 3) * 5;
962
    // bap=2 : 3 mantissas in 7 bits
963
    // bap=4 : 2 mantissas in 7 bits
964
    bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
965
    // bap=3 : each mantissa is 3 bits
966
    bits += mant_cnt[3] * 3;
967
    return bits;
968
}
969

    
970

    
971
/**
972
 * Calculate masking curve based on the final exponents.
973
 * Also calculate the power spectral densities to use in future calculations.
974
 */
975
static void bit_alloc_masking(AC3EncodeContext *s)
976
{
977
    int blk, ch;
978

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

    
1000

    
1001
/**
1002
 * Ensure that bap for each block and channel point to the current bap_buffer.
1003
 * They may have been switched during the bit allocation search.
1004
 */
1005
static void reset_block_bap(AC3EncodeContext *s)
1006
{
1007
    int blk, ch;
1008
    if (s->blocks[0].bap[0] == s->bap_buffer)
1009
        return;
1010
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1011
        for (ch = 0; ch < s->channels; ch++) {
1012
            s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
1013
        }
1014
    }
1015
}
1016

    
1017

    
1018
/**
1019
 * Run the bit allocation with a given SNR offset.
1020
 * This calculates the bit allocation pointers that will be used to determine
1021
 * the quantization of each mantissa.
1022
 * @return the number of bits needed for mantissas if the given SNR offset is
1023
 *         is used.
1024
 */
1025
static int bit_alloc(AC3EncodeContext *s, int snr_offset)
1026
{
1027
    int blk, ch;
1028
    int mantissa_bits;
1029
    int mant_cnt[5];
1030

    
1031
    snr_offset = (snr_offset - 240) << 2;
1032

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

    
1062

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

    
1073
    bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1074
    av_assert2(bits_left >= 0);
1075

    
1076
    snr_offset = s->coarse_snr_offset << 4;
1077

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

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

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

    
1103
    s->coarse_snr_offset = snr_offset >> 4;
1104
    for (ch = 0; ch < s->channels; ch++)
1105
        s->fine_snr_offset[ch] = snr_offset & 0xF;
1106

    
1107
    return 0;
1108
}
1109

    
1110

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

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

    
1151

    
1152
/**
1153
 * Reduce the bandwidth to reduce the number of bits used for a given SNR offset.
1154
 * This is a second fallback for when bit allocation still fails after exponents
1155
 * have been downgraded.
1156
 * @return non-zero if bandwidth reduction was unsuccessful
1157
 */
1158
static int reduce_bandwidth(AC3EncodeContext *s, int min_bw_code)
1159
{
1160
    int ch;
1161

    
1162
    if (s->bandwidth_code[0] > min_bw_code) {
1163
        for (ch = 0; ch < s->fbw_channels; ch++) {
1164
            s->bandwidth_code[ch]--;
1165
            s->nb_coefs[ch] = s->bandwidth_code[ch] * 3 + 73;
1166
        }
1167
        return 0;
1168
    }
1169
    return -1;
1170
}
1171

    
1172

    
1173
/**
1174
 * Perform bit allocation search.
1175
 * Finds the SNR offset value that maximizes quality and fits in the specified
1176
 * frame size.  Output is the SNR offset and a set of bit allocation pointers
1177
 * used to quantize the mantissas.
1178
 */
1179
static int compute_bit_allocation(AC3EncodeContext *s)
1180
{
1181
    int ret;
1182

    
1183
    count_frame_bits(s);
1184

    
1185
    bit_alloc_masking(s);
1186

    
1187
    ret = cbr_bit_allocation(s);
1188
    while (ret) {
1189
        /* fallback 1: downgrade exponents */
1190
        if (!downgrade_exponents(s)) {
1191
            extract_exponents(s);
1192
            encode_exponents(s);
1193
            group_exponents(s);
1194
            ret = compute_bit_allocation(s);
1195
            continue;
1196
        }
1197

    
1198
        /* fallback 2: reduce bandwidth */
1199
        /* only do this if the user has not specified a specific cutoff
1200
           frequency */
1201
        if (!s->cutoff && !reduce_bandwidth(s, 0)) {
1202
            process_exponents(s);
1203
            ret = compute_bit_allocation(s);
1204
            continue;
1205
        }
1206

    
1207
        /* fallbacks were not enough... */
1208
        break;
1209
    }
1210

    
1211
    return ret;
1212
}
1213

    
1214

    
1215
/**
1216
 * Symmetric quantization on 'levels' levels.
1217
 */
1218
static inline int sym_quant(int c, int e, int levels)
1219
{
1220
    int v = ((((levels * c) >> (24 - e)) + 1) >> 1) + (levels >> 1);
1221
    av_assert2(v >= 0 && v < levels);
1222
    return v;
1223
}
1224

    
1225

    
1226
/**
1227
 * Asymmetric quantization on 2^qbits levels.
1228
 */
1229
static inline int asym_quant(int c, int e, int qbits)
1230
{
1231
    int lshift, m, v;
1232

    
1233
    lshift = e + qbits - 24;
1234
    if (lshift >= 0)
1235
        v = c << lshift;
1236
    else
1237
        v = c >> (-lshift);
1238
    /* rounding */
1239
    v = (v + 1) >> 1;
1240
    m = (1 << (qbits-1));
1241
    if (v >= m)
1242
        v = m - 1;
1243
    av_assert2(v >= -m);
1244
    return v & ((1 << qbits)-1);
1245
}
1246

    
1247

    
1248
/**
1249
 * Quantize a set of mantissas for a single channel in a single block.
1250
 */
1251
static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1252
                                      uint8_t *exp,
1253
                                      uint8_t *bap, uint16_t *qmant, int n)
1254
{
1255
    int i;
1256

    
1257
    for (i = 0; i < n; i++) {
1258
        int v;
1259
        int c = fixed_coef[i];
1260
        int e = exp[i];
1261
        int b = bap[i];
1262
        switch (b) {
1263
        case 0:
1264
            v = 0;
1265
            break;
1266
        case 1:
1267
            v = sym_quant(c, e, 3);
1268
            switch (s->mant1_cnt) {
1269
            case 0:
1270
                s->qmant1_ptr = &qmant[i];
1271
                v = 9 * v;
1272
                s->mant1_cnt = 1;
1273
                break;
1274
            case 1:
1275
                *s->qmant1_ptr += 3 * v;
1276
                s->mant1_cnt = 2;
1277
                v = 128;
1278
                break;
1279
            default:
1280
                *s->qmant1_ptr += v;
1281
                s->mant1_cnt = 0;
1282
                v = 128;
1283
                break;
1284
            }
1285
            break;
1286
        case 2:
1287
            v = sym_quant(c, e, 5);
1288
            switch (s->mant2_cnt) {
1289
            case 0:
1290
                s->qmant2_ptr = &qmant[i];
1291
                v = 25 * v;
1292
                s->mant2_cnt = 1;
1293
                break;
1294
            case 1:
1295
                *s->qmant2_ptr += 5 * v;
1296
                s->mant2_cnt = 2;
1297
                v = 128;
1298
                break;
1299
            default:
1300
                *s->qmant2_ptr += v;
1301
                s->mant2_cnt = 0;
1302
                v = 128;
1303
                break;
1304
            }
1305
            break;
1306
        case 3:
1307
            v = sym_quant(c, e, 7);
1308
            break;
1309
        case 4:
1310
            v = sym_quant(c, e, 11);
1311
            switch (s->mant4_cnt) {
1312
            case 0:
1313
                s->qmant4_ptr = &qmant[i];
1314
                v = 11 * v;
1315
                s->mant4_cnt = 1;
1316
                break;
1317
            default:
1318
                *s->qmant4_ptr += v;
1319
                s->mant4_cnt = 0;
1320
                v = 128;
1321
                break;
1322
            }
1323
            break;
1324
        case 5:
1325
            v = sym_quant(c, e, 15);
1326
            break;
1327
        case 14:
1328
            v = asym_quant(c, e, 14);
1329
            break;
1330
        case 15:
1331
            v = asym_quant(c, e, 16);
1332
            break;
1333
        default:
1334
            v = asym_quant(c, e, b - 1);
1335
            break;
1336
        }
1337
        qmant[i] = v;
1338
    }
1339
}
1340

    
1341

    
1342
/**
1343
 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1344
 */
1345
static void quantize_mantissas(AC3EncodeContext *s)
1346
{
1347
    int blk, ch;
1348

    
1349

    
1350
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1351
        AC3Block *block = &s->blocks[blk];
1352
        AC3Block *ref_block;
1353
        AC3Mant m = { 0 };
1354

    
1355
        for (ch = 0; ch < s->channels; ch++) {
1356
            ref_block = block->exp_ref_block[ch];
1357
            quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1358
                                      ref_block->exp[ch], ref_block->bap[ch],
1359
                                      block->qmant[ch], s->nb_coefs[ch]);
1360
        }
1361
    }
1362
}
1363

    
1364

    
1365
/**
1366
 * Write the AC-3 frame header to the output bitstream.
1367
 */
1368
static void output_frame_header(AC3EncodeContext *s)
1369
{
1370
    AC3EncOptions *opt = &s->options;
1371

    
1372
    put_bits(&s->pb, 16, 0x0b77);   /* frame header */
1373
    put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
1374
    put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
1375
    put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1376
    put_bits(&s->pb, 5,  s->bitstream_id);
1377
    put_bits(&s->pb, 3,  s->bitstream_mode);
1378
    put_bits(&s->pb, 3,  s->channel_mode);
1379
    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1380
        put_bits(&s->pb, 2, s->center_mix_level);
1381
    if (s->channel_mode & 0x04)
1382
        put_bits(&s->pb, 2, s->surround_mix_level);
1383
    if (s->channel_mode == AC3_CHMODE_STEREO)
1384
        put_bits(&s->pb, 2, opt->dolby_surround_mode);
1385
    put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1386
    put_bits(&s->pb, 5, -opt->dialogue_level);
1387
    put_bits(&s->pb, 1, 0);         /* no compression control word */
1388
    put_bits(&s->pb, 1, 0);         /* no lang code */
1389
    put_bits(&s->pb, 1, opt->audio_production_info);
1390
    if (opt->audio_production_info) {
1391
        put_bits(&s->pb, 5, opt->mixing_level - 80);
1392
        put_bits(&s->pb, 2, opt->room_type);
1393
    }
1394
    put_bits(&s->pb, 1, opt->copyright);
1395
    put_bits(&s->pb, 1, opt->original);
1396
    if (s->bitstream_id == 6) {
1397
        /* alternate bit stream syntax */
1398
        put_bits(&s->pb, 1, opt->extended_bsi_1);
1399
        if (opt->extended_bsi_1) {
1400
            put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1401
            put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1402
            put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1403
            put_bits(&s->pb, 3, s->loro_center_mix_level);
1404
            put_bits(&s->pb, 3, s->loro_surround_mix_level);
1405
        }
1406
        put_bits(&s->pb, 1, opt->extended_bsi_2);
1407
        if (opt->extended_bsi_2) {
1408
            put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1409
            put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1410
            put_bits(&s->pb, 1, opt->ad_converter_type);
1411
            put_bits(&s->pb, 9, 0);     /* xbsi2 and encinfo : reserved */
1412
        }
1413
    } else {
1414
    put_bits(&s->pb, 1, 0);         /* no time code 1 */
1415
    put_bits(&s->pb, 1, 0);         /* no time code 2 */
1416
    }
1417
    put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
1418
}
1419

    
1420

    
1421
/**
1422
 * Write one audio block to the output bitstream.
1423
 */
1424
static void output_audio_block(AC3EncodeContext *s, int blk)
1425
{
1426
    int ch, i, baie, rbnd;
1427
    AC3Block *block = &s->blocks[blk];
1428

    
1429
    /* block switching */
1430
    for (ch = 0; ch < s->fbw_channels; ch++)
1431
        put_bits(&s->pb, 1, 0);
1432

    
1433
    /* dither flags */
1434
    for (ch = 0; ch < s->fbw_channels; ch++)
1435
        put_bits(&s->pb, 1, 1);
1436

    
1437
    /* dynamic range codes */
1438
    put_bits(&s->pb, 1, 0);
1439

    
1440
    /* channel coupling */
1441
    if (!blk) {
1442
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
1443
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
1444
    } else {
1445
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1446
    }
1447

    
1448
    /* stereo rematrixing */
1449
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1450
        put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1451
        if (block->new_rematrixing_strategy) {
1452
            /* rematrixing flags */
1453
            for (rbnd = 0; rbnd < s->num_rematrixing_bands; rbnd++)
1454
                put_bits(&s->pb, 1, block->rematrixing_flags[rbnd]);
1455
        }
1456
    }
1457

    
1458
    /* exponent strategy */
1459
    for (ch = 0; ch < s->fbw_channels; ch++)
1460
        put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1461
    if (s->lfe_on)
1462
        put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1463

    
1464
    /* bandwidth */
1465
    for (ch = 0; ch < s->fbw_channels; ch++) {
1466
        if (s->exp_strategy[ch][blk] != EXP_REUSE)
1467
            put_bits(&s->pb, 6, s->bandwidth_code[ch]);
1468
    }
1469

    
1470
    /* exponents */
1471
    for (ch = 0; ch < s->channels; ch++) {
1472
        int nb_groups;
1473

    
1474
        if (s->exp_strategy[ch][blk] == EXP_REUSE)
1475
            continue;
1476

    
1477
        /* DC exponent */
1478
        put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1479

    
1480
        /* exponent groups */
1481
        nb_groups = exponent_group_tab[s->exp_strategy[ch][blk]-1][s->nb_coefs[ch]];
1482
        for (i = 1; i <= nb_groups; i++)
1483
            put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1484

    
1485
        /* gain range info */
1486
        if (ch != s->lfe_channel)
1487
            put_bits(&s->pb, 2, 0);
1488
    }
1489

    
1490
    /* bit allocation info */
1491
    baie = (blk == 0);
1492
    put_bits(&s->pb, 1, baie);
1493
    if (baie) {
1494
        put_bits(&s->pb, 2, s->slow_decay_code);
1495
        put_bits(&s->pb, 2, s->fast_decay_code);
1496
        put_bits(&s->pb, 2, s->slow_gain_code);
1497
        put_bits(&s->pb, 2, s->db_per_bit_code);
1498
        put_bits(&s->pb, 3, s->floor_code);
1499
    }
1500

    
1501
    /* snr offset */
1502
    put_bits(&s->pb, 1, baie);
1503
    if (baie) {
1504
        put_bits(&s->pb, 6, s->coarse_snr_offset);
1505
        for (ch = 0; ch < s->channels; ch++) {
1506
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1507
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1508
        }
1509
    }
1510

    
1511
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1512
    put_bits(&s->pb, 1, 0); /* no data to skip */
1513

    
1514
    /* mantissas */
1515
    for (ch = 0; ch < s->channels; ch++) {
1516
        int b, q;
1517
        AC3Block *ref_block = block->exp_ref_block[ch];
1518
        for (i = 0; i < s->nb_coefs[ch]; i++) {
1519
            q = block->qmant[ch][i];
1520
            b = ref_block->bap[ch][i];
1521
            switch (b) {
1522
            case 0:                                         break;
1523
            case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
1524
            case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
1525
            case 3:               put_bits(&s->pb,   3, q); break;
1526
            case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
1527
            case 14:              put_bits(&s->pb,  14, q); break;
1528
            case 15:              put_bits(&s->pb,  16, q); break;
1529
            default:              put_bits(&s->pb, b-1, q); break;
1530
            }
1531
        }
1532
    }
1533
}
1534

    
1535

    
1536
/** CRC-16 Polynomial */
1537
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1538

    
1539

    
1540
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1541
{
1542
    unsigned int c;
1543

    
1544
    c = 0;
1545
    while (a) {
1546
        if (a & 1)
1547
            c ^= b;
1548
        a = a >> 1;
1549
        b = b << 1;
1550
        if (b & (1 << 16))
1551
            b ^= poly;
1552
    }
1553
    return c;
1554
}
1555

    
1556

    
1557
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1558
{
1559
    unsigned int r;
1560
    r = 1;
1561
    while (n) {
1562
        if (n & 1)
1563
            r = mul_poly(r, a, poly);
1564
        a = mul_poly(a, a, poly);
1565
        n >>= 1;
1566
    }
1567
    return r;
1568
}
1569

    
1570

    
1571
/**
1572
 * Fill the end of the frame with 0's and compute the two CRCs.
1573
 */
1574
static void output_frame_end(AC3EncodeContext *s)
1575
{
1576
    const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1577
    int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1578
    uint8_t *frame;
1579

    
1580
    frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1581

    
1582
    /* pad the remainder of the frame with zeros */
1583
    av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1584
    flush_put_bits(&s->pb);
1585
    frame = s->pb.buf;
1586
    pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1587
    av_assert2(pad_bytes >= 0);
1588
    if (pad_bytes > 0)
1589
        memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1590

    
1591
    /* compute crc1 */
1592
    /* this is not so easy because it is at the beginning of the data... */
1593
    crc1    = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1594
    crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1595
    crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1596
    AV_WB16(frame + 2, crc1);
1597

    
1598
    /* compute crc2 */
1599
    crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1600
                          s->frame_size - frame_size_58 - 3);
1601
    crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1602
    /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1603
    if (crc2 == 0x770B) {
1604
        frame[s->frame_size - 3] ^= 0x1;
1605
        crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1606
    }
1607
    crc2 = av_bswap16(crc2);
1608
    AV_WB16(frame + s->frame_size - 2, crc2);
1609
}
1610

    
1611

    
1612
/**
1613
 * Write the frame to the output bitstream.
1614
 */
1615
static void output_frame(AC3EncodeContext *s, unsigned char *frame)
1616
{
1617
    int blk;
1618

    
1619
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1620

    
1621
    output_frame_header(s);
1622

    
1623
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1624
        output_audio_block(s, blk);
1625

    
1626
    output_frame_end(s);
1627
}
1628

    
1629

    
1630
static void dprint_options(AVCodecContext *avctx)
1631
{
1632
#ifdef DEBUG
1633
    AC3EncodeContext *s = avctx->priv_data;
1634
    AC3EncOptions *opt = &s->options;
1635
    char strbuf[32];
1636

    
1637
    switch (s->bitstream_id) {
1638
    case  6:  strncpy(strbuf, "AC-3 (alt syntax)", 32);      break;
1639
    case  8:  strncpy(strbuf, "AC-3 (standard)", 32);        break;
1640
    case  9:  strncpy(strbuf, "AC-3 (dnet half-rate)", 32);  break;
1641
    case 10:  strncpy(strbuf, "AC-3 (dnet quater-rate", 32); break;
1642
    default: snprintf(strbuf, 32, "ERROR");
1643
    }
1644
    av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
1645
    av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
1646
    av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
1647
    av_dlog(avctx, "channel_layout: %s\n", strbuf);
1648
    av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
1649
    av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
1650
    if (s->cutoff)
1651
        av_dlog(avctx, "cutoff: %d\n", s->cutoff);
1652

    
1653
    av_dlog(avctx, "per_frame_metadata: %s\n",
1654
            opt->allow_per_frame_metadata?"on":"off");
1655
    if (s->has_center)
1656
        av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
1657
                s->center_mix_level);
1658
    else
1659
        av_dlog(avctx, "center_mixlev: {not written}\n");
1660
    if (s->has_surround)
1661
        av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
1662
                s->surround_mix_level);
1663
    else
1664
        av_dlog(avctx, "surround_mixlev: {not written}\n");
1665
    if (opt->audio_production_info) {
1666
        av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
1667
        switch (opt->room_type) {
1668
        case 0:  strncpy(strbuf, "notindicated", 32); break;
1669
        case 1:  strncpy(strbuf, "large", 32);        break;
1670
        case 2:  strncpy(strbuf, "small", 32);        break;
1671
        default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
1672
        }
1673
        av_dlog(avctx, "room_type: %s\n", strbuf);
1674
    } else {
1675
        av_dlog(avctx, "mixing_level: {not written}\n");
1676
        av_dlog(avctx, "room_type: {not written}\n");
1677
    }
1678
    av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
1679
    av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
1680
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1681
        switch (opt->dolby_surround_mode) {
1682
        case 0:  strncpy(strbuf, "notindicated", 32); break;
1683
        case 1:  strncpy(strbuf, "on", 32);           break;
1684
        case 2:  strncpy(strbuf, "off", 32);          break;
1685
        default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
1686
        }
1687
        av_dlog(avctx, "dsur_mode: %s\n", strbuf);
1688
    } else {
1689
        av_dlog(avctx, "dsur_mode: {not written}\n");
1690
    }
1691
    av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
1692

    
1693
    if (s->bitstream_id == 6) {
1694
        if (opt->extended_bsi_1) {
1695
            switch (opt->preferred_stereo_downmix) {
1696
            case 0:  strncpy(strbuf, "notindicated", 32); break;
1697
            case 1:  strncpy(strbuf, "ltrt", 32);         break;
1698
            case 2:  strncpy(strbuf, "loro", 32);         break;
1699
            default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
1700
            }
1701
            av_dlog(avctx, "dmix_mode: %s\n", strbuf);
1702
            av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
1703
                    opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
1704
            av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
1705
                    opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
1706
            av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
1707
                    opt->loro_center_mix_level, s->loro_center_mix_level);
1708
            av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
1709
                    opt->loro_surround_mix_level, s->loro_surround_mix_level);
1710
        } else {
1711
            av_dlog(avctx, "extended bitstream info 1: {not written}\n");
1712
        }
1713
        if (opt->extended_bsi_2) {
1714
            switch (opt->dolby_surround_ex_mode) {
1715
            case 0:  strncpy(strbuf, "notindicated", 32); break;
1716
            case 1:  strncpy(strbuf, "on", 32);           break;
1717
            case 2:  strncpy(strbuf, "off", 32);          break;
1718
            default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
1719
            }
1720
            av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
1721
            switch (opt->dolby_headphone_mode) {
1722
            case 0:  strncpy(strbuf, "notindicated", 32); break;
1723
            case 1:  strncpy(strbuf, "on", 32);           break;
1724
            case 2:  strncpy(strbuf, "off", 32);          break;
1725
            default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
1726
            }
1727
            av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
1728

    
1729
            switch (opt->ad_converter_type) {
1730
            case 0:  strncpy(strbuf, "standard", 32); break;
1731
            case 1:  strncpy(strbuf, "hdcd", 32);     break;
1732
            default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
1733
            }
1734
            av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
1735
        } else {
1736
            av_dlog(avctx, "extended bitstream info 2: {not written}\n");
1737
        }
1738
    }
1739
#endif
1740
}
1741

    
1742

    
1743
#define FLT_OPTION_THRESHOLD 0.01
1744

    
1745
static int validate_float_option(float v, const float *v_list, int v_list_size)
1746
{
1747
    int i;
1748

    
1749
    for (i = 0; i < v_list_size; i++) {
1750
        if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
1751
            v > (v_list[i] - FLT_OPTION_THRESHOLD))
1752
            break;
1753
    }
1754
    if (i == v_list_size)
1755
        return -1;
1756

    
1757
    return i;
1758
}
1759

    
1760

    
1761
static void validate_mix_level(void *log_ctx, const char *opt_name,
1762
                               float *opt_param, const float *list,
1763
                               int list_size, int default_value, int min_value,
1764
                               int *ctx_param)
1765
{
1766
    int mixlev = validate_float_option(*opt_param, list, list_size);
1767
    if (mixlev < min_value) {
1768
        mixlev = default_value;
1769
        if (*opt_param >= 0.0) {
1770
            av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
1771
                   "default value: %0.3f\n", opt_name, list[mixlev]);
1772
        }
1773
    }
1774
    *opt_param = list[mixlev];
1775
    *ctx_param = mixlev;
1776
}
1777

    
1778

    
1779
/**
1780
 * Validate metadata options as set by AVOption system.
1781
 * These values can optionally be changed per-frame.
1782
 */
1783
static int validate_metadata(AVCodecContext *avctx)
1784
{
1785
    AC3EncodeContext *s = avctx->priv_data;
1786
    AC3EncOptions *opt = &s->options;
1787

    
1788
    /* validate mixing levels */
1789
    if (s->has_center) {
1790
        validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
1791
                           cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
1792
                           &s->center_mix_level);
1793
    }
1794
    if (s->has_surround) {
1795
        validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
1796
                           surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
1797
                           &s->surround_mix_level);
1798
    }
1799

    
1800
    /* set audio production info flag */
1801
    if (opt->mixing_level >= 0 || opt->room_type >= 0) {
1802
        if (opt->mixing_level < 0) {
1803
            av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
1804
                   "room_type is set\n");
1805
            return AVERROR(EINVAL);
1806
        }
1807
        if (opt->mixing_level < 80) {
1808
            av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
1809
                   "80dB and 111dB\n");
1810
            return AVERROR(EINVAL);
1811
        }
1812
        /* default room type */
1813
        if (opt->room_type < 0)
1814
            opt->room_type = 0;
1815
        opt->audio_production_info = 1;
1816
    } else {
1817
        opt->audio_production_info = 0;
1818
    }
1819

    
1820
    /* set extended bsi 1 flag */
1821
    if ((s->has_center || s->has_surround) &&
1822
        (opt->preferred_stereo_downmix >= 0 ||
1823
         opt->ltrt_center_mix_level   >= 0 ||
1824
         opt->ltrt_surround_mix_level >= 0 ||
1825
         opt->loro_center_mix_level   >= 0 ||
1826
         opt->loro_surround_mix_level >= 0)) {
1827
        /* default preferred stereo downmix */
1828
        if (opt->preferred_stereo_downmix < 0)
1829
            opt->preferred_stereo_downmix = 0;
1830
        /* validate Lt/Rt center mix level */
1831
        validate_mix_level(avctx, "ltrt_center_mix_level",
1832
                           &opt->ltrt_center_mix_level, extmixlev_options,
1833
                           EXTMIXLEV_NUM_OPTIONS, 5, 0,
1834
                           &s->ltrt_center_mix_level);
1835
        /* validate Lt/Rt surround mix level */
1836
        validate_mix_level(avctx, "ltrt_surround_mix_level",
1837
                           &opt->ltrt_surround_mix_level, extmixlev_options,
1838
                           EXTMIXLEV_NUM_OPTIONS, 6, 3,
1839
                           &s->ltrt_surround_mix_level);
1840
        /* validate Lo/Ro center mix level */
1841
        validate_mix_level(avctx, "loro_center_mix_level",
1842
                           &opt->loro_center_mix_level, extmixlev_options,
1843
                           EXTMIXLEV_NUM_OPTIONS, 5, 0,
1844
                           &s->loro_center_mix_level);
1845
        /* validate Lo/Ro surround mix level */
1846
        validate_mix_level(avctx, "loro_surround_mix_level",
1847
                           &opt->loro_surround_mix_level, extmixlev_options,
1848
                           EXTMIXLEV_NUM_OPTIONS, 6, 3,
1849
                           &s->loro_surround_mix_level);
1850
        opt->extended_bsi_1 = 1;
1851
    } else {
1852
        opt->extended_bsi_1 = 0;
1853
    }
1854

    
1855
    /* set extended bsi 2 flag */
1856
    if (opt->dolby_surround_ex_mode >= 0 ||
1857
        opt->dolby_headphone_mode   >= 0 ||
1858
        opt->ad_converter_type      >= 0) {
1859
        /* default dolby surround ex mode */
1860
        if (opt->dolby_surround_ex_mode < 0)
1861
            opt->dolby_surround_ex_mode = 0;
1862
        /* default dolby headphone mode */
1863
        if (opt->dolby_headphone_mode < 0)
1864
            opt->dolby_headphone_mode = 0;
1865
        /* default A/D converter type */
1866
        if (opt->ad_converter_type < 0)
1867
            opt->ad_converter_type = 0;
1868
        opt->extended_bsi_2 = 1;
1869
    } else {
1870
        opt->extended_bsi_2 = 0;
1871
    }
1872

    
1873
    /* set bitstream id for alternate bitstream syntax */
1874
    if (opt->extended_bsi_1 || opt->extended_bsi_2) {
1875
        if (s->bitstream_id > 8 && s->bitstream_id < 11) {
1876
            static int warn_once = 1;
1877
            if (warn_once) {
1878
                av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
1879
                       "not compatible with reduced samplerates. writing of "
1880
                       "extended bitstream information will be disabled.\n");
1881
                warn_once = 0;
1882
            }
1883
        } else {
1884
            s->bitstream_id = 6;
1885
        }
1886
    }
1887

    
1888
    return 0;
1889
}
1890

    
1891

    
1892
/**
1893
 * Encode a single AC-3 frame.
1894
 */
1895
static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
1896
                            int buf_size, void *data)
1897
{
1898
    AC3EncodeContext *s = avctx->priv_data;
1899
    const SampleType *samples = data;
1900
    int ret;
1901

    
1902
    if (s->options.allow_per_frame_metadata) {
1903
        ret = validate_metadata(avctx);
1904
        if (ret)
1905
            return ret;
1906
    }
1907

    
1908
    if (s->bit_alloc.sr_code == 1)
1909
        adjust_frame_size(s);
1910

    
1911
    deinterleave_input_samples(s, samples);
1912

    
1913
    apply_mdct(s);
1914

    
1915
    scale_coefficients(s);
1916

    
1917
    compute_rematrixing_strategy(s);
1918

    
1919
    apply_rematrixing(s);
1920

    
1921
    process_exponents(s);
1922

    
1923
    ret = compute_bit_allocation(s);
1924
    if (ret) {
1925
        av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1926
        return ret;
1927
    }
1928

    
1929
    quantize_mantissas(s);
1930

    
1931
    output_frame(s, frame);
1932

    
1933
    return s->frame_size;
1934
}
1935

    
1936

    
1937
/**
1938
 * Finalize encoding and free any memory allocated by the encoder.
1939
 */
1940
static av_cold int ac3_encode_close(AVCodecContext *avctx)
1941
{
1942
    int blk, ch;
1943
    AC3EncodeContext *s = avctx->priv_data;
1944

    
1945
    for (ch = 0; ch < s->channels; ch++)
1946
        av_freep(&s->planar_samples[ch]);
1947
    av_freep(&s->planar_samples);
1948
    av_freep(&s->bap_buffer);
1949
    av_freep(&s->bap1_buffer);
1950
    av_freep(&s->mdct_coef_buffer);
1951
    av_freep(&s->fixed_coef_buffer);
1952
    av_freep(&s->exp_buffer);
1953
    av_freep(&s->grouped_exp_buffer);
1954
    av_freep(&s->psd_buffer);
1955
    av_freep(&s->band_psd_buffer);
1956
    av_freep(&s->mask_buffer);
1957
    av_freep(&s->qmant_buffer);
1958
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1959
        AC3Block *block = &s->blocks[blk];
1960
        av_freep(&block->bap);
1961
        av_freep(&block->mdct_coef);
1962
        av_freep(&block->fixed_coef);
1963
        av_freep(&block->exp);
1964
        av_freep(&block->grouped_exp);
1965
        av_freep(&block->psd);
1966
        av_freep(&block->band_psd);
1967
        av_freep(&block->mask);
1968
        av_freep(&block->qmant);
1969
    }
1970

    
1971
    mdct_end(&s->mdct);
1972

    
1973
    av_freep(&avctx->coded_frame);
1974
    return 0;
1975
}
1976

    
1977

    
1978
/**
1979
 * Set channel information during initialization.
1980
 */
1981
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1982
                                    int64_t *channel_layout)
1983
{
1984
    int ch_layout;
1985

    
1986
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
1987
        return AVERROR(EINVAL);
1988
    if ((uint64_t)*channel_layout > 0x7FF)
1989
        return AVERROR(EINVAL);
1990
    ch_layout = *channel_layout;
1991
    if (!ch_layout)
1992
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1993
    if (av_get_channel_layout_nb_channels(ch_layout) != channels)
1994
        return AVERROR(EINVAL);
1995

    
1996
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1997
    s->channels     = channels;
1998
    s->fbw_channels = channels - s->lfe_on;
1999
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
2000
    if (s->lfe_on)
2001
        ch_layout -= AV_CH_LOW_FREQUENCY;
2002

    
2003
    switch (ch_layout) {
2004
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
2005
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
2006
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
2007
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
2008
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
2009
    case AV_CH_LAYOUT_QUAD:
2010
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
2011
    case AV_CH_LAYOUT_5POINT0:
2012
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
2013
    default:
2014
        return AVERROR(EINVAL);
2015
    }
2016
    s->has_center   = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
2017
    s->has_surround =  s->channel_mode & 0x04;
2018

    
2019
    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
2020
    *channel_layout = ch_layout;
2021
    if (s->lfe_on)
2022
        *channel_layout |= AV_CH_LOW_FREQUENCY;
2023

    
2024
    return 0;
2025
}
2026

    
2027

    
2028
static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
2029
{
2030
    int i, ret;
2031

    
2032
    /* validate channel layout */
2033
    if (!avctx->channel_layout) {
2034
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
2035
                                      "encoder will guess the layout, but it "
2036
                                      "might be incorrect.\n");
2037
    }
2038
    ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
2039
    if (ret) {
2040
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
2041
        return ret;
2042
    }
2043

    
2044
    /* validate sample rate */
2045
    for (i = 0; i < 9; i++) {
2046
        if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
2047
            break;
2048
    }
2049
    if (i == 9) {
2050
        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
2051
        return AVERROR(EINVAL);
2052
    }
2053
    s->sample_rate        = avctx->sample_rate;
2054
    s->bit_alloc.sr_shift = i % 3;
2055
    s->bit_alloc.sr_code  = i / 3;
2056
    s->bitstream_id       = 8 + s->bit_alloc.sr_shift;
2057

    
2058
    /* validate bit rate */
2059
    for (i = 0; i < 19; i++) {
2060
        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
2061
            break;
2062
    }
2063
    if (i == 19) {
2064
        av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2065
        return AVERROR(EINVAL);
2066
    }
2067
    s->bit_rate        = avctx->bit_rate;
2068
    s->frame_size_code = i << 1;
2069

    
2070
    /* validate cutoff */
2071
    if (avctx->cutoff < 0) {
2072
        av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2073
        return AVERROR(EINVAL);
2074
    }
2075
    s->cutoff = avctx->cutoff;
2076
    if (s->cutoff > (s->sample_rate >> 1))
2077
        s->cutoff = s->sample_rate >> 1;
2078

    
2079
    /* validate audio service type / channels combination */
2080
    if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
2081
         avctx->channels == 1) ||
2082
        ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
2083
          avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY  ||
2084
          avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
2085
         && avctx->channels > 1)) {
2086
        av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
2087
                                    "specified number of channels\n");
2088
        return AVERROR(EINVAL);
2089
    }
2090

    
2091
    ret = validate_metadata(avctx);
2092
    if (ret)
2093
        return ret;
2094

    
2095
    return 0;
2096
}
2097

    
2098

    
2099
/**
2100
 * Set bandwidth for all channels.
2101
 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2102
 * default value will be used.
2103
 */
2104
static av_cold void set_bandwidth(AC3EncodeContext *s)
2105
{
2106
    int ch, bw_code;
2107

    
2108
    if (s->cutoff) {
2109
        /* calculate bandwidth based on user-specified cutoff frequency */
2110
        int fbw_coeffs;
2111
        fbw_coeffs     = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2112
        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2113
    } else {
2114
        /* use default bandwidth setting */
2115
        /* XXX: should compute the bandwidth according to the frame
2116
           size, so that we avoid annoying high frequency artifacts */
2117
        bw_code = 50;
2118
    }
2119

    
2120
    /* set number of coefficients for each channel */
2121
    for (ch = 0; ch < s->fbw_channels; ch++) {
2122
        s->bandwidth_code[ch] = bw_code;
2123
        s->nb_coefs[ch]       = bw_code * 3 + 73;
2124
    }
2125
    if (s->lfe_on)
2126
        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
2127
}
2128

    
2129

    
2130
static av_cold int allocate_buffers(AVCodecContext *avctx)
2131
{
2132
    int blk, ch;
2133
    AC3EncodeContext *s = avctx->priv_data;
2134

    
2135
    FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
2136
                     alloc_fail);
2137
    for (ch = 0; ch < s->channels; ch++) {
2138
        FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
2139
                          (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
2140
                          alloc_fail);
2141
    }
2142
    FF_ALLOC_OR_GOTO(avctx, s->bap_buffer,  AC3_MAX_BLOCKS * s->channels *
2143
                     AC3_MAX_COEFS * sizeof(*s->bap_buffer),  alloc_fail);
2144
    FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
2145
                     AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
2146
    FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
2147
                     AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
2148
    FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
2149
                     AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
2150
    FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
2151
                     128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
2152
    FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
2153
                     AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
2154
    FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
2155
                     64 * sizeof(*s->band_psd_buffer), alloc_fail);
2156
    FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
2157
                     64 * sizeof(*s->mask_buffer), alloc_fail);
2158
    FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
2159
                     AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
2160
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2161
        AC3Block *block = &s->blocks[blk];
2162
        FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
2163
                         alloc_fail);
2164
        FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
2165
                          alloc_fail);
2166
        FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
2167
                          alloc_fail);
2168
        FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
2169
                          alloc_fail);
2170
        FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
2171
                          alloc_fail);
2172
        FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
2173
                          alloc_fail);
2174
        FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
2175
                          alloc_fail);
2176
        FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
2177
                          alloc_fail);
2178

    
2179
        for (ch = 0; ch < s->channels; ch++) {
2180
            /* arrangement: block, channel, coeff */
2181
            block->bap[ch]         = &s->bap_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
2182
            block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (blk * s->channels + ch)];
2183
            block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * s->channels + ch)];
2184
            block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
2185
            block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * s->channels + ch)];
2186
            block->mask[ch]        = &s->mask_buffer       [64            * (blk * s->channels + ch)];
2187
            block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * s->channels + ch)];
2188

    
2189
            /* arrangement: channel, block, coeff */
2190
            block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2191
        }
2192
    }
2193

    
2194
    if (CONFIG_AC3ENC_FLOAT) {
2195
        FF_ALLOC_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * s->channels *
2196
                         AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
2197
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2198
            AC3Block *block = &s->blocks[blk];
2199
            FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2200
                              sizeof(*block->fixed_coef), alloc_fail);
2201
            for (ch = 0; ch < s->channels; ch++)
2202
                block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
2203
        }
2204
    } else {
2205
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2206
            AC3Block *block = &s->blocks[blk];
2207
            FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2208
                              sizeof(*block->fixed_coef), alloc_fail);
2209
            for (ch = 0; ch < s->channels; ch++)
2210
                block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2211
        }
2212
    }
2213

    
2214
    return 0;
2215
alloc_fail:
2216
    return AVERROR(ENOMEM);
2217
}
2218

    
2219

    
2220
/**
2221
 * Initialize the encoder.
2222
 */
2223
static av_cold int ac3_encode_init(AVCodecContext *avctx)
2224
{
2225
    AC3EncodeContext *s = avctx->priv_data;
2226
    int ret, frame_size_58;
2227

    
2228
    avctx->frame_size = AC3_FRAME_SIZE;
2229

    
2230
    ff_ac3_common_init();
2231

    
2232
    ret = validate_options(avctx, s);
2233
    if (ret)
2234
        return ret;
2235

    
2236
    s->bitstream_mode = avctx->audio_service_type;
2237
    if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2238
        s->bitstream_mode = 0x7;
2239

    
2240
    s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2241
    s->bits_written    = 0;
2242
    s->samples_written = 0;
2243
    s->frame_size      = s->frame_size_min;
2244

    
2245
    /* calculate crc_inv for both possible frame sizes */
2246
    frame_size_58 = (( s->frame_size    >> 2) + ( s->frame_size    >> 4)) << 1;
2247
    s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2248
    if (s->bit_alloc.sr_code == 1) {
2249
        frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2250
        s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2251
    }
2252

    
2253
    set_bandwidth(s);
2254

    
2255
    rematrixing_init(s);
2256

    
2257
    exponent_init(s);
2258

    
2259
    bit_alloc_init(s);
2260

    
2261
    ret = mdct_init(avctx, &s->mdct, 9);
2262
    if (ret)
2263
        goto init_fail;
2264

    
2265
    ret = allocate_buffers(avctx);
2266
    if (ret)
2267
        goto init_fail;
2268

    
2269
    avctx->coded_frame= avcodec_alloc_frame();
2270

    
2271
    dsputil_init(&s->dsp, avctx);
2272
    ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2273

    
2274
    dprint_options(avctx);
2275

    
2276
    return 0;
2277
init_fail:
2278
    ac3_encode_close(avctx);
2279
    return ret;
2280
}