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.

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