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.

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