Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ 3e954443

History | View | Annotate | Download (42.6 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 bsid;
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 halfratecod;
46
    unsigned int frmsizecod;
47
    unsigned int fscod; /* frequency */
48
    unsigned int acmod;
49
    int lfe;
50
    unsigned int bsmod;
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 sgaincod, sdecaycod, fdecaycod, dbkneecod, floorcod;
57
    AC3BitAllocParameters bit_alloc;
58
    int csnroffst;
59
    int fgaincod[AC3_MAX_CHANNELS];
60
    int fsnroffst[AC3_MAX_CHANNELS];
61
    /* mantissa encoding */
62
    int mant1_cnt, mant2_cnt, mant4_cnt;
63
} AC3EncodeContext;
64

    
65
#include "ac3tab.h"
66

    
67
#define MDCT_NBITS 9
68
#define N         (1 << MDCT_NBITS)
69

    
70
/* new exponents are sent if their Norm 1 exceed this number */
71
#define EXP_DIFF_THRESHOLD 1000
72

    
73
static void fft_init(int ln);
74

    
75
static inline int16_t fix15(float a)
76
{
77
    int v;
78
    v = (int)(a * (float)(1 << 15));
79
    if (v < -32767)
80
        v = -32767;
81
    else if (v > 32767)
82
        v = 32767;
83
    return v;
84
}
85

    
86
static inline int calc_lowcomp1(int a, int b0, int b1)
87
{
88
    if ((b0 + 256) == b1) {
89
        a = 384 ;
90
    } else if (b0 > b1) {
91
        a = a - 64;
92
        if (a < 0) a=0;
93
    }
94
    return a;
95
}
96

    
97
static inline int calc_lowcomp(int a, int b0, int b1, int bin)
98
{
99
    if (bin < 7) {
100
        if ((b0 + 256) == b1) {
101
            a = 384 ;
102
        } else if (b0 > b1) {
103
            a = a - 64;
104
            if (a < 0) a=0;
105
        }
106
    } else if (bin < 20) {
107
        if ((b0 + 256) == b1) {
108
            a = 320 ;
109
        } else if (b0 > b1) {
110
            a= a - 64;
111
            if (a < 0) a=0;
112
        }
113
    } else {
114
        a = a - 128;
115
        if (a < 0) a=0;
116
    }
117
    return a;
118
}
119

    
120
/* AC3 bit allocation. The algorithm is the one described in the AC3
121
   spec. */
122
void ac3_parametric_bit_allocation(AC3BitAllocParameters *s, uint8_t *bap,
123
                                   int8_t *exp, int start, int end,
124
                                   int snroffset, int fgain, int is_lfe,
125
                                   int deltbae,int deltnseg,
126
                                   uint8_t *deltoffst, uint8_t *deltlen, uint8_t *deltba)
