Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ 9d853336

History | View | Annotate | Download (56.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
/**
59
 * Data for a single audio block.
60
 */
61
typedef struct AC3Block {
62
    uint8_t  **bap;                             ///< bit allocation pointers (bap)
63
    int32_t  **mdct_coef;                       ///< MDCT coefficients
64
    uint8_t  **exp;                             ///< original exponents
65
    uint8_t  **encoded_exp;                     ///< encoded exponents
66
    uint8_t  **grouped_exp;                     ///< grouped exponents
67
    int16_t  **psd;                             ///< psd per frequency bin
68
    int16_t  **band_psd;                        ///< psd per critical band
69
    int16_t  **mask;                            ///< masking curve
70
    uint16_t **qmant;                           ///< quantized mantissas
71
    uint8_t  num_exp_groups[AC3_MAX_CHANNELS];  ///< number of exponent groups
72
    uint8_t  exp_strategy[AC3_MAX_CHANNELS];    ///< exponent strategies
73
    int8_t   exp_shift[AC3_MAX_CHANNELS];       ///< exponent shift values
74
} AC3Block;
75

    
76
/**
77
 * AC-3 encoder private context.
78
 */
79
typedef struct AC3EncodeContext {
80
    PutBitContext pb;                       ///< bitstream writer context
81

    
82
    AC3Block blocks[AC3_MAX_BLOCKS];        ///< per-block info
83

    
84
    int bitstream_id;                       ///< bitstream id                           (bsid)
85
    int bitstream_mode;                     ///< bitstream mode                         (bsmod)
86

    
87
    int bit_rate;                           ///< target bit rate, in bits-per-second
88
    int sample_rate;                        ///< sampling frequency, in Hz
89

    
90
    int frame_size_min;                     ///< minimum frame size in case rounding is necessary
91
    int frame_size;                         ///< current frame size in bytes
92
    int frame_size_code;                    ///< frame size code                        (frmsizecod)
93
    int bits_written;                       ///< bit count    (used to avg. bitrate)
94
    int samples_written;                    ///< sample count (used to avg. bitrate)
95

    
96
    int fbw_channels;                       ///< number of full-bandwidth channels      (nfchans)
97
    int channels;                           ///< total number of channels               (nchans)
98
    int lfe_on;                             ///< indicates if there is an LFE channel   (lfeon)
99
    int lfe_channel;                        ///< channel index of the LFE channel
100
    int channel_mode;                       ///< channel mode                           (acmod)
101
    const uint8_t *channel_map;             ///< channel map used to reorder channels
102

    
103
    int bandwidth_code[AC3_MAX_CHANNELS];   ///< bandwidth code (0 to 60)               (chbwcod)
104
    int nb_coefs[AC3_MAX_CHANNELS];
105

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

    
119
    /* mantissa encoding */
120
    int mant1_cnt, mant2_cnt, mant4_cnt;    ///< mantissa counts for bap=1,2,4
121
    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
122

    
123
    int16_t **planar_samples;
124
    uint8_t *bap_buffer;
125
    uint8_t *bap1_buffer;
126
    int32_t *mdct_coef_buffer;
127
    uint8_t *exp_buffer;
128
    uint8_t *encoded_exp_buffer;
129
    uint8_t *grouped_exp_buffer;
130
    int16_t *psd_buffer;
131
    int16_t *band_psd_buffer;
132
    int16_t *mask_buffer;
133
    uint16_t *qmant_buffer;
134

    
135
    DECLARE_ALIGNED(16, int16_t, windowed_samples)[AC3_WINDOW_SIZE];
136
} AC3EncodeContext;
137

    
138

    
139
/** MDCT and FFT tables */
140
static int16_t costab[64];
141
static int16_t sintab[64];
142
static int16_t xcos1[128];
143
static int16_t xsin1[128];
144

    
145

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

    
162

    
163
/**
164
 * Deinterleave input samples.
165
 * Channels are reordered from FFmpeg's default order to AC-3 order.
166
 */
167
static void deinterleave_input_samples(AC3EncodeContext *s,
168
                                       const int16_t *samples)
169
{
170
    int ch, i;
171

    
172
    /* deinterleave and remap input samples */
173
    for (ch = 0; ch < s->channels; ch++) {
174
        const int16_t *sptr;
175
        int sinc;
176

    
177
        /* copy last 256 samples of previous frame to the start of the current frame */
178
        memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
179
               AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
180

    
181
        /* deinterleave */
182
        sinc = s->channels;
183
        sptr = samples + s->channel_map[ch];
184
        for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
185
            s->planar_samples[ch][i] = *sptr;
186
            sptr += sinc;
187
        }
188
    }
189
}
190

    
191

    
192
/**
193
 * Initialize FFT tables.
194
 * @param ln log2(FFT size)
195
 */
196
static av_cold void fft_init(int ln)
197
{
198
    int i, n, n2;
199
    float alpha;
200

    
201
    n  = 1 << ln;
202
    n2 = n >> 1;
203

    
204
    for (i = 0; i < n2; i++) {
205
        alpha     = 2.0 * M_PI * i / n;
206
        costab[i] = FIX15(cos(alpha));
207
        sintab[i] = FIX15(sin(alpha));
208
    }
209
}
210

    
211

    
212
/**
213
 * Initialize MDCT tables.
214
 * @param nbits log2(MDCT size)
215
 */
216
static av_cold void mdct_init(int nbits)
217
{
218
    int i, n, n4;
219

    
220
    n  = 1 << nbits;
221
    n4 = n >> 2;
222

    
223
    fft_init(nbits - 2);
224

    
225
    for (i = 0; i < n4; i++) {
226
        float alpha = 2.0 * M_PI * (i + 1.0 / 8.0) / n;
227
        xcos1[i] = FIX15(-cos(alpha));
228
        xsin1[i] = FIX15(-sin(alpha));
229
    }
230
}
231

    
232

    
233
/** Butterfly op */
234
#define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1)  \
235
{                                                       \
236
  int ax, ay, bx, by;                                   \
237
  bx  = pre1;                                           \
238
  by  = pim1;                                           \
239
  ax  = qre1;                                           \
240
  ay  = qim1;                                           \
241
  pre = (bx + ax) >> 1;                                 \
242
  pim = (by + ay) >> 1;                                 \
243
  qre = (bx - ax) >> 1;                                 \
244
  qim = (by - ay) >> 1;                                 \
245
}
246

    
247

    
248
/** Complex multiply */
249
#define CMUL(pre, pim, are, aim, bre, bim)              \
250
{                                                       \
251
   pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;     \
252
   pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;     \
253
}
254

    
255

    
256
/**
257
 * Calculate a 2^n point complex FFT on 2^ln points.
258
 * @param z  complex input/output samples
259
 * @param ln log2(FFT size)
260
 */
