Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ e77fd066

History | View | Annotate | Download (42.9 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
#define MDCT_NBITS 9
37
#define MDCT_SAMPLES (1 << MDCT_NBITS)
38

    
39
#define SCALE_FLOAT(a, bits) lrintf((a) * (float)(1 << (bits)))
40

    
41
#define FIX15(a) av_clip_int16(SCALE_FLOAT(a, 15))
42

    
43
typedef struct IComplex {
44
    int16_t re,im;
45
} IComplex;
46

    
47
typedef struct AC3EncodeContext {
48
    PutBitContext pb;                       ///< bitstream writer context
49

    
50
    int bitstream_id;                       ///< bitstream id                           (bsid)
51
    int bitstream_mode;                     ///< bitstream mode                         (bsmod)
52

    
53
    int bit_rate;                           ///< target bit rate, in bits-per-second
54
    int sample_rate;                        ///< sampling frequency, in Hz
55

    
56
    int frame_size_min;                     ///< minimum frame size in case rounding is necessary
57
    int frame_size;                         ///< current frame size in words
58
    int frame_size_code;                    ///< frame size code                        (frmsizecod)
59
    int bits_written;                       ///< bit count    (used to avg. bitrate)
60
    int samples_written;                    ///< sample count (used to avg. bitrate)
61

    
62
    int fbw_channels;                       ///< number of full-bandwidth channels      (nfchans)
63
    int channels;                           ///< total number of channels               (nchans)
64
    int lfe_on;                             ///< indicates if there is an LFE channel   (lfeon)
65
    int lfe_channel;                        ///< channel index of the LFE channel
66
    int channel_mode;                       ///< channel mode                           (acmod)
67
    const uint8_t *channel_map;             ///< channel map used to reorder channels
68

    
69
    int bandwidth_code[AC3_MAX_CHANNELS];   ///< bandwidth code (0 to 60)               (chbwcod)
70
    int nb_coefs[AC3_MAX_CHANNELS];
71

    
72
    /* bitrate allocation control */
73
    int slow_gain_code;                     ///< slow gain code                         (sgaincod)
74
    int slow_decay_code;                    ///< slow decay code                        (sdcycod)
75
    int fast_decay_code;                    ///< fast decay code                        (fdcycod)
76
    int db_per_bit_code;                    ///< dB/bit code                            (dbpbcod)
77
    int floor_code;                         ///< floor code                             (floorcod)
78
    AC3BitAllocParameters bit_alloc;        ///< bit allocation parameters
79
    int coarse_snr_offset;                  ///< coarse SNR offsets                     (csnroffst)
80
    int fast_gain_code[AC3_MAX_CHANNELS];   ///< fast gain codes (signal-to-mask ratio) (fgaincod)
81
    int fine_snr_offset[AC3_MAX_CHANNELS];  ///< fine SNR offsets                       (fsnroffst)
82

    
83
    /* mantissa encoding */
84
    int mant1_cnt, mant2_cnt, mant4_cnt;    ///< mantissa counts for bap=1,2,4
85

    
86
    int16_t last_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE]; ///< last 256 samples from previous frame
87
} AC3EncodeContext;
88

    
89
static int16_t costab[64];
90
static int16_t sintab[64];
91
static int16_t xcos1[128];
92
static int16_t xsin1[128];
93

    
94
static av_cold void fft_init(int ln)
95
{
96
    int i, n, n2;
97
    float alpha;
98

    
99
    n  = 1 << ln;
100
    n2 = n >> 1;
101

    
102
    for (i = 0; i < n2; i++) {
103
        alpha     = 2.0 * M_PI * i / n;
104
        costab[i] = FIX15(cos(alpha));
105
        sintab[i] = FIX15(sin(alpha));
106
    }
107
}
108

    
109
static av_cold void mdct_init(int nbits)
110
{
111
    int i, n, n4;
112

    
113
    n  = 1 << nbits;
114
    n4 = n >> 2;
115

    
116
    fft_init(nbits - 2);
117

    
118
    for (i = 0; i < n4; i++) {
119
        float alpha = 2.0 * M_PI * (i + 1.0 / 8.0) / n;
120
        xcos1[i] = FIX15(-cos(alpha));
121
        xsin1[i] = FIX15(-sin(alpha));
122
    }
123
}
124

    
125
/* butter fly op */
126
#define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1)  \
127
{                                                       \
128
  int ax, ay, bx, by;                                   \
129
  bx  = pre1;                                           \
130
  by  = pim1;                                           \
131
  ax  = qre1;                                           \
132
  ay  = qim1;                                           \
133
  pre = (bx + ax) >> 1;                                 \
134
  pim = (by + ay) >> 1;                                 \
135
  qre = (bx - ax) >> 1;                                 \
136
  qim = (by - ay) >> 1;                                 \
137
}
138

    
139
#define CMUL(pre, pim, are, aim, bre, bim)              \
140
{                                                       \
141
   pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;     \
142
   pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;     \
143
}
144

    
145

    
146
/* do a 2^n point complex fft on 2^ln points. */
147
static void fft(IComplex *z, int ln)
148
{
149
    int j, l, np, np2;
150
    int nblocks, nloops;
151
    register IComplex *p,*q;
152
    int tmp_re, tmp_im;
153

    
154
    np = 1 << ln;
155

    
156
    /* reverse */
157
    for (j = 0; j < np; j++) {
158
        int k = av_reverse[j] >> (8 - ln);
159
        if (k < j)
160
            FFSWAP(IComplex, z[k], z[j]);
161
    }
162

    
163
    /* pass 0 */
164

    
165
    p = &z[0];
166
    j = np >> 1;
167
    do {
168
        BF(p[0].re, p[0].im, p[1].re, p[1].im,
169
           p[0].re, p[0].im, p[1].re, p[1].im);
170
        p += 2;
171
    } while (--j);
172

    
173
    /* pass 1 */
174

    
175
    p = &z[0];
176
    j = np >> 2;
177
    do {
178
        BF(p[0].re, p[0].im, p[2].re,  p[2].im,
179
           p[0].re, p[0].im, p[2].re,  p[2].im);
180
        BF(p[1].re, p[1].im, p[3].re,  p[3].im,
181
           p[1].re, p[1].im, p[3].im, -p[3].re);
182
        p+=4;
183
    } while (--j);
184

    
185
    /* pass 2 .. ln-1 */
186

    
187
    nblocks = np >> 3;
188
    nloops  =  1 << 2;
189
    np2     = np >> 1;
190
    do {
191
        p = z;
192
        q = z + nloops;
193
        for (j = 0; j < nblocks; j++) {
194
            BF(p->re, p->im, q->re, q->im,
195
               p->re, p->im, q->re, q->im);
196
            p++;
197
            q++;
198
            for(l = nblocks; l < np2; l += nblocks) {
199
                CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
200
                BF(p->re, p->im, q->re,  q->im,
201
                   p->re, p->im, tmp_re, tmp_im);
202
                p++;
203
                q++;
204
            }
205
            p += nloops;
206
            q += nloops;
207
        }
208
        nblocks = nblocks >> 1;
209
        nloops  = nloops  << 1;
210
    } while (nblocks);
211
}
212

    
213
static void mdct512(int32_t *out, int16_t *in)
214
{
215
    int i, re, im, re1, im1;
216
    int16_t rot[MDCT_SAMPLES];
217
    IComplex x[MDCT_SAMPLES/4];
218

    
219
    /* shift to simplify computations */
220
    for (i = 0; i < MDCT_SAMPLES/4; i++)
221
        rot[i] = -in[i + 3*MDCT_SAMPLES/4];
222
    for (;i < MDCT_SAMPLES; i++)
223
        rot[i] =  in[i -   MDCT_SAMPLES/4];
224

    
225
    /* pre rotation */
226
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
227
        re =  ((int)rot[               2*i] - (int)rot[MDCT_SAMPLES  -1-2*i]) >> 1;
228
        im = -((int)rot[MDCT_SAMPLES/2+2*i] - (int)rot[MDCT_SAMPLES/2-1-2*i]) >> 1;
229
        CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
230
    }
