Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ 5d6e4c16

History | View | Annotate | Download (41.5 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
//#define DEBUG
27
//#define DEBUG_BITALLOC
28
#include "libavutil/crc.h"
29
#include "avcodec.h"
30
#include "libavutil/common.h" /* for av_reverse */
31
#include "put_bits.h"
32
#include "ac3.h"
33
#include "audioconvert.h"
34

    
35
typedef struct AC3EncodeContext {
36
    PutBitContext pb;
37
    int nb_channels;
38
    int nb_all_channels;
39
    int lfe_channel;
40
    const uint8_t *channel_map;
41
    int bit_rate;
42
    unsigned int sample_rate;
43
    unsigned int bitstream_id;
44
    unsigned int frame_size_min; /* minimum frame size in case rounding is necessary */
45
    unsigned int frame_size; /* current frame size in words */
46
    unsigned int bits_written;
47
    unsigned int samples_written;
48
    int sr_shift;
49
    unsigned int frame_size_code;
50
    unsigned int sr_code; /* frequency */
51
    unsigned int channel_mode;
52
    int lfe;
53
    unsigned int bitstream_mode;
54
    short last_samples[AC3_MAX_CHANNELS][256];
55
    unsigned int chbwcod[AC3_MAX_CHANNELS];
56
    int nb_coefs[AC3_MAX_CHANNELS];
57

    
58
    /* bitrate allocation control */
59
    int slow_gain_code, slow_decay_code, fast_decay_code, db_per_bit_code, floor_code;
60
    AC3BitAllocParameters bit_alloc;
61
    int coarse_snr_offset;
62
    int fast_gain_code[AC3_MAX_CHANNELS];
63
    int fine_snr_offset[AC3_MAX_CHANNELS];
64
    /* mantissa encoding */
65
    int mant1_cnt, mant2_cnt, mant4_cnt;
66
} AC3EncodeContext;
67

    
68
static int16_t costab[64];
69
static int16_t sintab[64];
70
static int16_t xcos1[128];
71
static int16_t xsin1[128];
72

    
73
#define MDCT_NBITS 9
74
#define N         (1 << MDCT_NBITS)
75

    
76
/* new exponents are sent if their Norm 1 exceed this number */
77
#define EXP_DIFF_THRESHOLD 1000
78

    
79
static inline int16_t fix15(float a)
80
{
81
    int v;
82
    v = (int)(a * (float)(1 << 15));
83
    if (v < -32767)
84
        v = -32767;
85
    else if (v > 32767)
86
        v = 32767;
87
    return v;
88
}
89

    
90
typedef struct IComplex {
91
    short re,im;
92
} IComplex;
93

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

    
99
    n = 1 << ln;
100

    
101
    for(i=0;i<(n/2);i++) {
102
        alpha = 2 * M_PI * (float)i / (float)n;
103
        costab[i] = fix15(cos(alpha));
104
        sintab[i] = fix15(sin(alpha));
105
    }
106
}
107

    
108
/* butter fly op */
109
#define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1) \
110
{\
111
  int ax, ay, bx, by;\
112
  bx=pre1;\
113
  by=pim1;\
114
  ax=qre1;\
115
  ay=qim1;\
116
  pre = (bx + ax) >> 1;\
117
  pim = (by + ay) >> 1;\
118
  qre = (bx - ax) >> 1;\
119
  qim = (by - ay) >> 1;\
120
}
121

    
122
#define CMUL(pre, pim, are, aim, bre, bim) \
123
{\
124
   pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;\
125
   pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;\
126
}
127

    
128

    
129
/* do a 2^n point complex fft on 2^ln points. */
130
static void fft(IComplex *z, int ln)
131
{
132
    int        j, l, np, np2;
133
    int        nblocks, nloops;
134
    register IComplex *p,*q;
135
    int tmp_re, tmp_im;
136

    
137
    np = 1 << ln;
138

    
139
    /* reverse */
140
    for(j=0;j<np;j++) {
141
        int k = av_reverse[j] >> (8 - ln);
142
        if (k < j)
143
            FFSWAP(IComplex, z[k], z[j]);
144
    }
145

    
146
    /* pass 0 */
147

    
148
    p=&z[0];
149
    j=(np >> 1);
150
    do {
151
        BF(p[0].re, p[0].im, p[1].re, p[1].im,
152
           p[0].re, p[0].im, p[1].re, p[1].im);
153
        p+=2;
154
    } while (--j != 0);
155

    
156
    /* pass 1 */
157

    
158
    p=&z[0];
159
    j=np >> 2;
160
    do {
161
        BF(p[0].re, p[0].im, p[2].re, p[2].im,
162
           p[0].re, p[0].im, p[2].re, p[2].im);
163
        BF(p[1].re, p[1].im, p[3].re, p[3].im,
164
           p[1].re, p[1].im, p[3].im, -p[3].re);
165
        p+=4;
166
    } while (--j != 0);
167

    
168
    /* pass 2 .. ln-1 */
169

    
170
    nblocks = np >> 3;
171
    nloops = 1 << 2;
172
    np2 = np >> 1;
173
    do {
174
        p = z;
175
        q = z + nloops;
176
        for (j = 0; j < nblocks; ++j) {
177

    
178
            BF(p->re, p->im, q->re, q->im,
179
               p->re, p->im, q->re, q->im);
180

    
181
            p++;
182
            q++;
183
            for(l = nblocks; l < np2; l += nblocks) {
184
                CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
185
                BF(p->re, p->im, q->re, q->im,
186
                   p->re, p->im, tmp_re, tmp_im);
187
                p++;
188
                q++;
189
            }
190
            p += nloops;
191
            q += nloops;
192
        }
193
        nblocks = nblocks >> 1;
194
        nloops = nloops << 1;
195
    } while (nblocks != 0);
196
}
197

    
198
/* do a 512 point mdct */
199
static void mdct512(int32_t *out, int16_t *in)
200
{
201
    int i, re, im, re1, im1;
202
    int16_t rot[N];
203
    IComplex x[N/4];
204

    
205
    /* shift to simplify computations */
206
    for(i=0;i<N/4;i++)
207
        rot[i] = -in[i + 3*N/4];
208
    for(i=N/4;i<N;i++)
209
        rot[i] = in[i - N/4];
210

    
211
    /* pre rotation */
212
    for(i=0;i<N/4;i++) {
213
        re = ((int)rot[2*i] - (int)rot[N-1-2*i]) >> 1;
214
        im = -((int)rot[N/2+2*i] - (int)rot[N/2-1-2*i]) >> 1;
215
        CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
216
    }
217

    
218
    fft(x, MDCT_NBITS - 2);
219

    
220
    /* post rotation */
221
    for(i=0;i<N/4;i++) {
222
        re = x[i].re;
223
        im = x[i].im;
224
        CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
225
        out[2*i] = im1;
226
        out[N/2-1-2*i] = re1;
227
    }
228
}
229

    
230
/* XXX: use another norm ? */
231
static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
232
{
233
    int sum, i;
234
    sum = 0;
235
    for(i=0;i<n;i++) {
236
        sum += abs(exp1[i] - exp2[i]);
237
    }
238
    return sum;
239
}
240

    
241
static void compute_exp_strategy(uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
242
                                 uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
243
                                 int ch, int is_lfe)