127
{
128
    int bin,i,j,k,end1,v,v1,bndstrt,bndend,lowcomp,begin;
129
    int fastleak,slowleak,address,tmp;
130
    int16_t psd[256]; /* scaled exponents */
131
    int16_t bndpsd[50]; /* interpolated exponents */
132
    int16_t excite[50]; /* excitation */
133
    int16_t mask[50];   /* masking value */
134

    
135
    /* exponent mapping to PSD */
136
    for(bin=start;bin<end;bin++) {
137
        psd[bin]=(3072 - (exp[bin] << 7));
138
    }
139

    
140
    /* PSD integration */
141
    j=start;
142
    k=masktab[start];
143
    do {
144
        v=psd[j];
145
        j++;
146
        end1=bndtab[k+1];
147
        if (end1 > end) end1=end;
148
        for(i=j;i<end1;i++) {
149
            int c,adr;
150
            /* logadd */
151
            v1=psd[j];
152
            c=v-v1;
153
            if (c >= 0) {
154
                adr=c >> 1;
155
                if (adr > 255) adr=255;
156
                v=v + latab[adr];
157
            } else {
158
                adr=(-c) >> 1;
159
                if (adr > 255) adr=255;
160
                v=v1 + latab[adr];
161
            }
162
            j++;
163
        }
164
        bndpsd[k]=v;
165
        k++;
166
    } while (end > bndtab[k]);
167

    
168
    /* excitation function */
169
    bndstrt = masktab[start];
170
    bndend = masktab[end-1] + 1;
171

    
172
    if (bndstrt == 0) {
173
        lowcomp = 0;
174
        lowcomp = calc_lowcomp1(lowcomp, bndpsd[0], bndpsd[1]) ;
175
        excite[0] = bndpsd[0] - fgain - lowcomp ;
176
        lowcomp = calc_lowcomp1(lowcomp, bndpsd[1], bndpsd[2]) ;
177
        excite[1] = bndpsd[1] - fgain - lowcomp ;
178
        begin = 7 ;
179
        for (bin = 2; bin < 7; bin++) {
180
            if (!(is_lfe && bin == 6))
181
                lowcomp = calc_lowcomp1(lowcomp, bndpsd[bin], bndpsd[bin+1]) ;
182
            fastleak = bndpsd[bin] - fgain ;
183
            slowleak = bndpsd[bin] - s->sgain ;
184
            excite[bin] = fastleak - lowcomp ;
185
            if (!(is_lfe && bin == 6)) {
186
                if (bndpsd[bin] <= bndpsd[bin+1]) {
187
                    begin = bin + 1 ;
188
                    break ;
189
                }
190
            }
191
        }
192

    
193
        end1=bndend;
194
        if (end1 > 22) end1=22;
195

    
196
        for (bin = begin; bin < end1; bin++) {
197
            if (!(is_lfe && bin == 6))
198
                lowcomp = calc_lowcomp(lowcomp, bndpsd[bin], bndpsd[bin+1], bin) ;
199

    
200
            fastleak -= s->fdecay ;
201
            v = bndpsd[bin] - fgain;
202
            if (fastleak < v) fastleak = v;
203

    
204
            slowleak -= s->sdecay ;
205
            v = bndpsd[bin] - s->sgain;
206
            if (slowleak < v) slowleak = v;
207

    
208
            v=fastleak - lowcomp;
209
            if (slowleak > v) v=slowleak;
210

    
211
            excite[bin] = v;
212
        }
213
        begin = 22;
214
    } else {
215
        /* coupling channel */
216
        begin = bndstrt;
217

    
218
        fastleak = (s->cplfleak << 8) + 768;
219
        slowleak = (s->cplsleak << 8) + 768;
220
    }
221

    
222
    for (bin = begin; bin < bndend; bin++) {
223
        fastleak -= s->fdecay ;
224
        v = bndpsd[bin] - fgain;
225
        if (fastleak < v) fastleak = v;
226
        slowleak -= s->sdecay ;
227
        v = bndpsd[bin] - s->sgain;
228
        if (slowleak < v) slowleak = v;
229

    
230
        v=fastleak;
231
        if (slowleak > v) v = slowleak;
232
        excite[bin] = v;
233
    }
234

    
235
    /* compute masking curve */
236

    
237
    for (bin = bndstrt; bin < bndend; bin++) {
238
        v1 = excite[bin];
239
        tmp = s->dbknee - bndpsd[bin];
240
        if (tmp > 0) {
241
            v1 += tmp >> 2;
242
        }
243
        v=hth[bin >> s->halfratecod][s->fscod];
244
        if (v1 > v) v=v1;
245
        mask[bin] = v;
246
    }
247

    
248
    /* delta bit allocation */
249

    
250
    if (deltbae == 0 || deltbae == 1) {
251
        int band, seg, delta;
252
        band = 0 ;
253
        for (seg = 0; seg < deltnseg; seg++) {
254
            band += deltoffst[seg] ;
255
            if (deltba[seg] >= 4) {
256
                delta = (deltba[seg] - 3) << 7;
257
            } else {
258
                delta = (deltba[seg] - 4) << 7;
259
            }
260
            for (k = 0; k < deltlen[seg]; k++) {
261
                mask[band] += delta ;
262
                band++ ;
263
            }
264
        }
265
    }
266

    
267
    /* compute bit allocation */
268

    
269
    i = start ;
270
    j = masktab[start] ;
271
    do {
272
        v=mask[j];
273
        v -= snroffset ;
274
        v -= s->floor ;
275
        if (v < 0) v = 0;
276
        v &= 0x1fe0 ;
277
        v += s->floor ;
278

    
279
        end1=bndtab[j] + bndsz[j];
280
        if (end1 > end) end1=end;
281

    
282
        for (k = i; k < end1; k++) {
283
            address = (psd[i] - v) >> 5 ;
284
            if (address < 0) address=0;
285
            else if (address > 63) address=63;
286
            bap[i] = baptab[address];
287
            i++;
288
        }
289
    } while (end > bndtab[j++]) ;
290
}
291

    
292
typedef struct IComplex {
293
    short re,im;
294
} IComplex;
295

    
296
static void fft_init(int ln)
297
{
298
    int i, j, m, n;
299
    float alpha;
300

    
301
    n = 1 << ln;
302

    
303
    for(i=0;i<(n/2);i++) {
304
        alpha = 2 * M_PI * (float)i / (float)n;
305
        costab[i] = fix15(cos(alpha));
306
        sintab[i] = fix15(sin(alpha));
307
    }
308

    
309
    for(i=0;i<n;i++) {
310
        m=0;
311
        for(j=0;j<ln;j++) {
312
            m |= ((i >> j) & 1) << (ln-j-1);
313
        }
314
        fft_rev[i]=m;
315
    }
316
}
317

    
318
/* butter fly op */
319
#define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1) \
320
{\
321
  int ax, ay, bx, by;\
322
  bx=pre1;\
323
  by=pim1;\
324
  ax=qre1;\
325
  ay=qim1;\
326
  pre = (bx + ax) >> 1;\
327
  pim = (by + ay) >> 1;\
328
  qre = (bx - ax) >> 1;\
329
  qim = (by - ay) >> 1;\
330
}
331

    
332
#define MUL16(a,b) ((a) * (b))
333

    
334
#define CMUL(pre, pim, are, aim, bre, bim) \
335
{\
336
   pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;\
337
   pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;\
338
}
339

    
340

    
341
/* do a 2^n point complex fft on 2^ln points. */
342
static void fft(IComplex *z, int ln)
343
{
344
    int        j, l, np, np2;
345
    int        nblocks, nloops;
346
    register IComplex *p,*q;
347
    int tmp_re, tmp_im;
348

    
349
    np = 1 << ln;
350

    
351
    /* reverse */
352
    for(j=0;j<np;j++) {
353
        int k;
354
        IComplex tmp;
355
        k = fft_rev[j];
356
        if (k < j) {
357
            tmp = z[k];
358
            z[k] = z[j];
359
            z[j] = tmp;
360
        }
361
    }
362

    
363
    /* pass 0 */
364

    
365
    p=&z[0];
366
    j=(np >> 1);
367
    do {
368
        BF(p[0].re, p[0].im, p[1].re, p[1].im,
369
           p[0].re, p[0].im, p[1].re, p[1].im);
370
        p+=2;
371
    } while (--j != 0);
372

    
373
    /* pass 1 */
374

    
375
    p=&z[0];
376
    j=np >> 2;
377
    do {
378
        BF(p[0].re, p[0].im, p[2].re, p[2].im,
379
           p[0].re, p[0].im, p[2].re, p[2].im);
380
        BF(p[1].re, p[1].im, p[3].re, p[3].im,
381
           p[1].re, p[1].im, p[3].im, -p[3].re);
382
        p+=4;
383
    } while (--j != 0);
384

    
385
    /* pass 2 .. ln-1 */
386

    
387
    nblocks = np >> 3;
388
    nloops = 1 << 2;
389
    np2 = np >> 1;
390
    do {
391
        p = z;
392
        q = z + nloops;
393
        for (j = 0; j < nblocks; ++j) {
394

    
395
            BF(p->re, p->im, q->re, q->im,
396
               p->re, p->im, q->re, q->im);
397

    
398
            p++;
399
            q++;
400
            for(l = nblocks; l < np2; l += nblocks) {
401
                CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
402
                BF(p->re, p->im, q->re, q->im,
403
                   p->re, p->im, tmp_re, tmp_im);
404
                p++;
405
                q++;
406
            }
407
            p += nloops;
408
            q += nloops;
409
        }
410
        nblocks = nblocks >> 1;
411
        nloops = nloops << 1;
412
    } while (nblocks != 0);
413
}
414

    
415
/* do a 512 point mdct */
416
static void mdct512(int32_t *out, int16_t *in)
417
{
418
    int i, re, im, re1, im1;
419
    int16_t rot[N];
420
    IComplex x[N/4];
421

    
422
    /* shift to simplify computations */
423
    for(i=0;i<N/4;i++)
424
        rot[i] = -in[i + 3*N/4];
425
    for(i=N/4;i<N;i++)
426
        rot[i] = in[i - N/4];
427

    
428
    /* pre rotation */
429
    for(i=0;i<N/4;i++) {
430
        re = ((int)rot[2*i] - (int)rot[N-1-2*i]) >> 1;
431
        im = -((int)rot[N/2+2*i] - (int)rot[N/2-1-2*i]) >> 1;
432
        CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
433
    }
434

    
435
    fft(x, MDCT_NBITS - 2);
436

    
437
    /* post rotation */
438
    for(i=0;i<N/4;i++) {
439
        re = x[i].re;
440
        im = x[i].im;
441
        CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
442
        out[2*i] = im1;
443
        out[N/2-1-2*i] = re1;
444
    }
445
}
446

    
447
/* XXX: use another norm ? */
448
static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
449
{
450
    int sum, i;
451
    sum = 0;
452
    for(i=0;i<n;i++) {
453
        sum += abs(exp1[i] - exp2[i]);
454
    }
455
    return sum;
456
}
457

    
458
static void compute_exp_strategy(uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
459
                                 uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
460
                                 int ch, int is_lfe)
