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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 * The simplest AC3 encoder.
25 //#define DEBUG_BITALLOC
27 #include "bitstream.h"
31 typedef struct AC3EncodeContext {
37 unsigned int sample_rate;
39 unsigned int frame_size_min; /* minimum frame size in case rounding is necessary */
40 unsigned int frame_size; /* current frame size in words */
41 unsigned int bits_written;
42 unsigned int samples_written;
44 unsigned int frmsizecod;
45 unsigned int fscod; /* frequency */
49 short last_samples[AC3_MAX_CHANNELS][256];
50 unsigned int chbwcod[AC3_MAX_CHANNELS];
51 int nb_coefs[AC3_MAX_CHANNELS];
53 /* bitrate allocation control */
54 int sgaincod, sdecaycod, fdecaycod, dbkneecod, floorcod;
55 AC3BitAllocParameters bit_alloc;
57 int fgaincod[AC3_MAX_CHANNELS];
58 int fsnroffst[AC3_MAX_CHANNELS];
59 /* mantissa encoding */
60 int mant1_cnt, mant2_cnt, mant4_cnt;
66 #define N (1 << MDCT_NBITS)
68 /* new exponents are sent if their Norm 1 exceed this number */
69 #define EXP_DIFF_THRESHOLD 1000
71 static void fft_init(int ln);
73 static inline int16_t fix15(float a)
76 v = (int)(a * (float)(1 << 15));
86 * Generate a Kaiser Window.
88 static void k_window_init(int alpha, double *window, int n, int iter)
97 for(j=iter; j>0; j--) {
98 window[k] = (window[k] * x / (j*j)) + 1.0;
104 * Generate a Kaiser-Bessel Derived Window.
105 * @param alpha determines window shape
106 * @param window array to fill with window values
107 * @param iter number of iterations to use in BesselI0
110 static void kbd_window_init(int alpha, int16_t *out_window, int iter)
117 k_window_init(alpha, kwindow, n2, iter);
118 window[0] = kwindow[0];
119 for(k=1; k<n2; k++) {
120 window[k] = window[k-1] + kwindow[k];
122 for(k=0; k<n2; k++) {
123 window[k] = sqrt(window[k] / (window[n2-1]+1));
124 //out_window[k] = round(window[k]*((1<<15)-1)); //enable this for a rounded window
125 out_window[k] = fix15(window[k]);
129 static inline int calc_lowcomp1(int a, int b0, int b1)
131 if ((b0 + 256) == b1) {
133 } else if (b0 > b1) {
140 static inline int calc_lowcomp(int a, int b0, int b1, int bin)
143 if ((b0 + 256) == b1) {
145 } else if (b0 > b1) {
149 } else if (bin < 20) {
150 if ((b0 + 256) == b1) {
152 } else if (b0 > b1) {
163 /* AC3 bit allocation. The algorithm is the one described in the AC3
165 void ac3_parametric_bit_allocation(AC3BitAllocParameters *s, uint8_t *bap,
166 int8_t *exp, int start, int end,
167 int snroffset, int fgain, int is_lfe,
168 int deltbae,int deltnseg,
169 uint8_t *deltoffst, uint8_t *deltlen, uint8_t *deltba)
171 int bin,i,j,k,end1,v,v1,bndstrt,bndend,lowcomp,begin;
172 int fastleak,slowleak,address,tmp;
173 int16_t psd[256]; /* scaled exponents */
174 int16_t bndpsd[50]; /* interpolated exponents */
175 int16_t excite[50]; /* excitation */
176 int16_t mask[50]; /* masking value */
178 /* exponent mapping to PSD */
179 for(bin=start;bin<end;bin++) {
180 psd[bin]=(3072 - (exp[bin] << 7));
183 /* PSD integration */
190 if (end1 > end) end1=end;
191 for(i=j;i<end1;i++) {
198 if (adr > 255) adr=255;
202 if (adr > 255) adr=255;
209 } while (end > bndtab[k]);
211 /* excitation function */
212 bndstrt = masktab[start];
213 bndend = masktab[end-1] + 1;
217 lowcomp = calc_lowcomp1(lowcomp, bndpsd[0], bndpsd[1]) ;
218 excite[0] = bndpsd[0] - fgain - lowcomp ;
219 lowcomp = calc_lowcomp1(lowcomp, bndpsd[1], bndpsd[2]) ;
220 excite[1] = bndpsd[1] - fgain - lowcomp ;
222 for (bin = 2; bin < 7; bin++) {
223 if (!(is_lfe && bin == 6))
224 lowcomp = calc_lowcomp1(lowcomp, bndpsd[bin], bndpsd[bin+1]) ;
225 fastleak = bndpsd[bin] - fgain ;
226 slowleak = bndpsd[bin] - s->sgain ;
227 excite[bin] = fastleak - lowcomp ;
228 if (!(is_lfe && bin == 6)) {
229 if (bndpsd[bin] <= bndpsd[bin+1]) {
237 if (end1 > 22) end1=22;
239 for (bin = begin; bin < end1; bin++) {
240 if (!(is_lfe && bin == 6))
241 lowcomp = calc_lowcomp(lowcomp, bndpsd[bin], bndpsd[bin+1], bin) ;
243 fastleak -= s->fdecay ;
244 v = bndpsd[bin] - fgain;
245 if (fastleak < v) fastleak = v;
247 slowleak -= s->sdecay ;
248 v = bndpsd[bin] - s->sgain;
249 if (slowleak < v) slowleak = v;
251 v=fastleak - lowcomp;
252 if (slowleak > v) v=slowleak;
258 /* coupling channel */
261 fastleak = (s->cplfleak << 8) + 768;
262 slowleak = (s->cplsleak << 8) + 768;
265 for (bin = begin; bin < bndend; bin++) {
266 fastleak -= s->fdecay ;
267 v = bndpsd[bin] - fgain;
268 if (fastleak < v) fastleak = v;
269 slowleak -= s->sdecay ;
270 v = bndpsd[bin] - s->sgain;
271 if (slowleak < v) slowleak = v;
274 if (slowleak > v) v = slowleak;
278 /* compute masking curve */
280 for (bin = bndstrt; bin < bndend; bin++) {
282 tmp = s->dbknee - bndpsd[bin];
286 v=hth[bin >> s->halfratecod][s->fscod];
291 /* delta bit allocation */
293 if (deltbae == 0 || deltbae == 1) {
294 int band, seg, delta;
296 for (seg = 0; seg < deltnseg; seg++) {
297 band += deltoffst[seg] ;
298 if (deltba[seg] >= 4) {
299 delta = (deltba[seg] - 3) << 7;
301 delta = (deltba[seg] - 4) << 7;
303 for (k = 0; k < deltlen[seg]; k++) {
304 mask[band] += delta ;
310 /* compute bit allocation */
322 end1=bndtab[j] + bndsz[j];
323 if (end1 > end) end1=end;
325 for (k = i; k < end1; k++) {
326 address = (psd[i] - v) >> 5 ;
327 if (address < 0) address=0;
328 else if (address > 63) address=63;
329 bap[i] = baptab[address];
332 } while (end > bndtab[j++]) ;
335 typedef struct IComplex {
339 static void fft_init(int ln)
346 for(i=0;i<(n/2);i++) {
347 alpha = 2 * M_PI * (float)i / (float)n;
348 costab[i] = fix15(cos(alpha));
349 sintab[i] = fix15(sin(alpha));
355 m |= ((i >> j) & 1) << (ln-j-1);
362 #define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1) \
369 pre = (bx + ax) >> 1;\
370 pim = (by + ay) >> 1;\
371 qre = (bx - ax) >> 1;\
372 qim = (by - ay) >> 1;\
375 #define MUL16(a,b) ((a) * (b))
377 #define CMUL(pre, pim, are, aim, bre, bim) \
379 pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;\
380 pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;\
384 /* do a 2^n point complex fft on 2^ln points. */
385 static void fft(IComplex *z, int ln)
389 register IComplex *p,*q;
411 BF(p[0].re, p[0].im, p[1].re, p[1].im,
412 p[0].re, p[0].im, p[1].re, p[1].im);
421 BF(p[0].re, p[0].im, p[2].re, p[2].im,
422 p[0].re, p[0].im, p[2].re, p[2].im);
423 BF(p[1].re, p[1].im, p[3].re, p[3].im,
424 p[1].re, p[1].im, p[3].im, -p[3].re);
436 for (j = 0; j < nblocks; ++j) {
438 BF(p->re, p->im, q->re, q->im,
439 p->re, p->im, q->re, q->im);
443 for(l = nblocks; l < np2; l += nblocks) {
444 CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
445 BF(p->re, p->im, q->re, q->im,
446 p->re, p->im, tmp_re, tmp_im);
453 nblocks = nblocks >> 1;
454 nloops = nloops << 1;
455 } while (nblocks != 0);
458 /* do a 512 point mdct */
459 static void mdct512(int32_t *out, int16_t *in)
461 int i, re, im, re1, im1;
465 /* shift to simplify computations */
467 rot[i] = -in[i + 3*N/4];
469 rot[i] = in[i - N/4];
473 re = ((int)rot[2*i] - (int)rot[N-1-2*i]) >> 1;
474 im = -((int)rot[N/2+2*i] - (int)rot[N/2-1-2*i]) >> 1;
475 CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
478 fft(x, MDCT_NBITS - 2);
484 CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
486 out[N/2-1-2*i] = re1;
490 /* XXX: use another norm ? */
491 static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
496 sum += abs(exp1[i] - exp2[i]);
501 static void compute_exp_strategy(uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
502 uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
508 /* estimate if the exponent variation & decide if they should be
509 reused in the next frame */
510 exp_strategy[0][ch] = EXP_NEW;
511 for(i=1;i<NB_BLOCKS;i++) {
512 exp_diff = calc_exp_diff(exp[i][ch], exp[i-1][ch], N/2);
514 av_log(NULL, AV_LOG_DEBUG, "exp_diff=%d\n", exp_diff);
516 if (exp_diff > EXP_DIFF_THRESHOLD)
517 exp_strategy[i][ch] = EXP_NEW;
519 exp_strategy[i][ch] = EXP_REUSE;
524 /* now select the encoding strategy type : if exponents are often
525 recoded, we use a coarse encoding */
527 while (i < NB_BLOCKS) {
529 while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE)
533 exp_strategy[i][ch] = EXP_D45;
537 exp_strategy[i][ch] = EXP_D25;
540 exp_strategy[i][ch] = EXP_D15;
547 /* set exp[i] to min(exp[i], exp1[i]) */
548 static void exponent_min(uint8_t exp[N/2], uint8_t exp1[N/2], int n)
553 if (exp1[i] < exp[i])
558 /* update the exponents so that they are the ones the decoder will
559 decode. Return the number of bits used to code the exponents */
560 static int encode_exp(uint8_t encoded_exp[N/2],
565 int group_size, nb_groups, i, j, k, exp_min;
568 switch(exp_strategy) {
580 nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
582 /* for each group, compute the minimum exponent */
583 exp1[0] = exp[0]; /* DC exponent is handled separately */
585 for(i=1;i<=nb_groups;i++) {
587 assert(exp_min >= 0 && exp_min <= 24);
588 for(j=1;j<group_size;j++) {
589 if (exp[k+j] < exp_min)
596 /* constraint for DC exponent */
600 /* Decrease the delta between each groups to within 2
601 * so that they can be differentially encoded */
602 for (i=1;i<=nb_groups;i++)
603 exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
604 for (i=nb_groups-1;i>=0;i--)
605 exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
607 /* now we have the exponent values the decoder will see */
608 encoded_exp[0] = exp1[0];
610 for(i=1;i<=nb_groups;i++) {
611 for(j=0;j<group_size;j++) {
612 encoded_exp[k+j] = exp1[i];
618 av_log(NULL, AV_LOG_DEBUG, "exponents: strategy=%d\n", exp_strategy);
619 for(i=0;i<=nb_groups * group_size;i++) {
620 av_log(NULL, AV_LOG_DEBUG, "%d ", encoded_exp[i]);
622 av_log(NULL, AV_LOG_DEBUG, "\n");
625 return 4 + (nb_groups / 3) * 7;
628 /* return the size in bits taken by the mantissa */
629 static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
634 for(i=0;i<nb_coefs;i++) {
641 /* 3 mantissa in 5 bits */
642 if (s->mant1_cnt == 0)
644 if (++s->mant1_cnt == 3)
648 /* 3 mantissa in 7 bits */
649 if (s->mant2_cnt == 0)
651 if (++s->mant2_cnt == 3)
658 /* 2 mantissa in 7 bits */
659 if (s->mant4_cnt == 0)
661 if (++s->mant4_cnt == 2)
679 static int bit_alloc(AC3EncodeContext *s,
680 uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
681 uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
682 uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
683 int frame_bits, int csnroffst, int fsnroffst)
688 for(i=0;i<NB_BLOCKS;i++) {
692 for(ch=0;ch<s->nb_all_channels;ch++) {
693 ac3_parametric_bit_allocation(&s->bit_alloc,
694 bap[i][ch], (int8_t *)encoded_exp[i][ch],
696 (((csnroffst-15) << 4) +
698 fgaintab[s->fgaincod[ch]],
699 ch == s->lfe_channel,
700 2, 0, NULL, NULL, NULL);
701 frame_bits += compute_mantissa_size(s, bap[i][ch],
706 printf("csnr=%d fsnr=%d frame_bits=%d diff=%d\n",
707 csnroffst, fsnroffst, frame_bits,
708 16 * s->frame_size - ((frame_bits + 7) & ~7));
710 return 16 * s->frame_size - frame_bits;
715 static int compute_bit_allocation(AC3EncodeContext *s,
716 uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
717 uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
718 uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
722 int csnroffst, fsnroffst;
723 uint8_t bap1[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
724 static int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
726 /* init default parameters */
732 for(ch=0;ch<s->nb_all_channels;ch++)
735 /* compute real values */
736 s->bit_alloc.fscod = s->fscod;
737 s->bit_alloc.halfratecod = s->halfratecod;
738 s->bit_alloc.sdecay = sdecaytab[s->sdecaycod] >> s->halfratecod;
739 s->bit_alloc.fdecay = fdecaytab[s->fdecaycod] >> s->halfratecod;
740 s->bit_alloc.sgain = sgaintab[s->sgaincod];
741 s->bit_alloc.dbknee = dbkneetab[s->dbkneecod];
742 s->bit_alloc.floor = floortab[s->floorcod];
746 // if (s->acmod == 2)
748 frame_bits += frame_bits_inc[s->acmod];
751 for(i=0;i<NB_BLOCKS;i++) {
752 frame_bits += s->nb_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
754 frame_bits++; /* rematstr */
755 if(i==0) frame_bits += 4;
757 frame_bits += 2 * s->nb_channels; /* chexpstr[2] * c */
759 frame_bits++; /* lfeexpstr */
760 for(ch=0;ch<s->nb_channels;ch++) {
761 if (exp_strategy[i][ch] != EXP_REUSE)
762 frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
764 frame_bits++; /* baie */
765 frame_bits++; /* snr */
766 frame_bits += 2; /* delta / skip */
768 frame_bits++; /* cplinu for block 0 */
770 /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
772 /* (fsnoffset[4] + fgaincod[4]) * c */
773 frame_bits += 2*4 + 3 + 6 + s->nb_all_channels * (4 + 3);
775 /* auxdatae, crcrsv */
781 /* now the big work begins : do the bit allocation. Modify the snr
782 offset until we can pack everything in the requested frame size */
784 csnroffst = s->csnroffst;
785 while (csnroffst >= 0 &&
786 bit_alloc(s, bap, encoded_exp, exp_strategy, frame_bits, csnroffst, 0) < 0)
787 csnroffst -= SNR_INC1;
789 av_log(NULL, AV_LOG_ERROR, "Bit allocation failed, try increasing the bitrate, -ab 384 for example!\n");
792 while ((csnroffst + SNR_INC1) <= 63 &&
793 bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits,
794 csnroffst + SNR_INC1, 0) >= 0) {
795 csnroffst += SNR_INC1;
796 memcpy(bap, bap1, sizeof(bap1));
798 while ((csnroffst + 1) <= 63 &&
799 bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits, csnroffst + 1, 0) >= 0) {
801 memcpy(bap, bap1, sizeof(bap1));
805 while ((fsnroffst + SNR_INC1) <= 15 &&
806 bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits,
807 csnroffst, fsnroffst + SNR_INC1) >= 0) {
808 fsnroffst += SNR_INC1;
809 memcpy(bap, bap1, sizeof(bap1));
811 while ((fsnroffst + 1) <= 15 &&
812 bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits,
813 csnroffst, fsnroffst + 1) >= 0) {
815 memcpy(bap, bap1, sizeof(bap1));
818 s->csnroffst = csnroffst;
819 for(ch=0;ch<s->nb_all_channels;ch++)
820 s->fsnroffst[ch] = fsnroffst;
821 #if defined(DEBUG_BITALLOC)
826 for(ch=0;ch<s->nb_all_channels;ch++) {
827 printf("Block #%d Ch%d:\n", i, ch);
829 for(j=0;j<s->nb_coefs[ch];j++) {
830 printf("%d ",bap[i][ch][j]);
840 void ac3_common_init(void)
843 /* compute bndtab and masktab from bandsz */
849 for(j=0;j<v;j++) masktab[k++]=i;
856 static int AC3_encode_init(AVCodecContext *avctx)
858 int freq = avctx->sample_rate;
859 int bitrate = avctx->bit_rate;
860 int channels = avctx->channels;
861 AC3EncodeContext *s = avctx->priv_data;
864 static const uint8_t acmod_defs[6] = {
868 0x06, /* L R SL SR */
869 0x07, /* L C R SL SR */
870 0x07, /* L C R SL SR (+LFE) */
873 avctx->frame_size = AC3_FRAME_SIZE;
875 /* number of channels */
876 if (channels < 1 || channels > 6)
878 s->acmod = acmod_defs[channels - 1];
879 s->lfe = (channels == 6) ? 1 : 0;
880 s->nb_all_channels = channels;
881 s->nb_channels = channels > 5 ? 5 : channels;
882 s->lfe_channel = s->lfe ? 5 : -1;
887 if ((ac3_freqs[j] >> i) == freq)
892 s->sample_rate = freq;
895 s->bsid = 8 + s->halfratecod;
896 s->bsmod = 0; /* complete main audio service */
898 /* bitrate & frame size */
901 if ((ac3_bitratetab[i] >> s->halfratecod) == bitrate)
906 s->bit_rate = bitrate;
907 s->frmsizecod = i << 1;
908 s->frame_size_min = (bitrate * 1000 * AC3_FRAME_SIZE) / (freq * 16);
910 s->samples_written = 0;
911 s->frame_size = s->frame_size_min;
913 /* bit allocation init */
914 for(ch=0;ch<s->nb_channels;ch++) {
915 /* bandwidth for each channel */
916 /* XXX: should compute the bandwidth according to the frame
917 size, so that we avoid anoying high freq artefacts */
918 s->chbwcod[ch] = 50; /* sample bandwidth as mpeg audio layer 2 table 0 */
919 s->nb_coefs[ch] = ((s->chbwcod[ch] + 12) * 3) + 37;
922 s->nb_coefs[s->lfe_channel] = 7; /* fixed */
924 /* initial snr offset */
930 kbd_window_init(5.0, ac3_window, 50);
932 fft_init(MDCT_NBITS - 2);
934 alpha = 2 * M_PI * (i + 1.0 / 8.0) / (float)N;
935 xcos1[i] = fix15(-cos(alpha));
936 xsin1[i] = fix15(-sin(alpha));
939 avctx->coded_frame= avcodec_alloc_frame();
940 avctx->coded_frame->key_frame= 1;
945 /* output the AC3 frame header */
946 static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
948 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
950 put_bits(&s->pb, 16, 0x0b77); /* frame header */
951 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
952 put_bits(&s->pb, 2, s->fscod);
953 put_bits(&s->pb, 6, s->frmsizecod + (s->frame_size - s->frame_size_min));
954 put_bits(&s->pb, 5, s->bsid);
955 put_bits(&s->pb, 3, s->bsmod);
956 put_bits(&s->pb, 3, s->acmod);
957 if ((s->acmod & 0x01) && s->acmod != 0x01)
958 put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
960 put_bits(&s->pb, 2, 1); /* XXX -6 dB */
961 if (s->acmod == 0x02)
962 put_bits(&s->pb, 2, 0); /* surround not indicated */
963 put_bits(&s->pb, 1, s->lfe); /* LFE */
964 put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
965 put_bits(&s->pb, 1, 0); /* no compression control word */
966 put_bits(&s->pb, 1, 0); /* no lang code */
967 put_bits(&s->pb, 1, 0); /* no audio production info */
968 put_bits(&s->pb, 1, 0); /* no copyright */
969 put_bits(&s->pb, 1, 1); /* original bitstream */
970 put_bits(&s->pb, 1, 0); /* no time code 1 */
971 put_bits(&s->pb, 1, 0); /* no time code 2 */
972 put_bits(&s->pb, 1, 0); /* no addtional bit stream info */
975 /* symetric quantization on 'levels' levels */
976 static inline int sym_quant(int c, int e, int levels)
981 v = (levels * (c << e)) >> 24;
983 v = (levels >> 1) + v;
985 v = (levels * ((-c) << e)) >> 24;
987 v = (levels >> 1) - v;
989 assert (v >= 0 && v < levels);
993 /* asymetric quantization on 2^qbits levels */
994 static inline int asym_quant(int c, int e, int qbits)
998 lshift = e + qbits - 24;
1005 m = (1 << (qbits-1));
1009 return v & ((1 << qbits)-1);
1012 /* Output one audio block. There are NB_BLOCKS audio blocks in one AC3
1014 static void output_audio_block(AC3EncodeContext *s,
1015 uint8_t exp_strategy[AC3_MAX_CHANNELS],
1016 uint8_t encoded_exp[AC3_MAX_CHANNELS][N/2],
1017 uint8_t bap[AC3_MAX_CHANNELS][N/2],
1018 int32_t mdct_coefs[AC3_MAX_CHANNELS][N/2],
1019 int8_t global_exp[AC3_MAX_CHANNELS],
1022 int ch, nb_groups, group_size, i, baie, rbnd;
1024 uint16_t qmant[AC3_MAX_CHANNELS][N/2];
1026 int mant1_cnt, mant2_cnt, mant4_cnt;
1027 uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
1028 int delta0, delta1, delta2;
1030 for(ch=0;ch<s->nb_channels;ch++)
1031 put_bits(&s->pb, 1, 0); /* 512 point MDCT */
1032 for(ch=0;ch<s->nb_channels;ch++)
1033 put_bits(&s->pb, 1, 1); /* no dither */
1034 put_bits(&s->pb, 1, 0); /* no dynamic range */
1035 if (block_num == 0) {
1036 /* for block 0, even if no coupling, we must say it. This is a
1038 put_bits(&s->pb, 1, 1); /* coupling strategy present */
1039 put_bits(&s->pb, 1, 0); /* no coupling strategy */
1041 put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1048 /* first block must define rematrixing (rematstr) */
1049 put_bits(&s->pb, 1, 1);
1051 /* dummy rematrixing rematflg(1:4)=0 */
1052 for (rbnd=0;rbnd<4;rbnd++)
1053 put_bits(&s->pb, 1, 0);
1057 /* no matrixing (but should be used in the future) */
1058 put_bits(&s->pb, 1, 0);
1064 static int count = 0;
1065 av_log(NULL, AV_LOG_DEBUG, "Block #%d (%d)\n", block_num, count++);
1068 /* exponent strategy */
1069 for(ch=0;ch<s->nb_channels;ch++) {
1070 put_bits(&s->pb, 2, exp_strategy[ch]);
1074 put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
1077 for(ch=0;ch<s->nb_channels;ch++) {
1078 if (exp_strategy[ch] != EXP_REUSE)
1079 put_bits(&s->pb, 6, s->chbwcod[ch]);
1083 for (ch = 0; ch < s->nb_all_channels; ch++) {
1084 switch(exp_strategy[ch]) {
1098 nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
1099 p = encoded_exp[ch];
1101 /* first exponent */
1103 put_bits(&s->pb, 4, exp1);
1105 /* next ones are delta encoded */
1106 for(i=0;i<nb_groups;i++) {
1107 /* merge three delta in one code */
1111 delta0 = exp1 - exp0 + 2;
1116 delta1 = exp1 - exp0 + 2;
1121 delta2 = exp1 - exp0 + 2;
1123 put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
1126 if (ch != s->lfe_channel)
1127 put_bits(&s->pb, 2, 0); /* no gain range info */
1130 /* bit allocation info */
1131 baie = (block_num == 0);
1132 put_bits(&s->pb, 1, baie);
1134 put_bits(&s->pb, 2, s->sdecaycod);
1135 put_bits(&s->pb, 2, s->fdecaycod);
1136 put_bits(&s->pb, 2, s->sgaincod);
1137 put_bits(&s->pb, 2, s->dbkneecod);
1138 put_bits(&s->pb, 3, s->floorcod);
1142 put_bits(&s->pb, 1, baie); /* always present with bai */
1144 put_bits(&s->pb, 6, s->csnroffst);
1145 for(ch=0;ch<s->nb_all_channels;ch++) {
1146 put_bits(&s->pb, 4, s->fsnroffst[ch]);
1147 put_bits(&s->pb, 3, s->fgaincod[ch]);
1151 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1152 put_bits(&s->pb, 1, 0); /* no data to skip */
1154 /* mantissa encoding : we use two passes to handle the grouping. A
1155 one pass method may be faster, but it would necessitate to
1156 modify the output stream. */
1158 /* first pass: quantize */
1159 mant1_cnt = mant2_cnt = mant4_cnt = 0;
1160 qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
1162 for (ch = 0; ch < s->nb_all_channels; ch++) {
1165 for(i=0;i<s->nb_coefs[ch];i++) {
1166 c = mdct_coefs[ch][i];
1167 e = encoded_exp[ch][i] - global_exp[ch];
1174 v = sym_quant(c, e, 3);
1177 qmant1_ptr = &qmant[ch][i];
1182 *qmant1_ptr += 3 * v;
1194 v = sym_quant(c, e, 5);
1197 qmant2_ptr = &qmant[ch][i];
1202 *qmant2_ptr += 5 * v;
1214 v = sym_quant(c, e, 7);
1217 v = sym_quant(c, e, 11);
1220 qmant4_ptr = &qmant[ch][i];
1232 v = sym_quant(c, e, 15);
1235 v = asym_quant(c, e, 14);
1238 v = asym_quant(c, e, 16);
1241 v = asym_quant(c, e, b - 1);
1248 /* second pass : output the values */
1249 for (ch = 0; ch < s->nb_all_channels; ch++) {
1252 for(i=0;i<s->nb_coefs[ch];i++) {
1260 put_bits(&s->pb, 5, q);
1264 put_bits(&s->pb, 7, q);
1267 put_bits(&s->pb, 3, q);
1271 put_bits(&s->pb, 7, q);
1274 put_bits(&s->pb, 14, q);
1277 put_bits(&s->pb, 16, q);
1280 put_bits(&s->pb, b - 1, q);
1287 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1289 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1305 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1311 r = mul_poly(r, a, poly);
1312 a = mul_poly(a, a, poly);
1319 /* compute log2(max(abs(tab[]))) */
1320 static int log2_tab(int16_t *tab, int n)
1331 static void lshift_tab(int16_t *tab, int n, int lshift)
1339 } else if (lshift < 0) {
1347 /* fill the end of the frame and compute the two crcs */
1348 static int output_frame_end(AC3EncodeContext *s)
1350 int frame_size, frame_size_58, n, crc1, crc2, crc_inv;
1353 frame_size = s->frame_size; /* frame size in words */
1354 /* align to 8 bits */
1355 flush_put_bits(&s->pb);
1356 /* add zero bytes to reach the frame size */
1358 n = 2 * s->frame_size - (pbBufPtr(&s->pb) - frame) - 2;
1361 memset(pbBufPtr(&s->pb), 0, n);
1363 /* Now we must compute both crcs : this is not so easy for crc1
1364 because it is at the beginning of the data... */
1365 frame_size_58 = (frame_size >> 1) + (frame_size >> 3);
1366 crc1 = bswap_16(av_crc(av_crc8005, 0, frame + 4, 2 * frame_size_58 - 4));
1367 /* XXX: could precompute crc_inv */
1368 crc_inv = pow_poly((CRC16_POLY >> 1), (16 * frame_size_58) - 16, CRC16_POLY);
1369 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1370 frame[2] = crc1 >> 8;
1373 crc2 = bswap_16(av_crc(av_crc8005, 0, frame + 2 * frame_size_58, (frame_size - frame_size_58) * 2 - 2));
1374 frame[2*frame_size - 2] = crc2 >> 8;
1375 frame[2*frame_size - 1] = crc2;
1377 // printf("n=%d frame_size=%d\n", n, frame_size);
1378 return frame_size * 2;
1381 static int AC3_encode_frame(AVCodecContext *avctx,
1382 unsigned char *frame, int buf_size, void *data)
1384 AC3EncodeContext *s = avctx->priv_data;
1385 int16_t *samples = data;
1387 int16_t input_samples[N];
1388 int32_t mdct_coef[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1389 uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1390 uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS];
1391 uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1392 uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1393 int8_t exp_samples[NB_BLOCKS][AC3_MAX_CHANNELS];
1397 for(ch=0;ch<s->nb_all_channels;ch++) {
1398 /* fixed mdct to the six sub blocks & exponent computation */
1399 for(i=0;i<NB_BLOCKS;i++) {
1403 /* compute input samples */
1404 memcpy(input_samples, s->last_samples[ch], N/2 * sizeof(int16_t));
1405 sinc = s->nb_all_channels;
1406 sptr = samples + (sinc * (N/2) * i) + ch;
1407 for(j=0;j<N/2;j++) {
1409 input_samples[j + N/2] = v;
1410 s->last_samples[ch][j] = v;
1414 /* apply the MDCT window */
1415 for(j=0;j<N/2;j++) {
1416 input_samples[j] = MUL16(input_samples[j],
1417 ac3_window[j]) >> 15;
1418 input_samples[N-j-1] = MUL16(input_samples[N-j-1],
1419 ac3_window[j]) >> 15;
1422 /* Normalize the samples to use the maximum available
1424 v = 14 - log2_tab(input_samples, N);
1427 exp_samples[i][ch] = v - 9;
1428 lshift_tab(input_samples, N, v);
1431 mdct512(mdct_coef[i][ch], input_samples);
1433 /* compute "exponents". We take into account the
1434 normalization there */
1435 for(j=0;j<N/2;j++) {
1437 v = abs(mdct_coef[i][ch][j]);
1441 e = 23 - av_log2(v) + exp_samples[i][ch];
1444 mdct_coef[i][ch][j] = 0;
1451 compute_exp_strategy(exp_strategy, exp, ch, ch == s->lfe_channel);
1453 /* compute the exponents as the decoder will see them. The
1454 EXP_REUSE case must be handled carefully : we select the
1455 min of the exponents */
1457 while (i < NB_BLOCKS) {
1459 while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE) {
1460 exponent_min(exp[i][ch], exp[j][ch], s->nb_coefs[ch]);
1463 frame_bits += encode_exp(encoded_exp[i][ch],
1464 exp[i][ch], s->nb_coefs[ch],
1465 exp_strategy[i][ch]);
1466 /* copy encoded exponents for reuse case */
1467 for(k=i+1;k<j;k++) {
1468 memcpy(encoded_exp[k][ch], encoded_exp[i][ch],
1469 s->nb_coefs[ch] * sizeof(uint8_t));
1475 /* adjust for fractional frame sizes */
1476 while(s->bits_written >= s->bit_rate*1000 && s->samples_written >= s->sample_rate) {
1477 s->bits_written -= s->bit_rate*1000;
1478 s->samples_written -= s->sample_rate;
1480 s->frame_size = s->frame_size_min + (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate*1000);
1481 s->bits_written += s->frame_size * 16;
1482 s->samples_written += AC3_FRAME_SIZE;
1484 compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
1485 /* everything is known... let's output the frame */
1486 output_frame_header(s, frame);
1488 for(i=0;i<NB_BLOCKS;i++) {
1489 output_audio_block(s, exp_strategy[i], encoded_exp[i],
1490 bap[i], mdct_coef[i], exp_samples[i], i);
1492 return output_frame_end(s);
1495 static int AC3_encode_close(AVCodecContext *avctx)
1497 av_freep(&avctx->coded_frame);
1502 /*************************************************************************/
1509 IComplex in[FN], in1[FN];
1511 float sum_re, sum_im, a;
1516 in[i].re = random() % 65535 - 32767;
1517 in[i].im = random() % 65535 - 32767;
1527 a = -2 * M_PI * (n * k) / FN;
1528 sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1529 sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1531 printf("%3d: %6d,%6d %6.0f,%6.0f\n",
1532 k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1536 void mdct_test(void)
1539 int32_t output[N/2];
1542 float s, a, err, e, emax;
1546 input[i] = (random() % 65535 - 32767) * 9 / 10;
1547 input1[i] = input[i];
1550 mdct512(output, input);
1553 for(k=0;k<N/2;k++) {
1556 a = (2*M_PI*(2*n+1+N/2)*(2*k+1) / (4 * N));
1557 s += input1[n] * cos(a);
1559 output1[k] = -2 * s / N;
1564 for(i=0;i<N/2;i++) {
1565 printf("%3d: %7d %7.0f\n", i, output[i], output1[i]);
1566 e = output[i] - output1[i];
1571 printf("err2=%f emax=%f\n", err / (N/2), emax);
1576 AC3EncodeContext ctx;
1577 unsigned char frame[AC3_MAX_CODED_FRAME_SIZE];
1578 short samples[AC3_FRAME_SIZE];
1581 AC3_encode_init(&ctx, 44100, 64000, 1);
1586 for(i=0;i<AC3_FRAME_SIZE;i++)
1587 samples[i] = (int)(sin(2*M_PI*i*1000.0/44100) * 10000);
1588 ret = AC3_encode_frame(&ctx, frame, samples);
1589 printf("ret=%d\n", ret);
1593 AVCodec ac3_encoder = {
1597 sizeof(AC3EncodeContext),