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.

2085 lines
63KB

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