Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ 89bedc4d

History | View | Annotate | Download (57.1 KB)

1
/*
2
 * The simplest AC-3 encoder
3
 * Copyright (c) 2000 Fabrice Bellard
4
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
 */
21

    
22
/**
23
 * @file
24
 * The simplest AC-3 encoder.
25
 */
26

    
27
//#define DEBUG
28

    
29
#include "libavcore/audioconvert.h"
30
#include "libavutil/crc.h"
31
#include "avcodec.h"
32
#include "put_bits.h"
33
#include "ac3.h"
34
#include "audioconvert.h"
35

    
36

    
37
#define MDCT_NBITS 9
38
#define MDCT_SAMPLES (1 << MDCT_NBITS)
39

    
40
/** Maximum number of exponent groups. +1 for separate DC exponent. */
41
#define AC3_MAX_EXP_GROUPS 85
42

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

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

    
49

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

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

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

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

    
89
    AC3Block blocks[AC3_MAX_BLOCKS];        ///< per-block info
90

    
91
    int bitstream_id;                       ///< bitstream id                           (bsid)
92
    int bitstream_mode;                     ///< bitstream mode                         (bsmod)
93

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

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

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

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

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

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

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

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

    
145

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

    
152

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

    
169

    
170
/**
171
 * Deinterleave input samples.
172
 * Channels are reordered from FFmpeg's default order to AC-3 order.
173
 */
174
static void deinterleave_input_samples(AC3EncodeContext *s,
175
                                       const int16_t *samples)
176
{
177
    int ch, i;
178

    
179
    /* deinterleave and remap input samples */
180
    for (ch = 0; ch < s->channels; ch++) {
181
        const int16_t *sptr;
182
        int sinc;
183

    
184
        /* copy last 256 samples of previous frame to the start of the current frame */
185
        memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
186
               AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
187

    
188
        /* deinterleave */
189
        sinc = s->channels;
190
        sptr = samples + s->channel_map[ch];
191
        for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
192
            s->planar_samples[ch][i] = *sptr;
193
            sptr += sinc;
194
        }
195
    }
196
}
197

    
198

    
199
/**
200
 * Finalize MDCT and free allocated memory.
201
 */
202
static av_cold void mdct_end(AC3MDCTContext *mdct)
203
{
204
    av_freep(&mdct->rot_tmp);
205
    av_freep(&mdct->cplx_tmp);
206
}
207

    
208

    
209

    
210
/**
211
 * Initialize FFT tables.
212
 * @param ln log2(FFT size)
213
 */
214
static av_cold void fft_init(int ln)
215
{
216
    int i, n, n2;
217
    float alpha;
218

    
219
    n  = 1 << ln;
220
    n2 = n >> 1;
221

    
222
    for (i = 0; i < n2; i++) {
223
        alpha     = 2.0 * M_PI * i / n;
224
        costab[i] = FIX15(cos(alpha));
225
        sintab[i] = FIX15(sin(alpha));
226
    }
227
}
228

    
229

    
230
/**
231
 * Initialize MDCT tables.
232
 * @param nbits log2(MDCT size)
233
 */
234
static av_cold int mdct_init(AC3MDCTContext *mdct, int nbits)
235
{
236
    int i, n, n4;
237

    
238
    n  = 1 << nbits;
239
    n4 = n >> 2;
240

    
241
    fft_init(nbits - 2);
242

    
243
    FF_ALLOC_OR_GOTO(mdct->avctx, mdct->rot_tmp,  n  * sizeof(*mdct->rot_tmp),
244
                     mdct_alloc_fail);
245
    FF_ALLOC_OR_GOTO(mdct->avctx, mdct->cplx_tmp, n4 * sizeof(*mdct->cplx_tmp),
246
                     mdct_alloc_fail);
247

    
248
    for (i = 0; i < n4; i++) {
249
        float alpha = 2.0 * M_PI * (i + 1.0 / 8.0) / n;
250
        xcos1[i] = FIX15(-cos(alpha));
251
        xsin1[i] = FIX15(-sin(alpha));
252
    }
253

    
254
    return 0;
255
mdct_alloc_fail:
256
    return AVERROR(ENOMEM);
257
}
258

    
259

    
260
/** Butterfly op */
261
#define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1)  \
262
{                                                       \
263
  int ax, ay, bx, by;                                   \
264
  bx  = pre1;                                           \
265
  by  = pim1;                                           \
266
  ax  = qre1;                                           \
267
  ay  = qim1;                                           \
268
  pre = (bx + ax) >> 1;                                 \
269
  pim = (by + ay) >> 1;                                 \
270
  qre = (bx - ax) >> 1;                                 \
271
  qim = (by - ay) >> 1;                                 \
272
}
273

    
274

    
275
/** Complex multiply */
276
#define CMUL(pre, pim, are, aim, bre, bim)              \
277
{                                                       \
278
   pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;     \
279
   pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;     \
280
}
281

    
282

    
283
/**
284
 * Calculate a 2^n point complex FFT on 2^ln points.
285
 * @param z  complex input/output samples
286
 * @param ln log2(FFT size)
287
 */
288
static void fft(IComplex *z, int ln)
289
{
290
    int j, l, np, np2;
291
    int nblocks, nloops;
292
    register IComplex *p,*q;
293
    int tmp_re, tmp_im;
294

    
295
    np = 1 << ln;
296

    
297
    /* reverse */
298
    for (j = 0; j < np; j++) {
299
        int k = av_reverse[j] >> (8 - ln);
300
        if (k < j)
301
            FFSWAP(IComplex, z[k], z[j]);
302
    }
303

    
304
    /* pass 0 */
305

    
306
    p = &z[0];
307
    j = np >> 1;
308
    do {
309
        BF(p[0].re, p[0].im, p[1].re, p[1].im,
310
           p[0].re, p[0].im, p[1].re, p[1].im);
311
        p += 2;
312
    } while (--j);
313

    
314
    /* pass 1 */
315

    
316
    p = &z[0];
317
    j = np >> 2;
318
    do {
319
        BF(p[0].re, p[0].im, p[2].re,  p[2].im,
320
           p[0].re, p[0].im, p[2].re,  p[2].im);
321
        BF(p[1].re, p[1].im, p[3].re,  p[3].im,
322
           p[1].re, p[1].im, p[3].im, -p[3].re);
323
        p+=4;
324
    } while (--j);
325

    
326
    /* pass 2 .. ln-1 */
327

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

    
354

    
355
/**
356
 * Calculate a 512-point MDCT
357
 * @param out 256 output frequency coefficients
358
 * @param in  512 windowed input audio samples
359
 */
360
static void mdct512(AC3MDCTContext *mdct, int32_t *out, int16_t *in)
361
{
362
    int i, re, im;
363
    int16_t *rot = mdct->rot_tmp;
364
    IComplex *x  = mdct->cplx_tmp;
365

    
366
    /* shift to simplify computations */
367
    for (i = 0; i < MDCT_SAMPLES/4; i++)
368
        rot[i] = -in[i + 3*MDCT_SAMPLES/4];
369
    memcpy(&rot[MDCT_SAMPLES/4], &in[0], 3*MDCT_SAMPLES/4*sizeof(*in));
370

    
371
    /* pre rotation */
372
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
373
        re =  ((int)rot[               2*i] - (int)rot[MDCT_SAMPLES  -1-2*i]) >> 1;
374
        im = -((int)rot[MDCT_SAMPLES/2+2*i] - (int)rot[MDCT_SAMPLES/2-1-2*i]) >> 1;
375
        CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
376
    }
377

    
378
    fft(x, MDCT_NBITS - 2);
379

    
380
    /* post rotation */
381
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
382
        re = x[i].re;
383
        im = x[i].im;
384
        CMUL(out[MDCT_SAMPLES/2-1-2*i], out[2*i], re, im, xsin1[i], xcos1[i]);
385
    }
