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