244
{
245
    int i, j;
246
    int exp_diff;
247

    
248
    /* estimate if the exponent variation & decide if they should be
249
       reused in the next frame */
250
    exp_strategy[0][ch] = EXP_NEW;
251
    for(i=1;i<NB_BLOCKS;i++) {
252
        exp_diff = calc_exp_diff(exp[i][ch], exp[i-1][ch], N/2);
253
        dprintf(NULL, "exp_diff=%d\n", exp_diff);
254
        if (exp_diff > EXP_DIFF_THRESHOLD)
255
            exp_strategy[i][ch] = EXP_NEW;
256
        else
257
            exp_strategy[i][ch] = EXP_REUSE;
258
    }
259
    if (is_lfe)
260
        return;
261

    
262
    /* now select the encoding strategy type : if exponents are often
263
       recoded, we use a coarse encoding */
264
    i = 0;
265
    while (i < NB_BLOCKS) {
266
        j = i + 1;
267
        while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE)
268
            j++;
269
        switch(j - i) {
270
        case 1:
271
            exp_strategy[i][ch] = EXP_D45;
272
            break;
273
        case 2:
274
        case 3:
275
            exp_strategy[i][ch] = EXP_D25;
276
            break;
277
        default:
278
            exp_strategy[i][ch] = EXP_D15;
279
            break;
280
        }
281
        i = j;
282
    }
283
}
284

    
285
/* set exp[i] to min(exp[i], exp1[i]) */
286
static void exponent_min(uint8_t exp[N/2], uint8_t exp1[N/2], int n)
287
{
288
    int i;
289

    
290
    for(i=0;i<n;i++) {
291
        if (exp1[i] < exp[i])
292
            exp[i] = exp1[i];
293
    }
294
}
295

    
296
/* update the exponents so that they are the ones the decoder will
297
   decode. Return the number of bits used to code the exponents */
298
static int encode_exp(uint8_t encoded_exp[N/2],
299
                      uint8_t exp[N/2],
300
                      int nb_exps,
301
                      int exp_strategy)
