Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ e86ea34d

History | View | Annotate | Download (57.1 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 FFmpeg.
8
 *
9
 * FFmpeg 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
 * FFmpeg 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 FFmpeg; 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

    
31
#include "libavcore/audioconvert.h"
32
#include "libavutil/crc.h"
33
#include "avcodec.h"
34
#include "put_bits.h"
35
#include "dsputil.h"
36
#include "ac3.h"
37
#include "audioconvert.h"
38

    
39

    
40
#define MDCT_NBITS 9
41
#define MDCT_SAMPLES (1 << MDCT_NBITS)
42

    
43
/** Maximum number of exponent groups. +1 for separate DC exponent. */
44
#define AC3_MAX_EXP_GROUPS 85
45

    
46
/** Scale a float value by 2^bits and convert to an integer. */
47
#define SCALE_FLOAT(a, bits) lrintf((a) * (float)(1 << (bits)))
48

    
49
/** Scale a float value by 2^15, convert to an integer, and clip to int16_t range. */
50
#define FIX15(a) av_clip_int16(SCALE_FLOAT(a, 15))
51

    
52

    
53
/**
54
 * Compex number.
55
 * Used in fixed-point MDCT calculation.
56
 */
57
typedef struct IComplex {
58
    int16_t re,im;
59
} IComplex;
60

    
61
typedef struct AC3MDCTContext {
62
    AVCodecContext *avctx;                  ///< parent context for av_log()
63
    int16_t *rot_tmp;                       ///< temp buffer for pre-rotated samples
64
    IComplex *cplx_tmp;                     ///< temp buffer for complex pre-rotated samples
65
} AC3MDCTContext;
66

    
67
/**
68
 * Data for a single audio block.
69
 */
70
typedef struct AC3Block {
71
    uint8_t  **bap;                             ///< bit allocation pointers (bap)
72
    int32_t  **mdct_coef;                       ///< MDCT coefficients
73
    uint8_t  **exp;                             ///< original exponents
74
    uint8_t  **grouped_exp;                     ///< grouped exponents
75
    int16_t  **psd;                             ///< psd per frequency bin
76
    int16_t  **band_psd;                        ///< psd per critical band
77
    int16_t  **mask;                            ///< masking curve
78
    uint16_t **qmant;                           ///< quantized mantissas
79
    uint8_t  exp_strategy[AC3_MAX_CHANNELS];    ///< exponent strategies
80
    int8_t   exp_shift[AC3_MAX_CHANNELS];       ///< exponent shift values
81
} AC3Block;
82

    
83
/**
84
 * AC-3 encoder private context.
85
 */
86
typedef struct AC3EncodeContext {
87
    PutBitContext pb;                       ///< bitstream writer context
88
    DSPContext dsp;
89
    AC3MDCTContext mdct;                    ///< MDCT context
90

    
91
    AC3Block blocks[AC3_MAX_BLOCKS];        ///< per-block info
92

    
93
    int bitstream_id;                       ///< bitstream id                           (bsid)
94
    int bitstream_mode;                     ///< bitstream mode                         (bsmod)
95

    
96
    int bit_rate;                           ///< target bit rate, in bits-per-second
97
    int sample_rate;                        ///< sampling frequency, in Hz
98

    
99
    int frame_size_min;                     ///< minimum frame size in case rounding is necessary
100
    int frame_size;                         ///< current frame size in bytes
101
    int frame_size_code;                    ///< frame size code                        (frmsizecod)
102
    int bits_written;                       ///< bit count    (used to avg. bitrate)
103
    int samples_written;                    ///< sample count (used to avg. bitrate)
104

    
105
    int fbw_channels;                       ///< number of full-bandwidth channels      (nfchans)
106
    int channels;                           ///< total number of channels               (nchans)
107
    int lfe_on;                             ///< indicates if there is an LFE channel   (lfeon)
108
    int lfe_channel;                        ///< channel index of the LFE channel
109
    int channel_mode;                       ///< channel mode                           (acmod)
110
    const uint8_t *channel_map;             ///< channel map used to reorder channels
111

    
112
    int bandwidth_code[AC3_MAX_CHANNELS];   ///< bandwidth code (0 to 60)               (chbwcod)
113
    int nb_coefs[AC3_MAX_CHANNELS];
114

    
115
    /* bitrate allocation control */
116
    int slow_gain_code;                     ///< slow gain code                         (sgaincod)
117
    int slow_decay_code;                    ///< slow decay code                        (sdcycod)
118
    int fast_decay_code;                    ///< fast decay code                        (fdcycod)
119
    int db_per_bit_code;                    ///< dB/bit code                            (dbpbcod)
120
    int floor_code;                         ///< floor code                             (floorcod)
121
    AC3BitAllocParameters bit_alloc;        ///< bit allocation parameters
122
    int coarse_snr_offset;                  ///< coarse SNR offsets                     (csnroffst)
123
    int fast_gain_code[AC3_MAX_CHANNELS];   ///< fast gain codes (signal-to-mask ratio) (fgaincod)
124
    int fine_snr_offset[AC3_MAX_CHANNELS];  ///< fine SNR offsets                       (fsnroffst)
125
    int frame_bits;                         ///< all frame bits except exponents and mantissas
126
    int exponent_bits;                      ///< number of bits used for exponents
127

    
128
    /* mantissa encoding */
129
    int mant1_cnt, mant2_cnt, mant4_cnt;    ///< mantissa counts for bap=1,2,4
130
    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
131

    
132
    int16_t **planar_samples;
133
    uint8_t *bap_buffer;
134
    uint8_t *bap1_buffer;
135
    int32_t *mdct_coef_buffer;
136
    uint8_t *exp_buffer;
137
    uint8_t *grouped_exp_buffer;
138
    int16_t *psd_buffer;
139
    int16_t *band_psd_buffer;
140
    int16_t *mask_buffer;
141
    uint16_t *qmant_buffer;
142

    
143
    DECLARE_ALIGNED(16, int16_t, windowed_samples)[AC3_WINDOW_SIZE];
144
} AC3EncodeContext;
145

    
146

    
147
/** MDCT and FFT tables */
148
static int16_t costab[64];
149
static int16_t sintab[64];
150
static int16_t xcos1[128];
151
static int16_t xsin1[128];
152

    
153
/**
154
 * LUT for number of exponent groups.
155
 * exponent_group_tab[exponent strategy-1][number of coefficients]
156
 */
157
uint8_t exponent_group_tab[3][256];
158

    
159

    
160
/**
161
 * Adjust the frame size to make the average bit rate match the target bit rate.
162
 * This is only needed for 11025, 22050, and 44100 sample rates.
163
 */
164
static void adjust_frame_size(AC3EncodeContext *s)
165
{
166
    while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
167
        s->bits_written    -= s->bit_rate;
168
        s->samples_written -= s->sample_rate;
169
    }
170
    s->frame_size = s->frame_size_min +
171
                    2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
172
    s->bits_written    += s->frame_size * 8;
173
    s->samples_written += AC3_FRAME_SIZE;
174
}
175

    
176

    
177
/**
178
 * Deinterleave input samples.
179
 * Channels are reordered from FFmpeg's default order to AC-3 order.
180
 */
181
static void deinterleave_input_samples(AC3EncodeContext *s,
182
                                       const int16_t *samples)
183
{
184
    int ch, i;
185

    
186
    /* deinterleave and remap input samples */
187
    for (ch = 0; ch < s->channels; ch++) {
188
        const int16_t *sptr;
189
        int sinc;
190

    
191
        /* copy last 256 samples of previous frame to the start of the current frame */
192
        memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
193
               AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
194

    
195
        /* deinterleave */
196
        sinc = s->channels;
197
        sptr = samples + s->channel_map[ch];
198
        for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
199
            s->planar_samples[ch][i] = *sptr;
200
            sptr += sinc;
201
        }
202
    }
