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.

2810 lines
101KB

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