Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ e05a3ac7

History | View | Annotate | Download (78.7 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(16, 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, i;
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
            uint8_t *exp   = block->exp[ch];
571
            int32_t *coef = block->fixed_coef[ch];
572
            for (i = 0; i < AC3_MAX_COEFS; i++) {
573
                int e;
574
                int v = abs(coef[i]);
575
                if (v == 0)
576
                    e = 24;
577
                else {
578
                    e = 23 - av_log2(v);
579
                    if (e >= 24) {
580
                        e = 24;
581
                        coef[i] = 0;
582
                    }
583
                    av_assert2(e >= 0);
584
                }
585
                exp[i] = e;
586
            }
587
        }
588
    }
589
}
590

    
591

    
592
/**
593
 * Exponent Difference Threshold.
594
 * New exponents are sent if their SAD exceed this number.
595
 */
596
#define EXP_DIFF_THRESHOLD 500
597

    
598

    
599
/**
600
 * Calculate exponent strategies for all blocks in a single channel.
601
 */
602
static void compute_exp_strategy_ch(AC3EncodeContext *s, uint8_t *exp_strategy,
603
                                    uint8_t *exp)
604
{
605
    int blk, blk1;
606
    int exp_diff;
607

    
608
    /* estimate if the exponent variation & decide if they should be
609
       reused in the next frame */
610
    exp_strategy[0] = EXP_NEW;
611
    exp += AC3_MAX_COEFS;
612
    for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
613
        exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
614
        if (exp_diff > EXP_DIFF_THRESHOLD)
615
            exp_strategy[blk] = EXP_NEW;
616
        else
617
            exp_strategy[blk] = EXP_REUSE;
618
        exp += AC3_MAX_COEFS;
619
    }
620

    
621
    /* now select the encoding strategy type : if exponents are often
622
       recoded, we use a coarse encoding */
623
    blk = 0;
624
    while (blk < AC3_MAX_BLOCKS) {
625
        blk1 = blk + 1;
626
        while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
627
            blk1++;
628
        switch (blk1 - blk) {
629
        case 1:  exp_strategy[blk] = EXP_D45; break;
630
        case 2:
631
        case 3:  exp_strategy[blk] = EXP_D25; break;
632
        default: exp_strategy[blk] = EXP_D15; break;
633
        }
634
        blk = blk1;
635
    }
636
}
637

    
638

    
639
/**
640
 * Calculate exponent strategies for all channels.
641
 * Array arrangement is reversed to simplify the per-channel calculation.
642
 */
643
static void compute_exp_strategy(AC3EncodeContext *s)
644
{
645
    int ch, blk;
646

    
647
    for (ch = 0; ch < s->fbw_channels; ch++) {
648
        compute_exp_strategy_ch(s, s->exp_strategy[ch], s->blocks[0].exp[ch]);
649
    }
650
    if (s->lfe_on) {
651
        ch = s->lfe_channel;
652
        s->exp_strategy[ch][0] = EXP_D15;
653
        for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
654
            s->exp_strategy[ch][blk] = EXP_REUSE;
655
    }
656
}
657

    
658

    
659
/**
660
 * Update the exponents so that they are the ones the decoder will decode.
661
 */
662
static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy)
663
{
664
    int nb_groups, i, k;
665

    
666
    nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
667

    
668
    /* for each group, compute the minimum exponent */
669
    switch(exp_strategy) {
670
    case EXP_D25:
671
        for (i = 1, k = 1; i <= nb_groups; i++) {
672
            uint8_t exp_min = exp[k];
673
            if (exp[k+1] < exp_min)
674
                exp_min = exp[k+1];
675
            exp[i] = exp_min;
676
            k += 2;
677
        }
678
        break;
679
    case EXP_D45:
680
        for (i = 1, k = 1; i <= nb_groups; i++) {
681
            uint8_t exp_min = exp[k];
682
            if (exp[k+1] < exp_min)
683
                exp_min = exp[k+1];
684
            if (exp[k+2] < exp_min)
685
                exp_min = exp[k+2];
686
            if (exp[k+3] < exp_min)
687
                exp_min = exp[k+3];
688
            exp[i] = exp_min;
689
            k += 4;
690
        }
691
        break;
692
    }
693

    
694
    /* constraint for DC exponent */
695
    if (exp[0] > 15)
696
        exp[0] = 15;
697

    
698
    /* decrease the delta between each groups to within 2 so that they can be
699
       differentially encoded */
700
    for (i = 1; i <= nb_groups; i++)
701
        exp[i] = FFMIN(exp[i], exp[i-1] + 2);
702
    i--;
703
    while (--i >= 0)
704
        exp[i] = FFMIN(exp[i], exp[i+1] + 2);
705

    
706
    /* now we have the exponent values the decoder will see */
707
    switch (exp_strategy) {
708
    case EXP_D25:
709
        for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
710
            uint8_t exp1 = exp[i];
711
            exp[k--] = exp1;
712
            exp[k--] = exp1;
713
        }
714
        break;
715
    case EXP_D45:
716
        for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
717
            exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
718
            k -= 4;
719
        }
720
        break;
721
    }
722
}
723

    
724

    
725
/**
726
 * Encode exponents from original extracted form to what the decoder will see.
727
 * This copies and groups exponents based on exponent strategy and reduces
728
 * deltas between adjacent exponent groups so that they can be differentially
729
 * encoded.
730
 */
731
static void encode_exponents(AC3EncodeContext *s)
732
{
733
    int blk, blk1, ch;
734
    uint8_t *exp, *exp_strategy;
735
    int nb_coefs, num_reuse_blocks;
736

    
737
    for (ch = 0; ch < s->channels; ch++) {
738
        exp          = s->blocks[0].exp[ch];
739
        exp_strategy = s->exp_strategy[ch];
740
        nb_coefs     = s->nb_coefs[ch];
741

    
742
        blk = 0;
743
        while (blk < AC3_MAX_BLOCKS) {
744
            blk1 = blk + 1;
745

    
746
            /* count the number of EXP_REUSE blocks after the current block
747
               and set exponent reference block pointers */
748
            s->blocks[blk].exp_ref_block[ch] = &s->blocks[blk];
749
            while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
750
                s->blocks[blk1].exp_ref_block[ch] = &s->blocks[blk];
751
                blk1++;
752
            }
753
            num_reuse_blocks = blk1 - blk - 1;
754

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

    
758
            encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk]);
759

    
760
            exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
761
            blk = blk1;
762
        }
763
    }