461
{
462
    int i, j;
463
    int exp_diff;
464

    
465
    /* estimate if the exponent variation & decide if they should be
466
       reused in the next frame */
467
    exp_strategy[0][ch] = EXP_NEW;
468
    for(i=1;i<NB_BLOCKS;i++) {
469
        exp_diff = calc_exp_diff(exp[i][ch], exp[i-1][ch], N/2);
470
#ifdef DEBUG
471
        av_log(NULL, AV_LOG_DEBUG, "exp_diff=%d\n", exp_diff);
472
#endif
473
        if (exp_diff > EXP_DIFF_THRESHOLD)
474
            exp_strategy[i][ch] = EXP_NEW;
475
        else
476
            exp_strategy[i][ch] = EXP_REUSE;
477
    }
478
    if (is_lfe)
479
        return;
480

    
481
    /* now select the encoding strategy type : if exponents are often
482
       recoded, we use a coarse encoding */
483
    i = 0;
484
    while (i < NB_BLOCKS) {
485
        j = i + 1;
486
        while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE)
487
            j++;
488
        switch(j - i) {
489
        case 1:
490
            exp_strategy[i][ch] = EXP_D45;
491
            break;
492
        case 2:
493
        case 3:
494
            exp_strategy[i][ch] = EXP_D25;
495
            break;
496
        default:
497
            exp_strategy[i][ch] = EXP_D15;
498
            break;
499
        }
500
        i = j;
501
    }
502
}
503

    
504
/* set exp[i] to min(exp[i], exp1[i]) */
505
static void exponent_min(uint8_t exp[N/2], uint8_t exp1[N/2], int n)
506
{
507
    int i;
508

    
509
    for(i=0;i<n;i++) {
510
        if (exp1[i] < exp[i])
511
            exp[i] = exp1[i];
512
    }
513
}
514

    
515
/* update the exponents so that they are the ones the decoder will
516
   decode. Return the number of bits used to code the exponents */
517
static int encode_exp(uint8_t encoded_exp[N/2],
518
                      uint8_t exp[N/2],
519
                      int nb_exps,
520
                      int exp_strategy)
521
{
522
    int group_size, nb_groups, i, j, k, exp_min;
523
    uint8_t exp1[N/2];
524

    
525
    switch(exp_strategy) {
526
    case EXP_D15:
527
        group_size = 1;
528
        break;
529
    case EXP_D25:
530
        group_size = 2;
531
        break;
532
    default:
533
    case EXP_D45:
534
        group_size = 4;
535
        break;
536
    }
537
    nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
538

    
539
    /* for each group, compute the minimum exponent */
540
    exp1[0] = exp[0]; /* DC exponent is handled separately */
541
    k = 1;
542
    for(i=1;i<=nb_groups;i++) {
543
        exp_min = exp[k];
544
        assert(exp_min >= 0 && exp_min <= 24);
545
        for(j=1;j<group_size;j++) {
546
            if (exp[k+j] < exp_min)
547
                exp_min = exp[k+j];
548
        }
549
        exp1[i] = exp_min;
550
        k += group_size;
551
    }
552

    
553
    /* constraint for DC exponent */
554
    if (exp1[0] > 15)
555
        exp1[0] = 15;
556

    
557
    /* Decrease the delta between each groups to within 2
558
     * so that they can be differentially encoded */
559
    for (i=1;i<=nb_groups;i++)
560
        exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
561
    for (i=nb_groups-1;i>=0;i--)
562
        exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
563

    
564
    /* now we have the exponent values the decoder will see */
565
    encoded_exp[0] = exp1[0];
566
    k = 1;
567
    for(i=1;i<=nb_groups;i++) {
568
        for(j=0;j<group_size;j++) {
569
            encoded_exp[k+j] = exp1[i];
570
        }
571
        k += group_size;
572
    }
573

    
574
#if defined(DEBUG)
575
    av_log(NULL, AV_LOG_DEBUG, "exponents: strategy=%d\n", exp_strategy);
576
    for(i=0;i<=nb_groups * group_size;i++) {
577
        av_log(NULL, AV_LOG_DEBUG, "%d ", encoded_exp[i]);
578
    }
579
    av_log(NULL, AV_LOG_DEBUG, "\n");
580
#endif
581

    
582
    return 4 + (nb_groups / 3) * 7;
583
}
584

    
585
/* return the size in bits taken by the mantissa */
586
static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
587
{
588
    int bits, mant, i;
589

    
590
    bits = 0;
591
    for(i=0;i<nb_coefs;i++) {
592
        mant = m[i];
593
        switch(mant) {
594
        case 0:
595
            /* nothing */
596
            break;
597
        case 1:
598
            /* 3 mantissa in 5 bits */
599
            if (s->mant1_cnt == 0)
600
                bits += 5;
601
            if (++s->mant1_cnt == 3)
602
                s->mant1_cnt = 0;
603
            break;
604
        case 2:
605
            /* 3 mantissa in 7 bits */
606
            if (s->mant2_cnt == 0)
607
                bits += 7;
608
            if (++s->mant2_cnt == 3)
609
                s->mant2_cnt = 0;
610
            break;
611
        case 3:
612
            bits += 3;
613
            break;
614
        case 4:
615
            /* 2 mantissa in 7 bits */
616
            if (s->mant4_cnt == 0)
617
                bits += 7;
618
            if (++s->mant4_cnt == 2)
619
                s->mant4_cnt = 0;
620
            break;
621
        case 14:
622
            bits += 14;
623
            break;
624
        case 15:
625
            bits += 16;
626
            break;
627
        default:
628
            bits += mant - 1;
629
            break;
630
        }
631
    }
632
    return bits;
633
}
634

    
635

    
636
static int bit_alloc(AC3EncodeContext *s,
637
                     uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
638
                     uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
639
                     uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
640
                     int frame_bits, int csnroffst, int fsnroffst)
