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.

2259 lines
78KB

  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[AC3_MAX_CHANNELS]; ///< 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 blocks in a single channel.
  477. */
  478. static void compute_exp_strategy_ch(AC3EncodeContext *s, uint8_t *exp_strategy,
  479. uint8_t *exp)
  480. {
  481. int blk, blk1;
  482. int exp_diff;
  483. /* estimate if the exponent variation & decide if they should be
  484. reused in the next frame */
  485. exp_strategy[0] = EXP_NEW;
  486. exp += AC3_MAX_COEFS;
  487. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
  488. exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
  489. if (exp_diff > EXP_DIFF_THRESHOLD)
  490. exp_strategy[blk] = EXP_NEW;
  491. else
  492. exp_strategy[blk] = EXP_REUSE;
  493. exp += AC3_MAX_COEFS;
  494. }
  495. /* now select the encoding strategy type : if exponents are often
  496. recoded, we use a coarse encoding */
  497. blk = 0;
  498. while (blk < AC3_MAX_BLOCKS) {
  499. blk1 = blk + 1;
  500. while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
  501. blk1++;
  502. switch (blk1 - blk) {
  503. case 1: exp_strategy[blk] = EXP_D45; break;
  504. case 2:
  505. case 3: exp_strategy[blk] = EXP_D25; break;
  506. default: exp_strategy[blk] = EXP_D15; break;
  507. }
  508. blk = blk1;
  509. }
  510. }
  511. /**
  512. * Calculate exponent strategies for all channels.
  513. * Array arrangement is reversed to simplify the per-channel calculation.
  514. */
  515. static void compute_exp_strategy(AC3EncodeContext *s)
  516. {
  517. int ch, blk;
  518. for (ch = 0; ch < s->fbw_channels; ch++) {
  519. compute_exp_strategy_ch(s, s->exp_strategy[ch], s->blocks[0].exp[ch]);
  520. }
  521. if (s->lfe_on) {
  522. ch = s->lfe_channel;
  523. s->exp_strategy[ch][0] = EXP_D15;
  524. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
  525. s->exp_strategy[ch][blk] = EXP_REUSE;
  526. }
  527. }
  528. /**
  529. * Update the exponents so that they are the ones the decoder will decode.
  530. */
  531. static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy)
  532. {
  533. int nb_groups, i, k;
  534. nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
  535. /* for each group, compute the minimum exponent */
  536. switch(exp_strategy) {
  537. case EXP_D25:
  538. for (i = 1, k = 1; i <= nb_groups; i++) {
  539. uint8_t exp_min = exp[k];
  540. if (exp[k+1] < exp_min)
  541. exp_min = exp[k+1];
  542. exp[i] = exp_min;
  543. k += 2;
  544. }
  545. break;
  546. case EXP_D45:
  547. for (i = 1, k = 1; i <= nb_groups; i++) {
  548. uint8_t exp_min = exp[k];
  549. if (exp[k+1] < exp_min)
  550. exp_min = exp[k+1];
  551. if (exp[k+2] < exp_min)
  552. exp_min = exp[k+2];
  553. if (exp[k+3] < exp_min)
  554. exp_min = exp[k+3];
  555. exp[i] = exp_min;
  556. k += 4;
  557. }
  558. break;
  559. }
  560. /* constraint for DC exponent */
  561. if (exp[0] > 15)
  562. exp[0] = 15;
  563. /* decrease the delta between each groups to within 2 so that they can be
  564. differentially encoded */
  565. for (i = 1; i <= nb_groups; i++)
  566. exp[i] = FFMIN(exp[i], exp[i-1] + 2);
  567. i--;
  568. while (--i >= 0)
  569. exp[i] = FFMIN(exp[i], exp[i+1] + 2);
  570. /* now we have the exponent values the decoder will see */
  571. switch (exp_strategy) {
  572. case EXP_D25:
  573. for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
  574. uint8_t exp1 = exp[i];
  575. exp[k--] = exp1;
  576. exp[k--] = exp1;
  577. }
  578. break;
  579. case EXP_D45:
  580. for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
  581. exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
  582. k -= 4;
  583. }
  584. break;
  585. }
  586. }
  587. /**
  588. * Encode exponents from original extracted form to what the decoder will see.
  589. * This copies and groups exponents based on exponent strategy and reduces
  590. * deltas between adjacent exponent groups so that they can be differentially
  591. * encoded.
  592. */
  593. static void encode_exponents(AC3EncodeContext *s)
  594. {
  595. int blk, blk1, ch;
  596. uint8_t *exp, *exp_strategy;
  597. int nb_coefs, num_reuse_blocks;
  598. for (ch = 0; ch < s->channels; ch++) {
  599. exp = s->blocks[0].exp[ch];
  600. exp_strategy = s->exp_strategy[ch];
  601. nb_coefs = s->nb_coefs[ch];
  602. blk = 0;
  603. while (blk < AC3_MAX_BLOCKS) {
  604. blk1 = blk + 1;
  605. /* count the number of EXP_REUSE blocks after the current block
  606. and set exponent reference block pointers */
  607. s->blocks[blk].exp_ref_block[ch] = &s->blocks[blk];
  608. while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
  609. s->blocks[blk1].exp_ref_block[ch] = &s->blocks[blk];
  610. blk1++;
  611. }
  612. num_reuse_blocks = blk1 - blk - 1;
  613. /* for the EXP_REUSE case we select the min of the exponents */
  614. s->ac3dsp.ac3_exponent_min(exp, num_reuse_blocks, nb_coefs);
  615. encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk]);
  616. exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
  617. blk = blk1;
  618. }
  619. }
  620. }
  621. /**
  622. * Group exponents.
  623. * 3 delta-encoded exponents are in each 7-bit group. The number of groups
  624. * varies depending on exponent strategy and bandwidth.
  625. */
  626. static void group_exponents(AC3EncodeContext *s)
  627. {
  628. int blk, ch, i;
  629. int group_size, nb_groups, bit_count;
  630. uint8_t *p;
  631. int delta0, delta1, delta2;
  632. int exp0, exp1;
  633. bit_count = 0;
  634. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  635. AC3Block *block = &s->blocks[blk];
  636. for (ch = 0; ch < s->channels; ch++) {
  637. int exp_strategy = s->exp_strategy[ch][blk];
  638. if (exp_strategy == EXP_REUSE)
  639. continue;
  640. group_size = exp_strategy + (exp_strategy == EXP_D45);
  641. nb_groups = exponent_group_tab[exp_strategy-1][s->nb_coefs[ch]];
  642. bit_count += 4 + (nb_groups * 7);
  643. p = block->exp[ch];
  644. /* DC exponent */
  645. exp1 = *p++;
  646. block->grouped_exp[ch][0] = exp1;
  647. /* remaining exponents are delta encoded */
  648. for (i = 1; i <= nb_groups; i++) {
  649. /* merge three delta in one code */
  650. exp0 = exp1;
  651. exp1 = p[0];
  652. p += group_size;
  653. delta0 = exp1 - exp0 + 2;
  654. av_assert2(delta0 >= 0 && delta0 <= 4);
  655. exp0 = exp1;
  656. exp1 = p[0];
  657. p += group_size;
  658. delta1 = exp1 - exp0 + 2;
  659. av_assert2(delta1 >= 0 && delta1 <= 4);
  660. exp0 = exp1;
  661. exp1 = p[0];
  662. p += group_size;
  663. delta2 = exp1 - exp0 + 2;
  664. av_assert2(delta2 >= 0 && delta2 <= 4);
  665. block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
  666. }
  667. }
  668. }
  669. s->exponent_bits = bit_count;
  670. }
  671. /**
  672. * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
  673. * Extract exponents from MDCT coefficients, calculate exponent strategies,
  674. * and encode final exponents.
  675. */
  676. static void process_exponents(AC3EncodeContext *s)
  677. {
  678. extract_exponents(s);
  679. compute_exp_strategy(s);
  680. encode_exponents(s);
  681. group_exponents(s);
  682. emms_c();
  683. }
  684. /**
  685. * Count frame bits that are based solely on fixed parameters.
  686. * This only has to be run once when the encoder is initialized.
  687. */
  688. static void count_frame_bits_fixed(AC3EncodeContext *s)
  689. {
  690. static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
  691. int blk;
  692. int frame_bits;
  693. /* assumptions:
  694. * no dynamic range codes
  695. * no channel coupling
  696. * bit allocation parameters do not change between blocks
  697. * SNR offsets do not change between blocks
  698. * no delta bit allocation
  699. * no skipped data
  700. * no auxilliary data
  701. */
  702. /* header size */
  703. frame_bits = 65;
  704. frame_bits += frame_bits_inc[s->channel_mode];
  705. /* audio blocks */
  706. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  707. frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
  708. if (s->channel_mode == AC3_CHMODE_STEREO) {
  709. frame_bits++; /* rematstr */
  710. }
  711. frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
  712. if (s->lfe_on)
  713. frame_bits++; /* lfeexpstr */
  714. frame_bits++; /* baie */
  715. frame_bits++; /* snr */
  716. frame_bits += 2; /* delta / skip */
  717. }
  718. frame_bits++; /* cplinu for block 0 */
  719. /* bit alloc info */
  720. /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
  721. /* csnroffset[6] */
  722. /* (fsnoffset[4] + fgaincod[4]) * c */
  723. frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
  724. /* auxdatae, crcrsv */
  725. frame_bits += 2;
  726. /* CRC */
  727. frame_bits += 16;
  728. s->frame_bits_fixed = frame_bits;
  729. }
  730. /**
  731. * Initialize bit allocation.
  732. * Set default parameter codes and calculate parameter values.
  733. */
  734. static void bit_alloc_init(AC3EncodeContext *s)
  735. {
  736. int ch;
  737. /* init default parameters */
  738. s->slow_decay_code = 2;
  739. s->fast_decay_code = 1;
  740. s->slow_gain_code = 1;
  741. s->db_per_bit_code = 3;
  742. s->floor_code = 7;
  743. for (ch = 0; ch < s->channels; ch++)
  744. s->fast_gain_code[ch] = 4;
  745. /* initial snr offset */
  746. s->coarse_snr_offset = 40;
  747. /* compute real values */
  748. /* currently none of these values change during encoding, so we can just
  749. set them once at initialization */
  750. s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
  751. s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
  752. s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
  753. s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
  754. s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
  755. count_frame_bits_fixed(s);
  756. }
  757. /**
  758. * Count the bits used to encode the frame, minus exponents and mantissas.
  759. * Bits based on fixed parameters have already been counted, so now we just
  760. * have to add the bits based on parameters that change during encoding.
  761. */
  762. static void count_frame_bits(AC3EncodeContext *s)
  763. {
  764. AC3EncOptions *opt = &s->options;
  765. int blk, ch;
  766. int frame_bits = 0;
  767. if (opt->audio_production_info)
  768. frame_bits += 7;
  769. if (s->bitstream_id == 6) {
  770. if (opt->extended_bsi_1)
  771. frame_bits += 14;
  772. if (opt->extended_bsi_2)
  773. frame_bits += 14;
  774. }
  775. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  776. /* stereo rematrixing */
  777. if (s->channel_mode == AC3_CHMODE_STEREO &&
  778. s->blocks[blk].new_rematrixing_strategy) {
  779. frame_bits += s->num_rematrixing_bands;
  780. }
  781. for (ch = 0; ch < s->fbw_channels; ch++) {
  782. if (s->exp_strategy[ch][blk] != EXP_REUSE)
  783. frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
  784. }
  785. }
  786. s->frame_bits = s->frame_bits_fixed + frame_bits;
  787. }
  788. /**
  789. * Finalize the mantissa bit count by adding in the grouped mantissas.
  790. */
  791. static int compute_mantissa_size_final(int mant_cnt[5])
  792. {
  793. // bap=1 : 3 mantissas in 5 bits
  794. int bits = (mant_cnt[1] / 3) * 5;
  795. // bap=2 : 3 mantissas in 7 bits
  796. // bap=4 : 2 mantissas in 7 bits
  797. bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
  798. // bap=3 : each mantissa is 3 bits
  799. bits += mant_cnt[3] * 3;
  800. return bits;
  801. }
  802. /**
  803. * Calculate masking curve based on the final exponents.
  804. * Also calculate the power spectral densities to use in future calculations.
  805. */
  806. static void bit_alloc_masking(AC3EncodeContext *s)
  807. {
  808. int blk, ch;
  809. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  810. AC3Block *block = &s->blocks[blk];
  811. for (ch = 0; ch < s->channels; ch++) {
  812. /* We only need psd and mask for calculating bap.
  813. Since we currently do not calculate bap when exponent
  814. strategy is EXP_REUSE we do not need to calculate psd or mask. */
  815. if (s->exp_strategy[ch][blk] != EXP_REUSE) {
  816. ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
  817. s->nb_coefs[ch],
  818. block->psd[ch], block->band_psd[ch]);
  819. ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
  820. 0, s->nb_coefs[ch],
  821. ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
  822. ch == s->lfe_channel,
  823. DBA_NONE, 0, NULL, NULL, NULL,
  824. block->mask[ch]);
  825. }
  826. }
  827. }
  828. }
  829. /**
  830. * Ensure that bap for each block and channel point to the current bap_buffer.
  831. * They may have been switched during the bit allocation search.
  832. */
  833. static void reset_block_bap(AC3EncodeContext *s)
  834. {
  835. int blk, ch;
  836. if (s->blocks[0].bap[0] == s->bap_buffer)
  837. return;
  838. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  839. for (ch = 0; ch < s->channels; ch++) {
  840. s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
  841. }
  842. }
  843. }
  844. /**
  845. * Run the bit allocation with a given SNR offset.
  846. * This calculates the bit allocation pointers that will be used to determine
  847. * the quantization of each mantissa.
  848. * @return the number of bits needed for mantissas if the given SNR offset is
  849. * is used.
  850. */
  851. static int bit_alloc(AC3EncodeContext *s, int snr_offset)
  852. {
  853. int blk, ch;
  854. int mantissa_bits;
  855. int mant_cnt[5];
  856. snr_offset = (snr_offset - 240) << 2;
  857. reset_block_bap(s);
  858. mantissa_bits = 0;
  859. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  860. AC3Block *block = &s->blocks[blk];
  861. AC3Block *ref_block;
  862. // initialize grouped mantissa counts. these are set so that they are
  863. // padded to the next whole group size when bits are counted in
  864. // compute_mantissa_size_final
  865. mant_cnt[0] = mant_cnt[3] = 0;
  866. mant_cnt[1] = mant_cnt[2] = 2;
  867. mant_cnt[4] = 1;
  868. for (ch = 0; ch < s->channels; ch++) {
  869. /* Currently the only bit allocation parameters which vary across
  870. blocks within a frame are the exponent values. We can take
  871. advantage of that by reusing the bit allocation pointers
  872. whenever we reuse exponents. */
  873. ref_block = block->exp_ref_block[ch];
  874. if (s->exp_strategy[ch][blk] != EXP_REUSE) {
  875. s->ac3dsp.bit_alloc_calc_bap(ref_block->mask[ch],
  876. ref_block->psd[ch], 0,
  877. s->nb_coefs[ch], snr_offset,
  878. s->bit_alloc.floor, ff_ac3_bap_tab,
  879. ref_block->bap[ch]);
  880. }
  881. mantissa_bits += s->ac3dsp.compute_mantissa_size(mant_cnt,
  882. ref_block->bap[ch],
  883. s->nb_coefs[ch]);
  884. }
  885. mantissa_bits += compute_mantissa_size_final(mant_cnt);
  886. }
  887. return mantissa_bits;
  888. }
  889. /**
  890. * Constant bitrate bit allocation search.
  891. * Find the largest SNR offset that will allow data to fit in the frame.
  892. */
  893. static int cbr_bit_allocation(AC3EncodeContext *s)
  894. {
  895. int ch;
  896. int bits_left;
  897. int snr_offset, snr_incr;
  898. bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
  899. av_assert2(bits_left >= 0);
  900. snr_offset = s->coarse_snr_offset << 4;
  901. /* if previous frame SNR offset was 1023, check if current frame can also
  902. use SNR offset of 1023. if so, skip the search. */
  903. if ((snr_offset | s->fine_snr_offset[0]) == 1023) {
  904. if (bit_alloc(s, 1023) <= bits_left)
  905. return 0;
  906. }
  907. while (snr_offset >= 0 &&
  908. bit_alloc(s, snr_offset) > bits_left) {
  909. snr_offset -= 64;
  910. }
  911. if (snr_offset < 0)
  912. return AVERROR(EINVAL);
  913. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  914. for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
  915. while (snr_offset + snr_incr <= 1023 &&
  916. bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
  917. snr_offset += snr_incr;
  918. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  919. }
  920. }
  921. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  922. reset_block_bap(s);
  923. s->coarse_snr_offset = snr_offset >> 4;
  924. for (ch = 0; ch < s->channels; ch++)
  925. s->fine_snr_offset[ch] = snr_offset & 0xF;
  926. return 0;
  927. }
  928. /**
  929. * Downgrade exponent strategies to reduce the bits used by the exponents.
  930. * This is a fallback for when bit allocation fails with the normal exponent
  931. * strategies. Each time this function is run it only downgrades the
  932. * strategy in 1 channel of 1 block.
  933. * @return non-zero if downgrade was unsuccessful
  934. */
  935. static int downgrade_exponents(AC3EncodeContext *s)
  936. {
  937. int ch, blk;
  938. for (ch = 0; ch < s->fbw_channels; ch++) {
  939. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  940. if (s->exp_strategy[ch][blk] == EXP_D15) {
  941. s->exp_strategy[ch][blk] = EXP_D25;
  942. return 0;
  943. }
  944. }
  945. }
  946. for (ch = 0; ch < s->fbw_channels; ch++) {
  947. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  948. if (s->exp_strategy[ch][blk] == EXP_D25) {
  949. s->exp_strategy[ch][blk] = EXP_D45;
  950. return 0;
  951. }
  952. }
  953. }
  954. for (ch = 0; ch < s->fbw_channels; ch++) {
  955. /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
  956. the block number > 0 */
  957. for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
  958. if (s->exp_strategy[ch][blk] > EXP_REUSE) {
  959. s->exp_strategy[ch][blk] = EXP_REUSE;
  960. return 0;
  961. }
  962. }
  963. }
  964. return -1;
  965. }
  966. /**
  967. * Reduce the bandwidth to reduce the number of bits used for a given SNR offset.
  968. * This is a second fallback for when bit allocation still fails after exponents
  969. * have been downgraded.
  970. * @return non-zero if bandwidth reduction was unsuccessful
  971. */
  972. static int reduce_bandwidth(AC3EncodeContext *s, int min_bw_code)
  973. {
  974. int ch;
  975. if (s->bandwidth_code[0] > min_bw_code) {
  976. for (ch = 0; ch < s->fbw_channels; ch++) {
  977. s->bandwidth_code[ch]--;
  978. s->nb_coefs[ch] = s->bandwidth_code[ch] * 3 + 73;
  979. }
  980. return 0;
  981. }
  982. return -1;
  983. }
  984. /**
  985. * Perform bit allocation search.
  986. * Finds the SNR offset value that maximizes quality and fits in the specified
  987. * frame size. Output is the SNR offset and a set of bit allocation pointers
  988. * used to quantize the mantissas.
  989. */
  990. static int compute_bit_allocation(AC3EncodeContext *s)
  991. {
  992. int ret;
  993. count_frame_bits(s);
  994. bit_alloc_masking(s);
  995. ret = cbr_bit_allocation(s);
  996. while (ret) {
  997. /* fallback 1: downgrade exponents */
  998. if (!downgrade_exponents(s)) {
  999. extract_exponents(s);
  1000. encode_exponents(s);
  1001. group_exponents(s);
  1002. ret = compute_bit_allocation(s);
  1003. continue;
  1004. }
  1005. /* fallback 2: reduce bandwidth */
  1006. /* only do this if the user has not specified a specific cutoff
  1007. frequency */
  1008. if (!s->cutoff && !reduce_bandwidth(s, 0)) {
  1009. process_exponents(s);
  1010. ret = compute_bit_allocation(s);
  1011. continue;
  1012. }
  1013. /* fallbacks were not enough... */
  1014. break;
  1015. }
  1016. return ret;
  1017. }
  1018. /**
  1019. * Symmetric quantization on 'levels' levels.
  1020. */
  1021. static inline int sym_quant(int c, int e, int levels)
  1022. {
  1023. int v = (((levels * c) >> (24 - e)) + levels) >> 1;
  1024. av_assert2(v >= 0 && v < levels);
  1025. return v;
  1026. }
  1027. /**
  1028. * Asymmetric quantization on 2^qbits levels.
  1029. */
  1030. static inline int asym_quant(int c, int e, int qbits)
  1031. {
  1032. int lshift, m, v;
  1033. lshift = e + qbits - 24;
  1034. if (lshift >= 0)
  1035. v = c << lshift;
  1036. else
  1037. v = c >> (-lshift);
  1038. /* rounding */
  1039. v = (v + 1) >> 1;
  1040. m = (1 << (qbits-1));
  1041. if (v >= m)
  1042. v = m - 1;
  1043. av_assert2(v >= -m);
  1044. return v & ((1 << qbits)-1);
  1045. }
  1046. /**
  1047. * Quantize a set of mantissas for a single channel in a single block.
  1048. */
  1049. static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
  1050. uint8_t *exp,
  1051. uint8_t *bap, uint16_t *qmant, int n)
  1052. {
  1053. int i;
  1054. for (i = 0; i < n; i++) {
  1055. int v;
  1056. int c = fixed_coef[i];
  1057. int e = exp[i];
  1058. int b = bap[i];
  1059. switch (b) {
  1060. case 0:
  1061. v = 0;
  1062. break;
  1063. case 1:
  1064. v = sym_quant(c, e, 3);
  1065. switch (s->mant1_cnt) {
  1066. case 0:
  1067. s->qmant1_ptr = &qmant[i];
  1068. v = 9 * v;
  1069. s->mant1_cnt = 1;
  1070. break;
  1071. case 1:
  1072. *s->qmant1_ptr += 3 * v;
  1073. s->mant1_cnt = 2;
  1074. v = 128;
  1075. break;
  1076. default:
  1077. *s->qmant1_ptr += v;
  1078. s->mant1_cnt = 0;
  1079. v = 128;
  1080. break;
  1081. }
  1082. break;
  1083. case 2:
  1084. v = sym_quant(c, e, 5);
  1085. switch (s->mant2_cnt) {
  1086. case 0:
  1087. s->qmant2_ptr = &qmant[i];
  1088. v = 25 * v;
  1089. s->mant2_cnt = 1;
  1090. break;
  1091. case 1:
  1092. *s->qmant2_ptr += 5 * v;
  1093. s->mant2_cnt = 2;
  1094. v = 128;
  1095. break;
  1096. default:
  1097. *s->qmant2_ptr += v;
  1098. s->mant2_cnt = 0;
  1099. v = 128;
  1100. break;
  1101. }
  1102. break;
  1103. case 3:
  1104. v = sym_quant(c, e, 7);
  1105. break;
  1106. case 4:
  1107. v = sym_quant(c, e, 11);
  1108. switch (s->mant4_cnt) {
  1109. case 0:
  1110. s->qmant4_ptr = &qmant[i];
  1111. v = 11 * v;
  1112. s->mant4_cnt = 1;
  1113. break;
  1114. default:
  1115. *s->qmant4_ptr += v;
  1116. s->mant4_cnt = 0;
  1117. v = 128;
  1118. break;
  1119. }
  1120. break;
  1121. case 5:
  1122. v = sym_quant(c, e, 15);
  1123. break;
  1124. case 14:
  1125. v = asym_quant(c, e, 14);
  1126. break;
  1127. case 15:
  1128. v = asym_quant(c, e, 16);
  1129. break;
  1130. default:
  1131. v = asym_quant(c, e, b - 1);
  1132. break;
  1133. }
  1134. qmant[i] = v;
  1135. }
  1136. }
  1137. /**
  1138. * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
  1139. */
  1140. static void quantize_mantissas(AC3EncodeContext *s)
  1141. {
  1142. int blk, ch;
  1143. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1144. AC3Block *block = &s->blocks[blk];
  1145. AC3Block *ref_block;
  1146. AC3Mant m = { 0 };
  1147. for (ch = 0; ch < s->channels; ch++) {
  1148. ref_block = block->exp_ref_block[ch];
  1149. quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
  1150. ref_block->exp[ch], ref_block->bap[ch],
  1151. block->qmant[ch], s->nb_coefs[ch]);
  1152. }
  1153. }
  1154. }
  1155. /**
  1156. * Write the AC-3 frame header to the output bitstream.
  1157. */
  1158. static void output_frame_header(AC3EncodeContext *s)
  1159. {
  1160. AC3EncOptions *opt = &s->options;
  1161. put_bits(&s->pb, 16, 0x0b77); /* frame header */
  1162. put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
  1163. put_bits(&s->pb, 2, s->bit_alloc.sr_code);
  1164. put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
  1165. put_bits(&s->pb, 5, s->bitstream_id);
  1166. put_bits(&s->pb, 3, s->bitstream_mode);
  1167. put_bits(&s->pb, 3, s->channel_mode);
  1168. if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
  1169. put_bits(&s->pb, 2, s->center_mix_level);
  1170. if (s->channel_mode & 0x04)
  1171. put_bits(&s->pb, 2, s->surround_mix_level);
  1172. if (s->channel_mode == AC3_CHMODE_STEREO)
  1173. put_bits(&s->pb, 2, opt->dolby_surround_mode);
  1174. put_bits(&s->pb, 1, s->lfe_on); /* LFE */
  1175. put_bits(&s->pb, 5, -opt->dialogue_level);
  1176. put_bits(&s->pb, 1, 0); /* no compression control word */
  1177. put_bits(&s->pb, 1, 0); /* no lang code */
  1178. put_bits(&s->pb, 1, opt->audio_production_info);
  1179. if (opt->audio_production_info) {
  1180. put_bits(&s->pb, 5, opt->mixing_level - 80);
  1181. put_bits(&s->pb, 2, opt->room_type);
  1182. }
  1183. put_bits(&s->pb, 1, opt->copyright);
  1184. put_bits(&s->pb, 1, opt->original);
  1185. if (s->bitstream_id == 6) {
  1186. /* alternate bit stream syntax */
  1187. put_bits(&s->pb, 1, opt->extended_bsi_1);
  1188. if (opt->extended_bsi_1) {
  1189. put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
  1190. put_bits(&s->pb, 3, s->ltrt_center_mix_level);
  1191. put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
  1192. put_bits(&s->pb, 3, s->loro_center_mix_level);
  1193. put_bits(&s->pb, 3, s->loro_surround_mix_level);
  1194. }
  1195. put_bits(&s->pb, 1, opt->extended_bsi_2);
  1196. if (opt->extended_bsi_2) {
  1197. put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
  1198. put_bits(&s->pb, 2, opt->dolby_headphone_mode);
  1199. put_bits(&s->pb, 1, opt->ad_converter_type);
  1200. put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
  1201. }
  1202. } else {
  1203. put_bits(&s->pb, 1, 0); /* no time code 1 */
  1204. put_bits(&s->pb, 1, 0); /* no time code 2 */
  1205. }
  1206. put_bits(&s->pb, 1, 0); /* no additional bit stream info */
  1207. }
  1208. /**
  1209. * Write one audio block to the output bitstream.
  1210. */
  1211. static void output_audio_block(AC3EncodeContext *s, int blk)
  1212. {
  1213. int ch, i, baie, rbnd;
  1214. AC3Block *block = &s->blocks[blk];
  1215. /* block switching */
  1216. for (ch = 0; ch < s->fbw_channels; ch++)
  1217. put_bits(&s->pb, 1, 0);
  1218. /* dither flags */
  1219. for (ch = 0; ch < s->fbw_channels; ch++)
  1220. put_bits(&s->pb, 1, 1);
  1221. /* dynamic range codes */
  1222. put_bits(&s->pb, 1, 0);
  1223. /* channel coupling */
  1224. if (!blk) {
  1225. put_bits(&s->pb, 1, 1); /* coupling strategy present */
  1226. put_bits(&s->pb, 1, 0); /* no coupling strategy */
  1227. } else {
  1228. put_bits(&s->pb, 1, 0); /* no new coupling strategy */
  1229. }
  1230. /* stereo rematrixing */
  1231. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1232. put_bits(&s->pb, 1, block->new_rematrixing_strategy);
  1233. if (block->new_rematrixing_strategy) {
  1234. /* rematrixing flags */
  1235. for (rbnd = 0; rbnd < s->num_rematrixing_bands; rbnd++)
  1236. put_bits(&s->pb, 1, block->rematrixing_flags[rbnd]);
  1237. }
  1238. }
  1239. /* exponent strategy */
  1240. for (ch = 0; ch < s->fbw_channels; ch++)
  1241. put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
  1242. if (s->lfe_on)
  1243. put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
  1244. /* bandwidth */
  1245. for (ch = 0; ch < s->fbw_channels; ch++) {
  1246. if (s->exp_strategy[ch][blk] != EXP_REUSE)
  1247. put_bits(&s->pb, 6, s->bandwidth_code[ch]);
  1248. }
  1249. /* exponents */
  1250. for (ch = 0; ch < s->channels; ch++) {
  1251. int nb_groups;
  1252. if (s->exp_strategy[ch][blk] == EXP_REUSE)
  1253. continue;
  1254. /* DC exponent */
  1255. put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
  1256. /* exponent groups */
  1257. nb_groups = exponent_group_tab[s->exp_strategy[ch][blk]-1][s->nb_coefs[ch]];
  1258. for (i = 1; i <= nb_groups; i++)
  1259. put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
  1260. /* gain range info */
  1261. if (ch != s->lfe_channel)
  1262. put_bits(&s->pb, 2, 0);
  1263. }
  1264. /* bit allocation info */
  1265. baie = (blk == 0);
  1266. put_bits(&s->pb, 1, baie);
  1267. if (baie) {
  1268. put_bits(&s->pb, 2, s->slow_decay_code);
  1269. put_bits(&s->pb, 2, s->fast_decay_code);
  1270. put_bits(&s->pb, 2, s->slow_gain_code);
  1271. put_bits(&s->pb, 2, s->db_per_bit_code);
  1272. put_bits(&s->pb, 3, s->floor_code);
  1273. }
  1274. /* snr offset */
  1275. put_bits(&s->pb, 1, baie);
  1276. if (baie) {
  1277. put_bits(&s->pb, 6, s->coarse_snr_offset);
  1278. for (ch = 0; ch < s->channels; ch++) {
  1279. put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
  1280. put_bits(&s->pb, 3, s->fast_gain_code[ch]);
  1281. }
  1282. }
  1283. put_bits(&s->pb, 1, 0); /* no delta bit allocation */
  1284. put_bits(&s->pb, 1, 0); /* no data to skip */
  1285. /* mantissas */
  1286. for (ch = 0; ch < s->channels; ch++) {
  1287. int b, q;
  1288. AC3Block *ref_block = block->exp_ref_block[ch];
  1289. for (i = 0; i < s->nb_coefs[ch]; i++) {
  1290. q = block->qmant[ch][i];
  1291. b = ref_block->bap[ch][i];
  1292. switch (b) {
  1293. case 0: break;
  1294. case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
  1295. case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
  1296. case 3: put_bits(&s->pb, 3, q); break;
  1297. case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
  1298. case 14: put_bits(&s->pb, 14, q); break;
  1299. case 15: put_bits(&s->pb, 16, q); break;
  1300. default: put_bits(&s->pb, b-1, q); break;
  1301. }
  1302. }
  1303. }
  1304. }
  1305. /** CRC-16 Polynomial */
  1306. #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
  1307. static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
  1308. {
  1309. unsigned int c;
  1310. c = 0;
  1311. while (a) {
  1312. if (a & 1)
  1313. c ^= b;
  1314. a = a >> 1;
  1315. b = b << 1;
  1316. if (b & (1 << 16))
  1317. b ^= poly;
  1318. }
  1319. return c;
  1320. }
  1321. static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
  1322. {
  1323. unsigned int r;
  1324. r = 1;
  1325. while (n) {
  1326. if (n & 1)
  1327. r = mul_poly(r, a, poly);
  1328. a = mul_poly(a, a, poly);
  1329. n >>= 1;
  1330. }
  1331. return r;
  1332. }
  1333. /**
  1334. * Fill the end of the frame with 0's and compute the two CRCs.
  1335. */
  1336. static void output_frame_end(AC3EncodeContext *s)
  1337. {
  1338. const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
  1339. int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
  1340. uint8_t *frame;
  1341. frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
  1342. /* pad the remainder of the frame with zeros */
  1343. av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
  1344. flush_put_bits(&s->pb);
  1345. frame = s->pb.buf;
  1346. pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
  1347. av_assert2(pad_bytes >= 0);
  1348. if (pad_bytes > 0)
  1349. memset(put_bits_ptr(&s->pb), 0, pad_bytes);
  1350. /* compute crc1 */
  1351. /* this is not so easy because it is at the beginning of the data... */
  1352. crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
  1353. crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
  1354. crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
  1355. AV_WB16(frame + 2, crc1);
  1356. /* compute crc2 */
  1357. crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
  1358. s->frame_size - frame_size_58 - 3);
  1359. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1360. /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
  1361. if (crc2 == 0x770B) {
  1362. frame[s->frame_size - 3] ^= 0x1;
  1363. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1364. }
  1365. crc2 = av_bswap16(crc2);
  1366. AV_WB16(frame + s->frame_size - 2, crc2);
  1367. }
  1368. /**
  1369. * Write the frame to the output bitstream.
  1370. */
  1371. static void output_frame(AC3EncodeContext *s, unsigned char *frame)
  1372. {
  1373. int blk;
  1374. init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
  1375. output_frame_header(s);
  1376. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1377. output_audio_block(s, blk);
  1378. output_frame_end(s);
  1379. }
  1380. static void dprint_options(AVCodecContext *avctx)
  1381. {
  1382. #ifdef DEBUG
  1383. AC3EncodeContext *s = avctx->priv_data;
  1384. AC3EncOptions *opt = &s->options;
  1385. char strbuf[32];
  1386. switch (s->bitstream_id) {
  1387. case 6: strncpy(strbuf, "AC-3 (alt syntax)", 32); break;
  1388. case 8: strncpy(strbuf, "AC-3 (standard)", 32); break;
  1389. case 9: strncpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
  1390. case 10: strncpy(strbuf, "AC-3 (dnet quater-rate", 32); break;
  1391. default: snprintf(strbuf, 32, "ERROR");
  1392. }
  1393. av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
  1394. av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
  1395. av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
  1396. av_dlog(avctx, "channel_layout: %s\n", strbuf);
  1397. av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
  1398. av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
  1399. if (s->cutoff)
  1400. av_dlog(avctx, "cutoff: %d\n", s->cutoff);
  1401. av_dlog(avctx, "per_frame_metadata: %s\n",
  1402. opt->allow_per_frame_metadata?"on":"off");
  1403. if (s->has_center)
  1404. av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
  1405. s->center_mix_level);
  1406. else
  1407. av_dlog(avctx, "center_mixlev: {not written}\n");
  1408. if (s->has_surround)
  1409. av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
  1410. s->surround_mix_level);
  1411. else
  1412. av_dlog(avctx, "surround_mixlev: {not written}\n");
  1413. if (opt->audio_production_info) {
  1414. av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
  1415. switch (opt->room_type) {
  1416. case 0: strncpy(strbuf, "notindicated", 32); break;
  1417. case 1: strncpy(strbuf, "large", 32); break;
  1418. case 2: strncpy(strbuf, "small", 32); break;
  1419. default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
  1420. }
  1421. av_dlog(avctx, "room_type: %s\n", strbuf);
  1422. } else {
  1423. av_dlog(avctx, "mixing_level: {not written}\n");
  1424. av_dlog(avctx, "room_type: {not written}\n");
  1425. }
  1426. av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
  1427. av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
  1428. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1429. switch (opt->dolby_surround_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_mode);
  1434. }
  1435. av_dlog(avctx, "dsur_mode: %s\n", strbuf);
  1436. } else {
  1437. av_dlog(avctx, "dsur_mode: {not written}\n");
  1438. }
  1439. av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
  1440. if (s->bitstream_id == 6) {
  1441. if (opt->extended_bsi_1) {
  1442. switch (opt->preferred_stereo_downmix) {
  1443. case 0: strncpy(strbuf, "notindicated", 32); break;
  1444. case 1: strncpy(strbuf, "ltrt", 32); break;
  1445. case 2: strncpy(strbuf, "loro", 32); break;
  1446. default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
  1447. }
  1448. av_dlog(avctx, "dmix_mode: %s\n", strbuf);
  1449. av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
  1450. opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
  1451. av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
  1452. opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
  1453. av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
  1454. opt->loro_center_mix_level, s->loro_center_mix_level);
  1455. av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
  1456. opt->loro_surround_mix_level, s->loro_surround_mix_level);
  1457. } else {
  1458. av_dlog(avctx, "extended bitstream info 1: {not written}\n");
  1459. }
  1460. if (opt->extended_bsi_2) {
  1461. switch (opt->dolby_surround_ex_mode) {
  1462. case 0: strncpy(strbuf, "notindicated", 32); break;
  1463. case 1: strncpy(strbuf, "on", 32); break;
  1464. case 2: strncpy(strbuf, "off", 32); break;
  1465. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
  1466. }
  1467. av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
  1468. switch (opt->dolby_headphone_mode) {
  1469. case 0: strncpy(strbuf, "notindicated", 32); break;
  1470. case 1: strncpy(strbuf, "on", 32); break;
  1471. case 2: strncpy(strbuf, "off", 32); break;
  1472. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
  1473. }
  1474. av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
  1475. switch (opt->ad_converter_type) {
  1476. case 0: strncpy(strbuf, "standard", 32); break;
  1477. case 1: strncpy(strbuf, "hdcd", 32); break;
  1478. default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
  1479. }
  1480. av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
  1481. } else {
  1482. av_dlog(avctx, "extended bitstream info 2: {not written}\n");
  1483. }
  1484. }
  1485. #endif
  1486. }
  1487. #define FLT_OPTION_THRESHOLD 0.01
  1488. static int validate_float_option(float v, const float *v_list, int v_list_size)
  1489. {
  1490. int i;
  1491. for (i = 0; i < v_list_size; i++) {
  1492. if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
  1493. v > (v_list[i] - FLT_OPTION_THRESHOLD))
  1494. break;
  1495. }
  1496. if (i == v_list_size)
  1497. return -1;
  1498. return i;
  1499. }
  1500. static void validate_mix_level(void *log_ctx, const char *opt_name,
  1501. float *opt_param, const float *list,
  1502. int list_size, int default_value, int min_value,
  1503. int *ctx_param)
  1504. {
  1505. int mixlev = validate_float_option(*opt_param, list, list_size);
  1506. if (mixlev < min_value) {
  1507. mixlev = default_value;
  1508. if (*opt_param >= 0.0) {
  1509. av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
  1510. "default value: %0.3f\n", opt_name, list[mixlev]);
  1511. }
  1512. }
  1513. *opt_param = list[mixlev];
  1514. *ctx_param = mixlev;
  1515. }
  1516. /**
  1517. * Validate metadata options as set by AVOption system.
  1518. * These values can optionally be changed per-frame.
  1519. */
  1520. static int validate_metadata(AVCodecContext *avctx)
  1521. {
  1522. AC3EncodeContext *s = avctx->priv_data;
  1523. AC3EncOptions *opt = &s->options;
  1524. /* validate mixing levels */
  1525. if (s->has_center) {
  1526. validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
  1527. cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
  1528. &s->center_mix_level);
  1529. }
  1530. if (s->has_surround) {
  1531. validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
  1532. surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
  1533. &s->surround_mix_level);
  1534. }
  1535. /* set audio production info flag */
  1536. if (opt->mixing_level >= 0 || opt->room_type >= 0) {
  1537. if (opt->mixing_level < 0) {
  1538. av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
  1539. "room_type is set\n");
  1540. return AVERROR(EINVAL);
  1541. }
  1542. if (opt->mixing_level < 80) {
  1543. av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
  1544. "80dB and 111dB\n");
  1545. return AVERROR(EINVAL);
  1546. }
  1547. /* default room type */
  1548. if (opt->room_type < 0)
  1549. opt->room_type = 0;
  1550. opt->audio_production_info = 1;
  1551. } else {
  1552. opt->audio_production_info = 0;
  1553. }
  1554. /* set extended bsi 1 flag */
  1555. if ((s->has_center || s->has_surround) &&
  1556. (opt->preferred_stereo_downmix >= 0 ||
  1557. opt->ltrt_center_mix_level >= 0 ||
  1558. opt->ltrt_surround_mix_level >= 0 ||
  1559. opt->loro_center_mix_level >= 0 ||
  1560. opt->loro_surround_mix_level >= 0)) {
  1561. /* default preferred stereo downmix */
  1562. if (opt->preferred_stereo_downmix < 0)
  1563. opt->preferred_stereo_downmix = 0;
  1564. /* validate Lt/Rt center mix level */
  1565. validate_mix_level(avctx, "ltrt_center_mix_level",
  1566. &opt->ltrt_center_mix_level, extmixlev_options,
  1567. EXTMIXLEV_NUM_OPTIONS, 5, 0,
  1568. &s->ltrt_center_mix_level);
  1569. /* validate Lt/Rt surround mix level */
  1570. validate_mix_level(avctx, "ltrt_surround_mix_level",
  1571. &opt->ltrt_surround_mix_level, extmixlev_options,
  1572. EXTMIXLEV_NUM_OPTIONS, 6, 3,
  1573. &s->ltrt_surround_mix_level);
  1574. /* validate Lo/Ro center mix level */
  1575. validate_mix_level(avctx, "loro_center_mix_level",
  1576. &opt->loro_center_mix_level, extmixlev_options,
  1577. EXTMIXLEV_NUM_OPTIONS, 5, 0,
  1578. &s->loro_center_mix_level);
  1579. /* validate Lo/Ro surround mix level */
  1580. validate_mix_level(avctx, "loro_surround_mix_level",
  1581. &opt->loro_surround_mix_level, extmixlev_options,
  1582. EXTMIXLEV_NUM_OPTIONS, 6, 3,
  1583. &s->loro_surround_mix_level);
  1584. opt->extended_bsi_1 = 1;
  1585. } else {
  1586. opt->extended_bsi_1 = 0;
  1587. }
  1588. /* set extended bsi 2 flag */
  1589. if (opt->dolby_surround_ex_mode >= 0 ||
  1590. opt->dolby_headphone_mode >= 0 ||
  1591. opt->ad_converter_type >= 0) {
  1592. /* default dolby surround ex mode */
  1593. if (opt->dolby_surround_ex_mode < 0)
  1594. opt->dolby_surround_ex_mode = 0;
  1595. /* default dolby headphone mode */
  1596. if (opt->dolby_headphone_mode < 0)
  1597. opt->dolby_headphone_mode = 0;
  1598. /* default A/D converter type */
  1599. if (opt->ad_converter_type < 0)
  1600. opt->ad_converter_type = 0;
  1601. opt->extended_bsi_2 = 1;
  1602. } else {
  1603. opt->extended_bsi_2 = 0;
  1604. }
  1605. /* set bitstream id for alternate bitstream syntax */
  1606. if (opt->extended_bsi_1 || opt->extended_bsi_2) {
  1607. if (s->bitstream_id > 8 && s->bitstream_id < 11) {
  1608. static int warn_once = 1;
  1609. if (warn_once) {
  1610. av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
  1611. "not compatible with reduced samplerates. writing of "
  1612. "extended bitstream information will be disabled.\n");
  1613. warn_once = 0;
  1614. }
  1615. } else {
  1616. s->bitstream_id = 6;
  1617. }
  1618. }
  1619. return 0;
  1620. }
  1621. /**
  1622. * Encode a single AC-3 frame.
  1623. */
  1624. static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
  1625. int buf_size, void *data)
  1626. {
  1627. AC3EncodeContext *s = avctx->priv_data;
  1628. const SampleType *samples = data;
  1629. int ret;
  1630. if (s->options.allow_per_frame_metadata) {
  1631. ret = validate_metadata(avctx);
  1632. if (ret)
  1633. return ret;
  1634. }
  1635. if (s->bit_alloc.sr_code == 1)
  1636. adjust_frame_size(s);
  1637. deinterleave_input_samples(s, samples);
  1638. apply_mdct(s);
  1639. scale_coefficients(s);
  1640. compute_rematrixing_strategy(s);
  1641. apply_rematrixing(s);
  1642. process_exponents(s);
  1643. ret = compute_bit_allocation(s);
  1644. if (ret) {
  1645. av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
  1646. return ret;
  1647. }
  1648. quantize_mantissas(s);
  1649. output_frame(s, frame);
  1650. return s->frame_size;
  1651. }
  1652. /**
  1653. * Finalize encoding and free any memory allocated by the encoder.
  1654. */
  1655. static av_cold int ac3_encode_close(AVCodecContext *avctx)
  1656. {
  1657. int blk, ch;
  1658. AC3EncodeContext *s = avctx->priv_data;
  1659. for (ch = 0; ch < s->channels; ch++)
  1660. av_freep(&s->planar_samples[ch]);
  1661. av_freep(&s->planar_samples);
  1662. av_freep(&s->bap_buffer);
  1663. av_freep(&s->bap1_buffer);
  1664. av_freep(&s->mdct_coef_buffer);
  1665. av_freep(&s->fixed_coef_buffer);
  1666. av_freep(&s->exp_buffer);
  1667. av_freep(&s->grouped_exp_buffer);
  1668. av_freep(&s->psd_buffer);
  1669. av_freep(&s->band_psd_buffer);
  1670. av_freep(&s->mask_buffer);
  1671. av_freep(&s->qmant_buffer);
  1672. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1673. AC3Block *block = &s->blocks[blk];
  1674. av_freep(&block->bap);
  1675. av_freep(&block->mdct_coef);
  1676. av_freep(&block->fixed_coef);
  1677. av_freep(&block->exp);
  1678. av_freep(&block->grouped_exp);
  1679. av_freep(&block->psd);
  1680. av_freep(&block->band_psd);
  1681. av_freep(&block->mask);
  1682. av_freep(&block->qmant);
  1683. }
  1684. mdct_end(&s->mdct);
  1685. av_freep(&avctx->coded_frame);
  1686. return 0;
  1687. }
  1688. /**
  1689. * Set channel information during initialization.
  1690. */
  1691. static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
  1692. int64_t *channel_layout)
  1693. {
  1694. int ch_layout;
  1695. if (channels < 1 || channels > AC3_MAX_CHANNELS)
  1696. return AVERROR(EINVAL);
  1697. if ((uint64_t)*channel_layout > 0x7FF)
  1698. return AVERROR(EINVAL);
  1699. ch_layout = *channel_layout;
  1700. if (!ch_layout)
  1701. ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
  1702. s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
  1703. s->channels = channels;
  1704. s->fbw_channels = channels - s->lfe_on;
  1705. s->lfe_channel = s->lfe_on ? s->fbw_channels : -1;
  1706. if (s->lfe_on)
  1707. ch_layout -= AV_CH_LOW_FREQUENCY;
  1708. switch (ch_layout) {
  1709. case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
  1710. case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
  1711. case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
  1712. case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
  1713. case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
  1714. case AV_CH_LAYOUT_QUAD:
  1715. case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
  1716. case AV_CH_LAYOUT_5POINT0:
  1717. case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
  1718. default:
  1719. return AVERROR(EINVAL);
  1720. }
  1721. s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
  1722. s->has_surround = s->channel_mode & 0x04;
  1723. s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
  1724. *channel_layout = ch_layout;
  1725. if (s->lfe_on)
  1726. *channel_layout |= AV_CH_LOW_FREQUENCY;
  1727. return 0;
  1728. }
  1729. static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
  1730. {
  1731. int i, ret;
  1732. /* validate channel layout */
  1733. if (!avctx->channel_layout) {
  1734. av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
  1735. "encoder will guess the layout, but it "
  1736. "might be incorrect.\n");
  1737. }
  1738. ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
  1739. if (ret) {
  1740. av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
  1741. return ret;
  1742. }
  1743. /* validate sample rate */
  1744. for (i = 0; i < 9; i++) {
  1745. if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
  1746. break;
  1747. }
  1748. if (i == 9) {
  1749. av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
  1750. return AVERROR(EINVAL);
  1751. }
  1752. s->sample_rate = avctx->sample_rate;
  1753. s->bit_alloc.sr_shift = i % 3;
  1754. s->bit_alloc.sr_code = i / 3;
  1755. s->bitstream_id = 8 + s->bit_alloc.sr_shift;
  1756. /* validate bit rate */
  1757. for (i = 0; i < 19; i++) {
  1758. if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
  1759. break;
  1760. }
  1761. if (i == 19) {
  1762. av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
  1763. return AVERROR(EINVAL);
  1764. }
  1765. s->bit_rate = avctx->bit_rate;
  1766. s->frame_size_code = i << 1;
  1767. /* validate cutoff */
  1768. if (avctx->cutoff < 0) {
  1769. av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
  1770. return AVERROR(EINVAL);
  1771. }
  1772. s->cutoff = avctx->cutoff;
  1773. if (s->cutoff > (s->sample_rate >> 1))
  1774. s->cutoff = s->sample_rate >> 1;
  1775. /* validate audio service type / channels combination */
  1776. if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
  1777. avctx->channels == 1) ||
  1778. ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
  1779. avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
  1780. avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
  1781. && avctx->channels > 1)) {
  1782. av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
  1783. "specified number of channels\n");
  1784. return AVERROR(EINVAL);
  1785. }
  1786. ret = validate_metadata(avctx);
  1787. if (ret)
  1788. return ret;
  1789. s->rematrixing_enabled = s->options.stereo_rematrixing &&
  1790. (s->channel_mode == AC3_CHMODE_STEREO);
  1791. return 0;
  1792. }
  1793. /**
  1794. * Set bandwidth for all channels.
  1795. * The user can optionally supply a cutoff frequency. Otherwise an appropriate
  1796. * default value will be used.
  1797. */
  1798. static av_cold void set_bandwidth(AC3EncodeContext *s)
  1799. {
  1800. int ch, bw_code;
  1801. if (s->cutoff) {
  1802. /* calculate bandwidth based on user-specified cutoff frequency */
  1803. int fbw_coeffs;
  1804. fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
  1805. bw_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
  1806. } else {
  1807. /* use default bandwidth setting */
  1808. bw_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
  1809. }
  1810. /* set number of coefficients for each channel */
  1811. for (ch = 0; ch < s->fbw_channels; ch++) {
  1812. s->bandwidth_code[ch] = bw_code;
  1813. s->nb_coefs[ch] = bw_code * 3 + 73;
  1814. }
  1815. if (s->lfe_on)
  1816. s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
  1817. }
  1818. static av_cold int allocate_buffers(AVCodecContext *avctx)
  1819. {
  1820. int blk, ch;
  1821. AC3EncodeContext *s = avctx->priv_data;
  1822. FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
  1823. alloc_fail);
  1824. for (ch = 0; ch < s->channels; ch++) {
  1825. FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
  1826. (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
  1827. alloc_fail);
  1828. }
  1829. FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * s->channels *
  1830. AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
  1831. FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
  1832. AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
  1833. FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
  1834. AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
  1835. FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
  1836. AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
  1837. FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
  1838. 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
  1839. FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
  1840. AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
  1841. FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
  1842. 64 * sizeof(*s->band_psd_buffer), alloc_fail);
  1843. FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
  1844. 64 * sizeof(*s->mask_buffer), alloc_fail);
  1845. FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
  1846. AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
  1847. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1848. AC3Block *block = &s->blocks[blk];
  1849. FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
  1850. alloc_fail);
  1851. FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
  1852. alloc_fail);
  1853. FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
  1854. alloc_fail);
  1855. FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
  1856. alloc_fail);
  1857. FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
  1858. alloc_fail);
  1859. FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
  1860. alloc_fail);
  1861. FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
  1862. alloc_fail);
  1863. FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
  1864. alloc_fail);
  1865. for (ch = 0; ch < s->channels; ch++) {
  1866. /* arrangement: block, channel, coeff */
  1867. block->bap[ch] = &s->bap_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1868. block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1869. block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * s->channels + ch)];
  1870. block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1871. block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * s->channels + ch)];
  1872. block->mask[ch] = &s->mask_buffer [64 * (blk * s->channels + ch)];
  1873. block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1874. /* arrangement: channel, block, coeff */
  1875. block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
  1876. }
  1877. }
  1878. if (CONFIG_AC3ENC_FLOAT) {
  1879. FF_ALLOC_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * s->channels *
  1880. AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
  1881. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1882. AC3Block *block = &s->blocks[blk];
  1883. FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
  1884. sizeof(*block->fixed_coef), alloc_fail);
  1885. for (ch = 0; ch < s->channels; ch++)
  1886. block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
  1887. }
  1888. } else {
  1889. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1890. AC3Block *block = &s->blocks[blk];
  1891. FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
  1892. sizeof(*block->fixed_coef), alloc_fail);
  1893. for (ch = 0; ch < s->channels; ch++)
  1894. block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
  1895. }
  1896. }
  1897. return 0;
  1898. alloc_fail:
  1899. return AVERROR(ENOMEM);
  1900. }
  1901. /**
  1902. * Initialize the encoder.
  1903. */
  1904. static av_cold int ac3_encode_init(AVCodecContext *avctx)
  1905. {
  1906. AC3EncodeContext *s = avctx->priv_data;
  1907. int ret, frame_size_58;
  1908. avctx->frame_size = AC3_FRAME_SIZE;
  1909. ff_ac3_common_init();
  1910. ret = validate_options(avctx, s);
  1911. if (ret)
  1912. return ret;
  1913. s->bitstream_mode = avctx->audio_service_type;
  1914. if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
  1915. s->bitstream_mode = 0x7;
  1916. s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
  1917. s->bits_written = 0;
  1918. s->samples_written = 0;
  1919. s->frame_size = s->frame_size_min;
  1920. /* calculate crc_inv for both possible frame sizes */
  1921. frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
  1922. s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  1923. if (s->bit_alloc.sr_code == 1) {
  1924. frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
  1925. s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  1926. }
  1927. set_bandwidth(s);
  1928. exponent_init(s);
  1929. bit_alloc_init(s);
  1930. ret = mdct_init(avctx, &s->mdct, 9);
  1931. if (ret)
  1932. goto init_fail;
  1933. ret = allocate_buffers(avctx);
  1934. if (ret)
  1935. goto init_fail;
  1936. avctx->coded_frame= avcodec_alloc_frame();
  1937. dsputil_init(&s->dsp, avctx);
  1938. ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
  1939. dprint_options(avctx);
  1940. return 0;
  1941. init_fail:
  1942. ac3_encode_close(avctx);
  1943. return ret;
  1944. }