764
}
765

    
766

    
767
/**
768
 * Group exponents.
769
 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
770
 * varies depending on exponent strategy and bandwidth.
771
 */
772
static void group_exponents(AC3EncodeContext *s)
773
{
774
    int blk, ch, i;
775
    int group_size, nb_groups, bit_count;
776
    uint8_t *p;
777
    int delta0, delta1, delta2;
778
    int exp0, exp1;
779

    
780
    bit_count = 0;
781
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
782
        AC3Block *block = &s->blocks[blk];
783
        for (ch = 0; ch < s->channels; ch++) {
784
            int exp_strategy = s->exp_strategy[ch][blk];
785
            if (exp_strategy == EXP_REUSE)
786
                continue;
787
            group_size = exp_strategy + (exp_strategy == EXP_D45);
788
            nb_groups = exponent_group_tab[exp_strategy-1][s->nb_coefs[ch]];
789
            bit_count += 4 + (nb_groups * 7);
790
            p = block->exp[ch];
791

    
792
            /* DC exponent */
793
            exp1 = *p++;
794
            block->grouped_exp[ch][0] = exp1;
795

    
796
            /* remaining exponents are delta encoded */
797
            for (i = 1; i <= nb_groups; i++) {
798
                /* merge three delta in one code */
799
                exp0   = exp1;
800
                exp1   = p[0];
801
                p     += group_size;
802
                delta0 = exp1 - exp0 + 2;
803
                av_assert2(delta0 >= 0 && delta0 <= 4);
804

    
805
                exp0   = exp1;
806
                exp1   = p[0];
807
                p     += group_size;
808
                delta1 = exp1 - exp0 + 2;
809
                av_assert2(delta1 >= 0 && delta1 <= 4);
810

    
811
                exp0   = exp1;
812
                exp1   = p[0];
813
                p     += group_size;
814
                delta2 = exp1 - exp0 + 2;
815
                av_assert2(delta2 >= 0 && delta2 <= 4);
816

    
817
                block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
818
            }
819
        }
820
    }
821

    
822
    s->exponent_bits = bit_count;
823
}
824

    
825

    
826
/**
827
 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
828
 * Extract exponents from MDCT coefficients, calculate exponent strategies,
829
 * and encode final exponents.
830
 */
831
static void process_exponents(AC3EncodeContext *s)
832
{
833
    extract_exponents(s);
834

    
835
    compute_exp_strategy(s);
836

    
837
    encode_exponents(s);
838

    
839
    group_exponents(s);
840

    
841
    emms_c();
842
}
843

    
844

    
845
/**
846
 * Count frame bits that are based solely on fixed parameters.
847
 * This only has to be run once when the encoder is initialized.
848
 */
849
static void count_frame_bits_fixed(AC3EncodeContext *s)
850
{
851
    static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
852
    int blk;
853
    int frame_bits;
854

    
855
    /* assumptions:
856
     *   no dynamic range codes
857
     *   no channel coupling
858
     *   bit allocation parameters do not change between blocks
859
     *   SNR offsets do not change between blocks
860
     *   no delta bit allocation
861
     *   no skipped data
862
     *   no auxilliary data
863
     */
864

    
865
    /* header size */
866
    frame_bits = 65;
867
    frame_bits += frame_bits_inc[s->channel_mode];
868

    
869
    /* audio blocks */
870
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
871
        frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
872
        if (s->channel_mode == AC3_CHMODE_STEREO) {
873
            frame_bits++; /* rematstr */
874
        }
875
        frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
876
        if (s->lfe_on)
877
            frame_bits++; /* lfeexpstr */
878
        frame_bits++; /* baie */
879
        frame_bits++; /* snr */
880
        frame_bits += 2; /* delta / skip */
881
    }
882
    frame_bits++; /* cplinu for block 0 */
883
    /* bit alloc info */
884
    /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
885
    /* csnroffset[6] */
886
    /* (fsnoffset[4] + fgaincod[4]) * c */
887
    frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
888

    
889
    /* auxdatae, crcrsv */
890
    frame_bits += 2;
891

    
892
    /* CRC */
893
    frame_bits += 16;
894

    
895
    s->frame_bits_fixed = frame_bits;
896
}
897

    
898

    
899
/**
900
 * Initialize bit allocation.
901
 * Set default parameter codes and calculate parameter values.
902
 */
903
static void bit_alloc_init(AC3EncodeContext *s)
904
{
905
    int ch;
906

    
907
    /* init default parameters */
908
    s->slow_decay_code = 2;
909
    s->fast_decay_code = 1;
910
    s->slow_gain_code  = 1;
911
    s->db_per_bit_code = 3;
912
    s->floor_code      = 7;
913
    for (ch = 0; ch < s->channels; ch++)
914
        s->fast_gain_code[ch] = 4;
915

    
916
    /* initial snr offset */
917
    s->coarse_snr_offset = 40;
918

    
919
    /* compute real values */
920
    /* currently none of these values change during encoding, so we can just
921
       set them once at initialization */
922
    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
923
    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
924
    s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
925
    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
926
    s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
927

    
928
    count_frame_bits_fixed(s);
929
}
930

    
931

    
932
/**
933
 * Count the bits used to encode the frame, minus exponents and mantissas.
934
 * Bits based on fixed parameters have already been counted, so now we just
935
 * have to add the bits based on parameters that change during encoding.
936
 */
937
static void count_frame_bits(AC3EncodeContext *s)
938
{
939
    AC3EncOptions *opt = &s->options;
940
    int blk, ch;
941
    int frame_bits = 0;
942

    
943
    if (opt->audio_production_info)
944
        frame_bits += 7;
945
    if (s->bitstream_id == 6) {
946
        if (opt->extended_bsi_1)
947
            frame_bits += 14;
948
        if (opt->extended_bsi_2)
949
            frame_bits += 14;
950
    }
951

    
952
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
953
        /* stereo rematrixing */
954
        if (s->channel_mode == AC3_CHMODE_STEREO &&
955
            s->blocks[blk].new_rematrixing_strategy) {
956
            frame_bits += s->num_rematrixing_bands;
957
        }
958

    
959
        for (ch = 0; ch < s->fbw_channels; ch++) {
960
            if (s->exp_strategy[ch][blk] != EXP_REUSE)
961
                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
962
        }
963
    }
964
    s->frame_bits = s->frame_bits_fixed + frame_bits;
965
}
966

    
967

    
968
/**
969
 * Finalize the mantissa bit count by adding in the grouped mantissas.
970
 */
