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