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.

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