641
{
642
    int i, ch;
643

    
644
    /* compute size */
645
    for(i=0;i<NB_BLOCKS;i++) {
646
        s->mant1_cnt = 0;
647
        s->mant2_cnt = 0;
648
        s->mant4_cnt = 0;
649
        for(ch=0;ch<s->nb_all_channels;ch++) {
650
            ac3_parametric_bit_allocation(&s->bit_alloc,
651
                                          bap[i][ch], (int8_t *)encoded_exp[i][ch],
652
                                          0, s->nb_coefs[ch],
653
                                          (((csnroffst-15) << 4) +
654
                                           fsnroffst) << 2,
655
                                          fgaintab[s->fgaincod[ch]],
656
                                          ch == s->lfe_channel,
657
                                          2, 0, NULL, NULL, NULL);
658
            frame_bits += compute_mantissa_size(s, bap[i][ch],
659
                                                 s->nb_coefs[ch]);
660
        }
661
    }
662
#if 0
663
    printf("csnr=%d fsnr=%d frame_bits=%d diff=%d\n",
664
           csnroffst, fsnroffst, frame_bits,
665
           16 * s->frame_size - ((frame_bits + 7) & ~7));
666
#endif
667
    return 16 * s->frame_size - frame_bits;
668
}
669

    
670
#define SNR_INC1 4
671

    
672
static int compute_bit_allocation(AC3EncodeContext *s,
673
                                  uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
674
                                  uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
675
                                  uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
676
                                  int frame_bits)
677
{
678
    int i, ch;
679
    int csnroffst, fsnroffst;
680
    uint8_t bap1[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
681
    static int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
682

    
683
    /* init default parameters */
684
    s->sdecaycod = 2;
685
    s->fdecaycod = 1;
686
    s->sgaincod = 1;
687
    s->dbkneecod = 2;
688
    s->floorcod = 4;
689
    for(ch=0;ch<s->nb_all_channels;ch++)
690
        s->fgaincod[ch] = 4;
691

    
692
    /* compute real values */
693
    s->bit_alloc.fscod = s->fscod;
694
    s->bit_alloc.halfratecod = s->halfratecod;
695
    s->bit_alloc.sdecay = sdecaytab[s->sdecaycod] >> s->halfratecod;
696
    s->bit_alloc.fdecay = fdecaytab[s->fdecaycod] >> s->halfratecod;
697
    s->bit_alloc.sgain = sgaintab[s->sgaincod];
698
    s->bit_alloc.dbknee = dbkneetab[s->dbkneecod];
699
    s->bit_alloc.floor = floortab[s->floorcod];
700

    
701
    /* header size */
702
    frame_bits += 65;
703
    // if (s->acmod == 2)
704
    //    frame_bits += 2;
705
    frame_bits += frame_bits_inc[s->acmod];
706

    
707
    /* audio blocks */
708
    for(i=0;i<NB_BLOCKS;i++) {
709
        frame_bits += s->nb_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
710
        if (s->acmod == 2) {
711
            frame_bits++; /* rematstr */
712
            if(i==0) frame_bits += 4;
713
        }
714
        frame_bits += 2 * s->nb_channels; /* chexpstr[2] * c */
715
        if (s->lfe)
716
            frame_bits++; /* lfeexpstr */
717
        for(ch=0;ch<s->nb_channels;ch++) {
718
            if (exp_strategy[i][ch] != EXP_REUSE)
719
                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
720
        }
721
        frame_bits++; /* baie */
722
        frame_bits++; /* snr */
723
        frame_bits += 2; /* delta / skip */
724
    }
725
    frame_bits++; /* cplinu for block 0 */
726
    /* bit alloc info */
727
    /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
728
    /* csnroffset[6] */
729
    /* (fsnoffset[4] + fgaincod[4]) * c */
730
    frame_bits += 2*4 + 3 + 6 + s->nb_all_channels * (4 + 3);
731

    
732
    /* auxdatae, crcrsv */
733
    frame_bits += 2;
734

    
735
    /* CRC */
736
    frame_bits += 16;
737

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

    
741
    csnroffst = s->csnroffst;
742
    while (csnroffst >= 0 &&
743
           bit_alloc(s, bap, encoded_exp, exp_strategy, frame_bits, csnroffst, 0) < 0)
744
        csnroffst -= SNR_INC1;
745
    if (csnroffst < 0) {
746
        av_log(NULL, AV_LOG_ERROR, "Bit allocation failed, try increasing the bitrate, -ab 384 for example!\n");
747
        return -1;
748
    }
749
    while ((csnroffst + SNR_INC1) <= 63 &&
750
           bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits,
751
                     csnroffst + SNR_INC1, 0) >= 0) {
752
        csnroffst += SNR_INC1;
753
        memcpy(bap, bap1, sizeof(bap1));
754
    }
755
    while ((csnroffst + 1) <= 63 &&
756
           bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits, csnroffst + 1, 0) >= 0) {
757
        csnroffst++;
758
        memcpy(bap, bap1, sizeof(bap1));
759
    }
760

    
761
    fsnroffst = 0;
762
    while ((fsnroffst + SNR_INC1) <= 15 &&
763
           bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits,
764
                     csnroffst, fsnroffst + SNR_INC1) >= 0) {
765
        fsnroffst += SNR_INC1;
766
        memcpy(bap, bap1, sizeof(bap1));
767
    }
768
    while ((fsnroffst + 1) <= 15 &&
769
           bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits,
770
                     csnroffst, fsnroffst + 1) >= 0) {
771
        fsnroffst++;
772
        memcpy(bap, bap1, sizeof(bap1));
773
    }
774

    
775
    s->csnroffst = csnroffst;
776
    for(ch=0;ch<s->nb_all_channels;ch++)
777
        s->fsnroffst[ch] = fsnroffst;
778
#if defined(DEBUG_BITALLOC)
779
    {
780
        int j;
781

    
782
        for(i=0;i<6;i++) {
783
            for(ch=0;ch<s->nb_all_channels;ch++) {
784
                printf("Block #%d Ch%d:\n", i, ch);
785
                printf("bap=");
786
                for(j=0;j<s->nb_coefs[ch];j++) {
787
                    printf("%d ",bap[i][ch][j]);
788
                }
789
                printf("\n");
790
            }
791
        }
792
    }
793
#endif
794
    return 0;
