Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ 9d853336

History | View | Annotate | Download (56.1 KB)

1 de6d9b64 Fabrice Bellard
/*
2 14b70628 Justin Ruggles
 * The simplest AC-3 encoder
3 406792e7 Diego Biurrun
 * Copyright (c) 2000 Fabrice Bellard
4 de6d9b64 Fabrice Bellard
 *
5 b78e7197 Diego Biurrun
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8 ff4ec49e Fabrice Bellard
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10 b78e7197 Diego Biurrun
 * version 2.1 of the License, or (at your option) any later version.
11 de6d9b64 Fabrice Bellard
 *
12 b78e7197 Diego Biurrun
 * FFmpeg is distributed in the hope that it will be useful,
13 de6d9b64 Fabrice Bellard
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ff4ec49e Fabrice Bellard
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16 de6d9b64 Fabrice Bellard
 *
17 ff4ec49e Fabrice Bellard
 * You should have received a copy of the GNU Lesser General Public
18 b78e7197 Diego Biurrun
 * License along with FFmpeg; if not, write to the Free Software
19 5509bffa Diego Biurrun
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 de6d9b64 Fabrice Bellard
 */
21 983e3246 Michael Niedermayer
22
/**
23 ba87f080 Diego Biurrun
 * @file
24 14b70628 Justin Ruggles
 * The simplest AC-3 encoder.
25 983e3246 Michael Niedermayer
 */
26 6a988808 Justin Ruggles
27 1a565432 Fabrice Bellard
//#define DEBUG
28 22c0b03c Justin Ruggles
29 63e8d976 Stefano Sabatini
#include "libavcore/audioconvert.h"
30 245976da Diego Biurrun
#include "libavutil/crc.h"
31 de6d9b64 Fabrice Bellard
#include "avcodec.h"
32 b2755007 Stefano Sabatini
#include "put_bits.h"
33 6107fa87 Fabrice Bellard
#include "ac3.h"
34 120b4557 Justin Ruggles
#include "audioconvert.h"
35 6107fa87 Fabrice Bellard
36 2f8ae522 Justin Ruggles
37 e77fd066 Justin Ruggles
#define MDCT_NBITS 9
38
#define MDCT_SAMPLES (1 << MDCT_NBITS)
39
40 f94bacc5 Justin Ruggles
/** Maximum number of exponent groups. +1 for separate DC exponent. */
41
#define AC3_MAX_EXP_GROUPS 85
42
43 c36ce0f8 Justin Ruggles
/** Scale a float value by 2^bits and convert to an integer. */
44 918cd225 Justin Ruggles
#define SCALE_FLOAT(a, bits) lrintf((a) * (float)(1 << (bits)))
45
46 c36ce0f8 Justin Ruggles
/** Scale a float value by 2^15, convert to an integer, and clip to int16_t range. */
47 e77fd066 Justin Ruggles
#define FIX15(a) av_clip_int16(SCALE_FLOAT(a, 15))
48
49 2f8ae522 Justin Ruggles
50 c36ce0f8 Justin Ruggles
/**
51
 * Compex number.
52
 * Used in fixed-point MDCT calculation.
53
 */
54 e77fd066 Justin Ruggles
typedef struct IComplex {
55
    int16_t re,im;
56
} IComplex;
57
58 c36ce0f8 Justin Ruggles
/**
59 5901cebe Justin Ruggles
 * Data for a single audio block.
60
 */
61
typedef struct AC3Block {
62 b6f6204d Justin Ruggles
    uint8_t  **bap;                             ///< bit allocation pointers (bap)
63
    int32_t  **mdct_coef;                       ///< MDCT coefficients
64
    uint8_t  **exp;                             ///< original exponents
65
    uint8_t  **encoded_exp;                     ///< encoded exponents
66
    uint8_t  **grouped_exp;                     ///< grouped exponents
67
    int16_t  **psd;                             ///< psd per frequency bin
68
    int16_t  **band_psd;                        ///< psd per critical band
69
    int16_t  **mask;                            ///< masking curve
70
    uint16_t **qmant;                           ///< quantized mantissas
71
    uint8_t  num_exp_groups[AC3_MAX_CHANNELS];  ///< number of exponent groups
72
    uint8_t  exp_strategy[AC3_MAX_CHANNELS];    ///< exponent strategies
73
    int8_t   exp_shift[AC3_MAX_CHANNELS];       ///< exponent shift values
74 5901cebe Justin Ruggles
} AC3Block;
75
76
/**
77 c36ce0f8 Justin Ruggles
 * AC-3 encoder private context.
78
 */
79 6107fa87 Fabrice Bellard
typedef struct AC3EncodeContext {
80 07965463 Justin Ruggles
    PutBitContext pb;                       ///< bitstream writer context
81 7e5a4bf8 Justin Ruggles
82 5901cebe Justin Ruggles
    AC3Block blocks[AC3_MAX_BLOCKS];        ///< per-block info
83
84 07965463 Justin Ruggles
    int bitstream_id;                       ///< bitstream id                           (bsid)
85
    int bitstream_mode;                     ///< bitstream mode                         (bsmod)
86 7e5a4bf8 Justin Ruggles
87 07965463 Justin Ruggles
    int bit_rate;                           ///< target bit rate, in bits-per-second
88
    int sample_rate;                        ///< sampling frequency, in Hz
89 7e5a4bf8 Justin Ruggles
90 07965463 Justin Ruggles
    int frame_size_min;                     ///< minimum frame size in case rounding is necessary
91 427e2293 Justin Ruggles
    int frame_size;                         ///< current frame size in bytes
92 07965463 Justin Ruggles
    int frame_size_code;                    ///< frame size code                        (frmsizecod)
93
    int bits_written;                       ///< bit count    (used to avg. bitrate)
94
    int samples_written;                    ///< sample count (used to avg. bitrate)
95 7e5a4bf8 Justin Ruggles
96 07965463 Justin Ruggles
    int fbw_channels;                       ///< number of full-bandwidth channels      (nfchans)
97
    int channels;                           ///< total number of channels               (nchans)
98
    int lfe_on;                             ///< indicates if there is an LFE channel   (lfeon)
99
    int lfe_channel;                        ///< channel index of the LFE channel
100
    int channel_mode;                       ///< channel mode                           (acmod)
101
    const uint8_t *channel_map;             ///< channel map used to reorder channels
102 7e5a4bf8 Justin Ruggles
103 07965463 Justin Ruggles
    int bandwidth_code[AC3_MAX_CHANNELS];   ///< bandwidth code (0 to 60)               (chbwcod)
104 6107fa87 Fabrice Bellard
    int nb_coefs[AC3_MAX_CHANNELS];
105 115329f1 Diego Biurrun
106 6107fa87 Fabrice Bellard
    /* bitrate allocation control */
107 07965463 Justin Ruggles
    int slow_gain_code;                     ///< slow gain code                         (sgaincod)
108
    int slow_decay_code;                    ///< slow decay code                        (sdcycod)
109
    int fast_decay_code;                    ///< fast decay code                        (fdcycod)
110
    int db_per_bit_code;                    ///< dB/bit code                            (dbpbcod)
111
    int floor_code;                         ///< floor code                             (floorcod)
112
    AC3BitAllocParameters bit_alloc;        ///< bit allocation parameters
113
    int coarse_snr_offset;                  ///< coarse SNR offsets                     (csnroffst)
114
    int fast_gain_code[AC3_MAX_CHANNELS];   ///< fast gain codes (signal-to-mask ratio) (fgaincod)
115
    int fine_snr_offset[AC3_MAX_CHANNELS];  ///< fine SNR offsets                       (fsnroffst)
116 359c1d19 Justin Ruggles
    int frame_bits;                         ///< all frame bits except exponents and mantissas
117
    int exponent_bits;                      ///< number of bits used for exponents
118 7e5a4bf8 Justin Ruggles
119 6107fa87 Fabrice Bellard
    /* mantissa encoding */
120 07965463 Justin Ruggles
    int mant1_cnt, mant2_cnt, mant4_cnt;    ///< mantissa counts for bap=1,2,4
121 b6a1e523 Justin Ruggles
    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
122 7e5a4bf8 Justin Ruggles
123 e8d21fba Justin Ruggles
    int16_t **planar_samples;
124 171bc51c Justin Ruggles
    uint8_t *bap_buffer;
125
    uint8_t *bap1_buffer;
126 b6f6204d Justin Ruggles
    int32_t *mdct_coef_buffer;
127
    uint8_t *exp_buffer;
128
    uint8_t *encoded_exp_buffer;
129
    uint8_t *grouped_exp_buffer;
130
    int16_t *psd_buffer;
131
    int16_t *band_psd_buffer;
132
    int16_t *mask_buffer;
133
    uint16_t *qmant_buffer;
134 aa645b98 Justin Ruggles
135
    DECLARE_ALIGNED(16, int16_t, windowed_samples)[AC3_WINDOW_SIZE];
136 6107fa87 Fabrice Bellard
} AC3EncodeContext;
137 de6d9b64 Fabrice Bellard
138 2f8ae522 Justin Ruggles
139 c36ce0f8 Justin Ruggles
/** MDCT and FFT tables */
140 4258a0a3 Justin Ruggles
static int16_t costab[64];
141
static int16_t sintab[64];
142
static int16_t xcos1[128];
143
static int16_t xsin1[128];
144 de6d9b64 Fabrice Bellard
145 2f8ae522 Justin Ruggles
146 c36ce0f8 Justin Ruggles
/**
147 160d85f5 Justin Ruggles
 * Adjust the frame size to make the average bit rate match the target bit rate.
148
 * This is only needed for 11025, 22050, and 44100 sample rates.
149
 */
150
static void adjust_frame_size(AC3EncodeContext *s)
151
{
152
    while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
153
        s->bits_written    -= s->bit_rate;
154
        s->samples_written -= s->sample_rate;
155
    }
156 2d82d9b1 Justin Ruggles
    s->frame_size = s->frame_size_min +
157
                    2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
158 160d85f5 Justin Ruggles
    s->bits_written    += s->frame_size * 8;
159
    s->samples_written += AC3_FRAME_SIZE;
160
}
161
162
163
/**
164 4acc790f Justin Ruggles
 * Deinterleave input samples.
165
 * Channels are reordered from FFmpeg's default order to AC-3 order.
166
 */
167
static void deinterleave_input_samples(AC3EncodeContext *s,
168 266d24be Justin Ruggles
                                       const int16_t *samples)
169 4acc790f Justin Ruggles
{
170
    int ch, i;
171
172
    /* deinterleave and remap input samples */
173
    for (ch = 0; ch < s->channels; ch++) {
174
        const int16_t *sptr;
175
        int sinc;
176
177
        /* copy last 256 samples of previous frame to the start of the current frame */
178 1c3e117e Justin Ruggles
        memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
179 266d24be Justin Ruggles
               AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
180 4acc790f Justin Ruggles
181
        /* deinterleave */
182
        sinc = s->channels;
183
        sptr = samples + s->channel_map[ch];
184
        for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
185 266d24be Justin Ruggles
            s->planar_samples[ch][i] = *sptr;
186 4acc790f Justin Ruggles
            sptr += sinc;
187
        }
188
    }
189
}
190
191
192
/**
193 c36ce0f8 Justin Ruggles
 * Initialize FFT tables.
194
 * @param ln log2(FFT size)
195
 */
