Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ac3enc.c @ 11ce8834

History | View | Annotate | Download (39 KB)

1
/*
2
 * The simplest AC3 encoder
3
 * Copyright (c) 2000 Gerard Lantau.
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 2 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program 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
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
 */
19
//#define DEBUG
20
//#define DEBUG_BITALLOC
21
#include "avcodec.h"
22
#include <math.h>
23

    
24
#include "ac3enc.h"
25
#include "ac3tab.h"
26

    
27

    
28
#define MDCT_NBITS 9
29
#define N         (1 << MDCT_NBITS)
30
#define NB_BLOCKS 6 /* number of PCM blocks inside an AC3 frame */
31

    
32
/* new exponents are sent if their Norm 1 exceed this number */
33
#define EXP_DIFF_THRESHOLD 1000
34

    
35
/* exponent encoding strategy */
36
#define EXP_REUSE 0
37
#define EXP_NEW   1
38

    
39
#define EXP_D15   1
40
#define EXP_D25   2
41
#define EXP_D45   3
42

    
43
static void fft_init(int ln);
44
static void ac3_crc_init(void);
45

    
46
static inline INT16 fix15(float a)
47
{
48
    int v;
49
    v = (int)(a * (float)(1 << 15));
50
    if (v < -32767)
51
        v = -32767;
52
    else if (v > 32767) 
53
        v = 32767;
54
    return v;
55
}
56

    
57
static inline int calc_lowcomp1(int a, int b0, int b1)
58
{
59
    if ((b0 + 256) == b1) {
60
        a = 384 ;
61
    } else if (b0 > b1) { 
62
        a = a - 64;
63
        if (a < 0) a=0;
64
    }
65
    return a;
66
}
67

    
68
static inline int calc_lowcomp(int a, int b0, int b1, int bin)
69
{
70
    if (bin < 7) {
71
        if ((b0 + 256) == b1) {
72
            a = 384 ;
73
        } else if (b0 > b1) { 
74
            a = a - 64;
75
            if (a < 0) a=0;
76
        }
77
    } else if (bin < 20) {
78
        if ((b0 + 256) == b1) {
79
            a = 320 ;
80
        } else if (b0 > b1) {
81
            a= a - 64;
82
            if (a < 0) a=0;
83
        }
84
    } else {
85
        a = a - 128;
86
        if (a < 0) a=0;
87
    }
88
    return a;
89
}
90

    
91
/* AC3 bit allocation. The algorithm is the one described in the AC3
92
   spec with some optimizations because of our simplified encoding
93
   assumptions. */
94
void parametric_bit_allocation(AC3EncodeContext *s, UINT8 *bap,
95
                               INT8 *exp, int start, int end,
96
                               int snroffset, int fgain)