203
}
204

    
205

    
206
/**
207
 * Finalize MDCT and free allocated memory.
208
 */
209
static av_cold void mdct_end(AC3MDCTContext *mdct)
210
{
211
    av_freep(&mdct->rot_tmp);
212
    av_freep(&mdct->cplx_tmp);
213
}
214

    
215

    
216

    
217
/**
218
 * Initialize FFT tables.
219
 * @param ln log2(FFT size)
220
 */
221
static av_cold void fft_init(int ln)
222
{
223
    int i, n, n2;
224
    float alpha;
225

    
226
    n  = 1 << ln;
227
    n2 = n >> 1;
228

    
229
    for (i = 0; i < n2; i++) {
230
        alpha     = 2.0 * M_PI * i / n;
231
        costab[i] = FIX15(cos(alpha));
232
        sintab[i] = FIX15(sin(alpha));
233
    }
234
}
235

    
236

    
237
/**
238
 * Initialize MDCT tables.
239
 * @param nbits log2(MDCT size)
240
 */
241
static av_cold int mdct_init(AC3MDCTContext *mdct, int nbits)
242
{
243
    int i, n, n4;
244

    
245
    n  = 1 << nbits;
246
    n4 = n >> 2;
247

    
248
    fft_init(nbits - 2);
249

    
250
    FF_ALLOC_OR_GOTO(mdct->avctx, mdct->rot_tmp,  n  * sizeof(*mdct->rot_tmp),
251
                     mdct_alloc_fail);
252
    FF_ALLOC_OR_GOTO(mdct->avctx, mdct->cplx_tmp, n4 * sizeof(*mdct->cplx_tmp),
253
                     mdct_alloc_fail);
254

    
255
    for (i = 0; i < n4; i++) {
256
        float alpha = 2.0 * M_PI * (i + 1.0 / 8.0) / n;
257
        xcos1[i] = FIX15(-cos(alpha));
258
        xsin1[i] = FIX15(-sin(alpha));
259
    }
260

    
261
    return 0;
262
mdct_alloc_fail:
263
    return AVERROR(ENOMEM);
264
}
265

    
266

    
267
/** Butterfly op */
268
#define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1)  \
269
{                                                       \
270
  int ax, ay, bx, by;                                   \
271
  bx  = pre1;                                           \
272
  by  = pim1;                                           \
273
  ax  = qre1;                                           \
274
  ay  = qim1;                                           \
275
  pre = (bx + ax) >> 1;                                 \
276
  pim = (by + ay) >> 1;                                 \
277
  qre = (bx - ax) >> 1;                                 \
278
  qim = (by - ay) >> 1;                                 \
279
}
280

    
281

    
282
/** Complex multiply */
283
#define CMUL(pre, pim, are, aim, bre, bim)              \
284
{                                                       \
285
   pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;     \
286
   pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;     \
287
}
288

    
289

    
290
/**
291
 * Calculate a 2^n point complex FFT on 2^ln points.
292
 * @param z  complex input/output samples
293
 * @param ln log2(FFT size)
294
 */
295
static void fft(IComplex *z, int ln)
296
{
297
    int j, l, np, np2;
298
    int nblocks, nloops;
299
    register IComplex *p,*q;
300
    int tmp_re, tmp_im;
301

    
302
    np = 1 << ln;
303

    
304
    /* reverse */
305
    for (j = 0; j < np; j++) {
306
        int k = av_reverse[j] >> (8 - ln);
307
        if (k < j)
308
            FFSWAP(IComplex, z[k], z[j]);
309
    }
310

    
311
    /* pass 0 */
312

    
313
    p = &z[0];
314
    j = np >> 1;
315
    do {
316
        BF(p[0].re, p[0].im, p[1].re, p[1].im,
317
           p[0].re, p[0].im, p[1].re, p[1].im);
318
        p += 2;
319
    } while (--j);
320

    
321
    /* pass 1 */
322

    
323
    p = &z[0];
324
    j = np >> 2;
325
    do {
326
        BF(p[0].re, p[0].im, p[2].re,  p[2].im,
327
           p[0].re, p[0].im, p[2].re,  p[2].im);
328
        BF(p[1].re, p[1].im, p[3].re,  p[3].im,
329
           p[1].re, p[1].im, p[3].im, -p[3].re);
330
        p+=4;
331
    } while (--j);
332

    
333
    /* pass 2 .. ln-1 */
334

    
335
    nblocks = np >> 3;
336
    nloops  =  1 << 2;
337
    np2     = np >> 1;
338
    do {
339
        p = z;
340
        q = z + nloops;
341
        for (j = 0; j < nblocks; j++) {
342
            BF(p->re, p->im, q->re, q->im,
343
               p->re, p->im, q->re, q->im);
344
            p++;
345
            q++;
346
            for(l = nblocks; l < np2; l += nblocks) {
347
                CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
348
                BF(p->re, p->im, q->re,  q->im,
349
                   p->re, p->im, tmp_re, tmp_im);
350
                p++;
351
                q++;
352
            }
353
            p += nloops;
354
            q += nloops;
355
        }
356
        nblocks = nblocks >> 1;
357
        nloops  = nloops  << 1;
358
    } while (nblocks);
359
}
360

    
361

    
362
/**
363
 * Calculate a 512-point MDCT
364
 * @param out 256 output frequency coefficients
365
 * @param in  512 windowed input audio samples
366
 */
367
static void mdct512(AC3MDCTContext *mdct, int32_t *out, int16_t *in)
368
{
369
    int i, re, im;
370
    int16_t *rot = mdct->rot_tmp;
371
    IComplex *x  = mdct->cplx_tmp;
372

    
373
    /* shift to simplify computations */
374
    for (i = 0; i < MDCT_SAMPLES/4; i++)
375
        rot[i] = -in[i + 3*MDCT_SAMPLES/4];
376
    memcpy(&rot[MDCT_SAMPLES/4], &in[0], 3*MDCT_SAMPLES/4*sizeof(*in));
377

    
378
    /* pre rotation */
379
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
380
        re =  ((int)rot[               2*i] - (int)rot[MDCT_SAMPLES  -1-2*i]) >> 1;
381
        im = -((int)rot[MDCT_SAMPLES/2+2*i] - (int)rot[MDCT_SAMPLES/2-1-2*i]) >> 1;
382
        CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
383
    }
384

    
385
    fft(x, MDCT_NBITS - 2);
386

    
387
    /* post rotation */
388
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
389
        re = x[i].re;
390
        im = x[i].im;
391
        CMUL(out[MDCT_SAMPLES/2-1-2*i], out[2*i], re, im, xsin1[i], xcos1[i]);
392
    }
393
}
394

    
395

    
396
/**
397
 * Apply KBD window to input samples prior to MDCT.
398
 */
399
static void apply_window(int16_t *output, const int16_t *input,
400
                         const int16_t *window, int n)
401
{
402
    int i;
403
    int n2 = n >> 1;
404

    
405
    for (i = 0; i < n2; i++) {
406
        output[i]     = MUL16(input[i],     window[i]) >> 15;
407
        output[n-i-1] = MUL16(input[n-i-1], window[i]) >> 15;
408
    }
409
}
410

    
411

    
412
/**
413
 * Calculate the log2() of the maximum absolute value in an array.
414
 * @param tab input array
415
 * @param n   number of values in the array
416
 * @return    log2(max(abs(tab[])))
417
 */
418
static int log2_tab(int16_t *tab, int n)
419
{
420
    int i, v;
421

    
422
    v = 0;
423
    for (i = 0; i < n; i++)
424
        v |= abs(tab[i]);
425

    
426
    return av_log2(v);
427
}
428

    
429

    
430
/**
431
 * Left-shift each value in an array by a specified amount.
432
 * @param tab    input array
433
 * @param n      number of values in the array
434
 * @param lshift left shift amount. a negative value means right shift.
435
 */
