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