261
static void fft(IComplex *z, int ln)
262
{
263
    int j, l, np, np2;
264
    int nblocks, nloops;
265
    register IComplex *p,*q;
266
    int tmp_re, tmp_im;
267

    
268
    np = 1 << ln;
269

    
270
    /* reverse */
271
    for (j = 0; j < np; j++) {
272
        int k = av_reverse[j] >> (8 - ln);
273
        if (k < j)
274
            FFSWAP(IComplex, z[k], z[j]);
275
    }
276

    
277
    /* pass 0 */
278

    
279
    p = &z[0];
280
    j = np >> 1;
281
    do {
282
        BF(p[0].re, p[0].im, p[1].re, p[1].im,
283
           p[0].re, p[0].im, p[1].re, p[1].im);
284
        p += 2;
285
    } while (--j);
286

    
287
    /* pass 1 */
288

    
289
    p = &z[0];
290
    j = np >> 2;
291
    do {
292
        BF(p[0].re, p[0].im, p[2].re,  p[2].im,
293
           p[0].re, p[0].im, p[2].re,  p[2].im);
294
        BF(p[1].re, p[1].im, p[3].re,  p[3].im,
295
           p[1].re, p[1].im, p[3].im, -p[3].re);
296
        p+=4;
297
    } while (--j);
298

    
299
    /* pass 2 .. ln-1 */
300

    
301
    nblocks = np >> 3;
302
    nloops  =  1 << 2;
303
    np2     = np >> 1;
304
    do {
305
        p = z;
306
        q = z + nloops;
307
        for (j = 0; j < nblocks; j++) {
308
            BF(p->re, p->im, q->re, q->im,
309
               p->re, p->im, q->re, q->im);
310
            p++;
311
            q++;
312
            for(l = nblocks; l < np2; l += nblocks) {
313
                CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
314
                BF(p->re, p->im, q->re,  q->im,
315
                   p->re, p->im, tmp_re, tmp_im);
316
                p++;
317
                q++;
318
            }
319
            p += nloops;
320
            q += nloops;
321
        }
322
        nblocks = nblocks >> 1;
323
        nloops  = nloops  << 1;
324
    } while (nblocks);
325
}
326

    
327

    
328
/**
329
 * Calculate a 512-point MDCT
330
 * @param out 256 output frequency coefficients
331
 * @param in  512 windowed input audio samples
332
 */
333
static void mdct512(int32_t *out, int16_t *in)
334
{
335
    int i, re, im, re1, im1;
336
    int16_t rot[MDCT_SAMPLES];
337
    IComplex x[MDCT_SAMPLES/4];
338

    
339
    /* shift to simplify computations */
340
    for (i = 0; i < MDCT_SAMPLES/4; i++)
341
        rot[i] = -in[i + 3*MDCT_SAMPLES/4];
342
    memcpy(&rot[MDCT_SAMPLES/4], &in[0], 3*MDCT_SAMPLES/4*sizeof(*in));
343

    
344
    /* pre rotation */
345
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
346
        re =  ((int)rot[               2*i] - (int)rot[MDCT_SAMPLES  -1-2*i]) >> 1;
347
        im = -((int)rot[MDCT_SAMPLES/2+2*i] - (int)rot[MDCT_SAMPLES/2-1-2*i]) >> 1;
348
        CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
349
    }
350

    
351
    fft(x, MDCT_NBITS - 2);
352

    
353
    /* post rotation */
354
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
355
        re = x[i].re;
356
        im = x[i].im;
357
        CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
358
        out[                 2*i] = im1;
359
        out[MDCT_SAMPLES/2-1-2*i] = re1;
360
    }
361
}
362

    
363

    
364
/**
365
 * Apply KBD window to input samples prior to MDCT.
366
 */
367
static void apply_window(int16_t *output, const int16_t *input,
368
                         const int16_t *window, int n)
369
{
370
    int i;
371
    int n2 = n >> 1;
372

    
373
    for (i = 0; i < n2; i++) {
374
        output[i]     = MUL16(input[i],     window[i]) >> 15;
375
        output[n-i-1] = MUL16(input[n-i-1], window[i]) >> 15;
376
    }
377
}
378

    
379

    
380
/**
381
 * Calculate the log2() of the maximum absolute value in an array.
382
 * @param tab input array
383
 * @param n   number of values in the array
384
 * @return    log2(max(abs(tab[])))
385
 */
386
static int log2_tab(int16_t *tab, int n)
387
{
388
    int i, v;
389

    
390
    v = 0;
391
    for (i = 0; i < n; i++)
392
        v |= abs(tab[i]);
393

    
394
    return av_log2(v);
395
}
396

    
397

    
398
/**
399
 * Left-shift each value in an array by a specified amount.
400
 * @param tab    input array
401
 * @param n      number of values in the array
402
 * @param lshift left shift amount. a negative value means right shift.
403
 */
404
static void lshift_tab(int16_t *tab, int n, int lshift)
405
{
406
    int i;
407

    
408
    if (lshift > 0) {
409
        for (i = 0; i < n; i++)
410
            tab[i] <<= lshift;
411
    } else if (lshift < 0) {
412
        lshift = -lshift;
413
        for (i = 0; i < n; i++)
414
            tab[i] >>= lshift;
415
    }
416
}
417

    
418

    
419
/**
420
 * Normalize the input samples to use the maximum available precision.
421
 * This assumes signed 16-bit input samples. Exponents are reduced by 9 to
422
 * match the 24-bit internal precision for MDCT coefficients.
423
 *
424
 * @return exponent shift
425
 */
426
static int normalize_samples(AC3EncodeContext *s)
427
{
428
    int v = 14 - log2_tab(s->windowed_samples, AC3_WINDOW_SIZE);
429
    v = FFMAX(0, v);
430
    lshift_tab(s->windowed_samples, AC3_WINDOW_SIZE, v);
431
    return v - 9;
432
}
433

    
434

    
435
/**
436
 * Apply the MDCT to input samples to generate frequency coefficients.
437
 * This applies the KBD window and normalizes the input to reduce precision
438
 * loss due to fixed-point calculations.
439
 */
440
static void apply_mdct(AC3EncodeContext *s)
441
{
442
    int blk, ch;
443

    
444
    for (ch = 0; ch < s->channels; ch++) {
445
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
446
            AC3Block *block = &s->blocks[blk];
447
            const int16_t *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
448

    
449
            apply_window(s->windowed_samples, input_samples, ff_ac3_window, AC3_WINDOW_SIZE);
450

    
451
            block->exp_shift[ch] = normalize_samples(s);
452

    
453
            mdct512(block->mdct_coef[ch], s->windowed_samples);
454
        }
455
    }
456
}
457

    
458

    
459
/**
460
 * Extract exponents from the MDCT coefficients.
461
 * This takes into account the normalization that was done to the input samples
462
 * by adjusting the exponents by the exponent shift values.
463
 */
464
static void extract_exponents(AC3EncodeContext *s)
465
{
466
    int blk, ch, i;
467

    
468
    for (ch = 0; ch < s->channels; ch++) {
469
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
470
            AC3Block *block = &s->blocks[blk];
471
            for (i = 0; i < AC3_MAX_COEFS; i++) {
472
                int e;
473
                int v = abs(block->mdct_coef[ch][i]);
474
                if (v == 0)
475
                    e = 24;
476
                else {
477
                    e = 23 - av_log2(v) + block->exp_shift[ch];
478
                    if (e >= 24) {
479
                        e = 24;
480
                        block->mdct_coef[ch][i] = 0;
481
                    }
482
                }
483
                block->exp[ch][i] = e;
484
            }
485
        }
486
    }
487
}
488

    
489

    
490
/**
491
 * Calculate the sum of absolute differences (SAD) between 2 sets of exponents.
492
 */
493
static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
494
{
495
    int sum, i;
496
    sum = 0;
497
    for (i = 0; i < n; i++)
498
        sum += abs(exp1[i] - exp2[i]);
499
    return sum;
500
}
501

    
502

    
503
/**
504
 * Exponent Difference Threshold.
505
 * New exponents are sent if their SAD exceed this number.
506
 */
507
#define EXP_DIFF_THRESHOLD 1000
508

    
509

    
510
/**
511
 * Calculate exponent strategies for all blocks in a single channel.
512
 */