386
}
387

    
388

    
389
/**
390
 * Apply KBD window to input samples prior to MDCT.
391
 */
392
static void apply_window(int16_t *output, const int16_t *input,
393
                         const int16_t *window, int n)
394
{
395
    int i;
396
    int n2 = n >> 1;
397

    
398
    for (i = 0; i < n2; i++) {
399
        output[i]     = MUL16(input[i],     window[i]) >> 15;
400
        output[n-i-1] = MUL16(input[n-i-1], window[i]) >> 15;
401
    }
402
}
403

    
404

    
405
/**
406
 * Calculate the log2() of the maximum absolute value in an array.
407
 * @param tab input array
408
 * @param n   number of values in the array
409
 * @return    log2(max(abs(tab[])))
410
 */
411
static int log2_tab(int16_t *tab, int n)
412
{
413
    int i, v;
414

    
415
    v = 0;
416
    for (i = 0; i < n; i++)
417
        v |= abs(tab[i]);
418

    
419
    return av_log2(v);
420
}
421

    
422

    
423
/**
424
 * Left-shift each value in an array by a specified amount.
425
 * @param tab    input array
426
 * @param n      number of values in the array
427
 * @param lshift left shift amount. a negative value means right shift.
428
 */
429
static void lshift_tab(int16_t *tab, int n, int lshift)
430
{
431
    int i;
432

    
433
    if (lshift > 0) {
434
        for (i = 0; i < n; i++)
435
            tab[i] <<= lshift;
436
    } else if (lshift < 0) {
437
        lshift = -lshift;
438
        for (i = 0; i < n; i++)
439
            tab[i] >>= lshift;
440
    }
441
}
442

    
443

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

    
459

    
460
/**
461
 * Apply the MDCT to input samples to generate frequency coefficients.
462
 * This applies the KBD window and normalizes the input to reduce precision
463
 * loss due to fixed-point calculations.
464
 */
465
static void apply_mdct(AC3EncodeContext *s)
466
{
467
    int blk, ch;
468

    
469
    for (ch = 0; ch < s->channels; ch++) {
470
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
471
            AC3Block *block = &s->blocks[blk];
472
            const int16_t *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
473

    
474
            apply_window(s->windowed_samples, input_samples, ff_ac3_window, AC3_WINDOW_SIZE);
475

    
476
            block->exp_shift[ch] = normalize_samples(s);
477

    
478
            mdct512(&s->mdct, block->mdct_coef[ch], s->windowed_samples);
479
        }
480
    }
481
}
482

    
483

    
484
/**
485
 * Extract exponents from the MDCT coefficients.
486
 * This takes into account the normalization that was done to the input samples
487
 * by adjusting the exponents by the exponent shift values.
488
 */
489
static void extract_exponents(AC3EncodeContext *s)
490
{
491
    int blk, ch, i;
492

    
493
    for (ch = 0; ch < s->channels; ch++) {
494
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
495
            AC3Block *block = &s->blocks[blk];
496
            for (i = 0; i < AC3_MAX_COEFS; i++) {
497
                int e;
498
                int v = abs(block->mdct_coef[ch][i]);
499
                if (v == 0)
500
                    e = 24;
501
                else {
502
                    e = 23 - av_log2(v) + block->exp_shift[ch];
503
                    if (e >= 24) {
504
                        e = 24;
505
                        block->mdct_coef[ch][i] = 0;
506
                    }
507
                }
508
                block->exp[ch][i] = e;
509
            }
510
        }
511
    }
512
}
513

    
514

    
515
/**
516
 * Calculate the sum of absolute differences (SAD) between 2 sets of exponents.
517
 */
518
static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
519
{
520
    int sum, i;
521
    sum = 0;
522
    for (i = 0; i < n; i++)
523
        sum += abs(exp1[i] - exp2[i]);
524
    return sum;
525
}
526

    
527

    
528
/**
529
 * Exponent Difference Threshold.
530
 * New exponents are sent if their SAD exceed this number.
531
 */
532
#define EXP_DIFF_THRESHOLD 1000
533

    
534

    
535
/**
536
 * Calculate exponent strategies for all blocks in a single channel.
537
 */
538
static void compute_exp_strategy_ch(uint8_t *exp_strategy, uint8_t **exp)
539
{
540
    int blk, blk1;
541
    int exp_diff;
542

    
543
    /* estimate if the exponent variation & decide if they should be
544
       reused in the next frame */
545
    exp_strategy[0] = EXP_NEW;
546
    for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
547
        exp_diff = calc_exp_diff(exp[blk], exp[blk-1], AC3_MAX_COEFS);
548
        if (exp_diff > EXP_DIFF_THRESHOLD)
549
            exp_strategy[blk] = EXP_NEW;
550
        else
551
            exp_strategy[blk] = EXP_REUSE;
552
    }
553

    
554
    /* now select the encoding strategy type : if exponents are often
555
       recoded, we use a coarse encoding */
556
    blk = 0;
557
    while (blk < AC3_MAX_BLOCKS) {
558
        blk1 = blk + 1;
559
        while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
560
            blk1++;
561
        switch (blk1 - blk) {
562
        case 1:  exp_strategy[blk] = EXP_D45; break;
563
        case 2:
564
        case 3:  exp_strategy[blk] = EXP_D25; break;
565
        default: exp_strategy[blk] = EXP_D15; break;
566
        }
567
        blk = blk1;
568
    }
569
}
570

    
571

    
572
/**
573
 * Calculate exponent strategies for all channels.
574
 * Array arrangement is reversed to simplify the per-channel calculation.
575
 */
576
static void compute_exp_strategy(AC3EncodeContext *s)
577
{
578
    uint8_t *exp1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
579
    uint8_t exp_str1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
580
    int ch, blk;
581

    
582
    for (ch = 0; ch < s->fbw_channels; ch++) {
583
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
584
            exp1[ch][blk]     = s->blocks[blk].exp[ch];
585
            exp_str1[ch][blk] = s->blocks[blk].exp_strategy[ch];
586
        }
587

    
588
        compute_exp_strategy_ch(exp_str1[ch], exp1[ch]);
589

    
590
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
591
            s->blocks[blk].exp_strategy[ch] = exp_str1[ch][blk];
592
    }
593
    if (s->lfe_on) {
594
        ch = s->lfe_channel;
595
        s->blocks[0].exp_strategy[ch] = EXP_D15;
596
        for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
597
            s->blocks[blk].exp_strategy[ch] = EXP_REUSE;
598
    }
599
}
600

    
601

    
602
/**
603
 * Set each encoded exponent in a block to the minimum of itself and the
604
 * exponent in the same frequency bin of a following block.
605
 * exp[i] = min(exp[i], exp1[i]
606
 */
