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.

1505 lines
42KB

  1. /*
  2. * The simplest AC3 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 ac3enc.c
  23. * The simplest AC3 encoder.
  24. */
  25. //#define DEBUG
  26. //#define DEBUG_BITALLOC
  27. #include "avcodec.h"
  28. #include "bitstream.h"
  29. #include "crc.h"
  30. #include "ac3.h"
  31. typedef struct AC3EncodeContext {
  32. PutBitContext pb;
  33. int nb_channels;
  34. int nb_all_channels;
  35. int lfe_channel;
  36. int bit_rate;
  37. unsigned int sample_rate;
  38. unsigned int bsid;
  39. unsigned int frame_size_min; /* minimum frame size in case rounding is necessary */
  40. unsigned int frame_size; /* current frame size in words */
  41. unsigned int bits_written;
  42. unsigned int samples_written;
  43. int halfratecod;
  44. unsigned int frmsizecod;
  45. unsigned int fscod; /* frequency */
  46. unsigned int acmod;
  47. int lfe;
  48. unsigned int bsmod;
  49. short last_samples[AC3_MAX_CHANNELS][256];
  50. unsigned int chbwcod[AC3_MAX_CHANNELS];
  51. int nb_coefs[AC3_MAX_CHANNELS];
  52. /* bitrate allocation control */
  53. int sgaincod, sdecaycod, fdecaycod, dbkneecod, floorcod;
  54. AC3BitAllocParameters bit_alloc;
  55. int csnroffst;
  56. int fgaincod[AC3_MAX_CHANNELS];
  57. int fsnroffst[AC3_MAX_CHANNELS];
  58. /* mantissa encoding */
  59. int mant1_cnt, mant2_cnt, mant4_cnt;
  60. } AC3EncodeContext;
  61. #include "ac3tab.h"
  62. #define MDCT_NBITS 9
  63. #define N (1 << MDCT_NBITS)
  64. /* new exponents are sent if their Norm 1 exceed this number */
  65. #define EXP_DIFF_THRESHOLD 1000
  66. static void fft_init(int ln);
  67. static inline int16_t fix15(float a)
  68. {
  69. int v;
  70. v = (int)(a * (float)(1 << 15));
  71. if (v < -32767)
  72. v = -32767;
  73. else if (v > 32767)
  74. v = 32767;
  75. return v;
  76. }
  77. static inline int calc_lowcomp1(int a, int b0, int b1, int c)
  78. {
  79. if ((b0 + 256) == b1) {
  80. a = c;
  81. } else if (b0 > b1) {
  82. a = FFMAX(a - 64, 0);
  83. }
  84. return a;
  85. }
  86. static inline int calc_lowcomp(int a, int b0, int b1, int bin)
  87. {
  88. if (bin < 7) {
  89. return calc_lowcomp1(a, b0, b1, 384);
  90. } else if (bin < 20) {
  91. return calc_lowcomp1(a, b0, b1, 320);
  92. } else {
  93. return FFMAX(a - 128, 0);
  94. }
  95. }
  96. /* AC3 bit allocation. The algorithm is the one described in the AC3
  97. spec. */
  98. void ac3_parametric_bit_allocation(AC3BitAllocParameters *s, uint8_t *bap,
  99. int8_t *exp, int start, int end,
  100. int snroffset, int fgain, int is_lfe,
  101. int deltbae,int deltnseg,
  102. uint8_t *deltoffst, uint8_t *deltlen, uint8_t *deltba)
  103. {
  104. int bin,i,j,k,end1,v,bndstrt,bndend,lowcomp,begin;
  105. int fastleak,slowleak,address,tmp;
  106. int16_t psd[256]; /* scaled exponents */
  107. int16_t bndpsd[50]; /* interpolated exponents */
  108. int16_t excite[50]; /* excitation */
  109. int16_t mask[50]; /* masking value */
  110. /* exponent mapping to PSD */
  111. for(bin=start;bin<end;bin++) {
  112. psd[bin]=(3072 - (exp[bin] << 7));
  113. }
  114. /* PSD integration */
  115. j=start;
  116. k=masktab[start];
  117. do {
  118. v=psd[j];
  119. j++;
  120. end1 = FFMIN(bndtab[k+1], end);
  121. for(i=j;i<end1;i++) {
  122. /* logadd */
  123. int adr = FFMIN(FFABS(v - psd[j]) >> 1, 255);
  124. v = FFMAX(v, psd[j]) + latab[adr];
  125. j++;
  126. }
  127. bndpsd[k]=v;
  128. k++;
  129. } while (end > bndtab[k]);
  130. /* excitation function */
  131. bndstrt = masktab[start];
  132. bndend = masktab[end-1] + 1;
  133. if (bndstrt == 0) {
  134. lowcomp = 0;
  135. lowcomp = calc_lowcomp1(lowcomp, bndpsd[0], bndpsd[1], 384);
  136. excite[0] = bndpsd[0] - fgain - lowcomp;
  137. lowcomp = calc_lowcomp1(lowcomp, bndpsd[1], bndpsd[2], 384);
  138. excite[1] = bndpsd[1] - fgain - lowcomp;
  139. begin = 7;
  140. for (bin = 2; bin < 7; bin++) {
  141. if (!(is_lfe && bin == 6))
  142. lowcomp = calc_lowcomp1(lowcomp, bndpsd[bin], bndpsd[bin+1], 384);
  143. fastleak = bndpsd[bin] - fgain;
  144. slowleak = bndpsd[bin] - s->sgain;
  145. excite[bin] = fastleak - lowcomp;
  146. if (!(is_lfe && bin == 6)) {
  147. if (bndpsd[bin] <= bndpsd[bin+1]) {
  148. begin = bin + 1;
  149. break;
  150. }
  151. }
  152. }
  153. end1=bndend;
  154. if (end1 > 22) end1=22;
  155. for (bin = begin; bin < end1; bin++) {
  156. if (!(is_lfe && bin == 6))
  157. lowcomp = calc_lowcomp(lowcomp, bndpsd[bin], bndpsd[bin+1], bin);
  158. fastleak = FFMAX(fastleak - s->fdecay, bndpsd[bin] - fgain);
  159. slowleak = FFMAX(slowleak - s->sdecay, bndpsd[bin] - s->sgain);
  160. excite[bin] = FFMAX(fastleak - lowcomp, slowleak);
  161. }
  162. begin = 22;
  163. } else {
  164. /* coupling channel */
  165. begin = bndstrt;
  166. fastleak = (s->cplfleak << 8) + 768;
  167. slowleak = (s->cplsleak << 8) + 768;
  168. }
  169. for (bin = begin; bin < bndend; bin++) {
  170. fastleak = FFMAX(fastleak - s->fdecay, bndpsd[bin] - fgain);
  171. slowleak = FFMAX(slowleak - s->sdecay, bndpsd[bin] - s->sgain);
  172. excite[bin] = FFMAX(fastleak, slowleak);
  173. }
  174. /* compute masking curve */
  175. for (bin = bndstrt; bin < bndend; bin++) {
  176. tmp = s->dbknee - bndpsd[bin];
  177. if (tmp > 0) {
  178. excite[bin] += tmp >> 2;
  179. }
  180. mask[bin] = FFMAX(hth[bin >> s->halfratecod][s->fscod], excite[bin]);
  181. }
  182. /* delta bit allocation */
  183. if (deltbae == 0 || deltbae == 1) {
  184. int band, seg, delta;
  185. band = 0;
  186. for (seg = 0; seg < deltnseg; seg++) {
  187. band += deltoffst[seg];
  188. if (deltba[seg] >= 4) {
  189. delta = (deltba[seg] - 3) << 7;
  190. } else {
  191. delta = (deltba[seg] - 4) << 7;
  192. }
  193. for (k = 0; k < deltlen[seg]; k++) {
  194. mask[band] += delta;
  195. band++;
  196. }
  197. }
  198. }
  199. /* compute bit allocation */
  200. i = start;
  201. j = masktab[start];
  202. do {
  203. v = (FFMAX(mask[j] - snroffset - s->floor, 0) & 0x1FE0) + s->floor;
  204. end1 = FFMIN(bndtab[j] + bndsz[j], end);
  205. for (k = i; k < end1; k++) {
  206. address = av_clip((psd[i] - v) >> 5, 0, 63);
  207. bap[i] = baptab[address];
  208. i++;
  209. }
  210. } while (end > bndtab[j++]);
  211. }
  212. typedef struct IComplex {
  213. short re,im;
  214. } IComplex;
  215. static void fft_init(int ln)
  216. {
  217. int i, j, m, n;
  218. float alpha;
  219. n = 1 << ln;
  220. for(i=0;i<(n/2);i++) {
  221. alpha = 2 * M_PI * (float)i / (float)n;
  222. costab[i] = fix15(cos(alpha));
  223. sintab[i] = fix15(sin(alpha));
  224. }
  225. for(i=0;i<n;i++) {
  226. m=0;
  227. for(j=0;j<ln;j++) {
  228. m |= ((i >> j) & 1) << (ln-j-1);
  229. }
  230. fft_rev[i]=m;
  231. }
  232. }
  233. /* butter fly op */
  234. #define BF(pre, pim, qre, qim, pre1, pim1, qre1, qim1) \
  235. {\
  236. int ax, ay, bx, by;\
  237. bx=pre1;\
  238. by=pim1;\
  239. ax=qre1;\
  240. ay=qim1;\
  241. pre = (bx + ax) >> 1;\
  242. pim = (by + ay) >> 1;\
  243. qre = (bx - ax) >> 1;\
  244. qim = (by - ay) >> 1;\
  245. }
  246. #define MUL16(a,b) ((a) * (b))
  247. #define CMUL(pre, pim, are, aim, bre, bim) \
  248. {\
  249. pre = (MUL16(are, bre) - MUL16(aim, bim)) >> 15;\
  250. pim = (MUL16(are, bim) + MUL16(bre, aim)) >> 15;\
  251. }
  252. /* do a 2^n point complex fft on 2^ln points. */
  253. static void fft(IComplex *z, int ln)
  254. {
  255. int j, l, np, np2;
  256. int nblocks, nloops;
  257. register IComplex *p,*q;
  258. int tmp_re, tmp_im;
  259. np = 1 << ln;
  260. /* reverse */
  261. for(j=0;j<np;j++) {
  262. int k;
  263. IComplex tmp;
  264. k = fft_rev[j];
  265. if (k < j) {
  266. tmp = z[k];
  267. z[k] = z[j];
  268. z[j] = tmp;
  269. }
  270. }
  271. /* pass 0 */
  272. p=&z[0];
  273. j=(np >> 1);
  274. do {
  275. BF(p[0].re, p[0].im, p[1].re, p[1].im,
  276. p[0].re, p[0].im, p[1].re, p[1].im);
  277. p+=2;
  278. } while (--j != 0);
  279. /* pass 1 */
  280. p=&z[0];
  281. j=np >> 2;
  282. do {
  283. BF(p[0].re, p[0].im, p[2].re, p[2].im,
  284. p[0].re, p[0].im, p[2].re, p[2].im);
  285. BF(p[1].re, p[1].im, p[3].re, p[3].im,
  286. p[1].re, p[1].im, p[3].im, -p[3].re);
  287. p+=4;
  288. } while (--j != 0);
  289. /* pass 2 .. ln-1 */
  290. nblocks = np >> 3;
  291. nloops = 1 << 2;
  292. np2 = np >> 1;
  293. do {
  294. p = z;
  295. q = z + nloops;
  296. for (j = 0; j < nblocks; ++j) {
  297. BF(p->re, p->im, q->re, q->im,
  298. p->re, p->im, q->re, q->im);
  299. p++;
  300. q++;
  301. for(l = nblocks; l < np2; l += nblocks) {
  302. CMUL(tmp_re, tmp_im, costab[l], -sintab[l], q->re, q->im);
  303. BF(p->re, p->im, q->re, q->im,
  304. p->re, p->im, tmp_re, tmp_im);
  305. p++;
  306. q++;
  307. }
  308. p += nloops;
  309. q += nloops;
  310. }
  311. nblocks = nblocks >> 1;
  312. nloops = nloops << 1;
  313. } while (nblocks != 0);
  314. }
  315. /* do a 512 point mdct */
  316. static void mdct512(int32_t *out, int16_t *in)
  317. {
  318. int i, re, im, re1, im1;
  319. int16_t rot[N];
  320. IComplex x[N/4];
  321. /* shift to simplify computations */
  322. for(i=0;i<N/4;i++)
  323. rot[i] = -in[i + 3*N/4];
  324. for(i=N/4;i<N;i++)
  325. rot[i] = in[i - N/4];
  326. /* pre rotation */
  327. for(i=0;i<N/4;i++) {
  328. re = ((int)rot[2*i] - (int)rot[N-1-2*i]) >> 1;
  329. im = -((int)rot[N/2+2*i] - (int)rot[N/2-1-2*i]) >> 1;
  330. CMUL(x[i].re, x[i].im, re, im, -xcos1[i], xsin1[i]);
  331. }
  332. fft(x, MDCT_NBITS - 2);
  333. /* post rotation */
  334. for(i=0;i<N/4;i++) {
  335. re = x[i].re;
  336. im = x[i].im;
  337. CMUL(re1, im1, re, im, xsin1[i], xcos1[i]);
  338. out[2*i] = im1;
  339. out[N/2-1-2*i] = re1;
  340. }
  341. }
  342. /* XXX: use another norm ? */
  343. static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
  344. {
  345. int sum, i;
  346. sum = 0;
  347. for(i=0;i<n;i++) {
  348. sum += abs(exp1[i] - exp2[i]);
  349. }
  350. return sum;
  351. }
  352. static void compute_exp_strategy(uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
  353. uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
  354. int ch, int is_lfe)
  355. {
  356. int i, j;
  357. int exp_diff;
  358. /* estimate if the exponent variation & decide if they should be
  359. reused in the next frame */
  360. exp_strategy[0][ch] = EXP_NEW;
  361. for(i=1;i<NB_BLOCKS;i++) {
  362. exp_diff = calc_exp_diff(exp[i][ch], exp[i-1][ch], N/2);
  363. #ifdef DEBUG
  364. av_log(NULL, AV_LOG_DEBUG, "exp_diff=%d\n", exp_diff);
  365. #endif
  366. if (exp_diff > EXP_DIFF_THRESHOLD)
  367. exp_strategy[i][ch] = EXP_NEW;
  368. else
  369. exp_strategy[i][ch] = EXP_REUSE;
  370. }
  371. if (is_lfe)
  372. return;
  373. /* now select the encoding strategy type : if exponents are often
  374. recoded, we use a coarse encoding */
  375. i = 0;
  376. while (i < NB_BLOCKS) {
  377. j = i + 1;
  378. while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE)
  379. j++;
  380. switch(j - i) {
  381. case 1:
  382. exp_strategy[i][ch] = EXP_D45;
  383. break;
  384. case 2:
  385. case 3:
  386. exp_strategy[i][ch] = EXP_D25;
  387. break;
  388. default:
  389. exp_strategy[i][ch] = EXP_D15;
  390. break;
  391. }
  392. i = j;
  393. }
  394. }
  395. /* set exp[i] to min(exp[i], exp1[i]) */
  396. static void exponent_min(uint8_t exp[N/2], uint8_t exp1[N/2], int n)
  397. {
  398. int i;
  399. for(i=0;i<n;i++) {
  400. if (exp1[i] < exp[i])
  401. exp[i] = exp1[i];
  402. }
  403. }
  404. /* update the exponents so that they are the ones the decoder will
  405. decode. Return the number of bits used to code the exponents */
  406. static int encode_exp(uint8_t encoded_exp[N/2],
  407. uint8_t exp[N/2],
  408. int nb_exps,
  409. int exp_strategy)
  410. {
  411. int group_size, nb_groups, i, j, k, exp_min;
  412. uint8_t exp1[N/2];
  413. switch(exp_strategy) {
  414. case EXP_D15:
  415. group_size = 1;
  416. break;
  417. case EXP_D25:
  418. group_size = 2;
  419. break;
  420. default:
  421. case EXP_D45:
  422. group_size = 4;
  423. break;
  424. }
  425. nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
  426. /* for each group, compute the minimum exponent */
  427. exp1[0] = exp[0]; /* DC exponent is handled separately */
  428. k = 1;
  429. for(i=1;i<=nb_groups;i++) {
  430. exp_min = exp[k];
  431. assert(exp_min >= 0 && exp_min <= 24);
  432. for(j=1;j<group_size;j++) {
  433. if (exp[k+j] < exp_min)
  434. exp_min = exp[k+j];
  435. }
  436. exp1[i] = exp_min;
  437. k += group_size;
  438. }
  439. /* constraint for DC exponent */
  440. if (exp1[0] > 15)
  441. exp1[0] = 15;
  442. /* Decrease the delta between each groups to within 2
  443. * so that they can be differentially encoded */
  444. for (i=1;i<=nb_groups;i++)
  445. exp1[i] = FFMIN(exp1[i], exp1[i-1] + 2);
  446. for (i=nb_groups-1;i>=0;i--)
  447. exp1[i] = FFMIN(exp1[i], exp1[i+1] + 2);
  448. /* now we have the exponent values the decoder will see */
  449. encoded_exp[0] = exp1[0];
  450. k = 1;
  451. for(i=1;i<=nb_groups;i++) {
  452. for(j=0;j<group_size;j++) {
  453. encoded_exp[k+j] = exp1[i];
  454. }
  455. k += group_size;
  456. }
  457. #if defined(DEBUG)
  458. av_log(NULL, AV_LOG_DEBUG, "exponents: strategy=%d\n", exp_strategy);
  459. for(i=0;i<=nb_groups * group_size;i++) {
  460. av_log(NULL, AV_LOG_DEBUG, "%d ", encoded_exp[i]);
  461. }
  462. av_log(NULL, AV_LOG_DEBUG, "\n");
  463. #endif
  464. return 4 + (nb_groups / 3) * 7;
  465. }
  466. /* return the size in bits taken by the mantissa */
  467. static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
  468. {
  469. int bits, mant, i;
  470. bits = 0;
  471. for(i=0;i<nb_coefs;i++) {
  472. mant = m[i];
  473. switch(mant) {
  474. case 0:
  475. /* nothing */
  476. break;
  477. case 1:
  478. /* 3 mantissa in 5 bits */
  479. if (s->mant1_cnt == 0)
  480. bits += 5;
  481. if (++s->mant1_cnt == 3)
  482. s->mant1_cnt = 0;
  483. break;
  484. case 2:
  485. /* 3 mantissa in 7 bits */
  486. if (s->mant2_cnt == 0)
  487. bits += 7;
  488. if (++s->mant2_cnt == 3)
  489. s->mant2_cnt = 0;
  490. break;
  491. case 3:
  492. bits += 3;
  493. break;
  494. case 4:
  495. /* 2 mantissa in 7 bits */
  496. if (s->mant4_cnt == 0)
  497. bits += 7;
  498. if (++s->mant4_cnt == 2)
  499. s->mant4_cnt = 0;
  500. break;
  501. case 14:
  502. bits += 14;
  503. break;
  504. case 15:
  505. bits += 16;
  506. break;
  507. default:
  508. bits += mant - 1;
  509. break;
  510. }
  511. }
  512. return bits;
  513. }
  514. static int bit_alloc(AC3EncodeContext *s,
  515. uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
  516. uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
  517. uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
  518. int frame_bits, int csnroffst, int fsnroffst)
  519. {
  520. int i, ch;
  521. /* compute size */
  522. for(i=0;i<NB_BLOCKS;i++) {
  523. s->mant1_cnt = 0;
  524. s->mant2_cnt = 0;
  525. s->mant4_cnt = 0;
  526. for(ch=0;ch<s->nb_all_channels;ch++) {
  527. ac3_parametric_bit_allocation(&s->bit_alloc,
  528. bap[i][ch], (int8_t *)encoded_exp[i][ch],
  529. 0, s->nb_coefs[ch],
  530. (((csnroffst-15) << 4) +
  531. fsnroffst) << 2,
  532. fgaintab[s->fgaincod[ch]],
  533. ch == s->lfe_channel,
  534. 2, 0, NULL, NULL, NULL);
  535. frame_bits += compute_mantissa_size(s, bap[i][ch],
  536. s->nb_coefs[ch]);
  537. }
  538. }
  539. #if 0
  540. printf("csnr=%d fsnr=%d frame_bits=%d diff=%d\n",
  541. csnroffst, fsnroffst, frame_bits,
  542. 16 * s->frame_size - ((frame_bits + 7) & ~7));
  543. #endif
  544. return 16 * s->frame_size - frame_bits;
  545. }
  546. #define SNR_INC1 4
  547. static int compute_bit_allocation(AC3EncodeContext *s,
  548. uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
  549. uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2],
  550. uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS],
  551. int frame_bits)
  552. {
  553. int i, ch;
  554. int csnroffst, fsnroffst;
  555. uint8_t bap1[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
  556. static int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
  557. /* init default parameters */
  558. s->sdecaycod = 2;
  559. s->fdecaycod = 1;
  560. s->sgaincod = 1;
  561. s->dbkneecod = 2;
  562. s->floorcod = 4;
  563. for(ch=0;ch<s->nb_all_channels;ch++)
  564. s->fgaincod[ch] = 4;
  565. /* compute real values */
  566. s->bit_alloc.fscod = s->fscod;
  567. s->bit_alloc.halfratecod = s->halfratecod;
  568. s->bit_alloc.sdecay = sdecaytab[s->sdecaycod] >> s->halfratecod;
  569. s->bit_alloc.fdecay = fdecaytab[s->fdecaycod] >> s->halfratecod;
  570. s->bit_alloc.sgain = sgaintab[s->sgaincod];
  571. s->bit_alloc.dbknee = dbkneetab[s->dbkneecod];
  572. s->bit_alloc.floor = floortab[s->floorcod];
  573. /* header size */
  574. frame_bits += 65;
  575. // if (s->acmod == 2)
  576. // frame_bits += 2;
  577. frame_bits += frame_bits_inc[s->acmod];
  578. /* audio blocks */
  579. for(i=0;i<NB_BLOCKS;i++) {
  580. frame_bits += s->nb_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
  581. if (s->acmod == 2) {
  582. frame_bits++; /* rematstr */
  583. if(i==0) frame_bits += 4;
  584. }
  585. frame_bits += 2 * s->nb_channels; /* chexpstr[2] * c */
  586. if (s->lfe)
  587. frame_bits++; /* lfeexpstr */
  588. for(ch=0;ch<s->nb_channels;ch++) {
  589. if (exp_strategy[i][ch] != EXP_REUSE)
  590. frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
  591. }
  592. frame_bits++; /* baie */
  593. frame_bits++; /* snr */
  594. frame_bits += 2; /* delta / skip */
  595. }
  596. frame_bits++; /* cplinu for block 0 */
  597. /* bit alloc info */
  598. /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
  599. /* csnroffset[6] */
  600. /* (fsnoffset[4] + fgaincod[4]) * c */
  601. frame_bits += 2*4 + 3 + 6 + s->nb_all_channels * (4 + 3);
  602. /* auxdatae, crcrsv */
  603. frame_bits += 2;
  604. /* CRC */
  605. frame_bits += 16;
  606. /* now the big work begins : do the bit allocation. Modify the snr
  607. offset until we can pack everything in the requested frame size */
  608. csnroffst = s->csnroffst;
  609. while (csnroffst >= 0 &&
  610. bit_alloc(s, bap, encoded_exp, exp_strategy, frame_bits, csnroffst, 0) < 0)
  611. csnroffst -= SNR_INC1;
  612. if (csnroffst < 0) {
  613. av_log(NULL, AV_LOG_ERROR, "Bit allocation failed, try increasing the bitrate, -ab 384 for example!\n");
  614. return -1;
  615. }
  616. while ((csnroffst + SNR_INC1) <= 63 &&
  617. bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits,
  618. csnroffst + SNR_INC1, 0) >= 0) {
  619. csnroffst += SNR_INC1;
  620. memcpy(bap, bap1, sizeof(bap1));
  621. }
  622. while ((csnroffst + 1) <= 63 &&
  623. bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits, csnroffst + 1, 0) >= 0) {
  624. csnroffst++;
  625. memcpy(bap, bap1, sizeof(bap1));
  626. }
  627. fsnroffst = 0;
  628. while ((fsnroffst + SNR_INC1) <= 15 &&
  629. bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits,
  630. csnroffst, fsnroffst + SNR_INC1) >= 0) {
  631. fsnroffst += SNR_INC1;
  632. memcpy(bap, bap1, sizeof(bap1));
  633. }
  634. while ((fsnroffst + 1) <= 15 &&
  635. bit_alloc(s, bap1, encoded_exp, exp_strategy, frame_bits,
  636. csnroffst, fsnroffst + 1) >= 0) {
  637. fsnroffst++;
  638. memcpy(bap, bap1, sizeof(bap1));
  639. }
  640. s->csnroffst = csnroffst;
  641. for(ch=0;ch<s->nb_all_channels;ch++)
  642. s->fsnroffst[ch] = fsnroffst;
  643. #if defined(DEBUG_BITALLOC)
  644. {
  645. int j;
  646. for(i=0;i<6;i++) {
  647. for(ch=0;ch<s->nb_all_channels;ch++) {
  648. printf("Block #%d Ch%d:\n", i, ch);
  649. printf("bap=");
  650. for(j=0;j<s->nb_coefs[ch];j++) {
  651. printf("%d ",bap[i][ch][j]);
  652. }
  653. printf("\n");
  654. }
  655. }
  656. }
  657. #endif
  658. return 0;
  659. }
  660. void ac3_common_init(void)
  661. {
  662. int i, j, k, l, v;
  663. /* compute bndtab and masktab from bandsz */
  664. k = 0;
  665. l = 0;
  666. for(i=0;i<50;i++) {
  667. bndtab[i] = l;
  668. v = bndsz[i];
  669. for(j=0;j<v;j++) masktab[k++]=i;
  670. l += v;
  671. }
  672. bndtab[50] = l;
  673. }
  674. static int AC3_encode_init(AVCodecContext *avctx)
  675. {
  676. int freq = avctx->sample_rate;
  677. int bitrate = avctx->bit_rate;
  678. int channels = avctx->channels;
  679. AC3EncodeContext *s = avctx->priv_data;
  680. int i, j, ch;
  681. float alpha;
  682. static const uint8_t acmod_defs[6] = {
  683. 0x01, /* C */
  684. 0x02, /* L R */
  685. 0x03, /* L C R */
  686. 0x06, /* L R SL SR */
  687. 0x07, /* L C R SL SR */
  688. 0x07, /* L C R SL SR (+LFE) */
  689. };
  690. avctx->frame_size = AC3_FRAME_SIZE;
  691. /* number of channels */
  692. if (channels < 1 || channels > 6)
  693. return -1;
  694. s->acmod = acmod_defs[channels - 1];
  695. s->lfe = (channels == 6) ? 1 : 0;
  696. s->nb_all_channels = channels;
  697. s->nb_channels = channels > 5 ? 5 : channels;
  698. s->lfe_channel = s->lfe ? 5 : -1;
  699. /* frequency */
  700. for(i=0;i<3;i++) {
  701. for(j=0;j<3;j++)
  702. if ((ac3_freqs[j] >> i) == freq)
  703. goto found;
  704. }
  705. return -1;
  706. found:
  707. s->sample_rate = freq;
  708. s->halfratecod = i;
  709. s->fscod = j;
  710. s->bsid = 8 + s->halfratecod;
  711. s->bsmod = 0; /* complete main audio service */
  712. /* bitrate & frame size */
  713. bitrate /= 1000;
  714. for(i=0;i<19;i++) {
  715. if ((ac3_bitratetab[i] >> s->halfratecod) == bitrate)
  716. break;
  717. }
  718. if (i == 19)
  719. return -1;
  720. s->bit_rate = bitrate;
  721. s->frmsizecod = i << 1;
  722. s->frame_size_min = (bitrate * 1000 * AC3_FRAME_SIZE) / (freq * 16);
  723. s->bits_written = 0;
  724. s->samples_written = 0;
  725. s->frame_size = s->frame_size_min;
  726. /* bit allocation init */
  727. for(ch=0;ch<s->nb_channels;ch++) {
  728. /* bandwidth for each channel */
  729. /* XXX: should compute the bandwidth according to the frame
  730. size, so that we avoid anoying high freq artefacts */
  731. s->chbwcod[ch] = 50; /* sample bandwidth as mpeg audio layer 2 table 0 */
  732. s->nb_coefs[ch] = ((s->chbwcod[ch] + 12) * 3) + 37;
  733. }
  734. if (s->lfe) {
  735. s->nb_coefs[s->lfe_channel] = 7; /* fixed */
  736. }
  737. /* initial snr offset */
  738. s->csnroffst = 40;
  739. ac3_common_init();
  740. /* mdct init */
  741. fft_init(MDCT_NBITS - 2);
  742. for(i=0;i<N/4;i++) {
  743. alpha = 2 * M_PI * (i + 1.0 / 8.0) / (float)N;
  744. xcos1[i] = fix15(-cos(alpha));
  745. xsin1[i] = fix15(-sin(alpha));
  746. }
  747. avctx->coded_frame= avcodec_alloc_frame();
  748. avctx->coded_frame->key_frame= 1;
  749. return 0;
  750. }
  751. /* output the AC3 frame header */
  752. static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
  753. {
  754. init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
  755. put_bits(&s->pb, 16, 0x0b77); /* frame header */
  756. put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
  757. put_bits(&s->pb, 2, s->fscod);
  758. put_bits(&s->pb, 6, s->frmsizecod + (s->frame_size - s->frame_size_min));
  759. put_bits(&s->pb, 5, s->bsid);
  760. put_bits(&s->pb, 3, s->bsmod);
  761. put_bits(&s->pb, 3, s->acmod);
  762. if ((s->acmod & 0x01) && s->acmod != 0x01)
  763. put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
  764. if (s->acmod & 0x04)
  765. put_bits(&s->pb, 2, 1); /* XXX -6 dB */
  766. if (s->acmod == 0x02)
  767. put_bits(&s->pb, 2, 0); /* surround not indicated */
  768. put_bits(&s->pb, 1, s->lfe); /* LFE */
  769. put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
  770. put_bits(&s->pb, 1, 0); /* no compression control word */
  771. put_bits(&s->pb, 1, 0); /* no lang code */
  772. put_bits(&s->pb, 1, 0); /* no audio production info */
  773. put_bits(&s->pb, 1, 0); /* no copyright */
  774. put_bits(&s->pb, 1, 1); /* original bitstream */
  775. put_bits(&s->pb, 1, 0); /* no time code 1 */
  776. put_bits(&s->pb, 1, 0); /* no time code 2 */
  777. put_bits(&s->pb, 1, 0); /* no addtional bit stream info */
  778. }
  779. /* symetric quantization on 'levels' levels */
  780. static inline int sym_quant(int c, int e, int levels)
  781. {
  782. int v;
  783. if (c >= 0) {
  784. v = (levels * (c << e)) >> 24;
  785. v = (v + 1) >> 1;
  786. v = (levels >> 1) + v;
  787. } else {
  788. v = (levels * ((-c) << e)) >> 24;
  789. v = (v + 1) >> 1;
  790. v = (levels >> 1) - v;
  791. }
  792. assert (v >= 0 && v < levels);
  793. return v;
  794. }
  795. /* asymetric quantization on 2^qbits levels */
  796. static inline int asym_quant(int c, int e, int qbits)
  797. {
  798. int lshift, m, v;
  799. lshift = e + qbits - 24;
  800. if (lshift >= 0)
  801. v = c << lshift;
  802. else
  803. v = c >> (-lshift);
  804. /* rounding */
  805. v = (v + 1) >> 1;
  806. m = (1 << (qbits-1));
  807. if (v >= m)
  808. v = m - 1;
  809. assert(v >= -m);
  810. return v & ((1 << qbits)-1);
  811. }
  812. /* Output one audio block. There are NB_BLOCKS audio blocks in one AC3
  813. frame */
  814. static void output_audio_block(AC3EncodeContext *s,
  815. uint8_t exp_strategy[AC3_MAX_CHANNELS],
  816. uint8_t encoded_exp[AC3_MAX_CHANNELS][N/2],
  817. uint8_t bap[AC3_MAX_CHANNELS][N/2],
  818. int32_t mdct_coefs[AC3_MAX_CHANNELS][N/2],
  819. int8_t global_exp[AC3_MAX_CHANNELS],
  820. int block_num)
  821. {
  822. int ch, nb_groups, group_size, i, baie, rbnd;
  823. uint8_t *p;
  824. uint16_t qmant[AC3_MAX_CHANNELS][N/2];
  825. int exp0, exp1;
  826. int mant1_cnt, mant2_cnt, mant4_cnt;
  827. uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
  828. int delta0, delta1, delta2;
  829. for(ch=0;ch<s->nb_channels;ch++)
  830. put_bits(&s->pb, 1, 0); /* 512 point MDCT */
  831. for(ch=0;ch<s->nb_channels;ch++)
  832. put_bits(&s->pb, 1, 1); /* no dither */
  833. put_bits(&s->pb, 1, 0); /* no dynamic range */
  834. if (block_num == 0) {
  835. /* for block 0, even if no coupling, we must say it. This is a
  836. waste of bit :-) */
  837. put_bits(&s->pb, 1, 1); /* coupling strategy present */
  838. put_bits(&s->pb, 1, 0); /* no coupling strategy */
  839. } else {
  840. put_bits(&s->pb, 1, 0); /* no new coupling strategy */
  841. }
  842. if (s->acmod == 2)
  843. {
  844. if(block_num==0)
  845. {
  846. /* first block must define rematrixing (rematstr) */
  847. put_bits(&s->pb, 1, 1);
  848. /* dummy rematrixing rematflg(1:4)=0 */
  849. for (rbnd=0;rbnd<4;rbnd++)
  850. put_bits(&s->pb, 1, 0);
  851. }
  852. else
  853. {
  854. /* no matrixing (but should be used in the future) */
  855. put_bits(&s->pb, 1, 0);
  856. }
  857. }
  858. #if defined(DEBUG)
  859. {
  860. static int count = 0;
  861. av_log(NULL, AV_LOG_DEBUG, "Block #%d (%d)\n", block_num, count++);
  862. }
  863. #endif
  864. /* exponent strategy */
  865. for(ch=0;ch<s->nb_channels;ch++) {
  866. put_bits(&s->pb, 2, exp_strategy[ch]);
  867. }
  868. if (s->lfe) {
  869. put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
  870. }
  871. for(ch=0;ch<s->nb_channels;ch++) {
  872. if (exp_strategy[ch] != EXP_REUSE)
  873. put_bits(&s->pb, 6, s->chbwcod[ch]);
  874. }
  875. /* exponents */
  876. for (ch = 0; ch < s->nb_all_channels; ch++) {
  877. switch(exp_strategy[ch]) {
  878. case EXP_REUSE:
  879. continue;
  880. case EXP_D15:
  881. group_size = 1;
  882. break;
  883. case EXP_D25:
  884. group_size = 2;
  885. break;
  886. default:
  887. case EXP_D45:
  888. group_size = 4;
  889. break;
  890. }
  891. nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
  892. p = encoded_exp[ch];
  893. /* first exponent */
  894. exp1 = *p++;
  895. put_bits(&s->pb, 4, exp1);
  896. /* next ones are delta encoded */
  897. for(i=0;i<nb_groups;i++) {
  898. /* merge three delta in one code */
  899. exp0 = exp1;
  900. exp1 = p[0];
  901. p += group_size;
  902. delta0 = exp1 - exp0 + 2;
  903. exp0 = exp1;
  904. exp1 = p[0];
  905. p += group_size;
  906. delta1 = exp1 - exp0 + 2;
  907. exp0 = exp1;
  908. exp1 = p[0];
  909. p += group_size;
  910. delta2 = exp1 - exp0 + 2;
  911. put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
  912. }
  913. if (ch != s->lfe_channel)
  914. put_bits(&s->pb, 2, 0); /* no gain range info */
  915. }
  916. /* bit allocation info */
  917. baie = (block_num == 0);
  918. put_bits(&s->pb, 1, baie);
  919. if (baie) {
  920. put_bits(&s->pb, 2, s->sdecaycod);
  921. put_bits(&s->pb, 2, s->fdecaycod);
  922. put_bits(&s->pb, 2, s->sgaincod);
  923. put_bits(&s->pb, 2, s->dbkneecod);
  924. put_bits(&s->pb, 3, s->floorcod);
  925. }
  926. /* snr offset */
  927. put_bits(&s->pb, 1, baie); /* always present with bai */
  928. if (baie) {
  929. put_bits(&s->pb, 6, s->csnroffst);
  930. for(ch=0;ch<s->nb_all_channels;ch++) {
  931. put_bits(&s->pb, 4, s->fsnroffst[ch]);
  932. put_bits(&s->pb, 3, s->fgaincod[ch]);
  933. }
  934. }
  935. put_bits(&s->pb, 1, 0); /* no delta bit allocation */
  936. put_bits(&s->pb, 1, 0); /* no data to skip */
  937. /* mantissa encoding : we use two passes to handle the grouping. A
  938. one pass method may be faster, but it would necessitate to
  939. modify the output stream. */
  940. /* first pass: quantize */
  941. mant1_cnt = mant2_cnt = mant4_cnt = 0;
  942. qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
  943. for (ch = 0; ch < s->nb_all_channels; ch++) {
  944. int b, c, e, v;
  945. for(i=0;i<s->nb_coefs[ch];i++) {
  946. c = mdct_coefs[ch][i];
  947. e = encoded_exp[ch][i] - global_exp[ch];
  948. b = bap[ch][i];
  949. switch(b) {
  950. case 0:
  951. v = 0;
  952. break;
  953. case 1:
  954. v = sym_quant(c, e, 3);
  955. switch(mant1_cnt) {
  956. case 0:
  957. qmant1_ptr = &qmant[ch][i];
  958. v = 9 * v;
  959. mant1_cnt = 1;
  960. break;
  961. case 1:
  962. *qmant1_ptr += 3 * v;
  963. mant1_cnt = 2;
  964. v = 128;
  965. break;
  966. default:
  967. *qmant1_ptr += v;
  968. mant1_cnt = 0;
  969. v = 128;
  970. break;
  971. }
  972. break;
  973. case 2:
  974. v = sym_quant(c, e, 5);
  975. switch(mant2_cnt) {
  976. case 0:
  977. qmant2_ptr = &qmant[ch][i];
  978. v = 25 * v;
  979. mant2_cnt = 1;
  980. break;
  981. case 1:
  982. *qmant2_ptr += 5 * v;
  983. mant2_cnt = 2;
  984. v = 128;
  985. break;
  986. default:
  987. *qmant2_ptr += v;
  988. mant2_cnt = 0;
  989. v = 128;
  990. break;
  991. }
  992. break;
  993. case 3:
  994. v = sym_quant(c, e, 7);
  995. break;
  996. case 4:
  997. v = sym_quant(c, e, 11);
  998. switch(mant4_cnt) {
  999. case 0:
  1000. qmant4_ptr = &qmant[ch][i];
  1001. v = 11 * v;
  1002. mant4_cnt = 1;
  1003. break;
  1004. default:
  1005. *qmant4_ptr += v;
  1006. mant4_cnt = 0;
  1007. v = 128;
  1008. break;
  1009. }
  1010. break;
  1011. case 5:
  1012. v = sym_quant(c, e, 15);
  1013. break;
  1014. case 14:
  1015. v = asym_quant(c, e, 14);
  1016. break;
  1017. case 15:
  1018. v = asym_quant(c, e, 16);
  1019. break;
  1020. default:
  1021. v = asym_quant(c, e, b - 1);
  1022. break;
  1023. }
  1024. qmant[ch][i] = v;
  1025. }
  1026. }
  1027. /* second pass : output the values */
  1028. for (ch = 0; ch < s->nb_all_channels; ch++) {
  1029. int b, q;
  1030. for(i=0;i<s->nb_coefs[ch];i++) {
  1031. q = qmant[ch][i];
  1032. b = bap[ch][i];
  1033. switch(b) {
  1034. case 0:
  1035. break;
  1036. case 1:
  1037. if (q != 128)
  1038. put_bits(&s->pb, 5, q);
  1039. break;
  1040. case 2:
  1041. if (q != 128)
  1042. put_bits(&s->pb, 7, q);
  1043. break;
  1044. case 3:
  1045. put_bits(&s->pb, 3, q);
  1046. break;
  1047. case 4:
  1048. if (q != 128)
  1049. put_bits(&s->pb, 7, q);
  1050. break;
  1051. case 14:
  1052. put_bits(&s->pb, 14, q);
  1053. break;
  1054. case 15:
  1055. put_bits(&s->pb, 16, q);
  1056. break;
  1057. default:
  1058. put_bits(&s->pb, b - 1, q);
  1059. break;
  1060. }
  1061. }
  1062. }
  1063. }
  1064. #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
  1065. static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
  1066. {
  1067. unsigned int c;
  1068. c = 0;
  1069. while (a) {
  1070. if (a & 1)
  1071. c ^= b;
  1072. a = a >> 1;
  1073. b = b << 1;
  1074. if (b & (1 << 16))
  1075. b ^= poly;
  1076. }
  1077. return c;
  1078. }
  1079. static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
  1080. {
  1081. unsigned int r;
  1082. r = 1;
  1083. while (n) {
  1084. if (n & 1)
  1085. r = mul_poly(r, a, poly);
  1086. a = mul_poly(a, a, poly);
  1087. n >>= 1;
  1088. }
  1089. return r;
  1090. }
  1091. /* compute log2(max(abs(tab[]))) */
  1092. static int log2_tab(int16_t *tab, int n)
  1093. {
  1094. int i, v;
  1095. v = 0;
  1096. for(i=0;i<n;i++) {
  1097. v |= abs(tab[i]);
  1098. }
  1099. return av_log2(v);
  1100. }
  1101. static void lshift_tab(int16_t *tab, int n, int lshift)
  1102. {
  1103. int i;
  1104. if (lshift > 0) {
  1105. for(i=0;i<n;i++) {
  1106. tab[i] <<= lshift;
  1107. }
  1108. } else if (lshift < 0) {
  1109. lshift = -lshift;
  1110. for(i=0;i<n;i++) {
  1111. tab[i] >>= lshift;
  1112. }
  1113. }
  1114. }
  1115. /* fill the end of the frame and compute the two crcs */
  1116. static int output_frame_end(AC3EncodeContext *s)
  1117. {
  1118. int frame_size, frame_size_58, n, crc1, crc2, crc_inv;
  1119. uint8_t *frame;
  1120. frame_size = s->frame_size; /* frame size in words */
  1121. /* align to 8 bits */
  1122. flush_put_bits(&s->pb);
  1123. /* add zero bytes to reach the frame size */
  1124. frame = s->pb.buf;
  1125. n = 2 * s->frame_size - (pbBufPtr(&s->pb) - frame) - 2;
  1126. assert(n >= 0);
  1127. if(n>0)
  1128. memset(pbBufPtr(&s->pb), 0, n);
  1129. /* Now we must compute both crcs : this is not so easy for crc1
  1130. because it is at the beginning of the data... */
  1131. frame_size_58 = (frame_size >> 1) + (frame_size >> 3);
  1132. crc1 = bswap_16(av_crc(av_crc8005, 0, frame + 4, 2 * frame_size_58 - 4));
  1133. /* XXX: could precompute crc_inv */
  1134. crc_inv = pow_poly((CRC16_POLY >> 1), (16 * frame_size_58) - 16, CRC16_POLY);
  1135. crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
  1136. frame[2] = crc1 >> 8;
  1137. frame[3] = crc1;
  1138. crc2 = bswap_16(av_crc(av_crc8005, 0, frame + 2 * frame_size_58, (frame_size - frame_size_58) * 2 - 2));
  1139. frame[2*frame_size - 2] = crc2 >> 8;
  1140. frame[2*frame_size - 1] = crc2;
  1141. // printf("n=%d frame_size=%d\n", n, frame_size);
  1142. return frame_size * 2;
  1143. }
  1144. static int AC3_encode_frame(AVCodecContext *avctx,
  1145. unsigned char *frame, int buf_size, void *data)
  1146. {
  1147. AC3EncodeContext *s = avctx->priv_data;
  1148. int16_t *samples = data;
  1149. int i, j, k, v, ch;
  1150. int16_t input_samples[N];
  1151. int32_t mdct_coef[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
  1152. uint8_t exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
  1153. uint8_t exp_strategy[NB_BLOCKS][AC3_MAX_CHANNELS];
  1154. uint8_t encoded_exp[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
  1155. uint8_t bap[NB_BLOCKS][AC3_MAX_CHANNELS][N/2];
  1156. int8_t exp_samples[NB_BLOCKS][AC3_MAX_CHANNELS];
  1157. int frame_bits;
  1158. frame_bits = 0;
  1159. for(ch=0;ch<s->nb_all_channels;ch++) {
  1160. /* fixed mdct to the six sub blocks & exponent computation */
  1161. for(i=0;i<NB_BLOCKS;i++) {
  1162. int16_t *sptr;
  1163. int sinc;
  1164. /* compute input samples */
  1165. memcpy(input_samples, s->last_samples[ch], N/2 * sizeof(int16_t));
  1166. sinc = s->nb_all_channels;
  1167. sptr = samples + (sinc * (N/2) * i) + ch;
  1168. for(j=0;j<N/2;j++) {
  1169. v = *sptr;
  1170. input_samples[j + N/2] = v;
  1171. s->last_samples[ch][j] = v;
  1172. sptr += sinc;
  1173. }
  1174. /* apply the MDCT window */
  1175. for(j=0;j<N/2;j++) {
  1176. input_samples[j] = MUL16(input_samples[j],
  1177. ac3_window[j]) >> 15;
  1178. input_samples[N-j-1] = MUL16(input_samples[N-j-1],
  1179. ac3_window[j]) >> 15;
  1180. }
  1181. /* Normalize the samples to use the maximum available
  1182. precision */
  1183. v = 14 - log2_tab(input_samples, N);
  1184. if (v < 0)
  1185. v = 0;
  1186. exp_samples[i][ch] = v - 10;
  1187. lshift_tab(input_samples, N, v);
  1188. /* do the MDCT */
  1189. mdct512(mdct_coef[i][ch], input_samples);
  1190. /* compute "exponents". We take into account the
  1191. normalization there */
  1192. for(j=0;j<N/2;j++) {
  1193. int e;
  1194. v = abs(mdct_coef[i][ch][j]);
  1195. if (v == 0)
  1196. e = 24;
  1197. else {
  1198. e = 23 - av_log2(v) + exp_samples[i][ch];
  1199. if (e >= 24) {
  1200. e = 24;
  1201. mdct_coef[i][ch][j] = 0;
  1202. }
  1203. }
  1204. exp[i][ch][j] = e;
  1205. }
  1206. }
  1207. compute_exp_strategy(exp_strategy, exp, ch, ch == s->lfe_channel);
  1208. /* compute the exponents as the decoder will see them. The
  1209. EXP_REUSE case must be handled carefully : we select the
  1210. min of the exponents */
  1211. i = 0;
  1212. while (i < NB_BLOCKS) {
  1213. j = i + 1;
  1214. while (j < NB_BLOCKS && exp_strategy[j][ch] == EXP_REUSE) {
  1215. exponent_min(exp[i][ch], exp[j][ch], s->nb_coefs[ch]);
  1216. j++;
  1217. }
  1218. frame_bits += encode_exp(encoded_exp[i][ch],
  1219. exp[i][ch], s->nb_coefs[ch],
  1220. exp_strategy[i][ch]);
  1221. /* copy encoded exponents for reuse case */
  1222. for(k=i+1;k<j;k++) {
  1223. memcpy(encoded_exp[k][ch], encoded_exp[i][ch],
  1224. s->nb_coefs[ch] * sizeof(uint8_t));
  1225. }
  1226. i = j;
  1227. }
  1228. }
  1229. /* adjust for fractional frame sizes */
  1230. while(s->bits_written >= s->bit_rate*1000 && s->samples_written >= s->sample_rate) {
  1231. s->bits_written -= s->bit_rate*1000;
  1232. s->samples_written -= s->sample_rate;
  1233. }
  1234. s->frame_size = s->frame_size_min + (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate*1000);
  1235. s->bits_written += s->frame_size * 16;
  1236. s->samples_written += AC3_FRAME_SIZE;
  1237. compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
  1238. /* everything is known... let's output the frame */
  1239. output_frame_header(s, frame);
  1240. for(i=0;i<NB_BLOCKS;i++) {
  1241. output_audio_block(s, exp_strategy[i], encoded_exp[i],
  1242. bap[i], mdct_coef[i], exp_samples[i], i);
  1243. }
  1244. return output_frame_end(s);
  1245. }
  1246. static int AC3_encode_close(AVCodecContext *avctx)
  1247. {
  1248. av_freep(&avctx->coded_frame);
  1249. return 0;
  1250. }
  1251. #if 0
  1252. /*************************************************************************/
  1253. /* TEST */
  1254. #define FN (N/4)
  1255. void fft_test(void)
  1256. {
  1257. IComplex in[FN], in1[FN];
  1258. int k, n, i;
  1259. float sum_re, sum_im, a;
  1260. /* FFT test */
  1261. for(i=0;i<FN;i++) {
  1262. in[i].re = random() % 65535 - 32767;
  1263. in[i].im = random() % 65535 - 32767;
  1264. in1[i] = in[i];
  1265. }
  1266. fft(in, 7);
  1267. /* do it by hand */
  1268. for(k=0;k<FN;k++) {
  1269. sum_re = 0;
  1270. sum_im = 0;
  1271. for(n=0;n<FN;n++) {
  1272. a = -2 * M_PI * (n * k) / FN;
  1273. sum_re += in1[n].re * cos(a) - in1[n].im * sin(a);
  1274. sum_im += in1[n].re * sin(a) + in1[n].im * cos(a);
  1275. }
  1276. printf("%3d: %6d,%6d %6.0f,%6.0f\n",
  1277. k, in[k].re, in[k].im, sum_re / FN, sum_im / FN);
  1278. }
  1279. }
  1280. void mdct_test(void)
  1281. {
  1282. int16_t input[N];
  1283. int32_t output[N/2];
  1284. float input1[N];
  1285. float output1[N/2];
  1286. float s, a, err, e, emax;
  1287. int i, k, n;
  1288. for(i=0;i<N;i++) {
  1289. input[i] = (random() % 65535 - 32767) * 9 / 10;
  1290. input1[i] = input[i];
  1291. }
  1292. mdct512(output, input);
  1293. /* do it by hand */
  1294. for(k=0;k<N/2;k++) {
  1295. s = 0;
  1296. for(n=0;n<N;n++) {
  1297. a = (2*M_PI*(2*n+1+N/2)*(2*k+1) / (4 * N));
  1298. s += input1[n] * cos(a);
  1299. }
  1300. output1[k] = -2 * s / N;
  1301. }
  1302. err = 0;
  1303. emax = 0;
  1304. for(i=0;i<N/2;i++) {
  1305. printf("%3d: %7d %7.0f\n", i, output[i], output1[i]);
  1306. e = output[i] - output1[i];
  1307. if (e > emax)
  1308. emax = e;
  1309. err += e * e;
  1310. }
  1311. printf("err2=%f emax=%f\n", err / (N/2), emax);
  1312. }
  1313. void test_ac3(void)
  1314. {
  1315. AC3EncodeContext ctx;
  1316. unsigned char frame[AC3_MAX_CODED_FRAME_SIZE];
  1317. short samples[AC3_FRAME_SIZE];
  1318. int ret, i;
  1319. AC3_encode_init(&ctx, 44100, 64000, 1);
  1320. fft_test();
  1321. mdct_test();
  1322. for(i=0;i<AC3_FRAME_SIZE;i++)
  1323. samples[i] = (int)(sin(2*M_PI*i*1000.0/44100) * 10000);
  1324. ret = AC3_encode_frame(&ctx, frame, samples);
  1325. printf("ret=%d\n", ret);
  1326. }
  1327. #endif
  1328. AVCodec ac3_encoder = {
  1329. "ac3",
  1330. CODEC_TYPE_AUDIO,
  1331. CODEC_ID_AC3,
  1332. sizeof(AC3EncodeContext),
  1333. AC3_encode_init,
  1334. AC3_encode_frame,
  1335. AC3_encode_close,
  1336. NULL,
  1337. };