OSDN Git Service

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