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