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.

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