513
static void compute_exp_strategy_ch(uint8_t *exp_strategy, uint8_t **exp)
514
{
515
    int blk, blk1;
516
    int exp_diff;
517

    
518
    /* estimate if the exponent variation & decide if they should be
519
       reused in the next frame */
520
    exp_strategy[0] = EXP_NEW;
521
    for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
522
        exp_diff = calc_exp_diff(exp[blk], exp[blk-1], AC3_MAX_COEFS);
523
        if (exp_diff > EXP_DIFF_THRESHOLD)
524
            exp_strategy[blk] = EXP_NEW;
525
        else
526
            exp_strategy[blk] = EXP_REUSE;
527
    }
528

    
529
    /* now select the encoding strategy type : if exponents are often
530
       recoded, we use a coarse encoding */
531
    blk = 0;
532
    while (blk < AC3_MAX_BLOCKS) {
533
        blk1 = blk + 1;
534
        while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
535
            blk1++;
536
        switch (blk1 - blk) {
537
        case 1:  exp_strategy[blk] = EXP_D45; break;
538
        case 2:
539
        case 3:  exp_strategy[blk] = EXP_D25; break;
540
        default: exp_strategy[blk] = EXP_D15; break;
541
        }
542
        blk = blk1;
543
    }
544
}
545

    
546

    
547
/**
548
 * Calculate exponent strategies for all channels.
549
 * Array arrangement is reversed to simplify the per-channel calculation.
550
 */
551
static void compute_exp_strategy(AC3EncodeContext *s)
552
{
553
    uint8_t *exp1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
554
    uint8_t exp_str1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
555
    int ch, blk;
556

    
557
    for (ch = 0; ch < s->fbw_channels; ch++) {
558
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
559
            exp1[ch][blk]     = s->blocks[blk].exp[ch];
560
            exp_str1[ch][blk] = s->blocks[blk].exp_strategy[ch];
561
        }
562

    
563
        compute_exp_strategy_ch(exp_str1[ch], exp1[ch]);
564

    
565
        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
566
            s->blocks[blk].exp_strategy[ch] = exp_str1[ch][blk];
567
    }
568
    if (s->lfe_on) {
569
        ch = s->lfe_channel;
570
        s->blocks[0].exp_strategy[ch] = EXP_D15;
571
        for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
572
            s->blocks[blk].exp_strategy[ch] = EXP_REUSE;
573
    }
574
}
575

    
576

    
577
/**
578
 * Set each encoded exponent in a block to the minimum of itself and the
579
 * exponent in the same frequency bin of a following block.
580
 * exp[i] = min(exp[i], exp1[i]
581
 */
582
static void exponent_min(uint8_t *exp, uint8_t *exp1, int n)
583
{
584
    int i;
585
    for (i = 0; i < n; i++) {
586
        if (exp1[i] < exp[i])
587
            exp[i] = exp1[i];
588
    }
589
}
590

    
591

    
592
/**
593
 * Update the exponents so that they are the ones the decoder will decode.
594
 */
595
static void encode_exponents_blk_ch(uint8_t *encoded_exp, uint8_t *exp,
596
                                    int nb_exps, int exp_strategy,
597
                                    uint8_t *num_exp_groups)
598
{
599
    int group_size, nb_groups, i, j, k, exp_min;
600
    uint8_t exp1[AC3_MAX_COEFS];
601

    
602
    group_size = exp_strategy + (exp_strategy == EXP_D45);
603
    *num_exp_groups = (nb_exps + (group_size * 3) - 4) / (3 * group_size);
604
    nb_groups = *num_exp_groups * 3;
605

    
606
    /* for each group, compute the minimum exponent */
607
    exp1[0] = exp[0]; /* DC exponent is handled separately */
608
    k = 1;
609
    for (i = 1; i <= nb_groups; i++) {
610
        exp_min = exp[k];
611
        assert(exp_min >= 0 && exp_min <= 24);
612
        for (j = 1; j < group_size; j++) {
613
            if (exp[k+j] < exp_min)
614
                exp_min = exp[k+j];
615
        }
616
        exp1[i] = exp_min;
617
        k += group_size;
618
    }
619

    
620
    /* constraint for DC exponent */
621
    if (exp1[0] > 15)
622
        exp1[0] = 15;
623

    
624
    /* decrease the delta between each groups to within 2 so that they can be
625
       differentially encoded */
626
    for (i = 1; i <= nb_groups; i++)
627
        exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
628
    for (i = nb_groups-1; i >= 0; i--)
629
        exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
630

    
631
    /* now we have the exponent values the decoder will see */
632
    encoded_exp[0] = exp1[0];
633
    k = 1;
634
    for (i = 1; i <= nb_groups; i++) {
635
        for (j = 0; j < group_size; j++)
636
            encoded_exp[k+j] = exp1[i];
637
        k += group_size;
638
    }
639
}
640

    
641

    
642
/**
643
 * Encode exponents from original extracted form to what the decoder will see.
644
 * This copies and groups exponents based on exponent strategy and reduces
645
 * deltas between adjacent exponent groups so that they can be differentially
646
 * encoded.
647
 */
648
static void encode_exponents(AC3EncodeContext *s)
649
{
650
    int blk, blk1, blk2, ch;
651
    AC3Block *block, *block1, *block2;
652

    
653
    for (ch = 0; ch < s->channels; ch++) {
654
        blk = 0;
655
        block = &s->blocks[0];
656
        while (blk < AC3_MAX_BLOCKS) {
657
            blk1 = blk + 1;
658
            block1 = block + 1;
659
            /* for the EXP_REUSE case we select the min of the exponents */
660
            while (blk1 < AC3_MAX_BLOCKS && block1->exp_strategy[ch] == EXP_REUSE) {
661
                exponent_min(block->exp[ch], block1->exp[ch], s->nb_coefs[ch]);
662
                blk1++;
663
                block1++;
664
            }
665
            encode_exponents_blk_ch(block->encoded_exp[ch],
666
                                    block->exp[ch], s->nb_coefs[ch],
667
                                    block->exp_strategy[ch],
668
                                    &block->num_exp_groups[ch]);
669
            /* copy encoded exponents for reuse case */
670
            block2 = block + 1;
671
            for (blk2 = blk+1; blk2 < blk1; blk2++, block2++) {
672
                memcpy(block2->encoded_exp[ch], block->encoded_exp[ch],
673
                       s->nb_coefs[ch] * sizeof(uint8_t));
674
            }
675
            blk = blk1;
676
            block = block1;
677
        }
678
    }
679
}
680

    
681

    
682
/**
683
 * Group exponents.
684
 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
685
 * varies depending on exponent strategy and bandwidth.
686
 */
687
static void group_exponents(AC3EncodeContext *s)
688
{
689
    int blk, ch, i;
690
    int group_size, bit_count;
691
    uint8_t *p;
692
    int delta0, delta1, delta2;
693
    int exp0, exp1;
694

    
695
    bit_count = 0;
696
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
697
        AC3Block *block = &s->blocks[blk];
698
        for (ch = 0; ch < s->channels; ch++) {
699
            if (block->exp_strategy[ch] == EXP_REUSE) {
700
                block->num_exp_groups[ch] = 0;
701
                continue;
702
            }
703
            group_size = block->exp_strategy[ch] + (block->exp_strategy[ch] == EXP_D45);
704
            bit_count += 4 + (block->num_exp_groups[ch] * 7);
705
            p = block->encoded_exp[ch];
706

    
707
            /* DC exponent */
708
            exp1 = *p++;
709
            block->grouped_exp[ch][0] = exp1;
710

    
711
            /* remaining exponents are delta encoded */
712
            for (i = 1; i <= block->num_exp_groups[ch]; i++) {
713
                /* merge three delta in one code */
714
                exp0   = exp1;
715
                exp1   = p[0];
716
                p     += group_size;
717
                delta0 = exp1 - exp0 + 2;
718

    
719
                exp0   = exp1;
720
                exp1   = p[0];
721
                p     += group_size;
722
                delta1 = exp1 - exp0 + 2;
723

    
724
                exp0   = exp1;
725
                exp1   = p[0];
726
                p     += group_size;
727
                delta2 = exp1 - exp0 + 2;
728

    
729
                block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
730
            }
731
        }
732
    }