436
static void lshift_tab(int16_t *tab, int n, int lshift)
437
{
438
    int i;
439

    
440
    if (lshift > 0) {
441
        for (i = 0; i < n; i++)
442
            tab[i] <<= lshift;
443
    } else if (lshift < 0) {
444
        lshift = -lshift;
445
        for (i = 0; i < n; i++)
446
            tab[i] >>= lshift;
447
    }
448
}
449

    
450

    
451
/**
452
 * Normalize the input samples to use the maximum available precision.
453
 * This assumes signed 16-bit input samples. Exponents are reduced by 9 to
454
 * match the 24-bit internal precision for MDCT coefficients.
455
 *
456
 * @return exponent shift
457
 */
458
static int normalize_samples(AC3EncodeContext *s)
459
{
460
    int v = 14 - log2_tab(s->windowed_samples, AC3_WINDOW_SIZE);
461
    v = FFMAX(0, v);
462
    lshift_tab(s->windowed_samples, AC3_WINDOW_SIZE, v);
463
    return v - 9;
464
}
465

    
466

    
467
/**
468
 * Apply the MDCT to input samples to generate frequency coefficients.
469
 * This applies the KBD window and normalizes the input to reduce precision
470
 * loss due to fixed-point calculations.
471
 */
472
static void apply_mdct(AC3EncodeContext *s)
473
{
474
    int blk, ch;
475

    
476
    for (ch = 0; ch < s->channels; ch++) {
477
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
478
            AC3Block *block = &s->blocks[blk];
479
            const int16_t *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
480

    
481
            apply_window(s->windowed_samples, input_samples, ff_ac3_window, AC3_WINDOW_SIZE);
482

    
483
            block->exp_shift[ch] = normalize_samples(s);
484

    
485
            mdct512(&s->mdct, block->mdct_coef[ch], s->windowed_samples);
486
        }
487
    }
488
}
489

    
490

    
491
/**
492
 * Initialize exponent tables.
493
 */
494
static av_cold void exponent_init(AC3EncodeContext *s)
495
{
496
    int i;
497
    for (i = 73; i < 256; i++) {
498
        exponent_group_tab[0][i] = (i - 1) /  3;
499
        exponent_group_tab[1][i] = (i + 2) /  6;
500
        exponent_group_tab[2][i] = (i + 8) / 12;
501
    }
502
}
503

    
504

    
505
/**
506
 * Extract exponents from the MDCT coefficients.
507
 * This takes into account the normalization that was done to the input samples
508
 * by adjusting the exponents by the exponent shift values.
509
 */
510
static void extract_exponents(AC3EncodeContext *s)
511
{
512
    int blk, ch, i;
513

    
514
    for (ch = 0; ch < s->channels; ch++) {
515
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
516
            AC3Block *block = &s->blocks[blk];
517
            for (i = 0; i < AC3_MAX_COEFS; i++) {
518
                int e;
519
                int v = abs(block->mdct_coef[ch][i]);
520
                if (v == 0)
521
                    e = 24;
522
                else {
523
                    e = 23 - av_log2(v) + block->exp_shift[ch];
524
                    if (e >= 24) {
525
                        e = 24;
526
                        block->mdct_coef[ch][i] = 0;
527
                    }
528
                }
529
                block->exp[ch][i] = e;
530
            }
531
        }
532
    }
533
}
534

    
535

    
536
/**
537
 * Exponent Difference Threshold.
538
 * New exponents are sent if their SAD exceed this number.
539
 */
540
#define EXP_DIFF_THRESHOLD 1000
541

    
542

    
543
/**
544
 * Calculate exponent strategies for all blocks in a single channel.
545
 */
546
static void compute_exp_strategy_ch(AC3EncodeContext *s, uint8_t *exp_strategy, uint8_t **exp)
547
{
548
    int blk, blk1;
549
    int exp_diff;
550

    
551
    /* estimate if the exponent variation & decide if they should be
552
       reused in the next frame */
553
    exp_strategy[0] = EXP_NEW;
554
    for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
555
        exp_diff = s->dsp.sad[0](NULL, exp[blk], exp[blk-1], 16, 16);
556
        if (exp_diff > EXP_DIFF_THRESHOLD)
557
            exp_strategy[blk] = EXP_NEW;
558
        else
559
            exp_strategy[blk] = EXP_REUSE;
560
    }
561

    
562
    /* now select the encoding strategy type : if exponents are often
563
       recoded, we use a coarse encoding */
564
    blk = 0;
565
    while (blk < AC3_MAX_BLOCKS) {
566
        blk1 = blk + 1;
567
        while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
568
            blk1++;
569
        switch (blk1 - blk) {
570
        case 1:  exp_strategy[blk] = EXP_D45; break;
571
        case 2:
572
        case 3:  exp_strategy[blk] = EXP_D25; break;
573
        default: exp_strategy[blk] = EXP_D15; break;
574
        }
575
        blk = blk1;
576
    }
577
}
578

    
579

    
580
/**
581
 * Calculate exponent strategies for all channels.
582
 * Array arrangement is reversed to simplify the per-channel calculation.
583
 */
584
static void compute_exp_strategy(AC3EncodeContext *s)
585
{
586
    uint8_t *exp1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
587
    uint8_t exp_str1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
588
    int ch, blk;
589

    
590
    for (ch = 0; ch < s->fbw_channels; ch++) {
591
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
592
            exp1[ch][blk]     = s->blocks[blk].exp[ch];
593
            exp_str1[ch][blk] = s->blocks[blk].exp_strategy[ch];
594
        }
595

    
596
        compute_exp_strategy_ch(s, exp_str1[ch], exp1[ch]);
597

    
598
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
599
            s->blocks[blk].exp_strategy[ch] = exp_str1[ch][blk];
600
    }
601
    if (s->lfe_on) {
602
        ch = s->lfe_channel;
603
        s->blocks[0].exp_strategy[ch] = EXP_D15;
604
        for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
605
            s->blocks[blk].exp_strategy[ch] = EXP_REUSE;
606
    }
607
}
608

    
609

    
610
/**
611
 * Set each encoded exponent in a block to the minimum of itself and the
612
 * exponent in the same frequency bin of a following block.
613
 * exp[i] = min(exp[i], exp1[i]
614
 */
615
static void exponent_min(uint8_t *exp, uint8_t *exp1, int n)
616
{
617
    int i;
618
    for (i = 0; i < n; i++) {
619
        if (exp1[i] < exp[i])
620
            exp[i] = exp1[i];
621
    }
622
}
623

    
624

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

    
633
    nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
634

    
635
    /* for each group, compute the minimum exponent */
636
    switch(exp_strategy) {
637
    case EXP_D25:
638
        for (i = 1, k = 1; i <= nb_groups; i++) {
639
            uint8_t exp_min = exp[k];
640
            if (exp[k+1] < exp_min)
641
                exp_min = exp[k+1];
642
            exp[i] = exp_min;
643
            k += 2;
644
        }
645
        break;
646
    case EXP_D45:
647
        for (i = 1, k = 1; i <= nb_groups; i++) {
648
            uint8_t exp_min = exp[k];
649
            if (exp[k+1] < exp_min)
650
                exp_min = exp[k+1];
651
            if (exp[k+2] < exp_min)
652
                exp_min = exp[k+2];
653
            if (exp[k+3] < exp_min)
654
                exp_min = exp[k+3];
655
            exp[i] = exp_min;
656
            k += 4;
657
        }
658
        break;
659
    }
660

    
661
    /* constraint for DC exponent */
662
    if (exp[0] > 15)
663
        exp[0] = 15;
