Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ 8745e9c4

History | View | Annotate | Download (78.2 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
/* stereo rematrixing algorithms */
56
#define AC3_REMATRIXING_IS_STATIC 0x1
57
#define AC3_REMATRIXING_SUMS    0
58
#define AC3_REMATRIXING_NONE    1
59
#define AC3_REMATRIXING_ALWAYS  3
60

    
61
#if CONFIG_AC3ENC_FLOAT
62
#define MAC_COEF(d,a,b) ((d)+=(a)*(b))
63
typedef float SampleType;
64
typedef float CoefType;
65
typedef float CoefSumType;
66
#else
67
#define MAC_COEF(d,a,b) MAC64(d,a,b)
68
typedef int16_t SampleType;
69
typedef int32_t CoefType;
70
typedef int64_t CoefSumType;
71
#endif
72

    
73
typedef struct AC3MDCTContext {
74
    const SampleType *window;           ///< MDCT window function
75
    FFTContext fft;                     ///< FFT context for MDCT calculation
76
} AC3MDCTContext;
77

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

    
104
    /* other encoding options */
105
    int allow_per_frame_metadata;
106
} AC3EncOptions;
107

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

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

    
138
    AC3Block blocks[AC3_MAX_BLOCKS];        ///< per-block info
139

    
140
    int bitstream_id;                       ///< bitstream id                           (bsid)
141
    int bitstream_mode;                     ///< bitstream mode                         (bsmod)
142

    
143
    int bit_rate;                           ///< target bit rate, in bits-per-second
144
    int sample_rate;                        ///< sampling frequency, in Hz
145

    
146
    int frame_size_min;                     ///< minimum frame size in case rounding is necessary
147
    int frame_size;                         ///< current frame size in bytes
148
    int frame_size_code;                    ///< frame size code                        (frmsizecod)
149
    uint16_t crc_inv[2];
150
    int bits_written;                       ///< bit count    (used to avg. bitrate)
151
    int samples_written;                    ///< sample count (used to avg. bitrate)
152

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

    
162
    int center_mix_level;                   ///< center mix level code
163
    int surround_mix_level;                 ///< surround mix level code
164
    int ltrt_center_mix_level;              ///< Lt/Rt center mix level code
165
    int ltrt_surround_mix_level;            ///< Lt/Rt surround mix level code
166
    int loro_center_mix_level;              ///< Lo/Ro center mix level code
167
    int loro_surround_mix_level;            ///< Lo/Ro surround mix level code
168

    
169
    int cutoff;                             ///< user-specified cutoff frequency, in Hz
170
    int bandwidth_code[AC3_MAX_CHANNELS];   ///< bandwidth code (0 to 60)               (chbwcod)
171
    int nb_coefs[AC3_MAX_CHANNELS];
172

    
173
    int rematrixing;                        ///< determines how rematrixing strategy is calculated
174
    int num_rematrixing_bands;              ///< number of rematrixing bands
175

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

    
190
    SampleType **planar_samples;
191
    uint8_t *bap_buffer;
192
    uint8_t *bap1_buffer;
193
    CoefType *mdct_coef_buffer;
194
    int32_t *fixed_coef_buffer;
195
    uint8_t *exp_buffer;
196
    uint8_t *grouped_exp_buffer;
197
    int16_t *psd_buffer;
198
    int16_t *band_psd_buffer;
199
    int16_t *mask_buffer;
200
    uint16_t *qmant_buffer;
201

    
202
    uint8_t exp_strategy[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< exponent strategies
203

    
204
    DECLARE_ALIGNED(32, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
205
} AC3EncodeContext;
206

    
207
typedef struct AC3Mant {
208
    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
209
    int mant1_cnt, mant2_cnt, mant4_cnt;    ///< mantissa counts for bap=1,2,4
210
} AC3Mant;
211

    
212
#define CMIXLEV_NUM_OPTIONS 3
213
static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
214
    LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
215
};
216

    
217
#define SURMIXLEV_NUM_OPTIONS 3
218
static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
219
    LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
220
};
221

    
222
#define EXTMIXLEV_NUM_OPTIONS 8
223
static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
224
    LEVEL_PLUS_3DB,  LEVEL_PLUS_1POINT5DB,  LEVEL_ONE,       LEVEL_MINUS_4POINT5DB,
225
    LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