196 5ef251e5 Daniel Verkamp
static av_cold void fft_init(int ln)
197 de6d9b64 Fabrice Bellard
{
198 b84a211b Justin Ruggles
    int i, n, n2;
199 de6d9b64 Fabrice Bellard
    float alpha;
200
201 b84a211b Justin Ruggles
    n  = 1 << ln;
202
    n2 = n >> 1;
203 de6d9b64 Fabrice Bellard
204 b84a211b Justin Ruggles
    for (i = 0; i < n2; i++) {
205
        alpha     = 2.0 * M_PI * i / n;
206 918cd225 Justin Ruggles
        costab[i] = FIX15(cos(alpha));
207
        sintab[i] = FIX15(sin(alpha));
208 de6d9b64 Fabrice Bellard
    }
209
}
210
211 2f8ae522 Justin Ruggles
212 c36ce0f8 Justin Ruggles
/**
213
 * Initialize MDCT tables.
214
 * @param nbits log2(MDCT size)
215
 */
216 a8d2b06b Justin Ruggles
static av_cold void mdct_init(int nbits)
217
{
218 b84a211b Justin Ruggles
    int i, n, n4;
219
220
    n  = 1 << nbits;
221
    n4 = n >> 2;
222 a8d2b06b Justin Ruggles
223
    fft_init(nbits - 2);
224
225 6a988808 Justin Ruggles
    for (i = 0; i < n4; i++) {
226 b84a211b Justin Ruggles
        float alpha = 2.0 * M_PI * (i + 1.0 / 8.0) / n;
227 918cd225 Justin Ruggles
        xcos1[i] = FIX15(-cos(alpha));
228
        xsin1[i] = FIX15(-sin(alpha));
229 a8d2b06b Justin Ruggles
    }
230
}
231
232 2f8ae522 Justin Ruggles
233 c36ce0f8 Justin Ruggles
/** Butterfly op */
234 6a988808 Justin Ruggles
#define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1)  \
235
{                                                       \
236
  int ax, ay, bx, by;                                   \
237
  bx  = pre1;                                           \
238
  by  = pim1;                                           \
239
  ax  = qre1;                                           \
240
  ay  = qim1;                                           \
241
  pre = (bx + ax) >> 1;                                 \
242
  pim = (by + ay) >> 1;                                 \
243
  qre = (bx - ax) >> 1;                                 \
244
  qim = (by - ay) >> 1;                                 \
245 de6d9b64 Fabrice Bellard
}
246
247 2f8ae522 Justin Ruggles
248 c36ce0f8 Justin Ruggles
/** Complex multiply */
249 6a988808 Justin Ruggles
#define CMUL(pre, pim, are, aim, bre, bim)              \
250
{                                                       \
251
   pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;     \
252
   pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;     \
253 de6d9b64 Fabrice Bellard
}
254
255
256 c36ce0f8 Justin Ruggles
/**
257
 * Calculate a 2^n point complex FFT on 2^ln points.
258
 * @param z  complex input/output samples
259
 * @param ln log2(FFT size)
260
 */
261 de6d9b64 Fabrice Bellard
static void fft(IComplex *z, int ln)
262
{
263 6a988808 Justin Ruggles
    int j, l, np, np2;
264
    int nblocks, nloops;
265 de6d9b64 Fabrice Bellard
    register IComplex *p,*q;
266
    int tmp_re, tmp_im;
267
268
    np = 1 << ln;
269
270
    /* reverse */
271 6a988808 Justin Ruggles
    for (j = 0; j < np; j++) {
272 91cc5d37 Francesco Lavra
        int k = av_reverse[j] >> (8 - ln);
273 f952b30c Reimar Döffinger
        if (k < j)
274
            FFSWAP(IComplex, z[k], z[j]);
275 de6d9b64 Fabrice Bellard
    }
276
277
    /* pass 0 */
278
279 6a988808 Justin Ruggles
    p = &z[0];
280
    j = np >> 1;
281 de6d9b64 Fabrice Bellard
    do {
282 115329f1 Diego Biurrun
        BF(p[0].re, p[0].im, p[1].re, p[1].im,
283 de6d9b64 Fabrice Bellard
           p[0].re, p[0].im, p[1].re, p[1].im);
284 6a988808 Justin Ruggles
        p += 2;
285
    } while (--j);
286 de6d9b64 Fabrice Bellard
287
    /* pass 1 */
288
289 6a988808 Justin Ruggles
    p = &z[0];
290
    j = np >> 2;
291 de6d9b64 Fabrice Bellard
    do {
292 6a988808 Justin Ruggles
        BF(p[0].re, p[0].im, p[2].re,  p[2].im,
293
           p[0].re, p[0].im, p[2].re,  p[2].im);
294
        BF(p[1].re, p[1].im, p[3].re,  p[3].im,
295 de6d9b64 Fabrice Bellard
           p[1].re, p[1].im, p[3].im, -p[3].re);
296
        p+=4;
297 6a988808 Justin Ruggles
    } while (--j);
298 de6d9b64 Fabrice Bellard
299
    /* pass 2 .. ln-1 */
300
301
    nblocks = np >> 3;
302 6a988808 Justin Ruggles
    nloops  =  1 << 2;
303
    np2     = np >> 1;
304 de6d9b64 Fabrice Bellard
    do {
305
        p = z;
306
        q = z + nloops;
307 6a988808 Justin Ruggles
        for (j = 0; j < nblocks; j++) {
308 de6d9b64 Fabrice Bellard
            BF(p->re, p->im, q->re, q->im,
309
               p->re, p->im, q->re, q->im);
310
            p++;
311
            q++;
312
            for(l = nblocks; l < np2; l += nblocks) {
313
                CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
314 6a988808 Justin Ruggles
                BF(p->re, p->im, q->re,  q->im,
315 de6d9b64 Fabrice Bellard
                   p->re, p->im, tmp_re, tmp_im);
316
                p++;
317
                q++;
318
            }
319
            p += nloops;
320
            q += nloops;
321
        }
322
        nblocks = nblocks >> 1;
323 6a988808 Justin Ruggles
        nloops  = nloops  << 1;
324
    } while (nblocks);
325 de6d9b64 Fabrice Bellard
}
326
327 2f8ae522 Justin Ruggles
328 c36ce0f8 Justin Ruggles
/**
329
 * Calculate a 512-point MDCT
330
 * @param out 256 output frequency coefficients
331
 * @param in  512 windowed input audio samples
332
 */
333 0c1a9eda Zdenek Kabelac
static void mdct512(int32_t *out, int16_t *in)
334 de6d9b64 Fabrice Bellard
{
335
    int i, re, im, re1, im1;
336 7066cc8f Justin Ruggles
    int16_t rot[MDCT_SAMPLES];
337
    IComplex x[MDCT_SAMPLES/4];
338 de6d9b64 Fabrice Bellard
339
    /* shift to simplify computations */
340 6a988808 Justin Ruggles
    for (i = 0; i < MDCT_SAMPLES/4; i++)
341 7066cc8f Justin Ruggles
        rot[i] = -in[i + 3*MDCT_SAMPLES/4];
342 9d853336 Justin Ruggles
    memcpy(&rot[MDCT_SAMPLES/4], &in[0], 3*MDCT_SAMPLES/4*sizeof(*in));
343 115329f1 Diego Biurrun
344 de6d9b64 Fabrice Bellard
    /* pre rotation */
345 6a988808 Justin Ruggles
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
346
        re =  ((int)rot[               2*i] - (int)rot[MDCT_SAMPLES  -1-2*i]) >> 1;
347 7066cc8f Justin Ruggles
        im = -((int)rot[MDCT_SAMPLES/2+2*i] - (int)rot[MDCT_SAMPLES/2-1-2*i]) >> 1;
348 de6d9b64 Fabrice Bellard
        CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
349
    }
350
351
    fft(x, MDCT_NBITS - 2);
352 115329f1 Diego Biurrun
353 de6d9b64 Fabrice Bellard
    /* post rotation */
354 6a988808 Justin Ruggles
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
355 de6d9b64 Fabrice Bellard
        re = x[i].re;
356
        im = x[i].im;
357
        CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
358 6a988808 Justin Ruggles
        out[                 2*i] = im1;
359 7066cc8f Justin Ruggles
        out[MDCT_SAMPLES/2-1-2*i] = re1;
360 de6d9b64 Fabrice Bellard
    }
361
}
362
363 2f8ae522 Justin Ruggles
364 c36ce0f8 Justin Ruggles
/**
365 0a0a8500 Justin Ruggles
 * Apply KBD window to input samples prior to MDCT.
366
 */
367
static void apply_window(int16_t *output, const int16_t *input,
368
                         const int16_t *window, int n)
369
{
370
    int i;
371
    int n2 = n >> 1;
372
373
    for (i = 0; i < n2; i++) {
374
        output[i]     = MUL16(input[i],     window[i]) >> 15;
375
        output[n-i-1] = MUL16(input[n-i-1], window[i]) >> 15;
376
    }
377
}
378
379
380
/**
381 c36ce0f8 Justin Ruggles
 * Calculate the log2() of the maximum absolute value in an array.
382
 * @param tab input array
383
 * @param n   number of values in the array
384
 * @return    log2(max(abs(tab[])))
385
 */
386 e77fd066 Justin Ruggles
static int log2_tab(int16_t *tab, int n)
387
{
388
    int i, v;
389
390
    v = 0;
391
    for (i = 0; i < n; i++)
392
        v |= abs(tab[i]);
393
394
    return av_log2(v);
395
}
396
397 2f8ae522 Justin Ruggles
398 c36ce0f8 Justin Ruggles
/**
399
 * Left-shift each value in an array by a specified amount.
400
 * @param tab    input array
401
 * @param n      number of values in the array
402
 * @param lshift left shift amount. a negative value means right shift.
403
 */
404 e77fd066 Justin Ruggles
static void lshift_tab(int16_t *tab, int n, int lshift)
405
{
406
    int i;
407
408
    if (lshift > 0) {
409 2d82d9b1 Justin Ruggles
        for (i = 0; i < n; i++)
410 e77fd066 Justin Ruggles
            tab[i] <<= lshift;
411
    } else if (lshift < 0) {
412
        lshift = -lshift;
413
        for (i = 0; i < n; i++)
414
            tab[i] >>= lshift;
415
    }
416
}
417
418 2f8ae522 Justin Ruggles
419 c36ce0f8 Justin Ruggles
/**
420 0a0a8500 Justin Ruggles
 * Normalize the input samples to use the maximum available precision.
421
 * This assumes signed 16-bit input samples. Exponents are reduced by 9 to
422
 * match the 24-bit internal precision for MDCT coefficients.
423
 *
424
 * @return exponent shift
425
 */
426 266d24be Justin Ruggles
static int normalize_samples(AC3EncodeContext *s)
427 0a0a8500 Justin Ruggles
{
428 266d24be Justin Ruggles
    int v = 14 - log2_tab(s->windowed_samples, AC3_WINDOW_SIZE);
429 0a0a8500 Justin Ruggles
    v = FFMAX(0, v);
430 266d24be Justin Ruggles
    lshift_tab(s->windowed_samples, AC3_WINDOW_SIZE, v);
431 0a0a8500 Justin Ruggles
    return v - 9;
432
}
433
434
435
/**
436
 * Apply the MDCT to input samples to generate frequency coefficients.
437
 * This applies the KBD window and normalizes the input to reduce precision
438
 * loss due to fixed-point calculations.
439
 */
