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.

2504 lines
85KB

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