226
};
227

    
228

    
229
#define OFFSET(param) offsetof(AC3EncodeContext, options.param)
230
#define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
231

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

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

    
283

    
284
/* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
285

    
286
static av_cold void mdct_end(AC3MDCTContext *mdct);
287

    
288
static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
289
                             int nbits);
290

    
291
static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
292
                         const SampleType *window, unsigned int len);
293

    
294
static int normalize_samples(AC3EncodeContext *s);
295

    
296
static void scale_coefficients(AC3EncodeContext *s);
297

    
298

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

    
305

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

    
331

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

    
340
    { {  0,  0,  0, 12, 16, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
341
      {  0,  0,  0, 16, 20, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
342
      {  0,  0,  0, 32, 40, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
343

    
344
    { {  0,  0,  0,  0,  0,  0,  0, 20, 24, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
345
      {  0,  0,  0,  0,  0,  0,  4, 24, 28, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
346
      {  0,  0,  0,  0,  0,  0, 20, 44, 52, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
347

    
348
    { {  0,  0,  0,  0,  0,  0,  0,  0,  0, 16, 24, 32, 40, 48, 48, 48, 48, 48, 48 },
349
      {  0,  0,  0,  0,  0,  0,  0,  0,  4, 20, 28, 36, 44, 56, 56, 56, 56, 56, 56 },
350
      {  0,  0,  0,  0,  0,  0,  0,  0, 20, 40, 48, 60, 60, 60, 60, 60, 60, 60, 60 } },
351

    
352
    { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 12, 24, 32, 48, 48, 48, 48, 48, 48 },
353
      {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 16, 28, 36, 56, 56, 56, 56, 56, 56 },
354
      {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 32, 48, 60, 60, 60, 60, 60, 60, 60 } },
355

    
356
    { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  8, 20, 32, 40, 48, 48, 48, 48 },
357
      {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 12, 24, 36, 44, 56, 56, 56, 56 },
358
      {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 28, 44, 60, 60, 60, 60, 60, 60 } }
359
};
360

    
361

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

    
378

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

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

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

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

    
407

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

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

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

    
424
            block->coeff_shift[ch] = normalize_samples(s);
425

    
426
            s->mdct.fft.mdct_calcw(&s->mdct.fft, block->mdct_coef[ch],
427
                                   s->windowed_samples);
428
        }
429
    }
430
}
431

    
432

    
433
/**
434
 * Initialize stereo rematrixing.
435
 * If the strategy does not change for each frame, set the rematrixing flags.
436
 */
437
static void rematrixing_init(AC3EncodeContext *s)
438
{
439
    if (s->channel_mode == AC3_CHMODE_STEREO)
440
        s->rematrixing = AC3_REMATRIXING_SUMS;
441
    else
442
        s->rematrixing = AC3_REMATRIXING_NONE;
443
    /* NOTE: AC3_REMATRIXING_ALWAYS might be used in
444
             the future in conjunction with channel coupling. */
445

    
446
    if (s->rematrixing & AC3_REMATRIXING_IS_STATIC) {
447
        int flag = (s->rematrixing == AC3_REMATRIXING_ALWAYS);
448
        s->blocks[0].new_rematrixing_strategy = 1;
449
        memset(s->blocks[0].rematrixing_flags, flag,
450
               sizeof(s->blocks[0].rematrixing_flags));
451
    }
452
}
453

    
454

    
455
/**
456
 * Determine rematrixing flags for each block and band.
457
 */
458
static void compute_rematrixing_strategy(AC3EncodeContext *s)
459
{
460
    int nb_coefs;
461
    int blk, bnd, i;
462
    AC3Block *block, *block0;
463

    
464
    s->num_rematrixing_bands = 4;
465

    
466
    if (s->rematrixing & AC3_REMATRIXING_IS_STATIC)
467
        return;
468

    
469
    nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
470

    
471
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
472
        block = &s->blocks[blk];
473
        block->new_rematrixing_strategy = !blk;
474
        for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
475
            /* calculate calculate sum of squared coeffs for one band in one block */
476
            int start = ff_ac3_rematrix_band_tab[bnd];
477
            int end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
478
            CoefSumType sum[4] = {0,};
479
            for (i = start; i < end; i++) {
480
                CoefType lt = block->mdct_coef[0][i];
481
                CoefType rt = block->mdct_coef[1][i];
482
                CoefType md = lt + rt;
483
                CoefType sd = lt - rt;
484
                MAC_COEF(sum[0], lt, lt);
485
                MAC_COEF(sum[1], rt, rt);
486
                MAC_COEF(sum[2], md, md);
487
                MAC_COEF(sum[3], sd, sd);
488
            }
489

    
490
            /* compare sums to determine if rematrixing will be used for this band */
491
            if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
492
                block->rematrixing_flags[bnd] = 1;
493
            else
494
                block->rematrixing_flags[bnd] = 0;
495

    
496
            /* determine if new rematrixing flags will be sent */
497
            if (blk &&
498
                block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
499
                block->new_rematrixing_strategy = 1;
500
            }
501
        }
