• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files

hvirtual/quicktime/ffmpeg/libavcodec/ac3enc.c

Go to the documentation of this file.
00001 /*
00002  * The simplest AC3 encoder
00003  * Copyright (c) 2000 Fabrice Bellard.
00004  *
00005  * This library is free software; you can redistribute it and/or
00006  * modify it under the terms of the GNU Lesser General Public
00007  * License as published by the Free Software Foundation; either
00008  * version 2 of the License, or (at your option) any later version.
00009  *
00010  * This library is distributed in the hope that it will be useful,
00011  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00012  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00013  * Lesser General Public License for more details.
00014  *
00015  * You should have received a copy of the GNU Lesser General Public
00016  * License along with this library; if not, write to the Free Software
00017  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
00018  */
00019 
00024 //#define DEBUG
00025 //#define DEBUG_BITALLOC
00026 #include "avcodec.h"
00027 #include "bitstream.h"
00028 #include "ac3.h"
00029 
00030 typedef struct AC3EncodeContext {
00031     PutBitContext pb;
00032     int nb_channels;
00033     int nb_all_channels;
00034     int lfe_channel;
00035     int bit_rate;
00036     unsigned int sample_rate;
00037     unsigned int bsid;
00038     unsigned int frame_size_min; /* minimum frame size in case rounding is necessary */
00039     unsigned int frame_size; /* current frame size in words */
00040     int halfratecod;
00041     unsigned int frmsizecod;
00042     unsigned int fscod; /* frequency */
00043     unsigned int acmod;
00044     int lfe;
00045     unsigned int bsmod;
00046     short last_samples[AC3_MAX_CHANNELS][256];
00047     unsigned int chbwcod[AC3_MAX_CHANNELS];
00048     int nb_coefs[AC3_MAX_CHANNELS];
00049     
00050     /* bitrate allocation control */
00051     int sgaincod, sdecaycod, fdecaycod, dbkneecod, floorcod; 
00052     AC3BitAllocParameters bit_alloc;
00053     int csnroffst;
00054     int fgaincod[AC3_MAX_CHANNELS];
00055     int fsnroffst[AC3_MAX_CHANNELS];
00056     /* mantissa encoding */
00057     int mant1_cnt, mant2_cnt, mant4_cnt;
00058 } AC3EncodeContext;
00059 
00060 #include "ac3tab.h"
00061 
00062 #define MDCT_NBITS 9
00063 #define N         (1 << MDCT_NBITS)
00064 
00065 /* new exponents are sent if their Norm 1 exceed this number */
00066 #define EXP_DIFF_THRESHOLD 1000
00067 
00068 static void fft_init(int ln);
00069 static void ac3_crc_init(void);
00070 
00071 static inline int16_t fix15(float a)
00072 {
00073     int v;
00074     v = (int)(a * (float)(1 << 15));
00075     if (v < -32767)
00076         v = -32767;
00077     else if (v > 32767) 
00078         v = 32767;
00079     return v;
00080 }
00081 
00082 static inline int calc_lowcomp1(int a, int b0, int b1)
00083 {
00084     if ((b0 + 256) == b1) {
00085         a = 384 ;
00086     } else if (b0 > b1) { 
00087         a = a - 64;
00088         if (a < 0) a=0;
00089     }
00090     return a;
00091 }
00092 
00093 static inline int calc_lowcomp(int a, int b0, int b1, int bin)
00094 {
00095     if (bin < 7) {
00096         if ((b0 + 256) == b1) {
00097             a = 384 ;
00098         } else if (b0 > b1) { 
00099             a = a - 64;
00100             if (a < 0) a=0;
00101         }
00102     } else if (bin < 20) {
00103         if ((b0 + 256) == b1) {
00104             a = 320 ;
00105         } else if (b0 > b1) {
00106             a= a - 64;
00107             if (a < 0) a=0;
00108         }
00109     } else {
00110         a = a - 128;
00111         if (a < 0) a=0;
00112     }
00113     return a;
00114 }
00115 
00116 /* AC3 bit allocation. The algorithm is the one described in the AC3
00117    spec. */
00118 void ac3_parametric_bit_allocation(AC3BitAllocParameters *s, uint8_t *bap,
00119                                    int8_t *exp, int start, int end,
00120                                    int snroffset, int fgain, int is_lfe,
00121                                    int deltbae,int deltnseg, 
00122                                    uint8_t *deltoffst, uint8_t *deltlen, uint8_t *deltba)
00123 {
00124     int bin,i,j,k,end1,v,v1,bndstrt,bndend,lowcomp,begin;
00125     int fastleak,slowleak,address,tmp;
00126     int16_t psd[256]; /* scaled exponents */
00127     int16_t bndpsd[50]; /* interpolated exponents */
00128     int16_t excite[50]; /* excitation */
00129     int16_t mask[50];   /* masking value */
00130 
00131     /* exponent mapping to PSD */
00132     for(bin=start;bin<end;bin++) {
00133         psd[bin]=(3072 - (exp[bin] << 7));
00134     }
00135 
00136     /* PSD integration */
00137     j=start;
00138     k=masktab[start];
00139     do {
00140         v=psd[j];
00141         j++;
00142         end1=bndtab[k+1];
00143         if (end1 > end) end1=end;
00144         for(i=j;i<end1;i++) {
00145             int c,adr;
00146             /* logadd */
00147             v1=psd[j];
00148             c=v-v1;
00149             if (c >= 0) {
00150                 adr=c >> 1;
00151                 if (adr > 255) adr=255;
00152                 v=v + latab[adr];
00153             } else {
00154                 adr=(-c) >> 1;
00155                 if (adr > 255) adr=255;
00156                 v=v1 + latab[adr];
00157             }
00158             j++;
00159         }
00160         bndpsd[k]=v;
00161         k++;
00162     } while (end > bndtab[k]);
00163 
00164     /* excitation function */
00165     bndstrt = masktab[start];
00166     bndend = masktab[end-1] + 1;
00167     
00168     if (bndstrt == 0) {
00169         lowcomp = 0;
00170         lowcomp = calc_lowcomp1(lowcomp, bndpsd[0], bndpsd[1]) ;
00171         excite[0] = bndpsd[0] - fgain - lowcomp ;
00172         lowcomp = calc_lowcomp1(lowcomp, bndpsd[1], bndpsd[2]) ;
00173         excite[1] = bndpsd[1] - fgain - lowcomp ;
00174         begin = 7 ;
00175         for (bin = 2; bin < 7; bin++) {
00176             if (!(is_lfe && bin == 6))
00177                 lowcomp = calc_lowcomp1(lowcomp, bndpsd[bin], bndpsd[bin+1]) ;
00178             fastleak = bndpsd[bin] - fgain ;
00179             slowleak = bndpsd[bin] - s->sgain ;
00180             excite[bin] = fastleak - lowcomp ;
00181             if (!(is_lfe && bin == 6)) {
00182                 if (bndpsd[bin] <= bndpsd[bin+1]) {
00183                     begin = bin + 1 ;
00184                     break ;
00185                 }
00186             }
00187         }
00188     
00189         end1=bndend;
00190         if (end1 > 22) end1=22;
00191     
00192         for (bin = begin; bin < end1; bin++) {
00193             if (!(is_lfe && bin == 6))
00194                 lowcomp = calc_lowcomp(lowcomp, bndpsd[bin], bndpsd[bin+1], bin) ;
00195         
00196             fastleak -= s->fdecay ;
00197             v = bndpsd[bin] - fgain;
00198             if (fastleak < v) fastleak = v;
00199         
00200             slowleak -= s->sdecay ;
00201             v = bndpsd[bin] - s->sgain;
00202             if (slowleak < v) slowleak = v;
00203         
00204             v=fastleak - lowcomp;
00205             if (slowleak > v) v=slowleak;
00206         
00207             excite[bin] = v;
00208         }
00209         begin = 22;
00210     } else {
00211         /* coupling channel */
00212         begin = bndstrt;
00213         
00214         fastleak = (s->cplfleak << 8) + 768;
00215         slowleak = (s->cplsleak << 8) + 768;
00216     }
00217 
00218     for (bin = begin; bin < bndend; bin++) {
00219         fastleak -= s->fdecay ;
00220         v = bndpsd[bin] - fgain;
00221         if (fastleak < v) fastleak = v;
00222         slowleak -= s->sdecay ;
00223         v = bndpsd[bin] - s->sgain;
00224         if (slowleak < v) slowleak = v;
00225 
00226         v=fastleak;
00227         if (slowleak > v) v = slowleak;
00228         excite[bin] = v;
00229     }
00230 
00231     /* compute masking curve */
00232 
00233     for (bin = bndstrt; bin < bndend; bin++) {
00234         v1 = excite[bin];
00235         tmp = s->dbknee - bndpsd[bin];
00236         if (tmp > 0) {
00237             v1 += tmp >> 2;
00238         }
00239         v=hth[bin >> s->halfratecod][s->fscod];
00240         if (v1 > v) v=v1;
00241         mask[bin] = v;
00242     }
00243 
00244     /* delta bit allocation */
00245 
00246     if (deltbae == 0 || deltbae == 1) {
00247         int band, seg, delta;
00248         band = 0 ;
00249         for (seg = 0; seg < deltnseg; seg++) {
00250             band += deltoffst[seg] ;
00251             if (deltba[seg] >= 4) {
00252                 delta = (deltba[seg] - 3) << 7;
00253             } else {
00254                 delta = (deltba[seg] - 4) << 7;
00255             }
00256             for (k = 0; k < deltlen[seg]; k++) {
00257                 mask[band] += delta ;
00258                 band++ ;
00259             }
00260         }
00261     }
00262 
00263     /* compute bit allocation */
00264     
00265     i = start ;
00266     j = masktab[start] ;
00267     do {
00268         v=mask[j];
00269         v -= snroffset ;
00270         v -= s->floor ;
00271         if (v < 0) v = 0;
00272         v &= 0x1fe0 ;
00273         v += s->floor ;
00274 
00275         end1=bndtab[j] + bndsz[j];
00276         if (end1 > end) end1=end;
00277 
00278         for (k = i; k < end1; k++) {
00279             address = (psd[i] - v) >> 5 ;
00280             if (address < 0) address=0;
00281             else if (address > 63) address=63;
00282             bap[i] = baptab[address];
00283             i++;
00284         }
00285     } while (end > bndtab[j++]) ;
00286 }
00287 
00288 typedef struct IComplex {
00289     short re,im;
00290 } IComplex;
00291 
00292 static void fft_init(int ln)
00293 {
00294     int i, j, m, n;
00295     float alpha;
00296 
00297     n = 1 << ln;
00298 
00299     for(i=0;i<(n/2);i++) {
00300         alpha = 2 * M_PI * (float)i / (float)n;
00301         costab[i] = fix15(cos(alpha));
00302         sintab[i] = fix15(sin(alpha));
00303     }
00304 
00305     for(i=0;i<n;i++) {
00306         m=0;
00307         for(j=0;j<ln;j++) {
00308             m |= ((i >> j) & 1) << (ln-j-1);
00309         }
00310         fft_rev[i]=m;
00311     }
00312 }
00313 
00314 /* butter fly op */
00315 #define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1) \
00316 {\
00317   int ax, ay, bx, by;\
00318   bx=pre1;\
00319   by=pim1;\
00320   ax=qre1;\
00321   ay=qim1;\
00322   pre = (bx + ax) >> 1;\
00323   pim = (by + ay) >> 1;\
00324   qre = (bx - ax) >> 1;\
00325   qim = (by - ay) >> 1;\
00326 }
00327 
00328 #define MUL16(a,b) ((a) * (b))
00329 
00330 #define CMUL(pre, pim, are, aim, bre, bim) \
00331 {\
00332    pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;\
00333    pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;\
00334 }
00335 
00336 
00337 /* do a 2^n point complex fft on 2^ln points. */
00338 static void fft(IComplex *z, int ln)
00339 {
00340     int j, l, np, np2;
00341     int nblocks, nloops;
00342     register IComplex *p,*q;
00343     int tmp_re, tmp_im;
00344 
00345     np = 1 << ln;
00346 
00347     /* reverse */
00348     for(j=0;j<np;j++) {
00349         int k;
00350         IComplex tmp;
00351         k = fft_rev[j];
00352         if (k < j) {
00353             tmp = z[k];
00354             z[k] = z[j];
00355             z[j] = tmp;
00356         }
00357     }
00358 
00359     /* pass 0 */
00360 
00361     p=&z[0];
00362     j=(np >> 1);
00363     do {
00364         BF(p[0].re, p[0].im, p[1].re, p[1].im, 
00365            p[0].re, p[0].im, p[1].re, p[1].im);
00366         p+=2;
00367     } while (--j != 0);
00368 
00369     /* pass 1 */
00370 
00371     p=&z[0];
00372     j=np >> 2;
00373     do {
00374         BF(p[0].re, p[0].im, p[2].re, p[2].im, 
00375            p[0].re, p[0].im, p[2].re, p[2].im);
00376         BF(p[1].re, p[1].im, p[3].re, p[3].im, 
00377            p[1].re, p[1].im, p[3].im, -p[3].re);
00378         p+=4;
00379     } while (--j != 0);
00380 
00381     /* pass 2 .. ln-1 */
00382 
00383     nblocks = np >> 3;
00384     nloops = 1 << 2;
00385     np2 = np >> 1;
00386     do {
00387         p = z;
00388         q = z + nloops;
00389         for (j = 0; j < nblocks; ++j) {
00390 
00391             BF(p->re, p->im, q->re, q->im,
00392                p->re, p->im, q->re, q->im);
00393             
00394             p++;
00395             q++;
00396             for(l = nblocks; l < np2; l += nblocks) {
00397                 CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
00398                 BF(p->re, p->im, q->re, q->im,
00399                    p->re, p->im, tmp_re, tmp_im);
00400                 p++;
00401                 q++;
00402             }
00403             p += nloops;
00404             q += nloops;
00405         }
00406         nblocks = nblocks >> 1;
00407         nloops = nloops << 1;
00408     } while (nblocks != 0);
00409 }
00410 
00411 /* do a 512 point mdct */
00412 static void mdct512(int32_t *out, int16_t *in)
00413 {
00414     int i, re, im, re1, im1;
00415     int16_t rot[N]; 
00416     IComplex x[N/4];
00417 
00418     /* shift to simplify computations */
00419     for(i=0;i<N/4;i++)
00420         rot[i] = -in[i + 3*N/4];
00421     for(i=N/4;i<N;i++)
00422         rot[i] = in[i - N/4];
00423         
00424     /* pre rotation */
00425     for(i=0;i<N/4;i++) {
00426         re = ((int)rot[2*i] - (int)rot[N-1-2*i]) >> 1;
00427         im = -((int)rot[N/2+2*i] - (int)rot[N/2-1-2*i]) >> 1;
00428         CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
00429     }
00430 
00431     fft(x, MDCT_NBITS - 2);
00432   
00433     /* post rotation */
00434     for(i=0;i<N/4;i++) {
00435         re = x[i].re;
00436         im = x[i].im;
00437         CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
00438         out[2*i] = im1;
00439         out[N/2-1-2*i] = re1;
00440     }
00441 }
00442 
00443 /* XXX: use another norm ? */
00444 static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
00445 {
00446     int sum, i;
00447     sum = 0;
00448     for(i=0;i<n;i++) {
00449         sum += abs(exp1[i] - exp2[i]);
00450     }
00451     return sum;
00452 }
00453 
00454 static void compute_exp_strategy(uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
00455                                  uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
00456                                  int ch, int is_lfe)
00457 {
00458     int i, j;
00459     int exp_diff;
00460     
00461     /* estimate if the exponent variation & decide if they should be
00462        reused in the next frame */
00463     exp_strategy[0][ch] = EXP_NEW;
00464     for(i=1;i<NB_BLOCKS;i++) {
00465         exp_diff = calc_exp_diff(exp[i][ch], exp[i-1][ch], N/2);
00466 #ifdef DEBUG            
00467         av_log(NULL, AV_LOG_DEBUG, "exp_diff=%d\n", exp_diff);
00468 #endif
00469         if (exp_diff > EXP_DIFF_THRESHOLD)
00470             exp_strategy[i][ch] = EXP_NEW;
00471         else
00472             exp_strategy[i][ch] = EXP_REUSE;
00473     }
00474     if (is_lfe)
00475         return;
00476 
00477     /* now select the encoding strategy type : if exponents are often
00478        recoded, we use a coarse encoding */
00479     i = 0;
00480     while (i < NB_BLOCKS) {
00481         j = i + 1;
00482         while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE)
00483             j++;
00484         switch(j - i) {
00485         case 1:
00486             exp_strategy[i][ch] = EXP_D45;
00487             break;
00488         case 2:
00489         case 3:
00490             exp_strategy[i][ch] = EXP_D25;
00491             break;
00492         default:
00493             exp_strategy[i][ch] = EXP_D15;
00494             break;
00495         }
00496         i = j;
00497     }
00498 }
00499 
00500 /* set exp[i] to min(exp[i], exp1[i]) */
00501 static void exponent_min(uint8_t exp[N/2], uint8_t exp1[N/2], int n)
00502 {
00503     int i;
00504 
00505     for(i=0;i<n;i++) {
00506         if (exp1[i] < exp[i])
00507             exp[i] = exp1[i];
00508     }
00509 }
00510                                  
00511 /* update the exponents so that they are the ones the decoder will
00512    decode. Return the number of bits used to code the exponents */
00513 static int encode_exp(uint8_t encoded_exp[N/2], 
00514                       uint8_t exp[N/2], 
00515                       int nb_exps,
00516                       int exp_strategy)
00517 {
00518     int group_size, nb_groups, i, j, k, exp_min;
00519     uint8_t exp1[N/2];
00520 
00521     switch(exp_strategy) {
00522     case EXP_D15:
00523         group_size = 1;
00524         break;
00525     case EXP_D25:
00526         group_size = 2;
00527         break;
00528     default:
00529     case EXP_D45:
00530         group_size = 4;
00531         break;
00532     }
00533     nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
00534 
00535     /* for each group, compute the minimum exponent */
00536     exp1[0] = exp[0]; /* DC exponent is handled separately */
00537     k = 1;
00538     for(i=1;i<=nb_groups;i++) {
00539         exp_min = exp[k];
00540         assert(exp_min >= 0 && exp_min <= 24);
00541         for(j=1;j<group_size;j++) {
00542             if (exp[k+j] < exp_min)
00543                 exp_min = exp[k+j];
00544         }
00545         exp1[i] = exp_min;
00546         k += group_size;
00547     }
00548 
00549     /* constraint for DC exponent */
00550     if (exp1[0] > 15)
00551         exp1[0] = 15;
00552 
00553     /* Decrease the delta between each groups to within 2
00554      * so that they can be differentially encoded */
00555     for (i=1;i<=nb_groups;i++)
00556         exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
00557     for (i=nb_groups-1;i>=0;i--)
00558         exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
00559 
00560     /* now we have the exponent values the decoder will see */
00561     encoded_exp[0] = exp1[0];
00562     k = 1;
00563     for(i=1;i<=nb_groups;i++) {
00564         for(j=0;j<group_size;j++) {
00565             encoded_exp[k+j] = exp1[i];
00566         }
00567         k += group_size;
00568     }
00569     
00570 #if defined(DEBUG)
00571     av_log(NULL, AV_LOG_DEBUG, "exponents: strategy=%d\n", exp_strategy);
00572     for(i=0;i<=nb_groups * group_size;i++) {
00573         av_log(NULL, AV_LOG_DEBUG, "%d ", encoded_exp[i]);
00574     }
00575     av_log(NULL, AV_LOG_DEBUG, "\n");
00576 #endif
00577 
00578     return 4 + (nb_groups / 3) * 7;
00579 }
00580 
00581 /* return the size in bits taken by the mantissa */
00582 static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
00583 {
00584     int bits, mant, i;
00585 
00586     bits = 0;
00587     for(i=0;i<nb_coefs;i++) {
00588         mant = m[i];
00589         switch(mant) {
00590         case 0:
00591             /* nothing */
00592             break;
00593         case 1:
00594             /* 3 mantissa in 5 bits */
00595             if (s->mant1_cnt == 0) 
00596                 bits += 5;
00597             if (++s->mant1_cnt == 3)
00598                 s->mant1_cnt = 0;
00599             break;
00600         case 2:
00601             /* 3 mantissa in 7 bits */
00602             if (s->mant2_cnt == 0) 
00603                 bits += 7;
00604             if (++s->mant2_cnt == 3)
00605                 s->mant2_cnt = 0;
00606             break;
00607         case 3:
00608             bits += 3;
00609             break;
00610         case 4:
00611             /* 2 mantissa in 7 bits */
00612             if (s->mant4_cnt == 0)
00613                 bits += 7;
00614             if (++s->mant4_cnt == 2) 
00615                 s->mant4_cnt = 0;
00616             break;
00617         case 14:
00618             bits += 14;
00619             break;
00620         case 15:
00621             bits += 16;
00622             break;
00623         default:
00624             bits += mant - 1;
00625             break;
00626         }
00627     }
00628     return bits;
00629 }
00630 
00631 
00632 static int bit_alloc(AC3EncodeContext *s,
00633                      uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
00634                      uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
00635                      uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
00636                      int frame_bits, int csnroffst, int fsnroffst)
00637 {
00638     int i, ch;
00639 
00640     /* compute size */
00641     for(i=0;i<NB_BLOCKS;i++) {
00642         s->mant1_cnt = 0;
00643         s->mant2_cnt = 0;
00644         s->mant4_cnt = 0;
00645         for(ch=0;ch<s->nb_all_channels;ch++) {
00646             ac3_parametric_bit_allocation(&s->bit_alloc, 
00647                                           bap[i][ch], (int8_t *)encoded_exp[i][ch], 
00648                                           0, s->nb_coefs[ch], 
00649                                           (((csnroffst-15) << 4) + 
00650                                            fsnroffst) << 2, 
00651                                           fgaintab[s->fgaincod[ch]],
00652                                           ch == s->lfe_channel,
00653                                           2, 0, NULL, NULL, NULL);
00654             frame_bits += compute_mantissa_size(s, bap[i][ch], 
00655                                                  s->nb_coefs[ch]);
00656         }
00657     }
00658 #if 0
00659     printf("csnr=%d fsnr=%d frame_bits=%d diff=%d\n", 
00660            csnroffst, fsnroffst, frame_bits, 
00661            16 * s->frame_size - ((frame_bits + 7) & ~7));
00662 #endif
00663     return 16 * s->frame_size - frame_bits;
00664 }
00665 
00666 #define SNR_INC1 4
00667 
00668 static int compute_bit_allocation(AC3EncodeContext *s,
00669                                   uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
00670                                   uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
00671                                   uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
00672                                   int frame_bits)
00673 {
00674     int i, ch;
00675     int csnroffst, fsnroffst;
00676     uint8_t bap1[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
00677     static int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
00678 
00679     /* init default parameters */
00680     s->sdecaycod = 2;
00681     s->fdecaycod = 1;
00682     s->sgaincod = 1;
00683     s->dbkneecod = 2;
00684     s->floorcod = 4;
00685     for(ch=0;ch<s->nb_all_channels;ch++) 
00686         s->fgaincod[ch] = 4;
00687     
00688     /* compute real values */
00689     s->bit_alloc.fscod = s->fscod;
00690     s->bit_alloc.halfratecod = s->halfratecod;
00691     s->bit_alloc.sdecay = sdecaytab[s->sdecaycod] >> s->halfratecod;
00692     s->bit_alloc.fdecay = fdecaytab[s->fdecaycod] >> s->halfratecod;
00693     s->bit_alloc.sgain = sgaintab[s->sgaincod];
00694     s->bit_alloc.dbknee = dbkneetab[s->dbkneecod];
00695     s->bit_alloc.floor = floortab[s->floorcod];
00696     
00697     /* header size */
00698     frame_bits += 65;
00699     // if (s->acmod == 2)
00700     //    frame_bits += 2;
00701     frame_bits += frame_bits_inc[s->acmod];
00702 
00703     /* audio blocks */
00704     for(i=0;i<NB_BLOCKS;i++) {
00705         frame_bits += s->nb_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
00706         if (s->acmod == 2) {
00707             frame_bits++; /* rematstr */
00708             if(i==0) frame_bits += 4;
00709         }
00710         frame_bits += 2 * s->nb_channels; /* chexpstr[2] * c */
00711         if (s->lfe)
00712             frame_bits++; /* lfeexpstr */
00713         for(ch=0;ch<s->nb_channels;ch++) {
00714             if (exp_strategy[i][ch] != EXP_REUSE)
00715                 frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
00716         }
00717         frame_bits++; /* baie */
00718         frame_bits++; /* snr */
00719         frame_bits += 2; /* delta / skip */
00720     }
00721     frame_bits++; /* cplinu for block 0 */
00722     /* bit alloc info */
00723     /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
00724     /* csnroffset[6] */
00725     /* (fsnoffset[4] + fgaincod[4]) * c */
00726     frame_bits += 2*4 + 3 + 6 + s->nb_all_channels * (4 + 3);
00727 
00728     /* auxdatae, crcrsv */
00729     frame_bits += 2;
00730 
00731     /* CRC */
00732     frame_bits += 16;
00733 
00734     /* now the big work begins : do the bit allocation. Modify the snr
00735        offset until we can pack everything in the requested frame size */
00736 
00737     csnroffst = s->csnroffst;
00738     while (csnroffst >= 0 && 
00739            bit_alloc(s, bap, encoded_exp, exp_strategy, frame_bits, csnroffst, 0) < 0)
00740         csnroffst -= SNR_INC1;
00741     if (csnroffst < 0) {
00742         av_log(NULL, AV_LOG_ERROR, "Yack, Error !!!\n");
00743         return -1;
00744     }
00745     while ((csnroffst + SNR_INC1) <= 63 && 
00746            bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits, 
00747                      csnroffst + SNR_INC1, 0) >= 0) {
00748         csnroffst += SNR_INC1;
00749         memcpy(bap, bap1, sizeof(bap1));
00750     }
00751     while ((csnroffst + 1) <= 63 && 
00752            bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits, csnroffst + 1, 0) >= 0) {
00753         csnroffst++;
00754         memcpy(bap, bap1, sizeof(bap1));
00755     }
00756 
00757     fsnroffst = 0;
00758     while ((fsnroffst + SNR_INC1) <= 15 && 
00759            bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits, 
00760                      csnroffst, fsnroffst + SNR_INC1) >= 0) {
00761         fsnroffst += SNR_INC1;
00762         memcpy(bap, bap1, sizeof(bap1));
00763     }
00764     while ((fsnroffst + 1) <= 15 && 
00765            bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits, 
00766                      csnroffst, fsnroffst + 1) >= 0) {
00767         fsnroffst++;
00768         memcpy(bap, bap1, sizeof(bap1));
00769     }
00770     
00771     s->csnroffst = csnroffst;
00772     for(ch=0;ch<s->nb_all_channels;ch++)
00773         s->fsnroffst[ch] = fsnroffst;
00774 #if defined(DEBUG_BITALLOC)
00775     {
00776         int j;
00777 
00778         for(i=0;i<6;i++) {
00779             for(ch=0;ch<s->nb_all_channels;ch++) {
00780                 printf("Block #%d Ch%d:\n", i, ch);
00781                 printf("bap=");
00782                 for(j=0;j<s->nb_coefs[ch];j++) {
00783                     printf("%d ",bap[i][ch][j]);
00784                 }
00785                 printf("\n");
00786             }
00787         }
00788     }
00789 #endif
00790     return 0;
00791 }
00792 
00793 void ac3_common_init(void)
00794 {
00795     int i, j, k, l, v;
00796     /* compute bndtab and masktab from bandsz */
00797     k = 0;
00798     l = 0;
00799     for(i=0;i<50;i++) {
00800         bndtab[i] = l;
00801         v = bndsz[i];
00802         for(j=0;j<v;j++) masktab[k++]=i;
00803         l += v;
00804     }
00805     bndtab[50] = 0;
00806 }
00807 
00808 
00809 static int AC3_encode_init(AVCodecContext *avctx)
00810 {
00811     int freq = avctx->sample_rate;
00812     int bitrate = avctx->bit_rate;
00813     int channels = avctx->channels;
00814     AC3EncodeContext *s = avctx->priv_data;
00815     int i, j, ch;
00816     float alpha;
00817     static const uint8_t acmod_defs[6] = {
00818         0x01, /* C */
00819         0x02, /* L R */
00820         0x03, /* L C R */
00821         0x06, /* L R SL SR */
00822         0x07, /* L C R SL SR */
00823         0x07, /* L C R SL SR (+LFE) */
00824     };
00825 
00826     avctx->frame_size = AC3_FRAME_SIZE;
00827     
00828     /* number of channels */
00829     if (channels < 1 || channels > 6)
00830         return -1;
00831     s->acmod = acmod_defs[channels - 1];
00832     s->lfe = (channels == 6) ? 1 : 0;
00833     s->nb_all_channels = channels;
00834     s->nb_channels = channels > 5 ? 5 : channels;
00835     s->lfe_channel = s->lfe ? 5 : -1;
00836 
00837     /* frequency */
00838     for(i=0;i<3;i++) {
00839         for(j=0;j<3;j++) 
00840             if ((ac3_freqs[j] >> i) == freq)
00841                 goto found;
00842     }
00843     return -1;
00844  found:    
00845     s->sample_rate = freq;
00846     s->halfratecod = i;
00847     s->fscod = j;
00848     s->bsid = 8 + s->halfratecod;
00849     s->bsmod = 0; /* complete main audio service */
00850 
00851     /* bitrate & frame size */
00852     bitrate /= 1000;
00853     for(i=0;i<19;i++) {
00854         if ((ac3_bitratetab[i] >> s->halfratecod) == bitrate)
00855             break;
00856     }
00857     if (i == 19)
00858         return -1;
00859     s->bit_rate = bitrate;
00860     s->frmsizecod = i << 1;
00861     s->frame_size_min = (bitrate * 1000 * AC3_FRAME_SIZE) / (freq * 16);
00862     /* for now we do not handle fractional sizes */
00863     s->frame_size = s->frame_size_min;
00864     
00865     /* bit allocation init */
00866     for(ch=0;ch<s->nb_channels;ch++) {
00867         /* bandwidth for each channel */
00868         /* XXX: should compute the bandwidth according to the frame
00869            size, so that we avoid anoying high freq artefacts */
00870         s->chbwcod[ch] = 50; /* sample bandwidth as mpeg audio layer 2 table 0 */
00871         s->nb_coefs[ch] = ((s->chbwcod[ch] + 12) * 3) + 37;
00872     }
00873     if (s->lfe) {
00874         s->nb_coefs[s->lfe_channel] = 7; /* fixed */
00875     }
00876     /* initial snr offset */
00877     s->csnroffst = 40;
00878 
00879     ac3_common_init();
00880 
00881     /* mdct init */
00882     fft_init(MDCT_NBITS - 2);
00883     for(i=0;i<N/4;i++) {
00884         alpha = 2 * M_PI * (i + 1.0 / 8.0) / (float)N;
00885         xcos1[i] = fix15(-cos(alpha));
00886         xsin1[i] = fix15(-sin(alpha));
00887     }
00888 
00889     ac3_crc_init();
00890     
00891     avctx->coded_frame= avcodec_alloc_frame();
00892     avctx->coded_frame->key_frame= 1;
00893 
00894     return 0;
00895 }
00896 
00897 /* output the AC3 frame header */
00898 static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
00899 {
00900     init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
00901 
00902     put_bits(&s->pb, 16, 0x0b77); /* frame header */
00903     put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
00904     put_bits(&s->pb, 2, s->fscod);
00905     put_bits(&s->pb, 6, s->frmsizecod + (s->frame_size - s->frame_size_min));
00906     put_bits(&s->pb, 5, s->bsid);
00907     put_bits(&s->pb, 3, s->bsmod);
00908     put_bits(&s->pb, 3, s->acmod);
00909     if ((s->acmod & 0x01) && s->acmod != 0x01)
00910         put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
00911     if (s->acmod & 0x04)
00912         put_bits(&s->pb, 2, 1); /* XXX -6 dB */
00913     if (s->acmod == 0x02)
00914         put_bits(&s->pb, 2, 0); /* surround not indicated */
00915     put_bits(&s->pb, 1, s->lfe); /* LFE */
00916     put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
00917     put_bits(&s->pb, 1, 0); /* no compression control word */
00918     put_bits(&s->pb, 1, 0); /* no lang code */
00919     put_bits(&s->pb, 1, 0); /* no audio production info */
00920     put_bits(&s->pb, 1, 0); /* no copyright */
00921     put_bits(&s->pb, 1, 1); /* original bitstream */
00922     put_bits(&s->pb, 1, 0); /* no time code 1 */
00923     put_bits(&s->pb, 1, 0); /* no time code 2 */
00924     put_bits(&s->pb, 1, 0); /* no addtional bit stream info */
00925 }
00926 
00927 /* symetric quantization on 'levels' levels */
00928 static inline int sym_quant(int c, int e, int levels)
00929 {
00930     int v;
00931 
00932     if (c >= 0) {
00933         v = (levels * (c << e)) >> 24;
00934         v = (v + 1) >> 1;
00935         v = (levels >> 1) + v;
00936     } else {
00937         v = (levels * ((-c) << e)) >> 24;
00938         v = (v + 1) >> 1;
00939         v = (levels >> 1) - v;
00940     }
00941     assert (v >= 0 && v < levels);
00942     return v;
00943 }
00944 
00945 /* asymetric quantization on 2^qbits levels */
00946 static inline int asym_quant(int c, int e, int qbits)
00947 {
00948     int lshift, m, v;
00949 
00950     lshift = e + qbits - 24;
00951     if (lshift >= 0)
00952         v = c << lshift;
00953     else
00954         v = c >> (-lshift);
00955     /* rounding */
00956     v = (v + 1) >> 1;
00957     m = (1 << (qbits-1));
00958     if (v >= m)
00959         v = m - 1;
00960     assert(v >= -m);
00961     return v & ((1 << qbits)-1);
00962 }
00963 
00964 /* Output one audio block. There are NB_BLOCKS audio blocks in one AC3
00965    frame */
00966 static void output_audio_block(AC3EncodeContext *s,
00967                                uint8_t exp_strategy[AC3_MAX_CHANNELS],
00968                                uint8_t encoded_exp[AC3_MAX_CHANNELS][N/2],
00969                                uint8_t bap[AC3_MAX_CHANNELS][N/2],
00970                                int32_t mdct_coefs[AC3_MAX_CHANNELS][N/2],
00971                                int8_t global_exp[AC3_MAX_CHANNELS],
00972                                int block_num)
00973 {
00974     int ch, nb_groups, group_size, i, baie, rbnd;
00975     uint8_t *p;
00976     uint16_t qmant[AC3_MAX_CHANNELS][N/2];
00977     int exp0, exp1;
00978     int mant1_cnt, mant2_cnt, mant4_cnt;
00979     uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
00980     int delta0, delta1, delta2;
00981 
00982     for(ch=0;ch<s->nb_channels;ch++) 
00983         put_bits(&s->pb, 1, 0); /* 512 point MDCT */
00984     for(ch=0;ch<s->nb_channels;ch++) 
00985         put_bits(&s->pb, 1, 1); /* no dither */
00986     put_bits(&s->pb, 1, 0); /* no dynamic range */
00987     if (block_num == 0) {
00988         /* for block 0, even if no coupling, we must say it. This is a
00989            waste of bit :-) */
00990         put_bits(&s->pb, 1, 1); /* coupling strategy present */
00991         put_bits(&s->pb, 1, 0); /* no coupling strategy */
00992     } else {
00993         put_bits(&s->pb, 1, 0); /* no new coupling strategy */
00994     }
00995 
00996     if (s->acmod == 2)
00997       {
00998         if(block_num==0)
00999           {
01000             /* first block must define rematrixing (rematstr)  */
01001             put_bits(&s->pb, 1, 1); 
01002             
01003             /* dummy rematrixing rematflg(1:4)=0 */
01004             for (rbnd=0;rbnd<4;rbnd++)
01005               put_bits(&s->pb, 1, 0); 
01006           }
01007         else 
01008           {
01009             /* no matrixing (but should be used in the future) */
01010             put_bits(&s->pb, 1, 0);
01011           } 
01012       }
01013 
01014 #if defined(DEBUG) 
01015     {
01016       static int count = 0;
01017       av_log(NULL, AV_LOG_DEBUG, "Block #%d (%d)\n", block_num, count++);
01018     }
01019 #endif
01020     /* exponent strategy */
01021     for(ch=0;ch<s->nb_channels;ch++) {
01022         put_bits(&s->pb, 2, exp_strategy[ch]);
01023     }
01024     
01025     if (s->lfe) {
01026         put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
01027     }
01028 
01029     for(ch=0;ch<s->nb_channels;ch++) {
01030         if (exp_strategy[ch] != EXP_REUSE)
01031             put_bits(&s->pb, 6, s->chbwcod[ch]);
01032     }
01033     
01034     /* exponents */
01035     for (ch = 0; ch < s->nb_all_channels; ch++) {
01036         switch(exp_strategy[ch]) {
01037         case EXP_REUSE:
01038             continue;
01039         case EXP_D15:
01040             group_size = 1;
01041             break;
01042         case EXP_D25:
01043             group_size = 2;
01044             break;
01045         default:
01046         case EXP_D45:
01047             group_size = 4;
01048             break;
01049         }
01050         nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
01051         p = encoded_exp[ch];
01052 
01053         /* first exponent */
01054         exp1 = *p++;
01055         put_bits(&s->pb, 4, exp1);
01056 
01057         /* next ones are delta encoded */
01058         for(i=0;i<nb_groups;i++) {
01059             /* merge three delta in one code */
01060             exp0 = exp1;
01061             exp1 = p[0];
01062             p += group_size;
01063             delta0 = exp1 - exp0 + 2;
01064 
01065             exp0 = exp1;
01066             exp1 = p[0];
01067             p += group_size;
01068             delta1 = exp1 - exp0 + 2;
01069 
01070             exp0 = exp1;
01071             exp1 = p[0];
01072             p += group_size;
01073             delta2 = exp1 - exp0 + 2;
01074 
01075             put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
01076         }
01077 
01078         if (ch != s->lfe_channel)
01079             put_bits(&s->pb, 2, 0); /* no gain range info */
01080     }
01081 
01082     /* bit allocation info */
01083     baie = (block_num == 0);
01084     put_bits(&s->pb, 1, baie);
01085     if (baie) {
01086         put_bits(&s->pb, 2, s->sdecaycod);
01087         put_bits(&s->pb, 2, s->fdecaycod);
01088         put_bits(&s->pb, 2, s->sgaincod);
01089         put_bits(&s->pb, 2, s->dbkneecod);
01090         put_bits(&s->pb, 3, s->floorcod);
01091     }
01092 
01093     /* snr offset */
01094     put_bits(&s->pb, 1, baie); /* always present with bai */
01095     if (baie) {
01096         put_bits(&s->