971
static int compute_mantissa_size_final(int mant_cnt[5])
972
{
973
    // bap=1 : 3 mantissas in 5 bits
974
    int bits = (mant_cnt[1] / 3) * 5;
975
    // bap=2 : 3 mantissas in 7 bits
976
    // bap=4 : 2 mantissas in 7 bits
977
    bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
978
    // bap=3 : each mantissa is 3 bits
979
    bits += mant_cnt[3] * 3;
980
    return bits;
981
}
982

    
983

    
984
/**
985
 * Calculate masking curve based on the final exponents.
986
 * Also calculate the power spectral densities to use in future calculations.
987
 */
988
static void bit_alloc_masking(AC3EncodeContext *s)
989
{
990
    int blk, ch;
991

    
992
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
993
        AC3Block *block = &s->blocks[blk];
994
        for (ch = 0; ch < s->channels; ch++) {
995
            /* We only need psd and mask for calculating bap.
996
               Since we currently do not calculate bap when exponent
997
               strategy is EXP_REUSE we do not need to calculate psd or mask. */
998
            if (s->exp_strategy[ch][blk] != EXP_REUSE) {
999
                ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
1000
                                          s->nb_coefs[ch],
1001
                                          block->psd[ch], block->band_psd[ch]);
1002
                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
1003
                                           0, s->nb_coefs[ch],
1004
                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
1005
                                           ch == s->lfe_channel,
1006
                                           DBA_NONE, 0, NULL, NULL, NULL,
1007
                                           block->mask[ch]);
1008
            }
1009
        }
1010
    }
1011
}
1012

    
1013

    
1014
/**
1015
 * Ensure that bap for each block and channel point to the current bap_buffer.
1016
 * They may have been switched during the bit allocation search.
1017
 */
1018
static void reset_block_bap(AC3EncodeContext *s)
1019
{
1020
    int blk, ch;
1021
    if (s->blocks[0].bap[0] == s->bap_buffer)
1022
        return;
1023
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1024
        for (ch = 0; ch < s->channels; ch++) {
1025
            s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
1026
        }
1027
    }
1028
}
1029

    
1030

    
1031
/**
1032
 * Run the bit allocation with a given SNR offset.
1033
 * This calculates the bit allocation pointers that will be used to determine
1034
 * the quantization of each mantissa.
1035
 * @return the number of bits needed for mantissas if the given SNR offset is
1036
 *         is used.
1037
 */
1038
static int bit_alloc(AC3EncodeContext *s, int snr_offset)
1039
{
1040
    int blk, ch;
1041
    int mantissa_bits;
1042
    int mant_cnt[5];
1043

    
1044
    snr_offset = (snr_offset - 240) << 2;
1045

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

    
1075

    
1076
/**
1077
 * Constant bitrate bit allocation search.
1078
 * Find the largest SNR offset that will allow data to fit in the frame.
1079
 */
1080
static int cbr_bit_allocation(AC3EncodeContext *s)
1081
{
1082
    int ch;
1083
    int bits_left;
1084
    int snr_offset, snr_incr;
1085

    
1086
    bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1087
    av_assert2(bits_left >= 0);
1088

    
1089
    snr_offset = s->coarse_snr_offset << 4;
1090

    
1091
    /* if previous frame SNR offset was 1023, check if current frame can also
1092
       use SNR offset of 1023. if so, skip the search. */
1093
    if ((snr_offset | s->fine_snr_offset[0]) == 1023) {
1094
        if (bit_alloc(s, 1023) <= bits_left)
1095
            return 0;
1096
    }
1097

    
1098
    while (snr_offset >= 0 &&
1099
           bit_alloc(s, snr_offset) > bits_left) {
1100
        snr_offset -= 64;
1101
    }
1102
    if (snr_offset < 0)
1103
        return AVERROR(EINVAL);
1104

    
1105
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1106
    for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1107
        while (snr_offset + snr_incr <= 1023 &&
1108
               bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1109
            snr_offset += snr_incr;
1110
            FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1111
        }
1112
    }
1113
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1114
    reset_block_bap(s);
1115

    
1116
    s->coarse_snr_offset = snr_offset >> 4;
1117
    for (ch = 0; ch < s->channels; ch++)
1118
        s->fine_snr_offset[ch] = snr_offset & 0xF;
1119

    
1120
    return 0;
1121
}
1122

    
1123

    
1124
/**
1125
 * Downgrade exponent strategies to reduce the bits used by the exponents.
1126
 * This is a fallback for when bit allocation fails with the normal exponent
1127
 * strategies.  Each time this function is run it only downgrades the
1128
 * strategy in 1 channel of 1 block.
1129
 * @return non-zero if downgrade was unsuccessful
1130
 */
1131
static int downgrade_exponents(AC3EncodeContext *s)
1132
{
1133
    int ch, blk;
1134

    
1135
    for (ch = 0; ch < s->fbw_channels; ch++) {
1136
        for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1137
            if (s->exp_strategy[ch][blk] == EXP_D15) {
1138
                s->exp_strategy[ch][blk] = EXP_D25;
1139
                return 0;
1140
            }
1141
        }
1142
    }
1143
    for (ch = 0; ch < s->fbw_channels; ch++) {
1144
        for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1145
            if (s->exp_strategy[ch][blk] == EXP_D25) {
1146
                s->exp_strategy[ch][blk] = EXP_D45;
1147
                return 0;
1148
            }
1149
        }
1150
    }
1151
    for (ch = 0; ch < s->fbw_channels; ch++) {
1152
        /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
1153
           the block number > 0 */
1154
        for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
1155
            if (s->exp_strategy[ch][blk] > EXP_REUSE) {
1156
                s->exp_strategy[ch][blk] = EXP_REUSE;
1157
                return 0;
1158
            }
1159
        }
1160
    }
1161
    return -1;
1162
}
1163

    
1164

    
1165
/**
1166
 * Reduce the bandwidth to reduce the number of bits used for a given SNR offset.
1167
 * This is a second fallback for when bit allocation still fails after exponents
1168
 * have been downgraded.
1169
 * @return non-zero if bandwidth reduction was unsuccessful
1170
 */