664

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

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

    
691

    
692
/**
693
 * Encode exponents from original extracted form to what the decoder will see.
694
 * This copies and groups exponents based on exponent strategy and reduces
695
 * deltas between adjacent exponent groups so that they can be differentially
696
 * encoded.
697
 */
698
static void encode_exponents(AC3EncodeContext *s)
699
{
700
    int blk, blk1, blk2, ch;
701
    AC3Block *block, *block1, *block2;
702

    
703
    for (ch = 0; ch < s->channels; ch++) {
704
        blk = 0;
705
        block = &s->blocks[0];
706
        while (blk < AC3_MAX_BLOCKS) {
707
            blk1 = blk + 1;
708
            block1 = block + 1;
709
            /* for the EXP_REUSE case we select the min of the exponents */
710
            while (blk1 < AC3_MAX_BLOCKS && block1->exp_strategy[ch] == EXP_REUSE) {
711
                exponent_min(block->exp[ch], block1->exp[ch], s->nb_coefs[ch]);
712
                blk1++;
713
                block1++;
714
            }
715
            encode_exponents_blk_ch(block->exp[ch], s->nb_coefs[ch],
716
                                    block->exp_strategy[ch]);
717
            /* copy encoded exponents for reuse case */
718
            block2 = block + 1;
719
            for (blk2 = blk+1; blk2 < blk1; blk2++, block2++) {
720
                memcpy(block2->exp[ch], block->exp[ch],
721
                       s->nb_coefs[ch] * sizeof(uint8_t));
722
            }
723
            blk = blk1;
724
            block = block1;
725
        }
726
    }
727
}
728

    
729

    
730
/**
731
 * Group exponents.
732
 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
733
 * varies depending on exponent strategy and bandwidth.
734
 */
735
static void group_exponents(AC3EncodeContext *s)
736
{
737
    int blk, ch, i;
738
    int group_size, nb_groups, bit_count;
739
    uint8_t *p;
740
    int delta0, delta1, delta2;
741
    int exp0, exp1;
742

    
743
    bit_count = 0;
744
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
745
        AC3Block *block = &s->blocks[blk];
746
        for (ch = 0; ch < s->channels; ch++) {
747
            if (block->exp_strategy[ch] == EXP_REUSE) {
748
                continue;
749
            }
750
            group_size = block->exp_strategy[ch] + (block->exp_strategy[ch] == EXP_D45);
751
            nb_groups = exponent_group_tab[block->exp_strategy[ch]-1][s->nb_coefs[ch]];
752
            bit_count += 4 + (nb_groups * 7);
753
            p = block->exp[ch];
754

    
755
            /* DC exponent */
756
            exp1 = *p++;
757
            block->grouped_exp[ch][0] = exp1;
758

    
759
            /* remaining exponents are delta encoded */
760
            for (i = 1; i <= nb_groups; i++) {
761
                /* merge three delta in one code */
762
                exp0   = exp1;
763
                exp1   = p[0];
764
                p     += group_size;
765
                delta0 = exp1 - exp0 + 2;
766

    
767
                exp0   = exp1;
768
                exp1   = p[0];
769
                p     += group_size;
770
                delta1 = exp1 - exp0 + 2;
771

    
772
                exp0   = exp1;
773
                exp1   = p[0];
774
                p     += group_size;
775
                delta2 = exp1 - exp0 + 2;
776

    
777
                block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
778
            }
779
        }
780
    }
781

    
782
    s->exponent_bits = bit_count;
783
}
784

    
785

    
786
/**
787
 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
788
 * Extract exponents from MDCT coefficients, calculate exponent strategies,
789
 * and encode final exponents.
790
 */
791
static void process_exponents(AC3EncodeContext *s)
792
{
793
    extract_exponents(s);
794

    
795
    compute_exp_strategy(s);
796

    
797
    encode_exponents(s);
798

    
799
    group_exponents(s);
800
}
801

    
802

    
803
/**
804
 * Initialize bit allocation.
805
 * Set default parameter codes and calculate parameter values.
806
 */
807
static void bit_alloc_init(AC3EncodeContext *s)
808
{
809
    int ch;
810

    
811
    /* init default parameters */
812
    s->slow_decay_code = 2;
813
    s->fast_decay_code = 1;
814
    s->slow_gain_code  = 1;
815
    s->db_per_bit_code = 2;
816
    s->floor_code      = 4;
817
    for (ch = 0; ch < s->channels; ch++)
818
        s->fast_gain_code[ch] = 4;
819

    
820
    /* initial snr offset */
821
    s->coarse_snr_offset = 40;
822

    
823
    /* compute real values */
824
    /* currently none of these values change during encoding, so we can just
825
       set them once at initialization */
826
    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
827
    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
828
    s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
829
    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
830
    s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
831
}
832

    
833

    
834
/**
835
 * Count the bits used to encode the frame, minus exponents and mantissas.
836
 */
837
static void count_frame_bits(AC3EncodeContext *s)
838
{
839
    static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
840
    int blk, ch;
841
    int frame_bits;
842

    
843
    /* header size */
844
    frame_bits = 65;
845
    frame_bits += frame_bits_inc[s->channel_mode];
846

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

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

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

    
879
    s->frame_bits = frame_bits;
880
}
881

    
882

    
883
/**
884
 * Calculate the number of bits needed to encode a set of mantissas.
885
 */
886
static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *bap, int nb_coefs)
887
{
888
    int bits, b, i;
889

    
890
    bits = 0;
891
    for (i = 0; i < nb_coefs; i++) {
892
        b = bap[i];
893
        switch (b) {
894
        case 0:
895
            /* bap=0 mantissas are not encoded */
896
            break;
897
        case 1:
898
            /* 3 mantissas in 5 bits */
899
            if (s->mant1_cnt == 0)
900
                bits += 5;
901
            if (++s->mant1_cnt == 3)
902
                s->mant1_cnt = 0;
903
            break;
904
        case 2:
905
            /* 3 mantissas in 7 bits */
906
            if (s->mant2_cnt == 0)
907
                bits += 7;
908
            if (++s->mant2_cnt == 3)
909
                s->mant2_cnt = 0;
910
            break;
911
        case 3:
912
            bits += 3;
913
            break;
914
        case 4:
915
            /* 2 mantissas in 7 bits */
916
            if (s->mant4_cnt == 0)
917
                bits += 7;
918
            if (++s->mant4_cnt == 2)
919
                s->mant4_cnt = 0;
920
            break;
921
        case 14:
922
            bits += 14;
923
            break;
924
        case 15:
925
            bits += 16;
926
            break;
927
        default:
928
            bits += b - 1;
929
            break;
930
        }
931
    }
932
    return bits;
933
}
934

    
935

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

    
944
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
945
        AC3Block *block = &s->blocks[blk];
946
        for (ch = 0; ch < s->channels; ch++) {
947
            if (block->exp_strategy[ch] == EXP_REUSE) {
948
                AC3Block *block1 = &s->blocks[blk-1];
949
                memcpy(block->psd[ch],  block1->psd[ch],  AC3_MAX_COEFS*sizeof(block->psd[0][0]));
950
                memcpy(block->mask[ch], block1->mask[ch], AC3_CRITICAL_BANDS*sizeof(block->mask[0][0]));
951
            } else {
952
                ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
953
                                          s->nb_coefs[ch],
954
                                          block->psd[ch], block->band_psd[ch]);
955
                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
956
                                           0, s->nb_coefs[ch],
957
                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
958
                                           ch == s->lfe_channel,
959
                                           DBA_NONE, 0, NULL, NULL, NULL,
960
                                           block->mask[ch]);
961
            }
962
        }
963
    }
964
}
965

    
966

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

    
983

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

    
997
    snr_offset = (snr_offset - 240) << 2;
998

    
999
    reset_block_bap(s);
