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.

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