1171
static int reduce_bandwidth(AC3EncodeContext *s, int min_bw_code)
1172
{
1173
    int ch;
1174

    
1175
    if (s->bandwidth_code[0] > min_bw_code) {
1176
        for (ch = 0; ch < s->fbw_channels; ch++) {
1177
            s->bandwidth_code[ch]--;
1178
            s->nb_coefs[ch] = s->bandwidth_code[ch] * 3 + 73;
1179
        }
1180
        return 0;
1181
    }
1182
    return -1;
1183
}
1184

    
1185

    
1186
/**
1187
 * Perform bit allocation search.
1188
 * Finds the SNR offset value that maximizes quality and fits in the specified
1189
 * frame size.  Output is the SNR offset and a set of bit allocation pointers
1190
 * used to quantize the mantissas.
1191
 */
1192
static int compute_bit_allocation(AC3EncodeContext *s)
1193
{
1194
    int ret;
1195

    
1196
    count_frame_bits(s);
1197

    
1198
    bit_alloc_masking(s);
1199

    
1200
    ret = cbr_bit_allocation(s);
1201
    while (ret) {
1202
        /* fallback 1: downgrade exponents */
1203
        if (!downgrade_exponents(s)) {
1204
            extract_exponents(s);
1205
            encode_exponents(s);
1206
            group_exponents(s);
1207
            ret = compute_bit_allocation(s);
1208
            continue;
1209
        }
1210

    
1211
        /* fallback 2: reduce bandwidth */
1212
        /* only do this if the user has not specified a specific cutoff
1213
           frequency */
1214
        if (!s->cutoff && !reduce_bandwidth(s, 0)) {
1215
            process_exponents(s);
1216
            ret = compute_bit_allocation(s);
1217
            continue;
1218
        }
1219

    
1220
        /* fallbacks were not enough... */
1221
        break;
1222
    }
1223

    
1224
    return ret;
1225
}
1226

    
1227

    
1228
/**
1229
 * Symmetric quantization on 'levels' levels.
1230
 */
1231
static inline int sym_quant(int c, int e, int levels)
1232
{
1233
    int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1234
    av_assert2(v >= 0 && v < levels);
1235
    return v;
1236
}
1237

    
1238

    
1239
/**
1240
 * Asymmetric quantization on 2^qbits levels.
1241
 */
1242
static inline int asym_quant(int c, int e, int qbits)
1243
{
1244
    int lshift, m, v;
1245

    
1246
    lshift = e + qbits - 24;
1247
    if (lshift >= 0)
1248
        v = c << lshift;
1249
    else
1250
        v = c >> (-lshift);
1251
    /* rounding */
1252
    v = (v + 1) >> 1;
1253
    m = (1 << (qbits-1));
1254
    if (v >= m)
1255
        v = m - 1;
1256
    av_assert2(v >= -m);
1257
    return v & ((1 << qbits)-1);
1258
}
1259

    
1260

    
1261
/**
1262
 * Quantize a set of mantissas for a single channel in a single block.
1263
 */
1264
static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1265
                                      uint8_t *exp,
1266
                                      uint8_t *bap, uint16_t *qmant, int n)
1267
{
1268
    int i;
1269

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

    
1354

    
1355
/**
1356
 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1357
 */
1358
static void quantize_mantissas(AC3EncodeContext *s)
1359
{
1360
    int blk, ch;
1361

    
1362

    
1363
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1364
        AC3Block *block = &s->blocks[blk];
1365
        AC3Block *ref_block;
1366
        AC3Mant m = { 0 };
1367

    
1368
        for (ch = 0; ch < s->channels; ch++) {
1369
            ref_block = block->exp_ref_block[ch];
1370
            quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1371
                                      ref_block->exp[ch], ref_block->bap[ch],
1372
                                      block->qmant[ch], s->nb_coefs[ch]);
1373
        }
1374
    }
1375
}
1376

    
1377

    
1378
/**
1379
 * Write the AC-3 frame header to the output bitstream.
1380
 */
1381
static void output_frame_header(AC3EncodeContext *s)
1382
{
1383
    AC3EncOptions *opt = &s->options;
1384

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

    
1433

    
1434
/**
1435
 * Write one audio block to the output bitstream.
1436
 */
1437
static void output_audio_block(AC3EncodeContext *s, int blk)
1438
{
1439
    int ch, i, baie, rbnd;
1440
    AC3Block *block = &s->blocks[blk];
1441

    
1442
    /* block switching */
1443
    for (ch = 0; ch < s->fbw_channels; ch++)
1444
        put_bits(&s->pb, 1, 0);
1445

    
1446
    /* dither flags */
1447
    for (ch = 0; ch < s->fbw_channels; ch++)
1448
        put_bits(&s->pb, 1, 1);
1449

    
1450
    /* dynamic range codes */
1451
    put_bits(&s->pb, 1, 0);
1452

    
1453
    /* channel coupling */
1454
    if (!blk) {
1455
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
1456
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
1457
    } else {
1458
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1459
    }
1460

    
1461
    /* stereo rematrixing */
1462
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1463
        put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1464
        if (block->new_rematrixing_strategy) {
1465
            /* rematrixing flags */
1466
            for (rbnd = 0; rbnd < s->num_rematrixing_bands; rbnd++)
1467
                put_bits(&s->pb, 1, block->rematrixing_flags[rbnd]);
1468
        }
1469
    }
1470

    
1471
    /* exponent strategy */
1472
    for (ch = 0; ch < s->fbw_channels; ch++)
1473
        put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1474
    if (s->lfe_on)
1475
        put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1476

    
1477
    /* bandwidth */
1478
    for (ch = 0; ch < s->fbw_channels; ch++) {
1479
        if (s->exp_strategy[ch][blk] != EXP_REUSE)
1480
            put_bits(&s->pb, 6, s->bandwidth_code[ch]);
1481
    }
1482

    
1483
    /* exponents */
1484
    for (ch = 0; ch < s->channels; ch++) {
1485
        int nb_groups;
1486

    
1487
        if (s->exp_strategy[ch][blk] == EXP_REUSE)
1488
            continue;
1489

    
1490
        /* DC exponent */
1491
        put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1492

    
1493
        /* exponent groups */
1494
        nb_groups = exponent_group_tab[s->exp_strategy[ch][blk]-1][s->nb_coefs[ch]];
1495
        for (i = 1; i <= nb_groups; i++)
1496
            put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1497

    
1498
        /* gain range info */
1499
        if (ch != s->lfe_channel)
1500
            put_bits(&s->pb, 2, 0);
1501
    }
1502

    
1503
    /* bit allocation info */
1504
    baie = (blk == 0);
1505
    put_bits(&s->pb, 1, baie);
1506
    if (baie) {
1507
        put_bits(&s->pb, 2, s->slow_decay_code);
1508
        put_bits(&s->pb, 2, s->fast_decay_code);
1509
        put_bits(&s->pb, 2, s->slow_gain_code);
1510
        put_bits(&s->pb, 2, s->db_per_bit_code);
1511
        put_bits(&s->pb, 3, s->floor_code);
1512
    }
1513

    
1514
    /* snr offset */
1515
    put_bits(&s->pb, 1, baie);
1516
    if (baie) {
1517
        put_bits(&s->pb, 6, s->coarse_snr_offset);
1518
        for (ch = 0; ch < s->channels; ch++) {
1519
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1520
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1521
        }
1522
    }
1523

    
1524
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1525
    put_bits(&s->pb, 1, 0); /* no data to skip */
1526

    
1527
    /* mantissas */
1528
    for (ch = 0; ch < s->channels; ch++) {
1529
        int b, q;
1530
        AC3Block *ref_block = block->exp_ref_block[ch];
1531
        for (i = 0; i < s->nb_coefs[ch]; i++) {
1532
            q = block->qmant[ch][i];
1533
            b = ref_block->bap[ch][i];
1534
            switch (b) {
1535
            case 0:                                         break;
1536
            case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
1537
            case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
1538
            case 3:               put_bits(&s->pb,   3, q); break;
1539
            case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
1540
            case 14:              put_bits(&s->pb,  14, q); break;
1541
            case 15:              put_bits(&s->pb,  16, q); break;
1542
            default:              put_bits(&s->pb, b-1, q); break;
1543
            }
1544
        }
1545
    }
1546
}
1547

    
1548

    
1549
/** CRC-16 Polynomial */
1550
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1551

    
1552

    
1553
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1554
{
1555
    unsigned int c;
1556

    
1557
    c = 0;
1558
    while (a) {
1559
        if (a & 1)
1560
            c ^= b;
1561
        a = a >> 1;
1562
        b = b << 1;
1563
        if (b & (1 << 16))
1564
            b ^= poly;
1565
    }
1566
    return c;
1567
}
1568

    
1569

    
1570
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1571
{
1572
    unsigned int r;
1573
    r = 1;
1574
    while (n) {
1575
        if (n & 1)
1576
            r = mul_poly(r, a, poly);
1577
        a = mul_poly(a, a, poly);
1578
        n >>= 1;
1579
    }
1580
    return r;
1581
}
1582

    
1583

    
1584
/**
1585
 * Fill the end of the frame with 0's and compute the two CRCs.
1586
 */
