Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ 4142487d

History | View | Annotate | Download (77.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[AC3_MAX_CHANNELS];   ///< bandwidth code (0 to 60)               (chbwcod)
166
    int nb_coefs[AC3_MAX_CHANNELS];
167

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

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

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

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

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

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

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

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

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

    
223

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

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

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

    
280

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

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

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

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

    
291
static int normalize_samples(AC3EncodeContext *s);
292

    
293
static void scale_coefficients(AC3EncodeContext *s);
294

    
295

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

    
302

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

    
328

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

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

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

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

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

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

    
358

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

    
375

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

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

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

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

    
404

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

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

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

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

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

    
429

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

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

    
442
    s->num_rematrixing_bands = 4;
443

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

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

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

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

    
483

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

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

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

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

    
518

    
519
/**
520
 * Initialize exponent tables.
521
 */
522
static av_cold void exponent_init(AC3EncodeContext *s)
523
{
524
    int 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 blocks in a single channel.
565
 */
566
static void compute_exp_strategy_ch(AC3EncodeContext *s, uint8_t *exp_strategy,
567
                                    uint8_t *exp)
568
{
569
    int blk, blk1;
570
    int exp_diff;
571

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

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

    
602

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

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

    
622

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

    
630
    nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
631

    
632
    /* for each group, compute the minimum exponent */
633
    switch(exp_strategy) {
634
    case EXP_D25:
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
            exp[i] = exp_min;
640
            k += 2;
641
        }
642
        break;
643
    case EXP_D45:
644
        for (i = 1, k = 1; i <= nb_groups; i++) {
645
            uint8_t exp_min = exp[k];
646
            if (exp[k+1] < exp_min)
647
                exp_min = exp[k+1];
648
            if (exp[k+2] < exp_min)
649
                exp_min = exp[k+2];
650
            if (exp[k+3] < exp_min)
651
                exp_min = exp[k+3];
652
            exp[i] = exp_min;
653
            k += 4;
654
        }
655
        break;
656
    }
657

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

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

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

    
688

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

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

    
706
        blk = 0;
707
        while (blk < AC3_MAX_BLOCKS) {
708
            blk1 = blk + 1;
709

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

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

    
722
            encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk]);
723

    
724
            exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
725
            blk = blk1;
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
 * Finalize the mantissa bit count by adding in the grouped mantissas.
934
 */
935
static int compute_mantissa_size_final(int mant_cnt[5])
936
{
937
    // bap=1 : 3 mantissas in 5 bits
938
    int bits = (mant_cnt[1] / 3) * 5;
939
    // bap=2 : 3 mantissas in 7 bits
940
    // bap=4 : 2 mantissas in 7 bits
941
    bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
942
    // bap=3 : each mantissa is 3 bits
943
    bits += mant_cnt[3] * 3;
944
    return bits;
945
}
946

    
947

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

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

    
977

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

    
994

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

    
1008
    snr_offset = (snr_offset - 240) << 2;
1009

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

    
1043

    
1044
/**
1045
 * Constant bitrate bit allocation search.
1046
 * Find the largest SNR offset that will allow data to fit in the frame.
1047
 */
1048
static int cbr_bit_allocation(AC3EncodeContext *s)
1049
{
1050
    int ch;
1051
    int bits_left;
1052
    int snr_offset, snr_incr;
1053

    
1054
    bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1055
    if (bits_left < 0)
1056
        return AVERROR(EINVAL);
1057

    
1058
    snr_offset = s->coarse_snr_offset << 4;
1059

    
1060
    /* if previous frame SNR offset was 1023, check if current frame can also
1061
       use SNR offset of 1023. if so, skip the search. */
1062
    if ((snr_offset | s->fine_snr_offset[0]) == 1023) {
1063
        if (bit_alloc(s, 1023) <= bits_left)
1064
            return 0;
1065
    }
1066

    
1067
    while (snr_offset >= 0 &&
1068
           bit_alloc(s, snr_offset) > bits_left) {
1069
        snr_offset -= 64;
1070
    }
1071
    if (snr_offset < 0)
1072
        return AVERROR(EINVAL);
1073

    
1074
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1075
    for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1076
        while (snr_offset + snr_incr <= 1023 &&
1077
               bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1078
            snr_offset += snr_incr;
1079
            FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1080
        }
1081
    }
1082
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1083
    reset_block_bap(s);
1084

    
1085
    s->coarse_snr_offset = snr_offset >> 4;
1086
    for (ch = 0; ch < s->channels; ch++)
1087
        s->fine_snr_offset[ch] = snr_offset & 0xF;
1088

    
1089
    return 0;
1090
}
1091

    
1092

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

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

    
1133

    
1134
/**
1135
 * Reduce the bandwidth to reduce the number of bits used for a given SNR offset.
1136
 * This is a second fallback for when bit allocation still fails after exponents
1137
 * have been downgraded.
1138
 * @return non-zero if bandwidth reduction was unsuccessful
1139
 */
