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.

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