440 266d24be Justin Ruggles
static void apply_mdct(AC3EncodeContext *s)
441 0a0a8500 Justin Ruggles
{
442
    int blk, ch;
443
444
    for (ch = 0; ch < s->channels; ch++) {
445
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
446 5901cebe Justin Ruggles
            AC3Block *block = &s->blocks[blk];
447 266d24be Justin Ruggles
            const int16_t *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
448 0a0a8500 Justin Ruggles
449 266d24be Justin Ruggles
            apply_window(s->windowed_samples, input_samples, ff_ac3_window, AC3_WINDOW_SIZE);
450 0a0a8500 Justin Ruggles
451 5901cebe Justin Ruggles
            block->exp_shift[ch] = normalize_samples(s);
452 0a0a8500 Justin Ruggles
453 5901cebe Justin Ruggles
            mdct512(block->mdct_coef[ch], s->windowed_samples);
454 0a0a8500 Justin Ruggles
        }
455
    }
456
}
457
458
459
/**
460 dfdf73eb Justin Ruggles
 * Extract exponents from the MDCT coefficients.
461
 * This takes into account the normalization that was done to the input samples
462
 * by adjusting the exponents by the exponent shift values.
463
 */
464 266d24be Justin Ruggles
static void extract_exponents(AC3EncodeContext *s)
465 dfdf73eb Justin Ruggles
{
466
    int blk, ch, i;
467
468
    for (ch = 0; ch < s->channels; ch++) {
469
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
470 5901cebe Justin Ruggles
            AC3Block *block = &s->blocks[blk];
471 dfdf73eb Justin Ruggles
            for (i = 0; i < AC3_MAX_COEFS; i++) {
472
                int e;
473 5901cebe Justin Ruggles
                int v = abs(block->mdct_coef[ch][i]);
474 dfdf73eb Justin Ruggles
                if (v == 0)
475
                    e = 24;
476
                else {
477 5901cebe Justin Ruggles
                    e = 23 - av_log2(v) + block->exp_shift[ch];
478 dfdf73eb Justin Ruggles
                    if (e >= 24) {
479
                        e = 24;
480 5901cebe Justin Ruggles
                        block->mdct_coef[ch][i] = 0;
481 dfdf73eb Justin Ruggles
                    }
482
                }
483 5901cebe Justin Ruggles
                block->exp[ch][i] = e;
484 dfdf73eb Justin Ruggles
            }
485
        }
486
    }
487
}
488
489
490
/**
491 c36ce0f8 Justin Ruggles
 * Calculate the sum of absolute differences (SAD) between 2 sets of exponents.
492
 */
493 0c1a9eda Zdenek Kabelac
static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
494 de6d9b64 Fabrice Bellard
{
495
    int sum, i;
496
    sum = 0;
497 6a988808 Justin Ruggles
    for (i = 0; i < n; i++)
498 de6d9b64 Fabrice Bellard
        sum += abs(exp1[i] - exp2[i]);
499
    return sum;
500
}
501
502 2f8ae522 Justin Ruggles
503 c36ce0f8 Justin Ruggles
/**
504
 * Exponent Difference Threshold.
505
 * New exponents are sent if their SAD exceed this number.
506
 */
507 6a988808 Justin Ruggles
#define EXP_DIFF_THRESHOLD 1000
508
509 2f8ae522 Justin Ruggles
510 c36ce0f8 Justin Ruggles
/**
511
 * Calculate exponent strategies for all blocks in a single channel.
512
 */
513 d7da8080 Justin Ruggles
static void compute_exp_strategy_ch(uint8_t *exp_strategy, uint8_t **exp)
514 de6d9b64 Fabrice Bellard
{
515 ce67b7cd Justin Ruggles
    int blk, blk1;
516 de6d9b64 Fabrice Bellard
    int exp_diff;
517 115329f1 Diego Biurrun
518 de6d9b64 Fabrice Bellard
    /* estimate if the exponent variation & decide if they should be
519
       reused in the next frame */
520 d7da8080 Justin Ruggles
    exp_strategy[0] = EXP_NEW;
521 ce67b7cd Justin Ruggles
    for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
522 d7da8080 Justin Ruggles
        exp_diff = calc_exp_diff(exp[blk], exp[blk-1], AC3_MAX_COEFS);
523 de6d9b64 Fabrice Bellard
        if (exp_diff > EXP_DIFF_THRESHOLD)
524 d7da8080 Justin Ruggles
            exp_strategy[blk] = EXP_NEW;
525 de6d9b64 Fabrice Bellard
        else
526 d7da8080 Justin Ruggles
            exp_strategy[blk] = EXP_REUSE;
527 de6d9b64 Fabrice Bellard
    }
528 30b68f33 Zdenek Kabelac
529 de6d9b64 Fabrice Bellard
    /* now select the encoding strategy type : if exponents are often
530
       recoded, we use a coarse encoding */
531 ce67b7cd Justin Ruggles
    blk = 0;
532
    while (blk < AC3_MAX_BLOCKS) {
533
        blk1 = blk + 1;
534 d7da8080 Justin Ruggles
        while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
535 ce67b7cd Justin Ruggles
            blk1++;
536
        switch (blk1 - blk) {
537 d7da8080 Justin Ruggles
        case 1:  exp_strategy[blk] = EXP_D45; break;
538 de6d9b64 Fabrice Bellard
        case 2:
539 d7da8080 Justin Ruggles
        case 3:  exp_strategy[blk] = EXP_D25; break;
540
        default: exp_strategy[blk] = EXP_D15; break;
541 de6d9b64 Fabrice Bellard
        }
542 ce67b7cd Justin Ruggles
        blk = blk1;
543 de6d9b64 Fabrice Bellard
    }
544
}
545
546 2f8ae522 Justin Ruggles
547 c36ce0f8 Justin Ruggles
/**
548 dfdf73eb Justin Ruggles
 * Calculate exponent strategies for all channels.
549 d7da8080 Justin Ruggles
 * Array arrangement is reversed to simplify the per-channel calculation.
550 dfdf73eb Justin Ruggles
 */
551 266d24be Justin Ruggles
static void compute_exp_strategy(AC3EncodeContext *s)
552 dfdf73eb Justin Ruggles
{
553 d7da8080 Justin Ruggles
    uint8_t *exp1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
554
    uint8_t exp_str1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
555
    int ch, blk;
556 dfdf73eb Justin Ruggles
557 d7da8080 Justin Ruggles
    for (ch = 0; ch < s->fbw_channels; ch++) {
558
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
559 5901cebe Justin Ruggles
            exp1[ch][blk]     = s->blocks[blk].exp[ch];
560
            exp_str1[ch][blk] = s->blocks[blk].exp_strategy[ch];
561 d7da8080 Justin Ruggles
        }
562
563
        compute_exp_strategy_ch(exp_str1[ch], exp1[ch]);
564
565
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
566 5901cebe Justin Ruggles
            s->blocks[blk].exp_strategy[ch] = exp_str1[ch][blk];
567 d7da8080 Justin Ruggles
    }
568
    if (s->lfe_on) {
569
        ch = s->lfe_channel;
570 5901cebe Justin Ruggles
        s->blocks[0].exp_strategy[ch] = EXP_D15;
571 06f6f785 Justin Ruggles
        for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
572 5901cebe Justin Ruggles
            s->blocks[blk].exp_strategy[ch] = EXP_REUSE;
573 dfdf73eb Justin Ruggles
    }
574
}
575
576
577
/**
578 c36ce0f8 Justin Ruggles
 * Set each encoded exponent in a block to the minimum of itself and the
579
 * exponent in the same frequency bin of a following block.
580
 * exp[i] = min(exp[i], exp1[i]
581
 */
582 2d82d9b1 Justin Ruggles
static void exponent_min(uint8_t *exp, uint8_t *exp1, int n)
583 de6d9b64 Fabrice Bellard
{
584
    int i;
585 6a988808 Justin Ruggles
    for (i = 0; i < n; i++) {
586 de6d9b64 Fabrice Bellard
        if (exp1[i] < exp[i])
587
            exp[i] = exp1[i];
588
    }
589
}
590 115329f1 Diego Biurrun
591 2f8ae522 Justin Ruggles
592 c36ce0f8 Justin Ruggles
/**
593
 * Update the exponents so that they are the ones the decoder will decode.
594
 */
595 2d82d9b1 Justin Ruggles
static void encode_exponents_blk_ch(uint8_t *encoded_exp, uint8_t *exp,
596 d3325d55 Justin Ruggles
                                    int nb_exps, int exp_strategy,
597
                                    uint8_t *num_exp_groups)
598 de6d9b64 Fabrice Bellard
{
599 e44cad52 Jeff Muizelaar
    int group_size, nb_groups, i, j, k, exp_min;
600 7066cc8f Justin Ruggles
    uint8_t exp1[AC3_MAX_COEFS];
601 de6d9b64 Fabrice Bellard
602 02877def Justin Ruggles
    group_size = exp_strategy + (exp_strategy == EXP_D45);
603 d3325d55 Justin Ruggles
    *num_exp_groups = (nb_exps + (group_size * 3) - 4) / (3 * group_size);
604
    nb_groups = *num_exp_groups * 3;
605 de6d9b64 Fabrice Bellard
606
    /* for each group, compute the minimum exponent */
607
    exp1[0] = exp[0]; /* DC exponent is handled separately */
608
    k = 1;
609 6a988808 Justin Ruggles
    for (i = 1; i <= nb_groups; i++) {
610 de6d9b64 Fabrice Bellard
        exp_min = exp[k];
611
        assert(exp_min >= 0 && exp_min <= 24);
612 6a988808 Justin Ruggles
        for (j = 1; j < group_size; j++) {
613 de6d9b64 Fabrice Bellard
            if (exp[k+j] < exp_min)
614
                exp_min = exp[k+j];
615
        }
616
        exp1[i] = exp_min;
617
        k += group_size;
618
    }
619
620
    /* constraint for DC exponent */
621
    if (exp1[0] > 15)
622
        exp1[0] = 15;
623
624 6a988808 Justin Ruggles
    /* decrease the delta between each groups to within 2 so that they can be
625
       differentially encoded */
626
    for (i = 1; i <= nb_groups; i++)
627 bb270c08 Diego Biurrun
        exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
628 6a988808 Justin Ruggles
    for (i = nb_groups-1; i >= 0; i--)
629 bb270c08 Diego Biurrun
        exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
630 e44cad52 Jeff Muizelaar
631 de6d9b64 Fabrice Bellard
    /* now we have the exponent values the decoder will see */
632
    encoded_exp[0] = exp1[0];
633
    k = 1;
634 6a988808 Justin Ruggles
    for (i = 1; i <= nb_groups; i++) {
635
        for (j = 0; j < group_size; j++)
636 de6d9b64 Fabrice Bellard
            encoded_exp[k+j] = exp1[i];
637
        k += group_size;
638
    }
639
}
640
641 2f8ae522 Justin Ruggles
642 c36ce0f8 Justin Ruggles
/**
643 dfdf73eb Justin Ruggles
 * Encode exponents from original extracted form to what the decoder will see.
644
 * This copies and groups exponents based on exponent strategy and reduces
645
 * deltas between adjacent exponent groups so that they can be differentially
646
 * encoded.
647
 */
