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.

2095 lines
63KB

  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 DEBUG
  28. #include "libavcore/audioconvert.h"
  29. #include "libavutil/crc.h"
  30. #include "avcodec.h"
  31. #include "put_bits.h"
  32. #include "dsputil.h"
  33. #include "ac3.h"
  34. #include "audioconvert.h"
  35. /** Maximum number of exponent groups. +1 for separate DC exponent. */
  36. #define AC3_MAX_EXP_GROUPS 85
  37. /** Scale a float value by 2^bits and convert to an integer. */
  38. #define SCALE_FLOAT(a, bits) lrintf((a) * (float)(1 << (bits)))
  39. typedef int16_t SampleType;
  40. typedef int32_t CoefType;
  41. #define SCALE_COEF(a) (a)
  42. /** Scale a float value by 2^15, convert to an integer, and clip to range -32767..32767. */
  43. #define FIX15(a) av_clip(SCALE_FLOAT(a, 15), -32767, 32767)
  44. /**
  45. * Compex number.
  46. * Used in fixed-point MDCT calculation.
  47. */
  48. typedef struct IComplex {
  49. int16_t re,im;
  50. } IComplex;
  51. typedef struct AC3MDCTContext {
  52. const int16_t *window; ///< MDCT window function
  53. int nbits; ///< log2(transform size)
  54. int16_t *costab; ///< FFT cos table
  55. int16_t *sintab; ///< FFT sin table
  56. int16_t *xcos1; ///< MDCT cos table
  57. int16_t *xsin1; ///< MDCT sin table
  58. int16_t *rot_tmp; ///< temp buffer for pre-rotated samples
  59. IComplex *cplx_tmp; ///< temp buffer for complex pre-rotated samples
  60. } AC3MDCTContext;
  61. /**
  62. * Data for a single audio block.
  63. */
  64. typedef struct AC3Block {
  65. uint8_t **bap; ///< bit allocation pointers (bap)
  66. CoefType **mdct_coef; ///< MDCT coefficients
  67. uint8_t **exp; ///< original exponents
  68. uint8_t **grouped_exp; ///< grouped exponents
  69. int16_t **psd; ///< psd per frequency bin
  70. int16_t **band_psd; ///< psd per critical band
  71. int16_t **mask; ///< masking curve
  72. uint16_t **qmant; ///< quantized mantissas
  73. uint8_t exp_strategy[AC3_MAX_CHANNELS]; ///< exponent strategies
  74. int8_t exp_shift[AC3_MAX_CHANNELS]; ///< exponent shift values
  75. } AC3Block;
  76. /**
  77. * AC-3 encoder private context.
  78. */
  79. typedef struct AC3EncodeContext {
  80. PutBitContext pb; ///< bitstream writer context
  81. DSPContext dsp;
  82. AC3MDCTContext mdct; ///< MDCT context
  83. AC3Block blocks[AC3_MAX_BLOCKS]; ///< per-block info
  84. int bitstream_id; ///< bitstream id (bsid)
  85. int bitstream_mode; ///< bitstream mode (bsmod)
  86. int bit_rate; ///< target bit rate, in bits-per-second
  87. int sample_rate; ///< sampling frequency, in Hz
  88. int frame_size_min; ///< minimum frame size in case rounding is necessary
  89. int frame_size; ///< current frame size in bytes
  90. int frame_size_code; ///< frame size code (frmsizecod)
  91. uint16_t crc_inv[2];
  92. int bits_written; ///< bit count (used to avg. bitrate)
  93. int samples_written; ///< sample count (used to avg. bitrate)
  94. int fbw_channels; ///< number of full-bandwidth channels (nfchans)
  95. int channels; ///< total number of channels (nchans)
  96. int lfe_on; ///< indicates if there is an LFE channel (lfeon)
  97. int lfe_channel; ///< channel index of the LFE channel
  98. int channel_mode; ///< channel mode (acmod)
  99. const uint8_t *channel_map; ///< channel map used to reorder channels
  100. int cutoff; ///< user-specified cutoff frequency, in Hz
  101. int bandwidth_code[AC3_MAX_CHANNELS]; ///< bandwidth code (0 to 60) (chbwcod)
  102. int nb_coefs[AC3_MAX_CHANNELS];
  103. /* bitrate allocation control */
  104. int slow_gain_code; ///< slow gain code (sgaincod)
  105. int slow_decay_code; ///< slow decay code (sdcycod)
  106. int fast_decay_code; ///< fast decay code (fdcycod)
  107. int db_per_bit_code; ///< dB/bit code (dbpbcod)
  108. int floor_code; ///< floor code (floorcod)
  109. AC3BitAllocParameters bit_alloc; ///< bit allocation parameters
  110. int coarse_snr_offset; ///< coarse SNR offsets (csnroffst)
  111. int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signal-to-mask ratio) (fgaincod)
  112. int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst)
  113. int frame_bits_fixed; ///< number of non-coefficient bits for fixed parameters
  114. int frame_bits; ///< all frame bits except exponents and mantissas
  115. int exponent_bits; ///< number of bits used for exponents
  116. /* mantissa encoding */
  117. int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
  118. uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
  119. SampleType **planar_samples;
  120. uint8_t *bap_buffer;
  121. uint8_t *bap1_buffer;
  122. CoefType *mdct_coef_buffer;
  123. uint8_t *exp_buffer;
  124. uint8_t *grouped_exp_buffer;
  125. int16_t *psd_buffer;
  126. int16_t *band_psd_buffer;
  127. int16_t *mask_buffer;
  128. uint16_t *qmant_buffer;
  129. DECLARE_ALIGNED(16, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
  130. } AC3EncodeContext;
  131. /**
  132. * LUT for number of exponent groups.
  133. * exponent_group_tab[exponent strategy-1][number of coefficients]
  134. */
  135. static uint8_t exponent_group_tab[3][256];
  136. /**
  137. * List of supported channel layouts.
  138. */
  139. static const int64_t ac3_channel_layouts[] = {
  140. AV_CH_LAYOUT_MONO,
  141. AV_CH_LAYOUT_STEREO,
  142. AV_CH_LAYOUT_2_1,
  143. AV_CH_LAYOUT_SURROUND,
  144. AV_CH_LAYOUT_2_2,
  145. AV_CH_LAYOUT_QUAD,
  146. AV_CH_LAYOUT_4POINT0,
  147. AV_CH_LAYOUT_5POINT0,
  148. AV_CH_LAYOUT_5POINT0_BACK,
  149. (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
  150. (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
  151. (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
  152. (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
  153. (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
  154. (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
  155. (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
  156. AV_CH_LAYOUT_5POINT1,
  157. AV_CH_LAYOUT_5POINT1_BACK,
  158. 0
  159. };
  160. /**
  161. * Adjust the frame size to make the average bit rate match the target bit rate.
  162. * This is only needed for 11025, 22050, and 44100 sample rates.
  163. */
  164. static void adjust_frame_size(AC3EncodeContext *s)
  165. {
  166. while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
  167. s->bits_written -= s->bit_rate;
  168. s->samples_written -= s->sample_rate;
  169. }
  170. s->frame_size = s->frame_size_min +
  171. 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
  172. s->bits_written += s->frame_size * 8;
  173. s->samples_written += AC3_FRAME_SIZE;
  174. }
  175. /**
  176. * Deinterleave input samples.
  177. * Channels are reordered from FFmpeg's default order to AC-3 order.
  178. */
  179. static void deinterleave_input_samples(AC3EncodeContext *s,
  180. const SampleType *samples)
  181. {
  182. int ch, i;
  183. /* deinterleave and remap input samples */
  184. for (ch = 0; ch < s->channels; ch++) {
  185. const SampleType *sptr;
  186. int sinc;
  187. /* copy last 256 samples of previous frame to the start of the current frame */
  188. memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
  189. AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
  190. /* deinterleave */
  191. sinc = s->channels;
  192. sptr = samples + s->channel_map[ch];
  193. for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
  194. s->planar_samples[ch][i] = *sptr;
  195. sptr += sinc;
  196. }
  197. }
  198. }
  199. /**
  200. * Finalize MDCT and free allocated memory.
  201. */
  202. static av_cold void mdct_end(AC3MDCTContext *mdct)
  203. {
  204. mdct->nbits = 0;
  205. av_freep(&mdct->costab);
  206. av_freep(&mdct->sintab);
  207. av_freep(&mdct->xcos1);
  208. av_freep(&mdct->xsin1);
  209. av_freep(&mdct->rot_tmp);
  210. av_freep(&mdct->cplx_tmp);
  211. }
  212. /**
  213. * Initialize FFT tables.
  214. * @param ln log2(FFT size)
  215. */
  216. static av_cold int fft_init(AVCodecContext *avctx, AC3MDCTContext *mdct, int ln)
  217. {
  218. int i, n, n2;
  219. float alpha;
  220. n = 1 << ln;
  221. n2 = n >> 1;
  222. FF_ALLOC_OR_GOTO(avctx, mdct->costab, n2 * sizeof(*mdct->costab), fft_alloc_fail);
  223. FF_ALLOC_OR_GOTO(avctx, mdct->sintab, n2 * sizeof(*mdct->sintab), fft_alloc_fail);
  224. for (i = 0; i < n2; i++) {
  225. alpha = 2.0 * M_PI * i / n;
  226. mdct->costab[i] = FIX15(cos(alpha));
  227. mdct->sintab[i] = FIX15(sin(alpha));
  228. }
  229. return 0;
  230. fft_alloc_fail:
  231. mdct_end(mdct);
  232. return AVERROR(ENOMEM);
  233. }
  234. /**
  235. * Initialize MDCT tables.
  236. * @param nbits log2(MDCT size)
  237. */
  238. static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
  239. int nbits)
  240. {
  241. int i, n, n4, ret;
  242. n = 1 << nbits;
  243. n4 = n >> 2;
  244. mdct->nbits = nbits;
  245. ret = fft_init(avctx, mdct, nbits - 2);
  246. if (ret)
  247. return ret;
  248. mdct->window = ff_ac3_window;
  249. FF_ALLOC_OR_GOTO(avctx, mdct->xcos1, n4 * sizeof(*mdct->xcos1), mdct_alloc_fail);
  250. FF_ALLOC_OR_GOTO(avctx, mdct->xsin1, n4 * sizeof(*mdct->xsin1), mdct_alloc_fail);
  251. FF_ALLOC_OR_GOTO(avctx, mdct->rot_tmp, n * sizeof(*mdct->rot_tmp), mdct_alloc_fail);
  252. FF_ALLOC_OR_GOTO(avctx, mdct->cplx_tmp, n4 * sizeof(*mdct->cplx_tmp), mdct_alloc_fail);
  253. for (i = 0; i < n4; i++) {
  254. float alpha = 2.0 * M_PI * (i + 1.0 / 8.0) / n;
  255. mdct->xcos1[i] = FIX15(-cos(alpha));
  256. mdct->xsin1[i] = FIX15(-sin(alpha));
  257. }
  258. return 0;
  259. mdct_alloc_fail:
  260. mdct_end(mdct);
  261. return AVERROR(ENOMEM);
  262. }
  263. /** Butterfly op */
  264. #define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1) \
  265. { \
  266. int ax, ay, bx, by; \
  267. bx = pre1; \
  268. by = pim1; \
  269. ax = qre1; \
  270. ay = qim1; \
  271. pre = (bx + ax) >> 1; \
  272. pim = (by + ay) >> 1; \
  273. qre = (bx - ax) >> 1; \
  274. qim = (by - ay) >> 1; \
  275. }
  276. /** Complex multiply */
  277. #define CMUL(pre, pim, are, aim, bre, bim) \
  278. { \
  279. pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15; \
  280. pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15; \
  281. }
  282. /**
  283. * Calculate a 2^n point complex FFT on 2^ln points.
  284. * @param z complex input/output samples
  285. * @param ln log2(FFT size)
  286. */
  287. static void fft(AC3MDCTContext *mdct, IComplex *z, int ln)
  288. {
  289. int j, l, np, np2;
  290. int nblocks, nloops;
  291. register IComplex *p,*q;
  292. int tmp_re, tmp_im;
  293. np = 1 << ln;
  294. /* reverse */
  295. for (j = 0; j < np; j++) {
  296. int k = av_reverse[j] >> (8 - ln);
  297. if (k < j)
  298. FFSWAP(IComplex, z[k], z[j]);
  299. }
  300. /* pass 0 */
  301. p = &z[0];
  302. j = np >> 1;
  303. do {
  304. BF(p[0].re, p[0].im, p[1].re, p[1].im,
  305. p[0].re, p[0].im, p[1].re, p[1].im);
  306. p += 2;
  307. } while (--j);
  308. /* pass 1 */
  309. p = &z[0];
  310. j = np >> 2;
  311. do {
  312. BF(p[0].re, p[0].im, p[2].re, p[2].im,
  313. p[0].re, p[0].im, p[2].re, p[2].im);
  314. BF(p[1].re, p[1].im, p[3].re, p[3].im,
  315. p[1].re, p[1].im, p[3].im, -p[3].re);
  316. p+=4;
  317. } while (--j);
  318. /* pass 2 .. ln-1 */
  319. nblocks = np >> 3;
  320. nloops = 1 << 2;
  321. np2 = np >> 1;
  322. do {
  323. p = z;
  324. q = z + nloops;
  325. for (j = 0; j < nblocks; j++) {
  326. BF(p->re, p->im, q->re, q->im,
  327. p->re, p->im, q->re, q->im);
  328. p++;
  329. q++;
  330. for(l = nblocks; l < np2; l += nblocks) {
  331. CMUL(tmp_re, tmp_im, mdct->costab[l], -mdct->sintab[l], q->re, q->im);
  332. BF(p->re, p->im, q->re, q->im,
  333. p->re, p->im, tmp_re, tmp_im);
  334. p++;
  335. q++;
  336. }
  337. p += nloops;
  338. q += nloops;
  339. }
  340. nblocks = nblocks >> 1;
  341. nloops = nloops << 1;
  342. } while (nblocks);
  343. }
  344. /**
  345. * Calculate a 512-point MDCT
  346. * @param out 256 output frequency coefficients
  347. * @param in 512 windowed input audio samples
  348. */
  349. static void mdct512(AC3MDCTContext *mdct, int32_t *out, int16_t *in)
  350. {
  351. int i, re, im, n, n2, n4;
  352. int16_t *rot = mdct->rot_tmp;
  353. IComplex *x = mdct->cplx_tmp;
  354. n = 1 << mdct->nbits;
  355. n2 = n >> 1;
  356. n4 = n >> 2;
  357. /* shift to simplify computations */
  358. for (i = 0; i <n4; i++)
  359. rot[i] = -in[i + 3*n4];
  360. memcpy(&rot[n4], &in[0], 3*n4*sizeof(*in));
  361. /* pre rotation */
  362. for (i = 0; i < n4; i++) {
  363. re = ((int)rot[ 2*i] - (int)rot[ n-1-2*i]) >> 1;
  364. im = -((int)rot[n2+2*i] - (int)rot[n2-1-2*i]) >> 1;
  365. CMUL(x[i].re, x[i].im, re, im, -mdct->xcos1[i], mdct->xsin1[i]);
  366. }
  367. fft(mdct, x, mdct->nbits - 2);
  368. /* post rotation */
  369. for (i = 0; i < n4; i++) {
  370. re = x[i].re;
  371. im = x[i].im;
  372. CMUL(out[n2-1-2*i], out[2*i], re, im, mdct->xsin1[i], mdct->xcos1[i]);
  373. }
  374. }
  375. /**
  376. * Apply KBD window to input samples prior to MDCT.
  377. */
  378. static void apply_window(int16_t *output, const int16_t *input,
  379. const int16_t *window, int n)
  380. {
  381. int i;
  382. int n2 = n >> 1;
  383. for (i = 0; i < n2; i++) {
  384. output[i] = MUL16(input[i], window[i]) >> 15;
  385. output[n-i-1] = MUL16(input[n-i-1], window[i]) >> 15;
  386. }
  387. }
  388. /**
  389. * Calculate the log2() of the maximum absolute value in an array.
  390. * @param tab input array
  391. * @param n number of values in the array
  392. * @return log2(max(abs(tab[])))
  393. */
  394. static int log2_tab(int16_t *tab, int n)
  395. {
  396. int i, v;
  397. v = 0;
  398. for (i = 0; i < n; i++)
  399. v |= abs(tab[i]);
  400. return av_log2(v);
  401. }
  402. /**
  403. * Left-shift each value in an array by a specified amount.
  404. * @param tab input array
  405. * @param n number of values in the array
  406. * @param lshift left shift amount. a negative value means right shift.
  407. */
  408. static void lshift_tab(int16_t *tab, int n, int lshift)
  409. {
  410. int i;
  411. if (lshift > 0) {
  412. for (i = 0; i < n; i++)
  413. tab[i] <<= lshift;
  414. } else if (lshift < 0) {
  415. lshift = -lshift;
  416. for (i = 0; i < n; i++)
  417. tab[i] >>= lshift;
  418. }
  419. }
  420. /**
  421. * Normalize the input samples to use the maximum available precision.
  422. * This assumes signed 16-bit input samples. Exponents are reduced by 9 to
  423. * match the 24-bit internal precision for MDCT coefficients.
  424. *
  425. * @return exponent shift
  426. */
  427. static int normalize_samples(AC3EncodeContext *s)
  428. {
  429. int v = 14 - log2_tab(s->windowed_samples, AC3_WINDOW_SIZE);
  430. v = FFMAX(0, v);
  431. lshift_tab(s->windowed_samples, AC3_WINDOW_SIZE, v);
  432. return v - 9;
  433. }
  434. /**
  435. * Apply the MDCT to input samples to generate frequency coefficients.
  436. * This applies the KBD window and normalizes the input to reduce precision
  437. * loss due to fixed-point calculations.
  438. */
  439. static void apply_mdct(AC3EncodeContext *s)
  440. {
  441. int blk, ch;
  442. for (ch = 0; ch < s->channels; ch++) {
  443. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  444. AC3Block *block = &s->blocks[blk];
  445. const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
  446. apply_window(s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
  447. block->exp_shift[ch] = normalize_samples(s);
  448. mdct512(&s->mdct, block->mdct_coef[ch], s->windowed_samples);
  449. }
  450. }
  451. }
  452. /**
  453. * Initialize exponent tables.
  454. */
  455. static av_cold void exponent_init(AC3EncodeContext *s)
  456. {
  457. int i;
  458. for (i = 73; i < 256; i++) {
  459. exponent_group_tab[0][i] = (i - 1) / 3;
  460. exponent_group_tab[1][i] = (i + 2) / 6;
  461. exponent_group_tab[2][i] = (i + 8) / 12;
  462. }
  463. /* LFE */
  464. exponent_group_tab[0][7] = 2;
  465. }
  466. /**
  467. * Extract exponents from the MDCT coefficients.
  468. * This takes into account the normalization that was done to the input samples
  469. * by adjusting the exponents by the exponent shift values.
  470. */
  471. static void extract_exponents(AC3EncodeContext *s)
  472. {
  473. int blk, ch, i;
  474. for (ch = 0; ch < s->channels; ch++) {
  475. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  476. AC3Block *block = &s->blocks[blk];
  477. for (i = 0; i < AC3_MAX_COEFS; i++) {
  478. int e;
  479. int v = abs(SCALE_COEF(block->mdct_coef[ch][i]));
  480. if (v == 0)
  481. e = 24;
  482. else {
  483. e = 23 - av_log2(v) + block->exp_shift[ch];
  484. if (e >= 24) {
  485. e = 24;
  486. block->mdct_coef[ch][i] = 0;
  487. }
  488. }
  489. block->exp[ch][i] = e;
  490. }
  491. }
  492. }
  493. }
  494. /**
  495. * Exponent Difference Threshold.
  496. * New exponents are sent if their SAD exceed this number.
  497. */
  498. #define EXP_DIFF_THRESHOLD 1000
  499. /**
  500. * Calculate exponent strategies for all blocks in a single channel.
  501. */
  502. static void compute_exp_strategy_ch(AC3EncodeContext *s, uint8_t *exp_strategy,
  503. uint8_t **exp)
  504. {
  505. int blk, blk1;
  506. int exp_diff;
  507. /* estimate if the exponent variation & decide if they should be
  508. reused in the next frame */
  509. exp_strategy[0] = EXP_NEW;
  510. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
  511. exp_diff = s->dsp.sad[0](NULL, exp[blk], exp[blk-1], 16, 16);
  512. if (exp_diff > EXP_DIFF_THRESHOLD)
  513. exp_strategy[blk] = EXP_NEW;
  514. else
  515. exp_strategy[blk] = EXP_REUSE;
  516. }
  517. emms_c();
  518. /* now select the encoding strategy type : if exponents are often
  519. recoded, we use a coarse encoding */
  520. blk = 0;
  521. while (blk < AC3_MAX_BLOCKS) {
  522. blk1 = blk + 1;
  523. while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
  524. blk1++;
  525. switch (blk1 - blk) {
  526. case 1: exp_strategy[blk] = EXP_D45; break;
  527. case 2:
  528. case 3: exp_strategy[blk] = EXP_D25; break;
  529. default: exp_strategy[blk] = EXP_D15; break;
  530. }
  531. blk = blk1;
  532. }
  533. }
  534. /**
  535. * Calculate exponent strategies for all channels.
  536. * Array arrangement is reversed to simplify the per-channel calculation.
  537. */
  538. static void compute_exp_strategy(AC3EncodeContext *s)
  539. {
  540. uint8_t *exp1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
  541. uint8_t exp_str1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
  542. int ch, blk;
  543. for (ch = 0; ch < s->fbw_channels; ch++) {
  544. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  545. exp1[ch][blk] = s->blocks[blk].exp[ch];
  546. exp_str1[ch][blk] = s->blocks[blk].exp_strategy[ch];
  547. }
  548. compute_exp_strategy_ch(s, exp_str1[ch], exp1[ch]);
  549. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  550. s->blocks[blk].exp_strategy[ch] = exp_str1[ch][blk];
  551. }
  552. if (s->lfe_on) {
  553. ch = s->lfe_channel;
  554. s->blocks[0].exp_strategy[ch] = EXP_D15;
  555. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
  556. s->blocks[blk].exp_strategy[ch] = EXP_REUSE;
  557. }
  558. }
  559. /**
  560. * Set each encoded exponent in a block to the minimum of itself and the
  561. * exponent in the same frequency bin of a following block.
  562. * exp[i] = min(exp[i], exp1[i]
  563. */
  564. static void exponent_min(uint8_t *exp, uint8_t *exp1, int n)
  565. {
  566. int i;
  567. for (i = 0; i < n; i++) {
  568. if (exp1[i] < exp[i])
  569. exp[i] = exp1[i];
  570. }
  571. }
  572. /**
  573. * Update the exponents so that they are the ones the decoder will decode.
  574. */
  575. static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy)
  576. {
  577. int nb_groups, i, k;
  578. nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
  579. /* for each group, compute the minimum exponent */
  580. switch(exp_strategy) {
  581. case EXP_D25:
  582. for (i = 1, k = 1; i <= nb_groups; i++) {
  583. uint8_t exp_min = exp[k];
  584. if (exp[k+1] < exp_min)
  585. exp_min = exp[k+1];
  586. exp[i] = exp_min;
  587. k += 2;
  588. }
  589. break;
  590. case EXP_D45:
  591. for (i = 1, k = 1; i <= nb_groups; i++) {
  592. uint8_t exp_min = exp[k];
  593. if (exp[k+1] < exp_min)
  594. exp_min = exp[k+1];
  595. if (exp[k+2] < exp_min)
  596. exp_min = exp[k+2];
  597. if (exp[k+3] < exp_min)
  598. exp_min = exp[k+3];
  599. exp[i] = exp_min;
  600. k += 4;
  601. }
  602. break;
  603. }
  604. /* constraint for DC exponent */
  605. if (exp[0] > 15)
  606. exp[0] = 15;
  607. /* decrease the delta between each groups to within 2 so that they can be
  608. differentially encoded */
  609. for (i = 1; i <= nb_groups; i++)
  610. exp[i] = FFMIN(exp[i], exp[i-1] + 2);
  611. i--;
  612. while (--i >= 0)
  613. exp[i] = FFMIN(exp[i], exp[i+1] + 2);
  614. /* now we have the exponent values the decoder will see */
  615. switch (exp_strategy) {
  616. case EXP_D25:
  617. for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
  618. uint8_t exp1 = exp[i];
  619. exp[k--] = exp1;
  620. exp[k--] = exp1;
  621. }
  622. break;
  623. case EXP_D45:
  624. for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
  625. exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
  626. k -= 4;
  627. }
  628. break;
  629. }
  630. }
  631. /**
  632. * Encode exponents from original extracted form to what the decoder will see.
  633. * This copies and groups exponents based on exponent strategy and reduces
  634. * deltas between adjacent exponent groups so that they can be differentially
  635. * encoded.
  636. */
  637. static void encode_exponents(AC3EncodeContext *s)
  638. {
  639. int blk, blk1, blk2, ch;
  640. AC3Block *block, *block1, *block2;
  641. for (ch = 0; ch < s->channels; ch++) {
  642. blk = 0;
  643. block = &s->blocks[0];
  644. while (blk < AC3_MAX_BLOCKS) {
  645. blk1 = blk + 1;
  646. block1 = block + 1;
  647. /* for the EXP_REUSE case we select the min of the exponents */
  648. while (blk1 < AC3_MAX_BLOCKS && block1->exp_strategy[ch] == EXP_REUSE) {
  649. exponent_min(block->exp[ch], block1->exp[ch], s->nb_coefs[ch]);
  650. blk1++;
  651. block1++;
  652. }
  653. encode_exponents_blk_ch(block->exp[ch], s->nb_coefs[ch],
  654. block->exp_strategy[ch]);
  655. /* copy encoded exponents for reuse case */
  656. block2 = block + 1;
  657. for (blk2 = blk+1; blk2 < blk1; blk2++, block2++) {
  658. memcpy(block2->exp[ch], block->exp[ch],
  659. s->nb_coefs[ch] * sizeof(uint8_t));
  660. }
  661. blk = blk1;
  662. block = block1;
  663. }
  664. }
  665. }
  666. /**
  667. * Group exponents.
  668. * 3 delta-encoded exponents are in each 7-bit group. The number of groups
  669. * varies depending on exponent strategy and bandwidth.
  670. */
  671. static void group_exponents(AC3EncodeContext *s)
  672. {
  673. int blk, ch, i;
  674. int group_size, nb_groups, bit_count;
  675. uint8_t *p;
  676. int delta0, delta1, delta2;
  677. int exp0, exp1;
  678. bit_count = 0;
  679. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  680. AC3Block *block = &s->blocks[blk];
  681. for (ch = 0; ch < s->channels; ch++) {
  682. if (block->exp_strategy[ch] == EXP_REUSE) {
  683. continue;
  684. }
  685. group_size = block->exp_strategy[ch] + (block->exp_strategy[ch] == EXP_D45);
  686. nb_groups = exponent_group_tab[block->exp_strategy[ch]-1][s->nb_coefs[ch]];
  687. bit_count += 4 + (nb_groups * 7);
  688. p = block->exp[ch];
  689. /* DC exponent */
  690. exp1 = *p++;
  691. block->grouped_exp[ch][0] = exp1;
  692. /* remaining exponents are delta encoded */
  693. for (i = 1; i <= nb_groups; i++) {
  694. /* merge three delta in one code */
  695. exp0 = exp1;
  696. exp1 = p[0];
  697. p += group_size;
  698. delta0 = exp1 - exp0 + 2;
  699. exp0 = exp1;
  700. exp1 = p[0];
  701. p += group_size;
  702. delta1 = exp1 - exp0 + 2;
  703. exp0 = exp1;
  704. exp1 = p[0];
  705. p += group_size;
  706. delta2 = exp1 - exp0 + 2;
  707. block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
  708. }
  709. }
  710. }
  711. s->exponent_bits = bit_count;
  712. }
  713. /**
  714. * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
  715. * Extract exponents from MDCT coefficients, calculate exponent strategies,
  716. * and encode final exponents.
  717. */
  718. static void process_exponents(AC3EncodeContext *s)
  719. {
  720. extract_exponents(s);
  721. compute_exp_strategy(s);
  722. encode_exponents(s);
  723. group_exponents(s);
  724. }
  725. /**
  726. * Count frame bits that are based solely on fixed parameters.
  727. * This only has to be run once when the encoder is initialized.
  728. */
  729. static void count_frame_bits_fixed(AC3EncodeContext *s)
  730. {
  731. static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
  732. int blk;
  733. int frame_bits;
  734. /* assumptions:
  735. * no dynamic range codes
  736. * no channel coupling
  737. * no rematrixing
  738. * bit allocation parameters do not change between blocks
  739. * SNR offsets do not change between blocks
  740. * no delta bit allocation
  741. * no skipped data
  742. * no auxilliary data
  743. */
  744. /* header size */
  745. frame_bits = 65;
  746. frame_bits += frame_bits_inc[s->channel_mode];
  747. /* audio blocks */
  748. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  749. frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
  750. if (s->channel_mode == AC3_CHMODE_STEREO) {
  751. frame_bits++; /* rematstr */
  752. if (!blk)
  753. frame_bits += 4;
  754. }
  755. frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
  756. if (s->lfe_on)
  757. frame_bits++; /* lfeexpstr */
  758. frame_bits++; /* baie */
  759. frame_bits++; /* snr */
  760. frame_bits += 2; /* delta / skip */
  761. }
  762. frame_bits++; /* cplinu for block 0 */
  763. /* bit alloc info */
  764. /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
  765. /* csnroffset[6] */
  766. /* (fsnoffset[4] + fgaincod[4]) * c */
  767. frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
  768. /* auxdatae, crcrsv */
  769. frame_bits += 2;
  770. /* CRC */
  771. frame_bits += 16;
  772. s->frame_bits_fixed = frame_bits;
  773. }
  774. /**
  775. * Initialize bit allocation.
  776. * Set default parameter codes and calculate parameter values.
  777. */
  778. static void bit_alloc_init(AC3EncodeContext *s)
  779. {
  780. int ch;
  781. /* init default parameters */
  782. s->slow_decay_code = 2;
  783. s->fast_decay_code = 1;
  784. s->slow_gain_code = 1;
  785. s->db_per_bit_code = 3;
  786. s->floor_code = 4;
  787. for (ch = 0; ch < s->channels; ch++)
  788. s->fast_gain_code[ch] = 4;
  789. /* initial snr offset */
  790. s->coarse_snr_offset = 40;
  791. /* compute real values */
  792. /* currently none of these values change during encoding, so we can just
  793. set them once at initialization */
  794. s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
  795. s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
  796. s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
  797. s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
  798. s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
  799. count_frame_bits_fixed(s);
  800. }
  801. /**
  802. * Count the bits used to encode the frame, minus exponents and mantissas.
  803. * Bits based on fixed parameters have already been counted, so now we just
  804. * have to add the bits based on parameters that change during encoding.
  805. */
  806. static void count_frame_bits(AC3EncodeContext *s)
  807. {
  808. int blk, ch;
  809. int frame_bits = 0;
  810. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  811. uint8_t *exp_strategy = s->blocks[blk].exp_strategy;
  812. for (ch = 0; ch < s->fbw_channels; ch++) {
  813. if (exp_strategy[ch] != EXP_REUSE)
  814. frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
  815. }
  816. }
  817. s->frame_bits = s->frame_bits_fixed + frame_bits;
  818. }
  819. /**
  820. * Calculate the number of bits needed to encode a set of mantissas.
  821. */
  822. static int compute_mantissa_size(int mant_cnt[5], uint8_t *bap, int nb_coefs)
  823. {
  824. int bits, b, i;
  825. bits = 0;
  826. for (i = 0; i < nb_coefs; i++) {
  827. b = bap[i];
  828. if (b <= 4) {
  829. // bap=1 to bap=4 will be counted in compute_mantissa_size_final
  830. mant_cnt[b]++;
  831. } else if (b <= 13) {
  832. // bap=5 to bap=13 use (bap-1) bits
  833. bits += b - 1;
  834. } else {
  835. // bap=14 uses 14 bits and bap=15 uses 16 bits
  836. bits += (b == 14) ? 14 : 16;
  837. }
  838. }
  839. return bits;
  840. }
  841. /**
  842. * Finalize the mantissa bit count by adding in the grouped mantissas.
  843. */
  844. static int compute_mantissa_size_final(int mant_cnt[5])
  845. {
  846. // bap=1 : 3 mantissas in 5 bits
  847. int bits = (mant_cnt[1] / 3) * 5;
  848. // bap=2 : 3 mantissas in 7 bits
  849. // bap=4 : 2 mantissas in 7 bits
  850. bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
  851. // bap=3 : each mantissa is 3 bits
  852. bits += mant_cnt[3] * 3;
  853. return bits;
  854. }
  855. /**
  856. * Calculate masking curve based on the final exponents.
  857. * Also calculate the power spectral densities to use in future calculations.
  858. */
  859. static void bit_alloc_masking(AC3EncodeContext *s)
  860. {
  861. int blk, ch;
  862. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  863. AC3Block *block = &s->blocks[blk];
  864. for (ch = 0; ch < s->channels; ch++) {
  865. /* We only need psd and mask for calculating bap.
  866. Since we currently do not calculate bap when exponent
  867. strategy is EXP_REUSE we do not need to calculate psd or mask. */
  868. if (block->exp_strategy[ch] != EXP_REUSE) {
  869. ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
  870. s->nb_coefs[ch],
  871. block->psd[ch], block->band_psd[ch]);
  872. ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
  873. 0, s->nb_coefs[ch],
  874. ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
  875. ch == s->lfe_channel,
  876. DBA_NONE, 0, NULL, NULL, NULL,
  877. block->mask[ch]);
  878. }
  879. }
  880. }
  881. }
  882. /**
  883. * Ensure that bap for each block and channel point to the current bap_buffer.
  884. * They may have been switched during the bit allocation search.
  885. */
  886. static void reset_block_bap(AC3EncodeContext *s)
  887. {
  888. int blk, ch;
  889. if (s->blocks[0].bap[0] == s->bap_buffer)
  890. return;
  891. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  892. for (ch = 0; ch < s->channels; ch++) {
  893. s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
  894. }
  895. }
  896. }
  897. /**
  898. * Run the bit allocation with a given SNR offset.
  899. * This calculates the bit allocation pointers that will be used to determine
  900. * the quantization of each mantissa.
  901. * @return the number of bits needed for mantissas if the given SNR offset is
  902. * is used.
  903. */
  904. static int bit_alloc(AC3EncodeContext *s, int snr_offset)
  905. {
  906. int blk, ch;
  907. int mantissa_bits;
  908. int mant_cnt[5];
  909. snr_offset = (snr_offset - 240) << 2;
  910. reset_block_bap(s);
  911. mantissa_bits = 0;
  912. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  913. AC3Block *block = &s->blocks[blk];
  914. // initialize grouped mantissa counts. these are set so that they are
  915. // padded to the next whole group size when bits are counted in
  916. // compute_mantissa_size_final
  917. mant_cnt[0] = mant_cnt[3] = 0;
  918. mant_cnt[1] = mant_cnt[2] = 2;
  919. mant_cnt[4] = 1;
  920. for (ch = 0; ch < s->channels; ch++) {
  921. /* Currently the only bit allocation parameters which vary across
  922. blocks within a frame are the exponent values. We can take
  923. advantage of that by reusing the bit allocation pointers
  924. whenever we reuse exponents. */
  925. if (block->exp_strategy[ch] == EXP_REUSE) {
  926. memcpy(block->bap[ch], s->blocks[blk-1].bap[ch], AC3_MAX_COEFS);
  927. } else {
  928. ff_ac3_bit_alloc_calc_bap(block->mask[ch], block->psd[ch], 0,
  929. s->nb_coefs[ch], snr_offset,
  930. s->bit_alloc.floor, ff_ac3_bap_tab,
  931. block->bap[ch]);
  932. }
  933. mantissa_bits += compute_mantissa_size(mant_cnt, block->bap[ch], s->nb_coefs[ch]);
  934. }
  935. mantissa_bits += compute_mantissa_size_final(mant_cnt);
  936. }
  937. return mantissa_bits;
  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. snr_offset = s->coarse_snr_offset << 4;
  950. /* if previous frame SNR offset was 1023, check if current frame can also
  951. use SNR offset of 1023. if so, skip the search. */
  952. if ((snr_offset | s->fine_snr_offset[0]) == 1023) {
  953. if (bit_alloc(s, 1023) <= bits_left)
  954. return 0;
  955. }
  956. while (snr_offset >= 0 &&
  957. bit_alloc(s, snr_offset) > bits_left) {
  958. snr_offset -= 64;
  959. }
  960. if (snr_offset < 0)
  961. return AVERROR(EINVAL);
  962. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  963. for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
  964. while (snr_offset + snr_incr <= 1023 &&
  965. bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
  966. snr_offset += snr_incr;
  967. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  968. }
  969. }
  970. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  971. reset_block_bap(s);
  972. s->coarse_snr_offset = snr_offset >> 4;
  973. for (ch = 0; ch < s->channels; ch++)
  974. s->fine_snr_offset[ch] = snr_offset & 0xF;
  975. return 0;
  976. }
  977. /**
  978. * Downgrade exponent strategies to reduce the bits used by the exponents.
  979. * This is a fallback for when bit allocation fails with the normal exponent
  980. * strategies. Each time this function is run it only downgrades the
  981. * strategy in 1 channel of 1 block.
  982. * @return non-zero if downgrade was unsuccessful
  983. */
  984. static int downgrade_exponents(AC3EncodeContext *s)
  985. {
  986. int ch, blk;
  987. for (ch = 0; ch < s->fbw_channels; ch++) {
  988. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  989. if (s->blocks[blk].exp_strategy[ch] == EXP_D15) {
  990. s->blocks[blk].exp_strategy[ch] = EXP_D25;
  991. return 0;
  992. }
  993. }
  994. }
  995. for (ch = 0; ch < s->fbw_channels; ch++) {
  996. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  997. if (s->blocks[blk].exp_strategy[ch] == EXP_D25) {
  998. s->blocks[blk].exp_strategy[ch] = EXP_D45;
  999. return 0;
  1000. }
  1001. }
  1002. }
  1003. for (ch = 0; ch < s->fbw_channels; ch++) {
  1004. /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
  1005. the block number > 0 */
  1006. for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
  1007. if (s->blocks[blk].exp_strategy[ch] > EXP_REUSE) {
  1008. s->blocks[blk].exp_strategy[ch] = EXP_REUSE;
  1009. return 0;
  1010. }
  1011. }
  1012. }
  1013. return -1;
  1014. }
  1015. /**
  1016. * Reduce the bandwidth to reduce the number of bits used for a given SNR offset.
  1017. * This is a second fallback for when bit allocation still fails after exponents
  1018. * have been downgraded.
  1019. * @return non-zero if bandwidth reduction was unsuccessful
  1020. */
  1021. static int reduce_bandwidth(AC3EncodeContext *s, int min_bw_code)
  1022. {
  1023. int ch;
  1024. if (s->bandwidth_code[0] > min_bw_code) {
  1025. for (ch = 0; ch < s->fbw_channels; ch++) {
  1026. s->bandwidth_code[ch]--;
  1027. s->nb_coefs[ch] = s->bandwidth_code[ch] * 3 + 73;
  1028. }
  1029. return 0;
  1030. }
  1031. return -1;
  1032. }
  1033. /**
  1034. * Perform bit allocation search.
  1035. * Finds the SNR offset value that maximizes quality and fits in the specified
  1036. * frame size. Output is the SNR offset and a set of bit allocation pointers
  1037. * used to quantize the mantissas.
  1038. */
  1039. static int compute_bit_allocation(AC3EncodeContext *s)
  1040. {
  1041. int ret;
  1042. count_frame_bits(s);
  1043. bit_alloc_masking(s);
  1044. ret = cbr_bit_allocation(s);
  1045. while (ret) {
  1046. /* fallback 1: downgrade exponents */
  1047. if (!downgrade_exponents(s)) {
  1048. extract_exponents(s);
  1049. encode_exponents(s);
  1050. group_exponents(s);
  1051. ret = compute_bit_allocation(s);
  1052. continue;
  1053. }
  1054. /* fallback 2: reduce bandwidth */
  1055. /* only do this if the user has not specified a specific cutoff
  1056. frequency */
  1057. if (!s->cutoff && !reduce_bandwidth(s, 0)) {
  1058. process_exponents(s);
  1059. ret = compute_bit_allocation(s);
  1060. continue;
  1061. }
  1062. /* fallbacks were not enough... */
  1063. break;
  1064. }
  1065. return ret;
  1066. }
  1067. /**
  1068. * Symmetric quantization on 'levels' levels.
  1069. */
  1070. static inline int sym_quant(int c, int e, int levels)
  1071. {
  1072. int v;
  1073. if (c >= 0) {
  1074. v = (levels * (c << e)) >> 24;
  1075. v = (v + 1) >> 1;
  1076. v = (levels >> 1) + v;
  1077. } else {
  1078. v = (levels * ((-c) << e)) >> 24;
  1079. v = (v + 1) >> 1;
  1080. v = (levels >> 1) - v;
  1081. }
  1082. assert(v >= 0 && v < levels);
  1083. return v;
  1084. }
  1085. /**
  1086. * Asymmetric quantization on 2^qbits levels.
  1087. */
  1088. static inline int asym_quant(int c, int e, int qbits)
  1089. {
  1090. int lshift, m, v;
  1091. lshift = e + qbits - 24;
  1092. if (lshift >= 0)
  1093. v = c << lshift;
  1094. else
  1095. v = c >> (-lshift);
  1096. /* rounding */
  1097. v = (v + 1) >> 1;
  1098. m = (1 << (qbits-1));
  1099. if (v >= m)
  1100. v = m - 1;
  1101. assert(v >= -m);
  1102. return v & ((1 << qbits)-1);
  1103. }
  1104. /**
  1105. * Quantize a set of mantissas for a single channel in a single block.
  1106. */
  1107. static void quantize_mantissas_blk_ch(AC3EncodeContext *s, CoefType *mdct_coef,
  1108. int8_t exp_shift, uint8_t *exp,
  1109. uint8_t *bap, uint16_t *qmant, int n)
  1110. {
  1111. int i;
  1112. for (i = 0; i < n; i++) {
  1113. int v;
  1114. int c = SCALE_COEF(mdct_coef[i]);
  1115. int e = exp[i] - exp_shift;
  1116. int b = bap[i];
  1117. switch (b) {
  1118. case 0:
  1119. v = 0;
  1120. break;
  1121. case 1:
  1122. v = sym_quant(c, e, 3);
  1123. switch (s->mant1_cnt) {
  1124. case 0:
  1125. s->qmant1_ptr = &qmant[i];
  1126. v = 9 * v;
  1127. s->mant1_cnt = 1;
  1128. break;
  1129. case 1:
  1130. *s->qmant1_ptr += 3 * v;
  1131. s->mant1_cnt = 2;
  1132. v = 128;
  1133. break;
  1134. default:
  1135. *s->qmant1_ptr += v;
  1136. s->mant1_cnt = 0;
  1137. v = 128;
  1138. break;
  1139. }
  1140. break;
  1141. case 2:
  1142. v = sym_quant(c, e, 5);
  1143. switch (s->mant2_cnt) {
  1144. case 0:
  1145. s->qmant2_ptr = &qmant[i];
  1146. v = 25 * v;
  1147. s->mant2_cnt = 1;
  1148. break;
  1149. case 1:
  1150. *s->qmant2_ptr += 5 * v;
  1151. s->mant2_cnt = 2;
  1152. v = 128;
  1153. break;
  1154. default:
  1155. *s->qmant2_ptr += v;
  1156. s->mant2_cnt = 0;
  1157. v = 128;
  1158. break;
  1159. }
  1160. break;
  1161. case 3:
  1162. v = sym_quant(c, e, 7);
  1163. break;
  1164. case 4:
  1165. v = sym_quant(c, e, 11);
  1166. switch (s->mant4_cnt) {
  1167. case 0:
  1168. s->qmant4_ptr = &qmant[i];
  1169. v = 11 * v;
  1170. s->mant4_cnt = 1;
  1171. break;
  1172. default:
  1173. *s->qmant4_ptr += v;
  1174. s->mant4_cnt = 0;
  1175. v = 128;
  1176. break;
  1177. }
  1178. break;
  1179. case 5:
  1180. v = sym_quant(c, e, 15);
  1181. break;
  1182. case 14:
  1183. v = asym_quant(c, e, 14);
  1184. break;
  1185. case 15:
  1186. v = asym_quant(c, e, 16);
  1187. break;
  1188. default:
  1189. v = asym_quant(c, e, b - 1);
  1190. break;
  1191. }
  1192. qmant[i] = v;
  1193. }
  1194. }
  1195. /**
  1196. * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
  1197. */
  1198. static void quantize_mantissas(AC3EncodeContext *s)
  1199. {
  1200. int blk, ch;
  1201. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1202. AC3Block *block = &s->blocks[blk];
  1203. s->mant1_cnt = s->mant2_cnt = s->mant4_cnt = 0;
  1204. s->qmant1_ptr = s->qmant2_ptr = s->qmant4_ptr = NULL;
  1205. for (ch = 0; ch < s->channels; ch++) {
  1206. quantize_mantissas_blk_ch(s, block->mdct_coef[ch], block->exp_shift[ch],
  1207. block->exp[ch], block->bap[ch],
  1208. block->qmant[ch], s->nb_coefs[ch]);
  1209. }
  1210. }
  1211. }
  1212. /**
  1213. * Write the AC-3 frame header to the output bitstream.
  1214. */
  1215. static void output_frame_header(AC3EncodeContext *s)
  1216. {
  1217. put_bits(&s->pb, 16, 0x0b77); /* frame header */
  1218. put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
  1219. put_bits(&s->pb, 2, s->bit_alloc.sr_code);
  1220. put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
  1221. put_bits(&s->pb, 5, s->bitstream_id);
  1222. put_bits(&s->pb, 3, s->bitstream_mode);
  1223. put_bits(&s->pb, 3, s->channel_mode);
  1224. if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
  1225. put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
  1226. if (s->channel_mode & 0x04)
  1227. put_bits(&s->pb, 2, 1); /* XXX -6 dB */
  1228. if (s->channel_mode == AC3_CHMODE_STEREO)
  1229. put_bits(&s->pb, 2, 0); /* surround not indicated */
  1230. put_bits(&s->pb, 1, s->lfe_on); /* LFE */
  1231. put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
  1232. put_bits(&s->pb, 1, 0); /* no compression control word */
  1233. put_bits(&s->pb, 1, 0); /* no lang code */
  1234. put_bits(&s->pb, 1, 0); /* no audio production info */
  1235. put_bits(&s->pb, 1, 0); /* no copyright */
  1236. put_bits(&s->pb, 1, 1); /* original bitstream */
  1237. put_bits(&s->pb, 1, 0); /* no time code 1 */
  1238. put_bits(&s->pb, 1, 0); /* no time code 2 */
  1239. put_bits(&s->pb, 1, 0); /* no additional bit stream info */
  1240. }
  1241. /**
  1242. * Write one audio block to the output bitstream.
  1243. */
  1244. static void output_audio_block(AC3EncodeContext *s, int block_num)
  1245. {
  1246. int ch, i, baie, rbnd;
  1247. AC3Block *block = &s->blocks[block_num];
  1248. /* block switching */
  1249. for (ch = 0; ch < s->fbw_channels; ch++)
  1250. put_bits(&s->pb, 1, 0);
  1251. /* dither flags */
  1252. for (ch = 0; ch < s->fbw_channels; ch++)
  1253. put_bits(&s->pb, 1, 1);
  1254. /* dynamic range codes */
  1255. put_bits(&s->pb, 1, 0);
  1256. /* channel coupling */
  1257. if (!block_num) {
  1258. put_bits(&s->pb, 1, 1); /* coupling strategy present */
  1259. put_bits(&s->pb, 1, 0); /* no coupling strategy */
  1260. } else {
  1261. put_bits(&s->pb, 1, 0); /* no new coupling strategy */
  1262. }
  1263. /* stereo rematrixing */
  1264. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1265. if (!block_num) {
  1266. /* first block must define rematrixing (rematstr) */
  1267. put_bits(&s->pb, 1, 1);
  1268. /* dummy rematrixing rematflg(1:4)=0 */
  1269. for (rbnd = 0; rbnd < 4; rbnd++)
  1270. put_bits(&s->pb, 1, 0);
  1271. } else {
  1272. /* no matrixing (but should be used in the future) */
  1273. put_bits(&s->pb, 1, 0);
  1274. }
  1275. }
  1276. /* exponent strategy */
  1277. for (ch = 0; ch < s->fbw_channels; ch++)
  1278. put_bits(&s->pb, 2, block->exp_strategy[ch]);
  1279. if (s->lfe_on)
  1280. put_bits(&s->pb, 1, block->exp_strategy[s->lfe_channel]);
  1281. /* bandwidth */
  1282. for (ch = 0; ch < s->fbw_channels; ch++) {
  1283. if (block->exp_strategy[ch] != EXP_REUSE)
  1284. put_bits(&s->pb, 6, s->bandwidth_code[ch]);
  1285. }
  1286. /* exponents */
  1287. for (ch = 0; ch < s->channels; ch++) {
  1288. int nb_groups;
  1289. if (block->exp_strategy[ch] == EXP_REUSE)
  1290. continue;
  1291. /* DC exponent */
  1292. put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
  1293. /* exponent groups */
  1294. nb_groups = exponent_group_tab[block->exp_strategy[ch]-1][s->nb_coefs[ch]];
  1295. for (i = 1; i <= nb_groups; i++)
  1296. put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
  1297. /* gain range info */
  1298. if (ch != s->lfe_channel)
  1299. put_bits(&s->pb, 2, 0);
  1300. }
  1301. /* bit allocation info */
  1302. baie = (block_num == 0);
  1303. put_bits(&s->pb, 1, baie);
  1304. if (baie) {
  1305. put_bits(&s->pb, 2, s->slow_decay_code);
  1306. put_bits(&s->pb, 2, s->fast_decay_code);
  1307. put_bits(&s->pb, 2, s->slow_gain_code);
  1308. put_bits(&s->pb, 2, s->db_per_bit_code);
  1309. put_bits(&s->pb, 3, s->floor_code);
  1310. }
  1311. /* snr offset */
  1312. put_bits(&s->pb, 1, baie);
  1313. if (baie) {
  1314. put_bits(&s->pb, 6, s->coarse_snr_offset);
  1315. for (ch = 0; ch < s->channels; ch++) {
  1316. put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
  1317. put_bits(&s->pb, 3, s->fast_gain_code[ch]);
  1318. }
  1319. }
  1320. put_bits(&s->pb, 1, 0); /* no delta bit allocation */
  1321. put_bits(&s->pb, 1, 0); /* no data to skip */
  1322. /* mantissas */
  1323. for (ch = 0; ch < s->channels; ch++) {
  1324. int b, q;
  1325. for (i = 0; i < s->nb_coefs[ch]; i++) {
  1326. q = block->qmant[ch][i];
  1327. b = block->bap[ch][i];
  1328. switch (b) {
  1329. case 0: break;
  1330. case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
  1331. case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
  1332. case 3: put_bits(&s->pb, 3, q); break;
  1333. case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
  1334. case 14: put_bits(&s->pb, 14, q); break;
  1335. case 15: put_bits(&s->pb, 16, q); break;
  1336. default: put_bits(&s->pb, b-1, q); break;
  1337. }
  1338. }
  1339. }
  1340. }
  1341. /** CRC-16 Polynomial */
  1342. #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
  1343. static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
  1344. {
  1345. unsigned int c;
  1346. c = 0;
  1347. while (a) {
  1348. if (a & 1)
  1349. c ^= b;
  1350. a = a >> 1;
  1351. b = b << 1;
  1352. if (b & (1 << 16))
  1353. b ^= poly;
  1354. }
  1355. return c;
  1356. }
  1357. static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
  1358. {
  1359. unsigned int r;
  1360. r = 1;
  1361. while (n) {
  1362. if (n & 1)
  1363. r = mul_poly(r, a, poly);
  1364. a = mul_poly(a, a, poly);
  1365. n >>= 1;
  1366. }
  1367. return r;
  1368. }
  1369. /**
  1370. * Fill the end of the frame with 0's and compute the two CRCs.
  1371. */
  1372. static void output_frame_end(AC3EncodeContext *s)
  1373. {
  1374. const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
  1375. int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
  1376. uint8_t *frame;
  1377. frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
  1378. /* pad the remainder of the frame with zeros */
  1379. flush_put_bits(&s->pb);
  1380. frame = s->pb.buf;
  1381. pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
  1382. assert(pad_bytes >= 0);
  1383. if (pad_bytes > 0)
  1384. memset(put_bits_ptr(&s->pb), 0, pad_bytes);
  1385. /* compute crc1 */
  1386. /* this is not so easy because it is at the beginning of the data... */
  1387. crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
  1388. crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
  1389. crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
  1390. AV_WB16(frame + 2, crc1);
  1391. /* compute crc2 */
  1392. crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
  1393. s->frame_size - frame_size_58 - 3);
  1394. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1395. /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
  1396. if (crc2 == 0x770B) {
  1397. frame[s->frame_size - 3] ^= 0x1;
  1398. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1399. }
  1400. crc2 = av_bswap16(crc2);
  1401. AV_WB16(frame + s->frame_size - 2, crc2);
  1402. }
  1403. /**
  1404. * Write the frame to the output bitstream.
  1405. */
  1406. static void output_frame(AC3EncodeContext *s, unsigned char *frame)
  1407. {
  1408. int blk;
  1409. init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
  1410. output_frame_header(s);
  1411. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1412. output_audio_block(s, blk);
  1413. output_frame_end(s);
  1414. }
  1415. /**
  1416. * Encode a single AC-3 frame.
  1417. */
  1418. static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
  1419. int buf_size, void *data)
  1420. {
  1421. AC3EncodeContext *s = avctx->priv_data;
  1422. const SampleType *samples = data;
  1423. int ret;
  1424. if (s->bit_alloc.sr_code == 1)
  1425. adjust_frame_size(s);
  1426. deinterleave_input_samples(s, samples);
  1427. apply_mdct(s);
  1428. process_exponents(s);
  1429. ret = compute_bit_allocation(s);
  1430. if (ret) {
  1431. av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
  1432. return ret;
  1433. }
  1434. quantize_mantissas(s);
  1435. output_frame(s, frame);
  1436. return s->frame_size;
  1437. }
  1438. /**
  1439. * Finalize encoding and free any memory allocated by the encoder.
  1440. */
  1441. static av_cold int ac3_encode_close(AVCodecContext *avctx)
  1442. {
  1443. int blk, ch;
  1444. AC3EncodeContext *s = avctx->priv_data;
  1445. for (ch = 0; ch < s->channels; ch++)
  1446. av_freep(&s->planar_samples[ch]);
  1447. av_freep(&s->planar_samples);
  1448. av_freep(&s->bap_buffer);
  1449. av_freep(&s->bap1_buffer);
  1450. av_freep(&s->mdct_coef_buffer);
  1451. av_freep(&s->exp_buffer);
  1452. av_freep(&s->grouped_exp_buffer);
  1453. av_freep(&s->psd_buffer);
  1454. av_freep(&s->band_psd_buffer);
  1455. av_freep(&s->mask_buffer);
  1456. av_freep(&s->qmant_buffer);
  1457. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1458. AC3Block *block = &s->blocks[blk];
  1459. av_freep(&block->bap);
  1460. av_freep(&block->mdct_coef);
  1461. av_freep(&block->exp);
  1462. av_freep(&block->grouped_exp);
  1463. av_freep(&block->psd);
  1464. av_freep(&block->band_psd);
  1465. av_freep(&block->mask);
  1466. av_freep(&block->qmant);
  1467. }
  1468. mdct_end(&s->mdct);
  1469. av_freep(&avctx->coded_frame);
  1470. return 0;
  1471. }
  1472. /**
  1473. * Set channel information during initialization.
  1474. */
  1475. static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
  1476. int64_t *channel_layout)
  1477. {
  1478. int ch_layout;
  1479. if (channels < 1 || channels > AC3_MAX_CHANNELS)
  1480. return AVERROR(EINVAL);
  1481. if ((uint64_t)*channel_layout > 0x7FF)
  1482. return AVERROR(EINVAL);
  1483. ch_layout = *channel_layout;
  1484. if (!ch_layout)
  1485. ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
  1486. if (av_get_channel_layout_nb_channels(ch_layout) != channels)
  1487. return AVERROR(EINVAL);
  1488. s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
  1489. s->channels = channels;
  1490. s->fbw_channels = channels - s->lfe_on;
  1491. s->lfe_channel = s->lfe_on ? s->fbw_channels : -1;
  1492. if (s->lfe_on)
  1493. ch_layout -= AV_CH_LOW_FREQUENCY;
  1494. switch (ch_layout) {
  1495. case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
  1496. case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
  1497. case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
  1498. case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
  1499. case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
  1500. case AV_CH_LAYOUT_QUAD:
  1501. case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
  1502. case AV_CH_LAYOUT_5POINT0:
  1503. case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
  1504. default:
  1505. return AVERROR(EINVAL);
  1506. }
  1507. s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
  1508. *channel_layout = ch_layout;
  1509. if (s->lfe_on)
  1510. *channel_layout |= AV_CH_LOW_FREQUENCY;
  1511. return 0;
  1512. }
  1513. static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
  1514. {
  1515. int i, ret;
  1516. /* validate channel layout */
  1517. if (!avctx->channel_layout) {
  1518. av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
  1519. "encoder will guess the layout, but it "
  1520. "might be incorrect.\n");
  1521. }
  1522. ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
  1523. if (ret) {
  1524. av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
  1525. return ret;
  1526. }
  1527. /* validate sample rate */
  1528. for (i = 0; i < 9; i++) {
  1529. if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
  1530. break;
  1531. }
  1532. if (i == 9) {
  1533. av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
  1534. return AVERROR(EINVAL);
  1535. }
  1536. s->sample_rate = avctx->sample_rate;
  1537. s->bit_alloc.sr_shift = i % 3;
  1538. s->bit_alloc.sr_code = i / 3;
  1539. /* validate bit rate */
  1540. for (i = 0; i < 19; i++) {
  1541. if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
  1542. break;
  1543. }
  1544. if (i == 19) {
  1545. av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
  1546. return AVERROR(EINVAL);
  1547. }
  1548. s->bit_rate = avctx->bit_rate;
  1549. s->frame_size_code = i << 1;
  1550. /* validate cutoff */
  1551. if (avctx->cutoff < 0) {
  1552. av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
  1553. return AVERROR(EINVAL);
  1554. }
  1555. s->cutoff = avctx->cutoff;
  1556. if (s->cutoff > (s->sample_rate >> 1))
  1557. s->cutoff = s->sample_rate >> 1;
  1558. return 0;
  1559. }
  1560. /**
  1561. * Set bandwidth for all channels.
  1562. * The user can optionally supply a cutoff frequency. Otherwise an appropriate
  1563. * default value will be used.
  1564. */
  1565. static av_cold void set_bandwidth(AC3EncodeContext *s)
  1566. {
  1567. int ch, bw_code;
  1568. if (s->cutoff) {
  1569. /* calculate bandwidth based on user-specified cutoff frequency */
  1570. int fbw_coeffs;
  1571. fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
  1572. bw_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
  1573. } else {
  1574. /* use default bandwidth setting */
  1575. /* XXX: should compute the bandwidth according to the frame
  1576. size, so that we avoid annoying high frequency artifacts */
  1577. bw_code = 50;
  1578. }
  1579. /* set number of coefficients for each channel */
  1580. for (ch = 0; ch < s->fbw_channels; ch++) {
  1581. s->bandwidth_code[ch] = bw_code;
  1582. s->nb_coefs[ch] = bw_code * 3 + 73;
  1583. }
  1584. if (s->lfe_on)
  1585. s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
  1586. }
  1587. static av_cold int allocate_buffers(AVCodecContext *avctx)
  1588. {
  1589. int blk, ch;
  1590. AC3EncodeContext *s = avctx->priv_data;
  1591. FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
  1592. alloc_fail);
  1593. for (ch = 0; ch < s->channels; ch++) {
  1594. FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
  1595. (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
  1596. alloc_fail);
  1597. }
  1598. FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * s->channels *
  1599. AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
  1600. FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
  1601. AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
  1602. FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
  1603. AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
  1604. FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
  1605. AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
  1606. FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
  1607. 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
  1608. FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
  1609. AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
  1610. FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
  1611. 64 * sizeof(*s->band_psd_buffer), alloc_fail);
  1612. FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
  1613. 64 * sizeof(*s->mask_buffer), alloc_fail);
  1614. FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
  1615. AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
  1616. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1617. AC3Block *block = &s->blocks[blk];
  1618. FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
  1619. alloc_fail);
  1620. FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
  1621. alloc_fail);
  1622. FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
  1623. alloc_fail);
  1624. FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
  1625. alloc_fail);
  1626. FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
  1627. alloc_fail);
  1628. FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
  1629. alloc_fail);
  1630. FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
  1631. alloc_fail);
  1632. FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
  1633. alloc_fail);
  1634. for (ch = 0; ch < s->channels; ch++) {
  1635. block->bap[ch] = &s->bap_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1636. block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1637. block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1638. block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * s->channels + ch)];
  1639. block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1640. block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * s->channels + ch)];
  1641. block->mask[ch] = &s->mask_buffer [64 * (blk * s->channels + ch)];
  1642. block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1643. }
  1644. }
  1645. return 0;
  1646. alloc_fail:
  1647. return AVERROR(ENOMEM);
  1648. }
  1649. /**
  1650. * Initialize the encoder.
  1651. */
  1652. static av_cold int ac3_encode_init(AVCodecContext *avctx)
  1653. {
  1654. AC3EncodeContext *s = avctx->priv_data;
  1655. int ret, frame_size_58;
  1656. avctx->frame_size = AC3_FRAME_SIZE;
  1657. ac3_common_init();
  1658. ret = validate_options(avctx, s);
  1659. if (ret)
  1660. return ret;
  1661. s->bitstream_id = 8 + s->bit_alloc.sr_shift;
  1662. s->bitstream_mode = 0; /* complete main audio service */
  1663. s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
  1664. s->bits_written = 0;
  1665. s->samples_written = 0;
  1666. s->frame_size = s->frame_size_min;
  1667. /* calculate crc_inv for both possible frame sizes */
  1668. frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
  1669. s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  1670. if (s->bit_alloc.sr_code == 1) {
  1671. frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
  1672. s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  1673. }
  1674. set_bandwidth(s);
  1675. exponent_init(s);
  1676. bit_alloc_init(s);
  1677. ret = mdct_init(avctx, &s->mdct, 9);
  1678. if (ret)
  1679. goto init_fail;
  1680. ret = allocate_buffers(avctx);
  1681. if (ret)
  1682. goto init_fail;
  1683. avctx->coded_frame= avcodec_alloc_frame();
  1684. dsputil_init(&s->dsp, avctx);
  1685. return 0;
  1686. init_fail:
  1687. ac3_encode_close(avctx);
  1688. return ret;
  1689. }
  1690. #ifdef TEST
  1691. /*************************************************************************/
  1692. /* TEST */
  1693. #include "libavutil/lfg.h"
  1694. #define MDCT_NBITS 9
  1695. #define MDCT_SAMPLES (1 << MDCT_NBITS)
  1696. #define FN (MDCT_SAMPLES/4)
  1697. static void fft_test(AC3MDCTContext *mdct, AVLFG *lfg)
  1698. {
  1699. IComplex in[FN], in1[FN];
  1700. int k, n, i;
  1701. float sum_re, sum_im, a;
  1702. for (i = 0; i < FN; i++) {
  1703. in[i].re = av_lfg_get(lfg) % 65535 - 32767;
  1704. in[i].im = av_lfg_get(lfg) % 65535 - 32767;
  1705. in1[i] = in[i];
  1706. }
  1707. fft(mdct, in, 7);
  1708. /* do it by hand */
  1709. for (k = 0; k < FN; k++) {
  1710. sum_re = 0;
  1711. sum_im = 0;
  1712. for (n = 0; n < FN; n++) {
  1713. a = -2 * M_PI * (n * k) / FN;
  1714. sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
  1715. sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
  1716. }
  1717. av_log(NULL, AV_LOG_DEBUG, "%3d: %6d,%6d %6.0f,%6.0f\n",
  1718. k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
  1719. }
  1720. }
  1721. static void mdct_test(AC3MDCTContext *mdct, AVLFG *lfg)
  1722. {
  1723. int16_t input[MDCT_SAMPLES];
  1724. int32_t output[AC3_MAX_COEFS];
  1725. float input1[MDCT_SAMPLES];
  1726. float output1[AC3_MAX_COEFS];
  1727. float s, a, err, e, emax;
  1728. int i, k, n;
  1729. for (i = 0; i < MDCT_SAMPLES; i++) {
  1730. input[i] = (av_lfg_get(lfg) % 65535 - 32767) * 9 / 10;
  1731. input1[i] = input[i];
  1732. }
  1733. mdct512(mdct, output, input);
  1734. /* do it by hand */
  1735. for (k = 0; k < AC3_MAX_COEFS; k++) {
  1736. s = 0;
  1737. for (n = 0; n < MDCT_SAMPLES; n++) {
  1738. a = (2*M_PI*(2*n+1+MDCT_SAMPLES/2)*(2*k+1) / (4 * MDCT_SAMPLES));
  1739. s += input1[n] * cos(a);
  1740. }
  1741. output1[k] = -2 * s / MDCT_SAMPLES;
  1742. }
  1743. err = 0;
  1744. emax = 0;
  1745. for (i = 0; i < AC3_MAX_COEFS; i++) {
  1746. av_log(NULL, AV_LOG_DEBUG, "%3d: %7d %7.0f\n", i, output[i], output1[i]);
  1747. e = output[i] - output1[i];
  1748. if (e > emax)
  1749. emax = e;
  1750. err += e * e;
  1751. }
  1752. av_log(NULL, AV_LOG_DEBUG, "err2=%f emax=%f\n", err / AC3_MAX_COEFS, emax);
  1753. }
  1754. int main(void)
  1755. {
  1756. AVLFG lfg;
  1757. AC3MDCTContext mdct;
  1758. mdct.avctx = NULL;
  1759. av_log_set_level(AV_LOG_DEBUG);
  1760. mdct_init(&mdct, 9);
  1761. fft_test(&mdct, &lfg);
  1762. mdct_test(&mdct, &lfg);
  1763. return 0;
  1764. }
  1765. #endif /* TEST */
  1766. AVCodec ac3_encoder = {
  1767. "ac3",
  1768. AVMEDIA_TYPE_AUDIO,
  1769. CODEC_ID_AC3,
  1770. sizeof(AC3EncodeContext),
  1771. ac3_encode_init,
  1772. ac3_encode_frame,
  1773. ac3_encode_close,
  1774. NULL,
  1775. .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
  1776. .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
  1777. .channel_layouts = ac3_channel_layouts,
  1778. };