607
static void exponent_min(uint8_t *exp, uint8_t *exp1, int n)
608
{
609
    int i;
610
    for (i = 0; i < n; i++) {
611
        if (exp1[i] < exp[i])
612
            exp[i] = exp1[i];
613
    }
614
}
615

    
616

    
617
/**
618
 * Update the exponents so that they are the ones the decoder will decode.
619
 */
620
static void encode_exponents_blk_ch(uint8_t *encoded_exp, uint8_t *exp,
621
                                    int nb_exps, int exp_strategy,
622
                                    uint8_t *num_exp_groups)
623
{
624
    int group_size, nb_groups, i, j, k, exp_min;
625
    uint8_t exp1[AC3_MAX_COEFS];
626

    
627
    group_size = exp_strategy + (exp_strategy == EXP_D45);
628
    *num_exp_groups = (nb_exps + (group_size * 3) - 4) / (3 * group_size);
629
    nb_groups = *num_exp_groups * 3;
630

    
631
    /* for each group, compute the minimum exponent */
632
    exp1[0] = exp[0]; /* DC exponent is handled separately */
633
    k = 1;
634
    for (i = 1; i <= nb_groups; i++) {
635
        exp_min = exp[k];
636
        assert(exp_min >= 0 && exp_min <= 24);
637
        for (j = 1; j < group_size; j++) {
638
            if (exp[k+j] < exp_min)
639
                exp_min = exp[k+j];
640
        }
641
        exp1[i] = exp_min;
642
        k += group_size;
643
    }
644

    
645
    /* constraint for DC exponent */
646
    if (exp1[0] > 15)
647
        exp1[0] = 15;
648

    
649
    /* decrease the delta between each groups to within 2 so that they can be
650
       differentially encoded */
651
    for (i = 1; i <= nb_groups; i++)
652
        exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
653
    for (i = nb_groups-1; i >= 0; i--)
654
        exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
655

    
656
    /* now we have the exponent values the decoder will see */
657
    encoded_exp[0] = exp1[0];
658
    k = 1;
659
    for (i = 1; i <= nb_groups; i++) {
660
        for (j = 0; j < group_size; j++)
661
            encoded_exp[k+j] = exp1[i];
662
        k += group_size;
663
    }
664
}
665

    
666

    
667
/**
668
 * Encode exponents from original extracted form to what the decoder will see.
669
 * This copies and groups exponents based on exponent strategy and reduces
670
 * deltas between adjacent exponent groups so that they can be differentially
671
 * encoded.
672
 */
673
static void encode_exponents(AC3EncodeContext *s)
674
{
675
    int blk, blk1, blk2, ch;
676
    AC3Block *block, *block1, *block2;
677

    
678
    for (ch = 0; ch < s->channels; ch++) {
679
        blk = 0;
680
        block = &s->blocks[0];
681
        while (blk < AC3_MAX_BLOCKS) {
682
            blk1 = blk + 1;
683
            block1 = block + 1;
684
            /* for the EXP_REUSE case we select the min of the exponents */
685
            while (blk1 < AC3_MAX_BLOCKS && block1->exp_strategy[ch] == EXP_REUSE) {
686
                exponent_min(block->exp[ch], block1->exp[ch], s->nb_coefs[ch]);
687
                blk1++;
688
                block1++;
689
            }
690
            encode_exponents_blk_ch(block->encoded_exp[ch],
691
                                    block->exp[ch], s->nb_coefs[ch],
692
                                    block->exp_strategy[ch],
693
                                    &block->num_exp_groups[ch]);
694
            /* copy encoded exponents for reuse case */
695
            block2 = block + 1;
696
            for (blk2 = blk+1; blk2 < blk1; blk2++, block2++) {
697
                memcpy(block2->encoded_exp[ch], block->encoded_exp[ch],
698
                       s->nb_coefs[ch] * sizeof(uint8_t));
699
            }
700
            blk = blk1;
701
            block = block1;
702
        }
703
    }
704
}
705

    
706

    
707
/**
708
 * Group exponents.
709
 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
710
 * varies depending on exponent strategy and bandwidth.
711
 */
712
static void group_exponents(AC3EncodeContext *s)
713
{
714
    int blk, ch, i;
715
    int group_size, bit_count;
716
    uint8_t *p;
717
    int delta0, delta1, delta2;
718
    int exp0, exp1;
719

    
720
    bit_count = 0;
721
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
722
        AC3Block *block = &s->blocks[blk];
723
        for (ch = 0; ch < s->channels; ch++) {
724
            if (block->exp_strategy[ch] == EXP_REUSE) {
725
                block->num_exp_groups[ch] = 0;
726
                continue;
727
            }
728
            group_size = block->exp_strategy[ch] + (block->exp_strategy[ch] == EXP_D45);
729
            bit_count += 4 + (block->num_exp_groups[ch] * 7);
730
            p = block->encoded_exp[ch];
731

    
732
            /* DC exponent */
733
            exp1 = *p++;
734
            block->grouped_exp[ch][0] = exp1;
735

    
736
            /* remaining exponents are delta encoded */
737
            for (i = 1; i <= block->num_exp_groups[ch]; i++) {
738
                /* merge three delta in one code */
739
                exp0   = exp1;
740
                exp1   = p[0];
741
                p     += group_size;
742
                delta0 = exp1 - exp0 + 2;
743

    
744
                exp0   = exp1;
745
                exp1   = p[0];
746
                p     += group_size;
747
                delta1 = exp1 - exp0 + 2;
748

    
749
                exp0   = exp1;
750
                exp1   = p[0];
751
                p     += group_size;
752
                delta2 = exp1 - exp0 + 2;
753

    
754
                block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
755
            }
756
        }
757
    }
758

    
759
    s->exponent_bits = bit_count;
760
}
761

    
762

    
763
/**
764
 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
765
 * Extract exponents from MDCT coefficients, calculate exponent strategies,
766
 * and encode final exponents.
767
 */
768
static void process_exponents(AC3EncodeContext *s)
769
{
770
    extract_exponents(s);
771

    
772
    compute_exp_strategy(s);
773

    
774
    encode_exponents(s);
775

    
776
    group_exponents(s);
777
}
778

    
779

    
780
/**
781
 * Initialize bit allocation.
782
 * Set default parameter codes and calculate parameter values.
783
 */
784
static void bit_alloc_init(AC3EncodeContext *s)
785
{
786
    int ch;
787

    
788
    /* init default parameters */
789
    s->slow_decay_code = 2;
790
    s->fast_decay_code = 1;
791
    s->slow_gain_code  = 1;
792
    s->db_per_bit_code = 2;
793
    s->floor_code      = 4;
794
    for (ch = 0; ch < s->channels; ch++)
795
        s->fast_gain_code[ch] = 4;
796

    
797
    /* initial snr offset */
798
    s->coarse_snr_offset = 40;
799

    
800
    /* compute real values */
801
    /* currently none of these values change during encoding, so we can just
802
       set them once at initialization */
803
    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
804
    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
805
    s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
806
    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
807
    s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
808
}
809

    
810

    
811
/**
812
 * Count the bits used to encode the frame, minus exponents and mantissas.
813
 */