648 266d24be Justin Ruggles
static void encode_exponents(AC3EncodeContext *s)
649 dfdf73eb Justin Ruggles
{
650
    int blk, blk1, blk2, ch;
651 5901cebe Justin Ruggles
    AC3Block *block, *block1, *block2;
652 dfdf73eb Justin Ruggles
653
    for (ch = 0; ch < s->channels; ch++) {
654
        blk = 0;
655 5901cebe Justin Ruggles
        block = &s->blocks[0];
656 dfdf73eb Justin Ruggles
        while (blk < AC3_MAX_BLOCKS) {
657
            blk1 = blk + 1;
658 5901cebe Justin Ruggles
            block1 = block + 1;
659 2d82d9b1 Justin Ruggles
            /* for the EXP_REUSE case we select the min of the exponents */
660 5901cebe Justin Ruggles
            while (blk1 < AC3_MAX_BLOCKS && block1->exp_strategy[ch] == EXP_REUSE) {
661
                exponent_min(block->exp[ch], block1->exp[ch], s->nb_coefs[ch]);
662 dfdf73eb Justin Ruggles
                blk1++;
663 5901cebe Justin Ruggles
                block1++;
664 dfdf73eb Justin Ruggles
            }
665 5901cebe Justin Ruggles
            encode_exponents_blk_ch(block->encoded_exp[ch],
666
                                    block->exp[ch], s->nb_coefs[ch],
667
                                    block->exp_strategy[ch],
668
                                    &block->num_exp_groups[ch]);
669 dfdf73eb Justin Ruggles
            /* copy encoded exponents for reuse case */
670 5901cebe Justin Ruggles
            block2 = block + 1;
671
            for (blk2 = blk+1; blk2 < blk1; blk2++, block2++) {
672
                memcpy(block2->encoded_exp[ch], block->encoded_exp[ch],
673 dfdf73eb Justin Ruggles
                       s->nb_coefs[ch] * sizeof(uint8_t));
674
            }
675
            blk = blk1;
676 5901cebe Justin Ruggles
            block = block1;
677 dfdf73eb Justin Ruggles
        }
678
    }
679 f94bacc5 Justin Ruggles
}
680
681
682
/**
683
 * Group exponents.
684
 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
685
 * varies depending on exponent strategy and bandwidth.
686
 */
687 266d24be Justin Ruggles
static void group_exponents(AC3EncodeContext *s)
688 f94bacc5 Justin Ruggles
{
689
    int blk, ch, i;
690
    int group_size, bit_count;
691
    uint8_t *p;
692
    int delta0, delta1, delta2;
693
    int exp0, exp1;
694
695
    bit_count = 0;
696
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
697 5901cebe Justin Ruggles
        AC3Block *block = &s->blocks[blk];
698 f94bacc5 Justin Ruggles
        for (ch = 0; ch < s->channels; ch++) {
699 5901cebe Justin Ruggles
            if (block->exp_strategy[ch] == EXP_REUSE) {
700
                block->num_exp_groups[ch] = 0;
701 f94bacc5 Justin Ruggles
                continue;
702
            }
703 5901cebe Justin Ruggles
            group_size = block->exp_strategy[ch] + (block->exp_strategy[ch] == EXP_D45);
704
            bit_count += 4 + (block->num_exp_groups[ch] * 7);
705
            p = block->encoded_exp[ch];
706 f94bacc5 Justin Ruggles
707
            /* DC exponent */
708
            exp1 = *p++;
709 5901cebe Justin Ruggles
            block->grouped_exp[ch][0] = exp1;
710 f94bacc5 Justin Ruggles
711
            /* remaining exponents are delta encoded */
712 5901cebe Justin Ruggles
            for (i = 1; i <= block->num_exp_groups[ch]; i++) {
713 f94bacc5 Justin Ruggles
                /* merge three delta in one code */
714
                exp0   = exp1;
715
                exp1   = p[0];
716
                p     += group_size;
717
                delta0 = exp1 - exp0 + 2;
718
719
                exp0   = exp1;
720
                exp1   = p[0];
721
                p     += group_size;
722
                delta1 = exp1 - exp0 + 2;
723
724
                exp0   = exp1;
725
                exp1   = p[0];
726
                p     += group_size;
727
                delta2 = exp1 - exp0 + 2;
728
729 5901cebe Justin Ruggles
                block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
730 f94bacc5 Justin Ruggles
            }
731
        }
732
    }
733 dfdf73eb Justin Ruggles
734 359c1d19 Justin Ruggles
    s->exponent_bits = bit_count;
735 dfdf73eb Justin Ruggles
}
736
737
738
/**
739
 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
740
 * Extract exponents from MDCT coefficients, calculate exponent strategies,
741
 * and encode final exponents.
742
 */
743 266d24be Justin Ruggles
static void process_exponents(AC3EncodeContext *s)
744 dfdf73eb Justin Ruggles
{
745 266d24be Justin Ruggles
    extract_exponents(s);
746 dfdf73eb Justin Ruggles
747 266d24be Justin Ruggles
    compute_exp_strategy(s);
748 dfdf73eb Justin Ruggles
749 266d24be Justin Ruggles
    encode_exponents(s);
750 f94bacc5 Justin Ruggles
751 266d24be Justin Ruggles
    group_exponents(s);
752 dfdf73eb Justin Ruggles
}
753
754
755
/**
756 793bbf95 Justin Ruggles
 * Initialize bit allocation.
757
 * Set default parameter codes and calculate parameter values.
758
 */
759
static void bit_alloc_init(AC3EncodeContext *s)
760
{
761
    int ch;
762
763
    /* init default parameters */
764
    s->slow_decay_code = 2;
765
    s->fast_decay_code = 1;
766
    s->slow_gain_code  = 1;
767
    s->db_per_bit_code = 2;
768
    s->floor_code      = 4;
769
    for (ch = 0; ch < s->channels; ch++)
770
        s->fast_gain_code[ch] = 4;
771
772
    /* initial snr offset */
773
    s->coarse_snr_offset = 40;
774
775
    /* compute real values */
776
    /* currently none of these values change during encoding, so we can just
777
       set them once at initialization */
778
    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
779
    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
780
    s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
781
    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
782
    s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
783
}
784
785
786
/**
787 8999944e Justin Ruggles
 * Count the bits used to encode the frame, minus exponents and mantissas.
788
 */
789 266d24be Justin Ruggles
static void count_frame_bits(AC3EncodeContext *s)
790 8999944e Justin Ruggles
{
791
    static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
792
    int blk, ch;
793
    int frame_bits;
794
795
    /* header size */
796
    frame_bits = 65;
797
    frame_bits += frame_bits_inc[s->channel_mode];
798
799
    /* audio blocks */
800
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
801
        frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
802
        if (s->channel_mode == AC3_CHMODE_STEREO) {
803
            frame_bits++; /* rematstr */
804
            if (!blk)
805
                frame_bits += 4;
806
        }
807
        frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
808
        if (s->lfe_on)
809
            frame_bits++; /* lfeexpstr */
810
        for (ch = 0; ch < s->fbw_channels; ch++) {
811 5901cebe Justin Ruggles
            if (s->blocks[blk].exp_strategy[ch] != EXP_REUSE)
812 8999944e Justin Ruggles
                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
813
        }
814
        frame_bits++; /* baie */
815
        frame_bits++; /* snr */
816
        frame_bits += 2; /* delta / skip */
817
    }
818
    frame_bits++; /* cplinu for block 0 */
819
    /* bit alloc info */
820
    /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
821
    /* csnroffset[6] */
822
    /* (fsnoffset[4] + fgaincod[4]) * c */
823
    frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
824
825
    /* auxdatae, crcrsv */
826
    frame_bits += 2;
827
828
    /* CRC */
829
    frame_bits += 16;
830
831 359c1d19 Justin Ruggles
    s->frame_bits = frame_bits;
832 8999944e Justin Ruggles
}
833
834
835
/**
836 c36ce0f8 Justin Ruggles
 * Calculate the number of bits needed to encode a set of mantissas.
837
 */
838 2d82d9b1 Justin Ruggles
static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *bap, int nb_coefs)
839 de6d9b64 Fabrice Bellard
{
840 2d82d9b1 Justin Ruggles
    int bits, b, i;
841 de6d9b64 Fabrice Bellard
842
    bits = 0;
843 6a988808 Justin Ruggles
    for (i = 0; i < nb_coefs; i++) {
844 2d82d9b1 Justin Ruggles
        b = bap[i];
845
        switch (b) {
846 de6d9b64 Fabrice Bellard
        case 0:
847 2d82d9b1 Justin Ruggles
            /* bap=0 mantissas are not encoded */
848 de6d9b64 Fabrice Bellard
            break;
849
        case 1:
850 2d82d9b1 Justin Ruggles
            /* 3 mantissas in 5 bits */
851 115329f1 Diego Biurrun
            if (s->mant1_cnt == 0)
852 de6d9b64 Fabrice Bellard
                bits += 5;
853
            if (++s->mant1_cnt == 3)
854
                s->mant1_cnt = 0;
855
            break;
856
        case 2:
857 2d82d9b1 Justin Ruggles
            /* 3 mantissas in 7 bits */
858 115329f1 Diego Biurrun
            if (s->mant2_cnt == 0)
859 de6d9b64 Fabrice Bellard
                bits += 7;
860
            if (++s->mant2_cnt == 3)
861
                s->mant2_cnt = 0;
862
            break;
863
        case 3:
864
            bits += 3;
865
            break;
866
        case 4:
867 2d82d9b1 Justin Ruggles
            /* 2 mantissas in 7 bits */
868 de6d9b64 Fabrice Bellard
            if (s->mant4_cnt == 0)
869
                bits += 7;
870 115329f1 Diego Biurrun
            if (++s->mant4_cnt == 2)
871 de6d9b64 Fabrice Bellard
                s->mant4_cnt = 0;
872
            break;
873
        case 14:
874
            bits += 14;
875
            break;
876
        case 15:
877
            bits += 16;
878
            break;
879
        default:
880 2d82d9b1 Justin Ruggles
            bits += b - 1;
881 de6d9b64 Fabrice Bellard
            break;
882
        }
883
    }
884
    return bits;
885
}
886
887
888 c36ce0f8 Justin Ruggles
/**
889
 * Calculate masking curve based on the final exponents.
890
 * Also calculate the power spectral densities to use in future calculations.
891
 */
892 266d24be Justin Ruggles
static void bit_alloc_masking(AC3EncodeContext *s)
893 bbd16dea Justin Ruggles
{
894
    int blk, ch;
895
896 6a988808 Justin Ruggles
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
897 5901cebe Justin Ruggles
        AC3Block *block = &s->blocks[blk];
898 6a988808 Justin Ruggles
        for (ch = 0; ch < s->channels; ch++) {
899 5901cebe Justin Ruggles
            if (block->exp_strategy[ch] == EXP_REUSE) {
900
                AC3Block *block1 = &s->blocks[blk-1];
901
                memcpy(block->psd[ch],  block1->psd[ch],  AC3_MAX_COEFS*sizeof(block->psd[0][0]));
902
                memcpy(block->mask[ch], block1->mask[ch], AC3_CRITICAL_BANDS*sizeof(block->mask[0][0]));
903 bbd16dea Justin Ruggles
            } else {
904 5901cebe Justin Ruggles
                ff_ac3_bit_alloc_calc_psd(block->encoded_exp[ch], 0,
905 bbd16dea Justin Ruggles
                                          s->nb_coefs[ch],
906 5901cebe Justin Ruggles
                                          block->psd[ch], block->band_psd[ch]);
907
                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
908 bbd16dea Justin Ruggles
                                           0, s->nb_coefs[ch],
909 5ce21342 Justin Ruggles
                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
910 bbd16dea Justin Ruggles
                                           ch == s->lfe_channel,
911 cc2a8443 Justin Ruggles
                                           DBA_NONE, 0, NULL, NULL, NULL,
912 5901cebe Justin Ruggles
                                           block->mask[ch]);
913 bbd16dea Justin Ruggles
            }
914
        }
