Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ 177fed4e

History | View | Annotate | Download (76.9 KB)

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

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

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

    
32
#include <stdint.h>
33

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

    
46

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

    
51

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
223

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

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

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

    
280

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

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

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

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

    
291
static int normalize_samples(AC3EncodeContext *s);
292

    
293
static void scale_coefficients(AC3EncodeContext *s);
294

    
295

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

    
302

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

    
328

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

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

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

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

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

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

    
358

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

    
375

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

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

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

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

    
404

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

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

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

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

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

    
429

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

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

    
442
    s->num_rematrixing_bands = 4;
443

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

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

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

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

    
483

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

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

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

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

    
518

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

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

    
536

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

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

    
555

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

    
562

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

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

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

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

    
613

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

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

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

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

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

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

    
679

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

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

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

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

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

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

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

    
721

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

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

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

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

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

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

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

    
777
    s->exponent_bits = bit_count;
778
}
779

    
780

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

    
790
    compute_exp_strategy(s);
791

    
792
    encode_exponents(s);
793

    
794
    group_exponents(s);
795

    
796
    emms_c();
797
}
798

    
799

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

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

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

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

    
844
    /* auxdatae, crcrsv */
845
    frame_bits += 2;
846

    
847
    /* CRC */
848
    frame_bits += 16;
849

    
850
    s->frame_bits_fixed = frame_bits;
851
}
852

    
853

    
854
/**
855
 * Initialize bit allocation.
856
 * Set default parameter codes and calculate parameter values.
857
 */
858
static void bit_alloc_init(AC3EncodeContext *s)
859
{
860
    int ch;
861

    
862
    /* init default parameters */
863
    s->slow_decay_code = 2;
864
    s->fast_decay_code = 1;
865
    s->slow_gain_code  = 1;
866
    s->db_per_bit_code = 3;
867
    s->floor_code      = 7;
868
    for (ch = 0; ch < s->channels; ch++)
869
        s->fast_gain_code[ch] = 4;
870

    
871
    /* initial snr offset */
872
    s->coarse_snr_offset = 40;
873

    
874
    /* compute real values */
875
    /* currently none of these values change during encoding, so we can just
876
       set them once at initialization */
877
    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
878
    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
879
    s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
880
    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
881
    s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
882

    
883
    count_frame_bits_fixed(s);
884
}
885

    
886

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

    
898
    if (opt->audio_production_info)
899
        frame_bits += 7;
900
    if (s->bitstream_id == 6) {
901
        if (opt->extended_bsi_1)
902
            frame_bits += 14;
903
        if (opt->extended_bsi_2)
904
            frame_bits += 14;
905
    }
906

    
907
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
908
        /* stereo rematrixing */
909
        if (s->channel_mode == AC3_CHMODE_STEREO &&
910
            s->blocks[blk].new_rematrixing_strategy) {
911
            frame_bits += s->num_rematrixing_bands;
912
        }
913

    
914
        for (ch = 0; ch < s->fbw_channels; ch++) {
915
            if (s->exp_strategy[ch][blk] != EXP_REUSE)
916
                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
917
        }
918
    }
919
    s->frame_bits = s->frame_bits_fixed + frame_bits;
920
}
921

    
922

    
923
/**
924
 * Finalize the mantissa bit count by adding in the grouped mantissas.
925
 */
926
static int compute_mantissa_size_final(int mant_cnt[5])
927
{
928
    // bap=1 : 3 mantissas in 5 bits
929
    int bits = (mant_cnt[1] / 3) * 5;
930
    // bap=2 : 3 mantissas in 7 bits
931
    // bap=4 : 2 mantissas in 7 bits
932
    bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
933
    // bap=3 : each mantissa is 3 bits
934
    bits += mant_cnt[3] * 3;
935
    return bits;
936
}
937

    
938

    
939
/**
940
 * Calculate masking curve based on the final exponents.
941
 * Also calculate the power spectral densities to use in future calculations.
942
 */
943
static void bit_alloc_masking(AC3EncodeContext *s)
944
{
945
    int blk, ch;
946

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

    
968

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

    
985

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

    
999
    snr_offset = (snr_offset - 240) << 2;
1000

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

    
1034

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

    
1045
    bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1046
    if (bits_left < 0)
1047
        return AVERROR(EINVAL);
1048

    
1049
    snr_offset = s->coarse_snr_offset << 4;
1050

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

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

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

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

    
1080
    return 0;
1081
}
1082

    
1083

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

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

    
1124

    
1125
/**
1126
 * Perform bit allocation search.
1127
 * Finds the SNR offset value that maximizes quality and fits in the specified
1128
 * frame size.  Output is the SNR offset and a set of bit allocation pointers
1129
 * used to quantize the mantissas.
1130
 */
1131
static int compute_bit_allocation(AC3EncodeContext *s)
1132
{
1133
    int ret;
1134

    
1135
    count_frame_bits(s);
1136

    
1137
    bit_alloc_masking(s);
1138

    
1139
    ret = cbr_bit_allocation(s);
1140
    while (ret) {
1141
        /* fallback 1: downgrade exponents */
1142
        if (!downgrade_exponents(s)) {
1143
            extract_exponents(s);
1144
            encode_exponents(s);
1145
            group_exponents(s);
1146
            ret = compute_bit_allocation(s);
1147
            continue;
1148
        }
1149

    
1150
        /* fallbacks were not enough... */
1151
        break;
1152
    }
1153

    
1154
    return ret;
1155
}
1156

    
1157

    
1158
/**
1159
 * Symmetric quantization on 'levels' levels.
1160
 */
