2 * The simplest AC-3 encoder
3 * Copyright (c) 2000 Fabrice Bellard
4 * Copyright (c) 2006-2010 Justin Ruggles <justin.ruggles@gmail.com>
5 * Copyright (c) 2006-2010 Prakash Punnoor <prakash@punnoor.de>
7 * This file is part of FFmpeg.
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 * The simplest AC-3 encoder.
31 #include "libavcore/audioconvert.h"
32 #include "libavutil/crc.h"
37 #include "audioconvert.h"
40 /** Maximum number of exponent groups. +1 for separate DC exponent. */
41 #define AC3_MAX_EXP_GROUPS 85
43 /** Scale a float value by 2^bits and convert to an integer. */
44 #define SCALE_FLOAT(a, bits) lrintf((a) * (float)(1 << (bits)))
46 /** Scale a float value by 2^15, convert to an integer, and clip to int16_t range. */
47 #define FIX15(a) av_clip_int16(SCALE_FLOAT(a, 15))
52 * Used in fixed-point MDCT calculation.
54 typedef struct IComplex {
58 typedef struct AC3MDCTContext {
59 AVCodecContext *avctx; ///< parent context for av_log()
60 int nbits; ///< log2(transform size)
61 int16_t *costab; ///< FFT cos table
62 int16_t *sintab; ///< FFT sin table
63 int16_t *xcos1; ///< MDCT cos table
64 int16_t *xsin1; ///< MDCT sin table
65 int16_t *rot_tmp; ///< temp buffer for pre-rotated samples
66 IComplex *cplx_tmp; ///< temp buffer for complex pre-rotated samples
70 * Data for a single audio block.
72 typedef struct AC3Block {
73 uint8_t **bap; ///< bit allocation pointers (bap)
74 int32_t **mdct_coef; ///< MDCT coefficients
75 uint8_t **exp; ///< original exponents
76 uint8_t **grouped_exp; ///< grouped exponents
77 int16_t **psd; ///< psd per frequency bin
78 int16_t **band_psd; ///< psd per critical band
79 int16_t **mask; ///< masking curve
80 uint16_t **qmant; ///< quantized mantissas
81 uint8_t exp_strategy[AC3_MAX_CHANNELS]; ///< exponent strategies
82 int8_t exp_shift[AC3_MAX_CHANNELS]; ///< exponent shift values
86 * AC-3 encoder private context.
88 typedef struct AC3EncodeContext {
89 PutBitContext pb; ///< bitstream writer context
91 AC3MDCTContext mdct; ///< MDCT context
93 AC3Block blocks[AC3_MAX_BLOCKS]; ///< per-block info
95 int bitstream_id; ///< bitstream id (bsid)
96 int bitstream_mode; ///< bitstream mode (bsmod)
98 int bit_rate; ///< target bit rate, in bits-per-second
99 int sample_rate; ///< sampling frequency, in Hz
101 int frame_size_min; ///< minimum frame size in case rounding is necessary
102 int frame_size; ///< current frame size in bytes
103 int frame_size_code; ///< frame size code (frmsizecod)
104 int bits_written; ///< bit count (used to avg. bitrate)
105 int samples_written; ///< sample count (used to avg. bitrate)
107 int fbw_channels; ///< number of full-bandwidth channels (nfchans)
108 int channels; ///< total number of channels (nchans)
109 int lfe_on; ///< indicates if there is an LFE channel (lfeon)
110 int lfe_channel; ///< channel index of the LFE channel
111 int channel_mode; ///< channel mode (acmod)
112 const uint8_t *channel_map; ///< channel map used to reorder channels
114 int bandwidth_code[AC3_MAX_CHANNELS]; ///< bandwidth code (0 to 60) (chbwcod)
115 int nb_coefs[AC3_MAX_CHANNELS];
117 /* bitrate allocation control */
118 int slow_gain_code; ///< slow gain code (sgaincod)
119 int slow_decay_code; ///< slow decay code (sdcycod)
120 int fast_decay_code; ///< fast decay code (fdcycod)
121 int db_per_bit_code; ///< dB/bit code (dbpbcod)
122 int floor_code; ///< floor code (floorcod)
123 AC3BitAllocParameters bit_alloc; ///< bit allocation parameters
124 int coarse_snr_offset; ///< coarse SNR offsets (csnroffst)
125 int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signal-to-mask ratio) (fgaincod)
126 int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst)
127 int frame_bits_fixed; ///< number of non-coefficient bits for fixed parameters
128 int frame_bits; ///< all frame bits except exponents and mantissas
129 int exponent_bits; ///< number of bits used for exponents
131 /* mantissa encoding */
132 int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
133 uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
135 int16_t **planar_samples;
137 uint8_t *bap1_buffer;
138 int32_t *mdct_coef_buffer;
140 uint8_t *grouped_exp_buffer;
142 int16_t *band_psd_buffer;
143 int16_t *mask_buffer;
144 uint16_t *qmant_buffer;
146 DECLARE_ALIGNED(16, int16_t, windowed_samples)[AC3_WINDOW_SIZE];
151 * LUT for number of exponent groups.
152 * exponent_group_tab[exponent strategy-1][number of coefficients]
154 uint8_t exponent_group_tab[3][256];
158 * Adjust the frame size to make the average bit rate match the target bit rate.
159 * This is only needed for 11025, 22050, and 44100 sample rates.
161 static void adjust_frame_size(AC3EncodeContext *s)
163 while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
164 s->bits_written -= s->bit_rate;
165 s->samples_written -= s->sample_rate;
167 s->frame_size = s->frame_size_min +
168 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
169 s->bits_written += s->frame_size * 8;
170 s->samples_written += AC3_FRAME_SIZE;
175 * Deinterleave input samples.
176 * Channels are reordered from FFmpeg's default order to AC-3 order.
178 static void deinterleave_input_samples(AC3EncodeContext *s,
179 const int16_t *samples)
183 /* deinterleave and remap input samples */
184 for (ch = 0; ch < s->channels; ch++) {
188 /* copy last 256 samples of previous frame to the start of the current frame */
189 memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
190 AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
194 sptr = samples + s->channel_map[ch];
195 for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
196 s->planar_samples[ch][i] = *sptr;
204 * Finalize MDCT and free allocated memory.
206 static av_cold void mdct_end(AC3MDCTContext *mdct)
209 av_freep(&mdct->costab);
210 av_freep(&mdct->sintab);
211 av_freep(&mdct->xcos1);
212 av_freep(&mdct->xsin1);
213 av_freep(&mdct->rot_tmp);
214 av_freep(&mdct->cplx_tmp);
220 * Initialize FFT tables.
221 * @param ln log2(FFT size)
223 static av_cold int fft_init(AC3MDCTContext *mdct, int ln)
231 FF_ALLOC_OR_GOTO(mdct->avctx, mdct->costab, n2 * sizeof(*mdct->costab),
233 FF_ALLOC_OR_GOTO(mdct->avctx, mdct->sintab, n2 * sizeof(*mdct->sintab),
236 for (i = 0; i < n2; i++) {
237 alpha = 2.0 * M_PI * i / n;
238 mdct->costab[i] = FIX15(cos(alpha));
239 mdct->sintab[i] = FIX15(sin(alpha));
245 return AVERROR(ENOMEM);
250 * Initialize MDCT tables.
251 * @param nbits log2(MDCT size)
253 static av_cold int mdct_init(AC3MDCTContext *mdct, int nbits)
262 ret = fft_init(mdct, nbits - 2);
266 FF_ALLOC_OR_GOTO(mdct->avctx, mdct->xcos1, n4 * sizeof(*mdct->xcos1),
268 FF_ALLOC_OR_GOTO(mdct->avctx, mdct->xsin1 , n4 * sizeof(*mdct->xsin1),
270 FF_ALLOC_OR_GOTO(mdct->avctx, mdct->rot_tmp, n * sizeof(*mdct->rot_tmp),
272 FF_ALLOC_OR_GOTO(mdct->avctx, mdct->cplx_tmp, n4 * sizeof(*mdct->cplx_tmp),
275 for (i = 0; i < n4; i++) {
276 float alpha = 2.0 * M_PI * (i + 1.0 / 8.0) / n;
277 mdct->xcos1[i] = FIX15(-cos(alpha));
278 mdct->xsin1[i] = FIX15(-sin(alpha));
284 return AVERROR(ENOMEM);
289 #define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1) \
291 int ax, ay, bx, by; \
296 pre = (bx + ax) >> 1; \
297 pim = (by + ay) >> 1; \
298 qre = (bx - ax) >> 1; \
299 qim = (by - ay) >> 1; \
303 /** Complex multiply */
304 #define CMUL(pre, pim, are, aim, bre, bim) \
306 pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15; \
307 pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15; \
312 * Calculate a 2^n point complex FFT on 2^ln points.
313 * @param z complex input/output samples
314 * @param ln log2(FFT size)
316 static void fft(AC3MDCTContext *mdct, IComplex *z, int ln)
320 register IComplex *p,*q;
326 for (j = 0; j < np; j++) {
327 int k = av_reverse[j] >> (8 - ln);
329 FFSWAP(IComplex, z[k], z[j]);
337 BF(p[0].re, p[0].im, p[1].re, p[1].im,
338 p[0].re, p[0].im, p[1].re, p[1].im);
347 BF(p[0].re, p[0].im, p[2].re, p[2].im,
348 p[0].re, p[0].im, p[2].re, p[2].im);
349 BF(p[1].re, p[1].im, p[3].re, p[3].im,
350 p[1].re, p[1].im, p[3].im, -p[3].re);
362 for (j = 0; j < nblocks; j++) {
363 BF(p->re, p->im, q->re, q->im,
364 p->re, p->im, q->re, q->im);
367 for(l = nblocks; l < np2; l += nblocks) {
368 CMUL(tmp_re, tmp_im, mdct->costab[l], -mdct->sintab[l], q->re, q->im);
369 BF(p->re, p->im, q->re, q->im,
370 p->re, p->im, tmp_re, tmp_im);
377 nblocks = nblocks >> 1;
378 nloops = nloops << 1;
384 * Calculate a 512-point MDCT
385 * @param out 256 output frequency coefficients
386 * @param in 512 windowed input audio samples
388 static void mdct512(AC3MDCTContext *mdct, int32_t *out, int16_t *in)
390 int i, re, im, n, n2, n4;
391 int16_t *rot = mdct->rot_tmp;
392 IComplex *x = mdct->cplx_tmp;
394 n = 1 << mdct->nbits;
398 /* shift to simplify computations */
399 for (i = 0; i <n4; i++)
400 rot[i] = -in[i + 3*n4];
401 memcpy(&rot[n4], &in[0], 3*n4*sizeof(*in));
404 for (i = 0; i < n4; i++) {
405 re = ((int)rot[ 2*i] - (int)rot[ n-1-2*i]) >> 1;
406 im = -((int)rot[n2+2*i] - (int)rot[n2-1-2*i]) >> 1;
407 CMUL(x[i].re, x[i].im, re, im, -mdct->xcos1[i], mdct->xsin1[i]);
410 fft(mdct, x, mdct->nbits - 2);
413 for (i = 0; i < n4; i++) {
416 CMUL(out[n2-1-2*i], out[2*i], re, im, mdct->xsin1[i], mdct->xcos1[i]);
422 * Apply KBD window to input samples prior to MDCT.
424 static void apply_window(int16_t *output, const int16_t *input,
425 const int16_t *window, int n)
430 for (i = 0; i < n2; i++) {
431 output[i] = MUL16(input[i], window[i]) >> 15;
432 output[n-i-1] = MUL16(input[n-i-1], window[i]) >> 15;
438 * Calculate the log2() of the maximum absolute value in an array.
439 * @param tab input array
440 * @param n number of values in the array
441 * @return log2(max(abs(tab[])))
443 static int log2_tab(int16_t *tab, int n)
448 for (i = 0; i < n; i++)
456 * Left-shift each value in an array by a specified amount.
457 * @param tab input array
458 * @param n number of values in the array
459 * @param lshift left shift amount. a negative value means right shift.
461 static void lshift_tab(int16_t *tab, int n, int lshift)
466 for (i = 0; i < n; i++)
468 } else if (lshift < 0) {
470 for (i = 0; i < n; i++)
477 * Normalize the input samples to use the maximum available precision.
478 * This assumes signed 16-bit input samples. Exponents are reduced by 9 to
479 * match the 24-bit internal precision for MDCT coefficients.
481 * @return exponent shift
483 static int normalize_samples(AC3EncodeContext *s)
485 int v = 14 - log2_tab(s->windowed_samples, AC3_WINDOW_SIZE);
487 lshift_tab(s->windowed_samples, AC3_WINDOW_SIZE, v);
493 * Apply the MDCT to input samples to generate frequency coefficients.
494 * This applies the KBD window and normalizes the input to reduce precision
495 * loss due to fixed-point calculations.
497 static void apply_mdct(AC3EncodeContext *s)
501 for (ch = 0; ch < s->channels; ch++) {
502 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
503 AC3Block *block = &s->blocks[blk];
504 const int16_t *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
506 apply_window(s->windowed_samples, input_samples, ff_ac3_window, AC3_WINDOW_SIZE);
508 block->exp_shift[ch] = normalize_samples(s);
510 mdct512(&s->mdct, block->mdct_coef[ch], s->windowed_samples);
517 * Initialize exponent tables.
519 static av_cold void exponent_init(AC3EncodeContext *s)
522 for (i = 73; i < 256; i++) {
523 exponent_group_tab[0][i] = (i - 1) / 3;
524 exponent_group_tab[1][i] = (i + 2) / 6;
525 exponent_group_tab[2][i] = (i + 8) / 12;
528 exponent_group_tab[0][7] = 2;
533 * Extract exponents from the MDCT coefficients.
534 * This takes into account the normalization that was done to the input samples
535 * by adjusting the exponents by the exponent shift values.
537 static void extract_exponents(AC3EncodeContext *s)
541 for (ch = 0; ch < s->channels; ch++) {
542 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
543 AC3Block *block = &s->blocks[blk];
544 for (i = 0; i < AC3_MAX_COEFS; i++) {
546 int v = abs(block->mdct_coef[ch][i]);
550 e = 23 - av_log2(v) + block->exp_shift[ch];
553 block->mdct_coef[ch][i] = 0;
556 block->exp[ch][i] = e;
564 * Exponent Difference Threshold.
565 * New exponents are sent if their SAD exceed this number.
567 #define EXP_DIFF_THRESHOLD 1000
571 * Calculate exponent strategies for all blocks in a single channel.
573 static void compute_exp_strategy_ch(AC3EncodeContext *s, uint8_t *exp_strategy, uint8_t **exp)
578 /* estimate if the exponent variation & decide if they should be
579 reused in the next frame */
580 exp_strategy[0] = EXP_NEW;
581 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
582 exp_diff = s->dsp.sad[0](NULL, exp[blk], exp[blk-1], 16, 16);
583 if (exp_diff > EXP_DIFF_THRESHOLD)
584 exp_strategy[blk] = EXP_NEW;
586 exp_strategy[blk] = EXP_REUSE;
589 /* now select the encoding strategy type : if exponents are often
590 recoded, we use a coarse encoding */
592 while (blk < AC3_MAX_BLOCKS) {
594 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
596 switch (blk1 - blk) {
597 case 1: exp_strategy[blk] = EXP_D45; break;
599 case 3: exp_strategy[blk] = EXP_D25; break;
600 default: exp_strategy[blk] = EXP_D15; break;
608 * Calculate exponent strategies for all channels.
609 * Array arrangement is reversed to simplify the per-channel calculation.
611 static void compute_exp_strategy(AC3EncodeContext *s)
613 uint8_t *exp1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
614 uint8_t exp_str1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
617 for (ch = 0; ch < s->fbw_channels; ch++) {
618 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
619 exp1[ch][blk] = s->blocks[blk].exp[ch];
620 exp_str1[ch][blk] = s->blocks[blk].exp_strategy[ch];
623 compute_exp_strategy_ch(s, exp_str1[ch], exp1[ch]);
625 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
626 s->blocks[blk].exp_strategy[ch] = exp_str1[ch][blk];
630 s->blocks[0].exp_strategy[ch] = EXP_D15;
631 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
632 s->blocks[blk].exp_strategy[ch] = EXP_REUSE;
638 * Set each encoded exponent in a block to the minimum of itself and the
639 * exponent in the same frequency bin of a following block.
640 * exp[i] = min(exp[i], exp1[i]
642 static void exponent_min(uint8_t *exp, uint8_t *exp1, int n)
645 for (i = 0; i < n; i++) {
646 if (exp1[i] < exp[i])
653 * Update the exponents so that they are the ones the decoder will decode.
655 static void encode_exponents_blk_ch(uint8_t *exp,
656 int nb_exps, int exp_strategy)
660 nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
662 /* for each group, compute the minimum exponent */
663 switch(exp_strategy) {
665 for (i = 1, k = 1; i <= nb_groups; i++) {
666 uint8_t exp_min = exp[k];
667 if (exp[k+1] < exp_min)
674 for (i = 1, k = 1; i <= nb_groups; i++) {
675 uint8_t exp_min = exp[k];
676 if (exp[k+1] < exp_min)
678 if (exp[k+2] < exp_min)
680 if (exp[k+3] < exp_min)
688 /* constraint for DC exponent */
692 /* decrease the delta between each groups to within 2 so that they can be
693 differentially encoded */
694 for (i = 1; i <= nb_groups; i++)
695 exp[i] = FFMIN(exp[i], exp[i-1] + 2);
698 exp[i] = FFMIN(exp[i], exp[i+1] + 2);
700 /* now we have the exponent values the decoder will see */
701 switch (exp_strategy) {
703 for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
704 uint8_t exp1 = exp[i];
710 for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
711 exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
720 * Encode exponents from original extracted form to what the decoder will see.
721 * This copies and groups exponents based on exponent strategy and reduces
722 * deltas between adjacent exponent groups so that they can be differentially
725 static void encode_exponents(AC3EncodeContext *s)
727 int blk, blk1, blk2, ch;
728 AC3Block *block, *block1, *block2;
730 for (ch = 0; ch < s->channels; ch++) {
732 block = &s->blocks[0];
733 while (blk < AC3_MAX_BLOCKS) {
736 /* for the EXP_REUSE case we select the min of the exponents */
737 while (blk1 < AC3_MAX_BLOCKS && block1->exp_strategy[ch] == EXP_REUSE) {
738 exponent_min(block->exp[ch], block1->exp[ch], s->nb_coefs[ch]);
742 encode_exponents_blk_ch(block->exp[ch], s->nb_coefs[ch],
743 block->exp_strategy[ch]);
744 /* copy encoded exponents for reuse case */
746 for (blk2 = blk+1; blk2 < blk1; blk2++, block2++) {
747 memcpy(block2->exp[ch], block->exp[ch],
748 s->nb_coefs[ch] * sizeof(uint8_t));
759 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
760 * varies depending on exponent strategy and bandwidth.
762 static void group_exponents(AC3EncodeContext *s)
765 int group_size, nb_groups, bit_count;
767 int delta0, delta1, delta2;
771 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
772 AC3Block *block = &s->blocks[blk];
773 for (ch = 0; ch < s->channels; ch++) {
774 if (block->exp_strategy[ch] == EXP_REUSE) {
777 group_size = block->exp_strategy[ch] + (block->exp_strategy[ch] == EXP_D45);
778 nb_groups = exponent_group_tab[block->exp_strategy[ch]-1][s->nb_coefs[ch]];
779 bit_count += 4 + (nb_groups * 7);
784 block->grouped_exp[ch][0] = exp1;
786 /* remaining exponents are delta encoded */
787 for (i = 1; i <= nb_groups; i++) {
788 /* merge three delta in one code */
792 delta0 = exp1 - exp0 + 2;
797 delta1 = exp1 - exp0 + 2;
802 delta2 = exp1 - exp0 + 2;
804 block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
809 s->exponent_bits = bit_count;
814 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
815 * Extract exponents from MDCT coefficients, calculate exponent strategies,
816 * and encode final exponents.
818 static void process_exponents(AC3EncodeContext *s)
820 extract_exponents(s);
822 compute_exp_strategy(s);
831 * Count frame bits that are based solely on fixed parameters.
832 * This only has to be run once when the encoder is initialized.
834 static void count_frame_bits_fixed(AC3EncodeContext *s)
836 static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
841 * no dynamic range codes
842 * no channel coupling
844 * bit allocation parameters do not change between blocks
845 * SNR offsets do not change between blocks
846 * no delta bit allocation
853 frame_bits += frame_bits_inc[s->channel_mode];
856 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
857 frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
858 if (s->channel_mode == AC3_CHMODE_STEREO) {
859 frame_bits++; /* rematstr */
863 frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
865 frame_bits++; /* lfeexpstr */
866 frame_bits++; /* baie */
867 frame_bits++; /* snr */
868 frame_bits += 2; /* delta / skip */
870 frame_bits++; /* cplinu for block 0 */
872 /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
874 /* (fsnoffset[4] + fgaincod[4]) * c */
875 frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
877 /* auxdatae, crcrsv */
883 s->frame_bits_fixed = frame_bits;
888 * Initialize bit allocation.
889 * Set default parameter codes and calculate parameter values.
891 static void bit_alloc_init(AC3EncodeContext *s)
895 /* init default parameters */
896 s->slow_decay_code = 2;
897 s->fast_decay_code = 1;
898 s->slow_gain_code = 1;
899 s->db_per_bit_code = 2;
901 for (ch = 0; ch < s->channels; ch++)
902 s->fast_gain_code[ch] = 4;
904 /* initial snr offset */
905 s->coarse_snr_offset = 40;
907 /* compute real values */
908 /* currently none of these values change during encoding, so we can just
909 set them once at initialization */
910 s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
911 s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
912 s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
913 s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
914 s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
916 count_frame_bits_fixed(s);
921 * Count the bits used to encode the frame, minus exponents and mantissas.
922 * Bits based on fixed parameters have already been counted, so now we just
923 * have to add the bits based on parameters that change during encoding.
925 static void count_frame_bits(AC3EncodeContext *s)
930 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
931 uint8_t *exp_strategy = s->blocks[blk].exp_strategy;
932 for (ch = 0; ch < s->fbw_channels; ch++) {
933 if (exp_strategy[ch] != EXP_REUSE)
934 frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
937 s->frame_bits = s->frame_bits_fixed + frame_bits;
942 * Calculate the number of bits needed to encode a set of mantissas.
944 static int compute_mantissa_size(int mant_cnt[5], uint8_t *bap, int nb_coefs)
949 for (i = 0; i < nb_coefs; i++) {
952 // bap=1 to bap=4 will be counted in compute_mantissa_size_final
954 } else if (b <= 13) {
955 // bap=5 to bap=13 use (bap-1) bits
958 // bap=14 uses 14 bits and bap=15 uses 16 bits
959 bits += (b == 14) ? 14 : 16;
967 * Finalize the mantissa bit count by adding in the grouped mantissas.
969 static int compute_mantissa_size_final(int mant_cnt[5])
971 // bap=1 : 3 mantissas in 5 bits
972 int bits = (mant_cnt[1] / 3) * 5;
973 // bap=2 : 3 mantissas in 7 bits
974 // bap=4 : 2 mantissas in 7 bits
975 bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
976 // bap=3 : each mantissa is 3 bits
977 bits += mant_cnt[3] * 3;
983 * Calculate masking curve based on the final exponents.
984 * Also calculate the power spectral densities to use in future calculations.
986 static void bit_alloc_masking(AC3EncodeContext *s)
990 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
991 AC3Block *block = &s->blocks[blk];
992 for (ch = 0; ch < s->channels; ch++) {
993 /* We only need psd and mask for calculating bap.
994 Since we currently do not calculate bap when exponent
995 strategy is EXP_REUSE we do not need to calculate psd or mask. */
996 if (block->exp_strategy[ch] != EXP_REUSE) {
997 ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
999 block->psd[ch], block->band_psd[ch]);
1000 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
1002 ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
1003 ch == s->lfe_channel,
1004 DBA_NONE, 0, NULL, NULL, NULL,
1013 * Ensure that bap for each block and channel point to the current bap_buffer.
1014 * They may have been switched during the bit allocation search.
1016 static void reset_block_bap(AC3EncodeContext *s)
1019 if (s->blocks[0].bap[0] == s->bap_buffer)
1021 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1022 for (ch = 0; ch < s->channels; ch++) {
1023 s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
1030 * Run the bit allocation with a given SNR offset.
1031 * This calculates the bit allocation pointers that will be used to determine
1032 * the quantization of each mantissa.
1033 * @return the number of bits needed for mantissas if the given SNR offset is
1036 static int bit_alloc(AC3EncodeContext *s,
1043 snr_offset = (snr_offset - 240) << 2;
1047 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1048 AC3Block *block = &s->blocks[blk];
1049 // initialize grouped mantissa counts. these are set so that they are
1050 // padded to the next whole group size when bits are counted in
1051 // compute_mantissa_size_final
1052 mant_cnt[0] = mant_cnt[3] = 0;
1053 mant_cnt[1] = mant_cnt[2] = 2;
1055 for (ch = 0; ch < s->channels; ch++) {
1056 /* Currently the only bit allocation parameters which vary across
1057 blocks within a frame are the exponent values. We can take
1058 advantage of that by reusing the bit allocation pointers
1059 whenever we reuse exponents. */
1060 if (block->exp_strategy[ch] == EXP_REUSE) {
1061 memcpy(block->bap[ch], s->blocks[blk-1].bap[ch], AC3_MAX_COEFS);
1063 ff_ac3_bit_alloc_calc_bap(block->mask[ch], block->psd[ch], 0,
1064 s->nb_coefs[ch], snr_offset,
1065 s->bit_alloc.floor, ff_ac3_bap_tab,
1068 mantissa_bits += compute_mantissa_size(mant_cnt, block->bap[ch], s->nb_coefs[ch]);
1070 mantissa_bits += compute_mantissa_size_final(mant_cnt);
1072 return mantissa_bits;
1077 * Constant bitrate bit allocation search.
1078 * Find the largest SNR offset that will allow data to fit in the frame.
1080 static int cbr_bit_allocation(AC3EncodeContext *s)
1084 int snr_offset, snr_incr;
1086 bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1088 snr_offset = s->coarse_snr_offset << 4;
1090 while (snr_offset >= 0 &&
1091 bit_alloc(s, snr_offset) > bits_left) {
1095 return AVERROR(EINVAL);
1097 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1098 for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1099 while (snr_offset + 64 <= 1023 &&
1100 bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1101 snr_offset += snr_incr;
1102 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1105 FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1108 s->coarse_snr_offset = snr_offset >> 4;
1109 for (ch = 0; ch < s->channels; ch++)
1110 s->fine_snr_offset[ch] = snr_offset & 0xF;
1117 * Perform bit allocation search.
1118 * Finds the SNR offset value that maximizes quality and fits in the specified
1119 * frame size. Output is the SNR offset and a set of bit allocation pointers
1120 * used to quantize the mantissas.
1122 static int compute_bit_allocation(AC3EncodeContext *s)
1124 count_frame_bits(s);
1126 bit_alloc_masking(s);
1128 return cbr_bit_allocation(s);
1133 * Symmetric quantization on 'levels' levels.
1135 static inline int sym_quant(int c, int e, int levels)
1140 v = (levels * (c << e)) >> 24;
1142 v = (levels >> 1) + v;
1144 v = (levels * ((-c) << e)) >> 24;
1146 v = (levels >> 1) - v;
1148 assert(v >= 0 && v < levels);
1154 * Asymmetric quantization on 2^qbits levels.
1156 static inline int asym_quant(int c, int e, int qbits)
1160 lshift = e + qbits - 24;
1167 m = (1 << (qbits-1));
1171 return v & ((1 << qbits)-1);
1176 * Quantize a set of mantissas for a single channel in a single block.
1178 static void quantize_mantissas_blk_ch(AC3EncodeContext *s,
1179 int32_t *mdct_coef, int8_t exp_shift,
1180 uint8_t *exp, uint8_t *bap,
1181 uint16_t *qmant, int n)
1185 for (i = 0; i < n; i++) {
1187 int c = mdct_coef[i];
1188 int e = exp[i] - exp_shift;
1195 v = sym_quant(c, e, 3);
1196 switch (s->mant1_cnt) {
1198 s->qmant1_ptr = &qmant[i];
1203 *s->qmant1_ptr += 3 * v;
1208 *s->qmant1_ptr += v;
1215 v = sym_quant(c, e, 5);
1216 switch (s->mant2_cnt) {
1218 s->qmant2_ptr = &qmant[i];
1223 *s->qmant2_ptr += 5 * v;
1228 *s->qmant2_ptr += v;
1235 v = sym_quant(c, e, 7);
1238 v = sym_quant(c, e, 11);
1239 switch (s->mant4_cnt) {
1241 s->qmant4_ptr = &qmant[i];
1246 *s->qmant4_ptr += v;
1253 v = sym_quant(c, e, 15);
1256 v = asym_quant(c, e, 14);
1259 v = asym_quant(c, e, 16);
1262 v = asym_quant(c, e, b - 1);
1271 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1273 static void quantize_mantissas(AC3EncodeContext *s)
1278 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1279 AC3Block *block = &s->blocks[blk];
1280 s->mant1_cnt = s->mant2_cnt = s->mant4_cnt = 0;
1281 s->qmant1_ptr = s->qmant2_ptr = s->qmant4_ptr = NULL;
1283 for (ch = 0; ch < s->channels; ch++) {
1284 quantize_mantissas_blk_ch(s, block->mdct_coef[ch], block->exp_shift[ch],
1285 block->exp[ch], block->bap[ch],
1286 block->qmant[ch], s->nb_coefs[ch]);
1293 * Write the AC-3 frame header to the output bitstream.
1295 static void output_frame_header(AC3EncodeContext *s)
1297 put_bits(&s->pb, 16, 0x0b77); /* frame header */
1298 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
1299 put_bits(&s->pb, 2, s->bit_alloc.sr_code);
1300 put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1301 put_bits(&s->pb, 5, s->bitstream_id);
1302 put_bits(&s->pb, 3, s->bitstream_mode);
1303 put_bits(&s->pb, 3, s->channel_mode);
1304 if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1305 put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
1306 if (s->channel_mode & 0x04)
1307 put_bits(&s->pb, 2, 1); /* XXX -6 dB */
1308 if (s->channel_mode == AC3_CHMODE_STEREO)
1309 put_bits(&s->pb, 2, 0); /* surround not indicated */
1310 put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1311 put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
1312 put_bits(&s->pb, 1, 0); /* no compression control word */
1313 put_bits(&s->pb, 1, 0); /* no lang code */
1314 put_bits(&s->pb, 1, 0); /* no audio production info */
1315 put_bits(&s->pb, 1, 0); /* no copyright */
1316 put_bits(&s->pb, 1, 1); /* original bitstream */
1317 put_bits(&s->pb, 1, 0); /* no time code 1 */
1318 put_bits(&s->pb, 1, 0); /* no time code 2 */
1319 put_bits(&s->pb, 1, 0); /* no additional bit stream info */
1324 * Write one audio block to the output bitstream.
1326 static void output_audio_block(AC3EncodeContext *s,
1329 int ch, i, baie, rbnd;
1330 AC3Block *block = &s->blocks[block_num];
1332 /* block switching */
1333 for (ch = 0; ch < s->fbw_channels; ch++)
1334 put_bits(&s->pb, 1, 0);
1337 for (ch = 0; ch < s->fbw_channels; ch++)
1338 put_bits(&s->pb, 1, 1);
1340 /* dynamic range codes */
1341 put_bits(&s->pb, 1, 0);
1343 /* channel coupling */
1345 put_bits(&s->pb, 1, 1); /* coupling strategy present */
1346 put_bits(&s->pb, 1, 0); /* no coupling strategy */
1348 put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1351 /* stereo rematrixing */
1352 if (s->channel_mode == AC3_CHMODE_STEREO) {
1354 /* first block must define rematrixing (rematstr) */
1355 put_bits(&s->pb, 1, 1);
1357 /* dummy rematrixing rematflg(1:4)=0 */
1358 for (rbnd = 0; rbnd < 4; rbnd++)
1359 put_bits(&s->pb, 1, 0);
1361 /* no matrixing (but should be used in the future) */
1362 put_bits(&s->pb, 1, 0);
1366 /* exponent strategy */
1367 for (ch = 0; ch < s->fbw_channels; ch++)
1368 put_bits(&s->pb, 2, block->exp_strategy[ch]);
1370 put_bits(&s->pb, 1, block->exp_strategy[s->lfe_channel]);
1373 for (ch = 0; ch < s->fbw_channels; ch++) {
1374 if (block->exp_strategy[ch] != EXP_REUSE)
1375 put_bits(&s->pb, 6, s->bandwidth_code[ch]);
1379 for (ch = 0; ch < s->channels; ch++) {
1382 if (block->exp_strategy[ch] == EXP_REUSE)
1386 put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1388 /* exponent groups */
1389 nb_groups = exponent_group_tab[block->exp_strategy[ch]-1][s->nb_coefs[ch]];
1390 for (i = 1; i <= nb_groups; i++)
1391 put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1393 /* gain range info */
1394 if (ch != s->lfe_channel)
1395 put_bits(&s->pb, 2, 0);
1398 /* bit allocation info */
1399 baie = (block_num == 0);
1400 put_bits(&s->pb, 1, baie);
1402 put_bits(&s->pb, 2, s->slow_decay_code);
1403 put_bits(&s->pb, 2, s->fast_decay_code);
1404 put_bits(&s->pb, 2, s->slow_gain_code);
1405 put_bits(&s->pb, 2, s->db_per_bit_code);
1406 put_bits(&s->pb, 3, s->floor_code);
1410 put_bits(&s->pb, 1, baie);
1412 put_bits(&s->pb, 6, s->coarse_snr_offset);
1413 for (ch = 0; ch < s->channels; ch++) {
1414 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1415 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1419 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1420 put_bits(&s->pb, 1, 0); /* no data to skip */
1423 for (ch = 0; ch < s->channels; ch++) {
1425 for (i = 0; i < s->nb_coefs[ch]; i++) {
1426 q = block->qmant[ch][i];
1427 b = block->bap[ch][i];
1430 case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
1431 case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
1432 case 3: put_bits(&s->pb, 3, q); break;
1433 case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
1434 case 14: put_bits(&s->pb, 14, q); break;
1435 case 15: put_bits(&s->pb, 16, q); break;
1436 default: put_bits(&s->pb, b-1, q); break;
1443 /** CRC-16 Polynomial */
1444 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1447 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1464 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1470 r = mul_poly(r, a, poly);
1471 a = mul_poly(a, a, poly);
1479 * Fill the end of the frame with 0's and compute the two CRCs.
1481 static void output_frame_end(AC3EncodeContext *s)
1483 int frame_size, frame_size_58, pad_bytes, crc1, crc2, crc_inv;
1486 frame_size = s->frame_size;
1487 frame_size_58 = ((frame_size >> 2) + (frame_size >> 4)) << 1;
1489 /* pad the remainder of the frame with zeros */
1490 flush_put_bits(&s->pb);
1492 pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1493 assert(pad_bytes >= 0);
1495 memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1498 /* this is not so easy because it is at the beginning of the data... */
1499 crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1500 frame + 4, frame_size_58 - 4));
1501 /* XXX: could precompute crc_inv */
1502 crc_inv = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
1503 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1504 AV_WB16(frame + 2, crc1);
1507 crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1508 frame + frame_size_58,
1509 frame_size - frame_size_58 - 2));
1510 AV_WB16(frame + frame_size - 2, crc2);
1515 * Write the frame to the output bitstream.
1517 static void output_frame(AC3EncodeContext *s,
1518 unsigned char *frame)
1522 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1524 output_frame_header(s);
1526 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1527 output_audio_block(s, blk);
1529 output_frame_end(s);
1534 * Encode a single AC-3 frame.
1536 static int ac3_encode_frame(AVCodecContext *avctx,
1537 unsigned char *frame, int buf_size, void *data)
1539 AC3EncodeContext *s = avctx->priv_data;
1540 const int16_t *samples = data;
1543 if (s->bit_alloc.sr_code == 1)
1544 adjust_frame_size(s);
1546 deinterleave_input_samples(s, samples);
1550 process_exponents(s);
1552 ret = compute_bit_allocation(s);
1554 av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1558 quantize_mantissas(s);
1560 output_frame(s, frame);
1562 return s->frame_size;
1567 * Finalize encoding and free any memory allocated by the encoder.
1569 static av_cold int ac3_encode_close(AVCodecContext *avctx)
1572 AC3EncodeContext *s = avctx->priv_data;
1574 for (ch = 0; ch < s->channels; ch++)
1575 av_freep(&s->planar_samples[ch]);
1576 av_freep(&s->planar_samples);
1577 av_freep(&s->bap_buffer);
1578 av_freep(&s->bap1_buffer);
1579 av_freep(&s->mdct_coef_buffer);
1580 av_freep(&s->exp_buffer);
1581 av_freep(&s->grouped_exp_buffer);
1582 av_freep(&s->psd_buffer);
1583 av_freep(&s->band_psd_buffer);
1584 av_freep(&s->mask_buffer);
1585 av_freep(&s->qmant_buffer);
1586 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1587 AC3Block *block = &s->blocks[blk];
1588 av_freep(&block->bap);
1589 av_freep(&block->mdct_coef);
1590 av_freep(&block->exp);
1591 av_freep(&block->grouped_exp);
1592 av_freep(&block->psd);
1593 av_freep(&block->band_psd);
1594 av_freep(&block->mask);
1595 av_freep(&block->qmant);
1600 av_freep(&avctx->coded_frame);
1606 * Set channel information during initialization.
1608 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1609 int64_t *channel_layout)
1613 if (channels < 1 || channels > AC3_MAX_CHANNELS)
1614 return AVERROR(EINVAL);
1615 if ((uint64_t)*channel_layout > 0x7FF)
1616 return AVERROR(EINVAL);
1617 ch_layout = *channel_layout;
1619 ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1620 if (av_get_channel_layout_nb_channels(ch_layout) != channels)
1621 return AVERROR(EINVAL);
1623 s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1624 s->channels = channels;
1625 s->fbw_channels = channels - s->lfe_on;
1626 s->lfe_channel = s->lfe_on ? s->fbw_channels : -1;
1628 ch_layout -= AV_CH_LOW_FREQUENCY;
1630 switch (ch_layout) {
1631 case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
1632 case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
1633 case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
1634 case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
1635 case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
1636 case AV_CH_LAYOUT_QUAD:
1637 case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
1638 case AV_CH_LAYOUT_5POINT0:
1639 case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
1641 return AVERROR(EINVAL);
1644 s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1645 *channel_layout = ch_layout;
1647 *channel_layout |= AV_CH_LOW_FREQUENCY;
1653 static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1657 /* validate channel layout */
1658 if (!avctx->channel_layout) {
1659 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1660 "encoder will guess the layout, but it "
1661 "might be incorrect.\n");
1663 ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1665 av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1669 /* validate sample rate */
1670 for (i = 0; i < 9; i++) {
1671 if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
1675 av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1676 return AVERROR(EINVAL);
1678 s->sample_rate = avctx->sample_rate;
1679 s->bit_alloc.sr_shift = i % 3;
1680 s->bit_alloc.sr_code = i / 3;
1682 /* validate bit rate */
1683 for (i = 0; i < 19; i++) {
1684 if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
1688 av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
1689 return AVERROR(EINVAL);
1691 s->bit_rate = avctx->bit_rate;
1692 s->frame_size_code = i << 1;
1699 * Set bandwidth for all channels.
1700 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
1701 * default value will be used.
1703 static av_cold void set_bandwidth(AC3EncodeContext *s, int cutoff)
1708 /* calculate bandwidth based on user-specified cutoff frequency */
1710 cutoff = av_clip(cutoff, 1, s->sample_rate >> 1);
1711 fbw_coeffs = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
1712 bw_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
1714 /* use default bandwidth setting */
1715 /* XXX: should compute the bandwidth according to the frame
1716 size, so that we avoid annoying high frequency artifacts */
1720 /* set number of coefficients for each channel */
1721 for (ch = 0; ch < s->fbw_channels; ch++) {
1722 s->bandwidth_code[ch] = bw_code;
1723 s->nb_coefs[ch] = bw_code * 3 + 73;
1726 s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
1730 static av_cold int allocate_buffers(AVCodecContext *avctx)
1733 AC3EncodeContext *s = avctx->priv_data;
1735 FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
1737 for (ch = 0; ch < s->channels; ch++) {
1738 FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
1739 (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
1742 FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * s->channels *
1743 AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
1744 FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
1745 AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
1746 FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
1747 AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
1748 FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
1749 AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
1750 FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
1751 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
1752 FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
1753 AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
1754 FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
1755 64 * sizeof(*s->band_psd_buffer), alloc_fail);
1756 FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
1757 64 * sizeof(*s->mask_buffer), alloc_fail);
1758 FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
1759 AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
1760 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1761 AC3Block *block = &s->blocks[blk];
1762 FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
1764 FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
1766 FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
1768 FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
1770 FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
1772 FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
1774 FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
1776 FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
1779 for (ch = 0; ch < s->channels; ch++) {
1780 block->bap[ch] = &s->bap_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
1781 block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
1782 block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
1783 block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * s->channels + ch)];
1784 block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
1785 block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * s->channels + ch)];
1786 block->mask[ch] = &s->mask_buffer [64 * (blk * s->channels + ch)];
1787 block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
1793 return AVERROR(ENOMEM);
1798 * Initialize the encoder.
1800 static av_cold int ac3_encode_init(AVCodecContext *avctx)
1802 AC3EncodeContext *s = avctx->priv_data;
1805 avctx->frame_size = AC3_FRAME_SIZE;
1809 ret = validate_options(avctx, s);
1813 s->bitstream_id = 8 + s->bit_alloc.sr_shift;
1814 s->bitstream_mode = 0; /* complete main audio service */
1816 s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
1817 s->bits_written = 0;
1818 s->samples_written = 0;
1819 s->frame_size = s->frame_size_min;
1821 set_bandwidth(s, avctx->cutoff);
1827 s->mdct.avctx = avctx;
1828 ret = mdct_init(&s->mdct, 9);
1832 ret = allocate_buffers(avctx);
1836 avctx->coded_frame= avcodec_alloc_frame();
1838 dsputil_init(&s->dsp, avctx);
1842 ac3_encode_close(avctx);
1848 /*************************************************************************/
1851 #include "libavutil/lfg.h"
1853 #define MDCT_NBITS 9
1854 #define MDCT_SAMPLES (1 << MDCT_NBITS)
1855 #define FN (MDCT_SAMPLES/4)
1858 static void fft_test(AC3MDCTContext *mdct, AVLFG *lfg)
1860 IComplex in[FN], in1[FN];
1862 float sum_re, sum_im, a;
1864 for (i = 0; i < FN; i++) {
1865 in[i].re = av_lfg_get(lfg) % 65535 - 32767;
1866 in[i].im = av_lfg_get(lfg) % 65535 - 32767;
1872 for (k = 0; k < FN; k++) {
1875 for (n = 0; n < FN; n++) {
1876 a = -2 * M_PI * (n * k) / FN;
1877 sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1878 sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1880 av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
1881 k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1886 static void mdct_test(AC3MDCTContext *mdct, AVLFG *lfg)
1888 int16_t input[MDCT_SAMPLES];
1889 int32_t output[AC3_MAX_COEFS];
1890 float input1[MDCT_SAMPLES];
1891 float output1[AC3_MAX_COEFS];
1892 float s, a, err, e, emax;
1895 for (i = 0; i < MDCT_SAMPLES; i++) {
1896 input[i] = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
1897 input1[i] = input[i];
1900 mdct512(mdct, output, input);
1903 for (k = 0; k < AC3_MAX_COEFS; k++) {
1905 for (n = 0; n < MDCT_SAMPLES; n++) {
1906 a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
1907 s += input1[n] * cos(a);
1909 output1[k] = -2 * s / MDCT_SAMPLES;
1914 for (i = 0; i < AC3_MAX_COEFS; i++) {
1915 av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
1916 e = output[i] - output1[i];
1921 av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
1928 AC3MDCTContext mdct;
1931 av_log_set_level(AV_LOG_DEBUG);
1932 mdct_init(&mdct, 9);
1934 fft_test(&mdct, &lfg);
1935 mdct_test(&mdct, &lfg);
1942 AVCodec ac3_encoder = {
1946 sizeof(AC3EncodeContext),
1951 .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1952 .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1953 .channel_layouts = (const int64_t[]){
1955 AV_CH_LAYOUT_STEREO,
1957 AV_CH_LAYOUT_SURROUND,
1960 AV_CH_LAYOUT_4POINT0,
1961 AV_CH_LAYOUT_5POINT0,
1962 AV_CH_LAYOUT_5POINT0_BACK,
1963 (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
1964 (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
1965 (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
1966 (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1967 (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
1968 (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
1969 (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
1970 AV_CH_LAYOUT_5POINT1,
1971 AV_CH_LAYOUT_5POINT1_BACK,