1140
static int reduce_bandwidth(AC3EncodeContext *s, int min_bw_code)
1141
{
1142
    int ch;
1143

    
1144
    if (s->bandwidth_code[0] > min_bw_code) {
1145
        for (ch = 0; ch < s->fbw_channels; ch++) {
1146
            s->bandwidth_code[ch]--;
1147
            s->nb_coefs[ch] = s->bandwidth_code[ch] * 3 + 73;
1148
        }
1149
        return 0;
1150
    }
1151
    return -1;
1152
}
1153

    
1154

    
1155
/**
1156
 * Perform bit allocation search.
1157
 * Finds the SNR offset value that maximizes quality and fits in the specified
1158
 * frame size.  Output is the SNR offset and a set of bit allocation pointers
1159
 * used to quantize the mantissas.
1160
 */
1161
static int compute_bit_allocation(AC3EncodeContext *s)
1162
{
1163
    int ret;
1164

    
1165
    count_frame_bits(s);
1166

    
1167
    bit_alloc_masking(s);
1168

    
1169
    ret = cbr_bit_allocation(s);
1170
    while (ret) {
1171
        /* fallback 1: downgrade exponents */
1172
        if (!downgrade_exponents(s)) {
1173
            extract_exponents(s);
1174
            encode_exponents(s);
1175
            group_exponents(s);
1176
            ret = compute_bit_allocation(s);
1177
            continue;
1178
        }
1179

    
1180
        /* fallback 2: reduce bandwidth */
1181
        /* only do this if the user has not specified a specific cutoff
1182
           frequency */
1183
        if (!s->cutoff && !reduce_bandwidth(s, 0)) {
1184
            process_exponents(s);
1185
            ret = compute_bit_allocation(s);
1186
            continue;
1187
        }
1188

    
1189
        /* fallbacks were not enough... */
1190
        break;
1191
    }
1192

    
1193
    return ret;
1194
}
1195

    
1196

    
1197
/**
1198
 * Symmetric quantization on 'levels' levels.
1199
 */
1200
static inline int sym_quant(int c, int e, int levels)
1201
{
1202
    int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1203
    av_assert2(v >= 0 && v < levels);
1204
    return v;
1205
}
1206

    
1207

    
1208
/**
1209
 * Asymmetric quantization on 2^qbits levels.
1210
 */
1211
static inline int asym_quant(int c, int e, int qbits)
1212
{
1213
    int lshift, m, v;
1214

    
1215
    lshift = e + qbits - 24;
1216
    if (lshift >= 0)
1217
        v = c << lshift;
1218
    else
1219
        v = c >> (-lshift);
1220
    /* rounding */
1221
    v = (v + 1) >> 1;
1222
    m = (1 << (qbits-1));
1223
    if (v >= m)
1224
        v = m - 1;
1225
    av_assert2(v >= -m);
1226
    return v & ((1 << qbits)-1);
1227
}
1228

    
1229

    
1230
/**
1231
 * Quantize a set of mantissas for a single channel in a single block.
1232
 */