1000
    mantissa_bits = 0;
1001
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1002
        AC3Block *block = &s->blocks[blk];
1003
        s->mant1_cnt = 0;
1004
        s->mant2_cnt = 0;
1005
        s->mant4_cnt = 0;
1006
        for (ch = 0; ch < s->channels; ch++) {
1007
            ff_ac3_bit_alloc_calc_bap(block->mask[ch], block->psd[ch], 0,
1008
                                      s->nb_coefs[ch], snr_offset,
1009
                                      s->bit_alloc.floor, ff_ac3_bap_tab,
1010
                                      block->bap[ch]);
1011
            mantissa_bits += compute_mantissa_size(s, block->bap[ch], s->nb_coefs[ch]);
1012
        }
1013
    }
1014
    return mantissa_bits;
1015
}
1016

    
1017

    
1018
/**
1019
 * Constant bitrate bit allocation search.
1020
 * Find the largest SNR offset that will allow data to fit in the frame.
1021
 */
1022
static int cbr_bit_allocation(AC3EncodeContext *s)
1023
{
1024
    int ch;
1025
    int bits_left;
1026
    int snr_offset;
1027

    
1028
    bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1029

    
1030
    snr_offset = s->coarse_snr_offset << 4;
1031

    
1032
    while (snr_offset >= 0 &&
1033
           bit_alloc(s, snr_offset) > bits_left) {
1034
        snr_offset -= 64;
1035
    }
1036
    if (snr_offset < 0)
1037
        return AVERROR(EINVAL);
1038

    
1039
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1040
    while (snr_offset + 64 <= 1023 &&
1041
           bit_alloc(s, snr_offset + 64) <= bits_left) {
1042
        snr_offset += 64;
1043
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1044
    }
1045
    while (snr_offset + 16 <= 1023 &&
1046
           bit_alloc(s, snr_offset + 16) <= bits_left) {
1047
        snr_offset += 16;
1048
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1049
    }
1050
    while (snr_offset + 4 <= 1023 &&
1051
           bit_alloc(s, snr_offset + 4) <= bits_left) {
1052
        snr_offset += 4;
1053
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1054
    }
1055
    while (snr_offset + 1 <= 1023 &&
1056
           bit_alloc(s, snr_offset + 1) <= bits_left) {
1057
        snr_offset++;
1058
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1059
    }
1060
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1061
    reset_block_bap(s);
1062

    
1063
    s->coarse_snr_offset = snr_offset >> 4;
1064
    for (ch = 0; ch < s->channels; ch++)
1065
        s->fine_snr_offset[ch] = snr_offset & 0xF;
1066

    
1067
    return 0;
1068
}
1069

    
1070

    
1071
/**
1072
 * Perform bit allocation search.
1073
 * Finds the SNR offset value that maximizes quality and fits in the specified
1074
 * frame size.  Output is the SNR offset and a set of bit allocation pointers
1075
 * used to quantize the mantissas.
1076
 */
1077
static int compute_bit_allocation(AC3EncodeContext *s)
1078
{
1079
    count_frame_bits(s);
1080

    
1081
    bit_alloc_masking(s);
1082

    
1083
    return cbr_bit_allocation(s);
1084
}
1085

    
1086

    
1087
/**
1088
 * Symmetric quantization on 'levels' levels.
1089
 */
1090
static inline int sym_quant(int c, int e, int levels)
1091
{
1092
    int v;
1093

    
1094
    if (c >= 0) {
1095
        v = (levels * (c << e)) >> 24;
1096
        v = (v + 1) >> 1;
1097
        v = (levels >> 1) + v;
1098
    } else {
1099
        v = (levels * ((-c) << e)) >> 24;
1100
        v = (v + 1) >> 1;
1101
        v = (levels >> 1) - v;
1102
    }
1103
    assert(v >= 0 && v < levels);
1104
    return v;
1105
}
1106

    
1107

    
1108
/**
1109
 * Asymmetric quantization on 2^qbits levels.
1110
 */
1111
static inline int asym_quant(int c, int e, int qbits)
1112
{
1113
    int lshift, m, v;
1114

    
1115
    lshift = e + qbits - 24;
1116
    if (lshift >= 0)
1117
        v = c << lshift;
1118
    else
1119
        v = c >> (-lshift);
1120
    /* rounding */
1121
    v = (v + 1) >> 1;
1122
    m = (1 << (qbits-1));
1123
    if (v >= m)
1124
        v = m - 1;
1125
    assert(v >= -m);
1126
    return v & ((1 << qbits)-1);
1127
}
1128

    
1129

    
1130
/**
1131
 * Quantize a set of mantissas for a single channel in a single block.
1132
 */
1133
static void quantize_mantissas_blk_ch(AC3EncodeContext *s,
1134
                                      int32_t *mdct_coef, int8_t exp_shift,
1135
                                      uint8_t *exp, uint8_t *bap,
1136
                                      uint16_t *qmant, int n)
1137
{
1138
    int i;
1139

    
1140
    for (i = 0; i < n; i++) {
1141
        int v;
1142
        int c = mdct_coef[i];
1143
        int e = exp[i] - exp_shift;
1144
        int b = bap[i];
1145
        switch (b) {
1146
        case 0:
1147
            v = 0;
1148
            break;
1149
        case 1:
1150
            v = sym_quant(c, e, 3);
1151
            switch (s->mant1_cnt) {
1152
            case 0:
1153
                s->qmant1_ptr = &qmant[i];
1154
                v = 9 * v;
1155
                s->mant1_cnt = 1;
1156
                break;
1157
            case 1:
1158
                *s->qmant1_ptr += 3 * v;
1159
                s->mant1_cnt = 2;
1160
                v = 128;
1161
                break;
1162
            default:
1163
                *s->qmant1_ptr += v;
1164
                s->mant1_cnt = 0;
1165
                v = 128;
1166
                break;
1167
            }
1168
            break;
1169
        case 2:
1170
            v = sym_quant(c, e, 5);
1171
            switch (s->mant2_cnt) {
1172
            case 0:
1173
                s->qmant2_ptr = &qmant[i];
1174
                v = 25 * v;
1175
                s->mant2_cnt = 1;
1176
                break;
1177
            case 1:
1178
                *s->qmant2_ptr += 5 * v;
1179
                s->mant2_cnt = 2;
1180
                v = 128;
1181
                break;
1182
            default:
1183
                *s->qmant2_ptr += v;
1184
                s->mant2_cnt = 0;
1185
                v = 128;
1186
                break;
1187
            }
1188
            break;
1189
        case 3:
1190
            v = sym_quant(c, e, 7);
1191
            break;
1192
        case 4:
1193
            v = sym_quant(c, e, 11);
1194
            switch (s->mant4_cnt) {
1195
            case 0:
1196
                s->qmant4_ptr = &qmant[i];
1197
                v = 11 * v;
1198
                s->mant4_cnt = 1;
1199
                break;
1200
            default:
1201
                *s->qmant4_ptr += v;
1202
                s->mant4_cnt = 0;
1203
                v = 128;
1204
                break;
1205
            }
1206
            break;
1207
        case 5:
1208
            v = sym_quant(c, e, 15);
1209
            break;
1210
        case 14:
1211
            v = asym_quant(c, e, 14);
1212
            break;
1213
        case 15:
1214
            v = asym_quant(c, e, 16);
1215
            break;
1216
        default:
1217
            v = asym_quant(c, e, b - 1);
1218
            break;
1219
        }
1220
        qmant[i] = v;
1221
    }
1222
}
1223

    
1224

    
1225
/**
1226
 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1227
 */
