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.

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