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 #define SCALE_FLOAT(a, bits) lrintf((a) * (float)(1 << (bits)))
38 typedef struct AC3EncodeContext {
39 PutBitContext pb; ///< bitstream writer context
41 int bitstream_id; ///< bitstream id (bsid)
42 int bitstream_mode; ///< bitstream mode (bsmod)
44 int bit_rate; ///< target bit rate, in bits-per-second
45 int sample_rate; ///< sampling frequency, in Hz
47 int frame_size_min; ///< minimum frame size in case rounding is necessary
48 int frame_size; ///< current frame size in words
49 int frame_size_code; ///< frame size code (frmsizecod)
50 int bits_written; ///< bit count (used to avg. bitrate)
51 int samples_written; ///< sample count (used to avg. bitrate)
53 int fbw_channels; ///< number of full-bandwidth channels (nfchans)
54 int channels; ///< total number of channels (nchans)
55 int lfe_on; ///< indicates if there is an LFE channel (lfeon)
56 int lfe_channel; ///< channel index of the LFE channel
57 int channel_mode; ///< channel mode (acmod)
58 const uint8_t *channel_map; ///< channel map used to reorder channels
60 int bandwidth_code[AC3_MAX_CHANNELS]; ///< bandwidth code (0 to 60) (chbwcod)
61 int nb_coefs[AC3_MAX_CHANNELS];
63 /* bitrate allocation control */
64 int slow_gain_code; ///< slow gain code (sgaincod)
65 int slow_decay_code; ///< slow decay code (sdcycod)
66 int fast_decay_code; ///< fast decay code (fdcycod)
67 int db_per_bit_code; ///< dB/bit code (dbpbcod)
68 int floor_code; ///< floor code (floorcod)
69 AC3BitAllocParameters bit_alloc; ///< bit allocation parameters
70 int coarse_snr_offset; ///< coarse SNR offsets (csnroffst)
71 int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signal-to-mask ratio) (fgaincod)
72 int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst)
74 /* mantissa encoding */
75 int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
77 int16_t last_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE]; ///< last 256 samples from previous frame
80 static int16_t costab[64];
81 static int16_t sintab[64];
82 static int16_t xcos1[128];
83 static int16_t xsin1[128];
86 #define MDCT_SAMPLES (1 << MDCT_NBITS)
88 /* new exponents are sent if their Norm 1 exceed this number */
89 #define EXP_DIFF_THRESHOLD 1000
91 #define FIX15(a) av_clip_int16(SCALE_FLOAT(a, 15))
93 typedef struct IComplex {
97 static av_cold void fft_init(int ln)
104 for(i=0;i<(n/2);i++) {
105 alpha = 2 * M_PI * (float)i / (float)n;
106 costab[i] = FIX15(cos(alpha));
107 sintab[i] = FIX15(sin(alpha));
111 static av_cold void mdct_init(int nbits)
121 alpha = 2 * M_PI * (i + 1.0 / 8.0) / n;
122 xcos1[i] = FIX15(-cos(alpha));
123 xsin1[i] = FIX15(-sin(alpha));
128 #define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1) \
135 pre = (bx + ax) >> 1;\
136 pim = (by + ay) >> 1;\
137 qre = (bx - ax) >> 1;\
138 qim = (by - ay) >> 1;\
141 #define CMUL(pre, pim, are, aim, bre, bim) \
143 pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;\
144 pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;\
148 /* do a 2^n point complex fft on 2^ln points. */
149 static void fft(IComplex *z, int ln)
153 register IComplex *p,*q;
160 int k = av_reverse[j] >> (8 - ln);
162 FFSWAP(IComplex, z[k], z[j]);
170 BF(p[0].re, p[0].im, p[1].re, p[1].im,
171 p[0].re, p[0].im, p[1].re, p[1].im);
180 BF(p[0].re, p[0].im, p[2].re, p[2].im,
181 p[0].re, p[0].im, p[2].re, p[2].im);
182 BF(p[1].re, p[1].im, p[3].re, p[3].im,
183 p[1].re, p[1].im, p[3].im, -p[3].re);
195 for (j = 0; j < nblocks; ++j) {
197 BF(p->re, p->im, q->re, q->im,
198 p->re, p->im, q->re, q->im);
202 for(l = nblocks; l < np2; l += nblocks) {
203 CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
204 BF(p->re, p->im, q->re, q->im,
205 p->re, p->im, tmp_re, tmp_im);
212 nblocks = nblocks >> 1;
213 nloops = nloops << 1;
214 } while (nblocks != 0);
217 /* do a 512 point mdct */
218 static void mdct512(int32_t *out, int16_t *in)
220 int i, re, im, re1, im1;
221 int16_t rot[MDCT_SAMPLES];
222 IComplex x[MDCT_SAMPLES/4];
224 /* shift to simplify computations */
225 for(i=0;i<MDCT_SAMPLES/4;i++)
226 rot[i] = -in[i + 3*MDCT_SAMPLES/4];
227 for(i=MDCT_SAMPLES/4;i<MDCT_SAMPLES;i++)
228 rot[i] = in[i - MDCT_SAMPLES/4];
231 for(i=0;i<MDCT_SAMPLES/4;i++) {
232 re = ((int)rot[2*i] - (int)rot[MDCT_SAMPLES-1-2*i]) >> 1;
233 im = -((int)rot[MDCT_SAMPLES/2+2*i] - (int)rot[MDCT_SAMPLES/2-1-2*i]) >> 1;
234 CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
237 fft(x, MDCT_NBITS - 2);
240 for(i=0;i<MDCT_SAMPLES/4;i++) {
243 CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
245 out[MDCT_SAMPLES/2-1-2*i] = re1;
249 /* XXX: use another norm ? */
250 static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
255 sum += abs(exp1[i] - exp2[i]);
260 static void compute_exp_strategy(uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
261 uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
267 /* estimate if the exponent variation & decide if they should be
268 reused in the next frame */
269 exp_strategy[0][ch] = EXP_NEW;
270 for(i=1;i<AC3_MAX_BLOCKS;i++) {
271 exp_diff = calc_exp_diff(exp[i][ch], exp[i-1][ch], AC3_MAX_COEFS);
272 if (exp_diff > EXP_DIFF_THRESHOLD)
273 exp_strategy[i][ch] = EXP_NEW;
275 exp_strategy[i][ch] = EXP_REUSE;
280 /* now select the encoding strategy type : if exponents are often
281 recoded, we use a coarse encoding */
283 while (i < AC3_MAX_BLOCKS) {
285 while (j < AC3_MAX_BLOCKS && exp_strategy[j][ch] == EXP_REUSE)
289 exp_strategy[i][ch] = EXP_D45;
293 exp_strategy[i][ch] = EXP_D25;
296 exp_strategy[i][ch] = EXP_D15;
303 /* set exp[i] to min(exp[i], exp1[i]) */
304 static void exponent_min(uint8_t exp[AC3_MAX_COEFS], uint8_t exp1[AC3_MAX_COEFS], int n)
309 if (exp1[i] < exp[i])
314 /* update the exponents so that they are the ones the decoder will
315 decode. Return the number of bits used to code the exponents */
316 static int encode_exp(uint8_t encoded_exp[AC3_MAX_COEFS],
317 uint8_t exp[AC3_MAX_COEFS],
321 int group_size, nb_groups, i, j, k, exp_min;
322 uint8_t exp1[AC3_MAX_COEFS];
324 switch(exp_strategy) {
336 nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
338 /* for each group, compute the minimum exponent */
339 exp1[0] = exp[0]; /* DC exponent is handled separately */
341 for(i=1;i<=nb_groups;i++) {
343 assert(exp_min >= 0 && exp_min <= 24);
344 for(j=1;j<group_size;j++) {
345 if (exp[k+j] < exp_min)
352 /* constraint for DC exponent */
356 /* Decrease the delta between each groups to within 2
357 * so that they can be differentially encoded */
358 for (i=1;i<=nb_groups;i++)
359 exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
360 for (i=nb_groups-1;i>=0;i--)
361 exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
363 /* now we have the exponent values the decoder will see */
364 encoded_exp[0] = exp1[0];
366 for(i=1;i<=nb_groups;i++) {
367 for(j=0;j<group_size;j++) {
368 encoded_exp[k+j] = exp1[i];
373 return 4 + (nb_groups / 3) * 7;
376 /* return the size in bits taken by the mantissa */
377 static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
382 for(i=0;i<nb_coefs;i++) {
389 /* 3 mantissa in 5 bits */
390 if (s->mant1_cnt == 0)
392 if (++s->mant1_cnt == 3)
396 /* 3 mantissa in 7 bits */
397 if (s->mant2_cnt == 0)
399 if (++s->mant2_cnt == 3)
406 /* 2 mantissa in 7 bits */
407 if (s->mant4_cnt == 0)
409 if (++s->mant4_cnt == 2)
427 static void bit_alloc_masking(AC3EncodeContext *s,
428 uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
429 uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
430 int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
431 int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][50])
434 int16_t band_psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][50];
436 for(blk=0; blk<AC3_MAX_BLOCKS; blk++) {
437 for(ch=0;ch<s->channels;ch++) {
438 if(exp_strategy[blk][ch] == EXP_REUSE) {
439 memcpy(psd[blk][ch], psd[blk-1][ch], AC3_MAX_COEFS*sizeof(int16_t));
440 memcpy(mask[blk][ch], mask[blk-1][ch], 50*sizeof(int16_t));
442 ff_ac3_bit_alloc_calc_psd(encoded_exp[blk][ch], 0,
444 psd[blk][ch], band_psd[blk][ch]);
445 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, band_psd[blk][ch],
447 ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
448 ch == s->lfe_channel,
449 DBA_NONE, 0, NULL, NULL, NULL,
456 static int bit_alloc(AC3EncodeContext *s,
457 int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][50],
458 int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
459 uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
460 int frame_bits, int coarse_snr_offset, int fine_snr_offset)
465 snr_offset = (((coarse_snr_offset - 15) << 4) + fine_snr_offset) << 2;
468 for(i=0;i<AC3_MAX_BLOCKS;i++) {
472 for(ch=0;ch<s->channels;ch++) {
473 ff_ac3_bit_alloc_calc_bap(mask[i][ch], psd[i][ch], 0,
474 s->nb_coefs[ch], snr_offset,
475 s->bit_alloc.floor, ff_ac3_bap_tab,
477 frame_bits += compute_mantissa_size(s, bap[i][ch],
481 return 16 * s->frame_size - frame_bits;
486 static int compute_bit_allocation(AC3EncodeContext *s,
487 uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
488 uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
489 uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
493 int coarse_snr_offset, fine_snr_offset;
494 uint8_t bap1[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
495 int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
496 int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][50];
497 static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
499 /* init default parameters */
500 s->slow_decay_code = 2;
501 s->fast_decay_code = 1;
502 s->slow_gain_code = 1;
503 s->db_per_bit_code = 2;
505 for(ch=0;ch<s->channels;ch++)
506 s->fast_gain_code[ch] = 4;
508 /* compute real values */
509 s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
510 s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
511 s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
512 s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
513 s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
517 // if (s->channel_mode == 2)
519 frame_bits += frame_bits_inc[s->channel_mode];
522 for(i=0;i<AC3_MAX_BLOCKS;i++) {
523 frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
524 if (s->channel_mode == AC3_CHMODE_STEREO) {
525 frame_bits++; /* rematstr */
526 if(i==0) frame_bits += 4;
528 frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
530 frame_bits++; /* lfeexpstr */
531 for(ch=0;ch<s->fbw_channels;ch++) {
532 if (exp_strategy[i][ch] != EXP_REUSE)
533 frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
535 frame_bits++; /* baie */
536 frame_bits++; /* snr */
537 frame_bits += 2; /* delta / skip */
539 frame_bits++; /* cplinu for block 0 */
541 /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
543 /* (fsnoffset[4] + fgaincod[4]) * c */
544 frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
546 /* auxdatae, crcrsv */
552 /* calculate psd and masking curve before doing bit allocation */
553 bit_alloc_masking(s, encoded_exp, exp_strategy, psd, mask);
555 /* now the big work begins : do the bit allocation. Modify the snr
556 offset until we can pack everything in the requested frame size */
558 coarse_snr_offset = s->coarse_snr_offset;
559 while (coarse_snr_offset >= 0 &&
560 bit_alloc(s, mask, psd, bap, frame_bits, coarse_snr_offset, 0) < 0)
561 coarse_snr_offset -= SNR_INC1;
562 if (coarse_snr_offset < 0) {
563 av_log(NULL, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
566 while ((coarse_snr_offset + SNR_INC1) <= 63 &&
567 bit_alloc(s, mask, psd, bap1, frame_bits,
568 coarse_snr_offset + SNR_INC1, 0) >= 0) {
569 coarse_snr_offset += SNR_INC1;
570 memcpy(bap, bap1, sizeof(bap1));
572 while ((coarse_snr_offset + 1) <= 63 &&
573 bit_alloc(s, mask, psd, bap1, frame_bits, coarse_snr_offset + 1, 0) >= 0) {
575 memcpy(bap, bap1, sizeof(bap1));
579 while ((fine_snr_offset + SNR_INC1) <= 15 &&
580 bit_alloc(s, mask, psd, bap1, frame_bits,
581 coarse_snr_offset, fine_snr_offset + SNR_INC1) >= 0) {
582 fine_snr_offset += SNR_INC1;
583 memcpy(bap, bap1, sizeof(bap1));
585 while ((fine_snr_offset + 1) <= 15 &&
586 bit_alloc(s, mask, psd, bap1, frame_bits,
587 coarse_snr_offset, fine_snr_offset + 1) >= 0) {
589 memcpy(bap, bap1, sizeof(bap1));
592 s->coarse_snr_offset = coarse_snr_offset;
593 for(ch=0;ch<s->channels;ch++)
594 s->fine_snr_offset[ch] = fine_snr_offset;
599 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
600 int64_t *channel_layout)
604 if (channels < 1 || channels > AC3_MAX_CHANNELS)
606 if ((uint64_t)*channel_layout > 0x7FF)
608 ch_layout = *channel_layout;
610 ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
611 if (av_get_channel_layout_nb_channels(ch_layout) != channels)
614 s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
615 s->channels = channels;
616 s->fbw_channels = channels - s->lfe_on;
617 s->lfe_channel = s->lfe_on ? s->fbw_channels : -1;
619 ch_layout -= AV_CH_LOW_FREQUENCY;
622 case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
623 case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
624 case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
625 case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
626 case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
627 case AV_CH_LAYOUT_QUAD:
628 case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
629 case AV_CH_LAYOUT_5POINT0:
630 case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
635 s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
636 *channel_layout = ch_layout;
638 *channel_layout |= AV_CH_LOW_FREQUENCY;
643 static av_cold int AC3_encode_init(AVCodecContext *avctx)
645 int freq = avctx->sample_rate;
646 int bitrate = avctx->bit_rate;
647 AC3EncodeContext *s = avctx->priv_data;
651 avctx->frame_size = AC3_FRAME_SIZE;
655 if (!avctx->channel_layout) {
656 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
657 "encoder will guess the layout, but it "
658 "might be incorrect.\n");
660 if (set_channel_info(s, avctx->channels, &avctx->channel_layout)) {
661 av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
668 if ((ff_ac3_sample_rate_tab[j] >> i) == freq)
673 s->sample_rate = freq;
674 s->bit_alloc.sr_shift = i;
675 s->bit_alloc.sr_code = j;
676 s->bitstream_id = 8 + s->bit_alloc.sr_shift;
677 s->bitstream_mode = 0; /* complete main audio service */
679 /* bitrate & frame size */
681 if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == bitrate)
686 s->bit_rate = bitrate;
687 s->frame_size_code = i << 1;
688 s->frame_size_min = ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
690 s->samples_written = 0;
691 s->frame_size = s->frame_size_min;
693 /* bit allocation init */
695 /* calculate bandwidth based on user-specified cutoff frequency */
696 int cutoff = av_clip(avctx->cutoff, 1, s->sample_rate >> 1);
697 int fbw_coeffs = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
698 bw_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
700 /* use default bandwidth setting */
701 /* XXX: should compute the bandwidth according to the frame
702 size, so that we avoid annoying high frequency artifacts */
705 for(ch=0;ch<s->fbw_channels;ch++) {
706 /* bandwidth for each channel */
707 s->bandwidth_code[ch] = bw_code;
708 s->nb_coefs[ch] = bw_code * 3 + 73;
711 s->nb_coefs[s->lfe_channel] = 7; /* fixed */
713 /* initial snr offset */
714 s->coarse_snr_offset = 40;
718 avctx->coded_frame= avcodec_alloc_frame();
719 avctx->coded_frame->key_frame= 1;
724 /* output the AC-3 frame header */
725 static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
727 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
729 put_bits(&s->pb, 16, 0x0b77); /* frame header */
730 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
731 put_bits(&s->pb, 2, s->bit_alloc.sr_code);
732 put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min));
733 put_bits(&s->pb, 5, s->bitstream_id);
734 put_bits(&s->pb, 3, s->bitstream_mode);
735 put_bits(&s->pb, 3, s->channel_mode);
736 if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
737 put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
738 if (s->channel_mode & 0x04)
739 put_bits(&s->pb, 2, 1); /* XXX -6 dB */
740 if (s->channel_mode == AC3_CHMODE_STEREO)
741 put_bits(&s->pb, 2, 0); /* surround not indicated */
742 put_bits(&s->pb, 1, s->lfe_on); /* LFE */
743 put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
744 put_bits(&s->pb, 1, 0); /* no compression control word */
745 put_bits(&s->pb, 1, 0); /* no lang code */
746 put_bits(&s->pb, 1, 0); /* no audio production info */
747 put_bits(&s->pb, 1, 0); /* no copyright */
748 put_bits(&s->pb, 1, 1); /* original bitstream */
749 put_bits(&s->pb, 1, 0); /* no time code 1 */
750 put_bits(&s->pb, 1, 0); /* no time code 2 */
751 put_bits(&s->pb, 1, 0); /* no additional bit stream info */
754 /* symetric quantization on 'levels' levels */
755 static inline int sym_quant(int c, int e, int levels)
760 v = (levels * (c << e)) >> 24;
762 v = (levels >> 1) + v;
764 v = (levels * ((-c) << e)) >> 24;
766 v = (levels >> 1) - v;
768 assert (v >= 0 && v < levels);
772 /* asymetric quantization on 2^qbits levels */
773 static inline int asym_quant(int c, int e, int qbits)
777 lshift = e + qbits - 24;
784 m = (1 << (qbits-1));
788 return v & ((1 << qbits)-1);
791 /* Output one audio block. There are AC3_MAX_BLOCKS audio blocks in one AC-3
793 static void output_audio_block(AC3EncodeContext *s,
794 uint8_t exp_strategy[AC3_MAX_CHANNELS],
795 uint8_t encoded_exp[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
796 uint8_t bap[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
797 int32_t mdct_coefs[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
798 int8_t global_exp[AC3_MAX_CHANNELS],
801 int ch, nb_groups, group_size, i, baie, rbnd;
803 uint16_t qmant[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
805 int mant1_cnt, mant2_cnt, mant4_cnt;
806 uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
807 int delta0, delta1, delta2;
809 for(ch=0;ch<s->fbw_channels;ch++)
810 put_bits(&s->pb, 1, 0); /* 512 point MDCT */
811 for(ch=0;ch<s->fbw_channels;ch++)
812 put_bits(&s->pb, 1, 1); /* no dither */
813 put_bits(&s->pb, 1, 0); /* no dynamic range */
814 if (block_num == 0) {
815 /* for block 0, even if no coupling, we must say it. This is a
817 put_bits(&s->pb, 1, 1); /* coupling strategy present */
818 put_bits(&s->pb, 1, 0); /* no coupling strategy */
820 put_bits(&s->pb, 1, 0); /* no new coupling strategy */
823 if (s->channel_mode == AC3_CHMODE_STEREO)
827 /* first block must define rematrixing (rematstr) */
828 put_bits(&s->pb, 1, 1);
830 /* dummy rematrixing rematflg(1:4)=0 */
831 for (rbnd=0;rbnd<4;rbnd++)
832 put_bits(&s->pb, 1, 0);
836 /* no matrixing (but should be used in the future) */
837 put_bits(&s->pb, 1, 0);
841 /* exponent strategy */
842 for(ch=0;ch<s->fbw_channels;ch++) {
843 put_bits(&s->pb, 2, exp_strategy[ch]);
847 put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
850 for(ch=0;ch<s->fbw_channels;ch++) {
851 if (exp_strategy[ch] != EXP_REUSE)
852 put_bits(&s->pb, 6, s->bandwidth_code[ch]);
856 for (ch = 0; ch < s->channels; ch++) {
857 switch(exp_strategy[ch]) {
871 nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
876 put_bits(&s->pb, 4, exp1);
878 /* next ones are delta encoded */
879 for(i=0;i<nb_groups;i++) {
880 /* merge three delta in one code */
884 delta0 = exp1 - exp0 + 2;
889 delta1 = exp1 - exp0 + 2;
894 delta2 = exp1 - exp0 + 2;
896 put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
899 if (ch != s->lfe_channel)
900 put_bits(&s->pb, 2, 0); /* no gain range info */
903 /* bit allocation info */
904 baie = (block_num == 0);
905 put_bits(&s->pb, 1, baie);
907 put_bits(&s->pb, 2, s->slow_decay_code);
908 put_bits(&s->pb, 2, s->fast_decay_code);
909 put_bits(&s->pb, 2, s->slow_gain_code);
910 put_bits(&s->pb, 2, s->db_per_bit_code);
911 put_bits(&s->pb, 3, s->floor_code);
915 put_bits(&s->pb, 1, baie); /* always present with bai */
917 put_bits(&s->pb, 6, s->coarse_snr_offset);
918 for(ch=0;ch<s->channels;ch++) {
919 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
920 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
924 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
925 put_bits(&s->pb, 1, 0); /* no data to skip */
927 /* mantissa encoding : we use two passes to handle the grouping. A
928 one pass method may be faster, but it would necessitate to
929 modify the output stream. */
931 /* first pass: quantize */
932 mant1_cnt = mant2_cnt = mant4_cnt = 0;
933 qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
935 for (ch = 0; ch < s->channels; ch++) {
938 for(i=0;i<s->nb_coefs[ch];i++) {
939 c = mdct_coefs[ch][i];
940 e = encoded_exp[ch][i] - global_exp[ch];
947 v = sym_quant(c, e, 3);
950 qmant1_ptr = &qmant[ch][i];
955 *qmant1_ptr += 3 * v;
967 v = sym_quant(c, e, 5);
970 qmant2_ptr = &qmant[ch][i];
975 *qmant2_ptr += 5 * v;
987 v = sym_quant(c, e, 7);
990 v = sym_quant(c, e, 11);
993 qmant4_ptr = &qmant[ch][i];
1005 v = sym_quant(c, e, 15);
1008 v = asym_quant(c, e, 14);
1011 v = asym_quant(c, e, 16);
1014 v = asym_quant(c, e, b - 1);
1021 /* second pass : output the values */
1022 for (ch = 0; ch < s->channels; ch++) {
1025 for(i=0;i<s->nb_coefs[ch];i++) {
1033 put_bits(&s->pb, 5, q);
1037 put_bits(&s->pb, 7, q);
1040 put_bits(&s->pb, 3, q);
1044 put_bits(&s->pb, 7, q);
1047 put_bits(&s->pb, 14, q);
1050 put_bits(&s->pb, 16, q);
1053 put_bits(&s->pb, b - 1, q);
1060 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1062 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1078 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1084 r = mul_poly(r, a, poly);
1085 a = mul_poly(a, a, poly);
1092 /* compute log2(max(abs(tab[]))) */
1093 static int log2_tab(int16_t *tab, int n)
1104 static void lshift_tab(int16_t *tab, int n, int lshift)
1112 } else if (lshift < 0) {
1120 /* fill the end of the frame and compute the two crcs */
1121 static int output_frame_end(AC3EncodeContext *s)
1123 int frame_size, frame_size_58, n, crc1, crc2, crc_inv;
1126 frame_size = s->frame_size; /* frame size in words */
1127 /* align to 8 bits */
1128 flush_put_bits(&s->pb);
1129 /* add zero bytes to reach the frame size */
1131 n = 2 * s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1134 memset(put_bits_ptr(&s->pb), 0, n);
1136 /* Now we must compute both crcs : this is not so easy for crc1
1137 because it is at the beginning of the data... */
1138 frame_size_58 = (frame_size >> 1) + (frame_size >> 3);
1139 crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1140 frame + 4, 2 * frame_size_58 - 4));
1141 /* XXX: could precompute crc_inv */
1142 crc_inv = pow_poly((CRC16_POLY >> 1), (16 * frame_size_58) - 16, CRC16_POLY);
1143 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1144 AV_WB16(frame+2,crc1);
1146 crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1147 frame + 2 * frame_size_58,
1148 (frame_size - frame_size_58) * 2 - 2));
1149 AV_WB16(frame+2*frame_size-2,crc2);
1151 // printf("n=%d frame_size=%d\n", n, frame_size);
1152 return frame_size * 2;
1155 static int AC3_encode_frame(AVCodecContext *avctx,
1156 unsigned char *frame, int buf_size, void *data)
1158 AC3EncodeContext *s = avctx->priv_data;
1159 const int16_t *samples = data;
1161 int16_t input_samples[AC3_WINDOW_SIZE];
1162 int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1163 uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1164 uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
1165 uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1166 uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1167 int8_t exp_samples[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
1171 for(ch=0;ch<s->channels;ch++) {
1172 int ich = s->channel_map[ch];
1173 /* fixed mdct to the six sub blocks & exponent computation */
1174 for(i=0;i<AC3_MAX_BLOCKS;i++) {
1175 const int16_t *sptr;
1178 /* compute input samples */
1179 memcpy(input_samples, s->last_samples[ich], AC3_BLOCK_SIZE * sizeof(int16_t));
1181 sptr = samples + (sinc * AC3_BLOCK_SIZE * i) + ich;
1182 for(j=0;j<AC3_BLOCK_SIZE;j++) {
1184 input_samples[j + AC3_BLOCK_SIZE] = v;
1185 s->last_samples[ich][j] = v;
1189 /* apply the MDCT window */
1190 for(j=0;j<AC3_BLOCK_SIZE;j++) {
1191 input_samples[j] = MUL16(input_samples[j],
1192 ff_ac3_window[j]) >> 15;
1193 input_samples[AC3_WINDOW_SIZE-j-1] = MUL16(input_samples[AC3_WINDOW_SIZE-j-1],
1194 ff_ac3_window[j]) >> 15;
1197 /* Normalize the samples to use the maximum available
1199 v = 14 - log2_tab(input_samples, AC3_WINDOW_SIZE);
1202 exp_samples[i][ch] = v - 9;
1203 lshift_tab(input_samples, AC3_WINDOW_SIZE, v);
1206 mdct512(mdct_coef[i][ch], input_samples);
1208 /* compute "exponents". We take into account the
1209 normalization there */
1210 for(j=0;j<AC3_MAX_COEFS;j++) {
1212 v = abs(mdct_coef[i][ch][j]);
1216 e = 23 - av_log2(v) + exp_samples[i][ch];
1219 mdct_coef[i][ch][j] = 0;
1226 compute_exp_strategy(exp_strategy, exp, ch, ch == s->lfe_channel);
1228 /* compute the exponents as the decoder will see them. The
1229 EXP_REUSE case must be handled carefully : we select the
1230 min of the exponents */
1232 while (i < AC3_MAX_BLOCKS) {
1234 while (j < AC3_MAX_BLOCKS && exp_strategy[j][ch] == EXP_REUSE) {
1235 exponent_min(exp[i][ch], exp[j][ch], s->nb_coefs[ch]);
1238 frame_bits += encode_exp(encoded_exp[i][ch],
1239 exp[i][ch], s->nb_coefs[ch],
1240 exp_strategy[i][ch]);
1241 /* copy encoded exponents for reuse case */
1242 for(k=i+1;k<j;k++) {
1243 memcpy(encoded_exp[k][ch], encoded_exp[i][ch],
1244 s->nb_coefs[ch] * sizeof(uint8_t));
1250 /* adjust for fractional frame sizes */
1251 while(s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
1252 s->bits_written -= s->bit_rate;
1253 s->samples_written -= s->sample_rate;
1255 s->frame_size = s->frame_size_min + (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
1256 s->bits_written += s->frame_size * 16;
1257 s->samples_written += AC3_FRAME_SIZE;
1259 compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
1260 /* everything is known... let's output the frame */
1261 output_frame_header(s, frame);
1263 for(i=0;i<AC3_MAX_BLOCKS;i++) {
1264 output_audio_block(s, exp_strategy[i], encoded_exp[i],
1265 bap[i], mdct_coef[i], exp_samples[i], i);
1267 return output_frame_end(s);
1270 static av_cold int AC3_encode_close(AVCodecContext *avctx)
1272 av_freep(&avctx->coded_frame);
1277 /*************************************************************************/
1280 #include "libavutil/lfg.h"
1282 #define FN (MDCT_SAMPLES/4)
1284 static void fft_test(AVLFG *lfg)
1286 IComplex in[FN], in1[FN];
1288 float sum_re, sum_im, a;
1293 in[i].re = av_lfg_get(lfg) % 65535 - 32767;
1294 in[i].im = av_lfg_get(lfg) % 65535 - 32767;
1304 a = -2 * M_PI * (n * k) / FN;
1305 sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1306 sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1308 av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
1309 k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1313 static void mdct_test(AVLFG *lfg)
1315 int16_t input[MDCT_SAMPLES];
1316 int32_t output[AC3_MAX_COEFS];
1317 float input1[MDCT_SAMPLES];
1318 float output1[AC3_MAX_COEFS];
1319 float s, a, err, e, emax;
1322 for(i=0;i<MDCT_SAMPLES;i++) {
1323 input[i] = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
1324 input1[i] = input[i];
1327 mdct512(output, input);
1330 for(k=0;k<AC3_MAX_COEFS;k++) {
1332 for(n=0;n<MDCT_SAMPLES;n++) {
1333 a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
1334 s += input1[n] * cos(a);
1336 output1[k] = -2 * s / MDCT_SAMPLES;
1341 for(i=0;i<AC3_MAX_COEFS;i++) {
1342 av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
1343 e = output[i] - output1[i];
1348 av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
1355 av_log_set_level(AV_LOG_DEBUG);
1365 AVCodec ac3_encoder = {
1369 sizeof(AC3EncodeContext),
1374 .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1375 .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1376 .channel_layouts = (const int64_t[]){
1378 AV_CH_LAYOUT_STEREO,
1380 AV_CH_LAYOUT_SURROUND,
1383 AV_CH_LAYOUT_4POINT0,
1384 AV_CH_LAYOUT_5POINT0,
1385 AV_CH_LAYOUT_5POINT0_BACK,
1386 (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
1387 (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
1388 (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
1389 (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1390 (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
1391 (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
1392 (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
1393 AV_CH_LAYOUT_5POINT1,
1394 AV_CH_LAYOUT_5POINT1_BACK,