795
}
796

    
797
void ac3_common_init(void)
798
{
799
    int i, j, k, l, v;
800
    /* compute bndtab and masktab from bandsz */
801
    k = 0;
802
    l = 0;
803
    for(i=0;i<50;i++) {
804
        bndtab[i] = l;
805
        v = bndsz[i];
806
        for(j=0;j<v;j++) masktab[k++]=i;
807
        l += v;
808
    }
809
    bndtab[50] = l;
810
}
811

    
812

    
813
static int AC3_encode_init(AVCodecContext *avctx)
814
{
815
    int freq = avctx->sample_rate;
816
    int bitrate = avctx->bit_rate;
817
    int channels = avctx->channels;
818
    AC3EncodeContext *s = avctx->priv_data;
819
    int i, j, ch;
820
    float alpha;
821
    static const uint8_t acmod_defs[6] = {
822
        0x01, /* C */
823
        0x02, /* L R */
824
        0x03, /* L C R */
825
        0x06, /* L R SL SR */
826
        0x07, /* L C R SL SR */
827
        0x07, /* L C R SL SR (+LFE) */
828
    };
829

    
830
    avctx->frame_size = AC3_FRAME_SIZE;
831

    
832
    /* number of channels */
833
    if (channels < 1 || channels > 6)
834
        return -1;
835
    s->acmod = acmod_defs[channels - 1];
836
    s->lfe = (channels == 6) ? 1 : 0;
837
    s->nb_all_channels = channels;
838
    s->nb_channels = channels > 5 ? 5 : channels;
839
    s->lfe_channel = s->lfe ? 5 : -1;
840

    
841
    /* frequency */
842
    for(i=0;i<3;i++) {
843
        for(j=0;j<3;j++)
844
            if ((ac3_freqs[j] >> i) == freq)
845
                goto found;
846
    }
847
    return -1;
848
 found:
849
    s->sample_rate = freq;
850
    s->halfratecod = i;
851
    s->fscod = j;
852
    s->bsid = 8 + s->halfratecod;
853
    s->bsmod = 0; /* complete main audio service */
854

    
855
    /* bitrate & frame size */
856
    bitrate /= 1000;
857
    for(i=0;i<19;i++) {
858
        if ((ac3_bitratetab[i] >> s->halfratecod) == bitrate)
859
            break;
860
    }
861
    if (i == 19)
862
        return -1;
863
    s->bit_rate = bitrate;
864
    s->frmsizecod = i << 1;
865
    s->frame_size_min = (bitrate * 1000 * AC3_FRAME_SIZE) / (freq * 16);
866
    s->bits_written = 0;
867
    s->samples_written = 0;
868
    s->frame_size = s->frame_size_min;
869

    
870
    /* bit allocation init */
871
    for(ch=0;ch<s->nb_channels;ch++) {
872
        /* bandwidth for each channel */
873
        /* XXX: should compute the bandwidth according to the frame
874
           size, so that we avoid anoying high freq artefacts */
875
        s->chbwcod[ch] = 50; /* sample bandwidth as mpeg audio layer 2 table 0 */
876
        s->nb_coefs[ch] = ((s->chbwcod[ch] + 12) * 3) + 37;
877
    }
878
    if (s->lfe) {
879
        s->nb_coefs[s->lfe_channel] = 7; /* fixed */
880
    }
881
    /* initial snr offset */
882
    s->csnroffst = 40;
883

    
884
    ac3_common_init();
885

    
886
    /* mdct init */
887
    fft_init(MDCT_NBITS - 2);
888
    for(i=0;i<N/4;i++) {
889
        alpha = 2 * M_PI * (i + 1.0 / 8.0) / (float)N;
890
        xcos1[i] = fix15(-cos(alpha));
891
        xsin1[i] = fix15(-sin(alpha));
892
    }
893

    
894
    avctx->coded_frame= avcodec_alloc_frame();
895
    avctx->coded_frame->key_frame= 1;
896

    
897
    return 0;
898
}
899

    
900
/* output the AC3 frame header */
901
static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
902
{
903
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
904

    
905
    put_bits(&s->pb, 16, 0x0b77); /* frame header */
906
    put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
907
    put_bits(&s->pb, 2, s->fscod);
908
    put_bits(&s->pb, 6, s->frmsizecod + (s->frame_size - s->frame_size_min));
909
    put_bits(&s->pb, 5, s->bsid);
910
    put_bits(&s->pb, 3, s->bsmod);
911
    put_bits(&s->pb, 3, s->acmod);
912
    if ((s->acmod & 0x01) && s->acmod != 0x01)
913
        put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
914
    if (s->acmod & 0x04)
915
        put_bits(&s->pb, 2, 1); /* XXX -6 dB */
916
    if (s->acmod == 0x02)
917
        put_bits(&s->pb, 2, 0); /* surround not indicated */
918
    put_bits(&s->pb, 1, s->lfe); /* LFE */
919
    put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
920
    put_bits(&s->pb, 1, 0); /* no compression control word */
921
    put_bits(&s->pb, 1, 0); /* no lang code */
922
    put_bits(&s->pb, 1, 0); /* no audio production info */
923
    put_bits(&s->pb, 1, 0); /* no copyright */
924
    put_bits(&s->pb, 1, 1); /* original bitstream */
925
    put_bits(&s->pb, 1, 0); /* no time code 1 */
926
    put_bits(&s->pb, 1, 0); /* no time code 2 */
927
    put_bits(&s->pb, 1, 0); /* no addtional bit stream info */
928
}
929

    
930
/* symetric quantization on 'levels' levels */
931
static inline int sym_quant(int c, int e, int levels)
932
{
933
    int v;
934

    
935
    if (c >= 0) {
936
        v = (levels * (c << e)) >> 24;
937
        v = (v + 1) >> 1;
938
        v = (levels >> 1) + v;
939
    } else {
940
        v = (levels * ((-c) << e)) >> 24;
941
        v = (v + 1) >> 1;
942
        v = (levels >> 1) - v;
943
    }
944
    assert (v >= 0 && v < levels);
945
    return v;
946
}
947

    
948
/* asymetric quantization on 2^qbits levels */
949
static inline int asym_quant(int c, int e, int qbits)
950
{
951
    int lshift, m, v;
952

    
953
    lshift = e + qbits - 24;
954
    if (lshift >= 0)
955
        v = c << lshift;
956
    else
957
        v = c >> (-lshift);
958
    /* rounding */
959
    v = (v + 1) >> 1;
960
    m = (1 << (qbits-1));
961
    if (v >= m)
962
        v = m - 1;
963
    assert(v >= -m);
964
    return v & ((1 << qbits)-1);
965
}
966

    
967
/* Output one audio block. There are NB_BLOCKS audio blocks in one AC3
968
   frame */
969
static void output_audio_block(AC3EncodeContext *s,
970
                               uint8_t exp_strategy[AC3_MAX_CHANNELS],
971
                               uint8_t encoded_exp[AC3_MAX_CHANNELS][N/2],
972
                               uint8_t bap[AC3_MAX_CHANNELS][N/2],
973
                               int32_t mdct_coefs[AC3_MAX_CHANNELS][N/2],
974
                               int8_t global_exp[AC3_MAX_CHANNELS],
975
                               int block_num)
