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