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.

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