1228
static void quantize_mantissas(AC3EncodeContext *s)
1229
{
1230
    int blk, ch;
1231

    
1232

    
1233
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1234
        AC3Block *block = &s->blocks[blk];
1235
        s->mant1_cnt  = s->mant2_cnt  = s->mant4_cnt  = 0;
1236
        s->qmant1_ptr = s->qmant2_ptr = s->qmant4_ptr = NULL;
1237

    
1238
        for (ch = 0; ch < s->channels; ch++) {
1239
            quantize_mantissas_blk_ch(s, block->mdct_coef[ch], block->exp_shift[ch],
1240
                                      block->exp[ch], block->bap[ch],
1241
                                      block->qmant[ch], s->nb_coefs[ch]);
1242
        }
1243
    }
1244
}
1245

    
1246

    
1247
/**
1248
 * Write the AC-3 frame header to the output bitstream.
1249
 */
1250
static void output_frame_header(AC3EncodeContext *s)
1251
{
1252
    put_bits(&s->pb, 16, 0x0b77);   /* frame header */
1253
    put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
1254
    put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
1255
    put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1256
    put_bits(&s->pb, 5,  s->bitstream_id);
1257
    put_bits(&s->pb, 3,  s->bitstream_mode);
1258
    put_bits(&s->pb, 3,  s->channel_mode);
1259
    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1260
        put_bits(&s->pb, 2, 1);     /* XXX -4.5 dB */
1261
    if (s->channel_mode & 0x04)
1262
        put_bits(&s->pb, 2, 1);     /* XXX -6 dB */
1263
    if (s->channel_mode == AC3_CHMODE_STEREO)
1264
        put_bits(&s->pb, 2, 0);     /* surround not indicated */
1265
    put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1266
    put_bits(&s->pb, 5, 31);        /* dialog norm: -31 db */
1267
    put_bits(&s->pb, 1, 0);         /* no compression control word */
1268
    put_bits(&s->pb, 1, 0);         /* no lang code */
1269
    put_bits(&s->pb, 1, 0);         /* no audio production info */
1270
    put_bits(&s->pb, 1, 0);         /* no copyright */
1271
    put_bits(&s->pb, 1, 1);         /* original bitstream */
1272
    put_bits(&s->pb, 1, 0);         /* no time code 1 */
1273
    put_bits(&s->pb, 1, 0);         /* no time code 2 */
1274
    put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
1275
}
1276

    
1277

    
1278
/**
1279
 * Write one audio block to the output bitstream.
1280
 */
1281
static void output_audio_block(AC3EncodeContext *s,
1282
                               int block_num)
1283
{
1284
    int ch, i, baie, rbnd;
1285
    AC3Block *block = &s->blocks[block_num];
1286

    
1287
    /* block switching */
1288
    for (ch = 0; ch < s->fbw_channels; ch++)
1289
        put_bits(&s->pb, 1, 0);
1290

    
1291
    /* dither flags */
1292
    for (ch = 0; ch < s->fbw_channels; ch++)
1293
        put_bits(&s->pb, 1, 1);
1294

    
1295
    /* dynamic range codes */
1296
    put_bits(&s->pb, 1, 0);
1297

    
1298
    /* channel coupling */
1299
    if (!block_num) {
1300
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
1301
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
1302
    } else {
1303
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1304
    }
1305

    
1306
    /* stereo rematrixing */
1307
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1308
        if (!block_num) {
1309
            /* first block must define rematrixing (rematstr) */
1310
            put_bits(&s->pb, 1, 1);
1311

    
1312
            /* dummy rematrixing rematflg(1:4)=0 */
1313
            for (rbnd = 0; rbnd < 4; rbnd++)
1314
                put_bits(&s->pb, 1, 0);
1315
        } else {
1316
            /* no matrixing (but should be used in the future) */
1317
            put_bits(&s->pb, 1, 0);
1318
        }
1319
    }
1320

    
1321
    /* exponent strategy */
1322
    for (ch = 0; ch < s->fbw_channels; ch++)
1323
        put_bits(&s->pb, 2, block->exp_strategy[ch]);
1324
    if (s->lfe_on)
1325
        put_bits(&s->pb, 1, block->exp_strategy[s->lfe_channel]);
1326

    
1327
    /* bandwidth */
1328
    for (ch = 0; ch < s->fbw_channels; ch++) {
1329
        if (block->exp_strategy[ch] != EXP_REUSE)
1330
            put_bits(&s->pb, 6, s->bandwidth_code[ch]);
1331
    }
1332

    
1333
    /* exponents */
1334
    for (ch = 0; ch < s->channels; ch++) {
1335
        int nb_groups;
1336

    
1337
        if (block->exp_strategy[ch] == EXP_REUSE)
1338
            continue;
1339

    
1340
        /* DC exponent */
1341
        put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1342

    
1343
        /* exponent groups */
1344
        nb_groups = exponent_group_tab[block->exp_strategy[ch]-1][s->nb_coefs[ch]];
1345
        for (i = 1; i <= nb_groups; i++)
1346
            put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1347

    
1348
        /* gain range info */
1349
        if (ch != s->lfe_channel)
1350
            put_bits(&s->pb, 2, 0);
1351
    }
1352

    
1353
    /* bit allocation info */
1354
    baie = (block_num == 0);
1355
    put_bits(&s->pb, 1, baie);
1356
    if (baie) {
1357
        put_bits(&s->pb, 2, s->slow_decay_code);
1358
        put_bits(&s->pb, 2, s->fast_decay_code);
1359
        put_bits(&s->pb, 2, s->slow_gain_code);
1360
        put_bits(&s->pb, 2, s->db_per_bit_code);
1361
        put_bits(&s->pb, 3, s->floor_code);
1362
    }
1363

    
1364
    /* snr offset */
1365
    put_bits(&s->pb, 1, baie);
1366
    if (baie) {
1367
        put_bits(&s->pb, 6, s->coarse_snr_offset);
1368
        for (ch = 0; ch < s->channels; ch++) {
1369
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1370
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1371
        }
1372
    }
1373

    
1374
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1375
    put_bits(&s->pb, 1, 0); /* no data to skip */
1376

    
1377
    /* mantissas */
1378
    for (ch = 0; ch < s->channels; ch++) {
1379
        int b, q;
1380
        for (i = 0; i < s->nb_coefs[ch]; i++) {
1381
            q = block->qmant[ch][i];
1382
            b = block->bap[ch][i];
1383
            switch (b) {
1384
            case 0:                                         break;
1385
            case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
1386
            case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
1387
            case 3:               put_bits(&s->pb,   3, q); break;
1388
            case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
1389
            case 14:              put_bits(&s->pb,  14, q); break;
1390
            case 15:              put_bits(&s->pb,  16, q); break;
1391
            default:              put_bits(&s->pb, b-1, q); break;
1392
            }
1393
        }
1394
    }
1395
}
1396

    
1397

    
1398
/** CRC-16 Polynomial */
1399
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1400

    
1401

    
1402
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1403
{
1404
    unsigned int c;
1405

    
1406
    c = 0;
1407
    while (a) {
1408
        if (a & 1)
1409
            c ^= b;
1410
        a = a >> 1;
1411
        b = b << 1;
1412
        if (b & (1 << 16))
1413
            b ^= poly;
1414
    }
1415
    return c;
1416
}
1417

    
1418

    
1419
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1420
{
1421
    unsigned int r;
1422
    r = 1;
1423
    while (n) {
1424
        if (n & 1)
1425
            r = mul_poly(r, a, poly);
1426
        a = mul_poly(a, a, poly);
1427
        n >>= 1;
1428
    }
1429
    return r;
1430
}
1431

    
1432

    
1433
/**
1434
 * Fill the end of the frame with 0's and compute the two CRCs.
1435
 */
