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.

1140 lines
38KB

  1. /*
  2. * AC-3 Audio Decoder
  3. * This code is developed as part of Google Summer of Code 2006 Program.
  4. *
  5. * Copyright (c) 2006 Kartikey Mahendra BHATT (bhattkm at gmail dot com).
  6. * Copyright (c) 2007 Justin Ruggles
  7. *
  8. * Portions of this code are derived from liba52
  9. * http://liba52.sourceforge.net
  10. * Copyright (C) 2000-2003 Michel Lespinasse <walken@zoy.org>
  11. * Copyright (C) 1999-2000 Aaron Holtzman <aholtzma@ess.engr.uvic.ca>
  12. *
  13. * This file is part of FFmpeg.
  14. *
  15. * FFmpeg is free software; you can redistribute it and/or
  16. * modify it under the terms of the GNU General Public
  17. * License as published by the Free Software Foundation; either
  18. * version 2 of the License, or (at your option) any later version.
  19. *
  20. * FFmpeg is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  23. * General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU General Public
  26. * License along with FFmpeg; if not, write to the Free Software
  27. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  28. */
  29. #include <stdio.h>
  30. #include <stddef.h>
  31. #include <math.h>
  32. #include <string.h>
  33. #include "avcodec.h"
  34. #include "ac3_parser.h"
  35. #include "bitstream.h"
  36. #include "dsputil.h"
  37. #include "random.h"
  38. /**
  39. * Table of bin locations for rematrixing bands
  40. * reference: Section 7.5.2 Rematrixing : Frequency Band Definitions
  41. */
  42. static const uint8_t rematrix_band_tbl[5] = { 13, 25, 37, 61, 253 };
  43. /* table for exponent to scale_factor mapping
  44. * scale_factor[i] = 2 ^ -(i + 15)
  45. */
  46. static float scale_factors[25];
  47. /** table for grouping exponents */
  48. static uint8_t exp_ungroup_tbl[128][3];
  49. static int16_t l3_quantizers_1[32];
  50. static int16_t l3_quantizers_2[32];
  51. static int16_t l3_quantizers_3[32];
  52. static int16_t l5_quantizers_1[128];
  53. static int16_t l5_quantizers_2[128];
  54. static int16_t l5_quantizers_3[128];
  55. static int16_t l7_quantizers[7];
  56. static int16_t l11_quantizers_1[128];
  57. static int16_t l11_quantizers_2[128];
  58. static int16_t l15_quantizers[15];
  59. static const uint8_t qntztab[16] = { 0, 5, 7, 3, 7, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16 };
  60. /* Adjustmens in dB gain */
  61. #define LEVEL_MINUS_3DB 0.7071067811865476
  62. #define LEVEL_MINUS_4POINT5DB 0.5946035575013605
  63. #define LEVEL_MINUS_6DB 0.5000000000000000
  64. #define LEVEL_PLUS_3DB 1.4142135623730951
  65. #define LEVEL_PLUS_6DB 2.0000000000000000
  66. #define LEVEL_ZERO 0.0000000000000000
  67. static const float clevs[4] = { LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB,
  68. LEVEL_MINUS_6DB, LEVEL_MINUS_4POINT5DB };
  69. static const float slevs[4] = { LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO, LEVEL_MINUS_6DB };
  70. #define AC3_OUTPUT_LFEON 8
  71. typedef struct {
  72. int acmod;
  73. int cmixlev;
  74. int surmixlev;
  75. int dsurmod;
  76. int blksw[AC3_MAX_CHANNELS];
  77. int dithflag[AC3_MAX_CHANNELS];
  78. int cplinu;
  79. int chincpl[AC3_MAX_CHANNELS];
  80. int phsflginu;
  81. int cplcoe;
  82. uint32_t cplbndstrc;
  83. int rematstr;
  84. int nrematbnd;
  85. int rematflg[AC3_MAX_CHANNELS];
  86. int cplexpstr;
  87. int lfeexpstr;
  88. int chexpstr[5];
  89. int cplsnroffst;
  90. int cplfgain;
  91. int snroffst[5];
  92. int fgain[5];
  93. int lfesnroffst;
  94. int lfefgain;
  95. int cpldeltbae;
  96. int deltbae[5];
  97. int cpldeltnseg;
  98. uint8_t cpldeltoffst[8];
  99. uint8_t cpldeltlen[8];
  100. uint8_t cpldeltba[8];
  101. int deltnseg[5];
  102. uint8_t deltoffst[5][8];
  103. uint8_t deltlen[5][8];
  104. uint8_t deltba[5][8];
  105. /* Derived Attributes. */
  106. int sampling_rate;
  107. int bit_rate;
  108. int frame_size;
  109. int nchans; //number of total channels
  110. int nfchans; //number of full-bandwidth channels
  111. int lfeon; //lfe channel in use
  112. int output_mode; ///< output channel configuration
  113. int out_channels; ///< number of output channels
  114. float dynrng; //dynamic range gain
  115. float dynrng2; //dynamic range gain for 1+1 mode
  116. float cplco[5][18]; //coupling coordinates
  117. int ncplbnd; //number of coupling bands
  118. int ncplsubnd; //number of coupling sub bands
  119. int cplstrtmant; //coupling start mantissa
  120. int cplendmant; //coupling end mantissa
  121. int endmant[5]; //channel end mantissas
  122. AC3BitAllocParameters bit_alloc_params; ///< bit allocation parameters
  123. int8_t dcplexps[256]; //decoded coupling exponents
  124. int8_t dexps[5][256]; //decoded fbw channel exponents
  125. int8_t dlfeexps[256]; //decoded lfe channel exponents
  126. uint8_t cplbap[256]; //coupling bit allocation pointers
  127. uint8_t bap[5][256]; //fbw channel bit allocation pointers
  128. uint8_t lfebap[256]; //lfe channel bit allocation pointers
  129. DECLARE_ALIGNED_16(float, transform_coeffs[AC3_MAX_CHANNELS][256]); //transform coefficients
  130. /* For IMDCT. */
  131. MDCTContext imdct_512; //for 512 sample imdct transform
  132. MDCTContext imdct_256; //for 256 sample imdct transform
  133. DSPContext dsp; //for optimization
  134. DECLARE_ALIGNED_16(float, output[AC3_MAX_CHANNELS][256]); //output after imdct transform and windowing
  135. DECLARE_ALIGNED_16(float, delay[AC3_MAX_CHANNELS][256]); //delay - added to the next block
  136. DECLARE_ALIGNED_16(float, tmp_imdct[256]); //temporary storage for imdct transform
  137. DECLARE_ALIGNED_16(float, tmp_output[512]); //temporary storage for output before windowing
  138. DECLARE_ALIGNED_16(float, window[256]); //window coefficients
  139. /* Miscellaneous. */
  140. GetBitContext gb;
  141. AVRandomState dith_state; //for dither generation
  142. } AC3DecodeContext;
  143. /*********** BEGIN INIT HELPER FUNCTIONS ***********/
  144. /**
  145. * Generate a Kaiser-Bessel Derived Window.
  146. */
  147. static void ac3_window_init(float *window)
  148. {
  149. int i, j;
  150. double sum = 0.0, bessel, tmp;
  151. double local_window[256];
  152. double alpha2 = (5.0 * M_PI / 256.0) * (5.0 * M_PI / 256.0);
  153. for (i = 0; i < 256; i++) {
  154. tmp = i * (256 - i) * alpha2;
  155. bessel = 1.0;
  156. for (j = 100; j > 0; j--) /* defaul to 100 iterations */
  157. bessel = bessel * tmp / (j * j) + 1;
  158. sum += bessel;
  159. local_window[i] = sum;
  160. }
  161. sum++;
  162. for (i = 0; i < 256; i++)
  163. window[i] = sqrt(local_window[i] / sum);
  164. }
  165. /*
  166. * Generate quantizer tables.
  167. */
  168. static void generate_quantizers_table(int16_t quantizers[], int level, int length)
  169. {
  170. int i;
  171. for (i = 0; i < length; i++)
  172. quantizers[i] = ((2 * i - level + 1) << 15) / level;
  173. }
  174. static void generate_quantizers_table_1(int16_t quantizers[], int level, int length1, int length2, int size)
  175. {
  176. int i, j;
  177. int16_t v;
  178. for (i = 0; i < length1; i++) {
  179. v = ((2 * i - level + 1) << 15) / level;
  180. for (j = 0; j < length2; j++)
  181. quantizers[i * length2 + j] = v;
  182. }
  183. for (i = length1 * length2; i < size; i++)
  184. quantizers[i] = 0;
  185. }
  186. static void generate_quantizers_table_2(int16_t quantizers[], int level, int length1, int length2, int size)
  187. {
  188. int i, j;
  189. int16_t v;
  190. for (i = 0; i < length1; i++) {
  191. v = ((2 * (i % level) - level + 1) << 15) / level;
  192. for (j = 0; j < length2; j++)
  193. quantizers[i * length2 + j] = v;
  194. }
  195. for (i = length1 * length2; i < size; i++)
  196. quantizers[i] = 0;
  197. }
  198. static void generate_quantizers_table_3(int16_t quantizers[], int level, int length1, int length2, int size)
  199. {
  200. int i, j;
  201. for (i = 0; i < length1; i++)
  202. for (j = 0; j < length2; j++)
  203. quantizers[i * length2 + j] = ((2 * (j % level) - level + 1) << 15) / level;
  204. for (i = length1 * length2; i < size; i++)
  205. quantizers[i] = 0;
  206. }
  207. /*
  208. * Initialize tables at runtime.
  209. */
  210. static void ac3_tables_init(void)
  211. {
  212. int i;
  213. /* Quantizer ungrouping tables. */
  214. // for level-3 quantizers
  215. generate_quantizers_table_1(l3_quantizers_1, 3, 3, 9, 32);
  216. generate_quantizers_table_2(l3_quantizers_2, 3, 9, 3, 32);
  217. generate_quantizers_table_3(l3_quantizers_3, 3, 9, 3, 32);
  218. //for level-5 quantizers
  219. generate_quantizers_table_1(l5_quantizers_1, 5, 5, 25, 128);
  220. generate_quantizers_table_2(l5_quantizers_2, 5, 25, 5, 128);
  221. generate_quantizers_table_3(l5_quantizers_3, 5, 25, 5, 128);
  222. //for level-7 quantizers
  223. generate_quantizers_table(l7_quantizers, 7, 7);
  224. //for level-4 quantizers
  225. generate_quantizers_table_2(l11_quantizers_1, 11, 11, 11, 128);
  226. generate_quantizers_table_3(l11_quantizers_2, 11, 11, 11, 128);
  227. //for level-15 quantizers
  228. generate_quantizers_table(l15_quantizers, 15, 15);
  229. /* End Quantizer ungrouping tables. */
  230. //generate scale factors
  231. for (i = 0; i < 25; i++)
  232. scale_factors[i] = pow(2.0, -(i + 15));
  233. /* generate exponent tables
  234. reference: Section 7.1.3 Exponent Decoding */
  235. for(i=0; i<128; i++) {
  236. exp_ungroup_tbl[i][0] = i / 25;
  237. exp_ungroup_tbl[i][1] = (i % 25) / 5;
  238. exp_ungroup_tbl[i][2] = (i % 25) % 5;
  239. }
  240. }
  241. static int ac3_decode_init(AVCodecContext *avctx)
  242. {
  243. AC3DecodeContext *ctx = avctx->priv_data;
  244. ac3_common_init();
  245. ac3_tables_init();
  246. ff_mdct_init(&ctx->imdct_256, 8, 1);
  247. ff_mdct_init(&ctx->imdct_512, 9, 1);
  248. ac3_window_init(ctx->window);
  249. dsputil_init(&ctx->dsp, avctx);
  250. av_init_random(0, &ctx->dith_state);
  251. return 0;
  252. }
  253. /*********** END INIT FUNCTIONS ***********/
  254. /**
  255. * Parses the 'sync info' and 'bit stream info' from the AC-3 bitstream.
  256. * GetBitContext within AC3DecodeContext must point to
  257. * start of the synchronized ac3 bitstream.
  258. */
  259. static int ac3_parse_header(AC3DecodeContext *ctx)
  260. {
  261. AC3HeaderInfo hdr;
  262. GetBitContext *gb = &ctx->gb;
  263. int err, i;
  264. err = ff_ac3_parse_header(gb->buffer, &hdr);
  265. if(err)
  266. return err;
  267. /* get decoding parameters from header info */
  268. ctx->bit_alloc_params.fscod = hdr.fscod;
  269. ctx->acmod = hdr.acmod;
  270. ctx->cmixlev = hdr.cmixlev;
  271. ctx->surmixlev = hdr.surmixlev;
  272. ctx->dsurmod = hdr.dsurmod;
  273. ctx->lfeon = hdr.lfeon;
  274. ctx->bit_alloc_params.halfratecod = hdr.halfratecod;
  275. ctx->sampling_rate = hdr.sample_rate;
  276. ctx->bit_rate = hdr.bit_rate;
  277. ctx->nchans = hdr.channels;
  278. ctx->nfchans = ctx->nchans - ctx->lfeon;
  279. ctx->frame_size = hdr.frame_size;
  280. /* set default output to all source channels */
  281. ctx->out_channels = ctx->nchans;
  282. ctx->output_mode = ctx->acmod;
  283. if(ctx->lfeon)
  284. ctx->output_mode |= AC3_OUTPUT_LFEON;
  285. /* skip over portion of header which has already been read */
  286. skip_bits(gb, 16); //skip the sync_word, sync_info->sync_word = get_bits(gb, 16);
  287. skip_bits(gb, 16); // skip crc1
  288. skip_bits(gb, 8); // skip fscod and frmsizecod
  289. skip_bits(gb, 11); // skip bsid, bsmod, and acmod
  290. if(ctx->acmod == AC3_ACMOD_STEREO) {
  291. skip_bits(gb, 2); // skip dsurmod
  292. } else {
  293. if((ctx->acmod & 1) && ctx->acmod != AC3_ACMOD_MONO)
  294. skip_bits(gb, 2); // skip cmixlev
  295. if(ctx->acmod & 4)
  296. skip_bits(gb, 2); // skip surmixlev
  297. }
  298. skip_bits1(gb); // skip lfeon
  299. /* read the rest of the bsi. read twice for dual mono mode. */
  300. i = !(ctx->acmod);
  301. do {
  302. skip_bits(gb, 5); //skip dialog normalization
  303. if (get_bits1(gb))
  304. skip_bits(gb, 8); //skip compression
  305. if (get_bits1(gb))
  306. skip_bits(gb, 8); //skip language code
  307. if (get_bits1(gb))
  308. skip_bits(gb, 7); //skip audio production information
  309. } while (i--);
  310. skip_bits(gb, 2); //skip copyright bit and original bitstream bit
  311. /* FIXME: read & use the xbsi1 downmix levels */
  312. if (get_bits1(gb))
  313. skip_bits(gb, 14); //skip timecode1
  314. if (get_bits1(gb))
  315. skip_bits(gb, 14); //skip timecode2
  316. if (get_bits1(gb)) {
  317. i = get_bits(gb, 6); //additional bsi length
  318. do {
  319. skip_bits(gb, 8);
  320. } while(i--);
  321. }
  322. return 0;
  323. }
  324. /**
  325. * Decodes the grouped exponents.
  326. * This function decodes the coded exponents according to exponent strategy
  327. * and stores them in the decoded exponents buffer.
  328. *
  329. * @param[in] gb GetBitContext which points to start of coded exponents
  330. * @param[in] expstr Exponent coding strategy
  331. * @param[in] ngrps Number of grouped exponents
  332. * @param[in] absexp Absolute exponent or DC exponent
  333. * @param[out] dexps Decoded exponents are stored in dexps
  334. */
  335. static void decode_exponents(GetBitContext *gb, int expstr, int ngrps,
  336. uint8_t absexp, int8_t *dexps)
  337. {
  338. int i, j, grp, grpsize;
  339. int dexp[256];
  340. int expacc, prevexp;
  341. /* unpack groups */
  342. grpsize = expstr + (expstr == EXP_D45);
  343. for(grp=0,i=0; grp<ngrps; grp++) {
  344. expacc = get_bits(gb, 7);
  345. dexp[i++] = exp_ungroup_tbl[expacc][0];
  346. dexp[i++] = exp_ungroup_tbl[expacc][1];
  347. dexp[i++] = exp_ungroup_tbl[expacc][2];
  348. }
  349. /* convert to absolute exps and expand groups */
  350. prevexp = absexp;
  351. for(i=0; i<ngrps*3; i++) {
  352. prevexp = av_clip(prevexp + dexp[i]-2, 0, 24);
  353. for(j=0; j<grpsize; j++) {
  354. dexps[(i*grpsize)+j] = prevexp;
  355. }
  356. }
  357. }
  358. typedef struct { /* grouped mantissas for 3-level 5-leve and 11-level quantization */
  359. int16_t l3_quantizers[3];
  360. int16_t l5_quantizers[3];
  361. int16_t l11_quantizers[2];
  362. int l3ptr;
  363. int l5ptr;
  364. int l11ptr;
  365. } mant_groups;
  366. /* Get the transform coefficients for coupling channel and uncouple channels.
  367. * The coupling transform coefficients starts at the the cplstrtmant, which is
  368. * equal to endmant[ch] for fbw channels. Hence we can uncouple channels before
  369. * getting transform coefficients for the channel.
  370. */
  371. static int get_transform_coeffs_cpling(AC3DecodeContext *ctx, mant_groups *m)
  372. {
  373. GetBitContext *gb = &ctx->gb;
  374. int ch, start, end, cplbndstrc, bnd, gcode, tbap;
  375. float cplcos[5], cplcoeff;
  376. uint8_t *exps = ctx->dcplexps;
  377. uint8_t *bap = ctx->cplbap;
  378. cplbndstrc = ctx->cplbndstrc;
  379. start = ctx->cplstrtmant;
  380. bnd = 0;
  381. while (start < ctx->cplendmant) {
  382. end = start + 12;
  383. while (cplbndstrc & 1) {
  384. end += 12;
  385. cplbndstrc >>= 1;
  386. }
  387. cplbndstrc >>= 1;
  388. for (ch = 0; ch < ctx->nfchans; ch++)
  389. cplcos[ch] = ctx->cplco[ch][bnd];
  390. bnd++;
  391. while (start < end) {
  392. tbap = bap[start];
  393. switch(tbap) {
  394. case 0:
  395. for (ch = 0; ch < ctx->nfchans; ch++)
  396. if (ctx->chincpl[ch]) {
  397. if (ctx->dithflag[ch]) {
  398. cplcoeff = (av_random(&ctx->dith_state) & 0xFFFF) * scale_factors[exps[start]];
  399. ctx->transform_coeffs[ch + 1][start] = cplcoeff * cplcos[ch] * LEVEL_MINUS_3DB;
  400. } else
  401. ctx->transform_coeffs[ch + 1][start] = 0;
  402. }
  403. start++;
  404. continue;
  405. case 1:
  406. if (m->l3ptr > 2) {
  407. gcode = get_bits(gb, 5);
  408. m->l3_quantizers[0] = l3_quantizers_1[gcode];
  409. m->l3_quantizers[1] = l3_quantizers_2[gcode];
  410. m->l3_quantizers[2] = l3_quantizers_3[gcode];
  411. m->l3ptr = 0;
  412. }
  413. cplcoeff = m->l3_quantizers[m->l3ptr++] * scale_factors[exps[start]];
  414. break;
  415. case 2:
  416. if (m->l5ptr > 2) {
  417. gcode = get_bits(gb, 7);
  418. m->l5_quantizers[0] = l5_quantizers_1[gcode];
  419. m->l5_quantizers[1] = l5_quantizers_2[gcode];
  420. m->l5_quantizers[2] = l5_quantizers_3[gcode];
  421. m->l5ptr = 0;
  422. }
  423. cplcoeff = m->l5_quantizers[m->l5ptr++] * scale_factors[exps[start]];
  424. break;
  425. case 3:
  426. cplcoeff = l7_quantizers[get_bits(gb, 3)] * scale_factors[exps[start]];
  427. break;
  428. case 4:
  429. if (m->l11ptr > 1) {
  430. gcode = get_bits(gb, 7);
  431. m->l11_quantizers[0] = l11_quantizers_1[gcode];
  432. m->l11_quantizers[1] = l11_quantizers_2[gcode];
  433. m->l11ptr = 0;
  434. }
  435. cplcoeff = m->l11_quantizers[m->l11ptr++] * scale_factors[exps[start]];
  436. break;
  437. case 5:
  438. cplcoeff = l15_quantizers[get_bits(gb, 4)] * scale_factors[exps[start]];
  439. break;
  440. default:
  441. cplcoeff = (get_sbits(gb, qntztab[tbap]) << (16 - qntztab[tbap])) * scale_factors[exps[start]];
  442. }
  443. for (ch = 0; ch < ctx->nfchans; ch++)
  444. if (ctx->chincpl[ch])
  445. ctx->transform_coeffs[ch + 1][start] = cplcoeff * cplcos[ch];
  446. start++;
  447. }
  448. }
  449. return 0;
  450. }
  451. /* Get the transform coefficients for particular channel */
  452. static int get_transform_coeffs_ch(AC3DecodeContext *ctx, int ch_index, mant_groups *m)
  453. {
  454. GetBitContext *gb = &ctx->gb;
  455. int i, gcode, tbap, dithflag, end;
  456. uint8_t *exps;
  457. uint8_t *bap;
  458. float *coeffs;
  459. if (ch_index != -1) { /* fbw channels */
  460. dithflag = ctx->dithflag[ch_index];
  461. exps = ctx->dexps[ch_index];
  462. bap = ctx->bap[ch_index];
  463. coeffs = ctx->transform_coeffs[ch_index + 1];
  464. end = ctx->endmant[ch_index];
  465. } else if (ch_index == -1) {
  466. dithflag = 0;
  467. exps = ctx->dlfeexps;
  468. bap = ctx->lfebap;
  469. coeffs = ctx->transform_coeffs[0];
  470. end = 7;
  471. }
  472. for (i = 0; i < end; i++) {
  473. tbap = bap[i];
  474. switch (tbap) {
  475. case 0:
  476. if (!dithflag) {
  477. coeffs[i] = 0;
  478. continue;
  479. }
  480. else {
  481. coeffs[i] = (av_random(&ctx->dith_state) & 0xFFFF) * scale_factors[exps[i]];
  482. coeffs[i] *= LEVEL_MINUS_3DB;
  483. continue;
  484. }
  485. case 1:
  486. if (m->l3ptr > 2) {
  487. gcode = get_bits(gb, 5);
  488. m->l3_quantizers[0] = l3_quantizers_1[gcode];
  489. m->l3_quantizers[1] = l3_quantizers_2[gcode];
  490. m->l3_quantizers[2] = l3_quantizers_3[gcode];
  491. m->l3ptr = 0;
  492. }
  493. coeffs[i] = m->l3_quantizers[m->l3ptr++] * scale_factors[exps[i]];
  494. continue;
  495. case 2:
  496. if (m->l5ptr > 2) {
  497. gcode = get_bits(gb, 7);
  498. m->l5_quantizers[0] = l5_quantizers_1[gcode];
  499. m->l5_quantizers[1] = l5_quantizers_2[gcode];
  500. m->l5_quantizers[2] = l5_quantizers_3[gcode];
  501. m->l5ptr = 0;
  502. }
  503. coeffs[i] = m->l5_quantizers[m->l5ptr++] * scale_factors[exps[i]];
  504. continue;
  505. case 3:
  506. coeffs[i] = l7_quantizers[get_bits(gb, 3)] * scale_factors[exps[i]];
  507. continue;
  508. case 4:
  509. if (m->l11ptr > 1) {
  510. gcode = get_bits(gb, 7);
  511. m->l11_quantizers[0] = l11_quantizers_1[gcode];
  512. m->l11_quantizers[1] = l11_quantizers_2[gcode];
  513. m->l11ptr = 0;
  514. }
  515. coeffs[i] = m->l11_quantizers[m->l11ptr++] * scale_factors[exps[i]];
  516. continue;
  517. case 5:
  518. coeffs[i] = l15_quantizers[get_bits(gb, 4)] * scale_factors[exps[i]];
  519. continue;
  520. default:
  521. coeffs[i] = (get_sbits(gb, qntztab[tbap]) << (16 - qntztab[tbap])) * scale_factors[exps[i]];
  522. continue;
  523. }
  524. }
  525. return 0;
  526. }
  527. /* Get the transform coefficients.
  528. * This function extracts the tranform coefficients form the ac3 bitstream.
  529. * This function is called after bit allocation is performed.
  530. */
  531. static int get_transform_coeffs(AC3DecodeContext * ctx)
  532. {
  533. int i, end;
  534. int got_cplchan = 0;
  535. mant_groups m;
  536. m.l3ptr = m.l5ptr = m.l11ptr = 3;
  537. for (i = 0; i < ctx->nfchans; i++) {
  538. /* transform coefficients for individual channel */
  539. if (get_transform_coeffs_ch(ctx, i, &m))
  540. return -1;
  541. /* tranform coefficients for coupling channels */
  542. if (ctx->chincpl[i]) {
  543. if (!got_cplchan) {
  544. if (get_transform_coeffs_cpling(ctx, &m)) {
  545. av_log(NULL, AV_LOG_ERROR, "error in decoupling channels\n");
  546. return -1;
  547. }
  548. got_cplchan = 1;
  549. }
  550. end = ctx->cplendmant;
  551. } else
  552. end = ctx->endmant[i];
  553. do
  554. ctx->transform_coeffs[i + 1][end] = 0;
  555. while(++end < 256);
  556. }
  557. if (ctx->lfeon) {
  558. if (get_transform_coeffs_ch(ctx, -1, &m))
  559. return -1;
  560. for (i = 7; i < 256; i++) {
  561. ctx->transform_coeffs[0][i] = 0;
  562. }
  563. }
  564. return 0;
  565. }
  566. /**
  567. * Performs stereo rematrixing.
  568. * reference: Section 7.5.4 Rematrixing : Decoding Technique
  569. */
  570. static void do_rematrixing(AC3DecodeContext *ctx)
  571. {
  572. int bnd, i;
  573. int end, bndend;
  574. float tmp0, tmp1;
  575. end = FFMIN(ctx->endmant[0], ctx->endmant[1]);
  576. for(bnd=0; bnd<ctx->nrematbnd; bnd++) {
  577. if(ctx->rematflg[bnd]) {
  578. bndend = FFMIN(end, rematrix_band_tbl[bnd+1]);
  579. for(i=rematrix_band_tbl[bnd]; i<bndend; i++) {
  580. tmp0 = ctx->transform_coeffs[1][i];
  581. tmp1 = ctx->transform_coeffs[2][i];
  582. ctx->transform_coeffs[1][i] = tmp0 + tmp1;
  583. ctx->transform_coeffs[2][i] = tmp0 - tmp1;
  584. }
  585. }
  586. }
  587. }
  588. /* This function performs the imdct on 256 sample transform
  589. * coefficients.
  590. */
  591. static void do_imdct_256(AC3DecodeContext *ctx, int chindex)
  592. {
  593. int i, k;
  594. DECLARE_ALIGNED_16(float, x[128]);
  595. FFTComplex z[2][64];
  596. float *o_ptr = ctx->tmp_output;
  597. for(i=0; i<2; i++) {
  598. /* de-interleave coefficients */
  599. for(k=0; k<128; k++) {
  600. x[k] = ctx->transform_coeffs[chindex][2*k+i];
  601. }
  602. /* run standard IMDCT */
  603. ctx->imdct_256.fft.imdct_calc(&ctx->imdct_256, o_ptr, x, ctx->tmp_imdct);
  604. /* reverse the post-rotation & reordering from standard IMDCT */
  605. for(k=0; k<32; k++) {
  606. z[i][32+k].re = -o_ptr[128+2*k];
  607. z[i][32+k].im = -o_ptr[2*k];
  608. z[i][31-k].re = o_ptr[2*k+1];
  609. z[i][31-k].im = o_ptr[128+2*k+1];
  610. }
  611. }
  612. /* apply AC-3 post-rotation & reordering */
  613. for(k=0; k<64; k++) {
  614. o_ptr[ 2*k ] = -z[0][ k].im;
  615. o_ptr[ 2*k+1] = z[0][63-k].re;
  616. o_ptr[128+2*k ] = -z[0][ k].re;
  617. o_ptr[128+2*k+1] = z[0][63-k].im;
  618. o_ptr[256+2*k ] = -z[1][ k].re;
  619. o_ptr[256+2*k+1] = z[1][63-k].im;
  620. o_ptr[384+2*k ] = z[1][ k].im;
  621. o_ptr[384+2*k+1] = -z[1][63-k].re;
  622. }
  623. }
  624. /* IMDCT Transform. */
  625. static inline void do_imdct(AC3DecodeContext *ctx)
  626. {
  627. int ch;
  628. if (ctx->output_mode & AC3_OUTPUT_LFEON) {
  629. ctx->imdct_512.fft.imdct_calc(&ctx->imdct_512, ctx->tmp_output,
  630. ctx->transform_coeffs[0], ctx->tmp_imdct);
  631. ctx->dsp.vector_fmul_add_add(ctx->output[0], ctx->tmp_output,
  632. ctx->window, ctx->delay[0], 384, 256, 1);
  633. ctx->dsp.vector_fmul_reverse(ctx->delay[0], ctx->tmp_output+256,
  634. ctx->window, 256);
  635. }
  636. for (ch=1; ch<=ctx->nfchans; ch++) {
  637. if (ctx->blksw[ch-1])
  638. do_imdct_256(ctx, ch);
  639. else
  640. ctx->imdct_512.fft.imdct_calc(&ctx->imdct_512, ctx->tmp_output,
  641. ctx->transform_coeffs[ch],
  642. ctx->tmp_imdct);
  643. ctx->dsp.vector_fmul_add_add(ctx->output[ch], ctx->tmp_output,
  644. ctx->window, ctx->delay[ch], 384, 256, 1);
  645. ctx->dsp.vector_fmul_reverse(ctx->delay[ch], ctx->tmp_output+256,
  646. ctx->window, 256);
  647. }
  648. }
  649. /* Parse the audio block from ac3 bitstream.
  650. * This function extract the audio block from the ac3 bitstream
  651. * and produces the output for the block. This function must
  652. * be called for each of the six audio block in the ac3 bitstream.
  653. */
  654. static int ac3_parse_audio_block(AC3DecodeContext *ctx, int blk)
  655. {
  656. int nfchans = ctx->nfchans;
  657. int acmod = ctx->acmod;
  658. int i, bnd, seg, grpsize, ch;
  659. GetBitContext *gb = &ctx->gb;
  660. int bit_alloc_flags = 0;
  661. int8_t *dexps;
  662. int mstrcplco, cplcoexp, cplcomant;
  663. int dynrng, chbwcod, ngrps, cplabsexp, skipl;
  664. for (i = 0; i < nfchans; i++) /*block switch flag */
  665. ctx->blksw[i] = get_bits1(gb);
  666. for (i = 0; i < nfchans; i++) /* dithering flag */
  667. ctx->dithflag[i] = get_bits1(gb);
  668. if (get_bits1(gb)) { /* dynamic range */
  669. dynrng = get_sbits(gb, 8);
  670. ctx->dynrng = ((((dynrng & 0x1f) | 0x20) << 13) * scale_factors[3 - (dynrng >> 5)]);
  671. } else if(blk == 0) {
  672. ctx->dynrng = 1.0;
  673. }
  674. if(acmod == AC3_ACMOD_DUALMONO) { /* dynamic range 1+1 mode */
  675. if(get_bits1(gb)) {
  676. dynrng = get_sbits(gb, 8);
  677. ctx->dynrng2 = ((((dynrng & 0x1f) | 0x20) << 13) * scale_factors[3 - (dynrng >> 5)]);
  678. } else if(blk == 0) {
  679. ctx->dynrng2 = 1.0;
  680. }
  681. }
  682. if (get_bits1(gb)) { /* coupling strategy */
  683. ctx->cplinu = get_bits1(gb);
  684. ctx->cplbndstrc = 0;
  685. if (ctx->cplinu) { /* coupling in use */
  686. int cplbegf, cplendf;
  687. for (i = 0; i < nfchans; i++)
  688. ctx->chincpl[i] = get_bits1(gb);
  689. if (acmod == AC3_ACMOD_STEREO)
  690. ctx->phsflginu = get_bits1(gb); //phase flag in use
  691. cplbegf = get_bits(gb, 4);
  692. cplendf = get_bits(gb, 4);
  693. if (3 + cplendf - cplbegf < 0) {
  694. av_log(NULL, AV_LOG_ERROR, "cplendf = %d < cplbegf = %d\n", cplendf, cplbegf);
  695. return -1;
  696. }
  697. ctx->ncplbnd = ctx->ncplsubnd = 3 + cplendf - cplbegf;
  698. ctx->cplstrtmant = cplbegf * 12 + 37;
  699. ctx->cplendmant = cplendf * 12 + 73;
  700. for (i = 0; i < ctx->ncplsubnd - 1; i++) /* coupling band structure */
  701. if (get_bits1(gb)) {
  702. ctx->cplbndstrc |= 1 << i;
  703. ctx->ncplbnd--;
  704. }
  705. } else {
  706. for (i = 0; i < nfchans; i++)
  707. ctx->chincpl[i] = 0;
  708. }
  709. }
  710. if (ctx->cplinu) {
  711. ctx->cplcoe = 0;
  712. for (i = 0; i < nfchans; i++)
  713. if (ctx->chincpl[i])
  714. if (get_bits1(gb)) { /* coupling co-ordinates */
  715. ctx->cplcoe |= 1 << i;
  716. mstrcplco = 3 * get_bits(gb, 2);
  717. for (bnd = 0; bnd < ctx->ncplbnd; bnd++) {
  718. cplcoexp = get_bits(gb, 4);
  719. cplcomant = get_bits(gb, 4);
  720. if (cplcoexp == 15)
  721. cplcomant <<= 14;
  722. else
  723. cplcomant = (cplcomant | 0x10) << 13;
  724. ctx->cplco[i][bnd] = cplcomant * scale_factors[cplcoexp + mstrcplco];
  725. }
  726. }
  727. if (acmod == AC3_ACMOD_STEREO && ctx->phsflginu && (ctx->cplcoe & 1 || ctx->cplcoe & 2))
  728. for (bnd = 0; bnd < ctx->ncplbnd; bnd++)
  729. if (get_bits1(gb))
  730. ctx->cplco[1][bnd] = -ctx->cplco[1][bnd];
  731. }
  732. if (acmod == AC3_ACMOD_STEREO) {/* rematrixing */
  733. ctx->rematstr = get_bits1(gb);
  734. if (ctx->rematstr) {
  735. ctx->nrematbnd = 4;
  736. if(ctx->cplinu && ctx->cplstrtmant <= 61)
  737. ctx->nrematbnd -= 1 + (ctx->cplstrtmant == 37);
  738. for(bnd=0; bnd<ctx->nrematbnd; bnd++)
  739. ctx->rematflg[bnd] = get_bits1(gb);
  740. }
  741. }
  742. ctx->cplexpstr = EXP_REUSE;
  743. ctx->lfeexpstr = EXP_REUSE;
  744. if (ctx->cplinu) /* coupling exponent strategy */
  745. ctx->cplexpstr = get_bits(gb, 2);
  746. for (i = 0; i < nfchans; i++) /* channel exponent strategy */
  747. ctx->chexpstr[i] = get_bits(gb, 2);
  748. if (ctx->lfeon) /* lfe exponent strategy */
  749. ctx->lfeexpstr = get_bits1(gb);
  750. for (i = 0; i < nfchans; i++) /* channel bandwidth code */
  751. if (ctx->chexpstr[i] != EXP_REUSE) {
  752. if (ctx->chincpl[i])
  753. ctx->endmant[i] = ctx->cplstrtmant;
  754. else {
  755. chbwcod = get_bits(gb, 6);
  756. if (chbwcod > 60) {
  757. av_log(NULL, AV_LOG_ERROR, "chbwcod = %d > 60", chbwcod);
  758. return -1;
  759. }
  760. ctx->endmant[i] = chbwcod * 3 + 73;
  761. }
  762. }
  763. if (ctx->cplexpstr != EXP_REUSE) {/* coupling exponents */
  764. bit_alloc_flags = 64;
  765. cplabsexp = get_bits(gb, 4) << 1;
  766. ngrps = (ctx->cplendmant - ctx->cplstrtmant) / (3 << (ctx->cplexpstr - 1));
  767. decode_exponents(gb, ctx->cplexpstr, ngrps, cplabsexp, ctx->dcplexps + ctx->cplstrtmant);
  768. }
  769. for (i = 0; i < nfchans; i++) /* fbw channel exponents */
  770. if (ctx->chexpstr[i] != EXP_REUSE) {
  771. bit_alloc_flags |= 1 << i;
  772. grpsize = 3 << (ctx->chexpstr[i] - 1);
  773. ngrps = (ctx->endmant[i] + grpsize - 4) / grpsize;
  774. dexps = ctx->dexps[i];
  775. dexps[0] = get_bits(gb, 4);
  776. decode_exponents(gb, ctx->chexpstr[i], ngrps, dexps[0], dexps + 1);
  777. skip_bits(gb, 2); /* skip gainrng */
  778. }
  779. if (ctx->lfeexpstr != EXP_REUSE) { /* lfe exponents */
  780. bit_alloc_flags |= 32;
  781. ctx->dlfeexps[0] = get_bits(gb, 4);
  782. decode_exponents(gb, ctx->lfeexpstr, 2, ctx->dlfeexps[0], ctx->dlfeexps + 1);
  783. }
  784. if (get_bits1(gb)) { /* bit allocation information */
  785. bit_alloc_flags = 127;
  786. ctx->bit_alloc_params.sdecay = ff_sdecaytab[get_bits(gb, 2)];
  787. ctx->bit_alloc_params.fdecay = ff_fdecaytab[get_bits(gb, 2)];
  788. ctx->bit_alloc_params.sgain = ff_sgaintab[get_bits(gb, 2)];
  789. ctx->bit_alloc_params.dbknee = ff_dbkneetab[get_bits(gb, 2)];
  790. ctx->bit_alloc_params.floor = ff_floortab[get_bits(gb, 3)];
  791. }
  792. if (get_bits1(gb)) { /* snroffset */
  793. int csnr;
  794. bit_alloc_flags = 127;
  795. csnr = (get_bits(gb, 6) - 15) << 4;
  796. if (ctx->cplinu) { /* coupling fine snr offset and fast gain code */
  797. ctx->cplsnroffst = (csnr + get_bits(gb, 4)) << 2;
  798. ctx->cplfgain = ff_fgaintab[get_bits(gb, 3)];
  799. }
  800. for (i = 0; i < nfchans; i++) { /* channel fine snr offset and fast gain code */
  801. ctx->snroffst[i] = (csnr + get_bits(gb, 4)) << 2;
  802. ctx->fgain[i] = ff_fgaintab[get_bits(gb, 3)];
  803. }
  804. if (ctx->lfeon) { /* lfe fine snr offset and fast gain code */
  805. ctx->lfesnroffst = (csnr + get_bits(gb, 4)) << 2;
  806. ctx->lfefgain = ff_fgaintab[get_bits(gb, 3)];
  807. }
  808. }
  809. if (ctx->cplinu && get_bits1(gb)) { /* coupling leak information */
  810. bit_alloc_flags |= 64;
  811. ctx->bit_alloc_params.cplfleak = get_bits(gb, 3);
  812. ctx->bit_alloc_params.cplsleak = get_bits(gb, 3);
  813. }
  814. if (get_bits1(gb)) { /* delta bit allocation information */
  815. bit_alloc_flags = 127;
  816. if (ctx->cplinu) {
  817. ctx->cpldeltbae = get_bits(gb, 2);
  818. if (ctx->cpldeltbae == DBA_RESERVED) {
  819. av_log(NULL, AV_LOG_ERROR, "coupling delta bit allocation strategy reserved\n");
  820. return -1;
  821. }
  822. }
  823. for (i = 0; i < nfchans; i++) {
  824. ctx->deltbae[i] = get_bits(gb, 2);
  825. if (ctx->deltbae[i] == DBA_RESERVED) {
  826. av_log(NULL, AV_LOG_ERROR, "delta bit allocation strategy reserved\n");
  827. return -1;
  828. }
  829. }
  830. if (ctx->cplinu)
  831. if (ctx->cpldeltbae == DBA_NEW) { /*coupling delta offset, len and bit allocation */
  832. ctx->cpldeltnseg = get_bits(gb, 3);
  833. for (seg = 0; seg <= ctx->cpldeltnseg; seg++) {
  834. ctx->cpldeltoffst[seg] = get_bits(gb, 5);
  835. ctx->cpldeltlen[seg] = get_bits(gb, 4);
  836. ctx->cpldeltba[seg] = get_bits(gb, 3);
  837. }
  838. }
  839. for (i = 0; i < nfchans; i++)
  840. if (ctx->deltbae[i] == DBA_NEW) {/*channel delta offset, len and bit allocation */
  841. ctx->deltnseg[i] = get_bits(gb, 3);
  842. for (seg = 0; seg <= ctx->deltnseg[i]; seg++) {
  843. ctx->deltoffst[i][seg] = get_bits(gb, 5);
  844. ctx->deltlen[i][seg] = get_bits(gb, 4);
  845. ctx->deltba[i][seg] = get_bits(gb, 3);
  846. }
  847. }
  848. } else if(blk == 0) {
  849. if(ctx->cplinu)
  850. ctx->cpldeltbae = DBA_NONE;
  851. for(i=0; i<nfchans; i++) {
  852. ctx->deltbae[i] = DBA_NONE;
  853. }
  854. }
  855. if (bit_alloc_flags) {
  856. if (ctx->cplinu && (bit_alloc_flags & 64))
  857. ac3_parametric_bit_allocation(&ctx->bit_alloc_params, ctx->cplbap,
  858. ctx->dcplexps, ctx->cplstrtmant,
  859. ctx->cplendmant, ctx->cplsnroffst,
  860. ctx->cplfgain, 0,
  861. ctx->cpldeltbae, ctx->cpldeltnseg,
  862. ctx->cpldeltoffst, ctx->cpldeltlen,
  863. ctx->cpldeltba);
  864. for (i = 0; i < nfchans; i++)
  865. if ((bit_alloc_flags >> i) & 1)
  866. ac3_parametric_bit_allocation(&ctx->bit_alloc_params,
  867. ctx->bap[i], ctx->dexps[i], 0,
  868. ctx->endmant[i], ctx->snroffst[i],
  869. ctx->fgain[i], 0, ctx->deltbae[i],
  870. ctx->deltnseg[i], ctx->deltoffst[i],
  871. ctx->deltlen[i], ctx->deltba[i]);
  872. if (ctx->lfeon && (bit_alloc_flags & 32))
  873. ac3_parametric_bit_allocation(&ctx->bit_alloc_params, ctx->lfebap,
  874. ctx->dlfeexps, 0, 7, ctx->lfesnroffst,
  875. ctx->lfefgain, 1,
  876. DBA_NONE, 0, NULL, NULL, NULL);
  877. }
  878. if (get_bits1(gb)) { /* unused dummy data */
  879. skipl = get_bits(gb, 9);
  880. while(skipl--)
  881. skip_bits(gb, 8);
  882. }
  883. /* unpack the transform coefficients
  884. * * this also uncouples channels if coupling is in use.
  885. */
  886. if (get_transform_coeffs(ctx)) {
  887. av_log(NULL, AV_LOG_ERROR, "Error in routine get_transform_coeffs\n");
  888. return -1;
  889. }
  890. /* recover coefficients if rematrixing is in use */
  891. if(ctx->acmod == AC3_ACMOD_STEREO)
  892. do_rematrixing(ctx);
  893. /* apply scaling to coefficients (headroom, dynrng) */
  894. if(ctx->lfeon) {
  895. for(i=0; i<7; i++) {
  896. ctx->transform_coeffs[0][i] *= 2.0f * ctx->dynrng;
  897. }
  898. }
  899. for(ch=1; ch<=ctx->nfchans; ch++) {
  900. float gain = 2.0f;
  901. if(ctx->acmod == AC3_ACMOD_DUALMONO && ch == 2) {
  902. gain *= ctx->dynrng2;
  903. } else {
  904. gain *= ctx->dynrng;
  905. }
  906. for(i=0; i<ctx->endmant[ch-1]; i++) {
  907. ctx->transform_coeffs[ch][i] *= gain;
  908. }
  909. }
  910. do_imdct(ctx);
  911. return 0;
  912. }
  913. static inline int16_t convert(int32_t i)
  914. {
  915. if (i > 0x43c07fff)
  916. return 32767;
  917. else if (i <= 0x43bf8000)
  918. return -32768;
  919. else
  920. return (i - 0x43c00000);
  921. }
  922. /* Decode ac3 frame.
  923. *
  924. * @param avctx Pointer to AVCodecContext
  925. * @param data Pointer to pcm smaples
  926. * @param data_size Set to number of pcm samples produced by decoding
  927. * @param buf Data to be decoded
  928. * @param buf_size Size of the buffer
  929. */
  930. static int ac3_decode_frame(AVCodecContext * avctx, void *data, int *data_size, uint8_t *buf, int buf_size)
  931. {
  932. AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
  933. int16_t *out_samples = (int16_t *)data;
  934. int i, j, k, start;
  935. int32_t *int_ptr[6];
  936. for (i = 0; i < 6; i++)
  937. int_ptr[i] = (int32_t *)(&ctx->output[i]);
  938. //Initialize the GetBitContext with the start of valid AC3 Frame.
  939. init_get_bits(&ctx->gb, buf, buf_size * 8);
  940. //Parse the syncinfo.
  941. if (ac3_parse_header(ctx)) {
  942. av_log(avctx, AV_LOG_ERROR, "\n");
  943. *data_size = 0;
  944. return buf_size;
  945. }
  946. avctx->sample_rate = ctx->sampling_rate;
  947. avctx->bit_rate = ctx->bit_rate;
  948. /* channel config */
  949. if (avctx->channels == 0) {
  950. avctx->channels = ctx->out_channels;
  951. }
  952. if(avctx->channels != ctx->out_channels) {
  953. av_log(avctx, AV_LOG_ERROR, "Cannot mix AC3 to %d channels.\n",
  954. avctx->channels);
  955. return -1;
  956. }
  957. //av_log(avctx, AV_LOG_INFO, "channels = %d \t bit rate = %d \t sampling rate = %d \n", avctx->channels, avctx->bit_rate * 1000, avctx->sample_rate);
  958. //Parse the Audio Blocks.
  959. for (i = 0; i < NB_BLOCKS; i++) {
  960. if (ac3_parse_audio_block(ctx, i)) {
  961. av_log(avctx, AV_LOG_ERROR, "error parsing the audio block\n");
  962. *data_size = 0;
  963. return ctx->frame_size;
  964. }
  965. start = (ctx->output_mode & AC3_OUTPUT_LFEON) ? 0 : 1;
  966. for (k = 0; k < 256; k++)
  967. for (j = start; j <= ctx->nfchans; j++)
  968. *(out_samples++) = convert(int_ptr[j][k]);
  969. }
  970. *data_size = NB_BLOCKS * 256 * avctx->channels * sizeof (int16_t);
  971. return ctx->frame_size;
  972. }
  973. /* Uninitialize ac3 decoder.
  974. */
  975. static int ac3_decode_end(AVCodecContext *avctx)
  976. {
  977. AC3DecodeContext *ctx = (AC3DecodeContext *)avctx->priv_data;
  978. ff_mdct_end(&ctx->imdct_512);
  979. ff_mdct_end(&ctx->imdct_256);
  980. return 0;
  981. }
  982. AVCodec ac3_decoder = {
  983. .name = "ac3",
  984. .type = CODEC_TYPE_AUDIO,
  985. .id = CODEC_ID_AC3,
  986. .priv_data_size = sizeof (AC3DecodeContext),
  987. .init = ac3_decode_init,
  988. .close = ac3_decode_end,
  989. .decode = ac3_decode_frame,
  990. };