2 * The simplest AC3 encoder
3 * Copyright (c) 2000 Gerard Lantau.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 //#define DEBUG_BITALLOC
34 #define N (1 << MDCT_NBITS)
35 #define NB_BLOCKS 6 /* number of PCM blocks inside an AC3 frame */
37 /* new exponents are sent if their Norm 1 exceed this number */
38 #define EXP_DIFF_THRESHOLD 1000
40 /* exponent encoding strategy */
48 static void fft_init(int ln);
49 static void ac3_crc_init(void);
51 static inline INT16 fix15(float a)
54 v = (int)(a * (float)(1 << 15));
62 static inline int calc_lowcomp1(int a, int b0, int b1)
64 if ((b0 + 256) == b1) {
73 static inline int calc_lowcomp(int a, int b0, int b1, int bin)
76 if ((b0 + 256) == b1) {
82 } else if (bin < 20) {
83 if ((b0 + 256) == b1) {
96 /* AC3 bit allocation. The algorithm is the one described in the AC3
97 spec with some optimizations because of our simplified encoding
99 void parametric_bit_allocation(AC3EncodeContext *s, UINT8 *bap,
100 INT8 *exp, int start, int end,
101 int snroffset, int fgain)
103 int bin,i,j,k,end1,v,v1,bndstrt,bndend,lowcomp,begin;
104 int fastleak,slowleak,address,tmp;
105 INT16 psd[256]; /* scaled exponents */
106 INT16 bndpsd[50]; /* interpolated exponents */
107 INT16 excite[50]; /* excitation */
108 INT16 mask[50]; /* masking value */
110 /* exponent mapping to PSD */
111 for(bin=start;bin<end;bin++) {
112 psd[bin]=(3072 - (exp[bin] << 7));
115 /* PSD integration */
122 if (end1 > end) end1=end;
123 for(i=j;i<end1;i++) {
130 if (adr > 255) adr=255;
134 if (adr > 255) adr=255;
141 } while (end > bndtab[k]);
143 /* excitation function */
144 bndstrt = masktab[start];
145 bndend = masktab[end-1] + 1;
148 lowcomp = calc_lowcomp1(lowcomp, bndpsd[0], bndpsd[1]) ;
149 excite[0] = bndpsd[0] - fgain - lowcomp ;
150 lowcomp = calc_lowcomp1(lowcomp, bndpsd[1], bndpsd[2]) ;
151 excite[1] = bndpsd[1] - fgain - lowcomp ;
153 for (bin = 2; bin < 7; bin++) {
154 lowcomp = calc_lowcomp1(lowcomp, bndpsd[bin], bndpsd[bin+1]) ;
155 fastleak = bndpsd[bin] - fgain ;
156 slowleak = bndpsd[bin] - s->sgain ;
157 excite[bin] = fastleak - lowcomp ;
158 if (bndpsd[bin] <= bndpsd[bin+1]) {
165 if (end1 > 22) end1=22;
167 for (bin = begin; bin < end1; bin++) {
168 lowcomp = calc_lowcomp(lowcomp, bndpsd[bin], bndpsd[bin+1], bin) ;
170 fastleak -= s->fdecay ;
171 v = bndpsd[bin] - fgain;
172 if (fastleak < v) fastleak = v;
174 slowleak -= s->sdecay ;
175 v = bndpsd[bin] - s->sgain;
176 if (slowleak < v) slowleak = v;
178 v=fastleak - lowcomp;
179 if (slowleak > v) v=slowleak;
184 for (bin = 22; bin < bndend; bin++) {
185 fastleak -= s->fdecay ;
186 v = bndpsd[bin] - fgain;
187 if (fastleak < v) fastleak = v;
188 slowleak -= s->sdecay ;
189 v = bndpsd[bin] - s->sgain;
190 if (slowleak < v) slowleak = v;
193 if (slowleak > v) v = slowleak;
197 /* compute masking curve */
199 for (bin = bndstrt; bin < bndend; bin++) {
201 tmp = s->dbknee - bndpsd[bin];
205 v=hth[bin >> s->halfratecod][s->fscod];
210 /* compute bit allocation */
222 end1=bndtab[j] + bndsz[j];
223 if (end1 > end) end1=end;
225 for (k = i; k < end1; k++) {
226 address = (psd[i] - v) >> 5 ;
227 if (address < 0) address=0;
228 else if (address > 63) address=63;
229 bap[i] = baptab[address];
232 } while (end > bndtab[j++]) ;
235 typedef struct IComplex {
239 static void fft_init(int ln)
246 for(i=0;i<(n/2);i++) {
247 alpha = 2 * M_PI * (float)i / (float)n;
248 costab[i] = fix15(cos(alpha));
249 sintab[i] = fix15(sin(alpha));
255 m |= ((i >> j) & 1) << (ln-j-1);
262 #define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1) \
269 pre = (bx + ax) >> 1;\
270 pim = (by + ay) >> 1;\
271 qre = (bx - ax) >> 1;\
272 qim = (by - ay) >> 1;\
275 #define MUL16(a,b) ((a) * (b))
277 #define CMUL(pre, pim, are, aim, bre, bim) \
279 pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;\
280 pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;\
284 /* do a 2^n point complex fft on 2^ln points. */
285 static void fft(IComplex *z, int ln)
289 register IComplex *p,*q;
311 BF(p[0].re, p[0].im, p[1].re, p[1].im,
312 p[0].re, p[0].im, p[1].re, p[1].im);
321 BF(p[0].re, p[0].im, p[2].re, p[2].im,
322 p[0].re, p[0].im, p[2].re, p[2].im);
323 BF(p[1].re, p[1].im, p[3].re, p[3].im,
324 p[1].re, p[1].im, p[3].im, -p[3].re);
336 for (j = 0; j < nblocks; ++j) {
338 BF(p->re, p->im, q->re, q->im,
339 p->re, p->im, q->re, q->im);
343 for(l = nblocks; l < np2; l += nblocks) {
344 CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
345 BF(p->re, p->im, q->re, q->im,
346 p->re, p->im, tmp_re, tmp_im);
353 nblocks = nblocks >> 1;
354 nloops = nloops << 1;
355 } while (nblocks != 0);
358 /* do a 512 point mdct */
359 static void mdct512(INT32 *out, INT16 *in)
361 int i, re, im, re1, im1;
365 /* shift to simplify computations */
367 rot[i] = -in[i + 3*N/4];
369 rot[i] = in[i - N/4];
373 re = ((int)rot[2*i] - (int)rot[N-1-2*i]) >> 1;
374 im = -((int)rot[N/2+2*i] - (int)rot[N/2-1-2*i]) >> 1;
375 CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
378 fft(x, MDCT_NBITS - 2);
384 CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
386 out[N/2-1-2*i] = re1;
390 /* XXX: use another norm ? */
391 static int calc_exp_diff(UINT8 *exp1, UINT8 *exp2, int n)
396 sum += abs(exp1[i] - exp2[i]);
401 static void compute_exp_strategy(UINT8 exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
402 UINT8 exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
408 /* estimate if the exponent variation & decide if they should be
409 reused in the next frame */
410 exp_strategy[0][ch] = EXP_NEW;
411 for(i=1;i<NB_BLOCKS;i++) {
412 exp_diff = calc_exp_diff(exp[i][ch], exp[i-1][ch], N/2);
414 printf("exp_diff=%d\n", exp_diff);
416 if (exp_diff > EXP_DIFF_THRESHOLD)
417 exp_strategy[i][ch] = EXP_NEW;
419 exp_strategy[i][ch] = EXP_REUSE;
421 /* now select the encoding strategy type : if exponents are often
422 recoded, we use a coarse encoding */
424 while (i < NB_BLOCKS) {
426 while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE)
430 exp_strategy[i][ch] = EXP_D45;
434 exp_strategy[i][ch] = EXP_D25;
437 exp_strategy[i][ch] = EXP_D15;
444 /* set exp[i] to min(exp[i], exp1[i]) */
445 static void exponent_min(UINT8 exp[N/2], UINT8 exp1[N/2], int n)
450 if (exp1[i] < exp[i])
455 /* update the exponents so that they are the ones the decoder will
456 decode. Return the number of bits used to code the exponents */
457 static int encode_exp(UINT8 encoded_exp[N/2],
462 int group_size, nb_groups, i, j, k, recurse, exp_min, delta;
465 switch(exp_strategy) {
477 nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
479 /* for each group, compute the minimum exponent */
480 exp1[0] = exp[0]; /* DC exponent is handled separately */
482 for(i=1;i<=nb_groups;i++) {
484 assert(exp_min >= 0 && exp_min <= 24);
485 for(j=1;j<group_size;j++) {
486 if (exp[k+j] < exp_min)
493 /* constraint for DC exponent */
497 /* Iterate until the delta constraints between each groups are
498 satisfyed. I'm sure it is possible to find a better algorithm,
502 for(i=1;i<=nb_groups;i++) {
503 delta = exp1[i] - exp1[i-1];
505 /* if delta too big, we encode a smaller exponent */
506 exp1[i] = exp1[i-1] + 2;
507 } else if (delta < -2) {
508 /* if delta is too small, we must decrease the previous
509 exponent, which means we must recurse */
511 exp1[i-1] = exp1[i] + 2;
516 /* now we have the exponent values the decoder will see */
517 encoded_exp[0] = exp1[0];
519 for(i=1;i<=nb_groups;i++) {
520 for(j=0;j<group_size;j++) {
521 encoded_exp[k+j] = exp1[i];
527 printf("exponents: strategy=%d\n", exp_strategy);
528 for(i=0;i<=nb_groups * group_size;i++) {
529 printf("%d ", encoded_exp[i]);
534 return 4 + (nb_groups / 3) * 7;
537 /* return the size in bits taken by the mantissa */
538 int compute_mantissa_size(AC3EncodeContext *s, UINT8 *m, int nb_coefs)
543 for(i=0;i<nb_coefs;i++) {
550 /* 3 mantissa in 5 bits */
551 if (s->mant1_cnt == 0)
553 if (++s->mant1_cnt == 3)
557 /* 3 mantissa in 7 bits */
558 if (s->mant2_cnt == 0)
560 if (++s->mant2_cnt == 3)
567 /* 2 mantissa in 7 bits */
568 if (s->mant4_cnt == 0)
570 if (++s->mant4_cnt == 2)
588 static int bit_alloc(AC3EncodeContext *s,
589 UINT8 bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
590 UINT8 encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
591 UINT8 exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
592 int frame_bits, int csnroffst, int fsnroffst)
597 for(i=0;i<NB_BLOCKS;i++) {
601 for(ch=0;ch<s->nb_channels;ch++) {
602 parametric_bit_allocation(s, bap[i][ch], (INT8 *)encoded_exp[i][ch],
604 (((csnroffst-15) << 4) +
606 fgaintab[s->fgaincod[ch]]);
607 frame_bits += compute_mantissa_size(s, bap[i][ch],
612 printf("csnr=%d fsnr=%d frame_bits=%d diff=%d\n",
613 csnroffst, fsnroffst, frame_bits,
614 16 * s->frame_size - ((frame_bits + 7) & ~7));
616 return 16 * s->frame_size - frame_bits;
621 static int compute_bit_allocation(AC3EncodeContext *s,
622 UINT8 bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
623 UINT8 encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
624 UINT8 exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
628 int csnroffst, fsnroffst;
629 UINT8 bap1[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
631 /* init default parameters */
637 for(ch=0;ch<s->nb_channels;ch++)
640 /* compute real values */
641 s->sdecay = sdecaytab[s->sdecaycod] >> s->halfratecod;
642 s->fdecay = fdecaytab[s->fdecaycod] >> s->halfratecod;
643 s->sgain = sgaintab[s->sgaincod];
644 s->dbknee = dbkneetab[s->dbkneecod];
645 s->floor = floortab[s->floorcod];
653 for(i=0;i<NB_BLOCKS;i++) {
654 frame_bits += s->nb_channels * 2 + 2;
657 frame_bits += 2 * s->nb_channels;
658 for(ch=0;ch<s->nb_channels;ch++) {
659 if (exp_strategy[i][ch] != EXP_REUSE)
662 frame_bits++; /* baie */
663 frame_bits++; /* snr */
664 frame_bits += 2; /* delta / skip */
666 frame_bits++; /* cplinu for block 0 */
668 frame_bits += 2*4 + 3 + 6 + s->nb_channels * (4 + 3);
673 /* now the big work begins : do the bit allocation. Modify the snr
674 offset until we can pack everything in the requested frame size */
676 csnroffst = s->csnroffst;
677 while (csnroffst >= 0 &&
678 bit_alloc(s, bap, encoded_exp, exp_strategy, frame_bits, csnroffst, 0) < 0)
679 csnroffst -= SNR_INC1;
681 fprintf(stderr, "Error !!!\n");
684 while ((csnroffst + SNR_INC1) <= 63 &&
685 bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits,
686 csnroffst + SNR_INC1, 0) >= 0) {
687 csnroffst += SNR_INC1;
688 memcpy(bap, bap1, sizeof(bap1));
690 while ((csnroffst + 1) <= 63 &&
691 bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits, csnroffst + 1, 0) >= 0) {
693 memcpy(bap, bap1, sizeof(bap1));
697 while ((fsnroffst + SNR_INC1) <= 15 &&
698 bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits,
699 csnroffst, fsnroffst + SNR_INC1) >= 0) {
700 fsnroffst += SNR_INC1;
701 memcpy(bap, bap1, sizeof(bap1));
703 while ((fsnroffst + 1) <= 15 &&
704 bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits,
705 csnroffst, fsnroffst + 1) >= 0) {
707 memcpy(bap, bap1, sizeof(bap1));
710 s->csnroffst = csnroffst;
711 for(ch=0;ch<s->nb_channels;ch++)
712 s->fsnroffst[ch] = fsnroffst;
713 #if defined(DEBUG_BITALLOC)
718 for(ch=0;ch<s->nb_channels;ch++) {
719 printf("Block #%d Ch%d:\n", i, ch);
721 for(j=0;j<s->nb_coefs[ch];j++) {
722 printf("%d ",bap[i][ch][j]);
732 static int AC3_encode_init(AVCodecContext *avctx)
734 int freq = avctx->sample_rate;
735 int bitrate = avctx->bit_rate;
736 int channels = avctx->channels;
737 AC3EncodeContext *s = avctx->priv_data;
738 int i, j, k, l, ch, v;
740 static unsigned short freqs[3] = { 48000, 44100, 32000 };
742 avctx->frame_size = AC3_FRAME_SIZE;
743 avctx->key_frame = 1; /* always key frame */
745 /* number of channels */
748 else if (channels == 2)
752 s->nb_channels = channels;
757 if ((freqs[j] >> i) == freq)
762 s->sample_rate = freq;
765 s->bsid = 8 + s->halfratecod;
766 s->bsmod = 0; /* complete main audio service */
768 /* bitrate & frame size */
771 if ((bitratetab[i] >> s->halfratecod) == bitrate)
776 s->bit_rate = bitrate;
777 s->frmsizecod = i << 1;
778 s->frame_size_min = (bitrate * 1000 * AC3_FRAME_SIZE) / (freq * 16);
779 /* for now we do not handle fractional sizes */
780 s->frame_size = s->frame_size_min;
782 /* bit allocation init */
783 for(ch=0;ch<s->nb_channels;ch++) {
784 /* bandwidth for each channel */
785 /* XXX: should compute the bandwidth according to the frame
786 size, so that we avoid anoying high freq artefacts */
787 s->chbwcod[ch] = 50; /* sample bandwidth as mpeg audio layer 2 table 0 */
788 s->nb_coefs[ch] = ((s->chbwcod[ch] + 12) * 3) + 37;
790 /* initial snr offset */
793 /* compute bndtab and masktab from bandsz */
799 for(j=0;j<v;j++) masktab[k++]=i;
805 fft_init(MDCT_NBITS - 2);
807 alpha = 2 * M_PI * (i + 1.0 / 8.0) / (float)N;
808 xcos1[i] = fix15(-cos(alpha));
809 xsin1[i] = fix15(-sin(alpha));
817 /* output the AC3 frame header */
818 static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
820 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE, NULL, NULL);
822 put_bits(&s->pb, 16, 0x0b77); /* frame header */
823 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
824 put_bits(&s->pb, 2, s->fscod);
825 put_bits(&s->pb, 6, s->frmsizecod + (s->frame_size - s->frame_size_min));
826 put_bits(&s->pb, 5, s->bsid);
827 put_bits(&s->pb, 3, s->bsmod);
828 put_bits(&s->pb, 3, s->acmod);
830 put_bits(&s->pb, 2, 0); /* surround not indicated */
832 put_bits(&s->pb, 1, 0); /* no LFE */
833 put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
834 put_bits(&s->pb, 1, 0); /* no compression control word */
835 put_bits(&s->pb, 1, 0); /* no lang code */
836 put_bits(&s->pb, 1, 0); /* no audio production info */
837 put_bits(&s->pb, 1, 0); /* no copyright */
838 put_bits(&s->pb, 1, 1); /* original bitstream */
839 put_bits(&s->pb, 1, 0); /* no time code 1 */
840 put_bits(&s->pb, 1, 0); /* no time code 2 */
841 put_bits(&s->pb, 1, 0); /* no addtional bit stream info */
844 /* symetric quantization on 'levels' levels */
845 static inline int sym_quant(int c, int e, int levels)
850 v = (levels * (c << e)) >> 25;
851 v = (levels >> 1) + v;
853 v = (levels * ((-c) << e)) >> 25;
854 v = (levels >> 1) - v;
856 assert (v >= 0 && v < levels);
860 /* asymetric quantization on 2^qbits levels */
861 static inline int asym_quant(int c, int e, int qbits)
865 lshift = e + qbits - 24;
872 m = (1 << (qbits-1));
876 return v & ((1 << qbits)-1);
879 /* Output one audio block. There are NB_BLOCKS audio blocks in one AC3
881 static void output_audio_block(AC3EncodeContext *s,
882 UINT8 exp_strategy[AC3_MAX_CHANNELS],
883 UINT8 encoded_exp[AC3_MAX_CHANNELS][N/2],
884 UINT8 bap[AC3_MAX_CHANNELS][N/2],
885 INT32 mdct_coefs[AC3_MAX_CHANNELS][N/2],
886 INT8 global_exp[AC3_MAX_CHANNELS],
889 int ch, nb_groups, group_size, i, baie;
891 UINT16 qmant[AC3_MAX_CHANNELS][N/2];
893 int mant1_cnt, mant2_cnt, mant4_cnt;
894 UINT16 *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
895 int delta0, delta1, delta2;
897 for(ch=0;ch<s->nb_channels;ch++)
898 put_bits(&s->pb, 1, 0); /* 512 point MDCT */
899 for(ch=0;ch<s->nb_channels;ch++)
900 put_bits(&s->pb, 1, 1); /* no dither */
901 put_bits(&s->pb, 1, 0); /* no dynamic range */
902 if (block_num == 0) {
903 /* for block 0, even if no coupling, we must say it. This is a
905 put_bits(&s->pb, 1, 1); /* coupling strategy present */
906 put_bits(&s->pb, 1, 0); /* no coupling strategy */
908 put_bits(&s->pb, 1, 0); /* no new coupling strategy */
912 put_bits(&s->pb, 1, 0); /* no matrixing (but should be used in the future) */
917 static int count = 0;
918 printf("Block #%d (%d)\n", block_num, count++);
921 /* exponent strategy */
922 for(ch=0;ch<s->nb_channels;ch++) {
923 put_bits(&s->pb, 2, exp_strategy[ch]);
926 for(ch=0;ch<s->nb_channels;ch++) {
927 if (exp_strategy[ch] != EXP_REUSE)
928 put_bits(&s->pb, 6, s->chbwcod[ch]);
932 for (ch = 0; ch < s->nb_channels; ch++) {
933 switch(exp_strategy[ch]) {
947 nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
952 put_bits(&s->pb, 4, exp1);
954 /* next ones are delta encoded */
955 for(i=0;i<nb_groups;i++) {
956 /* merge three delta in one code */
960 delta0 = exp1 - exp0 + 2;
965 delta1 = exp1 - exp0 + 2;
970 delta2 = exp1 - exp0 + 2;
972 put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
975 put_bits(&s->pb, 2, 0); /* no gain range info */
978 /* bit allocation info */
979 baie = (block_num == 0);
980 put_bits(&s->pb, 1, baie);
982 put_bits(&s->pb, 2, s->sdecaycod);
983 put_bits(&s->pb, 2, s->fdecaycod);
984 put_bits(&s->pb, 2, s->sgaincod);
985 put_bits(&s->pb, 2, s->dbkneecod);
986 put_bits(&s->pb, 3, s->floorcod);
990 put_bits(&s->pb, 1, baie); /* always present with bai */
992 put_bits(&s->pb, 6, s->csnroffst);
993 for(ch=0;ch<s->nb_channels;ch++) {
994 put_bits(&s->pb, 4, s->fsnroffst[ch]);
995 put_bits(&s->pb, 3, s->fgaincod[ch]);
999 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1000 put_bits(&s->pb, 1, 0); /* no data to skip */
1002 /* mantissa encoding : we use two passes to handle the grouping. A
1003 one pass method may be faster, but it would necessitate to
1004 modify the output stream. */
1006 /* first pass: quantize */
1007 mant1_cnt = mant2_cnt = mant4_cnt = 0;
1008 qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
1010 for (ch = 0; ch < s->nb_channels; ch++) {
1013 for(i=0;i<s->nb_coefs[ch];i++) {
1014 c = mdct_coefs[ch][i];
1015 e = encoded_exp[ch][i] - global_exp[ch];
1022 v = sym_quant(c, e, 3);
1025 qmant1_ptr = &qmant[ch][i];
1030 *qmant1_ptr += 3 * v;
1042 v = sym_quant(c, e, 5);
1045 qmant2_ptr = &qmant[ch][i];
1050 *qmant2_ptr += 5 * v;
1062 v = sym_quant(c, e, 7);
1065 v = sym_quant(c, e, 11);
1068 qmant4_ptr = &qmant[ch][i];
1080 v = sym_quant(c, e, 15);
1083 v = asym_quant(c, e, 14);
1086 v = asym_quant(c, e, 16);
1089 v = asym_quant(c, e, b - 1);
1096 /* second pass : output the values */
1097 for (ch = 0; ch < s->nb_channels; ch++) {
1100 for(i=0;i<s->nb_coefs[ch];i++) {
1108 put_bits(&s->pb, 5, q);
1112 put_bits(&s->pb, 7, q);
1115 put_bits(&s->pb, 3, q);
1119 put_bits(&s->pb, 7, q);
1122 put_bits(&s->pb, 14, q);
1125 put_bits(&s->pb, 16, q);
1128 put_bits(&s->pb, b - 1, q);
1135 /* compute the ac3 crc */
1137 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1139 static void ac3_crc_init(void)
1141 unsigned int c, n, k;
1143 for(n=0;n<256;n++) {
1145 for (k = 0; k < 8; k++) {
1147 c = ((c << 1) & 0xffff) ^ (CRC16_POLY & 0xffff);
1155 static unsigned int ac3_crc(UINT8 *data, int n, unsigned int crc)
1159 crc = (crc_table[data[i] ^ (crc >> 8)] ^ (crc << 8)) & 0xffff;
1164 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1180 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1186 r = mul_poly(r, a, poly);
1187 a = mul_poly(a, a, poly);
1194 /* compute log2(max(abs(tab[]))) */
1195 static int log2_tab(INT16 *tab, int n)
1206 static void lshift_tab(INT16 *tab, int n, int lshift)
1214 } else if (lshift < 0) {
1222 /* fill the end of the frame and compute the two crcs */
1223 static int output_frame_end(AC3EncodeContext *s)
1225 int frame_size, frame_size_58, n, crc1, crc2, crc_inv;
1228 frame_size = s->frame_size; /* frame size in words */
1229 /* align to 8 bits */
1230 flush_put_bits(&s->pb);
1231 /* add zero bytes to reach the frame size */
1233 n = 2 * s->frame_size - (s->pb.buf_ptr - frame) - 2;
1235 memset(s->pb.buf_ptr, 0, n);
1237 /* Now we must compute both crcs : this is not so easy for crc1
1238 because it is at the beginning of the data... */
1239 frame_size_58 = (frame_size >> 1) + (frame_size >> 3);
1240 crc1 = ac3_crc(frame + 4, (2 * frame_size_58) - 4, 0);
1241 /* XXX: could precompute crc_inv */
1242 crc_inv = pow_poly((CRC16_POLY >> 1), (16 * frame_size_58) - 16, CRC16_POLY);
1243 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1244 frame[2] = crc1 >> 8;
1247 crc2 = ac3_crc(frame + 2 * frame_size_58, (frame_size - frame_size_58) * 2 - 2, 0);
1248 frame[2*frame_size - 2] = crc2 >> 8;
1249 frame[2*frame_size - 1] = crc2;
1251 // printf("n=%d frame_size=%d\n", n, frame_size);
1252 return frame_size * 2;
1255 int AC3_encode_frame(AVCodecContext *avctx,
1256 unsigned char *frame, int buf_size, void *data)
1258 AC3EncodeContext *s = avctx->priv_data;
1259 short *samples = data;
1261 INT16 input_samples[N];
1262 INT32 mdct_coef[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1263 UINT8 exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1264 UINT8 exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS];
1265 UINT8 encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1266 UINT8 bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1267 INT8 exp_samples[NB_BLOCKS][AC3_MAX_CHANNELS];
1271 for(ch=0;ch<s->nb_channels;ch++) {
1272 /* fixed mdct to the six sub blocks & exponent computation */
1273 for(i=0;i<NB_BLOCKS;i++) {
1277 /* compute input samples */
1278 memcpy(input_samples, s->last_samples[ch], N/2 * sizeof(INT16));
1279 sinc = s->nb_channels;
1280 sptr = samples + (sinc * (N/2) * i) + ch;
1281 for(j=0;j<N/2;j++) {
1283 input_samples[j + N/2] = v;
1284 s->last_samples[ch][j] = v;
1288 /* apply the MDCT window */
1289 for(j=0;j<N/2;j++) {
1290 input_samples[j] = MUL16(input_samples[j],
1291 ac3_window[j]) >> 15;
1292 input_samples[N-j-1] = MUL16(input_samples[N-j-1],
1293 ac3_window[j]) >> 15;
1296 /* Normalize the samples to use the maximum available
1298 v = 14 - log2_tab(input_samples, N);
1301 exp_samples[i][ch] = v - 8;
1302 lshift_tab(input_samples, N, v);
1305 mdct512(mdct_coef[i][ch], input_samples);
1307 /* compute "exponents". We take into account the
1308 normalization there */
1309 for(j=0;j<N/2;j++) {
1311 v = abs(mdct_coef[i][ch][j]);
1315 e = 23 - log2(v) + exp_samples[i][ch];
1318 mdct_coef[i][ch][j] = 0;
1325 compute_exp_strategy(exp_strategy, exp, ch);
1327 /* compute the exponents as the decoder will see them. The
1328 EXP_REUSE case must be handled carefully : we select the
1329 min of the exponents */
1331 while (i < NB_BLOCKS) {
1333 while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE) {
1334 exponent_min(exp[i][ch], exp[j][ch], s->nb_coefs[ch]);
1337 frame_bits += encode_exp(encoded_exp[i][ch],
1338 exp[i][ch], s->nb_coefs[ch],
1339 exp_strategy[i][ch]);
1340 /* copy encoded exponents for reuse case */
1341 for(k=i+1;k<j;k++) {
1342 memcpy(encoded_exp[k][ch], encoded_exp[i][ch],
1343 s->nb_coefs[ch] * sizeof(UINT8));
1349 compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
1350 /* everything is known... let's output the frame */
1351 output_frame_header(s, frame);
1353 for(i=0;i<NB_BLOCKS;i++) {
1354 output_audio_block(s, exp_strategy[i], encoded_exp[i],
1355 bap[i], mdct_coef[i], exp_samples[i], i);
1357 return output_frame_end(s);
1361 /*************************************************************************/
1368 IComplex in[FN], in1[FN];
1370 float sum_re, sum_im, a;
1375 in[i].re = random() % 65535 - 32767;
1376 in[i].im = random() % 65535 - 32767;
1386 a = -2 * M_PI * (n * k) / FN;
1387 sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1388 sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1390 printf("%3d: %6d,%6d %6.0f,%6.0f\n",
1391 k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1395 void mdct_test(void)
1401 float s, a, err, e, emax;
1405 input[i] = (random() % 65535 - 32767) * 9 / 10;
1406 input1[i] = input[i];
1409 mdct512(output, input);
1412 for(k=0;k<N/2;k++) {
1415 a = (2*M_PI*(2*n+1+N/2)*(2*k+1) / (4 * N));
1416 s += input1[n] * cos(a);
1418 output1[k] = -2 * s / N;
1423 for(i=0;i<N/2;i++) {
1424 printf("%3d: %7d %7.0f\n", i, output[i], output1[i]);
1425 e = output[i] - output1[i];
1430 printf("err2=%f emax=%f\n", err / (N/2), emax);
1435 AC3EncodeContext ctx;
1436 unsigned char frame[AC3_MAX_CODED_FRAME_SIZE];
1437 short samples[AC3_FRAME_SIZE];
1440 AC3_encode_init(&ctx, 44100, 64000, 1);
1445 for(i=0;i<AC3_FRAME_SIZE;i++)
1446 samples[i] = (int)(sin(2*M_PI*i*1000.0/44100) * 10000);
1447 ret = AC3_encode_frame(&ctx, frame, samples);
1448 printf("ret=%d\n", ret);
1452 AVCodec ac3_encoder = {
1456 sizeof(AC3EncodeContext),