915
    }
916
}
917
918 2f8ae522 Justin Ruggles
919 c36ce0f8 Justin Ruggles
/**
920 171bc51c Justin Ruggles
 * Ensure that bap for each block and channel point to the current bap_buffer.
921
 * They may have been switched during the bit allocation search.
922
 */
923
static void reset_block_bap(AC3EncodeContext *s)
924
{
925
    int blk, ch;
926
    if (s->blocks[0].bap[0] == s->bap_buffer)
927
        return;
928
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
929
        for (ch = 0; ch < s->channels; ch++) {
930
            s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
931
        }
932
    }
933
}
934
935
936
/**
937 c36ce0f8 Justin Ruggles
 * Run the bit allocation with a given SNR offset.
938
 * This calculates the bit allocation pointers that will be used to determine
939
 * the quantization of each mantissa.
940 70fcd7ea Justin Ruggles
 * @return the number of bits needed for mantissas if the given SNR offset is
941
 *         is used.
942 c36ce0f8 Justin Ruggles
 */
943 de6d9b64 Fabrice Bellard
static int bit_alloc(AC3EncodeContext *s,
944 a0d763fc Justin Ruggles
                     int snr_offset)
945 de6d9b64 Fabrice Bellard
{
946 ce67b7cd Justin Ruggles
    int blk, ch;
947 a0d763fc Justin Ruggles
    int mantissa_bits;
948 319708da Justin Ruggles
949 a0d763fc Justin Ruggles
    snr_offset = (snr_offset - 240) << 2;
950 de6d9b64 Fabrice Bellard
951 171bc51c Justin Ruggles
    reset_block_bap(s);
952 70fcd7ea Justin Ruggles
    mantissa_bits = 0;
953 ce67b7cd Justin Ruggles
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
954 5901cebe Justin Ruggles
        AC3Block *block = &s->blocks[blk];
955 de6d9b64 Fabrice Bellard
        s->mant1_cnt = 0;
956
        s->mant2_cnt = 0;
957
        s->mant4_cnt = 0;
958 6a988808 Justin Ruggles
        for (ch = 0; ch < s->channels; ch++) {
959 5901cebe Justin Ruggles
            ff_ac3_bit_alloc_calc_bap(block->mask[ch], block->psd[ch], 0,
960 5ce21342 Justin Ruggles
                                      s->nb_coefs[ch], snr_offset,
961 687671f0 Justin Ruggles
                                      s->bit_alloc.floor, ff_ac3_bap_tab,
962 171bc51c Justin Ruggles
                                      block->bap[ch]);
963
            mantissa_bits += compute_mantissa_size(s, block->bap[ch], s->nb_coefs[ch]);
964 de6d9b64 Fabrice Bellard
        }
965
    }
966 70fcd7ea Justin Ruggles
    return mantissa_bits;
967 de6d9b64 Fabrice Bellard
}
968
969 2f8ae522 Justin Ruggles
970 c36ce0f8 Justin Ruggles
/**
971 cb6247cb Justin Ruggles
 * Constant bitrate bit allocation search.
972
 * Find the largest SNR offset that will allow data to fit in the frame.
973 c36ce0f8 Justin Ruggles
 */
974 cb6247cb Justin Ruggles
static int cbr_bit_allocation(AC3EncodeContext *s)
975 de6d9b64 Fabrice Bellard
{
976 8999944e Justin Ruggles
    int ch;
977 70fcd7ea Justin Ruggles
    int bits_left;
978 a0d763fc Justin Ruggles
    int snr_offset;
979 de6d9b64 Fabrice Bellard
980 70fcd7ea Justin Ruggles
    bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
981 7da4dc17 Justin Ruggles
982 a0d763fc Justin Ruggles
    snr_offset = s->coarse_snr_offset << 4;
983 7da4dc17 Justin Ruggles
984 a0d763fc Justin Ruggles
    while (snr_offset >= 0 &&
985 171bc51c Justin Ruggles
           bit_alloc(s, snr_offset) > bits_left) {
986 a0d763fc Justin Ruggles
        snr_offset -= 64;
987 7da4dc17 Justin Ruggles
    }
988 2d82d9b1 Justin Ruggles
    if (snr_offset < 0)
989 dc0bc0f8 Justin Ruggles
        return AVERROR(EINVAL);
990 7da4dc17 Justin Ruggles
991 171bc51c Justin Ruggles
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
992 a0d763fc Justin Ruggles
    while (snr_offset + 64 <= 1023 &&
993 171bc51c Justin Ruggles
           bit_alloc(s, snr_offset + 64) <= bits_left) {
994 a0d763fc Justin Ruggles
        snr_offset += 64;
995 171bc51c Justin Ruggles
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
996 de6d9b64 Fabrice Bellard
    }
997 a0d763fc Justin Ruggles
    while (snr_offset + 16 <= 1023 &&
998 171bc51c Justin Ruggles
           bit_alloc(s, snr_offset + 16) <= bits_left) {
999 a0d763fc Justin Ruggles
        snr_offset += 16;
1000 171bc51c Justin Ruggles
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1001 de6d9b64 Fabrice Bellard
    }
1002 a0d763fc Justin Ruggles
    while (snr_offset + 4 <= 1023 &&
1003 171bc51c Justin Ruggles
           bit_alloc(s, snr_offset + 4) <= bits_left) {
1004 a0d763fc Justin Ruggles
        snr_offset += 4;
1005 171bc51c Justin Ruggles
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1006 de6d9b64 Fabrice Bellard
    }
1007 a0d763fc Justin Ruggles
    while (snr_offset + 1 <= 1023 &&
1008 171bc51c Justin Ruggles
           bit_alloc(s, snr_offset + 1) <= bits_left) {
1009 a0d763fc Justin Ruggles
        snr_offset++;
1010 171bc51c Justin Ruggles
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1011 de6d9b64 Fabrice Bellard
    }
1012 171bc51c Justin Ruggles
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1013
    reset_block_bap(s);
1014 115329f1 Diego Biurrun
1015 a0d763fc Justin Ruggles
    s->coarse_snr_offset = snr_offset >> 4;
1016 6a988808 Justin Ruggles
    for (ch = 0; ch < s->channels; ch++)
1017 a0d763fc Justin Ruggles
        s->fine_snr_offset[ch] = snr_offset & 0xF;
1018 22c0b03c Justin Ruggles
1019 de6d9b64 Fabrice Bellard
    return 0;
1020
}
1021
1022 2f8ae522 Justin Ruggles
1023 c36ce0f8 Justin Ruggles
/**
1024 cb6247cb Justin Ruggles
 * Perform bit allocation search.
1025
 * Finds the SNR offset value that maximizes quality and fits in the specified
1026
 * frame size.  Output is the SNR offset and a set of bit allocation pointers
1027
 * used to quantize the mantissas.
1028
 */
1029
static int compute_bit_allocation(AC3EncodeContext *s)
1030
{
1031
    count_frame_bits(s);
1032
1033
    bit_alloc_masking(s);
1034
1035
    return cbr_bit_allocation(s);
1036
}
1037
1038
1039
/**
1040 c36ce0f8 Justin Ruggles
 * Symmetric quantization on 'levels' levels.
1041
 */
1042 de6d9b64 Fabrice Bellard
static inline int sym_quant(int c, int e, int levels)
1043
{
1044
    int v;
1045
1046
    if (c >= 0) {
1047 8d67072f Fabrice Bellard
        v = (levels * (c << e)) >> 24;
1048
        v = (v + 1) >> 1;
1049 de6d9b64 Fabrice Bellard
        v = (levels >> 1) + v;
1050
    } else {
1051 8d67072f Fabrice Bellard
        v = (levels * ((-c) << e)) >> 24;
1052
        v = (v + 1) >> 1;
1053 de6d9b64 Fabrice Bellard
        v = (levels >> 1) - v;
1054
    }
1055 2d82d9b1 Justin Ruggles
    assert(v >= 0 && v < levels);
1056 de6d9b64 Fabrice Bellard
    return v;
1057
}
1058
1059 2f8ae522 Justin Ruggles
1060 c36ce0f8 Justin Ruggles
/**
1061
 * Asymmetric quantization on 2^qbits levels.
1062
 */
1063 de6d9b64 Fabrice Bellard
static inline int asym_quant(int c, int e, int qbits)
1064
{
1065
    int lshift, m, v;
1066
1067
    lshift = e + qbits - 24;
1068
    if (lshift >= 0)
1069
        v = c << lshift;
1070
    else
1071
        v = c >> (-lshift);
1072
    /* rounding */
1073
    v = (v + 1) >> 1;
1074
    m = (1 << (qbits-1));
1075
    if (v >= m)
1076
        v = m - 1;
1077
    assert(v >= -m);
1078
    return v & ((1 << qbits)-1);
1079
}
1080
1081 2f8ae522 Justin Ruggles
1082 c36ce0f8 Justin Ruggles
/**
1083 b6a1e523 Justin Ruggles
 * Quantize a set of mantissas for a single channel in a single block.
1084
 */
1085
static void quantize_mantissas_blk_ch(AC3EncodeContext *s,
1086
                                      int32_t *mdct_coef, int8_t exp_shift,
1087
                                      uint8_t *encoded_exp, uint8_t *bap,
1088
                                      uint16_t *qmant, int n)
1089
{
1090
    int i;
1091
1092
    for (i = 0; i < n; i++) {
1093
        int v;
1094
        int c = mdct_coef[i];
1095
        int e = encoded_exp[i] - exp_shift;
1096
        int b = bap[i];
1097
        switch (b) {
1098
        case 0:
1099
            v = 0;
1100
            break;
1101
        case 1:
1102
            v = sym_quant(c, e, 3);
1103
            switch (s->mant1_cnt) {
1104
            case 0:
1105
                s->qmant1_ptr = &qmant[i];
1106
                v = 9 * v;
1107
                s->mant1_cnt = 1;
1108
                break;
1109
            case 1:
1110
                *s->qmant1_ptr += 3 * v;
1111
                s->mant1_cnt = 2;
1112
                v = 128;
1113
                break;
1114
            default:
1115
                *s->qmant1_ptr += v;
1116
                s->mant1_cnt = 0;
1117
                v = 128;
1118
                break;
1119
            }
1120
            break;
1121
        case 2:
1122
            v = sym_quant(c, e, 5);
1123
            switch (s->mant2_cnt) {
1124
            case 0:
1125
                s->qmant2_ptr = &qmant[i];
1126
                v = 25 * v;
1127
                s->mant2_cnt = 1;
1128
                break;
1129
            case 1:
1130
                *s->qmant2_ptr += 5 * v;
1131
                s->mant2_cnt = 2;
1132
                v = 128;
1133
                break;
1134
            default:
1135
                *s->qmant2_ptr += v;
1136
                s->mant2_cnt = 0;
1137
                v = 128;
1138
                break;
1139
            }
1140
            break;
1141
        case 3:
1142
            v = sym_quant(c, e, 7);
1143
            break;
1144
        case 4:
1145
            v = sym_quant(c, e, 11);
1146
            switch (s->mant4_cnt) {
1147
            case 0:
1148
                s->qmant4_ptr = &qmant[i];
1149
                v = 11 * v;
1150
                s->mant4_cnt = 1;
1151
                break;
1152
            default:
1153
                *s->qmant4_ptr += v;
1154
                s->mant4_cnt = 0;
1155
                v = 128;
1156
                break;
1157
            }
1158
            break;
1159
        case 5:
1160
            v = sym_quant(c, e, 15);
1161
            break;
1162
        case 14:
1163
            v = asym_quant(c, e, 14);
1164
            break;
1165
        case 15:
1166
            v = asym_quant(c, e, 16);
1167
            break;
1168
        default:
1169
            v = asym_quant(c, e, b - 1);
1170
            break;
1171
        }
1172
        qmant[i] = v;
1173
    }
1174
}
1175
1176
1177
/**
1178
 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1179
 */