1233
static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1234
                                      uint8_t *exp,
1235
                                      uint8_t *bap, uint16_t *qmant, int n)
1236
{
1237
    int i;
1238

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

    
1323

    
1324
/**
1325
 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1326
 */
1327
static void quantize_mantissas(AC3EncodeContext *s)
1328
{
1329
    int blk, ch;
1330

    
1331

    
1332
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1333
        AC3Block *block = &s->blocks[blk];
1334
        AC3Block *ref_block;
1335
        AC3Mant m = { 0 };
1336

    
1337
        for (ch = 0; ch < s->channels; ch++) {
1338
            ref_block = block->exp_ref_block[ch];
1339
            quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1340
                                      ref_block->exp[ch], ref_block->bap[ch],
1341
                                      block->qmant[ch], s->nb_coefs[ch]);
1342
        }
1343
    }
1344
}
1345

    
1346

    
1347
/**
1348
 * Write the AC-3 frame header to the output bitstream.
1349
 */
1350
static void output_frame_header(AC3EncodeContext *s)
1351
{
1352
    AC3EncOptions *opt = &s->options;
1353

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

    
1402

    
1403
/**
1404
 * Write one audio block to the output bitstream.
1405
 */
1406
static void output_audio_block(AC3EncodeContext *s, int blk)
1407
{
1408
    int ch, i, baie, rbnd;
1409
    AC3Block *block = &s->blocks[blk];
1410

    
1411
    /* block switching */
1412
    for (ch = 0; ch < s->fbw_channels; ch++)
1413
        put_bits(&s->pb, 1, 0);
1414

    
1415
    /* dither flags */
1416
    for (ch = 0; ch < s->fbw_channels; ch++)
1417
        put_bits(&s->pb, 1, 1);
1418

    
1419
    /* dynamic range codes */
1420
    put_bits(&s->pb, 1, 0);
1421

    
1422
    /* channel coupling */
1423
    if (!blk) {
1424
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
1425
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
1426
    } else {
1427
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1428
    }
1429

    
1430
    /* stereo rematrixing */
1431
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1432
        put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1433
        if (block->new_rematrixing_strategy) {
1434
            /* rematrixing flags */
1435
            for (rbnd = 0; rbnd < s->num_rematrixing_bands; rbnd++)
1436
                put_bits(&s->pb, 1, block->rematrixing_flags[rbnd]);
1437
        }
1438
    }
1439

    
1440
    /* exponent strategy */
1441
    for (ch = 0; ch < s->fbw_channels; ch++)
1442
        put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1443
    if (s->lfe_on)
1444
        put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1445

    
1446
    /* bandwidth */
1447
    for (ch = 0; ch < s->fbw_channels; ch++) {
1448
        if (s->exp_strategy[ch][blk] != EXP_REUSE)
1449
            put_bits(&s->pb, 6, s->bandwidth_code[ch]);
1450
    }
1451

    
1452
    /* exponents */
1453
    for (ch = 0; ch < s->channels; ch++) {
1454
        int nb_groups;
1455

    
1456
        if (s->exp_strategy[ch][blk] == EXP_REUSE)
1457
            continue;
1458

    
1459
        /* DC exponent */
1460
        put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1461

    
1462
        /* exponent groups */
1463
        nb_groups = exponent_group_tab[s->exp_strategy[ch][blk]-1][s->nb_coefs[ch]];
1464
        for (i = 1; i <= nb_groups; i++)
1465
            put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1466

    
1467
        /* gain range info */
1468
        if (ch != s->lfe_channel)
1469
            put_bits(&s->pb, 2, 0);
1470
    }
1471

    
1472
    /* bit allocation info */
1473
    baie = (blk == 0);
1474
    put_bits(&s->pb, 1, baie);
1475
    if (baie) {
1476
        put_bits(&s->pb, 2, s->slow_decay_code);
1477
        put_bits(&s->pb, 2, s->fast_decay_code);
1478
        put_bits(&s->pb, 2, s->slow_gain_code);
1479
        put_bits(&s->pb, 2, s->db_per_bit_code);
1480
        put_bits(&s->pb, 3, s->floor_code);
1481
    }
1482

    
1483
    /* snr offset */
1484
    put_bits(&s->pb, 1, baie);
1485
    if (baie) {
1486
        put_bits(&s->pb, 6, s->coarse_snr_offset);
1487
        for (ch = 0; ch < s->channels; ch++) {
1488
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1489
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1490
        }
1491
    }
1492

    
1493
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1494
    put_bits(&s->pb, 1, 0); /* no data to skip */
1495

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

    
1517

    
1518
/** CRC-16 Polynomial */
1519
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1520

    
1521

    
1522
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1523
{
1524
    unsigned int c;
1525

    
1526
    c = 0;
1527
    while (a) {
1528
        if (a & 1)
1529
            c ^= b;
1530
        a = a >> 1;
1531
        b = b << 1;
1532
        if (b & (1 << 16))
1533
            b ^= poly;
1534
    }
1535
    return c;
1536
}
1537

    
1538

    
1539
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1540
{
1541
    unsigned int r;
1542
    r = 1;
1543
    while (n) {
1544
        if (n & 1)
1545
            r = mul_poly(r, a, poly);
1546
        a = mul_poly(a, a, poly);
1547
        n >>= 1;
1548
    }
1549
    return r;
1550
}
1551

    
1552

    
1553
/**
1554
 * Fill the end of the frame with 0's and compute the two CRCs.
1555
 */
1556
static void output_frame_end(AC3EncodeContext *s)
1557
{
1558
    const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1559
    int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1560
    uint8_t *frame;
1561

    
1562
    frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1563

    
1564
    /* pad the remainder of the frame with zeros */
1565
    av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1566
    flush_put_bits(&s->pb);
1567
    frame = s->pb.buf;
1568
    pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1569
    av_assert2(pad_bytes >= 0);
1570
    if (pad_bytes > 0)
1571
        memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1572

    
1573
    /* compute crc1 */
1574
    /* this is not so easy because it is at the beginning of the data... */
1575
    crc1    = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1576
    crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1577
    crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1578
    AV_WB16(frame + 2, crc1);
1579

    
1580
    /* compute crc2 */
1581
    crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1582
                          s->frame_size - frame_size_58 - 3);
1583
    crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1584
    /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1585
    if (crc2 == 0x770B) {
1586
        frame[s->frame_size - 3] ^= 0x1;
1587
        crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1588
    }
1589
    crc2 = av_bswap16(crc2);
1590
    AV_WB16(frame + s->frame_size - 2, crc2);
1591
}
1592

    
1593

    
1594
/**
1595
 * Write the frame to the output bitstream.
1596
 */
