2 * The simplest AC3 encoder
3 * Copyright (c) 2000 Fabrice Bellard.
5 * This file is part of FFmpeg.
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.
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.
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
24 * The simplest AC3 encoder.
27 //#define DEBUG_BITALLOC
29 #include "bitstream.h"
33 typedef struct AC3EncodeContext {
39 unsigned int sample_rate;
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;
46 unsigned int frmsizecod;
47 unsigned int fscod; /* frequency */
51 short last_samples[AC3_MAX_CHANNELS][256];
52 unsigned int chbwcod[AC3_MAX_CHANNELS];
53 int nb_coefs[AC3_MAX_CHANNELS];
55 /* bitrate allocation control */
56 int sgaincod, sdecaycod, fdecaycod, dbkneecod, floorcod;
57 AC3BitAllocParameters bit_alloc;
59 int fgaincod[AC3_MAX_CHANNELS];
60 int fsnroffst[AC3_MAX_CHANNELS];
61 /* mantissa encoding */
62 int mant1_cnt, mant2_cnt, mant4_cnt;
68 #define N (1 << MDCT_NBITS)
70 /* new exponents are sent if their Norm 1 exceed this number */
71 #define EXP_DIFF_THRESHOLD 1000
73 static void fft_init(int ln);
75 static inline int16_t fix15(float a)
78 v = (int)(a * (float)(1 << 15));
86 static inline int calc_lowcomp1(int a, int b0, int b1, int c)
88 if ((b0 + 256) == b1) {
96 static inline int calc_lowcomp(int a, int b0, int b1, int bin)
99 return calc_lowcomp1(a, b0, b1, 384);
100 } else if (bin < 20) {
101 return calc_lowcomp1(a, b0, b1, 320);
103 return FFMAX(a - 128, 0);
107 /* AC3 bit allocation. The algorithm is the one described in the AC3
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)
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 */
122 /* exponent mapping to PSD */
123 for(bin=start;bin<end;bin++) {
124 psd[bin]=(3072 - (exp[bin] << 7));
127 /* PSD integration */
133 end1 = FFMIN(bndtab[k+1], end);
134 for(i=j;i<end1;i++) {
136 int adr = FFMIN(FFABS(v - psd[j]) >> 1, 255);
137 v = FFMAX(v, psd[j]) + latab[adr];
142 } while (end > bndtab[k]);
144 /* excitation function */
145 bndstrt = masktab[start];
146 bndend = masktab[end-1] + 1;
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;
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]) {
170 if (end1 > 22) end1=22;
172 for (bin = begin; bin < end1; bin++) {
173 if (!(is_lfe && bin == 6))
174 lowcomp = calc_lowcomp(lowcomp, bndpsd[bin], bndpsd[bin+1], bin);
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);
182 /* coupling channel */
185 fastleak = (s->cplfleak << 8) + 768;
186 slowleak = (s->cplsleak << 8) + 768;
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);
195 /* compute masking curve */
197 for (bin = bndstrt; bin < bndend; bin++) {
198 tmp = s->dbknee - bndpsd[bin];
200 excite[bin] += tmp >> 2;
202 mask[bin] = FFMAX(hth[bin >> s->halfratecod][s->fscod], excite[bin]);
205 /* delta bit allocation */
207 if (deltbae == 0 || deltbae == 1) {
208 int band, seg, delta;
210 for (seg = 0; seg < deltnseg; seg++) {
211 band += deltoffst[seg];
212 if (deltba[seg] >= 4) {
213 delta = (deltba[seg] - 3) << 7;
215 delta = (deltba[seg] - 4) << 7;
217 for (k = 0; k < deltlen[seg]; k++) {
224 /* compute bit allocation */
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];
236 } while (end > bndtab[j++]);
239 typedef struct IComplex {
243 static void fft_init(int ln)
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));
259 m |= ((i >> j) & 1) << (ln-j-1);
266 #define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1) \
273 pre = (bx + ax) >> 1;\
274 pim = (by + ay) >> 1;\
275 qre = (bx - ax) >> 1;\
276 qim = (by - ay) >> 1;\
279 #define MUL16(a,b) ((a) * (b))
281 #define CMUL(pre, pim, are, aim, bre, bim) \
283 pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;\
284 pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;\
288 /* do a 2^n point complex fft on 2^ln points. */
289 static void fft(IComplex *z, int ln)
293 register IComplex *p,*q;
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);
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);
340 for (j = 0; j < nblocks; ++j) {
342 BF(p->re, p->im, q->re, q->im,
343 p->re, p->im, q->re, q->im);
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);
357 nblocks = nblocks >> 1;
358 nloops = nloops << 1;
359 } while (nblocks != 0);
362 /* do a 512 point mdct */
363 static void mdct512(int32_t *out, int16_t *in)
365 int i, re, im, re1, im1;
369 /* shift to simplify computations */
371 rot[i] = -in[i + 3*N/4];
373 rot[i] = in[i - N/4];
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]);
382 fft(x, MDCT_NBITS - 2);
388 CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
390 out[N/2-1-2*i] = re1;
394 /* XXX: use another norm ? */
395 static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
400 sum += abs(exp1[i] - exp2[i]);
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],
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);
418 av_log(NULL, AV_LOG_DEBUG, "exp_diff=%d\n", exp_diff);
420 if (exp_diff > EXP_DIFF_THRESHOLD)
421 exp_strategy[i][ch] = EXP_NEW;
423 exp_strategy[i][ch] = EXP_REUSE;
428 /* now select the encoding strategy type : if exponents are often
429 recoded, we use a coarse encoding */
431 while (i < NB_BLOCKS) {
433 while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE)
437 exp_strategy[i][ch] = EXP_D45;
441 exp_strategy[i][ch] = EXP_D25;
444 exp_strategy[i][ch] = EXP_D15;
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)
457 if (exp1[i] < exp[i])
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],
469 int group_size, nb_groups, i, j, k, exp_min;
472 switch(exp_strategy) {
484 nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
486 /* for each group, compute the minimum exponent */
487 exp1[0] = exp[0]; /* DC exponent is handled separately */
489 for(i=1;i<=nb_groups;i++) {
491 assert(exp_min >= 0 && exp_min <= 24);
492 for(j=1;j<group_size;j++) {
493 if (exp[k+j] < exp_min)
500 /* constraint for DC exponent */
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);
511 /* now we have the exponent values the decoder will see */
512 encoded_exp[0] = exp1[0];
514 for(i=1;i<=nb_groups;i++) {
515 for(j=0;j<group_size;j++) {
516 encoded_exp[k+j] = exp1[i];
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]);
526 av_log(NULL, AV_LOG_DEBUG, "\n");
529 return 4 + (nb_groups / 3) * 7;
532 /* return the size in bits taken by the mantissa */
533 static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
538 for(i=0;i<nb_coefs;i++) {
545 /* 3 mantissa in 5 bits */
546 if (s->mant1_cnt == 0)
548 if (++s->mant1_cnt == 3)
552 /* 3 mantissa in 7 bits */
553 if (s->mant2_cnt == 0)
555 if (++s->mant2_cnt == 3)
562 /* 2 mantissa in 7 bits */
563 if (s->mant4_cnt == 0)
565 if (++s->mant4_cnt == 2)
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)
592 for(i=0;i<NB_BLOCKS;i++) {
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],
600 (((csnroffst-15) << 4) +
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],
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));
614 return 16 * s->frame_size - frame_bits;
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],
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 };
630 /* init default parameters */
636 for(ch=0;ch<s->nb_all_channels;ch++)
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];
650 // if (s->acmod == 2)
652 frame_bits += frame_bits_inc[s->acmod];
655 for(i=0;i<NB_BLOCKS;i++) {
656 frame_bits += s->nb_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
658 frame_bits++; /* rematstr */
659 if(i==0) frame_bits += 4;
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);
679 /* auxdatae, crcrsv */
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 */
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;
693 av_log(NULL, AV_LOG_ERROR, "Bit allocation failed, try increasing the bitrate, -ab 384 for example!\n");
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));
702 while ((csnroffst + 1) <= 63 &&
703 bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits, csnroffst + 1, 0) >= 0) {
705 memcpy(bap, bap1, sizeof(bap1));
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));
715 while ((fsnroffst + 1) <= 15 &&
716 bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits,
717 csnroffst, fsnroffst + 1) >= 0) {
719 memcpy(bap, bap1, sizeof(bap1));
722 s->csnroffst = csnroffst;
723 for(ch=0;ch<s->nb_all_channels;ch++)
724 s->fsnroffst[ch] = fsnroffst;
725 #if defined(DEBUG_BITALLOC)
730 for(ch=0;ch<s->nb_all_channels;ch++) {
731 printf("Block #%d Ch%d:\n", i, ch);
733 for(j=0;j<s->nb_coefs[ch];j++) {
734 printf("%d ",bap[i][ch][j]);
744 void ac3_common_init(void)
747 /* compute bndtab and masktab from bandsz */
753 for(j=0;j<v;j++) masktab[k++]=i;
760 static int AC3_encode_init(AVCodecContext *avctx)
762 int freq = avctx->sample_rate;
763 int bitrate = avctx->bit_rate;
764 int channels = avctx->channels;
765 AC3EncodeContext *s = avctx->priv_data;
768 static const uint8_t acmod_defs[6] = {
772 0x06, /* L R SL SR */
773 0x07, /* L C R SL SR */
774 0x07, /* L C R SL SR (+LFE) */
777 avctx->frame_size = AC3_FRAME_SIZE;
779 /* number of channels */
780 if (channels < 1 || channels > 6)
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;
791 if ((ac3_freqs[j] >> i) == freq)
796 s->sample_rate = freq;
799 s->bsid = 8 + s->halfratecod;
800 s->bsmod = 0; /* complete main audio service */
802 /* bitrate & frame size */
805 if ((ac3_bitratetab[i] >> s->halfratecod) == bitrate)
810 s->bit_rate = bitrate;
811 s->frmsizecod = i << 1;
812 s->frame_size_min = (bitrate * 1000 * AC3_FRAME_SIZE) / (freq * 16);
814 s->samples_written = 0;
815 s->frame_size = s->frame_size_min;
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;
826 s->nb_coefs[s->lfe_channel] = 7; /* fixed */
828 /* initial snr offset */
834 fft_init(MDCT_NBITS - 2);
836 alpha = 2 * M_PI * (i + 1.0 / 8.0) / (float)N;
837 xcos1[i] = fix15(-cos(alpha));
838 xsin1[i] = fix15(-sin(alpha));
841 avctx->coded_frame= avcodec_alloc_frame();
842 avctx->coded_frame->key_frame= 1;
847 /* output the AC3 frame header */
848 static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
850 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
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 */
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 */
877 /* symetric quantization on 'levels' levels */
878 static inline int sym_quant(int c, int e, int levels)
883 v = (levels * (c << e)) >> 24;
885 v = (levels >> 1) + v;
887 v = (levels * ((-c) << e)) >> 24;
889 v = (levels >> 1) - v;
891 assert (v >= 0 && v < levels);
895 /* asymetric quantization on 2^qbits levels */
896 static inline int asym_quant(int c, int e, int qbits)
900 lshift = e + qbits - 24;
907 m = (1 << (qbits-1));
911 return v & ((1 << qbits)-1);
914 /* Output one audio block. There are NB_BLOCKS audio blocks in one AC3
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],
924 int ch, nb_groups, group_size, i, baie, rbnd;
926 uint16_t qmant[AC3_MAX_CHANNELS][N/2];
928 int mant1_cnt, mant2_cnt, mant4_cnt;
929 uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
930 int delta0, delta1, delta2;
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
940 put_bits(&s->pb, 1, 1); /* coupling strategy present */
941 put_bits(&s->pb, 1, 0); /* no coupling strategy */
943 put_bits(&s->pb, 1, 0); /* no new coupling strategy */
950 /* first block must define rematrixing (rematstr) */
951 put_bits(&s->pb, 1, 1);
953 /* dummy rematrixing rematflg(1:4)=0 */
954 for (rbnd=0;rbnd<4;rbnd++)
955 put_bits(&s->pb, 1, 0);
959 /* no matrixing (but should be used in the future) */
960 put_bits(&s->pb, 1, 0);
966 static int count = 0;
967 av_log(NULL, AV_LOG_DEBUG, "Block #%d (%d)\n", block_num, count++);
970 /* exponent strategy */
971 for(ch=0;ch<s->nb_channels;ch++) {
972 put_bits(&s->pb, 2, exp_strategy[ch]);
976 put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
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]);
985 for (ch = 0; ch < s->nb_all_channels; ch++) {
986 switch(exp_strategy[ch]) {
1000 nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
1001 p = encoded_exp[ch];
1003 /* first exponent */
1005 put_bits(&s->pb, 4, exp1);
1007 /* next ones are delta encoded */
1008 for(i=0;i<nb_groups;i++) {
1009 /* merge three delta in one code */
1013 delta0 = exp1 - exp0 + 2;
1018 delta1 = exp1 - exp0 + 2;
1023 delta2 = exp1 - exp0 + 2;
1025 put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
1028 if (ch != s->lfe_channel)
1029 put_bits(&s->pb, 2, 0); /* no gain range info */
1032 /* bit allocation info */
1033 baie = (block_num == 0);
1034 put_bits(&s->pb, 1, 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);
1044 put_bits(&s->pb, 1, baie); /* always present with bai */
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]);
1053 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1054 put_bits(&s->pb, 1, 0); /* no data to skip */
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. */
1060 /* first pass: quantize */
1061 mant1_cnt = mant2_cnt = mant4_cnt = 0;
1062 qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
1064 for (ch = 0; ch < s->nb_all_channels; ch++) {
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];
1076 v = sym_quant(c, e, 3);
1079 qmant1_ptr = &qmant[ch][i];
1084 *qmant1_ptr += 3 * v;
1096 v = sym_quant(c, e, 5);
1099 qmant2_ptr = &qmant[ch][i];
1104 *qmant2_ptr += 5 * v;
1116 v = sym_quant(c, e, 7);
1119 v = sym_quant(c, e, 11);
1122 qmant4_ptr = &qmant[ch][i];
1134 v = sym_quant(c, e, 15);
1137 v = asym_quant(c, e, 14);
1140 v = asym_quant(c, e, 16);
1143 v = asym_quant(c, e, b - 1);
1150 /* second pass : output the values */
1151 for (ch = 0; ch < s->nb_all_channels; ch++) {
1154 for(i=0;i<s->nb_coefs[ch];i++) {
1162 put_bits(&s->pb, 5, q);
1166 put_bits(&s->pb, 7, q);
1169 put_bits(&s->pb, 3, q);
1173 put_bits(&s->pb, 7, q);
1176 put_bits(&s->pb, 14, q);
1179 put_bits(&s->pb, 16, q);
1182 put_bits(&s->pb, b - 1, q);
1189 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1191 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1207 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1213 r = mul_poly(r, a, poly);
1214 a = mul_poly(a, a, poly);
1221 /* compute log2(max(abs(tab[]))) */
1222 static int log2_tab(int16_t *tab, int n)
1233 static void lshift_tab(int16_t *tab, int n, int lshift)
1241 } else if (lshift < 0) {
1249 /* fill the end of the frame and compute the two crcs */
1250 static int output_frame_end(AC3EncodeContext *s)
1252 int frame_size, frame_size_58, n, crc1, crc2, crc_inv;
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 */
1260 n = 2 * s->frame_size - (pbBufPtr(&s->pb) - frame) - 2;
1263 memset(pbBufPtr(&s->pb), 0, n);
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;
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;
1279 // printf("n=%d frame_size=%d\n", n, frame_size);
1280 return frame_size * 2;
1283 static int AC3_encode_frame(AVCodecContext *avctx,
1284 unsigned char *frame, int buf_size, void *data)
1286 AC3EncodeContext *s = avctx->priv_data;
1287 int16_t *samples = data;
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];
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++) {
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++) {
1311 input_samples[j + N/2] = v;
1312 s->last_samples[ch][j] = v;
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;
1324 /* Normalize the samples to use the maximum available
1326 v = 14 - log2_tab(input_samples, N);
1329 exp_samples[i][ch] = v - 10;
1330 lshift_tab(input_samples, N, v);
1333 mdct512(mdct_coef[i][ch], input_samples);
1335 /* compute "exponents". We take into account the
1336 normalization there */
1337 for(j=0;j<N/2;j++) {
1339 v = abs(mdct_coef[i][ch][j]);
1343 e = 23 - av_log2(v) + exp_samples[i][ch];
1346 mdct_coef[i][ch][j] = 0;
1353 compute_exp_strategy(exp_strategy, exp, ch, ch == s->lfe_channel);
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 */
1359 while (i < NB_BLOCKS) {
1361 while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE) {
1362 exponent_min(exp[i][ch], exp[j][ch], s->nb_coefs[ch]);
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));
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;
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;
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);
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);
1394 return output_frame_end(s);
1397 static int AC3_encode_close(AVCodecContext *avctx)
1399 av_freep(&avctx->coded_frame);
1404 /*************************************************************************/
1411 IComplex in[FN], in1[FN];
1413 float sum_re, sum_im, a;
1418 in[i].re = random() % 65535 - 32767;
1419 in[i].im = random() % 65535 - 32767;
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);
1433 printf("%3d: %6d,%6d %6.0f,%6.0f\n",
1434 k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1438 void mdct_test(void)
1441 int32_t output[N/2];
1444 float s, a, err, e, emax;
1448 input[i] = (random() % 65535 - 32767) * 9 / 10;
1449 input1[i] = input[i];
1452 mdct512(output, input);
1455 for(k=0;k<N/2;k++) {
1458 a = (2*M_PI*(2*n+1+N/2)*(2*k+1) / (4 * N));
1459 s += input1[n] * cos(a);
1461 output1[k] = -2 * s / N;
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];
1473 printf("err2=%f emax=%f\n", err / (N/2), emax);
1478 AC3EncodeContext ctx;
1479 unsigned char frame[AC3_MAX_CODED_FRAME_SIZE];
1480 short samples[AC3_FRAME_SIZE];
1483 AC3_encode_init(&ctx, 44100, 64000, 1);
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);
1495 AVCodec ac3_encoder = {
1499 sizeof(AC3EncodeContext),