502
        block0 = block;
503
    }
504
}
505

    
506

    
507
/**
508
 * Apply stereo rematrixing to coefficients based on rematrixing flags.
509
 */
510
static void apply_rematrixing(AC3EncodeContext *s)
511
{
512
    int nb_coefs;
513
    int blk, bnd, i;
514
    int start, end;
515
    uint8_t *flags;
516

    
517
    if (s->rematrixing == AC3_REMATRIXING_NONE)
518
        return;
519

    
520
    nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
521

    
522
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
523
        AC3Block *block = &s->blocks[blk];
524
        if (block->new_rematrixing_strategy)
525
            flags = block->rematrixing_flags;
526
        for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
527
            if (flags[bnd]) {
528
                start = ff_ac3_rematrix_band_tab[bnd];
529
                end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
530
                for (i = start; i < end; i++) {
531
                    int32_t lt = block->fixed_coef[0][i];
532
                    int32_t rt = block->fixed_coef[1][i];
533
                    block->fixed_coef[0][i] = (lt + rt) >> 1;
534
                    block->fixed_coef[1][i] = (lt - rt) >> 1;
535
                }
536
            }
537
        }
538
    }
539
}
540

    
541

    
542
/**
543
 * Initialize exponent tables.
544
 */
545
static av_cold void exponent_init(AC3EncodeContext *s)
546
{
547
    int i;
548
    for (i = 73; i < 256; i++) {
549
        exponent_group_tab[0][i] = (i - 1) /  3;
550
        exponent_group_tab[1][i] = (i + 2) /  6;
551
        exponent_group_tab[2][i] = (i + 8) / 12;
552
    }
553
    /* LFE */
554
    exponent_group_tab[0][7] = 2;
555
}
556

    
557

    
558
/**
559
 * Extract exponents from the MDCT coefficients.
560
 * This takes into account the normalization that was done to the input samples
561
 * by adjusting the exponents by the exponent shift values.
562
 */
563
static void extract_exponents(AC3EncodeContext *s)
564
{
565
    int blk, ch;
566

    
567
    for (ch = 0; ch < s->channels; ch++) {
568
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
569
            AC3Block *block = &s->blocks[blk];
570
            s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch],
571
                                        AC3_MAX_COEFS);
572
        }
573
    }
574
}
575

    
576

    
577
/**
578
 * Exponent Difference Threshold.
579
 * New exponents are sent if their SAD exceed this number.
580
 */
581
#define EXP_DIFF_THRESHOLD 500
582

    
583

    
584
/**
585
 * Calculate exponent strategies for all blocks in a single channel.
586
 */
587
static void compute_exp_strategy_ch(AC3EncodeContext *s, uint8_t *exp_strategy,
588
                                    uint8_t *exp)
589
{
590
    int blk, blk1;
591
    int exp_diff;
592

    
593
    /* estimate if the exponent variation & decide if they should be
594
       reused in the next frame */
595
    exp_strategy[0] = EXP_NEW;
596
    exp += AC3_MAX_COEFS;
597
    for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
598
        exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
599
        if (exp_diff > EXP_DIFF_THRESHOLD)
600
            exp_strategy[blk] = EXP_NEW;
601
        else
602
            exp_strategy[blk] = EXP_REUSE;
603
        exp += AC3_MAX_COEFS;
604
    }
605

    
606
    /* now select the encoding strategy type : if exponents are often
607
       recoded, we use a coarse encoding */
608
    blk = 0;
609
    while (blk < AC3_MAX_BLOCKS) {
610
        blk1 = blk + 1;
611
        while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
612
            blk1++;
613
        switch (blk1 - blk) {
614
        case 1:  exp_strategy[blk] = EXP_D45; break;
615
        case 2:
616
        case 3:  exp_strategy[blk] = EXP_D25; break;
617
        default: exp_strategy[blk] = EXP_D15; break;
618
        }
619
        blk = blk1;
620
    }
