]> git.sesse.net Git - ffmpeg/blob - libavcodec/ac3enc.c
cosmetics
[ffmpeg] / libavcodec / ac3enc.c
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19 //#define DEBUG
20 //#define DEBUG_BITALLOC
21 #include "avcodec.h"
22
23 #include "ac3.h"
24
25 typedef struct AC3EncodeContext {
26     PutBitContext pb;
27     int nb_channels;
28     int nb_all_channels;
29     int lfe_channel;
30     int bit_rate;
31     unsigned int sample_rate;
32     unsigned int bsid;
33     unsigned int frame_size_min; /* minimum frame size in case rounding is necessary */
34     unsigned int frame_size; /* current frame size in words */
35     int halfratecod;
36     unsigned int frmsizecod;
37     unsigned int fscod; /* frequency */
38     unsigned int acmod;
39     int lfe;
40     unsigned int bsmod;
41     short last_samples[AC3_MAX_CHANNELS][256];
42     unsigned int chbwcod[AC3_MAX_CHANNELS];
43     int nb_coefs[AC3_MAX_CHANNELS];
44     
45     /* bitrate allocation control */
46     int sgaincod, sdecaycod, fdecaycod, dbkneecod, floorcod; 
47     AC3BitAllocParameters bit_alloc;
48     int csnroffst;
49     int fgaincod[AC3_MAX_CHANNELS];
50     int fsnroffst[AC3_MAX_CHANNELS];
51     /* mantissa encoding */
52     int mant1_cnt, mant2_cnt, mant4_cnt;
53 } AC3EncodeContext;
54
55 #include "ac3tab.h"
56
57 #define MDCT_NBITS 9
58 #define N         (1 << MDCT_NBITS)
59
60 /* new exponents are sent if their Norm 1 exceed this number */
61 #define EXP_DIFF_THRESHOLD 1000
62
63 static void fft_init(int ln);
64 static void ac3_crc_init(void);
65
66 static inline int16_t fix15(float a)
67 {
68     int v;
69     v = (int)(a * (float)(1 << 15));
70     if (v < -32767)
71         v = -32767;
72     else if (v > 32767) 
73         v = 32767;
74     return v;
75 }
76
77 static inline int calc_lowcomp1(int a, int b0, int b1)
78 {
79     if ((b0 + 256) == b1) {
80         a = 384 ;
81     } else if (b0 > b1) { 
82         a = a - 64;
83         if (a < 0) a=0;
84     }
85     return a;
86 }
87
88 static inline int calc_lowcomp(int a, int b0, int b1, int bin)
89 {
90     if (bin < 7) {
91         if ((b0 + 256) == b1) {
92             a = 384 ;
93         } else if (b0 > b1) { 
94             a = a - 64;
95             if (a < 0) a=0;
96         }
97     } else if (bin < 20) {
98         if ((b0 + 256) == b1) {
99             a = 320 ;
100         } else if (b0 > b1) {
101             a= a - 64;
102             if (a < 0) a=0;
103         }
104     } else {
105         a = a - 128;
106         if (a < 0) a=0;
107     }
108     return a;
109 }
110
111 /* AC3 bit allocation. The algorithm is the one described in the AC3
112    spec. */
113 void ac3_parametric_bit_allocation(AC3BitAllocParameters *s, uint8_t *bap,
114                                    int8_t *exp, int start, int end,
115                                    int snroffset, int fgain, int is_lfe,
116                                    int deltbae,int deltnseg, 
117                                    uint8_t *deltoffst, uint8_t *deltlen, uint8_t *deltba)
118 {
119     int bin,i,j,k,end1,v,v1,bndstrt,bndend,lowcomp,begin;
120     int fastleak,slowleak,address,tmp;
121     int16_t psd[256]; /* scaled exponents */
122     int16_t bndpsd[50]; /* interpolated exponents */
123     int16_t excite[50]; /* excitation */
124     int16_t mask[50];   /* masking value */
125
126     /* exponent mapping to PSD */
127     for(bin=start;bin<end;bin++) {
128         psd[bin]=(3072 - (exp[bin] << 7));
129     }
130
131     /* PSD integration */
132     j=start;
133     k=masktab[start];
134     do {
135         v=psd[j];
136         j++;
137         end1=bndtab[k+1];
138         if (end1 > end) end1=end;
139         for(i=j;i<end1;i++) {
140             int c,adr;
141             /* logadd */
142             v1=psd[j];
143             c=v-v1;
144             if (c >= 0) {
145                 adr=c >> 1;
146                 if (adr > 255) adr=255;
147                 v=v + latab[adr];
148             } else {
149                 adr=(-c) >> 1;
150                 if (adr > 255) adr=255;
151                 v=v1 + latab[adr];
152             }
153             j++;
154         }
155         bndpsd[k]=v;
156         k++;
157     } while (end > bndtab[k]);
158
159     /* excitation function */
160     bndstrt = masktab[start];
161     bndend = masktab[end-1] + 1;
162     
163     if (bndstrt == 0) {
164         lowcomp = 0;
165         lowcomp = calc_lowcomp1(lowcomp, bndpsd[0], bndpsd[1]) ;
166         excite[0] = bndpsd[0] - fgain - lowcomp ;
167         lowcomp = calc_lowcomp1(lowcomp, bndpsd[1], bndpsd[2]) ;
168         excite[1] = bndpsd[1] - fgain - lowcomp ;
169         begin = 7 ;
170         for (bin = 2; bin < 7; bin++) {
171             if (!(is_lfe && bin == 6))
172                 lowcomp = calc_lowcomp1(lowcomp, bndpsd[bin], bndpsd[bin+1]) ;
173             fastleak = bndpsd[bin] - fgain ;
174             slowleak = bndpsd[bin] - s->sgain ;
175             excite[bin] = fastleak - lowcomp ;
176             if (!(is_lfe && bin == 6)) {
177                 if (bndpsd[bin] <= bndpsd[bin+1]) {
178                     begin = bin + 1 ;
179                     break ;
180                 }
181             }
182         }
183     
184         end1=bndend;
185         if (end1 > 22) end1=22;
186     
187         for (bin = begin; bin < end1; bin++) {
188             if (!(is_lfe && bin == 6))
189                 lowcomp = calc_lowcomp(lowcomp, bndpsd[bin], bndpsd[bin+1], bin) ;
190         
191             fastleak -= s->fdecay ;
192             v = bndpsd[bin] - fgain;
193             if (fastleak < v) fastleak = v;
194         
195             slowleak -= s->sdecay ;
196             v = bndpsd[bin] - s->sgain;
197             if (slowleak < v) slowleak = v;
198         
199             v=fastleak - lowcomp;
200             if (slowleak > v) v=slowleak;
201         
202             excite[bin] = v;
203         }
204         begin = 22;
205     } else {
206         /* coupling channel */
207         begin = bndstrt;
208         
209         fastleak = (s->cplfleak << 8) + 768;
210         slowleak = (s->cplsleak << 8) + 768;
211     }
212
213     for (bin = begin; bin < bndend; bin++) {
214         fastleak -= s->fdecay ;
215         v = bndpsd[bin] - fgain;
216         if (fastleak < v) fastleak = v;
217         slowleak -= s->sdecay ;
218         v = bndpsd[bin] - s->sgain;
219         if (slowleak < v) slowleak = v;
220
221         v=fastleak;
222         if (slowleak > v) v = slowleak;
223         excite[bin] = v;
224     }
225
226     /* compute masking curve */
227
228     for (bin = bndstrt; bin < bndend; bin++) {
229         v1 = excite[bin];
230         tmp = s->dbknee - bndpsd[bin];
231         if (tmp > 0) {
232             v1 += tmp >> 2;
233         }
234         v=hth[bin >> s->halfratecod][s->fscod];
235         if (v1 > v) v=v1;
236         mask[bin] = v;
237     }
238
239     /* delta bit allocation */
240
241     if (deltbae == 0 || deltbae == 1) {
242         int band, seg, delta;
243         band = 0 ;
244         for (seg = 0; seg < deltnseg; seg++) {
245             band += deltoffst[seg] ;
246             if (deltba[seg] >= 4) {
247                 delta = (deltba[seg] - 3) << 7;
248             } else {
249                 delta = (deltba[seg] - 4) << 7;
250             }
251             for (k = 0; k < deltlen[seg]; k++) {
252                 mask[band] += delta ;
253                 band++ ;
254             }
255         }
256     }
257
258     /* compute bit allocation */
259     
260     i = start ;
261     j = masktab[start] ;
262     do {
263         v=mask[j];
264         v -= snroffset ;
265         v -= s->floor ;
266         if (v < 0) v = 0;
267         v &= 0x1fe0 ;
268         v += s->floor ;
269
270         end1=bndtab[j] + bndsz[j];
271         if (end1 > end) end1=end;
272
273         for (k = i; k < end1; k++) {
274             address = (psd[i] - v) >> 5 ;
275             if (address < 0) address=0;
276             else if (address > 63) address=63;
277             bap[i] = baptab[address];
278             i++;
279         }
280     } while (end > bndtab[j++]) ;
281 }
282
283 typedef struct IComplex {
284     short re,im;
285 } IComplex;
286
287 static void fft_init(int ln)
288 {
289     int i, j, m, n;
290     float alpha;
291
292     n = 1 << ln;
293
294     for(i=0;i<(n/2);i++) {
295         alpha = 2 * M_PI * (float)i / (float)n;
296         costab[i] = fix15(cos(alpha));
297         sintab[i] = fix15(sin(alpha));
298     }
299
300     for(i=0;i<n;i++) {
301         m=0;
302         for(j=0;j<ln;j++) {
303             m |= ((i >> j) & 1) << (ln-j-1);
304         }
305         fft_rev[i]=m;
306     }
307 }
308
309 /* butter fly op */
310 #define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1) \
311 {\
312   int ax, ay, bx, by;\
313   bx=pre1;\
314   by=pim1;\
315   ax=qre1;\
316   ay=qim1;\
317   pre = (bx + ax) >> 1;\
318   pim = (by + ay) >> 1;\
319   qre = (bx - ax) >> 1;\
320   qim = (by - ay) >> 1;\
321 }
322
323 #define MUL16(a,b) ((a) * (b))
324
325 #define CMUL(pre, pim, are, aim, bre, bim) \
326 {\
327    pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;\
328    pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;\
329 }
330
331
332 /* do a 2^n point complex fft on 2^ln points. */
333 static void fft(IComplex *z, int ln)
334 {
335     int j, l, np, np2;
336     int nblocks, nloops;
337     register IComplex *p,*q;
338     int tmp_re, tmp_im;
339
340     np = 1 << ln;
341
342     /* reverse */
343     for(j=0;j<np;j++) {
344         int k;
345         IComplex tmp;
346         k = fft_rev[j];
347         if (k < j) {
348             tmp = z[k];
349             z[k] = z[j];
350             z[j] = tmp;
351         }
352     }
353
354     /* pass 0 */
355
356     p=&z[0];
357     j=(np >> 1);
358     do {
359         BF(p[0].re, p[0].im, p[1].re, p[1].im, 
360            p[0].re, p[0].im, p[1].re, p[1].im);
361         p+=2;
362     } while (--j != 0);
363
364     /* pass 1 */
365
366     p=&z[0];
367     j=np >> 2;
368     do {
369         BF(p[0].re, p[0].im, p[2].re, p[2].im, 
370            p[0].re, p[0].im, p[2].re, p[2].im);
371         BF(p[1].re, p[1].im, p[3].re, p[3].im, 
372            p[1].re, p[1].im, p[3].im, -p[3].re);
373         p+=4;
374     } while (--j != 0);
375
376     /* pass 2 .. ln-1 */
377
378     nblocks = np >> 3;
379     nloops = 1 << 2;
380     np2 = np >> 1;
381     do {
382         p = z;
383         q = z + nloops;
384         for (j = 0; j < nblocks; ++j) {
385
386             BF(p->re, p->im, q->re, q->im,
387                p->re, p->im, q->re, q->im);
388             
389             p++;
390             q++;
391             for(l = nblocks; l < np2; l += nblocks) {
392                 CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
393                 BF(p->re, p->im, q->re, q->im,
394                    p->re, p->im, tmp_re, tmp_im);
395                 p++;
396                 q++;
397             }
398             p += nloops;
399             q += nloops;
400         }
401         nblocks = nblocks >> 1;
402         nloops = nloops << 1;
403     } while (nblocks != 0);
404 }
405
406 /* do a 512 point mdct */
407 static void mdct512(int32_t *out, int16_t *in)
408 {
409     int i, re, im, re1, im1;
410     int16_t rot[N]; 
411     IComplex x[N/4];
412
413     /* shift to simplify computations */
414     for(i=0;i<N/4;i++)
415         rot[i] = -in[i + 3*N/4];
416     for(i=N/4;i<N;i++)
417         rot[i] = in[i - N/4];
418         
419     /* pre rotation */
420     for(i=0;i<N/4;i++) {
421         re = ((int)rot[2*i] - (int)rot[N-1-2*i]) >> 1;
422         im = -((int)rot[N/2+2*i] - (int)rot[N/2-1-2*i]) >> 1;
423         CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
424     }
425
426     fft(x, MDCT_NBITS - 2);
427   
428     /* post rotation */
429     for(i=0;i<N/4;i++) {
430         re = x[i].re;
431         im = x[i].im;
432         CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
433         out[2*i] = im1;
434         out[N/2-1-2*i] = re1;
435     }
436 }
437
438 /* XXX: use another norm ? */
439 static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
440 {
441     int sum, i;
442     sum = 0;
443     for(i=0;i<n;i++) {
444         sum += abs(exp1[i] - exp2[i]);
445     }
446     return sum;
447 }
448
449 static void compute_exp_strategy(uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
450                                  uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
451                                  int ch, int is_lfe)
452 {
453     int i, j;
454     int exp_diff;
455     
456     /* estimate if the exponent variation & decide if they should be
457        reused in the next frame */
458     exp_strategy[0][ch] = EXP_NEW;
459     for(i=1;i<NB_BLOCKS;i++) {
460         exp_diff = calc_exp_diff(exp[i][ch], exp[i-1][ch], N/2);
461 #ifdef DEBUG            
462         printf("exp_diff=%d\n", exp_diff);
463 #endif
464         if (exp_diff > EXP_DIFF_THRESHOLD)
465             exp_strategy[i][ch] = EXP_NEW;
466         else
467             exp_strategy[i][ch] = EXP_REUSE;
468     }
469     if (is_lfe)
470         return;
471
472     /* now select the encoding strategy type : if exponents are often
473        recoded, we use a coarse encoding */
474     i = 0;
475     while (i < NB_BLOCKS) {
476         j = i + 1;
477         while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE)
478             j++;
479         switch(j - i) {
480         case 1:
481             exp_strategy[i][ch] = EXP_D45;
482             break;
483         case 2:
484         case 3:
485             exp_strategy[i][ch] = EXP_D25;
486             break;
487         default:
488             exp_strategy[i][ch] = EXP_D15;
489             break;
490         }
491         i = j;
492     }
493 }
494
495 /* set exp[i] to min(exp[i], exp1[i]) */
496 static void exponent_min(uint8_t exp[N/2], uint8_t exp1[N/2], int n)
497 {
498     int i;
499
500     for(i=0;i<n;i++) {
501         if (exp1[i] < exp[i])
502             exp[i] = exp1[i];
503     }
504 }
505                                  
506 /* update the exponents so that they are the ones the decoder will
507    decode. Return the number of bits used to code the exponents */
508 static int encode_exp(uint8_t encoded_exp[N/2], 
509                       uint8_t exp[N/2], 
510                       int nb_exps,
511                       int exp_strategy)
512 {
513     int group_size, nb_groups, i, j, k, recurse, exp_min, delta;
514     uint8_t exp1[N/2];
515
516     switch(exp_strategy) {
517     case EXP_D15:
518         group_size = 1;
519         break;
520     case EXP_D25:
521         group_size = 2;
522         break;
523     default:
524     case EXP_D45:
525         group_size = 4;
526         break;
527     }
528     nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
529
530     /* for each group, compute the minimum exponent */
531     exp1[0] = exp[0]; /* DC exponent is handled separately */
532     k = 1;
533     for(i=1;i<=nb_groups;i++) {
534         exp_min = exp[k];
535         assert(exp_min >= 0 && exp_min <= 24);
536         for(j=1;j<group_size;j++) {
537             if (exp[k+j] < exp_min)
538                 exp_min = exp[k+j];
539         }
540         exp1[i] = exp_min;
541         k += group_size;
542     }
543
544     /* constraint for DC exponent */
545     if (exp1[0] > 15)
546         exp1[0] = 15;
547
548     /* Iterate until the delta constraints between each groups are
549        satisfyed. I'm sure it is possible to find a better algorithm,
550        but I am lazy */
551     do {
552         recurse = 0;
553         for(i=1;i<=nb_groups;i++) {
554             delta = exp1[i] - exp1[i-1];
555             if (delta > 2) {
556                 /* if delta too big, we encode a smaller exponent */
557                 exp1[i] = exp1[i-1] + 2;
558             } else if (delta < -2) {
559                 /* if delta is too small, we must decrease the previous
560                exponent, which means we must recurse */
561                 recurse = 1;
562                 exp1[i-1] = exp1[i] + 2;
563             }
564         }
565     } while (recurse);
566     
567     /* now we have the exponent values the decoder will see */
568     encoded_exp[0] = exp1[0];
569     k = 1;
570     for(i=1;i<=nb_groups;i++) {
571         for(j=0;j<group_size;j++) {
572             encoded_exp[k+j] = exp1[i];
573         }
574         k += group_size;
575     }
576     
577 #if defined(DEBUG)
578     printf("exponents: strategy=%d\n", exp_strategy);
579     for(i=0;i<=nb_groups * group_size;i++) {
580         printf("%d ", encoded_exp[i]);
581     }
582     printf("\n");
583 #endif
584
585     return 4 + (nb_groups / 3) * 7;
586 }
587
588 /* return the size in bits taken by the mantissa */
589 static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
590 {
591     int bits, mant, i;
592
593     bits = 0;
594     for(i=0;i<nb_coefs;i++) {
595         mant = m[i];
596         switch(mant) {
597         case 0:
598             /* nothing */
599             break;
600         case 1:
601             /* 3 mantissa in 5 bits */
602             if (s->mant1_cnt == 0) 
603                 bits += 5;
604             if (++s->mant1_cnt == 3)
605                 s->mant1_cnt = 0;
606             break;
607         case 2:
608             /* 3 mantissa in 7 bits */
609             if (s->mant2_cnt == 0) 
610                 bits += 7;
611             if (++s->mant2_cnt == 3)
612                 s->mant2_cnt = 0;
613             break;
614         case 3:
615             bits += 3;
616             break;
617         case 4:
618             /* 2 mantissa in 7 bits */
619             if (s->mant4_cnt == 0)
620                 bits += 7;
621             if (++s->mant4_cnt == 2) 
622                 s->mant4_cnt = 0;
623             break;
624         case 14:
625             bits += 14;
626             break;
627         case 15:
628             bits += 16;
629             break;
630         default:
631             bits += mant - 1;
632             break;
633         }
634     }
635     return bits;
636 }
637
638
639 static int bit_alloc(AC3EncodeContext *s,
640                      uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
641                      uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
642                      uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
643                      int frame_bits, int csnroffst, int fsnroffst)
644 {
645     int i, ch;
646
647     /* compute size */
648     for(i=0;i<NB_BLOCKS;i++) {
649         s->mant1_cnt = 0;
650         s->mant2_cnt = 0;
651         s->mant4_cnt = 0;
652         for(ch=0;ch<s->nb_all_channels;ch++) {
653             ac3_parametric_bit_allocation(&s->bit_alloc, 
654                                           bap[i][ch], (int8_t *)encoded_exp[i][ch], 
655                                           0, s->nb_coefs[ch], 
656                                           (((csnroffst-15) << 4) + 
657                                            fsnroffst) << 2, 
658                                           fgaintab[s->fgaincod[ch]],
659                                           ch == s->lfe_channel,
660                                           2, 0, NULL, NULL, NULL);
661             frame_bits += compute_mantissa_size(s, bap[i][ch], 
662                                                  s->nb_coefs[ch]);
663         }
664     }
665 #if 0
666     printf("csnr=%d fsnr=%d frame_bits=%d diff=%d\n", 
667            csnroffst, fsnroffst, frame_bits, 
668            16 * s->frame_size - ((frame_bits + 7) & ~7));
669 #endif
670     return 16 * s->frame_size - frame_bits;
671 }
672
673 #define SNR_INC1 4
674
675 static int compute_bit_allocation(AC3EncodeContext *s,
676                                   uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
677                                   uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
678                                   uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
679                                   int frame_bits)
680 {
681     int i, ch;
682     int csnroffst, fsnroffst;
683     uint8_t bap1[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
684     static int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
685
686     /* init default parameters */
687     s->sdecaycod = 2;
688     s->fdecaycod = 1;
689     s->sgaincod = 1;
690     s->dbkneecod = 2;
691     s->floorcod = 4;
692     for(ch=0;ch<s->nb_all_channels;ch++) 
693         s->fgaincod[ch] = 4;
694     
695     /* compute real values */
696     s->bit_alloc.fscod = s->fscod;
697     s->bit_alloc.halfratecod = s->halfratecod;
698     s->bit_alloc.sdecay = sdecaytab[s->sdecaycod] >> s->halfratecod;
699     s->bit_alloc.fdecay = fdecaytab[s->fdecaycod] >> s->halfratecod;
700     s->bit_alloc.sgain = sgaintab[s->sgaincod];
701     s->bit_alloc.dbknee = dbkneetab[s->dbkneecod];
702     s->bit_alloc.floor = floortab[s->floorcod];
703     
704     /* header size */
705     frame_bits += 65;
706     // if (s->acmod == 2)
707     //    frame_bits += 2;
708     frame_bits += frame_bits_inc[s->acmod];
709
710     /* audio blocks */
711     for(i=0;i<NB_BLOCKS;i++) {
712         frame_bits += s->nb_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
713         if (s->acmod == 2)
714             frame_bits++; /* rematstr */
715         frame_bits += 2 * s->nb_channels; /* chexpstr[2] * c */
716         if (s->lfe)
717             frame_bits++; /* lfeexpstr */
718         for(ch=0;ch<s->nb_channels;ch++) {
719             if (exp_strategy[i][ch] != EXP_REUSE)
720                 frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
721         }
722         frame_bits++; /* baie */
723         frame_bits++; /* snr */
724         frame_bits += 2; /* delta / skip */
725     }
726     frame_bits++; /* cplinu for block 0 */
727     /* bit alloc info */
728     /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
729     /* csnroffset[6] */
730     /* (fsnoffset[4] + fgaincod[4]) * c */
731     frame_bits += 2*4 + 3 + 6 + s->nb_all_channels * (4 + 3);
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         fprintf(stderr, "Yack, Error !!!\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] = 0;
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     /* for now we do not handle fractional sizes */
865     s->frame_size = s->frame_size_min;
866     
867     /* bit allocation init */
868     for(ch=0;ch<s->nb_channels;ch++) {
869         /* bandwidth for each channel */
870         /* XXX: should compute the bandwidth according to the frame
871            size, so that we avoid anoying high freq artefacts */
872         s->chbwcod[ch] = 50; /* sample bandwidth as mpeg audio layer 2 table 0 */
873         s->nb_coefs[ch] = ((s->chbwcod[ch] + 12) * 3) + 37;
874     }
875     if (s->lfe) {
876         s->nb_coefs[s->lfe_channel] = 7; /* fixed */
877     }
878     /* initial snr offset */
879     s->csnroffst = 40;
880
881     ac3_common_init();
882
883     /* mdct init */
884     fft_init(MDCT_NBITS - 2);
885     for(i=0;i<N/4;i++) {
886         alpha = 2 * M_PI * (i + 1.0 / 8.0) / (float)N;
887         xcos1[i] = fix15(-cos(alpha));
888         xsin1[i] = fix15(-sin(alpha));
889     }
890
891     ac3_crc_init();
892     
893     avctx->coded_frame= avcodec_alloc_frame();
894     avctx->coded_frame->key_frame= 1;
895
896     return 0;
897 }
898
899 /* output the AC3 frame header */
900 static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
901 {
902     init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE, NULL, NULL);
903
904     put_bits(&s->pb, 16, 0x0b77); /* frame header */
905     put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
906     put_bits(&s->pb, 2, s->fscod);
907     put_bits(&s->pb, 6, s->frmsizecod + (s->frame_size - s->frame_size_min));
908     put_bits(&s->pb, 5, s->bsid);
909     put_bits(&s->pb, 3, s->bsmod);
910     put_bits(&s->pb, 3, s->acmod);
911     if ((s->acmod & 0x01) && s->acmod != 0x01)
912         put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
913     if (s->acmod & 0x04)
914         put_bits(&s->pb, 2, 1); /* XXX -6 dB */
915     if (s->acmod == 0x02)
916         put_bits(&s->pb, 2, 0); /* surround not indicated */
917     put_bits(&s->pb, 1, s->lfe); /* LFE */
918     put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
919     put_bits(&s->pb, 1, 0); /* no compression control word */
920     put_bits(&s->pb, 1, 0); /* no lang code */
921     put_bits(&s->pb, 1, 0); /* no audio production info */
922     put_bits(&s->pb, 1, 0); /* no copyright */
923     put_bits(&s->pb, 1, 1); /* original bitstream */
924     put_bits(&s->pb, 1, 0); /* no time code 1 */
925     put_bits(&s->pb, 1, 0); /* no time code 2 */
926     put_bits(&s->pb, 1, 0); /* no addtional bit stream info */
927 }
928
929 /* symetric quantization on 'levels' levels */
930 static inline int sym_quant(int c, int e, int levels)
931 {
932     int v;
933
934     if (c >= 0) {
935         v = (levels * (c << e)) >> 24;
936         v = (v + 1) >> 1;
937         v = (levels >> 1) + v;
938     } else {
939         v = (levels * ((-c) << e)) >> 24;
940         v = (v + 1) >> 1;
941         v = (levels >> 1) - v;
942     }
943     assert (v >= 0 && v < levels);
944     return v;
945 }
946
947 /* asymetric quantization on 2^qbits levels */
948 static inline int asym_quant(int c, int e, int qbits)
949 {
950     int lshift, m, v;
951
952     lshift = e + qbits - 24;
953     if (lshift >= 0)
954         v = c << lshift;
955     else
956         v = c >> (-lshift);
957     /* rounding */
958     v = (v + 1) >> 1;
959     m = (1 << (qbits-1));
960     if (v >= m)
961         v = m - 1;
962     assert(v >= -m);
963     return v & ((1 << qbits)-1);
964 }
965
966 /* Output one audio block. There are NB_BLOCKS audio blocks in one AC3
967    frame */
968 static void output_audio_block(AC3EncodeContext *s,
969                                uint8_t exp_strategy[AC3_MAX_CHANNELS],
970                                uint8_t encoded_exp[AC3_MAX_CHANNELS][N/2],
971                                uint8_t bap[AC3_MAX_CHANNELS][N/2],
972                                int32_t mdct_coefs[AC3_MAX_CHANNELS][N/2],
973                                int8_t global_exp[AC3_MAX_CHANNELS],
974                                int block_num)
975 {
976     int ch, nb_groups, group_size, i, baie;
977     uint8_t *p;
978     uint16_t qmant[AC3_MAX_CHANNELS][N/2];
979     int exp0, exp1;
980     int mant1_cnt, mant2_cnt, mant4_cnt;
981     uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
982     int delta0, delta1, delta2;
983
984     for(ch=0;ch<s->nb_channels;ch++) 
985         put_bits(&s->pb, 1, 0); /* 512 point MDCT */
986     for(ch=0;ch<s->nb_channels;ch++) 
987         put_bits(&s->pb, 1, 1); /* no dither */
988     put_bits(&s->pb, 1, 0); /* no dynamic range */
989     if (block_num == 0) {
990         /* for block 0, even if no coupling, we must say it. This is a
991            waste of bit :-) */
992         put_bits(&s->pb, 1, 1); /* coupling strategy present */
993         put_bits(&s->pb, 1, 0); /* no coupling strategy */
994     } else {
995         put_bits(&s->pb, 1, 0); /* no new coupling strategy */
996     }
997
998     if (s->acmod == 2) {
999         put_bits(&s->pb, 1, 0); /* no matrixing (but should be used in the future) */
1000     }
1001
1002 #if defined(DEBUG) 
1003     {
1004         static int count = 0;
1005         printf("Block #%d (%d)\n", block_num, count++);
1006     }
1007 #endif
1008     /* exponent strategy */
1009     for(ch=0;ch<s->nb_channels;ch++) {
1010         put_bits(&s->pb, 2, exp_strategy[ch]);
1011     }
1012     
1013     if (s->lfe) {
1014         put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
1015     }
1016
1017     for(ch=0;ch<s->nb_channels;ch++) {
1018         if (exp_strategy[ch] != EXP_REUSE)
1019             put_bits(&s->pb, 6, s->chbwcod[ch]);
1020     }
1021     
1022     /* exponents */
1023     for (ch = 0; ch < s->nb_all_channels; ch++) {
1024         switch(exp_strategy[ch]) {
1025         case EXP_REUSE:
1026             continue;
1027         case EXP_D15:
1028             group_size = 1;
1029             break;
1030         case EXP_D25:
1031             group_size = 2;
1032             break;
1033         default:
1034         case EXP_D45:
1035             group_size = 4;
1036             break;
1037         }
1038         nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
1039         p = encoded_exp[ch];
1040
1041         /* first exponent */
1042         exp1 = *p++;
1043         put_bits(&s->pb, 4, exp1);
1044
1045         /* next ones are delta encoded */
1046         for(i=0;i<nb_groups;i++) {
1047             /* merge three delta in one code */
1048             exp0 = exp1;
1049             exp1 = p[0];
1050             p += group_size;
1051             delta0 = exp1 - exp0 + 2;
1052
1053             exp0 = exp1;
1054             exp1 = p[0];
1055             p += group_size;
1056             delta1 = exp1 - exp0 + 2;
1057
1058             exp0 = exp1;
1059             exp1 = p[0];
1060             p += group_size;
1061             delta2 = exp1 - exp0 + 2;
1062
1063             put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
1064         }
1065
1066         if (ch != s->lfe_channel)
1067             put_bits(&s->pb, 2, 0); /* no gain range info */
1068     }
1069
1070     /* bit allocation info */
1071     baie = (block_num == 0);
1072     put_bits(&s->pb, 1, baie);
1073     if (baie) {
1074         put_bits(&s->pb, 2, s->sdecaycod);
1075         put_bits(&s->pb, 2, s->fdecaycod);
1076         put_bits(&s->pb, 2, s->sgaincod);
1077         put_bits(&s->pb, 2, s->dbkneecod);
1078         put_bits(&s->pb, 3, s->floorcod);
1079     }
1080
1081     /* snr offset */
1082     put_bits(&s->pb, 1, baie); /* always present with bai */
1083     if (baie) {
1084         put_bits(&s->pb, 6, s->csnroffst);
1085         for(ch=0;ch<s->nb_all_channels;ch++) {
1086             put_bits(&s->pb, 4, s->fsnroffst[ch]);
1087             put_bits(&s->pb, 3, s->fgaincod[ch]);
1088         }
1089     }
1090     
1091     put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1092     put_bits(&s->pb, 1, 0); /* no data to skip */
1093
1094     /* mantissa encoding : we use two passes to handle the grouping. A
1095        one pass method may be faster, but it would necessitate to
1096        modify the output stream. */
1097
1098     /* first pass: quantize */
1099     mant1_cnt = mant2_cnt = mant4_cnt = 0;
1100     qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
1101
1102     for (ch = 0; ch < s->nb_all_channels; ch++) {
1103         int b, c, e, v;
1104
1105         for(i=0;i<s->nb_coefs[ch];i++) {
1106             c = mdct_coefs[ch][i];
1107             e = encoded_exp[ch][i] - global_exp[ch];
1108             b = bap[ch][i];
1109             switch(b) {
1110             case 0:
1111                 v = 0;
1112                 break;
1113             case 1:
1114                 v = sym_quant(c, e, 3);
1115                 switch(mant1_cnt) {
1116                 case 0:
1117                     qmant1_ptr = &qmant[ch][i];
1118                     v = 9 * v;
1119                     mant1_cnt = 1;
1120                     break;
1121                 case 1:
1122                     *qmant1_ptr += 3 * v;
1123                     mant1_cnt = 2;
1124                     v = 128;
1125                     break;
1126                 default:
1127                     *qmant1_ptr += v;
1128                     mant1_cnt = 0;
1129                     v = 128;
1130                     break;
1131                 }
1132                 break;
1133             case 2:
1134                 v = sym_quant(c, e, 5);
1135                 switch(mant2_cnt) {
1136                 case 0:
1137                     qmant2_ptr = &qmant[ch][i];
1138                     v = 25 * v;
1139                     mant2_cnt = 1;
1140                     break;
1141                 case 1:
1142                     *qmant2_ptr += 5 * v;
1143                     mant2_cnt = 2;
1144                     v = 128;
1145                     break;
1146                 default:
1147                     *qmant2_ptr += v;
1148                     mant2_cnt = 0;
1149                     v = 128;
1150                     break;
1151                 }
1152                 break;
1153             case 3:
1154                 v = sym_quant(c, e, 7);
1155                 break;
1156             case 4:
1157                 v = sym_quant(c, e, 11);
1158                 switch(mant4_cnt) {
1159                 case 0:
1160                     qmant4_ptr = &qmant[ch][i];
1161                     v = 11 * v;
1162                     mant4_cnt = 1;
1163                     break;
1164                 default:
1165                     *qmant4_ptr += v;
1166                     mant4_cnt = 0;
1167                     v = 128;
1168                     break;
1169                 }
1170                 break;
1171             case 5:
1172                 v = sym_quant(c, e, 15);
1173                 break;
1174             case 14:
1175                 v = asym_quant(c, e, 14);
1176                 break;
1177             case 15:
1178                 v = asym_quant(c, e, 16);
1179                 break;
1180             default:
1181                 v = asym_quant(c, e, b - 1);
1182                 break;
1183             }
1184             qmant[ch][i] = v;
1185         }
1186     }
1187
1188     /* second pass : output the values */
1189     for (ch = 0; ch < s->nb_all_channels; ch++) {
1190         int b, q;
1191         
1192         for(i=0;i<s->nb_coefs[ch];i++) {
1193             q = qmant[ch][i];
1194             b = bap[ch][i];
1195             switch(b) {
1196             case 0:
1197                 break;
1198             case 1:
1199                 if (q != 128) 
1200                     put_bits(&s->pb, 5, q);
1201                 break;
1202             case 2:
1203                 if (q != 128) 
1204                     put_bits(&s->pb, 7, q);
1205                 break;
1206             case 3:
1207                 put_bits(&s->pb, 3, q);
1208                 break;
1209             case 4:
1210                 if (q != 128)
1211                     put_bits(&s->pb, 7, q);
1212                 break;
1213             case 14:
1214                 put_bits(&s->pb, 14, q);
1215                 break;
1216             case 15:
1217                 put_bits(&s->pb, 16, q);
1218                 break;
1219             default:
1220                 put_bits(&s->pb, b - 1, q);
1221                 break;
1222             }
1223         }
1224     }
1225 }
1226
1227 /* compute the ac3 crc */
1228
1229 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1230
1231 static void ac3_crc_init(void)
1232 {
1233     unsigned int c, n, k;
1234
1235     for(n=0;n<256;n++) {
1236         c = n << 8;
1237         for (k = 0; k < 8; k++) {
1238             if (c & (1 << 15)) 
1239                 c = ((c << 1) & 0xffff) ^ (CRC16_POLY & 0xffff);
1240             else
1241                 c = c << 1;
1242         }
1243         crc_table[n] = c;
1244     }
1245 }
1246
1247 static unsigned int ac3_crc(uint8_t *data, int n, unsigned int crc)
1248 {
1249     int i;
1250     for(i=0;i<n;i++) {
1251         crc = (crc_table[data[i] ^ (crc >> 8)] ^ (crc << 8)) & 0xffff;
1252     }
1253     return crc;
1254 }
1255
1256 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1257 {
1258     unsigned int c;
1259
1260     c = 0;
1261     while (a) {
1262         if (a & 1)
1263             c ^= b;
1264         a = a >> 1;
1265         b = b << 1;
1266         if (b & (1 << 16))
1267             b ^= poly;
1268     }
1269     return c;
1270 }
1271
1272 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1273 {
1274     unsigned int r;
1275     r = 1;
1276     while (n) {
1277         if (n & 1)
1278             r = mul_poly(r, a, poly);
1279         a = mul_poly(a, a, poly);
1280         n >>= 1;
1281     }
1282     return r;
1283 }
1284
1285
1286 /* compute log2(max(abs(tab[]))) */
1287 static int log2_tab(int16_t *tab, int n)
1288 {
1289     int i, v;
1290
1291     v = 0;
1292     for(i=0;i<n;i++) {
1293         v |= abs(tab[i]);
1294     }
1295     return av_log2(v);
1296 }
1297
1298 static void lshift_tab(int16_t *tab, int n, int lshift)
1299 {
1300     int i;
1301
1302     if (lshift > 0) {
1303         for(i=0;i<n;i++) {
1304             tab[i] <<= lshift;
1305         }
1306     } else if (lshift < 0) {
1307         lshift = -lshift;
1308         for(i=0;i<n;i++) {
1309             tab[i] >>= lshift;
1310         }
1311     }
1312 }
1313
1314 /* fill the end of the frame and compute the two crcs */
1315 static int output_frame_end(AC3EncodeContext *s)
1316 {
1317     int frame_size, frame_size_58, n, crc1, crc2, crc_inv;
1318     uint8_t *frame;
1319
1320     frame_size = s->frame_size; /* frame size in words */
1321     /* align to 8 bits */
1322     flush_put_bits(&s->pb);
1323     /* add zero bytes to reach the frame size */
1324     frame = s->pb.buf;
1325     n = 2 * s->frame_size - (pbBufPtr(&s->pb) - frame) - 2;
1326     assert(n >= 0);
1327     memset(pbBufPtr(&s->pb), 0, n);
1328     
1329     /* Now we must compute both crcs : this is not so easy for crc1
1330        because it is at the beginning of the data... */
1331     frame_size_58 = (frame_size >> 1) + (frame_size >> 3);
1332     crc1 = ac3_crc(frame + 4, (2 * frame_size_58) - 4, 0);
1333     /* XXX: could precompute crc_inv */
1334     crc_inv = pow_poly((CRC16_POLY >> 1), (16 * frame_size_58) - 16, CRC16_POLY);
1335     crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1336     frame[2] = crc1 >> 8;
1337     frame[3] = crc1;
1338     
1339     crc2 = ac3_crc(frame + 2 * frame_size_58, (frame_size - frame_size_58) * 2 - 2, 0);
1340     frame[2*frame_size - 2] = crc2 >> 8;
1341     frame[2*frame_size - 1] = crc2;
1342
1343     //    printf("n=%d frame_size=%d\n", n, frame_size);
1344     return frame_size * 2;
1345 }
1346
1347 static int AC3_encode_frame(AVCodecContext *avctx,
1348                             unsigned char *frame, int buf_size, void *data)
1349 {
1350     AC3EncodeContext *s = avctx->priv_data;
1351     short *samples = data;
1352     int i, j, k, v, ch;
1353     int16_t input_samples[N];
1354     int32_t mdct_coef[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1355     uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1356     uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS];
1357     uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1358     uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1359     int8_t exp_samples[NB_BLOCKS][AC3_MAX_CHANNELS];
1360     int frame_bits;
1361
1362     frame_bits = 0;
1363     for(ch=0;ch<s->nb_all_channels;ch++) {
1364         /* fixed mdct to the six sub blocks & exponent computation */
1365         for(i=0;i<NB_BLOCKS;i++) {
1366             int16_t *sptr;
1367             int sinc;
1368
1369             /* compute input samples */
1370             memcpy(input_samples, s->last_samples[ch], N/2 * sizeof(int16_t));
1371             sinc = s->nb_all_channels;
1372             sptr = samples + (sinc * (N/2) * i) + ch;
1373             for(j=0;j<N/2;j++) {
1374                 v = *sptr;
1375                 input_samples[j + N/2] = v;
1376                 s->last_samples[ch][j] = v; 
1377                 sptr += sinc;
1378             }
1379
1380             /* apply the MDCT window */
1381             for(j=0;j<N/2;j++) {
1382                 input_samples[j] = MUL16(input_samples[j], 
1383                                          ac3_window[j]) >> 15;
1384                 input_samples[N-j-1] = MUL16(input_samples[N-j-1], 
1385                                              ac3_window[j]) >> 15;
1386             }
1387         
1388             /* Normalize the samples to use the maximum available
1389                precision */
1390             v = 14 - log2_tab(input_samples, N);
1391             if (v < 0)
1392                 v = 0;
1393             exp_samples[i][ch] = v - 8;
1394             lshift_tab(input_samples, N, v);
1395
1396             /* do the MDCT */
1397             mdct512(mdct_coef[i][ch], input_samples);
1398             
1399             /* compute "exponents". We take into account the
1400                normalization there */
1401             for(j=0;j<N/2;j++) {
1402                 int e;
1403                 v = abs(mdct_coef[i][ch][j]);
1404                 if (v == 0)
1405                     e = 24;
1406                 else {
1407                     e = 23 - av_log2(v) + exp_samples[i][ch];
1408                     if (e >= 24) {
1409                         e = 24;
1410                         mdct_coef[i][ch][j] = 0;
1411                     }
1412                 }
1413                 exp[i][ch][j] = e;
1414             }
1415         }
1416         
1417         compute_exp_strategy(exp_strategy, exp, ch, ch == s->lfe_channel);
1418
1419         /* compute the exponents as the decoder will see them. The
1420            EXP_REUSE case must be handled carefully : we select the
1421            min of the exponents */
1422         i = 0;
1423         while (i < NB_BLOCKS) {
1424             j = i + 1;
1425             while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE) {
1426                 exponent_min(exp[i][ch], exp[j][ch], s->nb_coefs[ch]);
1427                 j++;
1428             }
1429             frame_bits += encode_exp(encoded_exp[i][ch],
1430                                      exp[i][ch], s->nb_coefs[ch], 
1431                                      exp_strategy[i][ch]);
1432             /* copy encoded exponents for reuse case */
1433             for(k=i+1;k<j;k++) {
1434                 memcpy(encoded_exp[k][ch], encoded_exp[i][ch], 
1435                        s->nb_coefs[ch] * sizeof(uint8_t));
1436             }
1437             i = j;
1438         }
1439     }
1440
1441     compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
1442     /* everything is known... let's output the frame */
1443     output_frame_header(s, frame);
1444         
1445     for(i=0;i<NB_BLOCKS;i++) {
1446         output_audio_block(s, exp_strategy[i], encoded_exp[i], 
1447                            bap[i], mdct_coef[i], exp_samples[i], i);
1448     }
1449     return output_frame_end(s);
1450 }
1451
1452 static int AC3_encode_close(AVCodecContext *avctx)
1453 {
1454     av_freep(&avctx->coded_frame);
1455     return 0;
1456 }
1457
1458 #if 0
1459 /*************************************************************************/
1460 /* TEST */
1461
1462 #define FN (N/4)
1463
1464 void fft_test(void)
1465 {
1466     IComplex in[FN], in1[FN];
1467     int k, n, i;
1468     float sum_re, sum_im, a;
1469
1470     /* FFT test */
1471
1472     for(i=0;i<FN;i++) {
1473         in[i].re = random() % 65535 - 32767;
1474         in[i].im = random() % 65535 - 32767;
1475         in1[i] = in[i];
1476     }
1477     fft(in, 7);
1478
1479     /* do it by hand */
1480     for(k=0;k<FN;k++) {
1481         sum_re = 0;
1482         sum_im = 0;
1483         for(n=0;n<FN;n++) {
1484             a = -2 * M_PI * (n * k) / FN;
1485             sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1486             sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1487         }
1488         printf("%3d: %6d,%6d %6.0f,%6.0f\n", 
1489                k, in[k].re, in[k].im, sum_re / FN, sum_im / FN); 
1490     }
1491 }
1492
1493 void mdct_test(void)
1494 {
1495     int16_t input[N];
1496     int32_t output[N/2];
1497     float input1[N];
1498     float output1[N/2];
1499     float s, a, err, e, emax;
1500     int i, k, n;
1501
1502     for(i=0;i<N;i++) {
1503         input[i] = (random() % 65535 - 32767) * 9 / 10;
1504         input1[i] = input[i];
1505     }
1506
1507     mdct512(output, input);
1508     
1509     /* do it by hand */
1510     for(k=0;k<N/2;k++) {
1511         s = 0;
1512         for(n=0;n<N;n++) {
1513             a = (2*M_PI*(2*n+1+N/2)*(2*k+1) / (4 * N));
1514             s += input1[n] * cos(a);
1515         }
1516         output1[k] = -2 * s / N;
1517     }
1518     
1519     err = 0;
1520     emax = 0;
1521     for(i=0;i<N/2;i++) {
1522         printf("%3d: %7d %7.0f\n", i, output[i], output1[i]);
1523         e = output[i] - output1[i];
1524         if (e > emax)
1525             emax = e;
1526         err += e * e;
1527     }
1528     printf("err2=%f emax=%f\n", err / (N/2), emax);
1529 }
1530
1531 void test_ac3(void)
1532 {
1533     AC3EncodeContext ctx;
1534     unsigned char frame[AC3_MAX_CODED_FRAME_SIZE];
1535     short samples[AC3_FRAME_SIZE];
1536     int ret, i;
1537     
1538     AC3_encode_init(&ctx, 44100, 64000, 1);
1539
1540     fft_test();
1541     mdct_test();
1542
1543     for(i=0;i<AC3_FRAME_SIZE;i++)
1544         samples[i] = (int)(sin(2*M_PI*i*1000.0/44100) * 10000);
1545     ret = AC3_encode_frame(&ctx, frame, samples);
1546     printf("ret=%d\n", ret);
1547 }
1548 #endif
1549
1550 AVCodec ac3_encoder = {
1551     "ac3",
1552     CODEC_TYPE_AUDIO,
1553     CODEC_ID_AC3,
1554     sizeof(AC3EncodeContext),
1555     AC3_encode_init,
1556     AC3_encode_frame,
1557     AC3_encode_close,
1558     NULL,
1559 };