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.

2071 lines
62KB

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