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.

1637 lines
56KB

  1. /*
  2. * MPEG-4 ALS decoder
  3. * Copyright (c) 2009 Thilo Borgmann <thilo.borgmann _at_ googlemail.com>
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file libavcodec/alsdec.c
  23. * MPEG-4 ALS decoder
  24. * @author Thilo Borgmann <thilo.borgmann _at_ googlemail.com>
  25. */
  26. //#define DEBUG
  27. #include "avcodec.h"
  28. #include "get_bits.h"
  29. #include "unary.h"
  30. #include "mpeg4audio.h"
  31. #include "bytestream.h"
  32. #include "bgmc.h"
  33. #include <stdint.h>
  34. /** Rice parameters and corresponding index offsets for decoding the
  35. * indices of scaled PARCOR values. The table choosen is set globally
  36. * by the encoder and stored in ALSSpecificConfig.
  37. */
  38. static const int8_t parcor_rice_table[3][20][2] = {
  39. { {-52, 4}, {-29, 5}, {-31, 4}, { 19, 4}, {-16, 4},
  40. { 12, 3}, { -7, 3}, { 9, 3}, { -5, 3}, { 6, 3},
  41. { -4, 3}, { 3, 3}, { -3, 2}, { 3, 2}, { -2, 2},
  42. { 3, 2}, { -1, 2}, { 2, 2}, { -1, 2}, { 2, 2} },
  43. { {-58, 3}, {-42, 4}, {-46, 4}, { 37, 5}, {-36, 4},
  44. { 29, 4}, {-29, 4}, { 25, 4}, {-23, 4}, { 20, 4},
  45. {-17, 4}, { 16, 4}, {-12, 4}, { 12, 3}, {-10, 4},
  46. { 7, 3}, { -4, 4}, { 3, 3}, { -1, 3}, { 1, 3} },
  47. { {-59, 3}, {-45, 5}, {-50, 4}, { 38, 4}, {-39, 4},
  48. { 32, 4}, {-30, 4}, { 25, 3}, {-23, 3}, { 20, 3},
  49. {-20, 3}, { 16, 3}, {-13, 3}, { 10, 3}, { -7, 3},
  50. { 3, 3}, { 0, 3}, { -1, 3}, { 2, 3}, { -1, 2} }
  51. };
  52. /** Scaled PARCOR values used for the first two PARCOR coefficients.
  53. * To be indexed by the Rice coded indices.
  54. * Generated by: parcor_scaled_values[i] = 32 + ((i * (i+1)) << 7) - (1 << 20)
  55. * Actual values are divided by 32 in order to be stored in 16 bits.
  56. */
  57. static const int16_t parcor_scaled_values[] = {
  58. -1048544 / 32, -1048288 / 32, -1047776 / 32, -1047008 / 32,
  59. -1045984 / 32, -1044704 / 32, -1043168 / 32, -1041376 / 32,
  60. -1039328 / 32, -1037024 / 32, -1034464 / 32, -1031648 / 32,
  61. -1028576 / 32, -1025248 / 32, -1021664 / 32, -1017824 / 32,
  62. -1013728 / 32, -1009376 / 32, -1004768 / 32, -999904 / 32,
  63. -994784 / 32, -989408 / 32, -983776 / 32, -977888 / 32,
  64. -971744 / 32, -965344 / 32, -958688 / 32, -951776 / 32,
  65. -944608 / 32, -937184 / 32, -929504 / 32, -921568 / 32,
  66. -913376 / 32, -904928 / 32, -896224 / 32, -887264 / 32,
  67. -878048 / 32, -868576 / 32, -858848 / 32, -848864 / 32,
  68. -838624 / 32, -828128 / 32, -817376 / 32, -806368 / 32,
  69. -795104 / 32, -783584 / 32, -771808 / 32, -759776 / 32,
  70. -747488 / 32, -734944 / 32, -722144 / 32, -709088 / 32,
  71. -695776 / 32, -682208 / 32, -668384 / 32, -654304 / 32,
  72. -639968 / 32, -625376 / 32, -610528 / 32, -595424 / 32,
  73. -580064 / 32, -564448 / 32, -548576 / 32, -532448 / 32,
  74. -516064 / 32, -499424 / 32, -482528 / 32, -465376 / 32,
  75. -447968 / 32, -430304 / 32, -412384 / 32, -394208 / 32,
  76. -375776 / 32, -357088 / 32, -338144 / 32, -318944 / 32,
  77. -299488 / 32, -279776 / 32, -259808 / 32, -239584 / 32,
  78. -219104 / 32, -198368 / 32, -177376 / 32, -156128 / 32,
  79. -134624 / 32, -112864 / 32, -90848 / 32, -68576 / 32,
  80. -46048 / 32, -23264 / 32, -224 / 32, 23072 / 32,
  81. 46624 / 32, 70432 / 32, 94496 / 32, 118816 / 32,
  82. 143392 / 32, 168224 / 32, 193312 / 32, 218656 / 32,
  83. 244256 / 32, 270112 / 32, 296224 / 32, 322592 / 32,
  84. 349216 / 32, 376096 / 32, 403232 / 32, 430624 / 32,
  85. 458272 / 32, 486176 / 32, 514336 / 32, 542752 / 32,
  86. 571424 / 32, 600352 / 32, 629536 / 32, 658976 / 32,
  87. 688672 / 32, 718624 / 32, 748832 / 32, 779296 / 32,
  88. 810016 / 32, 840992 / 32, 872224 / 32, 903712 / 32,
  89. 935456 / 32, 967456 / 32, 999712 / 32, 1032224 / 32
  90. };
  91. /** Gain values of p(0) for long-term prediction.
  92. * To be indexed by the Rice coded indices.
  93. */
  94. static const uint8_t ltp_gain_values [4][4] = {
  95. { 0, 8, 16, 24},
  96. {32, 40, 48, 56},
  97. {64, 70, 76, 82},
  98. {88, 92, 96, 100}
  99. };
  100. /** Inter-channel weighting factors for multi-channel correlation.
  101. * To be indexed by the Rice coded indices.
  102. */
  103. static const int16_t mcc_weightings[] = {
  104. 204, 192, 179, 166, 153, 140, 128, 115,
  105. 102, 89, 76, 64, 51, 38, 25, 12,
  106. 0, -12, -25, -38, -51, -64, -76, -89,
  107. -102, -115, -128, -140, -153, -166, -179, -192
  108. };
  109. /** Tail codes used in arithmetic coding using block Gilbert-Moore codes.
  110. */
  111. static const uint8_t tail_code[16][6] = {
  112. { 74, 44, 25, 13, 7, 3},
  113. { 68, 42, 24, 13, 7, 3},
  114. { 58, 39, 23, 13, 7, 3},
  115. {126, 70, 37, 19, 10, 5},
  116. {132, 70, 37, 20, 10, 5},
  117. {124, 70, 38, 20, 10, 5},
  118. {120, 69, 37, 20, 11, 5},
  119. {116, 67, 37, 20, 11, 5},
  120. {108, 66, 36, 20, 10, 5},
  121. {102, 62, 36, 20, 10, 5},
  122. { 88, 58, 34, 19, 10, 5},
  123. {162, 89, 49, 25, 13, 7},
  124. {156, 87, 49, 26, 14, 7},
  125. {150, 86, 47, 26, 14, 7},
  126. {142, 84, 47, 26, 14, 7},
  127. {131, 79, 46, 26, 14, 7}
  128. };
  129. enum RA_Flag {
  130. RA_FLAG_NONE,
  131. RA_FLAG_FRAMES,
  132. RA_FLAG_HEADER
  133. };
  134. typedef struct {
  135. uint32_t samples; ///< number of samples, 0xFFFFFFFF if unknown
  136. int resolution; ///< 000 = 8-bit; 001 = 16-bit; 010 = 24-bit; 011 = 32-bit
  137. int floating; ///< 1 = IEEE 32-bit floating-point, 0 = integer
  138. int frame_length; ///< frame length for each frame (last frame may differ)
  139. int ra_distance; ///< distance between RA frames (in frames, 0...255)
  140. enum RA_Flag ra_flag; ///< indicates where the size of ra units is stored
  141. int adapt_order; ///< adaptive order: 1 = on, 0 = off
  142. int coef_table; ///< table index of Rice code parameters
  143. int long_term_prediction; ///< long term prediction (LTP): 1 = on, 0 = off
  144. int max_order; ///< maximum prediction order (0..1023)
  145. int block_switching; ///< number of block switching levels
  146. int bgmc; ///< "Block Gilbert-Moore Code": 1 = on, 0 = off (Rice coding only)
  147. int sb_part; ///< sub-block partition
  148. int joint_stereo; ///< joint stereo: 1 = on, 0 = off
  149. int mc_coding; ///< extended inter-channel coding (multi channel coding): 1 = on, 0 = off
  150. int chan_config; ///< indicates that a chan_config_info field is present
  151. int chan_sort; ///< channel rearrangement: 1 = on, 0 = off
  152. int rlslms; ///< use "Recursive Least Square-Least Mean Square" predictor: 1 = on, 0 = off
  153. int chan_config_info; ///< mapping of channels to loudspeaker locations. Unused until setting channel configuration is implemented.
  154. int *chan_pos; ///< original channel positions
  155. } ALSSpecificConfig;
  156. typedef struct {
  157. int stop_flag;
  158. int master_channel;
  159. int time_diff_flag;
  160. int time_diff_sign;
  161. int time_diff_index;
  162. int weighting[6];
  163. } ALSChannelData;
  164. typedef struct {
  165. AVCodecContext *avctx;
  166. ALSSpecificConfig sconf;
  167. GetBitContext gb;
  168. unsigned int cur_frame_length; ///< length of the current frame to decode
  169. unsigned int frame_id; ///< the frame ID / number of the current frame
  170. unsigned int js_switch; ///< if true, joint-stereo decoding is enforced
  171. unsigned int num_blocks; ///< number of blocks used in the current frame
  172. unsigned int s_max; ///< maximum Rice parameter allowed in entropy coding
  173. uint8_t *bgmc_lut; ///< pointer at lookup tables used for BGMC
  174. unsigned int *bgmc_lut_status; ///< pointer at lookup table status flags used for BGMC
  175. int ltp_lag_length; ///< number of bits used for ltp lag value
  176. int *use_ltp; ///< contains use_ltp flags for all channels
  177. int *ltp_lag; ///< contains ltp lag values for all channels
  178. int **ltp_gain; ///< gain values for ltp 5-tap filter for a channel
  179. int *ltp_gain_buffer; ///< contains all gain values for ltp 5-tap filter
  180. int32_t **quant_cof; ///< quantized parcor coefficients for a channel
  181. int32_t *quant_cof_buffer; ///< contains all quantized parcor coefficients
  182. int32_t **lpc_cof; ///< coefficients of the direct form prediction filter for a channel
  183. int32_t *lpc_cof_buffer; ///< contains all coefficients of the direct form prediction filter
  184. int32_t *lpc_cof_reversed_buffer; ///< temporary buffer to set up a reversed versio of lpc_cof_buffer
  185. ALSChannelData **chan_data; ///< channel data for multi-channel correlation
  186. ALSChannelData *chan_data_buffer; ///< contains channel data for all channels
  187. int *reverted_channels; ///< stores a flag for each reverted channel
  188. int32_t *prev_raw_samples; ///< contains unshifted raw samples from the previous block
  189. int32_t **raw_samples; ///< decoded raw samples for each channel
  190. int32_t *raw_buffer; ///< contains all decoded raw samples including carryover samples
  191. } ALSDecContext;
  192. typedef struct {
  193. unsigned int block_length; ///< number of samples within the block
  194. unsigned int ra_block; ///< if true, this is a random access block
  195. int const_block; ///< if true, this is a constant value block
  196. int32_t const_val; ///< the sample value of a constant block
  197. int js_blocks; ///< true if this block contains a difference signal
  198. unsigned int shift_lsbs; ///< shift of values for this block
  199. unsigned int opt_order; ///< prediction order of this block
  200. int store_prev_samples;///< if true, carryover samples have to be stored
  201. int *use_ltp; ///< if true, long-term prediction is used
  202. int *ltp_lag; ///< lag value for long-term prediction
  203. int *ltp_gain; ///< gain values for ltp 5-tap filter
  204. int32_t *quant_cof; ///< quantized parcor coefficients
  205. int32_t *lpc_cof; ///< coefficients of the direct form prediction
  206. int32_t *raw_samples; ///< decoded raw samples / residuals for this block
  207. int32_t *prev_raw_samples; ///< contains unshifted raw samples from the previous block
  208. int32_t *raw_other; ///< decoded raw samples of the other channel of a channel pair
  209. } ALSBlockData;
  210. static av_cold void dprint_specific_config(ALSDecContext *ctx)
  211. {
  212. #ifdef DEBUG
  213. AVCodecContext *avctx = ctx->avctx;
  214. ALSSpecificConfig *sconf = &ctx->sconf;
  215. dprintf(avctx, "resolution = %i\n", sconf->resolution);
  216. dprintf(avctx, "floating = %i\n", sconf->floating);
  217. dprintf(avctx, "frame_length = %i\n", sconf->frame_length);
  218. dprintf(avctx, "ra_distance = %i\n", sconf->ra_distance);
  219. dprintf(avctx, "ra_flag = %i\n", sconf->ra_flag);
  220. dprintf(avctx, "adapt_order = %i\n", sconf->adapt_order);
  221. dprintf(avctx, "coef_table = %i\n", sconf->coef_table);
  222. dprintf(avctx, "long_term_prediction = %i\n", sconf->long_term_prediction);
  223. dprintf(avctx, "max_order = %i\n", sconf->max_order);
  224. dprintf(avctx, "block_switching = %i\n", sconf->block_switching);
  225. dprintf(avctx, "bgmc = %i\n", sconf->bgmc);
  226. dprintf(avctx, "sb_part = %i\n", sconf->sb_part);
  227. dprintf(avctx, "joint_stereo = %i\n", sconf->joint_stereo);
  228. dprintf(avctx, "mc_coding = %i\n", sconf->mc_coding);
  229. dprintf(avctx, "chan_config = %i\n", sconf->chan_config);
  230. dprintf(avctx, "chan_sort = %i\n", sconf->chan_sort);
  231. dprintf(avctx, "RLSLMS = %i\n", sconf->rlslms);
  232. dprintf(avctx, "chan_config_info = %i\n", sconf->chan_config_info);
  233. #endif
  234. }
  235. /** Reads an ALSSpecificConfig from a buffer into the output struct.
  236. */
  237. static av_cold int read_specific_config(ALSDecContext *ctx)
  238. {
  239. GetBitContext gb;
  240. uint64_t ht_size;
  241. int i, config_offset, crc_enabled;
  242. MPEG4AudioConfig m4ac;
  243. ALSSpecificConfig *sconf = &ctx->sconf;
  244. AVCodecContext *avctx = ctx->avctx;
  245. uint32_t als_id, header_size, trailer_size;
  246. init_get_bits(&gb, avctx->extradata, avctx->extradata_size * 8);
  247. config_offset = ff_mpeg4audio_get_config(&m4ac, avctx->extradata,
  248. avctx->extradata_size);
  249. if (config_offset < 0)
  250. return -1;
  251. skip_bits_long(&gb, config_offset);
  252. if (get_bits_left(&gb) < (30 << 3))
  253. return -1;
  254. // read the fixed items
  255. als_id = get_bits_long(&gb, 32);
  256. avctx->sample_rate = m4ac.sample_rate;
  257. skip_bits_long(&gb, 32); // sample rate already known
  258. sconf->samples = get_bits_long(&gb, 32);
  259. avctx->channels = m4ac.channels;
  260. skip_bits(&gb, 16); // number of channels already knwon
  261. skip_bits(&gb, 3); // skip file_type
  262. sconf->resolution = get_bits(&gb, 3);
  263. sconf->floating = get_bits1(&gb);
  264. skip_bits1(&gb); // skip msb_first
  265. sconf->frame_length = get_bits(&gb, 16) + 1;
  266. sconf->ra_distance = get_bits(&gb, 8);
  267. sconf->ra_flag = get_bits(&gb, 2);
  268. sconf->adapt_order = get_bits1(&gb);
  269. sconf->coef_table = get_bits(&gb, 2);
  270. sconf->long_term_prediction = get_bits1(&gb);
  271. sconf->max_order = get_bits(&gb, 10);
  272. sconf->block_switching = get_bits(&gb, 2);
  273. sconf->bgmc = get_bits1(&gb);
  274. sconf->sb_part = get_bits1(&gb);
  275. sconf->joint_stereo = get_bits1(&gb);
  276. sconf->mc_coding = get_bits1(&gb);
  277. sconf->chan_config = get_bits1(&gb);
  278. sconf->chan_sort = get_bits1(&gb);
  279. crc_enabled = get_bits1(&gb);
  280. sconf->rlslms = get_bits1(&gb);
  281. skip_bits(&gb, 5); // skip 5 reserved bits
  282. skip_bits1(&gb); // skip aux_data_enabled
  283. // check for ALSSpecificConfig struct
  284. if (als_id != MKBETAG('A','L','S','\0'))
  285. return -1;
  286. ctx->cur_frame_length = sconf->frame_length;
  287. // read channel config
  288. if (sconf->chan_config)
  289. sconf->chan_config_info = get_bits(&gb, 16);
  290. // TODO: use this to set avctx->channel_layout
  291. // read channel sorting
  292. if (sconf->chan_sort && avctx->channels > 1) {
  293. int chan_pos_bits = av_ceil_log2(avctx->channels);
  294. int bits_needed = avctx->channels * chan_pos_bits + 7;
  295. if (get_bits_left(&gb) < bits_needed)
  296. return -1;
  297. if (!(sconf->chan_pos = av_malloc(avctx->channels * sizeof(*sconf->chan_pos))))
  298. return AVERROR(ENOMEM);
  299. for (i = 0; i < avctx->channels; i++)
  300. sconf->chan_pos[i] = get_bits(&gb, chan_pos_bits);
  301. align_get_bits(&gb);
  302. // TODO: use this to actually do channel sorting
  303. } else {
  304. sconf->chan_sort = 0;
  305. }
  306. // read fixed header and trailer sizes,
  307. // if size = 0xFFFFFFFF then there is no data field!
  308. if (get_bits_left(&gb) < 64)
  309. return -1;
  310. header_size = get_bits_long(&gb, 32);
  311. trailer_size = get_bits_long(&gb, 32);
  312. if (header_size == 0xFFFFFFFF)
  313. header_size = 0;
  314. if (trailer_size == 0xFFFFFFFF)
  315. trailer_size = 0;
  316. ht_size = ((int64_t)(header_size) + (int64_t)(trailer_size)) << 3;
  317. // skip the header and trailer data
  318. if (get_bits_left(&gb) < ht_size)
  319. return -1;
  320. if (ht_size > INT32_MAX)
  321. return -1;
  322. skip_bits_long(&gb, ht_size);
  323. // skip the crc data
  324. if (crc_enabled) {
  325. if (get_bits_left(&gb) < 32)
  326. return -1;
  327. skip_bits_long(&gb, 32);
  328. }
  329. // no need to read the rest of ALSSpecificConfig (ra_unit_size & aux data)
  330. dprint_specific_config(ctx);
  331. return 0;
  332. }
  333. /** Checks the ALSSpecificConfig for unsupported features.
  334. */
  335. static int check_specific_config(ALSDecContext *ctx)
  336. {
  337. ALSSpecificConfig *sconf = &ctx->sconf;
  338. int error = 0;
  339. // report unsupported feature and set error value
  340. #define MISSING_ERR(cond, str, errval) \
  341. { \
  342. if (cond) { \
  343. av_log_missing_feature(ctx->avctx, str, 0); \
  344. error = errval; \
  345. } \
  346. }
  347. MISSING_ERR(sconf->floating, "Floating point decoding", -1);
  348. MISSING_ERR(sconf->rlslms, "Adaptive RLS-LMS prediction", -1);
  349. MISSING_ERR(sconf->chan_sort, "Channel sorting", 0);
  350. return error;
  351. }
  352. /** Parses the bs_info field to extract the block partitioning used in
  353. * block switching mode, refer to ISO/IEC 14496-3, section 11.6.2.
  354. */
  355. static void parse_bs_info(const uint32_t bs_info, unsigned int n,
  356. unsigned int div, unsigned int **div_blocks,
  357. unsigned int *num_blocks)
  358. {
  359. if (n < 31 && ((bs_info << n) & 0x40000000)) {
  360. // if the level is valid and the investigated bit n is set
  361. // then recursively check both children at bits (2n+1) and (2n+2)
  362. n *= 2;
  363. div += 1;
  364. parse_bs_info(bs_info, n + 1, div, div_blocks, num_blocks);
  365. parse_bs_info(bs_info, n + 2, div, div_blocks, num_blocks);
  366. } else {
  367. // else the bit is not set or the last level has been reached
  368. // (bit implicitly not set)
  369. **div_blocks = div;
  370. (*div_blocks)++;
  371. (*num_blocks)++;
  372. }
  373. }
  374. /** Reads and decodes a Rice codeword.
  375. */
  376. static int32_t decode_rice(GetBitContext *gb, unsigned int k)
  377. {
  378. int max = get_bits_left(gb) - k;
  379. int q = get_unary(gb, 0, max);
  380. int r = k ? get_bits1(gb) : !(q & 1);
  381. if (k > 1) {
  382. q <<= (k - 1);
  383. q += get_bits_long(gb, k - 1);
  384. } else if (!k) {
  385. q >>= 1;
  386. }
  387. return r ? q : ~q;
  388. }
  389. /** Converts PARCOR coefficient k to direct filter coefficient.
  390. */
  391. static void parcor_to_lpc(unsigned int k, const int32_t *par, int32_t *cof)
  392. {
  393. int i, j;
  394. for (i = 0, j = k - 1; i < j; i++, j--) {
  395. int tmp1 = ((MUL64(par[k], cof[j]) + (1 << 19)) >> 20);
  396. cof[j] += ((MUL64(par[k], cof[i]) + (1 << 19)) >> 20);
  397. cof[i] += tmp1;
  398. }
  399. if (i == j)
  400. cof[i] += ((MUL64(par[k], cof[j]) + (1 << 19)) >> 20);
  401. cof[k] = par[k];
  402. }
  403. /** Reads block switching field if necessary and sets actual block sizes.
  404. * Also assures that the block sizes of the last frame correspond to the
  405. * actual number of samples.
  406. */
  407. static void get_block_sizes(ALSDecContext *ctx, unsigned int *div_blocks,
  408. uint32_t *bs_info)
  409. {
  410. ALSSpecificConfig *sconf = &ctx->sconf;
  411. GetBitContext *gb = &ctx->gb;
  412. unsigned int *ptr_div_blocks = div_blocks;
  413. unsigned int b;
  414. if (sconf->block_switching) {
  415. unsigned int bs_info_len = 1 << (sconf->block_switching + 2);
  416. *bs_info = get_bits_long(gb, bs_info_len);
  417. *bs_info <<= (32 - bs_info_len);
  418. }
  419. ctx->num_blocks = 0;
  420. parse_bs_info(*bs_info, 0, 0, &ptr_div_blocks, &ctx->num_blocks);
  421. // The last frame may have an overdetermined block structure given in
  422. // the bitstream. In that case the defined block structure would need
  423. // more samples than available to be consistent.
  424. // The block structure is actually used but the block sizes are adapted
  425. // to fit the actual number of available samples.
  426. // Example: 5 samples, 2nd level block sizes: 2 2 2 2.
  427. // This results in the actual block sizes: 2 2 1 0.
  428. // This is not specified in 14496-3 but actually done by the reference
  429. // codec RM22 revision 2.
  430. // This appears to happen in case of an odd number of samples in the last
  431. // frame which is actually not allowed by the block length switching part
  432. // of 14496-3.
  433. // The ALS conformance files feature an odd number of samples in the last
  434. // frame.
  435. for (b = 0; b < ctx->num_blocks; b++)
  436. div_blocks[b] = ctx->sconf.frame_length >> div_blocks[b];
  437. if (ctx->cur_frame_length != ctx->sconf.frame_length) {
  438. unsigned int remaining = ctx->cur_frame_length;
  439. for (b = 0; b < ctx->num_blocks; b++) {
  440. if (remaining <= div_blocks[b]) {
  441. div_blocks[b] = remaining;
  442. ctx->num_blocks = b + 1;
  443. break;
  444. }
  445. remaining -= div_blocks[b];
  446. }
  447. }
  448. }
  449. /** Reads the block data for a constant block
  450. */
  451. static void read_const_block_data(ALSDecContext *ctx, ALSBlockData *bd)
  452. {
  453. ALSSpecificConfig *sconf = &ctx->sconf;
  454. AVCodecContext *avctx = ctx->avctx;
  455. GetBitContext *gb = &ctx->gb;
  456. bd->const_val = 0;
  457. bd->const_block = get_bits1(gb); // 1 = constant value, 0 = zero block (silence)
  458. bd->js_blocks = get_bits1(gb);
  459. // skip 5 reserved bits
  460. skip_bits(gb, 5);
  461. if (bd->const_block) {
  462. unsigned int const_val_bits = sconf->floating ? 24 : avctx->bits_per_raw_sample;
  463. bd->const_val = get_sbits_long(gb, const_val_bits);
  464. }
  465. // ensure constant block decoding by reusing this field
  466. bd->const_block = 1;
  467. }
  468. /** Decodes the block data for a constant block
  469. */
  470. static void decode_const_block_data(ALSDecContext *ctx, ALSBlockData *bd)
  471. {
  472. int smp = bd->block_length;
  473. int32_t val = bd->const_val;
  474. int32_t *dst = bd->raw_samples;
  475. // write raw samples into buffer
  476. for (; smp; smp--)
  477. *dst++ = val;
  478. }
  479. /** Reads the block data for a non-constant block
  480. */
  481. static int read_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)
  482. {
  483. ALSSpecificConfig *sconf = &ctx->sconf;
  484. AVCodecContext *avctx = ctx->avctx;
  485. GetBitContext *gb = &ctx->gb;
  486. unsigned int k;
  487. unsigned int s[8];
  488. unsigned int sx[8];
  489. unsigned int sub_blocks, log2_sub_blocks, sb_length;
  490. unsigned int start = 0;
  491. unsigned int opt_order;
  492. int sb;
  493. int32_t *quant_cof = bd->quant_cof;
  494. int32_t *current_res;
  495. // ensure variable block decoding by reusing this field
  496. bd->const_block = 0;
  497. bd->opt_order = 1;
  498. bd->js_blocks = get_bits1(gb);
  499. opt_order = bd->opt_order;
  500. // determine the number of subblocks for entropy decoding
  501. if (!sconf->bgmc && !sconf->sb_part) {
  502. log2_sub_blocks = 0;
  503. } else {
  504. if (sconf->bgmc && sconf->sb_part)
  505. log2_sub_blocks = get_bits(gb, 2);
  506. else
  507. log2_sub_blocks = 2 * get_bits1(gb);
  508. }
  509. sub_blocks = 1 << log2_sub_blocks;
  510. // do not continue in case of a damaged stream since
  511. // block_length must be evenly divisible by sub_blocks
  512. if (bd->block_length & (sub_blocks - 1)) {
  513. av_log(avctx, AV_LOG_WARNING,
  514. "Block length is not evenly divisible by the number of subblocks.\n");
  515. return -1;
  516. }
  517. sb_length = bd->block_length >> log2_sub_blocks;
  518. if (sconf->bgmc) {
  519. s[0] = get_bits(gb, 8 + (sconf->resolution > 1));
  520. for (k = 1; k < sub_blocks; k++)
  521. s[k] = s[k - 1] + decode_rice(gb, 2);
  522. for (k = 0; k < sub_blocks; k++) {
  523. sx[k] = s[k] & 0x0F;
  524. s [k] >>= 4;
  525. }
  526. } else {
  527. s[0] = get_bits(gb, 4 + (sconf->resolution > 1));
  528. for (k = 1; k < sub_blocks; k++)
  529. s[k] = s[k - 1] + decode_rice(gb, 0);
  530. }
  531. if (get_bits1(gb))
  532. bd->shift_lsbs = get_bits(gb, 4) + 1;
  533. bd->store_prev_samples = (bd->js_blocks && bd->raw_other) || bd->shift_lsbs;
  534. if (!sconf->rlslms) {
  535. if (sconf->adapt_order) {
  536. int opt_order_length = av_ceil_log2(av_clip((bd->block_length >> 3) - 1,
  537. 2, sconf->max_order + 1));
  538. bd->opt_order = get_bits(gb, opt_order_length);
  539. } else {
  540. bd->opt_order = sconf->max_order;
  541. }
  542. opt_order = bd->opt_order;
  543. if (opt_order) {
  544. int add_base;
  545. if (sconf->coef_table == 3) {
  546. add_base = 0x7F;
  547. // read coefficient 0
  548. quant_cof[0] = 32 * parcor_scaled_values[get_bits(gb, 7)];
  549. // read coefficient 1
  550. if (opt_order > 1)
  551. quant_cof[1] = -32 * parcor_scaled_values[get_bits(gb, 7)];
  552. // read coefficients 2 to opt_order
  553. for (k = 2; k < opt_order; k++)
  554. quant_cof[k] = get_bits(gb, 7);
  555. } else {
  556. int k_max;
  557. add_base = 1;
  558. // read coefficient 0 to 19
  559. k_max = FFMIN(opt_order, 20);
  560. for (k = 0; k < k_max; k++) {
  561. int rice_param = parcor_rice_table[sconf->coef_table][k][1];
  562. int offset = parcor_rice_table[sconf->coef_table][k][0];
  563. quant_cof[k] = decode_rice(gb, rice_param) + offset;
  564. }
  565. // read coefficients 20 to 126
  566. k_max = FFMIN(opt_order, 127);
  567. for (; k < k_max; k++)
  568. quant_cof[k] = decode_rice(gb, 2) + (k & 1);
  569. // read coefficients 127 to opt_order
  570. for (; k < opt_order; k++)
  571. quant_cof[k] = decode_rice(gb, 1);
  572. quant_cof[0] = 32 * parcor_scaled_values[quant_cof[0] + 64];
  573. if (opt_order > 1)
  574. quant_cof[1] = -32 * parcor_scaled_values[quant_cof[1] + 64];
  575. }
  576. for (k = 2; k < opt_order; k++)
  577. quant_cof[k] = (quant_cof[k] << 14) + (add_base << 13);
  578. }
  579. }
  580. // read LTP gain and lag values
  581. if (sconf->long_term_prediction) {
  582. *bd->use_ltp = get_bits1(gb);
  583. if (*bd->use_ltp) {
  584. int r, c;
  585. bd->ltp_gain[0] = decode_rice(gb, 1) << 3;
  586. bd->ltp_gain[1] = decode_rice(gb, 2) << 3;
  587. r = get_unary(gb, 0, 4);
  588. c = get_bits(gb, 2);
  589. bd->ltp_gain[2] = ltp_gain_values[r][c];
  590. bd->ltp_gain[3] = decode_rice(gb, 2) << 3;
  591. bd->ltp_gain[4] = decode_rice(gb, 1) << 3;
  592. *bd->ltp_lag = get_bits(gb, ctx->ltp_lag_length);
  593. *bd->ltp_lag += FFMAX(4, opt_order + 1);
  594. }
  595. }
  596. // read first value and residuals in case of a random access block
  597. if (bd->ra_block) {
  598. if (opt_order)
  599. bd->raw_samples[0] = decode_rice(gb, avctx->bits_per_raw_sample - 4);
  600. if (opt_order > 1)
  601. bd->raw_samples[1] = decode_rice(gb, FFMIN(s[0] + 3, ctx->s_max));
  602. if (opt_order > 2)
  603. bd->raw_samples[2] = decode_rice(gb, FFMIN(s[0] + 1, ctx->s_max));
  604. start = FFMIN(opt_order, 3);
  605. }
  606. // read all residuals
  607. if (sconf->bgmc) {
  608. unsigned int delta[sub_blocks];
  609. unsigned int k [sub_blocks];
  610. unsigned int b = av_clip((av_ceil_log2(bd->block_length) - 3) >> 1, 0, 5);
  611. unsigned int i = start;
  612. // read most significant bits
  613. unsigned int high;
  614. unsigned int low;
  615. unsigned int value;
  616. ff_bgmc_decode_init(gb, &high, &low, &value);
  617. current_res = bd->raw_samples + start;
  618. for (sb = 0; sb < sub_blocks; sb++, i = 0) {
  619. k [sb] = s[sb] > b ? s[sb] - b : 0;
  620. delta[sb] = 5 - s[sb] + k[sb];
  621. ff_bgmc_decode(gb, sb_length, current_res,
  622. delta[sb], sx[sb], &high, &low, &value, ctx->bgmc_lut, ctx->bgmc_lut_status);
  623. current_res += sb_length;
  624. }
  625. ff_bgmc_decode_end(gb);
  626. // read least significant bits and tails
  627. i = start;
  628. current_res = bd->raw_samples + start;
  629. for (sb = 0; sb < sub_blocks; sb++, i = 0) {
  630. unsigned int cur_tail_code = tail_code[sx[sb]][delta[sb]];
  631. unsigned int cur_k = k[sb];
  632. unsigned int cur_s = s[sb];
  633. for (; i < sb_length; i++) {
  634. int32_t res = *current_res;
  635. if (res == cur_tail_code) {
  636. unsigned int max_msb = (2 + (sx[sb] > 2) + (sx[sb] > 10))
  637. << (5 - delta[sb]);
  638. res = decode_rice(gb, cur_s);
  639. if (res >= 0) {
  640. res += (max_msb ) << cur_k;
  641. } else {
  642. res -= (max_msb - 1) << cur_k;
  643. }
  644. } else {
  645. if (res > cur_tail_code)
  646. res--;
  647. if (res & 1)
  648. res = -res;
  649. res >>= 1;
  650. if (cur_k) {
  651. res <<= cur_k;
  652. res |= get_bits_long(gb, cur_k);
  653. }
  654. }
  655. *current_res++ = res;
  656. }
  657. }
  658. } else {
  659. current_res = bd->raw_samples + start;
  660. for (sb = 0; sb < sub_blocks; sb++, start = 0)
  661. for (; start < sb_length; start++)
  662. *current_res++ = decode_rice(gb, s[sb]);
  663. }
  664. if (!sconf->mc_coding || ctx->js_switch)
  665. align_get_bits(gb);
  666. return 0;
  667. }
  668. /** Decodes the block data for a non-constant block
  669. */
  670. static int decode_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)
  671. {
  672. ALSSpecificConfig *sconf = &ctx->sconf;
  673. unsigned int block_length = bd->block_length;
  674. unsigned int smp = 0;
  675. unsigned int k;
  676. int opt_order = bd->opt_order;
  677. int sb;
  678. int64_t y;
  679. int32_t *quant_cof = bd->quant_cof;
  680. int32_t *lpc_cof = bd->lpc_cof;
  681. int32_t *raw_samples = bd->raw_samples;
  682. int32_t *raw_samples_end = bd->raw_samples + bd->block_length;
  683. int32_t *lpc_cof_reversed = ctx->lpc_cof_reversed_buffer;
  684. // reverse long-term prediction
  685. if (*bd->use_ltp) {
  686. int ltp_smp;
  687. for (ltp_smp = FFMAX(*bd->ltp_lag - 2, 0); ltp_smp < block_length; ltp_smp++) {
  688. int center = ltp_smp - *bd->ltp_lag;
  689. int begin = FFMAX(0, center - 2);
  690. int end = center + 3;
  691. int tab = 5 - (end - begin);
  692. int base;
  693. y = 1 << 6;
  694. for (base = begin; base < end; base++, tab++)
  695. y += MUL64(bd->ltp_gain[tab], raw_samples[base]);
  696. raw_samples[ltp_smp] += y >> 7;
  697. }
  698. }
  699. // reconstruct all samples from residuals
  700. if (bd->ra_block) {
  701. for (smp = 0; smp < opt_order; smp++) {
  702. y = 1 << 19;
  703. for (sb = 0; sb < smp; sb++)
  704. y += MUL64(lpc_cof[sb], raw_samples[-(sb + 1)]);
  705. *raw_samples++ -= y >> 20;
  706. parcor_to_lpc(smp, quant_cof, lpc_cof);
  707. }
  708. } else {
  709. for (k = 0; k < opt_order; k++)
  710. parcor_to_lpc(k, quant_cof, lpc_cof);
  711. // store previous samples in case that they have to be altered
  712. if (bd->store_prev_samples)
  713. memcpy(bd->prev_raw_samples, raw_samples - sconf->max_order,
  714. sizeof(*bd->prev_raw_samples) * sconf->max_order);
  715. // reconstruct difference signal for prediction (joint-stereo)
  716. if (bd->js_blocks && bd->raw_other) {
  717. int32_t *left, *right;
  718. if (bd->raw_other > raw_samples) { // D = R - L
  719. left = raw_samples;
  720. right = bd->raw_other;
  721. } else { // D = R - L
  722. left = bd->raw_other;
  723. right = raw_samples;
  724. }
  725. for (sb = -1; sb >= -sconf->max_order; sb--)
  726. raw_samples[sb] = right[sb] - left[sb];
  727. }
  728. // reconstruct shifted signal
  729. if (bd->shift_lsbs)
  730. for (sb = -1; sb >= -sconf->max_order; sb--)
  731. raw_samples[sb] >>= bd->shift_lsbs;
  732. }
  733. // reverse linear prediction coefficients for efficiency
  734. lpc_cof = lpc_cof + opt_order;
  735. for (sb = 0; sb < opt_order; sb++)
  736. lpc_cof_reversed[sb] = lpc_cof[-(sb + 1)];
  737. // reconstruct raw samples
  738. raw_samples = bd->raw_samples + smp;
  739. lpc_cof = lpc_cof_reversed + opt_order;
  740. for (; raw_samples < raw_samples_end; raw_samples++) {
  741. y = 1 << 19;
  742. for (sb = -opt_order; sb < 0; sb++)
  743. y += MUL64(lpc_cof[sb], raw_samples[sb]);
  744. *raw_samples -= y >> 20;
  745. }
  746. raw_samples = bd->raw_samples;
  747. // restore previous samples in case that they have been altered
  748. if (bd->store_prev_samples)
  749. memcpy(raw_samples - sconf->max_order, bd->prev_raw_samples,
  750. sizeof(*raw_samples) * sconf->max_order);
  751. return 0;
  752. }
  753. /** Reads the block data.
  754. */
  755. static int read_block(ALSDecContext *ctx, ALSBlockData *bd)
  756. {
  757. GetBitContext *gb = &ctx->gb;
  758. // read block type flag and read the samples accordingly
  759. if (get_bits1(gb)) {
  760. if (read_var_block_data(ctx, bd))
  761. return -1;
  762. } else {
  763. read_const_block_data(ctx, bd);
  764. }
  765. return 0;
  766. }
  767. /** Decodes the block data.
  768. */
  769. static int decode_block(ALSDecContext *ctx, ALSBlockData *bd)
  770. {
  771. unsigned int smp;
  772. // read block type flag and read the samples accordingly
  773. if (bd->const_block)
  774. decode_const_block_data(ctx, bd);
  775. else if (decode_var_block_data(ctx, bd))
  776. return -1;
  777. // TODO: read RLSLMS extension data
  778. if (bd->shift_lsbs)
  779. for (smp = 0; smp < bd->block_length; smp++)
  780. bd->raw_samples[smp] <<= bd->shift_lsbs;
  781. return 0;
  782. }
  783. /** Reads and decodes block data successively.
  784. */
  785. static int read_decode_block(ALSDecContext *ctx, ALSBlockData *bd)
  786. {
  787. int ret;
  788. ret = read_block(ctx, bd);
  789. if (ret)
  790. return ret;
  791. ret = decode_block(ctx, bd);
  792. return ret;
  793. }
  794. /** Computes the number of samples left to decode for the current frame and
  795. * sets these samples to zero.
  796. */
  797. static void zero_remaining(unsigned int b, unsigned int b_max,
  798. const unsigned int *div_blocks, int32_t *buf)
  799. {
  800. unsigned int count = 0;
  801. while (b < b_max)
  802. count += div_blocks[b];
  803. if (count)
  804. memset(buf, 0, sizeof(*buf) * count);
  805. }
  806. /** Decodes blocks independently.
  807. */
  808. static int decode_blocks_ind(ALSDecContext *ctx, unsigned int ra_frame,
  809. unsigned int c, const unsigned int *div_blocks,
  810. unsigned int *js_blocks)
  811. {
  812. unsigned int b;
  813. ALSBlockData bd;
  814. memset(&bd, 0, sizeof(ALSBlockData));
  815. bd.ra_block = ra_frame;
  816. bd.use_ltp = ctx->use_ltp;
  817. bd.ltp_lag = ctx->ltp_lag;
  818. bd.ltp_gain = ctx->ltp_gain[0];
  819. bd.quant_cof = ctx->quant_cof[0];
  820. bd.lpc_cof = ctx->lpc_cof[0];
  821. bd.prev_raw_samples = ctx->prev_raw_samples;
  822. bd.raw_samples = ctx->raw_samples[c];
  823. for (b = 0; b < ctx->num_blocks; b++) {
  824. bd.shift_lsbs = 0;
  825. bd.block_length = div_blocks[b];
  826. if (read_decode_block(ctx, &bd)) {
  827. // damaged block, write zero for the rest of the frame
  828. zero_remaining(b, ctx->num_blocks, div_blocks, bd.raw_samples);
  829. return -1;
  830. }
  831. bd.raw_samples += div_blocks[b];
  832. bd.ra_block = 0;
  833. }
  834. return 0;
  835. }
  836. /** Decodes blocks dependently.
  837. */
  838. static int decode_blocks(ALSDecContext *ctx, unsigned int ra_frame,
  839. unsigned int c, const unsigned int *div_blocks,
  840. unsigned int *js_blocks)
  841. {
  842. ALSSpecificConfig *sconf = &ctx->sconf;
  843. unsigned int offset = 0;
  844. unsigned int b;
  845. ALSBlockData bd[2];
  846. memset(bd, 0, 2 * sizeof(ALSBlockData));
  847. bd[0].ra_block = ra_frame;
  848. bd[0].use_ltp = ctx->use_ltp;
  849. bd[0].ltp_lag = ctx->ltp_lag;
  850. bd[0].ltp_gain = ctx->ltp_gain[0];
  851. bd[0].quant_cof = ctx->quant_cof[0];
  852. bd[0].lpc_cof = ctx->lpc_cof[0];
  853. bd[0].prev_raw_samples = ctx->prev_raw_samples;
  854. bd[0].js_blocks = *js_blocks;
  855. bd[1].ra_block = ra_frame;
  856. bd[1].use_ltp = ctx->use_ltp;
  857. bd[1].ltp_lag = ctx->ltp_lag;
  858. bd[1].ltp_gain = ctx->ltp_gain[0];
  859. bd[1].quant_cof = ctx->quant_cof[0];
  860. bd[1].lpc_cof = ctx->lpc_cof[0];
  861. bd[1].prev_raw_samples = ctx->prev_raw_samples;
  862. bd[1].js_blocks = *(js_blocks + 1);
  863. // decode all blocks
  864. for (b = 0; b < ctx->num_blocks; b++) {
  865. unsigned int s;
  866. bd[0].shift_lsbs = 0;
  867. bd[1].shift_lsbs = 0;
  868. bd[0].block_length = div_blocks[b];
  869. bd[1].block_length = div_blocks[b];
  870. bd[0].raw_samples = ctx->raw_samples[c ] + offset;
  871. bd[1].raw_samples = ctx->raw_samples[c + 1] + offset;
  872. bd[0].raw_other = bd[1].raw_samples;
  873. bd[1].raw_other = bd[0].raw_samples;
  874. if(read_decode_block(ctx, &bd[0]) || read_decode_block(ctx, &bd[1])) {
  875. // damaged block, write zero for the rest of the frame
  876. zero_remaining(b, ctx->num_blocks, div_blocks, bd[0].raw_samples);
  877. zero_remaining(b, ctx->num_blocks, div_blocks, bd[1].raw_samples);
  878. return -1;
  879. }
  880. // reconstruct joint-stereo blocks
  881. if (bd[0].js_blocks) {
  882. if (bd[1].js_blocks)
  883. av_log(ctx->avctx, AV_LOG_WARNING, "Invalid channel pair!\n");
  884. for (s = 0; s < div_blocks[b]; s++)
  885. bd[0].raw_samples[s] = bd[1].raw_samples[s] - bd[0].raw_samples[s];
  886. } else if (bd[1].js_blocks) {
  887. for (s = 0; s < div_blocks[b]; s++)
  888. bd[1].raw_samples[s] = bd[1].raw_samples[s] + bd[0].raw_samples[s];
  889. }
  890. offset += div_blocks[b];
  891. bd[0].ra_block = 0;
  892. bd[1].ra_block = 0;
  893. }
  894. // store carryover raw samples,
  895. // the others channel raw samples are stored by the calling function.
  896. memmove(ctx->raw_samples[c] - sconf->max_order,
  897. ctx->raw_samples[c] - sconf->max_order + sconf->frame_length,
  898. sizeof(*ctx->raw_samples[c]) * sconf->max_order);
  899. return 0;
  900. }
  901. /** Reads the channel data.
  902. */
  903. static int read_channel_data(ALSDecContext *ctx, ALSChannelData *cd, int c)
  904. {
  905. GetBitContext *gb = &ctx->gb;
  906. ALSChannelData *current = cd;
  907. unsigned int channels = ctx->avctx->channels;
  908. int entries = 0;
  909. while (entries < channels && !(current->stop_flag = get_bits1(gb))) {
  910. current->master_channel = get_bits_long(gb, av_ceil_log2(channels));
  911. if (current->master_channel >= channels) {
  912. av_log(ctx->avctx, AV_LOG_ERROR, "Invalid master channel!\n");
  913. return -1;
  914. }
  915. if (current->master_channel != c) {
  916. current->time_diff_flag = get_bits1(gb);
  917. current->weighting[0] = mcc_weightings[av_clip(decode_rice(gb, 1) + 16, 0, 32)];
  918. current->weighting[1] = mcc_weightings[av_clip(decode_rice(gb, 2) + 14, 0, 32)];
  919. current->weighting[2] = mcc_weightings[av_clip(decode_rice(gb, 1) + 16, 0, 32)];
  920. if (current->time_diff_flag) {
  921. current->weighting[3] = mcc_weightings[av_clip(decode_rice(gb, 1) + 16, 0, 32)];
  922. current->weighting[4] = mcc_weightings[av_clip(decode_rice(gb, 1) + 16, 0, 32)];
  923. current->weighting[5] = mcc_weightings[av_clip(decode_rice(gb, 1) + 16, 0, 32)];
  924. current->time_diff_sign = get_bits1(gb);
  925. current->time_diff_index = get_bits(gb, ctx->ltp_lag_length - 3) + 3;
  926. }
  927. }
  928. current++;
  929. entries++;
  930. }
  931. if (entries == channels) {
  932. av_log(ctx->avctx, AV_LOG_ERROR, "Damaged channel data!\n");
  933. return -1;
  934. }
  935. align_get_bits(gb);
  936. return 0;
  937. }
  938. /** Recursively reverts the inter-channel correlation for a block.
  939. */
  940. static int revert_channel_correlation(ALSDecContext *ctx, ALSBlockData *bd,
  941. ALSChannelData **cd, int *reverted,
  942. unsigned int offset, int c)
  943. {
  944. ALSChannelData *ch = cd[c];
  945. unsigned int dep = 0;
  946. unsigned int channels = ctx->avctx->channels;
  947. if (reverted[c])
  948. return 0;
  949. reverted[c] = 1;
  950. while (dep < channels && !ch[dep].stop_flag) {
  951. revert_channel_correlation(ctx, bd, cd, reverted, offset,
  952. ch[dep].master_channel);
  953. dep++;
  954. }
  955. if (dep == channels) {
  956. av_log(ctx->avctx, AV_LOG_WARNING, "Invalid channel correlation!\n");
  957. return -1;
  958. }
  959. bd->use_ltp = ctx->use_ltp + c;
  960. bd->ltp_lag = ctx->ltp_lag + c;
  961. bd->ltp_gain = ctx->ltp_gain[c];
  962. bd->lpc_cof = ctx->lpc_cof[c];
  963. bd->quant_cof = ctx->quant_cof[c];
  964. bd->raw_samples = ctx->raw_samples[c] + offset;
  965. dep = 0;
  966. while (!ch[dep].stop_flag) {
  967. unsigned int smp;
  968. unsigned int begin = 1;
  969. unsigned int end = bd->block_length - 1;
  970. int64_t y;
  971. int32_t *master = ctx->raw_samples[ch[dep].master_channel] + offset;
  972. if (ch[dep].time_diff_flag) {
  973. int t = ch[dep].time_diff_index;
  974. if (ch[dep].time_diff_sign) {
  975. t = -t;
  976. begin -= t;
  977. } else {
  978. end -= t;
  979. }
  980. for (smp = begin; smp < end; smp++) {
  981. y = (1 << 6) +
  982. MUL64(ch[dep].weighting[0], master[smp - 1 ]) +
  983. MUL64(ch[dep].weighting[1], master[smp ]) +
  984. MUL64(ch[dep].weighting[2], master[smp + 1 ]) +
  985. MUL64(ch[dep].weighting[3], master[smp - 1 + t]) +
  986. MUL64(ch[dep].weighting[4], master[smp + t]) +
  987. MUL64(ch[dep].weighting[5], master[smp + 1 + t]);
  988. bd->raw_samples[smp] += y >> 7;
  989. }
  990. } else {
  991. for (smp = begin; smp < end; smp++) {
  992. y = (1 << 6) +
  993. MUL64(ch[dep].weighting[0], master[smp - 1]) +
  994. MUL64(ch[dep].weighting[1], master[smp ]) +
  995. MUL64(ch[dep].weighting[2], master[smp + 1]);
  996. bd->raw_samples[smp] += y >> 7;
  997. }
  998. }
  999. dep++;
  1000. }
  1001. return 0;
  1002. }
  1003. /** Reads the frame data.
  1004. */
  1005. static int read_frame_data(ALSDecContext *ctx, unsigned int ra_frame)
  1006. {
  1007. ALSSpecificConfig *sconf = &ctx->sconf;
  1008. AVCodecContext *avctx = ctx->avctx;
  1009. GetBitContext *gb = &ctx->gb;
  1010. unsigned int div_blocks[32]; ///< block sizes.
  1011. unsigned int c;
  1012. unsigned int js_blocks[2];
  1013. uint32_t bs_info = 0;
  1014. // skip the size of the ra unit if present in the frame
  1015. if (sconf->ra_flag == RA_FLAG_FRAMES && ra_frame)
  1016. skip_bits_long(gb, 32);
  1017. if (sconf->mc_coding && sconf->joint_stereo) {
  1018. ctx->js_switch = get_bits1(gb);
  1019. align_get_bits(gb);
  1020. }
  1021. if (!sconf->mc_coding || ctx->js_switch) {
  1022. int independent_bs = !sconf->joint_stereo;
  1023. for (c = 0; c < avctx->channels; c++) {
  1024. js_blocks[0] = 0;
  1025. js_blocks[1] = 0;
  1026. get_block_sizes(ctx, div_blocks, &bs_info);
  1027. // if joint_stereo and block_switching is set, independent decoding
  1028. // is signaled via the first bit of bs_info
  1029. if (sconf->joint_stereo && sconf->block_switching)
  1030. if (bs_info >> 31)
  1031. independent_bs = 2;
  1032. // if this is the last channel, it has to be decoded independently
  1033. if (c == avctx->channels - 1)
  1034. independent_bs = 1;
  1035. if (independent_bs) {
  1036. if (decode_blocks_ind(ctx, ra_frame, c, div_blocks, js_blocks))
  1037. return -1;
  1038. independent_bs--;
  1039. } else {
  1040. if (decode_blocks(ctx, ra_frame, c, div_blocks, js_blocks))
  1041. return -1;
  1042. c++;
  1043. }
  1044. // store carryover raw samples
  1045. memmove(ctx->raw_samples[c] - sconf->max_order,
  1046. ctx->raw_samples[c] - sconf->max_order + sconf->frame_length,
  1047. sizeof(*ctx->raw_samples[c]) * sconf->max_order);
  1048. }
  1049. } else { // multi-channel coding
  1050. ALSBlockData bd;
  1051. int b;
  1052. int *reverted_channels = ctx->reverted_channels;
  1053. unsigned int offset = 0;
  1054. for (c = 0; c < avctx->channels; c++)
  1055. if (ctx->chan_data[c] < ctx->chan_data_buffer) {
  1056. av_log(ctx->avctx, AV_LOG_ERROR, "Invalid channel data!\n");
  1057. return -1;
  1058. }
  1059. memset(&bd, 0, sizeof(ALSBlockData));
  1060. memset(reverted_channels, 0, sizeof(*reverted_channels) * avctx->channels);
  1061. bd.ra_block = ra_frame;
  1062. bd.prev_raw_samples = ctx->prev_raw_samples;
  1063. get_block_sizes(ctx, div_blocks, &bs_info);
  1064. for (b = 0; b < ctx->num_blocks; b++) {
  1065. bd.shift_lsbs = 0;
  1066. bd.block_length = div_blocks[b];
  1067. for (c = 0; c < avctx->channels; c++) {
  1068. bd.use_ltp = ctx->use_ltp + c;
  1069. bd.ltp_lag = ctx->ltp_lag + c;
  1070. bd.ltp_gain = ctx->ltp_gain[c];
  1071. bd.lpc_cof = ctx->lpc_cof[c];
  1072. bd.quant_cof = ctx->quant_cof[c];
  1073. bd.raw_samples = ctx->raw_samples[c] + offset;
  1074. bd.raw_other = NULL;
  1075. read_block(ctx, &bd);
  1076. if (read_channel_data(ctx, ctx->chan_data[c], c))
  1077. return -1;
  1078. }
  1079. for (c = 0; c < avctx->channels; c++)
  1080. if (revert_channel_correlation(ctx, &bd, ctx->chan_data,
  1081. reverted_channels, offset, c))
  1082. return -1;
  1083. for (c = 0; c < avctx->channels; c++) {
  1084. bd.use_ltp = ctx->use_ltp + c;
  1085. bd.ltp_lag = ctx->ltp_lag + c;
  1086. bd.ltp_gain = ctx->ltp_gain[c];
  1087. bd.lpc_cof = ctx->lpc_cof[c];
  1088. bd.quant_cof = ctx->quant_cof[c];
  1089. bd.raw_samples = ctx->raw_samples[c] + offset;
  1090. decode_block(ctx, &bd);
  1091. }
  1092. memset(reverted_channels, 0, avctx->channels * sizeof(*reverted_channels));
  1093. offset += div_blocks[b];
  1094. bd.ra_block = 0;
  1095. }
  1096. // store carryover raw samples
  1097. for (c = 0; c < avctx->channels; c++)
  1098. memmove(ctx->raw_samples[c] - sconf->max_order,
  1099. ctx->raw_samples[c] - sconf->max_order + sconf->frame_length,
  1100. sizeof(*ctx->raw_samples[c]) * sconf->max_order);
  1101. }
  1102. // TODO: read_diff_float_data
  1103. return 0;
  1104. }
  1105. /** Decodes an ALS frame.
  1106. */
  1107. static int decode_frame(AVCodecContext *avctx,
  1108. void *data, int *data_size,
  1109. AVPacket *avpkt)
  1110. {
  1111. ALSDecContext *ctx = avctx->priv_data;
  1112. ALSSpecificConfig *sconf = &ctx->sconf;
  1113. const uint8_t *buffer = avpkt->data;
  1114. int buffer_size = avpkt->size;
  1115. int invalid_frame, size;
  1116. unsigned int c, sample, ra_frame, bytes_read, shift;
  1117. init_get_bits(&ctx->gb, buffer, buffer_size * 8);
  1118. // In the case that the distance between random access frames is set to zero
  1119. // (sconf->ra_distance == 0) no frame is treated as a random access frame.
  1120. // For the first frame, if prediction is used, all samples used from the
  1121. // previous frame are assumed to be zero.
  1122. ra_frame = sconf->ra_distance && !(ctx->frame_id % sconf->ra_distance);
  1123. // the last frame to decode might have a different length
  1124. if (sconf->samples != 0xFFFFFFFF)
  1125. ctx->cur_frame_length = FFMIN(sconf->samples - ctx->frame_id * (uint64_t) sconf->frame_length,
  1126. sconf->frame_length);
  1127. else
  1128. ctx->cur_frame_length = sconf->frame_length;
  1129. // decode the frame data
  1130. if ((invalid_frame = read_frame_data(ctx, ra_frame) < 0))
  1131. av_log(ctx->avctx, AV_LOG_WARNING,
  1132. "Reading frame data failed. Skipping RA unit.\n");
  1133. ctx->frame_id++;
  1134. // check for size of decoded data
  1135. size = ctx->cur_frame_length * avctx->channels *
  1136. (av_get_bits_per_sample_format(avctx->sample_fmt) >> 3);
  1137. if (size > *data_size) {
  1138. av_log(avctx, AV_LOG_ERROR, "Decoded data exceeds buffer size.\n");
  1139. return -1;
  1140. }
  1141. *data_size = size;
  1142. // transform decoded frame into output format
  1143. #define INTERLEAVE_OUTPUT(bps) \
  1144. { \
  1145. int##bps##_t *dest = (int##bps##_t*) data; \
  1146. shift = bps - ctx->avctx->bits_per_raw_sample; \
  1147. for (sample = 0; sample < ctx->cur_frame_length; sample++) \
  1148. for (c = 0; c < avctx->channels; c++) \
  1149. *dest++ = ctx->raw_samples[c][sample] << shift; \
  1150. }
  1151. if (ctx->avctx->bits_per_raw_sample <= 16) {
  1152. INTERLEAVE_OUTPUT(16)
  1153. } else {
  1154. INTERLEAVE_OUTPUT(32)
  1155. }
  1156. bytes_read = invalid_frame ? buffer_size :
  1157. (get_bits_count(&ctx->gb) + 7) >> 3;
  1158. return bytes_read;
  1159. }
  1160. /** Uninitializes the ALS decoder.
  1161. */
  1162. static av_cold int decode_end(AVCodecContext *avctx)
  1163. {
  1164. ALSDecContext *ctx = avctx->priv_data;
  1165. av_freep(&ctx->sconf.chan_pos);
  1166. ff_bgmc_end(&ctx->bgmc_lut, &ctx->bgmc_lut_status);
  1167. av_freep(&ctx->use_ltp);
  1168. av_freep(&ctx->ltp_lag);
  1169. av_freep(&ctx->ltp_gain);
  1170. av_freep(&ctx->ltp_gain_buffer);
  1171. av_freep(&ctx->quant_cof);
  1172. av_freep(&ctx->lpc_cof);
  1173. av_freep(&ctx->quant_cof_buffer);
  1174. av_freep(&ctx->lpc_cof_buffer);
  1175. av_freep(&ctx->lpc_cof_reversed_buffer);
  1176. av_freep(&ctx->prev_raw_samples);
  1177. av_freep(&ctx->raw_samples);
  1178. av_freep(&ctx->raw_buffer);
  1179. av_freep(&ctx->chan_data);
  1180. av_freep(&ctx->chan_data_buffer);
  1181. av_freep(&ctx->reverted_channels);
  1182. return 0;
  1183. }
  1184. /** Initializes the ALS decoder.
  1185. */
  1186. static av_cold int decode_init(AVCodecContext *avctx)
  1187. {
  1188. unsigned int c;
  1189. unsigned int channel_size;
  1190. int num_buffers;
  1191. ALSDecContext *ctx = avctx->priv_data;
  1192. ALSSpecificConfig *sconf = &ctx->sconf;
  1193. ctx->avctx = avctx;
  1194. if (!avctx->extradata) {
  1195. av_log(avctx, AV_LOG_ERROR, "Missing required ALS extradata.\n");
  1196. return -1;
  1197. }
  1198. if (read_specific_config(ctx)) {
  1199. av_log(avctx, AV_LOG_ERROR, "Reading ALSSpecificConfig failed.\n");
  1200. decode_end(avctx);
  1201. return -1;
  1202. }
  1203. if (check_specific_config(ctx)) {
  1204. decode_end(avctx);
  1205. return -1;
  1206. }
  1207. if (sconf->bgmc)
  1208. ff_bgmc_init(avctx, &ctx->bgmc_lut, &ctx->bgmc_lut_status);
  1209. if (sconf->floating) {
  1210. avctx->sample_fmt = SAMPLE_FMT_FLT;
  1211. avctx->bits_per_raw_sample = 32;
  1212. } else {
  1213. avctx->sample_fmt = sconf->resolution > 1
  1214. ? SAMPLE_FMT_S32 : SAMPLE_FMT_S16;
  1215. avctx->bits_per_raw_sample = (sconf->resolution + 1) * 8;
  1216. }
  1217. // set maximum Rice parameter for progressive decoding based on resolution
  1218. // This is not specified in 14496-3 but actually done by the reference
  1219. // codec RM22 revision 2.
  1220. ctx->s_max = sconf->resolution > 1 ? 31 : 15;
  1221. // set lag value for long-term prediction
  1222. ctx->ltp_lag_length = 8 + (avctx->sample_rate >= 96000) +
  1223. (avctx->sample_rate >= 192000);
  1224. // allocate quantized parcor coefficient buffer
  1225. num_buffers = sconf->mc_coding ? avctx->channels : 1;
  1226. ctx->quant_cof = av_malloc(sizeof(*ctx->quant_cof) * num_buffers);
  1227. ctx->lpc_cof = av_malloc(sizeof(*ctx->lpc_cof) * num_buffers);
  1228. ctx->quant_cof_buffer = av_malloc(sizeof(*ctx->quant_cof_buffer) *
  1229. num_buffers * sconf->max_order);
  1230. ctx->lpc_cof_buffer = av_malloc(sizeof(*ctx->lpc_cof_buffer) *
  1231. num_buffers * sconf->max_order);
  1232. ctx->lpc_cof_reversed_buffer = av_malloc(sizeof(*ctx->lpc_cof_buffer) *
  1233. sconf->max_order);
  1234. if (!ctx->quant_cof || !ctx->lpc_cof ||
  1235. !ctx->quant_cof_buffer || !ctx->lpc_cof_buffer ||
  1236. !ctx->lpc_cof_reversed_buffer) {
  1237. av_log(avctx, AV_LOG_ERROR, "Allocating buffer memory failed.\n");
  1238. return AVERROR(ENOMEM);
  1239. }
  1240. // assign quantized parcor coefficient buffers
  1241. for (c = 0; c < num_buffers; c++) {
  1242. ctx->quant_cof[c] = ctx->quant_cof_buffer + c * sconf->max_order;
  1243. ctx->lpc_cof[c] = ctx->lpc_cof_buffer + c * sconf->max_order;
  1244. }
  1245. // allocate and assign lag and gain data buffer for ltp mode
  1246. ctx->use_ltp = av_mallocz(sizeof(*ctx->use_ltp) * num_buffers);
  1247. ctx->ltp_lag = av_malloc (sizeof(*ctx->ltp_lag) * num_buffers);
  1248. ctx->ltp_gain = av_malloc (sizeof(*ctx->ltp_gain) * num_buffers);
  1249. ctx->ltp_gain_buffer = av_malloc (sizeof(*ctx->ltp_gain_buffer) *
  1250. num_buffers * 5);
  1251. if (!ctx->use_ltp || !ctx->ltp_lag ||
  1252. !ctx->ltp_gain || !ctx->ltp_gain_buffer) {
  1253. av_log(avctx, AV_LOG_ERROR, "Allocating buffer memory failed.\n");
  1254. decode_end(avctx);
  1255. return AVERROR(ENOMEM);
  1256. }
  1257. for (c = 0; c < num_buffers; c++)
  1258. ctx->ltp_gain[c] = ctx->ltp_gain_buffer + c * 5;
  1259. // allocate and assign channel data buffer for mcc mode
  1260. if (sconf->mc_coding) {
  1261. ctx->chan_data_buffer = av_malloc(sizeof(*ctx->chan_data_buffer) *
  1262. num_buffers * num_buffers);
  1263. ctx->chan_data = av_malloc(sizeof(*ctx->chan_data) *
  1264. num_buffers);
  1265. ctx->reverted_channels = av_malloc(sizeof(*ctx->reverted_channels) *
  1266. num_buffers);
  1267. if (!ctx->chan_data_buffer || !ctx->chan_data || !ctx->reverted_channels) {
  1268. av_log(avctx, AV_LOG_ERROR, "Allocating buffer memory failed.\n");
  1269. decode_end(avctx);
  1270. return AVERROR(ENOMEM);
  1271. }
  1272. for (c = 0; c < num_buffers; c++)
  1273. ctx->chan_data[c] = ctx->chan_data_buffer + c * num_buffers;
  1274. } else {
  1275. ctx->chan_data = NULL;
  1276. ctx->chan_data_buffer = NULL;
  1277. ctx->reverted_channels = NULL;
  1278. }
  1279. avctx->frame_size = sconf->frame_length;
  1280. channel_size = sconf->frame_length + sconf->max_order;
  1281. ctx->prev_raw_samples = av_malloc (sizeof(*ctx->prev_raw_samples) * sconf->max_order);
  1282. ctx->raw_buffer = av_mallocz(sizeof(*ctx-> raw_buffer) * avctx->channels * channel_size);
  1283. ctx->raw_samples = av_malloc (sizeof(*ctx-> raw_samples) * avctx->channels);
  1284. // allocate previous raw sample buffer
  1285. if (!ctx->prev_raw_samples || !ctx->raw_buffer|| !ctx->raw_samples) {
  1286. av_log(avctx, AV_LOG_ERROR, "Allocating buffer memory failed.\n");
  1287. decode_end(avctx);
  1288. return AVERROR(ENOMEM);
  1289. }
  1290. // assign raw samples buffers
  1291. ctx->raw_samples[0] = ctx->raw_buffer + sconf->max_order;
  1292. for (c = 1; c < avctx->channels; c++)
  1293. ctx->raw_samples[c] = ctx->raw_samples[c - 1] + channel_size;
  1294. return 0;
  1295. }
  1296. /** Flushes (resets) the frame ID after seeking.
  1297. */
  1298. static av_cold void flush(AVCodecContext *avctx)
  1299. {
  1300. ALSDecContext *ctx = avctx->priv_data;
  1301. ctx->frame_id = 0;
  1302. }
  1303. AVCodec als_decoder = {
  1304. "als",
  1305. CODEC_TYPE_AUDIO,
  1306. CODEC_ID_MP4ALS,
  1307. sizeof(ALSDecContext),
  1308. decode_init,
  1309. NULL,
  1310. decode_end,
  1311. decode_frame,
  1312. .flush = flush,
  1313. .capabilities = CODEC_CAP_SUBFRAMES,
  1314. .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 Audio Lossless Coding (ALS)"),
  1315. };