Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ 3abe5fbd

History | View | Annotate | Download (39.3 KB)

1
/*
2
 * The simplest AC3 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 ac3enc.c
24
 * The simplest AC3 encoder.
25
 */
26
//#define DEBUG
27
//#define DEBUG_BITALLOC
28
#include "avcodec.h"
29
#include "bitstream.h"
30
#include "crc.h"
31
#include "ac3.h"
32

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

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

    
65
static int16_t costab[64];
66
static int16_t sintab[64];
67
static int16_t fft_rev[512];
68
static int16_t xcos1[128];
69
static int16_t xsin1[128];
70

    
71
#define MDCT_NBITS 9
72
#define N         (1 << MDCT_NBITS)
73

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

    
77
static void fft_init(int ln);
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 void fft_init(int ln)
95
{
96
    int i, j, m, 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
    for(i=0;i<n;i++) {
108
        m=0;
109
        for(j=0;j<ln;j++) {
110
            m |= ((i >> j) & 1) << (ln-j-1);
111
        }
112
        fft_rev[i]=m;
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 MUL16(a,b) ((a) * (b))
131

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

    
138

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

    
147
    np = 1 << ln;
148

    
149
    /* reverse */
150
    for(j=0;j<np;j++) {
151
        int k;
152
        IComplex tmp;
153
        k = fft_rev[j];
154
        if (k < j) {
155
            tmp = z[k];
156
            z[k] = z[j];
157
            z[j] = tmp;
158
        }
159
    }
160

    
161
    /* pass 0 */
162

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

    
171
    /* pass 1 */
172

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

    
183
    /* pass 2 .. ln-1 */
184

    
185
    nblocks = np >> 3;
186
    nloops = 1 << 2;
187
    np2 = np >> 1;
188
    do {
189
        p = z;
190
        q = z + nloops;
191
        for (j = 0; j < nblocks; ++j) {
192

    
193
            BF(p->re, p->im, q->re, q->im,
194
               p->re, p->im, q->re, q->im);
195

    
196
            p++;
197
            q++;
198
            for(l = nblocks; l < np2; l += nblocks) {
199
                CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
200
                BF(p->re, p->im, q->re, q->im,
201
                   p->re, p->im, tmp_re, tmp_im);
202
                p++;
203
                q++;
204
            }
205
            p += nloops;
206
            q += nloops;
207
        }
208
        nblocks = nblocks >> 1;
209
        nloops = nloops << 1;
210
    } while (nblocks != 0);
211
}
212

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

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

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

    
233
    fft(x, MDCT_NBITS - 2);
234

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

    
245
/* XXX: use another norm ? */
246
static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
247
{
248
    int sum, i;
249
    sum = 0;
250
    for(i=0;i<n;i++) {
251
        sum += abs(exp1[i] - exp2[i]);
252
    }
253
    return sum;
254
}
255

    
256
static void compute_exp_strategy(uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
257
                                 uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
258
                                 int ch, int is_lfe)
259
{
260
    int i, j;
261
    int exp_diff;
262

    
263
    /* estimate if the exponent variation & decide if they should be
264
       reused in the next frame */
265
    exp_strategy[0][ch] = EXP_NEW;
266
    for(i=1;i<NB_BLOCKS;i++) {
267
        exp_diff = calc_exp_diff(exp[i][ch], exp[i-1][ch], N/2);
268
#ifdef DEBUG
269
        av_log(NULL, AV_LOG_DEBUG, "exp_diff=%d\n", exp_diff);
270
#endif
271
        if (exp_diff > EXP_DIFF_THRESHOLD)
272
            exp_strategy[i][ch] = EXP_NEW;
273
        else
274
            exp_strategy[i][ch] = EXP_REUSE;
275
    }
276
    if (is_lfe)
277
        return;
278

    
279
    /* now select the encoding strategy type : if exponents are often
280
       recoded, we use a coarse encoding */
281
    i = 0;
282
    while (i < NB_BLOCKS) {
283
        j = i + 1;
284
        while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE)
285
            j++;
286
        switch(j - i) {
287
        case 1:
288
            exp_strategy[i][ch] = EXP_D45;
289
            break;
290
        case 2:
291
        case 3:
292
            exp_strategy[i][ch] = EXP_D25;
293
            break;
294
        default:
295
            exp_strategy[i][ch] = EXP_D15;
296
            break;
297
        }
298
        i = j;
299
    }
300
}
301

    
302
/* set exp[i] to min(exp[i], exp1[i]) */
303
static void exponent_min(uint8_t exp[N/2], uint8_t exp1[N/2], int n)
304
{
305
    int i;
306

    
307
    for(i=0;i<n;i++) {
308
        if (exp1[i] < exp[i])
309
            exp[i] = exp1[i];
310
    }
311
}
312

    
313
/* update the exponents so that they are the ones the decoder will
314
   decode. Return the number of bits used to code the exponents */
315
static int encode_exp(uint8_t encoded_exp[N/2],
316
                      uint8_t exp[N/2],
317
                      int nb_exps,
318
                      int exp_strategy)
