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 {
45 int sr_code; /* frequency */
47 int frame_size_min; /* minimum frame size in case rounding is necessary */
48 int frame_size; /* current frame size in words */
58 const uint8_t *channel_map;
60 int chbwcod[AC3_MAX_CHANNELS];
61 int nb_coefs[AC3_MAX_CHANNELS];
63 /* bitrate allocation control */
64 int slow_gain_code, slow_decay_code, fast_decay_code, db_per_bit_code, floor_code;
65 AC3BitAllocParameters bit_alloc;
66 int coarse_snr_offset;
67 int fast_gain_code[AC3_MAX_CHANNELS];
68 int fine_snr_offset[AC3_MAX_CHANNELS];
70 /* mantissa encoding */
71 int mant1_cnt, mant2_cnt, mant4_cnt;
73 int16_t last_samples[AC3_MAX_CHANNELS][256];
76 static int16_t costab[64];
77 static int16_t sintab[64];
78 static int16_t xcos1[128];
79 static int16_t xsin1[128];
82 #define N (1 << MDCT_NBITS)
84 /* new exponents are sent if their Norm 1 exceed this number */
85 #define EXP_DIFF_THRESHOLD 1000
87 static inline int16_t fix15(float a)
90 v = (int)(a * (float)(1 << 15));
98 typedef struct IComplex {
102 static av_cold void fft_init(int ln)
109 for(i=0;i<(n/2);i++) {
110 alpha = 2 * M_PI * (float)i / (float)n;
111 costab[i] = fix15(cos(alpha));
112 sintab[i] = fix15(sin(alpha));
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 CMUL(pre, pim, are, aim, bre, bim) \
132 pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;\
133 pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;\
137 /* do a 2^n point complex fft on 2^ln points. */
138 static void fft(IComplex *z, int ln)
142 register IComplex *p,*q;
149 int k = av_reverse[j] >> (8 - ln);
151 FFSWAP(IComplex, z[k], z[j]);
159 BF(p[0].re, p[0].im, p[1].re, p[1].im,
160 p[0].re, p[0].im, p[1].re, p[1].im);
169 BF(p[0].re, p[0].im, p[2].re, p[2].im,
170 p[0].re, p[0].im, p[2].re, p[2].im);
171 BF(p[1].re, p[1].im, p[3].re, p[3].im,
172 p[1].re, p[1].im, p[3].im, -p[3].re);
184 for (j = 0; j < nblocks; ++j) {
186 BF(p->re, p->im, q->re, q->im,
187 p->re, p->im, q->re, q->im);
191 for(l = nblocks; l < np2; l += nblocks) {
192 CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
193 BF(p->re, p->im, q->re, q->im,
194 p->re, p->im, tmp_re, tmp_im);
201 nblocks = nblocks >> 1;
202 nloops = nloops << 1;
203 } while (nblocks != 0);
206 /* do a 512 point mdct */
207 static void mdct512(int32_t *out, int16_t *in)
209 int i, re, im, re1, im1;
213 /* shift to simplify computations */
215 rot[i] = -in[i + 3*N/4];
217 rot[i] = in[i - N/4];
221 re = ((int)rot[2*i] - (int)rot[N-1-2*i]) >> 1;
222 im = -((int)rot[N/2+2*i] - (int)rot[N/2-1-2*i]) >> 1;
223 CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
226 fft(x, MDCT_NBITS - 2);
232 CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
234 out[N/2-1-2*i] = re1;
238 /* XXX: use another norm ? */
239 static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
244 sum += abs(exp1[i] - exp2[i]);
249 static void compute_exp_strategy(uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
250 uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
256 /* estimate if the exponent variation & decide if they should be
257 reused in the next frame */
258 exp_strategy[0][ch] = EXP_NEW;
259 for(i=1;i<NB_BLOCKS;i++) {
260 exp_diff = calc_exp_diff(exp[i][ch], exp[i-1][ch], N/2);
261 dprintf(NULL, "exp_diff=%d\n", exp_diff);
262 if (exp_diff > EXP_DIFF_THRESHOLD)
263 exp_strategy[i][ch] = EXP_NEW;
265 exp_strategy[i][ch] = EXP_REUSE;
270 /* now select the encoding strategy type : if exponents are often
271 recoded, we use a coarse encoding */
273 while (i < NB_BLOCKS) {
275 while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE)
279 exp_strategy[i][ch] = EXP_D45;
283 exp_strategy[i][ch] = EXP_D25;
286 exp_strategy[i][ch] = EXP_D15;
293 /* set exp[i] to min(exp[i], exp1[i]) */
294 static void exponent_min(uint8_t exp[N/2], uint8_t exp1[N/2], int n)
299 if (exp1[i] < exp[i])
304 /* update the exponents so that they are the ones the decoder will
305 decode. Return the number of bits used to code the exponents */
306 static int encode_exp(uint8_t encoded_exp[N/2],
311 int group_size, nb_groups, i, j, k, exp_min;
314 switch(exp_strategy) {
326 nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
328 /* for each group, compute the minimum exponent */
329 exp1[0] = exp[0]; /* DC exponent is handled separately */
331 for(i=1;i<=nb_groups;i++) {
333 assert(exp_min >= 0 && exp_min <= 24);
334 for(j=1;j<group_size;j++) {
335 if (exp[k+j] < exp_min)
342 /* constraint for DC exponent */
346 /* Decrease the delta between each groups to within 2
347 * so that they can be differentially encoded */
348 for (i=1;i<=nb_groups;i++)
349 exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
350 for (i=nb_groups-1;i>=0;i--)
351 exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
353 /* now we have the exponent values the decoder will see */
354 encoded_exp[0] = exp1[0];
356 for(i=1;i<=nb_groups;i++) {
357 for(j=0;j<group_size;j++) {
358 encoded_exp[k+j] = exp1[i];
364 av_log(NULL, AV_LOG_DEBUG, "exponents: strategy=%d\n", exp_strategy);
365 for(i=0;i<=nb_groups * group_size;i++) {
366 av_log(NULL, AV_LOG_DEBUG, "%d ", encoded_exp[i]);
368 av_log(NULL, AV_LOG_DEBUG, "\n");
371 return 4 + (nb_groups / 3) * 7;
374 /* return the size in bits taken by the mantissa */
375 static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
380 for(i=0;i<nb_coefs;i++) {
387 /* 3 mantissa in 5 bits */
388 if (s->mant1_cnt == 0)
390 if (++s->mant1_cnt == 3)
394 /* 3 mantissa in 7 bits */
395 if (s->mant2_cnt == 0)
397 if (++s->mant2_cnt == 3)
404 /* 2 mantissa in 7 bits */
405 if (s->mant4_cnt == 0)
407 if (++s->mant4_cnt == 2)
425 static void bit_alloc_masking(AC3EncodeContext *s,
426 uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
427 uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
428 int16_t psd[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
429 int16_t mask[NB_BLOCKS][AC3_MAX_CHANNELS][50])
432 int16_t band_psd[NB_BLOCKS][AC3_MAX_CHANNELS][50];
434 for(blk=0; blk<NB_BLOCKS; blk++) {
435 for(ch=0;ch<s->nb_all_channels;ch++) {
436 if(exp_strategy[blk][ch] == EXP_REUSE) {
437 memcpy(psd[blk][ch], psd[blk-1][ch], (N/2)*sizeof(int16_t));
438 memcpy(mask[blk][ch], mask[blk-1][ch], 50*sizeof(int16_t));
440 ff_ac3_bit_alloc_calc_psd(encoded_exp[blk][ch], 0,
442 psd[blk][ch], band_psd[blk][ch]);
443 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, band_psd[blk][ch],
445 ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
446 ch == s->lfe_channel,
447 DBA_NONE, 0, NULL, NULL, NULL,
454 static int bit_alloc(AC3EncodeContext *s,
455 int16_t mask[NB_BLOCKS][AC3_MAX_CHANNELS][50],
456 int16_t psd[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
457 uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
458 int frame_bits, int coarse_snr_offset, int fine_snr_offset)
463 snr_offset = (((coarse_snr_offset - 15) << 4) + fine_snr_offset) << 2;
466 for(i=0;i<NB_BLOCKS;i++) {
470 for(ch=0;ch<s->nb_all_channels;ch++) {
471 ff_ac3_bit_alloc_calc_bap(mask[i][ch], psd[i][ch], 0,
472 s->nb_coefs[ch], snr_offset,
473 s->bit_alloc.floor, ff_ac3_bap_tab,
475 frame_bits += compute_mantissa_size(s, bap[i][ch],
480 printf("csnr=%d fsnr=%d frame_bits=%d diff=%d\n",
481 coarse_snr_offset, fine_snr_offset, frame_bits,
482 16 * s->frame_size - ((frame_bits + 7) & ~7));
484 return 16 * s->frame_size - frame_bits;
489 static int compute_bit_allocation(AC3EncodeContext *s,
490 uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
491 uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
492 uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
496 int coarse_snr_offset, fine_snr_offset;
497 uint8_t bap1[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
498 int16_t psd[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
499 int16_t mask[NB_BLOCKS][AC3_MAX_CHANNELS][50];
500 static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
502 /* init default parameters */
503 s->slow_decay_code = 2;
504 s->fast_decay_code = 1;
505 s->slow_gain_code = 1;
506 s->db_per_bit_code = 2;
508 for(ch=0;ch<s->nb_all_channels;ch++)
509 s->fast_gain_code[ch] = 4;
511 /* compute real values */
512 s->bit_alloc.sr_code = s->sr_code;
513 s->bit_alloc.sr_shift = s->sr_shift;
514 s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->sr_shift;
515 s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->sr_shift;
516 s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
517 s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
518 s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
522 // if (s->channel_mode == 2)
524 frame_bits += frame_bits_inc[s->channel_mode];
527 for(i=0;i<NB_BLOCKS;i++) {
528 frame_bits += s->nb_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
529 if (s->channel_mode == AC3_CHMODE_STEREO) {
530 frame_bits++; /* rematstr */
531 if(i==0) frame_bits += 4;
533 frame_bits += 2 * s->nb_channels; /* chexpstr[2] * c */
535 frame_bits++; /* lfeexpstr */
536 for(ch=0;ch<s->nb_channels;ch++) {
537 if (exp_strategy[i][ch] != EXP_REUSE)
538 frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
540 frame_bits++; /* baie */
541 frame_bits++; /* snr */
542 frame_bits += 2; /* delta / skip */
544 frame_bits++; /* cplinu for block 0 */
546 /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
548 /* (fsnoffset[4] + fgaincod[4]) * c */
549 frame_bits += 2*4 + 3 + 6 + s->nb_all_channels * (4 + 3);
551 /* auxdatae, crcrsv */
557 /* calculate psd and masking curve before doing bit allocation */
558 bit_alloc_masking(s, encoded_exp, exp_strategy, psd, mask);
560 /* now the big work begins : do the bit allocation. Modify the snr
561 offset until we can pack everything in the requested frame size */
563 coarse_snr_offset = s->coarse_snr_offset;
564 while (coarse_snr_offset >= 0 &&
565 bit_alloc(s, mask, psd, bap, frame_bits, coarse_snr_offset, 0) < 0)
566 coarse_snr_offset -= SNR_INC1;
567 if (coarse_snr_offset < 0) {
568 av_log(NULL, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
571 while ((coarse_snr_offset + SNR_INC1) <= 63 &&
572 bit_alloc(s, mask, psd, bap1, frame_bits,
573 coarse_snr_offset + SNR_INC1, 0) >= 0) {
574 coarse_snr_offset += SNR_INC1;
575 memcpy(bap, bap1, sizeof(bap1));
577 while ((coarse_snr_offset + 1) <= 63 &&
578 bit_alloc(s, mask, psd, bap1, frame_bits, coarse_snr_offset + 1, 0) >= 0) {
580 memcpy(bap, bap1, sizeof(bap1));
584 while ((fine_snr_offset + SNR_INC1) <= 15 &&
585 bit_alloc(s, mask, psd, bap1, frame_bits,
586 coarse_snr_offset, fine_snr_offset + SNR_INC1) >= 0) {
587 fine_snr_offset += SNR_INC1;
588 memcpy(bap, bap1, sizeof(bap1));
590 while ((fine_snr_offset + 1) <= 15 &&
591 bit_alloc(s, mask, psd, bap1, frame_bits,
592 coarse_snr_offset, fine_snr_offset + 1) >= 0) {
594 memcpy(bap, bap1, sizeof(bap1));
597 s->coarse_snr_offset = coarse_snr_offset;
598 for(ch=0;ch<s->nb_all_channels;ch++)
599 s->fine_snr_offset[ch] = fine_snr_offset;
600 #if defined(DEBUG_BITALLOC)
605 for(ch=0;ch<s->nb_all_channels;ch++) {
606 printf("Block #%d Ch%d:\n", i, ch);
608 for(j=0;j<s->nb_coefs[ch];j++) {
609 printf("%d ",bap[i][ch][j]);
619 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
620 int64_t *channel_layout)
624 if (channels < 1 || channels > AC3_MAX_CHANNELS)
626 if ((uint64_t)*channel_layout > 0x7FF)
628 ch_layout = *channel_layout;
630 ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
631 if (av_get_channel_layout_nb_channels(ch_layout) != channels)
634 s->lfe = !!(ch_layout & AV_CH_LOW_FREQUENCY);
635 s->nb_all_channels = channels;
636 s->nb_channels = channels - s->lfe;
637 s->lfe_channel = s->lfe ? s->nb_channels : -1;
639 ch_layout -= AV_CH_LOW_FREQUENCY;
642 case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
643 case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
644 case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
645 case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
646 case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
647 case AV_CH_LAYOUT_QUAD:
648 case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
649 case AV_CH_LAYOUT_5POINT0:
650 case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
655 s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe];
656 *channel_layout = ch_layout;
658 *channel_layout |= AV_CH_LOW_FREQUENCY;
663 static av_cold int AC3_encode_init(AVCodecContext *avctx)
665 int freq = avctx->sample_rate;
666 int bitrate = avctx->bit_rate;
667 AC3EncodeContext *s = avctx->priv_data;
672 avctx->frame_size = AC3_FRAME_SIZE;
676 if (!avctx->channel_layout) {
677 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
678 "encoder will guess the layout, but it "
679 "might be incorrect.\n");
681 if (set_channel_info(s, avctx->channels, &avctx->channel_layout)) {
682 av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
689 if ((ff_ac3_sample_rate_tab[j] >> i) == freq)
694 s->sample_rate = freq;
697 s->bitstream_id = 8 + s->sr_shift;
698 s->bitstream_mode = 0; /* complete main audio service */
700 /* bitrate & frame size */
702 if ((ff_ac3_bitrate_tab[i] >> s->sr_shift)*1000 == bitrate)
707 s->bit_rate = bitrate;
708 s->frame_size_code = i << 1;
709 s->frame_size_min = ff_ac3_frame_size_tab[s->frame_size_code][s->sr_code];
711 s->samples_written = 0;
712 s->frame_size = s->frame_size_min;
714 /* bit allocation init */
716 /* calculate bandwidth based on user-specified cutoff frequency */
717 int cutoff = av_clip(avctx->cutoff, 1, s->sample_rate >> 1);
718 int fbw_coeffs = cutoff * 512 / s->sample_rate;
719 bw_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
721 /* use default bandwidth setting */
722 /* XXX: should compute the bandwidth according to the frame
723 size, so that we avoid annoying high frequency artifacts */
726 for(ch=0;ch<s->nb_channels;ch++) {
727 /* bandwidth for each channel */
728 s->chbwcod[ch] = bw_code;
729 s->nb_coefs[ch] = bw_code * 3 + 73;
732 s->nb_coefs[s->lfe_channel] = 7; /* fixed */
734 /* initial snr offset */
735 s->coarse_snr_offset = 40;
738 fft_init(MDCT_NBITS - 2);
740 alpha = 2 * M_PI * (i + 1.0 / 8.0) / (float)N;
741 xcos1[i] = fix15(-cos(alpha));
742 xsin1[i] = fix15(-sin(alpha));
745 avctx->coded_frame= avcodec_alloc_frame();
746 avctx->coded_frame->key_frame= 1;
751 /* output the AC-3 frame header */
752 static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
754 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
756 put_bits(&s->pb, 16, 0x0b77); /* frame header */
757 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
758 put_bits(&s->pb, 2, s->sr_code);
759 put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min));
760 put_bits(&s->pb, 5, s->bitstream_id);
761 put_bits(&s->pb, 3, s->bitstream_mode);
762 put_bits(&s->pb, 3, s->channel_mode);
763 if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
764 put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
765 if (s->channel_mode & 0x04)
766 put_bits(&s->pb, 2, 1); /* XXX -6 dB */
767 if (s->channel_mode == AC3_CHMODE_STEREO)
768 put_bits(&s->pb, 2, 0); /* surround not indicated */
769 put_bits(&s->pb, 1, s->lfe); /* LFE */
770 put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
771 put_bits(&s->pb, 1, 0); /* no compression control word */
772 put_bits(&s->pb, 1, 0); /* no lang code */
773 put_bits(&s->pb, 1, 0); /* no audio production info */
774 put_bits(&s->pb, 1, 0); /* no copyright */
775 put_bits(&s->pb, 1, 1); /* original bitstream */
776 put_bits(&s->pb, 1, 0); /* no time code 1 */
777 put_bits(&s->pb, 1, 0); /* no time code 2 */
778 put_bits(&s->pb, 1, 0); /* no additional bit stream info */
781 /* symetric quantization on 'levels' levels */
782 static inline int sym_quant(int c, int e, int levels)
787 v = (levels * (c << e)) >> 24;
789 v = (levels >> 1) + v;
791 v = (levels * ((-c) << e)) >> 24;
793 v = (levels >> 1) - v;
795 assert (v >= 0 && v < levels);
799 /* asymetric quantization on 2^qbits levels */
800 static inline int asym_quant(int c, int e, int qbits)
804 lshift = e + qbits - 24;
811 m = (1 << (qbits-1));
815 return v & ((1 << qbits)-1);
818 /* Output one audio block. There are NB_BLOCKS audio blocks in one AC-3
820 static void output_audio_block(AC3EncodeContext *s,
821 uint8_t exp_strategy[AC3_MAX_CHANNELS],
822 uint8_t encoded_exp[AC3_MAX_CHANNELS][N/2],
823 uint8_t bap[AC3_MAX_CHANNELS][N/2],
824 int32_t mdct_coefs[AC3_MAX_CHANNELS][N/2],
825 int8_t global_exp[AC3_MAX_CHANNELS],
828 int ch, nb_groups, group_size, i, baie, rbnd;
830 uint16_t qmant[AC3_MAX_CHANNELS][N/2];
832 int mant1_cnt, mant2_cnt, mant4_cnt;
833 uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
834 int delta0, delta1, delta2;
836 for(ch=0;ch<s->nb_channels;ch++)
837 put_bits(&s->pb, 1, 0); /* 512 point MDCT */
838 for(ch=0;ch<s->nb_channels;ch++)
839 put_bits(&s->pb, 1, 1); /* no dither */
840 put_bits(&s->pb, 1, 0); /* no dynamic range */
841 if (block_num == 0) {
842 /* for block 0, even if no coupling, we must say it. This is a
844 put_bits(&s->pb, 1, 1); /* coupling strategy present */
845 put_bits(&s->pb, 1, 0); /* no coupling strategy */
847 put_bits(&s->pb, 1, 0); /* no new coupling strategy */
850 if (s->channel_mode == AC3_CHMODE_STEREO)
854 /* first block must define rematrixing (rematstr) */
855 put_bits(&s->pb, 1, 1);
857 /* dummy rematrixing rematflg(1:4)=0 */
858 for (rbnd=0;rbnd<4;rbnd++)
859 put_bits(&s->pb, 1, 0);
863 /* no matrixing (but should be used in the future) */
864 put_bits(&s->pb, 1, 0);
870 static int count = 0;
871 av_log(NULL, AV_LOG_DEBUG, "Block #%d (%d)\n", block_num, count++);
874 /* exponent strategy */
875 for(ch=0;ch<s->nb_channels;ch++) {
876 put_bits(&s->pb, 2, exp_strategy[ch]);
880 put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
883 for(ch=0;ch<s->nb_channels;ch++) {
884 if (exp_strategy[ch] != EXP_REUSE)
885 put_bits(&s->pb, 6, s->chbwcod[ch]);
889 for (ch = 0; ch < s->nb_all_channels; ch++) {
890 switch(exp_strategy[ch]) {
904 nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
909 put_bits(&s->pb, 4, exp1);
911 /* next ones are delta encoded */
912 for(i=0;i<nb_groups;i++) {
913 /* merge three delta in one code */
917 delta0 = exp1 - exp0 + 2;
922 delta1 = exp1 - exp0 + 2;
927 delta2 = exp1 - exp0 + 2;
929 put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
932 if (ch != s->lfe_channel)
933 put_bits(&s->pb, 2, 0); /* no gain range info */
936 /* bit allocation info */
937 baie = (block_num == 0);
938 put_bits(&s->pb, 1, baie);
940 put_bits(&s->pb, 2, s->slow_decay_code);
941 put_bits(&s->pb, 2, s->fast_decay_code);
942 put_bits(&s->pb, 2, s->slow_gain_code);
943 put_bits(&s->pb, 2, s->db_per_bit_code);
944 put_bits(&s->pb, 3, s->floor_code);
948 put_bits(&s->pb, 1, baie); /* always present with bai */
950 put_bits(&s->pb, 6, s->coarse_snr_offset);
951 for(ch=0;ch<s->nb_all_channels;ch++) {
952 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
953 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
957 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
958 put_bits(&s->pb, 1, 0); /* no data to skip */
960 /* mantissa encoding : we use two passes to handle the grouping. A
961 one pass method may be faster, but it would necessitate to
962 modify the output stream. */
964 /* first pass: quantize */
965 mant1_cnt = mant2_cnt = mant4_cnt = 0;
966 qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
968 for (ch = 0; ch < s->nb_all_channels; ch++) {
971 for(i=0;i<s->nb_coefs[ch];i++) {
972 c = mdct_coefs[ch][i];
973 e = encoded_exp[ch][i] - global_exp[ch];
980 v = sym_quant(c, e, 3);
983 qmant1_ptr = &qmant[ch][i];
988 *qmant1_ptr += 3 * v;
1000 v = sym_quant(c, e, 5);
1003 qmant2_ptr = &qmant[ch][i];
1008 *qmant2_ptr += 5 * v;
1020 v = sym_quant(c, e, 7);
1023 v = sym_quant(c, e, 11);
1026 qmant4_ptr = &qmant[ch][i];
1038 v = sym_quant(c, e, 15);
1041 v = asym_quant(c, e, 14);
1044 v = asym_quant(c, e, 16);
1047 v = asym_quant(c, e, b - 1);
1054 /* second pass : output the values */
1055 for (ch = 0; ch < s->nb_all_channels; ch++) {
1058 for(i=0;i<s->nb_coefs[ch];i++) {
1066 put_bits(&s->pb, 5, q);
1070 put_bits(&s->pb, 7, q);
1073 put_bits(&s->pb, 3, q);
1077 put_bits(&s->pb, 7, q);
1080 put_bits(&s->pb, 14, q);
1083 put_bits(&s->pb, 16, q);
1086 put_bits(&s->pb, b - 1, q);
1093 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1095 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1111 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1117 r = mul_poly(r, a, poly);
1118 a = mul_poly(a, a, poly);
1125 /* compute log2(max(abs(tab[]))) */
1126 static int log2_tab(int16_t *tab, int n)
1137 static void lshift_tab(int16_t *tab, int n, int lshift)
1145 } else if (lshift < 0) {
1153 /* fill the end of the frame and compute the two crcs */
1154 static int output_frame_end(AC3EncodeContext *s)
1156 int frame_size, frame_size_58, n, crc1, crc2, crc_inv;
1159 frame_size = s->frame_size; /* frame size in words */
1160 /* align to 8 bits */
1161 flush_put_bits(&s->pb);
1162 /* add zero bytes to reach the frame size */
1164 n = 2 * s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1167 memset(put_bits_ptr(&s->pb), 0, n);
1169 /* Now we must compute both crcs : this is not so easy for crc1
1170 because it is at the beginning of the data... */
1171 frame_size_58 = (frame_size >> 1) + (frame_size >> 3);
1172 crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1173 frame + 4, 2 * frame_size_58 - 4));
1174 /* XXX: could precompute crc_inv */
1175 crc_inv = pow_poly((CRC16_POLY >> 1), (16 * frame_size_58) - 16, CRC16_POLY);
1176 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1177 AV_WB16(frame+2,crc1);
1179 crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1180 frame + 2 * frame_size_58,
1181 (frame_size - frame_size_58) * 2 - 2));
1182 AV_WB16(frame+2*frame_size-2,crc2);
1184 // printf("n=%d frame_size=%d\n", n, frame_size);
1185 return frame_size * 2;
1188 static int AC3_encode_frame(AVCodecContext *avctx,
1189 unsigned char *frame, int buf_size, void *data)
1191 AC3EncodeContext *s = avctx->priv_data;
1192 const int16_t *samples = data;
1194 int16_t input_samples[N];
1195 int32_t mdct_coef[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1196 uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1197 uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS];
1198 uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1199 uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
1200 int8_t exp_samples[NB_BLOCKS][AC3_MAX_CHANNELS];
1204 for(ch=0;ch<s->nb_all_channels;ch++) {
1205 int ich = s->channel_map[ch];
1206 /* fixed mdct to the six sub blocks & exponent computation */
1207 for(i=0;i<NB_BLOCKS;i++) {
1208 const int16_t *sptr;
1211 /* compute input samples */
1212 memcpy(input_samples, s->last_samples[ich], N/2 * sizeof(int16_t));
1213 sinc = s->nb_all_channels;
1214 sptr = samples + (sinc * (N/2) * i) + ich;
1215 for(j=0;j<N/2;j++) {
1217 input_samples[j + N/2] = v;
1218 s->last_samples[ich][j] = v;
1222 /* apply the MDCT window */
1223 for(j=0;j<N/2;j++) {
1224 input_samples[j] = MUL16(input_samples[j],
1225 ff_ac3_window[j]) >> 15;
1226 input_samples[N-j-1] = MUL16(input_samples[N-j-1],
1227 ff_ac3_window[j]) >> 15;
1230 /* Normalize the samples to use the maximum available
1232 v = 14 - log2_tab(input_samples, N);
1235 exp_samples[i][ch] = v - 9;
1236 lshift_tab(input_samples, N, v);
1239 mdct512(mdct_coef[i][ch], input_samples);
1241 /* compute "exponents". We take into account the
1242 normalization there */
1243 for(j=0;j<N/2;j++) {
1245 v = abs(mdct_coef[i][ch][j]);
1249 e = 23 - av_log2(v) + exp_samples[i][ch];
1252 mdct_coef[i][ch][j] = 0;
1259 compute_exp_strategy(exp_strategy, exp, ch, ch == s->lfe_channel);
1261 /* compute the exponents as the decoder will see them. The
1262 EXP_REUSE case must be handled carefully : we select the
1263 min of the exponents */
1265 while (i < NB_BLOCKS) {
1267 while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE) {
1268 exponent_min(exp[i][ch], exp[j][ch], s->nb_coefs[ch]);
1271 frame_bits += encode_exp(encoded_exp[i][ch],
1272 exp[i][ch], s->nb_coefs[ch],
1273 exp_strategy[i][ch]);
1274 /* copy encoded exponents for reuse case */
1275 for(k=i+1;k<j;k++) {
1276 memcpy(encoded_exp[k][ch], encoded_exp[i][ch],
1277 s->nb_coefs[ch] * sizeof(uint8_t));
1283 /* adjust for fractional frame sizes */
1284 while(s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
1285 s->bits_written -= s->bit_rate;
1286 s->samples_written -= s->sample_rate;
1288 s->frame_size = s->frame_size_min + (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
1289 s->bits_written += s->frame_size * 16;
1290 s->samples_written += AC3_FRAME_SIZE;
1292 compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
1293 /* everything is known... let's output the frame */
1294 output_frame_header(s, frame);
1296 for(i=0;i<NB_BLOCKS;i++) {
1297 output_audio_block(s, exp_strategy[i], encoded_exp[i],
1298 bap[i], mdct_coef[i], exp_samples[i], i);
1300 return output_frame_end(s);
1303 static av_cold int AC3_encode_close(AVCodecContext *avctx)
1305 av_freep(&avctx->coded_frame);
1310 /*************************************************************************/
1318 IComplex in[FN], in1[FN];
1320 float sum_re, sum_im, a;
1325 in[i].re = random() % 65535 - 32767;
1326 in[i].im = random() % 65535 - 32767;
1336 a = -2 * M_PI * (n * k) / FN;
1337 sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1338 sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1340 printf("%3d: %6d,%6d %6.0f,%6.0f\n",
1341 k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1345 void mdct_test(void)
1348 int32_t output[N/2];
1351 float s, a, err, e, emax;
1355 input[i] = (random() % 65535 - 32767) * 9 / 10;
1356 input1[i] = input[i];
1359 mdct512(output, input);
1362 for(k=0;k<N/2;k++) {
1365 a = (2*M_PI*(2*n+1+N/2)*(2*k+1) / (4 * N));
1366 s += input1[n] * cos(a);
1368 output1[k] = -2 * s / N;
1373 for(i=0;i<N/2;i++) {
1374 printf("%3d: %7d %7.0f\n", i, output[i], output1[i]);
1375 e = output[i] - output1[i];
1380 printf("err2=%f emax=%f\n", err / (N/2), emax);
1385 AC3EncodeContext ctx;
1386 unsigned char frame[AC3_MAX_CODED_FRAME_SIZE];
1387 int16_t samples[AC3_FRAME_SIZE];
1390 AC3_encode_init(&ctx, 44100, 64000, 1);
1395 for(i=0;i<AC3_FRAME_SIZE;i++)
1396 samples[i] = (int)(sin(2*M_PI*i*1000.0/44100) * 10000);
1397 ret = AC3_encode_frame(&ctx, frame, samples);
1398 printf("ret=%d\n", ret);
1402 AVCodec ac3_encoder = {
1406 sizeof(AC3EncodeContext),
1411 .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1412 .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1413 .channel_layouts = (const int64_t[]){
1415 AV_CH_LAYOUT_STEREO,
1417 AV_CH_LAYOUT_SURROUND,
1420 AV_CH_LAYOUT_4POINT0,
1421 AV_CH_LAYOUT_5POINT0,
1422 AV_CH_LAYOUT_5POINT0_BACK,
1423 (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
1424 (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
1425 (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
1426 (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1427 (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
1428 (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
1429 (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
1430 AV_CH_LAYOUT_5POINT1,
1431 AV_CH_LAYOUT_5POINT1_BACK,