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.

1735 lines
54KB

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