319
{
320
    int group_size, nb_groups, i, j, k, exp_min;
321
    uint8_t exp1[N/2];
322

    
323
    switch(exp_strategy) {
324
    case EXP_D15:
325
        group_size = 1;
326
        break;
327
    case EXP_D25:
328
        group_size = 2;
329
        break;
330
    default:
331
    case EXP_D45:
332
        group_size = 4;
333
        break;
334
    }
335
    nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
336

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

    
351
    /* constraint for DC exponent */
352
    if (exp1[0] > 15)
353
        exp1[0] = 15;
354

    
355
    /* Decrease the delta between each groups to within 2
356
     * so that they can be differentially encoded */
357
    for (i=1;i<=nb_groups;i++)
358
        exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
359
    for (i=nb_groups-1;i>=0;i--)
360
        exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
361

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

    
372
#if defined(DEBUG)
373
    av_log(NULL, AV_LOG_DEBUG, "exponents: strategy=%d\n", exp_strategy);
374
    for(i=0;i<=nb_groups * group_size;i++) {
375
        av_log(NULL, AV_LOG_DEBUG, "%d ", encoded_exp[i]);
376
    }
377
    av_log(NULL, AV_LOG_DEBUG, "\n");
378
#endif
379

    
380
    return 4 + (nb_groups / 3) * 7;
381
}
382

    
383
/* return the size in bits taken by the mantissa */
384
static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
385
{
386
    int bits, mant, i;
387

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

    
433

    
434
static void bit_alloc_masking(AC3EncodeContext *s,
435
                              uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
436
                              uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
437
                              int16_t psd[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
438
                              int16_t mask[NB_BLOCKS][AC3_MAX_CHANNELS][50])
439
{
440
    int blk, ch;
441
    int16_t band_psd[NB_BLOCKS][AC3_MAX_CHANNELS][50];
442

    
443
    for(blk=0; blk<NB_BLOCKS; blk++) {
444
        for(ch=0;ch<s->nb_all_channels;ch++) {
445
            if(exp_strategy[blk][ch] == EXP_REUSE) {
446
                memcpy(psd[blk][ch], psd[blk-1][ch], (N/2)*sizeof(int16_t));
447
                memcpy(mask[blk][ch], mask[blk-1][ch], 50*sizeof(int16_t));
448
            } else {
449
                ff_ac3_bit_alloc_calc_psd(encoded_exp[blk][ch], 0,
450
                                          s->nb_coefs[ch],
451
                                          psd[blk][ch], band_psd[blk][ch]);
452
                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, band_psd[blk][ch],
453
                                           0, s->nb_coefs[ch],
454
                                           ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
455
                                           ch == s->lfe_channel,
456
                                           DBA_NONE, 0, NULL, NULL, NULL,
457
                                           mask[blk][ch]);
458
            }
459
        }
460
    }
461
}
462

    
463
static int bit_alloc(AC3EncodeContext *s,
464
                     int16_t mask[NB_BLOCKS][AC3_MAX_CHANNELS][50],
465
                     int16_t psd[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
466
                     uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
467
                     int frame_bits, int coarse_snr_offset, int fine_snr_offset)
468
{
469
    int i, ch;
470
    int snr_offset;
471

    
472
    snr_offset = (((coarse_snr_offset - 15) << 4) + fine_snr_offset) << 2;
473

    
474
    /* compute size */
475
    for(i=0;i<NB_BLOCKS;i++) {
476
        s->mant1_cnt = 0;
477
        s->mant2_cnt = 0;
478
        s->mant4_cnt = 0;
479
        for(ch=0;ch<s->nb_all_channels;ch++) {
480
            ff_ac3_bit_alloc_calc_bap(mask[i][ch], psd[i][ch], 0,
481
                                      s->nb_coefs[ch], snr_offset,
482
                                      s->bit_alloc.floor, bap[i][ch]);
483
            frame_bits += compute_mantissa_size(s, bap[i][ch],
484
                                                 s->nb_coefs[ch]);
485
        }
486
    }
487
#if 0
488
    printf("csnr=%d fsnr=%d frame_bits=%d diff=%d\n",
489
           coarse_snr_offset, fine_snr_offset, frame_bits,
490
           16 * s->frame_size - ((frame_bits + 7) & ~7));
491
#endif
492
    return 16 * s->frame_size - frame_bits;
493
}
494

    
495
#define SNR_INC1 4
496

    
497
static int compute_bit_allocation(AC3EncodeContext *s,
498
                                  uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
499
                                  uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
500
                                  uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
501
                                  int frame_bits)
502
{
503
    int i, ch;
504
    int coarse_snr_offset, fine_snr_offset;
505
    uint8_t bap1[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
506
    int16_t psd[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
507
    int16_t mask[NB_BLOCKS][AC3_MAX_CHANNELS][50];
508
    static int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
509

    
510
    /* init default parameters */
511
    s->slow_decay_code = 2;
512
    s->fast_decay_code = 1;
513
    s->slow_gain_code = 1;
514
    s->db_per_bit_code = 2;
515
    s->floor_code = 4;
516
    for(ch=0;ch<s->nb_all_channels;ch++)
517
        s->fast_gain_code[ch] = 4;
518

    
519
    /* compute real values */
520
    s->bit_alloc.sr_code = s->sr_code;
521
    s->bit_alloc.sr_shift = s->sr_shift;
522
    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->sr_shift;
523
    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->sr_shift;
524
    s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
525
    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
526
    s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
527

    
528
    /* header size */
529
    frame_bits += 65;
530
    // if (s->channel_mode == 2)
531
    //    frame_bits += 2;
532
    frame_bits += frame_bits_inc[s->channel_mode];
533

    
534
    /* audio blocks */
535
    for(i=0;i<NB_BLOCKS;i++) {
536
        frame_bits += s->nb_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
537
        if (s->channel_mode == AC3_CHMODE_STEREO) {
538
            frame_bits++; /* rematstr */
539
            if(i==0) frame_bits += 4;
540
        }
541
        frame_bits += 2 * s->nb_channels; /* chexpstr[2] * c */
542
        if (s->lfe)
543
            frame_bits++; /* lfeexpstr */
544
        for(ch=0;ch<s->nb_channels;ch++) {
545
            if (exp_strategy[i][ch] != EXP_REUSE)
546
                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
547
        }
548
        frame_bits++; /* baie */
549
        frame_bits++; /* snr */
550
        frame_bits += 2; /* delta / skip */
551
    }
552
    frame_bits++; /* cplinu for block 0 */
553
    /* bit alloc info */
554
    /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
555
    /* csnroffset[6] */
556
    /* (fsnoffset[4] + fgaincod[4]) * c */
557
    frame_bits += 2*4 + 3 + 6 + s->nb_all_channels * (4 + 3);
558

    
559
    /* auxdatae, crcrsv */
560
    frame_bits += 2;
561

    
562
    /* CRC */
563
    frame_bits += 16;
564

    
565
    /* calculate psd and masking curve before doing bit allocation */
566
    bit_alloc_masking(s, encoded_exp, exp_strategy, psd, mask);
567

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

    
571
    coarse_snr_offset = s->coarse_snr_offset;
572
    while (coarse_snr_offset >= 0 &&
573
           bit_alloc(s, mask, psd, bap, frame_bits, coarse_snr_offset, 0) < 0)
574
        coarse_snr_offset -= SNR_INC1;
575
    if (coarse_snr_offset < 0) {
576
        av_log(NULL, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
577
        return -1;
578
    }
579
    while ((coarse_snr_offset + SNR_INC1) <= 63 &&
580
           bit_alloc(s, mask, psd, bap1, frame_bits,
581
                     coarse_snr_offset + SNR_INC1, 0) >= 0) {
582
        coarse_snr_offset += SNR_INC1;
583
        memcpy(bap, bap1, sizeof(bap1));
584
    }
585
    while ((coarse_snr_offset + 1) <= 63 &&
586
           bit_alloc(s, mask, psd, bap1, frame_bits, coarse_snr_offset + 1, 0) >= 0) {
587
        coarse_snr_offset++;
588
        memcpy(bap, bap1, sizeof(bap1));
589
    }
590

    
591
    fine_snr_offset = 0;
592
    while ((fine_snr_offset + SNR_INC1) <= 15 &&
593
           bit_alloc(s, mask, psd, bap1, frame_bits,
594
                     coarse_snr_offset, fine_snr_offset + SNR_INC1) >= 0) {
595
        fine_snr_offset += SNR_INC1;
596
        memcpy(bap, bap1, sizeof(bap1));
597
    }
598
    while ((fine_snr_offset + 1) <= 15 &&
599
           bit_alloc(s, mask, psd, bap1, frame_bits,
600
                     coarse_snr_offset, fine_snr_offset + 1) >= 0) {
601
        fine_snr_offset++;
602
        memcpy(bap, bap1, sizeof(bap1));
603
    }
604

    
605
    s->coarse_snr_offset = coarse_snr_offset;
606
    for(ch=0;ch<s->nb_all_channels;ch++)
607
        s->fine_snr_offset[ch] = fine_snr_offset;
608
#if defined(DEBUG_BITALLOC)
609
    {
610
        int j;
611

    
612
        for(i=0;i<6;i++) {
613
            for(ch=0;ch<s->nb_all_channels;ch++) {
614
                printf("Block #%d Ch%d:\n", i, ch);
615
                printf("bap=");
616
                for(j=0;j<s->nb_coefs[ch];j++) {
617
                    printf("%d ",bap[i][ch][j]);
618
                }
619
                printf("\n");
620
            }
621
        }
622
    }
623
#endif
624
    return 0;
625
}
626

    
627
static int AC3_encode_init(AVCodecContext *avctx)
628
{
629
    int freq = avctx->sample_rate;
630
    int bitrate = avctx->bit_rate;
631
    int channels = avctx->channels;
632
    AC3EncodeContext *s = avctx->priv_data;
633
    int i, j, ch;
634
    float alpha;
635
    int bw_code;
636
    static const uint8_t channel_mode_defs[6] = {
637
        0x01, /* C */
638
        0x02, /* L R */
639
        0x03, /* L C R */
640
        0x06, /* L R SL SR */
641
        0x07, /* L C R SL SR */
642
        0x07, /* L C R SL SR (+LFE) */
643
    };
644

    
645
    avctx->frame_size = AC3_FRAME_SIZE;
646

    
647
    ac3_common_init();
648

    
649
    /* number of channels */
650
    if (channels < 1 || channels > 6)
651
        return -1;
652
    s->channel_mode = channel_mode_defs[channels - 1];
653
    s->lfe = (channels == 6) ? 1 : 0;
654
    s->nb_all_channels = channels;
655
    s->nb_channels = channels > 5 ? 5 : channels;
656
    s->lfe_channel = s->lfe ? 5 : -1;
657

    
658
    /* frequency */
659
    for(i=0;i<3;i++) {
660
        for(j=0;j<3;j++)
661
            if ((ff_ac3_sample_rate_tab[j] >> i) == freq)
662
                goto found;
663
    }
664
    return -1;
665
 found:
666
    s->sample_rate = freq;
667
    s->sr_shift = i;
668
    s->sr_code = j;
669
    s->bitstream_id = 8 + s->sr_shift;
670
    s->bitstream_mode = 0; /* complete main audio service */
671

    
672
    /* bitrate & frame size */
673
    for(i=0;i<19;i++) {
674
        if ((ff_ac3_bitrate_tab[i] >> s->sr_shift)*1000 == bitrate)
675
            break;
676
    }
677
    if (i == 19)
678
        return -1;
679
    s->bit_rate = bitrate;
680
    s->frame_size_code = i << 1;
681
    s->frame_size_min = ff_ac3_frame_size_tab[s->frame_size_code][s->sr_code];
682
    s->bits_written = 0;
683
    s->samples_written = 0;
684
    s->frame_size = s->frame_size_min;
685

    
686
    /* bit allocation init */
687
    if(avctx->cutoff) {
688
        /* calculate bandwidth based on user-specified cutoff frequency */
689
        int cutoff = av_clip(avctx->cutoff, 1, s->sample_rate >> 1);
690
        int fbw_coeffs = cutoff * 512 / s->sample_rate;
691
        bw_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
692
    } else {
693
        /* use default bandwidth setting */
694
        /* XXX: should compute the bandwidth according to the frame
695
           size, so that we avoid anoying high freq artefacts */
696
        bw_code = 50;
697
    }
698
    for(ch=0;ch<s->nb_channels;ch++) {
699
        /* bandwidth for each channel */
700
        s->chbwcod[ch] = bw_code;
701
        s->nb_coefs[ch] = bw_code * 3 + 73;
702
    }
703
    if (s->lfe) {
704
        s->nb_coefs[s->lfe_channel] = 7; /* fixed */
705
    }
706
    /* initial snr offset */
707
    s->coarse_snr_offset = 40;
708

    
709
    /* mdct init */
710
    fft_init(MDCT_NBITS - 2);
711
    for(i=0;i<N/4;i++) {
712
        alpha = 2 * M_PI * (i + 1.0 / 8.0) / (float)N;
713
        xcos1[i] = fix15(-cos(alpha));
714
        xsin1[i] = fix15(-sin(alpha));
715
    }
716

    
717
    avctx->coded_frame= avcodec_alloc_frame();
718
    avctx->coded_frame->key_frame= 1;
719

    
720
    return 0;
721
}
722

    
723
/* output the AC3 frame header */
724
static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
725
{
726
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
727

    
728
    put_bits(&s->pb, 16, 0x0b77); /* frame header */
729
    put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
730
    put_bits(&s->pb, 2, s->sr_code);
731
    put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min));
732
    put_bits(&s->pb, 5, s->bitstream_id);
733
    put_bits(&s->pb, 3, s->bitstream_mode);
734
    put_bits(&s->pb, 3, s->channel_mode);
735
    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
736
        put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
737
    if (s->channel_mode & 0x04)
738
        put_bits(&s->pb, 2, 1); /* XXX -6 dB */
739
    if (s->channel_mode == AC3_CHMODE_STEREO)
740
        put_bits(&s->pb, 2, 0); /* surround not indicated */
741
    put_bits(&s->pb, 1, s->lfe); /* LFE */
742
    put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
743
    put_bits(&s->pb, 1, 0); /* no compression control word */
744
    put_bits(&s->pb, 1, 0); /* no lang code */
745
    put_bits(&s->pb, 1, 0); /* no audio production info */
746
    put_bits(&s->pb, 1, 0); /* no copyright */
747
    put_bits(&s->pb, 1, 1); /* original bitstream */
748
    put_bits(&s->pb, 1, 0); /* no time code 1 */
749
    put_bits(&s->pb, 1, 0); /* no time code 2 */
750
    put_bits(&s->pb, 1, 0); /* no additional bit stream info */
751
}
752

    
753
/* symetric quantization on 'levels' levels */
754
static inline int sym_quant(int c, int e, int levels)
755
{
756
    int v;
757

    
758
    if (c >= 0) {
759
        v = (levels * (c << e)) >> 24;
760
        v = (v + 1) >> 1;
761
        v = (levels >> 1) + v;
762
    } else {
763
        v = (levels * ((-c) << e)) >> 24;
764
        v = (v + 1) >> 1;
765
        v = (levels >> 1) - v;
766
    }
767
    assert (v >= 0 && v < levels);
768
    return v;
769
}
770

    
771
/* asymetric quantization on 2^qbits levels */
772
static inline int asym_quant(int c, int e, int qbits)
773
{
774
    int lshift, m, v;
775

    
776
    lshift = e + qbits - 24;
777
    if (lshift >= 0)
778
        v = c << lshift;
779
    else
780
        v = c >> (-lshift);
781
    /* rounding */
782
    v = (v + 1) >> 1;
783
    m = (1 << (qbits-1));
784
    if (v >= m)
785
        v = m - 1;
786
    assert(v >= -m);
787
    return v & ((1 << qbits)-1);
788
}
789

    
790
/* Output one audio block. There are NB_BLOCKS audio blocks in one AC3
791
   frame */
792
static void output_audio_block(AC3EncodeContext *s,
793
                               uint8_t exp_strategy[AC3_MAX_CHANNELS],
794
                               uint8_t encoded_exp[AC3_MAX_CHANNELS][N/2],
795
                               uint8_t bap[AC3_MAX_CHANNELS][N/2],
796
                               int32_t mdct_coefs[AC3_MAX_CHANNELS][N/2],
797
                               int8_t global_exp[AC3_MAX_CHANNELS],
798
                               int block_num)
799
{
800
    int ch, nb_groups, group_size, i, baie, rbnd;
801
    uint8_t *p;
802
    uint16_t qmant[AC3_MAX_CHANNELS][N/2];
803
    int exp0, exp1;
804
    int mant1_cnt, mant2_cnt, mant4_cnt;
805
    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
806
    int delta0, delta1, delta2;
807

    
808
    for(ch=0;ch<s->nb_channels;ch++)
809
        put_bits(&s->pb, 1, 0); /* 512 point MDCT */
810
    for(ch=0;ch<s->nb_channels;ch++)
811
        put_bits(&s->pb, 1, 1); /* no dither */
812
    put_bits(&s->pb, 1, 0); /* no dynamic range */
813
    if (block_num == 0) {
814
        /* for block 0, even if no coupling, we must say it. This is a
815
           waste of bit :-) */
816
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
817
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
818
    } else {
819
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
820
    }
821

    
822
    if (s->channel_mode == AC3_CHMODE_STEREO)
823
      {
824
        if(block_num==0)
825
          {
826
            /* first block must define rematrixing (rematstr)  */
827
            put_bits(&s->pb, 1, 1);
828

    
829
            /* dummy rematrixing rematflg(1:4)=0 */
830
            for (rbnd=0;rbnd<4;rbnd++)
831
              put_bits(&s->pb, 1, 0);
832
          }
833
        else
834
          {
835
            /* no matrixing (but should be used in the future) */
836
            put_bits(&s->pb, 1, 0);
837
          }
838
      }
839

    
840
#if defined(DEBUG)
841
    {
842
      static int count = 0;
843
      av_log(NULL, AV_LOG_DEBUG, "Block #%d (%d)\n", block_num, count++);
844
    }
845
#endif
846
    /* exponent strategy */
847
    for(ch=0;ch<s->nb_channels;ch++) {
848
        put_bits(&s->pb, 2, exp_strategy[ch]);
849
    }
850

    
851
    if (s->lfe) {
852
        put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
853
    }
854

    
855
    for(ch=0;ch<s->nb_channels;ch++) {
856
        if (exp_strategy[ch] != EXP_REUSE)
857
            put_bits(&s->pb, 6, s->chbwcod[ch]);
858
    }
859

    
860
    /* exponents */
861
    for (ch = 0; ch < s->nb_all_channels; ch++) {
862
        switch(exp_strategy[ch]) {
863
        case EXP_REUSE:
864
            continue;
865
        case EXP_D15:
866
            group_size = 1;
867
            break;
868
        case EXP_D25:
869
            group_size = 2;
870
            break;
871
        default:
872
        case EXP_D45:
873
            group_size = 4;
874
            break;
875
        }
876
        nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
877
        p = encoded_exp[ch];
878

    
879
        /* first exponent */
880
        exp1 = *p++;
881
        put_bits(&s->pb, 4, exp1);
882

    
883
        /* next ones are delta encoded */
884
        for(i=0;i<nb_groups;i++) {
885
            /* merge three delta in one code */
886
            exp0 = exp1;
887
            exp1 = p[0];
888
            p += group_size;
889
            delta0 = exp1 - exp0 + 2;
890

    
891
            exp0 = exp1;
892
            exp1 = p[0];
893
            p += group_size;
894
            delta1 = exp1 - exp0 + 2;
895

    
896
            exp0 = exp1;
897
            exp1 = p[0];
898
            p += group_size;
899
            delta2 = exp1 - exp0 + 2;
900

    
901
            put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
902
        }
903

    
904
        if (ch != s->lfe_channel)
905
            put_bits(&s->pb, 2, 0); /* no gain range info */
906
    }
907

    
908
    /* bit allocation info */
909
    baie = (block_num == 0);
910
    put_bits(&s->pb, 1, baie);
911
    if (baie) {
912
        put_bits(&s->pb, 2, s->slow_decay_code);
913
        put_bits(&s->pb, 2, s->fast_decay_code);
914
        put_bits(&s->pb, 2, s->slow_gain_code);
915
        put_bits(&s->pb, 2, s->db_per_bit_code);
916
        put_bits(&s->pb, 3, s->floor_code);
917
    }
918

    
919
    /* snr offset */
920
    put_bits(&s->pb, 1, baie); /* always present with bai */
921
    if (baie) {
922
        put_bits(&s->pb, 6, s->coarse_snr_offset);
923
        for(ch=0;ch<s->nb_all_channels;ch++) {
924
            put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
925
            put_bits(&s->pb, 3, s->fast_gain_code[ch]);
926
        }
927
    }
928

    
929
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
930
    put_bits(&s->pb, 1, 0); /* no data to skip */
931

    
932
    /* mantissa encoding : we use two passes to handle the grouping. A
933
       one pass method may be faster, but it would necessitate to
934
       modify the output stream. */
935

    
936
    /* first pass: quantize */
937
    mant1_cnt = mant2_cnt = mant4_cnt = 0;
938
    qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
939

    
940
    for (ch = 0; ch < s->nb_all_channels; ch++) {
941
        int b, c, e, v;
942

    
943
        for(i=0;i<s->nb_coefs[ch];i++) {
944
            c = mdct_coefs[ch][i];
945
            e = encoded_exp[ch][i] - global_exp[ch];
946
            b = bap[ch][i];
947
            switch(b) {
948
            case 0:
949
                v = 0;
950
                break;
951
            case 1:
952
                v = sym_quant(c, e, 3);
953
                switch(mant1_cnt) {
954
                case 0:
955
                    qmant1_ptr = &qmant[ch][i];
956
                    v = 9 * v;
957
                    mant1_cnt = 1;
958
                    break;
959
                case 1:
960
                    *qmant1_ptr += 3 * v;
961
                    mant1_cnt = 2;
962
                    v = 128;
963
                    break;
964
                default:
965
                    *qmant1_ptr += v;
966
                    mant1_cnt = 0;
967
                    v = 128;
968
                    break;
969
                }
970
                break;
971
            case 2:
972
                v = sym_quant(c, e, 5);
973
                switch(mant2_cnt) {
974
                case 0:
975
                    qmant2_ptr = &qmant[ch][i];
976
                    v = 25 * v;
977
                    mant2_cnt = 1;
978
                    break;
979
                case 1:
980
                    *qmant2_ptr += 5 * v;
981
                    mant2_cnt = 2;
982
                    v = 128;
983
                    break;
984
                default:
985
                    *qmant2_ptr += v;
986
                    mant2_cnt = 0;
987
                    v = 128;
988
                    break;
989
                }
990
                break;
991
            case 3:
992
                v = sym_quant(c, e, 7);
993
                break;
994
            case 4:
995
                v = sym_quant(c, e, 11);
996
                switch(mant4_cnt) {
997
                case 0:
998
                    qmant4_ptr = &qmant[ch][i];
999
                    v = 11 * v;
1000
                    mant4_cnt = 1;
1001
                    break;
1002
                default:
1003
                    *qmant4_ptr += v;
1004
                    mant4_cnt = 0;
1005
                    v = 128;
1006
                    break;
1007
                }
1008
                break;
1009
            case 5:
1010
                v = sym_quant(c, e, 15);
1011
                break;
1012
            case 14:
1013
                v = asym_quant(c, e, 14);
1014
                break;
1015
            case 15:
1016
                v = asym_quant(c, e, 16);
1017
                break;
1018
            default:
1019
                v = asym_quant(c, e, b - 1);
1020
                break;
1021
            }
1022
            qmant[ch][i] = v;
1023
        }
1024
    }
1025

    
1026
    /* second pass : output the values */
1027
    for (ch = 0; ch < s->nb_all_channels; ch++) {
1028
        int b, q;
1029

    
1030
        for(i=0;i<s->nb_coefs[ch];i++) {
1031
            q = qmant[ch][i];
1032
            b = bap[ch][i];
1033
            switch(b) {
1034
            case 0:
1035
                break;
1036
            case 1:
1037
                if (q != 128)
1038
                    put_bits(&s->pb, 5, q);
1039
                break;
1040
            case 2:
1041
                if (q != 128)
1042
                    put_bits(&s->pb, 7, q);
1043
                break;
1044
            case 3:
1045
                put_bits(&s->pb, 3, q);
1046
                break;
1047
            case 4:
1048
                if (q != 128)
1049
                    put_bits(&s->pb, 7, q);
1050
                break;
1051
            case 14:
1052
                put_bits(&s->pb, 14, q);
1053
                break;
1054
            case 15:
1055
                put_bits(&s->pb, 16, q);
1056
                break;
1057
            default:
1058
                put_bits(&s->pb, b - 1, q);
1059
                break;
1060
            }
1061
        }
1062
    }
1063
}
1064

    
1065
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1066

    
1067
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1068
{
1069
    unsigned int c;
1070

    
1071
    c = 0;
1072
    while (a) {
1073
        if (a & 1)
1074
            c ^= b;
1075
        a = a >> 1;
1076
        b = b << 1;
1077
        if (b & (1 << 16))
1078
            b ^= poly;
1079
    }
1080
    return c;
1081
}
1082

    
1083
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1084
{
1085
    unsigned int r;
1086
    r = 1;
1087
    while (n) {
1088
        if (n & 1)
1089
            r = mul_poly(r, a, poly);
1090
        a = mul_poly(a, a, poly);
1091
        n >>= 1;
1092
    }
1093
    return r;
1094
}
1095

    
1096

    
1097
/* compute log2(max(abs(tab[]))) */
1098
static int log2_tab(int16_t *tab, int n)
1099
{
1100
    int i, v;
1101

    
1102
    v = 0;
1103
    for(i=0;i<n;i++) {
1104
        v |= abs(tab[i]);
1105
    }
1106
    return av_log2(v);
1107
}
1108

    
1109
static void lshift_tab(int16_t *tab, int n, int lshift)
1110
{
1111
    int i;
1112

    
1113
    if (lshift > 0) {
1114
        for(i=0;i<n;i++) {
1115
            tab[i] <<= lshift;
1116
        }
1117
    } else if (lshift < 0) {
1118
        lshift = -lshift;
1119
        for(i=0;i<n;i++) {
1120
            tab[i] >>= lshift;
1121
        }
1122
    }
1123
}
1124

    
1125
/* fill the end of the frame and compute the two crcs */
1126
static int output_frame_end(AC3EncodeContext *s)
1127
{
1128
    int frame_size, frame_size_58, n, crc1, crc2, crc_inv;
1129
    uint8_t *frame;
1130

    
1131
    frame_size = s->frame_size; /* frame size in words */
1132
    /* align to 8 bits */
1133
    flush_put_bits(&s->pb);
1134
    /* add zero bytes to reach the frame size */
1135
    frame = s->pb.buf;
1136
    n = 2 * s->frame_size - (pbBufPtr(&s->pb) - frame) - 2;
1137
    assert(n >= 0);
1138
    if(n>0)
1139
      memset(pbBufPtr(&s->pb), 0, n);
1140

    
1141
    /* Now we must compute both crcs : this is not so easy for crc1
1142
       because it is at the beginning of the data... */
1143
    frame_size_58 = (frame_size >> 1) + (frame_size >> 3);
1144
    crc1 = bswap_16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1145
                           frame + 4, 2 * frame_size_58 - 4));
1146
    /* XXX: could precompute crc_inv */
1147
    crc_inv = pow_poly((CRC16_POLY >> 1), (16 * frame_size_58) - 16, CRC16_POLY);
1148
    crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1149
    AV_WB16(frame+2,crc1);
1150

    
1151
    crc2 = bswap_16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1152
                           frame + 2 * frame_size_58,
1153
                           (frame_size - frame_size_58) * 2 - 2));