302
{
303
    int group_size, nb_groups, i, j, k, exp_min;
304
    uint8_t exp1[N/2];
305

    
306
    switch(exp_strategy) {
307
    case EXP_D15:
308
        group_size = 1;
309
        break;
310
    case EXP_D25:
311
        group_size = 2;
312
        break;
313
    default:
314
    case EXP_D45:
315
        group_size = 4;
316
        break;
317
    }
318
    nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
319

    
320
    /* for each group, compute the minimum exponent */
321
    exp1[0] = exp[0]; /* DC exponent is handled separately */
322
    k = 1;
323
    for(i=1;i<=nb_groups;i++) {
324
        exp_min = exp[k];
325
        assert(exp_min >= 0 && exp_min <= 24);
326
        for(j=1;j<group_size;j++) {
327
            if (exp[k+j] < exp_min)
328
                exp_min = exp[k+j];
329
        }
330
        exp1[i] = exp_min;
331
        k += group_size;
332
    }
333

    
334
    /* constraint for DC exponent */
335
    if (exp1[0] > 15)
336
        exp1[0] = 15;
337

    
338
    /* Decrease the delta between each groups to within 2
339
     * so that they can be differentially encoded */
340
    for (i=1;i<=nb_groups;i++)
341
        exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
342
    for (i=nb_groups-1;i>=0;i--)
343
        exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
344

    
345
    /* now we have the exponent values the decoder will see */
346
    encoded_exp[0] = exp1[0];
347
    k = 1;
348
    for(i=1;i<=nb_groups;i++) {
349
        for(j=0;j<group_size;j++) {
350
            encoded_exp[k+j] = exp1[i];
351
        }
352
        k += group_size;
353
    }
354

    
355
#if defined(DEBUG)
356
    av_log(NULL, AV_LOG_DEBUG, "exponents: strategy=%d\n", exp_strategy);
357
    for(i=0;i<=nb_groups * group_size;i++) {
358
        av_log(NULL, AV_LOG_DEBUG, "%d ", encoded_exp[i]);
359
    }
360
    av_log(NULL, AV_LOG_DEBUG, "\n");
361
#endif
362

    
363
    return 4 + (nb_groups / 3) * 7;
364
}
365

    
366
/* return the size in bits taken by the mantissa */
367
static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
368
{
369
    int bits, mant, i;
370

    
371
    bits = 0;
372
    for(i=0;i<nb_coefs;i++) {
373
        mant = m[i];
374
        switch(mant) {
375
        case 0:
376
            /* nothing */
377
            break;
378
        case 1:
379
            /* 3 mantissa in 5 bits */
380
            if (s->mant1_cnt == 0)
381
                bits += 5;
382
            if (++s->mant1_cnt == 3)
383
                s->mant1_cnt = 0;
384
            break;
385
        case 2:
386
            /* 3 mantissa in 7 bits */
387
            if (s->mant2_cnt == 0)
388
                bits += 7;
389
            if (++s->mant2_cnt == 3)
390
                s->mant2_cnt = 0;
391
            break;
392
        case 3:
393
            bits += 3;
394
            break;
395
        case 4:
396
            /* 2 mantissa in 7 bits */
397
            if (s->mant4_cnt == 0)
398
                bits += 7;
399
            if (++s->mant4_cnt == 2)
400
                s->mant4_cnt = 0;
401
            break;
402
        case 14:
403
            bits += 14;
404
            break;
405
        case 15:
406
            bits += 16;
407
            break;
408
        default:
409
            bits += mant - 1;
410
            break;
411
        }
412
    }
413
    return bits;
414
}
415

    
416

    
417
static void bit_alloc_masking(AC3EncodeContext *s,
418
                              uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
419
                              uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
420
                              int16_t psd[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
421
                              int16_t mask[NB_BLOCKS][AC3_MAX_CHANNELS][50])
422
{
423
    int blk, ch;
424
    int16_t band_psd[NB_BLOCKS][AC3_MAX_CHANNELS][50];
425

    
426
    for(blk=0; blk<NB_BLOCKS; blk++) {
427
        for(ch=0;ch<s->nb_all_channels;ch++) {
428
            if(exp_strategy[blk][ch] == EXP_REUSE) {
429
                memcpy(psd[blk][ch], psd[blk-1][ch], (N/2)*sizeof(int16_t));
430
                memcpy(mask[blk][ch], mask[blk-1][ch], 50*sizeof(int16_t));
431
            } else {
432
                ff_ac3_bit_alloc_calc_psd(encoded_exp[blk][ch], 0,
433
                                          s->nb_coefs[ch],
434
                                          psd[blk][ch], band_psd[blk][ch]);
435
                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, band_psd[blk][ch],
436
                                           0, s->nb_coefs[ch],
437
                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
438
                                           ch == s->lfe_channel,
439
                                           DBA_NONE, 0, NULL, NULL, NULL,
440
                                           mask[blk][ch]);
441
            }
442
        }
443
    }
444
}
445

    
446
static int bit_alloc(AC3EncodeContext *s,
447
                     int16_t mask[NB_BLOCKS][AC3_MAX_CHANNELS][50],
448
                     int16_t psd[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
449
                     uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
450
                     int frame_bits, int coarse_snr_offset, int fine_snr_offset)
451
{
452
    int i, ch;
453
    int snr_offset;
454

    
455
    snr_offset = (((coarse_snr_offset - 15) << 4) + fine_snr_offset) << 2;
456

    
457
    /* compute size */
458
    for(i=0;i<NB_BLOCKS;i++) {
459
        s->mant1_cnt = 0;
460
        s->mant2_cnt = 0;
461
        s->mant4_cnt = 0;
462
        for(ch=0;ch<s->nb_all_channels;ch++) {
463
            ff_ac3_bit_alloc_calc_bap(mask[i][ch], psd[i][ch], 0,
464
                                      s->nb_coefs[ch], snr_offset,
465
                                      s->bit_alloc.floor, ff_ac3_bap_tab,
466
                                      bap[i][ch]);
467
            frame_bits += compute_mantissa_size(s, bap[i][ch],
468
                                                 s->nb_coefs[ch]);
469
        }
470
    }
471
#if 0
472
    printf("csnr=%d fsnr=%d frame_bits=%d diff=%d\n",
473
           coarse_snr_offset, fine_snr_offset, frame_bits,
474
           16 * s->frame_size - ((frame_bits + 7) & ~7));
475
#endif
476
    return 16 * s->frame_size - frame_bits;
477
}
478

    
479
#define SNR_INC1 4
480

    
481
static int compute_bit_allocation(AC3EncodeContext *s,
482
                                  uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
483
                                  uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
484
                                  uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
485
                                  int frame_bits)
486
{
487
    int i, ch;
488
    int coarse_snr_offset, fine_snr_offset;
489
    uint8_t bap1[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
490
    int16_t psd[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
491
    int16_t mask[NB_BLOCKS][AC3_MAX_CHANNELS][50];
492
    static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
493

    
494
    /* init default parameters */
495
    s->slow_decay_code = 2;
496
    s->fast_decay_code = 1;
497
    s->slow_gain_code = 1;
498
    s->db_per_bit_code = 2;
499
    s->floor_code = 4;
500
    for(ch=0;ch<s->nb_all_channels;ch++)
501
        s->fast_gain_code[ch] = 4;
502

    
503
    /* compute real values */
504
    s->bit_alloc.sr_code = s->sr_code;
505
    s->bit_alloc.sr_shift = s->sr_shift;
506
    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->sr_shift;
507
    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->sr_shift;
508
    s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
509
    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
510
    s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
511

    
512
    /* header size */
513
    frame_bits += 65;
514
    // if (s->channel_mode == 2)
515
    //    frame_bits += 2;
516
    frame_bits += frame_bits_inc[s->channel_mode];
517

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

    
543
    /* auxdatae, crcrsv */
544
    frame_bits += 2;
545

    
546
    /* CRC */
547
    frame_bits += 16;
548

    
549
    /* calculate psd and masking curve before doing bit allocation */
550
    bit_alloc_masking(s, encoded_exp, exp_strategy, psd, mask);
551

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

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

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

    
589
    s->coarse_snr_offset = coarse_snr_offset;
590
    for(ch=0;ch<s->nb_all_channels;ch++)
591
        s->fine_snr_offset[ch] = fine_snr_offset;
592
#if defined(DEBUG_BITALLOC)
593
    {
594
        int j;
595

    
596
        for(i=0;i<6;i++) {
597
            for(ch=0;ch<s->nb_all_channels;ch++) {
598
                printf("Block #%d Ch%d:\n", i, ch);
599
                printf("bap=");
600
                for(j=0;j<s->nb_coefs[ch];j++) {
601
                    printf("%d ",bap[i][ch][j]);
602
                }
603
                printf("\n");
604
            }
605
        }
606
    }
607
#endif
608
    return 0;
609
}
610

    
611
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
612
                                    int64_t *channel_layout)
613
{
614
    int ch_layout;
615

    
616
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
617
        return -1;
618
    if ((uint64_t)*channel_layout > 0x7FF)
619
        return -1;
620
    ch_layout = *channel_layout;
621
    if (!ch_layout)
622
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
623
    if (avcodec_channel_layout_num_channels(ch_layout) != channels)
624
        return -1;
625

    
626
    s->lfe = !!(ch_layout & CH_LOW_FREQUENCY);
627
    s->nb_all_channels = channels;
628
    s->nb_channels = channels - s->lfe;
629
    s->lfe_channel = s->lfe ? s->nb_channels : -1;
630
    if (s->lfe)
631
        ch_layout -= CH_LOW_FREQUENCY;
632

    
633
    switch (ch_layout) {
634
    case CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
635
    case CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
636
    case CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
637
    case CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
638
    case CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
639
    case CH_LAYOUT_QUAD:
640
    case CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
641
    case CH_LAYOUT_5POINT0:
642
    case CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
643
    default:
644
        return -1;
645
    }
646

    
647
    s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe];
648
    *channel_layout = ch_layout;
649
    if (s->lfe)
650
        *channel_layout |= CH_LOW_FREQUENCY;
651

    
652
    return 0;
653
}
654

    
655
static av_cold int AC3_encode_init(AVCodecContext *avctx)
656
{
657
    int freq = avctx->sample_rate;
658
    int bitrate = avctx->bit_rate;
659
    AC3EncodeContext *s = avctx->priv_data;
660
    int i, j, ch;
661
    float alpha;
662
    int bw_code;
663

    
664
    avctx->frame_size = AC3_FRAME_SIZE;
665

    
666
    ac3_common_init();
667

    
668
    if (!avctx->channel_layout) {
669
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
670
                                      "encoder will guess the layout, but it "
671
                                      "might be incorrect.\n");
672
    }
673
    if (set_channel_info(s, avctx->channels, &avctx->channel_layout)) {
674
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
675
        return -1;
676
    }
677

    
678
    /* frequency */
679
    for(i=0;i<3;i++) {
680
        for(j=0;j<3;j++)
681
            if ((ff_ac3_sample_rate_tab[j] >> i) == freq)
682
                goto found;
683
    }
684
    return -1;
685
 found:
686
    s->sample_rate = freq;
687
    s->sr_shift = i;
688
    s->sr_code = j;
689
    s->bitstream_id = 8 + s->sr_shift;
690
    s->bitstream_mode = 0; /* complete main audio service */
691

    
692
    /* bitrate & frame size */
693
    for(i=0;i<19;i++) {
694
        if ((ff_ac3_bitrate_tab[i] >> s->sr_shift)*1000 == bitrate)
695
            break;
696
    }
697
    if (i == 19)
698
        return -1;
699
    s->bit_rate = bitrate;
700
    s->frame_size_code = i << 1;
701
    s->frame_size_min = ff_ac3_frame_size_tab[s->frame_size_code][s->sr_code];
702
    s->bits_written = 0;
703
    s->samples_written = 0;
704
    s->frame_size = s->frame_size_min;
705

    
706
    /* bit allocation init */
707
    if(avctx->cutoff) {
708
        /* calculate bandwidth based on user-specified cutoff frequency */
709
        int cutoff = av_clip(avctx->cutoff, 1, s->sample_rate >> 1);
710
        int fbw_coeffs = cutoff * 512 / s->sample_rate;
711
        bw_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
712
    } else {
713
        /* use default bandwidth setting */
714
        /* XXX: should compute the bandwidth according to the frame
715
           size, so that we avoid annoying high frequency artifacts */
716
        bw_code = 50;
717
    }
718
    for(ch=0;ch<s->nb_channels;ch++) {
719
        /* bandwidth for each channel */
720
        s->chbwcod[ch] = bw_code;
721
        s->nb_coefs[ch] = bw_code * 3 + 73;
722
    }
723
    if (s->lfe) {
724
        s->nb_coefs[s->lfe_channel] = 7; /* fixed */
725
    }
726
    /* initial snr offset */
727
    s->coarse_snr_offset = 40;
728

    
729
    /* mdct init */
730
    fft_init(MDCT_NBITS - 2);
731
    for(i=0;i<N/4;i++) {
732
        alpha = 2 * M_PI * (i + 1.0 / 8.0) / (float)N;
733
        xcos1[i] = fix15(-cos(alpha));
734
        xsin1[i] = fix15(-sin(alpha));
735
    }
736

    
737
    avctx->coded_frame= avcodec_alloc_frame();
738
    avctx->coded_frame->key_frame= 1;
739

    
740
    return 0;
741
}
742

    
743
/* output the AC-3 frame header */
744
static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
745
{
746
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
747

    
748
    put_bits(&s->pb, 16, 0x0b77); /* frame header */
749
    put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
750
    put_bits(&s->pb, 2, s->sr_code);
751
    put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min));