1436
static void output_frame_end(AC3EncodeContext *s)
1437
{
1438
    int frame_size, frame_size_58, pad_bytes, crc1, crc2, crc_inv;
1439
    uint8_t *frame;
1440

    
1441
    frame_size    = s->frame_size;
1442
    frame_size_58 = ((frame_size >> 2) + (frame_size >> 4)) << 1;
1443

    
1444
    /* pad the remainder of the frame with zeros */
1445
    flush_put_bits(&s->pb);
1446
    frame = s->pb.buf;
1447
    pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1448
    assert(pad_bytes >= 0);
1449
    if (pad_bytes > 0)
1450
        memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1451

    
1452
    /* compute crc1 */
1453
    /* this is not so easy because it is at the beginning of the data... */
1454
    crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1455
                             frame + 4, frame_size_58 - 4));
1456
    /* XXX: could precompute crc_inv */
1457
    crc_inv = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
1458
    crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1459
    AV_WB16(frame + 2, crc1);
1460

    
1461
    /* compute crc2 */
1462
    crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1463
                             frame + frame_size_58,
1464
                             frame_size - frame_size_58 - 2));
1465
    AV_WB16(frame + frame_size - 2, crc2);
1466
}
1467

    
1468

    
1469
/**
1470
 * Write the frame to the output bitstream.
1471
 */
1472
static void output_frame(AC3EncodeContext *s,
1473
                         unsigned char *frame)
1474
{
1475
    int blk;
1476

    
1477
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1478

    
1479
    output_frame_header(s);
1480

    
1481
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1482
        output_audio_block(s, blk);
1483

    
1484
    output_frame_end(s);
1485
}
1486

    
1487

    
1488
/**
1489
 * Encode a single AC-3 frame.
1490
 */
1491
static int ac3_encode_frame(AVCodecContext *avctx,
1492
                            unsigned char *frame, int buf_size, void *data)
1493
{
1494
    AC3EncodeContext *s = avctx->priv_data;
1495
    const int16_t *samples = data;
1496
    int ret;
1497

    
1498
    if (s->bit_alloc.sr_code == 1)
1499
        adjust_frame_size(s);
1500

    
1501
    deinterleave_input_samples(s, samples);
1502

    
1503
    apply_mdct(s);
1504

    
1505
    process_exponents(s);
1506

    
1507
    ret = compute_bit_allocation(s);
1508
    if (ret) {
1509
        av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1510
        return ret;
1511
    }
1512

    
1513
    quantize_mantissas(s);
1514

    
1515
    output_frame(s, frame);
1516

    
1517
    return s->frame_size;
1518
}
1519

    
1520

    
1521
/**
1522
 * Finalize encoding and free any memory allocated by the encoder.
1523
 */
1524
static av_cold int ac3_encode_close(AVCodecContext *avctx)
1525
{
1526
    int blk, ch;
1527
    AC3EncodeContext *s = avctx->priv_data;
1528

    
1529
    for (ch = 0; ch < s->channels; ch++)
1530
        av_freep(&s->planar_samples[ch]);
1531
    av_freep(&s->planar_samples);
1532
    av_freep(&s->bap_buffer);
1533
    av_freep(&s->bap1_buffer);
1534
    av_freep(&s->mdct_coef_buffer);
1535
    av_freep(&s->exp_buffer);
1536
    av_freep(&s->grouped_exp_buffer);
1537
    av_freep(&s->psd_buffer);
1538
    av_freep(&s->band_psd_buffer);
1539
    av_freep(&s->mask_buffer);
1540
    av_freep(&s->qmant_buffer);
1541
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1542
        AC3Block *block = &s->blocks[blk];
1543
        av_freep(&block->bap);
1544
        av_freep(&block->mdct_coef);
1545
        av_freep(&block->exp);
1546
        av_freep(&block->grouped_exp);
1547
        av_freep(&block->psd);
1548
        av_freep(&block->band_psd);
1549
        av_freep(&block->mask);
1550
        av_freep(&block->qmant);
1551
    }
1552

    
1553
    mdct_end(&s->mdct);
1554

    
1555
    av_freep(&avctx->coded_frame);
1556
    return 0;
1557
}
1558

    
1559

    
1560
/**
1561
 * Set channel information during initialization.
1562
 */
1563
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1564
                                    int64_t *channel_layout)
1565
{
1566
    int ch_layout;
1567

    
1568
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
1569
        return AVERROR(EINVAL);
1570
    if ((uint64_t)*channel_layout > 0x7FF)
1571
        return AVERROR(EINVAL);
1572
    ch_layout = *channel_layout;
1573
    if (!ch_layout)
1574
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1575
    if (av_get_channel_layout_nb_channels(ch_layout) != channels)
1576
        return AVERROR(EINVAL);
1577

    
1578
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1579
    s->channels     = channels;
1580
    s->fbw_channels = channels - s->lfe_on;
1581
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
1582
    if (s->lfe_on)
1583
        ch_layout -= AV_CH_LOW_FREQUENCY;
1584

    
1585
    switch (ch_layout) {
1586
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
1587
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
1588
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
1589
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
1590
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
1591
    case AV_CH_LAYOUT_QUAD:
1592
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
1593
    case AV_CH_LAYOUT_5POINT0:
1594
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
1595
    default:
1596
        return AVERROR(EINVAL);
1597
    }
1598

    
1599
    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1600
    *channel_layout = ch_layout;
1601
    if (s->lfe_on)
1602
        *channel_layout |= AV_CH_LOW_FREQUENCY;
1603

    
1604
    return 0;
1605
}
1606

    
1607

    
1608
static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1609
{
1610
    int i, ret;
1611

    
1612
    /* validate channel layout */
1613
    if (!avctx->channel_layout) {
1614
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1615
                                      "encoder will guess the layout, but it "
1616
                                      "might be incorrect.\n");
1617
    }
1618
    ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1619
    if (ret) {
1620
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1621
        return ret;
1622
    }
1623

    
1624
    /* validate sample rate */
1625
    for (i = 0; i < 9; i++) {
1626
        if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
1627
            break;
1628
    }
1629
    if (i == 9) {
1630
        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1631
        return AVERROR(EINVAL);
1632
    }
1633
    s->sample_rate        = avctx->sample_rate;
1634
    s->bit_alloc.sr_shift = i % 3;
1635
    s->bit_alloc.sr_code  = i / 3;
1636

    
1637
    /* validate bit rate */
1638
    for (i = 0; i < 19; i++) {
1639
        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
1640
            break;
1641
    }
1642
    if (i == 19) {
1643
        av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
1644
        return AVERROR(EINVAL);
1645
    }
1646
    s->bit_rate        = avctx->bit_rate;
1647
    s->frame_size_code = i << 1;
1648

    
1649
    return 0;
1650
}
1651

    
1652

    
1653
/**
1654
 * Set bandwidth for all channels.
1655
 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
1656
 * default value will be used.
1657
 */
1658
static av_cold void set_bandwidth(AC3EncodeContext *s, int cutoff)
1659
{
1660
    int ch, bw_code;
1661

    
1662
    if (cutoff) {
1663
        /* calculate bandwidth based on user-specified cutoff frequency */
1664
        int fbw_coeffs;
1665
        cutoff         = av_clip(cutoff, 1, s->sample_rate >> 1);
1666
        fbw_coeffs     = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
1667
        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
1668
    } else {
1669
        /* use default bandwidth setting */
1670
        /* XXX: should compute the bandwidth according to the frame
1671
           size, so that we avoid annoying high frequency artifacts */
1672
        bw_code = 50;
1673
    }
1674

    
1675
    /* set number of coefficients for each channel */
1676
    for (ch = 0; ch < s->fbw_channels; ch++) {
1677
        s->bandwidth_code[ch] = bw_code;
1678
        s->nb_coefs[ch]       = bw_code * 3 + 73;
1679
    }
1680
    if (s->lfe_on)
1681
        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
1682
}
1683

    
1684

    
1685
static av_cold int allocate_buffers(AVCodecContext *avctx)
1686
{
1687
    int blk, ch;
1688
    AC3EncodeContext *s = avctx->priv_data;
1689

    
1690
    FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
1691
                     alloc_fail);
