You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2221 lines
77KB

  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 Libav.
  8. *
  9. * Libav 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. * Libav 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 Libav; if not, write to the Free Software
  21. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  22. */
  23. /**
  24. * @file
  25. * The simplest AC-3 encoder.
  26. */
  27. //#define DEBUG
  28. //#define ASSERT_LEVEL 2
  29. #include <stdint.h>
  30. #include "libavutil/audioconvert.h"
  31. #include "libavutil/avassert.h"
  32. #include "libavutil/avstring.h"
  33. #include "libavutil/crc.h"
  34. #include "libavutil/opt.h"
  35. #include "avcodec.h"
  36. #include "put_bits.h"
  37. #include "dsputil.h"
  38. #include "ac3dsp.h"
  39. #include "ac3.h"
  40. #include "audioconvert.h"
  41. #include "fft.h"
  42. #ifndef CONFIG_AC3ENC_FLOAT
  43. #define CONFIG_AC3ENC_FLOAT 0
  44. #endif
  45. /** Maximum number of exponent groups. +1 for separate DC exponent. */
  46. #define AC3_MAX_EXP_GROUPS 85
  47. #if CONFIG_AC3ENC_FLOAT
  48. #define MAC_COEF(d,a,b) ((d)+=(a)*(b))
  49. typedef float SampleType;
  50. typedef float CoefType;
  51. typedef float CoefSumType;
  52. #else
  53. #define MAC_COEF(d,a,b) MAC64(d,a,b)
  54. typedef int16_t SampleType;
  55. typedef int32_t CoefType;
  56. typedef int64_t CoefSumType;
  57. #endif
  58. typedef struct AC3MDCTContext {
  59. const SampleType *window; ///< MDCT window function
  60. FFTContext fft; ///< FFT context for MDCT calculation
  61. } AC3MDCTContext;
  62. /**
  63. * Encoding Options used by AVOption.
  64. */
  65. typedef struct AC3EncOptions {
  66. /* AC-3 metadata options*/
  67. int dialogue_level;
  68. int bitstream_mode;
  69. float center_mix_level;
  70. float surround_mix_level;
  71. int dolby_surround_mode;
  72. int audio_production_info;
  73. int mixing_level;
  74. int room_type;
  75. int copyright;
  76. int original;
  77. int extended_bsi_1;
  78. int preferred_stereo_downmix;
  79. float ltrt_center_mix_level;
  80. float ltrt_surround_mix_level;
  81. float loro_center_mix_level;
  82. float loro_surround_mix_level;
  83. int extended_bsi_2;
  84. int dolby_surround_ex_mode;
  85. int dolby_headphone_mode;
  86. int ad_converter_type;
  87. /* other encoding options */
  88. int allow_per_frame_metadata;
  89. int stereo_rematrixing;
  90. } AC3EncOptions;
  91. /**
  92. * Data for a single audio block.
  93. */
  94. typedef struct AC3Block {
  95. uint8_t **bap; ///< bit allocation pointers (bap)
  96. CoefType **mdct_coef; ///< MDCT coefficients
  97. int32_t **fixed_coef; ///< fixed-point MDCT coefficients
  98. uint8_t **exp; ///< original exponents
  99. uint8_t **grouped_exp; ///< grouped exponents
  100. int16_t **psd; ///< psd per frequency bin
  101. int16_t **band_psd; ///< psd per critical band
  102. int16_t **mask; ///< masking curve
  103. uint16_t **qmant; ///< quantized mantissas
  104. uint8_t coeff_shift[AC3_MAX_CHANNELS]; ///< fixed-point coefficient shift values
  105. uint8_t new_rematrixing_strategy; ///< send new rematrixing flags in this block
  106. uint8_t rematrixing_flags[4]; ///< rematrixing flags
  107. struct AC3Block *exp_ref_block[AC3_MAX_CHANNELS]; ///< reference blocks for EXP_REUSE
  108. } AC3Block;
  109. /**
  110. * AC-3 encoder private context.
  111. */
  112. typedef struct AC3EncodeContext {
  113. AVClass *av_class; ///< AVClass used for AVOption
  114. AC3EncOptions options; ///< encoding options
  115. PutBitContext pb; ///< bitstream writer context
  116. DSPContext dsp;
  117. AC3DSPContext ac3dsp; ///< AC-3 optimized functions
  118. AC3MDCTContext mdct; ///< MDCT context
  119. AC3Block blocks[AC3_MAX_BLOCKS]; ///< per-block info
  120. int bitstream_id; ///< bitstream id (bsid)
  121. int bitstream_mode; ///< bitstream mode (bsmod)
  122. int bit_rate; ///< target bit rate, in bits-per-second
  123. int sample_rate; ///< sampling frequency, in Hz
  124. int frame_size_min; ///< minimum frame size in case rounding is necessary
  125. int frame_size; ///< current frame size in bytes
  126. int frame_size_code; ///< frame size code (frmsizecod)
  127. uint16_t crc_inv[2];
  128. int bits_written; ///< bit count (used to avg. bitrate)
  129. int samples_written; ///< sample count (used to avg. bitrate)
  130. int fbw_channels; ///< number of full-bandwidth channels (nfchans)
  131. int channels; ///< total number of channels (nchans)
  132. int lfe_on; ///< indicates if there is an LFE channel (lfeon)
  133. int lfe_channel; ///< channel index of the LFE channel
  134. int has_center; ///< indicates if there is a center channel
  135. int has_surround; ///< indicates if there are one or more surround channels
  136. int channel_mode; ///< channel mode (acmod)
  137. const uint8_t *channel_map; ///< channel map used to reorder channels
  138. int center_mix_level; ///< center mix level code
  139. int surround_mix_level; ///< surround mix level code
  140. int ltrt_center_mix_level; ///< Lt/Rt center mix level code
  141. int ltrt_surround_mix_level; ///< Lt/Rt surround mix level code
  142. int loro_center_mix_level; ///< Lo/Ro center mix level code
  143. int loro_surround_mix_level; ///< Lo/Ro surround mix level code
  144. int cutoff; ///< user-specified cutoff frequency, in Hz
  145. int bandwidth_code; ///< bandwidth code (0 to 60) (chbwcod)
  146. int nb_coefs[AC3_MAX_CHANNELS];
  147. int rematrixing_enabled; ///< stereo rematrixing enabled
  148. int num_rematrixing_bands; ///< number of rematrixing bands
  149. /* bitrate allocation control */
  150. int slow_gain_code; ///< slow gain code (sgaincod)
  151. int slow_decay_code; ///< slow decay code (sdcycod)
  152. int fast_decay_code; ///< fast decay code (fdcycod)
  153. int db_per_bit_code; ///< dB/bit code (dbpbcod)
  154. int floor_code; ///< floor code (floorcod)
  155. AC3BitAllocParameters bit_alloc; ///< bit allocation parameters
  156. int coarse_snr_offset; ///< coarse SNR offsets (csnroffst)
  157. int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signal-to-mask ratio) (fgaincod)
  158. int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst)
  159. int frame_bits_fixed; ///< number of non-coefficient bits for fixed parameters
  160. int frame_bits; ///< all frame bits except exponents and mantissas
  161. int exponent_bits; ///< number of bits used for exponents
  162. SampleType **planar_samples;
  163. uint8_t *bap_buffer;
  164. uint8_t *bap1_buffer;
  165. CoefType *mdct_coef_buffer;
  166. int32_t *fixed_coef_buffer;
  167. uint8_t *exp_buffer;
  168. uint8_t *grouped_exp_buffer;
  169. int16_t *psd_buffer;
  170. int16_t *band_psd_buffer;
  171. int16_t *mask_buffer;
  172. uint16_t *qmant_buffer;
  173. uint8_t exp_strategy[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< exponent strategies
  174. DECLARE_ALIGNED(32, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
  175. } AC3EncodeContext;
  176. typedef struct AC3Mant {
  177. uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
  178. int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
  179. } AC3Mant;
  180. #define CMIXLEV_NUM_OPTIONS 3
  181. static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
  182. LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
  183. };
  184. #define SURMIXLEV_NUM_OPTIONS 3
  185. static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
  186. LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
  187. };
  188. #define EXTMIXLEV_NUM_OPTIONS 8
  189. static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
  190. LEVEL_PLUS_3DB, LEVEL_PLUS_1POINT5DB, LEVEL_ONE, LEVEL_MINUS_4POINT5DB,
  191. LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
  192. };
  193. #define OFFSET(param) offsetof(AC3EncodeContext, options.param)
  194. #define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
  195. static const AVOption options[] = {
  196. /* Metadata Options */
  197. {"per_frame_metadata", "Allow Changing Metadata Per-Frame", OFFSET(allow_per_frame_metadata), FF_OPT_TYPE_INT, 0, 0, 1, AC3ENC_PARAM},
  198. /* downmix levels */
  199. {"center_mixlev", "Center Mix Level", OFFSET(center_mix_level), FF_OPT_TYPE_FLOAT, LEVEL_MINUS_4POINT5DB, 0.0, 1.0, AC3ENC_PARAM},
  200. {"surround_mixlev", "Surround Mix Level", OFFSET(surround_mix_level), FF_OPT_TYPE_FLOAT, LEVEL_MINUS_6DB, 0.0, 1.0, AC3ENC_PARAM},
  201. /* audio production information */
  202. {"mixing_level", "Mixing Level", OFFSET(mixing_level), FF_OPT_TYPE_INT, -1, -1, 111, AC3ENC_PARAM},
  203. {"room_type", "Room Type", OFFSET(room_type), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "room_type"},
  204. {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
  205. {"large", "Large Room", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
  206. {"small", "Small Room", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
  207. /* other metadata options */
  208. {"copyright", "Copyright Bit", OFFSET(copyright), FF_OPT_TYPE_INT, 0, 0, 1, AC3ENC_PARAM},
  209. {"dialnorm", "Dialogue Level (dB)", OFFSET(dialogue_level), FF_OPT_TYPE_INT, -31, -31, -1, AC3ENC_PARAM},
  210. {"dsur_mode", "Dolby Surround Mode", OFFSET(dolby_surround_mode), FF_OPT_TYPE_INT, 0, 0, 2, AC3ENC_PARAM, "dsur_mode"},
  211. {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
  212. {"on", "Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
  213. {"off", "Not Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
  214. {"original", "Original Bit Stream", OFFSET(original), FF_OPT_TYPE_INT, 1, 0, 1, AC3ENC_PARAM},
  215. /* extended bitstream information */
  216. {"dmix_mode", "Preferred Stereo Downmix Mode", OFFSET(preferred_stereo_downmix), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "dmix_mode"},
  217. {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
  218. {"ltrt", "Lt/Rt Downmix Preferred", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
  219. {"loro", "Lo/Ro Downmix Preferred", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
  220. {"ltrt_cmixlev", "Lt/Rt Center Mix Level", OFFSET(ltrt_center_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
  221. {"ltrt_surmixlev", "Lt/Rt Surround Mix Level", OFFSET(ltrt_surround_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
  222. {"loro_cmixlev", "Lo/Ro Center Mix Level", OFFSET(loro_center_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
  223. {"loro_surmixlev", "Lo/Ro Surround Mix Level", OFFSET(loro_surround_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
  224. {"dsurex_mode", "Dolby Surround EX Mode", OFFSET(dolby_surround_ex_mode), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "dsurex_mode"},
  225. {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
  226. {"on", "Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
  227. {"off", "Not Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
  228. {"dheadphone_mode", "Dolby Headphone Mode", OFFSET(dolby_headphone_mode), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "dheadphone_mode"},
  229. {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
  230. {"on", "Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
  231. {"off", "Not Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
  232. {"ad_conv_type", "A/D Converter Type", OFFSET(ad_converter_type), FF_OPT_TYPE_INT, -1, -1, 1, AC3ENC_PARAM, "ad_conv_type"},
  233. {"standard", "Standard (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
  234. {"hdcd", "HDCD", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
  235. /* Other Encoding Options */
  236. {"stereo_rematrixing", "Stereo Rematrixing", OFFSET(stereo_rematrixing), FF_OPT_TYPE_INT, 1, 0, 1, AC3ENC_PARAM},
  237. {NULL}
  238. };
  239. #if CONFIG_AC3ENC_FLOAT
  240. static AVClass ac3enc_class = { "AC-3 Encoder", av_default_item_name,
  241. options, LIBAVUTIL_VERSION_INT };
  242. #else
  243. static AVClass ac3enc_class = { "Fixed-Point AC-3 Encoder", av_default_item_name,
  244. options, LIBAVUTIL_VERSION_INT };
  245. #endif
  246. /* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
  247. static av_cold void mdct_end(AC3MDCTContext *mdct);
  248. static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
  249. int nbits);
  250. static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
  251. const SampleType *window, unsigned int len);
  252. static int normalize_samples(AC3EncodeContext *s);
  253. static void scale_coefficients(AC3EncodeContext *s);
  254. /**
  255. * LUT for number of exponent groups.
  256. * exponent_group_tab[exponent strategy-1][number of coefficients]
  257. */
  258. static uint8_t exponent_group_tab[3][256];
  259. /**
  260. * List of supported channel layouts.
  261. */
  262. static const int64_t ac3_channel_layouts[] = {
  263. AV_CH_LAYOUT_MONO,
  264. AV_CH_LAYOUT_STEREO,
  265. AV_CH_LAYOUT_2_1,
  266. AV_CH_LAYOUT_SURROUND,
  267. AV_CH_LAYOUT_2_2,
  268. AV_CH_LAYOUT_QUAD,
  269. AV_CH_LAYOUT_4POINT0,
  270. AV_CH_LAYOUT_5POINT0,
  271. AV_CH_LAYOUT_5POINT0_BACK,
  272. (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
  273. (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
  274. (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
  275. (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
  276. (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
  277. (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
  278. (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
  279. AV_CH_LAYOUT_5POINT1,
  280. AV_CH_LAYOUT_5POINT1_BACK,
  281. 0
  282. };
  283. /**
  284. * LUT to select the bandwidth code based on the bit rate, sample rate, and
  285. * number of full-bandwidth channels.
  286. * bandwidth_tab[fbw_channels-1][sample rate code][bit rate code]
  287. */
  288. static const uint8_t ac3_bandwidth_tab[5][3][19] = {
  289. // 32 40 48 56 64 80 96 112 128 160 192 224 256 320 384 448 512 576 640
  290. { { 0, 0, 0, 12, 16, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
  291. { 0, 0, 0, 16, 20, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
  292. { 0, 0, 0, 32, 40, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
  293. { { 0, 0, 0, 0, 0, 0, 0, 20, 24, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
  294. { 0, 0, 0, 0, 0, 0, 4, 24, 28, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
  295. { 0, 0, 0, 0, 0, 0, 20, 44, 52, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
  296. { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 24, 32, 40, 48, 48, 48, 48, 48, 48 },
  297. { 0, 0, 0, 0, 0, 0, 0, 0, 4, 20, 28, 36, 44, 56, 56, 56, 56, 56, 56 },
  298. { 0, 0, 0, 0, 0, 0, 0, 0, 20, 40, 48, 60, 60, 60, 60, 60, 60, 60, 60 } },
  299. { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 32, 48, 48, 48, 48, 48, 48 },
  300. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 28, 36, 56, 56, 56, 56, 56, 56 },
  301. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 48, 60, 60, 60, 60, 60, 60, 60 } },
  302. { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 20, 32, 40, 48, 48, 48, 48 },
  303. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 36, 44, 56, 56, 56, 56 },
  304. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 44, 60, 60, 60, 60, 60, 60 } }
  305. };
  306. /**
  307. * Adjust the frame size to make the average bit rate match the target bit rate.
  308. * This is only needed for 11025, 22050, and 44100 sample rates.
  309. */
  310. static void adjust_frame_size(AC3EncodeContext *s)
  311. {
  312. while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
  313. s->bits_written -= s->bit_rate;
  314. s->samples_written -= s->sample_rate;
  315. }
  316. s->frame_size = s->frame_size_min +
  317. 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
  318. s->bits_written += s->frame_size * 8;
  319. s->samples_written += AC3_FRAME_SIZE;
  320. }
  321. /**
  322. * Deinterleave input samples.
  323. * Channels are reordered from Libav's default order to AC-3 order.
  324. */
  325. static void deinterleave_input_samples(AC3EncodeContext *s,
  326. const SampleType *samples)
  327. {
  328. int ch, i;
  329. /* deinterleave and remap input samples */
  330. for (ch = 0; ch < s->channels; ch++) {
  331. const SampleType *sptr;
  332. int sinc;
  333. /* copy last 256 samples of previous frame to the start of the current frame */
  334. memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
  335. AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
  336. /* deinterleave */
  337. sinc = s->channels;
  338. sptr = samples + s->channel_map[ch];
  339. for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
  340. s->planar_samples[ch][i] = *sptr;
  341. sptr += sinc;
  342. }
  343. }
  344. }
  345. /**
  346. * Apply the MDCT to input samples to generate frequency coefficients.
  347. * This applies the KBD window and normalizes the input to reduce precision
  348. * loss due to fixed-point calculations.
  349. */
  350. static void apply_mdct(AC3EncodeContext *s)
  351. {
  352. int blk, ch;
  353. for (ch = 0; ch < s->channels; ch++) {
  354. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  355. AC3Block *block = &s->blocks[blk];
  356. const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
  357. apply_window(&s->dsp, s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
  358. block->coeff_shift[ch] = normalize_samples(s);
  359. s->mdct.fft.mdct_calcw(&s->mdct.fft, block->mdct_coef[ch],
  360. s->windowed_samples);
  361. }
  362. }
  363. }
  364. /**
  365. * Determine rematrixing flags for each block and band.
  366. */
  367. static void compute_rematrixing_strategy(AC3EncodeContext *s)
  368. {
  369. int nb_coefs;
  370. int blk, bnd, i;
  371. AC3Block *block, *block0;
  372. if (s->channel_mode != AC3_CHMODE_STEREO)
  373. return;
  374. s->num_rematrixing_bands = 4;
  375. nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
  376. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  377. block = &s->blocks[blk];
  378. block->new_rematrixing_strategy = !blk;
  379. if (!s->rematrixing_enabled)
  380. continue;
  381. for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
  382. /* calculate calculate sum of squared coeffs for one band in one block */
  383. int start = ff_ac3_rematrix_band_tab[bnd];
  384. int end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
  385. CoefSumType sum[4] = {0,};
  386. for (i = start; i < end; i++) {
  387. CoefType lt = block->mdct_coef[0][i];
  388. CoefType rt = block->mdct_coef[1][i];
  389. CoefType md = lt + rt;
  390. CoefType sd = lt - rt;
  391. MAC_COEF(sum[0], lt, lt);
  392. MAC_COEF(sum[1], rt, rt);
  393. MAC_COEF(sum[2], md, md);
  394. MAC_COEF(sum[3], sd, sd);
  395. }
  396. /* compare sums to determine if rematrixing will be used for this band */
  397. if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
  398. block->rematrixing_flags[bnd] = 1;
  399. else
  400. block->rematrixing_flags[bnd] = 0;
  401. /* determine if new rematrixing flags will be sent */
  402. if (blk &&
  403. block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
  404. block->new_rematrixing_strategy = 1;
  405. }
  406. }
  407. block0 = block;
  408. }
  409. }
  410. /**
  411. * Apply stereo rematrixing to coefficients based on rematrixing flags.
  412. */
  413. static void apply_rematrixing(AC3EncodeContext *s)
  414. {
  415. int nb_coefs;
  416. int blk, bnd, i;
  417. int start, end;
  418. uint8_t *flags;
  419. if (!s->rematrixing_enabled)
  420. return;
  421. nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
  422. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  423. AC3Block *block = &s->blocks[blk];
  424. if (block->new_rematrixing_strategy)
  425. flags = block->rematrixing_flags;
  426. for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
  427. if (flags[bnd]) {
  428. start = ff_ac3_rematrix_band_tab[bnd];
  429. end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
  430. for (i = start; i < end; i++) {
  431. int32_t lt = block->fixed_coef[0][i];
  432. int32_t rt = block->fixed_coef[1][i];
  433. block->fixed_coef[0][i] = (lt + rt) >> 1;
  434. block->fixed_coef[1][i] = (lt - rt) >> 1;
  435. }
  436. }
  437. }
  438. }
  439. }
  440. /**
  441. * Initialize exponent tables.
  442. */
  443. static av_cold void exponent_init(AC3EncodeContext *s)
  444. {
  445. int expstr, i, grpsize;
  446. for (expstr = EXP_D15-1; expstr <= EXP_D45-1; expstr++) {
  447. grpsize = 3 << expstr;
  448. for (i = 73; i < 256; i++) {
  449. exponent_group_tab[expstr][i] = (i + grpsize - 4) / grpsize;
  450. }
  451. }
  452. /* LFE */
  453. exponent_group_tab[0][7] = 2;
  454. }
  455. /**
  456. * Extract exponents from the MDCT coefficients.
  457. * This takes into account the normalization that was done to the input samples
  458. * by adjusting the exponents by the exponent shift values.
  459. */
  460. static void extract_exponents(AC3EncodeContext *s)
  461. {
  462. int blk, ch;
  463. for (ch = 0; ch < s->channels; ch++) {
  464. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  465. AC3Block *block = &s->blocks[blk];
  466. s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch],
  467. AC3_MAX_COEFS);
  468. }
  469. }
  470. }
  471. /**
  472. * Exponent Difference Threshold.
  473. * New exponents are sent if their SAD exceed this number.
  474. */
  475. #define EXP_DIFF_THRESHOLD 500
  476. /**
  477. * Calculate exponent strategies for all channels.
  478. * Array arrangement is reversed to simplify the per-channel calculation.
  479. */
  480. static void compute_exp_strategy(AC3EncodeContext *s)
  481. {
  482. int ch, blk, blk1;
  483. for (ch = 0; ch < s->fbw_channels; ch++) {
  484. uint8_t *exp_strategy = s->exp_strategy[ch];
  485. uint8_t *exp = s->blocks[0].exp[ch];
  486. int exp_diff;
  487. /* estimate if the exponent variation & decide if they should be
  488. reused in the next frame */
  489. exp_strategy[0] = EXP_NEW;
  490. exp += AC3_MAX_COEFS;
  491. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
  492. exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
  493. if (exp_diff > EXP_DIFF_THRESHOLD)
  494. exp_strategy[blk] = EXP_NEW;
  495. else
  496. exp_strategy[blk] = EXP_REUSE;
  497. exp += AC3_MAX_COEFS;
  498. }
  499. /* now select the encoding strategy type : if exponents are often
  500. recoded, we use a coarse encoding */
  501. blk = 0;
  502. while (blk < AC3_MAX_BLOCKS) {
  503. blk1 = blk + 1;
  504. while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
  505. blk1++;
  506. switch (blk1 - blk) {
  507. case 1: exp_strategy[blk] = EXP_D45; break;
  508. case 2:
  509. case 3: exp_strategy[blk] = EXP_D25; break;
  510. default: exp_strategy[blk] = EXP_D15; break;
  511. }
  512. blk = blk1;
  513. }
  514. }
  515. if (s->lfe_on) {
  516. ch = s->lfe_channel;
  517. s->exp_strategy[ch][0] = EXP_D15;
  518. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
  519. s->exp_strategy[ch][blk] = EXP_REUSE;
  520. }
  521. }
  522. /**
  523. * Update the exponents so that they are the ones the decoder will decode.
  524. */
  525. static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy)
  526. {
  527. int nb_groups, i, k;
  528. nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
  529. /* for each group, compute the minimum exponent */
  530. switch(exp_strategy) {
  531. case EXP_D25:
  532. for (i = 1, k = 1; i <= nb_groups; i++) {
  533. uint8_t exp_min = exp[k];
  534. if (exp[k+1] < exp_min)
  535. exp_min = exp[k+1];
  536. exp[i] = exp_min;
  537. k += 2;
  538. }
  539. break;
  540. case EXP_D45:
  541. for (i = 1, k = 1; i <= nb_groups; i++) {
  542. uint8_t exp_min = exp[k];
  543. if (exp[k+1] < exp_min)
  544. exp_min = exp[k+1];
  545. if (exp[k+2] < exp_min)
  546. exp_min = exp[k+2];
  547. if (exp[k+3] < exp_min)
  548. exp_min = exp[k+3];
  549. exp[i] = exp_min;
  550. k += 4;
  551. }
  552. break;
  553. }
  554. /* constraint for DC exponent */
  555. if (exp[0] > 15)
  556. exp[0] = 15;
  557. /* decrease the delta between each groups to within 2 so that they can be
  558. differentially encoded */
  559. for (i = 1; i <= nb_groups; i++)
  560. exp[i] = FFMIN(exp[i], exp[i-1] + 2);
  561. i--;
  562. while (--i >= 0)
  563. exp[i] = FFMIN(exp[i], exp[i+1] + 2);
  564. /* now we have the exponent values the decoder will see */
  565. switch (exp_strategy) {
  566. case EXP_D25:
  567. for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
  568. uint8_t exp1 = exp[i];
  569. exp[k--] = exp1;
  570. exp[k--] = exp1;
  571. }
  572. break;
  573. case EXP_D45:
  574. for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
  575. exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
  576. k -= 4;
  577. }
  578. break;
  579. }
  580. }
  581. /**
  582. * Encode exponents from original extracted form to what the decoder will see.
  583. * This copies and groups exponents based on exponent strategy and reduces
  584. * deltas between adjacent exponent groups so that they can be differentially
  585. * encoded.
  586. */
  587. static void encode_exponents(AC3EncodeContext *s)
  588. {
  589. int blk, blk1, ch;
  590. uint8_t *exp, *exp_strategy;
  591. int nb_coefs, num_reuse_blocks;
  592. for (ch = 0; ch < s->channels; ch++) {
  593. exp = s->blocks[0].exp[ch];
  594. exp_strategy = s->exp_strategy[ch];
  595. nb_coefs = s->nb_coefs[ch];
  596. blk = 0;
  597. while (blk < AC3_MAX_BLOCKS) {
  598. blk1 = blk + 1;
  599. /* count the number of EXP_REUSE blocks after the current block
  600. and set exponent reference block pointers */
  601. s->blocks[blk].exp_ref_block[ch] = &s->blocks[blk];
  602. while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
  603. s->blocks[blk1].exp_ref_block[ch] = &s->blocks[blk];
  604. blk1++;
  605. }
  606. num_reuse_blocks = blk1 - blk - 1;
  607. /* for the EXP_REUSE case we select the min of the exponents */
  608. s->ac3dsp.ac3_exponent_min(exp, num_reuse_blocks, nb_coefs);
  609. encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk]);
  610. exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
  611. blk = blk1;
  612. }
  613. }
  614. }
  615. /**
  616. * Group exponents.
  617. * 3 delta-encoded exponents are in each 7-bit group. The number of groups
  618. * varies depending on exponent strategy and bandwidth.
  619. */
  620. static void group_exponents(AC3EncodeContext *s)
  621. {
  622. int blk, ch, i;
  623. int group_size, nb_groups, bit_count;
  624. uint8_t *p;
  625. int delta0, delta1, delta2;
  626. int exp0, exp1;
  627. bit_count = 0;
  628. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  629. AC3Block *block = &s->blocks[blk];
  630. for (ch = 0; ch < s->channels; ch++) {
  631. int exp_strategy = s->exp_strategy[ch][blk];
  632. if (exp_strategy == EXP_REUSE)
  633. continue;
  634. group_size = exp_strategy + (exp_strategy == EXP_D45);
  635. nb_groups = exponent_group_tab[exp_strategy-1][s->nb_coefs[ch]];
  636. bit_count += 4 + (nb_groups * 7);
  637. p = block->exp[ch];
  638. /* DC exponent */
  639. exp1 = *p++;
  640. block->grouped_exp[ch][0] = exp1;
  641. /* remaining exponents are delta encoded */
  642. for (i = 1; i <= nb_groups; i++) {
  643. /* merge three delta in one code */
  644. exp0 = exp1;
  645. exp1 = p[0];
  646. p += group_size;
  647. delta0 = exp1 - exp0 + 2;
  648. av_assert2(delta0 >= 0 && delta0 <= 4);
  649. exp0 = exp1;
  650. exp1 = p[0];
  651. p += group_size;
  652. delta1 = exp1 - exp0 + 2;
  653. av_assert2(delta1 >= 0 && delta1 <= 4);
  654. exp0 = exp1;
  655. exp1 = p[0];
  656. p += group_size;
  657. delta2 = exp1 - exp0 + 2;
  658. av_assert2(delta2 >= 0 && delta2 <= 4);
  659. block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
  660. }
  661. }
  662. }
  663. s->exponent_bits = bit_count;
  664. }
  665. /**
  666. * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
  667. * Extract exponents from MDCT coefficients, calculate exponent strategies,
  668. * and encode final exponents.
  669. */
  670. static void process_exponents(AC3EncodeContext *s)
  671. {
  672. extract_exponents(s);
  673. compute_exp_strategy(s);
  674. encode_exponents(s);
  675. group_exponents(s);
  676. emms_c();
  677. }
  678. /**
  679. * Count frame bits that are based solely on fixed parameters.
  680. * This only has to be run once when the encoder is initialized.
  681. */
  682. static void count_frame_bits_fixed(AC3EncodeContext *s)
  683. {
  684. static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
  685. int blk;
  686. int frame_bits;
  687. /* assumptions:
  688. * no dynamic range codes
  689. * no channel coupling
  690. * bit allocation parameters do not change between blocks
  691. * SNR offsets do not change between blocks
  692. * no delta bit allocation
  693. * no skipped data
  694. * no auxilliary data
  695. */
  696. /* header size */
  697. frame_bits = 65;
  698. frame_bits += frame_bits_inc[s->channel_mode];
  699. /* audio blocks */
  700. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  701. frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
  702. if (s->channel_mode == AC3_CHMODE_STEREO) {
  703. frame_bits++; /* rematstr */
  704. }
  705. frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
  706. if (s->lfe_on)
  707. frame_bits++; /* lfeexpstr */
  708. frame_bits++; /* baie */
  709. frame_bits++; /* snr */
  710. frame_bits += 2; /* delta / skip */
  711. }
  712. frame_bits++; /* cplinu for block 0 */
  713. /* bit alloc info */
  714. /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
  715. /* csnroffset[6] */
  716. /* (fsnoffset[4] + fgaincod[4]) * c */
  717. frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
  718. /* auxdatae, crcrsv */
  719. frame_bits += 2;
  720. /* CRC */
  721. frame_bits += 16;
  722. s->frame_bits_fixed = frame_bits;
  723. }
  724. /**
  725. * Initialize bit allocation.
  726. * Set default parameter codes and calculate parameter values.
  727. */
  728. static void bit_alloc_init(AC3EncodeContext *s)
  729. {
  730. int ch;
  731. /* init default parameters */
  732. s->slow_decay_code = 2;
  733. s->fast_decay_code = 1;
  734. s->slow_gain_code = 1;
  735. s->db_per_bit_code = 3;
  736. s->floor_code = 7;
  737. for (ch = 0; ch < s->channels; ch++)
  738. s->fast_gain_code[ch] = 4;
  739. /* initial snr offset */
  740. s->coarse_snr_offset = 40;
  741. /* compute real values */
  742. /* currently none of these values change during encoding, so we can just
  743. set them once at initialization */
  744. s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
  745. s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
  746. s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
  747. s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
  748. s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
  749. count_frame_bits_fixed(s);
  750. }
  751. /**
  752. * Count the bits used to encode the frame, minus exponents and mantissas.
  753. * Bits based on fixed parameters have already been counted, so now we just
  754. * have to add the bits based on parameters that change during encoding.
  755. */
  756. static void count_frame_bits(AC3EncodeContext *s)
  757. {
  758. AC3EncOptions *opt = &s->options;
  759. int blk, ch;
  760. int frame_bits = 0;
  761. if (opt->audio_production_info)
  762. frame_bits += 7;
  763. if (s->bitstream_id == 6) {
  764. if (opt->extended_bsi_1)
  765. frame_bits += 14;
  766. if (opt->extended_bsi_2)
  767. frame_bits += 14;
  768. }
  769. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  770. /* stereo rematrixing */
  771. if (s->channel_mode == AC3_CHMODE_STEREO &&
  772. s->blocks[blk].new_rematrixing_strategy) {
  773. frame_bits += s->num_rematrixing_bands;
  774. }
  775. for (ch = 0; ch < s->fbw_channels; ch++) {
  776. if (s->exp_strategy[ch][blk] != EXP_REUSE)
  777. frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
  778. }
  779. }
  780. s->frame_bits = s->frame_bits_fixed + frame_bits;
  781. }
  782. /**
  783. * Finalize the mantissa bit count by adding in the grouped mantissas.
  784. */
  785. static int compute_mantissa_size_final(int mant_cnt[5])
  786. {
  787. // bap=1 : 3 mantissas in 5 bits
  788. int bits = (mant_cnt[1] / 3) * 5;
  789. // bap=2 : 3 mantissas in 7 bits
  790. // bap=4 : 2 mantissas in 7 bits
  791. bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
  792. // bap=3 : each mantissa is 3 bits
  793. bits += mant_cnt[3] * 3;
  794. return bits;
  795. }
  796. /**
  797. * Calculate masking curve based on the final exponents.
  798. * Also calculate the power spectral densities to use in future calculations.
  799. */
  800. static void bit_alloc_masking(AC3EncodeContext *s)
  801. {
  802. int blk, ch;
  803. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  804. AC3Block *block = &s->blocks[blk];
  805. for (ch = 0; ch < s->channels; ch++) {
  806. /* We only need psd and mask for calculating bap.
  807. Since we currently do not calculate bap when exponent
  808. strategy is EXP_REUSE we do not need to calculate psd or mask. */
  809. if (s->exp_strategy[ch][blk] != EXP_REUSE) {
  810. ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
  811. s->nb_coefs[ch],
  812. block->psd[ch], block->band_psd[ch]);
  813. ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
  814. 0, s->nb_coefs[ch],
  815. ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
  816. ch == s->lfe_channel,
  817. DBA_NONE, 0, NULL, NULL, NULL,
  818. block->mask[ch]);
  819. }
  820. }
  821. }
  822. }
  823. /**
  824. * Ensure that bap for each block and channel point to the current bap_buffer.
  825. * They may have been switched during the bit allocation search.
  826. */
  827. static void reset_block_bap(AC3EncodeContext *s)
  828. {
  829. int blk, ch;
  830. if (s->blocks[0].bap[0] == s->bap_buffer)
  831. return;
  832. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  833. for (ch = 0; ch < s->channels; ch++) {
  834. s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
  835. }
  836. }
  837. }
  838. /**
  839. * Run the bit allocation with a given SNR offset.
  840. * This calculates the bit allocation pointers that will be used to determine
  841. * the quantization of each mantissa.
  842. * @return the number of bits needed for mantissas if the given SNR offset is
  843. * is used.
  844. */
  845. static int bit_alloc(AC3EncodeContext *s, int snr_offset)
  846. {
  847. int blk, ch;
  848. int mantissa_bits;
  849. int mant_cnt[5];
  850. snr_offset = (snr_offset - 240) << 2;
  851. reset_block_bap(s);
  852. mantissa_bits = 0;
  853. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  854. AC3Block *block = &s->blocks[blk];
  855. AC3Block *ref_block;
  856. // initialize grouped mantissa counts. these are set so that they are
  857. // padded to the next whole group size when bits are counted in
  858. // compute_mantissa_size_final
  859. mant_cnt[0] = mant_cnt[3] = 0;
  860. mant_cnt[1] = mant_cnt[2] = 2;
  861. mant_cnt[4] = 1;
  862. for (ch = 0; ch < s->channels; ch++) {
  863. /* Currently the only bit allocation parameters which vary across
  864. blocks within a frame are the exponent values. We can take
  865. advantage of that by reusing the bit allocation pointers
  866. whenever we reuse exponents. */
  867. ref_block = block->exp_ref_block[ch];
  868. if (s->exp_strategy[ch][blk] != EXP_REUSE) {
  869. s->ac3dsp.bit_alloc_calc_bap(ref_block->mask[ch],
  870. ref_block->psd[ch], 0,
  871. s->nb_coefs[ch], snr_offset,
  872. s->bit_alloc.floor, ff_ac3_bap_tab,
  873. ref_block->bap[ch]);
  874. }
  875. mantissa_bits += s->ac3dsp.compute_mantissa_size(mant_cnt,
  876. ref_block->bap[ch],
  877. s->nb_coefs[ch]);
  878. }
  879. mantissa_bits += compute_mantissa_size_final(mant_cnt);
  880. }
  881. return mantissa_bits;
  882. }
  883. /**
  884. * Constant bitrate bit allocation search.
  885. * Find the largest SNR offset that will allow data to fit in the frame.
  886. */
  887. static int cbr_bit_allocation(AC3EncodeContext *s)
  888. {
  889. int ch;
  890. int bits_left;
  891. int snr_offset, snr_incr;
  892. bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
  893. if (bits_left < 0)
  894. return AVERROR(EINVAL);
  895. snr_offset = s->coarse_snr_offset << 4;
  896. /* if previous frame SNR offset was 1023, check if current frame can also
  897. use SNR offset of 1023. if so, skip the search. */
  898. if ((snr_offset | s->fine_snr_offset[0]) == 1023) {
  899. if (bit_alloc(s, 1023) <= bits_left)
  900. return 0;
  901. }
  902. while (snr_offset >= 0 &&
  903. bit_alloc(s, snr_offset) > bits_left) {
  904. snr_offset -= 64;
  905. }
  906. if (snr_offset < 0)
  907. return AVERROR(EINVAL);
  908. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  909. for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
  910. while (snr_offset + snr_incr <= 1023 &&
  911. bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
  912. snr_offset += snr_incr;
  913. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  914. }
  915. }
  916. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  917. reset_block_bap(s);
  918. s->coarse_snr_offset = snr_offset >> 4;
  919. for (ch = 0; ch < s->channels; ch++)
  920. s->fine_snr_offset[ch] = snr_offset & 0xF;
  921. return 0;
  922. }
  923. /**
  924. * Downgrade exponent strategies to reduce the bits used by the exponents.
  925. * This is a fallback for when bit allocation fails with the normal exponent
  926. * strategies. Each time this function is run it only downgrades the
  927. * strategy in 1 channel of 1 block.
  928. * @return non-zero if downgrade was unsuccessful
  929. */
  930. static int downgrade_exponents(AC3EncodeContext *s)
  931. {
  932. int ch, blk;
  933. for (ch = 0; ch < s->fbw_channels; ch++) {
  934. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  935. if (s->exp_strategy[ch][blk] == EXP_D15) {
  936. s->exp_strategy[ch][blk] = EXP_D25;
  937. return 0;
  938. }
  939. }
  940. }
  941. for (ch = 0; ch < s->fbw_channels; ch++) {
  942. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  943. if (s->exp_strategy[ch][blk] == EXP_D25) {
  944. s->exp_strategy[ch][blk] = EXP_D45;
  945. return 0;
  946. }
  947. }
  948. }
  949. for (ch = 0; ch < s->fbw_channels; ch++) {
  950. /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
  951. the block number > 0 */
  952. for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
  953. if (s->exp_strategy[ch][blk] > EXP_REUSE) {
  954. s->exp_strategy[ch][blk] = EXP_REUSE;
  955. return 0;
  956. }
  957. }
  958. }
  959. return -1;
  960. }
  961. /**
  962. * Perform bit allocation search.
  963. * Finds the SNR offset value that maximizes quality and fits in the specified
  964. * frame size. Output is the SNR offset and a set of bit allocation pointers
  965. * used to quantize the mantissas.
  966. */
  967. static int compute_bit_allocation(AC3EncodeContext *s)
  968. {
  969. int ret;
  970. count_frame_bits(s);
  971. bit_alloc_masking(s);
  972. ret = cbr_bit_allocation(s);
  973. while (ret) {
  974. /* fallback 1: downgrade exponents */
  975. if (!downgrade_exponents(s)) {
  976. extract_exponents(s);
  977. encode_exponents(s);
  978. group_exponents(s);
  979. ret = compute_bit_allocation(s);
  980. continue;
  981. }
  982. /* fallbacks were not enough... */
  983. break;
  984. }
  985. return ret;
  986. }
  987. /**
  988. * Symmetric quantization on 'levels' levels.
  989. */
  990. static inline int sym_quant(int c, int e, int levels)
  991. {
  992. int v = (((levels * c) >> (24 - e)) + levels) >> 1;
  993. av_assert2(v >= 0 && v < levels);
  994. return v;
  995. }
  996. /**
  997. * Asymmetric quantization on 2^qbits levels.
  998. */
  999. static inline int asym_quant(int c, int e, int qbits)
  1000. {
  1001. int lshift, m, v;
  1002. lshift = e + qbits - 24;
  1003. if (lshift >= 0)
  1004. v = c << lshift;
  1005. else
  1006. v = c >> (-lshift);
  1007. /* rounding */
  1008. v = (v + 1) >> 1;
  1009. m = (1 << (qbits-1));
  1010. if (v >= m)
  1011. v = m - 1;
  1012. av_assert2(v >= -m);
  1013. return v & ((1 << qbits)-1);
  1014. }
  1015. /**
  1016. * Quantize a set of mantissas for a single channel in a single block.
  1017. */
  1018. static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
  1019. uint8_t *exp,
  1020. uint8_t *bap, uint16_t *qmant, int n)
  1021. {
  1022. int i;
  1023. for (i = 0; i < n; i++) {
  1024. int v;
  1025. int c = fixed_coef[i];
  1026. int e = exp[i];
  1027. int b = bap[i];
  1028. switch (b) {
  1029. case 0:
  1030. v = 0;
  1031. break;
  1032. case 1:
  1033. v = sym_quant(c, e, 3);
  1034. switch (s->mant1_cnt) {
  1035. case 0:
  1036. s->qmant1_ptr = &qmant[i];
  1037. v = 9 * v;
  1038. s->mant1_cnt = 1;
  1039. break;
  1040. case 1:
  1041. *s->qmant1_ptr += 3 * v;
  1042. s->mant1_cnt = 2;
  1043. v = 128;
  1044. break;
  1045. default:
  1046. *s->qmant1_ptr += v;
  1047. s->mant1_cnt = 0;
  1048. v = 128;
  1049. break;
  1050. }
  1051. break;
  1052. case 2:
  1053. v = sym_quant(c, e, 5);
  1054. switch (s->mant2_cnt) {
  1055. case 0:
  1056. s->qmant2_ptr = &qmant[i];
  1057. v = 25 * v;
  1058. s->mant2_cnt = 1;
  1059. break;
  1060. case 1:
  1061. *s->qmant2_ptr += 5 * v;
  1062. s->mant2_cnt = 2;
  1063. v = 128;
  1064. break;
  1065. default:
  1066. *s->qmant2_ptr += v;
  1067. s->mant2_cnt = 0;
  1068. v = 128;
  1069. break;
  1070. }
  1071. break;
  1072. case 3:
  1073. v = sym_quant(c, e, 7);
  1074. break;
  1075. case 4:
  1076. v = sym_quant(c, e, 11);
  1077. switch (s->mant4_cnt) {
  1078. case 0:
  1079. s->qmant4_ptr = &qmant[i];
  1080. v = 11 * v;
  1081. s->mant4_cnt = 1;
  1082. break;
  1083. default:
  1084. *s->qmant4_ptr += v;
  1085. s->mant4_cnt = 0;
  1086. v = 128;
  1087. break;
  1088. }
  1089. break;
  1090. case 5:
  1091. v = sym_quant(c, e, 15);
  1092. break;
  1093. case 14:
  1094. v = asym_quant(c, e, 14);
  1095. break;
  1096. case 15:
  1097. v = asym_quant(c, e, 16);
  1098. break;
  1099. default:
  1100. v = asym_quant(c, e, b - 1);
  1101. break;
  1102. }
  1103. qmant[i] = v;
  1104. }
  1105. }
  1106. /**
  1107. * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
  1108. */
  1109. static void quantize_mantissas(AC3EncodeContext *s)
  1110. {
  1111. int blk, ch;
  1112. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1113. AC3Block *block = &s->blocks[blk];
  1114. AC3Block *ref_block;
  1115. AC3Mant m = { 0 };
  1116. for (ch = 0; ch < s->channels; ch++) {
  1117. ref_block = block->exp_ref_block[ch];
  1118. quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
  1119. ref_block->exp[ch], ref_block->bap[ch],
  1120. block->qmant[ch], s->nb_coefs[ch]);
  1121. }
  1122. }
  1123. }
  1124. /**
  1125. * Write the AC-3 frame header to the output bitstream.
  1126. */
  1127. static void output_frame_header(AC3EncodeContext *s)
  1128. {
  1129. AC3EncOptions *opt = &s->options;
  1130. put_bits(&s->pb, 16, 0x0b77); /* frame header */
  1131. put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
  1132. put_bits(&s->pb, 2, s->bit_alloc.sr_code);
  1133. put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
  1134. put_bits(&s->pb, 5, s->bitstream_id);
  1135. put_bits(&s->pb, 3, s->bitstream_mode);
  1136. put_bits(&s->pb, 3, s->channel_mode);
  1137. if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
  1138. put_bits(&s->pb, 2, s->center_mix_level);
  1139. if (s->channel_mode & 0x04)
  1140. put_bits(&s->pb, 2, s->surround_mix_level);
  1141. if (s->channel_mode == AC3_CHMODE_STEREO)
  1142. put_bits(&s->pb, 2, opt->dolby_surround_mode);
  1143. put_bits(&s->pb, 1, s->lfe_on); /* LFE */
  1144. put_bits(&s->pb, 5, -opt->dialogue_level);
  1145. put_bits(&s->pb, 1, 0); /* no compression control word */
  1146. put_bits(&s->pb, 1, 0); /* no lang code */
  1147. put_bits(&s->pb, 1, opt->audio_production_info);
  1148. if (opt->audio_production_info) {
  1149. put_bits(&s->pb, 5, opt->mixing_level - 80);
  1150. put_bits(&s->pb, 2, opt->room_type);
  1151. }
  1152. put_bits(&s->pb, 1, opt->copyright);
  1153. put_bits(&s->pb, 1, opt->original);
  1154. if (s->bitstream_id == 6) {
  1155. /* alternate bit stream syntax */
  1156. put_bits(&s->pb, 1, opt->extended_bsi_1);
  1157. if (opt->extended_bsi_1) {
  1158. put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
  1159. put_bits(&s->pb, 3, s->ltrt_center_mix_level);
  1160. put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
  1161. put_bits(&s->pb, 3, s->loro_center_mix_level);
  1162. put_bits(&s->pb, 3, s->loro_surround_mix_level);
  1163. }
  1164. put_bits(&s->pb, 1, opt->extended_bsi_2);
  1165. if (opt->extended_bsi_2) {
  1166. put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
  1167. put_bits(&s->pb, 2, opt->dolby_headphone_mode);
  1168. put_bits(&s->pb, 1, opt->ad_converter_type);
  1169. put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
  1170. }
  1171. } else {
  1172. put_bits(&s->pb, 1, 0); /* no time code 1 */
  1173. put_bits(&s->pb, 1, 0); /* no time code 2 */
  1174. }
  1175. put_bits(&s->pb, 1, 0); /* no additional bit stream info */
  1176. }
  1177. /**
  1178. * Write one audio block to the output bitstream.
  1179. */
  1180. static void output_audio_block(AC3EncodeContext *s, int blk)
  1181. {
  1182. int ch, i, baie, rbnd;
  1183. AC3Block *block = &s->blocks[blk];
  1184. /* block switching */
  1185. for (ch = 0; ch < s->fbw_channels; ch++)
  1186. put_bits(&s->pb, 1, 0);
  1187. /* dither flags */
  1188. for (ch = 0; ch < s->fbw_channels; ch++)
  1189. put_bits(&s->pb, 1, 1);
  1190. /* dynamic range codes */
  1191. put_bits(&s->pb, 1, 0);
  1192. /* channel coupling */
  1193. if (!blk) {
  1194. put_bits(&s->pb, 1, 1); /* coupling strategy present */
  1195. put_bits(&s->pb, 1, 0); /* no coupling strategy */
  1196. } else {
  1197. put_bits(&s->pb, 1, 0); /* no new coupling strategy */
  1198. }
  1199. /* stereo rematrixing */
  1200. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1201. put_bits(&s->pb, 1, block->new_rematrixing_strategy);
  1202. if (block->new_rematrixing_strategy) {
  1203. /* rematrixing flags */
  1204. for (rbnd = 0; rbnd < s->num_rematrixing_bands; rbnd++)
  1205. put_bits(&s->pb, 1, block->rematrixing_flags[rbnd]);
  1206. }
  1207. }
  1208. /* exponent strategy */
  1209. for (ch = 0; ch < s->fbw_channels; ch++)
  1210. put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
  1211. if (s->lfe_on)
  1212. put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
  1213. /* bandwidth */
  1214. for (ch = 0; ch < s->fbw_channels; ch++) {
  1215. if (s->exp_strategy[ch][blk] != EXP_REUSE)
  1216. put_bits(&s->pb, 6, s->bandwidth_code);
  1217. }
  1218. /* exponents */
  1219. for (ch = 0; ch < s->channels; ch++) {
  1220. int nb_groups;
  1221. if (s->exp_strategy[ch][blk] == EXP_REUSE)
  1222. continue;
  1223. /* DC exponent */
  1224. put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
  1225. /* exponent groups */
  1226. nb_groups = exponent_group_tab[s->exp_strategy[ch][blk]-1][s->nb_coefs[ch]];
  1227. for (i = 1; i <= nb_groups; i++)
  1228. put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
  1229. /* gain range info */
  1230. if (ch != s->lfe_channel)
  1231. put_bits(&s->pb, 2, 0);
  1232. }
  1233. /* bit allocation info */
  1234. baie = (blk == 0);
  1235. put_bits(&s->pb, 1, baie);
  1236. if (baie) {
  1237. put_bits(&s->pb, 2, s->slow_decay_code);
  1238. put_bits(&s->pb, 2, s->fast_decay_code);
  1239. put_bits(&s->pb, 2, s->slow_gain_code);
  1240. put_bits(&s->pb, 2, s->db_per_bit_code);
  1241. put_bits(&s->pb, 3, s->floor_code);
  1242. }
  1243. /* snr offset */
  1244. put_bits(&s->pb, 1, baie);
  1245. if (baie) {
  1246. put_bits(&s->pb, 6, s->coarse_snr_offset);
  1247. for (ch = 0; ch < s->channels; ch++) {
  1248. put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
  1249. put_bits(&s->pb, 3, s->fast_gain_code[ch]);
  1250. }
  1251. }
  1252. put_bits(&s->pb, 1, 0); /* no delta bit allocation */
  1253. put_bits(&s->pb, 1, 0); /* no data to skip */
  1254. /* mantissas */
  1255. for (ch = 0; ch < s->channels; ch++) {
  1256. int b, q;
  1257. AC3Block *ref_block = block->exp_ref_block[ch];
  1258. for (i = 0; i < s->nb_coefs[ch]; i++) {
  1259. q = block->qmant[ch][i];
  1260. b = ref_block->bap[ch][i];
  1261. switch (b) {
  1262. case 0: break;
  1263. case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
  1264. case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
  1265. case 3: put_bits(&s->pb, 3, q); break;
  1266. case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
  1267. case 14: put_bits(&s->pb, 14, q); break;
  1268. case 15: put_bits(&s->pb, 16, q); break;
  1269. default: put_bits(&s->pb, b-1, q); break;
  1270. }
  1271. }
  1272. }
  1273. }
  1274. /** CRC-16 Polynomial */
  1275. #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
  1276. static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
  1277. {
  1278. unsigned int c;
  1279. c = 0;
  1280. while (a) {
  1281. if (a & 1)
  1282. c ^= b;
  1283. a = a >> 1;
  1284. b = b << 1;
  1285. if (b & (1 << 16))
  1286. b ^= poly;
  1287. }
  1288. return c;
  1289. }
  1290. static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
  1291. {
  1292. unsigned int r;
  1293. r = 1;
  1294. while (n) {
  1295. if (n & 1)
  1296. r = mul_poly(r, a, poly);
  1297. a = mul_poly(a, a, poly);
  1298. n >>= 1;
  1299. }
  1300. return r;
  1301. }
  1302. /**
  1303. * Fill the end of the frame with 0's and compute the two CRCs.
  1304. */
  1305. static void output_frame_end(AC3EncodeContext *s)
  1306. {
  1307. const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
  1308. int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
  1309. uint8_t *frame;
  1310. frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
  1311. /* pad the remainder of the frame with zeros */
  1312. av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
  1313. flush_put_bits(&s->pb);
  1314. frame = s->pb.buf;
  1315. pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
  1316. av_assert2(pad_bytes >= 0);
  1317. if (pad_bytes > 0)
  1318. memset(put_bits_ptr(&s->pb), 0, pad_bytes);
  1319. /* compute crc1 */
  1320. /* this is not so easy because it is at the beginning of the data... */
  1321. crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
  1322. crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
  1323. crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
  1324. AV_WB16(frame + 2, crc1);
  1325. /* compute crc2 */
  1326. crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
  1327. s->frame_size - frame_size_58 - 3);
  1328. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1329. /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
  1330. if (crc2 == 0x770B) {
  1331. frame[s->frame_size - 3] ^= 0x1;
  1332. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1333. }
  1334. crc2 = av_bswap16(crc2);
  1335. AV_WB16(frame + s->frame_size - 2, crc2);
  1336. }
  1337. /**
  1338. * Write the frame to the output bitstream.
  1339. */
  1340. static void output_frame(AC3EncodeContext *s, unsigned char *frame)
  1341. {
  1342. int blk;
  1343. init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
  1344. output_frame_header(s);
  1345. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1346. output_audio_block(s, blk);
  1347. output_frame_end(s);
  1348. }
  1349. static void dprint_options(AVCodecContext *avctx)
  1350. {
  1351. #ifdef DEBUG
  1352. AC3EncodeContext *s = avctx->priv_data;
  1353. AC3EncOptions *opt = &s->options;
  1354. char strbuf[32];
  1355. switch (s->bitstream_id) {
  1356. case 6: av_strlcpy(strbuf, "AC-3 (alt syntax)", 32); break;
  1357. case 8: av_strlcpy(strbuf, "AC-3 (standard)", 32); break;
  1358. case 9: av_strlcpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
  1359. case 10: av_strlcpy(strbuf, "AC-3 (dnet quater-rate", 32); break;
  1360. default: snprintf(strbuf, 32, "ERROR");
  1361. }
  1362. av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
  1363. av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
  1364. av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
  1365. av_dlog(avctx, "channel_layout: %s\n", strbuf);
  1366. av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
  1367. av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
  1368. if (s->cutoff)
  1369. av_dlog(avctx, "cutoff: %d\n", s->cutoff);
  1370. av_dlog(avctx, "per_frame_metadata: %s\n",
  1371. opt->allow_per_frame_metadata?"on":"off");
  1372. if (s->has_center)
  1373. av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
  1374. s->center_mix_level);
  1375. else
  1376. av_dlog(avctx, "center_mixlev: {not written}\n");
  1377. if (s->has_surround)
  1378. av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
  1379. s->surround_mix_level);
  1380. else
  1381. av_dlog(avctx, "surround_mixlev: {not written}\n");
  1382. if (opt->audio_production_info) {
  1383. av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
  1384. switch (opt->room_type) {
  1385. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  1386. case 1: av_strlcpy(strbuf, "large", 32); break;
  1387. case 2: av_strlcpy(strbuf, "small", 32); break;
  1388. default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
  1389. }
  1390. av_dlog(avctx, "room_type: %s\n", strbuf);
  1391. } else {
  1392. av_dlog(avctx, "mixing_level: {not written}\n");
  1393. av_dlog(avctx, "room_type: {not written}\n");
  1394. }
  1395. av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
  1396. av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
  1397. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1398. switch (opt->dolby_surround_mode) {
  1399. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  1400. case 1: av_strlcpy(strbuf, "on", 32); break;
  1401. case 2: av_strlcpy(strbuf, "off", 32); break;
  1402. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
  1403. }
  1404. av_dlog(avctx, "dsur_mode: %s\n", strbuf);
  1405. } else {
  1406. av_dlog(avctx, "dsur_mode: {not written}\n");
  1407. }
  1408. av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
  1409. if (s->bitstream_id == 6) {
  1410. if (opt->extended_bsi_1) {
  1411. switch (opt->preferred_stereo_downmix) {
  1412. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  1413. case 1: av_strlcpy(strbuf, "ltrt", 32); break;
  1414. case 2: av_strlcpy(strbuf, "loro", 32); break;
  1415. default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
  1416. }
  1417. av_dlog(avctx, "dmix_mode: %s\n", strbuf);
  1418. av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
  1419. opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
  1420. av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
  1421. opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
  1422. av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
  1423. opt->loro_center_mix_level, s->loro_center_mix_level);
  1424. av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
  1425. opt->loro_surround_mix_level, s->loro_surround_mix_level);
  1426. } else {
  1427. av_dlog(avctx, "extended bitstream info 1: {not written}\n");
  1428. }
  1429. if (opt->extended_bsi_2) {
  1430. switch (opt->dolby_surround_ex_mode) {
  1431. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  1432. case 1: av_strlcpy(strbuf, "on", 32); break;
  1433. case 2: av_strlcpy(strbuf, "off", 32); break;
  1434. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
  1435. }
  1436. av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
  1437. switch (opt->dolby_headphone_mode) {
  1438. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  1439. case 1: av_strlcpy(strbuf, "on", 32); break;
  1440. case 2: av_strlcpy(strbuf, "off", 32); break;
  1441. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
  1442. }
  1443. av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
  1444. switch (opt->ad_converter_type) {
  1445. case 0: av_strlcpy(strbuf, "standard", 32); break;
  1446. case 1: av_strlcpy(strbuf, "hdcd", 32); break;
  1447. default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
  1448. }
  1449. av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
  1450. } else {
  1451. av_dlog(avctx, "extended bitstream info 2: {not written}\n");
  1452. }
  1453. }
  1454. #endif
  1455. }
  1456. #define FLT_OPTION_THRESHOLD 0.01
  1457. static int validate_float_option(float v, const float *v_list, int v_list_size)
  1458. {
  1459. int i;
  1460. for (i = 0; i < v_list_size; i++) {
  1461. if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
  1462. v > (v_list[i] - FLT_OPTION_THRESHOLD))
  1463. break;
  1464. }
  1465. if (i == v_list_size)
  1466. return -1;
  1467. return i;
  1468. }
  1469. static void validate_mix_level(void *log_ctx, const char *opt_name,
  1470. float *opt_param, const float *list,
  1471. int list_size, int default_value, int min_value,
  1472. int *ctx_param)
  1473. {
  1474. int mixlev = validate_float_option(*opt_param, list, list_size);
  1475. if (mixlev < min_value) {
  1476. mixlev = default_value;
  1477. if (*opt_param >= 0.0) {
  1478. av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
  1479. "default value: %0.3f\n", opt_name, list[mixlev]);
  1480. }
  1481. }
  1482. *opt_param = list[mixlev];
  1483. *ctx_param = mixlev;
  1484. }
  1485. /**
  1486. * Validate metadata options as set by AVOption system.
  1487. * These values can optionally be changed per-frame.
  1488. */
  1489. static int validate_metadata(AVCodecContext *avctx)
  1490. {
  1491. AC3EncodeContext *s = avctx->priv_data;
  1492. AC3EncOptions *opt = &s->options;
  1493. /* validate mixing levels */
  1494. if (s->has_center) {
  1495. validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
  1496. cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
  1497. &s->center_mix_level);
  1498. }
  1499. if (s->has_surround) {
  1500. validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
  1501. surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
  1502. &s->surround_mix_level);
  1503. }
  1504. /* set audio production info flag */
  1505. if (opt->mixing_level >= 0 || opt->room_type >= 0) {
  1506. if (opt->mixing_level < 0) {
  1507. av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
  1508. "room_type is set\n");
  1509. return AVERROR(EINVAL);
  1510. }
  1511. if (opt->mixing_level < 80) {
  1512. av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
  1513. "80dB and 111dB\n");
  1514. return AVERROR(EINVAL);
  1515. }
  1516. /* default room type */
  1517. if (opt->room_type < 0)
  1518. opt->room_type = 0;
  1519. opt->audio_production_info = 1;
  1520. } else {
  1521. opt->audio_production_info = 0;
  1522. }
  1523. /* set extended bsi 1 flag */
  1524. if ((s->has_center || s->has_surround) &&
  1525. (opt->preferred_stereo_downmix >= 0 ||
  1526. opt->ltrt_center_mix_level >= 0 ||
  1527. opt->ltrt_surround_mix_level >= 0 ||
  1528. opt->loro_center_mix_level >= 0 ||
  1529. opt->loro_surround_mix_level >= 0)) {
  1530. /* default preferred stereo downmix */
  1531. if (opt->preferred_stereo_downmix < 0)
  1532. opt->preferred_stereo_downmix = 0;
  1533. /* validate Lt/Rt center mix level */
  1534. validate_mix_level(avctx, "ltrt_center_mix_level",
  1535. &opt->ltrt_center_mix_level, extmixlev_options,
  1536. EXTMIXLEV_NUM_OPTIONS, 5, 0,
  1537. &s->ltrt_center_mix_level);
  1538. /* validate Lt/Rt surround mix level */
  1539. validate_mix_level(avctx, "ltrt_surround_mix_level",
  1540. &opt->ltrt_surround_mix_level, extmixlev_options,
  1541. EXTMIXLEV_NUM_OPTIONS, 6, 3,
  1542. &s->ltrt_surround_mix_level);
  1543. /* validate Lo/Ro center mix level */
  1544. validate_mix_level(avctx, "loro_center_mix_level",
  1545. &opt->loro_center_mix_level, extmixlev_options,
  1546. EXTMIXLEV_NUM_OPTIONS, 5, 0,
  1547. &s->loro_center_mix_level);
  1548. /* validate Lo/Ro surround mix level */
  1549. validate_mix_level(avctx, "loro_surround_mix_level",
  1550. &opt->loro_surround_mix_level, extmixlev_options,
  1551. EXTMIXLEV_NUM_OPTIONS, 6, 3,
  1552. &s->loro_surround_mix_level);
  1553. opt->extended_bsi_1 = 1;
  1554. } else {
  1555. opt->extended_bsi_1 = 0;
  1556. }
  1557. /* set extended bsi 2 flag */
  1558. if (opt->dolby_surround_ex_mode >= 0 ||
  1559. opt->dolby_headphone_mode >= 0 ||
  1560. opt->ad_converter_type >= 0) {
  1561. /* default dolby surround ex mode */
  1562. if (opt->dolby_surround_ex_mode < 0)
  1563. opt->dolby_surround_ex_mode = 0;
  1564. /* default dolby headphone mode */
  1565. if (opt->dolby_headphone_mode < 0)
  1566. opt->dolby_headphone_mode = 0;
  1567. /* default A/D converter type */
  1568. if (opt->ad_converter_type < 0)
  1569. opt->ad_converter_type = 0;
  1570. opt->extended_bsi_2 = 1;
  1571. } else {
  1572. opt->extended_bsi_2 = 0;
  1573. }
  1574. /* set bitstream id for alternate bitstream syntax */
  1575. if (opt->extended_bsi_1 || opt->extended_bsi_2) {
  1576. if (s->bitstream_id > 8 && s->bitstream_id < 11) {
  1577. static int warn_once = 1;
  1578. if (warn_once) {
  1579. av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
  1580. "not compatible with reduced samplerates. writing of "
  1581. "extended bitstream information will be disabled.\n");
  1582. warn_once = 0;
  1583. }
  1584. } else {
  1585. s->bitstream_id = 6;
  1586. }
  1587. }
  1588. return 0;
  1589. }
  1590. /**
  1591. * Encode a single AC-3 frame.
  1592. */
  1593. static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
  1594. int buf_size, void *data)
  1595. {
  1596. AC3EncodeContext *s = avctx->priv_data;
  1597. const SampleType *samples = data;
  1598. int ret;
  1599. if (s->options.allow_per_frame_metadata) {
  1600. ret = validate_metadata(avctx);
  1601. if (ret)
  1602. return ret;
  1603. }
  1604. if (s->bit_alloc.sr_code == 1)
  1605. adjust_frame_size(s);
  1606. deinterleave_input_samples(s, samples);
  1607. apply_mdct(s);
  1608. scale_coefficients(s);
  1609. compute_rematrixing_strategy(s);
  1610. apply_rematrixing(s);
  1611. process_exponents(s);
  1612. ret = compute_bit_allocation(s);
  1613. if (ret) {
  1614. av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
  1615. return ret;
  1616. }
  1617. quantize_mantissas(s);
  1618. output_frame(s, frame);
  1619. return s->frame_size;
  1620. }
  1621. /**
  1622. * Finalize encoding and free any memory allocated by the encoder.
  1623. */
  1624. static av_cold int ac3_encode_close(AVCodecContext *avctx)
  1625. {
  1626. int blk, ch;
  1627. AC3EncodeContext *s = avctx->priv_data;
  1628. for (ch = 0; ch < s->channels; ch++)
  1629. av_freep(&s->planar_samples[ch]);
  1630. av_freep(&s->planar_samples);
  1631. av_freep(&s->bap_buffer);
  1632. av_freep(&s->bap1_buffer);
  1633. av_freep(&s->mdct_coef_buffer);
  1634. av_freep(&s->fixed_coef_buffer);
  1635. av_freep(&s->exp_buffer);
  1636. av_freep(&s->grouped_exp_buffer);
  1637. av_freep(&s->psd_buffer);
  1638. av_freep(&s->band_psd_buffer);
  1639. av_freep(&s->mask_buffer);
  1640. av_freep(&s->qmant_buffer);
  1641. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1642. AC3Block *block = &s->blocks[blk];
  1643. av_freep(&block->bap);
  1644. av_freep(&block->mdct_coef);
  1645. av_freep(&block->fixed_coef);
  1646. av_freep(&block->exp);
  1647. av_freep(&block->grouped_exp);
  1648. av_freep(&block->psd);
  1649. av_freep(&block->band_psd);
  1650. av_freep(&block->mask);
  1651. av_freep(&block->qmant);
  1652. }
  1653. mdct_end(&s->mdct);
  1654. av_freep(&avctx->coded_frame);
  1655. return 0;
  1656. }
  1657. /**
  1658. * Set channel information during initialization.
  1659. */
  1660. static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
  1661. int64_t *channel_layout)
  1662. {
  1663. int ch_layout;
  1664. if (channels < 1 || channels > AC3_MAX_CHANNELS)
  1665. return AVERROR(EINVAL);
  1666. if ((uint64_t)*channel_layout > 0x7FF)
  1667. return AVERROR(EINVAL);
  1668. ch_layout = *channel_layout;
  1669. if (!ch_layout)
  1670. ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
  1671. s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
  1672. s->channels = channels;
  1673. s->fbw_channels = channels - s->lfe_on;
  1674. s->lfe_channel = s->lfe_on ? s->fbw_channels : -1;
  1675. if (s->lfe_on)
  1676. ch_layout -= AV_CH_LOW_FREQUENCY;
  1677. switch (ch_layout) {
  1678. case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
  1679. case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
  1680. case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
  1681. case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
  1682. case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
  1683. case AV_CH_LAYOUT_QUAD:
  1684. case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
  1685. case AV_CH_LAYOUT_5POINT0:
  1686. case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
  1687. default:
  1688. return AVERROR(EINVAL);
  1689. }
  1690. s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
  1691. s->has_surround = s->channel_mode & 0x04;
  1692. s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
  1693. *channel_layout = ch_layout;
  1694. if (s->lfe_on)
  1695. *channel_layout |= AV_CH_LOW_FREQUENCY;
  1696. return 0;
  1697. }
  1698. static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
  1699. {
  1700. int i, ret;
  1701. /* validate channel layout */
  1702. if (!avctx->channel_layout) {
  1703. av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
  1704. "encoder will guess the layout, but it "
  1705. "might be incorrect.\n");
  1706. }
  1707. ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
  1708. if (ret) {
  1709. av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
  1710. return ret;
  1711. }
  1712. /* validate sample rate */
  1713. for (i = 0; i < 9; i++) {
  1714. if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
  1715. break;
  1716. }
  1717. if (i == 9) {
  1718. av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
  1719. return AVERROR(EINVAL);
  1720. }
  1721. s->sample_rate = avctx->sample_rate;
  1722. s->bit_alloc.sr_shift = i % 3;
  1723. s->bit_alloc.sr_code = i / 3;
  1724. s->bitstream_id = 8 + s->bit_alloc.sr_shift;
  1725. /* validate bit rate */
  1726. for (i = 0; i < 19; i++) {
  1727. if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
  1728. break;
  1729. }
  1730. if (i == 19) {
  1731. av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
  1732. return AVERROR(EINVAL);
  1733. }
  1734. s->bit_rate = avctx->bit_rate;
  1735. s->frame_size_code = i << 1;
  1736. /* validate cutoff */
  1737. if (avctx->cutoff < 0) {
  1738. av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
  1739. return AVERROR(EINVAL);
  1740. }
  1741. s->cutoff = avctx->cutoff;
  1742. if (s->cutoff > (s->sample_rate >> 1))
  1743. s->cutoff = s->sample_rate >> 1;
  1744. /* validate audio service type / channels combination */
  1745. if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
  1746. avctx->channels == 1) ||
  1747. ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
  1748. avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
  1749. avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
  1750. && avctx->channels > 1)) {
  1751. av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
  1752. "specified number of channels\n");
  1753. return AVERROR(EINVAL);
  1754. }
  1755. ret = validate_metadata(avctx);
  1756. if (ret)
  1757. return ret;
  1758. s->rematrixing_enabled = s->options.stereo_rematrixing &&
  1759. (s->channel_mode == AC3_CHMODE_STEREO);
  1760. return 0;
  1761. }
  1762. /**
  1763. * Set bandwidth for all channels.
  1764. * The user can optionally supply a cutoff frequency. Otherwise an appropriate
  1765. * default value will be used.
  1766. */
  1767. static av_cold void set_bandwidth(AC3EncodeContext *s)
  1768. {
  1769. int ch;
  1770. if (s->cutoff) {
  1771. /* calculate bandwidth based on user-specified cutoff frequency */
  1772. int fbw_coeffs;
  1773. fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
  1774. s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
  1775. } else {
  1776. /* use default bandwidth setting */
  1777. s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
  1778. }
  1779. /* set number of coefficients for each channel */
  1780. for (ch = 0; ch < s->fbw_channels; ch++) {
  1781. s->nb_coefs[ch] = s->bandwidth_code * 3 + 73;
  1782. }
  1783. if (s->lfe_on)
  1784. s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
  1785. }
  1786. static av_cold int allocate_buffers(AVCodecContext *avctx)
  1787. {
  1788. int blk, ch;
  1789. AC3EncodeContext *s = avctx->priv_data;
  1790. FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
  1791. alloc_fail);
  1792. for (ch = 0; ch < s->channels; ch++) {
  1793. FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
  1794. (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
  1795. alloc_fail);
  1796. }
  1797. FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * s->channels *
  1798. AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
  1799. FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
  1800. AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
  1801. FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
  1802. AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
  1803. FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
  1804. AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
  1805. FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
  1806. 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
  1807. FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
  1808. AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
  1809. FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
  1810. 64 * sizeof(*s->band_psd_buffer), alloc_fail);
  1811. FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
  1812. 64 * sizeof(*s->mask_buffer), alloc_fail);
  1813. FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
  1814. AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
  1815. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1816. AC3Block *block = &s->blocks[blk];
  1817. FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
  1818. alloc_fail);
  1819. FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
  1820. alloc_fail);
  1821. FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
  1822. alloc_fail);
  1823. FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
  1824. alloc_fail);
  1825. FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
  1826. alloc_fail);
  1827. FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
  1828. alloc_fail);
  1829. FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
  1830. alloc_fail);
  1831. FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
  1832. alloc_fail);
  1833. for (ch = 0; ch < s->channels; ch++) {
  1834. /* arrangement: block, channel, coeff */
  1835. block->bap[ch] = &s->bap_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1836. block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1837. block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * s->channels + ch)];
  1838. block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1839. block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * s->channels + ch)];
  1840. block->mask[ch] = &s->mask_buffer [64 * (blk * s->channels + ch)];
  1841. block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1842. /* arrangement: channel, block, coeff */
  1843. block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
  1844. }
  1845. }
  1846. if (CONFIG_AC3ENC_FLOAT) {
  1847. FF_ALLOC_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * s->channels *
  1848. AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
  1849. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1850. AC3Block *block = &s->blocks[blk];
  1851. FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
  1852. sizeof(*block->fixed_coef), alloc_fail);
  1853. for (ch = 0; ch < s->channels; ch++)
  1854. block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
  1855. }
  1856. } else {
  1857. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1858. AC3Block *block = &s->blocks[blk];
  1859. FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
  1860. sizeof(*block->fixed_coef), alloc_fail);
  1861. for (ch = 0; ch < s->channels; ch++)
  1862. block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
  1863. }
  1864. }
  1865. return 0;
  1866. alloc_fail:
  1867. return AVERROR(ENOMEM);
  1868. }
  1869. /**
  1870. * Initialize the encoder.
  1871. */
  1872. static av_cold int ac3_encode_init(AVCodecContext *avctx)
  1873. {
  1874. AC3EncodeContext *s = avctx->priv_data;
  1875. int ret, frame_size_58;
  1876. avctx->frame_size = AC3_FRAME_SIZE;
  1877. ff_ac3_common_init();
  1878. ret = validate_options(avctx, s);
  1879. if (ret)
  1880. return ret;
  1881. s->bitstream_mode = avctx->audio_service_type;
  1882. if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
  1883. s->bitstream_mode = 0x7;
  1884. s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
  1885. s->bits_written = 0;
  1886. s->samples_written = 0;
  1887. s->frame_size = s->frame_size_min;
  1888. /* calculate crc_inv for both possible frame sizes */
  1889. frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
  1890. s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  1891. if (s->bit_alloc.sr_code == 1) {
  1892. frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
  1893. s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  1894. }
  1895. set_bandwidth(s);
  1896. exponent_init(s);
  1897. bit_alloc_init(s);
  1898. ret = mdct_init(avctx, &s->mdct, 9);
  1899. if (ret)
  1900. goto init_fail;
  1901. ret = allocate_buffers(avctx);
  1902. if (ret)
  1903. goto init_fail;
  1904. avctx->coded_frame= avcodec_alloc_frame();
  1905. dsputil_init(&s->dsp, avctx);
  1906. ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
  1907. dprint_options(avctx);
  1908. return 0;
  1909. init_fail:
  1910. ac3_encode_close(avctx);
  1911. return ret;
  1912. }