231

    
232
    fft(x, MDCT_NBITS - 2);
233

    
234
    /* post rotation */
235
    for (i = 0; i < MDCT_SAMPLES/4; i++) {
236
        re = x[i].re;
237
        im = x[i].im;
238
        CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
239
        out[                 2*i] = im1;
240
        out[MDCT_SAMPLES/2-1-2*i] = re1;
241
    }
242
}
243

    
244
/* compute log2(max(abs(tab[]))) */
245
static int log2_tab(int16_t *tab, int n)
246
{
247
    int i, v;
248

    
249
    v = 0;
250
    for (i = 0; i < n; i++)
251
        v |= abs(tab[i]);
252

    
253
    return av_log2(v);
254
}
255

    
256
static void lshift_tab(int16_t *tab, int n, int lshift)
257
{
258
    int i;
259

    
260
    if (lshift > 0) {
261
        for(i = 0; i < n; i++)
262
            tab[i] <<= lshift;
263
    } else if (lshift < 0) {
264
        lshift = -lshift;
265
        for (i = 0; i < n; i++)
266
            tab[i] >>= lshift;
267
    }
268
}
269

    
270
static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
271
{
272
    int sum, i;
273
    sum = 0;
274
    for (i = 0; i < n; i++)
275
        sum += abs(exp1[i] - exp2[i]);
276
    return sum;
277
}
278

    
279
/* new exponents are sent if their Norm 1 exceed this number */
280
#define EXP_DIFF_THRESHOLD 1000
281

    
282
static void compute_exp_strategy(uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
283
                                 uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
284
                                 int ch, int is_lfe)
285
{
286
    int i, j;
287
    int exp_diff;
288

    
289
    /* estimate if the exponent variation & decide if they should be
290
       reused in the next frame */
291
    exp_strategy[0][ch] = EXP_NEW;
292
    for (i = 1; i < AC3_MAX_BLOCKS; i++) {
293
        exp_diff = calc_exp_diff(exp[i][ch], exp[i-1][ch], AC3_MAX_COEFS);
294
        if (exp_diff > EXP_DIFF_THRESHOLD)
295
            exp_strategy[i][ch] = EXP_NEW;
296
        else
297
            exp_strategy[i][ch] = EXP_REUSE;
298
    }
299
    if (is_lfe)
300
        return;
301

    
302
    /* now select the encoding strategy type : if exponents are often
303
       recoded, we use a coarse encoding */
304
    i = 0;
305
    while (i < AC3_MAX_BLOCKS) {
306
        j = i + 1;
307
        while (j < AC3_MAX_BLOCKS && exp_strategy[j][ch] == EXP_REUSE)
308
            j++;
309
        switch (j - i) {
310
        case 1:  exp_strategy[i][ch] = EXP_D45; break;
311
        case 2:
312
        case 3:  exp_strategy[i][ch] = EXP_D25; break;
313
        default: exp_strategy[i][ch] = EXP_D15; break;
314
        }
315
        i = j;
316
    }
317
}
318

    
319
/* set exp[i] to min(exp[i], exp1[i]) */
320
static void exponent_min(uint8_t exp[AC3_MAX_COEFS], uint8_t exp1[AC3_MAX_COEFS], int n)
321
{
322
    int i;
323
    for (i = 0; i < n; i++) {
324
        if (exp1[i] < exp[i])
325
            exp[i] = exp1[i];
326
    }
327
}
328

    
329
/* update the exponents so that they are the ones the decoder will
330
   decode. Return the number of bits used to code the exponents */
331
static int encode_exp(uint8_t encoded_exp[AC3_MAX_COEFS],
332
                      uint8_t exp[AC3_MAX_COEFS],
333
                      int nb_exps, int exp_strategy)