1692
    for (ch = 0; ch < s->channels; ch++) {
1693
        FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
1694
                          (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
1695
                          alloc_fail);
1696
    }
1697
    FF_ALLOC_OR_GOTO(avctx, s->bap_buffer,  AC3_MAX_BLOCKS * s->channels *
1698
                     AC3_MAX_COEFS * sizeof(*s->bap_buffer),  alloc_fail);
1699
    FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
1700
                     AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
1701
    FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
1702
                     AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
1703
    FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
1704
                     AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
1705
    FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
1706
                     128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
1707
    FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
1708
                     AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
1709
    FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
1710
                     64 * sizeof(*s->band_psd_buffer), alloc_fail);
1711
    FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
1712
                     64 * sizeof(*s->mask_buffer), alloc_fail);
1713
    FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
1714
                     AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
1715
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1716
        AC3Block *block = &s->blocks[blk];
1717
        FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
1718
                         alloc_fail);
1719
        FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
1720
                          alloc_fail);
1721
        FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
1722
                          alloc_fail);
1723
        FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
1724
                          alloc_fail);
1725
        FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
1726
                          alloc_fail);
1727
        FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
1728
                          alloc_fail);
1729
        FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
1730
                          alloc_fail);
1731
        FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
1732
                          alloc_fail);
1733

    
1734
        for (ch = 0; ch < s->channels; ch++) {
1735
            block->bap[ch]         = &s->bap_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1736
            block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (blk * s->channels + ch)];
1737
            block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1738
            block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * s->channels + ch)];
1739
            block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1740
            block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * s->channels + ch)];
1741
            block->mask[ch]        = &s->mask_buffer       [64            * (blk * s->channels + ch)];
1742
            block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * s->channels + ch)];
1743
        }
1744
    }
1745

    
1746
    return 0;
1747
alloc_fail:
1748
    return AVERROR(ENOMEM);
1749
}
1750

    
1751

    
1752
/**
1753
 * Initialize the encoder.
1754
 */
1755
static av_cold int ac3_encode_init(AVCodecContext *avctx)
1756
{
1757
    AC3EncodeContext *s = avctx->priv_data;
1758
    int ret;
1759

    
1760
    avctx->frame_size = AC3_FRAME_SIZE;
1761

    
1762
    ac3_common_init();
1763

    
1764
    ret = validate_options(avctx, s);
1765
    if (ret)
1766
        return ret;
1767

    
1768
    s->bitstream_id   = 8 + s->bit_alloc.sr_shift;
1769
    s->bitstream_mode = 0; /* complete main audio service */
1770

    
1771
    s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
1772
    s->bits_written    = 0;
1773
    s->samples_written = 0;
1774
    s->frame_size      = s->frame_size_min;
1775

    
1776
    set_bandwidth(s, avctx->cutoff);
1777

    
1778
    exponent_init(s);
1779

    
1780
    bit_alloc_init(s);
1781

    
1782
    s->mdct.avctx = avctx;
1783
    ret = mdct_init(&s->mdct, 9);
1784
    if (ret)
1785
        goto init_fail;
1786

    
1787
    ret = allocate_buffers(avctx);
1788
    if (ret)
1789
        goto init_fail;
1790

    
1791
    avctx->coded_frame= avcodec_alloc_frame();
1792

    
1793
    dsputil_init(&s->dsp, avctx);
1794

    
1795
    return 0;
1796
init_fail:
1797
    ac3_encode_close(avctx);
1798
    return ret;
1799
}
1800

    
1801

    
1802
#ifdef TEST
1803
/*************************************************************************/
1804
/* TEST */
1805

    
1806
#include "libavutil/lfg.h"
1807

    
1808
#define FN (MDCT_SAMPLES/4)
1809

    
1810

    
1811
static void fft_test(AVLFG *lfg)
1812
{
1813
    IComplex in[FN], in1[FN];
1814
    int k, n, i;
1815
    float sum_re, sum_im, a;
1816

    
1817
    for (i = 0; i < FN; i++) {
1818
        in[i].re = av_lfg_get(lfg) % 65535 - 32767;
1819
        in[i].im = av_lfg_get(lfg) % 65535 - 32767;
1820
        in1[i]   = in[i];
1821
    }
1822
    fft(in, 7);
1823

    
1824
    /* do it by hand */
1825
    for (k = 0; k < FN; k++) {
1826
        sum_re = 0;
1827
        sum_im = 0;
1828
        for (n = 0; n < FN; n++) {
1829
            a = -2 * M_PI * (n * k) / FN;
1830
            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1831
            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1832
        }
1833
        av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
1834
               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1835
    }
1836
}
1837

    
1838

    
1839
static void mdct_test(AVLFG *lfg)
1840
{
1841
    int16_t input[MDCT_SAMPLES];
1842
    int32_t output[AC3_MAX_COEFS];
1843
    float input1[MDCT_SAMPLES];
1844
    float output1[AC3_MAX_COEFS];
1845
    float s, a, err, e, emax;
1846
    int i, k, n;
1847

    
1848
    for (i = 0; i < MDCT_SAMPLES; i++) {
1849
        input[i]  = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
1850
        input1[i] = input[i];
1851
    }
1852

    
1853
    mdct512(output, input);
1854

    
1855
    /* do it by hand */
1856
    for (k = 0; k < AC3_MAX_COEFS; k++) {
1857
        s = 0;
1858
        for (n = 0; n < MDCT_SAMPLES; n++) {
1859
            a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
1860
            s += input1[n] * cos(a);
1861
        }
1862
        output1[k] = -2 * s / MDCT_SAMPLES;
1863
    }
1864

    
1865
    err  = 0;
1866
    emax = 0;
1867
    for (i = 0; i < AC3_MAX_COEFS; i++) {
1868
        av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
1869
        e = output[i] - output1[i];
1870
        if (e > emax)
1871
            emax = e;
1872
        err += e * e;
1873
    }
1874
    av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
1875
}
1876

    
1877

    
1878
int main(void)
1879
{
1880
    AVLFG lfg;
1881

    
1882
    av_log_set_level(AV_LOG_DEBUG);
1883
    mdct_init(9);
1884

    
1885
    fft_test(&lfg);
1886
    mdct_test(&lfg);
1887

    
1888
    return 0;
1889
}
1890
#endif /* TEST */
1891

    
1892

    
1893
AVCodec ac3_encoder = {
1894
    "ac3",
1895
    AVMEDIA_TYPE_AUDIO,
1896
    CODEC_ID_AC3,
1897
    sizeof(AC3EncodeContext),
1898
    ac3_encode_init,
1899
    ac3_encode_frame,
1900
    ac3_encode_close,
1901
    NULL,
1902
    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1903
    .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1904
    .channel_layouts = (const int64_t[]){
1905
        AV_CH_LAYOUT_MONO,
1906
        AV_CH_LAYOUT_STEREO,
1907
        AV_CH_LAYOUT_2_1,
1908
        AV_CH_LAYOUT_SURROUND,
1909
        AV_CH_LAYOUT_2_2,
1910
        AV_CH_LAYOUT_QUAD,
1911
        AV_CH_LAYOUT_4POINT0,
1912
        AV_CH_LAYOUT_5POINT0,
1913
        AV_CH_LAYOUT_5POINT0_BACK,
1914
       (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
1915
       (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
1916
       (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
1917
       (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1918
       (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
1919
       (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
1920
       (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
1921
        AV_CH_LAYOUT_5POINT1,
1922
        AV_CH_LAYOUT_5POINT1_BACK,
1923
        0 },
1924
};