ac3dec.c 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365
  1. /*
  2. * AC-3 Audio Decoder
  3. * This code was developed as part of Google Summer of Code 2006.
  4. * E-AC-3 support was added as part of Google Summer of Code 2007.
  5. *
  6. * Copyright (c) 2006 Kartikey Mahendra BHATT (bhattkm at gmail dot com)
  7. * Copyright (c) 2007-2008 Bartlomiej Wolowiec <bartek.wolowiec@gmail.com>
  8. * Copyright (c) 2007 Justin Ruggles <justin.ruggles@gmail.com>
  9. *
  10. * This file is part of FFmpeg.
  11. *
  12. * FFmpeg is free software; you can redistribute it and/or
  13. * modify it under the terms of the GNU Lesser General Public
  14. * License as published by the Free Software Foundation; either
  15. * version 2.1 of the License, or (at your option) any later version.
  16. *
  17. * FFmpeg is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  20. * Lesser General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Lesser General Public
  23. * License along with FFmpeg; if not, write to the Free Software
  24. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  25. */
  26. #include <stdio.h>
  27. #include <stddef.h>
  28. #include <math.h>
  29. #include <string.h>
  30. #include "libavutil/crc.h"
  31. #include "internal.h"
  32. #include "aac_ac3_parser.h"
  33. #include "ac3_parser.h"
  34. #include "ac3dec.h"
  35. #include "ac3dec_data.h"
  36. /** Large enough for maximum possible frame size when the specification limit is ignored */
  37. #define AC3_FRAME_BUFFER_SIZE 32768
  38. /**
  39. * table for ungrouping 3 values in 7 bits.
  40. * used for exponents and bap=2 mantissas
  41. */
  42. static uint8_t ungroup_3_in_7_bits_tab[128][3];
  43. /** tables for ungrouping mantissas */
  44. static int b1_mantissas[32][3];
  45. static int b2_mantissas[128][3];
  46. static int b3_mantissas[8];
  47. static int b4_mantissas[128][2];
  48. static int b5_mantissas[16];
  49. /**
  50. * Quantization table: levels for symmetric. bits for asymmetric.
  51. * reference: Table 7.18 Mapping of bap to Quantizer
  52. */
  53. static const uint8_t quantization_tab[16] = {
  54. 0, 3, 5, 7, 11, 15,
  55. 5, 6, 7, 8, 9, 10, 11, 12, 14, 16
  56. };
  57. /** dynamic range table. converts codes to scale factors. */
  58. static float dynamic_range_tab[256];
  59. /** Adjustments in dB gain */
  60. #define LEVEL_PLUS_3DB 1.4142135623730950
  61. #define LEVEL_PLUS_1POINT5DB 1.1892071150027209
  62. #define LEVEL_MINUS_1POINT5DB 0.8408964152537145
  63. #define LEVEL_MINUS_3DB 0.7071067811865476
  64. #define LEVEL_MINUS_4POINT5DB 0.5946035575013605
  65. #define LEVEL_MINUS_6DB 0.5000000000000000
  66. #define LEVEL_MINUS_9DB 0.3535533905932738
  67. #define LEVEL_ZERO 0.0000000000000000
  68. #define LEVEL_ONE 1.0000000000000000
  69. static const float gain_levels[9] = {
  70. LEVEL_PLUS_3DB,
  71. LEVEL_PLUS_1POINT5DB,
  72. LEVEL_ONE,
  73. LEVEL_MINUS_1POINT5DB,
  74. LEVEL_MINUS_3DB,
  75. LEVEL_MINUS_4POINT5DB,
  76. LEVEL_MINUS_6DB,
  77. LEVEL_ZERO,
  78. LEVEL_MINUS_9DB
  79. };
  80. /**
  81. * Table for center mix levels
  82. * reference: Section 5.4.2.4 cmixlev
  83. */
  84. static const uint8_t center_levels[4] = { 4, 5, 6, 5 };
  85. /**
  86. * Table for surround mix levels
  87. * reference: Section 5.4.2.5 surmixlev
  88. */
  89. static const uint8_t surround_levels[4] = { 4, 6, 7, 6 };
  90. /**
  91. * Table for default stereo downmixing coefficients
  92. * reference: Section 7.8.2 Downmixing Into Two Channels
  93. */
  94. static const uint8_t ac3_default_coeffs[8][5][2] = {
  95. { { 2, 7 }, { 7, 2 }, },
  96. { { 4, 4 }, },
  97. { { 2, 7 }, { 7, 2 }, },
  98. { { 2, 7 }, { 5, 5 }, { 7, 2 }, },
  99. { { 2, 7 }, { 7, 2 }, { 6, 6 }, },
  100. { { 2, 7 }, { 5, 5 }, { 7, 2 }, { 8, 8 }, },
  101. { { 2, 7 }, { 7, 2 }, { 6, 7 }, { 7, 6 }, },
  102. { { 2, 7 }, { 5, 5 }, { 7, 2 }, { 6, 7 }, { 7, 6 }, },
  103. };
  104. /**
  105. * Symmetrical Dequantization
  106. * reference: Section 7.3.3 Expansion of Mantissas for Symmetrical Quantization
  107. * Tables 7.19 to 7.23
  108. */
  109. static inline int
  110. symmetric_dequant(int code, int levels)
  111. {
  112. return ((code - (levels >> 1)) << 24) / levels;
  113. }
  114. /*
  115. * Initialize tables at runtime.
  116. */
  117. static av_cold void ac3_tables_init(void)
  118. {
  119. int i;
  120. /* generate table for ungrouping 3 values in 7 bits
  121. reference: Section 7.1.3 Exponent Decoding */
  122. for(i=0; i<128; i++) {
  123. ungroup_3_in_7_bits_tab[i][0] = i / 25;
  124. ungroup_3_in_7_bits_tab[i][1] = (i % 25) / 5;
  125. ungroup_3_in_7_bits_tab[i][2] = (i % 25) % 5;
  126. }
  127. /* generate grouped mantissa tables
  128. reference: Section 7.3.5 Ungrouping of Mantissas */
  129. for(i=0; i<32; i++) {
  130. /* bap=1 mantissas */
  131. b1_mantissas[i][0] = symmetric_dequant(ff_ac3_ungroup_3_in_5_bits_tab[i][0], 3);
  132. b1_mantissas[i][1] = symmetric_dequant(ff_ac3_ungroup_3_in_5_bits_tab[i][1], 3);
  133. b1_mantissas[i][2] = symmetric_dequant(ff_ac3_ungroup_3_in_5_bits_tab[i][2], 3);
  134. }
  135. for(i=0; i<128; i++) {
  136. /* bap=2 mantissas */
  137. b2_mantissas[i][0] = symmetric_dequant(ungroup_3_in_7_bits_tab[i][0], 5);
  138. b2_mantissas[i][1] = symmetric_dequant(ungroup_3_in_7_bits_tab[i][1], 5);
  139. b2_mantissas[i][2] = symmetric_dequant(ungroup_3_in_7_bits_tab[i][2], 5);
  140. /* bap=4 mantissas */
  141. b4_mantissas[i][0] = symmetric_dequant(i / 11, 11);
  142. b4_mantissas[i][1] = symmetric_dequant(i % 11, 11);
  143. }
  144. /* generate ungrouped mantissa tables
  145. reference: Tables 7.21 and 7.23 */
  146. for(i=0; i<7; i++) {
  147. /* bap=3 mantissas */
  148. b3_mantissas[i] = symmetric_dequant(i, 7);
  149. }
  150. for(i=0; i<15; i++) {
  151. /* bap=5 mantissas */
  152. b5_mantissas[i] = symmetric_dequant(i, 15);
  153. }
  154. /* generate dynamic range table
  155. reference: Section 7.7.1 Dynamic Range Control */
  156. for(i=0; i<256; i++) {
  157. int v = (i >> 5) - ((i >> 7) << 3) - 5;
  158. dynamic_range_tab[i] = powf(2.0f, v) * ((i & 0x1F) | 0x20);
  159. }
  160. }
  161. /**
  162. * AVCodec initialization
  163. */
  164. static av_cold int ac3_decode_init(AVCodecContext *avctx)
  165. {
  166. AC3DecodeContext *s = avctx->priv_data;
  167. s->avctx = avctx;
  168. ac3_common_init();
  169. ac3_tables_init();
  170. ff_mdct_init(&s->imdct_256, 8, 1);
  171. ff_mdct_init(&s->imdct_512, 9, 1);
  172. ff_kbd_window_init(s->window, 5.0, 256);
  173. dsputil_init(&s->dsp, avctx);
  174. av_lfg_init(&s->dith_state, 0);
  175. /* set bias values for float to int16 conversion */
  176. if(s->dsp.float_to_int16_interleave == ff_float_to_int16_interleave_c) {
  177. s->add_bias = 385.0f;
  178. s->mul_bias = 1.0f;
  179. } else {
  180. s->add_bias = 0.0f;
  181. s->mul_bias = 32767.0f;
  182. }
  183. /* allow downmixing to stereo or mono */
  184. if (avctx->channels > 0 && avctx->request_channels > 0 &&
  185. avctx->request_channels < avctx->channels &&
  186. avctx->request_channels <= 2) {
  187. avctx->channels = avctx->request_channels;
  188. }
  189. s->downmixed = 1;
  190. /* allocate context input buffer */
  191. if (avctx->error_recognition >= FF_ER_CAREFUL) {
  192. s->input_buffer = av_mallocz(AC3_FRAME_BUFFER_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);
  193. if (!s->input_buffer)
  194. return AVERROR_NOMEM;
  195. }
  196. avctx->sample_fmt = SAMPLE_FMT_S16;
  197. return 0;
  198. }
  199. /**
  200. * Parse the 'sync info' and 'bit stream info' from the AC-3 bitstream.
  201. * GetBitContext within AC3DecodeContext must point to
  202. * the start of the synchronized AC-3 bitstream.
  203. */
  204. static int ac3_parse_header(AC3DecodeContext *s)
  205. {
  206. GetBitContext *gbc = &s->gbc;
  207. int i;
  208. /* read the rest of the bsi. read twice for dual mono mode. */
  209. i = !(s->channel_mode);
  210. do {
  211. skip_bits(gbc, 5); // skip dialog normalization
  212. if (get_bits1(gbc))
  213. skip_bits(gbc, 8); //skip compression
  214. if (get_bits1(gbc))
  215. skip_bits(gbc, 8); //skip language code
  216. if (get_bits1(gbc))
  217. skip_bits(gbc, 7); //skip audio production information
  218. } while (i--);
  219. skip_bits(gbc, 2); //skip copyright bit and original bitstream bit
  220. /* skip the timecodes (or extra bitstream information for Alternate Syntax)
  221. TODO: read & use the xbsi1 downmix levels */
  222. if (get_bits1(gbc))
  223. skip_bits(gbc, 14); //skip timecode1 / xbsi1
  224. if (get_bits1(gbc))
  225. skip_bits(gbc, 14); //skip timecode2 / xbsi2
  226. /* skip additional bitstream info */
  227. if (get_bits1(gbc)) {
  228. i = get_bits(gbc, 6);
  229. do {
  230. skip_bits(gbc, 8);
  231. } while(i--);
  232. }
  233. return 0;
  234. }
  235. /**
  236. * Common function to parse AC-3 or E-AC-3 frame header
  237. */
  238. static int parse_frame_header(AC3DecodeContext *s)
  239. {
  240. AC3HeaderInfo hdr;
  241. int err;
  242. err = ff_ac3_parse_header(&s->gbc, &hdr);
  243. if(err)
  244. return err;
  245. /* get decoding parameters from header info */
  246. s->bit_alloc_params.sr_code = hdr.sr_code;
  247. s->channel_mode = hdr.channel_mode;
  248. s->lfe_on = hdr.lfe_on;
  249. s->bit_alloc_params.sr_shift = hdr.sr_shift;
  250. s->sample_rate = hdr.sample_rate;
  251. s->bit_rate = hdr.bit_rate;
  252. s->channels = hdr.channels;
  253. s->fbw_channels = s->channels - s->lfe_on;
  254. s->lfe_ch = s->fbw_channels + 1;
  255. s->frame_size = hdr.frame_size;
  256. s->center_mix_level = hdr.center_mix_level;
  257. s->surround_mix_level = hdr.surround_mix_level;
  258. s->num_blocks = hdr.num_blocks;
  259. s->frame_type = hdr.frame_type;
  260. s->substreamid = hdr.substreamid;
  261. if(s->lfe_on) {
  262. s->start_freq[s->lfe_ch] = 0;
  263. s->end_freq[s->lfe_ch] = 7;
  264. s->num_exp_groups[s->lfe_ch] = 2;
  265. s->channel_in_cpl[s->lfe_ch] = 0;
  266. }
  267. if (hdr.bitstream_id <= 10) {
  268. s->eac3 = 0;
  269. s->snr_offset_strategy = 2;
  270. s->block_switch_syntax = 1;
  271. s->dither_flag_syntax = 1;
  272. s->bit_allocation_syntax = 1;
  273. s->fast_gain_syntax = 0;
  274. s->first_cpl_leak = 0;
  275. s->dba_syntax = 1;
  276. s->skip_syntax = 1;
  277. memset(s->channel_uses_aht, 0, sizeof(s->channel_uses_aht));
  278. return ac3_parse_header(s);
  279. } else {
  280. s->eac3 = 1;
  281. return ff_eac3_parse_header(s);
  282. }
  283. }
  284. /**
  285. * Set stereo downmixing coefficients based on frame header info.
  286. * reference: Section 7.8.2 Downmixing Into Two Channels
  287. */
  288. static void set_downmix_coeffs(AC3DecodeContext *s)
  289. {
  290. int i;
  291. float cmix = gain_levels[center_levels[s->center_mix_level]];
  292. float smix = gain_levels[surround_levels[s->surround_mix_level]];
  293. float norm0, norm1;
  294. for(i=0; i<s->fbw_channels; i++) {
  295. s->downmix_coeffs[i][0] = gain_levels[ac3_default_coeffs[s->channel_mode][i][0]];
  296. s->downmix_coeffs[i][1] = gain_levels[ac3_default_coeffs[s->channel_mode][i][1]];
  297. }
  298. if(s->channel_mode > 1 && s->channel_mode & 1) {
  299. s->downmix_coeffs[1][0] = s->downmix_coeffs[1][1] = cmix;
  300. }
  301. if(s->channel_mode == AC3_CHMODE_2F1R || s->channel_mode == AC3_CHMODE_3F1R) {
  302. int nf = s->channel_mode - 2;
  303. s->downmix_coeffs[nf][0] = s->downmix_coeffs[nf][1] = smix * LEVEL_MINUS_3DB;
  304. }
  305. if(s->channel_mode == AC3_CHMODE_2F2R || s->channel_mode == AC3_CHMODE_3F2R) {
  306. int nf = s->channel_mode - 4;
  307. s->downmix_coeffs[nf][0] = s->downmix_coeffs[nf+1][1] = smix;
  308. }
  309. /* renormalize */
  310. norm0 = norm1 = 0.0;
  311. for(i=0; i<s->fbw_channels; i++) {
  312. norm0 += s->downmix_coeffs[i][0];
  313. norm1 += s->downmix_coeffs[i][1];
  314. }
  315. norm0 = 1.0f / norm0;
  316. norm1 = 1.0f / norm1;
  317. for(i=0; i<s->fbw_channels; i++) {
  318. s->downmix_coeffs[i][0] *= norm0;
  319. s->downmix_coeffs[i][1] *= norm1;
  320. }
  321. if(s->output_mode == AC3_CHMODE_MONO) {
  322. for(i=0; i<s->fbw_channels; i++)
  323. s->downmix_coeffs[i][0] = (s->downmix_coeffs[i][0] + s->downmix_coeffs[i][1]) * LEVEL_MINUS_3DB;
  324. }
  325. }
  326. /**
  327. * Decode the grouped exponents according to exponent strategy.
  328. * reference: Section 7.1.3 Exponent Decoding
  329. */
  330. static int decode_exponents(GetBitContext *gbc, int exp_strategy, int ngrps,
  331. uint8_t absexp, int8_t *dexps)
  332. {
  333. int i, j, grp, group_size;
  334. int dexp[256];
  335. int expacc, prevexp;
  336. /* unpack groups */
  337. group_size = exp_strategy + (exp_strategy == EXP_D45);
  338. for(grp=0,i=0; grp<ngrps; grp++) {
  339. expacc = get_bits(gbc, 7);
  340. dexp[i++] = ungroup_3_in_7_bits_tab[expacc][0];
  341. dexp[i++] = ungroup_3_in_7_bits_tab[expacc][1];
  342. dexp[i++] = ungroup_3_in_7_bits_tab[expacc][2];
  343. }
  344. /* convert to absolute exps and expand groups */
  345. prevexp = absexp;
  346. for(i=0,j=0; i<ngrps*3; i++) {
  347. prevexp += dexp[i] - 2;
  348. if (prevexp > 24U)
  349. return -1;
  350. switch (group_size) {
  351. case 4: dexps[j++] = prevexp;
  352. dexps[j++] = prevexp;
  353. case 2: dexps[j++] = prevexp;
  354. case 1: dexps[j++] = prevexp;
  355. }
  356. }
  357. return 0;
  358. }
  359. /**
  360. * Generate transform coefficients for each coupled channel in the coupling
  361. * range using the coupling coefficients and coupling coordinates.
  362. * reference: Section 7.4.3 Coupling Coordinate Format
  363. */
  364. static void calc_transform_coeffs_cpl(AC3DecodeContext *s)
  365. {
  366. int i, j, ch, bnd, subbnd;
  367. subbnd = -1;
  368. i = s->start_freq[CPL_CH];
  369. for(bnd=0; bnd<s->num_cpl_bands; bnd++) {
  370. do {
  371. subbnd++;
  372. for(j=0; j<12; j++) {
  373. for(ch=1; ch<=s->fbw_channels; ch++) {
  374. if(s->channel_in_cpl[ch]) {
  375. s->fixed_coeffs[ch][i] = ((int64_t)s->fixed_coeffs[CPL_CH][i] * (int64_t)s->cpl_coords[ch][bnd]) >> 23;
  376. if (ch == 2 && s->phase_flags[bnd])
  377. s->fixed_coeffs[ch][i] = -s->fixed_coeffs[ch][i];
  378. }
  379. }
  380. i++;
  381. }
  382. } while(s->cpl_band_struct[subbnd]);
  383. }
  384. }
  385. /**
  386. * Grouped mantissas for 3-level 5-level and 11-level quantization
  387. */
  388. typedef struct {
  389. int b1_mant[2];
  390. int b2_mant[2];
  391. int b4_mant;
  392. int b1;
  393. int b2;
  394. int b4;
  395. } mant_groups;
  396. /**
  397. * Decode the transform coefficients for a particular channel
  398. * reference: Section 7.3 Quantization and Decoding of Mantissas
  399. */
  400. static void ac3_decode_transform_coeffs_ch(AC3DecodeContext *s, int ch_index, mant_groups *m)
  401. {
  402. int start_freq = s->start_freq[ch_index];
  403. int end_freq = s->end_freq[ch_index];
  404. uint8_t *baps = s->bap[ch_index];
  405. int8_t *exps = s->dexps[ch_index];
  406. int *coeffs = s->fixed_coeffs[ch_index];
  407. GetBitContext *gbc = &s->gbc;
  408. int freq;
  409. for(freq = start_freq; freq < end_freq; freq++){
  410. int bap = baps[freq];
  411. int mantissa;
  412. switch(bap){
  413. case 0:
  414. mantissa = (av_lfg_get(&s->dith_state) & 0x7FFFFF) - 0x400000;
  415. break;
  416. case 1:
  417. if(m->b1){
  418. m->b1--;
  419. mantissa = m->b1_mant[m->b1];
  420. }
  421. else{
  422. int bits = get_bits(gbc, 5);
  423. mantissa = b1_mantissas[bits][0];
  424. m->b1_mant[1] = b1_mantissas[bits][1];
  425. m->b1_mant[0] = b1_mantissas[bits][2];
  426. m->b1 = 2;
  427. }
  428. break;
  429. case 2:
  430. if(m->b2){
  431. m->b2--;
  432. mantissa = m->b2_mant[m->b2];
  433. }
  434. else{
  435. int bits = get_bits(gbc, 7);
  436. mantissa = b2_mantissas[bits][0];
  437. m->b2_mant[1] = b2_mantissas[bits][1];
  438. m->b2_mant[0] = b2_mantissas[bits][2];
  439. m->b2 = 2;
  440. }
  441. break;
  442. case 3:
  443. mantissa = b3_mantissas[get_bits(gbc, 3)];
  444. break;
  445. case 4:
  446. if(m->b4){
  447. m->b4 = 0;
  448. mantissa = m->b4_mant;
  449. }
  450. else{
  451. int bits = get_bits(gbc, 7);
  452. mantissa = b4_mantissas[bits][0];
  453. m->b4_mant = b4_mantissas[bits][1];
  454. m->b4 = 1;
  455. }
  456. break;
  457. case 5:
  458. mantissa = b5_mantissas[get_bits(gbc, 4)];
  459. break;
  460. default: /* 6 to 15 */
  461. mantissa = get_bits(gbc, quantization_tab[bap]);
  462. /* Shift mantissa and sign-extend it. */
  463. mantissa = (mantissa << (32-quantization_tab[bap]))>>8;
  464. break;
  465. }
  466. coeffs[freq] = mantissa >> exps[freq];
  467. }
  468. }
  469. /**
  470. * Remove random dithering from coefficients with zero-bit mantissas
  471. * reference: Section 7.3.4 Dither for Zero Bit Mantissas (bap=0)
  472. */
  473. static void remove_dithering(AC3DecodeContext *s) {
  474. int ch, i;
  475. int end=0;
  476. int *coeffs;
  477. uint8_t *bap;
  478. for(ch=1; ch<=s->fbw_channels; ch++) {
  479. if(!s->dither_flag[ch]) {
  480. coeffs = s->fixed_coeffs[ch];
  481. bap = s->bap[ch];
  482. if(s->channel_in_cpl[ch])
  483. end = s->start_freq[CPL_CH];
  484. else
  485. end = s->end_freq[ch];
  486. for(i=0; i<end; i++) {
  487. if(!bap[i])
  488. coeffs[i] = 0;
  489. }
  490. if(s->channel_in_cpl[ch]) {
  491. bap = s->bap[CPL_CH];
  492. for(; i<s->end_freq[CPL_CH]; i++) {
  493. if(!bap[i])
  494. coeffs[i] = 0;
  495. }
  496. }
  497. }
  498. }
  499. }
  500. static void decode_transform_coeffs_ch(AC3DecodeContext *s, int blk, int ch,
  501. mant_groups *m)
  502. {
  503. if (!s->channel_uses_aht[ch]) {
  504. ac3_decode_transform_coeffs_ch(s, ch, m);
  505. } else {
  506. /* if AHT is used, mantissas for all blocks are encoded in the first
  507. block of the frame. */
  508. int bin;
  509. if (!blk)
  510. ff_eac3_decode_transform_coeffs_aht_ch(s, ch);
  511. for (bin = s->start_freq[ch]; bin < s->end_freq[ch]; bin++) {
  512. s->fixed_coeffs[ch][bin] = s->pre_mantissa[ch][bin][blk] >> s->dexps[ch][bin];
  513. }
  514. }
  515. }
  516. /**
  517. * Decode the transform coefficients.
  518. */
  519. static void decode_transform_coeffs(AC3DecodeContext *s, int blk)
  520. {
  521. int ch, end;
  522. int got_cplchan = 0;
  523. mant_groups m;
  524. m.b1 = m.b2 = m.b4 = 0;
  525. for (ch = 1; ch <= s->channels; ch++) {
  526. /* transform coefficients for full-bandwidth channel */
  527. decode_transform_coeffs_ch(s, blk, ch, &m);
  528. /* tranform coefficients for coupling channel come right after the
  529. coefficients for the first coupled channel*/
  530. if (s->channel_in_cpl[ch]) {
  531. if (!got_cplchan) {
  532. decode_transform_coeffs_ch(s, blk, CPL_CH, &m);
  533. calc_transform_coeffs_cpl(s);
  534. got_cplchan = 1;
  535. }
  536. end = s->end_freq[CPL_CH];
  537. } else {
  538. end = s->end_freq[ch];
  539. }
  540. do
  541. s->fixed_coeffs[ch][end] = 0;
  542. while(++end < 256);
  543. }
  544. /* zero the dithered coefficients for appropriate channels */
  545. remove_dithering(s);
  546. }
  547. /**
  548. * Stereo rematrixing.
  549. * reference: Section 7.5.4 Rematrixing : Decoding Technique
  550. */
  551. static void do_rematrixing(AC3DecodeContext *s)
  552. {
  553. int bnd, i;
  554. int end, bndend;
  555. int tmp0, tmp1;
  556. end = FFMIN(s->end_freq[1], s->end_freq[2]);
  557. for(bnd=0; bnd<s->num_rematrixing_bands; bnd++) {
  558. if(s->rematrixing_flags[bnd]) {
  559. bndend = FFMIN(end, ff_ac3_rematrix_band_tab[bnd+1]);
  560. for(i=ff_ac3_rematrix_band_tab[bnd]; i<bndend; i++) {
  561. tmp0 = s->fixed_coeffs[1][i];
  562. tmp1 = s->fixed_coeffs[2][i];
  563. s->fixed_coeffs[1][i] = tmp0 + tmp1;
  564. s->fixed_coeffs[2][i] = tmp0 - tmp1;
  565. }
  566. }
  567. }
  568. }
  569. /**
  570. * Inverse MDCT Transform.
  571. * Convert frequency domain coefficients to time-domain audio samples.
  572. * reference: Section 7.9.4 Transformation Equations
  573. */
  574. static inline void do_imdct(AC3DecodeContext *s, int channels)
  575. {
  576. int ch;
  577. float add_bias = s->add_bias;
  578. if(s->out_channels==1 && channels>1)
  579. add_bias *= LEVEL_MINUS_3DB; // compensate for the gain in downmix
  580. for (ch=1; ch<=channels; ch++) {
  581. if (s->block_switch[ch]) {
  582. int i;
  583. float *x = s->tmp_output+128;
  584. for(i=0; i<128; i++)
  585. x[i] = s->transform_coeffs[ch][2*i];
  586. ff_imdct_half(&s->imdct_256, s->tmp_output, x);
  587. s->dsp.vector_fmul_window(s->output[ch-1], s->delay[ch-1], s->tmp_output, s->window, add_bias, 128);
  588. for(i=0; i<128; i++)
  589. x[i] = s->transform_coeffs[ch][2*i+1];
  590. ff_imdct_half(&s->imdct_256, s->delay[ch-1], x);
  591. } else {
  592. ff_imdct_half(&s->imdct_512, s->tmp_output, s->transform_coeffs[ch]);
  593. s->dsp.vector_fmul_window(s->output[ch-1], s->delay[ch-1], s->tmp_output, s->window, add_bias, 128);
  594. memcpy(s->delay[ch-1], s->tmp_output+128, 128*sizeof(float));
  595. }
  596. }
  597. }
  598. /**
  599. * Downmix the output to mono or stereo.
  600. */
  601. void ff_ac3_downmix_c(float (*samples)[256], float (*matrix)[2], int out_ch, int in_ch, int len)
  602. {
  603. int i, j;
  604. float v0, v1;
  605. if(out_ch == 2) {
  606. for(i=0; i<len; i++) {
  607. v0 = v1 = 0.0f;
  608. for(j=0; j<in_ch; j++) {
  609. v0 += samples[j][i] * matrix[j][0];
  610. v1 += samples[j][i] * matrix[j][1];
  611. }
  612. samples[0][i] = v0;
  613. samples[1][i] = v1;
  614. }
  615. } else if(out_ch == 1) {
  616. for(i=0; i<len; i++) {
  617. v0 = 0.0f;
  618. for(j=0; j<in_ch; j++)
  619. v0 += samples[j][i] * matrix[j][0];
  620. samples[0][i] = v0;
  621. }
  622. }
  623. }
  624. /**
  625. * Upmix delay samples from stereo to original channel layout.
  626. */
  627. static void ac3_upmix_delay(AC3DecodeContext *s)
  628. {
  629. int channel_data_size = sizeof(s->delay[0]);
  630. switch(s->channel_mode) {
  631. case AC3_CHMODE_DUALMONO:
  632. case AC3_CHMODE_STEREO:
  633. /* upmix mono to stereo */
  634. memcpy(s->delay[1], s->delay[0], channel_data_size);
  635. break;
  636. case AC3_CHMODE_2F2R:
  637. memset(s->delay[3], 0, channel_data_size);
  638. case AC3_CHMODE_2F1R:
  639. memset(s->delay[2], 0, channel_data_size);
  640. break;
  641. case AC3_CHMODE_3F2R:
  642. memset(s->delay[4], 0, channel_data_size);
  643. case AC3_CHMODE_3F1R:
  644. memset(s->delay[3], 0, channel_data_size);
  645. case AC3_CHMODE_3F:
  646. memcpy(s->delay[2], s->delay[1], channel_data_size);
  647. memset(s->delay[1], 0, channel_data_size);
  648. break;
  649. }
  650. }
  651. /**
  652. * Decode band structure for coupling, spectral extension, or enhanced coupling.
  653. * @param[in] gbc bit reader context
  654. * @param[in] blk block number
  655. * @param[in] eac3 flag to indicate E-AC-3
  656. * @param[in] ecpl flag to indicate enhanced coupling
  657. * @param[in] start_subband subband number for start of range
  658. * @param[in] end_subband subband number for end of range
  659. * @param[in] default_band_struct default band structure table
  660. * @param[out] band_struct decoded band structure
  661. * @param[out] num_subbands number of subbands (optionally NULL)
  662. * @param[out] num_bands number of bands (optionally NULL)
  663. * @param[out] band_sizes array containing the number of bins in each band (optionally NULL)
  664. */
  665. static void decode_band_structure(GetBitContext *gbc, int blk, int eac3,
  666. int ecpl, int start_subband, int end_subband,
  667. const uint8_t *default_band_struct,
  668. uint8_t *band_struct, int *num_subbands,
  669. int *num_bands, uint8_t *band_sizes)
  670. {
  671. int subbnd, bnd, n_subbands, n_bands=0;
  672. uint8_t bnd_sz[22];
  673. n_subbands = end_subband - start_subband;
  674. /* decode band structure from bitstream or use default */
  675. if (!eac3 || get_bits1(gbc)) {
  676. for (subbnd = 0; subbnd < n_subbands - 1; subbnd++) {
  677. band_struct[subbnd] = get_bits1(gbc);
  678. }
  679. } else if (!blk) {
  680. memcpy(band_struct,
  681. &default_band_struct[start_subband+1],
  682. n_subbands-1);
  683. }
  684. band_struct[n_subbands-1] = 0;
  685. /* calculate number of bands and band sizes based on band structure.
  686. note that the first 4 subbands in enhanced coupling span only 6 bins
  687. instead of 12. */
  688. if (num_bands || band_sizes ) {
  689. n_bands = n_subbands;
  690. bnd_sz[0] = ecpl ? 6 : 12;
  691. for (bnd = 0, subbnd = 1; subbnd < n_subbands; subbnd++) {
  692. int subbnd_size = (ecpl && subbnd < 4) ? 6 : 12;
  693. if (band_struct[subbnd-1]) {
  694. n_bands--;
  695. bnd_sz[bnd] += subbnd_size;
  696. } else {
  697. bnd_sz[++bnd] = subbnd_size;
  698. }
  699. }
  700. }
  701. /* set optional output params */
  702. if (num_subbands)
  703. *num_subbands = n_subbands;
  704. if (num_bands)
  705. *num_bands = n_bands;
  706. if (band_sizes)
  707. memcpy(band_sizes, bnd_sz, n_bands);
  708. }
  709. /**
  710. * Decode a single audio block from the AC-3 bitstream.
  711. */
  712. static int decode_audio_block(AC3DecodeContext *s, int blk)
  713. {
  714. int fbw_channels = s->fbw_channels;
  715. int channel_mode = s->channel_mode;
  716. int i, bnd, seg, ch;
  717. int different_transforms;
  718. int downmix_output;
  719. int cpl_in_use;
  720. GetBitContext *gbc = &s->gbc;
  721. uint8_t bit_alloc_stages[AC3_MAX_CHANNELS];
  722. memset(bit_alloc_stages, 0, AC3_MAX_CHANNELS);
  723. /* block switch flags */
  724. different_transforms = 0;
  725. if (s->block_switch_syntax) {
  726. for (ch = 1; ch <= fbw_channels; ch++) {
  727. s->block_switch[ch] = get_bits1(gbc);
  728. if(ch > 1 && s->block_switch[ch] != s->block_switch[1])
  729. different_transforms = 1;
  730. }
  731. }
  732. /* dithering flags */
  733. if (s->dither_flag_syntax) {
  734. for (ch = 1; ch <= fbw_channels; ch++) {
  735. s->dither_flag[ch] = get_bits1(gbc);
  736. }
  737. }
  738. /* dynamic range */
  739. i = !(s->channel_mode);
  740. do {
  741. if(get_bits1(gbc)) {
  742. s->dynamic_range[i] = ((dynamic_range_tab[get_bits(gbc, 8)]-1.0) *
  743. s->avctx->drc_scale)+1.0;
  744. } else if(blk == 0) {
  745. s->dynamic_range[i] = 1.0f;
  746. }
  747. } while(i--);
  748. /* spectral extension strategy */
  749. if (s->eac3 && (!blk || get_bits1(gbc))) {
  750. if (get_bits1(gbc)) {
  751. ff_log_missing_feature(s->avctx, "Spectral extension", 1);
  752. return -1;
  753. }
  754. /* TODO: parse spectral extension strategy info */
  755. }
  756. /* TODO: spectral extension coordinates */
  757. /* coupling strategy */
  758. if (s->eac3 ? s->cpl_strategy_exists[blk] : get_bits1(gbc)) {
  759. memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
  760. if (!s->eac3)
  761. s->cpl_in_use[blk] = get_bits1(gbc);
  762. if (s->cpl_in_use[blk]) {
  763. /* coupling in use */
  764. int cpl_start_subband, cpl_end_subband;
  765. if (channel_mode < AC3_CHMODE_STEREO) {
  766. av_log(s->avctx, AV_LOG_ERROR, "coupling not allowed in mono or dual-mono\n");
  767. return -1;
  768. }
  769. /* check for enhanced coupling */
  770. if (s->eac3 && get_bits1(gbc)) {
  771. /* TODO: parse enhanced coupling strategy info */
  772. ff_log_missing_feature(s->avctx, "Enhanced coupling", 1);
  773. return -1;
  774. }
  775. /* determine which channels are coupled */
  776. if (s->eac3 && s->channel_mode == AC3_CHMODE_STEREO) {
  777. s->channel_in_cpl[1] = 1;
  778. s->channel_in_cpl[2] = 1;
  779. } else {
  780. for (ch = 1; ch <= fbw_channels; ch++)
  781. s->channel_in_cpl[ch] = get_bits1(gbc);
  782. }
  783. /* phase flags in use */
  784. if (channel_mode == AC3_CHMODE_STEREO)
  785. s->phase_flags_in_use = get_bits1(gbc);
  786. /* coupling frequency range */
  787. /* TODO: modify coupling end freq if spectral extension is used */
  788. cpl_start_subband = get_bits(gbc, 4);
  789. cpl_end_subband = get_bits(gbc, 4) + 3;
  790. s->num_cpl_subbands = cpl_end_subband - cpl_start_subband;
  791. if (s->num_cpl_subbands < 0) {
  792. av_log(s->avctx, AV_LOG_ERROR, "invalid coupling range (%d > %d)\n",
  793. cpl_start_subband, cpl_end_subband);
  794. return -1;
  795. }
  796. s->start_freq[CPL_CH] = cpl_start_subband * 12 + 37;
  797. s->end_freq[CPL_CH] = cpl_end_subband * 12 + 37;
  798. decode_band_structure(gbc, blk, s->eac3, 0,
  799. cpl_start_subband, cpl_end_subband,
  800. ff_eac3_default_cpl_band_struct,
  801. s->cpl_band_struct, &s->num_cpl_subbands,
  802. &s->num_cpl_bands, NULL);
  803. } else {
  804. /* coupling not in use */
  805. for (ch = 1; ch <= fbw_channels; ch++) {
  806. s->channel_in_cpl[ch] = 0;
  807. s->first_cpl_coords[ch] = 1;
  808. }
  809. s->first_cpl_leak = s->eac3;
  810. s->phase_flags_in_use = 0;
  811. }
  812. } else if (!s->eac3) {
  813. if(!blk) {
  814. av_log(s->avctx, AV_LOG_ERROR, "new coupling strategy must be present in block 0\n");
  815. return -1;
  816. } else {
  817. s->cpl_in_use[blk] = s->cpl_in_use[blk-1];
  818. }
  819. }
  820. cpl_in_use = s->cpl_in_use[blk];
  821. /* coupling coordinates */
  822. if (cpl_in_use) {
  823. int cpl_coords_exist = 0;
  824. for (ch = 1; ch <= fbw_channels; ch++) {
  825. if (s->channel_in_cpl[ch]) {
  826. if ((s->eac3 && s->first_cpl_coords[ch]) || get_bits1(gbc)) {
  827. int master_cpl_coord, cpl_coord_exp, cpl_coord_mant;
  828. s->first_cpl_coords[ch] = 0;
  829. cpl_coords_exist = 1;
  830. master_cpl_coord = 3 * get_bits(gbc, 2);
  831. for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
  832. cpl_coord_exp = get_bits(gbc, 4);
  833. cpl_coord_mant = get_bits(gbc, 4);
  834. if (cpl_coord_exp == 15)
  835. s->cpl_coords[ch][bnd] = cpl_coord_mant << 22;
  836. else
  837. s->cpl_coords[ch][bnd] = (cpl_coord_mant + 16) << 21;
  838. s->cpl_coords[ch][bnd] >>= (cpl_coord_exp + master_cpl_coord);
  839. }
  840. } else if (!blk) {
  841. av_log(s->avctx, AV_LOG_ERROR, "new coupling coordinates must be present in block 0\n");
  842. return -1;
  843. }
  844. } else {
  845. /* channel not in coupling */
  846. s->first_cpl_coords[ch] = 1;
  847. }
  848. }
  849. /* phase flags */
  850. if (channel_mode == AC3_CHMODE_STEREO && cpl_coords_exist) {
  851. for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {
  852. s->phase_flags[bnd] = s->phase_flags_in_use? get_bits1(gbc) : 0;
  853. }
  854. }
  855. }
  856. /* stereo rematrixing strategy and band structure */
  857. if (channel_mode == AC3_CHMODE_STEREO) {
  858. if ((s->eac3 && !blk) || get_bits1(gbc)) {
  859. s->num_rematrixing_bands = 4;
  860. if(cpl_in_use && s->start_freq[CPL_CH] <= 61)
  861. s->num_rematrixing_bands -= 1 + (s->start_freq[CPL_CH] == 37);
  862. for(bnd=0; bnd<s->num_rematrixing_bands; bnd++)
  863. s->rematrixing_flags[bnd] = get_bits1(gbc);
  864. } else if (!blk) {
  865. av_log(s->avctx, AV_LOG_ERROR, "new rematrixing strategy must be present in block 0\n");
  866. return -1;
  867. }
  868. }
  869. /* exponent strategies for each channel */
  870. for (ch = !cpl_in_use; ch <= s->channels; ch++) {
  871. if (!s->eac3)
  872. s->exp_strategy[blk][ch] = get_bits(gbc, 2 - (ch == s->lfe_ch));
  873. if(s->exp_strategy[blk][ch] != EXP_REUSE)
  874. bit_alloc_stages[ch] = 3;
  875. }
  876. /* channel bandwidth */
  877. for (ch = 1; ch <= fbw_channels; ch++) {
  878. s->start_freq[ch] = 0;
  879. if (s->exp_strategy[blk][ch] != EXP_REUSE) {
  880. int group_size;
  881. int prev = s->end_freq[ch];
  882. if (s->channel_in_cpl[ch])
  883. s->end_freq[ch] = s->start_freq[CPL_CH];
  884. else {
  885. int bandwidth_code = get_bits(gbc, 6);
  886. if (bandwidth_code > 60) {
  887. av_log(s->avctx, AV_LOG_ERROR, "bandwidth code = %d > 60\n", bandwidth_code);
  888. return -1;
  889. }
  890. s->end_freq[ch] = bandwidth_code * 3 + 73;
  891. }
  892. group_size = 3 << (s->exp_strategy[blk][ch] - 1);
  893. s->num_exp_groups[ch] = (s->end_freq[ch]+group_size-4) / group_size;
  894. if(blk > 0 && s->end_freq[ch] != prev)
  895. memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);
  896. }
  897. }
  898. if (cpl_in_use && s->exp_strategy[blk][CPL_CH] != EXP_REUSE) {
  899. s->num_exp_groups[CPL_CH] = (s->end_freq[CPL_CH] - s->start_freq[CPL_CH]) /
  900. (3 << (s->exp_strategy[blk][CPL_CH] - 1));
  901. }
  902. /* decode exponents for each channel */
  903. for (ch = !cpl_in_use; ch <= s->channels; ch++) {
  904. if (s->exp_strategy[blk][ch] != EXP_REUSE) {
  905. s->dexps[ch][0] = get_bits(gbc, 4) << !ch;
  906. if (decode_exponents(gbc, s->exp_strategy[blk][ch],
  907. s->num_exp_groups[ch], s->dexps[ch][0],
  908. &s->dexps[ch][s->start_freq[ch]+!!ch])) {
  909. av_log(s->avctx, AV_LOG_ERROR, "exponent out-of-range\n");
  910. return -1;
  911. }
  912. if(ch != CPL_CH && ch != s->lfe_ch)
  913. skip_bits(gbc, 2); /* skip gainrng */
  914. }
  915. }
  916. /* bit allocation information */
  917. if (s->bit_allocation_syntax) {
  918. if (get_bits1(gbc)) {
  919. s->bit_alloc_params.slow_decay = ff_ac3_slow_decay_tab[get_bits(gbc, 2)] >> s->bit_alloc_params.sr_shift;
  920. s->bit_alloc_params.fast_decay = ff_ac3_fast_decay_tab[get_bits(gbc, 2)] >> s->bit_alloc_params.sr_shift;
  921. s->bit_alloc_params.slow_gain = ff_ac3_slow_gain_tab[get_bits(gbc, 2)];
  922. s->bit_alloc_params.db_per_bit = ff_ac3_db_per_bit_tab[get_bits(gbc, 2)];
  923. s->bit_alloc_params.floor = ff_ac3_floor_tab[get_bits(gbc, 3)];
  924. for(ch=!cpl_in_use; ch<=s->channels; ch++)
  925. bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
  926. } else if (!blk) {
  927. av_log(s->avctx, AV_LOG_ERROR, "new bit allocation info must be present in block 0\n");
  928. return -1;
  929. }
  930. }
  931. /* signal-to-noise ratio offsets and fast gains (signal-to-mask ratios) */
  932. if(!s->eac3 || !blk){
  933. if(s->snr_offset_strategy && get_bits1(gbc)) {
  934. int snr = 0;
  935. int csnr;
  936. csnr = (get_bits(gbc, 6) - 15) << 4;
  937. for (i = ch = !cpl_in_use; ch <= s->channels; ch++) {
  938. /* snr offset */
  939. if (ch == i || s->snr_offset_strategy == 2)
  940. snr = (csnr + get_bits(gbc, 4)) << 2;
  941. /* run at least last bit allocation stage if snr offset changes */
  942. if(blk && s->snr_offset[ch] != snr) {
  943. bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 1);
  944. }
  945. s->snr_offset[ch] = snr;
  946. /* fast gain (normal AC-3 only) */
  947. if (!s->eac3) {
  948. int prev = s->fast_gain[ch];
  949. s->fast_gain[ch] = ff_ac3_fast_gain_tab[get_bits(gbc, 3)];
  950. /* run last 2 bit allocation stages if fast gain changes */
  951. if(blk && prev != s->fast_gain[ch])
  952. bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
  953. }
  954. }
  955. } else if (!s->eac3 && !blk) {
  956. av_log(s->avctx, AV_LOG_ERROR, "new snr offsets must be present in block 0\n");
  957. return -1;
  958. }
  959. }
  960. /* fast gain (E-AC-3 only) */
  961. if (s->fast_gain_syntax && get_bits1(gbc)) {
  962. for (ch = !cpl_in_use; ch <= s->channels; ch++) {
  963. int prev = s->fast_gain[ch];
  964. s->fast_gain[ch] = ff_ac3_fast_gain_tab[get_bits(gbc, 3)];
  965. /* run last 2 bit allocation stages if fast gain changes */
  966. if(blk && prev != s->fast_gain[ch])
  967. bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
  968. }
  969. } else if (s->eac3 && !blk) {
  970. for (ch = !cpl_in_use; ch <= s->channels; ch++)
  971. s->fast_gain[ch] = ff_ac3_fast_gain_tab[4];
  972. }
  973. /* E-AC-3 to AC-3 converter SNR offset */
  974. if (s->frame_type == EAC3_FRAME_TYPE_INDEPENDENT && get_bits1(gbc)) {
  975. skip_bits(gbc, 10); // skip converter snr offset
  976. }
  977. /* coupling leak information */
  978. if (cpl_in_use) {
  979. if (s->first_cpl_leak || get_bits1(gbc)) {
  980. int fl = get_bits(gbc, 3);
  981. int sl = get_bits(gbc, 3);
  982. /* run last 2 bit allocation stages for coupling channel if
  983. coupling leak changes */
  984. if(blk && (fl != s->bit_alloc_params.cpl_fast_leak ||
  985. sl != s->bit_alloc_params.cpl_slow_leak)) {
  986. bit_alloc_stages[CPL_CH] = FFMAX(bit_alloc_stages[CPL_CH], 2);
  987. }
  988. s->bit_alloc_params.cpl_fast_leak = fl;
  989. s->bit_alloc_params.cpl_slow_leak = sl;
  990. } else if (!s->eac3 && !blk) {
  991. av_log(s->avctx, AV_LOG_ERROR, "new coupling leak info must be present in block 0\n");
  992. return -1;
  993. }
  994. s->first_cpl_leak = 0;
  995. }
  996. /* delta bit allocation information */
  997. if (s->dba_syntax && get_bits1(gbc)) {
  998. /* delta bit allocation exists (strategy) */
  999. for (ch = !cpl_in_use; ch <= fbw_channels; ch++) {
  1000. s->dba_mode[ch] = get_bits(gbc, 2);
  1001. if (s->dba_mode[ch] == DBA_RESERVED) {
  1002. av_log(s->avctx, AV_LOG_ERROR, "delta bit allocation strategy reserved\n");
  1003. return -1;
  1004. }
  1005. bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
  1006. }
  1007. /* channel delta offset, len and bit allocation */
  1008. for (ch = !cpl_in_use; ch <= fbw_channels; ch++) {
  1009. if (s->dba_mode[ch] == DBA_NEW) {
  1010. s->dba_nsegs[ch] = get_bits(gbc, 3);
  1011. for (seg = 0; seg <= s->dba_nsegs[ch]; seg++) {
  1012. s->dba_offsets[ch][seg] = get_bits(gbc, 5);
  1013. s->dba_lengths[ch][seg] = get_bits(gbc, 4);
  1014. s->dba_values[ch][seg] = get_bits(gbc, 3);
  1015. }
  1016. /* run last 2 bit allocation stages if new dba values */
  1017. bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);
  1018. }
  1019. }
  1020. } else if(blk == 0) {
  1021. for(ch=0; ch<=s->channels; ch++) {
  1022. s->dba_mode[ch] = DBA_NONE;
  1023. }
  1024. }
  1025. /* Bit allocation */
  1026. for(ch=!cpl_in_use; ch<=s->channels; ch++) {
  1027. if(bit_alloc_stages[ch] > 2) {
  1028. /* Exponent mapping into PSD and PSD integration */
  1029. ff_ac3_bit_alloc_calc_psd(s->dexps[ch],
  1030. s->start_freq[ch], s->end_freq[ch],
  1031. s->psd[ch], s->band_psd[ch]);
  1032. }
  1033. if(bit_alloc_stages[ch] > 1) {
  1034. /* Compute excitation function, Compute masking curve, and
  1035. Apply delta bit allocation */
  1036. if (ff_ac3_bit_alloc_calc_mask(&s->bit_alloc_params, s->band_psd[ch],
  1037. s->start_freq[ch], s->end_freq[ch],
  1038. s->fast_gain[ch], (ch == s->lfe_ch),
  1039. s->dba_mode[ch], s->dba_nsegs[ch],
  1040. s->dba_offsets[ch], s->dba_lengths[ch],
  1041. s->dba_values[ch], s->mask[ch])) {
  1042. av_log(s->avctx, AV_LOG_ERROR, "error in bit allocation\n");
  1043. return -1;
  1044. }
  1045. }
  1046. if(bit_alloc_stages[ch] > 0) {
  1047. /* Compute bit allocation */
  1048. const uint8_t *bap_tab = s->channel_uses_aht[ch] ?
  1049. ff_eac3_hebap_tab : ff_ac3_bap_tab;
  1050. ff_ac3_bit_alloc_calc_bap(s->mask[ch], s->psd[ch],
  1051. s->start_freq[ch], s->end_freq[ch],
  1052. s->snr_offset[ch],
  1053. s->bit_alloc_params.floor,
  1054. bap_tab, s->bap[ch]);
  1055. }
  1056. }
  1057. /* unused dummy data */
  1058. if (s->skip_syntax && get_bits1(gbc)) {
  1059. int skipl = get_bits(gbc, 9);
  1060. while(skipl--)
  1061. skip_bits(gbc, 8);
  1062. }
  1063. /* unpack the transform coefficients
  1064. this also uncouples channels if coupling is in use. */
  1065. decode_transform_coeffs(s, blk);
  1066. /* TODO: generate enhanced coupling coordinates and uncouple */
  1067. /* TODO: apply spectral extension */
  1068. /* recover coefficients if rematrixing is in use */
  1069. if(s->channel_mode == AC3_CHMODE_STEREO)
  1070. do_rematrixing(s);
  1071. /* apply scaling to coefficients (headroom, dynrng) */
  1072. for(ch=1; ch<=s->channels; ch++) {
  1073. float gain = s->mul_bias / 4194304.0f;
  1074. if(s->channel_mode == AC3_CHMODE_DUALMONO) {
  1075. gain *= s->dynamic_range[ch-1];
  1076. } else {
  1077. gain *= s->dynamic_range[0];
  1078. }
  1079. s->dsp.int32_to_float_fmul_scalar(s->transform_coeffs[ch], s->fixed_coeffs[ch], gain, 256);
  1080. }
  1081. /* downmix and MDCT. order depends on whether block switching is used for
  1082. any channel in this block. this is because coefficients for the long
  1083. and short transforms cannot be mixed. */
  1084. downmix_output = s->channels != s->out_channels &&
  1085. !((s->output_mode & AC3_OUTPUT_LFEON) &&
  1086. s->fbw_channels == s->out_channels);
  1087. if(different_transforms) {
  1088. /* the delay samples have already been downmixed, so we upmix the delay
  1089. samples in order to reconstruct all channels before downmixing. */
  1090. if(s->downmixed) {
  1091. s->downmixed = 0;
  1092. ac3_upmix_delay(s);
  1093. }
  1094. do_imdct(s, s->channels);
  1095. if(downmix_output) {
  1096. s->dsp.ac3_downmix(s->output, s->downmix_coeffs, s->out_channels, s->fbw_channels, 256);
  1097. }
  1098. } else {
  1099. if(downmix_output) {
  1100. s->dsp.ac3_downmix(s->transform_coeffs+1, s->downmix_coeffs, s->out_channels, s->fbw_channels, 256);
  1101. }
  1102. if(downmix_output && !s->downmixed) {
  1103. s->downmixed = 1;
  1104. s->dsp.ac3_downmix(s->delay, s->downmix_coeffs, s->out_channels, s->fbw_channels, 128);
  1105. }
  1106. do_imdct(s, s->out_channels);
  1107. }
  1108. return 0;
  1109. }
  1110. /**
  1111. * Decode a single AC-3 frame.
  1112. */
  1113. static int ac3_decode_frame(AVCodecContext * avctx, void *data, int *data_size,
  1114. const uint8_t *buf, int buf_size)
  1115. {
  1116. AC3DecodeContext *s = avctx->priv_data;
  1117. int16_t *out_samples = (int16_t *)data;
  1118. int blk, ch, err;
  1119. /* initialize the GetBitContext with the start of valid AC-3 Frame */
  1120. if (s->input_buffer) {
  1121. /* copy input buffer to decoder context to avoid reading past the end
  1122. of the buffer, which can be caused by a damaged input stream. */
  1123. memcpy(s->input_buffer, buf, FFMIN(buf_size, AC3_FRAME_BUFFER_SIZE));
  1124. init_get_bits(&s->gbc, s->input_buffer, buf_size * 8);
  1125. } else {
  1126. init_get_bits(&s->gbc, buf, buf_size * 8);
  1127. }
  1128. /* parse the syncinfo */
  1129. *data_size = 0;
  1130. err = parse_frame_header(s);
  1131. /* check that reported frame size fits in input buffer */
  1132. if(s->frame_size > buf_size) {
  1133. av_log(avctx, AV_LOG_ERROR, "incomplete frame\n");
  1134. err = AAC_AC3_PARSE_ERROR_FRAME_SIZE;
  1135. }
  1136. /* check for crc mismatch */
  1137. if(err != AAC_AC3_PARSE_ERROR_FRAME_SIZE && avctx->error_recognition >= FF_ER_CAREFUL) {
  1138. if(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, &buf[2], s->frame_size-2)) {
  1139. av_log(avctx, AV_LOG_ERROR, "frame CRC mismatch\n");
  1140. err = AAC_AC3_PARSE_ERROR_CRC;
  1141. }
  1142. }
  1143. if(err && err != AAC_AC3_PARSE_ERROR_CRC) {
  1144. switch(err) {
  1145. case AAC_AC3_PARSE_ERROR_SYNC:
  1146. av_log(avctx, AV_LOG_ERROR, "frame sync error\n");
  1147. return -1;
  1148. case AAC_AC3_PARSE_ERROR_BSID:
  1149. av_log(avctx, AV_LOG_ERROR, "invalid bitstream id\n");
  1150. break;
  1151. case AAC_AC3_PARSE_ERROR_SAMPLE_RATE:
  1152. av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
  1153. break;
  1154. case AAC_AC3_PARSE_ERROR_FRAME_SIZE:
  1155. av_log(avctx, AV_LOG_ERROR, "invalid frame size\n");
  1156. break;
  1157. case AAC_AC3_PARSE_ERROR_FRAME_TYPE:
  1158. /* skip frame if CRC is ok. otherwise use error concealment. */
  1159. /* TODO: add support for substreams and dependent frames */
  1160. if(s->frame_type == EAC3_FRAME_TYPE_DEPENDENT || s->substreamid) {
  1161. av_log(avctx, AV_LOG_ERROR, "unsupported frame type : skipping frame\n");
  1162. return s->frame_size;
  1163. } else {
  1164. av_log(avctx, AV_LOG_ERROR, "invalid frame type\n");
  1165. }
  1166. break;
  1167. default:
  1168. av_log(avctx, AV_LOG_ERROR, "invalid header\n");
  1169. break;
  1170. }
  1171. }
  1172. /* if frame is ok, set audio parameters */
  1173. if (!err) {
  1174. avctx->sample_rate = s->sample_rate;
  1175. avctx->bit_rate = s->bit_rate;
  1176. /* channel config */
  1177. s->out_channels = s->channels;
  1178. s->output_mode = s->channel_mode;
  1179. if(s->lfe_on)
  1180. s->output_mode |= AC3_OUTPUT_LFEON;
  1181. if (avctx->request_channels > 0 && avctx->request_channels <= 2 &&
  1182. avctx->request_channels < s->channels) {
  1183. s->out_channels = avctx->request_channels;
  1184. s->output_mode = avctx->request_channels == 1 ? AC3_CHMODE_MONO : AC3_CHMODE_STEREO;
  1185. }
  1186. avctx->channels = s->out_channels;
  1187. /* set downmixing coefficients if needed */
  1188. if(s->channels != s->out_channels && !((s->output_mode & AC3_OUTPUT_LFEON) &&
  1189. s->fbw_channels == s->out_channels)) {
  1190. set_downmix_coeffs(s);
  1191. }
  1192. } else if (!s->out_channels) {
  1193. s->out_channels = avctx->channels;
  1194. if(s->out_channels < s->channels)
  1195. s->output_mode = s->out_channels == 1 ? AC3_CHMODE_MONO : AC3_CHMODE_STEREO;
  1196. }
  1197. /* decode the audio blocks */
  1198. for (blk = 0; blk < s->num_blocks; blk++) {
  1199. const float *output[s->out_channels];
  1200. if (!err && decode_audio_block(s, blk)) {
  1201. av_log(avctx, AV_LOG_ERROR, "error decoding the audio block\n");
  1202. err = 1;
  1203. }
  1204. for (ch = 0; ch < s->out_channels; ch++)
  1205. output[ch] = s->output[ch];
  1206. s->dsp.float_to_int16_interleave(out_samples, output, 256, s->out_channels);
  1207. out_samples += 256 * s->out_channels;
  1208. }
  1209. *data_size = s->num_blocks * 256 * avctx->channels * sizeof (int16_t);
  1210. return s->frame_size;
  1211. }
  1212. /**
  1213. * Uninitialize the AC-3 decoder.
  1214. */
  1215. static av_cold int ac3_decode_end(AVCodecContext *avctx)
  1216. {
  1217. AC3DecodeContext *s = avctx->priv_data;
  1218. ff_mdct_end(&s->imdct_512);
  1219. ff_mdct_end(&s->imdct_256);
  1220. av_freep(&s->input_buffer);
  1221. return 0;
  1222. }
  1223. AVCodec ac3_decoder = {
  1224. .name = "ac3",
  1225. .type = CODEC_TYPE_AUDIO,
  1226. .id = CODEC_ID_AC3,
  1227. .priv_data_size = sizeof (AC3DecodeContext),
  1228. .init = ac3_decode_init,
  1229. .close = ac3_decode_end,
  1230. .decode = ac3_decode_frame,
  1231. .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52A (AC-3)"),
  1232. };
  1233. AVCodec eac3_decoder = {
  1234. .name = "eac3",
  1235. .type = CODEC_TYPE_AUDIO,
  1236. .id = CODEC_ID_EAC3,
  1237. .priv_data_size = sizeof (AC3DecodeContext),
  1238. .init = ac3_decode_init,
  1239. .close = ac3_decode_end,
  1240. .decode = ac3_decode_frame,
  1241. .long_name = NULL_IF_CONFIG_SMALL("ATSC A/52B (AC-3, E-AC-3)"),
  1242. };