334
{
335
    int group_size, nb_groups, i, j, k, exp_min;
336
    uint8_t exp1[AC3_MAX_COEFS];
337

    
338
    group_size = exp_strategy + (exp_strategy == EXP_D45);
339
    nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
340

    
341
    /* for each group, compute the minimum exponent */
342
    exp1[0] = exp[0]; /* DC exponent is handled separately */
343
    k = 1;
344
    for (i = 1; i <= nb_groups; i++) {
345
        exp_min = exp[k];
346
        assert(exp_min >= 0 && exp_min <= 24);
347
        for (j = 1; j < group_size; j++) {
348
            if (exp[k+j] < exp_min)
349
                exp_min = exp[k+j];
350
        }
351
        exp1[i] = exp_min;
352
        k += group_size;
353
    }
354

    
355
    /* constraint for DC exponent */
356
    if (exp1[0] > 15)
357
        exp1[0] = 15;
358

    
359
    /* decrease the delta between each groups to within 2 so that they can be
360
       differentially encoded */
361
    for (i = 1; i <= nb_groups; i++)
362
        exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
363
    for (i = nb_groups-1; i >= 0; i--)
364
        exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
365

    
366
    /* now we have the exponent values the decoder will see */
367
    encoded_exp[0] = exp1[0];
368
    k = 1;
369
    for (i = 1; i <= nb_groups; i++) {
370
        for (j = 0; j < group_size; j++)
371
            encoded_exp[k+j] = exp1[i];
372
        k += group_size;
373
    }
374

    
375
    return 4 + (nb_groups / 3) * 7;
376
}
377

    
378
/* return the size in bits taken by the mantissa */
379
static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
380
{
381
    int bits, mant, i;
382

    
383
    bits = 0;
384
    for (i = 0; i < nb_coefs; i++) {
385
        mant = m[i];
386
        switch (mant) {
387
        case 0:
388
            /* nothing */
389
            break;
390
        case 1:
391
            /* 3 mantissa in 5 bits */
392
            if (s->mant1_cnt == 0)
393
                bits += 5;
394
            if (++s->mant1_cnt == 3)
395
                s->mant1_cnt = 0;
396
            break;
397
        case 2:
398
            /* 3 mantissa in 7 bits */
399
            if (s->mant2_cnt == 0)
400
                bits += 7;
401
            if (++s->mant2_cnt == 3)
402
                s->mant2_cnt = 0;
403
            break;
404
        case 3:
405
            bits += 3;
406
            break;
407
        case 4:
408
            /* 2 mantissa in 7 bits */
409
            if (s->mant4_cnt == 0)
410
                bits += 7;
411
            if (++s->mant4_cnt == 2)
412
                s->mant4_cnt = 0;
413
            break;
414
        case 14:
415
            bits += 14;
416
            break;
417
        case 15:
418
            bits += 16;
419
            break;
420
        default:
421
            bits += mant - 1;
422
            break;
423
        }
424
    }
425
    return bits;
426
}
427

    
428

    
429
static void bit_alloc_masking(AC3EncodeContext *s,
430
                              uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
431
                              uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
432
                              int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
433
                              int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][50])
434
{
435
    int blk, ch;
436
    int16_t band_psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][50];
437

    
438
    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
439
        for (ch = 0; ch < s->channels; ch++) {
440
            if(exp_strategy[blk][ch] == EXP_REUSE) {
441
                memcpy(psd[blk][ch], psd[blk-1][ch], AC3_MAX_COEFS*sizeof(int16_t));
442
                memcpy(mask[blk][ch], mask[blk-1][ch], 50*sizeof(int16_t));
443
            } else {
444
                ff_ac3_bit_alloc_calc_psd(encoded_exp[blk][ch], 0,
445
                                          s->nb_coefs[ch],
446
                                          psd[blk][ch], band_psd[blk][ch]);
447
                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, band_psd[blk][ch],
448
                                           0, s->nb_coefs[ch],
449
                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
450
                                           ch == s->lfe_channel,
451
                                           DBA_NONE, 0, NULL, NULL, NULL,
452
                                           mask[blk][ch]);
453
            }
454
        }
455
    }
456
}
457

    
458
static int bit_alloc(AC3EncodeContext *s,
459
                     int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][50],
460
                     int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
461
                     uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
462
                     int frame_bits, int coarse_snr_offset, int fine_snr_offset)
463
{
464
    int i, ch;
465
    int snr_offset;
466

    
467
    snr_offset = (((coarse_snr_offset - 15) << 4) + fine_snr_offset) << 2;
468

    
469
    for (i = 0; i < AC3_MAX_BLOCKS; i++) {
470
        s->mant1_cnt = 0;
471
        s->mant2_cnt = 0;
472
        s->mant4_cnt = 0;
473
        for (ch = 0; ch < s->channels; ch++) {
474
            ff_ac3_bit_alloc_calc_bap(mask[i][ch], psd[i][ch], 0,
475
                                      s->nb_coefs[ch], snr_offset,
476
                                      s->bit_alloc.floor, ff_ac3_bap_tab,
477
                                      bap[i][ch]);
478
            frame_bits += compute_mantissa_size(s, bap[i][ch], s->nb_coefs[ch]);
479
        }
480
    }
481
    return 16 * s->frame_size - frame_bits;
482
}
483

    
484
#define SNR_INC1 4
485

    
486
static int compute_bit_allocation(AC3EncodeContext *s,
487
                                  uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
488
                                  uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
489
                                  uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
490
                                  int frame_bits)