621
}
622

    
623

    
624
/**
625
 * Calculate exponent strategies for all channels.
626
 * Array arrangement is reversed to simplify the per-channel calculation.
627
 */
628
static void compute_exp_strategy(AC3EncodeContext *s)
629
{
630
    int ch, blk;
631

    
632
    for (ch = 0; ch < s->fbw_channels; ch++) {
633
        compute_exp_strategy_ch(s, s->exp_strategy[ch], s->blocks[0].exp[ch]);
634
    }
635
    if (s->lfe_on) {
636
        ch = s->lfe_channel;
637
        s->exp_strategy[ch][0] = EXP_D15;
638
        for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
639
            s->exp_strategy[ch][blk] = EXP_REUSE;
640
    }
641
}
642

    
643

    
644
/**
645
 * Update the exponents so that they are the ones the decoder will decode.
646
 */
647
static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy)
648
{
649
    int nb_groups, i, k;
650

    
651
    nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
652

    
653
    /* for each group, compute the minimum exponent */
654
    switch(exp_strategy) {
655
    case EXP_D25:
656
        for (i = 1, k = 1; i <= nb_groups; i++) {
657
            uint8_t exp_min = exp[k];
658
            if (exp[k+1] < exp_min)
659
                exp_min = exp[k+1];
660
            exp[i] = exp_min;
661
            k += 2;
662
        }
663
        break;
664
    case EXP_D45:
665
        for (i = 1, k = 1; i <= nb_groups; i++) {
666
            uint8_t exp_min = exp[k];
667
            if (exp[k+1] < exp_min)
668
                exp_min = exp[k+1];
669
            if (exp[k+2] < exp_min)
670
                exp_min = exp[k+2];
671
            if (exp[k+3] < exp_min)
672
                exp_min = exp[k+3];
673
            exp[i] = exp_min;
674
            k += 4;
675
        }
676
        break;
677
    }
678

    
679
    /* constraint for DC exponent */
680
    if (exp[0] > 15)
681
        exp[0] = 15;
682

    
683
    /* decrease the delta between each groups to within 2 so that they can be
684
       differentially encoded */
685
    for (i = 1; i <= nb_groups; i++)
686
        exp[i] = FFMIN(exp[i], exp[i-1] + 2);
687
    i--;
688
    while (--i >= 0)
689
        exp[i] = FFMIN(exp[i], exp[i+1] + 2);
690

    
691
    /* now we have the exponent values the decoder will see */
692
    switch (exp_strategy) {
693
    case EXP_D25:
694
        for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
695
            uint8_t exp1 = exp[i];
696
            exp[k--] = exp1;
697
            exp[k--] = exp1;
698
        }
699
        break;
700
    case EXP_D45:
701
        for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
702
            exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
703
            k -= 4;
704
        }
705
        break;
706
    }
707
}
708

    
709

    
710
/**
711
 * Encode exponents from original extracted form to what the decoder will see.
712
 * This copies and groups exponents based on exponent strategy and reduces
713
 * deltas between adjacent exponent groups so that they can be differentially
714
 * encoded.
715
 */
716
static void encode_exponents(AC3EncodeContext *s)
717
{
718
    int blk, blk1, ch;
719
    uint8_t *exp, *exp_strategy;
720
    int nb_coefs, num_reuse_blocks;
721

    
722
    for (ch = 0; ch < s->channels; ch++) {
723
        exp          = s->blocks[0].exp[ch];
724
        exp_strategy = s->exp_strategy[ch];
725
        nb_coefs     = s->nb_coefs[ch];
726

    
727
        blk = 0;
728
        while (blk < AC3_MAX_BLOCKS) {
729
            blk1 = blk + 1;
730

    
731
            /* count the number of EXP_REUSE blocks after the current block
732
               and set exponent reference block pointers */
733
            s->blocks[blk].exp_ref_block[ch] = &s->blocks[blk];
734
            while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
735
                s->blocks[blk1].exp_ref_block[ch] = &s->blocks[blk];
736
                blk1++;
737
            }
738
            num_reuse_blocks = blk1 - blk - 1;
739

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

    
743
            encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk]);
744

    
745
            exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
746
            blk = blk1;