97
{
98
    int bin,i,j,k,end1,v,v1,bndstrt,bndend,lowcomp,begin;
99
    int fastleak,slowleak,address,tmp;
100
    INT16 psd[256]; /* scaled exponents */
101
    INT16 bndpsd[50]; /* interpolated exponents */
102
    INT16 excite[50]; /* excitation */
103
    INT16 mask[50];   /* masking value */
104

    
105
    /* exponent mapping to PSD */
106
    for(bin=start;bin<end;bin++) {
107
        psd[bin]=(3072 - (exp[bin] << 7));
108
    }
109

    
110
    /* PSD integration */
111
    j=start;
112
    k=masktab[start];
113
    do {
114
        v=psd[j];
115
        j++;
116
        end1=bndtab[k+1];
117
        if (end1 > end) end1=end;
118
        for(i=j;i<end1;i++) {
119
            int c,adr;
120
            /* logadd */
121
            v1=psd[j];
122
            c=v-v1;
123
            if (c >= 0) {
124
                adr=c >> 1;
125
                if (adr > 255) adr=255;
126
                v=v + latab[adr];
127
            } else {
128
                adr=(-c) >> 1;
129
                if (adr > 255) adr=255;
130
                v=v1 + latab[adr];
131
            }
132
            j++;
133
        }
134
        bndpsd[k]=v;
135
        k++;
136
    } while (end > bndtab[k]);
137

    
138
    /* excitation function */
139
    bndstrt = masktab[start];
140
    bndend = masktab[end-1] + 1;
141
    
142
    lowcomp = 0;
143
    lowcomp = calc_lowcomp1(lowcomp, bndpsd[0], bndpsd[1]) ;
144
    excite[0] = bndpsd[0] - fgain - lowcomp ;
145
    lowcomp = calc_lowcomp1(lowcomp, bndpsd[1], bndpsd[2]) ;
146
    excite[1] = bndpsd[1] - fgain - lowcomp ;
147
    begin = 7 ;
148
    for (bin = 2; bin < 7; bin++) {
149
        lowcomp = calc_lowcomp1(lowcomp, bndpsd[bin], bndpsd[bin+1]) ;
150
        fastleak = bndpsd[bin] - fgain ;
151
        slowleak = bndpsd[bin] - s->sgain ;
152
        excite[bin] = fastleak - lowcomp ;
153
        if (bndpsd[bin] <= bndpsd[bin+1]) {
154
            begin = bin + 1 ;
155
            break ;
156
        }
157
    }
158
    
159
    end1=bndend;
160
    if (end1 > 22) end1=22;
161
    
162
    for (bin = begin; bin < end1; bin++) {
163
        lowcomp = calc_lowcomp(lowcomp, bndpsd[bin], bndpsd[bin+1], bin) ;
164
        
165
        fastleak -= s->fdecay ;
166
        v = bndpsd[bin] - fgain;
167
        if (fastleak < v) fastleak = v;
168
        
169
        slowleak -= s->sdecay ;
170
        v = bndpsd[bin] - s->sgain;
171
        if (slowleak < v) slowleak = v;
172
        
173
        v=fastleak - lowcomp;
174
        if (slowleak > v) v=slowleak;
175
        
176
        excite[bin] = v;
177
    }
178

    
179
    for (bin = 22; bin < bndend; bin++) {
180
        fastleak -= s->fdecay ;
181
        v = bndpsd[bin] - fgain;
182
        if (fastleak < v) fastleak = v;
183
        slowleak -= s->sdecay ;
184
        v = bndpsd[bin] - s->sgain;
185
        if (slowleak < v) slowleak = v;
186

    
187
        v=fastleak;
188
        if (slowleak > v) v = slowleak;
189
        excite[bin] = v;
190
    }
191

    
192
    /* compute masking curve */
193

    
194
    for (bin = bndstrt; bin < bndend; bin++) {
195
        v1 = excite[bin];
196
        tmp = s->dbknee - bndpsd[bin];
197
        if (tmp > 0) {
198
            v1 += tmp >> 2;
199
        }
200
        v=hth[bin >> s->halfratecod][s->fscod];
201
        if (v1 > v) v=v1;
202
        mask[bin] = v;
203
    }
204

    
205
    /* compute bit allocation */
206
    
207
    i = start ;
208
    j = masktab[start] ;
209
    do {
210
        v=mask[j];
211
        v -= snroffset ;
212
        v -= s->floor ;
213
        if (v < 0) v = 0;
214
        v &= 0x1fe0 ;
215
        v += s->floor ;
216

    
217
        end1=bndtab[j] + bndsz[j];
218
        if (end1 > end) end1=end;
219

    
220
        for (k = i; k < end1; k++) {
221
            address = (psd[i] - v) >> 5 ;
222
            if (address < 0) address=0;
223
            else if (address > 63) address=63;
224
            bap[i] = baptab[address];
225
            i++;
226
        }
227
    } while (end > bndtab[j++]) ;
228
}
229

    
230
typedef struct IComplex {
231
    short re,im;
232
} IComplex;
233

    
234
static void fft_init(int ln)
235
{
236
    int i, j, m, n;
237
    float alpha;
238

    
239
    n = 1 << ln;
240

    
241
    for(i=0;i<(n/2);i++) {
242
        alpha = 2 * M_PI * (float)i / (float)n;
243
        costab[i] = fix15(cos(alpha));
244
        sintab[i] = fix15(sin(alpha));
245
    }
246

    
247
    for(i=0;i<n;i++) {
248
        m=0;
249
        for(j=0;j<ln;j++) {
250
            m |= ((i >> j) & 1) << (ln-j-1);
251
        }
252
        fft_rev[i]=m;
253
    }
254
}
255

    
256
/* butter fly op */
257
#define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1) \
258
{\
259
  int ax, ay, bx, by;\
260
  bx=pre1;\
261
  by=pim1;\
262
  ax=qre1;\
263
  ay=qim1;\
264
  pre = (bx + ax) >> 1;\
265
  pim = (by + ay) >> 1;\
266
  qre = (bx - ax) >> 1;\
267
  qim = (by - ay) >> 1;\
268
}
269

    
270
#define MUL16(a,b) ((a) * (b))
271

    
272
#define CMUL(pre, pim, are, aim, bre, bim) \
273
{\
274
   pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;\
275
   pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;\
276
}
277

    
278

    
279
/* do a 2^n point complex fft on 2^ln points. */
280
static void fft(IComplex *z, int ln)
281
{
282
    int        j, l, np, np2;
283
    int        nblocks, nloops;
284
    register IComplex *p,*q;
285
    int tmp_re, tmp_im;
286

    
287
    np = 1 << ln;
288

    
289
    /* reverse */
290
    for(j=0;j<np;j++) {
291
        int k;
292
        IComplex tmp;
293
        k = fft_rev[j];
294
        if (k < j) {
295
            tmp = z[k];
296
            z[k] = z[j];
297
            z[j] = tmp;
298
        }
299
    }
300

    
301
    /* pass 0 */
302

    
303
    p=&z[0];
304
    j=(np >> 1);
305
    do {
306
        BF(p[0].re, p[0].im, p[1].re, p[1].im, 
307
           p[0].re, p[0].im, p[1].re, p[1].im);
308
        p+=2;
309
    } while (--j != 0);
310

    
311
    /* pass 1 */
312

    
313
    p=&z[0];
314
    j=np >> 2;
315
    do {
316
        BF(p[0].re, p[0].im, p[2].re, p[2].im, 
317
           p[0].re, p[0].im, p[2].re, p[2].im);
318
        BF(p[1].re, p[1].im, p[3].re, p[3].im, 
319
           p[1].re, p[1].im, p[3].im, -p[3].re);
320
        p+=4;
321
    } while (--j != 0);
322

    
323
    /* pass 2 .. ln-1 */
324

    
325
    nblocks = np >> 3;
326
    nloops = 1 << 2;
327
    np2 = np >> 1;
328
    do {
329
        p = z;
330
        q = z + nloops;
331
        for (j = 0; j < nblocks; ++j) {
332

    
333
            BF(p->re, p->im, q->re, q->im,
334
               p->re, p->im, q->re, q->im);
335
            
336
            p++;
337
            q++;
338
            for(l = nblocks; l < np2; l += nblocks) {
339
                CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
340
                BF(p->re, p->im, q->re, q->im,
341
                   p->re, p->im, tmp_re, tmp_im);
342
                p++;
343
                q++;
344
            }
345
            p += nloops;
346
            q += nloops;
347
        }
348
        nblocks = nblocks >> 1;
349
        nloops = nloops << 1;
350
    } while (nblocks != 0);
351
}
352

    
353
/* do a 512 point mdct */
354
static void mdct512(INT32 *out, INT16 *in)
355
{
356
    int i, re, im, re1, im1;
357
    INT16 rot[N]; 
358
    IComplex x[N/4];
359

    
360
    /* shift to simplify computations */
361
    for(i=0;i<N/4;i++)
362
        rot[i] = -in[i + 3*N/4];
363
    for(i=N/4;i<N;i++)
364
        rot[i] = in[i - N/4];
365
        
366
    /* pre rotation */
367
    for(i=0;i<N/4;i++) {
368
        re = ((int)rot[2*i] - (int)rot[N-1-2*i]) >> 1;
369
        im = -((int)rot[N/2+2*i] - (int)rot[N/2-1-2*i]) >> 1;
370
        CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
371
    }
372

    
373
    fft(x, MDCT_NBITS - 2);
374
  
375
    /* post rotation */
376
    for(i=0;i<N/4;i++) {
377
        re = x[i].re;
378
        im = x[i].im;
379
        CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
380
        out[2*i] = im1;
381
        out[N/2-1-2*i] = re1;
382
    }
383
}
384

    
385
/* XXX: use another norm ? */
386
static int calc_exp_diff(UINT8 *exp1, UINT8 *exp2, int n)
387
{
388
    int sum, i;
389
    sum = 0;
390
    for(i=0;i<n;i++) {
391
        sum += abs(exp1[i] - exp2[i]);
392
    }
393
    return sum;
394
}
395

    
396
static void compute_exp_strategy(UINT8 exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
397
                                 UINT8 exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
398
                                 int ch)