1161
static inline int sym_quant(int c, int e, int levels)
1162
{
1163
    int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1164
    av_assert2(v >= 0 && v < levels);
1165
    return v;
1166
}
1167

    
1168

    
1169
/**
1170
 * Asymmetric quantization on 2^qbits levels.
1171
 */
1172
static inline int asym_quant(int c, int e, int qbits)
1173
{
1174
    int lshift, m, v;
1175

    
1176
    lshift = e + qbits - 24;
1177
    if (lshift >= 0)
1178
        v = c << lshift;
1179
    else
1180
        v = c >> (-lshift);
1181
    /* rounding */
1182
    v = (v + 1) >> 1;
1183
    m = (1 << (qbits-1));
1184
    if (v >= m)
1185
        v = m - 1;
1186
    av_assert2(v >= -m);
1187
    return v & ((1 << qbits)-1);
1188
}
1189

    
1190

    
1191
/**
1192
 * Quantize a set of mantissas for a single channel in a single block.
1193
 */
1194
static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1195
                                      uint8_t *exp,
1196
                                      uint8_t *bap, uint16_t *qmant, int n)
1197
{
1198
    int i;
1199

    
1200
    for (i = 0; i < n; i++) {
1201
        int v;
1202
        int c = fixed_coef[i];
1203
        int e = exp[i];
1204
        int b = bap[i];
1205
        switch (b) {
1206
        case 0:
1207
            v = 0;
1208
            break;
1209
        case 1:
1210
            v = sym_quant(c, e, 3);
1211
            switch (s->mant1_cnt) {
1212
            case 0:
1213
                s->qmant1_ptr = &qmant[i];
1214
                v = 9 * v;
1215
                s->mant1_cnt = 1;
1216
                break;
1217
            case 1:
1218
                *s->qmant1_ptr += 3 * v;
1219
                s->mant1_cnt = 2;
1220
                v = 128;
1221
                break;
1222
            default:
1223
                *s->qmant1_ptr += v;
1224
                s->mant1_cnt = 0;
1225
                v = 128;
1226
                break;
1227
            }
1228
            break;
1229
        case 2:
1230
            v = sym_quant(c, e, 5);
1231
            switch (s->mant2_cnt) {
1232
            case 0:
1233
                s->qmant2_ptr = &qmant[i];
1234
                v = 25 * v;
1235
                s->mant2_cnt = 1;
1236
                break;
1237
            case 1:
1238
                *s->qmant2_ptr += 5 * v;
1239
                s->mant2_cnt = 2;
1240
                v = 128;
1241
                break;
1242
            default:
1243
                *s->qmant2_ptr += v;
1244
                s->mant2_cnt = 0;
1245
                v = 128;
1246
                break;
1247
            }
1248
            break;
1249
        case 3:
1250
            v = sym_quant(c, e, 7);
1251
            break;
1252
        case 4:
1253
            v = sym_quant(c, e, 11);
1254
            switch (s->mant4_cnt) {
1255
            case 0:
1256
                s->qmant4_ptr = &qmant[i];
1257
                v = 11 * v;
1258
                s->mant4_cnt = 1;
1259
                break;
1260
            default:
1261
                *s->qmant4_ptr += v;
1262
                s->mant4_cnt = 0;
1263
                v = 128;
1264
                break;
1265
            }
1266
            break;
1267
        case 5:
1268
            v = sym_quant(c, e, 15);
1269
            break;
1270
        case 14:
1271
            v = asym_quant(c, e, 14);
1272
            break;
1273
        case 15:
1274
            v = asym_quant(c, e, 16);
1275
            break;
1276
        default:
1277
            v = asym_quant(c, e, b - 1);
1278
            break;
1279
        }
1280
        qmant[i] = v;
1281
    }
1282
}
1283

    
1284

    
1285
/**
1286
 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1287
 */
1288
static void quantize_mantissas(AC3EncodeContext *s)
1289
{
1290
    int blk, ch;
1291

    
1292

    
1293
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1294
        AC3Block *block = &s->blocks[blk];
1295
        AC3Block *ref_block;
1296
        AC3Mant m = { 0 };
1297

    
1298
        for (ch = 0; ch < s->channels; ch++) {
1299
            ref_block = block->exp_ref_block[ch];
1300
            quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1301
                                      ref_block->exp[ch], ref_block->bap[ch],
1302
                                      block->qmant[ch], s->nb_coefs[ch]);
1303
        }
1304
    }
1305
}
1306

    
1307

    
1308
/**
1309
 * Write the AC-3 frame header to the output bitstream.
1310
 */