814
static void count_frame_bits(AC3EncodeContext *s)
815
{
816
    static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
817
    int blk, ch;
818
    int frame_bits;
819

    
820
    /* header size */
821
    frame_bits = 65;
822
    frame_bits += frame_bits_inc[s->channel_mode];
823

    
824
    /* audio blocks */
825
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
826
        frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
827
        if (s->channel_mode == AC3_CHMODE_STEREO) {
828
            frame_bits++; /* rematstr */
829
            if (!blk)
830
                frame_bits += 4;
831
        }
832
        frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
833
        if (s->lfe_on)
834
            frame_bits++; /* lfeexpstr */
835
        for (ch = 0; ch < s->fbw_channels; ch++) {
836
            if (s->blocks[blk].exp_strategy[ch] != EXP_REUSE)
837
                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
838
        }
839
        frame_bits++; /* baie */
840
        frame_bits++; /* snr */
841
        frame_bits += 2; /* delta / skip */
842
    }
843
    frame_bits++; /* cplinu for block 0 */
844
    /* bit alloc info */
845
    /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
846
    /* csnroffset[6] */
847
    /* (fsnoffset[4] + fgaincod[4]) * c */
848
    frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
849

    
850
    /* auxdatae, crcrsv */
851
    frame_bits += 2;
852

    
853
    /* CRC */
854
    frame_bits += 16;
855

    
856
    s->frame_bits = frame_bits;
857
}
858

    
859

    
860
/**
861
 * Calculate the number of bits needed to encode a set of mantissas.
862
 */
863
static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *bap, int nb_coefs)
864
{
865
    int bits, b, i;
866

    
867
    bits = 0;
868
    for (i = 0; i < nb_coefs; i++) {
869
        b = bap[i];
870
        switch (b) {
871
        case 0:
872
            /* bap=0 mantissas are not encoded */
873
            break;
874
        case 1:
875
            /* 3 mantissas in 5 bits */
876
            if (s->mant1_cnt == 0)
877
                bits += 5;
878
            if (++s->mant1_cnt == 3)
879
                s->mant1_cnt = 0;
880
            break;
881
        case 2:
882
            /* 3 mantissas in 7 bits */
883
            if (s->mant2_cnt == 0)
884
                bits += 7;
885
            if (++s->mant2_cnt == 3)
886
                s->mant2_cnt = 0;
887
            break;
888
        case 3:
889
            bits += 3;
890
            break;
891
        case 4:
892
            /* 2 mantissas in 7 bits */
893
            if (s->mant4_cnt == 0)
894
                bits += 7;
895
            if (++s->mant4_cnt == 2)
896
                s->mant4_cnt = 0;
897
            break;
898
        case 14:
899
            bits += 14;
900
            break;
901
        case 15:
902
            bits += 16;
903
            break;
904
        default:
905
            bits += b - 1;
906
            break;
907
        }
908
    }
909
    return bits;
910
}
911

    
912

    
913
/**
914
 * Calculate masking curve based on the final exponents.
915
 * Also calculate the power spectral densities to use in future calculations.
916
 */
917
static void bit_alloc_masking(AC3EncodeContext *s)
918
{
919
    int blk, ch;
920

    
921
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
922
        AC3Block *block = &s->blocks[blk];
923
        for (ch = 0; ch < s->channels; ch++) {
924
            if (block->exp_strategy[ch] == EXP_REUSE) {
925
                AC3Block *block1 = &s->blocks[blk-1];
926
                memcpy(block->psd[ch],  block1->psd[ch],  AC3_MAX_COEFS*sizeof(block->psd[0][0]));
927
                memcpy(block->mask[ch], block1->mask[ch], AC3_CRITICAL_BANDS*sizeof(block->mask[0][0]));
928
            } else {
929
                ff_ac3_bit_alloc_calc_psd(block->encoded_exp[ch], 0,
930
                                          s->nb_coefs[ch],
931
                                          block->psd[ch], block->band_psd[ch]);
932
                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
933
                                           0, s->nb_coefs[ch],
934
                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
935
                                           ch == s->lfe_channel,
936
                                           DBA_NONE, 0, NULL, NULL, NULL,
937
                                           block->mask[ch]);
938
            }
939
        }
940
    }
941
}
942

    
943

    
944
/**
945
 * Ensure that bap for each block and channel point to the current bap_buffer.
946
 * They may have been switched during the bit allocation search.
947
 */
948
static void reset_block_bap(AC3EncodeContext *s)
949
{
950
    int blk, ch;
951
    if (s->blocks[0].bap[0] == s->bap_buffer)
952
        return;
953
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
954
        for (ch = 0; ch < s->channels; ch++) {
955
            s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
956
        }
957
    }
958
}
959

    
960

    
961
/**
962
 * Run the bit allocation with a given SNR offset.
963
 * This calculates the bit allocation pointers that will be used to determine
964
 * the quantization of each mantissa.
965
 * @return the number of bits needed for mantissas if the given SNR offset is
966
 *         is used.
967
 */
968
static int bit_alloc(AC3EncodeContext *s,
969
                     int snr_offset)
970
{
971
    int blk, ch;
972
    int mantissa_bits;
973

    
974
    snr_offset = (snr_offset - 240) << 2;
975

    
976
    reset_block_bap(s);
977
    mantissa_bits = 0;
978
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
979
        AC3Block *block = &s->blocks[blk];
980
        s->mant1_cnt = 0;
981
        s->mant2_cnt = 0;
982
        s->mant4_cnt = 0;
983
        for (ch = 0; ch < s->channels; ch++) {
984
            ff_ac3_bit_alloc_calc_bap(block->mask[ch], block->psd[ch], 0,
985
                                      s->nb_coefs[ch], snr_offset,
986
                                      s->bit_alloc.floor, ff_ac3_bap_tab,
987
                                      block->bap[ch]);
988
            mantissa_bits += compute_mantissa_size(s, block->bap[ch], s->nb_coefs[ch]);
989
        }
990
    }
991
    return mantissa_bits;
992
}
993

    
994

    
995
/**
996
 * Constant bitrate bit allocation search.
997
 * Find the largest SNR offset that will allow data to fit in the frame.
998
 */
999
static int cbr_bit_allocation(AC3EncodeContext *s)
1000
{
1001
    int ch;
1002
    int bits_left;
1003
    int snr_offset;
1004

    
1005
    bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1006

    
1007
    snr_offset = s->coarse_snr_offset << 4;
1008

    
1009
    while (snr_offset >= 0 &&
1010
           bit_alloc(s, snr_offset) > bits_left) {
1011
        snr_offset -= 64;
1012
    }
1013
    if (snr_offset < 0)
1014
        return AVERROR(EINVAL);
1015

    
1016
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1017
    while (snr_offset + 64 <= 1023 &&
1018
           bit_alloc(s, snr_offset + 64) <= bits_left) {
1019
        snr_offset += 64;
1020
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1021
    }
1022
    while (snr_offset + 16 <= 1023 &&
1023
           bit_alloc(s, snr_offset + 16) <= bits_left) {
1024
        snr_offset += 16;
1025
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1026
    }
1027
    while (snr_offset + 4 <= 1023 &&
1028
           bit_alloc(s, snr_offset + 4) <= bits_left) {
1029
        snr_offset += 4;
1030
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1031
    }
1032
    while (snr_offset + 1 <= 1023 &&
1033
           bit_alloc(s, snr_offset + 1) <= bits_left) {
1034
        snr_offset++;
1035
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1036
    }
1037
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1038
    reset_block_bap(s);
1039

    
1040
    s->coarse_snr_offset = snr_offset >> 4;
1041
    for (ch = 0; ch < s->channels; ch++)
1042
        s->fine_snr_offset[ch] = snr_offset & 0xF;
1043

    
1044
    return 0;
1045
}
1046

    
1047

    
1048
/**
1049
 * Perform bit allocation search.
1050
 * Finds the SNR offset value that maximizes quality and fits in the specified
1051
 * frame size.  Output is the SNR offset and a set of bit allocation pointers
1052
 * used to quantize the mantissas.
1053
 */