733

    
734
    s->exponent_bits = bit_count;
735
}
736

    
737

    
738
/**
739
 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
740
 * Extract exponents from MDCT coefficients, calculate exponent strategies,
741
 * and encode final exponents.
742
 */
743
static void process_exponents(AC3EncodeContext *s)
744
{
745
    extract_exponents(s);
746

    
747
    compute_exp_strategy(s);
748

    
749
    encode_exponents(s);
750

    
751
    group_exponents(s);
752
}
753

    
754

    
755
/**
756
 * Initialize bit allocation.
757
 * Set default parameter codes and calculate parameter values.
758
 */
759
static void bit_alloc_init(AC3EncodeContext *s)
760
{
761
    int ch;
762

    
763
    /* init default parameters */
764
    s->slow_decay_code = 2;
765
    s->fast_decay_code = 1;
766
    s->slow_gain_code  = 1;
767
    s->db_per_bit_code = 2;
768
    s->floor_code      = 4;
769
    for (ch = 0; ch < s->channels; ch++)
770
        s->fast_gain_code[ch] = 4;
771

    
772
    /* initial snr offset */
773
    s->coarse_snr_offset = 40;
774

    
775
    /* compute real values */
776
    /* currently none of these values change during encoding, so we can just
777
       set them once at initialization */
778
    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
779
    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
780
    s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
781
    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
782
    s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
783
}
784

    
785

    
786
/**
787
 * Count the bits used to encode the frame, minus exponents and mantissas.
788
 */
789
static void count_frame_bits(AC3EncodeContext *s)
790
{
791
    static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
792
    int blk, ch;
793
    int frame_bits;
794

    
795
    /* header size */
796
    frame_bits = 65;
797
    frame_bits += frame_bits_inc[s->channel_mode];
798

    
799
    /* audio blocks */
800
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
801
        frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
802
        if (s->channel_mode == AC3_CHMODE_STEREO) {
803
            frame_bits++; /* rematstr */
804
            if (!blk)
805
                frame_bits += 4;
806
        }
807
        frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
808
        if (s->lfe_on)
809
            frame_bits++; /* lfeexpstr */
810
        for (ch = 0; ch < s->fbw_channels; ch++) {
811
            if (s->blocks[blk].exp_strategy[ch] != EXP_REUSE)
812
                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
813
        }
814
        frame_bits++; /* baie */
815
        frame_bits++; /* snr */
816
        frame_bits += 2; /* delta / skip */
817
    }
818
    frame_bits++; /* cplinu for block 0 */
819
    /* bit alloc info */
820
    /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
821
    /* csnroffset[6] */
822
    /* (fsnoffset[4] + fgaincod[4]) * c */
823
    frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
824

    
825
    /* auxdatae, crcrsv */
826
    frame_bits += 2;
827

    
828
    /* CRC */
829
    frame_bits += 16;
830

    
831
    s->frame_bits = frame_bits;
832
}
833

    
834

    
835
/**
836
 * Calculate the number of bits needed to encode a set of mantissas.
837
 */
838
static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *bap, int nb_coefs)
839
{
840
    int bits, b, i;
841

    
842
    bits = 0;
843
    for (i = 0; i < nb_coefs; i++) {
844
        b = bap[i];
845
        switch (b) {
846
        case 0:
847
            /* bap=0 mantissas are not encoded */
848
            break;
849
        case 1:
850
            /* 3 mantissas in 5 bits */
851
            if (s->mant1_cnt == 0)
852
                bits += 5;
853
            if (++s->mant1_cnt == 3)
854
                s->mant1_cnt = 0;
855
            break;
856
        case 2:
857
            /* 3 mantissas in 7 bits */
858
            if (s->mant2_cnt == 0)
859
                bits += 7;
860
            if (++s->mant2_cnt == 3)
861
                s->mant2_cnt = 0;
862
            break;
863
        case 3:
864
            bits += 3;
865
            break;
866
        case 4:
867
            /* 2 mantissas in 7 bits */
868
            if (s->mant4_cnt == 0)
869
                bits += 7;
870
            if (++s->mant4_cnt == 2)
871
                s->mant4_cnt = 0;
872
            break;
873
        case 14:
874
            bits += 14;
875
            break;
876
        case 15:
877
            bits += 16;
878
            break;
879
        default:
880
            bits += b - 1;
881
            break;
882
        }
883
    }
884
    return bits;
885
}
886

    
887

    
888
/**
889
 * Calculate masking curve based on the final exponents.
890
 * Also calculate the power spectral densities to use in future calculations.
891
 */
892
static void bit_alloc_masking(AC3EncodeContext *s)
893
{
894
    int blk, ch;
895

    
896
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
897
        AC3Block *block = &s->blocks[blk];
898
        for (ch = 0; ch < s->channels; ch++) {
899
            if (block->exp_strategy[ch] == EXP_REUSE) {
900
                AC3Block *block1 = &s->blocks[blk-1];
901
                memcpy(block->psd[ch],  block1->psd[ch],  AC3_MAX_COEFS*sizeof(block->psd[0][0]));
902
                memcpy(block->mask[ch], block1->mask[ch], AC3_CRITICAL_BANDS*sizeof(block->mask[0][0]));
903
            } else {
904
                ff_ac3_bit_alloc_calc_psd(block->encoded_exp[ch], 0,
905
                                          s->nb_coefs[ch],
906
                                          block->psd[ch], block->band_psd[ch]);
907
                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
908
                                           0, s->nb_coefs[ch],
909
                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
910
                                           ch == s->lfe_channel,
911
                                           DBA_NONE, 0, NULL, NULL, NULL,
912
                                           block->mask[ch]);
913
            }
914
        }
915
    }
916
}
917

    
918

    
919
/**
920
 * Ensure that bap for each block and channel point to the current bap_buffer.
921
 * They may have been switched during the bit allocation search.
922
 */
923
static void reset_block_bap(AC3EncodeContext *s)
924
{
925
    int blk, ch;
926
    if (s->blocks[0].bap[0] == s->bap_buffer)
927
        return;
928
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
929
        for (ch = 0; ch < s->channels; ch++) {
930
            s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
931
        }
932
    }
933
}
934

    
935

    
936
/**
937
 * Run the bit allocation with a given SNR offset.
938
 * This calculates the bit allocation pointers that will be used to determine
939
 * the quantization of each mantissa.
940
 * @return the number of bits needed for mantissas if the given SNR offset is
941
 *         is used.
942
 */
943
static int bit_alloc(AC3EncodeContext *s,
944
                     int snr_offset)
945
{
946
    int blk, ch;
947
    int mantissa_bits;
948

    
949
    snr_offset = (snr_offset - 240) << 2;
950

    
951
    reset_block_bap(s);
952
    mantissa_bits = 0;
953
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
954
        AC3Block *block = &s->blocks[blk];
955
        s->mant1_cnt = 0;
956
        s->mant2_cnt = 0;
957
        s->mant4_cnt = 0;
958
        for (ch = 0; ch < s->channels; ch++) {
959
            ff_ac3_bit_alloc_calc_bap(block->mask[ch], block->psd[ch], 0,
960
                                      s->nb_coefs[ch], snr_offset,
961
                                      s->bit_alloc.floor, ff_ac3_bap_tab,
962
                                      block->bap[ch]);
963
            mantissa_bits += compute_mantissa_size(s, block->bap[ch], s->nb_coefs[ch]);
964
        }
965
    }