1311
static void output_frame_header(AC3EncodeContext *s)
1312
{
1313
    AC3EncOptions *opt = &s->options;
1314

    
1315
    put_bits(&s->pb, 16, 0x0b77);   /* frame header */
1316
    put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
1317
    put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
1318
    put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1319
    put_bits(&s->pb, 5,  s->bitstream_id);
1320
    put_bits(&s->pb, 3,  s->bitstream_mode);
1321
    put_bits(&s->pb, 3,  s->channel_mode);
1322
    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1323
        put_bits(&s->pb, 2, s->center_mix_level);
1324
    if (s->channel_mode & 0x04)
1325
        put_bits(&s->pb, 2, s->surround_mix_level);
1326
    if (s->channel_mode == AC3_CHMODE_STEREO)
1327
        put_bits(&s->pb, 2, opt->dolby_surround_mode);
1328
    put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1329
    put_bits(&s->pb, 5, -opt->dialogue_level);
1330
    put_bits(&s->pb, 1, 0);         /* no compression control word */
1331
    put_bits(&s->pb, 1, 0);         /* no lang code */
1332
    put_bits(&s->pb, 1, opt->audio_production_info);
1333
    if (opt->audio_production_info) {
1334
        put_bits(&s->pb, 5, opt->mixing_level - 80);
1335
        put_bits(&s->pb, 2, opt->room_type);
1336
    }
1337
    put_bits(&s->pb, 1, opt->copyright);
1338
    put_bits(&s->pb, 1, opt->original);
1339
    if (s->bitstream_id == 6) {
1340
        /* alternate bit stream syntax */
1341
        put_bits(&s->pb, 1, opt->extended_bsi_1);
1342
        if (opt->extended_bsi_1) {
1343
            put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1344
            put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1345
            put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1346
            put_bits(&s->pb, 3, s->loro_center_mix_level);
1347
            put_bits(&s->pb, 3, s->loro_surround_mix_level);
1348
        }
1349
        put_bits(&s->pb, 1, opt->extended_bsi_2);
1350
        if (opt->extended_bsi_2) {
1351
            put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1352
            put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1353
            put_bits(&s->pb, 1, opt->ad_converter_type);
1354
            put_bits(&s->pb, 9, 0);     /* xbsi2 and encinfo : reserved */
1355
        }
1356
    } else {
1357
    put_bits(&s->pb, 1, 0);         /* no time code 1 */
1358
    put_bits(&s->pb, 1, 0);         /* no time code 2 */
1359
    }
1360
    put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
1361
}
1362

    
1363

    
1364
/**
1365
 * Write one audio block to the output bitstream.
1366
 */
1367
static void output_audio_block(AC3EncodeContext *s, int blk)
1368
{
1369
    int ch, i, baie, rbnd;
1370
    AC3Block *block = &s->blocks[blk];
1371

    
1372
    /* block switching */
1373
    for (ch = 0; ch < s->fbw_channels; ch++)
1374
        put_bits(&s->pb, 1, 0);
1375

    
1376
    /* dither flags */
1377
    for (ch = 0; ch < s->fbw_channels; ch++)
1378
        put_bits(&s->pb, 1, 1);
1379

    
1380
    /* dynamic range codes */
1381
    put_bits(&s->pb, 1, 0);
1382

    
1383
    /* channel coupling */
1384
    if (!blk) {
1385
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
1386
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
1387
    } else {
1388
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1389
    }
1390

    
1391
    /* stereo rematrixing */
1392
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1393
        put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1394
        if (block->new_rematrixing_strategy) {
1395
            /* rematrixing flags */
1396
            for (rbnd = 0; rbnd < s->num_rematrixing_bands; rbnd++)
1397
                put_bits(&s->pb, 1, block->rematrixing_flags[rbnd]);
1398
        }
1399
    }
1400

    
1401
    /* exponent strategy */
1402
    for (ch = 0; ch < s->fbw_channels; ch++)
1403
        put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1404
    if (s->lfe_on)
1405
        put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1406

    
1407
    /* bandwidth */
1408
    for (ch = 0; ch < s->fbw_channels; ch++) {
1409
        if (s->exp_strategy[ch][blk] != EXP_REUSE)
1410
            put_bits(&s->pb, 6, s->bandwidth_code);
1411
    }
1412

    
1413
    /* exponents */
1414
    for (ch = 0; ch < s->channels; ch++) {
1415
        int nb_groups;
1416

    
1417
        if (s->exp_strategy[ch][blk] == EXP_REUSE)
1418
            continue;
1419

    
1420
        /* DC exponent */
1421
        put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1422

    
1423
        /* exponent groups */
1424
        nb_groups = exponent_group_tab[s->exp_strategy[ch][blk]-1][s->nb_coefs[ch]];
1425
        for (i = 1; i <= nb_groups; i++)
1426
            put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1427

    
1428
        /* gain range info */
1429
        if (ch != s->lfe_channel)
1430
            put_bits(&s->pb, 2, 0);
1431
    }
1432

    
1433
    /* bit allocation info */
1434
    baie = (blk == 0);
1435
    put_bits(&s->pb, 1, baie);
1436
    if (baie) {
1437
        put_bits(&s->pb, 2, s->slow_decay_code);
1438
        put_bits(&s->pb, 2, s->fast_decay_code);
1439
        put_bits(&s->pb, 2, s->slow_gain_code);
1440
        put_bits(&s->pb, 2, s->db_per_bit_code);
1441
        put_bits(&s->pb, 3, s->floor_code);
1442
    }
1443

    
1444
    /* snr offset */
1445
    put_bits(&s->pb, 1, baie);
1446
    if (baie) {
1447
        put_bits(&s->pb, 6, s->coarse_snr_offset);
1448
        for (ch = 0; ch < s->channels; ch++) {
1449
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1450
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1451
        }
1452
    }