491
{
492
    int i, ch;
493
    int coarse_snr_offset, fine_snr_offset;
494
    uint8_t bap1[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
495
    int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
496
    int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][50];
497
    static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
498

    
499
    /* init default parameters */
500
    s->slow_decay_code = 2;
501
    s->fast_decay_code = 1;
502
    s->slow_gain_code  = 1;
503
    s->db_per_bit_code = 2;
504
    s->floor_code      = 4;
505
    for (ch = 0; ch < s->channels; ch++)
506
        s->fast_gain_code[ch] = 4;
507

    
508
    /* compute real values */
509
    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
510
    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
511
    s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
512
    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
513
    s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
514

    
515
    /* header size */
516
    frame_bits += 65;
517
    // if (s->channel_mode == 2)
518
    //    frame_bits += 2;
519
    frame_bits += frame_bits_inc[s->channel_mode];
520

    
521
    /* audio blocks */
522
    for (i = 0; i < AC3_MAX_BLOCKS; i++) {
523
        frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
524
        if (s->channel_mode == AC3_CHMODE_STEREO) {
525
            frame_bits++; /* rematstr */
526
            if (!i)
527
                frame_bits += 4;
528
        }
529
        frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
530
        if (s->lfe_on)
531
            frame_bits++; /* lfeexpstr */
532
        for (ch = 0; ch < s->fbw_channels; ch++) {
533
            if (exp_strategy[i][ch] != EXP_REUSE)
534
                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
535
        }
536
        frame_bits++; /* baie */
537
        frame_bits++; /* snr */
538
        frame_bits += 2; /* delta / skip */
539
    }
540
    frame_bits++; /* cplinu for block 0 */
541
    /* bit alloc info */
542
    /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
543
    /* csnroffset[6] */
544
    /* (fsnoffset[4] + fgaincod[4]) * c */
545
    frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
546

    
547
    /* auxdatae, crcrsv */
548
    frame_bits += 2;
549

    
550
    /* CRC */
551
    frame_bits += 16;
552

    
553
    /* calculate psd and masking curve before doing bit allocation */
554
    bit_alloc_masking(s, encoded_exp, exp_strategy, psd, mask);
555

    
556
    /* now the big work begins : do the bit allocation. Modify the snr
557
       offset until we can pack everything in the requested frame size */
558

    
559
    coarse_snr_offset = s->coarse_snr_offset;
560
    while (coarse_snr_offset >= 0 &&
561
           bit_alloc(s, mask, psd, bap, frame_bits, coarse_snr_offset, 0) < 0)
562
        coarse_snr_offset -= SNR_INC1;
563
    if (coarse_snr_offset < 0) {
564
        av_log(NULL, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
565
        return -1;
566
    }
567
    while (coarse_snr_offset + SNR_INC1 <= 63 &&
568
           bit_alloc(s, mask, psd, bap1, frame_bits,
569
                     coarse_snr_offset + SNR_INC1, 0) >= 0) {
570
        coarse_snr_offset += SNR_INC1;
571
        memcpy(bap, bap1, sizeof(bap1));
572
    }
573
    while (coarse_snr_offset + 1 <= 63 &&
574
           bit_alloc(s, mask, psd, bap1, frame_bits, coarse_snr_offset + 1, 0) >= 0) {
575
        coarse_snr_offset++;
576
        memcpy(bap, bap1, sizeof(bap1));
577
    }
578

    
579
    fine_snr_offset = 0;
580
    while (fine_snr_offset + SNR_INC1 <= 15 &&
581
           bit_alloc(s, mask, psd, bap1, frame_bits,
582
                     coarse_snr_offset, fine_snr_offset + SNR_INC1) >= 0) {
583
        fine_snr_offset += SNR_INC1;
584
        memcpy(bap, bap1, sizeof(bap1));
585
    }
586
    while (fine_snr_offset + 1 <= 15 &&
587
           bit_alloc(s, mask, psd, bap1, frame_bits,
588
                     coarse_snr_offset, fine_snr_offset + 1) >= 0) {
589
        fine_snr_offset++;
590
        memcpy(bap, bap1, sizeof(bap1));
591
    }
592

    
593
    s->coarse_snr_offset = coarse_snr_offset;
594
    for (ch = 0; ch < s->channels; ch++)
595
        s->fine_snr_offset[ch] = fine_snr_offset;
596

    
597
    return 0;
598
}
599

    
600
/* output the AC-3 frame header */
601
static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
602
{
603
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
604

    
605
    put_bits(&s->pb, 16, 0x0b77);   /* frame header */
606
    put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
607
    put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
608
    put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min));
609
    put_bits(&s->pb, 5,  s->bitstream_id);
610
    put_bits(&s->pb, 3,  s->bitstream_mode);
611
    put_bits(&s->pb, 3,  s->channel_mode);
612
    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
613
        put_bits(&s->pb, 2, 1);     /* XXX -4.5 dB */
614
    if (s->channel_mode & 0x04)
615
        put_bits(&s->pb, 2, 1);     /* XXX -6 dB */
616
    if (s->channel_mode == AC3_CHMODE_STEREO)
617
        put_bits(&s->pb, 2, 0);     /* surround not indicated */
618
    put_bits(&s->pb, 1, s->lfe_on); /* LFE */
619
    put_bits(&s->pb, 5, 31);        /* dialog norm: -31 db */
620
    put_bits(&s->pb, 1, 0);         /* no compression control word */
621
    put_bits(&s->pb, 1, 0);         /* no lang code */
622
    put_bits(&s->pb, 1, 0);         /* no audio production info */
623
    put_bits(&s->pb, 1, 0);         /* no copyright */
624
    put_bits(&s->pb, 1, 1);         /* original bitstream */
625
    put_bits(&s->pb, 1, 0);         /* no time code 1 */
626
    put_bits(&s->pb, 1, 0);         /* no time code 2 */
627
    put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