1054
static int compute_bit_allocation(AC3EncodeContext *s)
1055
{
1056
    count_frame_bits(s);
1057

    
1058
    bit_alloc_masking(s);
1059

    
1060
    return cbr_bit_allocation(s);
1061
}
1062

    
1063

    
1064
/**
1065
 * Symmetric quantization on 'levels' levels.
1066
 */
1067
static inline int sym_quant(int c, int e, int levels)
1068
{
1069
    int v;
1070

    
1071
    if (c >= 0) {
1072
        v = (levels * (c << e)) >> 24;
1073
        v = (v + 1) >> 1;
1074
        v = (levels >> 1) + v;
1075
    } else {
1076
        v = (levels * ((-c) << e)) >> 24;
1077
        v = (v + 1) >> 1;
1078
        v = (levels >> 1) - v;
1079
    }
1080
    assert(v >= 0 && v < levels);
1081
    return v;
1082
}
1083

    
1084

    
1085
/**
1086
 * Asymmetric quantization on 2^qbits levels.
1087
 */
1088
static inline int asym_quant(int c, int e, int qbits)
1089
{
1090
    int lshift, m, v;
1091

    
1092
    lshift = e + qbits - 24;
1093
    if (lshift >= 0)
1094
        v = c << lshift;
1095
    else
1096
        v = c >> (-lshift);
1097
    /* rounding */
1098
    v = (v + 1) >> 1;
1099
    m = (1 << (qbits-1));
1100
    if (v >= m)
1101
        v = m - 1;
1102
    assert(v >= -m);
1103
    return v & ((1 << qbits)-1);
1104
}
1105

    
1106

    
1107
/**
1108
 * Quantize a set of mantissas for a single channel in a single block.
1109
 */
1110
static void quantize_mantissas_blk_ch(AC3EncodeContext *s,
1111
                                      int32_t *mdct_coef, int8_t exp_shift,
1112
                                      uint8_t *encoded_exp, uint8_t *bap,
1113
                                      uint16_t *qmant, int n)
1114
{
1115
    int i;
1116

    
1117
    for (i = 0; i < n; i++) {
1118
        int v;
1119
        int c = mdct_coef[i];
1120
        int e = encoded_exp[i] - exp_shift;
1121
        int b = bap[i];
1122
        switch (b) {
1123
        case 0:
1124
            v = 0;
1125
            break;
1126
        case 1:
1127
            v = sym_quant(c, e, 3);
1128
            switch (s->mant1_cnt) {
1129
            case 0:
1130
                s->qmant1_ptr = &qmant[i];
1131
                v = 9 * v;
1132
                s->mant1_cnt = 1;
1133
                break;
1134
            case 1:
1135
                *s->qmant1_ptr += 3 * v;
1136
                s->mant1_cnt = 2;
1137
                v = 128;
1138
                break;
1139
            default:
1140
                *s->qmant1_ptr += v;
1141
                s->mant1_cnt = 0;
1142
                v = 128;
1143
                break;
1144
            }
1145
            break;
1146
        case 2:
1147
            v = sym_quant(c, e, 5);
1148
            switch (s->mant2_cnt) {
1149
            case 0:
1150
                s->qmant2_ptr = &qmant[i];
1151
                v = 25 * v;
1152
                s->mant2_cnt = 1;
1153
                break;
1154
            case 1:
1155
                *s->qmant2_ptr += 5 * v;
1156
                s->mant2_cnt = 2;
1157
                v = 128;
1158
                break;
1159
            default:
1160
                *s->qmant2_ptr += v;
1161
                s->mant2_cnt = 0;
1162
                v = 128;
1163
                break;
1164
            }
1165
            break;
1166
        case 3:
1167
            v = sym_quant(c, e, 7);
1168
            break;
1169
        case 4:
1170
            v = sym_quant(c, e, 11);
1171
            switch (s->mant4_cnt) {
1172
            case 0:
1173
                s->qmant4_ptr = &qmant[i];
1174
                v = 11 * v;
1175
                s->mant4_cnt = 1;
1176
                break;
1177
            default:
1178
                *s->qmant4_ptr += v;
1179
                s->mant4_cnt = 0;
1180
                v = 128;
1181
                break;
1182
            }
1183
            break;
1184
        case 5:
1185
            v = sym_quant(c, e, 15);
1186
            break;
1187
        case 14:
1188
            v = asym_quant(c, e, 14);
1189
            break;
1190
        case 15:
1191
            v = asym_quant(c, e, 16);
1192
            break;
1193
        default:
1194
            v = asym_quant(c, e, b - 1);
1195
            break;
1196
        }
1197
        qmant[i] = v;
1198
    }
1199
}
1200

    
1201

    
1202
/**
1203
 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1204
 */
1205
static void quantize_mantissas(AC3EncodeContext *s)
1206
{
1207
    int blk, ch;
1208

    
1209

    
1210
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1211
        AC3Block *block = &s->blocks[blk];
1212
        s->mant1_cnt  = s->mant2_cnt  = s->mant4_cnt  = 0;
1213
        s->qmant1_ptr = s->qmant2_ptr = s->qmant4_ptr = NULL;
1214

    
1215
        for (ch = 0; ch < s->channels; ch++) {
1216
            quantize_mantissas_blk_ch(s, block->mdct_coef[ch], block->exp_shift[ch],
1217
                                      block->encoded_exp[ch], block->bap[ch],
1218
                                      block->qmant[ch], s->nb_coefs[ch]);
1219
        }
1220
    }
1221
}
1222

    
1223

    
1224
/**
1225
 * Write the AC-3 frame header to the output bitstream.
1226
 */
1227
static void output_frame_header(AC3EncodeContext *s)
1228
{
1229
    put_bits(&s->pb, 16, 0x0b77);   /* frame header */
1230
    put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
1231
    put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
1232
    put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1233
    put_bits(&s->pb, 5,  s->bitstream_id);
1234
    put_bits(&s->pb, 3,  s->bitstream_mode);
1235
    put_bits(&s->pb, 3,  s->channel_mode);
1236
    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1237
        put_bits(&s->pb, 2, 1);     /* XXX -4.5 dB */
1238
    if (s->channel_mode & 0x04)
1239
        put_bits(&s->pb, 2, 1);     /* XXX -6 dB */
1240
    if (s->channel_mode == AC3_CHMODE_STEREO)
1241
        put_bits(&s->pb, 2, 0);     /* surround not indicated */
1242
    put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1243
    put_bits(&s->pb, 5, 31);        /* dialog norm: -31 db */
1244
    put_bits(&s->pb, 1, 0);         /* no compression control word */
1245
    put_bits(&s->pb, 1, 0);         /* no lang code */
1246
    put_bits(&s->pb, 1, 0);         /* no audio production info */
1247
    put_bits(&s->pb, 1, 0);         /* no copyright */
1248
    put_bits(&s->pb, 1, 1);         /* original bitstream */
1249
    put_bits(&s->pb, 1, 0);         /* no time code 1 */
1250
    put_bits(&s->pb, 1, 0);         /* no time code 2 */
1251
    put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
1252
}
1253

    
1254

    
1255
/**
1256
 * Write one audio block to the output bitstream.
1257
 */
