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.

1974 lines
59KB

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