Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ 1df051e1

History | View | Annotate | Download (42.6 KB)

1
/*
2
 * The simplest AC3 encoder
3
 * Copyright (c) 2000 Fabrice Bellard.
4
 *
5
 * This library is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU Lesser General Public
7
 * License as published by the Free Software Foundation; either
8
 * version 2 of the License, or (at your option) any later version.
9
 *
10
 * This library is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 * Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public
16
 * License along with this library; if not, write to the Free Software
17
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
 */
19

    
20
/**
21
 * @file ac3enc.c
22
 * The simplest AC3 encoder.
23
 */
24
//#define DEBUG
25
//#define DEBUG_BITALLOC
26
#include "avcodec.h"
27
#include "bitstream.h"
28
#include "crc.h"
29
#include "ac3.h"
30

    
31
typedef struct AC3EncodeContext {
32
    PutBitContext pb;
33
    int nb_channels;
34
    int nb_all_channels;
35
    int lfe_channel;
36
    int bit_rate;
37
    unsigned int sample_rate;
38
    unsigned int bsid;
39
    unsigned int frame_size_min; /* minimum frame size in case rounding is necessary */
40
    unsigned int frame_size; /* current frame size in words */
41
    unsigned int bits_written;
42
    unsigned int samples_written;
43
    int halfratecod;
44
    unsigned int frmsizecod;
45
    unsigned int fscod; /* frequency */
46
    unsigned int acmod;
47
    int lfe;
48
    unsigned int bsmod;
49
    short last_samples[AC3_MAX_CHANNELS][256];
50
    unsigned int chbwcod[AC3_MAX_CHANNELS];
51
    int nb_coefs[AC3_MAX_CHANNELS];
52

    
53
    /* bitrate allocation control */
54
    int sgaincod, sdecaycod, fdecaycod, dbkneecod, floorcod;
55
    AC3BitAllocParameters bit_alloc;
56
    int csnroffst;
57
    int fgaincod[AC3_MAX_CHANNELS];
58
    int fsnroffst[AC3_MAX_CHANNELS];
59
    /* mantissa encoding */
60
    int mant1_cnt, mant2_cnt, mant4_cnt;
61
} AC3EncodeContext;
62

    
63
#include "ac3tab.h"
64

    
65
#define MDCT_NBITS 9
66
#define N         (1 << MDCT_NBITS)
67

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

    
71
static void fft_init(int ln);
72

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

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

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

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

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

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

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

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

    
191
        end1=bndend;
192
        if (end1 > 22) end1=22;
193

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

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

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

    
206
            v=fastleak - lowcomp;
207
            if (slowleak > v) v=slowleak;
208

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

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

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

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

    
233
    /* compute masking curve */
234

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

    
246
    /* delta bit allocation */
247

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

    
265
    /* compute bit allocation */
266

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

    
277
        end1=bndtab[j] + bndsz[j];
278
        if (end1 > end) end1=end;
279

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

    
290
typedef struct IComplex {
291
    short re,im;
292
} IComplex;
293

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

    
299
    n = 1 << ln;
300

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

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

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

    
330
#define MUL16(a,b) ((a) * (b))
331

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

    
338

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

    
347
    np = 1 << ln;
348

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

    
361
    /* pass 0 */
362

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

    
371
    /* pass 1 */
372

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

    
383
    /* pass 2 .. ln-1 */
384

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

    
393
            BF(p->re, p->im, q->re, q->im,
394
               p->re, p->im, q->re, q->im);
395

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

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

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

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

    
433
    fft(x, MDCT_NBITS - 2);
434

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
580
    return 4 + (nb_groups / 3) * 7;
581
}
582

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

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

    
633

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

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

    
668
#define SNR_INC1 4
669

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

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

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

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

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

    
730
    /* auxdatae, crcrsv */
731
    frame_bits += 2;
732

    
733
    /* CRC */
734
    frame_bits += 16;
735

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

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

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

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

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

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

    
810

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

    
828
    avctx->frame_size = AC3_FRAME_SIZE;
829

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

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

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

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

    
882
    ac3_common_init();
883

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

    
892
    avctx->coded_frame= avcodec_alloc_frame();
893
    avctx->coded_frame->key_frame= 1;
894

    
895
    return 0;
896
}
897

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1240
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1241

    
1242
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1243
{
1244
    unsigned int c;
1245

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

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

    
1271

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1404
        compute_exp_strategy(exp_strategy, exp, ch, ch == s->lfe_channel);
1405

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

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

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

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

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

    
1454
#if 0
1455
/*************************************************************************/
1456
/* TEST */
1457

1458
#define FN (N/4)
1459

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

1466
    /* FFT test */
1467

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

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

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

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

1503
    mdct512(output, input);
1504

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

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

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

1534
    AC3_encode_init(&ctx, 44100, 64000, 1);
1535

1536
    fft_test();
1537
    mdct_test();
1538

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

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