966
    return mantissa_bits;
967
}
968

    
969

    
970
/**
971
 * Constant bitrate bit allocation search.
972
 * Find the largest SNR offset that will allow data to fit in the frame.
973
 */
974
static int cbr_bit_allocation(AC3EncodeContext *s)
975
{
976
    int ch;
977
    int bits_left;
978
    int snr_offset;
979

    
980
    bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
981

    
982
    snr_offset = s->coarse_snr_offset << 4;
983

    
984
    while (snr_offset >= 0 &&
985
           bit_alloc(s, snr_offset) > bits_left) {
986
        snr_offset -= 64;
987
    }
988
    if (snr_offset < 0)
989
        return AVERROR(EINVAL);
990

    
991
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
992
    while (snr_offset + 64 <= 1023 &&
993
           bit_alloc(s, snr_offset + 64) <= bits_left) {
994
        snr_offset += 64;
995
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
996
    }
997
    while (snr_offset + 16 <= 1023 &&
998
           bit_alloc(s, snr_offset + 16) <= bits_left) {
999
        snr_offset += 16;
1000
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1001
    }
1002
    while (snr_offset + 4 <= 1023 &&
1003
           bit_alloc(s, snr_offset + 4) <= bits_left) {
1004
        snr_offset += 4;
1005
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1006
    }
1007
    while (snr_offset + 1 <= 1023 &&
1008
           bit_alloc(s, snr_offset + 1) <= bits_left) {
1009
        snr_offset++;
1010
        FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1011
    }
1012
    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1013
    reset_block_bap(s);
1014

    
1015
    s->coarse_snr_offset = snr_offset >> 4;
1016
    for (ch = 0; ch < s->channels; ch++)
1017
        s->fine_snr_offset[ch] = snr_offset & 0xF;
1018

    
1019
    return 0;
1020
}
1021

    
1022

    
1023
/**
1024
 * Perform bit allocation search.
1025
 * Finds the SNR offset value that maximizes quality and fits in the specified
1026
 * frame size.  Output is the SNR offset and a set of bit allocation pointers
1027
 * used to quantize the mantissas.
1028
 */
1029
static int compute_bit_allocation(AC3EncodeContext *s)
1030
{
1031
    count_frame_bits(s);
1032

    
1033
    bit_alloc_masking(s);
1034

    
1035
    return cbr_bit_allocation(s);
1036
}
1037

    
1038

    
1039
/**
1040
 * Symmetric quantization on 'levels' levels.
1041
 */
1042
static inline int sym_quant(int c, int e, int levels)
1043
{
1044
    int v;
1045

    
1046
    if (c >= 0) {
1047
        v = (levels * (c << e)) >> 24;
1048
        v = (v + 1) >> 1;
1049
        v = (levels >> 1) + v;
1050
    } else {
1051
        v = (levels * ((-c) << e)) >> 24;
1052
        v = (v + 1) >> 1;
1053
        v = (levels >> 1) - v;
1054
    }
1055
    assert(v >= 0 && v < levels);
1056
    return v;
1057
}
1058

    
1059

    
1060
/**
1061
 * Asymmetric quantization on 2^qbits levels.
1062
 */
1063
static inline int asym_quant(int c, int e, int qbits)
1064
{
1065
    int lshift, m, v;
1066

    
1067
    lshift = e + qbits - 24;
1068
    if (lshift >= 0)
1069
        v = c << lshift;
1070
    else
1071
        v = c >> (-lshift);
1072
    /* rounding */
1073
    v = (v + 1) >> 1;
1074
    m = (1 << (qbits-1));
1075
    if (v >= m)
1076
        v = m - 1;
1077
    assert(v >= -m);
1078
    return v & ((1 << qbits)-1);
1079
}
1080

    
1081

    
1082
/**
1083
 * Quantize a set of mantissas for a single channel in a single block.
1084
 */
1085
static void quantize_mantissas_blk_ch(AC3EncodeContext *s,
1086
                                      int32_t *mdct_coef, int8_t exp_shift,
1087
                                      uint8_t *encoded_exp, uint8_t *bap,
1088
                                      uint16_t *qmant, int n)
1089
{
1090
    int i;
1091

    
1092
    for (i = 0; i < n; i++) {
1093
        int v;
1094
        int c = mdct_coef[i];
1095
        int e = encoded_exp[i] - exp_shift;
1096
        int b = bap[i];
1097
        switch (b) {
1098
        case 0:
1099
            v = 0;
1100
            break;
1101
        case 1:
1102
            v = sym_quant(c, e, 3);
1103
            switch (s->mant1_cnt) {
1104
            case 0:
1105
                s->qmant1_ptr = &qmant[i];
1106
                v = 9 * v;
1107
                s->mant1_cnt = 1;
1108
                break;
1109
            case 1:
1110
                *s->qmant1_ptr += 3 * v;
1111
                s->mant1_cnt = 2;
1112
                v = 128;
1113
                break;
1114
            default:
1115
                *s->qmant1_ptr += v;
1116
                s->mant1_cnt = 0;
1117
                v = 128;
1118
                break;
1119
            }
1120
            break;
1121
        case 2:
1122
            v = sym_quant(c, e, 5);
1123
            switch (s->mant2_cnt) {
1124
            case 0:
1125
                s->qmant2_ptr = &qmant[i];
1126
                v = 25 * v;
1127
                s->mant2_cnt = 1;
1128
                break;
1129
            case 1:
1130
                *s->qmant2_ptr += 5 * v;
1131
                s->mant2_cnt = 2;
1132
                v = 128;
1133
                break;
1134
            default:
1135
                *s->qmant2_ptr += v;
1136
                s->mant2_cnt = 0;
1137
                v = 128;
1138
                break;
1139
            }
1140
            break;
1141
        case 3:
1142
            v = sym_quant(c, e, 7);
1143
            break;
1144
        case 4:
1145
            v = sym_quant(c, e, 11);
1146
            switch (s->mant4_cnt) {
1147
            case 0:
1148
                s->qmant4_ptr = &qmant[i];
1149
                v = 11 * v;
1150
                s->mant4_cnt = 1;
1151
                break;
1152
            default:
1153
                *s->qmant4_ptr += v;
1154
                s->mant4_cnt = 0;
1155
                v = 128;
1156
                break;
1157
            }
1158
            break;
1159
        case 5:
1160
            v = sym_quant(c, e, 15);
1161
            break;
1162
        case 14:
1163
            v = asym_quant(c, e, 14);
1164
            break;
1165
        case 15:
1166
            v = asym_quant(c, e, 16);
1167
            break;
1168
        default:
1169
            v = asym_quant(c, e, b - 1);
1170
            break;
1171
        }
1172
        qmant[i] = v;
1173
    }
1174
}
1175

    
1176

    
1177
/**
1178
 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1179
 */
1180
static void quantize_mantissas(AC3EncodeContext *s)
1181
{
1182
    int blk, ch;
1183

    
1184

    
1185
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1186
        AC3Block *block = &s->blocks[blk];
1187
        s->mant1_cnt  = s->mant2_cnt  = s->mant4_cnt  = 0;
1188
        s->qmant1_ptr = s->qmant2_ptr = s->qmant4_ptr = NULL;
1189

    
1190
        for (ch = 0; ch < s->channels; ch++) {
1191
            quantize_mantissas_blk_ch(s, block->mdct_coef[ch], block->exp_shift[ch],
1192
                                      block->encoded_exp[ch], block->bap[ch],
1193
                                      block->qmant[ch], s->nb_coefs[ch]);
1194
        }
1195
    }