1180 266d24be Justin Ruggles
static void quantize_mantissas(AC3EncodeContext *s)
1181 b6a1e523 Justin Ruggles
{
1182
    int blk, ch;
1183
1184
1185
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1186 5901cebe Justin Ruggles
        AC3Block *block = &s->blocks[blk];
1187 b6a1e523 Justin Ruggles
        s->mant1_cnt  = s->mant2_cnt  = s->mant4_cnt  = 0;
1188
        s->qmant1_ptr = s->qmant2_ptr = s->qmant4_ptr = NULL;
1189
1190
        for (ch = 0; ch < s->channels; ch++) {
1191 5901cebe Justin Ruggles
            quantize_mantissas_blk_ch(s, block->mdct_coef[ch], block->exp_shift[ch],
1192 171bc51c Justin Ruggles
                                      block->encoded_exp[ch], block->bap[ch],
1193 5901cebe Justin Ruggles
                                      block->qmant[ch], s->nb_coefs[ch]);
1194 b6a1e523 Justin Ruggles
        }
1195
    }
1196
}
1197
1198
1199
/**
1200 5b44ede0 Justin Ruggles
 * Write the AC-3 frame header to the output bitstream.
1201
 */
1202
static void output_frame_header(AC3EncodeContext *s)
1203
{
1204
    put_bits(&s->pb, 16, 0x0b77);   /* frame header */
1205
    put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
1206
    put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
1207
    put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1208
    put_bits(&s->pb, 5,  s->bitstream_id);
1209
    put_bits(&s->pb, 3,  s->bitstream_mode);
1210
    put_bits(&s->pb, 3,  s->channel_mode);
1211
    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1212
        put_bits(&s->pb, 2, 1);     /* XXX -4.5 dB */
1213
    if (s->channel_mode & 0x04)
1214
        put_bits(&s->pb, 2, 1);     /* XXX -6 dB */
1215
    if (s->channel_mode == AC3_CHMODE_STEREO)
1216
        put_bits(&s->pb, 2, 0);     /* surround not indicated */
1217
    put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1218
    put_bits(&s->pb, 5, 31);        /* dialog norm: -31 db */
1219
    put_bits(&s->pb, 1, 0);         /* no compression control word */
1220
    put_bits(&s->pb, 1, 0);         /* no lang code */
1221
    put_bits(&s->pb, 1, 0);         /* no audio production info */
1222
    put_bits(&s->pb, 1, 0);         /* no copyright */
1223
    put_bits(&s->pb, 1, 1);         /* original bitstream */
1224
    put_bits(&s->pb, 1, 0);         /* no time code 1 */
1225
    put_bits(&s->pb, 1, 0);         /* no time code 2 */
1226
    put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
1227
}
1228
1229
1230
/**
1231 c36ce0f8 Justin Ruggles
 * Write one audio block to the output bitstream.
1232
 */
1233 de6d9b64 Fabrice Bellard
static void output_audio_block(AC3EncodeContext *s,
1234
                               int block_num)
1235
{
1236 f94bacc5 Justin Ruggles
    int ch, i, baie, rbnd;
1237 5901cebe Justin Ruggles
    AC3Block *block = &s->blocks[block_num];
1238 de6d9b64 Fabrice Bellard
1239 2d82d9b1 Justin Ruggles
    /* block switching */
1240 6a988808 Justin Ruggles
    for (ch = 0; ch < s->fbw_channels; ch++)
1241 2d82d9b1 Justin Ruggles
        put_bits(&s->pb, 1, 0);
1242
1243
    /* dither flags */
1244 6a988808 Justin Ruggles
    for (ch = 0; ch < s->fbw_channels; ch++)
1245 2d82d9b1 Justin Ruggles
        put_bits(&s->pb, 1, 1);
1246
1247
    /* dynamic range codes */
1248
    put_bits(&s->pb, 1, 0);
1249
1250
    /* channel coupling */
1251 6a988808 Justin Ruggles
    if (!block_num) {
1252 de6d9b64 Fabrice Bellard
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
1253
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
1254
    } else {
1255
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1256
    }
1257
1258 2d82d9b1 Justin Ruggles
    /* stereo rematrixing */
1259 6a988808 Justin Ruggles
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1260
        if (!block_num) {
1261
            /* first block must define rematrixing (rematstr) */
1262 bb270c08 Diego Biurrun
            put_bits(&s->pb, 1, 1);
1263
1264
            /* dummy rematrixing rematflg(1:4)=0 */
1265 6a988808 Justin Ruggles
            for (rbnd = 0; rbnd < 4; rbnd++)
1266
                put_bits(&s->pb, 1, 0);
1267
        } else {
1268 bb270c08 Diego Biurrun
            /* no matrixing (but should be used in the future) */
1269
            put_bits(&s->pb, 1, 0);
1270 6a988808 Justin Ruggles
        }
1271
    }
1272 de6d9b64 Fabrice Bellard
1273
    /* exponent strategy */
1274 6a988808 Justin Ruggles
    for (ch = 0; ch < s->fbw_channels; ch++)
1275 5901cebe Justin Ruggles
        put_bits(&s->pb, 2, block->exp_strategy[ch]);
1276 6a988808 Justin Ruggles
    if (s->lfe_on)
1277 5901cebe Justin Ruggles
        put_bits(&s->pb, 1, block->exp_strategy[s->lfe_channel]);
1278 30b68f33 Zdenek Kabelac
1279 6a988808 Justin Ruggles
    /* bandwidth */
1280
    for (ch = 0; ch < s->fbw_channels; ch++) {
1281 5901cebe Justin Ruggles
        if (block->exp_strategy[ch] != EXP_REUSE)
1282 2d2692eb Justin Ruggles
            put_bits(&s->pb, 6, s->bandwidth_code[ch]);
1283 de6d9b64 Fabrice Bellard
    }
1284 115329f1 Diego Biurrun
1285 de6d9b64 Fabrice Bellard
    /* exponents */
1286 2d2692eb Justin Ruggles
    for (ch = 0; ch < s->channels; ch++) {
1287 5901cebe Justin Ruggles
        if (block->exp_strategy[ch] == EXP_REUSE)
1288 de6d9b64 Fabrice Bellard
            continue;
1289
1290 2d82d9b1 Justin Ruggles
        /* DC exponent */
1291 5901cebe Justin Ruggles
        put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1292 f94bacc5 Justin Ruggles
1293 2d82d9b1 Justin Ruggles
        /* exponent groups */
1294 5901cebe Justin Ruggles
        for (i = 1; i <= block->num_exp_groups[ch]; i++)
1295
            put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1296 de6d9b64 Fabrice Bellard
1297 2d82d9b1 Justin Ruggles
        /* gain range info */
1298 bb270c08 Diego Biurrun
        if (ch != s->lfe_channel)
1299 2d82d9b1 Justin Ruggles
            put_bits(&s->pb, 2, 0);
1300 de6d9b64 Fabrice Bellard
    }
1301
1302
    /* bit allocation info */
1303
    baie = (block_num == 0);
1304
    put_bits(&s->pb, 1, baie);
1305
    if (baie) {
1306 5ce21342 Justin Ruggles
        put_bits(&s->pb, 2, s->slow_decay_code);
1307
        put_bits(&s->pb, 2, s->fast_decay_code);
1308
        put_bits(&s->pb, 2, s->slow_gain_code);
1309
        put_bits(&s->pb, 2, s->db_per_bit_code);
1310
        put_bits(&s->pb, 3, s->floor_code);
1311 de6d9b64 Fabrice Bellard
    }
1312
1313
    /* snr offset */
1314 6a988808 Justin Ruggles
    put_bits(&s->pb, 1, baie);
1315 de6d9b64 Fabrice Bellard
    if (baie) {
1316 5ce21342 Justin Ruggles
        put_bits(&s->pb, 6, s->coarse_snr_offset);
1317 6a988808 Justin Ruggles
        for (ch = 0; ch < s->channels; ch++) {
1318 5ce21342 Justin Ruggles
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1319
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1320 de6d9b64 Fabrice Bellard
        }
1321
    }
1322 115329f1 Diego Biurrun
1323 de6d9b64 Fabrice Bellard
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1324
    put_bits(&s->pb, 1, 0); /* no data to skip */
1325
1326 2d82d9b1 Justin Ruggles
    /* mantissas */
1327 2d2692eb Justin Ruggles
    for (ch = 0; ch < s->channels; ch++) {
1328 de6d9b64 Fabrice Bellard
        int b, q;
1329 6a988808 Justin Ruggles
        for (i = 0; i < s->nb_coefs[ch]; i++) {
1330 5901cebe Justin Ruggles
            q = block->qmant[ch][i];
1331 171bc51c Justin Ruggles
            b = block->bap[ch][i];
1332 6a988808 Justin Ruggles
            switch (b) {
1333
            case 0:                                         break;
1334
            case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
1335
            case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
1336
            case 3:               put_bits(&s->pb,   3, q); break;
1337
            case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
1338
            case 14:              put_bits(&s->pb,  14, q); break;
1339
            case 15:              put_bits(&s->pb,  16, q); break;
1340
            default:              put_bits(&s->pb, b-1, q); break;
1341 de6d9b64 Fabrice Bellard
            }
1342
        }
1343
    }
1344
}
1345
1346 2f8ae522 Justin Ruggles
1347 c36ce0f8 Justin Ruggles
/** CRC-16 Polynomial */
1348 de6d9b64 Fabrice Bellard
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1349
1350 2f8ae522 Justin Ruggles
1351 de6d9b64 Fabrice Bellard
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1352
{
1353
    unsigned int c;
1354
1355
    c = 0;
1356
    while (a) {
1357
        if (a & 1)
1358
            c ^= b;
1359
        a = a >> 1;
1360
        b = b << 1;
1361
        if (b & (1 << 16))
1362
            b ^= poly;
1363
    }
1364
    return c;
1365
}
1366
1367 2f8ae522 Justin Ruggles
1368 de6d9b64 Fabrice Bellard
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1369
{
1370
    unsigned int r;
1371
    r = 1;
1372
    while (n) {
1373
        if (n & 1)
1374
            r = mul_poly(r, a, poly);
1375
        a = mul_poly(a, a, poly);
1376
        n >>= 1;
1377
    }
1378
    return r;
1379
}
1380
1381 2f8ae522 Justin Ruggles
1382 c36ce0f8 Justin Ruggles
/**
1383
 * Fill the end of the frame with 0's and compute the two CRCs.
1384
 */