1453

    
1454
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1455
    put_bits(&s->pb, 1, 0); /* no data to skip */
1456

    
1457
    /* mantissas */
1458
    for (ch = 0; ch < s->channels; ch++) {
1459
        int b, q;
1460
        AC3Block *ref_block = block->exp_ref_block[ch];
1461
        for (i = 0; i < s->nb_coefs[ch]; i++) {
1462
            q = block->qmant[ch][i];
1463
            b = ref_block->bap[ch][i];
1464
            switch (b) {
1465
            case 0:                                         break;
1466
            case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
1467
            case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
1468
            case 3:               put_bits(&s->pb,   3, q); break;
1469
            case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
1470
            case 14:              put_bits(&s->pb,  14, q); break;
1471
            case 15:              put_bits(&s->pb,  16, q); break;
1472
            default:              put_bits(&s->pb, b-1, q); break;
1473
            }
1474
        }
1475
    }
1476
}
1477

    
1478

    
1479
/** CRC-16 Polynomial */
1480
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1481

    
1482

    
1483
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1484
{
1485
    unsigned int c;
1486

    
1487
    c = 0;
1488
    while (a) {
1489
        if (a & 1)
1490
            c ^= b;
1491
        a = a >> 1;
1492
        b = b << 1;
1493
        if (b & (1 << 16))
1494
            b ^= poly;
1495
    }
1496
    return c;
1497
}
1498

    
1499

    
1500
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1501
{
1502
    unsigned int r;
1503
    r = 1;
1504
    while (n) {
1505
        if (n & 1)
1506
            r = mul_poly(r, a, poly);
1507
        a = mul_poly(a, a, poly);
1508
        n >>= 1;
1509
    }
1510
    return r;
1511
}
1512

    
1513

    
1514
/**
1515
 * Fill the end of the frame with 0's and compute the two CRCs.
1516
 */
1517
static void output_frame_end(AC3EncodeContext *s)
1518
{
1519
    const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1520
    int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1521
    uint8_t *frame;
1522

    
1523
    frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1524

    
1525
    /* pad the remainder of the frame with zeros */
1526
    av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1527
    flush_put_bits(&s->pb);
1528
    frame = s->pb.buf;
1529
    pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1530
    av_assert2(pad_bytes >= 0);
1531
    if (pad_bytes > 0)
1532
        memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1533

    
1534
    /* compute crc1 */
1535
    /* this is not so easy because it is at the beginning of the data... */
1536
    crc1    = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1537
    crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1538
    crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1539
    AV_WB16(frame + 2, crc1);
1540

    
1541
    /* compute crc2 */
1542
    crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1543
                          s->frame_size - frame_size_58 - 3);
1544
    crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1545
    /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1546
    if (crc2 == 0x770B) {
1547
        frame[s->frame_size - 3] ^= 0x1;
1548
        crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1549
    }
1550
    crc2 = av_bswap16(crc2);
1551
    AV_WB16(frame + s->frame_size - 2, crc2);
1552
}
1553

    
1554

    
1555
/**
1556
 * Write the frame to the output bitstream.
1557
 */
1558
static void output_frame(AC3EncodeContext *s, unsigned char *frame)
1559
{
1560
    int blk;
1561

    
1562
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1563

    
1564
    output_frame_header(s);
1565

    
1566
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1567
        output_audio_block(s, blk);
1568

    
1569
    output_frame_end(s);
1570
}
1571

    
1572

    
1573
static void dprint_options(AVCodecContext *avctx)
1574
{
1575
#ifdef DEBUG
1576
    AC3EncodeContext *s = avctx->priv_data;
1577
    AC3EncOptions *opt = &s->options;
1578
    char strbuf[32];
1579

    
1580
    switch (s->bitstream_id) {
1581
    case  6:  strncpy(strbuf, "AC-3 (alt syntax)", 32);      break;
1582
    case  8:  strncpy(strbuf, "AC-3 (standard)", 32);        break;
1583
    case  9:  strncpy(strbuf, "AC-3 (dnet half-rate)", 32);  break;
1584
    case 10:  strncpy(strbuf, "AC-3 (dnet quater-rate", 32); break;
1585
    default: snprintf(strbuf, 32, "ERROR");
1586
    }
1587
    av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
1588
    av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
1589
    av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
1590
    av_dlog(avctx, "channel_layout: %s\n", strbuf);
1591
    av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
1592
    av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
1593
    if (s->cutoff)
1594
        av_dlog(avctx, "cutoff: %d\n", s->cutoff);
1595

    
1596
    av_dlog(avctx, "per_frame_metadata: %s\n",
1597
            opt->allow_per_frame_metadata?"on":"off");
1598
    if (s->has_center)
1599
        av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
1600
                s->center_mix_level);
1601
    else
1602
        av_dlog(avctx, "center_mixlev: {not written}\n");
1603
    if (s->has_surround)
1604
        av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
1605
                s->surround_mix_level);
1606
    else
1607
        av_dlog(avctx, "surround_mixlev: {not written}\n");
1608
    if (opt->audio_production_info) {
1609
        av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
1610
        switch (opt->room_type) {
1611
        case 0:  strncpy(strbuf, "notindicated", 32); break;
1612
        case 1:  strncpy(strbuf, "large", 32);        break;
1613
        case 2:  strncpy(strbuf, "small", 32);        break;
1614
        default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
1615
        }
1616
        av_dlog(avctx, "room_type: %s\n", strbuf);
1617
    } else {
1618
        av_dlog(avctx, "mixing_level: {not written}\n");
1619
        av_dlog(avctx, "room_type: {not written}\n");
1620
    }