1597
static void output_frame(AC3EncodeContext *s, unsigned char *frame)
1598
{
1599
    int blk;
1600

    
1601
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1602

    
1603
    output_frame_header(s);
1604

    
1605
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1606
        output_audio_block(s, blk);
1607

    
1608
    output_frame_end(s);
1609
}
1610

    
1611

    
1612
static void dprint_options(AVCodecContext *avctx)
1613
{
1614
#ifdef DEBUG
1615
    AC3EncodeContext *s = avctx->priv_data;
1616
    AC3EncOptions *opt = &s->options;
1617
    char strbuf[32];
1618

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

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

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

    
1711
            switch (opt->ad_converter_type) {
1712
            case 0:  strncpy(strbuf, "standard", 32); break;
1713
            case 1:  strncpy(strbuf, "hdcd", 32);     break;
1714
            default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
1715
            }
1716
            av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
1717
        } else {
1718
            av_dlog(avctx, "extended bitstream info 2: {not written}\n");
1719
        }
1720
    }
1721
#endif
1722
}
1723

    
1724

    
1725
#define FLT_OPTION_THRESHOLD 0.01
1726

    
1727
static int validate_float_option(float v, const float *v_list, int v_list_size)
1728
{
1729
    int i;
1730

    
1731
    for (i = 0; i < v_list_size; i++) {
1732
        if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
1733
            v > (v_list[i] - FLT_OPTION_THRESHOLD))
1734
            break;
1735
    }