1385 1971ab6e Justin Ruggles
static void output_frame_end(AC3EncodeContext *s)
1386 de6d9b64 Fabrice Bellard
{
1387 eed00252 Justin Ruggles
    int frame_size, frame_size_58, pad_bytes, crc1, crc2, crc_inv;
1388 0c1a9eda Zdenek Kabelac
    uint8_t *frame;
1389 de6d9b64 Fabrice Bellard
1390 2d82d9b1 Justin Ruggles
    frame_size    = s->frame_size;
1391
    frame_size_58 = ((frame_size >> 2) + (frame_size >> 4)) << 1;
1392
1393
    /* pad the remainder of the frame with zeros */
1394 de6d9b64 Fabrice Bellard
    flush_put_bits(&s->pb);
1395
    frame = s->pb.buf;
1396 427e2293 Justin Ruggles
    pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1397 eed00252 Justin Ruggles
    assert(pad_bytes >= 0);
1398
    if (pad_bytes > 0)
1399
        memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1400 115329f1 Diego Biurrun
1401 2d82d9b1 Justin Ruggles
    /* compute crc1 */
1402
    /* this is not so easy because it is at the beginning of the data... */
1403 8fc0162a Måns Rullgård
    crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1404 427e2293 Justin Ruggles
                             frame + 4, frame_size_58 - 4));
1405 de6d9b64 Fabrice Bellard
    /* XXX: could precompute crc_inv */
1406 427e2293 Justin Ruggles
    crc_inv = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
1407 6a988808 Justin Ruggles
    crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1408
    AV_WB16(frame + 2, crc1);
1409 115329f1 Diego Biurrun
1410 2d82d9b1 Justin Ruggles
    /* compute crc2 */
1411 8fc0162a Måns Rullgård
    crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1412 427e2293 Justin Ruggles
                             frame + frame_size_58,
1413
                             frame_size - frame_size_58 - 2));
1414
    AV_WB16(frame + frame_size - 2, crc2);
1415 de6d9b64 Fabrice Bellard
}
1416
1417 2f8ae522 Justin Ruggles
1418 c36ce0f8 Justin Ruggles
/**
1419 67d979fe Justin Ruggles
 * Write the frame to the output bitstream.
1420
 */
1421
static void output_frame(AC3EncodeContext *s,
1422 266d24be Justin Ruggles
                         unsigned char *frame)
1423 67d979fe Justin Ruggles
{
1424
    int blk;
1425
1426
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1427
1428
    output_frame_header(s);
1429
1430 2d82d9b1 Justin Ruggles
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1431 266d24be Justin Ruggles
        output_audio_block(s, blk);
1432 67d979fe Justin Ruggles
1433
    output_frame_end(s);
1434
}
1435
1436
1437
/**
1438 c36ce0f8 Justin Ruggles
 * Encode a single AC-3 frame.
1439
 */
1440 a0a9204e Justin Ruggles
static int ac3_encode_frame(AVCodecContext *avctx,
1441 6107fa87 Fabrice Bellard
                            unsigned char *frame, int buf_size, void *data)
1442 de6d9b64 Fabrice Bellard
{
1443
    AC3EncodeContext *s = avctx->priv_data;
1444 edac49da Reimar Döffinger
    const int16_t *samples = data;
1445 dc0bc0f8 Justin Ruggles
    int ret;
1446 de6d9b64 Fabrice Bellard
1447 160d85f5 Justin Ruggles
    if (s->bit_alloc.sr_code == 1)
1448
        adjust_frame_size(s);
1449
1450 266d24be Justin Ruggles
    deinterleave_input_samples(s, samples);
1451 12ed6226 Justin Ruggles
1452 266d24be Justin Ruggles
    apply_mdct(s);
1453 115329f1 Diego Biurrun
1454 266d24be Justin Ruggles
    process_exponents(s);
1455 de6d9b64 Fabrice Bellard
1456 266d24be Justin Ruggles
    ret = compute_bit_allocation(s);
1457 dc0bc0f8 Justin Ruggles
    if (ret) {
1458
        av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1459
        return ret;
1460
    }
1461 084f5c5a Justin Ruggles
1462 266d24be Justin Ruggles
    quantize_mantissas(s);
1463 b6a1e523 Justin Ruggles
1464 266d24be Justin Ruggles
    output_frame(s, frame);
1465 1971ab6e Justin Ruggles
1466 427e2293 Justin Ruggles
    return s->frame_size;
1467 de6d9b64 Fabrice Bellard
}
1468
1469 2f8ae522 Justin Ruggles
1470 c36ce0f8 Justin Ruggles
/**
1471
 * Finalize encoding and free any memory allocated by the encoder.
1472
 */
1473 a0a9204e Justin Ruggles
static av_cold int ac3_encode_close(AVCodecContext *avctx)
1474 492cd3a9 Michael Niedermayer
{
1475 e8d21fba Justin Ruggles
    int blk, ch;
1476 171bc51c Justin Ruggles
    AC3EncodeContext *s = avctx->priv_data;
1477
1478 e8d21fba Justin Ruggles
    for (ch = 0; ch < s->channels; ch++)
1479
        av_freep(&s->planar_samples[ch]);
1480
    av_freep(&s->planar_samples);
1481 171bc51c Justin Ruggles
    av_freep(&s->bap_buffer);
1482
    av_freep(&s->bap1_buffer);
1483 b6f6204d Justin Ruggles
    av_freep(&s->mdct_coef_buffer);
1484
    av_freep(&s->exp_buffer);
1485
    av_freep(&s->encoded_exp_buffer);
1486
    av_freep(&s->grouped_exp_buffer);
1487
    av_freep(&s->psd_buffer);
1488
    av_freep(&s->band_psd_buffer);
1489
    av_freep(&s->mask_buffer);
1490
    av_freep(&s->qmant_buffer);
1491 171bc51c Justin Ruggles
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1492
        AC3Block *block = &s->blocks[blk];
1493
        av_freep(&block->bap);
1494 b6f6204d Justin Ruggles
        av_freep(&block->mdct_coef);
1495
        av_freep(&block->exp);
1496
        av_freep(&block->encoded_exp);
1497
        av_freep(&block->grouped_exp);
1498
        av_freep(&block->psd);
1499
        av_freep(&block->band_psd);
1500
        av_freep(&block->mask);
1501
        av_freep(&block->qmant);
1502 171bc51c Justin Ruggles
    }
1503
1504 492cd3a9 Michael Niedermayer
    av_freep(&avctx->coded_frame);
1505 ef9f7306 Måns Rullgård
    return 0;
1506 492cd3a9 Michael Niedermayer
}
1507
1508 2f8ae522 Justin Ruggles
1509 c36ce0f8 Justin Ruggles
/**
1510
 * Set channel information during initialization.
1511
 */
1512 e77fd066 Justin Ruggles
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1513
                                    int64_t *channel_layout)
1514
{
1515
    int ch_layout;
1516
1517
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
1518 ddf63d37 Justin Ruggles
        return AVERROR(EINVAL);
1519 e77fd066 Justin Ruggles
    if ((uint64_t)*channel_layout > 0x7FF)
1520 ddf63d37 Justin Ruggles
        return AVERROR(EINVAL);
1521 e77fd066 Justin Ruggles
    ch_layout = *channel_layout;
1522
    if (!ch_layout)
1523
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1524
    if (av_get_channel_layout_nb_channels(ch_layout) != channels)
1525 ddf63d37 Justin Ruggles
        return AVERROR(EINVAL);
1526 e77fd066 Justin Ruggles
1527
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1528
    s->channels     = channels;
1529
    s->fbw_channels = channels - s->lfe_on;
1530
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
1531
    if (s->lfe_on)
1532
        ch_layout -= AV_CH_LOW_FREQUENCY;
1533
1534
    switch (ch_layout) {
1535
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
1536
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
1537
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
1538
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
1539
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
1540
    case AV_CH_LAYOUT_QUAD:
1541
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
1542
    case AV_CH_LAYOUT_5POINT0:
1543
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
1544
    default:
1545 ddf63d37 Justin Ruggles
        return AVERROR(EINVAL);
1546 e77fd066 Justin Ruggles
    }
1547
1548
    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1549
    *channel_layout = ch_layout;
1550
    if (s->lfe_on)
1551
        *channel_layout |= AV_CH_LOW_FREQUENCY;
1552
1553
    return 0;
1554
}
1555
1556 2f8ae522 Justin Ruggles
1557 8f60f70d Justin Ruggles
static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1558 e77fd066 Justin Ruggles
{
1559 ddf63d37 Justin Ruggles
    int i, ret;
1560 e77fd066 Justin Ruggles
1561 e0685bc9 Justin Ruggles
    /* validate channel layout */
1562 e77fd066 Justin Ruggles
    if (!avctx->channel_layout) {
1563
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1564
                                      "encoder will guess the layout, but it "
1565
                                      "might be incorrect.\n");
1566
    }
1567 ddf63d37 Justin Ruggles
    ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1568
    if (ret) {
1569 e77fd066 Justin Ruggles
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1570 ddf63d37 Justin Ruggles
        return ret;
1571 e77fd066 Justin Ruggles
    }
1572
1573 e0685bc9 Justin Ruggles
    /* validate sample rate */
1574 99ca4f73 Justin Ruggles
    for (i = 0; i < 9; i++) {
1575
        if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
1576
            break;
1577 e77fd066 Justin Ruggles
    }
1578 99ca4f73 Justin Ruggles
    if (i == 9) {
1579 ddf63d37 Justin Ruggles
        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1580
        return AVERROR(EINVAL);
1581 99ca4f73 Justin Ruggles
    }
1582 1607db0a Justin Ruggles
    s->sample_rate        = avctx->sample_rate;
1583 99ca4f73 Justin Ruggles
    s->bit_alloc.sr_shift = i % 3;
1584
    s->bit_alloc.sr_code  = i / 3;
1585 e77fd066 Justin Ruggles
1586 e0685bc9 Justin Ruggles
    /* validate bit rate */
1587 e77fd066 Justin Ruggles
    for (i = 0; i < 19; i++) {
1588 1607db0a Justin Ruggles
        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
1589 e77fd066 Justin Ruggles
            break;
1590
    }
1591 ddf63d37 Justin Ruggles
    if (i == 19) {
1592
        av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
1593
        return AVERROR(EINVAL);
1594
    }
1595 1607db0a Justin Ruggles
    s->bit_rate        = avctx->bit_rate;
1596 e77fd066 Justin Ruggles
    s->frame_size_code = i << 1;
1597 8f60f70d Justin Ruggles
1598
    return 0;
1599
}
1600
1601
1602
/**
1603 282255bb Justin Ruggles
 * Set bandwidth for all channels.
1604
 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
1605
 * default value will be used.
1606
 */
1607
static av_cold void set_bandwidth(AC3EncodeContext *s, int cutoff)
1608
{
1609
    int ch, bw_code;
1610
1611
    if (cutoff) {
1612
        /* calculate bandwidth based on user-specified cutoff frequency */
1613
        int fbw_coeffs;
1614
        cutoff         = av_clip(cutoff, 1, s->sample_rate >> 1);
1615
        fbw_coeffs     = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
1616
        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
1617
    } else {
1618
        /* use default bandwidth setting */
1619
        /* XXX: should compute the bandwidth according to the frame
1620
           size, so that we avoid annoying high frequency artifacts */
1621
        bw_code = 50;
1622
    }
1623
1624
    /* set number of coefficients for each channel */
1625
    for (ch = 0; ch < s->fbw_channels; ch++) {
1626
        s->bandwidth_code[ch] = bw_code;
1627
        s->nb_coefs[ch]       = bw_code * 3 + 73;
1628
    }
1629
    if (s->lfe_on)
1630
        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
1631
}
1632
1633
1634 171bc51c Justin Ruggles
static av_cold int allocate_buffers(AVCodecContext *avctx)
1635
{
1636 e8d21fba Justin Ruggles
    int blk, ch;
1637 171bc51c Justin Ruggles
    AC3EncodeContext *s = avctx->priv_data;
1638
1639 e8d21fba Justin Ruggles
    FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
1640
                     alloc_fail);