1621
    av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
1622
    av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
1623
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1624
        switch (opt->dolby_surround_mode) {
1625
        case 0:  strncpy(strbuf, "notindicated", 32); break;
1626
        case 1:  strncpy(strbuf, "on", 32);           break;
1627
        case 2:  strncpy(strbuf, "off", 32);          break;
1628
        default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
1629
        }
1630
        av_dlog(avctx, "dsur_mode: %s\n", strbuf);
1631
    } else {
1632
        av_dlog(avctx, "dsur_mode: {not written}\n");
1633
    }
1634
    av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
1635

    
1636
    if (s->bitstream_id == 6) {
1637
        if (opt->extended_bsi_1) {
1638
            switch (opt->preferred_stereo_downmix) {
1639
            case 0:  strncpy(strbuf, "notindicated", 32); break;
1640
            case 1:  strncpy(strbuf, "ltrt", 32);         break;
1641
            case 2:  strncpy(strbuf, "loro", 32);         break;
1642
            default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
1643
            }
1644
            av_dlog(avctx, "dmix_mode: %s\n", strbuf);
1645
            av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
1646
                    opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
1647
            av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
1648
                    opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
1649
            av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
1650
                    opt->loro_center_mix_level, s->loro_center_mix_level);
1651
            av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
1652
                    opt->loro_surround_mix_level, s->loro_surround_mix_level);
1653
        } else {
1654
            av_dlog(avctx, "extended bitstream info 1: {not written}\n");
1655
        }
1656
        if (opt->extended_bsi_2) {
1657
            switch (opt->dolby_surround_ex_mode) {
1658
            case 0:  strncpy(strbuf, "notindicated", 32); break;
1659
            case 1:  strncpy(strbuf, "on", 32);           break;
1660
            case 2:  strncpy(strbuf, "off", 32);          break;
1661
            default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
1662
            }
1663
            av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
1664
            switch (opt->dolby_headphone_mode) {
1665
            case 0:  strncpy(strbuf, "notindicated", 32); break;
1666
            case 1:  strncpy(strbuf, "on", 32);           break;
1667
            case 2:  strncpy(strbuf, "off", 32);          break;
1668
            default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
1669
            }
1670
            av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
1671

    
1672
            switch (opt->ad_converter_type) {
1673
            case 0:  strncpy(strbuf, "standard", 32); break;
1674
            case 1:  strncpy(strbuf, "hdcd", 32);     break;
1675
            default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
1676
            }
1677
            av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
1678
        } else {
1679
            av_dlog(avctx, "extended bitstream info 2: {not written}\n");
1680
        }
1681
    }
1682
#endif
1683
}
1684

    
1685

    
1686
#define FLT_OPTION_THRESHOLD 0.01
1687

    
1688
static int validate_float_option(float v, const float *v_list, int v_list_size)
1689
{
1690
    int i;
1691

    
1692
    for (i = 0; i < v_list_size; i++) {
1693
        if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
1694
            v > (v_list[i] - FLT_OPTION_THRESHOLD))
1695
            break;
1696
    }
1697
    if (i == v_list_size)
1698
        return -1;
1699

    
1700
    return i;
1701
}
1702

    
1703

    
1704
static void validate_mix_level(void *log_ctx, const char *opt_name,
1705
                               float *opt_param, const float *list,
1706
                               int list_size, int default_value, int min_value,
1707
                               int *ctx_param)
1708
{
1709
    int mixlev = validate_float_option(*opt_param, list, list_size);
1710
    if (mixlev < min_value) {
1711
        mixlev = default_value;
1712
        if (*opt_param >= 0.0) {
1713
            av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
1714
                   "default value: %0.3f\n", opt_name, list[mixlev]);
1715
        }
1716
    }
1717
    *opt_param = list[mixlev];
1718
    *ctx_param = mixlev;
1719
}
1720

    
1721

    
1722
/**
1723
 * Validate metadata options as set by AVOption system.
1724
 * These values can optionally be changed per-frame.
1725
 */
1726
static int validate_metadata(AVCodecContext *avctx)
1727
{
1728
    AC3EncodeContext *s = avctx->priv_data;
1729
    AC3EncOptions *opt = &s->options;
1730

    
1731
    /* validate mixing levels */
1732
    if (s->has_center) {
1733
        validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
1734
                           cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
1735
                           &s->center_mix_level);
1736
    }
1737
    if (s->has_surround) {
1738
        validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
1739
                           surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
1740
                           &s->surround_mix_level);
1741
    }
1742

    
1743
    /* set audio production info flag */
1744
    if (opt->mixing_level >= 0 || opt->room_type >= 0) {
1745
        if (opt->mixing_level < 0) {
1746
            av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
1747
                   "room_type is set\n");
1748
            return AVERROR(EINVAL);
1749
        }
1750
        if (opt->mixing_level < 80) {
1751
            av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
1752
                   "80dB and 111dB\n");
1753
            return AVERROR(EINVAL);
1754
        }
1755
        /* default room type */
1756
        if (opt->room_type < 0)
1757
            opt->room_type = 0;