1196
}
1197

    
1198

    
1199
/**
1200
 * Write the AC-3 frame header to the output bitstream.
1201
 */
1202
static void output_frame_header(AC3EncodeContext *s)
1203
{
1204
    put_bits(&s->pb, 16, 0x0b77);   /* frame header */
1205
    put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
1206
    put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
1207
    put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1208
    put_bits(&s->pb, 5,  s->bitstream_id);
1209
    put_bits(&s->pb, 3,  s->bitstream_mode);
1210
    put_bits(&s->pb, 3,  s->channel_mode);
1211
    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1212
        put_bits(&s->pb, 2, 1);     /* XXX -4.5 dB */
1213
    if (s->channel_mode & 0x04)
1214
        put_bits(&s->pb, 2, 1);     /* XXX -6 dB */
1215
    if (s->channel_mode == AC3_CHMODE_STEREO)
1216
        put_bits(&s->pb, 2, 0);     /* surround not indicated */
1217
    put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1218
    put_bits(&s->pb, 5, 31);        /* dialog norm: -31 db */
1219
    put_bits(&s->pb, 1, 0);         /* no compression control word */
1220
    put_bits(&s->pb, 1, 0);         /* no lang code */
1221
    put_bits(&s->pb, 1, 0);         /* no audio production info */
1222
    put_bits(&s->pb, 1, 0);         /* no copyright */
1223
    put_bits(&s->pb, 1, 1);         /* original bitstream */
1224
    put_bits(&s->pb, 1, 0);         /* no time code 1 */
1225
    put_bits(&s->pb, 1, 0);         /* no time code 2 */
1226
    put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
1227
}
1228

    
1229

    
1230
/**
1231
 * Write one audio block to the output bitstream.
1232
 */
1233
static void output_audio_block(AC3EncodeContext *s,
1234
                               int block_num)
1235
{
1236
    int ch, i, baie, rbnd;
1237
    AC3Block *block = &s->blocks[block_num];
1238

    
1239
    /* block switching */
1240
    for (ch = 0; ch < s->fbw_channels; ch++)
1241
        put_bits(&s->pb, 1, 0);
1242

    
1243
    /* dither flags */
1244
    for (ch = 0; ch < s->fbw_channels; ch++)
1245
        put_bits(&s->pb, 1, 1);
1246

    
1247
    /* dynamic range codes */
1248
    put_bits(&s->pb, 1, 0);
1249

    
1250
    /* channel coupling */
1251
    if (!block_num) {
1252
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
1253
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
1254
    } else {
1255
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1256
    }
1257

    
1258
    /* stereo rematrixing */
1259
    if (s->channel_mode == AC3_CHMODE_STEREO) {
1260
        if (!block_num) {
1261
            /* first block must define rematrixing (rematstr) */
1262
            put_bits(&s->pb, 1, 1);
1263

    
1264
            /* dummy rematrixing rematflg(1:4)=0 */
1265
            for (rbnd = 0; rbnd < 4; rbnd++)
1266
                put_bits(&s->pb, 1, 0);
1267
        } else {
1268
            /* no matrixing (but should be used in the future) */
1269
            put_bits(&s->pb, 1, 0);
1270
        }
1271
    }
1272

    
1273
    /* exponent strategy */
1274
    for (ch = 0; ch < s->fbw_channels; ch++)
1275
        put_bits(&s->pb, 2, block->exp_strategy[ch]);
1276
    if (s->lfe_on)
1277
        put_bits(&s->pb, 1, block->exp_strategy[s->lfe_channel]);
1278

    
1279
    /* bandwidth */
1280
    for (ch = 0; ch < s->fbw_channels; ch++) {
1281
        if (block->exp_strategy[ch] != EXP_REUSE)
1282
            put_bits(&s->pb, 6, s->bandwidth_code[ch]);
1283
    }
1284

    
1285
    /* exponents */
1286
    for (ch = 0; ch < s->channels; ch++) {
1287
        if (block->exp_strategy[ch] == EXP_REUSE)
1288
            continue;
1289

    
1290
        /* DC exponent */
1291
        put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1292

    
1293
        /* exponent groups */
1294
        for (i = 1; i <= block->num_exp_groups[ch]; i++)
1295
            put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1296

    
1297
        /* gain range info */
1298
        if (ch != s->lfe_channel)
1299
            put_bits(&s->pb, 2, 0);
1300
    }
1301

    
1302
    /* bit allocation info */
1303
    baie = (block_num == 0);
1304
    put_bits(&s->pb, 1, baie);
1305
    if (baie) {
1306
        put_bits(&s->pb, 2, s->slow_decay_code);
1307
        put_bits(&s->pb, 2, s->fast_decay_code);
1308
        put_bits(&s->pb, 2, s->slow_gain_code);
1309
        put_bits(&s->pb, 2, s->db_per_bit_code);
1310
        put_bits(&s->pb, 3, s->floor_code);
1311
    }
1312

    
1313
    /* snr offset */
1314
    put_bits(&s->pb, 1, baie);
1315
    if (baie) {
1316
        put_bits(&s->pb, 6, s->coarse_snr_offset);
1317
        for (ch = 0; ch < s->channels; ch++) {
1318
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1319
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1320
        }
1321
    }
1322

    
1323
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1324
    put_bits(&s->pb, 1, 0); /* no data to skip */
1325

    
1326
    /* mantissas */
1327
    for (ch = 0; ch < s->channels; ch++) {
1328
        int b, q;
1329
        for (i = 0; i < s->nb_coefs[ch]; i++) {
1330
            q = block->qmant[ch][i];
1331
            b = block->bap[ch][i];
1332
            switch (b) {
1333
            case 0:                                         break;
1334
            case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
1335
            case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
1336
            case 3:               put_bits(&s->pb,   3, q); break;
1337
            case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
1338
            case 14:              put_bits(&s->pb,  14, q); break;
1339
            case 15:              put_bits(&s->pb,  16, q); break;
1340
            default:              put_bits(&s->pb, b-1, q); break;
1341
            }
1342
        }
1343
    }
1344
}
1345

    
1346

    
1347
/** CRC-16 Polynomial */
1348
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1349

    
1350

    
1351
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1352
{
1353
    unsigned int c;
1354

    
1355
    c = 0;
1356
    while (a) {
1357
        if (a & 1)
1358
            c ^= b;
1359
        a = a >> 1;
1360
        b = b << 1;
1361
        if (b & (1 << 16))
1362
            b ^= poly;
1363
    }
1364
    return c;
1365
}
1366

    
1367

    
1368
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1369
{
1370
    unsigned int r;
1371
    r = 1;
1372
    while (n) {
1373
        if (n & 1)
1374
            r = mul_poly(r, a, poly);
1375
        a = mul_poly(a, a, poly);
1376
        n >>= 1;
1377
    }
1378
    return r;
1379
}
1380

    
1381

    
1382
/**
1383
 * Fill the end of the frame with 0's and compute the two CRCs.
1384
 */
1385
static void output_frame_end(AC3EncodeContext *s)
1386
{
1387
    int frame_size, frame_size_58, pad_bytes, crc1, crc2, crc_inv;
1388
    uint8_t *frame;
1389

    
1390
    frame_size    = s->frame_size;
1391
    frame_size_58 = ((frame_size >> 2) + (frame_size >> 4)) << 1;
1392

    
1393
    /* pad the remainder of the frame with zeros */
1394
    flush_put_bits(&s->pb);
1395
    frame = s->pb.buf;
1396
    pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1397
    assert(pad_bytes >= 0);
1398
    if (pad_bytes > 0)
1399
        memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1400

    
1401
    /* compute crc1 */
1402
    /* this is not so easy because it is at the beginning of the data... */
1403
    crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1404
                             frame + 4, frame_size_58 - 4));