1258
static void output_audio_block(AC3EncodeContext *s,
1259
                               int block_num)
1260
{
1261
    int ch, i, baie, rbnd;
1262
    AC3Block *block = &s->blocks[block_num];
1263

    
1264
    /* block switching */
1265
    for (ch = 0; ch < s->fbw_channels; ch++)
1266
        put_bits(&s->pb, 1, 0);
1267

    
1268
    /* dither flags */
1269
    for (ch = 0; ch < s->fbw_channels; ch++)
1270
        put_bits(&s->pb, 1, 1);
1271

    
1272
    /* dynamic range codes */
1273
    put_bits(&s->pb, 1, 0);
1274

    
1275
    /* channel coupling */
1276
    if (!block_num) {
1277
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
1278
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
1279
    } else {
1280
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1281
    }
1282

    
1283
    /* stereo rematrixing */
1284
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1285
        if (!block_num) {
1286
            /* first block must define rematrixing (rematstr) */
1287
            put_bits(&s->pb, 1, 1);
1288

    
1289
            /* dummy rematrixing rematflg(1:4)=0 */
1290
            for (rbnd = 0; rbnd < 4; rbnd++)
1291
                put_bits(&s->pb, 1, 0);
1292
        } else {
1293
            /* no matrixing (but should be used in the future) */
1294
            put_bits(&s->pb, 1, 0);
1295
        }
1296
    }
1297

    
1298
    /* exponent strategy */
1299
    for (ch = 0; ch < s->fbw_channels; ch++)
1300
        put_bits(&s->pb, 2, block->exp_strategy[ch]);
1301
    if (s->lfe_on)
1302
        put_bits(&s->pb, 1, block->exp_strategy[s->lfe_channel]);
1303

    
1304
    /* bandwidth */
1305
    for (ch = 0; ch < s->fbw_channels; ch++) {
1306
        if (block->exp_strategy[ch] != EXP_REUSE)
1307
            put_bits(&s->pb, 6, s->bandwidth_code[ch]);
1308
    }
1309

    
1310
    /* exponents */
1311
    for (ch = 0; ch < s->channels; ch++) {
1312
        if (block->exp_strategy[ch] == EXP_REUSE)
1313
            continue;
1314

    
1315
        /* DC exponent */
1316
        put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1317

    
1318
        /* exponent groups */
1319
        for (i = 1; i <= block->num_exp_groups[ch]; i++)
1320
            put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1321

    
1322
        /* gain range info */
1323
        if (ch != s->lfe_channel)
1324
            put_bits(&s->pb, 2, 0);
1325
    }
1326

    
1327
    /* bit allocation info */
1328
    baie = (block_num == 0);
1329
    put_bits(&s->pb, 1, baie);
1330
    if (baie) {
1331
        put_bits(&s->pb, 2, s->slow_decay_code);
1332
        put_bits(&s->pb, 2, s->fast_decay_code);
1333
        put_bits(&s->pb, 2, s->slow_gain_code);
1334
        put_bits(&s->pb, 2, s->db_per_bit_code);
1335
        put_bits(&s->pb, 3, s->floor_code);
1336
    }
1337

    
1338
    /* snr offset */
1339
    put_bits(&s->pb, 1, baie);
1340
    if (baie) {
1341
        put_bits(&s->pb, 6, s->coarse_snr_offset);
1342
        for (ch = 0; ch < s->channels; ch++) {
1343
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1344
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1345
        }
1346
    }
1347

    
1348
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1349
    put_bits(&s->pb, 1, 0); /* no data to skip */
1350

    
1351
    /* mantissas */
1352
    for (ch = 0; ch < s->channels; ch++) {
1353
        int b, q;
1354
        for (i = 0; i < s->nb_coefs[ch]; i++) {
1355
            q = block->qmant[ch][i];
1356
            b = block->bap[ch][i];
1357
            switch (b) {
1358
            case 0:                                         break;
1359
            case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
1360
            case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
1361
            case 3:               put_bits(&s->pb,   3, q); break;
1362
            case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
1363
            case 14:              put_bits(&s->pb,  14, q); break;
1364
            case 15:              put_bits(&s->pb,  16, q); break;
1365
            default:              put_bits(&s->pb, b-1, q); break;
1366
            }
1367
        }
1368
    }
1369
}
1370

    
1371

    
1372
/** CRC-16 Polynomial */
1373
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1374

    
1375

    
1376
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1377
{
1378
    unsigned int c;
1379

    
1380
    c = 0;
1381
    while (a) {
1382
        if (a & 1)
1383
            c ^= b;
1384
        a = a >> 1;
1385
        b = b << 1;
1386
        if (b & (1 << 16))
1387
            b ^= poly;
1388
    }
1389
    return c;
1390
}
1391

    
1392

    
1393
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1394
{
1395
    unsigned int r;
1396
    r = 1;
1397
    while (n) {
1398
        if (n & 1)
1399
            r = mul_poly(r, a, poly);
1400
        a = mul_poly(a, a, poly);
1401
        n >>= 1;
1402
    }
1403
    return r;
1404
}
1405

    
1406

    
1407
/**
1408
 * Fill the end of the frame with 0's and compute the two CRCs.
1409
 */
1410
static void output_frame_end(AC3EncodeContext *s)
1411
{
1412
    int frame_size, frame_size_58, pad_bytes, crc1, crc2, crc_inv;
1413
    uint8_t *frame;
1414

    
1415
    frame_size    = s->frame_size;
1416
    frame_size_58 = ((frame_size >> 2) + (frame_size >> 4)) << 1;
1417

    
1418
    /* pad the remainder of the frame with zeros */
1419
    flush_put_bits(&s->pb);
1420
    frame = s->pb.buf;
1421
    pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1422
    assert(pad_bytes >= 0);
1423
    if (pad_bytes > 0)
1424
        memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1425

    
1426
    /* compute crc1 */
1427
    /* this is not so easy because it is at the beginning of the data... */
1428
    crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1429
                             frame + 4, frame_size_58 - 4));
1430
    /* XXX: could precompute crc_inv */
1431
    crc_inv = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
1432
    crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1433
    AV_WB16(frame + 2, crc1);
1434

    
1435
    /* compute crc2 */
1436
    crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1437
                             frame + frame_size_58,
1438
                             frame_size - frame_size_58 - 2));
1439
    AV_WB16(frame + frame_size - 2, crc2);
1440
}
1441

    
1442

    
1443
/**
1444
 * Write the frame to the output bitstream.
1445
 */
1446
static void output_frame(AC3EncodeContext *s,
1447
                         unsigned char *frame)
1448
{
1449
    int blk;
1450

    
1451
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1452

    
1453
    output_frame_header(s);
1454

    
1455
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1456
        output_audio_block(s, blk);
1457

    
1458
    output_frame_end(s);
1459
}
1460

    
1461

    
1462
/**
1463
 * Encode a single AC-3 frame.
1464
 */