1758
        opt->audio_production_info = 1;
1759
    } else {
1760
        opt->audio_production_info = 0;
1761
    }
1762

    
1763
    /* set extended bsi 1 flag */
1764
    if ((s->has_center || s->has_surround) &&
1765
        (opt->preferred_stereo_downmix >= 0 ||
1766
         opt->ltrt_center_mix_level   >= 0 ||
1767
         opt->ltrt_surround_mix_level >= 0 ||
1768
         opt->loro_center_mix_level   >= 0 ||
1769
         opt->loro_surround_mix_level >= 0)) {
1770
        /* default preferred stereo downmix */
1771
        if (opt->preferred_stereo_downmix < 0)
1772
            opt->preferred_stereo_downmix = 0;
1773
        /* validate Lt/Rt center mix level */
1774
        validate_mix_level(avctx, "ltrt_center_mix_level",
1775
                           &opt->ltrt_center_mix_level, extmixlev_options,
1776
                           EXTMIXLEV_NUM_OPTIONS, 5, 0,
1777
                           &s->ltrt_center_mix_level);
1778
        /* validate Lt/Rt surround mix level */
1779
        validate_mix_level(avctx, "ltrt_surround_mix_level",
1780
                           &opt->ltrt_surround_mix_level, extmixlev_options,
1781
                           EXTMIXLEV_NUM_OPTIONS, 6, 3,
1782
                           &s->ltrt_surround_mix_level);
1783
        /* validate Lo/Ro center mix level */
1784
        validate_mix_level(avctx, "loro_center_mix_level",
1785
                           &opt->loro_center_mix_level, extmixlev_options,
1786
                           EXTMIXLEV_NUM_OPTIONS, 5, 0,
1787
                           &s->loro_center_mix_level);
1788
        /* validate Lo/Ro surround mix level */
1789
        validate_mix_level(avctx, "loro_surround_mix_level",
1790
                           &opt->loro_surround_mix_level, extmixlev_options,
1791
                           EXTMIXLEV_NUM_OPTIONS, 6, 3,
1792
                           &s->loro_surround_mix_level);
1793
        opt->extended_bsi_1 = 1;
1794
    } else {
1795
        opt->extended_bsi_1 = 0;
1796
    }
1797

    
1798
    /* set extended bsi 2 flag */
1799
    if (opt->dolby_surround_ex_mode >= 0 ||
1800
        opt->dolby_headphone_mode   >= 0 ||
1801
        opt->ad_converter_type      >= 0) {
1802
        /* default dolby surround ex mode */
1803
        if (opt->dolby_surround_ex_mode < 0)
1804
            opt->dolby_surround_ex_mode = 0;
1805
        /* default dolby headphone mode */
1806
        if (opt->dolby_headphone_mode < 0)
1807
            opt->dolby_headphone_mode = 0;
1808
        /* default A/D converter type */
1809
        if (opt->ad_converter_type < 0)
1810
            opt->ad_converter_type = 0;
1811
        opt->extended_bsi_2 = 1;
1812
    } else {
1813
        opt->extended_bsi_2 = 0;
1814
    }
1815

    
1816
    /* set bitstream id for alternate bitstream syntax */
1817
    if (opt->extended_bsi_1 || opt->extended_bsi_2) {
1818
        if (s->bitstream_id > 8 && s->bitstream_id < 11) {
1819
            static int warn_once = 1;
1820
            if (warn_once) {
1821
                av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
1822
                       "not compatible with reduced samplerates. writing of "
1823
                       "extended bitstream information will be disabled.\n");
1824
                warn_once = 0;
1825
            }
1826
        } else {
1827
            s->bitstream_id = 6;
1828
        }
1829
    }
1830

    
1831
    return 0;
1832
}
1833

    
1834

    
1835
/**
1836
 * Encode a single AC-3 frame.
1837
 */
1838
static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
1839
                            int buf_size, void *data)
1840
{
1841
    AC3EncodeContext *s = avctx->priv_data;
1842
    const SampleType *samples = data;
1843
    int ret;
1844

    
1845
    if (s->options.allow_per_frame_metadata) {
1846
        ret = validate_metadata(avctx);
1847
        if (ret)
1848
            return ret;
1849
    }
1850

    
1851
    if (s->bit_alloc.sr_code == 1)
1852
        adjust_frame_size(s);
1853

    
1854
    deinterleave_input_samples(s, samples);
1855

    
1856
    apply_mdct(s);
1857

    
1858
    scale_coefficients(s);
1859

    
1860
    compute_rematrixing_strategy(s);
1861

    
1862
    apply_rematrixing(s);
1863

    
1864
    process_exponents(s);
1865

    
1866
    ret = compute_bit_allocation(s);
1867
    if (ret) {
1868
        av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1869
        return ret;
1870
    }
1871

    
1872
    quantize_mantissas(s);
1873

    
1874
    output_frame(s, frame);
1875

    
1876
    return s->frame_size;
1877
}
1878

    
1879

    
1880
/**
1881
 * Finalize encoding and free any memory allocated by the encoder.
1882
 */