1736
    if (i == v_list_size)
1737
        return -1;
1738

    
1739
    return i;
1740
}
1741

    
1742

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

    
1760

    
1761
/**
1762
 * Validate metadata options as set by AVOption system.
1763
 * These values can optionally be changed per-frame.
1764
 */
1765
static int validate_metadata(AVCodecContext *avctx)
1766
{
1767
    AC3EncodeContext *s = avctx->priv_data;
1768
    AC3EncOptions *opt = &s->options;
1769

    
1770
    /* validate mixing levels */
1771
    if (s->has_center) {
1772
        validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
1773
                           cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
1774
                           &s->center_mix_level);
1775
    }
1776
    if (s->has_surround) {
1777
        validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
1778
                           surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
1779
                           &s->surround_mix_level);
1780
    }
1781

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

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

    
1837
    /* set extended bsi 2 flag */
1838
    if (opt->dolby_surround_ex_mode >= 0 ||
1839
        opt->dolby_headphone_mode   >= 0 ||
1840
        opt->ad_converter_type      >= 0) {
1841
        /* default dolby surround ex mode */
1842
        if (opt->dolby_surround_ex_mode < 0)
1843
            opt->dolby_surround_ex_mode = 0;
1844
        /* default dolby headphone mode */
1845
        if (opt->dolby_headphone_mode < 0)
1846
            opt->dolby_headphone_mode = 0;
1847
        /* default A/D converter type */
1848
        if (opt->ad_converter_type < 0)
1849
            opt->ad_converter_type = 0;
1850
        opt->extended_bsi_2 = 1;
1851
    } else {
1852
        opt->extended_bsi_2 = 0;
1853
    }
1854

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

    
1870
    return 0;
1871
}
1872

    
1873

    
1874
/**
1875
 * Encode a single AC-3 frame.
1876
 */
1877
static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
1878
                            int buf_size, void *data)
1879
{
1880
    AC3EncodeContext *s = avctx->priv_data;
1881
    const SampleType *samples = data;
1882
    int ret;
1883

    
1884
    if (s->options.allow_per_frame_metadata) {
1885
        ret = validate_metadata(avctx);
1886
        if (ret)
1887
            return ret;
1888
    }
1889

    
1890
    if (s->bit_alloc.sr_code == 1)
1891
        adjust_frame_size(s);
1892

    
1893
    deinterleave_input_samples(s, samples);
1894

    
1895
    apply_mdct(s);
1896

    
1897
    scale_coefficients(s);
1898

    
1899
    compute_rematrixing_strategy(s);
1900

    
1901
    apply_rematrixing(s);
1902

    
1903
    process_exponents(s);
1904

    
1905
    ret = compute_bit_allocation(s);
1906
    if (ret) {
1907
        av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1908
        return ret;
1909
    }
1910

    
1911
    quantize_mantissas(s);
1912

    
1913
    output_frame(s, frame);
1914

    
1915
    return s->frame_size;
1916
}
1917

    
1918

    
1919
/**
1920
 * Finalize encoding and free any memory allocated by the encoder.
1921
 */
1922
static av_cold int ac3_encode_close(AVCodecContext *avctx)
1923
{
1924
    int blk, ch;
1925
    AC3EncodeContext *s = avctx->priv_data;
1926

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

    
1953
    mdct_end(&s->mdct);
1954

    
1955
    av_freep(&avctx->coded_frame);
1956
    return 0;
1957
}
1958

    
1959

    
1960
/**
1961
 * Set channel information during initialization.
1962
 */
1963
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1964
                                    int64_t *channel_layout)