1587
static void output_frame_end(AC3EncodeContext *s)
1588
{
1589
    const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1590
    int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1591
    uint8_t *frame;
1592

    
1593
    frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1594

    
1595
    /* pad the remainder of the frame with zeros */
1596
    av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1597
    flush_put_bits(&s->pb);
1598
    frame = s->pb.buf;
1599
    pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1600
    av_assert2(pad_bytes >= 0);
1601
    if (pad_bytes > 0)
1602
        memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1603

    
1604
    /* compute crc1 */
1605
    /* this is not so easy because it is at the beginning of the data... */
1606
    crc1    = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1607
    crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1608
    crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1609
    AV_WB16(frame + 2, crc1);
1610

    
1611
    /* compute crc2 */
1612
    crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1613
                          s->frame_size - frame_size_58 - 3);
1614
    crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1615
    /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1616
    if (crc2 == 0x770B) {
1617
        frame[s->frame_size - 3] ^= 0x1;
1618
        crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1619
    }
1620
    crc2 = av_bswap16(crc2);
1621
    AV_WB16(frame + s->frame_size - 2, crc2);
1622
}
1623

    
1624

    
1625
/**
1626
 * Write the frame to the output bitstream.
1627
 */
1628
static void output_frame(AC3EncodeContext *s, unsigned char *frame)
1629
{
1630
    int blk;
1631

    
1632
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1633

    
1634
    output_frame_header(s);
1635

    
1636
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1637
        output_audio_block(s, blk);
1638

    
1639
    output_frame_end(s);
1640
}
1641

    
1642

    
1643
static void dprint_options(AVCodecContext *avctx)
1644
{
1645
#ifdef DEBUG
1646
    AC3EncodeContext *s = avctx->priv_data;
1647
    AC3EncOptions *opt = &s->options;
1648
    char strbuf[32];
1649

    
1650
    switch (s->bitstream_id) {
1651
    case  6:  strncpy(strbuf, "AC-3 (alt syntax)", 32);      break;
1652
    case  8:  strncpy(strbuf, "AC-3 (standard)", 32);        break;
1653
    case  9:  strncpy(strbuf, "AC-3 (dnet half-rate)", 32);  break;
1654
    case 10:  strncpy(strbuf, "AC-3 (dnet quater-rate", 32); break;
1655
    default: snprintf(strbuf, 32, "ERROR");
1656
    }
1657
    av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
1658
    av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
1659
    av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
1660
    av_dlog(avctx, "channel_layout: %s\n", strbuf);
1661
    av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
1662
    av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
1663
    if (s->cutoff)
1664
        av_dlog(avctx, "cutoff: %d\n", s->cutoff);
1665

    
1666
    av_dlog(avctx, "per_frame_metadata: %s\n",
1667
            opt->allow_per_frame_metadata?"on":"off");
1668
    if (s->has_center)
1669
        av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
1670
                s->center_mix_level);
1671
    else
1672
        av_dlog(avctx, "center_mixlev: {not written}\n");
1673
    if (s->has_surround)
1674
        av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
1675
                s->surround_mix_level);
1676
    else
1677
        av_dlog(avctx, "surround_mixlev: {not written}\n");
1678
    if (opt->audio_production_info) {
1679
        av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
1680
        switch (opt->room_type) {
1681
        case 0:  strncpy(strbuf, "notindicated", 32); break;
1682
        case 1:  strncpy(strbuf, "large", 32);        break;
1683
        case 2:  strncpy(strbuf, "small", 32);        break;
1684
        default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
1685
        }
1686
        av_dlog(avctx, "room_type: %s\n", strbuf);
1687
    } else {
1688
        av_dlog(avctx, "mixing_level: {not written}\n");
1689
        av_dlog(avctx, "room_type: {not written}\n");
1690
    }
1691
    av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
1692
    av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
1693
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1694
        switch (opt->dolby_surround_mode) {
1695
        case 0:  strncpy(strbuf, "notindicated", 32); break;
1696
        case 1:  strncpy(strbuf, "on", 32);           break;
1697
        case 2:  strncpy(strbuf, "off", 32);          break;
1698
        default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
1699
        }