752
    put_bits(&s->pb, 5, s->bitstream_id);
753
    put_bits(&s->pb, 3, s->bitstream_mode);
754
    put_bits(&s->pb, 3, s->channel_mode);
755
    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
756
        put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
757
    if (s->channel_mode & 0x04)
758
        put_bits(&s->pb, 2, 1); /* XXX -6 dB */
759
    if (s->channel_mode == AC3_CHMODE_STEREO)
760
        put_bits(&s->pb, 2, 0); /* surround not indicated */
761
    put_bits(&s->pb, 1, s->lfe); /* LFE */
762
    put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
763
    put_bits(&s->pb, 1, 0); /* no compression control word */
764
    put_bits(&s->pb, 1, 0); /* no lang code */
765
    put_bits(&s->pb, 1, 0); /* no audio production info */
766
    put_bits(&s->pb, 1, 0); /* no copyright */
767
    put_bits(&s->pb, 1, 1); /* original bitstream */
768
    put_bits(&s->pb, 1, 0); /* no time code 1 */
769
    put_bits(&s->pb, 1, 0); /* no time code 2 */
770
    put_bits(&s->pb, 1, 0); /* no additional bit stream info */
771
}
772

    
773
/* symetric quantization on 'levels' levels */
774
static inline int sym_quant(int c, int e, int levels)
775
{
776
    int v;
777

    
778
    if (c >= 0) {
779
        v = (levels * (c << e)) >> 24;
780
        v = (v + 1) >> 1;
781
        v = (levels >> 1) + v;
782
    } else {
783
        v = (levels * ((-c) << e)) >> 24;
784
        v = (v + 1) >> 1;
785
        v = (levels >> 1) - v;
786
    }
787
    assert (v >= 0 && v < levels);
788
    return v;
789
}
790

    
791
/* asymetric quantization on 2^qbits levels */
792
static inline int asym_quant(int c, int e, int qbits)
793
{
794
    int lshift, m, v;
795

    
796
    lshift = e + qbits - 24;
797
    if (lshift >= 0)
798
        v = c << lshift;
799
    else
800
        v = c >> (-lshift);
801
    /* rounding */
802
    v = (v + 1) >> 1;
803
    m = (1 << (qbits-1));
804
    if (v >= m)
805
        v = m - 1;
806
    assert(v >= -m);
807
    return v & ((1 << qbits)-1);
808
}
809

    
810
/* Output one audio block. There are NB_BLOCKS audio blocks in one AC-3
811
   frame */