1965
{
1966
    int ch_layout;
1967

    
1968
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
1969
        return AVERROR(EINVAL);
1970
    if ((uint64_t)*channel_layout > 0x7FF)
1971
        return AVERROR(EINVAL);
1972
    ch_layout = *channel_layout;
1973
    if (!ch_layout)
1974
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1975

    
1976
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1977
    s->channels     = channels;
1978
    s->fbw_channels = channels - s->lfe_on;
1979
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
1980
    if (s->lfe_on)
1981
        ch_layout -= AV_CH_LOW_FREQUENCY;
1982

    
1983
    switch (ch_layout) {
1984
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
1985
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
1986
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
1987
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
1988
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
1989
    case AV_CH_LAYOUT_QUAD:
1990
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
1991
    case AV_CH_LAYOUT_5POINT0:
1992
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
1993
    default:
1994
        return AVERROR(EINVAL);
1995
    }
1996
    s->has_center   = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
1997
    s->has_surround =  s->channel_mode & 0x04;
1998

    
1999
    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
2000
    *channel_layout = ch_layout;
2001
    if (s->lfe_on)
2002
        *channel_layout |= AV_CH_LOW_FREQUENCY;
2003

    
2004
    return 0;
2005
}
2006

    
2007

    
2008
static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
2009
{
2010
    int i, ret;
2011

    
2012
    /* validate channel layout */
2013
    if (!avctx->channel_layout) {
2014
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
2015
                                      "encoder will guess the layout, but it "
2016
                                      "might be incorrect.\n");
2017
    }
2018
    ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
2019
    if (ret) {
2020
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
2021
        return ret;
2022
    }
2023

    
2024
    /* validate sample rate */
2025
    for (i = 0; i < 9; i++) {
2026
        if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
2027
            break;
2028
    }
2029
    if (i == 9) {
2030
        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
2031
        return AVERROR(EINVAL);
2032
    }
2033
    s->sample_rate        = avctx->sample_rate;
2034
    s->bit_alloc.sr_shift = i % 3;
2035
    s->bit_alloc.sr_code  = i / 3;
2036
    s->bitstream_id       = 8 + s->bit_alloc.sr_shift;
2037

    
2038
    /* validate bit rate */
2039
    for (i = 0; i < 19; i++) {
2040
        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
2041
            break;
2042
    }
2043
    if (i == 19) {
2044
        av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2045
        return AVERROR(EINVAL);
2046
    }
2047
    s->bit_rate        = avctx->bit_rate;
2048
    s->frame_size_code = i << 1;
2049

    
2050
    /* validate cutoff */
2051
    if (avctx->cutoff < 0) {
2052
        av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2053
        return AVERROR(EINVAL);
2054
    }
2055
    s->cutoff = avctx->cutoff;
2056
    if (s->cutoff > (s->sample_rate >> 1))
2057
        s->cutoff = s->sample_rate >> 1;
2058

    
2059
    /* validate audio service type / channels combination */
2060
    if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
2061
         avctx->channels == 1) ||
2062
        ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
2063
          avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY  ||
2064
          avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
2065
         && avctx->channels > 1)) {
2066
        av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
2067
                                    "specified number of channels\n");
2068
        return AVERROR(EINVAL);
2069
    }
2070

    
2071
    ret = validate_metadata(avctx);
2072
    if (ret)
2073
        return ret;
2074

    
2075
    s->rematrixing_enabled = s->options.stereo_rematrixing &&
2076
                             (s->channel_mode == AC3_CHMODE_STEREO);
2077

    
2078
    return 0;
2079
}
2080

    
2081

    
2082
/**
2083
 * Set bandwidth for all channels.
2084
 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2085
 * default value will be used.
2086
 */
