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