628
}
629

    
630
/* symetric quantization on 'levels' levels */
631
static inline int sym_quant(int c, int e, int levels)
632
{
633
    int v;
634

    
635
    if (c >= 0) {
636
        v = (levels * (c << e)) >> 24;
637
        v = (v + 1) >> 1;
638
        v = (levels >> 1) + v;
639
    } else {
640
        v = (levels * ((-c) << e)) >> 24;
641
        v = (v + 1) >> 1;
642
        v = (levels >> 1) - v;
643
    }
644
    assert (v >= 0 && v < levels);
645
    return v;
646
}
647

    
648
/* asymetric quantization on 2^qbits levels */
649
static inline int asym_quant(int c, int e, int qbits)
650
{
651
    int lshift, m, v;
652

    
653
    lshift = e + qbits - 24;
654
    if (lshift >= 0)
655
        v = c << lshift;
656
    else
657
        v = c >> (-lshift);
658
    /* rounding */
659
    v = (v + 1) >> 1;
660
    m = (1 << (qbits-1));
661
    if (v >= m)
662
        v = m - 1;
663
    assert(v >= -m);
664
    return v & ((1 << qbits)-1);
665
}
666

    
667
/* Output one audio block. There are AC3_MAX_BLOCKS audio blocks in one AC-3
668
   frame */
669
static void output_audio_block(AC3EncodeContext *s,
670
                               uint8_t exp_strategy[AC3_MAX_CHANNELS],
671
                               uint8_t encoded_exp[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
672
                               uint8_t bap[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
673
                               int32_t mdct_coefs[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
674
                               int8_t global_exp[AC3_MAX_CHANNELS],
675
                               int block_num)
676
{
677
    int ch, nb_groups, group_size, i, baie, rbnd;
678
    uint8_t *p;
679
    uint16_t qmant[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
680
    int exp0, exp1;
681
    int mant1_cnt, mant2_cnt, mant4_cnt;
682
    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
683
    int delta0, delta1, delta2;
684

    
685
    for (ch = 0; ch < s->fbw_channels; ch++)
686
        put_bits(&s->pb, 1, 0); /* no block switching */
687
    for (ch = 0; ch < s->fbw_channels; ch++)
688
        put_bits(&s->pb, 1, 1); /* no dither */
689
    put_bits(&s->pb, 1, 0);     /* no dynamic range */
690
    if (!block_num) {
691
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
692
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
693
    } else {
694
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
695
    }
696

    
697
    if (s->channel_mode == AC3_CHMODE_STEREO) {
698
        if (!block_num) {
699
            /* first block must define rematrixing (rematstr) */
700
            put_bits(&s->pb, 1, 1);
701

    
702
            /* dummy rematrixing rematflg(1:4)=0 */
703
            for (rbnd = 0; rbnd < 4; rbnd++)
704
                put_bits(&s->pb, 1, 0);
705
        } else {
706
            /* no matrixing (but should be used in the future) */
707
            put_bits(&s->pb, 1, 0);
708
        }
709
    }
710

    
711
    /* exponent strategy */
712
    for (ch = 0; ch < s->fbw_channels; ch++)
713
        put_bits(&s->pb, 2, exp_strategy[ch]);
714

    
715
    if (s->lfe_on)
716
        put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
717

    
718
    /* bandwidth */
719
    for (ch = 0; ch < s->fbw_channels; ch++) {
720
        if (exp_strategy[ch] != EXP_REUSE)
721
            put_bits(&s->pb, 6, s->bandwidth_code[ch]);
722
    }
723

    
724
    /* exponents */
725
    for (ch = 0; ch < s->channels; ch++) {
726
        if (exp_strategy[ch] == EXP_REUSE)
727
            continue;
728
        group_size = exp_strategy[ch] + (exp_strategy[ch] == EXP_D45);
729
        nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
730
        p = encoded_exp[ch];
731

    
732
        /* first exponent */
733
        exp1 = *p++;
734
        put_bits(&s->pb, 4, exp1);
735

    
736
        /* next ones are delta encoded */
737
        for (i = 0; i < nb_groups; 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
            put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
755
        }
756

    
757
        if (ch != s->lfe_channel)
758
            put_bits(&s->pb, 2, 0); /* no gain range info */
759
    }
760

    
761
    /* bit allocation info */
762
    baie = (block_num == 0);
763
    put_bits(&s->pb, 1, baie);
764
    if (baie) {
765
        put_bits(&s->pb, 2, s->slow_decay_code);
766
        put_bits(&s->pb, 2, s->fast_decay_code);
767
        put_bits(&s->pb, 2, s->slow_gain_code);
768
        put_bits(&s->pb, 2, s->db_per_bit_code);
769
        put_bits(&s->pb, 3, s->floor_code);
770
    }
771

    
772
    /* snr offset */
773
    put_bits(&s->pb, 1, baie);
774
    if (baie) {
775
        put_bits(&s->pb, 6, s->coarse_snr_offset);
776
        for (ch = 0; ch < s->channels; ch++) {
777
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
778
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
779
        }
780
    }
781

    
782
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
783
    put_bits(&s->pb, 1, 0); /* no data to skip */
784

    
785
    /* mantissa encoding : we use two passes to handle the grouping. A
786
       one pass method may be faster, but it would necessitate to
787
       modify the output stream. */
788

    
789
    /* first pass: quantize */
790
    mant1_cnt = mant2_cnt = mant4_cnt = 0;
791
    qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
792

    
793
    for (ch = 0; ch < s->channels; ch++) {
794
        int b, c, e, v;
795

    
796
        for (i = 0; i < s->nb_coefs[ch]; i++) {
797
            c = mdct_coefs[ch][i];
798
            e = encoded_exp[ch][i] - global_exp[ch];
799
            b = bap[ch][i];
800
            switch (b) {
801
            case 0:
802
                v = 0;
803
                break;
804
            case 1:
805
                v = sym_quant(c, e, 3);
806
                switch (mant1_cnt) {
807
                case 0:
808
                    qmant1_ptr = &qmant[ch][i];
809
                    v = 9 * v;
810
                    mant1_cnt = 1;
811
                    break;
812
                case 1:
813
                    *qmant1_ptr += 3 * v;
814
                    mant1_cnt = 2;
815
                    v = 128;
816
                    break;
817
                default:
818
                    *qmant1_ptr += v;
819
                    mant1_cnt = 0;
820
                    v = 128;
821
                    break;
822
                }
823
                break;
824
            case 2:
825
                v = sym_quant(c, e, 5);
826
                switch (mant2_cnt) {
827
                case 0:
828
                    qmant2_ptr = &qmant[ch][i];
829
                    v = 25 * v;
830
                    mant2_cnt = 1;
831
                    break;
832
                case 1:
833
                    *qmant2_ptr += 5 * v;
834
                    mant2_cnt = 2;
835
                    v = 128;
836
                    break;
837
                default:
838
                    *qmant2_ptr += v;
839
                    mant2_cnt = 0;
840
                    v = 128;
841
                    break;
842
                }
843
                break;
844
            case 3:
845
                v = sym_quant(c, e, 7);
846
                break;
847
            case 4:
848
                v = sym_quant(c, e, 11);
849
                switch (mant4_cnt) {
850
                case 0:
851
                    qmant4_ptr = &qmant[ch][i];
852
                    v = 11 * v;
853
                    mant4_cnt = 1;
854
                    break;
855
                default:
856
                    *qmant4_ptr += v;
857
                    mant4_cnt = 0;
858
                    v = 128;
859
                    break;
860
                }
861
                break;
862
            case 5:
863
                v = sym_quant(c, e, 15);
864
                break;
865
            case 14:
866
                v = asym_quant(c, e, 14);
867
                break;
868
            case 15:
869
                v = asym_quant(c, e, 16);
870
                break;
871
            default:
872
                v = asym_quant(c, e, b - 1);
873
                break;
874
            }
875
            qmant[ch][i] = v;
876
        }
877
    }
878

    
879
    /* second pass : output the values */
880
    for (ch = 0; ch < s->channels; ch++) {
881
        int b, q;
882

    
883
        for (i = 0; i < s->nb_coefs[ch]; i++) {
884
            q = qmant[ch][i];
885
            b = bap[ch][i];
886
            switch (b) {
887
            case 0:                                         break;
888
            case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
889
            case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
890
            case 3:               put_bits(&s->pb,   3, q); break;
891
            case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
892
            case 14:              put_bits(&s->pb,  14, q); break;
893
            case 15:              put_bits(&s->pb,  16, q); break;
894
            default:              put_bits(&s->pb, b-1, q); break;
895
            }
896
        }
897
    }
898
}
899

    
900
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
901

    
902
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
903
{
904
    unsigned int c;
905

    
906
    c = 0;
907
    while (a) {
908
        if (a & 1)
909
            c ^= b;
910
        a = a >> 1;
911
        b = b << 1;
912
        if (b & (1 << 16))
913
            b ^= poly;
914
    }
915
    return c;
916
}
917

    
918
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
919
{
920
    unsigned int r;
921
    r = 1;
922
    while (n) {
923
        if (n & 1)
924
            r = mul_poly(r, a, poly);
925
        a = mul_poly(a, a, poly);
926
        n >>= 1;
927
    }
928
    return r;
929
}
930

    
931
/* fill the end of the frame and compute the two crcs */
932
static int output_frame_end(AC3EncodeContext *s)
933
{
934
    int frame_size, frame_size_58, n, crc1, crc2, crc_inv;
935
    uint8_t *frame;
936

    
937
    frame_size = s->frame_size; /* frame size in words */
938
    /* align to 8 bits */
939
    flush_put_bits(&s->pb);
940
    /* add zero bytes to reach the frame size */
941
    frame = s->pb.buf;
942
    n = 2 * s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
943
    assert(n >= 0);
944
    if (n > 0)
945
        memset(put_bits_ptr(&s->pb), 0, n);
946

    
947
    /* Now we must compute both crcs : this is not so easy for crc1
948
       because it is at the beginning of the data... */
949
    frame_size_58 = (frame_size >> 1) + (frame_size >> 3);
950

    
951
    crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
952
                             frame + 4, 2 * frame_size_58 - 4));
953

    
954
    /* XXX: could precompute crc_inv */
955
    crc_inv = pow_poly((CRC16_POLY >> 1), (16 * frame_size_58) - 16, CRC16_POLY);
956
    crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
957
    AV_WB16(frame + 2, crc1);
958

    
959
    crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
960
                             frame + 2 * frame_size_58,
961
                             (frame_size - frame_size_58) * 2 - 2));
962
    AV_WB16(frame + 2*frame_size - 2, crc2);
963

    
964
    return frame_size * 2;
965
}
966

    
967
static int AC3_encode_frame(AVCodecContext *avctx,
968
                            unsigned char *frame, int buf_size, void *data)