399
{
400
    int i, j;
401
    int exp_diff;
402
    
403
    /* estimate if the exponent variation & decide if they should be
404
       reused in the next frame */
405
    exp_strategy[0][ch] = EXP_NEW;
406
    for(i=1;i<NB_BLOCKS;i++) {
407
        exp_diff = calc_exp_diff(exp[i][ch], exp[i-1][ch], N/2);
408
#ifdef DEBUG            
409
        printf("exp_diff=%d\n", exp_diff);
410
#endif
411
        if (exp_diff > EXP_DIFF_THRESHOLD)
412
            exp_strategy[i][ch] = EXP_NEW;
413
        else
414
            exp_strategy[i][ch] = EXP_REUSE;
415
    }
416
    /* now select the encoding strategy type : if exponents are often
417
       recoded, we use a coarse encoding */
418
    i = 0;
419
    while (i < NB_BLOCKS) {
420
        j = i + 1;
421
        while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE)
422
            j++;
423
        switch(j - i) {
424
        case 1:
425
            exp_strategy[i][ch] = EXP_D45;
426
            break;
427
        case 2:
428
        case 3:
429
            exp_strategy[i][ch] = EXP_D25;
430
            break;
431
        default:
432
            exp_strategy[i][ch] = EXP_D15;
433
            break;
434
        }
435
        i = j;
436
    }
437
}
438

    
439
/* set exp[i] to min(exp[i], exp1[i]) */
440
static void exponent_min(UINT8 exp[N/2], UINT8 exp1[N/2], int n)
441
{
442
    int i;
443

    
444
    for(i=0;i<n;i++) {
445
        if (exp1[i] < exp[i])
446
            exp[i] = exp1[i];
447
    }
448
}
449
                                 
450
/* update the exponents so that they are the ones the decoder will
451
   decode. Return the number of bits used to code the exponents */
452
static int encode_exp(UINT8 encoded_exp[N/2], 
453
                      UINT8 exp[N/2], 
454
                      int nb_exps,
455
                      int exp_strategy)
456
{
457
    int group_size, nb_groups, i, j, k, recurse, exp_min, delta;
458
    UINT8 exp1[N/2];
459

    
460
    switch(exp_strategy) {
461
    case EXP_D15:
462
        group_size = 1;
463
        break;
464
    case EXP_D25:
465
        group_size = 2;
466
        break;
467
    default:
468
    case EXP_D45:
469
        group_size = 4;
470
        break;
471
    }
472
    nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
473

    
474
    /* for each group, compute the minimum exponent */
475
    exp1[0] = exp[0]; /* DC exponent is handled separately */
476
    k = 1;
477
    for(i=1;i<=nb_groups;i++) {
478
        exp_min = exp[k];
479
        assert(exp_min >= 0 && exp_min <= 24);
480
        for(j=1;j<group_size;j++) {
481
            if (exp[k+j] < exp_min)
482
                exp_min = exp[k+j];
483
        }
484
        exp1[i] = exp_min;
485
        k += group_size;
486
    }
487

    
488
    /* constraint for DC exponent */
489
    if (exp1[0] > 15)
490
        exp1[0] = 15;
491

    
492
    /* Iterate until the delta constraints between each groups are
493
       satisfyed. I'm sure it is possible to find a better algorithm,
494
       but I am lazy */
495
    do {
496
        recurse = 0;
497
        for(i=1;i<=nb_groups;i++) {
498
            delta = exp1[i] - exp1[i-1];
499
            if (delta > 2) {
500
                /* if delta too big, we encode a smaller exponent */
501
                exp1[i] = exp1[i-1] + 2;
502
            } else if (delta < -2) {
503
                /* if delta is too small, we must decrease the previous
504
               exponent, which means we must recurse */
505
                recurse = 1;
506
                exp1[i-1] = exp1[i] + 2;
507
            }
508
        }
509
    } while (recurse);
510
    
511
    /* now we have the exponent values the decoder will see */
512
    encoded_exp[0] = exp1[0];
513
    k = 1;
514
    for(i=1;i<=nb_groups;i++) {
515
        for(j=0;j<group_size;j++) {
516
            encoded_exp[k+j] = exp1[i];
517
        }
518
        k += group_size;
519
    }
520
    
521
#if defined(DEBUG)
522
    printf("exponents: strategy=%d\n", exp_strategy);
523
    for(i=0;i<=nb_groups * group_size;i++) {
524
        printf("%d ", encoded_exp[i]);
525
    }
526
    printf("\n");
527
#endif
528

    
529
    return 4 + (nb_groups / 3) * 7;
530
}
531

    
532
/* return the size in bits taken by the mantissa */
533
int compute_mantissa_size(AC3EncodeContext *s, UINT8 *m, int nb_coefs)
534
{
535
    int bits, mant, i;
536

    
537
    bits = 0;
538
    for(i=0;i<nb_coefs;i++) {
539
        mant = m[i];
540
        switch(mant) {
541
        case 0:
542
            /* nothing */
543
            break;
544
        case 1:
545
            /* 3 mantissa in 5 bits */
546
            if (s->mant1_cnt == 0) 
547
                bits += 5;
548
            if (++s->mant1_cnt == 3)
549
                s->mant1_cnt = 0;
550
            break;
551
        case 2:
552
            /* 3 mantissa in 7 bits */
553
            if (s->mant2_cnt == 0) 
554
                bits += 7;
555
            if (++s->mant2_cnt == 3)
556
                s->mant2_cnt = 0;
557
            break;
558
        case 3:
559
            bits += 3;
560
            break;
561
        case 4:
562
            /* 2 mantissa in 7 bits */
563
            if (s->mant4_cnt == 0)
564
                bits += 7;
565
            if (++s->mant4_cnt == 2) 
566
                s->mant4_cnt = 0;
567
            break;
568
        case 14:
569
            bits += 14;
570
            break;
571
        case 15:
572
            bits += 16;
573
            break;
574
        default:
575
            bits += mant - 1;
576
            break;
577
        }
578
    }
579
    return bits;
580
}
581

    
582

    
583
static int bit_alloc(AC3EncodeContext *s,
584
                     UINT8 bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
585
                     UINT8 encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
586
                     UINT8 exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
587
                     int frame_bits, int csnroffst, int fsnroffst)
