Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ 2d2692eb

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 "libavcore/audioconvert.h"
29
#include "libavutil/crc.h"
30
#include "avcodec.h"
31
#include "libavutil/common.h" /* for av_reverse */
32
#include "put_bits.h"
33
#include "ac3.h"
34
#include "audioconvert.h"
35

    
36
typedef struct AC3EncodeContext {
37
    PutBitContext pb;
38

    
39
    int bitstream_id;
40
    int bitstream_mode;
41

    
42
    int bit_rate;
43
    int sample_rate;
44
    int sr_shift;
45
    int sr_code; /* frequency */
46

    
47
    int frame_size_min; /* minimum frame size in case rounding is necessary */
48
    int frame_size; /* current frame size in words */
49
    int frame_size_code;
50
    int bits_written;
51
    int samples_written;
52

    
53
    int fbw_channels;
54
    int channels;
55
    int lfe_on;
56
    int lfe_channel;
57
    int channel_mode;
58
    const uint8_t *channel_map;
59

    
60
    int bandwidth_code[AC3_MAX_CHANNELS];
61
    int nb_coefs[AC3_MAX_CHANNELS];
62

    
63
    /* bitrate allocation control */
64
    int slow_gain_code, slow_decay_code, fast_decay_code, db_per_bit_code, floor_code;
65
    AC3BitAllocParameters bit_alloc;
66
    int coarse_snr_offset;
67
    int fast_gain_code[AC3_MAX_CHANNELS];
68
    int fine_snr_offset[AC3_MAX_CHANNELS];
69

    
70
    /* mantissa encoding */
71
    int mant1_cnt, mant2_cnt, mant4_cnt;
72

    
73
    int16_t last_samples[AC3_MAX_CHANNELS][256];
74
} AC3EncodeContext;
75

    
76
static int16_t costab[64];
77
static int16_t sintab[64];
78
static int16_t xcos1[128];
79
static int16_t xsin1[128];
80

    
81
#define MDCT_NBITS 9
82
#define N         (1 << MDCT_NBITS)
83

    
84
/* new exponents are sent if their Norm 1 exceed this number */
85
#define EXP_DIFF_THRESHOLD 1000
86

    
87
static inline int16_t fix15(float a)
88
{
89
    int v;
90
    v = (int)(a * (float)(1 << 15));
91
    if (v < -32767)
92
        v = -32767;
93
    else if (v > 32767)
94
        v = 32767;
95
    return v;
96
}
97

    
98
typedef struct IComplex {
99
    int16_t re,im;
100
} IComplex;
101

    
102
static av_cold void fft_init(int ln)
103
{
104
    int i, n;
105
    float alpha;
106

    
107
    n = 1 << ln;
108

    
109
    for(i=0;i<(n/2);i++) {
110
        alpha = 2 * M_PI * (float)i / (float)n;
111
        costab[i] = fix15(cos(alpha));
112
        sintab[i] = fix15(sin(alpha));
113
    }
114
}
115

    
116
/* butter fly op */
117
#define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1) \
118
{\
119
  int ax, ay, bx, by;\
120
  bx=pre1;\
121
  by=pim1;\
122
  ax=qre1;\
123
  ay=qim1;\
124
  pre = (bx + ax) >> 1;\
125
  pim = (by + ay) >> 1;\
126
  qre = (bx - ax) >> 1;\
127
  qim = (by - ay) >> 1;\
128
}
129

    
130
#define CMUL(pre, pim, are, aim, bre, bim) \
131
{\
132
   pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;\
133
   pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;\
134
}
135

    
136

    
137
/* do a 2^n point complex fft on 2^ln points. */
138
static void fft(IComplex *z, int ln)
139
{
140
    int        j, l, np, np2;
141
    int        nblocks, nloops;
142
    register IComplex *p,*q;
143
    int tmp_re, tmp_im;
144

    
145
    np = 1 << ln;
146

    
147
    /* reverse */
148
    for(j=0;j<np;j++) {
149
        int k = av_reverse[j] >> (8 - ln);
150
        if (k < j)
151
            FFSWAP(IComplex, z[k], z[j]);
152
    }
153

    
154
    /* pass 0 */
155

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

    
164
    /* pass 1 */
165

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

    
176
    /* pass 2 .. ln-1 */
177

    
178
    nblocks = np >> 3;
179
    nloops = 1 << 2;
180
    np2 = np >> 1;
181
    do {
182
        p = z;
183
        q = z + nloops;
184
        for (j = 0; j < nblocks; ++j) {
185

    
186
            BF(p->re, p->im, q->re, q->im,
187
               p->re, p->im, q->re, q->im);
188

    
189
            p++;
190
            q++;
191
            for(l = nblocks; l < np2; l += nblocks) {
192
                CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
193
                BF(p->re, p->im, q->re, q->im,
194
                   p->re, p->im, tmp_re, tmp_im);
195
                p++;
196
                q++;
197
            }
198
            p += nloops;
199
            q += nloops;
200
        }
201
        nblocks = nblocks >> 1;
202
        nloops = nloops << 1;
203
    } while (nblocks != 0);
204
}
205

    
206
/* do a 512 point mdct */
207
static void mdct512(int32_t *out, int16_t *in)
208
{
209
    int i, re, im, re1, im1;
210
    int16_t rot[N];
211
    IComplex x[N/4];
212

    
213
    /* shift to simplify computations */
214
    for(i=0;i<N/4;i++)
215
        rot[i] = -in[i + 3*N/4];
216
    for(i=N/4;i<N;i++)
217
        rot[i] = in[i - N/4];
218

    
219
    /* pre rotation */
220
    for(i=0;i<N/4;i++) {
221
        re = ((int)rot[2*i] - (int)rot[N-1-2*i]) >> 1;
222
        im = -((int)rot[N/2+2*i] - (int)rot[N/2-1-2*i]) >> 1;
223
        CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
224
    }
225

    
226
    fft(x, MDCT_NBITS - 2);
227

    
228
    /* post rotation */
229
    for(i=0;i<N/4;i++) {
230
        re = x[i].re;
231
        im = x[i].im;
232
        CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
233
        out[2*i] = im1;
234
        out[N/2-1-2*i] = re1;
235
    }
236
}
237

    
238
/* XXX: use another norm ? */
239
static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
240
{
241
    int sum, i;
242
    sum = 0;
243
    for(i=0;i<n;i++) {
244
        sum += abs(exp1[i] - exp2[i]);
245
    }
246
    return sum;
247
}
248

    
249
static void compute_exp_strategy(uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
250
                                 uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
251
                                 int ch, int is_lfe)