976
{
977
    int ch, nb_groups, group_size, i, baie, rbnd;
978
    uint8_t *p;
979
    uint16_t qmant[AC3_MAX_CHANNELS][N/2];
980
    int exp0, exp1;
981
    int mant1_cnt, mant2_cnt, mant4_cnt;
982
    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
983
    int delta0, delta1, delta2;
984

    
985
    for(ch=0;ch<s->nb_channels;ch++)
986
        put_bits(&s->pb, 1, 0); /* 512 point MDCT */
987
    for(ch=0;ch<s->nb_channels;ch++)
988
        put_bits(&s->pb, 1, 1); /* no dither */
989
    put_bits(&s->pb, 1, 0); /* no dynamic range */
990
    if (block_num == 0) {
991
        /* for block 0, even if no coupling, we must say it. This is a
992
           waste of bit :-) */
993
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
994
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
995
    } else {
996
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
997
    }
998

    
999
    if (s->acmod == 2)
1000
      {
1001
        if(block_num==0)
1002
          {
1003
            /* first block must define rematrixing (rematstr)  */
1004
            put_bits(&s->pb, 1, 1);
1005

    
1006
            /* dummy rematrixing rematflg(1:4)=0 */
1007
            for (rbnd=0;rbnd<4;rbnd++)
1008
              put_bits(&s->pb, 1, 0);
1009
          }
1010
        else
1011
          {
1012
            /* no matrixing (but should be used in the future) */
1013
            put_bits(&s->pb, 1, 0);
1014
          }
1015
      }
1016

    
1017
#if defined(DEBUG)
1018
    {
1019
      static int count = 0;
1020
      av_log(NULL, AV_LOG_DEBUG, "Block #%d (%d)\n", block_num, count++);
1021
    }
1022
#endif
1023
    /* exponent strategy */
1024
    for(ch=0;ch<s->nb_channels;ch++) {
1025
        put_bits(&s->pb, 2, exp_strategy[ch]);
1026
    }
1027

    
1028
    if (s->lfe) {
1029
        put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
1030
    }
1031

    
1032
    for(ch=0;ch<s->nb_channels;ch++) {
1033
        if (exp_strategy[ch] != EXP_REUSE)
1034
            put_bits(&s->pb, 6, s->chbwcod[ch]);
1035
    }
1036

    
1037
    /* exponents */
1038
    for (ch = 0; ch < s->nb_all_channels; ch++) {
1039
        switch(exp_strategy[ch]) {
1040
        case EXP_REUSE:
1041
            continue;
1042
        case EXP_D15:
1043
            group_size = 1;
1044
            break;
1045
        case EXP_D25:
1046
            group_size = 2;
1047
            break;
1048
        default:
1049
        case EXP_D45:
1050
            group_size = 4;
1051
            break;
1052
        }
1053
        nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
1054
        p = encoded_exp[ch];
1055

    
1056
        /* first exponent */
1057
        exp1 = *p++;
1058
        put_bits(&s->pb, 4, exp1);
1059

    
1060
        /* next ones are delta encoded */
1061
        for(i=0;i<nb_groups;i++) {
1062
            /* merge three delta in one code */
1063
            exp0 = exp1;
1064
            exp1 = p[0];
1065
            p += group_size;
1066
            delta0 = exp1 - exp0 + 2;
1067

    
1068
            exp0 = exp1;
1069
            exp1 = p[0];
1070
            p += group_size;
1071
            delta1 = exp1 - exp0 + 2;
1072

    
1073
            exp0 = exp1;
1074
            exp1 = p[0];
1075
            p += group_size;
1076
            delta2 = exp1 - exp0 + 2;
1077

    
1078
            put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
1079
        }
1080

    
1081
        if (ch != s->lfe_channel)
1082
            put_bits(&s->pb, 2, 0); /* no gain range info */
1083
    }
1084

    
1085
    /* bit allocation info */
1086
    baie = (block_num == 0);
1087
    put_bits(&s->pb, 1, baie);
1088
    if (baie) {
1089
        put_bits(&s->pb, 2, s->sdecaycod);
1090
        put_bits(&s->pb, 2, s->fdecaycod);
1091
        put_bits(&s->pb, 2, s->sgaincod);
1092
        put_bits(&s->pb, 2, s->dbkneecod);
1093
        put_bits(&s->pb, 3, s->floorcod);
1094
    }
1095

    
1096
    /* snr offset */
1097
    put_bits(&s->pb, 1, baie); /* always present with bai */
1098
    if (baie) {
1099
        put_bits(&s->pb, 6, s->csnroffst);
1100
        for(ch=0;ch<s->nb_all_channels;ch++) {
1101
            put_bits(&s->pb, 4, s->fsnroffst[ch]);
1102
            put_bits(&s->pb, 3, s->fgaincod[ch]);
1103
        }
1104
    }
1105

    
1106
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1107
    put_bits(&s->pb, 1, 0); /* no data to skip */
1108

    
1109
    /* mantissa encoding : we use two passes to handle the grouping. A
1110
       one pass method may be faster, but it would necessitate to
1111
       modify the output stream. */
1112

    
1113
    /* first pass: quantize */
1114
    mant1_cnt = mant2_cnt = mant4_cnt = 0;
1115
    qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
1116

    
1117
    for (ch = 0; ch < s->nb_all_channels; ch++) {
1118
        int b, c, e, v;
1119

    
1120
        for(i=0;i<s->nb_coefs[ch];i++) {
1121
            c = mdct_coefs[ch][i];
1122
            e = encoded_exp[ch][i] - global_exp[ch];
1123
            b = bap[ch][i];
1124
            switch(b) {
1125
            case 0:
1126
                v = 0;
1127
                break;
1128
            case 1:
1129
                v = sym_quant(c, e, 3);
1130
                switch(mant1_cnt) {
1131
                case 0:
1132
                    qmant1_ptr = &qmant[ch][i];
1133
                    v = 9 * v;
1134
                    mant1_cnt = 1;
1135
                    break;
1136
                case 1:
1137
                    *qmant1_ptr += 3 * v;
1138
                    mant1_cnt = 2;
1139
                    v = 128;
1140
                    break;
1141
                default:
1142
                    *qmant1_ptr += v;
1143
                    mant1_cnt = 0;
1144
                    v = 128;
1145
                    break;
1146
                }
1147
                break;
1148
            case 2:
1149
                v = sym_quant(c, e, 5);
1150
                switch(mant2_cnt) {
1151
                case 0:
1152
                    qmant2_ptr = &qmant[ch][i];
1153
                    v = 25 * v;
1154
                    mant2_cnt = 1;
1155
                    break;
1156
                case 1:
1157
                    *qmant2_ptr += 5 * v;
1158
                    mant2_cnt = 2;
1159
                    v = 128;
1160
                    break;
1161
                default:
1162
                    *qmant2_ptr += v;
1163
                    mant2_cnt = 0;
1164
                    v = 128;
1165
                    break;
1166
                }
1167
                break;
1168
            case 3:
1169
                v = sym_quant(c, e, 7);
1170
                break;
1171
            case 4:
1172
                v = sym_quant(c, e, 11);
1173
                switch(mant4_cnt) {
1174
                case 0:
1175
                    qmant4_ptr = &qmant[ch][i];
1176
                    v = 11 * v;
1177
                    mant4_cnt = 1;
1178
                    break;
1179
                default:
1180
                    *qmant4_ptr += v;
1181
                    mant4_cnt = 0;
1182
                    v = 128;
1183
                    break;
1184
                }
1185
                break;
1186
            case 5:
1187
                v = sym_quant(c, e, 15);
1188
                break;
1189
            case 14:
1190
                v = asym_quant(c, e, 14);
1191
                break;
1192
            case 15:
1193
                v = asym_quant(c, e, 16);
1194
                break;
1195
            default:
1196
                v = asym_quant(c, e, b - 1);
1197
                break;
1198
            }
1199
            qmant[ch][i] = v;
1200
        }
1201
    }
1202

    
1203
    /* second pass : output the values */
1204
    for (ch = 0; ch < s->nb_all_channels; ch++) {
1205
        int b, q;
1206

    
1207
        for(i=0;i<s->nb_coefs[ch];i++) {
1208
            q = qmant[ch][i];
1209
            b = bap[ch][i];
1210
            switch(b) {
1211
            case 0:
1212
                break;
1213
            case 1:
1214
                if (q != 128)
1215
                    put_bits(&s->pb, 5, q);
1216
                break;
1217
            case 2:
1218
                if (q != 128)
1219
                    put_bits(&s->pb, 7, q);
1220
                break;
1221
            case 3:
1222
                put_bits(&s->pb, 3, q);
1223
                break;
1224
            case 4:
1225
                if (q != 128)
1226
                    put_bits(&s->pb, 7, q);
1227
                break;
1228
            case 14:
1229
                put_bits(&s->pb, 14, q);
1230
                break;
1231
            case 15:
1232
                put_bits(&s->pb, 16, q);
1233
                break;
1234
            default:
1235
                put_bits(&s->pb, b - 1, q);
1236
                break;
1237
            }
1238
        }
1239
    }
1240
}
1241

    
1242
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1243

    
1244
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1245
{
1246
    unsigned int c;
1247

    
1248
    c = 0;
1249
    while (a) {
1250
        if (a & 1)
1251
            c ^= b;
1252
        a = a >> 1;
1253
        b = b << 1;
1254
        if (b & (1 << 16))
1255
            b ^= poly;
1256
    }
1257
    return c;
1258
}
1259

    
1260
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1261
{
1262
    unsigned int r;
1263
    r = 1;
1264
    while (n) {
1265
        if (n & 1)
1266
            r = mul_poly(r, a, poly);
1267
        a = mul_poly(a, a, poly);
1268
        n >>= 1;
1269
    }
1270
    return r;
1271
}
1272

    
1273

    
1274
/* compute log2(max(abs(tab[]))) */
1275
static int log2_tab(int16_t *tab, int n)
1276
{
1277
    int i, v;
1278

    
1279
    v = 0;
1280
    for(i=0;i<n;i++) {
1281
        v |= abs(tab[i]);
1282
    }
1283
    return av_log2(v);
1284
}
1285

    
1286
static void lshift_tab(int16_t *tab, int n, int lshift)
1287
{
1288
    int i;
1289

    
1290
    if (lshift > 0) {
1291
        for(i=0;i<n;i++) {
1292
            tab[i] <<= lshift;
1293
        }
1294
    } else if (lshift < 0) {
1295
        lshift = -lshift;
1296
        for(i=0;i<n;i++) {
1297
            tab[i] >>= lshift;
1298
        }
1299
    }
1300
}
1301

    
1302
/* fill the end of the frame and compute the two crcs */
1303
static int output_frame_end(AC3EncodeContext *s)
1304
{
1305
    int frame_size, frame_size_58, n, crc1, crc2, crc_inv;
1306
    uint8_t *frame;
1307

    
1308
    frame_size = s->frame_size; /* frame size in words */
1309
    /* align to 8 bits */
1310
    flush_put_bits(&s->pb);
1311
    /* add zero bytes to reach the frame size */
1312
    frame = s->pb.buf;
1313
    n = 2 * s->frame_size - (pbBufPtr(&s->pb) - frame) - 2;
1314
    assert(n >= 0);
1315
    if(n>0)
1316
      memset(pbBufPtr(&s->pb), 0, n);
1317

    
1318
    /* Now we must compute both crcs : this is not so easy for crc1
1319
       because it is at the beginning of the data... */
1320
    frame_size_58 = (frame_size >> 1) + (frame_size >> 3);
1321
    crc1 = bswap_16(av_crc(av_crc8005, 0, frame + 4, 2 * frame_size_58 - 4));
1322
    /* XXX: could precompute crc_inv */
1323
    crc_inv = pow_poly((CRC16_POLY >> 1), (16 * frame_size_58) - 16, CRC16_POLY);
1324
    crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1325
    frame[2] = crc1 >> 8;
1326
    frame[3] = crc1;
1327

    
1328
    crc2 = bswap_16(av_crc(av_crc8005, 0, frame + 2 * frame_size_58, (frame_size - frame_size_58) * 2 - 2));
1329
    frame[2*frame_size - 2] = crc2 >> 8;
1330
    frame[2*frame_size - 1] = crc2;
1331

    
1332
    //    printf("n=%d frame_size=%d\n", n, frame_size);
1333
    return frame_size * 2;
1334
}
1335

    
1336
static int AC3_encode_frame(AVCodecContext *avctx,
1337
                            unsigned char *frame, int buf_size, void *data)