1405
    /* XXX: could precompute crc_inv */
1406
    crc_inv = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
1407
    crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1408
    AV_WB16(frame + 2, crc1);
1409

    
1410
    /* compute crc2 */
1411
    crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1412
                             frame + frame_size_58,
1413
                             frame_size - frame_size_58 - 2));
1414
    AV_WB16(frame + frame_size - 2, crc2);
1415
}
1416

    
1417

    
1418
/**
1419
 * Write the frame to the output bitstream.
1420
 */
1421
static void output_frame(AC3EncodeContext *s,
1422
                         unsigned char *frame)
1423
{
1424
    int blk;
1425

    
1426
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1427

    
1428
    output_frame_header(s);
1429

    
1430
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1431
        output_audio_block(s, blk);
1432

    
1433
    output_frame_end(s);
1434
}
1435

    
1436

    
1437
/**
1438
 * Encode a single AC-3 frame.
1439
 */
1440
static int ac3_encode_frame(AVCodecContext *avctx,
1441
                            unsigned char *frame, int buf_size, void *data)
1442
{
1443
    AC3EncodeContext *s = avctx->priv_data;
1444
    const int16_t *samples = data;
1445
    int ret;
1446

    
1447
    if (s->bit_alloc.sr_code == 1)
1448
        adjust_frame_size(s);
1449

    
1450
    deinterleave_input_samples(s, samples);
1451

    
1452
    apply_mdct(s);
1453

    
1454
    process_exponents(s);
1455

    
1456
    ret = compute_bit_allocation(s);
1457
    if (ret) {
1458
        av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1459
        return ret;
1460
    }
1461

    
1462
    quantize_mantissas(s);
1463

    
1464
    output_frame(s, frame);
1465

    
1466
    return s->frame_size;
1467
}
1468

    
1469

    
1470
/**
1471
 * Finalize encoding and free any memory allocated by the encoder.
1472
 */
1473
static av_cold int ac3_encode_close(AVCodecContext *avctx)
1474
{
1475
    int blk, ch;
1476
    AC3EncodeContext *s = avctx->priv_data;
1477

    
1478
    for (ch = 0; ch < s->channels; ch++)
1479
        av_freep(&s->planar_samples[ch]);
1480
    av_freep(&s->planar_samples);
1481
    av_freep(&s->bap_buffer);
1482
    av_freep(&s->bap1_buffer);
1483
    av_freep(&s->mdct_coef_buffer);
1484
    av_freep(&s->exp_buffer);
1485
    av_freep(&s->encoded_exp_buffer);
1486
    av_freep(&s->grouped_exp_buffer);
1487
    av_freep(&s->psd_buffer);
1488
    av_freep(&s->band_psd_buffer);
1489
    av_freep(&s->mask_buffer);
1490
    av_freep(&s->qmant_buffer);
1491
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1492
        AC3Block *block = &s->blocks[blk];
1493
        av_freep(&block->bap);
1494
        av_freep(&block->mdct_coef);
1495
        av_freep(&block->exp);
1496
        av_freep(&block->encoded_exp);
1497
        av_freep(&block->grouped_exp);
1498
        av_freep(&block->psd);
1499
        av_freep(&block->band_psd);
1500
        av_freep(&block->mask);
1501
        av_freep(&block->qmant);
1502
    }
1503

    
1504
    av_freep(&avctx->coded_frame);
1505
    return 0;
1506
}
1507

    
1508

    
1509
/**
1510
 * Set channel information during initialization.
1511
 */
1512
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1513
                                    int64_t *channel_layout)
1514
{
1515
    int ch_layout;
1516

    
1517
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
1518
        return AVERROR(EINVAL);
1519
    if ((uint64_t)*channel_layout > 0x7FF)
1520
        return AVERROR(EINVAL);
1521
    ch_layout = *channel_layout;
1522
    if (!ch_layout)
1523
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1524
    if (av_get_channel_layout_nb_channels(ch_layout) != channels)
1525
        return AVERROR(EINVAL);
1526

    
1527
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1528
    s->channels     = channels;
1529
    s->fbw_channels = channels - s->lfe_on;
1530
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
1531
    if (s->lfe_on)
1532
        ch_layout -= AV_CH_LOW_FREQUENCY;
1533

    
1534
    switch (ch_layout) {
1535
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
1536
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
1537
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
1538
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
1539
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
1540
    case AV_CH_LAYOUT_QUAD:
1541
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
1542
    case AV_CH_LAYOUT_5POINT0:
1543
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
1544
    default:
1545
        return AVERROR(EINVAL);
1546
    }
1547

    
1548
    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1549
    *channel_layout = ch_layout;
1550
    if (s->lfe_on)
1551
        *channel_layout |= AV_CH_LOW_FREQUENCY;
1552

    
1553
    return 0;
1554
}
1555

    
1556

    
1557
static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1558
{
1559
    int i, ret;
1560

    
1561
    /* validate channel layout */
1562
    if (!avctx->channel_layout) {
1563
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1564
                                      "encoder will guess the layout, but it "
1565
                                      "might be incorrect.\n");
1566
    }
1567
    ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1568
    if (ret) {
1569
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1570
        return ret;
1571
    }
1572

    
1573
    /* validate sample rate */
1574
    for (i = 0; i < 9; i++) {
1575
        if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
1576
            break;
1577
    }
1578
    if (i == 9) {
1579
        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1580
        return AVERROR(EINVAL);
1581
    }
1582
    s->sample_rate        = avctx->sample_rate;
1583
    s->bit_alloc.sr_shift = i % 3;
1584
    s->bit_alloc.sr_code  = i / 3;
1585

    
1586
    /* validate bit rate */
1587
    for (i = 0; i < 19; i++) {
1588
        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
1589
            break;
1590
    }
1591
    if (i == 19) {
1592
        av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
1593
        return AVERROR(EINVAL);
1594
    }
1595
    s->bit_rate        = avctx->bit_rate;
1596
    s->frame_size_code = i << 1;
1597

    
1598
    return 0;
1599
}
1600

    
1601

    
1602
/**
1603
 * Set bandwidth for all channels.
1604
 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
1605
 * default value will be used.
1606
 */
1607
static av_cold void set_bandwidth(AC3EncodeContext *s, int cutoff)
1608
{
1609
    int ch, bw_code;
1610

    
1611
    if (cutoff) {
1612
        /* calculate bandwidth based on user-specified cutoff frequency */
1613
        int fbw_coeffs;
1614
        cutoff         = av_clip(cutoff, 1, s->sample_rate >> 1);
1615
        fbw_coeffs     = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
1616
        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
1617
    } else {
1618
        /* use default bandwidth setting */
1619
        /* XXX: should compute the bandwidth according to the frame
1620
           size, so that we avoid annoying high frequency artifacts */
1621
        bw_code = 50;
1622
    }
1623

    
1624
    /* set number of coefficients for each channel */
1625
    for (ch = 0; ch < s->fbw_channels; ch++) {
1626
        s->bandwidth_code[ch] = bw_code;
1627
        s->nb_coefs[ch]       = bw_code * 3 + 73;
1628
    }
1629
    if (s->lfe_on)
1630
        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
1631
}
1632

    
1633

    
1634
static av_cold int allocate_buffers(AVCodecContext *avctx)
1635
{
1636
    int blk, ch;
1637
    AC3EncodeContext *s = avctx->priv_data;
1638

    
1639
    FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
1640
                     alloc_fail);
1641
    for (ch = 0; ch < s->channels; ch++) {
1642
        FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
1643
                          (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
1644
                          alloc_fail);
1645
    }
