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.

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