Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ 991f3de1

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
} AC3Block;
116

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

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

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

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

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

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

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

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

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

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

    
180
    /* mantissa encoding */
181
    int mant1_cnt, mant2_cnt, mant4_cnt;    ///< mantissa counts for bap=1,2,4
182
    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
183

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

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

    
198
    DECLARE_ALIGNED(16, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
199
} AC3EncodeContext;
200

    
201

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

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

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

    
218

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

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

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

    
273

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

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

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

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

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

    
286
static int normalize_samples(AC3EncodeContext *s);
287

    
288
static void scale_coefficients(AC3EncodeContext *s);
289

    
290

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

    
297

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

    
323

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

    
340

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

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

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

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

    
369

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

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

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

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

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

    
393

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

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

    
415

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

    
425
    s->num_rematrixing_bands = 4;
426

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

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

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

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

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

    
467

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

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

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

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

    
502

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

    
518

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

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

    
552

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

    
559

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

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

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

    
599

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

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

    
619

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

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

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

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

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

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

    
685

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

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

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

    
707
            /* count the number of EXP_REUSE blocks after the current block */
708
            while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
709
                blk1++;
710
            num_reuse_blocks = blk1 - blk - 1;
711

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

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

    
717
            /* copy encoded exponents for reuse case */
718
            exp1 = exp + AC3_MAX_COEFS;
719
            while (blk < blk1-1) {
720
                memcpy(exp1, exp, nb_coefs * sizeof(*exp));
721
                exp1 += AC3_MAX_COEFS;
722
                blk++;
723
            }
724
            blk = blk1;
725
            exp = exp1;
726
        }
727
    }
728
}
729

    
730

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

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

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

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

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

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

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

    
786
    s->exponent_bits = bit_count;
787
}
788

    
789

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

    
799
    compute_exp_strategy(s);
800

    
801
    encode_exponents(s);
802

    
803
    group_exponents(s);
804

    
805
    emms_c();
806
}
807

    
808

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

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

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

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

    
853
    /* auxdatae, crcrsv */
854
    frame_bits += 2;
855

    
856
    /* CRC */
857
    frame_bits += 16;
858

    
859
    s->frame_bits_fixed = frame_bits;
860
}
861

    
862

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

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

    
880
    /* initial snr offset */
881
    s->coarse_snr_offset = 40;
882

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

    
892
    count_frame_bits_fixed(s);
893
}
894

    
895

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

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

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

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

    
931

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

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

    
956

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

    
972

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

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

    
1002

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

    
1019

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

    
1033
    snr_offset = (snr_offset - 240) << 2;
1034

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

    
1065

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

    
1076
    bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1077
    av_assert2(bits_left >= 0);
1078

    
1079
    snr_offset = s->coarse_snr_offset << 4;
1080

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

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

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

    
1106
    s->coarse_snr_offset = snr_offset >> 4;
1107
    for (ch = 0; ch < s->channels; ch++)
1108
        s->fine_snr_offset[ch] = snr_offset & 0xF;
1109

    
1110
    return 0;
1111
}
1112

    
1113

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

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

    
1154

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

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

    
1175

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

    
1186
    count_frame_bits(s);
1187

    
1188
    bit_alloc_masking(s);
1189

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

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

    
1210
        /* fallbacks were not enough... */
1211
        break;
1212
    }
1213

    
1214
    return ret;
1215
}
1216

    
1217

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

    
1228

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

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

    
1250

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

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

    
1344

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

    
1352

    
1353
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1354
        AC3Block *block = &s->blocks[blk];
1355
        s->mant1_cnt  = s->mant2_cnt  = s->mant4_cnt  = 0;
1356
        s->qmant1_ptr = s->qmant2_ptr = s->qmant4_ptr = NULL;
1357

    
1358
        for (ch = 0; ch < s->channels; ch++) {
1359
            quantize_mantissas_blk_ch(s, block->fixed_coef[ch],
1360
                                      block->exp[ch], block->bap[ch],
1361
                                      block->qmant[ch], s->nb_coefs[ch]);
1362
        }
1363
    }
1364
}
1365

    
1366

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

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

    
1422

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1536

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

    
1540

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

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

    
1557

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

    
1571

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

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

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

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

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

    
1612

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

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

    
1622
    output_frame_header(s);
1623

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

    
1627
    output_frame_end(s);
1628
}
1629

    
1630

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

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

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

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

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

    
1743

    
1744
#define FLT_OPTION_THRESHOLD 0.01
1745

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

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

    
1758
    return i;
1759
}
1760

    
1761

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

    
1779

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

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

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

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

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

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

    
1889
    return 0;
1890
}
1891

    
1892

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

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

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

    
1912
    deinterleave_input_samples(s, samples);
1913

    
1914
    apply_mdct(s);
1915

    
1916
    scale_coefficients(s);
1917

    
1918
    compute_rematrixing_strategy(s);
1919

    
1920
    apply_rematrixing(s);
1921

    
1922
    process_exponents(s);
1923

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

    
1930
    quantize_mantissas(s);
1931

    
1932
    output_frame(s, frame);
1933

    
1934
    return s->frame_size;
1935
}
1936

    
1937

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

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

    
1972
    mdct_end(&s->mdct);
1973

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

    
1978

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

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

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

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

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

    
2025
    return 0;
2026
}
2027

    
2028

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

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

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

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

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

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

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

    
2096
    return 0;
2097
}
2098

    
2099

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

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

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

    
2130

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

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

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

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

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

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

    
2220

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

    
2229
    avctx->frame_size = AC3_FRAME_SIZE;
2230

    
2231
    ff_ac3_common_init();
2232

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

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

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

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

    
2254
    set_bandwidth(s);
2255

    
2256
    rematrixing_init(s);
2257

    
2258
    exponent_init(s);
2259

    
2260
    bit_alloc_init(s);
2261

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

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

    
2270
    avctx->coded_frame= avcodec_alloc_frame();
2271

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

    
2275
    dprint_options(avctx);
2276

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