]> git.sesse.net Git - ffmpeg/blob - libavcodec/ac3enc.c
107fe937f978a63f64ae8b5513dc92ab151d6375
[ffmpeg] / libavcodec / ac3enc.c
1 /*
2  * The simplest AC-3 encoder
3  * Copyright (c) 2000 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
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.
11  *
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.
16  *
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
20  */
21
22 /**
23  * @file
24  * The simplest AC-3 encoder.
25  */
26
27 //#define DEBUG
28
29 #include "libavcore/audioconvert.h"
30 #include "libavutil/crc.h"
31 #include "avcodec.h"
32 #include "put_bits.h"
33 #include "ac3.h"
34 #include "audioconvert.h"
35
36
37 #define MDCT_NBITS 9
38 #define MDCT_SAMPLES (1 << MDCT_NBITS)
39
40 /** Maximum number of exponent groups. +1 for separate DC exponent. */
41 #define AC3_MAX_EXP_GROUPS 85
42
43 /** Scale a float value by 2^bits and convert to an integer. */
44 #define SCALE_FLOAT(a, bits) lrintf((a) * (float)(1 << (bits)))
45
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))
48
49
50 /**
51  * Compex number.
52  * Used in fixed-point MDCT calculation.
53  */
54 typedef struct IComplex {
55     int16_t re,im;
56 } IComplex;
57
58 /**
59  * Data for a single audio block.
60  */
61 typedef struct AC3Block {
62     int32_t  mdct_coef[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
63     uint8_t  exp[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
64     uint8_t  exp_strategy[AC3_MAX_CHANNELS];
65     uint8_t  encoded_exp[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
66     uint8_t  num_exp_groups[AC3_MAX_CHANNELS];
67     uint8_t  grouped_exp[AC3_MAX_CHANNELS][AC3_MAX_EXP_GROUPS];
68     int16_t  psd[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
69     int16_t  band_psd[AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];
70     int16_t  mask[AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];
71     int8_t   exp_shift[AC3_MAX_CHANNELS];
72     uint16_t qmant[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
73 } AC3Block;
74
75 /**
76  * AC-3 encoder private context.
77  */
78 typedef struct AC3EncodeContext {
79     PutBitContext pb;                       ///< bitstream writer context
80
81     AC3Block blocks[AC3_MAX_BLOCKS];        ///< per-block info
82
83     int bitstream_id;                       ///< bitstream id                           (bsid)
84     int bitstream_mode;                     ///< bitstream mode                         (bsmod)
85
86     int bit_rate;                           ///< target bit rate, in bits-per-second
87     int sample_rate;                        ///< sampling frequency, in Hz
88
89     int frame_size_min;                     ///< minimum frame size in case rounding is necessary
90     int frame_size;                         ///< current frame size in bytes
91     int frame_size_code;                    ///< frame size code                        (frmsizecod)
92     int bits_written;                       ///< bit count    (used to avg. bitrate)
93     int samples_written;                    ///< sample count (used to avg. bitrate)
94
95     int fbw_channels;                       ///< number of full-bandwidth channels      (nfchans)
96     int channels;                           ///< total number of channels               (nchans)
97     int lfe_on;                             ///< indicates if there is an LFE channel   (lfeon)
98     int lfe_channel;                        ///< channel index of the LFE channel
99     int channel_mode;                       ///< channel mode                           (acmod)
100     const uint8_t *channel_map;             ///< channel map used to reorder channels
101
102     int bandwidth_code[AC3_MAX_CHANNELS];   ///< bandwidth code (0 to 60)               (chbwcod)
103     int nb_coefs[AC3_MAX_CHANNELS];
104
105     /* bitrate allocation control */
106     int slow_gain_code;                     ///< slow gain code                         (sgaincod)
107     int slow_decay_code;                    ///< slow decay code                        (sdcycod)
108     int fast_decay_code;                    ///< fast decay code                        (fdcycod)
109     int db_per_bit_code;                    ///< dB/bit code                            (dbpbcod)
110     int floor_code;                         ///< floor code                             (floorcod)
111     AC3BitAllocParameters bit_alloc;        ///< bit allocation parameters
112     int coarse_snr_offset;                  ///< coarse SNR offsets                     (csnroffst)
113     int fast_gain_code[AC3_MAX_CHANNELS];   ///< fast gain codes (signal-to-mask ratio) (fgaincod)
114     int fine_snr_offset[AC3_MAX_CHANNELS];  ///< fine SNR offsets                       (fsnroffst)
115     int frame_bits;                         ///< all frame bits except exponents and mantissas
116     int exponent_bits;                      ///< number of bits used for exponents
117
118     /* mantissa encoding */
119     int mant1_cnt, mant2_cnt, mant4_cnt;    ///< mantissa counts for bap=1,2,4
120     uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
121
122     int16_t last_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE]; ///< last 256 samples from previous frame
123     int16_t planar_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE+AC3_FRAME_SIZE];
124     int16_t windowed_samples[AC3_WINDOW_SIZE];
125     uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
126     uint8_t bap1[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
127 } AC3EncodeContext;
128
129
130 /** MDCT and FFT tables */
131 static int16_t costab[64];
132 static int16_t sintab[64];
133 static int16_t xcos1[128];
134 static int16_t xsin1[128];
135
136
137 /**
138  * Adjust the frame size to make the average bit rate match the target bit rate.
139  * This is only needed for 11025, 22050, and 44100 sample rates.
140  */
141 static void adjust_frame_size(AC3EncodeContext *s)
142 {
143     while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
144         s->bits_written    -= s->bit_rate;
145         s->samples_written -= s->sample_rate;
146     }
147     s->frame_size = s->frame_size_min +
148                     2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
149     s->bits_written    += s->frame_size * 8;
150     s->samples_written += AC3_FRAME_SIZE;
151 }
152
153
154 /**
155  * Deinterleave input samples.
156  * Channels are reordered from FFmpeg's default order to AC-3 order.
157  */
158 static void deinterleave_input_samples(AC3EncodeContext *s,
159                                        const int16_t *samples)
160 {
161     int ch, i;
162
163     /* deinterleave and remap input samples */
164     for (ch = 0; ch < s->channels; ch++) {
165         const int16_t *sptr;
166         int sinc;
167
168         /* copy last 256 samples of previous frame to the start of the current frame */
169         memcpy(&s->planar_samples[ch][0], s->last_samples[ch],
170                AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
171
172         /* deinterleave */
173         sinc = s->channels;
174         sptr = samples + s->channel_map[ch];
175         for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
176             s->planar_samples[ch][i] = *sptr;
177             sptr += sinc;
178         }
179
180         /* save last 256 samples for next frame */
181         memcpy(s->last_samples[ch], &s->planar_samples[ch][6* AC3_BLOCK_SIZE],
182                AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
183     }
184 }
185
186
187 /**
188  * Initialize FFT tables.
189  * @param ln log2(FFT size)
190  */
191 static av_cold void fft_init(int ln)
192 {
193     int i, n, n2;
194     float alpha;
195
196     n  = 1 << ln;
197     n2 = n >> 1;
198
199     for (i = 0; i < n2; i++) {
200         alpha     = 2.0 * M_PI * i / n;
201         costab[i] = FIX15(cos(alpha));
202         sintab[i] = FIX15(sin(alpha));
203     }
204 }
205
206
207 /**
208  * Initialize MDCT tables.
209  * @param nbits log2(MDCT size)
210  */
211 static av_cold void mdct_init(int nbits)
212 {
213     int i, n, n4;
214
215     n  = 1 << nbits;
216     n4 = n >> 2;
217
218     fft_init(nbits - 2);
219
220     for (i = 0; i < n4; i++) {
221         float alpha = 2.0 * M_PI * (i + 1.0 / 8.0) / n;
222         xcos1[i] = FIX15(-cos(alpha));
223         xsin1[i] = FIX15(-sin(alpha));
224     }
225 }
226
227
228 /** Butterfly op */
229 #define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1)  \
230 {                                                       \
231   int ax, ay, bx, by;                                   \
232   bx  = pre1;                                           \
233   by  = pim1;                                           \
234   ax  = qre1;                                           \
235   ay  = qim1;                                           \
236   pre = (bx + ax) >> 1;                                 \
237   pim = (by + ay) >> 1;                                 \
238   qre = (bx - ax) >> 1;                                 \
239   qim = (by - ay) >> 1;                                 \
240 }
241
242
243 /** Complex multiply */
244 #define CMUL(pre, pim, are, aim, bre, bim)              \
245 {                                                       \
246    pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;     \
247    pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;     \
248 }
249
250
251 /**
252  * Calculate a 2^n point complex FFT on 2^ln points.
253  * @param z  complex input/output samples
254  * @param ln log2(FFT size)
255  */
256 static void fft(IComplex *z, int ln)
257 {
258     int j, l, np, np2;
259     int nblocks, nloops;
260     register IComplex *p,*q;
261     int tmp_re, tmp_im;
262
263     np = 1 << ln;
264
265     /* reverse */
266     for (j = 0; j < np; j++) {
267         int k = av_reverse[j] >> (8 - ln);
268         if (k < j)
269             FFSWAP(IComplex, z[k], z[j]);
270     }
271
272     /* pass 0 */
273
274     p = &z[0];
275     j = np >> 1;
276     do {
277         BF(p[0].re, p[0].im, p[1].re, p[1].im,
278            p[0].re, p[0].im, p[1].re, p[1].im);
279         p += 2;
280     } while (--j);
281
282     /* pass 1 */
283
284     p = &z[0];
285     j = np >> 2;
286     do {
287         BF(p[0].re, p[0].im, p[2].re,  p[2].im,
288            p[0].re, p[0].im, p[2].re,  p[2].im);
289         BF(p[1].re, p[1].im, p[3].re,  p[3].im,
290            p[1].re, p[1].im, p[3].im, -p[3].re);
291         p+=4;
292     } while (--j);
293
294     /* pass 2 .. ln-1 */
295
296     nblocks = np >> 3;
297     nloops  =  1 << 2;
298     np2     = np >> 1;
299     do {
300         p = z;
301         q = z + nloops;
302         for (j = 0; j < nblocks; j++) {
303             BF(p->re, p->im, q->re, q->im,
304                p->re, p->im, q->re, q->im);
305             p++;
306             q++;
307             for(l = nblocks; l < np2; l += nblocks) {
308                 CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
309                 BF(p->re, p->im, q->re,  q->im,
310                    p->re, p->im, tmp_re, tmp_im);
311                 p++;
312                 q++;
313             }
314             p += nloops;
315             q += nloops;
316         }
317         nblocks = nblocks >> 1;
318         nloops  = nloops  << 1;
319     } while (nblocks);
320 }
321
322
323 /**
324  * Calculate a 512-point MDCT
325  * @param out 256 output frequency coefficients
326  * @param in  512 windowed input audio samples
327  */
328 static void mdct512(int32_t *out, int16_t *in)
329 {
330     int i, re, im, re1, im1;
331     int16_t rot[MDCT_SAMPLES];
332     IComplex x[MDCT_SAMPLES/4];
333
334     /* shift to simplify computations */
335     for (i = 0; i < MDCT_SAMPLES/4; i++)
336         rot[i] = -in[i + 3*MDCT_SAMPLES/4];
337     for (;i < MDCT_SAMPLES; i++)
338         rot[i] =  in[i -   MDCT_SAMPLES/4];
339
340     /* pre rotation */
341     for (i = 0; i < MDCT_SAMPLES/4; i++) {
342         re =  ((int)rot[               2*i] - (int)rot[MDCT_SAMPLES  -1-2*i]) >> 1;
343         im = -((int)rot[MDCT_SAMPLES/2+2*i] - (int)rot[MDCT_SAMPLES/2-1-2*i]) >> 1;
344         CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
345     }
346
347     fft(x, MDCT_NBITS - 2);
348
349     /* post rotation */
350     for (i = 0; i < MDCT_SAMPLES/4; i++) {
351         re = x[i].re;
352         im = x[i].im;
353         CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
354         out[                 2*i] = im1;
355         out[MDCT_SAMPLES/2-1-2*i] = re1;
356     }
357 }
358
359
360 /**
361  * Apply KBD window to input samples prior to MDCT.
362  */
363 static void apply_window(int16_t *output, const int16_t *input,
364                          const int16_t *window, int n)
365 {
366     int i;
367     int n2 = n >> 1;
368
369     for (i = 0; i < n2; i++) {
370         output[i]     = MUL16(input[i],     window[i]) >> 15;
371         output[n-i-1] = MUL16(input[n-i-1], window[i]) >> 15;
372     }
373 }
374
375
376 /**
377  * Calculate the log2() of the maximum absolute value in an array.
378  * @param tab input array
379  * @param n   number of values in the array
380  * @return    log2(max(abs(tab[])))
381  */
382 static int log2_tab(int16_t *tab, int n)
383 {
384     int i, v;
385
386     v = 0;
387     for (i = 0; i < n; i++)
388         v |= abs(tab[i]);
389
390     return av_log2(v);
391 }
392
393
394 /**
395  * Left-shift each value in an array by a specified amount.
396  * @param tab    input array
397  * @param n      number of values in the array
398  * @param lshift left shift amount. a negative value means right shift.
399  */
400 static void lshift_tab(int16_t *tab, int n, int lshift)
401 {
402     int i;
403
404     if (lshift > 0) {
405         for (i = 0; i < n; i++)
406             tab[i] <<= lshift;
407     } else if (lshift < 0) {
408         lshift = -lshift;
409         for (i = 0; i < n; i++)
410             tab[i] >>= lshift;
411     }
412 }
413
414
415 /**
416  * Normalize the input samples to use the maximum available precision.
417  * This assumes signed 16-bit input samples. Exponents are reduced by 9 to
418  * match the 24-bit internal precision for MDCT coefficients.
419  *
420  * @return exponent shift
421  */
422 static int normalize_samples(AC3EncodeContext *s)
423 {
424     int v = 14 - log2_tab(s->windowed_samples, AC3_WINDOW_SIZE);
425     v = FFMAX(0, v);
426     lshift_tab(s->windowed_samples, AC3_WINDOW_SIZE, v);
427     return v - 9;
428 }
429
430
431 /**
432  * Apply the MDCT to input samples to generate frequency coefficients.
433  * This applies the KBD window and normalizes the input to reduce precision
434  * loss due to fixed-point calculations.
435  */
436 static void apply_mdct(AC3EncodeContext *s)
437 {
438     int blk, ch;
439
440     for (ch = 0; ch < s->channels; ch++) {
441         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
442             AC3Block *block = &s->blocks[blk];
443             const int16_t *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
444
445             apply_window(s->windowed_samples, input_samples, ff_ac3_window, AC3_WINDOW_SIZE);
446
447             block->exp_shift[ch] = normalize_samples(s);
448
449             mdct512(block->mdct_coef[ch], s->windowed_samples);
450         }
451     }
452 }
453
454
455 /**
456  * Extract exponents from the MDCT coefficients.
457  * This takes into account the normalization that was done to the input samples
458  * by adjusting the exponents by the exponent shift values.
459  */
460 static void extract_exponents(AC3EncodeContext *s)
461 {
462     int blk, ch, i;
463
464     for (ch = 0; ch < s->channels; ch++) {
465         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
466             AC3Block *block = &s->blocks[blk];
467             for (i = 0; i < AC3_MAX_COEFS; i++) {
468                 int e;
469                 int v = abs(block->mdct_coef[ch][i]);
470                 if (v == 0)
471                     e = 24;
472                 else {
473                     e = 23 - av_log2(v) + block->exp_shift[ch];
474                     if (e >= 24) {
475                         e = 24;
476                         block->mdct_coef[ch][i] = 0;
477                     }
478                 }
479                 block->exp[ch][i] = e;
480             }
481         }
482     }
483 }
484
485
486 /**
487  * Calculate the sum of absolute differences (SAD) between 2 sets of exponents.
488  */
489 static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
490 {
491     int sum, i;
492     sum = 0;
493     for (i = 0; i < n; i++)
494         sum += abs(exp1[i] - exp2[i]);
495     return sum;
496 }
497
498
499 /**
500  * Exponent Difference Threshold.
501  * New exponents are sent if their SAD exceed this number.
502  */
503 #define EXP_DIFF_THRESHOLD 1000
504
505
506 /**
507  * Calculate exponent strategies for all blocks in a single channel.
508  */
509 static void compute_exp_strategy_ch(uint8_t *exp_strategy, uint8_t **exp)
510 {
511     int blk, blk1;
512     int exp_diff;
513
514     /* estimate if the exponent variation & decide if they should be
515        reused in the next frame */
516     exp_strategy[0] = EXP_NEW;
517     for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
518         exp_diff = calc_exp_diff(exp[blk], exp[blk-1], AC3_MAX_COEFS);
519         if (exp_diff > EXP_DIFF_THRESHOLD)
520             exp_strategy[blk] = EXP_NEW;
521         else
522             exp_strategy[blk] = EXP_REUSE;
523     }
524
525     /* now select the encoding strategy type : if exponents are often
526        recoded, we use a coarse encoding */
527     blk = 0;
528     while (blk < AC3_MAX_BLOCKS) {
529         blk1 = blk + 1;
530         while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
531             blk1++;
532         switch (blk1 - blk) {
533         case 1:  exp_strategy[blk] = EXP_D45; break;
534         case 2:
535         case 3:  exp_strategy[blk] = EXP_D25; break;
536         default: exp_strategy[blk] = EXP_D15; break;
537         }
538         blk = blk1;
539     }
540 }
541
542
543 /**
544  * Calculate exponent strategies for all channels.
545  * Array arrangement is reversed to simplify the per-channel calculation.
546  */
547 static void compute_exp_strategy(AC3EncodeContext *s)
548 {
549     uint8_t *exp1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
550     uint8_t exp_str1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
551     int ch, blk;
552
553     for (ch = 0; ch < s->fbw_channels; ch++) {
554         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
555             exp1[ch][blk]     = s->blocks[blk].exp[ch];
556             exp_str1[ch][blk] = s->blocks[blk].exp_strategy[ch];
557         }
558
559         compute_exp_strategy_ch(exp_str1[ch], exp1[ch]);
560
561         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
562             s->blocks[blk].exp_strategy[ch] = exp_str1[ch][blk];
563     }
564     if (s->lfe_on) {
565         ch = s->lfe_channel;
566         s->blocks[0].exp_strategy[ch] = EXP_D15;
567         for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
568             s->blocks[blk].exp_strategy[ch] = EXP_REUSE;
569     }
570 }
571
572
573 /**
574  * Set each encoded exponent in a block to the minimum of itself and the
575  * exponent in the same frequency bin of a following block.
576  * exp[i] = min(exp[i], exp1[i]
577  */
578 static void exponent_min(uint8_t *exp, uint8_t *exp1, int n)
579 {
580     int i;
581     for (i = 0; i < n; i++) {
582         if (exp1[i] < exp[i])
583             exp[i] = exp1[i];
584     }
585 }
586
587
588 /**
589  * Update the exponents so that they are the ones the decoder will decode.
590  */
591 static void encode_exponents_blk_ch(uint8_t *encoded_exp, uint8_t *exp,
592                                     int nb_exps, int exp_strategy,
593                                     uint8_t *num_exp_groups)
594 {
595     int group_size, nb_groups, i, j, k, exp_min;
596     uint8_t exp1[AC3_MAX_COEFS];
597
598     group_size = exp_strategy + (exp_strategy == EXP_D45);
599     *num_exp_groups = (nb_exps + (group_size * 3) - 4) / (3 * group_size);
600     nb_groups = *num_exp_groups * 3;
601
602     /* for each group, compute the minimum exponent */
603     exp1[0] = exp[0]; /* DC exponent is handled separately */
604     k = 1;
605     for (i = 1; i <= nb_groups; i++) {
606         exp_min = exp[k];
607         assert(exp_min >= 0 && exp_min <= 24);
608         for (j = 1; j < group_size; j++) {
609             if (exp[k+j] < exp_min)
610                 exp_min = exp[k+j];
611         }
612         exp1[i] = exp_min;
613         k += group_size;
614     }
615
616     /* constraint for DC exponent */
617     if (exp1[0] > 15)
618         exp1[0] = 15;
619
620     /* decrease the delta between each groups to within 2 so that they can be
621        differentially encoded */
622     for (i = 1; i <= nb_groups; i++)
623         exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
624     for (i = nb_groups-1; i >= 0; i--)
625         exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
626
627     /* now we have the exponent values the decoder will see */
628     encoded_exp[0] = exp1[0];
629     k = 1;
630     for (i = 1; i <= nb_groups; i++) {
631         for (j = 0; j < group_size; j++)
632             encoded_exp[k+j] = exp1[i];
633         k += group_size;
634     }
635 }
636
637
638 /**
639  * Encode exponents from original extracted form to what the decoder will see.
640  * This copies and groups exponents based on exponent strategy and reduces
641  * deltas between adjacent exponent groups so that they can be differentially
642  * encoded.
643  */
644 static void encode_exponents(AC3EncodeContext *s)
645 {
646     int blk, blk1, blk2, ch;
647     AC3Block *block, *block1, *block2;
648
649     for (ch = 0; ch < s->channels; ch++) {
650         blk = 0;
651         block = &s->blocks[0];
652         while (blk < AC3_MAX_BLOCKS) {
653             blk1 = blk + 1;
654             block1 = block + 1;
655             /* for the EXP_REUSE case we select the min of the exponents */
656             while (blk1 < AC3_MAX_BLOCKS && block1->exp_strategy[ch] == EXP_REUSE) {
657                 exponent_min(block->exp[ch], block1->exp[ch], s->nb_coefs[ch]);
658                 blk1++;
659                 block1++;
660             }
661             encode_exponents_blk_ch(block->encoded_exp[ch],
662                                     block->exp[ch], s->nb_coefs[ch],
663                                     block->exp_strategy[ch],
664                                     &block->num_exp_groups[ch]);
665             /* copy encoded exponents for reuse case */
666             block2 = block + 1;
667             for (blk2 = blk+1; blk2 < blk1; blk2++, block2++) {
668                 memcpy(block2->encoded_exp[ch], block->encoded_exp[ch],
669                        s->nb_coefs[ch] * sizeof(uint8_t));
670             }
671             blk = blk1;
672             block = block1;
673         }
674     }
675 }
676
677
678 /**
679  * Group exponents.
680  * 3 delta-encoded exponents are in each 7-bit group. The number of groups
681  * varies depending on exponent strategy and bandwidth.
682  */
683 static void group_exponents(AC3EncodeContext *s)
684 {
685     int blk, ch, i;
686     int group_size, bit_count;
687     uint8_t *p;
688     int delta0, delta1, delta2;
689     int exp0, exp1;
690
691     bit_count = 0;
692     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
693         AC3Block *block = &s->blocks[blk];
694         for (ch = 0; ch < s->channels; ch++) {
695             if (block->exp_strategy[ch] == EXP_REUSE) {
696                 block->num_exp_groups[ch] = 0;
697                 continue;
698             }
699             group_size = block->exp_strategy[ch] + (block->exp_strategy[ch] == EXP_D45);
700             bit_count += 4 + (block->num_exp_groups[ch] * 7);
701             p = block->encoded_exp[ch];
702
703             /* DC exponent */
704             exp1 = *p++;
705             block->grouped_exp[ch][0] = exp1;
706
707             /* remaining exponents are delta encoded */
708             for (i = 1; i <= block->num_exp_groups[ch]; i++) {
709                 /* merge three delta in one code */
710                 exp0   = exp1;
711                 exp1   = p[0];
712                 p     += group_size;
713                 delta0 = exp1 - exp0 + 2;
714
715                 exp0   = exp1;
716                 exp1   = p[0];
717                 p     += group_size;
718                 delta1 = exp1 - exp0 + 2;
719
720                 exp0   = exp1;
721                 exp1   = p[0];
722                 p     += group_size;
723                 delta2 = exp1 - exp0 + 2;
724
725                 block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
726             }
727         }
728     }
729
730     s->exponent_bits = bit_count;
731 }
732
733
734 /**
735  * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
736  * Extract exponents from MDCT coefficients, calculate exponent strategies,
737  * and encode final exponents.
738  */
739 static void process_exponents(AC3EncodeContext *s)
740 {
741     extract_exponents(s);
742
743     compute_exp_strategy(s);
744
745     encode_exponents(s);
746
747     group_exponents(s);
748 }
749
750
751 /**
752  * Initialize bit allocation.
753  * Set default parameter codes and calculate parameter values.
754  */
755 static void bit_alloc_init(AC3EncodeContext *s)
756 {
757     int ch;
758
759     /* init default parameters */
760     s->slow_decay_code = 2;
761     s->fast_decay_code = 1;
762     s->slow_gain_code  = 1;
763     s->db_per_bit_code = 2;
764     s->floor_code      = 4;
765     for (ch = 0; ch < s->channels; ch++)
766         s->fast_gain_code[ch] = 4;
767
768     /* initial snr offset */
769     s->coarse_snr_offset = 40;
770
771     /* compute real values */
772     /* currently none of these values change during encoding, so we can just
773        set them once at initialization */
774     s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
775     s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
776     s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
777     s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
778     s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
779 }
780
781
782 /**
783  * Count the bits used to encode the frame, minus exponents and mantissas.
784  */
785 static void count_frame_bits(AC3EncodeContext *s)
786 {
787     static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
788     int blk, ch;
789     int frame_bits;
790
791     /* header size */
792     frame_bits = 65;
793     frame_bits += frame_bits_inc[s->channel_mode];
794
795     /* audio blocks */
796     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
797         frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
798         if (s->channel_mode == AC3_CHMODE_STEREO) {
799             frame_bits++; /* rematstr */
800             if (!blk)
801                 frame_bits += 4;
802         }
803         frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
804         if (s->lfe_on)
805             frame_bits++; /* lfeexpstr */
806         for (ch = 0; ch < s->fbw_channels; ch++) {
807             if (s->blocks[blk].exp_strategy[ch] != EXP_REUSE)
808                 frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
809         }
810         frame_bits++; /* baie */
811         frame_bits++; /* snr */
812         frame_bits += 2; /* delta / skip */
813     }
814     frame_bits++; /* cplinu for block 0 */
815     /* bit alloc info */
816     /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
817     /* csnroffset[6] */
818     /* (fsnoffset[4] + fgaincod[4]) * c */
819     frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
820
821     /* auxdatae, crcrsv */
822     frame_bits += 2;
823
824     /* CRC */
825     frame_bits += 16;
826
827     s->frame_bits = frame_bits;
828 }
829
830
831 /**
832  * Calculate the number of bits needed to encode a set of mantissas.
833  */
834 static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *bap, int nb_coefs)
835 {
836     int bits, b, i;
837
838     bits = 0;
839     for (i = 0; i < nb_coefs; i++) {
840         b = bap[i];
841         switch (b) {
842         case 0:
843             /* bap=0 mantissas are not encoded */
844             break;
845         case 1:
846             /* 3 mantissas in 5 bits */
847             if (s->mant1_cnt == 0)
848                 bits += 5;
849             if (++s->mant1_cnt == 3)
850                 s->mant1_cnt = 0;
851             break;
852         case 2:
853             /* 3 mantissas in 7 bits */
854             if (s->mant2_cnt == 0)
855                 bits += 7;
856             if (++s->mant2_cnt == 3)
857                 s->mant2_cnt = 0;
858             break;
859         case 3:
860             bits += 3;
861             break;
862         case 4:
863             /* 2 mantissas in 7 bits */
864             if (s->mant4_cnt == 0)
865                 bits += 7;
866             if (++s->mant4_cnt == 2)
867                 s->mant4_cnt = 0;
868             break;
869         case 14:
870             bits += 14;
871             break;
872         case 15:
873             bits += 16;
874             break;
875         default:
876             bits += b - 1;
877             break;
878         }
879     }
880     return bits;
881 }
882
883
884 /**
885  * Calculate masking curve based on the final exponents.
886  * Also calculate the power spectral densities to use in future calculations.
887  */
888 static void bit_alloc_masking(AC3EncodeContext *s)
889 {
890     int blk, ch;
891
892     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
893         AC3Block *block = &s->blocks[blk];
894         for (ch = 0; ch < s->channels; ch++) {
895             if (block->exp_strategy[ch] == EXP_REUSE) {
896                 AC3Block *block1 = &s->blocks[blk-1];
897                 memcpy(block->psd[ch],  block1->psd[ch],  AC3_MAX_COEFS*sizeof(block->psd[0][0]));
898                 memcpy(block->mask[ch], block1->mask[ch], AC3_CRITICAL_BANDS*sizeof(block->mask[0][0]));
899             } else {
900                 ff_ac3_bit_alloc_calc_psd(block->encoded_exp[ch], 0,
901                                           s->nb_coefs[ch],
902                                           block->psd[ch], block->band_psd[ch]);
903                 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
904                                            0, s->nb_coefs[ch],
905                                            ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
906                                            ch == s->lfe_channel,
907                                            DBA_NONE, 0, NULL, NULL, NULL,
908                                            block->mask[ch]);
909             }
910         }
911     }
912 }
913
914
915 /**
916  * Run the bit allocation with a given SNR offset.
917  * This calculates the bit allocation pointers that will be used to determine
918  * the quantization of each mantissa.
919  * @return the number of bits needed for mantissas if the given SNR offset is
920  *         is used.
921  */
922 static int bit_alloc(AC3EncodeContext *s,
923                      uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
924                      int snr_offset)
925 {
926     int blk, ch;
927     int mantissa_bits;
928
929     snr_offset = (snr_offset - 240) << 2;
930
931     mantissa_bits = 0;
932     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
933         AC3Block *block = &s->blocks[blk];
934         s->mant1_cnt = 0;
935         s->mant2_cnt = 0;
936         s->mant4_cnt = 0;
937         for (ch = 0; ch < s->channels; ch++) {
938             ff_ac3_bit_alloc_calc_bap(block->mask[ch], block->psd[ch], 0,
939                                       s->nb_coefs[ch], snr_offset,
940                                       s->bit_alloc.floor, ff_ac3_bap_tab,
941                                       bap[blk][ch]);
942             mantissa_bits += compute_mantissa_size(s, bap[blk][ch], s->nb_coefs[ch]);
943         }
944     }
945     return mantissa_bits;
946 }
947
948
949 /**
950  * Constant bitrate bit allocation search.
951  * Find the largest SNR offset that will allow data to fit in the frame.
952  */
953 static int cbr_bit_allocation(AC3EncodeContext *s)
954 {
955     int ch;
956     int bits_left;
957     int snr_offset;
958
959     bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
960
961     snr_offset = s->coarse_snr_offset << 4;
962
963     while (snr_offset >= 0 &&
964            bit_alloc(s, s->bap, snr_offset) > bits_left) {
965         snr_offset -= 64;
966     }
967     if (snr_offset < 0)
968         return AVERROR(EINVAL);
969
970     while (snr_offset + 64 <= 1023 &&
971            bit_alloc(s, s->bap1, snr_offset + 64) <= bits_left) {
972         snr_offset += 64;
973         memcpy(s->bap, s->bap1, sizeof(s->bap1));
974     }
975     while (snr_offset + 16 <= 1023 &&
976            bit_alloc(s, s->bap1, snr_offset + 16) <= bits_left) {
977         snr_offset += 16;
978         memcpy(s->bap, s->bap1, sizeof(s->bap1));
979     }
980     while (snr_offset + 4 <= 1023 &&
981            bit_alloc(s, s->bap1, snr_offset + 4) <= bits_left) {
982         snr_offset += 4;
983         memcpy(s->bap, s->bap1, sizeof(s->bap1));
984     }
985     while (snr_offset + 1 <= 1023 &&
986            bit_alloc(s, s->bap1, snr_offset + 1) <= bits_left) {
987         snr_offset++;
988         memcpy(s->bap, s->bap1, sizeof(s->bap1));
989     }
990
991     s->coarse_snr_offset = snr_offset >> 4;
992     for (ch = 0; ch < s->channels; ch++)
993         s->fine_snr_offset[ch] = snr_offset & 0xF;
994
995     return 0;
996 }
997
998
999 /**
1000  * Perform bit allocation search.
1001  * Finds the SNR offset value that maximizes quality and fits in the specified
1002  * frame size.  Output is the SNR offset and a set of bit allocation pointers
1003  * used to quantize the mantissas.
1004  */
1005 static int compute_bit_allocation(AC3EncodeContext *s)
1006 {
1007     count_frame_bits(s);
1008
1009     bit_alloc_masking(s);
1010
1011     return cbr_bit_allocation(s);
1012 }
1013
1014
1015 /**
1016  * Symmetric quantization on 'levels' levels.
1017  */
1018 static inline int sym_quant(int c, int e, int levels)
1019 {
1020     int v;
1021
1022     if (c >= 0) {
1023         v = (levels * (c << e)) >> 24;
1024         v = (v + 1) >> 1;
1025         v = (levels >> 1) + v;
1026     } else {
1027         v = (levels * ((-c) << e)) >> 24;
1028         v = (v + 1) >> 1;
1029         v = (levels >> 1) - v;
1030     }
1031     assert(v >= 0 && v < levels);
1032     return v;
1033 }
1034
1035
1036 /**
1037  * Asymmetric quantization on 2^qbits levels.
1038  */
1039 static inline int asym_quant(int c, int e, int qbits)
1040 {
1041     int lshift, m, v;
1042
1043     lshift = e + qbits - 24;
1044     if (lshift >= 0)
1045         v = c << lshift;
1046     else
1047         v = c >> (-lshift);
1048     /* rounding */
1049     v = (v + 1) >> 1;
1050     m = (1 << (qbits-1));
1051     if (v >= m)
1052         v = m - 1;
1053     assert(v >= -m);
1054     return v & ((1 << qbits)-1);
1055 }
1056
1057
1058 /**
1059  * Quantize a set of mantissas for a single channel in a single block.
1060  */
1061 static void quantize_mantissas_blk_ch(AC3EncodeContext *s,
1062                                       int32_t *mdct_coef, int8_t exp_shift,
1063                                       uint8_t *encoded_exp, uint8_t *bap,
1064                                       uint16_t *qmant, int n)
1065 {
1066     int i;
1067
1068     for (i = 0; i < n; i++) {
1069         int v;
1070         int c = mdct_coef[i];
1071         int e = encoded_exp[i] - exp_shift;
1072         int b = bap[i];
1073         switch (b) {
1074         case 0:
1075             v = 0;
1076             break;
1077         case 1:
1078             v = sym_quant(c, e, 3);
1079             switch (s->mant1_cnt) {
1080             case 0:
1081                 s->qmant1_ptr = &qmant[i];
1082                 v = 9 * v;
1083                 s->mant1_cnt = 1;
1084                 break;
1085             case 1:
1086                 *s->qmant1_ptr += 3 * v;
1087                 s->mant1_cnt = 2;
1088                 v = 128;
1089                 break;
1090             default:
1091                 *s->qmant1_ptr += v;
1092                 s->mant1_cnt = 0;
1093                 v = 128;
1094                 break;
1095             }
1096             break;
1097         case 2:
1098             v = sym_quant(c, e, 5);
1099             switch (s->mant2_cnt) {
1100             case 0:
1101                 s->qmant2_ptr = &qmant[i];
1102                 v = 25 * v;
1103                 s->mant2_cnt = 1;
1104                 break;
1105             case 1:
1106                 *s->qmant2_ptr += 5 * v;
1107                 s->mant2_cnt = 2;
1108                 v = 128;
1109                 break;
1110             default:
1111                 *s->qmant2_ptr += v;
1112                 s->mant2_cnt = 0;
1113                 v = 128;
1114                 break;
1115             }
1116             break;
1117         case 3:
1118             v = sym_quant(c, e, 7);
1119             break;
1120         case 4:
1121             v = sym_quant(c, e, 11);
1122             switch (s->mant4_cnt) {
1123             case 0:
1124                 s->qmant4_ptr = &qmant[i];
1125                 v = 11 * v;
1126                 s->mant4_cnt = 1;
1127                 break;
1128             default:
1129                 *s->qmant4_ptr += v;
1130                 s->mant4_cnt = 0;
1131                 v = 128;
1132                 break;
1133             }
1134             break;
1135         case 5:
1136             v = sym_quant(c, e, 15);
1137             break;
1138         case 14:
1139             v = asym_quant(c, e, 14);
1140             break;
1141         case 15:
1142             v = asym_quant(c, e, 16);
1143             break;
1144         default:
1145             v = asym_quant(c, e, b - 1);
1146             break;
1147         }
1148         qmant[i] = v;
1149     }
1150 }
1151
1152
1153 /**
1154  * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1155  */
1156 static void quantize_mantissas(AC3EncodeContext *s)
1157 {
1158     int blk, ch;
1159
1160
1161     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1162         AC3Block *block = &s->blocks[blk];
1163         s->mant1_cnt  = s->mant2_cnt  = s->mant4_cnt  = 0;
1164         s->qmant1_ptr = s->qmant2_ptr = s->qmant4_ptr = NULL;
1165
1166         for (ch = 0; ch < s->channels; ch++) {
1167             quantize_mantissas_blk_ch(s, block->mdct_coef[ch], block->exp_shift[ch],
1168                                       block->encoded_exp[ch], s->bap[blk][ch],
1169                                       block->qmant[ch], s->nb_coefs[ch]);
1170         }
1171     }
1172 }
1173
1174
1175 /**
1176  * Write the AC-3 frame header to the output bitstream.
1177  */
1178 static void output_frame_header(AC3EncodeContext *s)
1179 {
1180     put_bits(&s->pb, 16, 0x0b77);   /* frame header */
1181     put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
1182     put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
1183     put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1184     put_bits(&s->pb, 5,  s->bitstream_id);
1185     put_bits(&s->pb, 3,  s->bitstream_mode);
1186     put_bits(&s->pb, 3,  s->channel_mode);
1187     if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1188         put_bits(&s->pb, 2, 1);     /* XXX -4.5 dB */
1189     if (s->channel_mode & 0x04)
1190         put_bits(&s->pb, 2, 1);     /* XXX -6 dB */
1191     if (s->channel_mode == AC3_CHMODE_STEREO)
1192         put_bits(&s->pb, 2, 0);     /* surround not indicated */
1193     put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1194     put_bits(&s->pb, 5, 31);        /* dialog norm: -31 db */
1195     put_bits(&s->pb, 1, 0);         /* no compression control word */
1196     put_bits(&s->pb, 1, 0);         /* no lang code */
1197     put_bits(&s->pb, 1, 0);         /* no audio production info */
1198     put_bits(&s->pb, 1, 0);         /* no copyright */
1199     put_bits(&s->pb, 1, 1);         /* original bitstream */
1200     put_bits(&s->pb, 1, 0);         /* no time code 1 */
1201     put_bits(&s->pb, 1, 0);         /* no time code 2 */
1202     put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
1203 }
1204
1205
1206 /**
1207  * Write one audio block to the output bitstream.
1208  */
1209 static void output_audio_block(AC3EncodeContext *s,
1210                                int block_num)
1211 {
1212     int ch, i, baie, rbnd;
1213     AC3Block *block = &s->blocks[block_num];
1214
1215     /* block switching */
1216     for (ch = 0; ch < s->fbw_channels; ch++)
1217         put_bits(&s->pb, 1, 0);
1218
1219     /* dither flags */
1220     for (ch = 0; ch < s->fbw_channels; ch++)
1221         put_bits(&s->pb, 1, 1);
1222
1223     /* dynamic range codes */
1224     put_bits(&s->pb, 1, 0);
1225
1226     /* channel coupling */
1227     if (!block_num) {
1228         put_bits(&s->pb, 1, 1); /* coupling strategy present */
1229         put_bits(&s->pb, 1, 0); /* no coupling strategy */
1230     } else {
1231         put_bits(&s->pb, 1, 0); /* no new coupling strategy */
1232     }
1233
1234     /* stereo rematrixing */
1235     if (s->channel_mode == AC3_CHMODE_STEREO) {
1236         if (!block_num) {
1237             /* first block must define rematrixing (rematstr) */
1238             put_bits(&s->pb, 1, 1);
1239
1240             /* dummy rematrixing rematflg(1:4)=0 */
1241             for (rbnd = 0; rbnd < 4; rbnd++)
1242                 put_bits(&s->pb, 1, 0);
1243         } else {
1244             /* no matrixing (but should be used in the future) */
1245             put_bits(&s->pb, 1, 0);
1246         }
1247     }
1248
1249     /* exponent strategy */
1250     for (ch = 0; ch < s->fbw_channels; ch++)
1251         put_bits(&s->pb, 2, block->exp_strategy[ch]);
1252     if (s->lfe_on)
1253         put_bits(&s->pb, 1, block->exp_strategy[s->lfe_channel]);
1254
1255     /* bandwidth */
1256     for (ch = 0; ch < s->fbw_channels; ch++) {
1257         if (block->exp_strategy[ch] != EXP_REUSE)
1258             put_bits(&s->pb, 6, s->bandwidth_code[ch]);
1259     }
1260
1261     /* exponents */
1262     for (ch = 0; ch < s->channels; ch++) {
1263         if (block->exp_strategy[ch] == EXP_REUSE)
1264             continue;
1265
1266         /* DC exponent */
1267         put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
1268
1269         /* exponent groups */
1270         for (i = 1; i <= block->num_exp_groups[ch]; i++)
1271             put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1272
1273         /* gain range info */
1274         if (ch != s->lfe_channel)
1275             put_bits(&s->pb, 2, 0);
1276     }
1277
1278     /* bit allocation info */
1279     baie = (block_num == 0);
1280     put_bits(&s->pb, 1, baie);
1281     if (baie) {
1282         put_bits(&s->pb, 2, s->slow_decay_code);
1283         put_bits(&s->pb, 2, s->fast_decay_code);
1284         put_bits(&s->pb, 2, s->slow_gain_code);
1285         put_bits(&s->pb, 2, s->db_per_bit_code);
1286         put_bits(&s->pb, 3, s->floor_code);
1287     }
1288
1289     /* snr offset */
1290     put_bits(&s->pb, 1, baie);
1291     if (baie) {
1292         put_bits(&s->pb, 6, s->coarse_snr_offset);
1293         for (ch = 0; ch < s->channels; ch++) {
1294             put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1295             put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1296         }
1297     }
1298
1299     put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1300     put_bits(&s->pb, 1, 0); /* no data to skip */
1301
1302     /* mantissas */
1303     for (ch = 0; ch < s->channels; ch++) {
1304         int b, q;
1305         for (i = 0; i < s->nb_coefs[ch]; i++) {
1306             q = block->qmant[ch][i];
1307             b = s->bap[block_num][ch][i];
1308             switch (b) {
1309             case 0:                                         break;
1310             case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
1311             case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
1312             case 3:               put_bits(&s->pb,   3, q); break;
1313             case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
1314             case 14:              put_bits(&s->pb,  14, q); break;
1315             case 15:              put_bits(&s->pb,  16, q); break;
1316             default:              put_bits(&s->pb, b-1, q); break;
1317             }
1318         }
1319     }
1320 }
1321
1322
1323 /** CRC-16 Polynomial */
1324 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1325
1326
1327 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1328 {
1329     unsigned int c;
1330
1331     c = 0;
1332     while (a) {
1333         if (a & 1)
1334             c ^= b;
1335         a = a >> 1;
1336         b = b << 1;
1337         if (b & (1 << 16))
1338             b ^= poly;
1339     }
1340     return c;
1341 }
1342
1343
1344 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1345 {
1346     unsigned int r;
1347     r = 1;
1348     while (n) {
1349         if (n & 1)
1350             r = mul_poly(r, a, poly);
1351         a = mul_poly(a, a, poly);
1352         n >>= 1;
1353     }
1354     return r;
1355 }
1356
1357
1358 /**
1359  * Fill the end of the frame with 0's and compute the two CRCs.
1360  */
1361 static void output_frame_end(AC3EncodeContext *s)
1362 {
1363     int frame_size, frame_size_58, pad_bytes, crc1, crc2, crc_inv;
1364     uint8_t *frame;
1365
1366     frame_size    = s->frame_size;
1367     frame_size_58 = ((frame_size >> 2) + (frame_size >> 4)) << 1;
1368
1369     /* pad the remainder of the frame with zeros */
1370     flush_put_bits(&s->pb);
1371     frame = s->pb.buf;
1372     pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1373     assert(pad_bytes >= 0);
1374     if (pad_bytes > 0)
1375         memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1376
1377     /* compute crc1 */
1378     /* this is not so easy because it is at the beginning of the data... */
1379     crc1 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1380                              frame + 4, frame_size_58 - 4));
1381     /* XXX: could precompute crc_inv */
1382     crc_inv = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
1383     crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1384     AV_WB16(frame + 2, crc1);
1385
1386     /* compute crc2 */
1387     crc2 = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1388                              frame + frame_size_58,
1389                              frame_size - frame_size_58 - 2));
1390     AV_WB16(frame + frame_size - 2, crc2);
1391 }
1392
1393
1394 /**
1395  * Write the frame to the output bitstream.
1396  */
1397 static void output_frame(AC3EncodeContext *s,
1398                          unsigned char *frame)
1399 {
1400     int blk;
1401
1402     init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1403
1404     output_frame_header(s);
1405
1406     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1407         output_audio_block(s, blk);
1408
1409     output_frame_end(s);
1410 }
1411
1412
1413 /**
1414  * Encode a single AC-3 frame.
1415  */
1416 static int ac3_encode_frame(AVCodecContext *avctx,
1417                             unsigned char *frame, int buf_size, void *data)
1418 {
1419     AC3EncodeContext *s = avctx->priv_data;
1420     const int16_t *samples = data;
1421     int ret;
1422
1423     if (s->bit_alloc.sr_code == 1)
1424         adjust_frame_size(s);
1425
1426     deinterleave_input_samples(s, samples);
1427
1428     apply_mdct(s);
1429
1430     process_exponents(s);
1431
1432     ret = compute_bit_allocation(s);
1433     if (ret) {
1434         av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
1435         return ret;
1436     }
1437
1438     quantize_mantissas(s);
1439
1440     output_frame(s, frame);
1441
1442     return s->frame_size;
1443 }
1444
1445
1446 /**
1447  * Finalize encoding and free any memory allocated by the encoder.
1448  */
1449 static av_cold int ac3_encode_close(AVCodecContext *avctx)
1450 {
1451     av_freep(&avctx->coded_frame);
1452     return 0;
1453 }
1454
1455
1456 /**
1457  * Set channel information during initialization.
1458  */
1459 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
1460                                     int64_t *channel_layout)
1461 {
1462     int ch_layout;
1463
1464     if (channels < 1 || channels > AC3_MAX_CHANNELS)
1465         return AVERROR(EINVAL);
1466     if ((uint64_t)*channel_layout > 0x7FF)
1467         return AVERROR(EINVAL);
1468     ch_layout = *channel_layout;
1469     if (!ch_layout)
1470         ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
1471     if (av_get_channel_layout_nb_channels(ch_layout) != channels)
1472         return AVERROR(EINVAL);
1473
1474     s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
1475     s->channels     = channels;
1476     s->fbw_channels = channels - s->lfe_on;
1477     s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;
1478     if (s->lfe_on)
1479         ch_layout -= AV_CH_LOW_FREQUENCY;
1480
1481     switch (ch_layout) {
1482     case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
1483     case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
1484     case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
1485     case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
1486     case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
1487     case AV_CH_LAYOUT_QUAD:
1488     case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
1489     case AV_CH_LAYOUT_5POINT0:
1490     case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
1491     default:
1492         return AVERROR(EINVAL);
1493     }
1494
1495     s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
1496     *channel_layout = ch_layout;
1497     if (s->lfe_on)
1498         *channel_layout |= AV_CH_LOW_FREQUENCY;
1499
1500     return 0;
1501 }
1502
1503
1504 static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
1505 {
1506     int i, ret;
1507
1508     /* validate channel layout */
1509     if (!avctx->channel_layout) {
1510         av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
1511                                       "encoder will guess the layout, but it "
1512                                       "might be incorrect.\n");
1513     }
1514     ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
1515     if (ret) {
1516         av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
1517         return ret;
1518     }
1519
1520     /* validate sample rate */
1521     for (i = 0; i < 9; i++) {
1522         if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
1523             break;
1524     }
1525     if (i == 9) {
1526         av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
1527         return AVERROR(EINVAL);
1528     }
1529     s->sample_rate        = avctx->sample_rate;
1530     s->bit_alloc.sr_shift = i % 3;
1531     s->bit_alloc.sr_code  = i / 3;
1532
1533     /* validate bit rate */
1534     for (i = 0; i < 19; i++) {
1535         if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
1536             break;
1537     }
1538     if (i == 19) {
1539         av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
1540         return AVERROR(EINVAL);
1541     }
1542     s->bit_rate        = avctx->bit_rate;
1543     s->frame_size_code = i << 1;
1544
1545     return 0;
1546 }
1547
1548
1549 /**
1550  * Set bandwidth for all channels.
1551  * The user can optionally supply a cutoff frequency. Otherwise an appropriate
1552  * default value will be used.
1553  */
1554 static av_cold void set_bandwidth(AC3EncodeContext *s, int cutoff)
1555 {
1556     int ch, bw_code;
1557
1558     if (cutoff) {
1559         /* calculate bandwidth based on user-specified cutoff frequency */
1560         int fbw_coeffs;
1561         cutoff         = av_clip(cutoff, 1, s->sample_rate >> 1);
1562         fbw_coeffs     = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
1563         bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
1564     } else {
1565         /* use default bandwidth setting */
1566         /* XXX: should compute the bandwidth according to the frame
1567            size, so that we avoid annoying high frequency artifacts */
1568         bw_code = 50;
1569     }
1570
1571     /* set number of coefficients for each channel */
1572     for (ch = 0; ch < s->fbw_channels; ch++) {
1573         s->bandwidth_code[ch] = bw_code;
1574         s->nb_coefs[ch]       = bw_code * 3 + 73;
1575     }
1576     if (s->lfe_on)
1577         s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
1578 }
1579
1580
1581 /**
1582  * Initialize the encoder.
1583  */
1584 static av_cold int ac3_encode_init(AVCodecContext *avctx)
1585 {
1586     AC3EncodeContext *s = avctx->priv_data;
1587     int ret;
1588
1589     avctx->frame_size = AC3_FRAME_SIZE;
1590
1591     ac3_common_init();
1592
1593     ret = validate_options(avctx, s);
1594     if (ret)
1595         return ret;
1596
1597     s->bitstream_id   = 8 + s->bit_alloc.sr_shift;
1598     s->bitstream_mode = 0; /* complete main audio service */
1599
1600     s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
1601     s->bits_written    = 0;
1602     s->samples_written = 0;
1603     s->frame_size      = s->frame_size_min;
1604
1605     set_bandwidth(s, avctx->cutoff);
1606
1607     bit_alloc_init(s);
1608
1609     mdct_init(9);
1610
1611     avctx->coded_frame= avcodec_alloc_frame();
1612     avctx->coded_frame->key_frame= 1;
1613
1614     return 0;
1615 }
1616
1617
1618 #ifdef TEST
1619 /*************************************************************************/
1620 /* TEST */
1621
1622 #include "libavutil/lfg.h"
1623
1624 #define FN (MDCT_SAMPLES/4)
1625
1626
1627 static void fft_test(AVLFG *lfg)
1628 {
1629     IComplex in[FN], in1[FN];
1630     int k, n, i;
1631     float sum_re, sum_im, a;
1632
1633     for (i = 0; i < FN; i++) {
1634         in[i].re = av_lfg_get(lfg) % 65535 - 32767;
1635         in[i].im = av_lfg_get(lfg) % 65535 - 32767;
1636         in1[i]   = in[i];
1637     }
1638     fft(in, 7);
1639
1640     /* do it by hand */
1641     for (k = 0; k < FN; k++) {
1642         sum_re = 0;
1643         sum_im = 0;
1644         for (n = 0; n < FN; n++) {
1645             a = -2 * M_PI * (n * k) / FN;
1646             sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
1647             sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
1648         }
1649         av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
1650                k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
1651     }
1652 }
1653
1654
1655 static void mdct_test(AVLFG *lfg)
1656 {
1657     int16_t input[MDCT_SAMPLES];
1658     int32_t output[AC3_MAX_COEFS];
1659     float input1[MDCT_SAMPLES];
1660     float output1[AC3_MAX_COEFS];
1661     float s, a, err, e, emax;
1662     int i, k, n;
1663
1664     for (i = 0; i < MDCT_SAMPLES; i++) {
1665         input[i]  = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
1666         input1[i] = input[i];
1667     }
1668
1669     mdct512(output, input);
1670
1671     /* do it by hand */
1672     for (k = 0; k < AC3_MAX_COEFS; k++) {
1673         s = 0;
1674         for (n = 0; n < MDCT_SAMPLES; n++) {
1675             a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
1676             s += input1[n] * cos(a);
1677         }
1678         output1[k] = -2 * s / MDCT_SAMPLES;
1679     }
1680
1681     err  = 0;
1682     emax = 0;
1683     for (i = 0; i < AC3_MAX_COEFS; i++) {
1684         av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
1685         e = output[i] - output1[i];
1686         if (e > emax)
1687             emax = e;
1688         err += e * e;
1689     }
1690     av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
1691 }
1692
1693
1694 int main(void)
1695 {
1696     AVLFG lfg;
1697
1698     av_log_set_level(AV_LOG_DEBUG);
1699     mdct_init(9);
1700
1701     fft_test(&lfg);
1702     mdct_test(&lfg);
1703
1704     return 0;
1705 }
1706 #endif /* TEST */
1707
1708
1709 AVCodec ac3_encoder = {
1710     "ac3",
1711     AVMEDIA_TYPE_AUDIO,
1712     CODEC_ID_AC3,
1713     sizeof(AC3EncodeContext),
1714     ac3_encode_init,
1715     ac3_encode_frame,
1716     ac3_encode_close,
1717     NULL,
1718     .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1719     .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
1720     .channel_layouts = (const int64_t[]){
1721         AV_CH_LAYOUT_MONO,
1722         AV_CH_LAYOUT_STEREO,
1723         AV_CH_LAYOUT_2_1,
1724         AV_CH_LAYOUT_SURROUND,
1725         AV_CH_LAYOUT_2_2,
1726         AV_CH_LAYOUT_QUAD,
1727         AV_CH_LAYOUT_4POINT0,
1728         AV_CH_LAYOUT_5POINT0,
1729         AV_CH_LAYOUT_5POINT0_BACK,
1730        (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
1731        (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
1732        (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
1733        (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
1734        (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
1735        (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
1736        (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
1737         AV_CH_LAYOUT_5POINT1,
1738         AV_CH_LAYOUT_5POINT1_BACK,
1739         0 },
1740 };