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.

2764 lines
93KB

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