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