]> git.sesse.net Git - ffmpeg/blob - libavcodec/ac3enc.c
resample: clarify supported resampling.
[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 ASSERT_LEVEL 2
30
31 #include <stdint.h>
32
33 #include "libavutil/audioconvert.h"
34 #include "libavutil/avassert.h"
35 #include "libavutil/avstring.h"
36 #include "libavutil/crc.h"
37 #include "libavutil/opt.h"
38 #include "avcodec.h"
39 #include "put_bits.h"
40 #include "dsputil.h"
41 #include "ac3dsp.h"
42 #include "ac3.h"
43 #include "audioconvert.h"
44 #include "fft.h"
45
46 #include "ac3enc.h"
47 #include "eac3enc.h"
48
49 typedef struct AC3Mant {
50     uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
51     int mant1_cnt, mant2_cnt, mant4_cnt;    ///< mantissa counts for bap=1,2,4
52 } AC3Mant;
53
54 #define CMIXLEV_NUM_OPTIONS 3
55 static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
56     LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
57 };
58
59 #define SURMIXLEV_NUM_OPTIONS 3
60 static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
61     LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
62 };
63
64 #define EXTMIXLEV_NUM_OPTIONS 8
65 static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
66     LEVEL_PLUS_3DB,  LEVEL_PLUS_1POINT5DB,  LEVEL_ONE,       LEVEL_MINUS_4POINT5DB,
67     LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
68 };
69
70
71 #define OFFSET(param) offsetof(AC3EncodeContext, options.param)
72 #define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
73
74 #define AC3ENC_TYPE_AC3_FIXED   0
75 #define AC3ENC_TYPE_AC3         1
76 #define AC3ENC_TYPE_EAC3        2
77
78 #if CONFIG_AC3ENC_FLOAT
79 #define AC3ENC_TYPE AC3ENC_TYPE_AC3
80 #include "ac3enc_opts_template.c"
81 static AVClass ac3enc_class = { "AC-3 Encoder", av_default_item_name,
82                                 ac3_options, LIBAVUTIL_VERSION_INT };
83 #undef AC3ENC_TYPE
84 #define AC3ENC_TYPE AC3ENC_TYPE_EAC3
85 #include "ac3enc_opts_template.c"
86 static AVClass eac3enc_class = { "E-AC-3 Encoder", av_default_item_name,
87                                  eac3_options, LIBAVUTIL_VERSION_INT };
88 #else
89 #define AC3ENC_TYPE AC3ENC_TYPE_AC3_FIXED
90 #include "ac3enc_opts_template.c"
91 static AVClass ac3enc_class = { "Fixed-Point AC-3 Encoder", av_default_item_name,
92                                 ac3fixed_options, LIBAVUTIL_VERSION_INT };
93 #endif
94
95
96 /* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
97
98 static av_cold void mdct_end(AC3MDCTContext *mdct);
99
100 static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
101                              int nbits);
102
103 static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
104                          const SampleType *window, unsigned int len);
105
106 static int normalize_samples(AC3EncodeContext *s);
107
108 static void scale_coefficients(AC3EncodeContext *s);
109
110
111 /**
112  * LUT for number of exponent groups.
113  * exponent_group_tab[coupling][exponent strategy-1][number of coefficients]
114  */
115 static uint8_t exponent_group_tab[2][3][256];
116
117
118 /**
119  * List of supported channel layouts.
120  */
121 #if CONFIG_AC3ENC_FLOAT || !CONFIG_AC3_FLOAT_ENCODER //we need this exactly once compiled in
122 const int64_t ff_ac3_channel_layouts[] = {
123      AV_CH_LAYOUT_MONO,
124      AV_CH_LAYOUT_STEREO,
125      AV_CH_LAYOUT_2_1,
126      AV_CH_LAYOUT_SURROUND,
127      AV_CH_LAYOUT_2_2,
128      AV_CH_LAYOUT_QUAD,
129      AV_CH_LAYOUT_4POINT0,
130      AV_CH_LAYOUT_5POINT0,
131      AV_CH_LAYOUT_5POINT0_BACK,
132     (AV_CH_LAYOUT_MONO     | AV_CH_LOW_FREQUENCY),
133     (AV_CH_LAYOUT_STEREO   | AV_CH_LOW_FREQUENCY),
134     (AV_CH_LAYOUT_2_1      | AV_CH_LOW_FREQUENCY),
135     (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
136     (AV_CH_LAYOUT_2_2      | AV_CH_LOW_FREQUENCY),
137     (AV_CH_LAYOUT_QUAD     | AV_CH_LOW_FREQUENCY),
138     (AV_CH_LAYOUT_4POINT0  | AV_CH_LOW_FREQUENCY),
139      AV_CH_LAYOUT_5POINT1,
140      AV_CH_LAYOUT_5POINT1_BACK,
141      0
142 };
143 #endif
144
145
146 /**
147  * LUT to select the bandwidth code based on the bit rate, sample rate, and
148  * number of full-bandwidth channels.
149  * bandwidth_tab[fbw_channels-1][sample rate code][bit rate code]
150  */
151 static const uint8_t ac3_bandwidth_tab[5][3][19] = {
152 //      32  40  48  56  64  80  96 112 128 160 192 224 256 320 384 448 512 576 640
153
154     { {  0,  0,  0, 12, 16, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
155       {  0,  0,  0, 16, 20, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
156       {  0,  0,  0, 32, 40, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
157
158     { {  0,  0,  0,  0,  0,  0,  0, 20, 24, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
159       {  0,  0,  0,  0,  0,  0,  4, 24, 28, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
160       {  0,  0,  0,  0,  0,  0, 20, 44, 52, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
161
162     { {  0,  0,  0,  0,  0,  0,  0,  0,  0, 16, 24, 32, 40, 48, 48, 48, 48, 48, 48 },
163       {  0,  0,  0,  0,  0,  0,  0,  0,  4, 20, 28, 36, 44, 56, 56, 56, 56, 56, 56 },
164       {  0,  0,  0,  0,  0,  0,  0,  0, 20, 40, 48, 60, 60, 60, 60, 60, 60, 60, 60 } },
165
166     { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 12, 24, 32, 48, 48, 48, 48, 48, 48 },
167       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 16, 28, 36, 56, 56, 56, 56, 56, 56 },
168       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 32, 48, 60, 60, 60, 60, 60, 60, 60 } },
169
170     { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  8, 20, 32, 40, 48, 48, 48, 48 },
171       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 12, 24, 36, 44, 56, 56, 56, 56 },
172       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 28, 44, 60, 60, 60, 60, 60, 60 } }
173 };
174
175
176 /**
177  * LUT to select the coupling start band based on the bit rate, sample rate, and
178  * number of full-bandwidth channels. -1 = coupling off
179  * ac3_coupling_start_tab[channel_mode-2][sample rate code][bit rate code]
180  *
181  * TODO: more testing for optimal parameters.
182  *       multi-channel tests at 44.1kHz and 32kHz.
183  */
184 static const int8_t ac3_coupling_start_tab[6][3][19] = {
185 //      32  40  48  56  64  80  96 112 128 160 192 224 256 320 384 448 512 576 640
186
187     // 2/0
188     { {  0,  0,  0,  0,  0,  0,  0,  1,  1,  7,  8, 11, 12, -1, -1, -1, -1, -1, -1 },
189       {  0,  0,  0,  0,  0,  0,  1,  3,  5,  7, 10, 12, 13, -1, -1, -1, -1, -1, -1 },
190       {  0,  0,  0,  0,  1,  2,  2,  9, 13, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
191
192     // 3/0
193     { {  0,  0,  0,  0,  0,  0,  0,  0,  2,  2,  6,  9, 11, 12, 13, -1, -1, -1, -1 },
194       {  0,  0,  0,  0,  0,  0,  0,  0,  2,  2,  6,  9, 11, 12, 13, -1, -1, -1, -1 },
195       { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
196
197     // 2/1 - untested
198     { {  0,  0,  0,  0,  0,  0,  0,  0,  2,  2,  6,  9, 11, 12, 13, -1, -1, -1, -1 },
199       {  0,  0,  0,  0,  0,  0,  0,  0,  2,  2,  6,  9, 11, 12, 13, -1, -1, -1, -1 },
200       { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
201
202     // 3/1
203     { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3,  2, 10, 11, 11, 12, 12, 14, -1 },
204       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3,  2, 10, 11, 11, 12, 12, 14, -1 },
205       { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
206
207     // 2/2 - untested
208     { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3,  2, 10, 11, 11, 12, 12, 14, -1 },
209       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  3,  2, 10, 11, 11, 12, 12, 14, -1 },
210       { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
211
212     // 3/2
213     { {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  6,  8, 11, 12, 12, -1, -1 },
214       {  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  6,  8, 11, 12, 12, -1, -1 },
215       { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
216 };
217
218
219 /**
220  * Adjust the frame size to make the average bit rate match the target bit rate.
221  * This is only needed for 11025, 22050, and 44100 sample rates or any E-AC-3.
222  */
223 static void adjust_frame_size(AC3EncodeContext *s)
224 {
225     while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
226         s->bits_written    -= s->bit_rate;
227         s->samples_written -= s->sample_rate;
228     }
229     s->frame_size = s->frame_size_min +
230                     2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
231     s->bits_written    += s->frame_size * 8;
232     s->samples_written += AC3_FRAME_SIZE;
233 }
234
235
236 /**
237  * Deinterleave input samples.
238  * Channels are reordered from FFmpeg's default order to AC-3 order.
239  */
240 static void deinterleave_input_samples(AC3EncodeContext *s,
241                                        const SampleType *samples)
242 {
243     int ch, i;
244
245     /* deinterleave and remap input samples */
246     for (ch = 0; ch < s->channels; ch++) {
247         const SampleType *sptr;
248         int sinc;
249
250         /* copy last 256 samples of previous frame to the start of the current frame */
251         memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
252                AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
253
254         /* deinterleave */
255         sinc = s->channels;
256         sptr = samples + s->channel_map[ch];
257         for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
258             s->planar_samples[ch][i] = *sptr;
259             sptr += sinc;
260         }
261     }
262 }
263
264
265 /**
266  * Apply the MDCT to input samples to generate frequency coefficients.
267  * This applies the KBD window and normalizes the input to reduce precision
268  * loss due to fixed-point calculations.
269  */
270 static void apply_mdct(AC3EncodeContext *s)
271 {
272     int blk, ch;
273
274     for (ch = 0; ch < s->channels; ch++) {
275         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
276             AC3Block *block = &s->blocks[blk];
277             const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
278
279             apply_window(&s->dsp, s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
280
281             block->coeff_shift[ch+1] = normalize_samples(s);
282
283             s->mdct.fft.mdct_calcw(&s->mdct.fft, block->mdct_coef[ch+1],
284                                    s->windowed_samples);
285         }
286     }
287 }
288
289
290 static void compute_coupling_strategy(AC3EncodeContext *s)
291 {
292     int blk, ch;
293     int got_cpl_snr;
294
295     /* set coupling use flags for each block/channel */
296     /* TODO: turn coupling on/off and adjust start band based on bit usage */
297     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
298         AC3Block *block = &s->blocks[blk];
299         for (ch = 1; ch <= s->fbw_channels; ch++)
300             block->channel_in_cpl[ch] = s->cpl_on;
301     }
302
303     /* enable coupling for each block if at least 2 channels have coupling
304        enabled for that block */
305     got_cpl_snr = 0;
306     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
307         AC3Block *block = &s->blocks[blk];
308         block->num_cpl_channels = 0;
309         for (ch = 1; ch <= s->fbw_channels; ch++)
310             block->num_cpl_channels += block->channel_in_cpl[ch];
311         block->cpl_in_use = block->num_cpl_channels > 1;
312         if (!block->cpl_in_use) {
313             block->num_cpl_channels = 0;
314             for (ch = 1; ch <= s->fbw_channels; ch++)
315                 block->channel_in_cpl[ch] = 0;
316         }
317
318         block->new_cpl_strategy = !blk;
319         if (blk) {
320             for (ch = 1; ch <= s->fbw_channels; ch++) {
321                 if (block->channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]) {
322                     block->new_cpl_strategy = 1;
323                     break;
324                 }
325             }
326         }
327         block->new_cpl_leak = block->new_cpl_strategy;
328
329         if (!blk || (block->cpl_in_use && !got_cpl_snr)) {
330             block->new_snr_offsets = 1;
331             if (block->cpl_in_use)
332                 got_cpl_snr = 1;
333         } else {
334             block->new_snr_offsets = 0;
335         }
336     }
337
338     /* set bandwidth for each channel */
339     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
340         AC3Block *block = &s->blocks[blk];
341         for (ch = 1; ch <= s->fbw_channels; ch++) {
342             if (block->channel_in_cpl[ch])
343                 block->end_freq[ch] = s->start_freq[CPL_CH];
344             else
345                 block->end_freq[ch] = s->bandwidth_code * 3 + 73;
346         }
347     }
348 }
349
350
351 /**
352  * Calculate a single coupling coordinate.
353  */
354 static inline float calc_cpl_coord(float energy_ch, float energy_cpl)
355 {
356     float coord = 0.125;
357     if (energy_cpl > 0)
358         coord *= sqrtf(energy_ch / energy_cpl);
359     return coord;
360 }
361
362
363 /**
364  * Calculate coupling channel and coupling coordinates.
365  * TODO: Currently this is only used for the floating-point encoder. I was
366  *       able to make it work for the fixed-point encoder, but quality was
367  *       generally lower in most cases than not using coupling. If a more
368  *       adaptive coupling strategy were to be implemented it might be useful
369  *       at that time to use coupling for the fixed-point encoder as well.
370  */
371 static void apply_channel_coupling(AC3EncodeContext *s)
372 {
373 #if CONFIG_AC3ENC_FLOAT
374     LOCAL_ALIGNED_16(float,   cpl_coords,       [AC3_MAX_BLOCKS], [AC3_MAX_CHANNELS][16]);
375     LOCAL_ALIGNED_16(int32_t, fixed_cpl_coords, [AC3_MAX_BLOCKS], [AC3_MAX_CHANNELS][16]);
376     int blk, ch, bnd, i, j;
377     CoefSumType energy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][16] = {{{0}}};
378     int num_cpl_coefs = s->num_cpl_subbands * 12;
379
380     memset(cpl_coords,       0, AC3_MAX_BLOCKS * sizeof(*cpl_coords));
381     memset(fixed_cpl_coords, 0, AC3_MAX_BLOCKS * sizeof(*fixed_cpl_coords));
382
383     /* calculate coupling channel from fbw channels */
384     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
385         AC3Block *block = &s->blocks[blk];
386         CoefType *cpl_coef = &block->mdct_coef[CPL_CH][s->start_freq[CPL_CH]];
387         if (!block->cpl_in_use)
388             continue;
389         memset(cpl_coef-1, 0, (num_cpl_coefs+4) * sizeof(*cpl_coef));
390         for (ch = 1; ch <= s->fbw_channels; ch++) {
391             CoefType *ch_coef = &block->mdct_coef[ch][s->start_freq[CPL_CH]];
392             if (!block->channel_in_cpl[ch])
393                 continue;
394             for (i = 0; i < num_cpl_coefs; i++)
395                 cpl_coef[i] += ch_coef[i];
396         }
397         /* note: coupling start bin % 4 will always be 1 and num_cpl_coefs
398                  will always be a multiple of 12, so we need to subtract 1 from
399                  the start and add 4 to the length when using optimized
400                  functions which require 16-byte alignment. */
401
402         /* coefficients must be clipped to +/- 1.0 in order to be encoded */
403         s->dsp.vector_clipf(cpl_coef-1, cpl_coef-1, -1.0f, 1.0f, num_cpl_coefs+4);
404
405         /* scale coupling coefficients from float to 24-bit fixed-point */
406         s->ac3dsp.float_to_fixed24(&block->fixed_coef[CPL_CH][s->start_freq[CPL_CH]-1],
407                                    cpl_coef-1, num_cpl_coefs+4);
408     }
409
410     /* calculate energy in each band in coupling channel and each fbw channel */
411     /* TODO: possibly use SIMD to speed up energy calculation */
412     bnd = 0;
413     i = s->start_freq[CPL_CH];
414     while (i < s->cpl_end_freq) {
415         int band_size = s->cpl_band_sizes[bnd];
416         for (ch = CPL_CH; ch <= s->fbw_channels; ch++) {
417             for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
418                 AC3Block *block = &s->blocks[blk];
419                 if (!block->cpl_in_use || (ch > CPL_CH && !block->channel_in_cpl[ch]))
420                     continue;
421                 for (j = 0; j < band_size; j++) {
422                     CoefType v = block->mdct_coef[ch][i+j];
423                     MAC_COEF(energy[blk][ch][bnd], v, v);
424                 }
425             }
426         }
427         i += band_size;
428         bnd++;
429     }
430
431     /* determine which blocks to send new coupling coordinates for */
432     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
433         AC3Block *block  = &s->blocks[blk];
434         AC3Block *block0 = blk ? &s->blocks[blk-1] : NULL;
435         int new_coords = 0;
436         CoefSumType coord_diff[AC3_MAX_CHANNELS] = {0,};
437
438         if (block->cpl_in_use) {
439             /* calculate coupling coordinates for all blocks and calculate the
440                average difference between coordinates in successive blocks */
441             for (ch = 1; ch <= s->fbw_channels; ch++) {
442                 if (!block->channel_in_cpl[ch])
443                     continue;
444
445                 for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
446                     cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy[blk][ch][bnd],
447                                                               energy[blk][CPL_CH][bnd]);
448                     if (blk > 0 && block0->cpl_in_use &&
449                         block0->channel_in_cpl[ch]) {
450                         coord_diff[ch] += fabs(cpl_coords[blk-1][ch][bnd] -
451                                                cpl_coords[blk  ][ch][bnd]);
452                     }
453                 }
454                 coord_diff[ch] /= s->num_cpl_bands;
455             }
456
457             /* send new coordinates if this is the first block, if previous
458              * block did not use coupling but this block does, the channels
459              * using coupling has changed from the previous block, or the
460              * coordinate difference from the last block for any channel is
461              * greater than a threshold value. */
462             if (blk == 0) {
463                 new_coords = 1;
464             } else if (!block0->cpl_in_use) {
465                 new_coords = 1;
466             } else {
467                 for (ch = 1; ch <= s->fbw_channels; ch++) {
468                     if (block->channel_in_cpl[ch] && !block0->channel_in_cpl[ch]) {
469                         new_coords = 1;
470                         break;
471                     }
472                 }
473                 if (!new_coords) {
474                     for (ch = 1; ch <= s->fbw_channels; ch++) {
475                         if (block->channel_in_cpl[ch] && coord_diff[ch] > 0.04) {
476                             new_coords = 1;
477                             break;
478                         }
479                     }
480                 }
481             }
482         }
483         block->new_cpl_coords = new_coords;
484     }
485
486     /* calculate final coupling coordinates, taking into account reusing of
487        coordinates in successive blocks */
488     for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
489         blk = 0;
490         while (blk < AC3_MAX_BLOCKS) {
491             int blk1;
492             CoefSumType energy_cpl;
493             AC3Block *block  = &s->blocks[blk];
494
495             if (!block->cpl_in_use) {
496                 blk++;
497                 continue;
498             }
499
500             energy_cpl = energy[blk][CPL_CH][bnd];
501             blk1 = blk+1;
502             while (!s->blocks[blk1].new_cpl_coords && blk1 < AC3_MAX_BLOCKS) {
503                 if (s->blocks[blk1].cpl_in_use)
504                     energy_cpl += energy[blk1][CPL_CH][bnd];
505                 blk1++;
506             }
507
508             for (ch = 1; ch <= s->fbw_channels; ch++) {
509                 CoefType energy_ch;
510                 if (!block->channel_in_cpl[ch])
511                     continue;
512                 energy_ch = energy[blk][ch][bnd];
513                 blk1 = blk+1;
514                 while (!s->blocks[blk1].new_cpl_coords && blk1 < AC3_MAX_BLOCKS) {
515                     if (s->blocks[blk1].cpl_in_use)
516                         energy_ch += energy[blk1][ch][bnd];
517                     blk1++;
518                 }
519                 cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy_ch, energy_cpl);
520             }
521             blk = blk1;
522         }
523     }
524
525     /* calculate exponents/mantissas for coupling coordinates */
526     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
527         AC3Block *block = &s->blocks[blk];
528         if (!block->cpl_in_use || !block->new_cpl_coords)
529             continue;
530
531         s->ac3dsp.float_to_fixed24(fixed_cpl_coords[blk][1],
532                                    cpl_coords[blk][1],
533                                    s->fbw_channels * 16);
534         s->ac3dsp.extract_exponents(block->cpl_coord_exp[1],
535                                     fixed_cpl_coords[blk][1],
536                                     s->fbw_channels * 16);
537
538         for (ch = 1; ch <= s->fbw_channels; ch++) {
539             int bnd, min_exp, max_exp, master_exp;
540
541             /* determine master exponent */
542             min_exp = max_exp = block->cpl_coord_exp[ch][0];
543             for (bnd = 1; bnd < s->num_cpl_bands; bnd++) {
544                 int exp = block->cpl_coord_exp[ch][bnd];
545                 min_exp = FFMIN(exp, min_exp);
546                 max_exp = FFMAX(exp, max_exp);
547             }
548             master_exp = ((max_exp - 15) + 2) / 3;
549             master_exp = FFMAX(master_exp, 0);
550             while (min_exp < master_exp * 3)
551                 master_exp--;
552             for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
553                 block->cpl_coord_exp[ch][bnd] = av_clip(block->cpl_coord_exp[ch][bnd] -
554                                                         master_exp * 3, 0, 15);
555             }
556             block->cpl_master_exp[ch] = master_exp;
557
558             /* quantize mantissas */
559             for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
560                 int cpl_exp  = block->cpl_coord_exp[ch][bnd];
561                 int cpl_mant = (fixed_cpl_coords[blk][ch][bnd] << (5 + cpl_exp + master_exp * 3)) >> 24;
562                 if (cpl_exp == 15)
563                     cpl_mant >>= 1;
564                 else
565                     cpl_mant -= 16;
566
567                 block->cpl_coord_mant[ch][bnd] = cpl_mant;
568             }
569         }
570     }
571
572     if (CONFIG_EAC3_ENCODER && s->eac3)
573         ff_eac3_set_cpl_states(s);
574 #endif /* CONFIG_AC3ENC_FLOAT */
575 }
576
577
578 /**
579  * Determine rematrixing flags for each block and band.
580  */
581 static void compute_rematrixing_strategy(AC3EncodeContext *s)
582 {
583     int nb_coefs;
584     int blk, bnd, i;
585     AC3Block *block, *block0;
586
587     if (s->channel_mode != AC3_CHMODE_STEREO)
588         return;
589
590     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
591         block = &s->blocks[blk];
592         block->new_rematrixing_strategy = !blk;
593
594         if (!s->rematrixing_enabled) {
595             block0 = block;
596             continue;
597         }
598
599         block->num_rematrixing_bands = 4;
600         if (block->cpl_in_use) {
601             block->num_rematrixing_bands -= (s->start_freq[CPL_CH] <= 61);
602             block->num_rematrixing_bands -= (s->start_freq[CPL_CH] == 37);
603             if (blk && block->num_rematrixing_bands != block0->num_rematrixing_bands)
604                 block->new_rematrixing_strategy = 1;
605         }
606         nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
607
608         for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {
609             /* calculate calculate sum of squared coeffs for one band in one block */
610             int start = ff_ac3_rematrix_band_tab[bnd];
611             int end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
612             CoefSumType sum[4] = {0,};
613             for (i = start; i < end; i++) {
614                 CoefType lt = block->mdct_coef[1][i];
615                 CoefType rt = block->mdct_coef[2][i];
616                 CoefType md = lt + rt;
617                 CoefType sd = lt - rt;
618                 MAC_COEF(sum[0], lt, lt);
619                 MAC_COEF(sum[1], rt, rt);
620                 MAC_COEF(sum[2], md, md);
621                 MAC_COEF(sum[3], sd, sd);
622             }
623
624             /* compare sums to determine if rematrixing will be used for this band */
625             if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
626                 block->rematrixing_flags[bnd] = 1;
627             else
628                 block->rematrixing_flags[bnd] = 0;
629
630             /* determine if new rematrixing flags will be sent */
631             if (blk &&
632                 block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
633                 block->new_rematrixing_strategy = 1;
634             }
635         }
636         block0 = block;
637     }
638 }
639
640
641 /**
642  * Apply stereo rematrixing to coefficients based on rematrixing flags.
643  */
644 static void apply_rematrixing(AC3EncodeContext *s)
645 {
646     int nb_coefs;
647     int blk, bnd, i;
648     int start, end;
649     uint8_t *flags;
650
651     if (!s->rematrixing_enabled)
652         return;
653
654     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
655         AC3Block *block = &s->blocks[blk];
656         if (block->new_rematrixing_strategy)
657             flags = block->rematrixing_flags;
658         nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
659         for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {
660             if (flags[bnd]) {
661                 start = ff_ac3_rematrix_band_tab[bnd];
662                 end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
663                 for (i = start; i < end; i++) {
664                     int32_t lt = block->fixed_coef[1][i];
665                     int32_t rt = block->fixed_coef[2][i];
666                     block->fixed_coef[1][i] = (lt + rt) >> 1;
667                     block->fixed_coef[2][i] = (lt - rt) >> 1;
668                 }
669             }
670         }
671     }
672 }
673
674
675 /**
676  * Initialize exponent tables.
677  */
678 static av_cold void exponent_init(AC3EncodeContext *s)
679 {
680     int expstr, i, grpsize;
681
682     for (expstr = EXP_D15-1; expstr <= EXP_D45-1; expstr++) {
683         grpsize = 3 << expstr;
684         for (i = 12; i < 256; i++) {
685             exponent_group_tab[0][expstr][i] = (i + grpsize - 4) / grpsize;
686             exponent_group_tab[1][expstr][i] = (i              ) / grpsize;
687         }
688     }
689     /* LFE */
690     exponent_group_tab[0][0][7] = 2;
691 }
692
693
694 /**
695  * Extract exponents from the MDCT coefficients.
696  * This takes into account the normalization that was done to the input samples
697  * by adjusting the exponents by the exponent shift values.
698  */
699 static void extract_exponents(AC3EncodeContext *s)
700 {
701     int ch        = !s->cpl_on;
702     int chan_size = AC3_MAX_COEFS * AC3_MAX_BLOCKS * (s->channels - ch + 1);
703     AC3Block *block = &s->blocks[0];
704
705     s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch], chan_size);
706 }
707
708
709 /**
710  * Exponent Difference Threshold.
711  * New exponents are sent if their SAD exceed this number.
712  */
713 #define EXP_DIFF_THRESHOLD 500
714
715
716 /**
717  * Calculate exponent strategies for all channels.
718  * Array arrangement is reversed to simplify the per-channel calculation.
719  */
720 static void compute_exp_strategy(AC3EncodeContext *s)
721 {
722     int ch, blk, blk1;
723
724     for (ch = !s->cpl_on; ch <= s->fbw_channels; ch++) {
725         uint8_t *exp_strategy = s->exp_strategy[ch];
726         uint8_t *exp          = s->blocks[0].exp[ch];
727         int exp_diff;
728
729         /* estimate if the exponent variation & decide if they should be
730            reused in the next frame */
731         exp_strategy[0] = EXP_NEW;
732         exp += AC3_MAX_COEFS;
733         for (blk = 1; blk < AC3_MAX_BLOCKS; blk++, exp += AC3_MAX_COEFS) {
734             if ((ch == CPL_CH && (!s->blocks[blk].cpl_in_use || !s->blocks[blk-1].cpl_in_use)) ||
735                 (ch  > CPL_CH && (s->blocks[blk].channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]))) {
736                 exp_strategy[blk] = EXP_NEW;
737                 continue;
738             }
739             exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
740             exp_strategy[blk] = EXP_REUSE;
741             if (ch == CPL_CH && exp_diff > (EXP_DIFF_THRESHOLD * (s->blocks[blk].end_freq[ch] - s->start_freq[ch]) / AC3_MAX_COEFS))
742                 exp_strategy[blk] = EXP_NEW;
743             else if (ch > CPL_CH && exp_diff > EXP_DIFF_THRESHOLD)
744                 exp_strategy[blk] = EXP_NEW;
745         }
746
747         /* now select the encoding strategy type : if exponents are often
748            recoded, we use a coarse encoding */
749         blk = 0;
750         while (blk < AC3_MAX_BLOCKS) {
751             blk1 = blk + 1;
752             while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
753                 blk1++;
754             switch (blk1 - blk) {
755             case 1:  exp_strategy[blk] = EXP_D45; break;
756             case 2:
757             case 3:  exp_strategy[blk] = EXP_D25; break;
758             default: exp_strategy[blk] = EXP_D15; break;
759             }
760             blk = blk1;
761         }
762     }
763     if (s->lfe_on) {
764         ch = s->lfe_channel;
765         s->exp_strategy[ch][0] = EXP_D15;
766         for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
767             s->exp_strategy[ch][blk] = EXP_REUSE;
768     }
769 }
770
771
772 /**
773  * Update the exponents so that they are the ones the decoder will decode.
774  */
775 static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy,
776                                     int cpl)
777 {
778     int nb_groups, i, k;
779
780     nb_groups = exponent_group_tab[cpl][exp_strategy-1][nb_exps] * 3;
781
782     /* for each group, compute the minimum exponent */
783     switch(exp_strategy) {
784     case EXP_D25:
785         for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
786             uint8_t exp_min = exp[k];
787             if (exp[k+1] < exp_min)
788                 exp_min = exp[k+1];
789             exp[i-cpl] = exp_min;
790             k += 2;
791         }
792         break;
793     case EXP_D45:
794         for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
795             uint8_t exp_min = exp[k];
796             if (exp[k+1] < exp_min)
797                 exp_min = exp[k+1];
798             if (exp[k+2] < exp_min)
799                 exp_min = exp[k+2];
800             if (exp[k+3] < exp_min)
801                 exp_min = exp[k+3];
802             exp[i-cpl] = exp_min;
803             k += 4;
804         }
805         break;
806     }
807
808     /* constraint for DC exponent */
809     if (!cpl && exp[0] > 15)
810         exp[0] = 15;
811
812     /* decrease the delta between each groups to within 2 so that they can be
813        differentially encoded */
814     for (i = 1; i <= nb_groups; i++)
815         exp[i] = FFMIN(exp[i], exp[i-1] + 2);
816     i--;
817     while (--i >= 0)
818         exp[i] = FFMIN(exp[i], exp[i+1] + 2);
819
820     if (cpl)
821         exp[-1] = exp[0] & ~1;
822
823     /* now we have the exponent values the decoder will see */
824     switch (exp_strategy) {
825     case EXP_D25:
826         for (i = nb_groups, k = (nb_groups * 2)-cpl; i > 0; i--) {
827             uint8_t exp1 = exp[i-cpl];
828             exp[k--] = exp1;
829             exp[k--] = exp1;
830         }
831         break;
832     case EXP_D45:
833         for (i = nb_groups, k = (nb_groups * 4)-cpl; i > 0; i--) {
834             exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i-cpl];
835             k -= 4;
836         }
837         break;
838     }
839 }
840
841
842 /**
843  * Encode exponents from original extracted form to what the decoder will see.
844  * This copies and groups exponents based on exponent strategy and reduces
845  * deltas between adjacent exponent groups so that they can be differentially
846  * encoded.
847  */
848 static void encode_exponents(AC3EncodeContext *s)
849 {
850     int blk, blk1, ch, cpl;
851     uint8_t *exp, *exp_strategy;
852     int nb_coefs, num_reuse_blocks;
853
854     for (ch = !s->cpl_on; ch <= s->channels; ch++) {
855         exp          = s->blocks[0].exp[ch] + s->start_freq[ch];
856         exp_strategy = s->exp_strategy[ch];
857
858         cpl = (ch == CPL_CH);
859         blk = 0;
860         while (blk < AC3_MAX_BLOCKS) {
861             AC3Block *block = &s->blocks[blk];
862             if (cpl && !block->cpl_in_use) {
863                 exp += AC3_MAX_COEFS;
864                 blk++;
865                 continue;
866             }
867             nb_coefs = block->end_freq[ch] - s->start_freq[ch];
868             blk1 = blk + 1;
869
870             /* count the number of EXP_REUSE blocks after the current block
871                and set exponent reference block numbers */
872             s->exp_ref_block[ch][blk] = blk;
873             while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
874                 s->exp_ref_block[ch][blk1] = blk;
875                 blk1++;
876             }
877             num_reuse_blocks = blk1 - blk - 1;
878
879             /* for the EXP_REUSE case we select the min of the exponents */
880             s->ac3dsp.ac3_exponent_min(exp-s->start_freq[ch], num_reuse_blocks,
881                                        AC3_MAX_COEFS);
882
883             encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk], cpl);
884
885             exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
886             blk = blk1;
887         }
888     }
889
890     /* reference block numbers have been changed, so reset ref_bap_set */
891     s->ref_bap_set = 0;
892 }
893
894
895 /**
896  * Group exponents.
897  * 3 delta-encoded exponents are in each 7-bit group. The number of groups
898  * varies depending on exponent strategy and bandwidth.
899  */
900 static void group_exponents(AC3EncodeContext *s)
901 {
902     int blk, ch, i, cpl;
903     int group_size, nb_groups, bit_count;
904     uint8_t *p;
905     int delta0, delta1, delta2;
906     int exp0, exp1;
907
908     bit_count = 0;
909     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
910         AC3Block *block = &s->blocks[blk];
911         for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
912             int exp_strategy = s->exp_strategy[ch][blk];
913             if (exp_strategy == EXP_REUSE)
914                 continue;
915             cpl = (ch == CPL_CH);
916             group_size = exp_strategy + (exp_strategy == EXP_D45);
917             nb_groups = exponent_group_tab[cpl][exp_strategy-1][block->end_freq[ch]-s->start_freq[ch]];
918             bit_count += 4 + (nb_groups * 7);
919             p = block->exp[ch] + s->start_freq[ch] - cpl;
920
921             /* DC exponent */
922             exp1 = *p++;
923             block->grouped_exp[ch][0] = exp1;
924
925             /* remaining exponents are delta encoded */
926             for (i = 1; i <= nb_groups; i++) {
927                 /* merge three delta in one code */
928                 exp0   = exp1;
929                 exp1   = p[0];
930                 p     += group_size;
931                 delta0 = exp1 - exp0 + 2;
932                 av_assert2(delta0 >= 0 && delta0 <= 4);
933
934                 exp0   = exp1;
935                 exp1   = p[0];
936                 p     += group_size;
937                 delta1 = exp1 - exp0 + 2;
938                 av_assert2(delta1 >= 0 && delta1 <= 4);
939
940                 exp0   = exp1;
941                 exp1   = p[0];
942                 p     += group_size;
943                 delta2 = exp1 - exp0 + 2;
944                 av_assert2(delta2 >= 0 && delta2 <= 4);
945
946                 block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
947             }
948         }
949     }
950
951     s->exponent_bits = bit_count;
952 }
953
954
955 /**
956  * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
957  * Extract exponents from MDCT coefficients, calculate exponent strategies,
958  * and encode final exponents.
959  */
960 static void process_exponents(AC3EncodeContext *s)
961 {
962     extract_exponents(s);
963
964     compute_exp_strategy(s);
965
966     encode_exponents(s);
967
968     group_exponents(s);
969
970     emms_c();
971 }
972
973
974 /**
975  * Count frame bits that are based solely on fixed parameters.
976  * This only has to be run once when the encoder is initialized.
977  */
978 static void count_frame_bits_fixed(AC3EncodeContext *s)
979 {
980     static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
981     int blk;
982     int frame_bits;
983
984     /* assumptions:
985      *   no dynamic range codes
986      *   bit allocation parameters do not change between blocks
987      *   no delta bit allocation
988      *   no skipped data
989      *   no auxilliary data
990      *   no E-AC-3 metadata
991      */
992
993     /* header */
994     frame_bits = 16; /* sync info */
995     if (s->eac3) {
996         /* bitstream info header */
997         frame_bits += 35;
998         frame_bits += 1 + 1 + 1;
999         /* audio frame header */
1000         frame_bits += 2;
1001         frame_bits += 10;
1002         /* exponent strategy */
1003         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1004             frame_bits += 2 * s->fbw_channels + s->lfe_on;
1005         /* converter exponent strategy */
1006         frame_bits += s->fbw_channels * 5;
1007         /* snr offsets */
1008         frame_bits += 10;
1009         /* block start info */
1010         frame_bits++;
1011     } else {
1012         frame_bits += 49;
1013         frame_bits += frame_bits_inc[s->channel_mode];
1014     }
1015
1016     /* audio blocks */
1017     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1018         if (!s->eac3) {
1019             /* block switch flags */
1020             frame_bits += s->fbw_channels;
1021
1022             /* dither flags */
1023             frame_bits += s->fbw_channels;
1024         }
1025
1026         /* dynamic range */
1027         frame_bits++;
1028
1029         /* spectral extension */
1030         if (s->eac3)
1031             frame_bits++;
1032
1033         if (!s->eac3) {
1034             /* exponent strategy */
1035             frame_bits += 2 * s->fbw_channels;
1036             if (s->lfe_on)
1037                 frame_bits++;
1038
1039             /* bit allocation params */
1040             frame_bits++;
1041             if (!blk)
1042                 frame_bits += 2 + 2 + 2 + 2 + 3;
1043         }
1044
1045         /* converter snr offset */
1046         if (s->eac3)
1047             frame_bits++;
1048
1049         if (!s->eac3) {
1050             /* delta bit allocation */
1051             frame_bits++;
1052
1053             /* skipped data */
1054             frame_bits++;
1055         }
1056     }
1057
1058     /* auxiliary data */
1059     frame_bits++;
1060
1061     /* CRC */
1062     frame_bits += 1 + 16;
1063
1064     s->frame_bits_fixed = frame_bits;
1065 }
1066
1067
1068 /**
1069  * Initialize bit allocation.
1070  * Set default parameter codes and calculate parameter values.
1071  */
1072 static void bit_alloc_init(AC3EncodeContext *s)
1073 {
1074     int ch;
1075
1076     /* init default parameters */
1077     s->slow_decay_code = 2;
1078     s->fast_decay_code = 1;
1079     s->slow_gain_code  = 1;
1080     s->db_per_bit_code = s->eac3 ? 2 : 3;
1081     s->floor_code      = 7;
1082     for (ch = 0; ch <= s->channels; ch++)
1083         s->fast_gain_code[ch] = 4;
1084
1085     /* initial snr offset */
1086     s->coarse_snr_offset = 40;
1087
1088     /* compute real values */
1089     /* currently none of these values change during encoding, so we can just
1090        set them once at initialization */
1091     s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
1092     s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
1093     s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
1094     s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
1095     s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
1096     s->bit_alloc.cpl_fast_leak = 0;
1097     s->bit_alloc.cpl_slow_leak = 0;
1098
1099     count_frame_bits_fixed(s);
1100 }
1101
1102
1103 /**
1104  * Count the bits used to encode the frame, minus exponents and mantissas.
1105  * Bits based on fixed parameters have already been counted, so now we just
1106  * have to add the bits based on parameters that change during encoding.
1107  */
1108 static void count_frame_bits(AC3EncodeContext *s)
1109 {
1110     AC3EncOptions *opt = &s->options;
1111     int blk, ch;
1112     int frame_bits = 0;
1113
1114     /* header */
1115     if (s->eac3) {
1116         /* coupling */
1117         if (s->channel_mode > AC3_CHMODE_MONO) {
1118             frame_bits++;
1119             for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
1120                 AC3Block *block = &s->blocks[blk];
1121                 frame_bits++;
1122                 if (block->new_cpl_strategy)
1123                     frame_bits++;
1124             }
1125         }
1126         /* coupling exponent strategy */
1127         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1128             frame_bits += 2 * s->blocks[blk].cpl_in_use;
1129     } else {
1130         if (opt->audio_production_info)
1131             frame_bits += 7;
1132         if (s->bitstream_id == 6) {
1133             if (opt->extended_bsi_1)
1134                 frame_bits += 14;
1135             if (opt->extended_bsi_2)
1136                 frame_bits += 14;
1137         }
1138     }
1139
1140     /* audio blocks */
1141     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1142         AC3Block *block = &s->blocks[blk];
1143
1144         /* coupling strategy */
1145         if (!s->eac3)
1146             frame_bits++;
1147         if (block->new_cpl_strategy) {
1148             if (!s->eac3)
1149                 frame_bits++;
1150             if (block->cpl_in_use) {
1151                 if (s->eac3)
1152                     frame_bits++;
1153                 if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO)
1154                     frame_bits += s->fbw_channels;
1155                 if (s->channel_mode == AC3_CHMODE_STEREO)
1156                     frame_bits++;
1157                 frame_bits += 4 + 4;
1158                 if (s->eac3)
1159                     frame_bits++;
1160                 else
1161                     frame_bits += s->num_cpl_subbands - 1;
1162             }
1163         }
1164
1165         /* coupling coordinates */
1166         if (block->cpl_in_use) {
1167             for (ch = 1; ch <= s->fbw_channels; ch++) {
1168                 if (block->channel_in_cpl[ch]) {
1169                     if (!s->eac3 || block->new_cpl_coords != 2)
1170                         frame_bits++;
1171                     if (block->new_cpl_coords) {
1172                         frame_bits += 2;
1173                         frame_bits += (4 + 4) * s->num_cpl_bands;
1174                     }
1175                 }
1176             }
1177         }
1178
1179         /* stereo rematrixing */
1180         if (s->channel_mode == AC3_CHMODE_STEREO) {
1181             if (!s->eac3 || blk > 0)
1182                 frame_bits++;
1183             if (s->blocks[blk].new_rematrixing_strategy)
1184                 frame_bits += block->num_rematrixing_bands;
1185         }
1186
1187         /* bandwidth codes & gain range */
1188         for (ch = 1; ch <= s->fbw_channels; ch++) {
1189             if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1190                 if (!block->channel_in_cpl[ch])
1191                     frame_bits += 6;
1192                 frame_bits += 2;
1193             }
1194         }
1195
1196         /* coupling exponent strategy */
1197         if (!s->eac3 && block->cpl_in_use)
1198             frame_bits += 2;
1199
1200         /* snr offsets and fast gain codes */
1201         if (!s->eac3) {
1202             frame_bits++;
1203             if (block->new_snr_offsets)
1204                 frame_bits += 6 + (s->channels + block->cpl_in_use) * (4 + 3);
1205         }
1206
1207         /* coupling leak info */
1208         if (block->cpl_in_use) {
1209             if (!s->eac3 || block->new_cpl_leak != 2)
1210                 frame_bits++;
1211             if (block->new_cpl_leak)
1212                 frame_bits += 3 + 3;
1213         }
1214     }
1215
1216     s->frame_bits = s->frame_bits_fixed + frame_bits;
1217 }
1218
1219
1220 /**
1221  * Calculate masking curve based on the final exponents.
1222  * Also calculate the power spectral densities to use in future calculations.
1223  */
1224 static void bit_alloc_masking(AC3EncodeContext *s)
1225 {
1226     int blk, ch;
1227
1228     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1229         AC3Block *block = &s->blocks[blk];
1230         for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1231             /* We only need psd and mask for calculating bap.
1232                Since we currently do not calculate bap when exponent
1233                strategy is EXP_REUSE we do not need to calculate psd or mask. */
1234             if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1235                 ff_ac3_bit_alloc_calc_psd(block->exp[ch], s->start_freq[ch],
1236                                           block->end_freq[ch], block->psd[ch],
1237                                           block->band_psd[ch]);
1238                 ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
1239                                            s->start_freq[ch], block->end_freq[ch],
1240                                            ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
1241                                            ch == s->lfe_channel,
1242                                            DBA_NONE, 0, NULL, NULL, NULL,
1243                                            block->mask[ch]);
1244             }
1245         }
1246     }
1247 }
1248
1249
1250 /**
1251  * Ensure that bap for each block and channel point to the current bap_buffer.
1252  * They may have been switched during the bit allocation search.
1253  */
1254 static void reset_block_bap(AC3EncodeContext *s)
1255 {
1256     int blk, ch;
1257     uint8_t *ref_bap;
1258
1259     if (s->ref_bap[0][0] == s->bap_buffer && s->ref_bap_set)
1260         return;
1261
1262     ref_bap = s->bap_buffer;
1263     for (ch = 0; ch <= s->channels; ch++) {
1264         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1265             s->ref_bap[ch][blk] = ref_bap + AC3_MAX_COEFS * s->exp_ref_block[ch][blk];
1266         ref_bap += AC3_MAX_COEFS * AC3_MAX_BLOCKS;
1267     }
1268     s->ref_bap_set = 1;
1269 }
1270
1271
1272 /**
1273  * Initialize mantissa counts.
1274  * These are set so that they are padded to the next whole group size when bits
1275  * are counted in compute_mantissa_size.
1276  */
1277 static void count_mantissa_bits_init(uint16_t mant_cnt[AC3_MAX_BLOCKS][16])
1278 {
1279     int blk;
1280
1281     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1282         memset(mant_cnt[blk], 0, sizeof(mant_cnt[blk]));
1283         mant_cnt[blk][1] = mant_cnt[blk][2] = 2;
1284         mant_cnt[blk][4] = 1;
1285     }
1286 }
1287
1288
1289 /**
1290  * Update mantissa bit counts for all blocks in 1 channel in a given bandwidth
1291  * range.
1292  */
1293 static void count_mantissa_bits_update_ch(AC3EncodeContext *s, int ch,
1294                                           uint16_t mant_cnt[AC3_MAX_BLOCKS][16],
1295                                           int start, int end)
1296 {
1297     int blk;
1298
1299     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1300         AC3Block *block = &s->blocks[blk];
1301         if (ch == CPL_CH && !block->cpl_in_use)
1302             continue;
1303         s->ac3dsp.update_bap_counts(mant_cnt[blk],
1304                                     s->ref_bap[ch][blk] + start,
1305                                     FFMIN(end, block->end_freq[ch]) - start);
1306     }
1307 }
1308
1309
1310 /**
1311  * Count the number of mantissa bits in the frame based on the bap values.
1312  */
1313 static int count_mantissa_bits(AC3EncodeContext *s)
1314 {
1315     int ch, max_end_freq;
1316     LOCAL_ALIGNED_16(uint16_t, mant_cnt, [AC3_MAX_BLOCKS], [16]);
1317
1318     count_mantissa_bits_init(mant_cnt);
1319
1320     max_end_freq = s->bandwidth_code * 3 + 73;
1321     for (ch = !s->cpl_enabled; ch <= s->channels; ch++)
1322         count_mantissa_bits_update_ch(s, ch, mant_cnt, s->start_freq[ch],
1323                                       max_end_freq);
1324
1325     return s->ac3dsp.compute_mantissa_size(mant_cnt);
1326 }
1327
1328
1329 /**
1330  * Run the bit allocation with a given SNR offset.
1331  * This calculates the bit allocation pointers that will be used to determine
1332  * the quantization of each mantissa.
1333  * @return the number of bits needed for mantissas if the given SNR offset is
1334  *         is used.
1335  */
1336 static int bit_alloc(AC3EncodeContext *s, int snr_offset)
1337 {
1338     int blk, ch;
1339
1340     snr_offset = (snr_offset - 240) << 2;
1341
1342     reset_block_bap(s);
1343     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1344         AC3Block *block = &s->blocks[blk];
1345
1346         for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1347             /* Currently the only bit allocation parameters which vary across
1348                blocks within a frame are the exponent values.  We can take
1349                advantage of that by reusing the bit allocation pointers
1350                whenever we reuse exponents. */
1351             if (s->exp_strategy[ch][blk] != EXP_REUSE) {
1352                 s->ac3dsp.bit_alloc_calc_bap(block->mask[ch], block->psd[ch],
1353                                              s->start_freq[ch], block->end_freq[ch],
1354                                              snr_offset, s->bit_alloc.floor,
1355                                              ff_ac3_bap_tab, s->ref_bap[ch][blk]);
1356             }
1357         }
1358     }
1359     return count_mantissa_bits(s);
1360 }
1361
1362
1363 /**
1364  * Constant bitrate bit allocation search.
1365  * Find the largest SNR offset that will allow data to fit in the frame.
1366  */
1367 static int cbr_bit_allocation(AC3EncodeContext *s)
1368 {
1369     int ch;
1370     int bits_left;
1371     int snr_offset, snr_incr;
1372
1373     bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
1374     if (bits_left < 0)
1375         return AVERROR(EINVAL);
1376
1377     snr_offset = s->coarse_snr_offset << 4;
1378
1379     /* if previous frame SNR offset was 1023, check if current frame can also
1380        use SNR offset of 1023. if so, skip the search. */
1381     if ((snr_offset | s->fine_snr_offset[1]) == 1023) {
1382         if (bit_alloc(s, 1023) <= bits_left)
1383             return 0;
1384     }
1385
1386     while (snr_offset >= 0 &&
1387            bit_alloc(s, snr_offset) > bits_left) {
1388         snr_offset -= 64;
1389     }
1390     if (snr_offset < 0)
1391         return AVERROR(EINVAL);
1392
1393     FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1394     for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
1395         while (snr_offset + snr_incr <= 1023 &&
1396                bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
1397             snr_offset += snr_incr;
1398             FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1399         }
1400     }
1401     FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
1402     reset_block_bap(s);
1403
1404     s->coarse_snr_offset = snr_offset >> 4;
1405     for (ch = !s->cpl_on; ch <= s->channels; ch++)
1406         s->fine_snr_offset[ch] = snr_offset & 0xF;
1407
1408     return 0;
1409 }
1410
1411
1412 /**
1413  * Downgrade exponent strategies to reduce the bits used by the exponents.
1414  * This is a fallback for when bit allocation fails with the normal exponent
1415  * strategies.  Each time this function is run it only downgrades the
1416  * strategy in 1 channel of 1 block.
1417  * @return non-zero if downgrade was unsuccessful
1418  */
1419 static int downgrade_exponents(AC3EncodeContext *s)
1420 {
1421     int ch, blk;
1422
1423     for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1424         for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
1425             if (s->exp_strategy[ch][blk] == EXP_D15) {
1426                 s->exp_strategy[ch][blk] = EXP_D25;
1427                 return 0;
1428             }
1429         }
1430     }
1431     for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
1432         for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
1433             if (s->exp_strategy[ch][blk] == EXP_D25) {
1434                 s->exp_strategy[ch][blk] = EXP_D45;
1435                 return 0;
1436             }
1437         }
1438     }
1439     /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
1440        the block number > 0 */
1441     for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
1442         for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
1443             if (s->exp_strategy[ch][blk] > EXP_REUSE) {
1444                 s->exp_strategy[ch][blk] = EXP_REUSE;
1445                 return 0;
1446             }
1447         }
1448     }
1449     return -1;
1450 }
1451
1452
1453 /**
1454  * Perform bit allocation search.
1455  * Finds the SNR offset value that maximizes quality and fits in the specified
1456  * frame size.  Output is the SNR offset and a set of bit allocation pointers
1457  * used to quantize the mantissas.
1458  */
1459 static int compute_bit_allocation(AC3EncodeContext *s)
1460 {
1461     int ret;
1462
1463     count_frame_bits(s);
1464
1465     bit_alloc_masking(s);
1466
1467     ret = cbr_bit_allocation(s);
1468     while (ret) {
1469         /* fallback 1: disable channel coupling */
1470         if (s->cpl_on) {
1471             s->cpl_on = 0;
1472             compute_coupling_strategy(s);
1473             compute_rematrixing_strategy(s);
1474             apply_rematrixing(s);
1475             process_exponents(s);
1476             ret = compute_bit_allocation(s);
1477             continue;
1478         }
1479
1480         /* fallback 2: downgrade exponents */
1481         if (!downgrade_exponents(s)) {
1482             extract_exponents(s);
1483             encode_exponents(s);
1484             group_exponents(s);
1485             ret = compute_bit_allocation(s);
1486             continue;
1487         }
1488
1489         /* fallbacks were not enough... */
1490         break;
1491     }
1492
1493     return ret;
1494 }
1495
1496
1497 /**
1498  * Symmetric quantization on 'levels' levels.
1499  */
1500 static inline int sym_quant(int c, int e, int levels)
1501 {
1502     int v = (((levels * c) >> (24 - e)) + levels) >> 1;
1503     av_assert2(v >= 0 && v < levels);
1504     return v;
1505 }
1506
1507
1508 /**
1509  * Asymmetric quantization on 2^qbits levels.
1510  */
1511 static inline int asym_quant(int c, int e, int qbits)
1512 {
1513     int lshift, m, v;
1514
1515     lshift = e + qbits - 24;
1516     if (lshift >= 0)
1517         v = c << lshift;
1518     else
1519         v = c >> (-lshift);
1520     /* rounding */
1521     v = (v + 1) >> 1;
1522     m = (1 << (qbits-1));
1523     if (v >= m)
1524         v = m - 1;
1525     av_assert2(v >= -m);
1526     return v & ((1 << qbits)-1);
1527 }
1528
1529
1530 /**
1531  * Quantize a set of mantissas for a single channel in a single block.
1532  */
1533 static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
1534                                       uint8_t *exp, uint8_t *bap,
1535                                       uint16_t *qmant, int start_freq,
1536                                       int end_freq)
1537 {
1538     int i;
1539
1540     for (i = start_freq; i < end_freq; i++) {
1541         int v;
1542         int c = fixed_coef[i];
1543         int e = exp[i];
1544         int b = bap[i];
1545         switch (b) {
1546         case 0:
1547             v = 0;
1548             break;
1549         case 1:
1550             v = sym_quant(c, e, 3);
1551             switch (s->mant1_cnt) {
1552             case 0:
1553                 s->qmant1_ptr = &qmant[i];
1554                 v = 9 * v;
1555                 s->mant1_cnt = 1;
1556                 break;
1557             case 1:
1558                 *s->qmant1_ptr += 3 * v;
1559                 s->mant1_cnt = 2;
1560                 v = 128;
1561                 break;
1562             default:
1563                 *s->qmant1_ptr += v;
1564                 s->mant1_cnt = 0;
1565                 v = 128;
1566                 break;
1567             }
1568             break;
1569         case 2:
1570             v = sym_quant(c, e, 5);
1571             switch (s->mant2_cnt) {
1572             case 0:
1573                 s->qmant2_ptr = &qmant[i];
1574                 v = 25 * v;
1575                 s->mant2_cnt = 1;
1576                 break;
1577             case 1:
1578                 *s->qmant2_ptr += 5 * v;
1579                 s->mant2_cnt = 2;
1580                 v = 128;
1581                 break;
1582             default:
1583                 *s->qmant2_ptr += v;
1584                 s->mant2_cnt = 0;
1585                 v = 128;
1586                 break;
1587             }
1588             break;
1589         case 3:
1590             v = sym_quant(c, e, 7);
1591             break;
1592         case 4:
1593             v = sym_quant(c, e, 11);
1594             switch (s->mant4_cnt) {
1595             case 0:
1596                 s->qmant4_ptr = &qmant[i];
1597                 v = 11 * v;
1598                 s->mant4_cnt = 1;
1599                 break;
1600             default:
1601                 *s->qmant4_ptr += v;
1602                 s->mant4_cnt = 0;
1603                 v = 128;
1604                 break;
1605             }
1606             break;
1607         case 5:
1608             v = sym_quant(c, e, 15);
1609             break;
1610         case 14:
1611             v = asym_quant(c, e, 14);
1612             break;
1613         case 15:
1614             v = asym_quant(c, e, 16);
1615             break;
1616         default:
1617             v = asym_quant(c, e, b - 1);
1618             break;
1619         }
1620         qmant[i] = v;
1621     }
1622 }
1623
1624
1625 /**
1626  * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
1627  */
1628 static void quantize_mantissas(AC3EncodeContext *s)
1629 {
1630     int blk, ch, ch0=0, got_cpl;
1631
1632     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
1633         AC3Block *block = &s->blocks[blk];
1634         AC3Mant m = { 0 };
1635
1636         got_cpl = !block->cpl_in_use;
1637         for (ch = 1; ch <= s->channels; ch++) {
1638             if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1639                 ch0     = ch - 1;
1640                 ch      = CPL_CH;
1641                 got_cpl = 1;
1642             }
1643             quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
1644                                       s->blocks[s->exp_ref_block[ch][blk]].exp[ch],
1645                                       s->ref_bap[ch][blk], block->qmant[ch],
1646                                       s->start_freq[ch], block->end_freq[ch]);
1647             if (ch == CPL_CH)
1648                 ch = ch0;
1649         }
1650     }
1651 }
1652
1653
1654 /**
1655  * Write the AC-3 frame header to the output bitstream.
1656  */
1657 static void ac3_output_frame_header(AC3EncodeContext *s)
1658 {
1659     AC3EncOptions *opt = &s->options;
1660
1661     put_bits(&s->pb, 16, 0x0b77);   /* frame header */
1662     put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
1663     put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
1664     put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
1665     put_bits(&s->pb, 5,  s->bitstream_id);
1666     put_bits(&s->pb, 3,  s->bitstream_mode);
1667     put_bits(&s->pb, 3,  s->channel_mode);
1668     if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
1669         put_bits(&s->pb, 2, s->center_mix_level);
1670     if (s->channel_mode & 0x04)
1671         put_bits(&s->pb, 2, s->surround_mix_level);
1672     if (s->channel_mode == AC3_CHMODE_STEREO)
1673         put_bits(&s->pb, 2, opt->dolby_surround_mode);
1674     put_bits(&s->pb, 1, s->lfe_on); /* LFE */
1675     put_bits(&s->pb, 5, -opt->dialogue_level);
1676     put_bits(&s->pb, 1, 0);         /* no compression control word */
1677     put_bits(&s->pb, 1, 0);         /* no lang code */
1678     put_bits(&s->pb, 1, opt->audio_production_info);
1679     if (opt->audio_production_info) {
1680         put_bits(&s->pb, 5, opt->mixing_level - 80);
1681         put_bits(&s->pb, 2, opt->room_type);
1682     }
1683     put_bits(&s->pb, 1, opt->copyright);
1684     put_bits(&s->pb, 1, opt->original);
1685     if (s->bitstream_id == 6) {
1686         /* alternate bit stream syntax */
1687         put_bits(&s->pb, 1, opt->extended_bsi_1);
1688         if (opt->extended_bsi_1) {
1689             put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
1690             put_bits(&s->pb, 3, s->ltrt_center_mix_level);
1691             put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
1692             put_bits(&s->pb, 3, s->loro_center_mix_level);
1693             put_bits(&s->pb, 3, s->loro_surround_mix_level);
1694         }
1695         put_bits(&s->pb, 1, opt->extended_bsi_2);
1696         if (opt->extended_bsi_2) {
1697             put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
1698             put_bits(&s->pb, 2, opt->dolby_headphone_mode);
1699             put_bits(&s->pb, 1, opt->ad_converter_type);
1700             put_bits(&s->pb, 9, 0);     /* xbsi2 and encinfo : reserved */
1701         }
1702     } else {
1703     put_bits(&s->pb, 1, 0);         /* no time code 1 */
1704     put_bits(&s->pb, 1, 0);         /* no time code 2 */
1705     }
1706     put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
1707 }
1708
1709
1710 /**
1711  * Write one audio block to the output bitstream.
1712  */
1713 static void output_audio_block(AC3EncodeContext *s, int blk)
1714 {
1715     int ch, i, baie, bnd, got_cpl;
1716     int av_uninit(ch0);
1717     AC3Block *block = &s->blocks[blk];
1718
1719     /* block switching */
1720     if (!s->eac3) {
1721         for (ch = 0; ch < s->fbw_channels; ch++)
1722             put_bits(&s->pb, 1, 0);
1723     }
1724
1725     /* dither flags */
1726     if (!s->eac3) {
1727         for (ch = 0; ch < s->fbw_channels; ch++)
1728             put_bits(&s->pb, 1, 1);
1729     }
1730
1731     /* dynamic range codes */
1732     put_bits(&s->pb, 1, 0);
1733
1734     /* spectral extension */
1735     if (s->eac3)
1736         put_bits(&s->pb, 1, 0);
1737
1738     /* channel coupling */
1739     if (!s->eac3)
1740         put_bits(&s->pb, 1, block->new_cpl_strategy);
1741     if (block->new_cpl_strategy) {
1742         if (!s->eac3)
1743             put_bits(&s->pb, 1, block->cpl_in_use);
1744         if (block->cpl_in_use) {
1745             int start_sub, end_sub;
1746             if (s->eac3)
1747                 put_bits(&s->pb, 1, 0); /* enhanced coupling */
1748             if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO) {
1749                 for (ch = 1; ch <= s->fbw_channels; ch++)
1750                     put_bits(&s->pb, 1, block->channel_in_cpl[ch]);
1751             }
1752             if (s->channel_mode == AC3_CHMODE_STEREO)
1753                 put_bits(&s->pb, 1, 0); /* phase flags in use */
1754             start_sub = (s->start_freq[CPL_CH] - 37) / 12;
1755             end_sub   = (s->cpl_end_freq       - 37) / 12;
1756             put_bits(&s->pb, 4, start_sub);
1757             put_bits(&s->pb, 4, end_sub - 3);
1758             /* coupling band structure */
1759             if (s->eac3) {
1760                 put_bits(&s->pb, 1, 0); /* use default */
1761             } else {
1762                 for (bnd = start_sub+1; bnd < end_sub; bnd++)
1763                     put_bits(&s->pb, 1, ff_eac3_default_cpl_band_struct[bnd]);
1764             }
1765         }
1766     }
1767
1768     /* coupling coordinates */
1769     if (block->cpl_in_use) {
1770         for (ch = 1; ch <= s->fbw_channels; ch++) {
1771             if (block->channel_in_cpl[ch]) {
1772                 if (!s->eac3 || block->new_cpl_coords != 2)
1773                     put_bits(&s->pb, 1, block->new_cpl_coords);
1774                 if (block->new_cpl_coords) {
1775                     put_bits(&s->pb, 2, block->cpl_master_exp[ch]);
1776                     for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
1777                         put_bits(&s->pb, 4, block->cpl_coord_exp [ch][bnd]);
1778                         put_bits(&s->pb, 4, block->cpl_coord_mant[ch][bnd]);
1779                     }
1780                 }
1781             }
1782         }
1783     }
1784
1785     /* stereo rematrixing */
1786     if (s->channel_mode == AC3_CHMODE_STEREO) {
1787         if (!s->eac3 || blk > 0)
1788             put_bits(&s->pb, 1, block->new_rematrixing_strategy);
1789         if (block->new_rematrixing_strategy) {
1790             /* rematrixing flags */
1791             for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++)
1792                 put_bits(&s->pb, 1, block->rematrixing_flags[bnd]);
1793         }
1794     }
1795
1796     /* exponent strategy */
1797     if (!s->eac3) {
1798         for (ch = !block->cpl_in_use; ch <= s->fbw_channels; ch++)
1799             put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
1800         if (s->lfe_on)
1801             put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
1802     }
1803
1804     /* bandwidth */
1805     for (ch = 1; ch <= s->fbw_channels; ch++) {
1806         if (s->exp_strategy[ch][blk] != EXP_REUSE && !block->channel_in_cpl[ch])
1807             put_bits(&s->pb, 6, s->bandwidth_code);
1808     }
1809
1810     /* exponents */
1811     for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1812         int nb_groups;
1813         int cpl = (ch == CPL_CH);
1814
1815         if (s->exp_strategy[ch][blk] == EXP_REUSE)
1816             continue;
1817
1818         /* DC exponent */
1819         put_bits(&s->pb, 4, block->grouped_exp[ch][0] >> cpl);
1820
1821         /* exponent groups */
1822         nb_groups = exponent_group_tab[cpl][s->exp_strategy[ch][blk]-1][block->end_freq[ch]-s->start_freq[ch]];
1823         for (i = 1; i <= nb_groups; i++)
1824             put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
1825
1826         /* gain range info */
1827         if (ch != s->lfe_channel && !cpl)
1828             put_bits(&s->pb, 2, 0);
1829     }
1830
1831     /* bit allocation info */
1832     if (!s->eac3) {
1833         baie = (blk == 0);
1834         put_bits(&s->pb, 1, baie);
1835         if (baie) {
1836             put_bits(&s->pb, 2, s->slow_decay_code);
1837             put_bits(&s->pb, 2, s->fast_decay_code);
1838             put_bits(&s->pb, 2, s->slow_gain_code);
1839             put_bits(&s->pb, 2, s->db_per_bit_code);
1840             put_bits(&s->pb, 3, s->floor_code);
1841         }
1842     }
1843
1844     /* snr offset */
1845     if (!s->eac3) {
1846         put_bits(&s->pb, 1, block->new_snr_offsets);
1847         if (block->new_snr_offsets) {
1848             put_bits(&s->pb, 6, s->coarse_snr_offset);
1849             for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
1850                 put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
1851                 put_bits(&s->pb, 3, s->fast_gain_code[ch]);
1852             }
1853         }
1854     } else {
1855         put_bits(&s->pb, 1, 0); /* no converter snr offset */
1856     }
1857
1858     /* coupling leak */
1859     if (block->cpl_in_use) {
1860         if (!s->eac3 || block->new_cpl_leak != 2)
1861             put_bits(&s->pb, 1, block->new_cpl_leak);
1862         if (block->new_cpl_leak) {
1863             put_bits(&s->pb, 3, s->bit_alloc.cpl_fast_leak);
1864             put_bits(&s->pb, 3, s->bit_alloc.cpl_slow_leak);
1865         }
1866     }
1867
1868     if (!s->eac3) {
1869         put_bits(&s->pb, 1, 0); /* no delta bit allocation */
1870         put_bits(&s->pb, 1, 0); /* no data to skip */
1871     }
1872
1873     /* mantissas */
1874     got_cpl = !block->cpl_in_use;
1875     for (ch = 1; ch <= s->channels; ch++) {
1876         int b, q;
1877
1878         if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
1879             ch0     = ch - 1;
1880             ch      = CPL_CH;
1881             got_cpl = 1;
1882         }
1883         for (i = s->start_freq[ch]; i < block->end_freq[ch]; i++) {
1884             q = block->qmant[ch][i];
1885             b = s->ref_bap[ch][blk][i];
1886             switch (b) {
1887             case 0:                                         break;
1888             case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
1889             case 2: if (q != 128) put_bits(&s->pb,   7, q); break;
1890             case 3:               put_bits(&s->pb,   3, q); break;
1891             case 4: if (q != 128) put_bits(&s->pb,   7, q); break;
1892             case 14:              put_bits(&s->pb,  14, q); break;
1893             case 15:              put_bits(&s->pb,  16, q); break;
1894             default:              put_bits(&s->pb, b-1, q); break;
1895             }
1896         }
1897         if (ch == CPL_CH)
1898             ch = ch0;
1899     }
1900 }
1901
1902
1903 /** CRC-16 Polynomial */
1904 #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
1905
1906
1907 static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
1908 {
1909     unsigned int c;
1910
1911     c = 0;
1912     while (a) {
1913         if (a & 1)
1914             c ^= b;
1915         a = a >> 1;
1916         b = b << 1;
1917         if (b & (1 << 16))
1918             b ^= poly;
1919     }
1920     return c;
1921 }
1922
1923
1924 static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
1925 {
1926     unsigned int r;
1927     r = 1;
1928     while (n) {
1929         if (n & 1)
1930             r = mul_poly(r, a, poly);
1931         a = mul_poly(a, a, poly);
1932         n >>= 1;
1933     }
1934     return r;
1935 }
1936
1937
1938 /**
1939  * Fill the end of the frame with 0's and compute the two CRCs.
1940  */
1941 static void output_frame_end(AC3EncodeContext *s)
1942 {
1943     const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
1944     int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
1945     uint8_t *frame;
1946
1947     frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
1948
1949     /* pad the remainder of the frame with zeros */
1950     av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
1951     flush_put_bits(&s->pb);
1952     frame = s->pb.buf;
1953     pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
1954     av_assert2(pad_bytes >= 0);
1955     if (pad_bytes > 0)
1956         memset(put_bits_ptr(&s->pb), 0, pad_bytes);
1957
1958     if (s->eac3) {
1959         /* compute crc2 */
1960         crc2_partial = av_crc(crc_ctx, 0, frame + 2, s->frame_size - 5);
1961     } else {
1962     /* compute crc1 */
1963     /* this is not so easy because it is at the beginning of the data... */
1964     crc1    = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
1965     crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
1966     crc1    = mul_poly(crc_inv, crc1, CRC16_POLY);
1967     AV_WB16(frame + 2, crc1);
1968
1969     /* compute crc2 */
1970     crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
1971                           s->frame_size - frame_size_58 - 3);
1972     }
1973     crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1974     /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
1975     if (crc2 == 0x770B) {
1976         frame[s->frame_size - 3] ^= 0x1;
1977         crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
1978     }
1979     crc2 = av_bswap16(crc2);
1980     AV_WB16(frame + s->frame_size - 2, crc2);
1981 }
1982
1983
1984 /**
1985  * Write the frame to the output bitstream.
1986  */
1987 static void output_frame(AC3EncodeContext *s, unsigned char *frame)
1988 {
1989     int blk;
1990
1991     init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
1992
1993     if (CONFIG_EAC3_ENCODER && s->eac3)
1994         ff_eac3_output_frame_header(s);
1995     else
1996         ac3_output_frame_header(s);
1997
1998     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
1999         output_audio_block(s, blk);
2000
2001     output_frame_end(s);
2002 }
2003
2004
2005 static void dprint_options(AVCodecContext *avctx)
2006 {
2007 #ifdef DEBUG
2008     AC3EncodeContext *s = avctx->priv_data;
2009     AC3EncOptions *opt = &s->options;
2010     char strbuf[32];
2011
2012     switch (s->bitstream_id) {
2013     case  6:  av_strlcpy(strbuf, "AC-3 (alt syntax)",       32); break;
2014     case  8:  av_strlcpy(strbuf, "AC-3 (standard)",         32); break;
2015     case  9:  av_strlcpy(strbuf, "AC-3 (dnet half-rate)",   32); break;
2016     case 10:  av_strlcpy(strbuf, "AC-3 (dnet quater-rate)", 32); break;
2017     case 16:  av_strlcpy(strbuf, "E-AC-3 (enhanced)",       32); break;
2018     default: snprintf(strbuf, 32, "ERROR");
2019     }
2020     av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
2021     av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
2022     av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
2023     av_dlog(avctx, "channel_layout: %s\n", strbuf);
2024     av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
2025     av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
2026     if (s->cutoff)
2027         av_dlog(avctx, "cutoff: %d\n", s->cutoff);
2028
2029     av_dlog(avctx, "per_frame_metadata: %s\n",
2030             opt->allow_per_frame_metadata?"on":"off");
2031     if (s->has_center)
2032         av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
2033                 s->center_mix_level);
2034     else
2035         av_dlog(avctx, "center_mixlev: {not written}\n");
2036     if (s->has_surround)
2037         av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
2038                 s->surround_mix_level);
2039     else
2040         av_dlog(avctx, "surround_mixlev: {not written}\n");
2041     if (opt->audio_production_info) {
2042         av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
2043         switch (opt->room_type) {
2044         case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
2045         case 1:  av_strlcpy(strbuf, "large", 32);        break;
2046         case 2:  av_strlcpy(strbuf, "small", 32);        break;
2047         default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
2048         }
2049         av_dlog(avctx, "room_type: %s\n", strbuf);
2050     } else {
2051         av_dlog(avctx, "mixing_level: {not written}\n");
2052         av_dlog(avctx, "room_type: {not written}\n");
2053     }
2054     av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
2055     av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
2056     if (s->channel_mode == AC3_CHMODE_STEREO) {
2057         switch (opt->dolby_surround_mode) {
2058         case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
2059         case 1:  av_strlcpy(strbuf, "on", 32);           break;
2060         case 2:  av_strlcpy(strbuf, "off", 32);          break;
2061         default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
2062         }
2063         av_dlog(avctx, "dsur_mode: %s\n", strbuf);
2064     } else {
2065         av_dlog(avctx, "dsur_mode: {not written}\n");
2066     }
2067     av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
2068
2069     if (s->bitstream_id == 6) {
2070         if (opt->extended_bsi_1) {
2071             switch (opt->preferred_stereo_downmix) {
2072             case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
2073             case 1:  av_strlcpy(strbuf, "ltrt", 32);         break;
2074             case 2:  av_strlcpy(strbuf, "loro", 32);         break;
2075             default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
2076             }
2077             av_dlog(avctx, "dmix_mode: %s\n", strbuf);
2078             av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
2079                     opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
2080             av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
2081                     opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
2082             av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
2083                     opt->loro_center_mix_level, s->loro_center_mix_level);
2084             av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
2085                     opt->loro_surround_mix_level, s->loro_surround_mix_level);
2086         } else {
2087             av_dlog(avctx, "extended bitstream info 1: {not written}\n");
2088         }
2089         if (opt->extended_bsi_2) {
2090             switch (opt->dolby_surround_ex_mode) {
2091             case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
2092             case 1:  av_strlcpy(strbuf, "on", 32);           break;
2093             case 2:  av_strlcpy(strbuf, "off", 32);          break;
2094             default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
2095             }
2096             av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
2097             switch (opt->dolby_headphone_mode) {
2098             case 0:  av_strlcpy(strbuf, "notindicated", 32); break;
2099             case 1:  av_strlcpy(strbuf, "on", 32);           break;
2100             case 2:  av_strlcpy(strbuf, "off", 32);          break;
2101             default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
2102             }
2103             av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
2104
2105             switch (opt->ad_converter_type) {
2106             case 0:  av_strlcpy(strbuf, "standard", 32); break;
2107             case 1:  av_strlcpy(strbuf, "hdcd", 32);     break;
2108             default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
2109             }
2110             av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
2111         } else {
2112             av_dlog(avctx, "extended bitstream info 2: {not written}\n");
2113         }
2114     }
2115 #endif
2116 }
2117
2118
2119 #define FLT_OPTION_THRESHOLD 0.01
2120
2121 static int validate_float_option(float v, const float *v_list, int v_list_size)
2122 {
2123     int i;
2124
2125     for (i = 0; i < v_list_size; i++) {
2126         if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
2127             v > (v_list[i] - FLT_OPTION_THRESHOLD))
2128             break;
2129     }
2130     if (i == v_list_size)
2131         return -1;
2132
2133     return i;
2134 }
2135
2136
2137 static void validate_mix_level(void *log_ctx, const char *opt_name,
2138                                float *opt_param, const float *list,
2139                                int list_size, int default_value, int min_value,
2140                                int *ctx_param)
2141 {
2142     int mixlev = validate_float_option(*opt_param, list, list_size);
2143     if (mixlev < min_value) {
2144         mixlev = default_value;
2145         if (*opt_param >= 0.0) {
2146             av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
2147                    "default value: %0.3f\n", opt_name, list[mixlev]);
2148         }
2149     }
2150     *opt_param = list[mixlev];
2151     *ctx_param = mixlev;
2152 }
2153
2154
2155 /**
2156  * Validate metadata options as set by AVOption system.
2157  * These values can optionally be changed per-frame.
2158  */
2159 static int validate_metadata(AVCodecContext *avctx)
2160 {
2161     AC3EncodeContext *s = avctx->priv_data;
2162     AC3EncOptions *opt = &s->options;
2163
2164     /* validate mixing levels */
2165     if (s->has_center) {
2166         validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
2167                            cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
2168                            &s->center_mix_level);
2169     }
2170     if (s->has_surround) {
2171         validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
2172                            surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
2173                            &s->surround_mix_level);
2174     }
2175
2176     /* set audio production info flag */
2177     if (opt->mixing_level >= 0 || opt->room_type >= 0) {
2178         if (opt->mixing_level < 0) {
2179             av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
2180                    "room_type is set\n");
2181             return AVERROR(EINVAL);
2182         }
2183         if (opt->mixing_level < 80) {
2184             av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
2185                    "80dB and 111dB\n");
2186             return AVERROR(EINVAL);
2187         }
2188         /* default room type */
2189         if (opt->room_type < 0)
2190             opt->room_type = 0;
2191         opt->audio_production_info = 1;
2192     } else {
2193         opt->audio_production_info = 0;
2194     }
2195
2196     /* set extended bsi 1 flag */
2197     if ((s->has_center || s->has_surround) &&
2198         (opt->preferred_stereo_downmix >= 0 ||
2199          opt->ltrt_center_mix_level   >= 0 ||
2200          opt->ltrt_surround_mix_level >= 0 ||
2201          opt->loro_center_mix_level   >= 0 ||
2202          opt->loro_surround_mix_level >= 0)) {
2203         /* default preferred stereo downmix */
2204         if (opt->preferred_stereo_downmix < 0)
2205             opt->preferred_stereo_downmix = 0;
2206         /* validate Lt/Rt center mix level */
2207         validate_mix_level(avctx, "ltrt_center_mix_level",
2208                            &opt->ltrt_center_mix_level, extmixlev_options,
2209                            EXTMIXLEV_NUM_OPTIONS, 5, 0,
2210                            &s->ltrt_center_mix_level);
2211         /* validate Lt/Rt surround mix level */
2212         validate_mix_level(avctx, "ltrt_surround_mix_level",
2213                            &opt->ltrt_surround_mix_level, extmixlev_options,
2214                            EXTMIXLEV_NUM_OPTIONS, 6, 3,
2215                            &s->ltrt_surround_mix_level);
2216         /* validate Lo/Ro center mix level */
2217         validate_mix_level(avctx, "loro_center_mix_level",
2218                            &opt->loro_center_mix_level, extmixlev_options,
2219                            EXTMIXLEV_NUM_OPTIONS, 5, 0,
2220                            &s->loro_center_mix_level);
2221         /* validate Lo/Ro surround mix level */
2222         validate_mix_level(avctx, "loro_surround_mix_level",
2223                            &opt->loro_surround_mix_level, extmixlev_options,
2224                            EXTMIXLEV_NUM_OPTIONS, 6, 3,
2225                            &s->loro_surround_mix_level);
2226         opt->extended_bsi_1 = 1;
2227     } else {
2228         opt->extended_bsi_1 = 0;
2229     }
2230
2231     /* set extended bsi 2 flag */
2232     if (opt->dolby_surround_ex_mode >= 0 ||
2233         opt->dolby_headphone_mode   >= 0 ||
2234         opt->ad_converter_type      >= 0) {
2235         /* default dolby surround ex mode */
2236         if (opt->dolby_surround_ex_mode < 0)
2237             opt->dolby_surround_ex_mode = 0;
2238         /* default dolby headphone mode */
2239         if (opt->dolby_headphone_mode < 0)
2240             opt->dolby_headphone_mode = 0;
2241         /* default A/D converter type */
2242         if (opt->ad_converter_type < 0)
2243             opt->ad_converter_type = 0;
2244         opt->extended_bsi_2 = 1;
2245     } else {
2246         opt->extended_bsi_2 = 0;
2247     }
2248
2249     /* set bitstream id for alternate bitstream syntax */
2250     if (opt->extended_bsi_1 || opt->extended_bsi_2) {
2251         if (s->bitstream_id > 8 && s->bitstream_id < 11) {
2252             static int warn_once = 1;
2253             if (warn_once) {
2254                 av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
2255                        "not compatible with reduced samplerates. writing of "
2256                        "extended bitstream information will be disabled.\n");
2257                 warn_once = 0;
2258             }
2259         } else {
2260             s->bitstream_id = 6;
2261         }
2262     }
2263
2264     return 0;
2265 }
2266
2267
2268 /**
2269  * Encode a single AC-3 frame.
2270  */
2271 static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
2272                             int buf_size, void *data)
2273 {
2274     AC3EncodeContext *s = avctx->priv_data;
2275     const SampleType *samples = data;
2276     int ret;
2277
2278     if (!s->eac3 && s->options.allow_per_frame_metadata) {
2279         ret = validate_metadata(avctx);
2280         if (ret)
2281             return ret;
2282     }
2283
2284     if (s->bit_alloc.sr_code == 1 || s->eac3)
2285         adjust_frame_size(s);
2286
2287     deinterleave_input_samples(s, samples);
2288
2289     apply_mdct(s);
2290
2291     scale_coefficients(s);
2292
2293     s->cpl_on = s->cpl_enabled;
2294     compute_coupling_strategy(s);
2295
2296     if (s->cpl_on)
2297         apply_channel_coupling(s);
2298
2299     compute_rematrixing_strategy(s);
2300
2301     apply_rematrixing(s);
2302
2303     process_exponents(s);
2304
2305     ret = compute_bit_allocation(s);
2306     if (ret) {
2307         av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
2308         return ret;
2309     }
2310
2311     quantize_mantissas(s);
2312
2313     output_frame(s, frame);
2314
2315     return s->frame_size;
2316 }
2317
2318
2319 /**
2320  * Finalize encoding and free any memory allocated by the encoder.
2321  */
2322 static av_cold int ac3_encode_close(AVCodecContext *avctx)
2323 {
2324     int blk, ch;
2325     AC3EncodeContext *s = avctx->priv_data;
2326
2327     for (ch = 0; ch < s->channels; ch++)
2328         av_freep(&s->planar_samples[ch]);
2329     av_freep(&s->planar_samples);
2330     av_freep(&s->bap_buffer);
2331     av_freep(&s->bap1_buffer);
2332     av_freep(&s->mdct_coef_buffer);
2333     av_freep(&s->fixed_coef_buffer);
2334     av_freep(&s->exp_buffer);
2335     av_freep(&s->grouped_exp_buffer);
2336     av_freep(&s->psd_buffer);
2337     av_freep(&s->band_psd_buffer);
2338     av_freep(&s->mask_buffer);
2339     av_freep(&s->qmant_buffer);
2340     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2341         AC3Block *block = &s->blocks[blk];
2342         av_freep(&block->mdct_coef);
2343         av_freep(&block->fixed_coef);
2344         av_freep(&block->exp);
2345         av_freep(&block->grouped_exp);
2346         av_freep(&block->psd);
2347         av_freep(&block->band_psd);
2348         av_freep(&block->mask);
2349         av_freep(&block->qmant);
2350     }
2351
2352     mdct_end(&s->mdct);
2353
2354     av_freep(&avctx->coded_frame);
2355     return 0;
2356 }
2357
2358
2359 /**
2360  * Set channel information during initialization.
2361  */
2362 static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
2363                                     int64_t *channel_layout)
2364 {
2365     int ch_layout;
2366
2367     if (channels < 1 || channels > AC3_MAX_CHANNELS)
2368         return AVERROR(EINVAL);
2369     if ((uint64_t)*channel_layout > 0x7FF)
2370         return AVERROR(EINVAL);
2371     ch_layout = *channel_layout;
2372     if (!ch_layout)
2373         ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
2374
2375     s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
2376     s->channels     = channels;
2377     s->fbw_channels = channels - s->lfe_on;
2378     s->lfe_channel  = s->lfe_on ? s->fbw_channels + 1 : -1;
2379     if (s->lfe_on)
2380         ch_layout -= AV_CH_LOW_FREQUENCY;
2381
2382     switch (ch_layout) {
2383     case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;
2384     case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;
2385     case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;
2386     case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;
2387     case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;
2388     case AV_CH_LAYOUT_QUAD:
2389     case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;
2390     case AV_CH_LAYOUT_5POINT0:
2391     case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
2392     default:
2393         return AVERROR(EINVAL);
2394     }
2395     s->has_center   = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
2396     s->has_surround =  s->channel_mode & 0x04;
2397
2398     s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
2399     *channel_layout = ch_layout;
2400     if (s->lfe_on)
2401         *channel_layout |= AV_CH_LOW_FREQUENCY;
2402
2403     return 0;
2404 }
2405
2406
2407 static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
2408 {
2409     int i, ret, max_sr;
2410
2411     /* validate channel layout */
2412     if (!avctx->channel_layout) {
2413         av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
2414                                       "encoder will guess the layout, but it "
2415                                       "might be incorrect.\n");
2416     }
2417     ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
2418     if (ret) {
2419         av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
2420         return ret;
2421     }
2422
2423     /* validate sample rate */
2424     /* note: max_sr could be changed from 2 to 5 for E-AC-3 once we find a
2425              decoder that supports half sample rate so we can validate that
2426              the generated files are correct. */
2427     max_sr = s->eac3 ? 2 : 8;
2428     for (i = 0; i <= max_sr; i++) {
2429         if ((ff_ac3_sample_rate_tab[i % 3] >> (i / 3)) == avctx->sample_rate)
2430             break;
2431     }
2432     if (i > max_sr) {
2433         av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
2434         return AVERROR(EINVAL);
2435     }
2436     s->sample_rate        = avctx->sample_rate;
2437     s->bit_alloc.sr_shift = i / 3;
2438     s->bit_alloc.sr_code  = i % 3;
2439     s->bitstream_id       = s->eac3 ? 16 : 8 + s->bit_alloc.sr_shift;
2440
2441     /* validate bit rate */
2442     if (s->eac3) {
2443         int max_br, min_br, wpf, min_br_dist, min_br_code;
2444
2445         /* calculate min/max bitrate */
2446         max_br = 2048 * s->sample_rate / AC3_FRAME_SIZE * 16;
2447         min_br = ((s->sample_rate + (AC3_FRAME_SIZE-1)) / AC3_FRAME_SIZE) * 16;
2448         if (avctx->bit_rate < min_br || avctx->bit_rate > max_br) {
2449             av_log(avctx, AV_LOG_ERROR, "invalid bit rate. must be %d to %d "
2450                    "for this sample rate\n", min_br, max_br);
2451             return AVERROR(EINVAL);
2452         }
2453
2454         /* calculate words-per-frame for the selected bitrate */
2455         wpf = (avctx->bit_rate / 16) * AC3_FRAME_SIZE / s->sample_rate;
2456         av_assert1(wpf > 0 && wpf <= 2048);
2457
2458         /* find the closest AC-3 bitrate code to the selected bitrate.
2459            this is needed for lookup tables for bandwidth and coupling
2460            parameter selection */
2461         min_br_code = -1;
2462         min_br_dist = INT_MAX;
2463         for (i = 0; i < 19; i++) {
2464             int br_dist = abs(ff_ac3_bitrate_tab[i] * 1000 - avctx->bit_rate);
2465             if (br_dist < min_br_dist) {
2466                 min_br_dist = br_dist;
2467                 min_br_code = i;
2468             }
2469         }
2470
2471         /* make sure the minimum frame size is below the average frame size */
2472         s->frame_size_code = min_br_code << 1;
2473         while (wpf > 1 && wpf * s->sample_rate / AC3_FRAME_SIZE * 16 > avctx->bit_rate)
2474             wpf--;
2475         s->frame_size_min = 2 * wpf;
2476     } else {
2477         for (i = 0; i < 19; i++) {
2478             if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
2479                 break;
2480         }
2481         if (i == 19) {
2482             av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
2483             return AVERROR(EINVAL);
2484         }
2485         s->frame_size_code = i << 1;
2486         s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
2487     }
2488     s->bit_rate   = avctx->bit_rate;
2489     s->frame_size = s->frame_size_min;
2490
2491     /* validate cutoff */
2492     if (avctx->cutoff < 0) {
2493         av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
2494         return AVERROR(EINVAL);
2495     }
2496     s->cutoff = avctx->cutoff;
2497     if (s->cutoff > (s->sample_rate >> 1))
2498         s->cutoff = s->sample_rate >> 1;
2499
2500     /* validate audio service type / channels combination */
2501     if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
2502          avctx->channels == 1) ||
2503         ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
2504           avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY  ||
2505           avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
2506          && avctx->channels > 1)) {
2507         av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
2508                                     "specified number of channels\n");
2509         return AVERROR(EINVAL);
2510     }
2511
2512     if (!s->eac3) {
2513         ret = validate_metadata(avctx);
2514         if (ret)
2515             return ret;
2516     }
2517
2518     s->rematrixing_enabled = s->options.stereo_rematrixing &&
2519                              (s->channel_mode == AC3_CHMODE_STEREO);
2520
2521     s->cpl_enabled = s->options.channel_coupling &&
2522                      s->channel_mode >= AC3_CHMODE_STEREO &&
2523                      CONFIG_AC3ENC_FLOAT;
2524
2525     return 0;
2526 }
2527
2528
2529 /**
2530  * Set bandwidth for all channels.
2531  * The user can optionally supply a cutoff frequency. Otherwise an appropriate
2532  * default value will be used.
2533  */
2534 static av_cold void set_bandwidth(AC3EncodeContext *s)
2535 {
2536     int blk, ch;
2537     int av_uninit(cpl_start);
2538
2539     if (s->cutoff) {
2540         /* calculate bandwidth based on user-specified cutoff frequency */
2541         int fbw_coeffs;
2542         fbw_coeffs     = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
2543         s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
2544     } else {
2545         /* use default bandwidth setting */
2546         s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
2547     }
2548
2549     /* set number of coefficients for each channel */
2550     for (ch = 1; ch <= s->fbw_channels; ch++) {
2551         s->start_freq[ch] = 0;
2552         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2553             s->blocks[blk].end_freq[ch] = s->bandwidth_code * 3 + 73;
2554     }
2555     /* LFE channel always has 7 coefs */
2556     if (s->lfe_on) {
2557         s->start_freq[s->lfe_channel] = 0;
2558         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2559             s->blocks[blk].end_freq[ch] = 7;
2560     }
2561
2562     /* initialize coupling strategy */
2563     if (s->cpl_enabled) {
2564         if (s->options.cpl_start >= 0) {
2565             cpl_start = s->options.cpl_start;
2566         } else {
2567             cpl_start = ac3_coupling_start_tab[s->channel_mode-2][s->bit_alloc.sr_code][s->frame_size_code/2];
2568             if (cpl_start < 0)
2569                 s->cpl_enabled = 0;
2570         }
2571     }
2572     if (s->cpl_enabled) {
2573         int i, cpl_start_band, cpl_end_band;
2574         uint8_t *cpl_band_sizes = s->cpl_band_sizes;
2575
2576         cpl_end_band   = s->bandwidth_code / 4 + 3;
2577         cpl_start_band = av_clip(cpl_start, 0, FFMIN(cpl_end_band-1, 15));
2578
2579         s->num_cpl_subbands = cpl_end_band - cpl_start_band;
2580
2581         s->num_cpl_bands = 1;
2582         *cpl_band_sizes  = 12;
2583         for (i = cpl_start_band + 1; i < cpl_end_band; i++) {
2584             if (ff_eac3_default_cpl_band_struct[i]) {
2585                 *cpl_band_sizes += 12;
2586             } else {
2587                 s->num_cpl_bands++;
2588                 cpl_band_sizes++;
2589                 *cpl_band_sizes = 12;
2590             }
2591         }
2592
2593         s->start_freq[CPL_CH] = cpl_start_band * 12 + 37;
2594         s->cpl_end_freq       = cpl_end_band   * 12 + 37;
2595         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
2596             s->blocks[blk].end_freq[CPL_CH] = s->cpl_end_freq;
2597     }
2598 }
2599
2600
2601 static av_cold int allocate_buffers(AVCodecContext *avctx)
2602 {
2603     int blk, ch;
2604     AC3EncodeContext *s = avctx->priv_data;
2605     int channels = s->channels + 1; /* includes coupling channel */
2606
2607     FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
2608                      alloc_fail);
2609     for (ch = 0; ch < s->channels; ch++) {
2610         FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
2611                           (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
2612                           alloc_fail);
2613     }
2614     FF_ALLOC_OR_GOTO(avctx, s->bap_buffer,  AC3_MAX_BLOCKS * channels *
2615                      AC3_MAX_COEFS * sizeof(*s->bap_buffer),  alloc_fail);
2616     FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * channels *
2617                      AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
2618     FF_ALLOCZ_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * channels *
2619                       AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
2620     FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * channels *
2621                      AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
2622     FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * channels *
2623                      128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
2624     FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * channels *
2625                      AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
2626     FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * channels *
2627                      64 * sizeof(*s->band_psd_buffer), alloc_fail);
2628     FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * channels *
2629                      64 * sizeof(*s->mask_buffer), alloc_fail);
2630     FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * channels *
2631                      AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
2632     if (s->cpl_enabled) {
2633         FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_exp_buffer, AC3_MAX_BLOCKS * channels *
2634                          16 * sizeof(*s->cpl_coord_exp_buffer), alloc_fail);
2635         FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_mant_buffer, AC3_MAX_BLOCKS * channels *
2636                          16 * sizeof(*s->cpl_coord_mant_buffer), alloc_fail);
2637     }
2638     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2639         AC3Block *block = &s->blocks[blk];
2640         FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, channels * sizeof(*block->mdct_coef),
2641                           alloc_fail);
2642         FF_ALLOCZ_OR_GOTO(avctx, block->exp, channels * sizeof(*block->exp),
2643                           alloc_fail);
2644         FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, channels * sizeof(*block->grouped_exp),
2645                           alloc_fail);
2646         FF_ALLOCZ_OR_GOTO(avctx, block->psd, channels * sizeof(*block->psd),
2647                           alloc_fail);
2648         FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, channels * sizeof(*block->band_psd),
2649                           alloc_fail);
2650         FF_ALLOCZ_OR_GOTO(avctx, block->mask, channels * sizeof(*block->mask),
2651                           alloc_fail);
2652         FF_ALLOCZ_OR_GOTO(avctx, block->qmant, channels * sizeof(*block->qmant),
2653                           alloc_fail);
2654         if (s->cpl_enabled) {
2655             FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_exp, channels * sizeof(*block->cpl_coord_exp),
2656                               alloc_fail);
2657             FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_mant, channels * sizeof(*block->cpl_coord_mant),
2658                               alloc_fail);
2659         }
2660
2661         for (ch = 0; ch < channels; ch++) {
2662             /* arrangement: block, channel, coeff */
2663             block->grouped_exp[ch] = &s->grouped_exp_buffer[128           * (blk * channels + ch)];
2664             block->psd[ch]         = &s->psd_buffer        [AC3_MAX_COEFS * (blk * channels + ch)];
2665             block->band_psd[ch]    = &s->band_psd_buffer   [64            * (blk * channels + ch)];
2666             block->mask[ch]        = &s->mask_buffer       [64            * (blk * channels + ch)];
2667             block->qmant[ch]       = &s->qmant_buffer      [AC3_MAX_COEFS * (blk * channels + ch)];
2668             if (s->cpl_enabled) {
2669                 block->cpl_coord_exp[ch]  = &s->cpl_coord_exp_buffer [16  * (blk * channels + ch)];
2670                 block->cpl_coord_mant[ch] = &s->cpl_coord_mant_buffer[16  * (blk * channels + ch)];
2671             }
2672
2673             /* arrangement: channel, block, coeff */
2674             block->exp[ch]         = &s->exp_buffer        [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2675             block->mdct_coef[ch]   = &s->mdct_coef_buffer  [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2676         }
2677     }
2678
2679     if (CONFIG_AC3ENC_FLOAT) {
2680         FF_ALLOCZ_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * channels *
2681                           AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
2682         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2683             AC3Block *block = &s->blocks[blk];
2684             FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2685                               sizeof(*block->fixed_coef), alloc_fail);
2686             for (ch = 0; ch < channels; ch++)
2687                 block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
2688         }
2689     } else {
2690         for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
2691             AC3Block *block = &s->blocks[blk];
2692             FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
2693                               sizeof(*block->fixed_coef), alloc_fail);
2694             for (ch = 0; ch < channels; ch++)
2695                 block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
2696         }
2697     }
2698
2699     return 0;
2700 alloc_fail:
2701     return AVERROR(ENOMEM);
2702 }
2703
2704
2705 /**
2706  * Initialize the encoder.
2707  */
2708 static av_cold int ac3_encode_init(AVCodecContext *avctx)
2709 {
2710     AC3EncodeContext *s = avctx->priv_data;
2711     int ret, frame_size_58;
2712
2713     s->eac3 = avctx->codec_id == CODEC_ID_EAC3;
2714
2715     avctx->frame_size = AC3_FRAME_SIZE;
2716
2717     ff_ac3_common_init();
2718
2719     ret = validate_options(avctx, s);
2720     if (ret)
2721         return ret;
2722
2723     s->bitstream_mode = avctx->audio_service_type;
2724     if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
2725         s->bitstream_mode = 0x7;
2726
2727     s->bits_written    = 0;
2728     s->samples_written = 0;
2729
2730     /* calculate crc_inv for both possible frame sizes */
2731     frame_size_58 = (( s->frame_size    >> 2) + ( s->frame_size    >> 4)) << 1;
2732     s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2733     if (s->bit_alloc.sr_code == 1) {
2734         frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
2735         s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
2736     }
2737
2738     set_bandwidth(s);
2739
2740     exponent_init(s);
2741
2742     bit_alloc_init(s);
2743
2744     ret = mdct_init(avctx, &s->mdct, 9);
2745     if (ret)
2746         goto init_fail;
2747
2748     ret = allocate_buffers(avctx);
2749     if (ret)
2750         goto init_fail;
2751
2752     avctx->coded_frame= avcodec_alloc_frame();
2753
2754     dsputil_init(&s->dsp, avctx);
2755     ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
2756
2757     dprint_options(avctx);
2758
2759     return 0;
2760 init_fail:
2761     ac3_encode_close(avctx);
2762     return ret;
2763 }