252
{
253
    int i, j;
254
    int exp_diff;
255

    
256
    /* estimate if the exponent variation & decide if they should be
257
       reused in the next frame */
258
    exp_strategy[0][ch] = EXP_NEW;
259
    for(i=1;i<NB_BLOCKS;i++) {
260
        exp_diff = calc_exp_diff(exp[i][ch], exp[i-1][ch], N/2);
261
        dprintf(NULL, "exp_diff=%d\n", exp_diff);
262
        if (exp_diff > EXP_DIFF_THRESHOLD)
263
            exp_strategy[i][ch] = EXP_NEW;
264
        else
265
            exp_strategy[i][ch] = EXP_REUSE;
266
    }
267
    if (is_lfe)
268
        return;
269

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

    
293
/* set exp[i] to min(exp[i], exp1[i]) */
294
static void exponent_min(uint8_t exp[N/2], uint8_t exp1[N/2], int n)
295
{
296
    int i;
297

    
298
    for(i=0;i<n;i++) {
299
        if (exp1[i] < exp[i])
300
            exp[i] = exp1[i];
301
    }
302
}
303

    
304
/* update the exponents so that they are the ones the decoder will
305
   decode. Return the number of bits used to code the exponents */
306
static int encode_exp(uint8_t encoded_exp[N/2],
307
                      uint8_t exp[N/2],
308
                      int nb_exps,
309
                      int exp_strategy)
310
{
311
    int group_size, nb_groups, i, j, k, exp_min;
312
    uint8_t exp1[N/2];
313

    
314
    switch(exp_strategy) {
315
    case EXP_D15:
316
        group_size = 1;
317
        break;
318
    case EXP_D25:
319
        group_size = 2;
320
        break;
321
    default:
322
    case EXP_D45:
323
        group_size = 4;
324
        break;
325
    }
326
    nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
327

    
328
    /* for each group, compute the minimum exponent */
329
    exp1[0] = exp[0]; /* DC exponent is handled separately */
330
    k = 1;
331
    for(i=1;i<=nb_groups;i++) {
332
        exp_min = exp[k];
333
        assert(exp_min >= 0 && exp_min <= 24);
334
        for(j=1;j<group_size;j++) {
335
            if (exp[k+j] < exp_min)
336
                exp_min = exp[k+j];
337
        }
338
        exp1[i] = exp_min;
339
        k += group_size;
340
    }
341

    
342
    /* constraint for DC exponent */
343
    if (exp1[0] > 15)
344
        exp1[0] = 15;
345

    
346
    /* Decrease the delta between each groups to within 2
347
     * so that they can be differentially encoded */
348
    for (i=1;i<=nb_groups;i++)
349
        exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
350
    for (i=nb_groups-1;i>=0;i--)
351
        exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
352

    
353
    /* now we have the exponent values the decoder will see */
354
    encoded_exp[0] = exp1[0];
355
    k = 1;
356
    for(i=1;i<=nb_groups;i++) {
357
        for(j=0;j<group_size;j++) {
358
            encoded_exp[k+j] = exp1[i];
359
        }
360
        k += group_size;
361
    }
362

    
363
#if defined(DEBUG)
364
    av_log(NULL, AV_LOG_DEBUG, "exponents: strategy=%d\n", exp_strategy);
365
    for(i=0;i<=nb_groups * group_size;i++) {
366
        av_log(NULL, AV_LOG_DEBUG, "%d ", encoded_exp[i]);
367
    }
368
    av_log(NULL, AV_LOG_DEBUG, "\n");
369
#endif
370

    
371
    return 4 + (nb_groups / 3) * 7;
372
}
373

    
374
/* return the size in bits taken by the mantissa */
375
static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
376
{
377
    int bits, mant, i;
378

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

    
424

    
425
static void bit_alloc_masking(AC3EncodeContext *s,
426
                              uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
427
                              uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
428
                              int16_t psd[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
429
                              int16_t mask[NB_BLOCKS][AC3_MAX_CHANNELS][50])
430
{
431
    int blk, ch;
432
    int16_t band_psd[NB_BLOCKS][AC3_MAX_CHANNELS][50];
433

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

    
454
static int bit_alloc(AC3EncodeContext *s,
455
                     int16_t mask[NB_BLOCKS][AC3_MAX_CHANNELS][50],
456
                     int16_t psd[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
457
                     uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
458
                     int frame_bits, int coarse_snr_offset, int fine_snr_offset)
459
{
460
    int i, ch;
461
    int snr_offset;
462

    
463
    snr_offset = (((coarse_snr_offset - 15) << 4) + fine_snr_offset) << 2;
464

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

    
487
#define SNR_INC1 4
488

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

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

    
511
    /* compute real values */
512
    s->bit_alloc.sr_code = s->sr_code;
513
    s->bit_alloc.sr_shift = s->sr_shift;
514
    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->sr_shift;
515
    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->sr_shift;
516
    s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
517
    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
518
    s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
519

    
520
    /* header size */
521
    frame_bits += 65;
522
    // if (s->channel_mode == 2)
523
    //    frame_bits += 2;
524
    frame_bits += frame_bits_inc[s->channel_mode];
525

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

    
551
    /* auxdatae, crcrsv */
552
    frame_bits += 2;
553

    
554
    /* CRC */
555
    frame_bits += 16;
556

    
557
    /* calculate psd and masking curve before doing bit allocation */
558
    bit_alloc_masking(s, encoded_exp, exp_strategy, psd, mask);
559

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

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

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

    
597
    s->coarse_snr_offset = coarse_snr_offset;
598
    for(ch=0;ch<s->channels;ch++)
599
        s->fine_snr_offset[ch] = fine_snr_offset;
600
#if defined(DEBUG_BITALLOC)
601
    {
602
        int j;
603

    
604
        for(i=0;i<6;i++) {
605
            for(ch=0;ch<s->channels;ch++) {
606
                printf("Block #%d Ch%d:\n", i, ch);
607
                printf("bap=");
608
                for(j=0;j<s->nb_coefs[ch];j++) {
609
                    printf("%d ",bap[i][ch][j]);
610
                }
611
                printf("\n");
612
            }
613
        }
614
    }
615
#endif
616
    return 0;
617
}
618

    
619
static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
620
                                    int64_t *channel_layout)
621
{
622
    int ch_layout;
623

    
624
    if (channels < 1 || channels > AC3_MAX_CHANNELS)
625
        return -1;
626
    if ((uint64_t)*channel_layout > 0x7FF)
627
        return -1;
628
    ch_layout = *channel_layout;
629
    if (!ch_layout)
630
        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
631
    if (av_get_channel_layout_nb_channels(ch_layout) != channels)
632
        return -1;
633

    
634
    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
635
    s->channels     = channels;
636
    s->fbw_channels = channels - s->lfe_on;
637
    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
638
    if (s->lfe_on)
639
        ch_layout -= AV_CH_LOW_FREQUENCY;
640

    
641
    switch (ch_layout) {
642
    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
643
    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
644
    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
645
    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
646
    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
647
    case AV_CH_LAYOUT_QUAD:
648
    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
649
    case AV_CH_LAYOUT_5POINT0:
650
    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
651
    default:
652
        return -1;
653
    }
654

    
655
    s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
656
    *channel_layout = ch_layout;
657
    if (s->lfe_on)
658
        *channel_layout |= AV_CH_LOW_FREQUENCY;
659

    
660
    return 0;
661
}
662

    
663
static av_cold int AC3_encode_init(AVCodecContext *avctx)
664
{
665
    int freq = avctx->sample_rate;
666
    int bitrate = avctx->bit_rate;
667
    AC3EncodeContext *s = avctx->priv_data;
668
    int i, j, ch;
669
    float alpha;
670
    int bw_code;
671

    
672
    avctx->frame_size = AC3_FRAME_SIZE;
673

    
674
    ac3_common_init();
675

    
676
    if (!avctx->channel_layout) {
677
        av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
678
                                      "encoder will guess the layout, but it "
679
                                      "might be incorrect.\n");
680
    }
681
    if (set_channel_info(s, avctx->channels, &avctx->channel_layout)) {
682
        av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
683
        return -1;
684
    }
685

    
686
    /* frequency */
687
    for(i=0;i<3;i++) {
688
        for(j=0;j<3;j++)
689
            if ((ff_ac3_sample_rate_tab[j] >> i) == freq)
690
                goto found;
691
    }
692
    return -1;
693
 found:
694
    s->sample_rate = freq;
695
    s->sr_shift = i;
696
    s->sr_code = j;
697
    s->bitstream_id = 8 + s->sr_shift;
698
    s->bitstream_mode = 0; /* complete main audio service */
699

    
700
    /* bitrate & frame size */
701
    for(i=0;i<19;i++) {
702
        if ((ff_ac3_bitrate_tab[i] >> s->sr_shift)*1000 == bitrate)
703
            break;
704
    }
705
    if (i == 19)
706
        return -1;
707
    s->bit_rate = bitrate;
708
    s->frame_size_code = i << 1;
709
    s->frame_size_min = ff_ac3_frame_size_tab[s->frame_size_code][s->sr_code];
710
    s->bits_written = 0;
711
    s->samples_written = 0;
712
    s->frame_size = s->frame_size_min;
713

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

    
737
    /* mdct init */
738
    fft_init(MDCT_NBITS - 2);
739
    for(i=0;i<N/4;i++) {
740
        alpha = 2 * M_PI * (i + 1.0 / 8.0) / (float)N;
741
        xcos1[i] = fix15(-cos(alpha));
742
        xsin1[i] = fix15(-sin(alpha));
743
    }
744

    
745
    avctx->coded_frame= avcodec_alloc_frame();
746
    avctx->coded_frame->key_frame= 1;
747

    
748
    return 0;
749
}
750

    
751
/* output the AC-3 frame header */
752
static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
753
{
754
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
755

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

    
781
/* symetric quantization on 'levels' levels */
782
static inline int sym_quant(int c, int e, int levels)
783
{
784
    int v;
785

    
786
    if (c >= 0) {
787
        v = (levels * (c << e)) >> 24;
788
        v = (v + 1) >> 1;
789
        v = (levels >> 1) + v;
790
    } else {
791
        v = (levels * ((-c) << e)) >> 24;
792
        v = (v + 1) >> 1;
793
        v = (levels >> 1) - v;
794
    }
795
    assert (v >= 0 && v < levels);
796
    return v;
797
}
798

    
799
/* asymetric quantization on 2^qbits levels */
800
static inline int asym_quant(int c, int e, int qbits)
801
{
802
    int lshift, m, v;
803

    
804
    lshift = e + qbits - 24;
805
    if (lshift >= 0)
806
        v = c << lshift;
807
    else
808
        v = c >> (-lshift);
809
    /* rounding */
810
    v = (v + 1) >> 1;
811
    m = (1 << (qbits-1));
812
    if (v >= m)
813
        v = m - 1;
814
    assert(v >= -m);
815
    return v & ((1 << qbits)-1);
816
}
817

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

    
836
    for(ch=0;ch<s->fbw_channels;ch++)
837
        put_bits(&s->pb, 1, 0); /* 512 point MDCT */
838
    for(ch=0;ch<s->fbw_channels;ch++)
839
        put_bits(&s->pb, 1, 1); /* no dither */
840
    put_bits(&s->pb, 1, 0); /* no dynamic range */
841
    if (block_num == 0) {
842
        /* for block 0, even if no coupling, we must say it. This is a
843
           waste of bit :-) */
844
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
845
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
846
    } else {
847
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
848
    }
849

    
850
    if (s->channel_mode == AC3_CHMODE_STEREO)
851
      {
852
        if(block_num==0)
853
          {
854
            /* first block must define rematrixing (rematstr)  */
855
            put_bits(&s->pb, 1, 1);
856

    
857
            /* dummy rematrixing rematflg(1:4)=0 */
858
            for (rbnd=0;rbnd<4;rbnd++)
859
              put_bits(&s->pb, 1, 0);
860
          }
861
        else
862
          {
863
            /* no matrixing (but should be used in the future) */
864
            put_bits(&s->pb, 1, 0);
865
          }
866
      }
867

    
868
#if defined(DEBUG)
869
    {
870
      static int count = 0;
871
      av_log(NULL, AV_LOG_DEBUG, "Block #%d (%d)\n", block_num, count++);
872
    }
873
#endif
874
    /* exponent strategy */
875
    for(ch=0;ch<s->fbw_channels;ch++) {
876
        put_bits(&s->pb, 2, exp_strategy[ch]);
877
    }
878

    
879
    if (s->lfe_on) {
880
        put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
881
    }
882

    
883
    for(ch=0;ch<s->fbw_channels;ch++) {
884
        if (exp_strategy[ch] != EXP_REUSE)
885
            put_bits(&s->pb, 6, s->bandwidth_code[ch]);
886
    }
887

    
888
    /* exponents */
889
    for (ch = 0; ch < s->channels; ch++) {
890
        switch(exp_strategy[ch]) {
891
        case EXP_REUSE:
892
            continue;
893
        case EXP_D15:
894
            group_size = 1;
895
            break;
896
        case EXP_D25:
897
            group_size = 2;
898
            break;
899
        default:
900
        case EXP_D45:
901
            group_size = 4;
902
            break;
903
        }
904
        nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
905
        p = encoded_exp[ch];
906

    
907
        /* first exponent */
908
        exp1 = *p++;
909
        put_bits(&s->pb, 4, exp1);
910

    
911
        /* next ones are delta encoded */
912
        for(i=0;i<nb_groups;i++) {
913
            /* merge three delta in one code */
914
            exp0 = exp1;
915
            exp1 = p[0];
916
            p += group_size;
917
            delta0 = exp1 - exp0 + 2;
918

    
919
            exp0 = exp1;
920
            exp1 = p[0];
921
            p += group_size;
922
            delta1 = exp1 - exp0 + 2;
923

    
924
            exp0 = exp1;
925
            exp1 = p[0];
926
            p += group_size;
927
            delta2 = exp1 - exp0 + 2;
928

    
929
            put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
930
        }
931

    
932
        if (ch != s->lfe_channel)
933
            put_bits(&s->pb, 2, 0); /* no gain range info */
934
    }
935

    
936
    /* bit allocation info */
937
    baie = (block_num == 0);
938
    put_bits(&s->pb, 1, baie);
939
    if (baie) {
940
        put_bits(&s->pb, 2, s->slow_decay_code);
941
        put_bits(&s->pb, 2, s->fast_decay_code);
942
        put_bits(&s->pb, 2, s->slow_gain_code);
943
        put_bits(&s->pb, 2, s->db_per_bit_code);
944
        put_bits(&s->pb, 3, s->floor_code);
945
    }
946

    
947
    /* snr offset */
948
    put_bits(&s->pb, 1, baie); /* always present with bai */
949
    if (baie) {
950
        put_bits(&s->pb, 6, s->coarse_snr_offset);
951
        for(ch=0;ch<s->channels;ch++) {
952
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
953
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
954
        }
955
    }
956

    
957
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
958
    put_bits(&s->pb, 1, 0); /* no data to skip */
959

    
960
    /* mantissa encoding : we use two passes to handle the grouping. A
961
       one pass method may be faster, but it would necessitate to
962
       modify the output stream. */
963

    
964
    /* first pass: quantize */
965
    mant1_cnt = mant2_cnt = mant4_cnt = 0;
966
    qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
967

    
968
    for (ch = 0; ch < s->channels; ch++) {
969
        int b, c, e, v;
970

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

    
1054
    /* second pass : output the values */
1055
    for (ch = 0; ch < s->channels; ch++) {
1056
        int b, q;
1057

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

    
1093
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1094

    
1095
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1096
{
1097
    unsigned int c;
1098

    
1099
    c = 0;
1100
    while (a) {
1101
        if (a & 1)
1102
            c ^= b;
1103
        a = a >> 1;
1104
        b = b << 1;
1105
        if (b & (1 << 16))
1106
            b ^= poly;
1107
    }
1108
    return c;
1109
}
1110

    
1111
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1112
{
1113
    unsigned int r;
1114
    r = 1;
1115
    while (n) {
1116
        if (n & 1)
1117
            r = mul_poly(r, a, poly);
1118
        a = mul_poly(a, a, poly);
1119
        n >>= 1;
1120
    }
1121
    return r;
1122
}
1123

    
1124

    
1125
/* compute log2(max(abs(tab[]))) */
1126
static int log2_tab(int16_t *tab, int n)
1127
{
1128
    int i, v;
1129

    
1130
    v = 0;
1131
    for(i=0;i<n;i++) {
1132
        v |= abs(tab[i]);
1133
    }
1134
    return av_log2(v);
1135
}
1136

    
1137
static void lshift_tab(int16_t *tab, int n, int lshift)
1138
{
1139
    int i;
1140

    
1141
    if (lshift > 0) {
1142
        for(i=0;i<n;i++) {
1143
            tab[i] <<= lshift;
1144
        }
1145
    } else if (lshift < 0) {
1146
        lshift = -lshift;
1147
        for(i=0;i<n;i++) {
1148
            tab[i] >>= lshift;
1149
        }
1150
    }
1151
}
1152

    
1153
/* fill the end of the frame and compute the two crcs */
1154
static int output_frame_end(AC3EncodeContext *s)
1155
{
1156
    int frame_size, frame_size_58, n, crc1, crc2, crc_inv;
1157
    uint8_t *frame;
1158

    
1159
    frame_size = s->frame_size; /* frame size in words */
1160
    /* align to 8 bits */
1161
    flush_put_bits(&s->pb);
1162
    /* add zero bytes to reach the frame size */
1163
    frame = s->pb.buf;
1164
    n = 2 * s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1165
    assert(n >= 0);
1166
    if(n>0)
1167
      memset(put_bits_ptr(&s->pb), 0, n);
1168

    
1169
    /* Now we must compute both crcs : this is not so easy for crc1
1170
       because it is at the beginning of the data... */
1171
    frame_size_58 = (frame_size >> 1) + (frame_size >> 3);
1172
    crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1173
                           frame + 4, 2 * frame_size_58 - 4));
1174
    /* XXX: could precompute crc_inv */
1175
    crc_inv = pow_poly((CRC16_POLY >> 1), (16 * frame_size_58) - 16, CRC16_POLY);
1176
    crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1177
    AV_WB16(frame+2,crc1);
1178

    
1179
    crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1180
                           frame + 2 * frame_size_58,
1181
                           (frame_size - frame_size_58) * 2 - 2));
1182
    AV_WB16(frame+2*frame_size-2,crc2);
1183

    
1184
    //    printf("n=%d frame_size=%d\n", n, frame_size);
1185
    return frame_size * 2;
1186
}
1187

    
1188
static int AC3_encode_frame(AVCodecContext *avctx,
1189
                            unsigned char *frame, int buf_size, void *data)
1190
{
1191
    AC3EncodeContext *s = avctx->priv_data;
1192
    const int16_t *samples = data;
1193
    int i, j, k, v, ch;
1194
    int16_t input_samples[N];
1195
    int32_t mdct_coef[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1196
    uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1197
    uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS];
1198
    uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1199
    uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1200
    int8_t exp_samples[NB_BLOCKS][AC3_MAX_CHANNELS];
1201
    int frame_bits;
1202

    
1203
    frame_bits = 0;
1204
    for(ch=0;ch<s->channels;ch++) {
1205
        int ich = s->channel_map[ch];
1206
        /* fixed mdct to the six sub blocks & exponent computation */
1207
        for(i=0;i<NB_BLOCKS;i++) {
1208
            const int16_t *sptr;
1209
            int sinc;
1210

    
1211
            /* compute input samples */
1212
            memcpy(input_samples, s->last_samples[ich], N/2 * sizeof(int16_t));
1213
            sinc = s->channels;
1214
            sptr = samples + (sinc * (N/2) * i) + ich;
1215
            for(j=0;j<N/2;j++) {
1216
                v = *sptr;
1217
                input_samples[j + N/2] = v;
1218
                s->last_samples[ich][j] = v;
1219
                sptr += sinc;
1220
            }
1221

    
1222
            /* apply the MDCT window */
1223
            for(j=0;j<N/2;j++) {
1224
                input_samples[j] = MUL16(input_samples[j],
1225
                                         ff_ac3_window[j]) >> 15;
1226
                input_samples[N-j-1] = MUL16(input_samples[N-j-1],
1227
                                             ff_ac3_window[j]) >> 15;
1228
            }
1229

    
1230
            /* Normalize the samples to use the maximum available
1231
               precision */
1232
            v = 14 - log2_tab(input_samples, N);
1233
            if (v < 0)
1234
                v = 0;
1235
            exp_samples[i][ch] = v - 9;
1236
            lshift_tab(input_samples, N, v);
1237

    
1238
            /* do the MDCT */
1239
            mdct512(mdct_coef[i][ch], input_samples);
1240

    
1241
            /* compute "exponents". We take into account the
1242
               normalization there */
1243
            for(j=0;j<N/2;j++) {
1244
                int e;
1245
                v = abs(mdct_coef[i][ch][j]);
1246
                if (v == 0)
1247
                    e = 24;
1248
                else {
1249
                    e = 23 - av_log2(v) + exp_samples[i][ch];
1250
                    if (e >= 24) {
1251
                        e = 24;
1252
                        mdct_coef[i][ch][j] = 0;
1253
                    }
1254
                }
1255
                exp[i][ch][j] = e;
1256
            }
1257
        }
1258

    
1259
        compute_exp_strategy(exp_strategy, exp, ch, ch == s->lfe_channel);
1260

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

    
1283
    /* adjust for fractional frame sizes */
1284
    while(s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
1285
        s->bits_written -= s->bit_rate;
1286
        s->samples_written -= s->sample_rate;
1287
    }
1288
    s->frame_size = s->frame_size_min + (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
1289
    s->bits_written += s->frame_size * 16;
1290
    s->samples_written += AC3_FRAME_SIZE;
1291

    
1292
    compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
1293
    /* everything is known... let's output the frame */
1294
    output_frame_header(s, frame);
1295

    
1296
    for(i=0;i<NB_BLOCKS;i++) {
1297
        output_audio_block(s, exp_strategy[i], encoded_exp[i],
1298
                           bap[i], mdct_coef[i], exp_samples[i], i);
1299
    }
1300
    return output_frame_end(s);
1301
}
1302

    
1303
static av_cold int AC3_encode_close(AVCodecContext *avctx)
1304
{
1305
    av_freep(&avctx->coded_frame);
1306
    return 0;
1307
}
1308

    
1309
#if 0
1310
/*************************************************************************/
1311
/* TEST */
1312

1313
#undef random
1314
#define FN (N/4)
1315

1316
void fft_test(void)
1317
{
1318
    IComplex in[FN], in1[FN];
1319
    int k, n, i;
1320
    float sum_re, sum_im, a;
1321

1322
    /* FFT test */
1323

1324
    for(i=0;i<FN;i++) {
1325
        in[i].re = random() % 65535 - 32767;
1326
        in[i].im = random() % 65535 - 32767;
1327
        in1[i] = in[i];
1328
    }
1329
    fft(in, 7);
1330

1331
    /* do it by hand */
1332
    for(k=0;k<FN;k++) {
1333
        sum_re = 0;
1334
        sum_im = 0;
1335
        for(n=0;n<FN;n++) {
1336
            a = -2 * M_PI * (n * k) / FN;
1337
            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1338
            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1339
        }
1340
        printf("%3d: %6d,%6d %6.0f,%6.0f\n",
1341
               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1342
    }
1343
}
1344

1345
void mdct_test(void)
1346
{
1347
    int16_t input[N];
1348
    int32_t output[N/2];
1349
    float input1[N];
1350
    float output1[N/2];
1351
    float s, a, err, e, emax;
1352
    int i, k, n;
1353

1354
    for(i=0;i<N;i++) {
1355
        input[i] = (random() % 65535 - 32767) * 9 / 10;
1356
        input1[i] = input[i];
1357
    }
1358

1359
    mdct512(output, input);
1360

1361
    /* do it by hand */
1362
    for(k=0;k<N/2;k++) {
1363
        s = 0;
1364
        for(n=0;n<N;n++) {
1365
            a = (2*M_PI*(2*n+1+N/2)*(2*k+1) / (4 * N));
1366
            s += input1[n] * cos(a);
1367
        }
1368
        output1[k] = -2 * s / N;
1369
    }
1370

1371
    err = 0;
1372
    emax = 0;
1373
    for(i=0;i<N/2;i++) {
1374
        printf("%3d: %7d %7.0f\n", i, output[i], output1[i]);
1375
        e = output[i] - output1[i];
1376
        if (e > emax)
1377
            emax = e;
1378
        err += e * e;
1379
    }
1380
    printf("err2=%f emax=%f\n", err / (N/2), emax);
1381
}
1382

1383
void test_ac3(void)
1384
{
1385
    AC3EncodeContext ctx;
1386
    unsigned char frame[AC3_MAX_CODED_FRAME_SIZE];
1387
    int16_t samples[AC3_FRAME_SIZE];
1388
    int ret, i;
1389

1390
    AC3_encode_init(&ctx, 44100, 64000, 1);
1391

1392
    fft_test();
1393
    mdct_test();
1394

1395
    for(i=0;i<AC3_FRAME_SIZE;i++)
1396
        samples[i] = (int)(sin(2*M_PI*i*1000.0/44100) * 10000);
1397
    ret = AC3_encode_frame(&ctx, frame, samples);
1398
    printf("ret=%d\n", ret);
1399
}
1400
#endif
1401

    
1402
AVCodec ac3_encoder = {
1403
    "ac3",
1404
    AVMEDIA_TYPE_AUDIO,
1405
    CODEC_ID_AC3,
1406
    sizeof(AC3EncodeContext),
1407
    AC3_encode_init,
1408
    AC3_encode_frame,
1409
    AC3_encode_close,
1410
    NULL,
1411
    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1412
    .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1413
    .channel_layouts = (const int64_t[]){
1414
        AV_CH_LAYOUT_MONO,
1415
        AV_CH_LAYOUT_STEREO,
1416
        AV_CH_LAYOUT_2_1,
1417
        AV_CH_LAYOUT_SURROUND,
1418
        AV_CH_LAYOUT_2_2,
1419
        AV_CH_LAYOUT_QUAD,
1420
        AV_CH_LAYOUT_4POINT0,
1421
        AV_CH_LAYOUT_5POINT0,
1422
        AV_CH_LAYOUT_5POINT0_BACK,
1423
       (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
1424
       (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
1425
       (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
1426
       (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1427
       (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
1428
       (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
1429
       (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
1430
        AV_CH_LAYOUT_5POINT1,
1431
        AV_CH_LAYOUT_5POINT1_BACK,
1432
        0 },
1433
};