588
{
589
    int i, ch;
590

    
591
    /* compute size */
592
    for(i=0;i<NB_BLOCKS;i++) {
593
        s->mant1_cnt = 0;
594
        s->mant2_cnt = 0;
595
        s->mant4_cnt = 0;
596
        for(ch=0;ch<s->nb_channels;ch++) {
597
            parametric_bit_allocation(s, bap[i][ch], (INT8 *)encoded_exp[i][ch], 
598
                                      0, s->nb_coefs[ch], 
599
                                      (((csnroffst-15) << 4) + 
600
                                       fsnroffst) << 2, 
601
                                      fgaintab[s->fgaincod[ch]]);
602
            frame_bits += compute_mantissa_size(s, bap[i][ch], 
603
                                                 s->nb_coefs[ch]);
604
        }
605
    }
606
#if 0
607
    printf("csnr=%d fsnr=%d frame_bits=%d diff=%d\n", 
608
           csnroffst, fsnroffst, frame_bits, 
609
           16 * s->frame_size - ((frame_bits + 7) & ~7));
610
#endif
611
    return 16 * s->frame_size - frame_bits;
612
}
613

    
614
#define SNR_INC1 4
615

    
616
static int compute_bit_allocation(AC3EncodeContext *s,
617
                                  UINT8 bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
618
                                  UINT8 encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
619
                                  UINT8 exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
620
                                  int frame_bits)
621
{
622
    int i, ch;
623
    int csnroffst, fsnroffst;
624
    UINT8 bap1[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
625

    
626
    /* init default parameters */
627
    s->sdecaycod = 2;
628
    s->fdecaycod = 1;
629
    s->sgaincod = 1;
630
    s->dbkneecod = 2;
631
    s->floorcod = 4;
632
    for(ch=0;ch<s->nb_channels;ch++) 
633
        s->fgaincod[ch] = 4;
634
    
635
    /* compute real values */
636
    s->sdecay = sdecaytab[s->sdecaycod] >> s->halfratecod;
637
    s->fdecay = fdecaytab[s->fdecaycod] >> s->halfratecod;
638
    s->sgain = sgaintab[s->sgaincod];
639
    s->dbknee = dbkneetab[s->dbkneecod];
640
    s->floor = floortab[s->floorcod];
641

    
642
    /* header size */
643
    frame_bits += 65;
644
    if (s->acmod == 2)
645
        frame_bits += 2;
646

    
647
    /* audio blocks */
648
    for(i=0;i<NB_BLOCKS;i++) {
649
        frame_bits += s->nb_channels * 2 + 2;
650
        if (s->acmod == 2)
651
            frame_bits++;
652
        frame_bits += 2 * s->nb_channels;
653
        for(ch=0;ch<s->nb_channels;ch++) {
654
            if (exp_strategy[i][ch] != EXP_REUSE)
655
                frame_bits += 6 + 2;
656
        }
657
        frame_bits++; /* baie */
658
        frame_bits++; /* snr */
659
        frame_bits += 2; /* delta / skip */
660
    }
661
    frame_bits++; /* cplinu for block 0 */
662
    /* bit alloc info */
663
    frame_bits += 2*4 + 3 + 6 + s->nb_channels * (4 + 3);
664

    
665
    /* CRC */
666
    frame_bits += 16;
667

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

    
671
    csnroffst = s->csnroffst;
672
    while (csnroffst >= 0 && 
673
           bit_alloc(s, bap, encoded_exp, exp_strategy, frame_bits, csnroffst, 0) < 0)
674
        csnroffst -= SNR_INC1;
675
    if (csnroffst < 0) {
676
        fprintf(stderr, "Error !!!\n");
677
        return -1;
678
    }
679
    while ((csnroffst + SNR_INC1) <= 63 && 
680
           bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits, 
681
                     csnroffst + SNR_INC1, 0) >= 0) {
682
        csnroffst += SNR_INC1;
683
        memcpy(bap, bap1, sizeof(bap1));
684
    }
685
    while ((csnroffst + 1) <= 63 && 
686
           bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits, csnroffst + 1, 0) >= 0) {
687
        csnroffst++;
688
        memcpy(bap, bap1, sizeof(bap1));
689
    }
690

    
691
    fsnroffst = 0;
692
    while ((fsnroffst + SNR_INC1) <= 15 && 
693
           bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits, 
694
                     csnroffst, fsnroffst + SNR_INC1) >= 0) {
695
        fsnroffst += SNR_INC1;
696
        memcpy(bap, bap1, sizeof(bap1));
697
    }
698
    while ((fsnroffst + 1) <= 15 && 
699
           bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits, 
700
                     csnroffst, fsnroffst + 1) >= 0) {
701
        fsnroffst++;
702
        memcpy(bap, bap1, sizeof(bap1));
703
    }
704
    
705
    s->csnroffst = csnroffst;
706
    for(ch=0;ch<s->nb_channels;ch++)
707
        s->fsnroffst[ch] = fsnroffst;
708
#if defined(DEBUG_BITALLOC)
709
    {
710
        int j;
711

    
712
        for(i=0;i<6;i++) {
713
            for(ch=0;ch<s->nb_channels;ch++) {
714
                printf("Block #%d Ch%d:\n", i, ch);
715
                printf("bap=");
716
                for(j=0;j<s->nb_coefs[ch];j++) {
717
                    printf("%d ",bap[i][ch][j]);
718
                }
719
                printf("\n");
720
            }
721
        }
722
    }
723
#endif
724
    return 0;
