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.

3023 lines
106KB

  1. /*
  2. * The simplest AC-3 encoder
  3. * Copyright (c) 2000 Fabrice Bellard
  4. * Copyright (c) 2006-2010 Justin Ruggles <justin.ruggles@gmail.com>
  5. * Copyright (c) 2006-2010 Prakash Punnoor <prakash@punnoor.de>
  6. *
  7. * This file is part of Libav.
  8. *
  9. * Libav is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU Lesser General Public
  11. * License as published by the Free Software Foundation; either
  12. * version 2.1 of the License, or (at your option) any later version.
  13. *
  14. * Libav is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * Lesser General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Lesser General Public
  20. * License along with Libav; if not, write to the Free Software
  21. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  22. */
  23. /**
  24. * @file
  25. * The simplest AC-3 encoder.
  26. */
  27. //#define DEBUG
  28. //#define ASSERT_LEVEL 2
  29. #include <stdint.h>
  30. #include "libavutil/audioconvert.h"
  31. #include "libavutil/avassert.h"
  32. #include "libavutil/avstring.h"
  33. #include "libavutil/crc.h"
  34. #include "libavutil/opt.h"
  35. #include "avcodec.h"
  36. #include "put_bits.h"
  37. #include "dsputil.h"
  38. #include "ac3dsp.h"
  39. #include "ac3.h"
  40. #include "audioconvert.h"
  41. #include "fft.h"
  42. #ifndef CONFIG_AC3ENC_FLOAT
  43. #define CONFIG_AC3ENC_FLOAT 0
  44. #endif
  45. /** Maximum number of exponent groups. +1 for separate DC exponent. */
  46. #define AC3_MAX_EXP_GROUPS 85
  47. #if CONFIG_AC3ENC_FLOAT
  48. #define MAC_COEF(d,a,b) ((d)+=(a)*(b))
  49. typedef float SampleType;
  50. typedef float CoefType;
  51. typedef float CoefSumType;
  52. #else
  53. #define MAC_COEF(d,a,b) MAC64(d,a,b)
  54. typedef int16_t SampleType;
  55. typedef int32_t CoefType;
  56. typedef int64_t CoefSumType;
  57. #endif
  58. typedef struct AC3MDCTContext {
  59. const SampleType *window; ///< MDCT window function
  60. FFTContext fft; ///< FFT context for MDCT calculation
  61. } AC3MDCTContext;
  62. /**
  63. * Encoding Options used by AVOption.
  64. */
  65. typedef struct AC3EncOptions {
  66. /* AC-3 metadata options*/
  67. int dialogue_level;
  68. int bitstream_mode;
  69. float center_mix_level;
  70. float surround_mix_level;
  71. int dolby_surround_mode;
  72. int audio_production_info;
  73. int mixing_level;
  74. int room_type;
  75. int copyright;
  76. int original;
  77. int extended_bsi_1;
  78. int preferred_stereo_downmix;
  79. float ltrt_center_mix_level;
  80. float ltrt_surround_mix_level;
  81. float loro_center_mix_level;
  82. float loro_surround_mix_level;
  83. int extended_bsi_2;
  84. int dolby_surround_ex_mode;
  85. int dolby_headphone_mode;
  86. int ad_converter_type;
  87. /* other encoding options */
  88. int allow_per_frame_metadata;
  89. int stereo_rematrixing;
  90. int channel_coupling;
  91. int cpl_start;
  92. } AC3EncOptions;
  93. /**
  94. * Data for a single audio block.
  95. */
  96. typedef struct AC3Block {
  97. uint8_t **bap; ///< bit allocation pointers (bap)
  98. CoefType **mdct_coef; ///< MDCT coefficients
  99. int32_t **fixed_coef; ///< fixed-point MDCT coefficients
  100. uint8_t **exp; ///< original exponents
  101. uint8_t **grouped_exp; ///< grouped exponents
  102. int16_t **psd; ///< psd per frequency bin
  103. int16_t **band_psd; ///< psd per critical band
  104. int16_t **mask; ///< masking curve
  105. uint16_t **qmant; ///< quantized mantissas
  106. uint8_t **cpl_coord_exp; ///< coupling coord exponents (cplcoexp)
  107. uint8_t **cpl_coord_mant; ///< coupling coord mantissas (cplcomant)
  108. uint8_t coeff_shift[AC3_MAX_CHANNELS]; ///< fixed-point coefficient shift values
  109. uint8_t new_rematrixing_strategy; ///< send new rematrixing flags in this block
  110. int num_rematrixing_bands; ///< number of rematrixing bands
  111. uint8_t rematrixing_flags[4]; ///< rematrixing flags
  112. struct AC3Block *exp_ref_block[AC3_MAX_CHANNELS]; ///< reference blocks for EXP_REUSE
  113. int new_cpl_strategy; ///< send new coupling strategy
  114. int cpl_in_use; ///< coupling in use for this block (cplinu)
  115. uint8_t channel_in_cpl[AC3_MAX_CHANNELS]; ///< channel in coupling (chincpl)
  116. int num_cpl_channels; ///< number of channels in coupling
  117. uint8_t new_cpl_coords; ///< send new coupling coordinates (cplcoe)
  118. uint8_t cpl_master_exp[AC3_MAX_CHANNELS]; ///< coupling coord master exponents (mstrcplco)
  119. int new_snr_offsets; ///< send new SNR offsets
  120. int new_cpl_leak; ///< send new coupling leak info
  121. int end_freq[AC3_MAX_CHANNELS]; ///< end frequency bin (endmant)
  122. } AC3Block;
  123. /**
  124. * AC-3 encoder private context.
  125. */
  126. typedef struct AC3EncodeContext {
  127. AVClass *av_class; ///< AVClass used for AVOption
  128. AC3EncOptions options; ///< encoding options
  129. PutBitContext pb; ///< bitstream writer context
  130. DSPContext dsp;
  131. AC3DSPContext ac3dsp; ///< AC-3 optimized functions
  132. AC3MDCTContext mdct; ///< MDCT context
  133. AC3Block blocks[AC3_MAX_BLOCKS]; ///< per-block info
  134. int eac3; ///< indicates if this is E-AC-3 vs. AC-3
  135. int bitstream_id; ///< bitstream id (bsid)
  136. int bitstream_mode; ///< bitstream mode (bsmod)
  137. int bit_rate; ///< target bit rate, in bits-per-second
  138. int sample_rate; ///< sampling frequency, in Hz
  139. int frame_size_min; ///< minimum frame size in case rounding is necessary
  140. int frame_size; ///< current frame size in bytes
  141. int frame_size_code; ///< frame size code (frmsizecod)
  142. uint16_t crc_inv[2];
  143. int64_t bits_written; ///< bit count (used to avg. bitrate)
  144. int64_t samples_written; ///< sample count (used to avg. bitrate)
  145. int fbw_channels; ///< number of full-bandwidth channels (nfchans)
  146. int channels; ///< total number of channels (nchans)
  147. int lfe_on; ///< indicates if there is an LFE channel (lfeon)
  148. int lfe_channel; ///< channel index of the LFE channel
  149. int has_center; ///< indicates if there is a center channel
  150. int has_surround; ///< indicates if there are one or more surround channels
  151. int channel_mode; ///< channel mode (acmod)
  152. const uint8_t *channel_map; ///< channel map used to reorder channels
  153. int center_mix_level; ///< center mix level code
  154. int surround_mix_level; ///< surround mix level code
  155. int ltrt_center_mix_level; ///< Lt/Rt center mix level code
  156. int ltrt_surround_mix_level; ///< Lt/Rt surround mix level code
  157. int loro_center_mix_level; ///< Lo/Ro center mix level code
  158. int loro_surround_mix_level; ///< Lo/Ro surround mix level code
  159. int cutoff; ///< user-specified cutoff frequency, in Hz
  160. int bandwidth_code; ///< bandwidth code (0 to 60) (chbwcod)
  161. int start_freq[AC3_MAX_CHANNELS]; ///< start frequency bin (strtmant)
  162. int cpl_end_freq; ///< coupling channel end frequency bin
  163. int cpl_on; ///< coupling turned on for this frame
  164. int cpl_enabled; ///< coupling enabled for all frames
  165. int num_cpl_subbands; ///< number of coupling subbands (ncplsubnd)
  166. int num_cpl_bands; ///< number of coupling bands (ncplbnd)
  167. uint8_t cpl_band_sizes[AC3_MAX_CPL_BANDS]; ///< number of coeffs in each coupling band
  168. int rematrixing_enabled; ///< stereo rematrixing enabled
  169. /* bitrate allocation control */
  170. int slow_gain_code; ///< slow gain code (sgaincod)
  171. int slow_decay_code; ///< slow decay code (sdcycod)
  172. int fast_decay_code; ///< fast decay code (fdcycod)
  173. int db_per_bit_code; ///< dB/bit code (dbpbcod)
  174. int floor_code; ///< floor code (floorcod)
  175. AC3BitAllocParameters bit_alloc; ///< bit allocation parameters
  176. int coarse_snr_offset; ///< coarse SNR offsets (csnroffst)
  177. int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signal-to-mask ratio) (fgaincod)
  178. int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst)
  179. int frame_bits_fixed; ///< number of non-coefficient bits for fixed parameters
  180. int frame_bits; ///< all frame bits except exponents and mantissas
  181. int exponent_bits; ///< number of bits used for exponents
  182. SampleType **planar_samples;
  183. uint8_t *bap_buffer;
  184. uint8_t *bap1_buffer;
  185. CoefType *mdct_coef_buffer;
  186. int32_t *fixed_coef_buffer;
  187. uint8_t *exp_buffer;
  188. uint8_t *grouped_exp_buffer;
  189. int16_t *psd_buffer;
  190. int16_t *band_psd_buffer;
  191. int16_t *mask_buffer;
  192. uint16_t *qmant_buffer;
  193. uint8_t *cpl_coord_exp_buffer;
  194. uint8_t *cpl_coord_mant_buffer;
  195. uint8_t exp_strategy[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< exponent strategies
  196. DECLARE_ALIGNED(32, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
  197. } AC3EncodeContext;
  198. typedef struct AC3Mant {
  199. uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
  200. int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
  201. } AC3Mant;
  202. #define CMIXLEV_NUM_OPTIONS 3
  203. static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
  204. LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
  205. };
  206. #define SURMIXLEV_NUM_OPTIONS 3
  207. static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
  208. LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
  209. };
  210. #define EXTMIXLEV_NUM_OPTIONS 8
  211. static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
  212. LEVEL_PLUS_3DB, LEVEL_PLUS_1POINT5DB, LEVEL_ONE, LEVEL_MINUS_4POINT5DB,
  213. LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
  214. };
  215. #define OFFSET(param) offsetof(AC3EncodeContext, options.param)
  216. #define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
  217. #define AC3ENC_TYPE_AC3_FIXED 0
  218. #define AC3ENC_TYPE_AC3 1
  219. #define AC3ENC_TYPE_EAC3 2
  220. #if CONFIG_AC3ENC_FLOAT
  221. #define AC3ENC_TYPE AC3ENC_TYPE_AC3
  222. #include "ac3enc_opts_template.c"
  223. static AVClass ac3enc_class = { "AC-3 Encoder", av_default_item_name,
  224. ac3_options, LIBAVUTIL_VERSION_INT };
  225. #undef AC3ENC_TYPE
  226. #define AC3ENC_TYPE AC3ENC_TYPE_EAC3
  227. #include "ac3enc_opts_template.c"
  228. static AVClass eac3enc_class = { "E-AC-3 Encoder", av_default_item_name,
  229. eac3_options, LIBAVUTIL_VERSION_INT };
  230. #else
  231. #define AC3ENC_TYPE AC3ENC_TYPE_AC3_FIXED
  232. #include "ac3enc_opts_template.c"
  233. static AVClass ac3enc_class = { "Fixed-Point AC-3 Encoder", av_default_item_name,
  234. ac3fixed_options, LIBAVUTIL_VERSION_INT };
  235. #endif
  236. /* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
  237. static av_cold void mdct_end(AC3MDCTContext *mdct);
  238. static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
  239. int nbits);
  240. static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
  241. const SampleType *window, unsigned int len);
  242. static int normalize_samples(AC3EncodeContext *s);
  243. static void scale_coefficients(AC3EncodeContext *s);
  244. /**
  245. * LUT for number of exponent groups.
  246. * exponent_group_tab[coupling][exponent strategy-1][number of coefficients]
  247. */
  248. static uint8_t exponent_group_tab[2][3][256];
  249. /**
  250. * List of supported channel layouts.
  251. */
  252. static const int64_t ac3_channel_layouts[] = {
  253. AV_CH_LAYOUT_MONO,
  254. AV_CH_LAYOUT_STEREO,
  255. AV_CH_LAYOUT_2_1,
  256. AV_CH_LAYOUT_SURROUND,
  257. AV_CH_LAYOUT_2_2,
  258. AV_CH_LAYOUT_QUAD,
  259. AV_CH_LAYOUT_4POINT0,
  260. AV_CH_LAYOUT_5POINT0,
  261. AV_CH_LAYOUT_5POINT0_BACK,
  262. (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
  263. (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
  264. (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
  265. (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
  266. (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
  267. (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
  268. (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
  269. AV_CH_LAYOUT_5POINT1,
  270. AV_CH_LAYOUT_5POINT1_BACK,
  271. 0
  272. };
  273. /**
  274. * LUT to select the bandwidth code based on the bit rate, sample rate, and
  275. * number of full-bandwidth channels.
  276. * bandwidth_tab[fbw_channels-1][sample rate code][bit rate code]
  277. */
  278. static const uint8_t ac3_bandwidth_tab[5][3][19] = {
  279. // 32 40 48 56 64 80 96 112 128 160 192 224 256 320 384 448 512 576 640
  280. { { 0, 0, 0, 12, 16, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
  281. { 0, 0, 0, 16, 20, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
  282. { 0, 0, 0, 32, 40, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
  283. { { 0, 0, 0, 0, 0, 0, 0, 20, 24, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
  284. { 0, 0, 0, 0, 0, 0, 4, 24, 28, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
  285. { 0, 0, 0, 0, 0, 0, 20, 44, 52, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
  286. { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 24, 32, 40, 48, 48, 48, 48, 48, 48 },
  287. { 0, 0, 0, 0, 0, 0, 0, 0, 4, 20, 28, 36, 44, 56, 56, 56, 56, 56, 56 },
  288. { 0, 0, 0, 0, 0, 0, 0, 0, 20, 40, 48, 60, 60, 60, 60, 60, 60, 60, 60 } },
  289. { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 32, 48, 48, 48, 48, 48, 48 },
  290. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 28, 36, 56, 56, 56, 56, 56, 56 },
  291. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 48, 60, 60, 60, 60, 60, 60, 60 } },
  292. { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 20, 32, 40, 48, 48, 48, 48 },
  293. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 36, 44, 56, 56, 56, 56 },
  294. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 44, 60, 60, 60, 60, 60, 60 } }
  295. };
  296. /**
  297. * LUT to select the coupling start band based on the bit rate, sample rate, and
  298. * number of full-bandwidth channels. -1 = coupling off
  299. * ac3_coupling_start_tab[channel_mode-2][sample rate code][bit rate code]
  300. *
  301. * TODO: more testing for optimal parameters.
  302. * multi-channel tests at 44.1kHz and 32kHz.
  303. */
  304. static const int8_t ac3_coupling_start_tab[6][3][19] = {
  305. // 32 40 48 56 64 80 96 112 128 160 192 224 256 320 384 448 512 576 640
  306. // 2/0
  307. { { 0, 0, 0, 0, 0, 0, 0, 1, 1, 7, 8, 11, 12, -1, -1, -1, -1, -1, -1 },
  308. { 0, 0, 0, 0, 0, 0, 1, 3, 5, 7, 10, 12, 13, -1, -1, -1, -1, -1, -1 },
  309. { 0, 0, 0, 0, 1, 2, 2, 9, 13, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
  310. // 3/0
  311. { { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
  312. { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
  313. { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
  314. // 2/1 - untested
  315. { { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
  316. { 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 6, 9, 11, 12, 13, -1, -1, -1, -1 },
  317. { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
  318. // 3/1
  319. { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
  320. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
  321. { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
  322. // 2/2 - untested
  323. { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
  324. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 10, 11, 11, 12, 12, 14, -1 },
  325. { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
  326. // 3/2
  327. { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 8, 11, 12, 12, -1, -1 },
  328. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 8, 11, 12, 12, -1, -1 },
  329. { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } },
  330. };
  331. /**
  332. * Adjust the frame size to make the average bit rate match the target bit rate.
  333. * This is only needed for 11025, 22050, and 44100 sample rates or any E-AC-3.
  334. */
  335. static void adjust_frame_size(AC3EncodeContext *s)
  336. {
  337. while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
  338. s->bits_written -= s->bit_rate;
  339. s->samples_written -= s->sample_rate;
  340. }
  341. s->frame_size = s->frame_size_min +
  342. 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
  343. s->bits_written += s->frame_size * 8;
  344. s->samples_written += AC3_FRAME_SIZE;
  345. }
  346. /**
  347. * Deinterleave input samples.
  348. * Channels are reordered from Libav's default order to AC-3 order.
  349. */
  350. static void deinterleave_input_samples(AC3EncodeContext *s,
  351. const SampleType *samples)
  352. {
  353. int ch, i;
  354. /* deinterleave and remap input samples */
  355. for (ch = 0; ch < s->channels; ch++) {
  356. const SampleType *sptr;
  357. int sinc;
  358. /* copy last 256 samples of previous frame to the start of the current frame */
  359. memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
  360. AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
  361. /* deinterleave */
  362. sinc = s->channels;
  363. sptr = samples + s->channel_map[ch];
  364. for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
  365. s->planar_samples[ch][i] = *sptr;
  366. sptr += sinc;
  367. }
  368. }
  369. }
  370. /**
  371. * Apply the MDCT to input samples to generate frequency coefficients.
  372. * This applies the KBD window and normalizes the input to reduce precision
  373. * loss due to fixed-point calculations.
  374. */
  375. static void apply_mdct(AC3EncodeContext *s)
  376. {
  377. int blk, ch;
  378. for (ch = 0; ch < s->channels; ch++) {
  379. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  380. AC3Block *block = &s->blocks[blk];
  381. const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
  382. apply_window(&s->dsp, s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
  383. block->coeff_shift[ch+1] = normalize_samples(s);
  384. s->mdct.fft.mdct_calcw(&s->mdct.fft, block->mdct_coef[ch+1],
  385. s->windowed_samples);
  386. }
  387. }
  388. }
  389. static void compute_coupling_strategy(AC3EncodeContext *s)
  390. {
  391. int blk, ch;
  392. int got_cpl_snr;
  393. /* set coupling use flags for each block/channel */
  394. /* TODO: turn coupling on/off and adjust start band based on bit usage */
  395. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  396. AC3Block *block = &s->blocks[blk];
  397. for (ch = 1; ch <= s->fbw_channels; ch++)
  398. block->channel_in_cpl[ch] = s->cpl_on;
  399. }
  400. /* enable coupling for each block if at least 2 channels have coupling
  401. enabled for that block */
  402. got_cpl_snr = 0;
  403. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  404. AC3Block *block = &s->blocks[blk];
  405. block->num_cpl_channels = 0;
  406. for (ch = 1; ch <= s->fbw_channels; ch++)
  407. block->num_cpl_channels += block->channel_in_cpl[ch];
  408. block->cpl_in_use = block->num_cpl_channels > 1;
  409. if (!block->cpl_in_use) {
  410. block->num_cpl_channels = 0;
  411. for (ch = 1; ch <= s->fbw_channels; ch++)
  412. block->channel_in_cpl[ch] = 0;
  413. }
  414. block->new_cpl_strategy = !blk;
  415. if (blk) {
  416. for (ch = 1; ch <= s->fbw_channels; ch++) {
  417. if (block->channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]) {
  418. block->new_cpl_strategy = 1;
  419. break;
  420. }
  421. }
  422. }
  423. block->new_cpl_leak = block->new_cpl_strategy;
  424. if (!blk || (block->cpl_in_use && !got_cpl_snr)) {
  425. block->new_snr_offsets = 1;
  426. if (block->cpl_in_use)
  427. got_cpl_snr = 1;
  428. } else {
  429. block->new_snr_offsets = 0;
  430. }
  431. }
  432. /* set bandwidth for each channel */
  433. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  434. AC3Block *block = &s->blocks[blk];
  435. for (ch = 1; ch <= s->fbw_channels; ch++) {
  436. if (block->channel_in_cpl[ch])
  437. block->end_freq[ch] = s->start_freq[CPL_CH];
  438. else
  439. block->end_freq[ch] = s->bandwidth_code * 3 + 73;
  440. }
  441. }
  442. }
  443. /**
  444. * Calculate a single coupling coordinate.
  445. */
  446. static inline float calc_cpl_coord(float energy_ch, float energy_cpl)
  447. {
  448. float coord = 0.125;
  449. if (energy_cpl > 0)
  450. coord *= sqrtf(energy_ch / energy_cpl);
  451. return coord;
  452. }
  453. /**
  454. * Calculate coupling channel and coupling coordinates.
  455. * TODO: Currently this is only used for the floating-point encoder. I was
  456. * able to make it work for the fixed-point encoder, but quality was
  457. * generally lower in most cases than not using coupling. If a more
  458. * adaptive coupling strategy were to be implemented it might be useful
  459. * at that time to use coupling for the fixed-point encoder as well.
  460. */
  461. static void apply_channel_coupling(AC3EncodeContext *s)
  462. {
  463. #if CONFIG_AC3ENC_FLOAT
  464. DECLARE_ALIGNED(16, float, cpl_coords) [AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][16] = {{{0}}};
  465. DECLARE_ALIGNED(16, int32_t, fixed_cpl_coords)[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][16] = {{{0}}};
  466. int blk, ch, bnd, i, j;
  467. CoefSumType energy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][16] = {{{0}}};
  468. int num_cpl_coefs = s->num_cpl_subbands * 12;
  469. /* calculate coupling channel from fbw channels */
  470. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  471. AC3Block *block = &s->blocks[blk];
  472. CoefType *cpl_coef = &block->mdct_coef[CPL_CH][s->start_freq[CPL_CH]];
  473. if (!block->cpl_in_use)
  474. continue;
  475. memset(cpl_coef-1, 0, (num_cpl_coefs+4) * sizeof(*cpl_coef));
  476. for (ch = 1; ch <= s->fbw_channels; ch++) {
  477. CoefType *ch_coef = &block->mdct_coef[ch][s->start_freq[CPL_CH]];
  478. if (!block->channel_in_cpl[ch])
  479. continue;
  480. for (i = 0; i < num_cpl_coefs; i++)
  481. cpl_coef[i] += ch_coef[i];
  482. }
  483. /* note: coupling start bin % 4 will always be 1 and num_cpl_coefs
  484. will always be a multiple of 12, so we need to subtract 1 from
  485. the start and add 4 to the length when using optimized
  486. functions which require 16-byte alignment. */
  487. /* coefficients must be clipped to +/- 1.0 in order to be encoded */
  488. s->dsp.vector_clipf(cpl_coef-1, cpl_coef-1, -1.0f, 1.0f, num_cpl_coefs+4);
  489. /* scale coupling coefficients from float to 24-bit fixed-point */
  490. s->ac3dsp.float_to_fixed24(&block->fixed_coef[CPL_CH][s->start_freq[CPL_CH]-1],
  491. cpl_coef-1, num_cpl_coefs+4);
  492. }
  493. /* calculate energy in each band in coupling channel and each fbw channel */
  494. /* TODO: possibly use SIMD to speed up energy calculation */
  495. bnd = 0;
  496. i = s->start_freq[CPL_CH];
  497. while (i < s->cpl_end_freq) {
  498. int band_size = s->cpl_band_sizes[bnd];
  499. for (ch = CPL_CH; ch <= s->fbw_channels; ch++) {
  500. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  501. AC3Block *block = &s->blocks[blk];
  502. if (!block->cpl_in_use || (ch > CPL_CH && !block->channel_in_cpl[ch]))
  503. continue;
  504. for (j = 0; j < band_size; j++) {
  505. CoefType v = block->mdct_coef[ch][i+j];
  506. MAC_COEF(energy[blk][ch][bnd], v, v);
  507. }
  508. }
  509. }
  510. i += band_size;
  511. bnd++;
  512. }
  513. /* determine which blocks to send new coupling coordinates for */
  514. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  515. AC3Block *block = &s->blocks[blk];
  516. AC3Block *block0 = blk ? &s->blocks[blk-1] : NULL;
  517. int new_coords = 0;
  518. CoefSumType coord_diff[AC3_MAX_CHANNELS] = {0,};
  519. if (block->cpl_in_use) {
  520. /* calculate coupling coordinates for all blocks and calculate the
  521. average difference between coordinates in successive blocks */
  522. for (ch = 1; ch <= s->fbw_channels; ch++) {
  523. if (!block->channel_in_cpl[ch])
  524. continue;
  525. for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
  526. cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy[blk][ch][bnd],
  527. energy[blk][CPL_CH][bnd]);
  528. if (blk > 0 && block0->cpl_in_use &&
  529. block0->channel_in_cpl[ch]) {
  530. coord_diff[ch] += fabs(cpl_coords[blk-1][ch][bnd] -
  531. cpl_coords[blk ][ch][bnd]);
  532. }
  533. }
  534. coord_diff[ch] /= s->num_cpl_bands;
  535. }
  536. /* send new coordinates if this is the first block, if previous
  537. * block did not use coupling but this block does, the channels
  538. * using coupling has changed from the previous block, or the
  539. * coordinate difference from the last block for any channel is
  540. * greater than a threshold value. */
  541. if (blk == 0) {
  542. new_coords = 1;
  543. } else if (!block0->cpl_in_use) {
  544. new_coords = 1;
  545. } else {
  546. for (ch = 1; ch <= s->fbw_channels; ch++) {
  547. if (block->channel_in_cpl[ch] && !block0->channel_in_cpl[ch]) {
  548. new_coords = 1;
  549. break;
  550. }
  551. }
  552. if (!new_coords) {
  553. for (ch = 1; ch <= s->fbw_channels; ch++) {
  554. if (block->channel_in_cpl[ch] && coord_diff[ch] > 0.04) {
  555. new_coords = 1;
  556. break;
  557. }
  558. }
  559. }
  560. }
  561. }
  562. block->new_cpl_coords = new_coords;
  563. }
  564. /* calculate final coupling coordinates, taking into account reusing of
  565. coordinates in successive blocks */
  566. for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
  567. blk = 0;
  568. while (blk < AC3_MAX_BLOCKS) {
  569. int blk1;
  570. CoefSumType energy_cpl;
  571. AC3Block *block = &s->blocks[blk];
  572. if (!block->cpl_in_use) {
  573. blk++;
  574. continue;
  575. }
  576. energy_cpl = energy[blk][CPL_CH][bnd];
  577. blk1 = blk+1;
  578. while (!s->blocks[blk1].new_cpl_coords && blk1 < AC3_MAX_BLOCKS) {
  579. if (s->blocks[blk1].cpl_in_use)
  580. energy_cpl += energy[blk1][CPL_CH][bnd];
  581. blk1++;
  582. }
  583. for (ch = 1; ch <= s->fbw_channels; ch++) {
  584. CoefType energy_ch;
  585. if (!block->channel_in_cpl[ch])
  586. continue;
  587. energy_ch = energy[blk][ch][bnd];
  588. blk1 = blk+1;
  589. while (!s->blocks[blk1].new_cpl_coords && blk1 < AC3_MAX_BLOCKS) {
  590. if (s->blocks[blk1].cpl_in_use)
  591. energy_ch += energy[blk1][ch][bnd];
  592. blk1++;
  593. }
  594. cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy_ch, energy_cpl);
  595. }
  596. blk = blk1;
  597. }
  598. }
  599. /* calculate exponents/mantissas for coupling coordinates */
  600. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  601. AC3Block *block = &s->blocks[blk];
  602. if (!block->cpl_in_use || !block->new_cpl_coords)
  603. continue;
  604. s->ac3dsp.float_to_fixed24(fixed_cpl_coords[blk][1],
  605. cpl_coords[blk][1],
  606. s->fbw_channels * 16);
  607. s->ac3dsp.extract_exponents(block->cpl_coord_exp[1],
  608. fixed_cpl_coords[blk][1],
  609. s->fbw_channels * 16);
  610. for (ch = 1; ch <= s->fbw_channels; ch++) {
  611. int bnd, min_exp, max_exp, master_exp;
  612. /* determine master exponent */
  613. min_exp = max_exp = block->cpl_coord_exp[ch][0];
  614. for (bnd = 1; bnd < s->num_cpl_bands; bnd++) {
  615. int exp = block->cpl_coord_exp[ch][bnd];
  616. min_exp = FFMIN(exp, min_exp);
  617. max_exp = FFMAX(exp, max_exp);
  618. }
  619. master_exp = ((max_exp - 15) + 2) / 3;
  620. master_exp = FFMAX(master_exp, 0);
  621. while (min_exp < master_exp * 3)
  622. master_exp--;
  623. for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
  624. block->cpl_coord_exp[ch][bnd] = av_clip(block->cpl_coord_exp[ch][bnd] -
  625. master_exp * 3, 0, 15);
  626. }
  627. block->cpl_master_exp[ch] = master_exp;
  628. /* quantize mantissas */
  629. for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
  630. int cpl_exp = block->cpl_coord_exp[ch][bnd];
  631. int cpl_mant = (fixed_cpl_coords[blk][ch][bnd] << (5 + cpl_exp + master_exp * 3)) >> 24;
  632. if (cpl_exp == 15)
  633. cpl_mant >>= 1;
  634. else
  635. cpl_mant -= 16;
  636. block->cpl_coord_mant[ch][bnd] = cpl_mant;
  637. }
  638. }
  639. }
  640. if (s->eac3) {
  641. /* set first cpl coords */
  642. int first_cpl_coords[AC3_MAX_CHANNELS];
  643. for (ch = 1; ch <= s->fbw_channels; ch++)
  644. first_cpl_coords[ch] = 1;
  645. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  646. AC3Block *block = &s->blocks[blk];
  647. for (ch = 1; ch <= s->fbw_channels; ch++) {
  648. if (block->channel_in_cpl[ch]) {
  649. if (first_cpl_coords[ch]) {
  650. block->new_cpl_coords = 2;
  651. first_cpl_coords[ch] = 0;
  652. }
  653. } else {
  654. first_cpl_coords[ch] = 1;
  655. }
  656. }
  657. }
  658. /* set first cpl leak */
  659. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  660. AC3Block *block = &s->blocks[blk];
  661. if (block->cpl_in_use) {
  662. block->new_cpl_leak = 2;
  663. break;
  664. }
  665. }
  666. }
  667. #endif /* CONFIG_AC3ENC_FLOAT */
  668. }
  669. /**
  670. * Determine rematrixing flags for each block and band.
  671. */
  672. static void compute_rematrixing_strategy(AC3EncodeContext *s)
  673. {
  674. int nb_coefs;
  675. int blk, bnd, i;
  676. AC3Block *block, *block0;
  677. if (s->channel_mode != AC3_CHMODE_STEREO)
  678. return;
  679. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  680. block = &s->blocks[blk];
  681. block->new_rematrixing_strategy = !blk;
  682. if (!s->rematrixing_enabled) {
  683. block0 = block;
  684. continue;
  685. }
  686. block->num_rematrixing_bands = 4;
  687. if (block->cpl_in_use) {
  688. block->num_rematrixing_bands -= (s->start_freq[CPL_CH] <= 61);
  689. block->num_rematrixing_bands -= (s->start_freq[CPL_CH] == 37);
  690. if (blk && block->num_rematrixing_bands != block0->num_rematrixing_bands)
  691. block->new_rematrixing_strategy = 1;
  692. }
  693. nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
  694. for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {
  695. /* calculate calculate sum of squared coeffs for one band in one block */
  696. int start = ff_ac3_rematrix_band_tab[bnd];
  697. int end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
  698. CoefSumType sum[4] = {0,};
  699. for (i = start; i < end; i++) {
  700. CoefType lt = block->mdct_coef[1][i];
  701. CoefType rt = block->mdct_coef[2][i];
  702. CoefType md = lt + rt;
  703. CoefType sd = lt - rt;
  704. MAC_COEF(sum[0], lt, lt);
  705. MAC_COEF(sum[1], rt, rt);
  706. MAC_COEF(sum[2], md, md);
  707. MAC_COEF(sum[3], sd, sd);
  708. }
  709. /* compare sums to determine if rematrixing will be used for this band */
  710. if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
  711. block->rematrixing_flags[bnd] = 1;
  712. else
  713. block->rematrixing_flags[bnd] = 0;
  714. /* determine if new rematrixing flags will be sent */
  715. if (blk &&
  716. block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
  717. block->new_rematrixing_strategy = 1;
  718. }
  719. }
  720. block0 = block;
  721. }
  722. }
  723. /**
  724. * Apply stereo rematrixing to coefficients based on rematrixing flags.
  725. */
  726. static void apply_rematrixing(AC3EncodeContext *s)
  727. {
  728. int nb_coefs;
  729. int blk, bnd, i;
  730. int start, end;
  731. uint8_t *flags;
  732. if (!s->rematrixing_enabled)
  733. return;
  734. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  735. AC3Block *block = &s->blocks[blk];
  736. if (block->new_rematrixing_strategy)
  737. flags = block->rematrixing_flags;
  738. nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);
  739. for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {
  740. if (flags[bnd]) {
  741. start = ff_ac3_rematrix_band_tab[bnd];
  742. end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
  743. for (i = start; i < end; i++) {
  744. int32_t lt = block->fixed_coef[1][i];
  745. int32_t rt = block->fixed_coef[2][i];
  746. block->fixed_coef[1][i] = (lt + rt) >> 1;
  747. block->fixed_coef[2][i] = (lt - rt) >> 1;
  748. }
  749. }
  750. }
  751. }
  752. }
  753. /**
  754. * Initialize exponent tables.
  755. */
  756. static av_cold void exponent_init(AC3EncodeContext *s)
  757. {
  758. int expstr, i, grpsize;
  759. for (expstr = EXP_D15-1; expstr <= EXP_D45-1; expstr++) {
  760. grpsize = 3 << expstr;
  761. for (i = 12; i < 256; i++) {
  762. exponent_group_tab[0][expstr][i] = (i + grpsize - 4) / grpsize;
  763. exponent_group_tab[1][expstr][i] = (i ) / grpsize;
  764. }
  765. }
  766. /* LFE */
  767. exponent_group_tab[0][0][7] = 2;
  768. }
  769. /**
  770. * Extract exponents from the MDCT coefficients.
  771. * This takes into account the normalization that was done to the input samples
  772. * by adjusting the exponents by the exponent shift values.
  773. */
  774. static void extract_exponents(AC3EncodeContext *s)
  775. {
  776. int blk, ch;
  777. for (ch = !s->cpl_on; ch <= s->channels; ch++) {
  778. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  779. AC3Block *block = &s->blocks[blk];
  780. s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch],
  781. AC3_MAX_COEFS);
  782. }
  783. }
  784. }
  785. /**
  786. * Exponent Difference Threshold.
  787. * New exponents are sent if their SAD exceed this number.
  788. */
  789. #define EXP_DIFF_THRESHOLD 500
  790. /**
  791. * Calculate exponent strategies for all channels.
  792. * Array arrangement is reversed to simplify the per-channel calculation.
  793. */
  794. static void compute_exp_strategy(AC3EncodeContext *s)
  795. {
  796. int ch, blk, blk1;
  797. for (ch = !s->cpl_on; ch <= s->fbw_channels; ch++) {
  798. uint8_t *exp_strategy = s->exp_strategy[ch];
  799. uint8_t *exp = s->blocks[0].exp[ch];
  800. int exp_diff;
  801. /* estimate if the exponent variation & decide if they should be
  802. reused in the next frame */
  803. exp_strategy[0] = EXP_NEW;
  804. exp += AC3_MAX_COEFS;
  805. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++, exp += AC3_MAX_COEFS) {
  806. if ((ch == CPL_CH && (!s->blocks[blk].cpl_in_use || !s->blocks[blk-1].cpl_in_use)) ||
  807. (ch > CPL_CH && (s->blocks[blk].channel_in_cpl[ch] != s->blocks[blk-1].channel_in_cpl[ch]))) {
  808. exp_strategy[blk] = EXP_NEW;
  809. continue;
  810. }
  811. exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
  812. exp_strategy[blk] = EXP_REUSE;
  813. if (ch == CPL_CH && exp_diff > (EXP_DIFF_THRESHOLD * (s->blocks[blk].end_freq[ch] - s->start_freq[ch]) / AC3_MAX_COEFS))
  814. exp_strategy[blk] = EXP_NEW;
  815. else if (ch > CPL_CH && exp_diff > EXP_DIFF_THRESHOLD)
  816. exp_strategy[blk] = EXP_NEW;
  817. }
  818. /* now select the encoding strategy type : if exponents are often
  819. recoded, we use a coarse encoding */
  820. blk = 0;
  821. while (blk < AC3_MAX_BLOCKS) {
  822. blk1 = blk + 1;
  823. while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
  824. blk1++;
  825. switch (blk1 - blk) {
  826. case 1: exp_strategy[blk] = EXP_D45; break;
  827. case 2:
  828. case 3: exp_strategy[blk] = EXP_D25; break;
  829. default: exp_strategy[blk] = EXP_D15; break;
  830. }
  831. blk = blk1;
  832. }
  833. }
  834. if (s->lfe_on) {
  835. ch = s->lfe_channel;
  836. s->exp_strategy[ch][0] = EXP_D15;
  837. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
  838. s->exp_strategy[ch][blk] = EXP_REUSE;
  839. }
  840. }
  841. /**
  842. * Update the exponents so that they are the ones the decoder will decode.
  843. */
  844. static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy,
  845. int cpl)
  846. {
  847. int nb_groups, i, k;
  848. nb_groups = exponent_group_tab[cpl][exp_strategy-1][nb_exps] * 3;
  849. /* for each group, compute the minimum exponent */
  850. switch(exp_strategy) {
  851. case EXP_D25:
  852. for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
  853. uint8_t exp_min = exp[k];
  854. if (exp[k+1] < exp_min)
  855. exp_min = exp[k+1];
  856. exp[i-cpl] = exp_min;
  857. k += 2;
  858. }
  859. break;
  860. case EXP_D45:
  861. for (i = 1, k = 1-cpl; i <= nb_groups; i++) {
  862. uint8_t exp_min = exp[k];
  863. if (exp[k+1] < exp_min)
  864. exp_min = exp[k+1];
  865. if (exp[k+2] < exp_min)
  866. exp_min = exp[k+2];
  867. if (exp[k+3] < exp_min)
  868. exp_min = exp[k+3];
  869. exp[i-cpl] = exp_min;
  870. k += 4;
  871. }
  872. break;
  873. }
  874. /* constraint for DC exponent */
  875. if (!cpl && exp[0] > 15)
  876. exp[0] = 15;
  877. /* decrease the delta between each groups to within 2 so that they can be
  878. differentially encoded */
  879. for (i = 1; i <= nb_groups; i++)
  880. exp[i] = FFMIN(exp[i], exp[i-1] + 2);
  881. i--;
  882. while (--i >= 0)
  883. exp[i] = FFMIN(exp[i], exp[i+1] + 2);
  884. if (cpl)
  885. exp[-1] = exp[0] & ~1;
  886. /* now we have the exponent values the decoder will see */
  887. switch (exp_strategy) {
  888. case EXP_D25:
  889. for (i = nb_groups, k = (nb_groups * 2)-cpl; i > 0; i--) {
  890. uint8_t exp1 = exp[i-cpl];
  891. exp[k--] = exp1;
  892. exp[k--] = exp1;
  893. }
  894. break;
  895. case EXP_D45:
  896. for (i = nb_groups, k = (nb_groups * 4)-cpl; i > 0; i--) {
  897. exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i-cpl];
  898. k -= 4;
  899. }
  900. break;
  901. }
  902. }
  903. /**
  904. * Encode exponents from original extracted form to what the decoder will see.
  905. * This copies and groups exponents based on exponent strategy and reduces
  906. * deltas between adjacent exponent groups so that they can be differentially
  907. * encoded.
  908. */
  909. static void encode_exponents(AC3EncodeContext *s)
  910. {
  911. int blk, blk1, ch, cpl;
  912. uint8_t *exp, *exp_strategy;
  913. int nb_coefs, num_reuse_blocks;
  914. for (ch = !s->cpl_on; ch <= s->channels; ch++) {
  915. exp = s->blocks[0].exp[ch] + s->start_freq[ch];
  916. exp_strategy = s->exp_strategy[ch];
  917. cpl = (ch == CPL_CH);
  918. blk = 0;
  919. while (blk < AC3_MAX_BLOCKS) {
  920. AC3Block *block = &s->blocks[blk];
  921. if (cpl && !block->cpl_in_use) {
  922. exp += AC3_MAX_COEFS;
  923. blk++;
  924. continue;
  925. }
  926. nb_coefs = block->end_freq[ch] - s->start_freq[ch];
  927. blk1 = blk + 1;
  928. /* count the number of EXP_REUSE blocks after the current block
  929. and set exponent reference block pointers */
  930. block->exp_ref_block[ch] = block;
  931. while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
  932. s->blocks[blk1].exp_ref_block[ch] = block;
  933. blk1++;
  934. }
  935. num_reuse_blocks = blk1 - blk - 1;
  936. /* for the EXP_REUSE case we select the min of the exponents */
  937. s->ac3dsp.ac3_exponent_min(exp-s->start_freq[ch], num_reuse_blocks,
  938. AC3_MAX_COEFS);
  939. encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk], cpl);
  940. exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
  941. blk = blk1;
  942. }
  943. }
  944. }
  945. /**
  946. * Group exponents.
  947. * 3 delta-encoded exponents are in each 7-bit group. The number of groups
  948. * varies depending on exponent strategy and bandwidth.
  949. */
  950. static void group_exponents(AC3EncodeContext *s)
  951. {
  952. int blk, ch, i, cpl;
  953. int group_size, nb_groups, bit_count;
  954. uint8_t *p;
  955. int delta0, delta1, delta2;
  956. int exp0, exp1;
  957. bit_count = 0;
  958. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  959. AC3Block *block = &s->blocks[blk];
  960. for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
  961. int exp_strategy = s->exp_strategy[ch][blk];
  962. if (exp_strategy == EXP_REUSE)
  963. continue;
  964. cpl = (ch == CPL_CH);
  965. group_size = exp_strategy + (exp_strategy == EXP_D45);
  966. nb_groups = exponent_group_tab[cpl][exp_strategy-1][block->end_freq[ch]-s->start_freq[ch]];
  967. bit_count += 4 + (nb_groups * 7);
  968. p = block->exp[ch] + s->start_freq[ch] - cpl;
  969. /* DC exponent */
  970. exp1 = *p++;
  971. block->grouped_exp[ch][0] = exp1;
  972. /* remaining exponents are delta encoded */
  973. for (i = 1; i <= nb_groups; i++) {
  974. /* merge three delta in one code */
  975. exp0 = exp1;
  976. exp1 = p[0];
  977. p += group_size;
  978. delta0 = exp1 - exp0 + 2;
  979. av_assert2(delta0 >= 0 && delta0 <= 4);
  980. exp0 = exp1;
  981. exp1 = p[0];
  982. p += group_size;
  983. delta1 = exp1 - exp0 + 2;
  984. av_assert2(delta1 >= 0 && delta1 <= 4);
  985. exp0 = exp1;
  986. exp1 = p[0];
  987. p += group_size;
  988. delta2 = exp1 - exp0 + 2;
  989. av_assert2(delta2 >= 0 && delta2 <= 4);
  990. block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
  991. }
  992. }
  993. }
  994. s->exponent_bits = bit_count;
  995. }
  996. /**
  997. * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
  998. * Extract exponents from MDCT coefficients, calculate exponent strategies,
  999. * and encode final exponents.
  1000. */
  1001. static void process_exponents(AC3EncodeContext *s)
  1002. {
  1003. extract_exponents(s);
  1004. compute_exp_strategy(s);
  1005. encode_exponents(s);
  1006. group_exponents(s);
  1007. emms_c();
  1008. }
  1009. /**
  1010. * Count frame bits that are based solely on fixed parameters.
  1011. * This only has to be run once when the encoder is initialized.
  1012. */
  1013. static void count_frame_bits_fixed(AC3EncodeContext *s)
  1014. {
  1015. static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
  1016. int blk;
  1017. int frame_bits;
  1018. /* assumptions:
  1019. * no dynamic range codes
  1020. * bit allocation parameters do not change between blocks
  1021. * no delta bit allocation
  1022. * no skipped data
  1023. * no auxilliary data
  1024. * no E-AC-3 metadata
  1025. */
  1026. /* header */
  1027. frame_bits = 16; /* sync info */
  1028. if (s->eac3) {
  1029. /* bitstream info header */
  1030. frame_bits += 35;
  1031. frame_bits += 1 + 1 + 1;
  1032. /* audio frame header */
  1033. frame_bits += 2;
  1034. frame_bits += 10;
  1035. /* exponent strategy */
  1036. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1037. frame_bits += 2 * s->fbw_channels + s->lfe_on;
  1038. /* converter exponent strategy */
  1039. frame_bits += s->fbw_channels * 5;
  1040. /* snr offsets */
  1041. frame_bits += 10;
  1042. /* block start info */
  1043. frame_bits++;
  1044. } else {
  1045. frame_bits += 49;
  1046. frame_bits += frame_bits_inc[s->channel_mode];
  1047. }
  1048. /* audio blocks */
  1049. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1050. if (!s->eac3) {
  1051. /* block switch flags */
  1052. frame_bits += s->fbw_channels;
  1053. /* dither flags */
  1054. frame_bits += s->fbw_channels;
  1055. }
  1056. /* dynamic range */
  1057. frame_bits++;
  1058. /* spectral extension */
  1059. if (s->eac3)
  1060. frame_bits++;
  1061. if (!s->eac3) {
  1062. /* exponent strategy */
  1063. frame_bits += 2 * s->fbw_channels;
  1064. if (s->lfe_on)
  1065. frame_bits++;
  1066. /* bit allocation params */
  1067. frame_bits++;
  1068. if (!blk)
  1069. frame_bits += 2 + 2 + 2 + 2 + 3;
  1070. }
  1071. /* converter snr offset */
  1072. if (s->eac3)
  1073. frame_bits++;
  1074. if (!s->eac3) {
  1075. /* delta bit allocation */
  1076. frame_bits++;
  1077. /* skipped data */
  1078. frame_bits++;
  1079. }
  1080. }
  1081. /* auxiliary data */
  1082. frame_bits++;
  1083. /* CRC */
  1084. frame_bits += 1 + 16;
  1085. s->frame_bits_fixed = frame_bits;
  1086. }
  1087. /**
  1088. * Initialize bit allocation.
  1089. * Set default parameter codes and calculate parameter values.
  1090. */
  1091. static void bit_alloc_init(AC3EncodeContext *s)
  1092. {
  1093. int ch;
  1094. /* init default parameters */
  1095. s->slow_decay_code = 2;
  1096. s->fast_decay_code = 1;
  1097. s->slow_gain_code = 1;
  1098. s->db_per_bit_code = s->eac3 ? 2 : 3;
  1099. s->floor_code = 7;
  1100. for (ch = 0; ch <= s->channels; ch++)
  1101. s->fast_gain_code[ch] = 4;
  1102. /* initial snr offset */
  1103. s->coarse_snr_offset = 40;
  1104. /* compute real values */
  1105. /* currently none of these values change during encoding, so we can just
  1106. set them once at initialization */
  1107. s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
  1108. s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
  1109. s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
  1110. s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
  1111. s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
  1112. s->bit_alloc.cpl_fast_leak = 0;
  1113. s->bit_alloc.cpl_slow_leak = 0;
  1114. count_frame_bits_fixed(s);
  1115. }
  1116. /**
  1117. * Count the bits used to encode the frame, minus exponents and mantissas.
  1118. * Bits based on fixed parameters have already been counted, so now we just
  1119. * have to add the bits based on parameters that change during encoding.
  1120. */
  1121. static void count_frame_bits(AC3EncodeContext *s)
  1122. {
  1123. AC3EncOptions *opt = &s->options;
  1124. int blk, ch;
  1125. int frame_bits = 0;
  1126. /* header */
  1127. if (s->eac3) {
  1128. /* coupling */
  1129. if (s->channel_mode > AC3_CHMODE_MONO) {
  1130. frame_bits++;
  1131. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
  1132. AC3Block *block = &s->blocks[blk];
  1133. frame_bits++;
  1134. if (block->new_cpl_strategy)
  1135. frame_bits++;
  1136. }
  1137. }
  1138. /* coupling exponent strategy */
  1139. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1140. frame_bits += 2 * s->blocks[blk].cpl_in_use;
  1141. } else {
  1142. if (opt->audio_production_info)
  1143. frame_bits += 7;
  1144. if (s->bitstream_id == 6) {
  1145. if (opt->extended_bsi_1)
  1146. frame_bits += 14;
  1147. if (opt->extended_bsi_2)
  1148. frame_bits += 14;
  1149. }
  1150. }
  1151. /* audio blocks */
  1152. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1153. AC3Block *block = &s->blocks[blk];
  1154. /* coupling strategy */
  1155. if (!s->eac3)
  1156. frame_bits++;
  1157. if (block->new_cpl_strategy) {
  1158. if (!s->eac3)
  1159. frame_bits++;
  1160. if (block->cpl_in_use) {
  1161. if (s->eac3)
  1162. frame_bits++;
  1163. if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO)
  1164. frame_bits += s->fbw_channels;
  1165. if (s->channel_mode == AC3_CHMODE_STEREO)
  1166. frame_bits++;
  1167. frame_bits += 4 + 4;
  1168. if (s->eac3)
  1169. frame_bits++;
  1170. else
  1171. frame_bits += s->num_cpl_subbands - 1;
  1172. }
  1173. }
  1174. /* coupling coordinates */
  1175. if (block->cpl_in_use) {
  1176. for (ch = 1; ch <= s->fbw_channels; ch++) {
  1177. if (block->channel_in_cpl[ch]) {
  1178. if (!s->eac3 || block->new_cpl_coords != 2)
  1179. frame_bits++;
  1180. if (block->new_cpl_coords) {
  1181. frame_bits += 2;
  1182. frame_bits += (4 + 4) * s->num_cpl_bands;
  1183. }
  1184. }
  1185. }
  1186. }
  1187. /* stereo rematrixing */
  1188. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1189. if (!s->eac3 || blk > 0)
  1190. frame_bits++;
  1191. if (s->blocks[blk].new_rematrixing_strategy)
  1192. frame_bits += block->num_rematrixing_bands;
  1193. }
  1194. /* bandwidth codes & gain range */
  1195. for (ch = 1; ch <= s->fbw_channels; ch++) {
  1196. if (s->exp_strategy[ch][blk] != EXP_REUSE) {
  1197. if (!block->channel_in_cpl[ch])
  1198. frame_bits += 6;
  1199. frame_bits += 2;
  1200. }
  1201. }
  1202. /* coupling exponent strategy */
  1203. if (!s->eac3 && block->cpl_in_use)
  1204. frame_bits += 2;
  1205. /* snr offsets and fast gain codes */
  1206. if (!s->eac3) {
  1207. frame_bits++;
  1208. if (block->new_snr_offsets)
  1209. frame_bits += 6 + (s->channels + block->cpl_in_use) * (4 + 3);
  1210. }
  1211. /* coupling leak info */
  1212. if (block->cpl_in_use) {
  1213. if (!s->eac3 || block->new_cpl_leak != 2)
  1214. frame_bits++;
  1215. if (block->new_cpl_leak)
  1216. frame_bits += 3 + 3;
  1217. }
  1218. }
  1219. s->frame_bits = s->frame_bits_fixed + frame_bits;
  1220. }
  1221. /**
  1222. * Finalize the mantissa bit count by adding in the grouped mantissas.
  1223. */
  1224. static int compute_mantissa_size_final(int mant_cnt[5])
  1225. {
  1226. // bap=1 : 3 mantissas in 5 bits
  1227. int bits = (mant_cnt[1] / 3) * 5;
  1228. // bap=2 : 3 mantissas in 7 bits
  1229. // bap=4 : 2 mantissas in 7 bits
  1230. bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
  1231. // bap=3 : each mantissa is 3 bits
  1232. bits += mant_cnt[3] * 3;
  1233. return bits;
  1234. }
  1235. /**
  1236. * Calculate masking curve based on the final exponents.
  1237. * Also calculate the power spectral densities to use in future calculations.
  1238. */
  1239. static void bit_alloc_masking(AC3EncodeContext *s)
  1240. {
  1241. int blk, ch;
  1242. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1243. AC3Block *block = &s->blocks[blk];
  1244. for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
  1245. /* We only need psd and mask for calculating bap.
  1246. Since we currently do not calculate bap when exponent
  1247. strategy is EXP_REUSE we do not need to calculate psd or mask. */
  1248. if (s->exp_strategy[ch][blk] != EXP_REUSE) {
  1249. ff_ac3_bit_alloc_calc_psd(block->exp[ch], s->start_freq[ch],
  1250. block->end_freq[ch], block->psd[ch],
  1251. block->band_psd[ch]);
  1252. ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
  1253. s->start_freq[ch], block->end_freq[ch],
  1254. ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
  1255. ch == s->lfe_channel,
  1256. DBA_NONE, 0, NULL, NULL, NULL,
  1257. block->mask[ch]);
  1258. }
  1259. }
  1260. }
  1261. }
  1262. /**
  1263. * Ensure that bap for each block and channel point to the current bap_buffer.
  1264. * They may have been switched during the bit allocation search.
  1265. */
  1266. static void reset_block_bap(AC3EncodeContext *s)
  1267. {
  1268. int blk, ch;
  1269. int channels = s->channels + 1;
  1270. if (s->blocks[0].bap[0] == s->bap_buffer)
  1271. return;
  1272. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1273. for (ch = 0; ch < channels; ch++) {
  1274. s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * channels + ch)];
  1275. }
  1276. }
  1277. }
  1278. /**
  1279. * Run the bit allocation with a given SNR offset.
  1280. * This calculates the bit allocation pointers that will be used to determine
  1281. * the quantization of each mantissa.
  1282. * @return the number of bits needed for mantissas if the given SNR offset is
  1283. * is used.
  1284. */
  1285. static int bit_alloc(AC3EncodeContext *s, int snr_offset)
  1286. {
  1287. int blk, ch;
  1288. int mantissa_bits;
  1289. int mant_cnt[5];
  1290. snr_offset = (snr_offset - 240) << 2;
  1291. reset_block_bap(s);
  1292. mantissa_bits = 0;
  1293. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1294. AC3Block *block = &s->blocks[blk];
  1295. AC3Block *ref_block;
  1296. int av_uninit(ch0);
  1297. int got_cpl = !block->cpl_in_use;
  1298. // initialize grouped mantissa counts. these are set so that they are
  1299. // padded to the next whole group size when bits are counted in
  1300. // compute_mantissa_size_final
  1301. mant_cnt[0] = mant_cnt[3] = 0;
  1302. mant_cnt[1] = mant_cnt[2] = 2;
  1303. mant_cnt[4] = 1;
  1304. for (ch = 1; ch <= s->channels; ch++) {
  1305. if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
  1306. ch0 = ch - 1;
  1307. ch = CPL_CH;
  1308. got_cpl = 1;
  1309. }
  1310. /* Currently the only bit allocation parameters which vary across
  1311. blocks within a frame are the exponent values. We can take
  1312. advantage of that by reusing the bit allocation pointers
  1313. whenever we reuse exponents. */
  1314. ref_block = block->exp_ref_block[ch];
  1315. if (s->exp_strategy[ch][blk] != EXP_REUSE) {
  1316. s->ac3dsp.bit_alloc_calc_bap(ref_block->mask[ch], ref_block->psd[ch],
  1317. s->start_freq[ch], block->end_freq[ch],
  1318. snr_offset, s->bit_alloc.floor,
  1319. ff_ac3_bap_tab, ref_block->bap[ch]);
  1320. }
  1321. mantissa_bits += s->ac3dsp.compute_mantissa_size(mant_cnt,
  1322. ref_block->bap[ch]+s->start_freq[ch],
  1323. block->end_freq[ch]-s->start_freq[ch]);
  1324. if (ch == CPL_CH)
  1325. ch = ch0;
  1326. }
  1327. mantissa_bits += compute_mantissa_size_final(mant_cnt);
  1328. }
  1329. return mantissa_bits;
  1330. }
  1331. /**
  1332. * Constant bitrate bit allocation search.
  1333. * Find the largest SNR offset that will allow data to fit in the frame.
  1334. */
  1335. static int cbr_bit_allocation(AC3EncodeContext *s)
  1336. {
  1337. int ch;
  1338. int bits_left;
  1339. int snr_offset, snr_incr;
  1340. bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
  1341. if (bits_left < 0)
  1342. return AVERROR(EINVAL);
  1343. snr_offset = s->coarse_snr_offset << 4;
  1344. /* if previous frame SNR offset was 1023, check if current frame can also
  1345. use SNR offset of 1023. if so, skip the search. */
  1346. if ((snr_offset | s->fine_snr_offset[1]) == 1023) {
  1347. if (bit_alloc(s, 1023) <= bits_left)
  1348. return 0;
  1349. }
  1350. while (snr_offset >= 0 &&
  1351. bit_alloc(s, snr_offset) > bits_left) {
  1352. snr_offset -= 64;
  1353. }
  1354. if (snr_offset < 0)
  1355. return AVERROR(EINVAL);
  1356. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  1357. for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
  1358. while (snr_offset + snr_incr <= 1023 &&
  1359. bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
  1360. snr_offset += snr_incr;
  1361. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  1362. }
  1363. }
  1364. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  1365. reset_block_bap(s);
  1366. s->coarse_snr_offset = snr_offset >> 4;
  1367. for (ch = !s->cpl_on; ch <= s->channels; ch++)
  1368. s->fine_snr_offset[ch] = snr_offset & 0xF;
  1369. return 0;
  1370. }
  1371. /**
  1372. * Downgrade exponent strategies to reduce the bits used by the exponents.
  1373. * This is a fallback for when bit allocation fails with the normal exponent
  1374. * strategies. Each time this function is run it only downgrades the
  1375. * strategy in 1 channel of 1 block.
  1376. * @return non-zero if downgrade was unsuccessful
  1377. */
  1378. static int downgrade_exponents(AC3EncodeContext *s)
  1379. {
  1380. int ch, blk;
  1381. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  1382. for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
  1383. if (s->exp_strategy[ch][blk] == EXP_D15) {
  1384. s->exp_strategy[ch][blk] = EXP_D25;
  1385. return 0;
  1386. }
  1387. }
  1388. }
  1389. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  1390. for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
  1391. if (s->exp_strategy[ch][blk] == EXP_D25) {
  1392. s->exp_strategy[ch][blk] = EXP_D45;
  1393. return 0;
  1394. }
  1395. }
  1396. }
  1397. /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
  1398. the block number > 0 */
  1399. for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
  1400. for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++) {
  1401. if (s->exp_strategy[ch][blk] > EXP_REUSE) {
  1402. s->exp_strategy[ch][blk] = EXP_REUSE;
  1403. return 0;
  1404. }
  1405. }
  1406. }
  1407. return -1;
  1408. }
  1409. /**
  1410. * Perform bit allocation search.
  1411. * Finds the SNR offset value that maximizes quality and fits in the specified
  1412. * frame size. Output is the SNR offset and a set of bit allocation pointers
  1413. * used to quantize the mantissas.
  1414. */
  1415. static int compute_bit_allocation(AC3EncodeContext *s)
  1416. {
  1417. int ret;
  1418. count_frame_bits(s);
  1419. bit_alloc_masking(s);
  1420. ret = cbr_bit_allocation(s);
  1421. while (ret) {
  1422. /* fallback 1: disable channel coupling */
  1423. if (s->cpl_on) {
  1424. s->cpl_on = 0;
  1425. compute_coupling_strategy(s);
  1426. compute_rematrixing_strategy(s);
  1427. apply_rematrixing(s);
  1428. process_exponents(s);
  1429. ret = compute_bit_allocation(s);
  1430. continue;
  1431. }
  1432. /* fallback 2: downgrade exponents */
  1433. if (!downgrade_exponents(s)) {
  1434. extract_exponents(s);
  1435. encode_exponents(s);
  1436. group_exponents(s);
  1437. ret = compute_bit_allocation(s);
  1438. continue;
  1439. }
  1440. /* fallbacks were not enough... */
  1441. break;
  1442. }
  1443. return ret;
  1444. }
  1445. /**
  1446. * Symmetric quantization on 'levels' levels.
  1447. */
  1448. static inline int sym_quant(int c, int e, int levels)
  1449. {
  1450. int v = (((levels * c) >> (24 - e)) + levels) >> 1;
  1451. av_assert2(v >= 0 && v < levels);
  1452. return v;
  1453. }
  1454. /**
  1455. * Asymmetric quantization on 2^qbits levels.
  1456. */
  1457. static inline int asym_quant(int c, int e, int qbits)
  1458. {
  1459. int lshift, m, v;
  1460. lshift = e + qbits - 24;
  1461. if (lshift >= 0)
  1462. v = c << lshift;
  1463. else
  1464. v = c >> (-lshift);
  1465. /* rounding */
  1466. v = (v + 1) >> 1;
  1467. m = (1 << (qbits-1));
  1468. if (v >= m)
  1469. v = m - 1;
  1470. av_assert2(v >= -m);
  1471. return v & ((1 << qbits)-1);
  1472. }
  1473. /**
  1474. * Quantize a set of mantissas for a single channel in a single block.
  1475. */
  1476. static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
  1477. uint8_t *exp, uint8_t *bap,
  1478. uint16_t *qmant, int start_freq,
  1479. int end_freq)
  1480. {
  1481. int i;
  1482. for (i = start_freq; i < end_freq; i++) {
  1483. int v;
  1484. int c = fixed_coef[i];
  1485. int e = exp[i];
  1486. int b = bap[i];
  1487. switch (b) {
  1488. case 0:
  1489. v = 0;
  1490. break;
  1491. case 1:
  1492. v = sym_quant(c, e, 3);
  1493. switch (s->mant1_cnt) {
  1494. case 0:
  1495. s->qmant1_ptr = &qmant[i];
  1496. v = 9 * v;
  1497. s->mant1_cnt = 1;
  1498. break;
  1499. case 1:
  1500. *s->qmant1_ptr += 3 * v;
  1501. s->mant1_cnt = 2;
  1502. v = 128;
  1503. break;
  1504. default:
  1505. *s->qmant1_ptr += v;
  1506. s->mant1_cnt = 0;
  1507. v = 128;
  1508. break;
  1509. }
  1510. break;
  1511. case 2:
  1512. v = sym_quant(c, e, 5);
  1513. switch (s->mant2_cnt) {
  1514. case 0:
  1515. s->qmant2_ptr = &qmant[i];
  1516. v = 25 * v;
  1517. s->mant2_cnt = 1;
  1518. break;
  1519. case 1:
  1520. *s->qmant2_ptr += 5 * v;
  1521. s->mant2_cnt = 2;
  1522. v = 128;
  1523. break;
  1524. default:
  1525. *s->qmant2_ptr += v;
  1526. s->mant2_cnt = 0;
  1527. v = 128;
  1528. break;
  1529. }
  1530. break;
  1531. case 3:
  1532. v = sym_quant(c, e, 7);
  1533. break;
  1534. case 4:
  1535. v = sym_quant(c, e, 11);
  1536. switch (s->mant4_cnt) {
  1537. case 0:
  1538. s->qmant4_ptr = &qmant[i];
  1539. v = 11 * v;
  1540. s->mant4_cnt = 1;
  1541. break;
  1542. default:
  1543. *s->qmant4_ptr += v;
  1544. s->mant4_cnt = 0;
  1545. v = 128;
  1546. break;
  1547. }
  1548. break;
  1549. case 5:
  1550. v = sym_quant(c, e, 15);
  1551. break;
  1552. case 14:
  1553. v = asym_quant(c, e, 14);
  1554. break;
  1555. case 15:
  1556. v = asym_quant(c, e, 16);
  1557. break;
  1558. default:
  1559. v = asym_quant(c, e, b - 1);
  1560. break;
  1561. }
  1562. qmant[i] = v;
  1563. }
  1564. }
  1565. /**
  1566. * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
  1567. */
  1568. static void quantize_mantissas(AC3EncodeContext *s)
  1569. {
  1570. int blk, ch, ch0=0, got_cpl;
  1571. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1572. AC3Block *block = &s->blocks[blk];
  1573. AC3Block *ref_block;
  1574. AC3Mant m = { 0 };
  1575. got_cpl = !block->cpl_in_use;
  1576. for (ch = 1; ch <= s->channels; ch++) {
  1577. if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
  1578. ch0 = ch - 1;
  1579. ch = CPL_CH;
  1580. got_cpl = 1;
  1581. }
  1582. ref_block = block->exp_ref_block[ch];
  1583. quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
  1584. ref_block->exp[ch],
  1585. ref_block->bap[ch], block->qmant[ch],
  1586. s->start_freq[ch], block->end_freq[ch]);
  1587. if (ch == CPL_CH)
  1588. ch = ch0;
  1589. }
  1590. }
  1591. }
  1592. /**
  1593. * Write the AC-3 frame header to the output bitstream.
  1594. */
  1595. static void ac3_output_frame_header(AC3EncodeContext *s)
  1596. {
  1597. AC3EncOptions *opt = &s->options;
  1598. put_bits(&s->pb, 16, 0x0b77); /* frame header */
  1599. put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
  1600. put_bits(&s->pb, 2, s->bit_alloc.sr_code);
  1601. put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
  1602. put_bits(&s->pb, 5, s->bitstream_id);
  1603. put_bits(&s->pb, 3, s->bitstream_mode);
  1604. put_bits(&s->pb, 3, s->channel_mode);
  1605. if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
  1606. put_bits(&s->pb, 2, s->center_mix_level);
  1607. if (s->channel_mode & 0x04)
  1608. put_bits(&s->pb, 2, s->surround_mix_level);
  1609. if (s->channel_mode == AC3_CHMODE_STEREO)
  1610. put_bits(&s->pb, 2, opt->dolby_surround_mode);
  1611. put_bits(&s->pb, 1, s->lfe_on); /* LFE */
  1612. put_bits(&s->pb, 5, -opt->dialogue_level);
  1613. put_bits(&s->pb, 1, 0); /* no compression control word */
  1614. put_bits(&s->pb, 1, 0); /* no lang code */
  1615. put_bits(&s->pb, 1, opt->audio_production_info);
  1616. if (opt->audio_production_info) {
  1617. put_bits(&s->pb, 5, opt->mixing_level - 80);
  1618. put_bits(&s->pb, 2, opt->room_type);
  1619. }
  1620. put_bits(&s->pb, 1, opt->copyright);
  1621. put_bits(&s->pb, 1, opt->original);
  1622. if (s->bitstream_id == 6) {
  1623. /* alternate bit stream syntax */
  1624. put_bits(&s->pb, 1, opt->extended_bsi_1);
  1625. if (opt->extended_bsi_1) {
  1626. put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
  1627. put_bits(&s->pb, 3, s->ltrt_center_mix_level);
  1628. put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
  1629. put_bits(&s->pb, 3, s->loro_center_mix_level);
  1630. put_bits(&s->pb, 3, s->loro_surround_mix_level);
  1631. }
  1632. put_bits(&s->pb, 1, opt->extended_bsi_2);
  1633. if (opt->extended_bsi_2) {
  1634. put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
  1635. put_bits(&s->pb, 2, opt->dolby_headphone_mode);
  1636. put_bits(&s->pb, 1, opt->ad_converter_type);
  1637. put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
  1638. }
  1639. } else {
  1640. put_bits(&s->pb, 1, 0); /* no time code 1 */
  1641. put_bits(&s->pb, 1, 0); /* no time code 2 */
  1642. }
  1643. put_bits(&s->pb, 1, 0); /* no additional bit stream info */
  1644. }
  1645. /**
  1646. * Write the E-AC-3 frame header to the output bitstream.
  1647. */
  1648. static void eac3_output_frame_header(AC3EncodeContext *s)
  1649. {
  1650. int blk, ch;
  1651. AC3EncOptions *opt = &s->options;
  1652. put_bits(&s->pb, 16, 0x0b77); /* sync word */
  1653. /* BSI header */
  1654. put_bits(&s->pb, 2, 0); /* stream type = independent */
  1655. put_bits(&s->pb, 3, 0); /* substream id = 0 */
  1656. put_bits(&s->pb, 11, (s->frame_size / 2) - 1); /* frame size */
  1657. if (s->bit_alloc.sr_shift) {
  1658. put_bits(&s->pb, 2, 0x3); /* fscod2 */
  1659. put_bits(&s->pb, 2, s->bit_alloc.sr_code); /* sample rate code */
  1660. } else {
  1661. put_bits(&s->pb, 2, s->bit_alloc.sr_code); /* sample rate code */
  1662. put_bits(&s->pb, 2, 0x3); /* number of blocks = 6 */
  1663. }
  1664. put_bits(&s->pb, 3, s->channel_mode); /* audio coding mode */
  1665. put_bits(&s->pb, 1, s->lfe_on); /* LFE channel indicator */
  1666. put_bits(&s->pb, 5, s->bitstream_id); /* bitstream id (EAC3=16) */
  1667. put_bits(&s->pb, 5, -opt->dialogue_level); /* dialogue normalization level */
  1668. put_bits(&s->pb, 1, 0); /* no compression gain */
  1669. put_bits(&s->pb, 1, 0); /* no mixing metadata */
  1670. /* TODO: mixing metadata */
  1671. put_bits(&s->pb, 1, 0); /* no info metadata */
  1672. /* TODO: info metadata */
  1673. put_bits(&s->pb, 1, 0); /* no additional bit stream info */
  1674. /* frame header */
  1675. put_bits(&s->pb, 1, 1); /* exponent strategy syntax = each block */
  1676. put_bits(&s->pb, 1, 0); /* aht enabled = no */
  1677. put_bits(&s->pb, 2, 0); /* snr offset strategy = 1 */
  1678. put_bits(&s->pb, 1, 0); /* transient pre-noise processing enabled = no */
  1679. put_bits(&s->pb, 1, 0); /* block switch syntax enabled = no */
  1680. put_bits(&s->pb, 1, 0); /* dither flag syntax enabled = no */
  1681. put_bits(&s->pb, 1, 0); /* bit allocation model syntax enabled = no */
  1682. put_bits(&s->pb, 1, 0); /* fast gain codes enabled = no */
  1683. put_bits(&s->pb, 1, 0); /* dba syntax enabled = no */
  1684. put_bits(&s->pb, 1, 0); /* skip field syntax enabled = no */
  1685. put_bits(&s->pb, 1, 0); /* spx enabled = no */
  1686. /* coupling strategy use flags */
  1687. if (s->channel_mode > AC3_CHMODE_MONO) {
  1688. put_bits(&s->pb, 1, s->blocks[0].cpl_in_use);
  1689. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
  1690. AC3Block *block = &s->blocks[blk];
  1691. put_bits(&s->pb, 1, block->new_cpl_strategy);
  1692. if (block->new_cpl_strategy)
  1693. put_bits(&s->pb, 1, block->cpl_in_use);
  1694. }
  1695. }
  1696. /* exponent strategy */
  1697. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1698. for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++)
  1699. put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
  1700. if (s->lfe_on) {
  1701. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1702. put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
  1703. }
  1704. /* E-AC-3 to AC-3 converter exponent strategy (unfortunately not optional...) */
  1705. for (ch = 1; ch <= s->fbw_channels; ch++)
  1706. put_bits(&s->pb, 5, 0);
  1707. /* snr offsets */
  1708. put_bits(&s->pb, 6, s->coarse_snr_offset);
  1709. put_bits(&s->pb, 4, s->fine_snr_offset[1]);
  1710. /* block start info */
  1711. put_bits(&s->pb, 1, 0);
  1712. }
  1713. /**
  1714. * Write one audio block to the output bitstream.
  1715. */
  1716. static void output_audio_block(AC3EncodeContext *s, int blk)
  1717. {
  1718. int ch, i, baie, bnd, got_cpl;
  1719. int av_uninit(ch0);
  1720. AC3Block *block = &s->blocks[blk];
  1721. /* block switching */
  1722. if (!s->eac3) {
  1723. for (ch = 0; ch < s->fbw_channels; ch++)
  1724. put_bits(&s->pb, 1, 0);
  1725. }
  1726. /* dither flags */
  1727. if (!s->eac3) {
  1728. for (ch = 0; ch < s->fbw_channels; ch++)
  1729. put_bits(&s->pb, 1, 1);
  1730. }
  1731. /* dynamic range codes */
  1732. put_bits(&s->pb, 1, 0);
  1733. /* spectral extension */
  1734. if (s->eac3)
  1735. put_bits(&s->pb, 1, 0);
  1736. /* channel coupling */
  1737. if (!s->eac3)
  1738. put_bits(&s->pb, 1, block->new_cpl_strategy);
  1739. if (block->new_cpl_strategy) {
  1740. if (!s->eac3)
  1741. put_bits(&s->pb, 1, block->cpl_in_use);
  1742. if (block->cpl_in_use) {
  1743. int start_sub, end_sub;
  1744. if (s->eac3)
  1745. put_bits(&s->pb, 1, 0); /* enhanced coupling */
  1746. if (!s->eac3 || s->channel_mode != AC3_CHMODE_STEREO) {
  1747. for (ch = 1; ch <= s->fbw_channels; ch++)
  1748. put_bits(&s->pb, 1, block->channel_in_cpl[ch]);
  1749. }
  1750. if (s->channel_mode == AC3_CHMODE_STEREO)
  1751. put_bits(&s->pb, 1, 0); /* phase flags in use */
  1752. start_sub = (s->start_freq[CPL_CH] - 37) / 12;
  1753. end_sub = (s->cpl_end_freq - 37) / 12;
  1754. put_bits(&s->pb, 4, start_sub);
  1755. put_bits(&s->pb, 4, end_sub - 3);
  1756. /* coupling band structure */
  1757. if (s->eac3) {
  1758. put_bits(&s->pb, 1, 0); /* use default */
  1759. } else {
  1760. for (bnd = start_sub+1; bnd < end_sub; bnd++)
  1761. put_bits(&s->pb, 1, ff_eac3_default_cpl_band_struct[bnd]);
  1762. }
  1763. }
  1764. }
  1765. /* coupling coordinates */
  1766. if (block->cpl_in_use) {
  1767. for (ch = 1; ch <= s->fbw_channels; ch++) {
  1768. if (block->channel_in_cpl[ch]) {
  1769. if (!s->eac3 || block->new_cpl_coords != 2)
  1770. put_bits(&s->pb, 1, block->new_cpl_coords);
  1771. if (block->new_cpl_coords) {
  1772. put_bits(&s->pb, 2, block->cpl_master_exp[ch]);
  1773. for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
  1774. put_bits(&s->pb, 4, block->cpl_coord_exp [ch][bnd]);
  1775. put_bits(&s->pb, 4, block->cpl_coord_mant[ch][bnd]);
  1776. }
  1777. }
  1778. }
  1779. }
  1780. }
  1781. /* stereo rematrixing */
  1782. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1783. if (!s->eac3 || blk > 0)
  1784. put_bits(&s->pb, 1, block->new_rematrixing_strategy);
  1785. if (block->new_rematrixing_strategy) {
  1786. /* rematrixing flags */
  1787. for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++)
  1788. put_bits(&s->pb, 1, block->rematrixing_flags[bnd]);
  1789. }
  1790. }
  1791. /* exponent strategy */
  1792. if (!s->eac3) {
  1793. for (ch = !block->cpl_in_use; ch <= s->fbw_channels; ch++)
  1794. put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
  1795. if (s->lfe_on)
  1796. put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
  1797. }
  1798. /* bandwidth */
  1799. for (ch = 1; ch <= s->fbw_channels; ch++) {
  1800. if (s->exp_strategy[ch][blk] != EXP_REUSE && !block->channel_in_cpl[ch])
  1801. put_bits(&s->pb, 6, s->bandwidth_code);
  1802. }
  1803. /* exponents */
  1804. for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
  1805. int nb_groups;
  1806. int cpl = (ch == CPL_CH);
  1807. if (s->exp_strategy[ch][blk] == EXP_REUSE)
  1808. continue;
  1809. /* DC exponent */
  1810. put_bits(&s->pb, 4, block->grouped_exp[ch][0] >> cpl);
  1811. /* exponent groups */
  1812. nb_groups = exponent_group_tab[cpl][s->exp_strategy[ch][blk]-1][block->end_freq[ch]-s->start_freq[ch]];
  1813. for (i = 1; i <= nb_groups; i++)
  1814. put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
  1815. /* gain range info */
  1816. if (ch != s->lfe_channel && !cpl)
  1817. put_bits(&s->pb, 2, 0);
  1818. }
  1819. /* bit allocation info */
  1820. if (!s->eac3) {
  1821. baie = (blk == 0);
  1822. put_bits(&s->pb, 1, baie);
  1823. if (baie) {
  1824. put_bits(&s->pb, 2, s->slow_decay_code);
  1825. put_bits(&s->pb, 2, s->fast_decay_code);
  1826. put_bits(&s->pb, 2, s->slow_gain_code);
  1827. put_bits(&s->pb, 2, s->db_per_bit_code);
  1828. put_bits(&s->pb, 3, s->floor_code);
  1829. }
  1830. }
  1831. /* snr offset */
  1832. if (!s->eac3) {
  1833. put_bits(&s->pb, 1, block->new_snr_offsets);
  1834. if (block->new_snr_offsets) {
  1835. put_bits(&s->pb, 6, s->coarse_snr_offset);
  1836. for (ch = !block->cpl_in_use; ch <= s->channels; ch++) {
  1837. put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
  1838. put_bits(&s->pb, 3, s->fast_gain_code[ch]);
  1839. }
  1840. }
  1841. } else {
  1842. put_bits(&s->pb, 1, 0); /* no converter snr offset */
  1843. }
  1844. /* coupling leak */
  1845. if (block->cpl_in_use) {
  1846. if (!s->eac3 || block->new_cpl_leak != 2)
  1847. put_bits(&s->pb, 1, block->new_cpl_leak);
  1848. if (block->new_cpl_leak) {
  1849. put_bits(&s->pb, 3, s->bit_alloc.cpl_fast_leak);
  1850. put_bits(&s->pb, 3, s->bit_alloc.cpl_slow_leak);
  1851. }
  1852. }
  1853. if (!s->eac3) {
  1854. put_bits(&s->pb, 1, 0); /* no delta bit allocation */
  1855. put_bits(&s->pb, 1, 0); /* no data to skip */
  1856. }
  1857. /* mantissas */
  1858. got_cpl = !block->cpl_in_use;
  1859. for (ch = 1; ch <= s->channels; ch++) {
  1860. int b, q;
  1861. AC3Block *ref_block;
  1862. if (!got_cpl && ch > 1 && block->channel_in_cpl[ch-1]) {
  1863. ch0 = ch - 1;
  1864. ch = CPL_CH;
  1865. got_cpl = 1;
  1866. }
  1867. ref_block = block->exp_ref_block[ch];
  1868. for (i = s->start_freq[ch]; i < block->end_freq[ch]; i++) {
  1869. q = block->qmant[ch][i];
  1870. b = ref_block->bap[ch][i];
  1871. switch (b) {
  1872. case 0: break;
  1873. case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
  1874. case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
  1875. case 3: put_bits(&s->pb, 3, q); break;
  1876. case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
  1877. case 14: put_bits(&s->pb, 14, q); break;
  1878. case 15: put_bits(&s->pb, 16, q); break;
  1879. default: put_bits(&s->pb, b-1, q); break;
  1880. }
  1881. }
  1882. if (ch == CPL_CH)
  1883. ch = ch0;
  1884. }
  1885. }
  1886. /** CRC-16 Polynomial */
  1887. #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
  1888. static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
  1889. {
  1890. unsigned int c;
  1891. c = 0;
  1892. while (a) {
  1893. if (a & 1)
  1894. c ^= b;
  1895. a = a >> 1;
  1896. b = b << 1;
  1897. if (b & (1 << 16))
  1898. b ^= poly;
  1899. }
  1900. return c;
  1901. }
  1902. static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
  1903. {
  1904. unsigned int r;
  1905. r = 1;
  1906. while (n) {
  1907. if (n & 1)
  1908. r = mul_poly(r, a, poly);
  1909. a = mul_poly(a, a, poly);
  1910. n >>= 1;
  1911. }
  1912. return r;
  1913. }
  1914. /**
  1915. * Fill the end of the frame with 0's and compute the two CRCs.
  1916. */
  1917. static void output_frame_end(AC3EncodeContext *s)
  1918. {
  1919. const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
  1920. int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
  1921. uint8_t *frame;
  1922. frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
  1923. /* pad the remainder of the frame with zeros */
  1924. av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
  1925. flush_put_bits(&s->pb);
  1926. frame = s->pb.buf;
  1927. pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
  1928. av_assert2(pad_bytes >= 0);
  1929. if (pad_bytes > 0)
  1930. memset(put_bits_ptr(&s->pb), 0, pad_bytes);
  1931. if (s->eac3) {
  1932. /* compute crc2 */
  1933. crc2_partial = av_crc(crc_ctx, 0, frame + 2, s->frame_size - 5);
  1934. } else {
  1935. /* compute crc1 */
  1936. /* this is not so easy because it is at the beginning of the data... */
  1937. crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
  1938. crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
  1939. crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
  1940. AV_WB16(frame + 2, crc1);
  1941. /* compute crc2 */
  1942. crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
  1943. s->frame_size - frame_size_58 - 3);
  1944. }
  1945. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1946. /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
  1947. if (crc2 == 0x770B) {
  1948. frame[s->frame_size - 3] ^= 0x1;
  1949. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1950. }
  1951. crc2 = av_bswap16(crc2);
  1952. AV_WB16(frame + s->frame_size - 2, crc2);
  1953. }
  1954. /**
  1955. * Write the frame to the output bitstream.
  1956. */
  1957. static void output_frame(AC3EncodeContext *s, unsigned char *frame)
  1958. {
  1959. int blk;
  1960. init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
  1961. if (s->eac3)
  1962. eac3_output_frame_header(s);
  1963. else
  1964. ac3_output_frame_header(s);
  1965. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1966. output_audio_block(s, blk);
  1967. output_frame_end(s);
  1968. }
  1969. static void dprint_options(AVCodecContext *avctx)
  1970. {
  1971. #ifdef DEBUG
  1972. AC3EncodeContext *s = avctx->priv_data;
  1973. AC3EncOptions *opt = &s->options;
  1974. char strbuf[32];
  1975. switch (s->bitstream_id) {
  1976. case 6: av_strlcpy(strbuf, "AC-3 (alt syntax)", 32); break;
  1977. case 8: av_strlcpy(strbuf, "AC-3 (standard)", 32); break;
  1978. case 9: av_strlcpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
  1979. case 10: av_strlcpy(strbuf, "AC-3 (dnet quater-rate)", 32); break;
  1980. case 16: av_strlcpy(strbuf, "E-AC-3 (enhanced)", 32); break;
  1981. default: snprintf(strbuf, 32, "ERROR");
  1982. }
  1983. av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
  1984. av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
  1985. av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
  1986. av_dlog(avctx, "channel_layout: %s\n", strbuf);
  1987. av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
  1988. av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
  1989. if (s->cutoff)
  1990. av_dlog(avctx, "cutoff: %d\n", s->cutoff);
  1991. av_dlog(avctx, "per_frame_metadata: %s\n",
  1992. opt->allow_per_frame_metadata?"on":"off");
  1993. if (s->has_center)
  1994. av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
  1995. s->center_mix_level);
  1996. else
  1997. av_dlog(avctx, "center_mixlev: {not written}\n");
  1998. if (s->has_surround)
  1999. av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
  2000. s->surround_mix_level);
  2001. else
  2002. av_dlog(avctx, "surround_mixlev: {not written}\n");
  2003. if (opt->audio_production_info) {
  2004. av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
  2005. switch (opt->room_type) {
  2006. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  2007. case 1: av_strlcpy(strbuf, "large", 32); break;
  2008. case 2: av_strlcpy(strbuf, "small", 32); break;
  2009. default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
  2010. }
  2011. av_dlog(avctx, "room_type: %s\n", strbuf);
  2012. } else {
  2013. av_dlog(avctx, "mixing_level: {not written}\n");
  2014. av_dlog(avctx, "room_type: {not written}\n");
  2015. }
  2016. av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
  2017. av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
  2018. if (s->channel_mode == AC3_CHMODE_STEREO) {
  2019. switch (opt->dolby_surround_mode) {
  2020. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  2021. case 1: av_strlcpy(strbuf, "on", 32); break;
  2022. case 2: av_strlcpy(strbuf, "off", 32); break;
  2023. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
  2024. }
  2025. av_dlog(avctx, "dsur_mode: %s\n", strbuf);
  2026. } else {
  2027. av_dlog(avctx, "dsur_mode: {not written}\n");
  2028. }
  2029. av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
  2030. if (s->bitstream_id == 6) {
  2031. if (opt->extended_bsi_1) {
  2032. switch (opt->preferred_stereo_downmix) {
  2033. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  2034. case 1: av_strlcpy(strbuf, "ltrt", 32); break;
  2035. case 2: av_strlcpy(strbuf, "loro", 32); break;
  2036. default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
  2037. }
  2038. av_dlog(avctx, "dmix_mode: %s\n", strbuf);
  2039. av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
  2040. opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
  2041. av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
  2042. opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
  2043. av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
  2044. opt->loro_center_mix_level, s->loro_center_mix_level);
  2045. av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
  2046. opt->loro_surround_mix_level, s->loro_surround_mix_level);
  2047. } else {
  2048. av_dlog(avctx, "extended bitstream info 1: {not written}\n");
  2049. }
  2050. if (opt->extended_bsi_2) {
  2051. switch (opt->dolby_surround_ex_mode) {
  2052. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  2053. case 1: av_strlcpy(strbuf, "on", 32); break;
  2054. case 2: av_strlcpy(strbuf, "off", 32); break;
  2055. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
  2056. }
  2057. av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
  2058. switch (opt->dolby_headphone_mode) {
  2059. case 0: av_strlcpy(strbuf, "notindicated", 32); break;
  2060. case 1: av_strlcpy(strbuf, "on", 32); break;
  2061. case 2: av_strlcpy(strbuf, "off", 32); break;
  2062. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
  2063. }
  2064. av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
  2065. switch (opt->ad_converter_type) {
  2066. case 0: av_strlcpy(strbuf, "standard", 32); break;
  2067. case 1: av_strlcpy(strbuf, "hdcd", 32); break;
  2068. default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
  2069. }
  2070. av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
  2071. } else {
  2072. av_dlog(avctx, "extended bitstream info 2: {not written}\n");
  2073. }
  2074. }
  2075. #endif
  2076. }
  2077. #define FLT_OPTION_THRESHOLD 0.01
  2078. static int validate_float_option(float v, const float *v_list, int v_list_size)
  2079. {
  2080. int i;
  2081. for (i = 0; i < v_list_size; i++) {
  2082. if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
  2083. v > (v_list[i] - FLT_OPTION_THRESHOLD))
  2084. break;
  2085. }
  2086. if (i == v_list_size)
  2087. return -1;
  2088. return i;
  2089. }
  2090. static void validate_mix_level(void *log_ctx, const char *opt_name,
  2091. float *opt_param, const float *list,
  2092. int list_size, int default_value, int min_value,
  2093. int *ctx_param)
  2094. {
  2095. int mixlev = validate_float_option(*opt_param, list, list_size);
  2096. if (mixlev < min_value) {
  2097. mixlev = default_value;
  2098. if (*opt_param >= 0.0) {
  2099. av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
  2100. "default value: %0.3f\n", opt_name, list[mixlev]);
  2101. }
  2102. }
  2103. *opt_param = list[mixlev];
  2104. *ctx_param = mixlev;
  2105. }
  2106. /**
  2107. * Validate metadata options as set by AVOption system.
  2108. * These values can optionally be changed per-frame.
  2109. */
  2110. static int validate_metadata(AVCodecContext *avctx)
  2111. {
  2112. AC3EncodeContext *s = avctx->priv_data;
  2113. AC3EncOptions *opt = &s->options;
  2114. /* validate mixing levels */
  2115. if (s->has_center) {
  2116. validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
  2117. cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
  2118. &s->center_mix_level);
  2119. }
  2120. if (s->has_surround) {
  2121. validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
  2122. surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
  2123. &s->surround_mix_level);
  2124. }
  2125. /* set audio production info flag */
  2126. if (opt->mixing_level >= 0 || opt->room_type >= 0) {
  2127. if (opt->mixing_level < 0) {
  2128. av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
  2129. "room_type is set\n");
  2130. return AVERROR(EINVAL);
  2131. }
  2132. if (opt->mixing_level < 80) {
  2133. av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
  2134. "80dB and 111dB\n");
  2135. return AVERROR(EINVAL);
  2136. }
  2137. /* default room type */
  2138. if (opt->room_type < 0)
  2139. opt->room_type = 0;
  2140. opt->audio_production_info = 1;
  2141. } else {
  2142. opt->audio_production_info = 0;
  2143. }
  2144. /* set extended bsi 1 flag */
  2145. if ((s->has_center || s->has_surround) &&
  2146. (opt->preferred_stereo_downmix >= 0 ||
  2147. opt->ltrt_center_mix_level >= 0 ||
  2148. opt->ltrt_surround_mix_level >= 0 ||
  2149. opt->loro_center_mix_level >= 0 ||
  2150. opt->loro_surround_mix_level >= 0)) {
  2151. /* default preferred stereo downmix */
  2152. if (opt->preferred_stereo_downmix < 0)
  2153. opt->preferred_stereo_downmix = 0;
  2154. /* validate Lt/Rt center mix level */
  2155. validate_mix_level(avctx, "ltrt_center_mix_level",
  2156. &opt->ltrt_center_mix_level, extmixlev_options,
  2157. EXTMIXLEV_NUM_OPTIONS, 5, 0,
  2158. &s->ltrt_center_mix_level);
  2159. /* validate Lt/Rt surround mix level */
  2160. validate_mix_level(avctx, "ltrt_surround_mix_level",
  2161. &opt->ltrt_surround_mix_level, extmixlev_options,
  2162. EXTMIXLEV_NUM_OPTIONS, 6, 3,
  2163. &s->ltrt_surround_mix_level);
  2164. /* validate Lo/Ro center mix level */
  2165. validate_mix_level(avctx, "loro_center_mix_level",
  2166. &opt->loro_center_mix_level, extmixlev_options,
  2167. EXTMIXLEV_NUM_OPTIONS, 5, 0,
  2168. &s->loro_center_mix_level);
  2169. /* validate Lo/Ro surround mix level */
  2170. validate_mix_level(avctx, "loro_surround_mix_level",
  2171. &opt->loro_surround_mix_level, extmixlev_options,
  2172. EXTMIXLEV_NUM_OPTIONS, 6, 3,
  2173. &s->loro_surround_mix_level);
  2174. opt->extended_bsi_1 = 1;
  2175. } else {
  2176. opt->extended_bsi_1 = 0;
  2177. }
  2178. /* set extended bsi 2 flag */
  2179. if (opt->dolby_surround_ex_mode >= 0 ||
  2180. opt->dolby_headphone_mode >= 0 ||
  2181. opt->ad_converter_type >= 0) {
  2182. /* default dolby surround ex mode */
  2183. if (opt->dolby_surround_ex_mode < 0)
  2184. opt->dolby_surround_ex_mode = 0;
  2185. /* default dolby headphone mode */
  2186. if (opt->dolby_headphone_mode < 0)
  2187. opt->dolby_headphone_mode = 0;
  2188. /* default A/D converter type */
  2189. if (opt->ad_converter_type < 0)
  2190. opt->ad_converter_type = 0;
  2191. opt->extended_bsi_2 = 1;
  2192. } else {
  2193. opt->extended_bsi_2 = 0;
  2194. }
  2195. /* set bitstream id for alternate bitstream syntax */
  2196. if (opt->extended_bsi_1 || opt->extended_bsi_2) {
  2197. if (s->bitstream_id > 8 && s->bitstream_id < 11) {
  2198. static int warn_once = 1;
  2199. if (warn_once) {
  2200. av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
  2201. "not compatible with reduced samplerates. writing of "
  2202. "extended bitstream information will be disabled.\n");
  2203. warn_once = 0;
  2204. }
  2205. } else {
  2206. s->bitstream_id = 6;
  2207. }
  2208. }
  2209. return 0;
  2210. }
  2211. /**
  2212. * Encode a single AC-3 frame.
  2213. */
  2214. static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
  2215. int buf_size, void *data)
  2216. {
  2217. AC3EncodeContext *s = avctx->priv_data;
  2218. const SampleType *samples = data;
  2219. int ret;
  2220. if (!s->eac3 && s->options.allow_per_frame_metadata) {
  2221. ret = validate_metadata(avctx);
  2222. if (ret)
  2223. return ret;
  2224. }
  2225. if (s->bit_alloc.sr_code == 1 || s->eac3)
  2226. adjust_frame_size(s);
  2227. deinterleave_input_samples(s, samples);
  2228. apply_mdct(s);
  2229. scale_coefficients(s);
  2230. s->cpl_on = s->cpl_enabled;
  2231. compute_coupling_strategy(s);
  2232. if (s->cpl_on)
  2233. apply_channel_coupling(s);
  2234. compute_rematrixing_strategy(s);
  2235. apply_rematrixing(s);
  2236. process_exponents(s);
  2237. ret = compute_bit_allocation(s);
  2238. if (ret) {
  2239. av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
  2240. return ret;
  2241. }
  2242. quantize_mantissas(s);
  2243. output_frame(s, frame);
  2244. return s->frame_size;
  2245. }
  2246. /**
  2247. * Finalize encoding and free any memory allocated by the encoder.
  2248. */
  2249. static av_cold int ac3_encode_close(AVCodecContext *avctx)
  2250. {
  2251. int blk, ch;
  2252. AC3EncodeContext *s = avctx->priv_data;
  2253. for (ch = 0; ch < s->channels; ch++)
  2254. av_freep(&s->planar_samples[ch]);
  2255. av_freep(&s->planar_samples);
  2256. av_freep(&s->bap_buffer);
  2257. av_freep(&s->bap1_buffer);
  2258. av_freep(&s->mdct_coef_buffer);
  2259. av_freep(&s->fixed_coef_buffer);
  2260. av_freep(&s->exp_buffer);
  2261. av_freep(&s->grouped_exp_buffer);
  2262. av_freep(&s->psd_buffer);
  2263. av_freep(&s->band_psd_buffer);
  2264. av_freep(&s->mask_buffer);
  2265. av_freep(&s->qmant_buffer);
  2266. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  2267. AC3Block *block = &s->blocks[blk];
  2268. av_freep(&block->bap);
  2269. av_freep(&block->mdct_coef);
  2270. av_freep(&block->fixed_coef);
  2271. av_freep(&block->exp);
  2272. av_freep(&block->grouped_exp);
  2273. av_freep(&block->psd);
  2274. av_freep(&block->band_psd);
  2275. av_freep(&block->mask);
  2276. av_freep(&block->qmant);
  2277. }
  2278. mdct_end(&s->mdct);
  2279. av_freep(&avctx->coded_frame);
  2280. return 0;
  2281. }
  2282. /**
  2283. * Set channel information during initialization.
  2284. */
  2285. static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
  2286. int64_t *channel_layout)
  2287. {
  2288. int ch_layout;
  2289. if (channels < 1 || channels > AC3_MAX_CHANNELS)
  2290. return AVERROR(EINVAL);
  2291. if ((uint64_t)*channel_layout > 0x7FF)
  2292. return AVERROR(EINVAL);
  2293. ch_layout = *channel_layout;
  2294. if (!ch_layout)
  2295. ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
  2296. s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
  2297. s->channels = channels;
  2298. s->fbw_channels = channels - s->lfe_on;
  2299. s->lfe_channel = s->lfe_on ? s->fbw_channels + 1 : -1;
  2300. if (s->lfe_on)
  2301. ch_layout -= AV_CH_LOW_FREQUENCY;
  2302. switch (ch_layout) {
  2303. case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
  2304. case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
  2305. case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
  2306. case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
  2307. case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
  2308. case AV_CH_LAYOUT_QUAD:
  2309. case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
  2310. case AV_CH_LAYOUT_5POINT0:
  2311. case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
  2312. default:
  2313. return AVERROR(EINVAL);
  2314. }
  2315. s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
  2316. s->has_surround = s->channel_mode & 0x04;
  2317. s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
  2318. *channel_layout = ch_layout;
  2319. if (s->lfe_on)
  2320. *channel_layout |= AV_CH_LOW_FREQUENCY;
  2321. return 0;
  2322. }
  2323. static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
  2324. {
  2325. int i, ret, max_sr;
  2326. /* validate channel layout */
  2327. if (!avctx->channel_layout) {
  2328. av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
  2329. "encoder will guess the layout, but it "
  2330. "might be incorrect.\n");
  2331. }
  2332. ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
  2333. if (ret) {
  2334. av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
  2335. return ret;
  2336. }
  2337. /* validate sample rate */
  2338. /* note: max_sr could be changed from 2 to 5 for E-AC-3 once we find a
  2339. decoder that supports half sample rate so we can validate that
  2340. the generated files are correct. */
  2341. max_sr = s->eac3 ? 2 : 8;
  2342. for (i = 0; i <= max_sr; i++) {
  2343. if ((ff_ac3_sample_rate_tab[i % 3] >> (i / 3)) == avctx->sample_rate)
  2344. break;
  2345. }
  2346. if (i > max_sr) {
  2347. av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
  2348. return AVERROR(EINVAL);
  2349. }
  2350. s->sample_rate = avctx->sample_rate;
  2351. s->bit_alloc.sr_shift = i / 3;
  2352. s->bit_alloc.sr_code = i % 3;
  2353. s->bitstream_id = s->eac3 ? 16 : 8 + s->bit_alloc.sr_shift;
  2354. /* validate bit rate */
  2355. if (s->eac3) {
  2356. int max_br, min_br, wpf, min_br_dist, min_br_code;
  2357. /* calculate min/max bitrate */
  2358. max_br = 2048 * s->sample_rate / AC3_FRAME_SIZE * 16;
  2359. min_br = ((s->sample_rate + (AC3_FRAME_SIZE-1)) / AC3_FRAME_SIZE) * 16;
  2360. if (avctx->bit_rate < min_br || avctx->bit_rate > max_br) {
  2361. av_log(avctx, AV_LOG_ERROR, "invalid bit rate. must be %d to %d "
  2362. "for this sample rate\n", min_br, max_br);
  2363. return AVERROR(EINVAL);
  2364. }
  2365. /* calculate words-per-frame for the selected bitrate */
  2366. wpf = (avctx->bit_rate / 16) * AC3_FRAME_SIZE / s->sample_rate;
  2367. av_assert1(wpf > 0 && wpf <= 2048);
  2368. /* find the closest AC-3 bitrate code to the selected bitrate.
  2369. this is needed for lookup tables for bandwidth and coupling
  2370. parameter selection */
  2371. min_br_code = -1;
  2372. min_br_dist = INT_MAX;
  2373. for (i = 0; i < 19; i++) {
  2374. int br_dist = abs(ff_ac3_bitrate_tab[i] * 1000 - avctx->bit_rate);
  2375. if (br_dist < min_br_dist) {
  2376. min_br_dist = br_dist;
  2377. min_br_code = i;
  2378. }
  2379. }
  2380. /* make sure the minimum frame size is below the average frame size */
  2381. s->frame_size_code = min_br_code << 1;
  2382. while (wpf > 1 && wpf * s->sample_rate / AC3_FRAME_SIZE * 16 > avctx->bit_rate)
  2383. wpf--;
  2384. s->frame_size_min = 2 * wpf;
  2385. } else {
  2386. for (i = 0; i < 19; i++) {
  2387. if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
  2388. break;
  2389. }
  2390. if (i == 19) {
  2391. av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
  2392. return AVERROR(EINVAL);
  2393. }
  2394. s->frame_size_code = i << 1;
  2395. s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
  2396. }
  2397. s->bit_rate = avctx->bit_rate;
  2398. s->frame_size = s->frame_size_min;
  2399. /* validate cutoff */
  2400. if (avctx->cutoff < 0) {
  2401. av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
  2402. return AVERROR(EINVAL);
  2403. }
  2404. s->cutoff = avctx->cutoff;
  2405. if (s->cutoff > (s->sample_rate >> 1))
  2406. s->cutoff = s->sample_rate >> 1;
  2407. /* validate audio service type / channels combination */
  2408. if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
  2409. avctx->channels == 1) ||
  2410. ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
  2411. avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
  2412. avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
  2413. && avctx->channels > 1)) {
  2414. av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
  2415. "specified number of channels\n");
  2416. return AVERROR(EINVAL);
  2417. }
  2418. if (!s->eac3) {
  2419. ret = validate_metadata(avctx);
  2420. if (ret)
  2421. return ret;
  2422. }
  2423. s->rematrixing_enabled = s->options.stereo_rematrixing &&
  2424. (s->channel_mode == AC3_CHMODE_STEREO);
  2425. s->cpl_enabled = s->options.channel_coupling &&
  2426. s->channel_mode >= AC3_CHMODE_STEREO &&
  2427. CONFIG_AC3ENC_FLOAT;
  2428. return 0;
  2429. }
  2430. /**
  2431. * Set bandwidth for all channels.
  2432. * The user can optionally supply a cutoff frequency. Otherwise an appropriate
  2433. * default value will be used.
  2434. */
  2435. static av_cold void set_bandwidth(AC3EncodeContext *s)
  2436. {
  2437. int blk, ch;
  2438. int av_uninit(cpl_start);
  2439. if (s->cutoff) {
  2440. /* calculate bandwidth based on user-specified cutoff frequency */
  2441. int fbw_coeffs;
  2442. fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
  2443. s->bandwidth_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
  2444. } else {
  2445. /* use default bandwidth setting */
  2446. s->bandwidth_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
  2447. }
  2448. /* set number of coefficients for each channel */
  2449. for (ch = 1; ch <= s->fbw_channels; ch++) {
  2450. s->start_freq[ch] = 0;
  2451. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  2452. s->blocks[blk].end_freq[ch] = s->bandwidth_code * 3 + 73;
  2453. }
  2454. /* LFE channel always has 7 coefs */
  2455. if (s->lfe_on) {
  2456. s->start_freq[s->lfe_channel] = 0;
  2457. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  2458. s->blocks[blk].end_freq[ch] = 7;
  2459. }
  2460. /* initialize coupling strategy */
  2461. if (s->cpl_enabled) {
  2462. if (s->options.cpl_start >= 0) {
  2463. cpl_start = s->options.cpl_start;
  2464. } else {
  2465. cpl_start = ac3_coupling_start_tab[s->channel_mode-2][s->bit_alloc.sr_code][s->frame_size_code/2];
  2466. if (cpl_start < 0)
  2467. s->cpl_enabled = 0;
  2468. }
  2469. }
  2470. if (s->cpl_enabled) {
  2471. int i, cpl_start_band, cpl_end_band;
  2472. uint8_t *cpl_band_sizes = s->cpl_band_sizes;
  2473. cpl_end_band = s->bandwidth_code / 4 + 3;
  2474. cpl_start_band = av_clip(cpl_start, 0, FFMIN(cpl_end_band-1, 15));
  2475. s->num_cpl_subbands = cpl_end_band - cpl_start_band;
  2476. s->num_cpl_bands = 1;
  2477. *cpl_band_sizes = 12;
  2478. for (i = cpl_start_band + 1; i < cpl_end_band; i++) {
  2479. if (ff_eac3_default_cpl_band_struct[i]) {
  2480. *cpl_band_sizes += 12;
  2481. } else {
  2482. s->num_cpl_bands++;
  2483. cpl_band_sizes++;
  2484. *cpl_band_sizes = 12;
  2485. }
  2486. }
  2487. s->start_freq[CPL_CH] = cpl_start_band * 12 + 37;
  2488. s->cpl_end_freq = cpl_end_band * 12 + 37;
  2489. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  2490. s->blocks[blk].end_freq[CPL_CH] = s->cpl_end_freq;
  2491. }
  2492. }
  2493. static av_cold int allocate_buffers(AVCodecContext *avctx)
  2494. {
  2495. int blk, ch;
  2496. AC3EncodeContext *s = avctx->priv_data;
  2497. int channels = s->channels + 1; /* includes coupling channel */
  2498. FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
  2499. alloc_fail);
  2500. for (ch = 0; ch < s->channels; ch++) {
  2501. FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
  2502. (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
  2503. alloc_fail);
  2504. }
  2505. FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * channels *
  2506. AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
  2507. FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * channels *
  2508. AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
  2509. FF_ALLOCZ_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * channels *
  2510. AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
  2511. FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * channels *
  2512. AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
  2513. FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * channels *
  2514. 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
  2515. FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * channels *
  2516. AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
  2517. FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * channels *
  2518. 64 * sizeof(*s->band_psd_buffer), alloc_fail);
  2519. FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * channels *
  2520. 64 * sizeof(*s->mask_buffer), alloc_fail);
  2521. FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * channels *
  2522. AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
  2523. if (s->cpl_enabled) {
  2524. FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_exp_buffer, AC3_MAX_BLOCKS * channels *
  2525. 16 * sizeof(*s->cpl_coord_exp_buffer), alloc_fail);
  2526. FF_ALLOC_OR_GOTO(avctx, s->cpl_coord_mant_buffer, AC3_MAX_BLOCKS * channels *
  2527. 16 * sizeof(*s->cpl_coord_mant_buffer), alloc_fail);
  2528. }
  2529. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  2530. AC3Block *block = &s->blocks[blk];
  2531. FF_ALLOC_OR_GOTO(avctx, block->bap, channels * sizeof(*block->bap),
  2532. alloc_fail);
  2533. FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, channels * sizeof(*block->mdct_coef),
  2534. alloc_fail);
  2535. FF_ALLOCZ_OR_GOTO(avctx, block->exp, channels * sizeof(*block->exp),
  2536. alloc_fail);
  2537. FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, channels * sizeof(*block->grouped_exp),
  2538. alloc_fail);
  2539. FF_ALLOCZ_OR_GOTO(avctx, block->psd, channels * sizeof(*block->psd),
  2540. alloc_fail);
  2541. FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, channels * sizeof(*block->band_psd),
  2542. alloc_fail);
  2543. FF_ALLOCZ_OR_GOTO(avctx, block->mask, channels * sizeof(*block->mask),
  2544. alloc_fail);
  2545. FF_ALLOCZ_OR_GOTO(avctx, block->qmant, channels * sizeof(*block->qmant),
  2546. alloc_fail);
  2547. if (s->cpl_enabled) {
  2548. FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_exp, channels * sizeof(*block->cpl_coord_exp),
  2549. alloc_fail);
  2550. FF_ALLOCZ_OR_GOTO(avctx, block->cpl_coord_mant, channels * sizeof(*block->cpl_coord_mant),
  2551. alloc_fail);
  2552. }
  2553. for (ch = 0; ch < channels; ch++) {
  2554. /* arrangement: block, channel, coeff */
  2555. block->bap[ch] = &s->bap_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
  2556. block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * channels + ch)];
  2557. block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
  2558. block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * channels + ch)];
  2559. block->mask[ch] = &s->mask_buffer [64 * (blk * channels + ch)];
  2560. block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * channels + ch)];
  2561. if (s->cpl_enabled) {
  2562. block->cpl_coord_exp[ch] = &s->cpl_coord_exp_buffer [16 * (blk * channels + ch)];
  2563. block->cpl_coord_mant[ch] = &s->cpl_coord_mant_buffer[16 * (blk * channels + ch)];
  2564. }
  2565. /* arrangement: channel, block, coeff */
  2566. block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
  2567. block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
  2568. }
  2569. }
  2570. if (CONFIG_AC3ENC_FLOAT) {
  2571. FF_ALLOCZ_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * channels *
  2572. AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
  2573. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  2574. AC3Block *block = &s->blocks[blk];
  2575. FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
  2576. sizeof(*block->fixed_coef), alloc_fail);
  2577. for (ch = 0; ch < channels; ch++)
  2578. block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
  2579. }
  2580. } else {
  2581. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  2582. AC3Block *block = &s->blocks[blk];
  2583. FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, channels *
  2584. sizeof(*block->fixed_coef), alloc_fail);
  2585. for (ch = 0; ch < channels; ch++)
  2586. block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
  2587. }
  2588. }
  2589. return 0;
  2590. alloc_fail:
  2591. return AVERROR(ENOMEM);
  2592. }
  2593. /**
  2594. * Initialize the encoder.
  2595. */
  2596. static av_cold int ac3_encode_init(AVCodecContext *avctx)
  2597. {
  2598. AC3EncodeContext *s = avctx->priv_data;
  2599. int ret, frame_size_58;
  2600. s->eac3 = avctx->codec_id == CODEC_ID_EAC3;
  2601. avctx->frame_size = AC3_FRAME_SIZE;
  2602. ff_ac3_common_init();
  2603. ret = validate_options(avctx, s);
  2604. if (ret)
  2605. return ret;
  2606. s->bitstream_mode = avctx->audio_service_type;
  2607. if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
  2608. s->bitstream_mode = 0x7;
  2609. s->bits_written = 0;
  2610. s->samples_written = 0;
  2611. /* calculate crc_inv for both possible frame sizes */
  2612. frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
  2613. s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  2614. if (s->bit_alloc.sr_code == 1) {
  2615. frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
  2616. s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  2617. }
  2618. set_bandwidth(s);
  2619. exponent_init(s);
  2620. bit_alloc_init(s);
  2621. ret = mdct_init(avctx, &s->mdct, 9);
  2622. if (ret)
  2623. goto init_fail;
  2624. ret = allocate_buffers(avctx);
  2625. if (ret)
  2626. goto init_fail;
  2627. avctx->coded_frame= avcodec_alloc_frame();
  2628. dsputil_init(&s->dsp, avctx);
  2629. ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
  2630. dprint_options(avctx);
  2631. return 0;
  2632. init_fail:
  2633. ac3_encode_close(avctx);
  2634. return ret;
  2635. }