1700
        av_dlog(avctx, "dsur_mode: %s\n", strbuf);
1701
    } else {
1702
        av_dlog(avctx, "dsur_mode: {not written}\n");
1703
    }
1704
    av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
1705

    
1706
    if (s->bitstream_id == 6) {
1707
        if (opt->extended_bsi_1) {
1708
            switch (opt->preferred_stereo_downmix) {
1709
            case 0:  strncpy(strbuf, "notindicated", 32); break;
1710
            case 1:  strncpy(strbuf, "ltrt", 32);         break;
1711
            case 2:  strncpy(strbuf, "loro", 32);         break;
1712
            default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
1713
            }
1714
            av_dlog(avctx, "dmix_mode: %s\n", strbuf);
1715
            av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
1716
                    opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
1717
            av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
1718
                    opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
1719
            av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
1720
                    opt->loro_center_mix_level, s->loro_center_mix_level);
1721
            av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
1722
                    opt->loro_surround_mix_level, s->loro_surround_mix_level);
1723
        } else {
1724
            av_dlog(avctx, "extended bitstream info 1: {not written}\n");
1725
        }
1726
        if (opt->extended_bsi_2) {
1727
            switch (opt->dolby_surround_ex_mode) {
1728
            case 0:  strncpy(strbuf, "notindicated", 32); break;
1729
            case 1:  strncpy(strbuf, "on", 32);           break;
1730
            case 2:  strncpy(strbuf, "off", 32);          break;
1731
            default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
1732
            }
1733
            av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
1734
            switch (opt->dolby_headphone_mode) {
1735
            case 0:  strncpy(strbuf, "notindicated", 32); break;
1736
            case 1:  strncpy(strbuf, "on", 32);           break;
1737
            case 2:  strncpy(strbuf, "off", 32);          break;
1738
            default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
1739
            }
1740
            av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
1741

    
1742
            switch (opt->ad_converter_type) {
1743
            case 0:  strncpy(strbuf, "standard", 32); break;
1744
            case 1:  strncpy(strbuf, "hdcd", 32);     break;
1745
            default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
1746
            }
1747
            av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
1748
        } else {
1749
            av_dlog(avctx, "extended bitstream info 2: {not written}\n");
1750
        }
1751
    }
1752
#endif
1753
}
1754

    
1755

    
1756
#define FLT_OPTION_THRESHOLD 0.01
1757

    
1758
static int validate_float_option(float v, const float *v_list, int v_list_size)
1759
{
1760
    int i;
1761

    
1762
    for (i = 0; i < v_list_size; i++) {
1763
        if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
1764
            v > (v_list[i] - FLT_OPTION_THRESHOLD))
1765
            break;
1766
    }
1767
    if (i == v_list_size)
1768
        return -1;
1769

    
1770
    return i;
1771
}
1772

    
1773

    
1774
static void validate_mix_level(void *log_ctx, const char *opt_name,
1775
                               float *opt_param, const float *list,
1776
                               int list_size, int default_value, int min_value,
1777
                               int *ctx_param)
1778
{
1779
    int mixlev = validate_float_option(*opt_param, list, list_size);
1780
    if (mixlev < min_value) {
1781
        mixlev = default_value;
1782
        if (*opt_param >= 0.0) {
1783
            av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
1784
                   "default value: %0.3f\n", opt_name, list[mixlev]);
1785
        }
1786
    }
1787
    *opt_param = list[mixlev];
1788
    *ctx_param = mixlev;
1789
}
1790

    
1791

    
1792
/**
1793
 * Validate metadata options as set by AVOption system.
1794
 * These values can optionally be changed per-frame.
1795
 */
1796
static int validate_metadata(AVCodecContext *avctx)
1797
{
1798
    AC3EncodeContext *s = avctx->priv_data;
1799
    AC3EncOptions *opt = &s->options;
1800

    
1801
    /* validate mixing levels */
1802
    if (s->has_center) {
1803
        validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
1804
                           cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
1805
                           &s->center_mix_level);
1806
    }
1807
    if (s->has_surround) {
1808
        validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
1809
                           surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
1810
                           &s->surround_mix_level);
1811
    }
1812

    
1813
    /* set audio production info flag */
1814
    if (opt->mixing_level >= 0 || opt->room_type >= 0) {
1815
        if (opt->mixing_level < 0) {
1816
            av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
1817
                   "room_type is set\n");
1818
            return AVERROR(EINVAL);
1819
        }
1820
        if (opt->mixing_level < 80) {
1821
            av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
1822
                   "80dB and 111dB\n");
1823
            return AVERROR(EINVAL);
1824
        }
1825
        /* default room type */
1826
        if (opt->room_type < 0)
1827
            opt->room_type = 0;
1828
        opt->audio_production_info = 1;
1829
    } else {
1830
        opt->audio_production_info = 0;
1831
    }
1832

    
1833
    /* set extended bsi 1 flag */
1834
    if ((s->has_center || s->has_surround) &&
1835
        (opt->preferred_stereo_downmix >= 0 ||
1836
         opt->ltrt_center_mix_level   >= 0 ||
1837
         opt->ltrt_surround_mix_level >= 0 ||
1838
         opt->loro_center_mix_level   >= 0 ||
1839
         opt->loro_surround_mix_level >= 0)) {
1840
        /* default preferred stereo downmix */
1841
        if (opt->preferred_stereo_downmix < 0)
1842
            opt->preferred_stereo_downmix = 0;
1843
        /* validate Lt/Rt center mix level */
1844
        validate_mix_level(avctx, "ltrt_center_mix_level",
1845
                           &opt->ltrt_center_mix_level, extmixlev_options,
1846
                           EXTMIXLEV_NUM_OPTIONS, 5, 0,
1847
                           &s->ltrt_center_mix_level);
1848
        /* validate Lt/Rt surround mix level */
1849
        validate_mix_level(avctx, "ltrt_surround_mix_level",
1850
                           &opt->ltrt_surround_mix_level, extmixlev_options,
1851
                           EXTMIXLEV_NUM_OPTIONS, 6, 3,
1852
                           &s->ltrt_surround_mix_level);
1853
        /* validate Lo/Ro center mix level */
1854
        validate_mix_level(avctx, "loro_center_mix_level",
1855
                           &opt->loro_center_mix_level, extmixlev_options,
1856
                           EXTMIXLEV_NUM_OPTIONS, 5, 0,
1857
                           &s->loro_center_mix_level);
1858
        /* validate Lo/Ro surround mix level */
1859
        validate_mix_level(avctx, "loro_surround_mix_level",
1860
                           &opt->loro_surround_mix_level, extmixlev_options,
1861
                           EXTMIXLEV_NUM_OPTIONS, 6, 3,
1862
                           &s->loro_surround_mix_level);
1863
        opt->extended_bsi_1 = 1;
1864
    } else {
1865
        opt->extended_bsi_1 = 0;
1866
    }