1154
    AV_WB16(frame+2*frame_size-2,crc2);
1155

    
1156
    //    printf("n=%d frame_size=%d\n", n, frame_size);
1157
    return frame_size * 2;
1158
}
1159

    
1160
static int AC3_encode_frame(AVCodecContext *avctx,
1161
                            unsigned char *frame, int buf_size, void *data)
1162
{
1163
    AC3EncodeContext *s = avctx->priv_data;
1164
    int16_t *samples = data;
1165
    int i, j, k, v, ch;
1166
    int16_t input_samples[N];
1167
    int32_t mdct_coef[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1168
    uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1169
    uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS];
1170
    uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1171
    uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1172
    int8_t exp_samples[NB_BLOCKS][AC3_MAX_CHANNELS];
1173
    int frame_bits;
1174

    
1175
    frame_bits = 0;
1176
    for(ch=0;ch<s->nb_all_channels;ch++) {
1177
        /* fixed mdct to the six sub blocks & exponent computation */
1178
        for(i=0;i<NB_BLOCKS;i++) {
1179
            int16_t *sptr;
1180
            int sinc;
1181

    
1182
            /* compute input samples */
1183
            memcpy(input_samples, s->last_samples[ch], N/2 * sizeof(int16_t));
1184
            sinc = s->nb_all_channels;
1185
            sptr = samples + (sinc * (N/2) * i) + ch;
1186
            for(j=0;j<N/2;j++) {
1187
                v = *sptr;
1188
                input_samples[j + N/2] = v;
1189
                s->last_samples[ch][j] = v;
1190
                sptr += sinc;
1191
            }
1192

    
1193
            /* apply the MDCT window */
1194
            for(j=0;j<N/2;j++) {
1195
                input_samples[j] = MUL16(input_samples[j],
1196
                                         ff_ac3_window[j]) >> 15;
1197
                input_samples[N-j-1] = MUL16(input_samples[N-j-1],
1198
                                             ff_ac3_window[j]) >> 15;
1199
            }
1200

    
1201
            /* Normalize the samples to use the maximum available
1202
               precision */
1203
            v = 14 - log2_tab(input_samples, N);
1204
            if (v < 0)
1205
                v = 0;
1206
            exp_samples[i][ch] = v - 9;
1207
            lshift_tab(input_samples, N, v);
1208

    
1209
            /* do the MDCT */
1210
            mdct512(mdct_coef[i][ch], input_samples);
1211

    
1212
            /* compute "exponents". We take into account the
1213
               normalization there */
1214
            for(j=0;j<N/2;j++) {
1215
                int e;
1216
                v = abs(mdct_coef[i][ch][j]);
1217
                if (v == 0)
1218
                    e = 24;
1219
                else {
1220
                    e = 23 - av_log2(v) + exp_samples[i][ch];
1221
                    if (e >= 24) {
1222
                        e = 24;
1223
                        mdct_coef[i][ch][j] = 0;
1224
                    }
1225
                }
1226
                exp[i][ch][j] = e;
1227
            }
1228
        }
1229

    
1230
        compute_exp_strategy(exp_strategy, exp, ch, ch == s->lfe_channel);
1231

    
1232
        /* compute the exponents as the decoder will see them. The
1233
           EXP_REUSE case must be handled carefully : we select the
1234
           min of the exponents */
1235
        i = 0;
1236
        while (i < NB_BLOCKS) {
1237
            j = i + 1;
1238
            while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE) {
1239
                exponent_min(exp[i][ch], exp[j][ch], s->nb_coefs[ch]);
1240
                j++;
1241
            }
1242
            frame_bits += encode_exp(encoded_exp[i][ch],
1243
                                     exp[i][ch], s->nb_coefs[ch],
1244
                                     exp_strategy[i][ch]);
1245
            /* copy encoded exponents for reuse case */
1246
            for(k=i+1;k<j;k++) {
1247
                memcpy(encoded_exp[k][ch], encoded_exp[i][ch],
1248
                       s->nb_coefs[ch] * sizeof(uint8_t));
1249
            }
1250
            i = j;
1251
        }
1252
    }