1883
static av_cold int ac3_encode_close(AVCodecContext *avctx)
1884
{
1885
    int blk, ch;
1886
    AC3EncodeContext *s = avctx->priv_data;
1887

    
1888
    for (ch = 0; ch < s->channels; ch++)
1889
        av_freep(&s->planar_samples[ch]);
1890
    av_freep(&s->planar_samples);
1891
    av_freep(&s->bap_buffer);
1892
    av_freep(&s->bap1_buffer);
1893
    av_freep(&s->mdct_coef_buffer);
1894
    av_freep(&s->fixed_coef_buffer);
1895
    av_freep(&s->exp_buffer);
1896
    av_freep(&s->grouped_exp_buffer);
1897
    av_freep(&s->psd_buffer);
1898
    av_freep(&s->band_psd_buffer);
1899
    av_freep(&s->mask_buffer);
1900
    av_freep(&s->qmant_buffer);
1901
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1902
        AC3Block *block = &s->blocks[blk];
1903
        av_freep(&block->bap);
1904
        av_freep(&block->mdct_coef);
1905
        av_freep(&block->fixed_coef);
1906
        av_freep(&block->exp);
1907
        av_freep(&block->grouped_exp);
1908
        av_freep(&block->psd);
1909
        av_freep(&block->band_psd);
1910
        av_freep(&block->mask);
1911
        av_freep(&block->qmant);
1912
    }
1913

    
1914
    mdct_end(&s->mdct);
1915

    
1916
    av_freep(&avctx->coded_frame);
1917
    return 0;
1918
}
1919

    
1920

    
1921
/**
1922
 * Set channel information during initialization.
1923
 */
1924
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1925
                                    int64_t *channel_layout)
1926
{
1927
    int ch_layout;
1928

    
1929
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
1930
        return AVERROR(EINVAL);
1931
    if ((uint64_t)*channel_layout > 0x7FF)
1932
        return AVERROR(EINVAL);
1933
    ch_layout = *channel_layout;
1934
    if (!ch_layout)
1935
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1936

    
1937
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1938
    s->channels     = channels;
1939
    s->fbw_channels = channels - s->lfe_on;
1940
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
1941
    if (s->lfe_on)
1942
        ch_layout -= AV_CH_LOW_FREQUENCY;
1943

    
1944
    switch (ch_layout) {
1945
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
1946
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
1947
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
1948
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
1949
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
1950
    case AV_CH_LAYOUT_QUAD:
1951
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
1952
    case AV_CH_LAYOUT_5POINT0:
1953
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
1954
    default:
1955
        return AVERROR(EINVAL);
1956
    }
1957
    s->has_center   = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
1958
    s->has_surround =  s->channel_mode & 0x04;
1959

    
1960
    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1961
    *channel_layout = ch_layout;
1962
    if (s->lfe_on)
1963
        *channel_layout |= AV_CH_LOW_FREQUENCY;
1964

    
1965
    return 0;
1966
}
1967

    
1968

    
1969
static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1970
{
1971
    int i, ret;
1972

    
1973
    /* validate channel layout */
1974
    if (!avctx->channel_layout) {
1975
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1976
                                      "encoder will guess the layout, but it "
1977
                                      "might be incorrect.\n");
1978
    }
1979
    ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1980
    if (ret) {
1981
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1982
        return ret;
1983
    }
1984

    
1985
    /* validate sample rate */
1986
    for (i = 0; i < 9; i++) {
1987
        if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
1988
            break;
1989
    }
1990
    if (i == 9) {
1991
        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1992
        return AVERROR(EINVAL);
1993
    }
1994
    s->sample_rate        = avctx->sample_rate;
1995
    s->bit_alloc.sr_shift = i % 3;
1996
    s->bit_alloc.sr_code  = i / 3;
1997
    s->bitstream_id       = 8 + s->bit_alloc.sr_shift;
1998

    
1999
    /* validate bit rate */
2000
    for (i = 0; i < 19; i++) {
2001
        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
2002
            break;
2003
    }
2004
    if (i == 19) {
2005
        av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2006
        return AVERROR(EINVAL);
2007
    }
2008
    s->bit_rate        = avctx->bit_rate;
2009
    s->frame_size_code = i << 1;
2010

    
2011
    /* validate cutoff */
2012
    if (avctx->cutoff < 0) {
2013
        av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2014
        return AVERROR(EINVAL);
2015
    }
2016
    s->cutoff = avctx->cutoff;
2017
    if (s->cutoff > (s->sample_rate >> 1))
2018
        s->cutoff = s->sample_rate >> 1;
2019

    
2020
    /* validate audio service type / channels combination */
2021
    if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
2022
         avctx->channels == 1) ||
2023
        ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
2024
          avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY  ||
2025
          avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
2026
         && avctx->channels > 1)) {
2027
        av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
2028
                                    "specified number of channels\n");
2029
        return AVERROR(EINVAL);
2030
    }
2031

    
2032
    ret = validate_metadata(avctx);
2033
    if (ret)
2034
        return ret;
2035

    
2036
    s->rematrixing_enabled = s->options.stereo_rematrixing &&
2037
                             (s->channel_mode == AC3_CHMODE_STEREO);
2038

    
2039
    return 0;
2040
}
2041

    
2042

    
2043
/**
2044
 * Set bandwidth for all channels.
2045
 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2046
 * default value will be used.
2047
 */
