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.

1558 lines
43KB

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