2 * The simplest AC3 encoder
3 * Copyright (c) 2000 Fabrice Bellard.
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.
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.
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
20 //#define DEBUG_BITALLOC
28 #define N (1 << MDCT_NBITS)
29 #define NB_BLOCKS 6 /* number of PCM blocks inside an AC3 frame */
31 /* new exponents are sent if their Norm 1 exceed this number */
32 #define EXP_DIFF_THRESHOLD 1000
34 /* exponent encoding strategy */
42 static void fft_init(int ln);
43 static void ac3_crc_init(void);
45 static inline INT16 fix15(float a)
48 v = (int)(a * (float)(1 << 15));
56 static inline int calc_lowcomp1(int a, int b0, int b1)
58 if ((b0 + 256) == b1) {
67 static inline int calc_lowcomp(int a, int b0, int b1, int bin)
70 if ((b0 + 256) == b1) {
76 } else if (bin < 20) {
77 if ((b0 + 256) == b1) {
90 /* AC3 bit allocation. The algorithm is the one described in the AC3
91 spec with some optimizations because of our simplified encoding
93 void parametric_bit_allocation(AC3EncodeContext *s, UINT8 *bap,
94 INT8 *exp, int start, int end,
95 int snroffset, int fgain, int is_lfe)
97 int bin,i,j,k,end1,v,v1,bndstrt,bndend,lowcomp,begin;
98 int fastleak,slowleak,address,tmp;
99 INT16 psd[256]; /* scaled exponents */
100 INT16 bndpsd[50]; /* interpolated exponents */
101 INT16 excite[50]; /* excitation */
102 INT16 mask[50]; /* masking value */
104 /* exponent mapping to PSD */
105 for(bin=start;bin<end;bin++) {
106 psd[bin]=(3072 - (exp[bin] << 7));
109 /* PSD integration */
116 if (end1 > end) end1=end;
117 for(i=j;i<end1;i++) {
124 if (adr > 255) adr=255;
128 if (adr > 255) adr=255;
135 } while (end > bndtab[k]);
137 /* excitation function */
138 bndstrt = masktab[start];
139 bndend = masktab[end-1] + 1;
142 lowcomp = calc_lowcomp1(lowcomp, bndpsd[0], bndpsd[1]) ;
143 excite[0] = bndpsd[0] - fgain - lowcomp ;
144 lowcomp = calc_lowcomp1(lowcomp, bndpsd[1], bndpsd[2]) ;
145 excite[1] = bndpsd[1] - fgain - lowcomp ;
147 for (bin = 2; bin < 7; bin++) {
148 if (!(is_lfe && bin == 6))
149 lowcomp = calc_lowcomp1(lowcomp, bndpsd[bin], bndpsd[bin+1]) ;
150 fastleak = bndpsd[bin] - fgain ;
151 slowleak = bndpsd[bin] - s->sgain ;
152 excite[bin] = fastleak - lowcomp ;
153 if (!(is_lfe && bin == 6)) {
154 if (bndpsd[bin] <= bndpsd[bin+1]) {
162 if (end1 > 22) end1=22;
164 for (bin = begin; bin < end1; bin++) {
165 if (!(is_lfe && bin == 6))
166 lowcomp = calc_lowcomp(lowcomp, bndpsd[bin], bndpsd[bin+1], bin) ;
168 fastleak -= s->fdecay ;
169 v = bndpsd[bin] - fgain;
170 if (fastleak < v) fastleak = v;
172 slowleak -= s->sdecay ;
173 v = bndpsd[bin] - s->sgain;
174 if (slowleak < v) slowleak = v;
176 v=fastleak - lowcomp;
177 if (slowleak > v) v=slowleak;
182 for (bin = 22; bin < bndend; bin++) {
183 fastleak -= s->fdecay ;
184 v = bndpsd[bin] - fgain;
185 if (fastleak < v) fastleak = v;
186 slowleak -= s->sdecay ;
187 v = bndpsd[bin] - s->sgain;
188 if (slowleak < v) slowleak = v;
191 if (slowleak > v) v = slowleak;
195 /* compute masking curve */
197 for (bin = bndstrt; bin < bndend; bin++) {
199 tmp = s->dbknee - bndpsd[bin];
203 v=hth[bin >> s->halfratecod][s->fscod];
208 /* compute bit allocation */
220 end1=bndtab[j] + bndsz[j];
221 if (end1 > end) end1=end;
223 for (k = i; k < end1; k++) {
224 address = (psd[i] - v) >> 5 ;
225 if (address < 0) address=0;
226 else if (address > 63) address=63;
227 bap[i] = baptab[address];
230 } while (end > bndtab[j++]) ;
233 typedef struct IComplex {
237 static void fft_init(int ln)
244 for(i=0;i<(n/2);i++) {
245 alpha = 2 * M_PI * (float)i / (float)n;
246 costab[i] = fix15(cos(alpha));
247 sintab[i] = fix15(sin(alpha));
253 m |= ((i >> j) & 1) << (ln-j-1);
260 #define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1) \
267 pre = (bx + ax) >> 1;\
268 pim = (by + ay) >> 1;\
269 qre = (bx - ax) >> 1;\
270 qim = (by - ay) >> 1;\
273 #define MUL16(a,b) ((a) * (b))
275 #define CMUL(pre, pim, are, aim, bre, bim) \
277 pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;\
278 pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;\
282 /* do a 2^n point complex fft on 2^ln points. */
283 static void fft(IComplex *z, int ln)
287 register IComplex *p,*q;
309 BF(p[0].re, p[0].im, p[1].re, p[1].im,
310 p[0].re, p[0].im, p[1].re, p[1].im);
319 BF(p[0].re, p[0].im, p[2].re, p[2].im,
320 p[0].re, p[0].im, p[2].re, p[2].im);
321 BF(p[1].re, p[1].im, p[3].re, p[3].im,
322 p[1].re, p[1].im, p[3].im, -p[3].re);
334 for (j = 0; j < nblocks; ++j) {
336 BF(p->re, p->im, q->re, q->im,
337 p->re, p->im, q->re, q->im);
341 for(l = nblocks; l < np2; l += nblocks) {
342 CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
343 BF(p->re, p->im, q->re, q->im,
344 p->re, p->im, tmp_re, tmp_im);
351 nblocks = nblocks >> 1;
352 nloops = nloops << 1;
353 } while (nblocks != 0);
356 /* do a 512 point mdct */
357 static void mdct512(INT32 *out, INT16 *in)
359 int i, re, im, re1, im1;
363 /* shift to simplify computations */
365 rot[i] = -in[i + 3*N/4];
367 rot[i] = in[i - N/4];
371 re = ((int)rot[2*i] - (int)rot[N-1-2*i]) >> 1;
372 im = -((int)rot[N/2+2*i] - (int)rot[N/2-1-2*i]) >> 1;
373 CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
376 fft(x, MDCT_NBITS - 2);
382 CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
384 out[N/2-1-2*i] = re1;
388 /* XXX: use another norm ? */
389 static int calc_exp_diff(UINT8 *exp1, UINT8 *exp2, int n)
394 sum += abs(exp1[i] - exp2[i]);
399 static void compute_exp_strategy(UINT8 exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
400 UINT8 exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
406 /* estimate if the exponent variation & decide if they should be
407 reused in the next frame */
408 exp_strategy[0][ch] = EXP_NEW;
409 for(i=1;i<NB_BLOCKS;i++) {
410 exp_diff = calc_exp_diff(exp[i][ch], exp[i-1][ch], N/2);
412 printf("exp_diff=%d\n", exp_diff);
414 if (exp_diff > EXP_DIFF_THRESHOLD)
415 exp_strategy[i][ch] = EXP_NEW;
417 exp_strategy[i][ch] = EXP_REUSE;
422 /* now select the encoding strategy type : if exponents are often
423 recoded, we use a coarse encoding */
425 while (i < NB_BLOCKS) {
427 while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE)
431 exp_strategy[i][ch] = EXP_D45;
435 exp_strategy[i][ch] = EXP_D25;
438 exp_strategy[i][ch] = EXP_D15;
445 /* set exp[i] to min(exp[i], exp1[i]) */
446 static void exponent_min(UINT8 exp[N/2], UINT8 exp1[N/2], int n)
451 if (exp1[i] < exp[i])
456 /* update the exponents so that they are the ones the decoder will
457 decode. Return the number of bits used to code the exponents */
458 static int encode_exp(UINT8 encoded_exp[N/2],
463 int group_size, nb_groups, i, j, k, recurse, exp_min, delta;
466 switch(exp_strategy) {
478 nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
480 /* for each group, compute the minimum exponent */
481 exp1[0] = exp[0]; /* DC exponent is handled separately */
483 for(i=1;i<=nb_groups;i++) {
485 assert(exp_min >= 0 && exp_min <= 24);
486 for(j=1;j<group_size;j++) {
487 if (exp[k+j] < exp_min)
494 /* constraint for DC exponent */
498 /* Iterate until the delta constraints between each groups are
499 satisfyed. I'm sure it is possible to find a better algorithm,
503 for(i=1;i<=nb_groups;i++) {
504 delta = exp1[i] - exp1[i-1];
506 /* if delta too big, we encode a smaller exponent */
507 exp1[i] = exp1[i-1] + 2;
508 } else if (delta < -2) {
509 /* if delta is too small, we must decrease the previous
510 exponent, which means we must recurse */
512 exp1[i-1] = exp1[i] + 2;
517 /* now we have the exponent values the decoder will see */
518 encoded_exp[0] = exp1[0];
520 for(i=1;i<=nb_groups;i++) {
521 for(j=0;j<group_size;j++) {
522 encoded_exp[k+j] = exp1[i];
528 printf("exponents: strategy=%d\n", exp_strategy);
529 for(i=0;i<=nb_groups * group_size;i++) {
530 printf("%d ", encoded_exp[i]);
535 return 4 + (nb_groups / 3) * 7;
538 /* return the size in bits taken by the mantissa */
539 int compute_mantissa_size(AC3EncodeContext *s, UINT8 *m, int nb_coefs)
544 for(i=0;i<nb_coefs;i++) {
551 /* 3 mantissa in 5 bits */
552 if (s->mant1_cnt == 0)
554 if (++s->mant1_cnt == 3)
558 /* 3 mantissa in 7 bits */
559 if (s->mant2_cnt == 0)
561 if (++s->mant2_cnt == 3)
568 /* 2 mantissa in 7 bits */
569 if (s->mant4_cnt == 0)
571 if (++s->mant4_cnt == 2)
589 static int bit_alloc(AC3EncodeContext *s,
590 UINT8 bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
591 UINT8 encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
592 UINT8 exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
593 int frame_bits, int csnroffst, int fsnroffst)
598 for(i=0;i<NB_BLOCKS;i++) {
602 for(ch=0;ch<s->nb_all_channels;ch++) {
603 parametric_bit_allocation(s, bap[i][ch], (INT8 *)encoded_exp[i][ch],
605 (((csnroffst-15) << 4) +
607 fgaintab[s->fgaincod[ch]],
608 ch == s->lfe_channel);
609 frame_bits += compute_mantissa_size(s, bap[i][ch],
614 printf("csnr=%d fsnr=%d frame_bits=%d diff=%d\n",
615 csnroffst, fsnroffst, frame_bits,
616 16 * s->frame_size - ((frame_bits + 7) & ~7));
618 return 16 * s->frame_size - frame_bits;
623 static int compute_bit_allocation(AC3EncodeContext *s,
624 UINT8 bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
625 UINT8 encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
626 UINT8 exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
630 int csnroffst, fsnroffst;
631 UINT8 bap1[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
632 static int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
634 /* init default parameters */
640 for(ch=0;ch<s->nb_all_channels;ch++)
643 /* compute real values */
644 s->sdecay = sdecaytab[s->sdecaycod] >> s->halfratecod;
645 s->fdecay = fdecaytab[s->fdecaycod] >> s->halfratecod;
646 s->sgain = sgaintab[s->sgaincod];
647 s->dbknee = dbkneetab[s->dbkneecod];
648 s->floor = floortab[s->floorcod];
652 // if (s->acmod == 2)
654 frame_bits += frame_bits_inc[s->acmod];
657 for(i=0;i<NB_BLOCKS;i++) {
658 frame_bits += s->nb_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
660 frame_bits++; /* rematstr */
661 frame_bits += 2 * s->nb_channels; /* chexpstr[2] * c */
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] */
668 frame_bits++; /* baie */
669 frame_bits++; /* snr */
670 frame_bits += 2; /* delta / skip */
672 frame_bits++; /* cplinu for block 0 */
674 /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
676 /* (fsnoffset[4] + fgaincod[4]) * c */
677 frame_bits += 2*4 + 3 + 6 + s->nb_all_channels * (4 + 3);
682 /* now the big work begins : do the bit allocation. Modify the snr
683 offset until we can pack everything in the requested frame size */
685 csnroffst = s->csnroffst;
686 while (csnroffst >= 0 &&
687 bit_alloc(s, bap, encoded_exp, exp_strategy, frame_bits, csnroffst, 0) < 0)
688 csnroffst -= SNR_INC1;
690 fprintf(stderr, "Yack, Error !!!\n");
693 while ((csnroffst + SNR_INC1) <= 63 &&
694 bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits,
695 csnroffst + SNR_INC1, 0) >= 0) {
696 csnroffst += SNR_INC1;
697 memcpy(bap, bap1, sizeof(bap1));
699 while ((csnroffst + 1) <= 63 &&
700 bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits, csnroffst + 1, 0) >= 0) {
702 memcpy(bap, bap1, sizeof(bap1));
706 while ((fsnroffst + SNR_INC1) <= 15 &&
707 bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits,
708 csnroffst, fsnroffst + SNR_INC1) >= 0) {
709 fsnroffst += SNR_INC1;
710 memcpy(bap, bap1, sizeof(bap1));
712 while ((fsnroffst + 1) <= 15 &&
713 bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits,
714 csnroffst, fsnroffst + 1) >= 0) {
716 memcpy(bap, bap1, sizeof(bap1));
719 s->csnroffst = csnroffst;
720 for(ch=0;ch<s->nb_all_channels;ch++)
721 s->fsnroffst[ch] = fsnroffst;
722 #if defined(DEBUG_BITALLOC)
727 for(ch=0;ch<s->nb_all_channels;ch++) {
728 printf("Block #%d Ch%d:\n", i, ch);
730 for(j=0;j<s->nb_coefs[ch];j++) {
731 printf("%d ",bap[i][ch][j]);
741 static int AC3_encode_init(AVCodecContext *avctx)
743 int freq = avctx->sample_rate;
744 int bitrate = avctx->bit_rate;
745 int channels = avctx->channels;
746 AC3EncodeContext *s = avctx->priv_data;
747 int i, j, k, l, ch, v;
749 static unsigned short freqs[3] = { 48000, 44100, 32000 };
750 static int acmod_defs[6] = {
754 0x06, /* L R SL SR */
755 0x07, /* L C R SL SR */
756 0x07, /* L C R SL SR (+LFE) */
759 avctx->frame_size = AC3_FRAME_SIZE;
760 avctx->key_frame = 1; /* always key frame */
762 /* number of channels */
763 if (channels < 1 || channels > 6)
765 s->acmod = acmod_defs[channels - 1];
766 s->lfe = (channels == 6) ? 1 : 0;
767 s->nb_all_channels = channels;
768 s->nb_channels = channels > 5 ? 5 : channels;
769 s->lfe_channel = s->lfe ? 5 : -1;
774 if ((freqs[j] >> i) == freq)
779 s->sample_rate = freq;
782 s->bsid = 8 + s->halfratecod;
783 s->bsmod = 0; /* complete main audio service */
785 /* bitrate & frame size */
788 if ((bitratetab[i] >> s->halfratecod) == bitrate)
793 s->bit_rate = bitrate;
794 s->frmsizecod = i << 1;
795 s->frame_size_min = (bitrate * 1000 * AC3_FRAME_SIZE) / (freq * 16);
796 /* for now we do not handle fractional sizes */
797 s->frame_size = s->frame_size_min;
799 /* bit allocation init */
800 for(ch=0;ch<s->nb_channels;ch++) {
801 /* bandwidth for each channel */
802 /* XXX: should compute the bandwidth according to the frame
803 size, so that we avoid anoying high freq artefacts */
804 s->chbwcod[ch] = 50; /* sample bandwidth as mpeg audio layer 2 table 0 */
805 s->nb_coefs[ch] = ((s->chbwcod[ch] + 12) * 3) + 37;
808 s->nb_coefs[s->lfe_channel] = 7; /* fixed */
810 /* initial snr offset */
813 /* compute bndtab and masktab from bandsz */
819 for(j=0;j<v;j++) masktab[k++]=i;
825 fft_init(MDCT_NBITS - 2);
827 alpha = 2 * M_PI * (i + 1.0 / 8.0) / (float)N;
828 xcos1[i] = fix15(-cos(alpha));
829 xsin1[i] = fix15(-sin(alpha));
837 /* output the AC3 frame header */
838 static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
840 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE, NULL, NULL);
842 put_bits(&s->pb, 16, 0x0b77); /* frame header */
843 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
844 put_bits(&s->pb, 2, s->fscod);
845 put_bits(&s->pb, 6, s->frmsizecod + (s->frame_size - s->frame_size_min));
846 put_bits(&s->pb, 5, s->bsid);
847 put_bits(&s->pb, 3, s->bsmod);
848 put_bits(&s->pb, 3, s->acmod);
849 if ((s->acmod & 0x01) && s->acmod != 0x01)
850 put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
852 put_bits(&s->pb, 2, 1); /* XXX -6 dB */
853 if (s->acmod == 0x02)
854 put_bits(&s->pb, 2, 0); /* surround not indicated */
855 put_bits(&s->pb, 1, s->lfe); /* LFE */
856 put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
857 put_bits(&s->pb, 1, 0); /* no compression control word */
858 put_bits(&s->pb, 1, 0); /* no lang code */
859 put_bits(&s->pb, 1, 0); /* no audio production info */
860 put_bits(&s->pb, 1, 0); /* no copyright */
861 put_bits(&s->pb, 1, 1); /* original bitstream */
862 put_bits(&s->pb, 1, 0); /* no time code 1 */
863 put_bits(&s->pb, 1, 0); /* no time code 2 */
864 put_bits(&s->pb, 1, 0); /* no addtional bit stream info */
867 /* symetric quantization on 'levels' levels */
868 static inline int sym_quant(int c, int e, int levels)
873 v = (levels * (c << e)) >> 24;
875 v = (levels >> 1) + v;
877 v = (levels * ((-c) << e)) >> 24;
879 v = (levels >> 1) - v;
881 assert (v >= 0 && v < levels);
885 /* asymetric quantization on 2^qbits levels */
886 static inline int asym_quant(int c, int e, int qbits)
890 lshift = e + qbits - 24;
897 m = (1 << (qbits-1));
901 return v & ((1 << qbits)-1);
904 /* Output one audio block. There are NB_BLOCKS audio blocks in one AC3
906 static void output_audio_block(AC3EncodeContext *s,
907 UINT8 exp_strategy[AC3_MAX_CHANNELS],
908 UINT8 encoded_exp[AC3_MAX_CHANNELS][N/2],
909 UINT8 bap[AC3_MAX_CHANNELS][N/2],
910 INT32 mdct_coefs[AC3_MAX_CHANNELS][N/2],
911 INT8 global_exp[AC3_MAX_CHANNELS],
914 int ch, nb_groups, group_size, i, baie;
916 UINT16 qmant[AC3_MAX_CHANNELS][N/2];
918 int mant1_cnt, mant2_cnt, mant4_cnt;
919 UINT16 *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
920 int delta0, delta1, delta2;
922 for(ch=0;ch<s->nb_channels;ch++)
923 put_bits(&s->pb, 1, 0); /* 512 point MDCT */
924 for(ch=0;ch<s->nb_channels;ch++)
925 put_bits(&s->pb, 1, 1); /* no dither */
926 put_bits(&s->pb, 1, 0); /* no dynamic range */
927 if (block_num == 0) {
928 /* for block 0, even if no coupling, we must say it. This is a
930 put_bits(&s->pb, 1, 1); /* coupling strategy present */
931 put_bits(&s->pb, 1, 0); /* no coupling strategy */
933 put_bits(&s->pb, 1, 0); /* no new coupling strategy */
937 put_bits(&s->pb, 1, 0); /* no matrixing (but should be used in the future) */
942 static int count = 0;
943 printf("Block #%d (%d)\n", block_num, count++);
946 /* exponent strategy */
947 for(ch=0;ch<s->nb_channels;ch++) {
948 put_bits(&s->pb, 2, exp_strategy[ch]);
952 put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
955 for(ch=0;ch<s->nb_channels;ch++) {
956 if (exp_strategy[ch] != EXP_REUSE)
957 put_bits(&s->pb, 6, s->chbwcod[ch]);
961 for (ch = 0; ch < s->nb_all_channels; ch++) {
962 switch(exp_strategy[ch]) {
976 nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
981 put_bits(&s->pb, 4, exp1);
983 /* next ones are delta encoded */
984 for(i=0;i<nb_groups;i++) {
985 /* merge three delta in one code */
989 delta0 = exp1 - exp0 + 2;
994 delta1 = exp1 - exp0 + 2;
999 delta2 = exp1 - exp0 + 2;
1001 put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
1004 if (ch != s->lfe_channel)
1005 put_bits(&s->pb, 2, 0); /* no gain range info */
1008 /* bit allocation info */
1009 baie = (block_num == 0);
1010 put_bits(&s->pb, 1, baie);
1012 put_bits(&s->pb, 2, s->sdecaycod);
1013 put_bits(&s->pb, 2, s->fdecaycod);
1014 put_bits(&s->pb, 2, s->sgaincod);
1015 put_bits(&s->pb, 2, s->dbkneecod);
1016 put_bits(&s->pb, 3, s->floorcod);
1020 put_bits(&s->pb, 1, baie); /* always present with bai */
1022 put_bits(&s->pb, 6, s->csnroffst);
1023 for(ch=0;ch<s->nb_all_channels;ch++) {
1024 put_bits(&s->pb, 4, s->fsnroffst[ch]);
1025 put_bits(&s->pb, 3, s->fgaincod[ch]);
1029 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1030 put_bits(&s->pb, 1, 0); /* no data to skip */
1032 /* mantissa encoding : we use two passes to handle the grouping. A
1033 one pass method may be faster, but it would necessitate to
1034 modify the output stream. */
1036 /* first pass: quantize */
1037 mant1_cnt = mant2_cnt = mant4_cnt = 0;
1038 qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
1040 for (ch = 0; ch < s->nb_all_channels; ch++) {
1043 for(i=0;i<s->nb_coefs[ch];i++) {
1044 c = mdct_coefs[ch][i];
1045 e = encoded_exp[ch][i] - global_exp[ch];
1052 v = sym_quant(c, e, 3);
1055 qmant1_ptr = &qmant[ch][i];
1060 *qmant1_ptr += 3 * v;
1072 v = sym_quant(c, e, 5);
1075 qmant2_ptr = &qmant[ch][i];
1080 *qmant2_ptr += 5 * v;
1092 v = sym_quant(c, e, 7);
1095 v = sym_quant(c, e, 11);
1098 qmant4_ptr = &qmant[ch][i];
1110 v = sym_quant(c, e, 15);
1113 v = asym_quant(c, e, 14);
1116 v = asym_quant(c, e, 16);
1119 v = asym_quant(c, e, b - 1);
1126 /* second pass : output the values */
1127 for (ch = 0; ch < s->nb_all_channels; ch++) {
1130 for(i=0;i<s->nb_coefs[ch];i++) {
1138 put_bits(&s->pb, 5, q);
1142 put_bits(&s->pb, 7, q);
1145 put_bits(&s->pb, 3, q);
1149 put_bits(&s->pb, 7, q);
1152 put_bits(&s->pb, 14, q);
1155 put_bits(&s->pb, 16, q);
1158 put_bits(&s->pb, b - 1, q);
1165 /* compute the ac3 crc */
1167 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1169 static void ac3_crc_init(void)
1171 unsigned int c, n, k;
1173 for(n=0;n<256;n++) {
1175 for (k = 0; k < 8; k++) {
1177 c = ((c << 1) & 0xffff) ^ (CRC16_POLY & 0xffff);
1185 static unsigned int ac3_crc(UINT8 *data, int n, unsigned int crc)
1189 crc = (crc_table[data[i] ^ (crc >> 8)] ^ (crc << 8)) & 0xffff;
1194 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1210 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1216 r = mul_poly(r, a, poly);
1217 a = mul_poly(a, a, poly);
1224 /* compute log2(max(abs(tab[]))) */
1225 static int log2_tab(INT16 *tab, int n)
1236 static void lshift_tab(INT16 *tab, int n, int lshift)
1244 } else if (lshift < 0) {
1252 /* fill the end of the frame and compute the two crcs */
1253 static int output_frame_end(AC3EncodeContext *s)
1255 int frame_size, frame_size_58, n, crc1, crc2, crc_inv;
1258 frame_size = s->frame_size; /* frame size in words */
1259 /* align to 8 bits */
1260 flush_put_bits(&s->pb);
1261 /* add zero bytes to reach the frame size */
1263 n = 2 * s->frame_size - (pbBufPtr(&s->pb) - frame) - 2;
1265 memset(pbBufPtr(&s->pb), 0, n);
1267 /* Now we must compute both crcs : this is not so easy for crc1
1268 because it is at the beginning of the data... */
1269 frame_size_58 = (frame_size >> 1) + (frame_size >> 3);
1270 crc1 = ac3_crc(frame + 4, (2 * frame_size_58) - 4, 0);
1271 /* XXX: could precompute crc_inv */
1272 crc_inv = pow_poly((CRC16_POLY >> 1), (16 * frame_size_58) - 16, CRC16_POLY);
1273 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1274 frame[2] = crc1 >> 8;
1277 crc2 = ac3_crc(frame + 2 * frame_size_58, (frame_size - frame_size_58) * 2 - 2, 0);
1278 frame[2*frame_size - 2] = crc2 >> 8;
1279 frame[2*frame_size - 1] = crc2;
1281 // printf("n=%d frame_size=%d\n", n, frame_size);
1282 return frame_size * 2;
1285 int AC3_encode_frame(AVCodecContext *avctx,
1286 unsigned char *frame, int buf_size, void *data)
1288 AC3EncodeContext *s = avctx->priv_data;
1289 short *samples = data;
1291 INT16 input_samples[N];
1292 INT32 mdct_coef[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1293 UINT8 exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1294 UINT8 exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS];
1295 UINT8 encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1296 UINT8 bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1297 INT8 exp_samples[NB_BLOCKS][AC3_MAX_CHANNELS];
1301 for(ch=0;ch<s->nb_all_channels;ch++) {
1302 /* fixed mdct to the six sub blocks & exponent computation */
1303 for(i=0;i<NB_BLOCKS;i++) {
1307 /* compute input samples */
1308 memcpy(input_samples, s->last_samples[ch], N/2 * sizeof(INT16));
1309 sinc = s->nb_all_channels;
1310 sptr = samples + (sinc * (N/2) * i) + ch;
1311 for(j=0;j<N/2;j++) {
1313 input_samples[j + N/2] = v;
1314 s->last_samples[ch][j] = v;
1318 /* apply the MDCT window */
1319 for(j=0;j<N/2;j++) {
1320 input_samples[j] = MUL16(input_samples[j],
1321 ac3_window[j]) >> 15;
1322 input_samples[N-j-1] = MUL16(input_samples[N-j-1],
1323 ac3_window[j]) >> 15;
1326 /* Normalize the samples to use the maximum available
1328 v = 14 - log2_tab(input_samples, N);
1331 exp_samples[i][ch] = v - 8;
1332 lshift_tab(input_samples, N, v);
1335 mdct512(mdct_coef[i][ch], input_samples);
1337 /* compute "exponents". We take into account the
1338 normalization there */
1339 for(j=0;j<N/2;j++) {
1341 v = abs(mdct_coef[i][ch][j]);
1345 e = 23 - av_log2(v) + exp_samples[i][ch];
1348 mdct_coef[i][ch][j] = 0;
1355 compute_exp_strategy(exp_strategy, exp, ch, ch == s->lfe_channel);
1357 /* compute the exponents as the decoder will see them. The
1358 EXP_REUSE case must be handled carefully : we select the
1359 min of the exponents */
1361 while (i < NB_BLOCKS) {
1363 while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE) {
1364 exponent_min(exp[i][ch], exp[j][ch], s->nb_coefs[ch]);
1367 frame_bits += encode_exp(encoded_exp[i][ch],
1368 exp[i][ch], s->nb_coefs[ch],
1369 exp_strategy[i][ch]);
1370 /* copy encoded exponents for reuse case */
1371 for(k=i+1;k<j;k++) {
1372 memcpy(encoded_exp[k][ch], encoded_exp[i][ch],
1373 s->nb_coefs[ch] * sizeof(UINT8));
1379 compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
1380 /* everything is known... let's output the frame */
1381 output_frame_header(s, frame);
1383 for(i=0;i<NB_BLOCKS;i++) {
1384 output_audio_block(s, exp_strategy[i], encoded_exp[i],
1385 bap[i], mdct_coef[i], exp_samples[i], i);
1387 return output_frame_end(s);
1391 /*************************************************************************/
1398 IComplex in[FN], in1[FN];
1400 float sum_re, sum_im, a;
1405 in[i].re = random() % 65535 - 32767;
1406 in[i].im = random() % 65535 - 32767;
1416 a = -2 * M_PI * (n * k) / FN;
1417 sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1418 sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1420 printf("%3d: %6d,%6d %6.0f,%6.0f\n",
1421 k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1425 void mdct_test(void)
1431 float s, a, err, e, emax;
1435 input[i] = (random() % 65535 - 32767) * 9 / 10;
1436 input1[i] = input[i];
1439 mdct512(output, input);
1442 for(k=0;k<N/2;k++) {
1445 a = (2*M_PI*(2*n+1+N/2)*(2*k+1) / (4 * N));
1446 s += input1[n] * cos(a);
1448 output1[k] = -2 * s / N;
1453 for(i=0;i<N/2;i++) {
1454 printf("%3d: %7d %7.0f\n", i, output[i], output1[i]);
1455 e = output[i] - output1[i];
1460 printf("err2=%f emax=%f\n", err / (N/2), emax);
1465 AC3EncodeContext ctx;
1466 unsigned char frame[AC3_MAX_CODED_FRAME_SIZE];
1467 short samples[AC3_FRAME_SIZE];
1470 AC3_encode_init(&ctx, 44100, 64000, 1);
1475 for(i=0;i<AC3_FRAME_SIZE;i++)
1476 samples[i] = (int)(sin(2*M_PI*i*1000.0/44100) * 10000);
1477 ret = AC3_encode_frame(&ctx, frame, samples);
1478 printf("ret=%d\n", ret);
1482 AVCodec ac3_encoder = {
1486 sizeof(AC3EncodeContext),