1465
static int ac3_encode_frame(AVCodecContext *avctx,
1466
                            unsigned char *frame, int buf_size, void *data)
1467
{
1468
    AC3EncodeContext *s = avctx->priv_data;
1469
    const int16_t *samples = data;
1470
    int ret;
1471

    
1472
    if (s->bit_alloc.sr_code == 1)
1473
        adjust_frame_size(s);
1474

    
1475
    deinterleave_input_samples(s, samples);
1476

    
1477
    apply_mdct(s);
1478

    
1479
    process_exponents(s);
1480

    
1481
    ret = compute_bit_allocation(s);
1482
    if (ret) {
1483
        av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1484
        return ret;
1485
    }
1486

    
1487
    quantize_mantissas(s);
1488

    
1489
    output_frame(s, frame);
1490

    
1491
    return s->frame_size;
1492
}
1493

    
1494

    
1495
/**
1496
 * Finalize encoding and free any memory allocated by the encoder.
1497
 */
1498
static av_cold int ac3_encode_close(AVCodecContext *avctx)
1499
{
1500
    int blk, ch;
1501
    AC3EncodeContext *s = avctx->priv_data;
1502

    
1503
    for (ch = 0; ch < s->channels; ch++)
1504
        av_freep(&s->planar_samples[ch]);
1505
    av_freep(&s->planar_samples);
1506
    av_freep(&s->bap_buffer);
1507
    av_freep(&s->bap1_buffer);
1508
    av_freep(&s->mdct_coef_buffer);
1509
    av_freep(&s->exp_buffer);
1510
    av_freep(&s->encoded_exp_buffer);
1511
    av_freep(&s->grouped_exp_buffer);
1512
    av_freep(&s->psd_buffer);
1513
    av_freep(&s->band_psd_buffer);
1514
    av_freep(&s->mask_buffer);
1515
    av_freep(&s->qmant_buffer);
1516
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1517
        AC3Block *block = &s->blocks[blk];
1518
        av_freep(&block->bap);
1519
        av_freep(&block->mdct_coef);
1520
        av_freep(&block->exp);
1521
        av_freep(&block->encoded_exp);
1522
        av_freep(&block->grouped_exp);
1523
        av_freep(&block->psd);
1524
        av_freep(&block->band_psd);
1525
        av_freep(&block->mask);
1526
        av_freep(&block->qmant);
1527
    }
1528

    
1529
    mdct_end(&s->mdct);
1530

    
1531
    av_freep(&avctx->coded_frame);
1532
    return 0;
1533
}
1534

    
1535

    
1536
/**
1537
 * Set channel information during initialization.
1538
 */
1539
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1540
                                    int64_t *channel_layout)
1541
{
1542
    int ch_layout;
1543

    
1544
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
1545
        return AVERROR(EINVAL);
1546
    if ((uint64_t)*channel_layout > 0x7FF)
1547
        return AVERROR(EINVAL);
1548
    ch_layout = *channel_layout;
1549
    if (!ch_layout)
1550
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1551
    if (av_get_channel_layout_nb_channels(ch_layout) != channels)
1552
        return AVERROR(EINVAL);
1553

    
1554
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1555
    s->channels     = channels;
1556
    s->fbw_channels = channels - s->lfe_on;
1557
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
1558
    if (s->lfe_on)
1559
        ch_layout -= AV_CH_LOW_FREQUENCY;
1560

    
1561
    switch (ch_layout) {
1562
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
1563
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
1564
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
1565
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
1566
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
1567
    case AV_CH_LAYOUT_QUAD:
1568
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
1569
    case AV_CH_LAYOUT_5POINT0:
1570
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
1571
    default:
1572
        return AVERROR(EINVAL);
1573
    }
1574

    
1575
    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1576
    *channel_layout = ch_layout;
1577
    if (s->lfe_on)
1578
        *channel_layout |= AV_CH_LOW_FREQUENCY;
1579

    
1580
    return 0;
1581
}
1582

    
1583

    
1584
static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1585
{
1586
    int i, ret;
1587

    
1588
    /* validate channel layout */
1589
    if (!avctx->channel_layout) {
1590
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1591
                                      "encoder will guess the layout, but it "
1592
                                      "might be incorrect.\n");
1593
    }
1594
    ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1595
    if (ret) {
1596
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1597
        return ret;
1598
    }
1599

    
1600
    /* validate sample rate */
1601
    for (i = 0; i < 9; i++) {
1602
        if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
1603
            break;
1604
    }
1605
    if (i == 9) {
1606
        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1607
        return AVERROR(EINVAL);
1608
    }
1609
    s->sample_rate        = avctx->sample_rate;
1610
    s->bit_alloc.sr_shift = i % 3;
1611
    s->bit_alloc.sr_code  = i / 3;
1612

    
1613
    /* validate bit rate */
1614
    for (i = 0; i < 19; i++) {
1615
        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
1616
            break;
1617
    }
1618
    if (i == 19) {
1619
        av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
1620
        return AVERROR(EINVAL);
1621
    }
1622
    s->bit_rate        = avctx->bit_rate;
1623
    s->frame_size_code = i << 1;
1624

    
1625
    return 0;
1626
}
1627

    
1628

    
1629
/**
1630
 * Set bandwidth for all channels.
1631
 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
1632
 * default value will be used.
1633
 */
1634
static av_cold void set_bandwidth(AC3EncodeContext *s, int cutoff)
1635
{
1636
    int ch, bw_code;
1637

    
1638
    if (cutoff) {
1639
        /* calculate bandwidth based on user-specified cutoff frequency */
1640
        int fbw_coeffs;
1641
        cutoff         = av_clip(cutoff, 1, s->sample_rate >> 1);
1642
        fbw_coeffs     = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
1643
        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
1644
    } else {
1645
        /* use default bandwidth setting */
1646
        /* XXX: should compute the bandwidth according to the frame
1647
           size, so that we avoid annoying high frequency artifacts */
1648
        bw_code = 50;
1649
    }
1650

    
1651
    /* set number of coefficients for each channel */
1652
    for (ch = 0; ch < s->fbw_channels; ch++) {
1653
        s->bandwidth_code[ch] = bw_code;
1654
        s->nb_coefs[ch]       = bw_code * 3 + 73;
1655
    }
1656
    if (s->lfe_on)
1657
        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
1658
}
1659

    
1660

    
1661
static av_cold int allocate_buffers(AVCodecContext *avctx)
1662
{
1663
    int blk, ch;
1664
    AC3EncodeContext *s = avctx->priv_data;
1665

    
1666
    FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
1667
                     alloc_fail);
1668
    for (ch = 0; ch < s->channels; ch++) {
1669
        FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
1670
                          (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
1671
                          alloc_fail);
1672
    }
1673
    FF_ALLOC_OR_GOTO(avctx, s->bap_buffer,  AC3_MAX_BLOCKS * s->channels *
1674
                     AC3_MAX_COEFS * sizeof(*s->bap_buffer),  alloc_fail);
1675
    FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
1676
                     AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
1677
    FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
1678
                     AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
1679
    FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
1680
                     AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
1681
    FF_ALLOC_OR_GOTO(avctx, s->encoded_exp_buffer, AC3_MAX_BLOCKS * s->channels *
1682
                     AC3_MAX_COEFS * sizeof(*s->encoded_exp_buffer), alloc_fail);
