2 * The simplest AC-3 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 AC-3 encoder.
27 //#define DEBUG_BITALLOC
28 #include "libavcore/audioconvert.h"
29 #include "libavutil/crc.h"
31 #include "libavutil/common.h" /* for av_reverse */
34 #include "audioconvert.h"
36 typedef struct AC3EncodeContext {
41 const uint8_t *channel_map;
43 unsigned int sample_rate;
44 unsigned int bitstream_id;
45 unsigned int frame_size_min; /* minimum frame size in case rounding is necessary */
46 unsigned int frame_size; /* current frame size in words */
47 unsigned int bits_written;
48 unsigned int samples_written;
50 unsigned int frame_size_code;
51 unsigned int sr_code; /* frequency */
52 unsigned int channel_mode;
54 unsigned int bitstream_mode;
55 short last_samples[AC3_MAX_CHANNELS][256];
56 unsigned int chbwcod[AC3_MAX_CHANNELS];
57 int nb_coefs[AC3_MAX_CHANNELS];
59 /* bitrate allocation control */
60 int slow_gain_code, slow_decay_code, fast_decay_code, db_per_bit_code, floor_code;
61 AC3BitAllocParameters bit_alloc;
62 int coarse_snr_offset;
63 int fast_gain_code[AC3_MAX_CHANNELS];
64 int fine_snr_offset[AC3_MAX_CHANNELS];
65 /* mantissa encoding */
66 int mant1_cnt, mant2_cnt, mant4_cnt;
69 static int16_t costab[64];
70 static int16_t sintab[64];
71 static int16_t xcos1[128];
72 static int16_t xsin1[128];
75 #define N (1 << MDCT_NBITS)
77 /* new exponents are sent if their Norm 1 exceed this number */
78 #define EXP_DIFF_THRESHOLD 1000
80 static inline int16_t fix15(float a)
83 v = (int)(a * (float)(1 << 15));
91 typedef struct IComplex {
95 static av_cold void fft_init(int ln)
102 for(i=0;i<(n/2);i++) {
103 alpha = 2 * M_PI * (float)i / (float)n;
104 costab[i] = fix15(cos(alpha));
105 sintab[i] = fix15(sin(alpha));
110 #define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1) \
117 pre = (bx + ax) >> 1;\
118 pim = (by + ay) >> 1;\
119 qre = (bx - ax) >> 1;\
120 qim = (by - ay) >> 1;\
123 #define CMUL(pre, pim, are, aim, bre, bim) \
125 pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;\
126 pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;\
130 /* do a 2^n point complex fft on 2^ln points. */
131 static void fft(IComplex *z, int ln)
135 register IComplex *p,*q;
142 int k = av_reverse[j] >> (8 - ln);
144 FFSWAP(IComplex, z[k], z[j]);
152 BF(p[0].re, p[0].im, p[1].re, p[1].im,
153 p[0].re, p[0].im, p[1].re, p[1].im);
162 BF(p[0].re, p[0].im, p[2].re, p[2].im,
163 p[0].re, p[0].im, p[2].re, p[2].im);
164 BF(p[1].re, p[1].im, p[3].re, p[3].im,
165 p[1].re, p[1].im, p[3].im, -p[3].re);
177 for (j = 0; j < nblocks; ++j) {
179 BF(p->re, p->im, q->re, q->im,
180 p->re, p->im, q->re, q->im);
184 for(l = nblocks; l < np2; l += nblocks) {
185 CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
186 BF(p->re, p->im, q->re, q->im,
187 p->re, p->im, tmp_re, tmp_im);
194 nblocks = nblocks >> 1;
195 nloops = nloops << 1;
196 } while (nblocks != 0);
199 /* do a 512 point mdct */
200 static void mdct512(int32_t *out, int16_t *in)
202 int i, re, im, re1, im1;
206 /* shift to simplify computations */
208 rot[i] = -in[i + 3*N/4];
210 rot[i] = in[i - N/4];
214 re = ((int)rot[2*i] - (int)rot[N-1-2*i]) >> 1;
215 im = -((int)rot[N/2+2*i] - (int)rot[N/2-1-2*i]) >> 1;
216 CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
219 fft(x, MDCT_NBITS - 2);
225 CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
227 out[N/2-1-2*i] = re1;
231 /* XXX: use another norm ? */
232 static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
237 sum += abs(exp1[i] - exp2[i]);
242 static void compute_exp_strategy(uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
243 uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
249 /* estimate if the exponent variation & decide if they should be
250 reused in the next frame */
251 exp_strategy[0][ch] = EXP_NEW;
252 for(i=1;i<NB_BLOCKS;i++) {
253 exp_diff = calc_exp_diff(exp[i][ch], exp[i-1][ch], N/2);
254 dprintf(NULL, "exp_diff=%d\n", exp_diff);
255 if (exp_diff > EXP_DIFF_THRESHOLD)
256 exp_strategy[i][ch] = EXP_NEW;
258 exp_strategy[i][ch] = EXP_REUSE;
263 /* now select the encoding strategy type : if exponents are often
264 recoded, we use a coarse encoding */
266 while (i < NB_BLOCKS) {
268 while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE)
272 exp_strategy[i][ch] = EXP_D45;
276 exp_strategy[i][ch] = EXP_D25;
279 exp_strategy[i][ch] = EXP_D15;
286 /* set exp[i] to min(exp[i], exp1[i]) */
287 static void exponent_min(uint8_t exp[N/2], uint8_t exp1[N/2], int n)
292 if (exp1[i] < exp[i])
297 /* update the exponents so that they are the ones the decoder will
298 decode. Return the number of bits used to code the exponents */
299 static int encode_exp(uint8_t encoded_exp[N/2],
304 int group_size, nb_groups, i, j, k, exp_min;
307 switch(exp_strategy) {
319 nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
321 /* for each group, compute the minimum exponent */
322 exp1[0] = exp[0]; /* DC exponent is handled separately */
324 for(i=1;i<=nb_groups;i++) {
326 assert(exp_min >= 0 && exp_min <= 24);
327 for(j=1;j<group_size;j++) {
328 if (exp[k+j] < exp_min)
335 /* constraint for DC exponent */
339 /* Decrease the delta between each groups to within 2
340 * so that they can be differentially encoded */
341 for (i=1;i<=nb_groups;i++)
342 exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
343 for (i=nb_groups-1;i>=0;i--)
344 exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
346 /* now we have the exponent values the decoder will see */
347 encoded_exp[0] = exp1[0];
349 for(i=1;i<=nb_groups;i++) {
350 for(j=0;j<group_size;j++) {
351 encoded_exp[k+j] = exp1[i];
357 av_log(NULL, AV_LOG_DEBUG, "exponents: strategy=%d\n", exp_strategy);
358 for(i=0;i<=nb_groups * group_size;i++) {
359 av_log(NULL, AV_LOG_DEBUG, "%d ", encoded_exp[i]);
361 av_log(NULL, AV_LOG_DEBUG, "\n");
364 return 4 + (nb_groups / 3) * 7;
367 /* return the size in bits taken by the mantissa */
368 static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
373 for(i=0;i<nb_coefs;i++) {
380 /* 3 mantissa in 5 bits */
381 if (s->mant1_cnt == 0)
383 if (++s->mant1_cnt == 3)
387 /* 3 mantissa in 7 bits */
388 if (s->mant2_cnt == 0)
390 if (++s->mant2_cnt == 3)
397 /* 2 mantissa in 7 bits */
398 if (s->mant4_cnt == 0)
400 if (++s->mant4_cnt == 2)
418 static void bit_alloc_masking(AC3EncodeContext *s,
419 uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
420 uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
421 int16_t psd[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
422 int16_t mask[NB_BLOCKS][AC3_MAX_CHANNELS][50])
425 int16_t band_psd[NB_BLOCKS][AC3_MAX_CHANNELS][50];
427 for(blk=0; blk<NB_BLOCKS; blk++) {
428 for(ch=0;ch<s->nb_all_channels;ch++) {
429 if(exp_strategy[blk][ch] == EXP_REUSE) {
430 memcpy(psd[blk][ch], psd[blk-1][ch], (N/2)*sizeof(int16_t));
431 memcpy(mask[blk][ch], mask[blk-1][ch], 50*sizeof(int16_t));
433 ff_ac3_bit_alloc_calc_psd(encoded_exp[blk][ch], 0,
435 psd[blk][ch], band_psd[blk][ch]);
436 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, band_psd[blk][ch],
438 ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
439 ch == s->lfe_channel,
440 DBA_NONE, 0, NULL, NULL, NULL,
447 static int bit_alloc(AC3EncodeContext *s,
448 int16_t mask[NB_BLOCKS][AC3_MAX_CHANNELS][50],
449 int16_t psd[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
450 uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
451 int frame_bits, int coarse_snr_offset, int fine_snr_offset)
456 snr_offset = (((coarse_snr_offset - 15) << 4) + fine_snr_offset) << 2;
459 for(i=0;i<NB_BLOCKS;i++) {
463 for(ch=0;ch<s->nb_all_channels;ch++) {
464 ff_ac3_bit_alloc_calc_bap(mask[i][ch], psd[i][ch], 0,
465 s->nb_coefs[ch], snr_offset,
466 s->bit_alloc.floor, ff_ac3_bap_tab,
468 frame_bits += compute_mantissa_size(s, bap[i][ch],
473 printf("csnr=%d fsnr=%d frame_bits=%d diff=%d\n",
474 coarse_snr_offset, fine_snr_offset, frame_bits,
475 16 * s->frame_size - ((frame_bits + 7) & ~7));
477 return 16 * s->frame_size - frame_bits;
482 static int compute_bit_allocation(AC3EncodeContext *s,
483 uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
484 uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
485 uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
489 int coarse_snr_offset, fine_snr_offset;
490 uint8_t bap1[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
491 int16_t psd[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
492 int16_t mask[NB_BLOCKS][AC3_MAX_CHANNELS][50];
493 static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
495 /* init default parameters */
496 s->slow_decay_code = 2;
497 s->fast_decay_code = 1;
498 s->slow_gain_code = 1;
499 s->db_per_bit_code = 2;
501 for(ch=0;ch<s->nb_all_channels;ch++)
502 s->fast_gain_code[ch] = 4;
504 /* compute real values */
505 s->bit_alloc.sr_code = s->sr_code;
506 s->bit_alloc.sr_shift = s->sr_shift;
507 s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->sr_shift;
508 s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->sr_shift;
509 s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
510 s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
511 s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
515 // if (s->channel_mode == 2)
517 frame_bits += frame_bits_inc[s->channel_mode];
520 for(i=0;i<NB_BLOCKS;i++) {
521 frame_bits += s->nb_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
522 if (s->channel_mode == AC3_CHMODE_STEREO) {
523 frame_bits++; /* rematstr */
524 if(i==0) frame_bits += 4;
526 frame_bits += 2 * s->nb_channels; /* chexpstr[2] * c */
528 frame_bits++; /* lfeexpstr */
529 for(ch=0;ch<s->nb_channels;ch++) {
530 if (exp_strategy[i][ch] != EXP_REUSE)
531 frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
533 frame_bits++; /* baie */
534 frame_bits++; /* snr */
535 frame_bits += 2; /* delta / skip */
537 frame_bits++; /* cplinu for block 0 */
539 /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
541 /* (fsnoffset[4] + fgaincod[4]) * c */
542 frame_bits += 2*4 + 3 + 6 + s->nb_all_channels * (4 + 3);
544 /* auxdatae, crcrsv */
550 /* calculate psd and masking curve before doing bit allocation */
551 bit_alloc_masking(s, encoded_exp, exp_strategy, psd, mask);
553 /* now the big work begins : do the bit allocation. Modify the snr
554 offset until we can pack everything in the requested frame size */
556 coarse_snr_offset = s->coarse_snr_offset;
557 while (coarse_snr_offset >= 0 &&
558 bit_alloc(s, mask, psd, bap, frame_bits, coarse_snr_offset, 0) < 0)
559 coarse_snr_offset -= SNR_INC1;
560 if (coarse_snr_offset < 0) {
561 av_log(NULL, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
564 while ((coarse_snr_offset + SNR_INC1) <= 63 &&
565 bit_alloc(s, mask, psd, bap1, frame_bits,
566 coarse_snr_offset + SNR_INC1, 0) >= 0) {
567 coarse_snr_offset += SNR_INC1;
568 memcpy(bap, bap1, sizeof(bap1));
570 while ((coarse_snr_offset + 1) <= 63 &&
571 bit_alloc(s, mask, psd, bap1, frame_bits, coarse_snr_offset + 1, 0) >= 0) {
573 memcpy(bap, bap1, sizeof(bap1));
577 while ((fine_snr_offset + SNR_INC1) <= 15 &&
578 bit_alloc(s, mask, psd, bap1, frame_bits,
579 coarse_snr_offset, fine_snr_offset + SNR_INC1) >= 0) {
580 fine_snr_offset += SNR_INC1;
581 memcpy(bap, bap1, sizeof(bap1));
583 while ((fine_snr_offset + 1) <= 15 &&
584 bit_alloc(s, mask, psd, bap1, frame_bits,
585 coarse_snr_offset, fine_snr_offset + 1) >= 0) {
587 memcpy(bap, bap1, sizeof(bap1));
590 s->coarse_snr_offset = coarse_snr_offset;
591 for(ch=0;ch<s->nb_all_channels;ch++)
592 s->fine_snr_offset[ch] = fine_snr_offset;
593 #if defined(DEBUG_BITALLOC)
598 for(ch=0;ch<s->nb_all_channels;ch++) {
599 printf("Block #%d Ch%d:\n", i, ch);
601 for(j=0;j<s->nb_coefs[ch];j++) {
602 printf("%d ",bap[i][ch][j]);
612 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
613 int64_t *channel_layout)
617 if (channels < 1 || channels > AC3_MAX_CHANNELS)
619 if ((uint64_t)*channel_layout > 0x7FF)
621 ch_layout = *channel_layout;
623 ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
624 if (av_get_channel_layout_nb_channels(ch_layout) != channels)
627 s->lfe = !!(ch_layout & AV_CH_LOW_FREQUENCY);
628 s->nb_all_channels = channels;
629 s->nb_channels = channels - s->lfe;
630 s->lfe_channel = s->lfe ? s->nb_channels : -1;
632 ch_layout -= AV_CH_LOW_FREQUENCY;
635 case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
636 case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
637 case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
638 case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
639 case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
640 case AV_CH_LAYOUT_QUAD:
641 case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
642 case AV_CH_LAYOUT_5POINT0:
643 case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
648 s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe];
649 *channel_layout = ch_layout;
651 *channel_layout |= AV_CH_LOW_FREQUENCY;
656 static av_cold int AC3_encode_init(AVCodecContext *avctx)
658 int freq = avctx->sample_rate;
659 int bitrate = avctx->bit_rate;
660 AC3EncodeContext *s = avctx->priv_data;
665 avctx->frame_size = AC3_FRAME_SIZE;
669 if (!avctx->channel_layout) {
670 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
671 "encoder will guess the layout, but it "
672 "might be incorrect.\n");
674 if (set_channel_info(s, avctx->channels, &avctx->channel_layout)) {
675 av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
682 if ((ff_ac3_sample_rate_tab[j] >> i) == freq)
687 s->sample_rate = freq;
690 s->bitstream_id = 8 + s->sr_shift;
691 s->bitstream_mode = 0; /* complete main audio service */
693 /* bitrate & frame size */
695 if ((ff_ac3_bitrate_tab[i] >> s->sr_shift)*1000 == bitrate)
700 s->bit_rate = bitrate;
701 s->frame_size_code = i << 1;
702 s->frame_size_min = ff_ac3_frame_size_tab[s->frame_size_code][s->sr_code];
704 s->samples_written = 0;
705 s->frame_size = s->frame_size_min;
707 /* bit allocation init */
709 /* calculate bandwidth based on user-specified cutoff frequency */
710 int cutoff = av_clip(avctx->cutoff, 1, s->sample_rate >> 1);
711 int fbw_coeffs = cutoff * 512 / s->sample_rate;
712 bw_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
714 /* use default bandwidth setting */
715 /* XXX: should compute the bandwidth according to the frame
716 size, so that we avoid annoying high frequency artifacts */
719 for(ch=0;ch<s->nb_channels;ch++) {
720 /* bandwidth for each channel */
721 s->chbwcod[ch] = bw_code;
722 s->nb_coefs[ch] = bw_code * 3 + 73;
725 s->nb_coefs[s->lfe_channel] = 7; /* fixed */
727 /* initial snr offset */
728 s->coarse_snr_offset = 40;
731 fft_init(MDCT_NBITS - 2);
733 alpha = 2 * M_PI * (i + 1.0 / 8.0) / (float)N;
734 xcos1[i] = fix15(-cos(alpha));
735 xsin1[i] = fix15(-sin(alpha));
738 avctx->coded_frame= avcodec_alloc_frame();
739 avctx->coded_frame->key_frame= 1;
744 /* output the AC-3 frame header */
745 static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
747 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
749 put_bits(&s->pb, 16, 0x0b77); /* frame header */
750 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
751 put_bits(&s->pb, 2, s->sr_code);
752 put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min));
753 put_bits(&s->pb, 5, s->bitstream_id);
754 put_bits(&s->pb, 3, s->bitstream_mode);
755 put_bits(&s->pb, 3, s->channel_mode);
756 if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
757 put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
758 if (s->channel_mode & 0x04)
759 put_bits(&s->pb, 2, 1); /* XXX -6 dB */
760 if (s->channel_mode == AC3_CHMODE_STEREO)
761 put_bits(&s->pb, 2, 0); /* surround not indicated */
762 put_bits(&s->pb, 1, s->lfe); /* LFE */
763 put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
764 put_bits(&s->pb, 1, 0); /* no compression control word */
765 put_bits(&s->pb, 1, 0); /* no lang code */
766 put_bits(&s->pb, 1, 0); /* no audio production info */
767 put_bits(&s->pb, 1, 0); /* no copyright */
768 put_bits(&s->pb, 1, 1); /* original bitstream */
769 put_bits(&s->pb, 1, 0); /* no time code 1 */
770 put_bits(&s->pb, 1, 0); /* no time code 2 */
771 put_bits(&s->pb, 1, 0); /* no additional bit stream info */
774 /* symetric quantization on 'levels' levels */
775 static inline int sym_quant(int c, int e, int levels)
780 v = (levels * (c << e)) >> 24;
782 v = (levels >> 1) + v;
784 v = (levels * ((-c) << e)) >> 24;
786 v = (levels >> 1) - v;
788 assert (v >= 0 && v < levels);
792 /* asymetric quantization on 2^qbits levels */
793 static inline int asym_quant(int c, int e, int qbits)
797 lshift = e + qbits - 24;
804 m = (1 << (qbits-1));
808 return v & ((1 << qbits)-1);
811 /* Output one audio block. There are NB_BLOCKS audio blocks in one AC-3
813 static void output_audio_block(AC3EncodeContext *s,
814 uint8_t exp_strategy[AC3_MAX_CHANNELS],
815 uint8_t encoded_exp[AC3_MAX_CHANNELS][N/2],
816 uint8_t bap[AC3_MAX_CHANNELS][N/2],
817 int32_t mdct_coefs[AC3_MAX_CHANNELS][N/2],
818 int8_t global_exp[AC3_MAX_CHANNELS],
821 int ch, nb_groups, group_size, i, baie, rbnd;
823 uint16_t qmant[AC3_MAX_CHANNELS][N/2];
825 int mant1_cnt, mant2_cnt, mant4_cnt;
826 uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
827 int delta0, delta1, delta2;
829 for(ch=0;ch<s->nb_channels;ch++)
830 put_bits(&s->pb, 1, 0); /* 512 point MDCT */
831 for(ch=0;ch<s->nb_channels;ch++)
832 put_bits(&s->pb, 1, 1); /* no dither */
833 put_bits(&s->pb, 1, 0); /* no dynamic range */
834 if (block_num == 0) {
835 /* for block 0, even if no coupling, we must say it. This is a
837 put_bits(&s->pb, 1, 1); /* coupling strategy present */
838 put_bits(&s->pb, 1, 0); /* no coupling strategy */
840 put_bits(&s->pb, 1, 0); /* no new coupling strategy */
843 if (s->channel_mode == AC3_CHMODE_STEREO)
847 /* first block must define rematrixing (rematstr) */
848 put_bits(&s->pb, 1, 1);
850 /* dummy rematrixing rematflg(1:4)=0 */
851 for (rbnd=0;rbnd<4;rbnd++)
852 put_bits(&s->pb, 1, 0);
856 /* no matrixing (but should be used in the future) */
857 put_bits(&s->pb, 1, 0);
863 static int count = 0;
864 av_log(NULL, AV_LOG_DEBUG, "Block #%d (%d)\n", block_num, count++);
867 /* exponent strategy */
868 for(ch=0;ch<s->nb_channels;ch++) {
869 put_bits(&s->pb, 2, exp_strategy[ch]);
873 put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
876 for(ch=0;ch<s->nb_channels;ch++) {
877 if (exp_strategy[ch] != EXP_REUSE)
878 put_bits(&s->pb, 6, s->chbwcod[ch]);
882 for (ch = 0; ch < s->nb_all_channels; ch++) {
883 switch(exp_strategy[ch]) {
897 nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
902 put_bits(&s->pb, 4, exp1);
904 /* next ones are delta encoded */
905 for(i=0;i<nb_groups;i++) {
906 /* merge three delta in one code */
910 delta0 = exp1 - exp0 + 2;
915 delta1 = exp1 - exp0 + 2;
920 delta2 = exp1 - exp0 + 2;
922 put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
925 if (ch != s->lfe_channel)
926 put_bits(&s->pb, 2, 0); /* no gain range info */
929 /* bit allocation info */
930 baie = (block_num == 0);
931 put_bits(&s->pb, 1, baie);
933 put_bits(&s->pb, 2, s->slow_decay_code);
934 put_bits(&s->pb, 2, s->fast_decay_code);
935 put_bits(&s->pb, 2, s->slow_gain_code);
936 put_bits(&s->pb, 2, s->db_per_bit_code);
937 put_bits(&s->pb, 3, s->floor_code);
941 put_bits(&s->pb, 1, baie); /* always present with bai */
943 put_bits(&s->pb, 6, s->coarse_snr_offset);
944 for(ch=0;ch<s->nb_all_channels;ch++) {
945 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
946 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
950 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
951 put_bits(&s->pb, 1, 0); /* no data to skip */
953 /* mantissa encoding : we use two passes to handle the grouping. A
954 one pass method may be faster, but it would necessitate to
955 modify the output stream. */
957 /* first pass: quantize */
958 mant1_cnt = mant2_cnt = mant4_cnt = 0;
959 qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
961 for (ch = 0; ch < s->nb_all_channels; ch++) {
964 for(i=0;i<s->nb_coefs[ch];i++) {
965 c = mdct_coefs[ch][i];
966 e = encoded_exp[ch][i] - global_exp[ch];
973 v = sym_quant(c, e, 3);
976 qmant1_ptr = &qmant[ch][i];
981 *qmant1_ptr += 3 * v;
993 v = sym_quant(c, e, 5);
996 qmant2_ptr = &qmant[ch][i];
1001 *qmant2_ptr += 5 * v;
1013 v = sym_quant(c, e, 7);
1016 v = sym_quant(c, e, 11);
1019 qmant4_ptr = &qmant[ch][i];
1031 v = sym_quant(c, e, 15);
1034 v = asym_quant(c, e, 14);
1037 v = asym_quant(c, e, 16);
1040 v = asym_quant(c, e, b - 1);
1047 /* second pass : output the values */
1048 for (ch = 0; ch < s->nb_all_channels; ch++) {
1051 for(i=0;i<s->nb_coefs[ch];i++) {
1059 put_bits(&s->pb, 5, q);
1063 put_bits(&s->pb, 7, q);
1066 put_bits(&s->pb, 3, q);
1070 put_bits(&s->pb, 7, q);
1073 put_bits(&s->pb, 14, q);
1076 put_bits(&s->pb, 16, q);
1079 put_bits(&s->pb, b - 1, q);
1086 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1088 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1104 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1110 r = mul_poly(r, a, poly);
1111 a = mul_poly(a, a, poly);
1118 /* compute log2(max(abs(tab[]))) */
1119 static int log2_tab(int16_t *tab, int n)
1130 static void lshift_tab(int16_t *tab, int n, int lshift)
1138 } else if (lshift < 0) {
1146 /* fill the end of the frame and compute the two crcs */
1147 static int output_frame_end(AC3EncodeContext *s)
1149 int frame_size, frame_size_58, n, crc1, crc2, crc_inv;
1152 frame_size = s->frame_size; /* frame size in words */
1153 /* align to 8 bits */
1154 flush_put_bits(&s->pb);
1155 /* add zero bytes to reach the frame size */
1157 n = 2 * s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1160 memset(put_bits_ptr(&s->pb), 0, n);
1162 /* Now we must compute both crcs : this is not so easy for crc1
1163 because it is at the beginning of the data... */
1164 frame_size_58 = (frame_size >> 1) + (frame_size >> 3);
1165 crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1166 frame + 4, 2 * frame_size_58 - 4));
1167 /* XXX: could precompute crc_inv */
1168 crc_inv = pow_poly((CRC16_POLY >> 1), (16 * frame_size_58) - 16, CRC16_POLY);
1169 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1170 AV_WB16(frame+2,crc1);
1172 crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1173 frame + 2 * frame_size_58,
1174 (frame_size - frame_size_58) * 2 - 2));
1175 AV_WB16(frame+2*frame_size-2,crc2);
1177 // printf("n=%d frame_size=%d\n", n, frame_size);
1178 return frame_size * 2;
1181 static int AC3_encode_frame(AVCodecContext *avctx,
1182 unsigned char *frame, int buf_size, void *data)
1184 AC3EncodeContext *s = avctx->priv_data;
1185 const int16_t *samples = data;
1187 int16_t input_samples[N];
1188 int32_t mdct_coef[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1189 uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1190 uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS];
1191 uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1192 uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1193 int8_t exp_samples[NB_BLOCKS][AC3_MAX_CHANNELS];
1197 for(ch=0;ch<s->nb_all_channels;ch++) {
1198 int ich = s->channel_map[ch];
1199 /* fixed mdct to the six sub blocks & exponent computation */
1200 for(i=0;i<NB_BLOCKS;i++) {
1201 const int16_t *sptr;
1204 /* compute input samples */
1205 memcpy(input_samples, s->last_samples[ich], N/2 * sizeof(int16_t));
1206 sinc = s->nb_all_channels;
1207 sptr = samples + (sinc * (N/2) * i) + ich;
1208 for(j=0;j<N/2;j++) {
1210 input_samples[j + N/2] = v;
1211 s->last_samples[ich][j] = v;
1215 /* apply the MDCT window */
1216 for(j=0;j<N/2;j++) {
1217 input_samples[j] = MUL16(input_samples[j],
1218 ff_ac3_window[j]) >> 15;
1219 input_samples[N-j-1] = MUL16(input_samples[N-j-1],
1220 ff_ac3_window[j]) >> 15;
1223 /* Normalize the samples to use the maximum available
1225 v = 14 - log2_tab(input_samples, N);
1228 exp_samples[i][ch] = v - 9;
1229 lshift_tab(input_samples, N, v);
1232 mdct512(mdct_coef[i][ch], input_samples);
1234 /* compute "exponents". We take into account the
1235 normalization there */
1236 for(j=0;j<N/2;j++) {
1238 v = abs(mdct_coef[i][ch][j]);
1242 e = 23 - av_log2(v) + exp_samples[i][ch];
1245 mdct_coef[i][ch][j] = 0;
1252 compute_exp_strategy(exp_strategy, exp, ch, ch == s->lfe_channel);
1254 /* compute the exponents as the decoder will see them. The
1255 EXP_REUSE case must be handled carefully : we select the
1256 min of the exponents */
1258 while (i < NB_BLOCKS) {
1260 while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE) {
1261 exponent_min(exp[i][ch], exp[j][ch], s->nb_coefs[ch]);
1264 frame_bits += encode_exp(encoded_exp[i][ch],
1265 exp[i][ch], s->nb_coefs[ch],
1266 exp_strategy[i][ch]);
1267 /* copy encoded exponents for reuse case */
1268 for(k=i+1;k<j;k++) {
1269 memcpy(encoded_exp[k][ch], encoded_exp[i][ch],
1270 s->nb_coefs[ch] * sizeof(uint8_t));
1276 /* adjust for fractional frame sizes */
1277 while(s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
1278 s->bits_written -= s->bit_rate;
1279 s->samples_written -= s->sample_rate;
1281 s->frame_size = s->frame_size_min + (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
1282 s->bits_written += s->frame_size * 16;
1283 s->samples_written += AC3_FRAME_SIZE;
1285 compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
1286 /* everything is known... let's output the frame */
1287 output_frame_header(s, frame);
1289 for(i=0;i<NB_BLOCKS;i++) {
1290 output_audio_block(s, exp_strategy[i], encoded_exp[i],
1291 bap[i], mdct_coef[i], exp_samples[i], i);
1293 return output_frame_end(s);
1296 static av_cold int AC3_encode_close(AVCodecContext *avctx)
1298 av_freep(&avctx->coded_frame);
1303 /*************************************************************************/
1311 IComplex in[FN], in1[FN];
1313 float sum_re, sum_im, a;
1318 in[i].re = random() % 65535 - 32767;
1319 in[i].im = random() % 65535 - 32767;
1329 a = -2 * M_PI * (n * k) / FN;
1330 sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1331 sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1333 printf("%3d: %6d,%6d %6.0f,%6.0f\n",
1334 k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1338 void mdct_test(void)
1341 int32_t output[N/2];
1344 float s, a, err, e, emax;
1348 input[i] = (random() % 65535 - 32767) * 9 / 10;
1349 input1[i] = input[i];
1352 mdct512(output, input);
1355 for(k=0;k<N/2;k++) {
1358 a = (2*M_PI*(2*n+1+N/2)*(2*k+1) / (4 * N));
1359 s += input1[n] * cos(a);
1361 output1[k] = -2 * s / N;
1366 for(i=0;i<N/2;i++) {
1367 printf("%3d: %7d %7.0f\n", i, output[i], output1[i]);
1368 e = output[i] - output1[i];
1373 printf("err2=%f emax=%f\n", err / (N/2), emax);
1378 AC3EncodeContext ctx;
1379 unsigned char frame[AC3_MAX_CODED_FRAME_SIZE];
1380 short samples[AC3_FRAME_SIZE];
1383 AC3_encode_init(&ctx, 44100, 64000, 1);
1388 for(i=0;i<AC3_FRAME_SIZE;i++)
1389 samples[i] = (int)(sin(2*M_PI*i*1000.0/44100) * 10000);
1390 ret = AC3_encode_frame(&ctx, frame, samples);
1391 printf("ret=%d\n", ret);
1395 AVCodec ac3_encoder = {
1399 sizeof(AC3EncodeContext),
1404 .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1405 .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1406 .channel_layouts = (const int64_t[]){
1408 AV_CH_LAYOUT_STEREO,
1410 AV_CH_LAYOUT_SURROUND,
1413 AV_CH_LAYOUT_4POINT0,
1414 AV_CH_LAYOUT_5POINT0,
1415 AV_CH_LAYOUT_5POINT0_BACK,
1416 (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
1417 (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
1418 (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
1419 (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1420 (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
1421 (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
1422 (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
1423 AV_CH_LAYOUT_5POINT1,
1424 AV_CH_LAYOUT_5POINT1_BACK,