1867

    
1868
    /* set extended bsi 2 flag */
1869
    if (opt->dolby_surround_ex_mode >= 0 ||
1870
        opt->dolby_headphone_mode   >= 0 ||
1871
        opt->ad_converter_type      >= 0) {
1872
        /* default dolby surround ex mode */
1873
        if (opt->dolby_surround_ex_mode < 0)
1874
            opt->dolby_surround_ex_mode = 0;
1875
        /* default dolby headphone mode */
1876
        if (opt->dolby_headphone_mode < 0)
1877
            opt->dolby_headphone_mode = 0;
1878
        /* default A/D converter type */
1879
        if (opt->ad_converter_type < 0)
1880
            opt->ad_converter_type = 0;
1881
        opt->extended_bsi_2 = 1;
1882
    } else {
1883
        opt->extended_bsi_2 = 0;
1884
    }
1885

    
1886
    /* set bitstream id for alternate bitstream syntax */
1887
    if (opt->extended_bsi_1 || opt->extended_bsi_2) {
1888
        if (s->bitstream_id > 8 && s->bitstream_id < 11) {
1889
            static int warn_once = 1;
1890
            if (warn_once) {
1891
                av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
1892
                       "not compatible with reduced samplerates. writing of "
1893
                       "extended bitstream information will be disabled.\n");
1894
                warn_once = 0;
1895
            }
1896
        } else {
1897
            s->bitstream_id = 6;
1898
        }
1899
    }
1900

    
1901
    return 0;
1902
}
1903

    
1904

    
1905
/**
1906
 * Encode a single AC-3 frame.
1907
 */
1908
static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
1909
                            int buf_size, void *data)
1910
{
1911
    AC3EncodeContext *s = avctx->priv_data;
1912
    const SampleType *samples = data;
1913
    int ret;
1914

    
1915
    if (s->options.allow_per_frame_metadata) {
1916
        ret = validate_metadata(avctx);
1917
        if (ret)
1918
            return ret;
1919
    }
1920

    
1921
    if (s->bit_alloc.sr_code == 1)
1922
        adjust_frame_size(s);
1923

    
1924
    deinterleave_input_samples(s, samples);
1925

    
1926
    apply_mdct(s);
1927

    
1928
    scale_coefficients(s);
1929

    
1930
    compute_rematrixing_strategy(s);
1931

    
1932
    apply_rematrixing(s);
1933

    
1934
    process_exponents(s);
1935

    
1936
    ret = compute_bit_allocation(s);
1937
    if (ret) {
1938
        av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1939
        return ret;
1940
    }
1941

    
1942
    quantize_mantissas(s);
1943

    
1944
    output_frame(s, frame);
1945

    
1946
    return s->frame_size;
1947
}
1948

    
1949

    
1950
/**
1951
 * Finalize encoding and free any memory allocated by the encoder.
1952
 */
1953
static av_cold int ac3_encode_close(AVCodecContext *avctx)
1954
{
1955
    int blk, ch;
1956
    AC3EncodeContext *s = avctx->priv_data;
1957

    
1958
    for (ch = 0; ch < s->channels; ch++)
1959
        av_freep(&s->planar_samples[ch]);
1960
    av_freep(&s->planar_samples);
1961
    av_freep(&s->bap_buffer);
1962
    av_freep(&s->bap1_buffer);
1963
    av_freep(&s->mdct_coef_buffer);
1964
    av_freep(&s->fixed_coef_buffer);
1965
    av_freep(&s->exp_buffer);
1966
    av_freep(&s->grouped_exp_buffer);
1967
    av_freep(&s->psd_buffer);
1968
    av_freep(&s->band_psd_buffer);
1969
    av_freep(&s->mask_buffer);
1970
    av_freep(&s->qmant_buffer);
1971
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1972
        AC3Block *block = &s->blocks[blk];
1973
        av_freep(&block->bap);
1974
        av_freep(&block->mdct_coef);
1975
        av_freep(&block->fixed_coef);
1976
        av_freep(&block->exp);
1977
        av_freep(&block->grouped_exp);
1978
        av_freep(&block->psd);
1979
        av_freep(&block->band_psd);
1980
        av_freep(&block->mask);
1981
        av_freep(&block->qmant);
1982
    }
1983

    
1984
    mdct_end(&s->mdct);
1985

    
1986
    av_freep(&avctx->coded_frame);
1987
    return 0;
1988
}
1989

    
1990

    
1991
/**
1992
 * Set channel information during initialization.
1993
 */
1994
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1995
                                    int64_t *channel_layout)
1996
{
1997
    int ch_layout;
1998

    
1999
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
2000
        return AVERROR(EINVAL);
2001
    if ((uint64_t)*channel_layout > 0x7FF)
2002
        return AVERROR(EINVAL);
2003
    ch_layout = *channel_layout;
2004
    if (!ch_layout)
2005
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
2006
    if (av_get_channel_layout_nb_channels(ch_layout) != channels)
2007
        return AVERROR(EINVAL);
2008

    
2009
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
2010
    s->channels     = channels;
2011
    s->fbw_channels = channels - s->lfe_on;
2012
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
2013
    if (s->lfe_on)
2014
        ch_layout -= AV_CH_LOW_FREQUENCY;
2015

    
2016
    switch (ch_layout) {
2017
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
2018
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
2019
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
2020
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
2021
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
2022
    case AV_CH_LAYOUT_QUAD:
2023
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
2024
    case AV_CH_LAYOUT_5POINT0:
2025
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
2026
    default:
2027
        return AVERROR(EINVAL);
2028
    }
2029
    s->has_center   = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
2030
    s->has_surround =  s->channel_mode & 0x04;
2031

    
2032
    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
2033
    *channel_layout = ch_layout;
2034
    if (s->lfe_on)
2035
        *channel_layout |= AV_CH_LOW_FREQUENCY;
2036

    
2037
    return 0;
2038
}
2039

    
2040

    
2041
static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
2042
{
2043
    int i, ret;
2044

    
2045
    /* validate channel layout */
2046
    if (!avctx->channel_layout) {
2047
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
2048
                                      "encoder will guess the layout, but it "
2049
                                      "might be incorrect.\n");
2050
    }