1646
    FF_ALLOC_OR_GOTO(avctx, s->bap_buffer,  AC3_MAX_BLOCKS * s->channels *
1647
                     AC3_MAX_COEFS * sizeof(*s->bap_buffer),  alloc_fail);
1648
    FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
1649
                     AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
1650
    FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
1651
                     AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
1652
    FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
1653
                     AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
1654
    FF_ALLOC_OR_GOTO(avctx, s->encoded_exp_buffer, AC3_MAX_BLOCKS * s->channels *
1655
                     AC3_MAX_COEFS * sizeof(*s->encoded_exp_buffer), alloc_fail);
1656
    FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
1657
                     128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
1658
    FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
1659
                     AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
1660
    FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
1661
                     64 * sizeof(*s->band_psd_buffer), alloc_fail);
1662
    FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
1663
                     64 * sizeof(*s->mask_buffer), alloc_fail);
1664
    FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
1665
                     AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
1666
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1667
        AC3Block *block = &s->blocks[blk];
1668
        FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
1669
                         alloc_fail);
1670
        FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
1671
                          alloc_fail);
1672
        FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
1673
                          alloc_fail);
1674
        FF_ALLOCZ_OR_GOTO(avctx, block->encoded_exp, s->channels * sizeof(*block->encoded_exp),
1675
                          alloc_fail);
1676
        FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
1677
                          alloc_fail);
1678
        FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
1679
                          alloc_fail);
1680
        FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
1681
                          alloc_fail);
1682
        FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
1683
                          alloc_fail);
1684
        FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
1685
                          alloc_fail);
1686

    
1687
        for (ch = 0; ch < s->channels; ch++) {
1688
            block->bap[ch]         = &s->bap_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1689
            block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (blk * s->channels + ch)];
1690
            block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1691
            block->encoded_exp[ch] = &s->encoded_exp_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
1692
            block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * s->channels + ch)];
1693
            block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * s->channels + ch)];
1694
            block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * s->channels + ch)];
1695
            block->mask[ch]        = &s->mask_buffer       [64            * (blk * s->channels + ch)];
1696
            block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * s->channels + ch)];
1697
        }
1698
    }
1699

    
1700
    return 0;
1701
alloc_fail:
1702
    return AVERROR(ENOMEM);
1703
}
1704

    
1705

    
1706
/**
1707
 * Initialize the encoder.
1708
 */
1709
static av_cold int ac3_encode_init(AVCodecContext *avctx)
1710
{
1711
    AC3EncodeContext *s = avctx->priv_data;
1712
    int ret;
1713

    
1714
    avctx->frame_size = AC3_FRAME_SIZE;
1715

    
1716
    ac3_common_init();
1717

    
1718
    ret = validate_options(avctx, s);
1719
    if (ret)
1720
        return ret;
1721

    
1722
    s->bitstream_id   = 8 + s->bit_alloc.sr_shift;
1723
    s->bitstream_mode = 0; /* complete main audio service */
1724

    
1725
    s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
1726
    s->bits_written    = 0;
1727
    s->samples_written = 0;
1728
    s->frame_size      = s->frame_size_min;
1729

    
1730
    set_bandwidth(s, avctx->cutoff);
1731

    
1732
    bit_alloc_init(s);
1733

    
1734
    mdct_init(9);
1735

    
1736
    ret = allocate_buffers(avctx);
1737
    if (ret) {
1738
        ac3_encode_close(avctx);
1739
        return ret;
1740
    }
1741

    
1742
    avctx->coded_frame= avcodec_alloc_frame();
1743

    
1744
    return 0;
1745
}
1746

    
1747

    
1748
#ifdef TEST
1749
/*************************************************************************/
1750
/* TEST */
1751

    
1752
#include "libavutil/lfg.h"
1753

    
1754
#define FN (MDCT_SAMPLES/4)
1755

    
1756

    
1757
static void fft_test(AVLFG *lfg)
1758
{
1759
    IComplex in[FN], in1[FN];
1760
    int k, n, i;
1761
    float sum_re, sum_im, a;
1762

    
1763
    for (i = 0; i < FN; i++) {
1764
        in[i].re = av_lfg_get(lfg) % 65535 - 32767;
1765
        in[i].im = av_lfg_get(lfg) % 65535 - 32767;
1766
        in1[i]   = in[i];
1767
    }
1768
    fft(in, 7);
1769

    
1770
    /* do it by hand */
1771
    for (k = 0; k < FN; k++) {
1772
        sum_re = 0;
1773
        sum_im = 0;
1774
        for (n = 0; n < FN; n++) {
1775
            a = -2 * M_PI * (n * k) / FN;
1776
            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1777
            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1778
        }
1779
        av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
1780
               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1781
    }
1782
}
1783

    
1784

    
1785
static void mdct_test(AVLFG *lfg)
1786
{
1787
    int16_t input[MDCT_SAMPLES];
1788
    int32_t output[AC3_MAX_COEFS];
1789
    float input1[MDCT_SAMPLES];
1790
    float output1[AC3_MAX_COEFS];
1791
    float s, a, err, e, emax;
1792
    int i, k, n;
1793

    
1794
    for (i = 0; i < MDCT_SAMPLES; i++) {
1795
        input[i]  = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
1796
        input1[i] = input[i];
1797
    }
1798

    
1799
    mdct512(output, input);
1800

    
1801
    /* do it by hand */
1802
    for (k = 0; k < AC3_MAX_COEFS; k++) {
1803
        s = 0;
1804
        for (n = 0; n < MDCT_SAMPLES; n++) {
1805
            a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
1806
            s += input1[n] * cos(a);
1807
        }
1808
        output1[k] = -2 * s / MDCT_SAMPLES;
1809
    }
1810

    
1811
    err  = 0;
1812
    emax = 0;
1813
    for (i = 0; i < AC3_MAX_COEFS; i++) {
1814
        av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
1815
        e = output[i] - output1[i];
1816
        if (e > emax)
1817
            emax = e;
1818
        err += e * e;
1819
    }
1820
    av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
1821
}
1822

    
1823

    
1824
int main(void)
1825
{
1826
    AVLFG lfg;
1827

    
1828
    av_log_set_level(AV_LOG_DEBUG);
1829
    mdct_init(9);
1830

    
1831
    fft_test(&lfg);
1832
    mdct_test(&lfg);
1833

    
1834
    return 0;
1835
}
1836
#endif /* TEST */
1837

    
1838

    
1839
AVCodec ac3_encoder = {
1840
    "ac3",
1841
    AVMEDIA_TYPE_AUDIO,
1842
    CODEC_ID_AC3,
1843
    sizeof(AC3EncodeContext),
1844
    ac3_encode_init,
1845
    ac3_encode_frame,
1846
    ac3_encode_close,
1847
    NULL,
1848
    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1849
    .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1850
    .channel_layouts = (const int64_t[]){
1851
        AV_CH_LAYOUT_MONO,
1852
        AV_CH_LAYOUT_STEREO,
1853
        AV_CH_LAYOUT_2_1,
1854
        AV_CH_LAYOUT_SURROUND,
1855
        AV_CH_LAYOUT_2_2,
1856
        AV_CH_LAYOUT_QUAD,
1857
        AV_CH_LAYOUT_4POINT0,
1858
        AV_CH_LAYOUT_5POINT0,
1859
        AV_CH_LAYOUT_5POINT0_BACK,
1860
       (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
1861
       (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
1862
       (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
1863
       (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1864
       (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
1865
       (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
1866
       (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
1867
        AV_CH_LAYOUT_5POINT1,
1868
        AV_CH_LAYOUT_5POINT1_BACK,
1869
        0 },
1870
};