747
        }
748
    }
749
}
750

    
751

    
752
/**
753
 * Group exponents.
754
 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
755
 * varies depending on exponent strategy and bandwidth.
756
 */
757
static void group_exponents(AC3EncodeContext *s)
758
{
759
    int blk, ch, i;
760
    int group_size, nb_groups, bit_count;
761
    uint8_t *p;
762
    int delta0, delta1, delta2;
763
    int exp0, exp1;
764

    
765
    bit_count = 0;
766
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
767
        AC3Block *block = &s->blocks[blk];
768
        for (ch = 0; ch < s->channels; ch++) {
769
            int exp_strategy = s->exp_strategy[ch][blk];
770
            if (exp_strategy == EXP_REUSE)
771
                continue;
772
            group_size = exp_strategy + (exp_strategy == EXP_D45);
773
            nb_groups = exponent_group_tab[exp_strategy-1][s->nb_coefs[ch]];
774
            bit_count += 4 + (nb_groups * 7);
775
            p = block->exp[ch];
776

    
777
            /* DC exponent */
778
            exp1 = *p++;
779
            block->grouped_exp[ch][0] = exp1;
780

    
781
            /* remaining exponents are delta encoded */
782
            for (i = 1; i <= nb_groups; i++) {
783
                /* merge three delta in one code */
784
                exp0   = exp1;
785
                exp1   = p[0];
786
                p     += group_size;
787
                delta0 = exp1 - exp0 + 2;
788
                av_assert2(delta0 >= 0 && delta0 <= 4);
789

    
790
                exp0   = exp1;
791
                exp1   = p[0];
792
                p     += group_size;
793
                delta1 = exp1 - exp0 + 2;
794
                av_assert2(delta1 >= 0 && delta1 <= 4);
795

    
796
                exp0   = exp1;
797
                exp1   = p[0];
798
                p     += group_size;
799
                delta2 = exp1 - exp0 + 2;
800
                av_assert2(delta2 >= 0 && delta2 <= 4);
801

    
802
                block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
803
            }
804
        }
805
    }
806

    
807
    s->exponent_bits = bit_count;
808
}
809

    
810

    
811
/**
812
 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
813
 * Extract exponents from MDCT coefficients, calculate exponent strategies,
814
 * and encode final exponents.
815
 */
816
static void process_exponents(AC3EncodeContext *s)
817
{
818
    extract_exponents(s);
819

    
820
    compute_exp_strategy(s);
821

    
822
    encode_exponents(s);
823

    
824
    group_exponents(s);
825

    
826
    emms_c();
827
}
828

    
829

    
830
/**
831
 * Count frame bits that are based solely on fixed parameters.
832
 * This only has to be run once when the encoder is initialized.
833
 */
834
static void count_frame_bits_fixed(AC3EncodeContext *s)
835
{
836
    static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
837
    int blk;
838
    int frame_bits;
839

    
840
    /* assumptions:
841
     *   no dynamic range codes
842
     *   no channel coupling
843
     *   bit allocation parameters do not change between blocks
844
     *   SNR offsets do not change between blocks
845
     *   no delta bit allocation
846
     *   no skipped data
847
     *   no auxilliary data
848
     */
849

    
850
    /* header size */
851
    frame_bits = 65;
852
    frame_bits += frame_bits_inc[s->channel_mode];
853

    
854
    /* audio blocks */
855
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
856
        frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
857
        if (s->channel_mode == AC3_CHMODE_STEREO) {
858
            frame_bits++; /* rematstr */
859
        }
860
        frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
861
        if (s->lfe_on)
862
            frame_bits++; /* lfeexpstr */
863
        frame_bits++; /* baie */
864
        frame_bits++; /* snr */
865
        frame_bits += 2; /* delta / skip */
866
    }
867
    frame_bits++; /* cplinu for block 0 */
868
    /* bit alloc info */
869
    /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
870
    /* csnroffset[6] */
871
    /* (fsnoffset[4] + fgaincod[4]) * c */
872
    frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
873

    
874
    /* auxdatae, crcrsv */
875
    frame_bits += 2;
876

    
877
    /* CRC */
878
    frame_bits += 16;
879

    
880
    s->frame_bits_fixed = frame_bits;
881
}
882

    
883

    
884
/**
885
 * Initialize bit allocation.
886
 * Set default parameter codes and calculate parameter values.
887
 */