812
static void output_audio_block(AC3EncodeContext *s,
813
                               uint8_t exp_strategy[AC3_MAX_CHANNELS],
814
                               uint8_t encoded_exp[AC3_MAX_CHANNELS][N/2],
815
                               uint8_t bap[AC3_MAX_CHANNELS][N/2],
816
                               int32_t mdct_coefs[AC3_MAX_CHANNELS][N/2],
817
                               int8_t global_exp[AC3_MAX_CHANNELS],
818
                               int block_num)
819
{
820
    int ch, nb_groups, group_size, i, baie, rbnd;
821
    uint8_t *p;
822
    uint16_t qmant[AC3_MAX_CHANNELS][N/2];
823
    int exp0, exp1;
824
    int mant1_cnt, mant2_cnt, mant4_cnt;
825
    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
826
    int delta0, delta1, delta2;
827

    
828
    for(ch=0;ch<s->nb_channels;ch++)
829
        put_bits(&s->pb, 1, 0); /* 512 point MDCT */
830
    for(ch=0;ch<s->nb_channels;ch++)
831
        put_bits(&s->pb, 1, 1); /* no dither */
832
    put_bits(&s->pb, 1, 0); /* no dynamic range */
833
    if (block_num == 0) {
834
        /* for block 0, even if no coupling, we must say it. This is a
835
           waste of bit :-) */
836
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
837
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
838
    } else {
839
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
840
    }
841

    
842
    if (s->channel_mode == AC3_CHMODE_STEREO)
843
      {
844
        if(block_num==0)
845
          {
846
            /* first block must define rematrixing (rematstr)  */
847
            put_bits(&s->pb, 1, 1);
848

    
849
            /* dummy rematrixing rematflg(1:4)=0 */
850
            for (rbnd=0;rbnd<4;rbnd++)
851
              put_bits(&s->pb, 1, 0);
852
          }
853
        else
854
          {
855
            /* no matrixing (but should be used in the future) */
856
            put_bits(&s->pb, 1, 0);
857
          }
858
      }
859

    
860
#if defined(DEBUG)
861
    {
862
      static int count = 0;
863
      av_log(NULL, AV_LOG_DEBUG, "Block #%d (%d)\n", block_num, count++);
864
    }
865
#endif
866
    /* exponent strategy */
867
    for(ch=0;ch<s->nb_channels;ch++) {
868
        put_bits(&s->pb, 2, exp_strategy[ch]);
869
    }
870

    
871
    if (s->lfe) {
872
        put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
873
    }
874

    
875
    for(ch=0;ch<s->nb_channels;ch++) {
876
        if (exp_strategy[ch] != EXP_REUSE)
877
            put_bits(&s->pb, 6, s->chbwcod[ch]);
878
    }
879

    
880
    /* exponents */
881
    for (ch = 0; ch < s->nb_all_channels; ch++) {
882
        switch(exp_strategy[ch]) {
883
        case EXP_REUSE:
884
            continue;
885
        case EXP_D15:
886
            group_size = 1;
887
            break;
888
        case EXP_D25:
889
            group_size = 2;
890
            break;
891
        default:
892
        case EXP_D45:
893
            group_size = 4;
894
            break;
895
        }
896
        nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
897
        p = encoded_exp[ch];
898

    
899
        /* first exponent */
900
        exp1 = *p++;
901
        put_bits(&s->pb, 4, exp1);
902

    
903
        /* next ones are delta encoded */
904
        for(i=0;i<nb_groups;i++) {
905
            /* merge three delta in one code */
906
            exp0 = exp1;
907
            exp1 = p[0];
908
            p += group_size;
909
            delta0 = exp1 - exp0 + 2;
910

    
911
            exp0 = exp1;
912
            exp1 = p[0];
913
            p += group_size;
914
            delta1 = exp1 - exp0 + 2;
915

    
916
            exp0 = exp1;
917
            exp1 = p[0];
918
            p += group_size;
919
            delta2 = exp1 - exp0 + 2;
920

    
921
            put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
922
        }
923

    
924
        if (ch != s->lfe_channel)
925
            put_bits(&s->pb, 2, 0); /* no gain range info */
926
    }
927

    
928
    /* bit allocation info */
929
    baie = (block_num == 0);
930
    put_bits(&s->pb, 1, baie);
931
    if (baie) {
932
        put_bits(&s->pb, 2, s->slow_decay_code);
933
        put_bits(&s->pb, 2, s->fast_decay_code);
934
        put_bits(&s->pb, 2, s->slow_gain_code);
935
        put_bits(&s->pb, 2, s->db_per_bit_code);
936
        put_bits(&s->pb, 3, s->floor_code);
937
    }
938

    
939
    /* snr offset */
940
    put_bits(&s->pb, 1, baie); /* always present with bai */
941
    if (baie) {
942
        put_bits(&s->pb, 6, s->coarse_snr_offset);
943
        for(ch=0;ch<s->nb_all_channels;ch++) {
944
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
945
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
946
        }
947
    }
948

    
949
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
950
    put_bits(&s->pb, 1, 0); /* no data to skip */
951

    
952
    /* mantissa encoding : we use two passes to handle the grouping. A
953
       one pass method may be faster, but it would necessitate to
954
       modify the output stream. */
955

    
956
    /* first pass: quantize */
957
    mant1_cnt = mant2_cnt = mant4_cnt = 0;
958
    qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
959

    
960
    for (ch = 0; ch < s->nb_all_channels; ch++) {
961
        int b, c, e, v;
962

    
963
        for(i=0;i<s->nb_coefs[ch];i++) {
964
            c = mdct_coefs[ch][i];
965
            e = encoded_exp[ch][i] - global_exp[ch];
966
            b = bap[ch][i];
967
            switch(b) {
968
            case 0:
969
                v = 0;
970
                break;
971
            case 1:
972
                v = sym_quant(c, e, 3);
973
                switch(mant1_cnt) {
974
                case 0:
975
                    qmant1_ptr = &qmant[ch][i];
976
                    v = 9 * v;
977
                    mant1_cnt = 1;
978
                    break;
979
                case 1:
980
                    *qmant1_ptr += 3 * v;
981
                    mant1_cnt = 2;
982
                    v = 128;
983
                    break;
984
                default:
985
                    *qmant1_ptr += v;
986
                    mant1_cnt = 0;
987
                    v = 128;
988
                    break;
989
                }
990
                break;
991
            case 2:
992
                v = sym_quant(c, e, 5);
993
                switch(mant2_cnt) {
994
                case 0:
995
                    qmant2_ptr = &qmant[ch][i];
996
                    v = 25 * v;
997
                    mant2_cnt = 1;
998
                    break;
999
                case 1:
1000
                    *qmant2_ptr += 5 * v;
1001
                    mant2_cnt = 2;
1002
                    v = 128;
1003
                    break;
1004
                default:
1005
                    *qmant2_ptr += v;
1006
                    mant2_cnt = 0;
1007
                    v = 128;
1008
                    break;
1009
                }
1010
                break;
1011
            case 3:
1012
                v = sym_quant(c, e, 7);
1013
                break;
1014
            case 4:
1015
                v = sym_quant(c, e, 11);
1016
                switch(mant4_cnt) {
1017
                case 0:
1018
                    qmant4_ptr = &qmant[ch][i];
1019
                    v = 11 * v;
1020
                    mant4_cnt = 1;
1021
                    break;
1022
                default:
1023
                    *qmant4_ptr += v;
1024
                    mant4_cnt = 0;
1025
                    v = 128;
1026
                    break;
1027
                }
1028
                break;
1029
            case 5:
1030
                v = sym_quant(c, e, 15);
1031
                break;
1032
            case 14:
1033
                v = asym_quant(c, e, 14);
1034
                break;
1035
            case 15:
1036
                v = asym_quant(c, e, 16);
1037
                break;
1038
            default:
1039
                v = asym_quant(c, e, b - 1);
1040
                break;
1041
            }
1042
            qmant[ch][i] = v;
1043
        }
1044
    }
1045

    
1046
    /* second pass : output the values */
1047
    for (ch = 0; ch < s->nb_all_channels; ch++) {
1048
        int b, q;
1049

    
1050
        for(i=0;i<s->nb_coefs[ch];i++) {
1051
            q = qmant[ch][i];
1052
            b = bap[ch][i];
1053
            switch(b) {
1054
            case 0:
1055
                break;
1056
            case 1:
1057
                if (q != 128)
1058
                    put_bits(&s->pb, 5, q);
1059
                break;
1060
            case 2:
1061
                if (q != 128)
1062
                    put_bits(&s->pb, 7, q);
1063
                break;
1064
            case 3:
1065
                put_bits(&s->pb, 3, q);
1066
                break;
1067
            case 4:
1068
                if (q != 128)
1069
                    put_bits(&s->pb, 7, q);
1070
                break;
1071
            case 14:
1072
                put_bits(&s->pb, 14, q);
1073
                break;
1074
            case 15:
1075
                put_bits(&s->pb, 16, q);
1076
                break;
1077
            default:
1078
                put_bits(&s->pb, b - 1, q);
1079
                break;
1080
            }
1081
        }
1082
    }
1083
}
1084

    
1085
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1086

    
1087
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1088
{
1089
    unsigned int c;
1090

    
1091
    c = 0;
1092
    while (a) {
1093
        if (a & 1)
1094
            c ^= b;
1095
        a = a >> 1;
1096
        b = b << 1;
1097
        if (b & (1 << 16))
1098
            b ^= poly;
1099
    }
1100
    return c;
1101
}
1102

    
1103
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1104
{
1105
    unsigned int r;
1106
    r = 1;
1107
    while (n) {
1108
        if (n & 1)
1109
            r = mul_poly(r, a, poly);
1110
        a = mul_poly(a, a, poly);
1111
        n >>= 1;
1112
    }
1113
    return r;
1114
}
1115

    
1116

    
1117
/* compute log2(max(abs(tab[]))) */
1118
static int log2_tab(int16_t *tab, int n)
1119
{
1120
    int i, v;
1121

    
1122
    v = 0;
1123
    for(i=0;i<n;i++) {
1124
        v |= abs(tab[i]);
1125
    }
1126
    return av_log2(v);
1127
}
1128

    
1129
static void lshift_tab(int16_t *tab, int n, int lshift)
1130
{
1131
    int i;
1132

    
1133
    if (lshift > 0) {
1134
        for(i=0;i<n;i++) {
1135
            tab[i] <<= lshift;
1136
        }
1137
    } else if (lshift < 0) {
1138
        lshift = -lshift;
1139
        for(i=0;i<n;i++) {
1140
            tab[i] >>= lshift;
1141
        }
1142
    }
1143
}
1144

    
1145
/* fill the end of the frame and compute the two crcs */
1146
static int output_frame_end(AC3EncodeContext *s)
1147
{
1148
    int frame_size, frame_size_58, n, crc1, crc2, crc_inv;
1149
    uint8_t *frame;
1150

    
1151
    frame_size = s->frame_size; /* frame size in words */
1152
    /* align to 8 bits */
1153
    flush_put_bits(&s->pb);
1154
    /* add zero bytes to reach the frame size */
1155
    frame = s->pb.buf;
1156
    n = 2 * s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1157
    assert(n >= 0);
1158
    if(n>0)
1159
      memset(put_bits_ptr(&s->pb), 0, n);
1160

    
1161
    /* Now we must compute both crcs : this is not so easy for crc1
1162
       because it is at the beginning of the data... */
1163
    frame_size_58 = (frame_size >> 1) + (frame_size >> 3);
1164
    crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1165
                           frame + 4, 2 * frame_size_58 - 4));
