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