888
static void bit_alloc_init(AC3EncodeContext *s)
889
{
890
    int ch;
891

    
892
    /* init default parameters */
893
    s->slow_decay_code = 2;
894
    s->fast_decay_code = 1;
895
    s->slow_gain_code  = 1;
896
    s->db_per_bit_code = 3;
897
    s->floor_code      = 7;
898
    for (ch = 0; ch < s->channels; ch++)
899
        s->fast_gain_code[ch] = 4;
900

    
901
    /* initial snr offset */
902
    s->coarse_snr_offset = 40;
903

    
904
    /* compute real values */
905
    /* currently none of these values change during encoding, so we can just
906
       set them once at initialization */
907
    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
908
    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
909
    s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
910
    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
911
    s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
912

    
913
    count_frame_bits_fixed(s);
914
}
915

    
916

    
917
/**
918
 * Count the bits used to encode the frame, minus exponents and mantissas.
919
 * Bits based on fixed parameters have already been counted, so now we just
920
 * have to add the bits based on parameters that change during encoding.
921
 */
922
static void count_frame_bits(AC3EncodeContext *s)
923
{
924
    AC3EncOptions *opt = &s->options;
925
    int blk, ch;
926
    int frame_bits = 0;
927

    
928
    if (opt->audio_production_info)
929
        frame_bits += 7;
930
    if (s->bitstream_id == 6) {
931
        if (opt->extended_bsi_1)
932
            frame_bits += 14;
933
        if (opt->extended_bsi_2)
934
            frame_bits += 14;
935
    }
936

    
937
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
938
        /* stereo rematrixing */
939
        if (s->channel_mode == AC3_CHMODE_STEREO &&
940
            s->blocks[blk].new_rematrixing_strategy) {
941
            frame_bits += s->num_rematrixing_bands;
942
        }
943

    
944
        for (ch = 0; ch < s->fbw_channels; ch++) {
945
            if (s->exp_strategy[ch][blk] != EXP_REUSE)
946
                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
947
        }
948
    }
949
    s->frame_bits = s->frame_bits_fixed + frame_bits;
950
}
951

    
952

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

    
968

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

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

    
998

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

    
1015

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

    
1029
    snr_offset = (snr_offset - 240) << 2;
1030

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

    
1060

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

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

    
1074
    snr_offset = s->coarse_snr_offset << 4;
1075

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

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

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

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

    
1105
    return 0;
1106
}
1107

    
1108

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

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

    
1149

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

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

    
1170

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

    
1181
    count_frame_bits(s);
1182

    
1183
    bit_alloc_masking(s);
1184

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

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

    
1205
        /* fallbacks were not enough... */
1206
        break;
1207
    }
1208

    
1209
    return ret;
1210
}
1211

    
1212

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

    
1223

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

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

    
1245

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

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

    
1339

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

    
1347

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

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

    
1362

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

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

    
1418

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1533

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

    
1537

    
1538
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1539
{
1540
    unsigned int c;
1541

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

    
1554

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

    
1568

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

    
1578
    frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1579

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

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

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

    
1609

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

    
1617
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1618

    
1619
    output_frame_header(s);
1620

    
1621
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1622
        output_audio_block(s, blk);
1623

    
1624
    output_frame_end(s);
1625
}
1626

    
1627

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

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

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

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

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

    
1740

    
1741
#define FLT_OPTION_THRESHOLD 0.01
1742

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

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

    
1755
    return i;
1756
}
1757

    
1758

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

    
1776

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

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

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

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

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

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

    
1886
    return 0;
1887
}
1888

    
1889

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

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

    
1906
    if (s->bit_alloc.sr_code == 1)
1907
        adjust_frame_size(s);
1908

    
1909
    deinterleave_input_samples(s, samples);
1910

    
1911
    apply_mdct(s);
1912

    
1913
    scale_coefficients(s);
1914

    
1915
    compute_rematrixing_strategy(s);
1916

    
1917
    apply_rematrixing(s);
1918

    
1919
    process_exponents(s);
1920

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

    
1927
    quantize_mantissas(s);
1928

    
1929
    output_frame(s, frame);
1930

    
1931
    return s->frame_size;
1932
}
1933

    
1934

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

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

    
1969
    mdct_end(&s->mdct);
1970

    
1971
    av_freep(&avctx->coded_frame);
1972
    return 0;
