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.

1869 lines
56KB

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