1683
    FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
1684
                     128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
1685
    FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
1686
                     AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
1687
    FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
1688
                     64 * sizeof(*s->band_psd_buffer), alloc_fail);
1689
    FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
1690
                     64 * sizeof(*s->mask_buffer), alloc_fail);
1691
    FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
1692
                     AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
1693
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1694
        AC3Block *block = &s->blocks[blk];
1695
        FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
1696
                         alloc_fail);
1697
        FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
1698
                          alloc_fail);
1699
        FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
1700
                          alloc_fail);
1701
        FF_ALLOCZ_OR_GOTO(avctx, block->encoded_exp, s->channels * sizeof(*block->encoded_exp),
1702
                          alloc_fail);
1703
        FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
1704
                          alloc_fail);
1705
        FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
1706
                          alloc_fail);
1707
        FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
1708
                          alloc_fail);
1709
        FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
1710
                          alloc_fail);
1711
        FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
1712
                          alloc_fail);
1713

    
1714
        for (ch = 0; ch < s->channels; ch++) {
1715
            block->bap[ch]         = &s->bap_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1716
            block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (blk * s->channels + ch)];
1717
            block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1718
            block->encoded_exp[ch] = &s->encoded_exp_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
1719
            block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * s->channels + ch)];
1720
            block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1721
            block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * s->channels + ch)];
1722
            block->mask[ch]        = &s->mask_buffer       [64            * (blk * s->channels + ch)];
1723
            block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * s->channels + ch)];
1724
        }
1725
    }
1726

    
1727
    return 0;
1728
alloc_fail:
1729
    return AVERROR(ENOMEM);
1730
}
1731

    
1732

    
1733
/**
1734
 * Initialize the encoder.
1735
 */
1736
static av_cold int ac3_encode_init(AVCodecContext *avctx)
1737
{
1738
    AC3EncodeContext *s = avctx->priv_data;
1739
    int ret;
1740

    
1741
    avctx->frame_size = AC3_FRAME_SIZE;
1742

    
1743
    ac3_common_init();
1744

    
1745
    ret = validate_options(avctx, s);
1746
    if (ret)
1747
        return ret;
1748

    
1749
    s->bitstream_id   = 8 + s->bit_alloc.sr_shift;
1750
    s->bitstream_mode = 0; /* complete main audio service */
1751

    
1752
    s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
1753
    s->bits_written    = 0;
1754
    s->samples_written = 0;
1755
    s->frame_size      = s->frame_size_min;
1756

    
1757
    set_bandwidth(s, avctx->cutoff);
1758

    
1759
    bit_alloc_init(s);
1760

    
1761
    s->mdct.avctx = avctx;
1762
    ret = mdct_init(&s->mdct, 9);
1763
    if (ret) {
1764
        goto init_fail;
1765
    }
1766

    
1767
    ret = allocate_buffers(avctx);
1768
    if (ret) {
1769
        goto init_fail;
1770
    }
1771

    
1772
    avctx->coded_frame= avcodec_alloc_frame();
1773

    
1774
    return 0;
1775
init_fail:
1776
    ac3_encode_close(avctx);
1777
    return ret;
1778
}
1779

    
1780

    
1781
#ifdef TEST
1782
/*************************************************************************/
1783
/* TEST */
1784

    
1785
#include "libavutil/lfg.h"
1786

    
1787
#define FN (MDCT_SAMPLES/4)
1788

    
1789

    
1790
static void fft_test(AVLFG *lfg)
1791
{
1792
    IComplex in[FN], in1[FN];
1793
    int k, n, i;
1794
    float sum_re, sum_im, a;
1795

    
1796
    for (i = 0; i < FN; i++) {
1797
        in[i].re = av_lfg_get(lfg) % 65535 - 32767;
1798
        in[i].im = av_lfg_get(lfg) % 65535 - 32767;
1799
        in1[i]   = in[i];
1800
    }
1801
    fft(in, 7);
1802

    
1803
    /* do it by hand */
1804
    for (k = 0; k < FN; k++) {
1805
        sum_re = 0;
1806
        sum_im = 0;
1807
        for (n = 0; n < FN; n++) {
1808
            a = -2 * M_PI * (n * k) / FN;
1809
            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1810
            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1811
        }
1812
        av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
1813
               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1814
    }
1815
}
1816

    
1817

    
1818
static void mdct_test(AVLFG *lfg)
1819
{
1820
    int16_t input[MDCT_SAMPLES];
1821
    int32_t output[AC3_MAX_COEFS];
1822
    float input1[MDCT_SAMPLES];
1823
    float output1[AC3_MAX_COEFS];
1824
    float s, a, err, e, emax;
1825
    int i, k, n;
1826

    
1827
    for (i = 0; i < MDCT_SAMPLES; i++) {
1828
        input[i]  = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
1829
        input1[i] = input[i];
1830
    }
1831

    
1832
    mdct512(output, input);
1833

    
1834
    /* do it by hand */
1835
    for (k = 0; k < AC3_MAX_COEFS; k++) {
1836
        s = 0;
1837
        for (n = 0; n < MDCT_SAMPLES; n++) {
1838
            a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
1839
            s += input1[n] * cos(a);
1840
        }
1841
        output1[k] = -2 * s / MDCT_SAMPLES;
1842
    }
1843

    
1844
    err  = 0;
1845
    emax = 0;
1846
    for (i = 0; i < AC3_MAX_COEFS; i++) {
1847
        av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
1848
        e = output[i] - output1[i];
1849
        if (e > emax)
1850
            emax = e;
1851
        err += e * e;
1852
    }
1853
    av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
1854
}
1855

    
1856

    
1857
int main(void)
1858
{
1859
    AVLFG lfg;
1860

    
1861
    av_log_set_level(AV_LOG_DEBUG);
1862
    mdct_init(9);
1863

    
1864
    fft_test(&lfg);
1865
    mdct_test(&lfg);
1866

    
1867
    return 0;
1868
}
1869
#endif /* TEST */
1870

    
1871

    
1872
AVCodec ac3_encoder = {
1873
    "ac3",
1874
    AVMEDIA_TYPE_AUDIO,
1875
    CODEC_ID_AC3,
1876
    sizeof(AC3EncodeContext),
1877
    ac3_encode_init,
1878
    ac3_encode_frame,
1879
    ac3_encode_close,
1880
    NULL,
1881
    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1882
    .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1883
    .channel_layouts = (const int64_t[]){
1884
        AV_CH_LAYOUT_MONO,
1885
        AV_CH_LAYOUT_STEREO,
1886
        AV_CH_LAYOUT_2_1,
1887
        AV_CH_LAYOUT_SURROUND,
1888
        AV_CH_LAYOUT_2_2,
1889
        AV_CH_LAYOUT_QUAD,
1890
        AV_CH_LAYOUT_4POINT0,
1891
        AV_CH_LAYOUT_5POINT0,
1892
        AV_CH_LAYOUT_5POINT0_BACK,
1893
       (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
1894
       (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
1895
       (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
1896
       (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1897
       (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
1898
       (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
1899
       (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
1900
        AV_CH_LAYOUT_5POINT1,
1901
        AV_CH_LAYOUT_5POINT1_BACK,
1902
        0 },
1903
};