1253

    
1254
    /* adjust for fractional frame sizes */
1255
    while(s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
1256
        s->bits_written -= s->bit_rate;
1257
        s->samples_written -= s->sample_rate;
1258
    }
1259
    s->frame_size = s->frame_size_min + (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
1260
    s->bits_written += s->frame_size * 16;
1261
    s->samples_written += AC3_FRAME_SIZE;
1262

    
1263
    compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
1264
    /* everything is known... let's output the frame */
1265
    output_frame_header(s, frame);
1266

    
1267
    for(i=0;i<NB_BLOCKS;i++) {
1268
        output_audio_block(s, exp_strategy[i], encoded_exp[i],
1269
                           bap[i], mdct_coef[i], exp_samples[i], i);
1270
    }
1271
    return output_frame_end(s);
1272
}
1273

    
1274
static int AC3_encode_close(AVCodecContext *avctx)
1275
{
1276
    av_freep(&avctx->coded_frame);
1277
    return 0;
1278
}
1279

    
1280
#if 0
1281
/*************************************************************************/
1282
/* TEST */
1283

1284
#undef random
1285
#define FN (N/4)
1286

1287
void fft_test(void)
1288
{
1289
    IComplex in[FN], in1[FN];
1290
    int k, n, i;
1291
    float sum_re, sum_im, a;
1292

1293
    /* FFT test */
1294

1295
    for(i=0;i<FN;i++) {
1296
        in[i].re = random() % 65535 - 32767;
1297
        in[i].im = random() % 65535 - 32767;
1298
        in1[i] = in[i];
1299
    }
1300
    fft(in, 7);
1301

1302
    /* do it by hand */
1303
    for(k=0;k<FN;k++) {
1304
        sum_re = 0;
1305
        sum_im = 0;
1306
        for(n=0;n<FN;n++) {
1307
            a = -2 * M_PI * (n * k) / FN;
1308
            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1309
            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1310
        }
1311
        printf("%3d: %6d,%6d %6.0f,%6.0f\n",
1312
               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1313
    }
1314
}
1315

1316
void mdct_test(void)
1317
{
1318
    int16_t input[N];
1319
    int32_t output[N/2];
1320
    float input1[N];
1321
    float output1[N/2];
1322
    float s, a, err, e, emax;
1323
    int i, k, n;
1324

1325
    for(i=0;i<N;i++) {
1326
        input[i] = (random() % 65535 - 32767) * 9 / 10;
1327
        input1[i] = input[i];
1328
    }
1329

1330
    mdct512(output, input);
1331

1332
    /* do it by hand */
1333
    for(k=0;k<N/2;k++) {
1334
        s = 0;
1335
        for(n=0;n<N;n++) {
1336
            a = (2*M_PI*(2*n+1+N/2)*(2*k+1) / (4 * N));
1337
            s += input1[n] * cos(a);
1338
        }
1339
        output1[k] = -2 * s / N;
1340
    }
1341

1342
    err = 0;
1343
    emax = 0;
1344
    for(i=0;i<N/2;i++) {
1345
        printf("%3d: %7d %7.0f\n", i, output[i], output1[i]);
1346
        e = output[i] - output1[i];
1347
        if (e > emax)
1348
            emax = e;
1349
        err += e * e;
1350
    }
1351
    printf("err2=%f emax=%f\n", err / (N/2), emax);
1352
}
1353

1354
void test_ac3(void)
1355
{
1356
    AC3EncodeContext ctx;
1357
    unsigned char frame[AC3_MAX_CODED_FRAME_SIZE];
1358
    short samples[AC3_FRAME_SIZE];
1359
    int ret, i;
1360

1361
    AC3_encode_init(&ctx, 44100, 64000, 1);
1362

1363
    fft_test();
1364
    mdct_test();
1365

1366
    for(i=0;i<AC3_FRAME_SIZE;i++)
1367
        samples[i] = (int)(sin(2*M_PI*i*1000.0/44100) * 10000);
1368
    ret = AC3_encode_frame(&ctx, frame, samples);
1369
    printf("ret=%d\n", ret);
1370
}
1371
#endif
1372

    
1373
AVCodec ac3_encoder = {
1374
    "ac3",
1375
    CODEC_TYPE_AUDIO,
1376
    CODEC_ID_AC3,
1377
    sizeof(AC3EncodeContext),
1378
    AC3_encode_init,
1379
    AC3_encode_frame,
1380
    AC3_encode_close,
1381
    NULL,
1382
};