725
}
726

    
727
static int AC3_encode_init(AVCodecContext *avctx)
728
{
729
    int freq = avctx->sample_rate;
730
    int bitrate = avctx->bit_rate;
731
    int channels = avctx->channels;
732
    AC3EncodeContext *s = avctx->priv_data;
733
    int i, j, k, l, ch, v;
734
    float alpha;
735
    static unsigned short freqs[3] = { 48000, 44100, 32000 };
736

    
737
    avctx->frame_size = AC3_FRAME_SIZE;
738
    avctx->key_frame = 1; /* always key frame */
739
    
740
    /* number of channels */
741
    if (channels == 1)
742
        s->acmod = 1;
743
    else if (channels == 2)
744
        s->acmod = 2;
745
    else
746
        return -1;
747
    s->nb_channels = channels;
748

    
749
    /* frequency */
750
    for(i=0;i<3;i++) {
751
        for(j=0;j<3;j++) 
752
            if ((freqs[j] >> i) == freq)
753
                goto found;
754
    }
755
    return -1;
756
 found:    
757
    s->sample_rate = freq;
758
    s->halfratecod = i;
759
    s->fscod = j;
760
    s->bsid = 8 + s->halfratecod;
761
    s->bsmod = 0; /* complete main audio service */
762

    
763
    /* bitrate & frame size */
764
    bitrate /= 1000;
765
    for(i=0;i<19;i++) {
766
        if ((bitratetab[i] >> s->halfratecod) == bitrate)
767
            break;
768
    }
769
    if (i == 19)
770
        return -1;
771
    s->bit_rate = bitrate;
772
    s->frmsizecod = i << 1;
773
    s->frame_size_min = (bitrate * 1000 * AC3_FRAME_SIZE) / (freq * 16);
774
    /* for now we do not handle fractional sizes */
775
    s->frame_size = s->frame_size_min;
776
    
777
    /* bit allocation init */
778
    for(ch=0;ch<s->nb_channels;ch++) {
779
        /* bandwidth for each channel */
780
        /* XXX: should compute the bandwidth according to the frame
781
           size, so that we avoid anoying high freq artefacts */
782
        s->chbwcod[ch] = 50; /* sample bandwidth as mpeg audio layer 2 table 0 */
783
        s->nb_coefs[ch] = ((s->chbwcod[ch] + 12) * 3) + 37;
784
    }
785
    /* initial snr offset */
786
    s->csnroffst = 40;
787

    
788
    /* compute bndtab and masktab from bandsz */
789
    k = 0;
790
    l = 0;
791
    for(i=0;i<50;i++) {
792
        bndtab[i] = l;
793
        v = bndsz[i];
794
        for(j=0;j<v;j++) masktab[k++]=i;
795
        l += v;
796
    }
797
    bndtab[50] = 0;
798

    
799
    /* mdct init */
800
    fft_init(MDCT_NBITS - 2);
801
    for(i=0;i<N/4;i++) {
802
        alpha = 2 * M_PI * (i + 1.0 / 8.0) / (float)N;
803
        xcos1[i] = fix15(-cos(alpha));
804
        xsin1[i] = fix15(-sin(alpha));
805
    }
806

    
807
    ac3_crc_init();
808

    
809
    return 0;
810
}
811

    
812
/* output the AC3 frame header */
813
static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
814
{
815
    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE, NULL, NULL);
816

    
817
    put_bits(&s->pb, 16, 0x0b77); /* frame header */
818
    put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
819
    put_bits(&s->pb, 2, s->fscod);
820
    put_bits(&s->pb, 6, s->frmsizecod + (s->frame_size - s->frame_size_min));
821
    put_bits(&s->pb, 5, s->bsid);
822
    put_bits(&s->pb, 3, s->bsmod);
823
    put_bits(&s->pb, 3, s->acmod);
824
    if (s->acmod == 2) {
825
        put_bits(&s->pb, 2, 0); /* surround not indicated */
826
    }
827
    put_bits(&s->pb, 1, 0); /* no LFE */
828
    put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
829
    put_bits(&s->pb, 1, 0); /* no compression control word */
830
    put_bits(&s->pb, 1, 0); /* no lang code */
831
    put_bits(&s->pb, 1, 0); /* no audio production info */
832
    put_bits(&s->pb, 1, 0); /* no copyright */
833
    put_bits(&s->pb, 1, 1); /* original bitstream */
834
    put_bits(&s->pb, 1, 0); /* no time code 1 */
835
    put_bits(&s->pb, 1, 0); /* no time code 2 */
836
    put_bits(&s->pb, 1, 0); /* no addtional bit stream info */
837
}
838

    
839
/* symetric quantization on 'levels' levels */
840
static inline int sym_quant(int c, int e, int levels)
841
{
842
    int v;
843

    
844
    if (c >= 0) {
845
        v = (levels * (c << e)) >> 24;
846
        v = (v + 1) >> 1;
847
        v = (levels >> 1) + v;
848
    } else {
849
        v = (levels * ((-c) << e)) >> 24;
850
        v = (v + 1) >> 1;
851
        v = (levels >> 1) - v;
852
    }
853
    assert (v >= 0 && v < levels);
854
    return v;
855
}
856

    
857
/* asymetric quantization on 2^qbits levels */
858
static inline int asym_quant(int c, int e, int qbits)
859
{
860
    int lshift, m, v;
861

    
862
    lshift = e + qbits - 24;
863
    if (lshift >= 0)
864
        v = c << lshift;
865
    else
866
        v = c >> (-lshift);
867
    /* rounding */
868
    v = (v + 1) >> 1;
869
    m = (1 << (qbits-1));
870
    if (v >= m)
871
        v = m - 1;
872
    assert(v >= -m);
873
    return v & ((1 << qbits)-1);
874
}
875

    
876
/* Output one audio block. There are NB_BLOCKS audio blocks in one AC3
877
   frame */
878
static void output_audio_block(AC3EncodeContext *s,
879
                               UINT8 exp_strategy[AC3_MAX_CHANNELS],
880
                               UINT8 encoded_exp[AC3_MAX_CHANNELS][N/2],
881
                               UINT8 bap[AC3_MAX_CHANNELS][N/2],
882
                               INT32 mdct_coefs[AC3_MAX_CHANNELS][N/2],
883
                               INT8 global_exp[AC3_MAX_CHANNELS],
884
                               int block_num)