1973
}
1974

    
1975

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

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

    
1992
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1993
    s->channels     = channels;
1994
    s->fbw_channels = channels - s->lfe_on;
1995
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
1996
    if (s->lfe_on)
1997
        ch_layout -= AV_CH_LOW_FREQUENCY;
1998

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

    
2015
    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
2016
    *channel_layout = ch_layout;
2017
    if (s->lfe_on)
2018
        *channel_layout |= AV_CH_LOW_FREQUENCY;
2019

    
2020
    return 0;
2021
}
2022

    
2023

    
2024
static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
2025
{
2026
    int i, ret;
2027

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

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

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

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

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

    
2087
    ret = validate_metadata(avctx);
2088
    if (ret)
2089
        return ret;
2090

    
2091
    return 0;
2092
}
2093

    
2094

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

    
2104
    if (s->cutoff) {
2105
        /* calculate bandwidth based on user-specified cutoff frequency */
2106
        int fbw_coeffs;
2107
        fbw_coeffs     = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2108
        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2109
    } else {
2110
        /* use default bandwidth setting */
2111
        bw_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2112
    }
2113

    
2114
    /* set number of coefficients for each channel */
2115
    for (ch = 0; ch < s->fbw_channels; ch++) {
2116
        s->bandwidth_code[ch] = bw_code;
2117
        s->nb_coefs[ch]       = bw_code * 3 + 73;
2118
    }
2119
    if (s->lfe_on)
2120
        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
2121
}
2122

    
2123

    
2124
static av_cold int allocate_buffers(AVCodecContext *avctx)
2125
{
2126
    int blk, ch;
2127
    AC3EncodeContext *s = avctx->priv_data;
2128

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

    
2173
        for (ch = 0; ch < s->channels; ch++) {
2174
            /* arrangement: block, channel, coeff */
2175
            block->bap[ch]         = &s->bap_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
2176
            block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (blk * s->channels + ch)];
2177
            block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * s->channels + ch)];
2178
            block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
2179
            block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * s->channels + ch)];
2180
            block->mask[ch]        = &s->mask_buffer       [64            * (blk * s->channels + ch)];
2181
            block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * s->channels + ch)];
2182

    
2183
            /* arrangement: channel, block, coeff */
2184
            block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2185
        }
2186
    }
2187

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

    
2208
    return 0;
2209
alloc_fail:
2210
    return AVERROR(ENOMEM);
2211
}
2212

    
2213

    
2214
/**
2215
 * Initialize the encoder.
2216
 */
2217
static av_cold int ac3_encode_init(AVCodecContext *avctx)
2218
{
2219
    AC3EncodeContext *s = avctx->priv_data;
2220
    int ret, frame_size_58;
2221

    
2222
    avctx->frame_size = AC3_FRAME_SIZE;
2223

    
2224
    ff_ac3_common_init();
2225

    
2226
    ret = validate_options(avctx, s);
2227
    if (ret)
2228
        return ret;
2229

    
2230
    s->bitstream_mode = avctx->audio_service_type;
2231
    if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2232
        s->bitstream_mode = 0x7;
2233

    
2234
    s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2235
    s->bits_written    = 0;
2236
    s->samples_written = 0;
2237
    s->frame_size      = s->frame_size_min;
2238

    
2239
    /* calculate crc_inv for both possible frame sizes */
2240
    frame_size_58 = (( s->frame_size    >> 2) + ( s->frame_size    >> 4)) << 1;
2241
    s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2242
    if (s->bit_alloc.sr_code == 1) {
2243
        frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2244
        s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2245
    }
2246

    
2247
    set_bandwidth(s);
2248

    
2249
    rematrixing_init(s);
2250

    
2251
    exponent_init(s);
2252

    
2253
    bit_alloc_init(s);
2254

    
2255
    ret = mdct_init(avctx, &s->mdct, 9);
2256
    if (ret)
2257
        goto init_fail;
2258

    
2259
    ret = allocate_buffers(avctx);
2260
    if (ret)
2261
        goto init_fail;
2262

    
2263
    avctx->coded_frame= avcodec_alloc_frame();
2264

    
2265
    dsputil_init(&s->dsp, avctx);
2266
    ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2267

    
2268
    dprint_options(avctx);
2269

    
2270
    return 0;
2271
init_fail:
2272
    ac3_encode_close(avctx);
2273
    return ret;
2274
}