1166
    /* XXX: could precompute crc_inv */
1167
    crc_inv = pow_poly((CRC16_POLY >> 1), (16 * frame_size_58) - 16, CRC16_POLY);
1168
    crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1169
    AV_WB16(frame+2,crc1);
1170

    
1171
    crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1172
                           frame + 2 * frame_size_58,
1173
                           (frame_size - frame_size_58) * 2 - 2));
1174
    AV_WB16(frame+2*frame_size-2,crc2);
1175

    
1176
    //    printf("n=%d frame_size=%d\n", n, frame_size);
1177
    return frame_size * 2;
1178
}
1179

    
1180
static int AC3_encode_frame(AVCodecContext *avctx,
1181
                            unsigned char *frame, int buf_size, void *data)
1182
{
1183
    AC3EncodeContext *s = avctx->priv_data;
1184
    const int16_t *samples = data;
1185
    int i, j, k, v, ch;
1186
    int16_t input_samples[N];
1187
    int32_t mdct_coef[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1188
    uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1189
    uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS];
1190
    uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1191
    uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1192
    int8_t exp_samples[NB_BLOCKS][AC3_MAX_CHANNELS];
1193
    int frame_bits;
1194

    
1195
    frame_bits = 0;
1196
    for(ch=0;ch<s->nb_all_channels;ch++) {
1197
        int ich = s->channel_map[ch];
1198
        /* fixed mdct to the six sub blocks & exponent computation */
1199
        for(i=0;i<NB_BLOCKS;i++) {
1200
            const int16_t *sptr;
1201
            int sinc;
1202

    
1203
            /* compute input samples */
1204
            memcpy(input_samples, s->last_samples[ich], N/2 * sizeof(int16_t));
1205
            sinc = s->nb_all_channels;
1206
            sptr = samples + (sinc * (N/2) * i) + ich;
1207
            for(j=0;j<N/2;j++) {
1208
                v = *sptr;
1209
                input_samples[j + N/2] = v;
1210
                s->last_samples[ich][j] = v;
1211
                sptr += sinc;
1212
            }
1213

    
1214
            /* apply the MDCT window */
1215
            for(j=0;j<N/2;j++) {
1216
                input_samples[j] = MUL16(input_samples[j],
1217
                                         ff_ac3_window[j]) >> 15;
1218
                input_samples[N-j-1] = MUL16(input_samples[N-j-1],
1219
                                             ff_ac3_window[j]) >> 15;
1220
            }
1221

    
1222
            /* Normalize the samples to use the maximum available
1223
               precision */
1224
            v = 14 - log2_tab(input_samples, N);
1225
            if (v < 0)
1226
                v = 0;
1227
            exp_samples[i][ch] = v - 9;
1228
            lshift_tab(input_samples, N, v);
1229

    
1230
            /* do the MDCT */
1231
            mdct512(mdct_coef[i][ch], input_samples);
1232

    
1233
            /* compute "exponents". We take into account the
1234
               normalization there */
1235
            for(j=0;j<N/2;j++) {
1236
                int e;
1237
                v = abs(mdct_coef[i][ch][j]);
1238
                if (v == 0)
1239
                    e = 24;
1240
                else {
1241
                    e = 23 - av_log2(v) + exp_samples[i][ch];
1242
                    if (e >= 24) {
1243
                        e = 24;
1244
                        mdct_coef[i][ch][j] = 0;
1245
                    }
1246
                }
1247
                exp[i][ch][j] = e;
1248
            }
1249
        }
1250

    
1251
        compute_exp_strategy(exp_strategy, exp, ch, ch == s->lfe_channel);
1252

    
1253
        /* compute the exponents as the decoder will see them. The
1254
           EXP_REUSE case must be handled carefully : we select the
1255
           min of the exponents */
1256
        i = 0;
1257
        while (i < NB_BLOCKS) {
1258
            j = i + 1;
1259
            while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE) {
1260
                exponent_min(exp[i][ch], exp[j][ch], s->nb_coefs[ch]);
1261
                j++;
1262
            }
1263
            frame_bits += encode_exp(encoded_exp[i][ch],
1264
                                     exp[i][ch], s->nb_coefs[ch],
1265
                                     exp_strategy[i][ch]);
1266
            /* copy encoded exponents for reuse case */
1267
            for(k=i+1;k<j;k++) {
1268
                memcpy(encoded_exp[k][ch], encoded_exp[i][ch],
1269
                       s->nb_coefs[ch] * sizeof(uint8_t));
1270
            }
1271
            i = j;
1272
        }
1273
    }