885
{
886
    int ch, nb_groups, group_size, i, baie;
887
    UINT8 *p;
888
    UINT16 qmant[AC3_MAX_CHANNELS][N/2];
889
    int exp0, exp1;
890
    int mant1_cnt, mant2_cnt, mant4_cnt;
891
    UINT16 *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
892
    int delta0, delta1, delta2;
893

    
894
    for(ch=0;ch<s->nb_channels;ch++) 
895
        put_bits(&s->pb, 1, 0); /* 512 point MDCT */
896
    for(ch=0;ch<s->nb_channels;ch++) 
897
        put_bits(&s->pb, 1, 1); /* no dither */
898
    put_bits(&s->pb, 1, 0); /* no dynamic range */
899
    if (block_num == 0) {
900
        /* for block 0, even if no coupling, we must say it. This is a
901
           waste of bit :-) */
902
        put_bits(&s->pb, 1, 1); /* coupling strategy present */
903
        put_bits(&s->pb, 1, 0); /* no coupling strategy */
904
    } else {
905
        put_bits(&s->pb, 1, 0); /* no new coupling strategy */
906
    }
907

    
908
    if (s->acmod == 2) {
909
        put_bits(&s->pb, 1, 0); /* no matrixing (but should be used in the future) */
910
    }
911

    
912
#if defined(DEBUG) 
913
    {
914
        static int count = 0;
915
        printf("Block #%d (%d)\n", block_num, count++);
916
    }
917
#endif
918
    /* exponent strategy */
919
    for(ch=0;ch<s->nb_channels;ch++) {
920
        put_bits(&s->pb, 2, exp_strategy[ch]);
921
    }
922
    
923
    for(ch=0;ch<s->nb_channels;ch++) {
924
        if (exp_strategy[ch] != EXP_REUSE)
925
            put_bits(&s->pb, 6, s->chbwcod[ch]);
926
    }
927
    
928
    /* exponents */
929
    for (ch = 0; ch < s->nb_channels; ch++) {
930
        switch(exp_strategy[ch]) {
931
        case EXP_REUSE:
932
            continue;
933
        case EXP_D15:
934
            group_size = 1;
935
            break;
936
        case EXP_D25:
937
            group_size = 2;
938
            break;
939
        default:
940
        case EXP_D45:
941
            group_size = 4;
942
            break;
943
        }
944
        nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
945
        p = encoded_exp[ch];
946

    
947
        /* first exponent */
948
        exp1 = *p++;
949
        put_bits(&s->pb, 4, exp1);
950

    
951
        /* next ones are delta encoded */
952
        for(i=0;i<nb_groups;i++) {
953
            /* merge three delta in one code */
954
            exp0 = exp1;
955
            exp1 = p[0];
956
            p += group_size;
957
            delta0 = exp1 - exp0 + 2;
958

    
959
            exp0 = exp1;
960
            exp1 = p[0];
961
            p += group_size;
962
            delta1 = exp1 - exp0 + 2;
963

    
964
            exp0 = exp1;
965
            exp1 = p[0];
966
            p += group_size;
967
            delta2 = exp1 - exp0 + 2;
968

    
969
            put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
970
        }
971

    
972
        put_bits(&s->pb, 2, 0); /* no gain range info */
973
    }
974

    
975
    /* bit allocation info */
976
    baie = (block_num == 0);
977
    put_bits(&s->pb, 1, baie);
978
    if (baie) {
979
        put_bits(&s->pb, 2, s->sdecaycod);
980
        put_bits(&s->pb, 2, s->fdecaycod);
981
        put_bits(&s->pb, 2, s->sgaincod);
982
        put_bits(&s->pb, 2, s->dbkneecod);
983
        put_bits(&s->pb, 3, s->floorcod);
984
    }
985

    
986
    /* snr offset */
987
    put_bits(&s->pb, 1, baie); /* always present with bai */
988
    if (baie) {
989
        put_bits(&s->pb, 6, s->csnroffst);
990
        for(ch=0;ch<s->nb_channels;ch++) {
991
            put_bits(&s->pb, 4, s->fsnroffst[ch]);
992
            put_bits(&s->pb, 3, s->fgaincod[ch]);
993
        }
994
    }
995
    
996
    put_bits(&s->pb, 1, 0); /* no delta bit allocation */
997
    put_bits(&s->pb, 1, 0); /* no data to skip */
998

    
999
    /* mantissa encoding : we use two passes to handle the grouping. A
1000
       one pass method may be faster, but it would necessitate to
1001
       modify the output stream. */
1002

    
1003
    /* first pass: quantize */
1004
    mant1_cnt = mant2_cnt = mant4_cnt = 0;
1005
    qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
1006

    
1007
    for (ch = 0; ch < s->nb_channels; ch++) {
1008
        int b, c, e, v;
1009

    
1010
        for(i=0;i<s->nb_coefs[ch];i++) {
1011
            c = mdct_coefs[ch][i];
1012
            e = encoded_exp[ch][i] - global_exp[ch];
1013
            b = bap[ch][i];
1014
            switch(b) {
1015
            case 0:
1016
                v = 0;
1017
                break;
1018
            case 1:
1019
                v = sym_quant(c, e, 3);
1020
                switch(mant1_cnt) {
1021
                case 0:
1022
                    qmant1_ptr = &qmant[ch][i];
1023
                    v = 9 * v;
1024
                    mant1_cnt = 1;
1025
                    break;
1026
                case 1:
1027
                    *qmant1_ptr += 3 * v;
1028
                    mant1_cnt = 2;
1029
                    v = 128;
1030
                    break;
1031
                default:
1032
                    *qmant1_ptr += v;
1033
                    mant1_cnt = 0;
1034
                    v = 128;
1035
                    break;
1036
                }
1037
                break;
1038
            case 2:
1039
                v = sym_quant(c, e, 5);
1040
                switch(mant2_cnt) {
1041
                case 0:
1042
                    qmant2_ptr = &qmant[ch][i];
1043
                    v = 25 * v;
1044
                    mant2_cnt = 1;
1045
                    break;
1046
                case 1:
1047
                    *qmant2_ptr += 5 * v;
1048
                    mant2_cnt = 2;
1049
                    v = 128;
1050
                    break;
1051
                default:
1052
                    *qmant2_ptr += v;
1053
                    mant2_cnt = 0;
1054
                    v = 128;
1055
                    break;
1056
                }
1057
                break;
1058
            case 3:
1059
                v = sym_quant(c, e, 7);
1060
                break;
1061
            case 4:
1062
                v = sym_quant(c, e, 11);
1063
                switch(mant4_cnt) {
1064
                case 0:
1065
                    qmant4_ptr = &qmant[ch][i];
1066
                    v = 11 * v;
1067
                    mant4_cnt = 1;
1068
                    break;
1069
                default:
1070
                    *qmant4_ptr += v;
1071
                    mant4_cnt = 0;
1072
                    v = 128;
1073
                    break;
1074
                }
1075
                break;
1076
            case 5:
1077
                v = sym_quant(c, e, 15);
1078
                break;
1079
            case 14:
1080
                v = asym_quant(c, e, 14);
1081
                break;
1082
            case 15:
1083
                v = asym_quant(c, e, 16);
1084
                break;
1085
            default:
1086
                v = asym_quant(c, e, b - 1);
1087
                break;
1088
            }
1089
            qmant[ch][i] = v;
1090
        }
1091
    }
1092

    
1093
    /* second pass : output the values */
1094
    for (ch = 0; ch < s->nb_channels; ch++) {
1095
        int b, q;
1096
        
1097
        for(i=0;i<s->nb_coefs[ch];i++) {
1098
            q = qmant[ch][i];
1099
            b = bap[ch][i];
1100
            switch(b) {
1101
            case 0:
1102
                break;
1103
            case 1:
1104
                if (q != 128) 
1105
                    put_bits(&s->pb, 5, q);
1106
                break;
1107
            case 2:
1108
                if (q != 128) 
1109
                    put_bits(&s->pb, 7, q);
1110
                break;
1111
            case 3:
1112
                put_bits(&s->pb, 3, q);
1113
                break;
1114
            case 4:
1115
                if (q != 128)
1116
                    put_bits(&s->pb, 7, q);
1117
                break;
1118
            case 14:
1119
                put_bits(&s->pb, 14, q);
1120
                break;
1121
            case 15:
1122
                put_bits(&s->pb, 16, q);
1123
                break;
1124
            default:
1125
                put_bits(&s->pb, b - 1, q);
1126
                break;
1127
            }
1128
        }
1129
    }
1130
}
1131

    
1132
/* compute the ac3 crc */
1133

    
1134
#define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1135

    
1136
static void ac3_crc_init(void)
1137
{
1138
    unsigned int c, n, k;
1139

    
1140
    for(n=0;n<256;n++) {
1141
        c = n << 8;
1142
        for (k = 0; k < 8; k++) {
1143
            if (c & (1 << 15)) 
1144
                c = ((c << 1) & 0xffff) ^ (CRC16_POLY & 0xffff);
1145
            else
1146
                c = c << 1;
1147
        }
1148
        crc_table[n] = c;
1149
    }
1150
}
1151

    
1152
static unsigned int ac3_crc(UINT8 *data, int n, unsigned int crc)
1153
{
1154
    int i;
1155
    for(i=0;i<n;i++) {
1156
        crc = (crc_table[data[i] ^ (crc >> 8)] ^ (crc << 8)) & 0xffff;
1157
    }
1158
    return crc;
1159
}
1160

    
1161
static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1162
{
1163
    unsigned int c;
1164

    
1165
    c = 0;
1166
    while (a) {
1167
        if (a & 1)
1168
            c ^= b;
1169
        a = a >> 1;
1170
        b = b << 1;
1171
        if (b & (1 << 16))
1172
            b ^= poly;
1173
    }
1174
    return c;
1175
}
1176

    
1177
static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1178
{
1179
    unsigned int r;
1180
    r = 1;
1181
    while (n) {
1182
        if (n & 1)
1183
            r = mul_poly(r, a, poly);
1184
        a = mul_poly(a, a, poly);
1185
        n >>= 1;
1186
    }
1187
    return r;
1188
}
1189

    
1190

    
1191
/* compute log2(max(abs(tab[]))) */
1192
static int log2_tab(INT16 *tab, int n)
1193
{
1194
    int i, v;
1195

    
1196
    v = 0;
1197
    for(i=0;i<n;i++) {
1198
        v |= abs(tab[i]);
1199
    }
1200
    return av_log2(v);
1201
}
1202

    
1203
static void lshift_tab(INT16 *tab, int n, int lshift)
1204
{
1205
    int i;
1206

    
1207
    if (lshift > 0) {
1208
        for(i=0;i<n;i++) {
1209
            tab[i] <<= lshift;
1210
        }
1211
    } else if (lshift < 0) {
1212
        lshift = -lshift;
1213
        for(i=0;i<n;i++) {
1214
            tab[i] >>= lshift;
1215
        }
1216
    }
1217
}
1218

    
1219
/* fill the end of the frame and compute the two crcs */
1220
static int output_frame_end(AC3EncodeContext *s)
1221
{
1222
    int frame_size, frame_size_58, n, crc1, crc2, crc_inv;
1223
    UINT8 *frame;
1224

    
1225
    frame_size = s->frame_size; /* frame size in words */
1226
    /* align to 8 bits */
1227
    flush_put_bits(&s->pb);
1228
    /* add zero bytes to reach the frame size */
1229
    frame = s->pb.buf;
1230
    n = 2 * s->frame_size - (pbBufPtr(&s->pb) - frame) - 2;
1231
    assert(n >= 0);
1232
    memset(pbBufPtr(&s->pb), 0, n);
1233
    
1234
    /* Now we must compute both crcs : this is not so easy for crc1
1235
       because it is at the beginning of the data... */
1236
    frame_size_58 = (frame_size >> 1) + (frame_size >> 3);
1237
    crc1 = ac3_crc(frame + 4, (2 * frame_size_58) - 4, 0);
1238
    /* XXX: could precompute crc_inv */
1239
    crc_inv = pow_poly((CRC16_POLY >> 1), (16 * frame_size_58) - 16, CRC16_POLY);
1240
    crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1241
    frame[2] = crc1 >> 8;
1242
    frame[3] = crc1;
1243
    
1244
    crc2 = ac3_crc(frame + 2 * frame_size_58, (frame_size - frame_size_58) * 2 - 2, 0);
1245
    frame[2*frame_size - 2] = crc2 >> 8;
1246
    frame[2*frame_size - 1] = crc2;
1247

    
1248
    //    printf("n=%d frame_size=%d\n", n, frame_size);
1249
    return frame_size * 2;
1250
}
1251

    
1252
int AC3_encode_frame(AVCodecContext *avctx,
1253
                     unsigned char *frame, int buf_size, void *data)