2051
    ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
2052
    if (ret) {
2053
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
2054
        return ret;
2055
    }
2056

    
2057
    /* validate sample rate */
2058
    for (i = 0; i < 9; i++) {
2059
        if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
2060
            break;
2061
    }
2062
    if (i == 9) {
2063
        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
2064
        return AVERROR(EINVAL);
2065
    }
2066
    s->sample_rate        = avctx->sample_rate;
2067
    s->bit_alloc.sr_shift = i % 3;
2068
    s->bit_alloc.sr_code  = i / 3;
2069
    s->bitstream_id       = 8 + s->bit_alloc.sr_shift;
2070

    
2071
    /* validate bit rate */
2072
    for (i = 0; i < 19; i++) {
2073
        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
2074
            break;
2075
    }
2076
    if (i == 19) {
2077
        av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2078
        return AVERROR(EINVAL);
2079
    }
2080
    s->bit_rate        = avctx->bit_rate;
2081
    s->frame_size_code = i << 1;
2082

    
2083
    /* validate cutoff */
2084
    if (avctx->cutoff < 0) {
2085
        av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2086
        return AVERROR(EINVAL);
2087
    }
2088
    s->cutoff = avctx->cutoff;
2089
    if (s->cutoff > (s->sample_rate >> 1))
2090
        s->cutoff = s->sample_rate >> 1;
2091

    
2092
    /* validate audio service type / channels combination */
2093
    if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
2094
         avctx->channels == 1) ||
2095
        ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
2096
          avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY  ||
2097
          avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
2098
         && avctx->channels > 1)) {
2099
        av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
2100
                                    "specified number of channels\n");
2101
        return AVERROR(EINVAL);
2102
    }
2103

    
2104
    ret = validate_metadata(avctx);
2105
    if (ret)
2106
        return ret;
2107

    
2108
    return 0;
2109
}
2110

    
2111

    
2112
/**
2113
 * Set bandwidth for all channels.
2114
 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2115
 * default value will be used.
2116
 */
2117
static av_cold void set_bandwidth(AC3EncodeContext *s)
2118
{
2119
    int ch, bw_code;
2120

    
2121
    if (s->cutoff) {
2122
        /* calculate bandwidth based on user-specified cutoff frequency */
2123
        int fbw_coeffs;
2124
        fbw_coeffs     = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2125
        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2126
    } else {
2127
        /* use default bandwidth setting */
2128
        bw_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2129
    }
2130

    
2131
    /* set number of coefficients for each channel */
2132
    for (ch = 0; ch < s->fbw_channels; ch++) {
2133
        s->bandwidth_code[ch] = bw_code;
2134
        s->nb_coefs[ch]       = bw_code * 3 + 73;
2135
    }
2136
    if (s->lfe_on)
2137
        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
2138
}
2139

    
2140

    
2141
static av_cold int allocate_buffers(AVCodecContext *avctx)
2142
{
2143
    int blk, ch;
2144
    AC3EncodeContext *s = avctx->priv_data;
2145

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

    
2190
        for (ch = 0; ch < s->channels; ch++) {
2191
            /* arrangement: block, channel, coeff */
2192
            block->bap[ch]         = &s->bap_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
2193
            block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (blk * s->channels + ch)];
2194
            block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * s->channels + ch)];
2195
            block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
2196
            block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * s->channels + ch)];
2197
            block->mask[ch]        = &s->mask_buffer       [64            * (blk * s->channels + ch)];
2198
            block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * s->channels + ch)];
2199

    
2200
            /* arrangement: channel, block, coeff */
2201
            block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2202
        }
2203
    }
2204

    
2205
    if (CONFIG_AC3ENC_FLOAT) {
2206
        FF_ALLOC_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * s->channels *
2207
                         AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
2208
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2209
            AC3Block *block = &s->blocks[blk];
2210
            FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2211
                              sizeof(*block->fixed_coef), alloc_fail);
2212
            for (ch = 0; ch < s->channels; ch++)
2213
                block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
2214
        }
2215
    } else {
2216
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2217
            AC3Block *block = &s->blocks[blk];
2218
            FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
2219
                              sizeof(*block->fixed_coef), alloc_fail);
2220
            for (ch = 0; ch < s->channels; ch++)
2221
                block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2222
        }
2223
    }
2224

    
2225
    return 0;
2226
alloc_fail:
2227
    return AVERROR(ENOMEM);
2228
}
2229

    
2230

    
2231
/**
2232
 * Initialize the encoder.
2233
 */
2234
static av_cold int ac3_encode_init(AVCodecContext *avctx)
2235
{
2236
    AC3EncodeContext *s = avctx->priv_data;
2237
    int ret, frame_size_58;
2238

    
2239
    avctx->frame_size = AC3_FRAME_SIZE;
2240

    
2241
    ff_ac3_common_init();
2242

    
2243
    ret = validate_options(avctx, s);
2244
    if (ret)
2245
        return ret;
2246

    
2247
    s->bitstream_mode = avctx->audio_service_type;
2248
    if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2249
        s->bitstream_mode = 0x7;
2250

    
2251
    s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2252
    s->bits_written    = 0;
2253
    s->samples_written = 0;
2254
    s->frame_size      = s->frame_size_min;
2255

    
2256
    /* calculate crc_inv for both possible frame sizes */
2257
    frame_size_58 = (( s->frame_size    >> 2) + ( s->frame_size    >> 4)) << 1;
2258
    s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2259
    if (s->bit_alloc.sr_code == 1) {
2260
        frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2261
        s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2262
    }
2263

    
2264
    set_bandwidth(s);
2265

    
2266
    rematrixing_init(s);
2267

    
2268
    exponent_init(s);
2269

    
2270
    bit_alloc_init(s);
2271

    
2272
    ret = mdct_init(avctx, &s->mdct, 9);
2273
    if (ret)
2274
        goto init_fail;
2275

    
2276
    ret = allocate_buffers(avctx);
2277
    if (ret)
2278
        goto init_fail;
2279

    
2280
    avctx->coded_frame= avcodec_alloc_frame();
2281

    
2282
    dsputil_init(&s->dsp, avctx);
2283
    ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2284

    
2285
    dprint_options(avctx);
2286

    
2287
    return 0;
2288
init_fail:
2289
    ac3_encode_close(avctx);
2290
    return ret;
2291
}