2087
static av_cold void set_bandwidth(AC3EncodeContext *s)
2088
{
2089
    int ch, bw_code;
2090

    
2091
    if (s->cutoff) {
2092
        /* calculate bandwidth based on user-specified cutoff frequency */
2093
        int fbw_coeffs;
2094
        fbw_coeffs     = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2095
        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2096
    } else {
2097
        /* use default bandwidth setting */
2098
        bw_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2099
    }
2100

    
2101
    /* set number of coefficients for each channel */
2102
    for (ch = 0; ch < s->fbw_channels; ch++) {
2103
        s->bandwidth_code[ch] = bw_code;
2104
        s->nb_coefs[ch]       = bw_code * 3 + 73;
2105
    }
2106
    if (s->lfe_on)
2107
        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
2108
}
2109

    
2110

    
2111
static av_cold int allocate_buffers(AVCodecContext *avctx)
2112
{
2113
    int blk, ch;
2114
    AC3EncodeContext *s = avctx->priv_data;
2115

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

    
2160
        for (ch = 0; ch < s->channels; ch++) {
2161
            /* arrangement: block, channel, coeff */
2162
            block->bap[ch]         = &s->bap_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
2163
            block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (blk * s->channels + ch)];
2164
            block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * s->channels + ch)];
2165
            block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
2166
            block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * s->channels + ch)];
2167
            block->mask[ch]        = &s->mask_buffer       [64            * (blk * s->channels + ch)];
2168
            block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * s->channels + ch)];
2169

    
2170
            /* arrangement: channel, block, coeff */
2171
            block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2172
        }
2173
    }
2174

    
2175
    if (CONFIG_AC3ENC_FLOAT) {
2176
        FF_ALLOC_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * s->channels *
2177
                         AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
2178
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2179
            AC3Block *block = &s->blocks[blk];
2180
            FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2181
                              sizeof(*block->fixed_coef), alloc_fail);
2182
            for (ch = 0; ch < s->channels; ch++)
2183
                block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
2184
        }
2185
    } else {
2186
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2187
            AC3Block *block = &s->blocks[blk];
2188
            FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2189
                              sizeof(*block->fixed_coef), alloc_fail);
2190
            for (ch = 0; ch < s->channels; ch++)
2191
                block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2192
        }
2193
    }
2194

    
2195
    return 0;
2196
alloc_fail:
2197
    return AVERROR(ENOMEM);
2198
}
2199

    
2200

    
2201
/**
2202
 * Initialize the encoder.
2203
 */
2204
static av_cold int ac3_encode_init(AVCodecContext *avctx)
2205
{
2206
    AC3EncodeContext *s = avctx->priv_data;
2207
    int ret, frame_size_58;
2208

    
2209
    avctx->frame_size = AC3_FRAME_SIZE;
2210

    
2211
    ff_ac3_common_init();
2212

    
2213
    ret = validate_options(avctx, s);
2214
    if (ret)
2215
        return ret;
2216

    
2217
    s->bitstream_mode = avctx->audio_service_type;
2218
    if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2219
        s->bitstream_mode = 0x7;
2220

    
2221
    s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2222
    s->bits_written    = 0;
2223
    s->samples_written = 0;
2224
    s->frame_size      = s->frame_size_min;
2225

    
2226
    /* calculate crc_inv for both possible frame sizes */
2227
    frame_size_58 = (( s->frame_size    >> 2) + ( s->frame_size    >> 4)) << 1;
2228
    s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2229
    if (s->bit_alloc.sr_code == 1) {
2230
        frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2231
        s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2232
    }
2233

    
2234
    set_bandwidth(s);
2235

    
2236
    exponent_init(s);
2237

    
2238
    bit_alloc_init(s);
2239

    
2240
    ret = mdct_init(avctx, &s->mdct, 9);
2241
    if (ret)
2242
        goto init_fail;
2243

    
2244
    ret = allocate_buffers(avctx);
2245
    if (ret)
2246
        goto init_fail;
2247

    
2248
    avctx->coded_frame= avcodec_alloc_frame();
2249

    
2250
    dsputil_init(&s->dsp, avctx);
2251
    ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2252

    
2253
    dprint_options(avctx);
2254

    
2255
    return 0;
2256
init_fail:
2257
    ac3_encode_close(avctx);
2258
    return ret;
2259
}