1338
{
1339
    AC3EncodeContext *s = avctx->priv_data;
1340
    int16_t *samples = data;
1341
    int i, j, k, v, ch;
1342
    int16_t input_samples[N];
1343
    int32_t mdct_coef[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1344
    uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1345
    uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS];
1346
    uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1347
    uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1348
    int8_t exp_samples[NB_BLOCKS][AC3_MAX_CHANNELS];
1349
    int frame_bits;
1350

    
1351
    frame_bits = 0;
1352
    for(ch=0;ch<s->nb_all_channels;ch++) {
1353
        /* fixed mdct to the six sub blocks & exponent computation */
1354
        for(i=0;i<NB_BLOCKS;i++) {
1355
            int16_t *sptr;
1356
            int sinc;
1357

    
1358
            /* compute input samples */
1359
            memcpy(input_samples, s->last_samples[ch], N/2 * sizeof(int16_t));
1360
            sinc = s->nb_all_channels;
1361
            sptr = samples + (sinc * (N/2) * i) + ch;
1362
            for(j=0;j<N/2;j++) {
1363
                v = *sptr;
1364
                input_samples[j + N/2] = v;
1365
                s->last_samples[ch][j] = v;
1366
                sptr += sinc;
1367
            }
1368

    
1369
            /* apply the MDCT window */
1370
            for(j=0;j<N/2;j++) {
1371
                input_samples[j] = MUL16(input_samples[j],
1372
                                         ac3_window[j]) >> 15;
1373
                input_samples[N-j-1] = MUL16(input_samples[N-j-1],
1374
                                             ac3_window[j]) >> 15;
1375
            }
1376

    
1377
            /* Normalize the samples to use the maximum available
1378
               precision */
1379
            v = 14 - log2_tab(input_samples, N);
1380
            if (v < 0)
1381
                v = 0;
1382
            exp_samples[i][ch] = v - 10;
1383
            lshift_tab(input_samples, N, v);
1384

    
1385
            /* do the MDCT */
1386
            mdct512(mdct_coef[i][ch], input_samples);
1387

    
1388
            /* compute "exponents". We take into account the
1389
               normalization there */
1390
            for(j=0;j<N/2;j++) {
1391
                int e;
1392
                v = abs(mdct_coef[i][ch][j]);
1393
                if (v == 0)
1394
                    e = 24;
1395
                else {
1396
                    e = 23 - av_log2(v) + exp_samples[i][ch];
1397
                    if (e >= 24) {
1398
                        e = 24;
1399
                        mdct_coef[i][ch][j] = 0;
1400
                    }
1401
                }
1402
                exp[i][ch][j] = e;
1403
            }
1404
        }
1405

    
1406
        compute_exp_strategy(exp_strategy, exp, ch, ch == s->lfe_channel);
1407

    
1408
        /* compute the exponents as the decoder will see them. The
1409
           EXP_REUSE case must be handled carefully : we select the
1410
           min of the exponents */
1411
        i = 0;
1412
        while (i < NB_BLOCKS) {
1413
            j = i + 1;
1414
            while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE) {
1415
                exponent_min(exp[i][ch], exp[j][ch], s->nb_coefs[ch]);
1416
                j++;
1417
            }
1418
            frame_bits += encode_exp(encoded_exp[i][ch],
1419
                                     exp[i][ch], s->nb_coefs[ch],
1420
                                     exp_strategy[i][ch]);
1421
            /* copy encoded exponents for reuse case */
1422
            for(k=i+1;k<j;k++) {
1423
                memcpy(encoded_exp[k][ch], encoded_exp[i][ch],
1424
                       s->nb_coefs[ch] * sizeof(uint8_t));
1425
            }
1426
            i = j;
1427
        }
1428
    }