1254
{
1255
    AC3EncodeContext *s = avctx->priv_data;
1256
    short *samples = data;
1257
    int i, j, k, v, ch;
1258
    INT16 input_samples[N];
1259
    INT32 mdct_coef[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1260
    UINT8 exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1261
    UINT8 exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS];
1262
    UINT8 encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1263
    UINT8 bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1264
    INT8 exp_samples[NB_BLOCKS][AC3_MAX_CHANNELS];
1265
    int frame_bits;
1266

    
1267
    frame_bits = 0;
1268
    for(ch=0;ch<s->nb_channels;ch++) {
1269
        /* fixed mdct to the six sub blocks & exponent computation */
1270
        for(i=0;i<NB_BLOCKS;i++) {
1271
            INT16 *sptr;
1272
            int sinc;
1273

    
1274
            /* compute input samples */
1275
            memcpy(input_samples, s->last_samples[ch], N/2 * sizeof(INT16));
1276
            sinc = s->nb_channels;
1277
            sptr = samples + (sinc * (N/2) * i) + ch;
1278
            for(j=0;j<N/2;j++) {
1279
                v = *sptr;
1280
                input_samples[j + N/2] = v;
1281
                s->last_samples[ch][j] = v; 
1282
                sptr += sinc;
1283
            }
1284

    
1285
            /* apply the MDCT window */
1286
            for(j=0;j<N/2;j++) {
1287
                input_samples[j] = MUL16(input_samples[j], 
1288
                                         ac3_window[j]) >> 15;
1289
                input_samples[N-j-1] = MUL16(input_samples[N-j-1], 
1290
                                             ac3_window[j]) >> 15;
1291
            }
1292
        
1293
            /* Normalize the samples to use the maximum available
1294
               precision */
1295
            v = 14 - log2_tab(input_samples, N);
1296
            if (v < 0)
1297
                v = 0;
1298
            exp_samples[i][ch] = v - 8;
1299
            lshift_tab(input_samples, N, v);
1300

    
1301
            /* do the MDCT */
1302
            mdct512(mdct_coef[i][ch], input_samples);
1303
            
1304
            /* compute "exponents". We take into account the
1305
               normalization there */
1306
            for(j=0;j<N/2;j++) {
1307
                int e;
1308
                v = abs(mdct_coef[i][ch][j]);
1309
                if (v == 0)
1310
                    e = 24;
1311
                else {
1312
                    e = 23 - av_log2(v) + exp_samples[i][ch];
1313
                    if (e >= 24) {
1314
                        e = 24;
1315
                        mdct_coef[i][ch][j] = 0;
1316
                    }
1317
                }
1318
                exp[i][ch][j] = e;
1319
            }
1320
        }
1321
        
1322
        compute_exp_strategy(exp_strategy, exp, ch);
1323

    
1324
        /* compute the exponents as the decoder will see them. The
1325
           EXP_REUSE case must be handled carefully : we select the
1326
           min of the exponents */
1327
        i = 0;
1328
        while (i < NB_BLOCKS) {
1329
            j = i + 1;
1330
            while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE) {
1331
                exponent_min(exp[i][ch], exp[j][ch], s->nb_coefs[ch]);
1332
                j++;
1333
            }
1334
            frame_bits += encode_exp(encoded_exp[i][ch],
1335
                                     exp[i][ch], s->nb_coefs[ch], 
1336
                                     exp_strategy[i][ch]);
1337
            /* copy encoded exponents for reuse case */
1338
            for(k=i+1;k<j;k++) {
1339
                memcpy(encoded_exp[k][ch], encoded_exp[i][ch], 
1340
                       s->nb_coefs[ch] * sizeof(UINT8));
1341
            }
1342
            i = j;
1343
        }
1344
    }