2048
static av_cold void set_bandwidth(AC3EncodeContext *s)
2049
{
2050
    int ch;
2051

    
2052
    if (s->cutoff) {
2053
        /* calculate bandwidth based on user-specified cutoff frequency */
2054
        int fbw_coeffs;
2055
        fbw_coeffs     = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2056
        s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2057
    } else {
2058
        /* use default bandwidth setting */
2059
        s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2060
    }
2061

    
2062
    /* set number of coefficients for each channel */
2063
    for (ch = 0; ch < s->fbw_channels; ch++) {
2064
        s->nb_coefs[ch] = s->bandwidth_code * 3 + 73;
2065
    }
2066
    if (s->lfe_on)
2067
        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
2068
}
2069

    
2070

    
2071
static av_cold int allocate_buffers(AVCodecContext *avctx)
2072
{
2073
    int blk, ch;
2074
    AC3EncodeContext *s = avctx->priv_data;
2075

    
2076
    FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
2077
                     alloc_fail);
2078
    for (ch = 0; ch < s->channels; ch++) {
2079
        FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
2080
                          (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
2081
                          alloc_fail);
2082
    }
2083
    FF_ALLOC_OR_GOTO(avctx, s->bap_buffer,  AC3_MAX_BLOCKS * s->channels *
2084
                     AC3_MAX_COEFS * sizeof(*s->bap_buffer),  alloc_fail);
2085
    FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
2086
                     AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
2087
    FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
2088
                     AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
2089
    FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
2090
                     AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
2091
    FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
2092
                     128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
2093
    FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
2094
                     AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
2095
    FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
2096
                     64 * sizeof(*s->band_psd_buffer), alloc_fail);
2097
    FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
2098
                     64 * sizeof(*s->mask_buffer), alloc_fail);
2099
    FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
2100
                     AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
2101
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2102
        AC3Block *block = &s->blocks[blk];
2103
        FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
2104
                         alloc_fail);
2105
        FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
2106
                          alloc_fail);
2107
        FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
2108
                          alloc_fail);
2109
        FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
2110
                          alloc_fail);
2111
        FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
2112
                          alloc_fail);
2113
        FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
2114
                          alloc_fail);
2115
        FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
2116
                          alloc_fail);
2117
        FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
2118
                          alloc_fail);
2119

    
2120
        for (ch = 0; ch < s->channels; ch++) {
2121
            /* arrangement: block, channel, coeff */
2122
            block->bap[ch]         = &s->bap_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
2123
            block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (blk * s->channels + ch)];
2124
            block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * s->channels + ch)];
2125
            block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
2126
            block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * s->channels + ch)];
2127
            block->mask[ch]        = &s->mask_buffer       [64            * (blk * s->channels + ch)];
2128
            block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * s->channels + ch)];
2129

    
2130
            /* arrangement: channel, block, coeff */
2131
            block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2132
        }
2133
    }
2134

    
2135
    if (CONFIG_AC3ENC_FLOAT) {
2136
        FF_ALLOC_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * s->channels *
2137
                         AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
2138
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2139
            AC3Block *block = &s->blocks[blk];
2140
            FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2141
                              sizeof(*block->fixed_coef), alloc_fail);
2142
            for (ch = 0; ch < s->channels; ch++)
2143
                block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
2144
        }
2145
    } else {
2146
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2147
            AC3Block *block = &s->blocks[blk];
2148
            FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2149
                              sizeof(*block->fixed_coef), alloc_fail);
2150
            for (ch = 0; ch < s->channels; ch++)
2151
                block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2152
        }
2153
    }
2154

    
2155
    return 0;
2156
alloc_fail:
2157
    return AVERROR(ENOMEM);
2158
}
2159

    
2160

    
2161
/**
2162
 * Initialize the encoder.
2163
 */
2164
static av_cold int ac3_encode_init(AVCodecContext *avctx)
2165
{
2166
    AC3EncodeContext *s = avctx->priv_data;
2167
    int ret, frame_size_58;
2168

    
2169
    avctx->frame_size = AC3_FRAME_SIZE;
2170

    
2171
    ff_ac3_common_init();
2172

    
2173
    ret = validate_options(avctx, s);
2174
    if (ret)
2175
        return ret;
2176

    
2177
    s->bitstream_mode = avctx->audio_service_type;
2178
    if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2179
        s->bitstream_mode = 0x7;
2180

    
2181
    s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2182
    s->bits_written    = 0;
2183
    s->samples_written = 0;
2184
    s->frame_size      = s->frame_size_min;
2185

    
2186
    /* calculate crc_inv for both possible frame sizes */
2187
    frame_size_58 = (( s->frame_size    >> 2) + ( s->frame_size    >> 4)) << 1;
2188
    s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2189
    if (s->bit_alloc.sr_code == 1) {
2190
        frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2191
        s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2192
    }
2193

    
2194
    set_bandwidth(s);
2195

    
2196
    exponent_init(s);
2197

    
2198
    bit_alloc_init(s);
2199

    
2200
    ret = mdct_init(avctx, &s->mdct, 9);
2201
    if (ret)
2202
        goto init_fail;
2203

    
2204
    ret = allocate_buffers(avctx);
2205
    if (ret)
2206
        goto init_fail;
2207

    
2208
    avctx->coded_frame= avcodec_alloc_frame();
2209

    
2210
    dsputil_init(&s->dsp, avctx);
2211
    ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2212

    
2213
    dprint_options(avctx);
2214

    
2215
    return 0;
2216
init_fail:
2217
    ac3_encode_close(avctx);
2218
    return ret;
2219
}