969
{
970
    AC3EncodeContext *s = avctx->priv_data;
971
    const int16_t *samples = data;
972
    int i, j, k, v, ch;
973
    int16_t input_samples[AC3_WINDOW_SIZE];
974
    int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
975
    uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
976
    uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
977
    uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
978
    uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
979
    int8_t exp_samples[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
980
    int frame_bits;
981

    
982
    frame_bits = 0;
983
    for (ch = 0; ch < s->channels; ch++) {
984
        int ich = s->channel_map[ch];
985
        /* fixed mdct to the six sub blocks & exponent computation */
986
        for (i = 0; i < AC3_MAX_BLOCKS; i++) {
987
            const int16_t *sptr;
988
            int sinc;
989

    
990
            /* compute input samples */
991
            memcpy(input_samples, s->last_samples[ich], AC3_BLOCK_SIZE * sizeof(int16_t));
992
            sinc = s->channels;
993
            sptr = samples + (sinc * AC3_BLOCK_SIZE * i) + ich;
994
            for (j = 0; j < AC3_BLOCK_SIZE; j++) {
995
                v = *sptr;
996
                input_samples[j + AC3_BLOCK_SIZE] = v;
997
                s->last_samples[ich][j] = v;
998
                sptr += sinc;
999
            }
1000

    
1001
            /* apply the MDCT window */
1002
            for (j = 0; j < AC3_BLOCK_SIZE; j++) {
1003
                input_samples[j]                   = MUL16(input_samples[j],
1004
                                                           ff_ac3_window[j]) >> 15;
1005
                input_samples[AC3_WINDOW_SIZE-j-1] = MUL16(input_samples[AC3_WINDOW_SIZE-j-1],
1006
                                                           ff_ac3_window[j]) >> 15;
1007
            }
1008

    
1009
            /* Normalize the samples to use the maximum available precision */
1010
            v = 14 - log2_tab(input_samples, AC3_WINDOW_SIZE);
1011
            if (v < 0)
1012
                v = 0;
1013
            exp_samples[i][ch] = v - 9;
1014
            lshift_tab(input_samples, AC3_WINDOW_SIZE, v);
1015

    
1016
            /* do the MDCT */
1017
            mdct512(mdct_coef[i][ch], input_samples);
1018

    
1019
            /* compute "exponents". We take into account the normalization there */
1020
            for (j = 0; j < AC3_MAX_COEFS; j++) {
1021
                int e;
1022
                v = abs(mdct_coef[i][ch][j]);
1023
                if (v == 0)
1024
                    e = 24;
1025
                else {
1026
                    e = 23 - av_log2(v) + exp_samples[i][ch];
1027
                    if (e >= 24) {
1028
                        e = 24;
1029
                        mdct_coef[i][ch][j] = 0;
1030
                    }
1031
                }
1032
                exp[i][ch][j] = e;
1033
            }
1034
        }
1035

    
1036
        compute_exp_strategy(exp_strategy, exp, ch, ch == s->lfe_channel);
1037

    
1038
        /* compute the exponents as the decoder will see them. The
1039
           EXP_REUSE case must be handled carefully : we select the
1040
           min of the exponents */
1041
        i = 0;
1042
        while (i < AC3_MAX_BLOCKS) {
1043
            j = i + 1;
1044
            while (j < AC3_MAX_BLOCKS && exp_strategy[j][ch] == EXP_REUSE) {
1045
                exponent_min(exp[i][ch], exp[j][ch], s->nb_coefs[ch]);
1046
                j++;
1047
            }
1048
            frame_bits += encode_exp(encoded_exp[i][ch],
1049
                                     exp[i][ch], s->nb_coefs[ch],
1050
                                     exp_strategy[i][ch]);
1051
            /* copy encoded exponents for reuse case */
1052
            for (k = i+1; k < j; k++) {
1053
                memcpy(encoded_exp[k][ch], encoded_exp[i][ch],
1054
                       s->nb_coefs[ch] * sizeof(uint8_t));
1055
            }
1056
            i = j;
1057
        }
1058
    }
1059

    
1060
    /* adjust for fractional frame sizes */
1061
    while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
1062
        s->bits_written    -= s->bit_rate;
1063
        s->samples_written -= s->sample_rate;
1064
    }
1065
    s->frame_size = s->frame_size_min + (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
1066
    s->bits_written    += s->frame_size * 16;
1067
    s->samples_written += AC3_FRAME_SIZE;
1068

    
1069
    compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
1070
    /* everything is known... let's output the frame */
1071
    output_frame_header(s, frame);
1072

    
1073
    for (i = 0; i < AC3_MAX_BLOCKS; i++) {
1074
        output_audio_block(s, exp_strategy[i], encoded_exp[i],
1075
                           bap[i], mdct_coef[i], exp_samples[i], i);
1076
    }
1077
    return output_frame_end(s);
1078
}
1079

    
1080
static av_cold int AC3_encode_close(AVCodecContext *avctx)
1081
{
1082
    av_freep(&avctx->coded_frame);
1083
    return 0;
1084
}
1085

    
1086
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1087
                                    int64_t *channel_layout)
