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.
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 {
37 PutBitContext pb; ///< bitstream writer context
39 int bitstream_id; ///< bitstream id (bsid)
40 int bitstream_mode; ///< bitstream mode (bsmod)
42 int bit_rate; ///< target bit rate, in bits-per-second
43 int sample_rate; ///< sampling frequency, in Hz
45 int frame_size_min; ///< minimum frame size in case rounding is necessary
46 int frame_size; ///< current frame size in words
47 int frame_size_code; ///< frame size code (frmsizecod)
48 int bits_written; ///< bit count (used to avg. bitrate)
49 int samples_written; ///< sample count (used to avg. bitrate)
51 int fbw_channels; ///< number of full-bandwidth channels (nfchans)
52 int channels; ///< total number of channels (nchans)
53 int lfe_on; ///< indicates if there is an LFE channel (lfeon)
54 int lfe_channel; ///< channel index of the LFE channel
55 int channel_mode; ///< channel mode (acmod)
56 const uint8_t *channel_map; ///< channel map used to reorder channels
58 int bandwidth_code[AC3_MAX_CHANNELS]; ///< bandwidth code (0 to 60) (chbwcod)
59 int nb_coefs[AC3_MAX_CHANNELS];
61 /* bitrate allocation control */
62 int slow_gain_code; ///< slow gain code (sgaincod)
63 int slow_decay_code; ///< slow decay code (sdcycod)
64 int fast_decay_code; ///< fast decay code (fdcycod)
65 int db_per_bit_code; ///< dB/bit code (dbpbcod)
66 int floor_code; ///< floor code (floorcod)
67 AC3BitAllocParameters bit_alloc; ///< bit allocation parameters
68 int coarse_snr_offset; ///< coarse SNR offsets (csnroffst)
69 int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signal-to-mask ratio) (fgaincod)
70 int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst)
72 /* mantissa encoding */
73 int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
75 int16_t last_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE]; ///< last 256 samples from previous frame
78 static int16_t costab[64];
79 static int16_t sintab[64];
80 static int16_t xcos1[128];
81 static int16_t xsin1[128];
84 #define MDCT_SAMPLES (1 << MDCT_NBITS)
86 /* new exponents are sent if their Norm 1 exceed this number */
87 #define EXP_DIFF_THRESHOLD 1000
89 static inline int16_t fix15(float a)
92 v = (int)(a * (float)(1 << 15));
100 typedef struct IComplex {
104 static av_cold void fft_init(int ln)
111 for(i=0;i<(n/2);i++) {
112 alpha = 2 * M_PI * (float)i / (float)n;
113 costab[i] = fix15(cos(alpha));
114 sintab[i] = fix15(sin(alpha));
118 static av_cold void mdct_init(int nbits)
128 alpha = 2 * M_PI * (i + 1.0 / 8.0) / n;
129 xcos1[i] = fix15(-cos(alpha));
130 xsin1[i] = fix15(-sin(alpha));
135 #define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1) \
142 pre = (bx + ax) >> 1;\
143 pim = (by + ay) >> 1;\
144 qre = (bx - ax) >> 1;\
145 qim = (by - ay) >> 1;\
148 #define CMUL(pre, pim, are, aim, bre, bim) \
150 pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;\
151 pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;\
155 /* do a 2^n point complex fft on 2^ln points. */
156 static void fft(IComplex *z, int ln)
160 register IComplex *p,*q;
167 int k = av_reverse[j] >> (8 - ln);
169 FFSWAP(IComplex, z[k], z[j]);
177 BF(p[0].re, p[0].im, p[1].re, p[1].im,
178 p[0].re, p[0].im, p[1].re, p[1].im);
187 BF(p[0].re, p[0].im, p[2].re, p[2].im,
188 p[0].re, p[0].im, p[2].re, p[2].im);
189 BF(p[1].re, p[1].im, p[3].re, p[3].im,
190 p[1].re, p[1].im, p[3].im, -p[3].re);
202 for (j = 0; j < nblocks; ++j) {
204 BF(p->re, p->im, q->re, q->im,
205 p->re, p->im, q->re, q->im);
209 for(l = nblocks; l < np2; l += nblocks) {
210 CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
211 BF(p->re, p->im, q->re, q->im,
212 p->re, p->im, tmp_re, tmp_im);
219 nblocks = nblocks >> 1;
220 nloops = nloops << 1;
221 } while (nblocks != 0);
224 /* do a 512 point mdct */
225 static void mdct512(int32_t *out, int16_t *in)
227 int i, re, im, re1, im1;
228 int16_t rot[MDCT_SAMPLES];
229 IComplex x[MDCT_SAMPLES/4];
231 /* shift to simplify computations */
232 for(i=0;i<MDCT_SAMPLES/4;i++)
233 rot[i] = -in[i + 3*MDCT_SAMPLES/4];
234 for(i=MDCT_SAMPLES/4;i<MDCT_SAMPLES;i++)
235 rot[i] = in[i - MDCT_SAMPLES/4];
238 for(i=0;i<MDCT_SAMPLES/4;i++) {
239 re = ((int)rot[2*i] - (int)rot[MDCT_SAMPLES-1-2*i]) >> 1;
240 im = -((int)rot[MDCT_SAMPLES/2+2*i] - (int)rot[MDCT_SAMPLES/2-1-2*i]) >> 1;
241 CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
244 fft(x, MDCT_NBITS - 2);
247 for(i=0;i<MDCT_SAMPLES/4;i++) {
250 CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
252 out[MDCT_SAMPLES/2-1-2*i] = re1;
256 /* XXX: use another norm ? */
257 static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
262 sum += abs(exp1[i] - exp2[i]);
267 static void compute_exp_strategy(uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
268 uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
274 /* estimate if the exponent variation & decide if they should be
275 reused in the next frame */
276 exp_strategy[0][ch] = EXP_NEW;
277 for(i=1;i<AC3_MAX_BLOCKS;i++) {
278 exp_diff = calc_exp_diff(exp[i][ch], exp[i-1][ch], AC3_MAX_COEFS);
279 if (exp_diff > EXP_DIFF_THRESHOLD)
280 exp_strategy[i][ch] = EXP_NEW;
282 exp_strategy[i][ch] = EXP_REUSE;
287 /* now select the encoding strategy type : if exponents are often
288 recoded, we use a coarse encoding */
290 while (i < AC3_MAX_BLOCKS) {
292 while (j < AC3_MAX_BLOCKS && exp_strategy[j][ch] == EXP_REUSE)
296 exp_strategy[i][ch] = EXP_D45;
300 exp_strategy[i][ch] = EXP_D25;
303 exp_strategy[i][ch] = EXP_D15;
310 /* set exp[i] to min(exp[i], exp1[i]) */
311 static void exponent_min(uint8_t exp[AC3_MAX_COEFS], uint8_t exp1[AC3_MAX_COEFS], int n)
316 if (exp1[i] < exp[i])
321 /* update the exponents so that they are the ones the decoder will
322 decode. Return the number of bits used to code the exponents */
323 static int encode_exp(uint8_t encoded_exp[AC3_MAX_COEFS],
324 uint8_t exp[AC3_MAX_COEFS],
328 int group_size, nb_groups, i, j, k, exp_min;
329 uint8_t exp1[AC3_MAX_COEFS];
331 switch(exp_strategy) {
343 nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
345 /* for each group, compute the minimum exponent */
346 exp1[0] = exp[0]; /* DC exponent is handled separately */
348 for(i=1;i<=nb_groups;i++) {
350 assert(exp_min >= 0 && exp_min <= 24);
351 for(j=1;j<group_size;j++) {
352 if (exp[k+j] < exp_min)
359 /* constraint for DC exponent */
363 /* Decrease the delta between each groups to within 2
364 * so that they can be differentially encoded */
365 for (i=1;i<=nb_groups;i++)
366 exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
367 for (i=nb_groups-1;i>=0;i--)
368 exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
370 /* now we have the exponent values the decoder will see */
371 encoded_exp[0] = exp1[0];
373 for(i=1;i<=nb_groups;i++) {
374 for(j=0;j<group_size;j++) {
375 encoded_exp[k+j] = exp1[i];
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[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
436 uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
437 int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
438 int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][50])
441 int16_t band_psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][50];
443 for(blk=0; blk<AC3_MAX_BLOCKS; blk++) {
444 for(ch=0;ch<s->channels;ch++) {
445 if(exp_strategy[blk][ch] == EXP_REUSE) {
446 memcpy(psd[blk][ch], psd[blk-1][ch], AC3_MAX_COEFS*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], band_psd[blk][ch]);
452 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, band_psd[blk][ch],
454 ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
455 ch == s->lfe_channel,
456 DBA_NONE, 0, NULL, NULL, NULL,
463 static int bit_alloc(AC3EncodeContext *s,
464 int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][50],
465 int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
466 uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
467 int frame_bits, int coarse_snr_offset, int fine_snr_offset)
472 snr_offset = (((coarse_snr_offset - 15) << 4) + fine_snr_offset) << 2;
475 for(i=0;i<AC3_MAX_BLOCKS;i++) {
479 for(ch=0;ch<s->channels;ch++) {
480 ff_ac3_bit_alloc_calc_bap(mask[i][ch], psd[i][ch], 0,
481 s->nb_coefs[ch], snr_offset,
482 s->bit_alloc.floor, ff_ac3_bap_tab,
484 frame_bits += compute_mantissa_size(s, bap[i][ch],
488 return 16 * s->frame_size - frame_bits;
493 static int compute_bit_allocation(AC3EncodeContext *s,
494 uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
495 uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
496 uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
500 int coarse_snr_offset, fine_snr_offset;
501 uint8_t bap1[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
502 int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
503 int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][50];
504 static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
506 /* init default parameters */
507 s->slow_decay_code = 2;
508 s->fast_decay_code = 1;
509 s->slow_gain_code = 1;
510 s->db_per_bit_code = 2;
512 for(ch=0;ch<s->channels;ch++)
513 s->fast_gain_code[ch] = 4;
515 /* compute real values */
516 s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
517 s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
518 s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
519 s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
520 s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
524 // if (s->channel_mode == 2)
526 frame_bits += frame_bits_inc[s->channel_mode];
529 for(i=0;i<AC3_MAX_BLOCKS;i++) {
530 frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
531 if (s->channel_mode == AC3_CHMODE_STEREO) {
532 frame_bits++; /* rematstr */
533 if(i==0) frame_bits += 4;
535 frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
537 frame_bits++; /* lfeexpstr */
538 for(ch=0;ch<s->fbw_channels;ch++) {
539 if (exp_strategy[i][ch] != EXP_REUSE)
540 frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
542 frame_bits++; /* baie */
543 frame_bits++; /* snr */
544 frame_bits += 2; /* delta / skip */
546 frame_bits++; /* cplinu for block 0 */
548 /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
550 /* (fsnoffset[4] + fgaincod[4]) * c */
551 frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
553 /* auxdatae, crcrsv */
559 /* calculate psd and masking curve before doing bit allocation */
560 bit_alloc_masking(s, encoded_exp, exp_strategy, psd, mask);
562 /* now the big work begins : do the bit allocation. Modify the snr
563 offset until we can pack everything in the requested frame size */
565 coarse_snr_offset = s->coarse_snr_offset;
566 while (coarse_snr_offset >= 0 &&
567 bit_alloc(s, mask, psd, bap, frame_bits, coarse_snr_offset, 0) < 0)
568 coarse_snr_offset -= SNR_INC1;
569 if (coarse_snr_offset < 0) {
570 av_log(NULL, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
573 while ((coarse_snr_offset + SNR_INC1) <= 63 &&
574 bit_alloc(s, mask, psd, bap1, frame_bits,
575 coarse_snr_offset + SNR_INC1, 0) >= 0) {
576 coarse_snr_offset += SNR_INC1;
577 memcpy(bap, bap1, sizeof(bap1));
579 while ((coarse_snr_offset + 1) <= 63 &&
580 bit_alloc(s, mask, psd, bap1, frame_bits, coarse_snr_offset + 1, 0) >= 0) {
582 memcpy(bap, bap1, sizeof(bap1));
586 while ((fine_snr_offset + SNR_INC1) <= 15 &&
587 bit_alloc(s, mask, psd, bap1, frame_bits,
588 coarse_snr_offset, fine_snr_offset + SNR_INC1) >= 0) {
589 fine_snr_offset += SNR_INC1;
590 memcpy(bap, bap1, sizeof(bap1));
592 while ((fine_snr_offset + 1) <= 15 &&
593 bit_alloc(s, mask, psd, bap1, frame_bits,
594 coarse_snr_offset, fine_snr_offset + 1) >= 0) {
596 memcpy(bap, bap1, sizeof(bap1));
599 s->coarse_snr_offset = coarse_snr_offset;
600 for(ch=0;ch<s->channels;ch++)
601 s->fine_snr_offset[ch] = fine_snr_offset;
606 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
607 int64_t *channel_layout)
611 if (channels < 1 || channels > AC3_MAX_CHANNELS)
613 if ((uint64_t)*channel_layout > 0x7FF)
615 ch_layout = *channel_layout;
617 ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
618 if (av_get_channel_layout_nb_channels(ch_layout) != channels)
621 s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
622 s->channels = channels;
623 s->fbw_channels = channels - s->lfe_on;
624 s->lfe_channel = s->lfe_on ? s->fbw_channels : -1;
626 ch_layout -= AV_CH_LOW_FREQUENCY;
629 case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
630 case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
631 case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
632 case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
633 case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
634 case AV_CH_LAYOUT_QUAD:
635 case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
636 case AV_CH_LAYOUT_5POINT0:
637 case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
642 s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
643 *channel_layout = ch_layout;
645 *channel_layout |= AV_CH_LOW_FREQUENCY;
650 static av_cold int AC3_encode_init(AVCodecContext *avctx)
652 int freq = avctx->sample_rate;
653 int bitrate = avctx->bit_rate;
654 AC3EncodeContext *s = avctx->priv_data;
658 avctx->frame_size = AC3_FRAME_SIZE;
662 if (!avctx->channel_layout) {
663 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
664 "encoder will guess the layout, but it "
665 "might be incorrect.\n");
667 if (set_channel_info(s, avctx->channels, &avctx->channel_layout)) {
668 av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
675 if ((ff_ac3_sample_rate_tab[j] >> i) == freq)
680 s->sample_rate = freq;
681 s->bit_alloc.sr_shift = i;
682 s->bit_alloc.sr_code = j;
683 s->bitstream_id = 8 + s->bit_alloc.sr_shift;
684 s->bitstream_mode = 0; /* complete main audio service */
686 /* bitrate & frame size */
688 if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == bitrate)
693 s->bit_rate = bitrate;
694 s->frame_size_code = i << 1;
695 s->frame_size_min = ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
697 s->samples_written = 0;
698 s->frame_size = s->frame_size_min;
700 /* bit allocation init */
702 /* calculate bandwidth based on user-specified cutoff frequency */
703 int cutoff = av_clip(avctx->cutoff, 1, s->sample_rate >> 1);
704 int fbw_coeffs = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
705 bw_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
707 /* use default bandwidth setting */
708 /* XXX: should compute the bandwidth according to the frame
709 size, so that we avoid annoying high frequency artifacts */
712 for(ch=0;ch<s->fbw_channels;ch++) {
713 /* bandwidth for each channel */
714 s->bandwidth_code[ch] = bw_code;
715 s->nb_coefs[ch] = bw_code * 3 + 73;
718 s->nb_coefs[s->lfe_channel] = 7; /* fixed */
720 /* initial snr offset */
721 s->coarse_snr_offset = 40;
725 avctx->coded_frame= avcodec_alloc_frame();
726 avctx->coded_frame->key_frame= 1;
731 /* output the AC-3 frame header */
732 static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
734 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
736 put_bits(&s->pb, 16, 0x0b77); /* frame header */
737 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
738 put_bits(&s->pb, 2, s->bit_alloc.sr_code);
739 put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min));
740 put_bits(&s->pb, 5, s->bitstream_id);
741 put_bits(&s->pb, 3, s->bitstream_mode);
742 put_bits(&s->pb, 3, s->channel_mode);
743 if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
744 put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
745 if (s->channel_mode & 0x04)
746 put_bits(&s->pb, 2, 1); /* XXX -6 dB */
747 if (s->channel_mode == AC3_CHMODE_STEREO)
748 put_bits(&s->pb, 2, 0); /* surround not indicated */
749 put_bits(&s->pb, 1, s->lfe_on); /* LFE */
750 put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
751 put_bits(&s->pb, 1, 0); /* no compression control word */
752 put_bits(&s->pb, 1, 0); /* no lang code */
753 put_bits(&s->pb, 1, 0); /* no audio production info */
754 put_bits(&s->pb, 1, 0); /* no copyright */
755 put_bits(&s->pb, 1, 1); /* original bitstream */
756 put_bits(&s->pb, 1, 0); /* no time code 1 */
757 put_bits(&s->pb, 1, 0); /* no time code 2 */
758 put_bits(&s->pb, 1, 0); /* no additional bit stream info */
761 /* symetric quantization on 'levels' levels */
762 static inline int sym_quant(int c, int e, int levels)
767 v = (levels * (c << e)) >> 24;
769 v = (levels >> 1) + v;
771 v = (levels * ((-c) << e)) >> 24;
773 v = (levels >> 1) - v;
775 assert (v >= 0 && v < levels);
779 /* asymetric quantization on 2^qbits levels */
780 static inline int asym_quant(int c, int e, int qbits)
784 lshift = e + qbits - 24;
791 m = (1 << (qbits-1));
795 return v & ((1 << qbits)-1);
798 /* Output one audio block. There are AC3_MAX_BLOCKS audio blocks in one AC-3
800 static void output_audio_block(AC3EncodeContext *s,
801 uint8_t exp_strategy[AC3_MAX_CHANNELS],
802 uint8_t encoded_exp[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
803 uint8_t bap[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
804 int32_t mdct_coefs[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
805 int8_t global_exp[AC3_MAX_CHANNELS],
808 int ch, nb_groups, group_size, i, baie, rbnd;
810 uint16_t qmant[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
812 int mant1_cnt, mant2_cnt, mant4_cnt;
813 uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
814 int delta0, delta1, delta2;
816 for(ch=0;ch<s->fbw_channels;ch++)
817 put_bits(&s->pb, 1, 0); /* 512 point MDCT */
818 for(ch=0;ch<s->fbw_channels;ch++)
819 put_bits(&s->pb, 1, 1); /* no dither */
820 put_bits(&s->pb, 1, 0); /* no dynamic range */
821 if (block_num == 0) {
822 /* for block 0, even if no coupling, we must say it. This is a
824 put_bits(&s->pb, 1, 1); /* coupling strategy present */
825 put_bits(&s->pb, 1, 0); /* no coupling strategy */
827 put_bits(&s->pb, 1, 0); /* no new coupling strategy */
830 if (s->channel_mode == AC3_CHMODE_STEREO)
834 /* first block must define rematrixing (rematstr) */
835 put_bits(&s->pb, 1, 1);
837 /* dummy rematrixing rematflg(1:4)=0 */
838 for (rbnd=0;rbnd<4;rbnd++)
839 put_bits(&s->pb, 1, 0);
843 /* no matrixing (but should be used in the future) */
844 put_bits(&s->pb, 1, 0);
848 /* exponent strategy */
849 for(ch=0;ch<s->fbw_channels;ch++) {
850 put_bits(&s->pb, 2, exp_strategy[ch]);
854 put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
857 for(ch=0;ch<s->fbw_channels;ch++) {
858 if (exp_strategy[ch] != EXP_REUSE)
859 put_bits(&s->pb, 6, s->bandwidth_code[ch]);
863 for (ch = 0; ch < s->channels; ch++) {
864 switch(exp_strategy[ch]) {
878 nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
883 put_bits(&s->pb, 4, exp1);
885 /* next ones are delta encoded */
886 for(i=0;i<nb_groups;i++) {
887 /* merge three delta in one code */
891 delta0 = exp1 - exp0 + 2;
896 delta1 = exp1 - exp0 + 2;
901 delta2 = exp1 - exp0 + 2;
903 put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
906 if (ch != s->lfe_channel)
907 put_bits(&s->pb, 2, 0); /* no gain range info */
910 /* bit allocation info */
911 baie = (block_num == 0);
912 put_bits(&s->pb, 1, baie);
914 put_bits(&s->pb, 2, s->slow_decay_code);
915 put_bits(&s->pb, 2, s->fast_decay_code);
916 put_bits(&s->pb, 2, s->slow_gain_code);
917 put_bits(&s->pb, 2, s->db_per_bit_code);
918 put_bits(&s->pb, 3, s->floor_code);
922 put_bits(&s->pb, 1, baie); /* always present with bai */
924 put_bits(&s->pb, 6, s->coarse_snr_offset);
925 for(ch=0;ch<s->channels;ch++) {
926 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
927 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
931 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
932 put_bits(&s->pb, 1, 0); /* no data to skip */
934 /* mantissa encoding : we use two passes to handle the grouping. A
935 one pass method may be faster, but it would necessitate to
936 modify the output stream. */
938 /* first pass: quantize */
939 mant1_cnt = mant2_cnt = mant4_cnt = 0;
940 qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
942 for (ch = 0; ch < s->channels; ch++) {
945 for(i=0;i<s->nb_coefs[ch];i++) {
946 c = mdct_coefs[ch][i];
947 e = encoded_exp[ch][i] - global_exp[ch];
954 v = sym_quant(c, e, 3);
957 qmant1_ptr = &qmant[ch][i];
962 *qmant1_ptr += 3 * v;
974 v = sym_quant(c, e, 5);
977 qmant2_ptr = &qmant[ch][i];
982 *qmant2_ptr += 5 * v;
994 v = sym_quant(c, e, 7);
997 v = sym_quant(c, e, 11);
1000 qmant4_ptr = &qmant[ch][i];
1012 v = sym_quant(c, e, 15);
1015 v = asym_quant(c, e, 14);
1018 v = asym_quant(c, e, 16);
1021 v = asym_quant(c, e, b - 1);
1028 /* second pass : output the values */
1029 for (ch = 0; ch < s->channels; ch++) {
1032 for(i=0;i<s->nb_coefs[ch];i++) {
1040 put_bits(&s->pb, 5, q);
1044 put_bits(&s->pb, 7, q);
1047 put_bits(&s->pb, 3, q);
1051 put_bits(&s->pb, 7, q);
1054 put_bits(&s->pb, 14, q);
1057 put_bits(&s->pb, 16, q);
1060 put_bits(&s->pb, b - 1, q);
1067 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1069 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1085 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1091 r = mul_poly(r, a, poly);
1092 a = mul_poly(a, a, poly);
1099 /* compute log2(max(abs(tab[]))) */
1100 static int log2_tab(int16_t *tab, int n)
1111 static void lshift_tab(int16_t *tab, int n, int lshift)
1119 } else if (lshift < 0) {
1127 /* fill the end of the frame and compute the two crcs */
1128 static int output_frame_end(AC3EncodeContext *s)
1130 int frame_size, frame_size_58, n, crc1, crc2, crc_inv;
1133 frame_size = s->frame_size; /* frame size in words */
1134 /* align to 8 bits */
1135 flush_put_bits(&s->pb);
1136 /* add zero bytes to reach the frame size */
1138 n = 2 * s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1141 memset(put_bits_ptr(&s->pb), 0, n);
1143 /* Now we must compute both crcs : this is not so easy for crc1
1144 because it is at the beginning of the data... */
1145 frame_size_58 = (frame_size >> 1) + (frame_size >> 3);
1146 crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1147 frame + 4, 2 * frame_size_58 - 4));
1148 /* XXX: could precompute crc_inv */
1149 crc_inv = pow_poly((CRC16_POLY >> 1), (16 * frame_size_58) - 16, CRC16_POLY);
1150 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1151 AV_WB16(frame+2,crc1);
1153 crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1154 frame + 2 * frame_size_58,
1155 (frame_size - frame_size_58) * 2 - 2));
1156 AV_WB16(frame+2*frame_size-2,crc2);
1158 // printf("n=%d frame_size=%d\n", n, frame_size);
1159 return frame_size * 2;
1162 static int AC3_encode_frame(AVCodecContext *avctx,
1163 unsigned char *frame, int buf_size, void *data)
1165 AC3EncodeContext *s = avctx->priv_data;
1166 const int16_t *samples = data;
1168 int16_t input_samples[AC3_WINDOW_SIZE];
1169 int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1170 uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1171 uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
1172 uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1173 uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1174 int8_t exp_samples[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
1178 for(ch=0;ch<s->channels;ch++) {
1179 int ich = s->channel_map[ch];
1180 /* fixed mdct to the six sub blocks & exponent computation */
1181 for(i=0;i<AC3_MAX_BLOCKS;i++) {
1182 const int16_t *sptr;
1185 /* compute input samples */
1186 memcpy(input_samples, s->last_samples[ich], AC3_BLOCK_SIZE * sizeof(int16_t));
1188 sptr = samples + (sinc * AC3_BLOCK_SIZE * i) + ich;
1189 for(j=0;j<AC3_BLOCK_SIZE;j++) {
1191 input_samples[j + AC3_BLOCK_SIZE] = v;
1192 s->last_samples[ich][j] = v;
1196 /* apply the MDCT window */
1197 for(j=0;j<AC3_BLOCK_SIZE;j++) {
1198 input_samples[j] = MUL16(input_samples[j],
1199 ff_ac3_window[j]) >> 15;
1200 input_samples[AC3_WINDOW_SIZE-j-1] = MUL16(input_samples[AC3_WINDOW_SIZE-j-1],
1201 ff_ac3_window[j]) >> 15;
1204 /* Normalize the samples to use the maximum available
1206 v = 14 - log2_tab(input_samples, AC3_WINDOW_SIZE);
1209 exp_samples[i][ch] = v - 9;
1210 lshift_tab(input_samples, AC3_WINDOW_SIZE, v);
1213 mdct512(mdct_coef[i][ch], input_samples);
1215 /* compute "exponents". We take into account the
1216 normalization there */
1217 for(j=0;j<AC3_MAX_COEFS;j++) {
1219 v = abs(mdct_coef[i][ch][j]);
1223 e = 23 - av_log2(v) + exp_samples[i][ch];
1226 mdct_coef[i][ch][j] = 0;
1233 compute_exp_strategy(exp_strategy, exp, ch, ch == s->lfe_channel);
1235 /* compute the exponents as the decoder will see them. The
1236 EXP_REUSE case must be handled carefully : we select the
1237 min of the exponents */
1239 while (i < AC3_MAX_BLOCKS) {
1241 while (j < AC3_MAX_BLOCKS && exp_strategy[j][ch] == EXP_REUSE) {
1242 exponent_min(exp[i][ch], exp[j][ch], s->nb_coefs[ch]);
1245 frame_bits += encode_exp(encoded_exp[i][ch],
1246 exp[i][ch], s->nb_coefs[ch],
1247 exp_strategy[i][ch]);
1248 /* copy encoded exponents for reuse case */
1249 for(k=i+1;k<j;k++) {
1250 memcpy(encoded_exp[k][ch], encoded_exp[i][ch],
1251 s->nb_coefs[ch] * sizeof(uint8_t));
1257 /* adjust for fractional frame sizes */
1258 while(s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
1259 s->bits_written -= s->bit_rate;
1260 s->samples_written -= s->sample_rate;
1262 s->frame_size = s->frame_size_min + (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
1263 s->bits_written += s->frame_size * 16;
1264 s->samples_written += AC3_FRAME_SIZE;
1266 compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
1267 /* everything is known... let's output the frame */
1268 output_frame_header(s, frame);
1270 for(i=0;i<AC3_MAX_BLOCKS;i++) {
1271 output_audio_block(s, exp_strategy[i], encoded_exp[i],
1272 bap[i], mdct_coef[i], exp_samples[i], i);
1274 return output_frame_end(s);
1277 static av_cold int AC3_encode_close(AVCodecContext *avctx)
1279 av_freep(&avctx->coded_frame);
1284 /*************************************************************************/
1287 #include "libavutil/lfg.h"
1289 #define FN (MDCT_SAMPLES/4)
1291 static void fft_test(AVLFG *lfg)
1293 IComplex in[FN], in1[FN];
1295 float sum_re, sum_im, a;
1300 in[i].re = av_lfg_get(lfg) % 65535 - 32767;
1301 in[i].im = av_lfg_get(lfg) % 65535 - 32767;
1311 a = -2 * M_PI * (n * k) / FN;
1312 sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1313 sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1315 av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
1316 k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1320 static void mdct_test(AVLFG *lfg)
1322 int16_t input[MDCT_SAMPLES];
1323 int32_t output[AC3_MAX_COEFS];
1324 float input1[MDCT_SAMPLES];
1325 float output1[AC3_MAX_COEFS];
1326 float s, a, err, e, emax;
1329 for(i=0;i<MDCT_SAMPLES;i++) {
1330 input[i] = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
1331 input1[i] = input[i];
1334 mdct512(output, input);
1337 for(k=0;k<AC3_MAX_COEFS;k++) {
1339 for(n=0;n<MDCT_SAMPLES;n++) {
1340 a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
1341 s += input1[n] * cos(a);
1343 output1[k] = -2 * s / MDCT_SAMPLES;
1348 for(i=0;i<AC3_MAX_COEFS;i++) {
1349 av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
1350 e = output[i] - output1[i];
1355 av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
1362 av_log_set_level(AV_LOG_DEBUG);
1372 AVCodec ac3_encoder = {
1376 sizeof(AC3EncodeContext),
1381 .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1382 .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1383 .channel_layouts = (const int64_t[]){
1385 AV_CH_LAYOUT_STEREO,
1387 AV_CH_LAYOUT_SURROUND,
1390 AV_CH_LAYOUT_4POINT0,
1391 AV_CH_LAYOUT_5POINT0,
1392 AV_CH_LAYOUT_5POINT0_BACK,
1393 (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
1394 (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
1395 (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
1396 (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1397 (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
1398 (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
1399 (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
1400 AV_CH_LAYOUT_5POINT1,
1401 AV_CH_LAYOUT_5POINT1_BACK,