1274

    
1275
    /* adjust for fractional frame sizes */
1276
    while(s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
1277
        s->bits_written -= s->bit_rate;
1278
        s->samples_written -= s->sample_rate;
1279
    }
1280
    s->frame_size = s->frame_size_min + (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
1281
    s->bits_written += s->frame_size * 16;
1282
    s->samples_written += AC3_FRAME_SIZE;
1283

    
1284
    compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
1285
    /* everything is known... let's output the frame */
1286
    output_frame_header(s, frame);
1287

    
1288
    for(i=0;i<NB_BLOCKS;i++) {
1289
        output_audio_block(s, exp_strategy[i], encoded_exp[i],
1290
                           bap[i], mdct_coef[i], exp_samples[i], i);
1291
    }
1292
    return output_frame_end(s);
1293
}
1294

    
1295
static av_cold int AC3_encode_close(AVCodecContext *avctx)
1296
{
1297
    av_freep(&avctx->coded_frame);
1298
    return 0;
1299
}
1300

    
1301
#if 0
1302
/*************************************************************************/
1303
/* TEST */
1304

1305
#undef random
1306
#define FN (N/4)
1307

1308
void fft_test(void)
1309
{
1310
    IComplex in[FN], in1[FN];
1311
    int k, n, i;
1312
    float sum_re, sum_im, a;
1313

1314
    /* FFT test */
1315

1316
    for(i=0;i<FN;i++) {
1317
        in[i].re = random() % 65535 - 32767;
1318
        in[i].im = random() % 65535 - 32767;
1319
        in1[i] = in[i];
1320
    }
1321
    fft(in, 7);
1322

1323
    /* do it by hand */
1324
    for(k=0;k<FN;k++) {
1325
        sum_re = 0;
1326
        sum_im = 0;
1327
        for(n=0;n<FN;n++) {
1328
            a = -2 * M_PI * (n * k) / FN;
1329
            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1330
            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1331
        }
1332
        printf("%3d: %6d,%6d %6.0f,%6.0f\n",
1333
               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1334
    }
1335
}
1336

1337
void mdct_test(void)
1338
{
1339
    int16_t input[N];
1340
    int32_t output[N/2];
1341
    float input1[N];
1342
    float output1[N/2];
1343
    float s, a, err, e, emax;
1344
    int i, k, n;
1345

1346
    for(i=0;i<N;i++) {
1347
        input[i] = (random() % 65535 - 32767) * 9 / 10;
1348
        input1[i] = input[i];
1349
    }
1350

1351
    mdct512(output, input);
1352

1353
    /* do it by hand */
1354
    for(k=0;k<N/2;k++) {
1355
        s = 0;
1356
        for(n=0;n<N;n++) {
1357
            a = (2*M_PI*(2*n+1+N/2)*(2*k+1) / (4 * N));
1358
            s += input1[n] * cos(a);
1359
        }
1360
        output1[k] = -2 * s / N;
1361
    }
1362

1363
    err = 0;
1364
    emax = 0;
1365
    for(i=0;i<N/2;i++) {
1366
        printf("%3d: %7d %7.0f\n", i, output[i], output1[i]);
1367
        e = output[i] - output1[i];
1368
        if (e > emax)
1369
            emax = e;
1370
        err += e * e;
1371
    }
1372
    printf("err2=%f emax=%f\n", err / (N/2), emax);
1373
}
1374

1375
void test_ac3(void)
1376
{
1377
    AC3EncodeContext ctx;
1378
    unsigned char frame[AC3_MAX_CODED_FRAME_SIZE];
1379
    short samples[AC3_FRAME_SIZE];
1380
    int ret, i;
1381

1382
    AC3_encode_init(&ctx, 44100, 64000, 1);
1383

1384
    fft_test();
1385
    mdct_test();
1386

1387
    for(i=0;i<AC3_FRAME_SIZE;i++)
1388
        samples[i] = (int)(sin(2*M_PI*i*1000.0/44100) * 10000);
1389
    ret = AC3_encode_frame(&ctx, frame, samples);
1390
    printf("ret=%d\n", ret);
1391
}
1392
#endif
1393

    
1394
AVCodec ac3_encoder = {
1395
    "ac3",
1396
    AVMEDIA_TYPE_AUDIO,
1397
    CODEC_ID_AC3,
1398
    sizeof(AC3EncodeContext),
1399
    AC3_encode_init,
1400
    AC3_encode_frame,
1401
    AC3_encode_close,
1402
    NULL,
1403
    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1404
    .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1405
    .channel_layouts = (const int64_t[]){
1406
        CH_LAYOUT_MONO,
1407
        CH_LAYOUT_STEREO,
1408
        CH_LAYOUT_2_1,
1409
        CH_LAYOUT_SURROUND,
1410
        CH_LAYOUT_2_2,
1411
        CH_LAYOUT_QUAD,
1412
        CH_LAYOUT_4POINT0,
1413
        CH_LAYOUT_5POINT0,
1414
        CH_LAYOUT_5POINT0_BACK,
1415
       (CH_LAYOUT_MONO     | CH_LOW_FREQUENCY),
1416
       (CH_LAYOUT_STEREO   | CH_LOW_FREQUENCY),
1417
       (CH_LAYOUT_2_1      | CH_LOW_FREQUENCY),
1418
       (CH_LAYOUT_SURROUND | CH_LOW_FREQUENCY),
1419
       (CH_LAYOUT_2_2      | CH_LOW_FREQUENCY),
1420
       (CH_LAYOUT_QUAD     | CH_LOW_FREQUENCY),
1421
       (CH_LAYOUT_4POINT0  | CH_LOW_FREQUENCY),
1422
        CH_LAYOUT_5POINT1,
1423
        CH_LAYOUT_5POINT1_BACK,
1424
        0 },
1425
};