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.

1583 lines
43KB

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