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;
65 static int16_t costab[64];
66 static int16_t sintab[64];
67 static int16_t fft_rev[512];
68 static int16_t xcos1[128];
69 static int16_t xsin1[128];
72 #define N (1 << MDCT_NBITS)
74 /* new exponents are sent if their Norm 1 exceed this number */
75 #define EXP_DIFF_THRESHOLD 1000
77 static void fft_init(int ln);
79 static inline int16_t fix15(float a)
82 v = (int)(a * (float)(1 << 15));
90 typedef struct IComplex {
94 static void fft_init(int ln)
101 for(i=0;i<(n/2);i++) {
102 alpha = 2 * M_PI * (float)i / (float)n;
103 costab[i] = fix15(cos(alpha));
104 sintab[i] = fix15(sin(alpha));
110 m |= ((i >> j) & 1) << (ln-j-1);
117 #define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1) \
124 pre = (bx + ax) >> 1;\
125 pim = (by + ay) >> 1;\
126 qre = (bx - ax) >> 1;\
127 qim = (by - ay) >> 1;\
130 #define MUL16(a,b) ((a) * (b))
132 #define CMUL(pre, pim, are, aim, bre, bim) \
134 pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;\
135 pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;\
139 /* do a 2^n point complex fft on 2^ln points. */
140 static void fft(IComplex *z, int ln)
144 register IComplex *p,*q;
166 BF(p[0].re, p[0].im, p[1].re, p[1].im,
167 p[0].re, p[0].im, p[1].re, p[1].im);
176 BF(p[0].re, p[0].im, p[2].re, p[2].im,
177 p[0].re, p[0].im, p[2].re, p[2].im);
178 BF(p[1].re, p[1].im, p[3].re, p[3].im,
179 p[1].re, p[1].im, p[3].im, -p[3].re);
191 for (j = 0; j < nblocks; ++j) {
193 BF(p->re, p->im, q->re, q->im,
194 p->re, p->im, q->re, q->im);
198 for(l = nblocks; l < np2; l += nblocks) {
199 CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
200 BF(p->re, p->im, q->re, q->im,
201 p->re, p->im, tmp_re, tmp_im);
208 nblocks = nblocks >> 1;
209 nloops = nloops << 1;
210 } while (nblocks != 0);
213 /* do a 512 point mdct */
214 static void mdct512(int32_t *out, int16_t *in)
216 int i, re, im, re1, im1;
220 /* shift to simplify computations */
222 rot[i] = -in[i + 3*N/4];
224 rot[i] = in[i - N/4];
228 re = ((int)rot[2*i] - (int)rot[N-1-2*i]) >> 1;
229 im = -((int)rot[N/2+2*i] - (int)rot[N/2-1-2*i]) >> 1;
230 CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
233 fft(x, MDCT_NBITS - 2);
239 CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
241 out[N/2-1-2*i] = re1;
245 /* XXX: use another norm ? */
246 static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
251 sum += abs(exp1[i] - exp2[i]);
256 static void compute_exp_strategy(uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
257 uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
263 /* estimate if the exponent variation & decide if they should be
264 reused in the next frame */
265 exp_strategy[0][ch] = EXP_NEW;
266 for(i=1;i<NB_BLOCKS;i++) {
267 exp_diff = calc_exp_diff(exp[i][ch], exp[i-1][ch], N/2);
269 av_log(NULL, AV_LOG_DEBUG, "exp_diff=%d\n", exp_diff);
271 if (exp_diff > EXP_DIFF_THRESHOLD)
272 exp_strategy[i][ch] = EXP_NEW;
274 exp_strategy[i][ch] = EXP_REUSE;
279 /* now select the encoding strategy type : if exponents are often
280 recoded, we use a coarse encoding */
282 while (i < NB_BLOCKS) {
284 while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE)
288 exp_strategy[i][ch] = EXP_D45;
292 exp_strategy[i][ch] = EXP_D25;
295 exp_strategy[i][ch] = EXP_D15;
302 /* set exp[i] to min(exp[i], exp1[i]) */
303 static void exponent_min(uint8_t exp[N/2], uint8_t exp1[N/2], int n)
308 if (exp1[i] < exp[i])
313 /* update the exponents so that they are the ones the decoder will
314 decode. Return the number of bits used to code the exponents */
315 static int encode_exp(uint8_t encoded_exp[N/2],
320 int group_size, nb_groups, i, j, k, exp_min;
323 switch(exp_strategy) {
335 nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
337 /* for each group, compute the minimum exponent */
338 exp1[0] = exp[0]; /* DC exponent is handled separately */
340 for(i=1;i<=nb_groups;i++) {
342 assert(exp_min >= 0 && exp_min <= 24);
343 for(j=1;j<group_size;j++) {
344 if (exp[k+j] < exp_min)
351 /* constraint for DC exponent */
355 /* Decrease the delta between each groups to within 2
356 * so that they can be differentially encoded */
357 for (i=1;i<=nb_groups;i++)
358 exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
359 for (i=nb_groups-1;i>=0;i--)
360 exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
362 /* now we have the exponent values the decoder will see */
363 encoded_exp[0] = exp1[0];
365 for(i=1;i<=nb_groups;i++) {
366 for(j=0;j<group_size;j++) {
367 encoded_exp[k+j] = exp1[i];
373 av_log(NULL, AV_LOG_DEBUG, "exponents: strategy=%d\n", exp_strategy);
374 for(i=0;i<=nb_groups * group_size;i++) {
375 av_log(NULL, AV_LOG_DEBUG, "%d ", encoded_exp[i]);
377 av_log(NULL, AV_LOG_DEBUG, "\n");
380 return 4 + (nb_groups / 3) * 7;
383 /* return the size in bits taken by the mantissa */
384 static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
389 for(i=0;i<nb_coefs;i++) {
396 /* 3 mantissa in 5 bits */
397 if (s->mant1_cnt == 0)
399 if (++s->mant1_cnt == 3)
403 /* 3 mantissa in 7 bits */
404 if (s->mant2_cnt == 0)
406 if (++s->mant2_cnt == 3)
413 /* 2 mantissa in 7 bits */
414 if (s->mant4_cnt == 0)
416 if (++s->mant4_cnt == 2)
434 static void bit_alloc_masking(AC3EncodeContext *s,
435 uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
436 uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
437 int16_t psd[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
438 int16_t mask[NB_BLOCKS][AC3_MAX_CHANNELS][50])
441 int16_t bndpsd[NB_BLOCKS][AC3_MAX_CHANNELS][50];
443 for(blk=0; blk<NB_BLOCKS; blk++) {
444 for(ch=0;ch<s->nb_all_channels;ch++) {
445 if(exp_strategy[blk][ch] == EXP_REUSE) {
446 memcpy(psd[blk][ch], psd[blk-1][ch], (N/2)*sizeof(int16_t));
447 memcpy(mask[blk][ch], mask[blk-1][ch], 50*sizeof(int16_t));
449 ff_ac3_bit_alloc_calc_psd(encoded_exp[blk][ch], 0,
451 psd[blk][ch], bndpsd[blk][ch]);
452 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, bndpsd[blk][ch],
454 ff_fgaintab[s->fgaincod[ch]],
455 ch == s->lfe_channel,
456 2, 0, NULL, NULL, NULL,
463 static int bit_alloc(AC3EncodeContext *s,
464 int16_t mask[NB_BLOCKS][AC3_MAX_CHANNELS][50],
465 int16_t psd[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
466 uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
467 int frame_bits, int csnroffst, int fsnroffst)
472 snroffset = (((csnroffst - 15) << 4) + fsnroffst) << 2;
475 for(i=0;i<NB_BLOCKS;i++) {
479 for(ch=0;ch<s->nb_all_channels;ch++) {
480 ff_ac3_bit_alloc_calc_bap(mask[i][ch], psd[i][ch], 0,
481 s->nb_coefs[ch], snroffset,
482 s->bit_alloc.floor, bap[i][ch]);
483 frame_bits += compute_mantissa_size(s, bap[i][ch],
488 printf("csnr=%d fsnr=%d frame_bits=%d diff=%d\n",
489 csnroffst, fsnroffst, frame_bits,
490 16 * s->frame_size - ((frame_bits + 7) & ~7));
492 return 16 * s->frame_size - frame_bits;
497 static int compute_bit_allocation(AC3EncodeContext *s,
498 uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
499 uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
500 uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
504 int csnroffst, fsnroffst;
505 uint8_t bap1[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
506 int16_t psd[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
507 int16_t mask[NB_BLOCKS][AC3_MAX_CHANNELS][50];
508 static int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
510 /* init default parameters */
516 for(ch=0;ch<s->nb_all_channels;ch++)
519 /* compute real values */
520 s->bit_alloc.fscod = s->fscod;
521 s->bit_alloc.halfratecod = s->halfratecod;
522 s->bit_alloc.sdecay = ff_sdecaytab[s->sdecaycod] >> s->halfratecod;
523 s->bit_alloc.fdecay = ff_fdecaytab[s->fdecaycod] >> s->halfratecod;
524 s->bit_alloc.sgain = ff_sgaintab[s->sgaincod];
525 s->bit_alloc.dbknee = ff_dbkneetab[s->dbkneecod];
526 s->bit_alloc.floor = ff_floortab[s->floorcod];
530 // if (s->acmod == 2)
532 frame_bits += frame_bits_inc[s->acmod];
535 for(i=0;i<NB_BLOCKS;i++) {
536 frame_bits += s->nb_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
538 frame_bits++; /* rematstr */
539 if(i==0) frame_bits += 4;
541 frame_bits += 2 * s->nb_channels; /* chexpstr[2] * c */
543 frame_bits++; /* lfeexpstr */
544 for(ch=0;ch<s->nb_channels;ch++) {
545 if (exp_strategy[i][ch] != EXP_REUSE)
546 frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
548 frame_bits++; /* baie */
549 frame_bits++; /* snr */
550 frame_bits += 2; /* delta / skip */
552 frame_bits++; /* cplinu for block 0 */
554 /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
556 /* (fsnoffset[4] + fgaincod[4]) * c */
557 frame_bits += 2*4 + 3 + 6 + s->nb_all_channels * (4 + 3);
559 /* auxdatae, crcrsv */
565 /* calculate psd and masking curve before doing bit allocation */
566 bit_alloc_masking(s, encoded_exp, exp_strategy, psd, mask);
568 /* now the big work begins : do the bit allocation. Modify the snr
569 offset until we can pack everything in the requested frame size */
571 csnroffst = s->csnroffst;
572 while (csnroffst >= 0 &&
573 bit_alloc(s, mask, psd, bap, frame_bits, csnroffst, 0) < 0)
574 csnroffst -= SNR_INC1;
576 av_log(NULL, AV_LOG_ERROR, "Bit allocation failed, try increasing the bitrate, -ab 384 for example!\n");
579 while ((csnroffst + SNR_INC1) <= 63 &&
580 bit_alloc(s, mask, psd, bap1, frame_bits,
581 csnroffst + SNR_INC1, 0) >= 0) {
582 csnroffst += SNR_INC1;
583 memcpy(bap, bap1, sizeof(bap1));
585 while ((csnroffst + 1) <= 63 &&
586 bit_alloc(s, mask, psd, bap1, frame_bits, csnroffst + 1, 0) >= 0) {
588 memcpy(bap, bap1, sizeof(bap1));
592 while ((fsnroffst + SNR_INC1) <= 15 &&
593 bit_alloc(s, mask, psd, bap1, frame_bits,
594 csnroffst, fsnroffst + SNR_INC1) >= 0) {
595 fsnroffst += SNR_INC1;
596 memcpy(bap, bap1, sizeof(bap1));
598 while ((fsnroffst + 1) <= 15 &&
599 bit_alloc(s, mask, psd, bap1, frame_bits,
600 csnroffst, fsnroffst + 1) >= 0) {
602 memcpy(bap, bap1, sizeof(bap1));
605 s->csnroffst = csnroffst;
606 for(ch=0;ch<s->nb_all_channels;ch++)
607 s->fsnroffst[ch] = fsnroffst;
608 #if defined(DEBUG_BITALLOC)
613 for(ch=0;ch<s->nb_all_channels;ch++) {
614 printf("Block #%d Ch%d:\n", i, ch);
616 for(j=0;j<s->nb_coefs[ch];j++) {
617 printf("%d ",bap[i][ch][j]);
627 static int AC3_encode_init(AVCodecContext *avctx)
629 int freq = avctx->sample_rate;
630 int bitrate = avctx->bit_rate;
631 int channels = avctx->channels;
632 AC3EncodeContext *s = avctx->priv_data;
635 static const uint8_t acmod_defs[6] = {
639 0x06, /* L R SL SR */
640 0x07, /* L C R SL SR */
641 0x07, /* L C R SL SR (+LFE) */
644 avctx->frame_size = AC3_FRAME_SIZE;
648 /* number of channels */
649 if (channels < 1 || channels > 6)
651 s->acmod = acmod_defs[channels - 1];
652 s->lfe = (channels == 6) ? 1 : 0;
653 s->nb_all_channels = channels;
654 s->nb_channels = channels > 5 ? 5 : channels;
655 s->lfe_channel = s->lfe ? 5 : -1;
660 if ((ff_ac3_freqs[j] >> i) == freq)
665 s->sample_rate = freq;
668 s->bsid = 8 + s->halfratecod;
669 s->bsmod = 0; /* complete main audio service */
671 /* bitrate & frame size */
674 if ((ff_ac3_bitratetab[i] >> s->halfratecod) == bitrate)
679 s->bit_rate = bitrate;
680 s->frmsizecod = i << 1;
681 s->frame_size_min = ff_ac3_frame_sizes[s->frmsizecod][s->fscod];
683 s->samples_written = 0;
684 s->frame_size = s->frame_size_min;
686 /* bit allocation init */
687 for(ch=0;ch<s->nb_channels;ch++) {
688 /* bandwidth for each channel */
689 /* XXX: should compute the bandwidth according to the frame
690 size, so that we avoid anoying high freq artefacts */
691 s->chbwcod[ch] = 50; /* sample bandwidth as mpeg audio layer 2 table 0 */
692 s->nb_coefs[ch] = ((s->chbwcod[ch] + 12) * 3) + 37;
695 s->nb_coefs[s->lfe_channel] = 7; /* fixed */
697 /* initial snr offset */
701 fft_init(MDCT_NBITS - 2);
703 alpha = 2 * M_PI * (i + 1.0 / 8.0) / (float)N;
704 xcos1[i] = fix15(-cos(alpha));
705 xsin1[i] = fix15(-sin(alpha));
708 avctx->coded_frame= avcodec_alloc_frame();
709 avctx->coded_frame->key_frame= 1;
714 /* output the AC3 frame header */
715 static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
717 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
719 put_bits(&s->pb, 16, 0x0b77); /* frame header */
720 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
721 put_bits(&s->pb, 2, s->fscod);
722 put_bits(&s->pb, 6, s->frmsizecod + (s->frame_size - s->frame_size_min));
723 put_bits(&s->pb, 5, s->bsid);
724 put_bits(&s->pb, 3, s->bsmod);
725 put_bits(&s->pb, 3, s->acmod);
726 if ((s->acmod & 0x01) && s->acmod != 0x01)
727 put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
729 put_bits(&s->pb, 2, 1); /* XXX -6 dB */
730 if (s->acmod == 0x02)
731 put_bits(&s->pb, 2, 0); /* surround not indicated */
732 put_bits(&s->pb, 1, s->lfe); /* LFE */
733 put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
734 put_bits(&s->pb, 1, 0); /* no compression control word */
735 put_bits(&s->pb, 1, 0); /* no lang code */
736 put_bits(&s->pb, 1, 0); /* no audio production info */
737 put_bits(&s->pb, 1, 0); /* no copyright */
738 put_bits(&s->pb, 1, 1); /* original bitstream */
739 put_bits(&s->pb, 1, 0); /* no time code 1 */
740 put_bits(&s->pb, 1, 0); /* no time code 2 */
741 put_bits(&s->pb, 1, 0); /* no addtional bit stream info */
744 /* symetric quantization on 'levels' levels */
745 static inline int sym_quant(int c, int e, int levels)
750 v = (levels * (c << e)) >> 24;
752 v = (levels >> 1) + v;
754 v = (levels * ((-c) << e)) >> 24;
756 v = (levels >> 1) - v;
758 assert (v >= 0 && v < levels);
762 /* asymetric quantization on 2^qbits levels */
763 static inline int asym_quant(int c, int e, int qbits)
767 lshift = e + qbits - 24;
774 m = (1 << (qbits-1));
778 return v & ((1 << qbits)-1);
781 /* Output one audio block. There are NB_BLOCKS audio blocks in one AC3
783 static void output_audio_block(AC3EncodeContext *s,
784 uint8_t exp_strategy[AC3_MAX_CHANNELS],
785 uint8_t encoded_exp[AC3_MAX_CHANNELS][N/2],
786 uint8_t bap[AC3_MAX_CHANNELS][N/2],
787 int32_t mdct_coefs[AC3_MAX_CHANNELS][N/2],
788 int8_t global_exp[AC3_MAX_CHANNELS],
791 int ch, nb_groups, group_size, i, baie, rbnd;
793 uint16_t qmant[AC3_MAX_CHANNELS][N/2];
795 int mant1_cnt, mant2_cnt, mant4_cnt;
796 uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
797 int delta0, delta1, delta2;
799 for(ch=0;ch<s->nb_channels;ch++)
800 put_bits(&s->pb, 1, 0); /* 512 point MDCT */
801 for(ch=0;ch<s->nb_channels;ch++)
802 put_bits(&s->pb, 1, 1); /* no dither */
803 put_bits(&s->pb, 1, 0); /* no dynamic range */
804 if (block_num == 0) {
805 /* for block 0, even if no coupling, we must say it. This is a
807 put_bits(&s->pb, 1, 1); /* coupling strategy present */
808 put_bits(&s->pb, 1, 0); /* no coupling strategy */
810 put_bits(&s->pb, 1, 0); /* no new coupling strategy */
817 /* first block must define rematrixing (rematstr) */
818 put_bits(&s->pb, 1, 1);
820 /* dummy rematrixing rematflg(1:4)=0 */
821 for (rbnd=0;rbnd<4;rbnd++)
822 put_bits(&s->pb, 1, 0);
826 /* no matrixing (but should be used in the future) */
827 put_bits(&s->pb, 1, 0);
833 static int count = 0;
834 av_log(NULL, AV_LOG_DEBUG, "Block #%d (%d)\n", block_num, count++);
837 /* exponent strategy */
838 for(ch=0;ch<s->nb_channels;ch++) {
839 put_bits(&s->pb, 2, exp_strategy[ch]);
843 put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
846 for(ch=0;ch<s->nb_channels;ch++) {
847 if (exp_strategy[ch] != EXP_REUSE)
848 put_bits(&s->pb, 6, s->chbwcod[ch]);
852 for (ch = 0; ch < s->nb_all_channels; ch++) {
853 switch(exp_strategy[ch]) {
867 nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
872 put_bits(&s->pb, 4, exp1);
874 /* next ones are delta encoded */
875 for(i=0;i<nb_groups;i++) {
876 /* merge three delta in one code */
880 delta0 = exp1 - exp0 + 2;
885 delta1 = exp1 - exp0 + 2;
890 delta2 = exp1 - exp0 + 2;
892 put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
895 if (ch != s->lfe_channel)
896 put_bits(&s->pb, 2, 0); /* no gain range info */
899 /* bit allocation info */
900 baie = (block_num == 0);
901 put_bits(&s->pb, 1, baie);
903 put_bits(&s->pb, 2, s->sdecaycod);
904 put_bits(&s->pb, 2, s->fdecaycod);
905 put_bits(&s->pb, 2, s->sgaincod);
906 put_bits(&s->pb, 2, s->dbkneecod);
907 put_bits(&s->pb, 3, s->floorcod);
911 put_bits(&s->pb, 1, baie); /* always present with bai */
913 put_bits(&s->pb, 6, s->csnroffst);
914 for(ch=0;ch<s->nb_all_channels;ch++) {
915 put_bits(&s->pb, 4, s->fsnroffst[ch]);
916 put_bits(&s->pb, 3, s->fgaincod[ch]);
920 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
921 put_bits(&s->pb, 1, 0); /* no data to skip */
923 /* mantissa encoding : we use two passes to handle the grouping. A
924 one pass method may be faster, but it would necessitate to
925 modify the output stream. */
927 /* first pass: quantize */
928 mant1_cnt = mant2_cnt = mant4_cnt = 0;
929 qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
931 for (ch = 0; ch < s->nb_all_channels; ch++) {
934 for(i=0;i<s->nb_coefs[ch];i++) {
935 c = mdct_coefs[ch][i];
936 e = encoded_exp[ch][i] - global_exp[ch];
943 v = sym_quant(c, e, 3);
946 qmant1_ptr = &qmant[ch][i];
951 *qmant1_ptr += 3 * v;
963 v = sym_quant(c, e, 5);
966 qmant2_ptr = &qmant[ch][i];
971 *qmant2_ptr += 5 * v;
983 v = sym_quant(c, e, 7);
986 v = sym_quant(c, e, 11);
989 qmant4_ptr = &qmant[ch][i];
1001 v = sym_quant(c, e, 15);
1004 v = asym_quant(c, e, 14);
1007 v = asym_quant(c, e, 16);
1010 v = asym_quant(c, e, b - 1);
1017 /* second pass : output the values */
1018 for (ch = 0; ch < s->nb_all_channels; ch++) {
1021 for(i=0;i<s->nb_coefs[ch];i++) {
1029 put_bits(&s->pb, 5, q);
1033 put_bits(&s->pb, 7, q);
1036 put_bits(&s->pb, 3, q);
1040 put_bits(&s->pb, 7, q);
1043 put_bits(&s->pb, 14, q);
1046 put_bits(&s->pb, 16, q);
1049 put_bits(&s->pb, b - 1, q);
1056 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1058 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1074 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1080 r = mul_poly(r, a, poly);
1081 a = mul_poly(a, a, poly);
1088 /* compute log2(max(abs(tab[]))) */
1089 static int log2_tab(int16_t *tab, int n)
1100 static void lshift_tab(int16_t *tab, int n, int lshift)
1108 } else if (lshift < 0) {
1116 /* fill the end of the frame and compute the two crcs */
1117 static int output_frame_end(AC3EncodeContext *s)
1119 int frame_size, frame_size_58, n, crc1, crc2, crc_inv;
1122 frame_size = s->frame_size; /* frame size in words */
1123 /* align to 8 bits */
1124 flush_put_bits(&s->pb);
1125 /* add zero bytes to reach the frame size */
1127 n = 2 * s->frame_size - (pbBufPtr(&s->pb) - frame) - 2;
1130 memset(pbBufPtr(&s->pb), 0, n);
1132 /* Now we must compute both crcs : this is not so easy for crc1
1133 because it is at the beginning of the data... */
1134 frame_size_58 = (frame_size >> 1) + (frame_size >> 3);
1135 crc1 = bswap_16(av_crc(av_crc8005, 0, frame + 4, 2 * frame_size_58 - 4));
1136 /* XXX: could precompute crc_inv */
1137 crc_inv = pow_poly((CRC16_POLY >> 1), (16 * frame_size_58) - 16, CRC16_POLY);
1138 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1139 AV_WB16(frame+2,crc1);
1141 crc2 = bswap_16(av_crc(av_crc8005, 0, frame + 2 * frame_size_58, (frame_size - frame_size_58) * 2 - 2));
1142 AV_WB16(frame+2*frame_size-2,crc2);
1144 // printf("n=%d frame_size=%d\n", n, frame_size);
1145 return frame_size * 2;
1148 static int AC3_encode_frame(AVCodecContext *avctx,
1149 unsigned char *frame, int buf_size, void *data)
1151 AC3EncodeContext *s = avctx->priv_data;
1152 int16_t *samples = data;
1154 int16_t input_samples[N];
1155 int32_t mdct_coef[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1156 uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1157 uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS];
1158 uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1159 uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1160 int8_t exp_samples[NB_BLOCKS][AC3_MAX_CHANNELS];
1164 for(ch=0;ch<s->nb_all_channels;ch++) {
1165 /* fixed mdct to the six sub blocks & exponent computation */
1166 for(i=0;i<NB_BLOCKS;i++) {
1170 /* compute input samples */
1171 memcpy(input_samples, s->last_samples[ch], N/2 * sizeof(int16_t));
1172 sinc = s->nb_all_channels;
1173 sptr = samples + (sinc * (N/2) * i) + ch;
1174 for(j=0;j<N/2;j++) {
1176 input_samples[j + N/2] = v;
1177 s->last_samples[ch][j] = v;
1181 /* apply the MDCT window */
1182 for(j=0;j<N/2;j++) {
1183 input_samples[j] = MUL16(input_samples[j],
1184 ff_ac3_window[j]) >> 15;
1185 input_samples[N-j-1] = MUL16(input_samples[N-j-1],
1186 ff_ac3_window[j]) >> 15;
1189 /* Normalize the samples to use the maximum available
1191 v = 14 - log2_tab(input_samples, N);
1194 exp_samples[i][ch] = v - 9;
1195 lshift_tab(input_samples, N, v);
1198 mdct512(mdct_coef[i][ch], input_samples);
1200 /* compute "exponents". We take into account the
1201 normalization there */
1202 for(j=0;j<N/2;j++) {
1204 v = abs(mdct_coef[i][ch][j]);
1208 e = 23 - av_log2(v) + exp_samples[i][ch];
1211 mdct_coef[i][ch][j] = 0;
1218 compute_exp_strategy(exp_strategy, exp, ch, ch == s->lfe_channel);
1220 /* compute the exponents as the decoder will see them. The
1221 EXP_REUSE case must be handled carefully : we select the
1222 min of the exponents */
1224 while (i < NB_BLOCKS) {
1226 while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE) {
1227 exponent_min(exp[i][ch], exp[j][ch], s->nb_coefs[ch]);
1230 frame_bits += encode_exp(encoded_exp[i][ch],
1231 exp[i][ch], s->nb_coefs[ch],
1232 exp_strategy[i][ch]);
1233 /* copy encoded exponents for reuse case */
1234 for(k=i+1;k<j;k++) {
1235 memcpy(encoded_exp[k][ch], encoded_exp[i][ch],
1236 s->nb_coefs[ch] * sizeof(uint8_t));
1242 /* adjust for fractional frame sizes */
1243 while(s->bits_written >= s->bit_rate*1000 && s->samples_written >= s->sample_rate) {
1244 s->bits_written -= s->bit_rate*1000;
1245 s->samples_written -= s->sample_rate;
1247 s->frame_size = s->frame_size_min + (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate*1000);
1248 s->bits_written += s->frame_size * 16;
1249 s->samples_written += AC3_FRAME_SIZE;
1251 compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
1252 /* everything is known... let's output the frame */
1253 output_frame_header(s, frame);
1255 for(i=0;i<NB_BLOCKS;i++) {
1256 output_audio_block(s, exp_strategy[i], encoded_exp[i],
1257 bap[i], mdct_coef[i], exp_samples[i], i);
1259 return output_frame_end(s);
1262 static int AC3_encode_close(AVCodecContext *avctx)
1264 av_freep(&avctx->coded_frame);
1269 /*************************************************************************/
1276 IComplex in[FN], in1[FN];
1278 float sum_re, sum_im, a;
1283 in[i].re = random() % 65535 - 32767;
1284 in[i].im = random() % 65535 - 32767;
1294 a = -2 * M_PI * (n * k) / FN;
1295 sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1296 sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1298 printf("%3d: %6d,%6d %6.0f,%6.0f\n",
1299 k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1303 void mdct_test(void)
1306 int32_t output[N/2];
1309 float s, a, err, e, emax;
1313 input[i] = (random() % 65535 - 32767) * 9 / 10;
1314 input1[i] = input[i];
1317 mdct512(output, input);
1320 for(k=0;k<N/2;k++) {
1323 a = (2*M_PI*(2*n+1+N/2)*(2*k+1) / (4 * N));
1324 s += input1[n] * cos(a);
1326 output1[k] = -2 * s / N;
1331 for(i=0;i<N/2;i++) {
1332 printf("%3d: %7d %7.0f\n", i, output[i], output1[i]);
1333 e = output[i] - output1[i];
1338 printf("err2=%f emax=%f\n", err / (N/2), emax);
1343 AC3EncodeContext ctx;
1344 unsigned char frame[AC3_MAX_CODED_FRAME_SIZE];
1345 short samples[AC3_FRAME_SIZE];
1348 AC3_encode_init(&ctx, 44100, 64000, 1);
1353 for(i=0;i<AC3_FRAME_SIZE;i++)
1354 samples[i] = (int)(sin(2*M_PI*i*1000.0/44100) * 10000);
1355 ret = AC3_encode_frame(&ctx, frame, samples);
1356 printf("ret=%d\n", ret);
1360 AVCodec ac3_encoder = {
1364 sizeof(AC3EncodeContext),