1429

    
1430
    /* adjust for fractional frame sizes */
1431
    while(s->bits_written >= s->bit_rate*1000 && s->samples_written >= s->sample_rate) {
1432
        s->bits_written -= s->bit_rate*1000;
1433
        s->samples_written -= s->sample_rate;
1434
    }
1435
    s->frame_size = s->frame_size_min + (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate*1000);
1436
    s->bits_written += s->frame_size * 16;
1437
    s->samples_written += AC3_FRAME_SIZE;
1438

    
1439
    compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
1440
    /* everything is known... let's output the frame */
1441
    output_frame_header(s, frame);
1442

    
1443
    for(i=0;i<NB_BLOCKS;i++) {
1444
        output_audio_block(s, exp_strategy[i], encoded_exp[i],
1445
                           bap[i], mdct_coef[i], exp_samples[i], i);
1446
    }
1447
    return output_frame_end(s);
1448
}
1449

    
1450
static int AC3_encode_close(AVCodecContext *avctx)
1451
{
1452
    av_freep(&avctx->coded_frame);
1453
    return 0;
1454
}
1455

    
1456
#if 0
1457
/*************************************************************************/
1458
/* TEST */
1459

1460
#define FN (N/4)
1461

1462
void fft_test(void)
1463
{
1464
    IComplex in[FN], in1[FN];
1465
    int k, n, i;
1466
    float sum_re, sum_im, a;
1467

1468
    /* FFT test */
1469

1470
    for(i=0;i<FN;i++) {
1471
        in[i].re = random() % 65535 - 32767;
1472
        in[i].im = random() % 65535 - 32767;
1473
        in1[i] = in[i];
1474
    }
1475
    fft(in, 7);
1476

1477
    /* do it by hand */
1478
    for(k=0;k<FN;k++) {
1479
        sum_re = 0;
1480
        sum_im = 0;
1481
        for(n=0;n<FN;n++) {
1482
            a = -2 * M_PI * (n * k) / FN;
1483
            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1484
            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1485
        }
1486
        printf("%3d: %6d,%6d %6.0f,%6.0f\n",
1487
               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1488
    }
1489
}
1490

1491
void mdct_test(void)
1492
{
1493
    int16_t input[N];
1494
    int32_t output[N/2];
1495
    float input1[N];
1496
    float output1[N/2];
1497
    float s, a, err, e, emax;
1498
    int i, k, n;
1499

1500
    for(i=0;i<N;i++) {
1501
        input[i] = (random() % 65535 - 32767) * 9 / 10;
1502
        input1[i] = input[i];
1503
    }
1504

1505
    mdct512(output, input);
1506

1507
    /* do it by hand */
1508
    for(k=0;k<N/2;k++) {
1509
        s = 0;
1510
        for(n=0;n<N;n++) {
1511
            a = (2*M_PI*(2*n+1+N/2)*(2*k+1) / (4 * N));
1512
            s += input1[n] * cos(a);
1513
        }
1514
        output1[k] = -2 * s / N;
1515
    }
1516

1517
    err = 0;
1518
    emax = 0;
1519
    for(i=0;i<N/2;i++) {
1520
        printf("%3d: %7d %7.0f\n", i, output[i], output1[i]);
1521
        e = output[i] - output1[i];
1522
        if (e > emax)
1523
            emax = e;
1524
        err += e * e;
1525
    }
1526
    printf("err2=%f emax=%f\n", err / (N/2), emax);
1527
}
1528

1529
void test_ac3(void)
1530
{
1531
    AC3EncodeContext ctx;
1532
    unsigned char frame[AC3_MAX_CODED_FRAME_SIZE];
1533
    short samples[AC3_FRAME_SIZE];
1534
    int ret, i;
1535

1536
    AC3_encode_init(&ctx, 44100, 64000, 1);
1537

1538
    fft_test();
1539
    mdct_test();
1540

1541
    for(i=0;i<AC3_FRAME_SIZE;i++)
1542
        samples[i] = (int)(sin(2*M_PI*i*1000.0/44100) * 10000);
1543
    ret = AC3_encode_frame(&ctx, frame, samples);
1544
    printf("ret=%d\n", ret);
1545
}
1546
#endif
1547

    
1548
AVCodec ac3_encoder = {
1549
    "ac3",
1550
    CODEC_TYPE_AUDIO,
1551
    CODEC_ID_AC3,
1552
    sizeof(AC3EncodeContext),
1553
    AC3_encode_init,
1554
    AC3_encode_frame,
1555
    AC3_encode_close,
1556
    NULL,
1557
};