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.
29 #include "libavcore/audioconvert.h"
30 #include "libavutil/crc.h"
34 #include "audioconvert.h"
38 #define MDCT_SAMPLES (1 << MDCT_NBITS)
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 {
59 * AC-3 encoder private context.
61 typedef struct AC3EncodeContext {
62 PutBitContext pb; ///< bitstream writer context
64 int bitstream_id; ///< bitstream id (bsid)
65 int bitstream_mode; ///< bitstream mode (bsmod)
67 int bit_rate; ///< target bit rate, in bits-per-second
68 int sample_rate; ///< sampling frequency, in Hz
70 int frame_size_min; ///< minimum frame size in case rounding is necessary
71 int frame_size; ///< current frame size in bytes
72 int frame_size_code; ///< frame size code (frmsizecod)
73 int bits_written; ///< bit count (used to avg. bitrate)
74 int samples_written; ///< sample count (used to avg. bitrate)
76 int fbw_channels; ///< number of full-bandwidth channels (nfchans)
77 int channels; ///< total number of channels (nchans)
78 int lfe_on; ///< indicates if there is an LFE channel (lfeon)
79 int lfe_channel; ///< channel index of the LFE channel
80 int channel_mode; ///< channel mode (acmod)
81 const uint8_t *channel_map; ///< channel map used to reorder channels
83 int bandwidth_code[AC3_MAX_CHANNELS]; ///< bandwidth code (0 to 60) (chbwcod)
84 int nb_coefs[AC3_MAX_CHANNELS];
86 /* bitrate allocation control */
87 int slow_gain_code; ///< slow gain code (sgaincod)
88 int slow_decay_code; ///< slow decay code (sdcycod)
89 int fast_decay_code; ///< fast decay code (fdcycod)
90 int db_per_bit_code; ///< dB/bit code (dbpbcod)
91 int floor_code; ///< floor code (floorcod)
92 AC3BitAllocParameters bit_alloc; ///< bit allocation parameters
93 int coarse_snr_offset; ///< coarse SNR offsets (csnroffst)
94 int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signal-to-mask ratio) (fgaincod)
95 int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst)
97 /* mantissa encoding */
98 int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
99 uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
101 int16_t last_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE]; ///< last 256 samples from previous frame
105 /** MDCT and FFT tables */
106 static int16_t costab[64];
107 static int16_t sintab[64];
108 static int16_t xcos1[128];
109 static int16_t xsin1[128];
113 * Adjust the frame size to make the average bit rate match the target bit rate.
114 * This is only needed for 11025, 22050, and 44100 sample rates.
116 static void adjust_frame_size(AC3EncodeContext *s)
118 while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
119 s->bits_written -= s->bit_rate;
120 s->samples_written -= s->sample_rate;
122 s->frame_size = s->frame_size_min + 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
123 s->bits_written += s->frame_size * 8;
124 s->samples_written += AC3_FRAME_SIZE;
129 * Deinterleave input samples.
130 * Channels are reordered from FFmpeg's default order to AC-3 order.
132 static void deinterleave_input_samples(AC3EncodeContext *s,
133 const int16_t *samples,
134 int16_t planar_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE+AC3_FRAME_SIZE])
138 /* deinterleave and remap input samples */
139 for (ch = 0; ch < s->channels; ch++) {
143 /* copy last 256 samples of previous frame to the start of the current frame */
144 memcpy(&planar_samples[ch][0], s->last_samples[ch],
145 AC3_BLOCK_SIZE * sizeof(planar_samples[0][0]));
149 sptr = samples + s->channel_map[ch];
150 for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
151 planar_samples[ch][i] = *sptr;
155 /* save last 256 samples for next frame */
156 memcpy(s->last_samples[ch], &planar_samples[ch][6* AC3_BLOCK_SIZE],
157 AC3_BLOCK_SIZE * sizeof(planar_samples[0][0]));
163 * Initialize FFT tables.
164 * @param ln log2(FFT size)
166 static av_cold void fft_init(int ln)
174 for (i = 0; i < n2; i++) {
175 alpha = 2.0 * M_PI * i / n;
176 costab[i] = FIX15(cos(alpha));
177 sintab[i] = FIX15(sin(alpha));
183 * Initialize MDCT tables.
184 * @param nbits log2(MDCT size)
186 static av_cold void mdct_init(int nbits)
195 for (i = 0; i < n4; i++) {
196 float alpha = 2.0 * M_PI * (i + 1.0 / 8.0) / n;
197 xcos1[i] = FIX15(-cos(alpha));
198 xsin1[i] = FIX15(-sin(alpha));
204 #define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1) \
206 int ax, ay, bx, by; \
211 pre = (bx + ax) >> 1; \
212 pim = (by + ay) >> 1; \
213 qre = (bx - ax) >> 1; \
214 qim = (by - ay) >> 1; \
218 /** Complex multiply */
219 #define CMUL(pre, pim, are, aim, bre, bim) \
221 pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15; \
222 pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15; \
227 * Calculate a 2^n point complex FFT on 2^ln points.
228 * @param z complex input/output samples
229 * @param ln log2(FFT size)
231 static void fft(IComplex *z, int ln)
235 register IComplex *p,*q;
241 for (j = 0; j < np; j++) {
242 int k = av_reverse[j] >> (8 - ln);
244 FFSWAP(IComplex, z[k], z[j]);
252 BF(p[0].re, p[0].im, p[1].re, p[1].im,
253 p[0].re, p[0].im, p[1].re, p[1].im);
262 BF(p[0].re, p[0].im, p[2].re, p[2].im,
263 p[0].re, p[0].im, p[2].re, p[2].im);
264 BF(p[1].re, p[1].im, p[3].re, p[3].im,
265 p[1].re, p[1].im, p[3].im, -p[3].re);
277 for (j = 0; j < nblocks; j++) {
278 BF(p->re, p->im, q->re, q->im,
279 p->re, p->im, q->re, q->im);
282 for(l = nblocks; l < np2; l += nblocks) {
283 CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
284 BF(p->re, p->im, q->re, q->im,
285 p->re, p->im, tmp_re, tmp_im);
292 nblocks = nblocks >> 1;
293 nloops = nloops << 1;
299 * Calculate a 512-point MDCT
300 * @param out 256 output frequency coefficients
301 * @param in 512 windowed input audio samples
303 static void mdct512(int32_t *out, int16_t *in)
305 int i, re, im, re1, im1;
306 int16_t rot[MDCT_SAMPLES];
307 IComplex x[MDCT_SAMPLES/4];
309 /* shift to simplify computations */
310 for (i = 0; i < MDCT_SAMPLES/4; i++)
311 rot[i] = -in[i + 3*MDCT_SAMPLES/4];
312 for (;i < MDCT_SAMPLES; i++)
313 rot[i] = in[i - MDCT_SAMPLES/4];
316 for (i = 0; i < MDCT_SAMPLES/4; i++) {
317 re = ((int)rot[ 2*i] - (int)rot[MDCT_SAMPLES -1-2*i]) >> 1;
318 im = -((int)rot[MDCT_SAMPLES/2+2*i] - (int)rot[MDCT_SAMPLES/2-1-2*i]) >> 1;
319 CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
322 fft(x, MDCT_NBITS - 2);
325 for (i = 0; i < MDCT_SAMPLES/4; i++) {
328 CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
330 out[MDCT_SAMPLES/2-1-2*i] = re1;
336 * Apply KBD window to input samples prior to MDCT.
338 static void apply_window(int16_t *output, const int16_t *input,
339 const int16_t *window, int n)
344 for (i = 0; i < n2; i++) {
345 output[i] = MUL16(input[i], window[i]) >> 15;
346 output[n-i-1] = MUL16(input[n-i-1], window[i]) >> 15;
352 * Calculate the log2() of the maximum absolute value in an array.
353 * @param tab input array
354 * @param n number of values in the array
355 * @return log2(max(abs(tab[])))
357 static int log2_tab(int16_t *tab, int n)
362 for (i = 0; i < n; i++)
370 * Left-shift each value in an array by a specified amount.
371 * @param tab input array
372 * @param n number of values in the array
373 * @param lshift left shift amount. a negative value means right shift.
375 static void lshift_tab(int16_t *tab, int n, int lshift)
380 for(i = 0; i < n; i++)
382 } else if (lshift < 0) {
384 for (i = 0; i < n; i++)
391 * Normalize the input samples to use the maximum available precision.
392 * This assumes signed 16-bit input samples. Exponents are reduced by 9 to
393 * match the 24-bit internal precision for MDCT coefficients.
395 * @return exponent shift
397 static int normalize_samples(AC3EncodeContext *s,
398 int16_t windowed_samples[AC3_WINDOW_SIZE])
400 int v = 14 - log2_tab(windowed_samples, AC3_WINDOW_SIZE);
402 lshift_tab(windowed_samples, AC3_WINDOW_SIZE, v);
408 * Apply the MDCT to input samples to generate frequency coefficients.
409 * This applies the KBD window and normalizes the input to reduce precision
410 * loss due to fixed-point calculations.
412 static void apply_mdct(AC3EncodeContext *s,
413 int16_t planar_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE+AC3_FRAME_SIZE],
414 int8_t exp_shift[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
415 int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS])
418 int16_t windowed_samples[AC3_WINDOW_SIZE];
420 for (ch = 0; ch < s->channels; ch++) {
421 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
422 const int16_t *input_samples = &planar_samples[ch][blk * AC3_BLOCK_SIZE];
424 apply_window(windowed_samples, input_samples, ff_ac3_window, AC3_WINDOW_SIZE);
426 exp_shift[blk][ch] = normalize_samples(s, windowed_samples);
428 mdct512(mdct_coef[blk][ch], windowed_samples);
435 * Extract exponents from the MDCT coefficients.
436 * This takes into account the normalization that was done to the input samples
437 * by adjusting the exponents by the exponent shift values.
439 static void extract_exponents(AC3EncodeContext *s,
440 int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
441 int8_t exp_shift[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
442 uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS])
446 /* extract exponents */
447 for (ch = 0; ch < s->channels; ch++) {
448 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
449 /* compute "exponents". We take into account the normalization there */
450 for (i = 0; i < AC3_MAX_COEFS; i++) {
452 int v = abs(mdct_coef[blk][ch][i]);
456 e = 23 - av_log2(v) + exp_shift[blk][ch];
459 mdct_coef[blk][ch][i] = 0;
470 * Calculate the sum of absolute differences (SAD) between 2 sets of exponents.
472 static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
476 for (i = 0; i < n; i++)
477 sum += abs(exp1[i] - exp2[i]);
483 * Exponent Difference Threshold.
484 * New exponents are sent if their SAD exceed this number.
486 #define EXP_DIFF_THRESHOLD 1000
490 * Calculate exponent strategies for all blocks in a single channel.
492 static void compute_exp_strategy_ch(uint8_t *exp_strategy, uint8_t **exp)
497 /* estimate if the exponent variation & decide if they should be
498 reused in the next frame */
499 exp_strategy[0] = EXP_NEW;
500 for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
501 exp_diff = calc_exp_diff(exp[blk], exp[blk-1], AC3_MAX_COEFS);
502 if (exp_diff > EXP_DIFF_THRESHOLD)
503 exp_strategy[blk] = EXP_NEW;
505 exp_strategy[blk] = EXP_REUSE;
508 /* now select the encoding strategy type : if exponents are often
509 recoded, we use a coarse encoding */
511 while (blk < AC3_MAX_BLOCKS) {
513 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
515 switch (blk1 - blk) {
516 case 1: exp_strategy[blk] = EXP_D45; break;
518 case 3: exp_strategy[blk] = EXP_D25; break;
519 default: exp_strategy[blk] = EXP_D15; break;
527 * Calculate exponent strategies for all channels.
528 * Array arrangement is reversed to simplify the per-channel calculation.
530 static void compute_exp_strategy(AC3EncodeContext *s,
531 uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
532 uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS])
534 uint8_t *exp1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
535 uint8_t exp_str1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
538 for (ch = 0; ch < s->fbw_channels; ch++) {
539 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
540 exp1[ch][blk] = exp[blk][ch];
541 exp_str1[ch][blk] = exp_strategy[blk][ch];
544 compute_exp_strategy_ch(exp_str1[ch], exp1[ch]);
546 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
547 exp_strategy[blk][ch] = exp_str1[ch][blk];
551 exp_strategy[0][ch] = EXP_D15;
552 for (blk = 1; blk < 5; blk++)
553 exp_strategy[blk][ch] = EXP_REUSE;
559 * Set each encoded exponent in a block to the minimum of itself and the
560 * exponent in the same frequency bin of a following block.
561 * exp[i] = min(exp[i], exp1[i]
563 static void exponent_min(uint8_t exp[AC3_MAX_COEFS], uint8_t exp1[AC3_MAX_COEFS], int n)
566 for (i = 0; i < n; i++) {
567 if (exp1[i] < exp[i])
574 * Update the exponents so that they are the ones the decoder will decode.
576 static void encode_exponents_blk_ch(uint8_t encoded_exp[AC3_MAX_COEFS],
577 uint8_t exp[AC3_MAX_COEFS],
578 int nb_exps, int exp_strategy)
580 int group_size, nb_groups, i, j, k, exp_min;
581 uint8_t exp1[AC3_MAX_COEFS];
583 group_size = exp_strategy + (exp_strategy == EXP_D45);
584 nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
586 /* for each group, compute the minimum exponent */
587 exp1[0] = exp[0]; /* DC exponent is handled separately */
589 for (i = 1; i <= nb_groups; i++) {
591 assert(exp_min >= 0 && exp_min <= 24);
592 for (j = 1; j < group_size; j++) {
593 if (exp[k+j] < exp_min)
600 /* constraint for DC exponent */
604 /* decrease the delta between each groups to within 2 so that they can be
605 differentially encoded */
606 for (i = 1; i <= nb_groups; i++)
607 exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
608 for (i = nb_groups-1; i >= 0; i--)
609 exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
611 /* now we have the exponent values the decoder will see */
612 encoded_exp[0] = exp1[0];
614 for (i = 1; i <= nb_groups; i++) {
615 for (j = 0; j < group_size; j++)
616 encoded_exp[k+j] = exp1[i];
623 * Encode exponents from original extracted form to what the decoder will see.
624 * This copies and groups exponents based on exponent strategy and reduces
625 * deltas between adjacent exponent groups so that they can be differentially
628 static void encode_exponents(AC3EncodeContext *s,
629 uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
630 uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
631 uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS])
633 int blk, blk1, blk2, ch;
635 for (ch = 0; ch < s->channels; ch++) {
636 /* for the EXP_REUSE case we select the min of the exponents */
638 while (blk < AC3_MAX_BLOCKS) {
640 while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1][ch] == EXP_REUSE) {
641 exponent_min(exp[blk][ch], exp[blk1][ch], s->nb_coefs[ch]);
644 encode_exponents_blk_ch(encoded_exp[blk][ch],
645 exp[blk][ch], s->nb_coefs[ch],
646 exp_strategy[blk][ch]);
647 /* copy encoded exponents for reuse case */
648 for (blk2 = blk+1; blk2 < blk1; blk2++) {
649 memcpy(encoded_exp[blk2][ch], encoded_exp[blk][ch],
650 s->nb_coefs[ch] * sizeof(uint8_t));
660 * 3 delta-encoded exponents are in each 7-bit group. The number of groups
661 * varies depending on exponent strategy and bandwidth.
662 * @return bits needed to encode the exponents
664 static int group_exponents(AC3EncodeContext *s,
665 uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
666 uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
667 uint8_t num_exp_groups[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
668 uint8_t grouped_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_EXP_GROUPS])
671 int group_size, bit_count;
673 int delta0, delta1, delta2;
677 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
678 for (ch = 0; ch < s->channels; ch++) {
679 if (exp_strategy[blk][ch] == EXP_REUSE) {
680 num_exp_groups[blk][ch] = 0;
683 group_size = exp_strategy[blk][ch] + (exp_strategy[blk][ch] == EXP_D45);
684 num_exp_groups[blk][ch] = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
685 bit_count += 4 + (num_exp_groups[blk][ch] * 7);
686 p = encoded_exp[blk][ch];
690 grouped_exp[blk][ch][0] = exp1;
692 /* remaining exponents are delta encoded */
693 for (i = 1; i <= num_exp_groups[blk][ch]; i++) {
694 /* merge three delta in one code */
698 delta0 = exp1 - exp0 + 2;
703 delta1 = exp1 - exp0 + 2;
708 delta2 = exp1 - exp0 + 2;
710 grouped_exp[blk][ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
720 * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
721 * Extract exponents from MDCT coefficients, calculate exponent strategies,
722 * and encode final exponents.
723 * @return bits needed to encode the exponents
725 static int process_exponents(AC3EncodeContext *s,
726 int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
727 int8_t exp_shift[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
728 uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
729 uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
730 uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
731 uint8_t num_exp_groups[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
732 uint8_t grouped_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_EXP_GROUPS])
734 extract_exponents(s, mdct_coef, exp_shift, exp);
736 compute_exp_strategy(s, exp_strategy, exp);
738 encode_exponents(s, exp, exp_strategy, encoded_exp);
740 return group_exponents(s, encoded_exp, exp_strategy, num_exp_groups, grouped_exp);
745 * Calculate the number of bits needed to encode a set of mantissas.
747 static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
752 for (i = 0; i < nb_coefs; i++) {
759 /* 3 mantissa in 5 bits */
760 if (s->mant1_cnt == 0)
762 if (++s->mant1_cnt == 3)
766 /* 3 mantissa in 7 bits */
767 if (s->mant2_cnt == 0)
769 if (++s->mant2_cnt == 3)
776 /* 2 mantissa in 7 bits */
777 if (s->mant4_cnt == 0)
779 if (++s->mant4_cnt == 2)
798 * Calculate masking curve based on the final exponents.
799 * Also calculate the power spectral densities to use in future calculations.
801 static void bit_alloc_masking(AC3EncodeContext *s,
802 uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
803 uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
804 int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
805 int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS])
808 int16_t band_psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];
810 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
811 for (ch = 0; ch < s->channels; ch++) {
812 if(exp_strategy[blk][ch] == EXP_REUSE) {
813 memcpy(psd[blk][ch], psd[blk-1][ch], AC3_MAX_COEFS*sizeof(psd[0][0][0]));
814 memcpy(mask[blk][ch], mask[blk-1][ch], AC3_CRITICAL_BANDS*sizeof(mask[0][0][0]));
816 ff_ac3_bit_alloc_calc_psd(encoded_exp[blk][ch], 0,
818 psd[blk][ch], band_psd[blk][ch]);
819 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, band_psd[blk][ch],
821 ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
822 ch == s->lfe_channel,
823 DBA_NONE, 0, NULL, NULL, NULL,
832 * Run the bit allocation with a given SNR offset.
833 * This calculates the bit allocation pointers that will be used to determine
834 * the quantization of each mantissa.
835 * @return the number of remaining bits (positive or negative) if the given
836 * SNR offset is used to quantize the mantissas.
838 static int bit_alloc(AC3EncodeContext *s,
839 int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS],
840 int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
841 uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
842 int frame_bits, int coarse_snr_offset, int fine_snr_offset)
847 snr_offset = (((coarse_snr_offset - 15) << 4) + fine_snr_offset) << 2;
849 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
853 for (ch = 0; ch < s->channels; ch++) {
854 ff_ac3_bit_alloc_calc_bap(mask[blk][ch], psd[blk][ch], 0,
855 s->nb_coefs[ch], snr_offset,
856 s->bit_alloc.floor, ff_ac3_bap_tab,
858 frame_bits += compute_mantissa_size(s, bap[blk][ch], s->nb_coefs[ch]);
861 return 8 * s->frame_size - frame_bits;
868 * Perform bit allocation search.
869 * Finds the SNR offset value that maximizes quality and fits in the specified
870 * frame size. Output is the SNR offset and a set of bit allocation pointers
871 * used to quantize the mantissas.
873 static int compute_bit_allocation(AC3EncodeContext *s,
874 uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
875 uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
876 uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
880 int coarse_snr_offset, fine_snr_offset;
881 uint8_t bap1[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
882 int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
883 int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];
884 static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
886 /* init default parameters */
887 s->slow_decay_code = 2;
888 s->fast_decay_code = 1;
889 s->slow_gain_code = 1;
890 s->db_per_bit_code = 2;
892 for (ch = 0; ch < s->channels; ch++)
893 s->fast_gain_code[ch] = 4;
895 /* compute real values */
896 s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
897 s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
898 s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
899 s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
900 s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
904 // if (s->channel_mode == 2)
906 frame_bits += frame_bits_inc[s->channel_mode];
909 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
910 frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
911 if (s->channel_mode == AC3_CHMODE_STEREO) {
912 frame_bits++; /* rematstr */
916 frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
918 frame_bits++; /* lfeexpstr */
919 for (ch = 0; ch < s->fbw_channels; ch++) {
920 if (exp_strategy[blk][ch] != EXP_REUSE)
921 frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
923 frame_bits++; /* baie */
924 frame_bits++; /* snr */
925 frame_bits += 2; /* delta / skip */
927 frame_bits++; /* cplinu for block 0 */
929 /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
931 /* (fsnoffset[4] + fgaincod[4]) * c */
932 frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
934 /* auxdatae, crcrsv */
940 /* calculate psd and masking curve before doing bit allocation */
941 bit_alloc_masking(s, encoded_exp, exp_strategy, psd, mask);
943 /* now the big work begins : do the bit allocation. Modify the snr
944 offset until we can pack everything in the requested frame size */
946 coarse_snr_offset = s->coarse_snr_offset;
947 while (coarse_snr_offset >= 0 &&
948 bit_alloc(s, mask, psd, bap, frame_bits, coarse_snr_offset, 0) < 0)
949 coarse_snr_offset -= SNR_INC1;
950 if (coarse_snr_offset < 0) {
951 av_log(NULL, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
954 while (coarse_snr_offset + SNR_INC1 <= 63 &&
955 bit_alloc(s, mask, psd, bap1, frame_bits,
956 coarse_snr_offset + SNR_INC1, 0) >= 0) {
957 coarse_snr_offset += SNR_INC1;
958 memcpy(bap, bap1, sizeof(bap1));
960 while (coarse_snr_offset + 1 <= 63 &&
961 bit_alloc(s, mask, psd, bap1, frame_bits, coarse_snr_offset + 1, 0) >= 0) {
963 memcpy(bap, bap1, sizeof(bap1));
967 while (fine_snr_offset + SNR_INC1 <= 15 &&
968 bit_alloc(s, mask, psd, bap1, frame_bits,
969 coarse_snr_offset, fine_snr_offset + SNR_INC1) >= 0) {
970 fine_snr_offset += SNR_INC1;
971 memcpy(bap, bap1, sizeof(bap1));
973 while (fine_snr_offset + 1 <= 15 &&
974 bit_alloc(s, mask, psd, bap1, frame_bits,
975 coarse_snr_offset, fine_snr_offset + 1) >= 0) {
977 memcpy(bap, bap1, sizeof(bap1));
980 s->coarse_snr_offset = coarse_snr_offset;
981 for (ch = 0; ch < s->channels; ch++)
982 s->fine_snr_offset[ch] = fine_snr_offset;
989 * Symmetric quantization on 'levels' levels.
991 static inline int sym_quant(int c, int e, int levels)
996 v = (levels * (c << e)) >> 24;
998 v = (levels >> 1) + v;
1000 v = (levels * ((-c) << e)) >> 24;
1002 v = (levels >> 1) - v;
1004 assert (v >= 0 && v < levels);
1010 * Asymmetric quantization on 2^qbits levels.
1012 static inline int asym_quant(int c, int e, int qbits)
1016 lshift = e + qbits - 24;
1023 m = (1 << (qbits-1));
1027 return v & ((1 << qbits)-1);
1032 * Quantize a set of mantissas for a single channel in a single block.
1034 static void quantize_mantissas_blk_ch(AC3EncodeContext *s,
1035 int32_t *mdct_coef, int8_t exp_shift,
1036 uint8_t *encoded_exp, uint8_t *bap,
1037 uint16_t *qmant, int n)
1041 for (i = 0; i < n; i++) {
1043 int c = mdct_coef[i];
1044 int e = encoded_exp[i] - exp_shift;
1051 v = sym_quant(c, e, 3);
1052 switch (s->mant1_cnt) {
1054 s->qmant1_ptr = &qmant[i];
1059 *s->qmant1_ptr += 3 * v;
1064 *s->qmant1_ptr += v;
1071 v = sym_quant(c, e, 5);
1072 switch (s->mant2_cnt) {
1074 s->qmant2_ptr = &qmant[i];
1079 *s->qmant2_ptr += 5 * v;
1084 *s->qmant2_ptr += v;
1091 v = sym_quant(c, e, 7);
1094 v = sym_quant(c, e, 11);
1095 switch (s->mant4_cnt) {
1097 s->qmant4_ptr = &qmant[i];
1102 *s->qmant4_ptr += v;
1109 v = sym_quant(c, e, 15);
1112 v = asym_quant(c, e, 14);
1115 v = asym_quant(c, e, 16);
1118 v = asym_quant(c, e, b - 1);
1127 * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1129 static void quantize_mantissas(AC3EncodeContext *s,
1130 int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
1131 int8_t exp_shift[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
1132 uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
1133 uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
1134 uint16_t qmant[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS])
1139 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1140 s->mant1_cnt = s->mant2_cnt = s->mant4_cnt = 0;
1141 s->qmant1_ptr = s->qmant2_ptr = s->qmant4_ptr = NULL;
1143 for (ch = 0; ch < s->channels; ch++) {
1144 quantize_mantissas_blk_ch(s, mdct_coef[blk][ch], exp_shift[blk][ch],
1145 encoded_exp[blk][ch], bap[blk][ch],
1146 qmant[blk][ch], s->nb_coefs[ch]);
1153 * Write the AC-3 frame header to the output bitstream.
1155 static void output_frame_header(AC3EncodeContext *s)
1157 put_bits(&s->pb, 16, 0x0b77); /* frame header */
1158 put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
1159 put_bits(&s->pb, 2, s->bit_alloc.sr_code);
1160 put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1161 put_bits(&s->pb, 5, s->bitstream_id);
1162 put_bits(&s->pb, 3, s->bitstream_mode);
1163 put_bits(&s->pb, 3, s->channel_mode);
1164 if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1165 put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
1166 if (s->channel_mode & 0x04)
1167 put_bits(&s->pb, 2, 1); /* XXX -6 dB */
1168 if (s->channel_mode == AC3_CHMODE_STEREO)
1169 put_bits(&s->pb, 2, 0); /* surround not indicated */
1170 put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1171 put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
1172 put_bits(&s->pb, 1, 0); /* no compression control word */
1173 put_bits(&s->pb, 1, 0); /* no lang code */
1174 put_bits(&s->pb, 1, 0); /* no audio production info */
1175 put_bits(&s->pb, 1, 0); /* no copyright */
1176 put_bits(&s->pb, 1, 1); /* original bitstream */
1177 put_bits(&s->pb, 1, 0); /* no time code 1 */
1178 put_bits(&s->pb, 1, 0); /* no time code 2 */
1179 put_bits(&s->pb, 1, 0); /* no additional bit stream info */
1184 * Write one audio block to the output bitstream.
1186 static void output_audio_block(AC3EncodeContext *s,
1187 uint8_t exp_strategy[AC3_MAX_CHANNELS],
1188 uint8_t num_exp_groups[AC3_MAX_CHANNELS],
1189 uint8_t grouped_exp[AC3_MAX_CHANNELS][AC3_MAX_EXP_GROUPS],
1190 uint8_t bap[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
1191 uint16_t qmant[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
1194 int ch, i, baie, rbnd;
1196 for (ch = 0; ch < s->fbw_channels; ch++)
1197 put_bits(&s->pb, 1, 0); /* no block switching */
1198 for (ch = 0; ch < s->fbw_channels; ch++)
1199 put_bits(&s->pb, 1, 1); /* no dither */
1200 put_bits(&s->pb, 1, 0); /* no dynamic range */
1202 put_bits(&s->pb, 1, 1); /* coupling strategy present */
1203 put_bits(&s->pb, 1, 0); /* no coupling strategy */
1205 put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1208 if (s->channel_mode == AC3_CHMODE_STEREO) {
1210 /* first block must define rematrixing (rematstr) */
1211 put_bits(&s->pb, 1, 1);
1213 /* dummy rematrixing rematflg(1:4)=0 */
1214 for (rbnd = 0; rbnd < 4; rbnd++)
1215 put_bits(&s->pb, 1, 0);
1217 /* no matrixing (but should be used in the future) */
1218 put_bits(&s->pb, 1, 0);
1222 /* exponent strategy */
1223 for (ch = 0; ch < s->fbw_channels; ch++)
1224 put_bits(&s->pb, 2, exp_strategy[ch]);
1227 put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
1230 for (ch = 0; ch < s->fbw_channels; ch++) {
1231 if (exp_strategy[ch] != EXP_REUSE)
1232 put_bits(&s->pb, 6, s->bandwidth_code[ch]);
1236 for (ch = 0; ch < s->channels; ch++) {
1237 if (exp_strategy[ch] == EXP_REUSE)
1240 /* first exponent */
1241 put_bits(&s->pb, 4, grouped_exp[ch][0]);
1243 /* next ones are delta-encoded and grouped */
1244 for (i = 1; i <= num_exp_groups[ch]; i++)
1245 put_bits(&s->pb, 7, grouped_exp[ch][i]);
1247 if (ch != s->lfe_channel)
1248 put_bits(&s->pb, 2, 0); /* no gain range info */
1251 /* bit allocation info */
1252 baie = (block_num == 0);
1253 put_bits(&s->pb, 1, baie);
1255 put_bits(&s->pb, 2, s->slow_decay_code);
1256 put_bits(&s->pb, 2, s->fast_decay_code);
1257 put_bits(&s->pb, 2, s->slow_gain_code);
1258 put_bits(&s->pb, 2, s->db_per_bit_code);
1259 put_bits(&s->pb, 3, s->floor_code);
1263 put_bits(&s->pb, 1, baie);
1265 put_bits(&s->pb, 6, s->coarse_snr_offset);
1266 for (ch = 0; ch < s->channels; ch++) {
1267 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1268 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1272 put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1273 put_bits(&s->pb, 1, 0); /* no data to skip */
1275 /* mantissa encoding */
1276 for (ch = 0; ch < s->channels; ch++) {
1279 for (i = 0; i < s->nb_coefs[ch]; i++) {
1284 case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
1285 case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
1286 case 3: put_bits(&s->pb, 3, q); break;
1287 case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
1288 case 14: put_bits(&s->pb, 14, q); break;
1289 case 15: put_bits(&s->pb, 16, q); break;
1290 default: put_bits(&s->pb, b-1, q); break;
1297 /** CRC-16 Polynomial */
1298 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1301 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1318 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1324 r = mul_poly(r, a, poly);
1325 a = mul_poly(a, a, poly);
1333 * Fill the end of the frame with 0's and compute the two CRCs.
1335 static void output_frame_end(AC3EncodeContext *s)
1337 int frame_size, frame_size_58, pad_bytes, crc1, crc2, crc_inv;
1340 frame_size = s->frame_size; /* frame size in words */
1341 /* align to 8 bits */
1342 flush_put_bits(&s->pb);
1343 /* add zero bytes to reach the frame size */
1345 pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1346 assert(pad_bytes >= 0);
1348 memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1350 /* Now we must compute both crcs : this is not so easy for crc1
1351 because it is at the beginning of the data... */
1352 frame_size_58 = ((frame_size >> 2) + (frame_size >> 4)) << 1;
1354 crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1355 frame + 4, frame_size_58 - 4));
1357 /* XXX: could precompute crc_inv */
1358 crc_inv = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
1359 crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
1360 AV_WB16(frame + 2, crc1);
1362 crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1363 frame + frame_size_58,
1364 frame_size - frame_size_58 - 2));
1365 AV_WB16(frame + frame_size - 2, crc2);
1370 * Write the frame to the output bitstream.
1372 static void output_frame(AC3EncodeContext *s,
1373 unsigned char *frame,
1374 uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
1375 uint8_t num_exp_groups[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
1376 uint8_t grouped_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_EXP_GROUPS],
1377 uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
1378 uint16_t qmant[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS])
1382 init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1384 output_frame_header(s);
1386 for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1387 output_audio_block(s, exp_strategy[blk], num_exp_groups[blk],
1388 grouped_exp[blk], bap[blk], qmant[blk], blk);
1391 output_frame_end(s);
1396 * Encode a single AC-3 frame.
1398 static int ac3_encode_frame(AVCodecContext *avctx,
1399 unsigned char *frame, int buf_size, void *data)
1401 AC3EncodeContext *s = avctx->priv_data;
1402 const int16_t *samples = data;
1403 int16_t planar_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE+AC3_FRAME_SIZE];
1404 int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1405 uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1406 uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
1407 uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1408 uint8_t num_exp_groups[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
1409 uint8_t grouped_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_EXP_GROUPS];
1410 uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1411 int8_t exp_shift[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
1412 uint16_t qmant[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
1415 if (s->bit_alloc.sr_code == 1)
1416 adjust_frame_size(s);
1418 deinterleave_input_samples(s, samples, planar_samples);
1420 apply_mdct(s, planar_samples, exp_shift, mdct_coef);
1422 frame_bits = process_exponents(s, mdct_coef, exp_shift, exp, exp_strategy,
1423 encoded_exp, num_exp_groups, grouped_exp);
1425 compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
1427 quantize_mantissas(s, mdct_coef, exp_shift, encoded_exp, bap, qmant);
1429 output_frame(s, frame, exp_strategy, num_exp_groups, grouped_exp, bap, qmant);
1431 return s->frame_size;
1436 * Finalize encoding and free any memory allocated by the encoder.
1438 static av_cold int ac3_encode_close(AVCodecContext *avctx)
1440 av_freep(&avctx->coded_frame);
1446 * Set channel information during initialization.
1448 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1449 int64_t *channel_layout)
1453 if (channels < 1 || channels > AC3_MAX_CHANNELS)
1454 return AVERROR(EINVAL);
1455 if ((uint64_t)*channel_layout > 0x7FF)
1456 return AVERROR(EINVAL);
1457 ch_layout = *channel_layout;
1459 ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1460 if (av_get_channel_layout_nb_channels(ch_layout) != channels)
1461 return AVERROR(EINVAL);
1463 s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1464 s->channels = channels;
1465 s->fbw_channels = channels - s->lfe_on;
1466 s->lfe_channel = s->lfe_on ? s->fbw_channels : -1;
1468 ch_layout -= AV_CH_LOW_FREQUENCY;
1470 switch (ch_layout) {
1471 case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
1472 case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
1473 case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
1474 case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
1475 case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
1476 case AV_CH_LAYOUT_QUAD:
1477 case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
1478 case AV_CH_LAYOUT_5POINT0:
1479 case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
1481 return AVERROR(EINVAL);
1484 s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1485 *channel_layout = ch_layout;
1487 *channel_layout |= AV_CH_LOW_FREQUENCY;
1493 static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1497 /* validate channel layout */
1498 if (!avctx->channel_layout) {
1499 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1500 "encoder will guess the layout, but it "
1501 "might be incorrect.\n");
1503 ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1505 av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1509 /* validate sample rate */
1510 for (i = 0; i < 9; i++) {
1511 if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
1515 av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1516 return AVERROR(EINVAL);
1518 s->sample_rate = avctx->sample_rate;
1519 s->bit_alloc.sr_shift = i % 3;
1520 s->bit_alloc.sr_code = i / 3;
1522 /* validate bit rate */
1523 for (i = 0; i < 19; i++) {
1524 if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
1528 av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
1529 return AVERROR(EINVAL);
1531 s->bit_rate = avctx->bit_rate;
1532 s->frame_size_code = i << 1;
1539 * Set bandwidth for all channels.
1540 * The user can optionally supply a cutoff frequency. Otherwise an appropriate
1541 * default value will be used.
1543 static av_cold void set_bandwidth(AC3EncodeContext *s, int cutoff)
1548 /* calculate bandwidth based on user-specified cutoff frequency */
1550 cutoff = av_clip(cutoff, 1, s->sample_rate >> 1);
1551 fbw_coeffs = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
1552 bw_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
1554 /* use default bandwidth setting */
1555 /* XXX: should compute the bandwidth according to the frame
1556 size, so that we avoid annoying high frequency artifacts */
1560 /* set number of coefficients for each channel */
1561 for (ch = 0; ch < s->fbw_channels; ch++) {
1562 s->bandwidth_code[ch] = bw_code;
1563 s->nb_coefs[ch] = bw_code * 3 + 73;
1566 s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
1571 * Initialize the encoder.
1573 static av_cold int ac3_encode_init(AVCodecContext *avctx)
1575 AC3EncodeContext *s = avctx->priv_data;
1578 avctx->frame_size = AC3_FRAME_SIZE;
1582 ret = validate_options(avctx, s);
1586 s->bitstream_id = 8 + s->bit_alloc.sr_shift;
1587 s->bitstream_mode = 0; /* complete main audio service */
1589 s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
1590 s->bits_written = 0;
1591 s->samples_written = 0;
1592 s->frame_size = s->frame_size_min;
1594 set_bandwidth(s, avctx->cutoff);
1596 /* initial snr offset */
1597 s->coarse_snr_offset = 40;
1601 avctx->coded_frame= avcodec_alloc_frame();
1602 avctx->coded_frame->key_frame= 1;
1609 /*************************************************************************/
1612 #include "libavutil/lfg.h"
1614 #define FN (MDCT_SAMPLES/4)
1617 static void fft_test(AVLFG *lfg)
1619 IComplex in[FN], in1[FN];
1621 float sum_re, sum_im, a;
1623 for (i = 0; i < FN; i++) {
1624 in[i].re = av_lfg_get(lfg) % 65535 - 32767;
1625 in[i].im = av_lfg_get(lfg) % 65535 - 32767;
1631 for (k = 0; k < FN; k++) {
1634 for (n = 0; n < FN; n++) {
1635 a = -2 * M_PI * (n * k) / FN;
1636 sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1637 sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1639 av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
1640 k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1645 static void mdct_test(AVLFG *lfg)
1647 int16_t input[MDCT_SAMPLES];
1648 int32_t output[AC3_MAX_COEFS];
1649 float input1[MDCT_SAMPLES];
1650 float output1[AC3_MAX_COEFS];
1651 float s, a, err, e, emax;
1654 for (i = 0; i < MDCT_SAMPLES; i++) {
1655 input[i] = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
1656 input1[i] = input[i];
1659 mdct512(output, input);
1662 for (k = 0; k < AC3_MAX_COEFS; k++) {
1664 for (n = 0; n < MDCT_SAMPLES; n++) {
1665 a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
1666 s += input1[n] * cos(a);
1668 output1[k] = -2 * s / MDCT_SAMPLES;
1673 for (i = 0; i < AC3_MAX_COEFS; i++) {
1674 av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
1675 e = output[i] - output1[i];
1680 av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
1688 av_log_set_level(AV_LOG_DEBUG);
1699 AVCodec ac3_encoder = {
1703 sizeof(AC3EncodeContext),
1708 .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1709 .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1710 .channel_layouts = (const int64_t[]){
1712 AV_CH_LAYOUT_STEREO,
1714 AV_CH_LAYOUT_SURROUND,
1717 AV_CH_LAYOUT_4POINT0,
1718 AV_CH_LAYOUT_5POINT0,
1719 AV_CH_LAYOUT_5POINT0_BACK,
1720 (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
1721 (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
1722 (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
1723 (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1724 (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
1725 (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
1726 (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
1727 AV_CH_LAYOUT_5POINT1,
1728 AV_CH_LAYOUT_5POINT1_BACK,