1088
{
1089
    int ch_layout;
1090

    
1091
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
1092
        return -1;
1093
    if ((uint64_t)*channel_layout > 0x7FF)
1094
        return -1;
1095
    ch_layout = *channel_layout;
1096
    if (!ch_layout)
1097
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1098
    if (av_get_channel_layout_nb_channels(ch_layout) != channels)
1099
        return -1;
1100

    
1101
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1102
    s->channels     = channels;
1103
    s->fbw_channels = channels - s->lfe_on;
1104
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
1105
    if (s->lfe_on)
1106
        ch_layout -= AV_CH_LOW_FREQUENCY;
1107

    
1108
    switch (ch_layout) {
1109
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
1110
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
1111
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
1112
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
1113
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
1114
    case AV_CH_LAYOUT_QUAD:
1115
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
1116
    case AV_CH_LAYOUT_5POINT0:
1117
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
1118
    default:
1119
        return -1;
1120
    }
1121

    
1122
    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1123
    *channel_layout = ch_layout;
1124
    if (s->lfe_on)
1125
        *channel_layout |= AV_CH_LOW_FREQUENCY;
1126

    
1127
    return 0;
1128
}
1129

    
1130
static av_cold int AC3_encode_init(AVCodecContext *avctx)
1131
{
1132
    int freq = avctx->sample_rate;
1133
    int bitrate = avctx->bit_rate;
1134
    AC3EncodeContext *s = avctx->priv_data;
1135
    int i, j, ch;
1136
    int bw_code;
1137

    
1138
    avctx->frame_size = AC3_FRAME_SIZE;
1139

    
1140
    ac3_common_init();
1141

    
1142
    if (!avctx->channel_layout) {
1143
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1144
                                      "encoder will guess the layout, but it "
1145
                                      "might be incorrect.\n");
1146
    }
1147
    if (set_channel_info(s, avctx->channels, &avctx->channel_layout)) {
1148
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1149
        return -1;
1150
    }
1151

    
1152
    /* frequency */
1153
    for (i = 0; i < 3; i++) {
1154
        for (j = 0; j < 3; j++)
1155
            if ((ff_ac3_sample_rate_tab[j] >> i) == freq)
1156
                goto found;
1157
    }
1158
    return -1;
1159
 found:
1160
    s->sample_rate        = freq;
1161
    s->bit_alloc.sr_shift = i;