1345

    
1346
    compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
1347
    /* everything is known... let's output the frame */
1348
    output_frame_header(s, frame);
1349
        
1350
    for(i=0;i<NB_BLOCKS;i++) {
1351
        output_audio_block(s, exp_strategy[i], encoded_exp[i], 
1352
                           bap[i], mdct_coef[i], exp_samples[i], i);
1353
    }
1354
    return output_frame_end(s);
1355
}
1356

    
1357
#if 0
1358
/*************************************************************************/
1359
/* TEST */
1360

1361
#define FN (N/4)
1362

1363
void fft_test(void)
1364
{
1365
    IComplex in[FN], in1[FN];
1366
    int k, n, i;
1367
    float sum_re, sum_im, a;
1368

1369
    /* FFT test */
1370

1371
    for(i=0;i<FN;i++) {
1372
        in[i].re = random() % 65535 - 32767;
1373
        in[i].im = random() % 65535 - 32767;
1374
        in1[i] = in[i];
1375
    }
1376
    fft(in, 7);
1377

1378
    /* do it by hand */
1379
    for(k=0;k<FN;k++) {
1380
        sum_re = 0;
1381
        sum_im = 0;
1382
        for(n=0;n<FN;n++) {
1383
            a = -2 * M_PI * (n * k) / FN;
1384
            sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1385
            sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1386
        }
1387
        printf("%3d: %6d,%6d %6.0f,%6.0f\n", 
1388
               k, in[k].re, in[k].im, sum_re / FN, sum_im / FN); 
1389
    }
1390
}
1391

1392
void mdct_test(void)
1393
{
1394
    INT16 input[N];
1395
    INT32 output[N/2];
1396
    float input1[N];
1397
    float output1[N/2];
1398
    float s, a, err, e, emax;
1399
    int i, k, n;
1400

1401
    for(i=0;i<N;i++) {
1402
        input[i] = (random() % 65535 - 32767) * 9 / 10;
1403
        input1[i] = input[i];
1404
    }
1405

1406
    mdct512(output, input);
1407
    
1408
    /* do it by hand */
1409
    for(k=0;k<N/2;k++) {
1410
        s = 0;
1411
        for(n=0;n<N;n++) {
1412
            a = (2*M_PI*(2*n+1+N/2)*(2*k+1) / (4 * N));
1413
            s += input1[n] * cos(a);
1414
        }
1415
        output1[k] = -2 * s / N;
1416
    }
1417
    
1418
    err = 0;
1419
    emax = 0;
1420
    for(i=0;i<N/2;i++) {
1421
        printf("%3d: %7d %7.0f\n", i, output[i], output1[i]);
1422
        e = output[i] - output1[i];
1423
        if (e > emax)
1424
            emax = e;
1425
        err += e * e;
1426
    }
1427
    printf("err2=%f emax=%f\n", err / (N/2), emax);
1428
}
1429

1430
void test_ac3(void)
1431
{
1432
    AC3EncodeContext ctx;
1433
    unsigned char frame[AC3_MAX_CODED_FRAME_SIZE];
1434
    short samples[AC3_FRAME_SIZE];
1435
    int ret, i;
1436
    
1437
    AC3_encode_init(&ctx, 44100, 64000, 1);
1438

1439
    fft_test();
1440
    mdct_test();
1441

1442
    for(i=0;i<AC3_FRAME_SIZE;i++)
1443
        samples[i] = (int)(sin(2*M_PI*i*1000.0/44100) * 10000);
1444
    ret = AC3_encode_frame(&ctx, frame, samples);
1445
    printf("ret=%d\n", ret);
1446
}
1447
#endif
1448

    
1449
AVCodec ac3_encoder = {
1450
    "ac3",
1451
    CODEC_TYPE_AUDIO,
1452
    CODEC_ID_AC3,
1453
    sizeof(AC3EncodeContext),
1454
    AC3_encode_init,
1455
    AC3_encode_frame,
1456
    NULL,
1457
};