1641
    for (ch = 0; ch < s->channels; ch++) {
1642
        FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
1643
                          (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
1644
                          alloc_fail);
1645
    }
1646 171bc51c Justin Ruggles
    FF_ALLOC_OR_GOTO(avctx, s->bap_buffer,  AC3_MAX_BLOCKS * s->channels *
1647
                     AC3_MAX_COEFS * sizeof(*s->bap_buffer),  alloc_fail);
1648
    FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
1649
                     AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
1650 b6f6204d Justin Ruggles
    FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
1651
                     AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
1652
    FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
1653
                     AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
1654
    FF_ALLOC_OR_GOTO(avctx, s->encoded_exp_buffer, AC3_MAX_BLOCKS * s->channels *
1655
                     AC3_MAX_COEFS * sizeof(*s->encoded_exp_buffer), alloc_fail);
1656
    FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
1657
                     128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
1658
    FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
1659
                     AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
1660
    FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
1661
                     64 * sizeof(*s->band_psd_buffer), alloc_fail);
1662
    FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
1663
                     64 * sizeof(*s->mask_buffer), alloc_fail);
1664
    FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
1665
                     AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
1666 171bc51c Justin Ruggles
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1667
        AC3Block *block = &s->blocks[blk];
1668
        FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
1669
                         alloc_fail);
1670 b6f6204d Justin Ruggles
        FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
1671
                          alloc_fail);
1672
        FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
1673
                          alloc_fail);
1674
        FF_ALLOCZ_OR_GOTO(avctx, block->encoded_exp, s->channels * sizeof(*block->encoded_exp),
1675
                          alloc_fail);
1676
        FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
1677
                          alloc_fail);
1678
        FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
1679
                          alloc_fail);
1680
        FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
1681
                          alloc_fail);
1682
        FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
1683
                          alloc_fail);
1684
        FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
1685
                          alloc_fail);
1686
1687
        for (ch = 0; ch < s->channels; ch++) {
1688
            block->bap[ch]         = &s->bap_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1689
            block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (blk * s->channels + ch)];
1690
            block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1691
            block->encoded_exp[ch] = &s->encoded_exp_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
1692
            block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * s->channels + ch)];
1693
            block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1694
            block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * s->channels + ch)];
1695
            block->mask[ch]        = &s->mask_buffer       [64            * (blk * s->channels + ch)];
1696
            block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * s->channels + ch)];
1697
        }
1698 171bc51c Justin Ruggles
    }
1699
1700
    return 0;
1701
alloc_fail:
1702
    return AVERROR(ENOMEM);
1703
}
1704
1705
1706 282255bb Justin Ruggles
/**
1707 8f60f70d Justin Ruggles
 * Initialize the encoder.
1708
 */
1709
static av_cold int ac3_encode_init(AVCodecContext *avctx)
1710
{
1711
    AC3EncodeContext *s = avctx->priv_data;
1712 282255bb Justin Ruggles
    int ret;
1713 8f60f70d Justin Ruggles
1714
    avctx->frame_size = AC3_FRAME_SIZE;
1715
1716
    ac3_common_init();
1717
1718
    ret = validate_options(avctx, s);
1719
    if (ret)
1720
        return ret;
1721
1722 e35c984a Justin Ruggles
    s->bitstream_id   = 8 + s->bit_alloc.sr_shift;
1723
    s->bitstream_mode = 0; /* complete main audio service */
1724
1725 427e2293 Justin Ruggles
    s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
1726 e77fd066 Justin Ruggles
    s->bits_written    = 0;
1727
    s->samples_written = 0;
1728
    s->frame_size      = s->frame_size_min;
1729
1730 282255bb Justin Ruggles
    set_bandwidth(s, avctx->cutoff);
1731 e77fd066 Justin Ruggles
1732 793bbf95 Justin Ruggles
    bit_alloc_init(s);
1733 e77fd066 Justin Ruggles
1734
    mdct_init(9);
1735
1736 171bc51c Justin Ruggles
    ret = allocate_buffers(avctx);
1737
    if (ret) {
1738
        ac3_encode_close(avctx);
1739
        return ret;
1740
    }
1741
1742 e77fd066 Justin Ruggles
    avctx->coded_frame= avcodec_alloc_frame();
1743
1744
    return 0;
1745
}
1746
1747 2f8ae522 Justin Ruggles
1748 228315bb Justin Ruggles
#ifdef TEST
1749 de6d9b64 Fabrice Bellard
/*************************************************************************/
1750
/* TEST */
1751
1752 228315bb Justin Ruggles
#include "libavutil/lfg.h"
1753 de6d9b64 Fabrice Bellard
1754 228315bb Justin Ruggles
#define FN (MDCT_SAMPLES/4)
1755
1756 2f8ae522 Justin Ruggles
1757 228315bb Justin Ruggles
static void fft_test(AVLFG *lfg)
1758 de6d9b64 Fabrice Bellard
{
1759
    IComplex in[FN], in1[FN];
1760
    int k, n, i;
1761
    float sum_re, sum_im, a;
1762
1763 6a988808 Justin Ruggles
    for (i = 0; i < FN; i++) {
1764 228315bb Justin Ruggles
        in[i].re = av_lfg_get(lfg) % 65535 - 32767;
1765
        in[i].im = av_lfg_get(lfg) % 65535 - 32767;
1766 6a988808 Justin Ruggles
        in1[i]   = in[i];
1767 de6d9b64 Fabrice Bellard
    }
1768
    fft(in, 7);
1769
1770
    /* do it by hand */
1771 6a988808 Justin Ruggles
    for (k = 0; k < FN; k++) {
1772 de6d9b64 Fabrice Bellard
        sum_re = 0;
1773
        sum_im = 0;
1774 6a988808 Justin Ruggles
        for (n = 0; n < FN; n++) {
1775 de6d9b64 Fabrice Bellard
            a = -2 * M_PI * (n * k) / FN;
1776
            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1777
            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1778
        }
1779 228315bb Justin Ruggles
        av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
1780 115329f1 Diego Biurrun
               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1781 de6d9b64 Fabrice Bellard
    }
1782
}
1783
1784 2f8ae522 Justin Ruggles
1785 228315bb Justin Ruggles
static void mdct_test(AVLFG *lfg)
1786 de6d9b64 Fabrice Bellard
{
1787 228315bb Justin Ruggles
    int16_t input[MDCT_SAMPLES];
1788
    int32_t output[AC3_MAX_COEFS];
1789
    float input1[MDCT_SAMPLES];
1790
    float output1[AC3_MAX_COEFS];
1791 de6d9b64 Fabrice Bellard
    float s, a, err, e, emax;
1792
    int i, k, n;
1793
1794 6a988808 Justin Ruggles
    for (i = 0; i < MDCT_SAMPLES; i++) {
1795
        input[i]  = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
1796 de6d9b64 Fabrice Bellard
        input1[i] = input[i];
1797
    }
1798
1799
    mdct512(output, input);
1800 115329f1 Diego Biurrun
1801 de6d9b64 Fabrice Bellard
    /* do it by hand */
1802 6a988808 Justin Ruggles
    for (k = 0; k < AC3_MAX_COEFS; k++) {
1803 de6d9b64 Fabrice Bellard
        s = 0;
1804 6a988808 Justin Ruggles
        for (n = 0; n < MDCT_SAMPLES; n++) {
1805 228315bb Justin Ruggles
            a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
1806 de6d9b64 Fabrice Bellard
            s += input1[n] * cos(a);
1807
        }
1808 228315bb Justin Ruggles
        output1[k] = -2 * s / MDCT_SAMPLES;
1809 de6d9b64 Fabrice Bellard
    }
1810 115329f1 Diego Biurrun
1811 6a988808 Justin Ruggles
    err  = 0;
1812 de6d9b64 Fabrice Bellard
    emax = 0;
1813 6a988808 Justin Ruggles
    for (i = 0; i < AC3_MAX_COEFS; i++) {
1814 228315bb Justin Ruggles
        av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
1815 de6d9b64 Fabrice Bellard
        e = output[i] - output1[i];
1816
        if (e > emax)
1817
            emax = e;
1818
        err += e * e;
1819
    }
1820 228315bb Justin Ruggles
    av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
1821 de6d9b64 Fabrice Bellard
}
1822
1823 2f8ae522 Justin Ruggles
1824 228315bb Justin Ruggles
int main(void)
1825 de6d9b64 Fabrice Bellard
{
1826 228315bb Justin Ruggles
    AVLFG lfg;
1827 115329f1 Diego Biurrun
1828 228315bb Justin Ruggles
    av_log_set_level(AV_LOG_DEBUG);
1829
    mdct_init(9);
1830 de6d9b64 Fabrice Bellard
1831 228315bb Justin Ruggles
    fft_test(&lfg);
1832
    mdct_test(&lfg);
1833 de6d9b64 Fabrice Bellard
1834 228315bb Justin Ruggles
    return 0;
1835 de6d9b64 Fabrice Bellard
}
1836 228315bb Justin Ruggles
#endif /* TEST */
1837 de6d9b64 Fabrice Bellard
1838 2f8ae522 Justin Ruggles
1839 de6d9b64 Fabrice Bellard
AVCodec ac3_encoder = {
1840
    "ac3",
1841 72415b2a Stefano Sabatini
    AVMEDIA_TYPE_AUDIO,
1842 de6d9b64 Fabrice Bellard
    CODEC_ID_AC3,
1843
    sizeof(AC3EncodeContext),
1844 a0a9204e Justin Ruggles
    ac3_encode_init,
1845
    ac3_encode_frame,
1846
    ac3_encode_close,
1847 de6d9b64 Fabrice Bellard
    NULL,
1848 5d6e4c16 Stefano Sabatini
    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1849 2988c93d Justin Ruggles
    .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1850 b5f09d31 Reimar Döffinger
    .channel_layouts = (const int64_t[]){
1851 63e8d976 Stefano Sabatini
        AV_CH_LAYOUT_MONO,
1852
        AV_CH_LAYOUT_STEREO,
1853
        AV_CH_LAYOUT_2_1,
1854
        AV_CH_LAYOUT_SURROUND,
1855
        AV_CH_LAYOUT_2_2,
1856
        AV_CH_LAYOUT_QUAD,
1857
        AV_CH_LAYOUT_4POINT0,
1858
        AV_CH_LAYOUT_5POINT0,
1859
        AV_CH_LAYOUT_5POINT0_BACK,
1860
       (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
1861
       (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
1862
       (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
1863
       (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1864
       (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
1865
       (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
1866
       (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
1867
        AV_CH_LAYOUT_5POINT1,
1868
        AV_CH_LAYOUT_5POINT1_BACK,
1869 120b4557 Justin Ruggles
        0 },
1870 de6d9b64 Fabrice Bellard
};