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