1162
    s->bit_alloc.sr_code  = j;
1163
    s->bitstream_id       = 8 + s->bit_alloc.sr_shift;
1164
    s->bitstream_mode     = 0; /* complete main audio service */
1165

    
1166
    /* bitrate & frame size */
1167
    for (i = 0; i < 19; i++) {
1168
        if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == bitrate)
1169
            break;
1170
    }
1171
    if (i == 19)
1172
        return -1;
1173
    s->bit_rate        = bitrate;
1174
    s->frame_size_code = i << 1;
1175
    s->frame_size_min  = ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
1176
    s->bits_written    = 0;
1177
    s->samples_written = 0;
1178
    s->frame_size      = s->frame_size_min;
1179

    
1180
    /* set bandwidth */
1181
    if(avctx->cutoff) {
1182
        /* calculate bandwidth based on user-specified cutoff frequency */
1183
        int cutoff     = av_clip(avctx->cutoff, 1, s->sample_rate >> 1);
1184
        int fbw_coeffs = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
1185
        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
1186
    } else {
1187
        /* use default bandwidth setting */
1188
        /* XXX: should compute the bandwidth according to the frame
1189
           size, so that we avoid annoying high frequency artifacts */
1190
        bw_code = 50;
1191
    }
1192
    for(ch=0;ch<s->fbw_channels;ch++) {
1193
        /* bandwidth for each channel */
1194
        s->bandwidth_code[ch] = bw_code;
1195
        s->nb_coefs[ch]       = bw_code * 3 + 73;
1196
    }
1197
    if (s->lfe_on)
1198
        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
1199

    
1200
    /* initial snr offset */
1201
    s->coarse_snr_offset = 40;
1202

    
1203
    mdct_init(9);
1204

    
1205
    avctx->coded_frame= avcodec_alloc_frame();
1206
    avctx->coded_frame->key_frame= 1;
1207

    
1208
    return 0;
1209
}
1210

    
1211
#ifdef TEST
1212
/*************************************************************************/
1213
/* TEST */
1214

    
1215
#include "libavutil/lfg.h"
1216

    
1217
#define FN (MDCT_SAMPLES/4)
1218

    
1219
static void fft_test(AVLFG *lfg)
1220
{
1221
    IComplex in[FN], in1[FN];
1222
    int k, n, i;
1223
    float sum_re, sum_im, a;
1224

    
1225
    for (i = 0; i < FN; i++) {
1226
        in[i].re = av_lfg_get(lfg) % 65535 - 32767;
1227
        in[i].im = av_lfg_get(lfg) % 65535 - 32767;
1228
        in1[i]   = in[i];
1229
    }
1230
    fft(in, 7);
1231

    
1232
    /* do it by hand */
1233
    for (k = 0; k < FN; k++) {
1234
        sum_re = 0;
1235
        sum_im = 0;
1236
        for (n = 0; n < FN; n++) {
1237
            a = -2 * M_PI * (n * k) / FN;
1238
            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1239
            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1240
        }
1241
        av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
1242
               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1243
    }
1244
}
1245

    
1246
static void mdct_test(AVLFG *lfg)
1247
{
1248
    int16_t input[MDCT_SAMPLES];
1249
    int32_t output[AC3_MAX_COEFS];
1250
    float input1[MDCT_SAMPLES];
1251
    float output1[AC3_MAX_COEFS];
1252
    float s, a, err, e, emax;
1253
    int i, k, n;
1254

    
1255
    for (i = 0; i < MDCT_SAMPLES; i++) {
1256
        input[i]  = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
1257
        input1[i] = input[i];
1258
    }
1259

    
1260
    mdct512(output, input);
1261

    
1262
    /* do it by hand */
1263
    for (k = 0; k < AC3_MAX_COEFS; k++) {
1264
        s = 0;
1265
        for (n = 0; n < MDCT_SAMPLES; n++) {
1266
            a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
1267
            s += input1[n] * cos(a);
1268
        }
1269
        output1[k] = -2 * s / MDCT_SAMPLES;
1270
    }
1271

    
1272
    err  = 0;
1273
    emax = 0;
1274
    for (i = 0; i < AC3_MAX_COEFS; i++) {
1275
        av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
1276
        e = output[i] - output1[i];
1277
        if (e > emax)
1278
            emax = e;
1279
        err += e * e;
1280
    }
1281
    av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
1282
}
1283

    
1284
int main(void)
1285
{
1286
    AVLFG lfg;
1287

    
1288
    av_log_set_level(AV_LOG_DEBUG);
1289
    mdct_init(9);
1290

    
1291
    fft_test(&lfg);
1292
    mdct_test(&lfg);
1293

    
1294
    return 0;
1295
}
1296
#endif /* TEST */
1297

    
1298
AVCodec ac3_encoder = {
1299
    "ac3",
1300
    AVMEDIA_TYPE_AUDIO,
1301
    CODEC_ID_AC3,
1302
    sizeof(AC3EncodeContext),
1303
    AC3_encode_init,
1304
    AC3_encode_frame,
1305
    AC3_encode_close,
1306
    NULL,
1307
    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1308
    .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1309
    .channel_layouts = (const int64_t[]){
1310
        AV_CH_LAYOUT_MONO,
1311
        AV_CH_LAYOUT_STEREO,
1312
        AV_CH_LAYOUT_2_1,
1313
        AV_CH_LAYOUT_SURROUND,
1314
        AV_CH_LAYOUT_2_2,
1315
        AV_CH_LAYOUT_QUAD,
1316
        AV_CH_LAYOUT_4POINT0,
1317
        AV_CH_LAYOUT_5POINT0,
1318
        AV_CH_LAYOUT_5POINT0_BACK,
1319
       (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
1320
       (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
1321
       (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
1322
       (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1323
       (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
1324
       (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
1325
       (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
1326
        AV_CH_LAYOUT_5POINT1,
1327
        AV_CH_LAYOUT_5POINT1_BACK,
1328
        0 },
1329
};