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.

1633 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. bd->ltp_gain[0] = decode_rice(gb, 1) << 3;
  585. bd->ltp_gain[1] = decode_rice(gb, 2) << 3;
  586. bd->ltp_gain[2] = ltp_gain_values[get_unary(gb, 0, 4)][get_bits(gb, 2)];
  587. bd->ltp_gain[3] = decode_rice(gb, 2) << 3;
  588. bd->ltp_gain[4] = decode_rice(gb, 1) << 3;
  589. *bd->ltp_lag = get_bits(gb, ctx->ltp_lag_length);
  590. *bd->ltp_lag += FFMAX(4, opt_order + 1);
  591. }
  592. }
  593. // read first value and residuals in case of a random access block
  594. if (bd->ra_block) {
  595. if (opt_order)
  596. bd->raw_samples[0] = decode_rice(gb, avctx->bits_per_raw_sample - 4);
  597. if (opt_order > 1)
  598. bd->raw_samples[1] = decode_rice(gb, FFMIN(s[0] + 3, ctx->s_max));
  599. if (opt_order > 2)
  600. bd->raw_samples[2] = decode_rice(gb, FFMIN(s[0] + 1, ctx->s_max));
  601. start = FFMIN(opt_order, 3);
  602. }
  603. // read all residuals
  604. if (sconf->bgmc) {
  605. unsigned int delta[sub_blocks];
  606. unsigned int k [sub_blocks];
  607. unsigned int b = av_clip((av_ceil_log2(bd->block_length) - 3) >> 1, 0, 5);
  608. unsigned int i = start;
  609. // read most significant bits
  610. unsigned int high;
  611. unsigned int low;
  612. unsigned int value;
  613. ff_bgmc_decode_init(gb, &high, &low, &value);
  614. current_res = bd->raw_samples + start;
  615. for (sb = 0; sb < sub_blocks; sb++, i = 0) {
  616. k [sb] = s[sb] > b ? s[sb] - b : 0;
  617. delta[sb] = 5 - s[sb] + k[sb];
  618. ff_bgmc_decode(gb, sb_length, current_res,
  619. delta[sb], sx[sb], &high, &low, &value, ctx->bgmc_lut, ctx->bgmc_lut_status);
  620. current_res += sb_length;
  621. }
  622. ff_bgmc_decode_end(gb);
  623. // read least significant bits and tails
  624. i = start;
  625. current_res = bd->raw_samples + start;
  626. for (sb = 0; sb < sub_blocks; sb++, i = 0) {
  627. unsigned int cur_tail_code = tail_code[sx[sb]][delta[sb]];
  628. unsigned int cur_k = k[sb];
  629. unsigned int cur_s = s[sb];
  630. for (; i < sb_length; i++) {
  631. int32_t res = *current_res;
  632. if (res == cur_tail_code) {
  633. unsigned int max_msb = (2 + (sx[sb] > 2) + (sx[sb] > 10))
  634. << (5 - delta[sb]);
  635. res = decode_rice(gb, cur_s);
  636. if (res >= 0) {
  637. res += (max_msb ) << cur_k;
  638. } else {
  639. res -= (max_msb - 1) << cur_k;
  640. }
  641. } else {
  642. if (res > cur_tail_code)
  643. res--;
  644. if (res & 1)
  645. res = -res;
  646. res >>= 1;
  647. if (cur_k) {
  648. res <<= cur_k;
  649. res |= get_bits_long(gb, cur_k);
  650. }
  651. }
  652. *current_res++ = res;
  653. }
  654. }
  655. } else {
  656. current_res = bd->raw_samples + start;
  657. for (sb = 0; sb < sub_blocks; sb++, start = 0)
  658. for (; start < sb_length; start++)
  659. *current_res++ = decode_rice(gb, s[sb]);
  660. }
  661. if (!sconf->mc_coding || ctx->js_switch)
  662. align_get_bits(gb);
  663. return 0;
  664. }
  665. /** Decodes the block data for a non-constant block
  666. */
  667. static int decode_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)
  668. {
  669. ALSSpecificConfig *sconf = &ctx->sconf;
  670. unsigned int block_length = bd->block_length;
  671. unsigned int smp = 0;
  672. unsigned int k;
  673. int opt_order = bd->opt_order;
  674. int sb;
  675. int64_t y;
  676. int32_t *quant_cof = bd->quant_cof;
  677. int32_t *lpc_cof = bd->lpc_cof;
  678. int32_t *raw_samples = bd->raw_samples;
  679. int32_t *raw_samples_end = bd->raw_samples + bd->block_length;
  680. int32_t *lpc_cof_reversed = ctx->lpc_cof_reversed_buffer;
  681. // reverse long-term prediction
  682. if (*bd->use_ltp) {
  683. int ltp_smp;
  684. for (ltp_smp = FFMAX(*bd->ltp_lag - 2, 0); ltp_smp < block_length; ltp_smp++) {
  685. int center = ltp_smp - *bd->ltp_lag;
  686. int begin = FFMAX(0, center - 2);
  687. int end = center + 3;
  688. int tab = 5 - (end - begin);
  689. int base;
  690. y = 1 << 6;
  691. for (base = begin; base < end; base++, tab++)
  692. y += MUL64(bd->ltp_gain[tab], raw_samples[base]);
  693. raw_samples[ltp_smp] += y >> 7;
  694. }
  695. }
  696. // reconstruct all samples from residuals
  697. if (bd->ra_block) {
  698. for (smp = 0; smp < opt_order; smp++) {
  699. y = 1 << 19;
  700. for (sb = 0; sb < smp; sb++)
  701. y += MUL64(lpc_cof[sb], raw_samples[-(sb + 1)]);
  702. *raw_samples++ -= y >> 20;
  703. parcor_to_lpc(smp, quant_cof, lpc_cof);
  704. }
  705. } else {
  706. for (k = 0; k < opt_order; k++)
  707. parcor_to_lpc(k, quant_cof, lpc_cof);
  708. // store previous samples in case that they have to be altered
  709. if (bd->store_prev_samples)
  710. memcpy(bd->prev_raw_samples, raw_samples - sconf->max_order,
  711. sizeof(*bd->prev_raw_samples) * sconf->max_order);
  712. // reconstruct difference signal for prediction (joint-stereo)
  713. if (bd->js_blocks && bd->raw_other) {
  714. int32_t *left, *right;
  715. if (bd->raw_other > raw_samples) { // D = R - L
  716. left = raw_samples;
  717. right = bd->raw_other;
  718. } else { // D = R - L
  719. left = bd->raw_other;
  720. right = raw_samples;
  721. }
  722. for (sb = -1; sb >= -sconf->max_order; sb--)
  723. raw_samples[sb] = right[sb] - left[sb];
  724. }
  725. // reconstruct shifted signal
  726. if (bd->shift_lsbs)
  727. for (sb = -1; sb >= -sconf->max_order; sb--)
  728. raw_samples[sb] >>= bd->shift_lsbs;
  729. }
  730. // reverse linear prediction coefficients for efficiency
  731. lpc_cof = lpc_cof + opt_order;
  732. for (sb = 0; sb < opt_order; sb++)
  733. lpc_cof_reversed[sb] = lpc_cof[-(sb + 1)];
  734. // reconstruct raw samples
  735. raw_samples = bd->raw_samples + smp;
  736. lpc_cof = lpc_cof_reversed + opt_order;
  737. for (; raw_samples < raw_samples_end; raw_samples++) {
  738. y = 1 << 19;
  739. for (sb = -opt_order; sb < 0; sb++)
  740. y += MUL64(lpc_cof[sb], raw_samples[sb]);
  741. *raw_samples -= y >> 20;
  742. }
  743. raw_samples = bd->raw_samples;
  744. // restore previous samples in case that they have been altered
  745. if (bd->store_prev_samples)
  746. memcpy(raw_samples - sconf->max_order, bd->prev_raw_samples,
  747. sizeof(*raw_samples) * sconf->max_order);
  748. return 0;
  749. }
  750. /** Reads the block data.
  751. */
  752. static int read_block(ALSDecContext *ctx, ALSBlockData *bd)
  753. {
  754. GetBitContext *gb = &ctx->gb;
  755. // read block type flag and read the samples accordingly
  756. if (get_bits1(gb)) {
  757. if (read_var_block_data(ctx, bd))
  758. return -1;
  759. } else {
  760. read_const_block_data(ctx, bd);
  761. }
  762. return 0;
  763. }
  764. /** Decodes the block data.
  765. */
  766. static int decode_block(ALSDecContext *ctx, ALSBlockData *bd)
  767. {
  768. unsigned int smp;
  769. // read block type flag and read the samples accordingly
  770. if (bd->const_block)
  771. decode_const_block_data(ctx, bd);
  772. else if (decode_var_block_data(ctx, bd))
  773. return -1;
  774. // TODO: read RLSLMS extension data
  775. if (bd->shift_lsbs)
  776. for (smp = 0; smp < bd->block_length; smp++)
  777. bd->raw_samples[smp] <<= bd->shift_lsbs;
  778. return 0;
  779. }
  780. /** Reads and decodes block data successively.
  781. */
  782. static int read_decode_block(ALSDecContext *ctx, ALSBlockData *bd)
  783. {
  784. int ret;
  785. ret = read_block(ctx, bd);
  786. if (ret)
  787. return ret;
  788. ret = decode_block(ctx, bd);
  789. return ret;
  790. }
  791. /** Computes the number of samples left to decode for the current frame and
  792. * sets these samples to zero.
  793. */
  794. static void zero_remaining(unsigned int b, unsigned int b_max,
  795. const unsigned int *div_blocks, int32_t *buf)
  796. {
  797. unsigned int count = 0;
  798. while (b < b_max)
  799. count += div_blocks[b];
  800. if (count)
  801. memset(buf, 0, sizeof(*buf) * count);
  802. }
  803. /** Decodes blocks independently.
  804. */
  805. static int decode_blocks_ind(ALSDecContext *ctx, unsigned int ra_frame,
  806. unsigned int c, const unsigned int *div_blocks,
  807. unsigned int *js_blocks)
  808. {
  809. unsigned int b;
  810. ALSBlockData bd;
  811. memset(&bd, 0, sizeof(ALSBlockData));
  812. bd.ra_block = ra_frame;
  813. bd.use_ltp = ctx->use_ltp;
  814. bd.ltp_lag = ctx->ltp_lag;
  815. bd.ltp_gain = ctx->ltp_gain[0];
  816. bd.quant_cof = ctx->quant_cof[0];
  817. bd.lpc_cof = ctx->lpc_cof[0];
  818. bd.prev_raw_samples = ctx->prev_raw_samples;
  819. bd.raw_samples = ctx->raw_samples[c];
  820. for (b = 0; b < ctx->num_blocks; b++) {
  821. bd.shift_lsbs = 0;
  822. bd.block_length = div_blocks[b];
  823. if (read_decode_block(ctx, &bd)) {
  824. // damaged block, write zero for the rest of the frame
  825. zero_remaining(b, ctx->num_blocks, div_blocks, bd.raw_samples);
  826. return -1;
  827. }
  828. bd.raw_samples += div_blocks[b];
  829. bd.ra_block = 0;
  830. }
  831. return 0;
  832. }
  833. /** Decodes blocks dependently.
  834. */
  835. static int decode_blocks(ALSDecContext *ctx, unsigned int ra_frame,
  836. unsigned int c, const unsigned int *div_blocks,
  837. unsigned int *js_blocks)
  838. {
  839. ALSSpecificConfig *sconf = &ctx->sconf;
  840. unsigned int offset = 0;
  841. unsigned int b;
  842. ALSBlockData bd[2];
  843. memset(bd, 0, 2 * sizeof(ALSBlockData));
  844. bd[0].ra_block = ra_frame;
  845. bd[0].use_ltp = ctx->use_ltp;
  846. bd[0].ltp_lag = ctx->ltp_lag;
  847. bd[0].ltp_gain = ctx->ltp_gain[0];
  848. bd[0].quant_cof = ctx->quant_cof[0];
  849. bd[0].lpc_cof = ctx->lpc_cof[0];
  850. bd[0].prev_raw_samples = ctx->prev_raw_samples;
  851. bd[0].js_blocks = *js_blocks;
  852. bd[1].ra_block = ra_frame;
  853. bd[1].use_ltp = ctx->use_ltp;
  854. bd[1].ltp_lag = ctx->ltp_lag;
  855. bd[1].ltp_gain = ctx->ltp_gain[0];
  856. bd[1].quant_cof = ctx->quant_cof[0];
  857. bd[1].lpc_cof = ctx->lpc_cof[0];
  858. bd[1].prev_raw_samples = ctx->prev_raw_samples;
  859. bd[1].js_blocks = *(js_blocks + 1);
  860. // decode all blocks
  861. for (b = 0; b < ctx->num_blocks; b++) {
  862. unsigned int s;
  863. bd[0].shift_lsbs = 0;
  864. bd[1].shift_lsbs = 0;
  865. bd[0].block_length = div_blocks[b];
  866. bd[1].block_length = div_blocks[b];
  867. bd[0].raw_samples = ctx->raw_samples[c ] + offset;
  868. bd[1].raw_samples = ctx->raw_samples[c + 1] + offset;
  869. bd[0].raw_other = bd[1].raw_samples;
  870. bd[1].raw_other = bd[0].raw_samples;
  871. if(read_decode_block(ctx, &bd[0]) || read_decode_block(ctx, &bd[1])) {
  872. // damaged block, write zero for the rest of the frame
  873. zero_remaining(b, ctx->num_blocks, div_blocks, bd[0].raw_samples);
  874. zero_remaining(b, ctx->num_blocks, div_blocks, bd[1].raw_samples);
  875. return -1;
  876. }
  877. // reconstruct joint-stereo blocks
  878. if (bd[0].js_blocks) {
  879. if (bd[1].js_blocks)
  880. av_log(ctx->avctx, AV_LOG_WARNING, "Invalid channel pair!\n");
  881. for (s = 0; s < div_blocks[b]; s++)
  882. bd[0].raw_samples[s] = bd[1].raw_samples[s] - bd[0].raw_samples[s];
  883. } else if (bd[1].js_blocks) {
  884. for (s = 0; s < div_blocks[b]; s++)
  885. bd[1].raw_samples[s] = bd[1].raw_samples[s] + bd[0].raw_samples[s];
  886. }
  887. offset += div_blocks[b];
  888. bd[0].ra_block = 0;
  889. bd[1].ra_block = 0;
  890. }
  891. // store carryover raw samples,
  892. // the others channel raw samples are stored by the calling function.
  893. memmove(ctx->raw_samples[c] - sconf->max_order,
  894. ctx->raw_samples[c] - sconf->max_order + sconf->frame_length,
  895. sizeof(*ctx->raw_samples[c]) * sconf->max_order);
  896. return 0;
  897. }
  898. /** Reads the channel data.
  899. */
  900. static int read_channel_data(ALSDecContext *ctx, ALSChannelData *cd, int c)
  901. {
  902. GetBitContext *gb = &ctx->gb;
  903. ALSChannelData *current = cd;
  904. unsigned int channels = ctx->avctx->channels;
  905. int entries = 0;
  906. while (entries < channels && !(current->stop_flag = get_bits1(gb))) {
  907. current->master_channel = get_bits_long(gb, av_ceil_log2(channels));
  908. if (current->master_channel >= channels) {
  909. av_log(ctx->avctx, AV_LOG_ERROR, "Invalid master channel!\n");
  910. return -1;
  911. }
  912. if (current->master_channel != c) {
  913. current->time_diff_flag = get_bits1(gb);
  914. current->weighting[0] = mcc_weightings[av_clip(decode_rice(gb, 1) + 16, 0, 32)];
  915. current->weighting[1] = mcc_weightings[av_clip(decode_rice(gb, 2) + 14, 0, 32)];
  916. current->weighting[2] = mcc_weightings[av_clip(decode_rice(gb, 1) + 16, 0, 32)];
  917. if (current->time_diff_flag) {
  918. current->weighting[3] = mcc_weightings[av_clip(decode_rice(gb, 1) + 16, 0, 32)];
  919. current->weighting[4] = mcc_weightings[av_clip(decode_rice(gb, 1) + 16, 0, 32)];
  920. current->weighting[5] = mcc_weightings[av_clip(decode_rice(gb, 1) + 16, 0, 32)];
  921. current->time_diff_sign = get_bits1(gb);
  922. current->time_diff_index = get_bits(gb, ctx->ltp_lag_length - 3) + 3;
  923. }
  924. }
  925. current++;
  926. entries++;
  927. }
  928. if (entries == channels) {
  929. av_log(ctx->avctx, AV_LOG_ERROR, "Damaged channel data!\n");
  930. return -1;
  931. }
  932. align_get_bits(gb);
  933. return 0;
  934. }
  935. /** Recursively reverts the inter-channel correlation for a block.
  936. */
  937. static int revert_channel_correlation(ALSDecContext *ctx, ALSBlockData *bd,
  938. ALSChannelData **cd, int *reverted,
  939. unsigned int offset, int c)
  940. {
  941. ALSChannelData *ch = cd[c];
  942. unsigned int dep = 0;
  943. unsigned int channels = ctx->avctx->channels;
  944. if (reverted[c])
  945. return 0;
  946. reverted[c] = 1;
  947. while (dep < channels && !ch[dep].stop_flag) {
  948. revert_channel_correlation(ctx, bd, cd, reverted, offset,
  949. ch[dep].master_channel);
  950. dep++;
  951. }
  952. if (dep == channels) {
  953. av_log(ctx->avctx, AV_LOG_WARNING, "Invalid channel correlation!\n");
  954. return -1;
  955. }
  956. bd->use_ltp = ctx->use_ltp + c;
  957. bd->ltp_lag = ctx->ltp_lag + c;
  958. bd->ltp_gain = ctx->ltp_gain[c];
  959. bd->lpc_cof = ctx->lpc_cof[c];
  960. bd->quant_cof = ctx->quant_cof[c];
  961. bd->raw_samples = ctx->raw_samples[c] + offset;
  962. dep = 0;
  963. while (!ch[dep].stop_flag) {
  964. unsigned int smp;
  965. unsigned int begin = 1;
  966. unsigned int end = bd->block_length - 1;
  967. int64_t y;
  968. int32_t *master = ctx->raw_samples[ch[dep].master_channel] + offset;
  969. if (ch[dep].time_diff_flag) {
  970. int t = ch[dep].time_diff_index;
  971. if (ch[dep].time_diff_sign) {
  972. t = -t;
  973. begin -= t;
  974. } else {
  975. end -= t;
  976. }
  977. for (smp = begin; smp < end; smp++) {
  978. y = (1 << 6) +
  979. MUL64(ch[dep].weighting[0], master[smp - 1 ]) +
  980. MUL64(ch[dep].weighting[1], master[smp ]) +
  981. MUL64(ch[dep].weighting[2], master[smp + 1 ]) +
  982. MUL64(ch[dep].weighting[3], master[smp - 1 + t]) +
  983. MUL64(ch[dep].weighting[4], master[smp + t]) +
  984. MUL64(ch[dep].weighting[5], master[smp + 1 + t]);
  985. bd->raw_samples[smp] += y >> 7;
  986. }
  987. } else {
  988. for (smp = begin; smp < end; smp++) {
  989. y = (1 << 6) +
  990. MUL64(ch[dep].weighting[0], master[smp - 1]) +
  991. MUL64(ch[dep].weighting[1], master[smp ]) +
  992. MUL64(ch[dep].weighting[2], master[smp + 1]);
  993. bd->raw_samples[smp] += y >> 7;
  994. }
  995. }
  996. dep++;
  997. }
  998. return 0;
  999. }
  1000. /** Reads the frame data.
  1001. */
  1002. static int read_frame_data(ALSDecContext *ctx, unsigned int ra_frame)
  1003. {
  1004. ALSSpecificConfig *sconf = &ctx->sconf;
  1005. AVCodecContext *avctx = ctx->avctx;
  1006. GetBitContext *gb = &ctx->gb;
  1007. unsigned int div_blocks[32]; ///< block sizes.
  1008. unsigned int c;
  1009. unsigned int js_blocks[2];
  1010. uint32_t bs_info = 0;
  1011. // skip the size of the ra unit if present in the frame
  1012. if (sconf->ra_flag == RA_FLAG_FRAMES && ra_frame)
  1013. skip_bits_long(gb, 32);
  1014. if (sconf->mc_coding && sconf->joint_stereo) {
  1015. ctx->js_switch = get_bits1(gb);
  1016. align_get_bits(gb);
  1017. }
  1018. if (!sconf->mc_coding || ctx->js_switch) {
  1019. int independent_bs = !sconf->joint_stereo;
  1020. for (c = 0; c < avctx->channels; c++) {
  1021. js_blocks[0] = 0;
  1022. js_blocks[1] = 0;
  1023. get_block_sizes(ctx, div_blocks, &bs_info);
  1024. // if joint_stereo and block_switching is set, independent decoding
  1025. // is signaled via the first bit of bs_info
  1026. if (sconf->joint_stereo && sconf->block_switching)
  1027. if (bs_info >> 31)
  1028. independent_bs = 2;
  1029. // if this is the last channel, it has to be decoded independently
  1030. if (c == avctx->channels - 1)
  1031. independent_bs = 1;
  1032. if (independent_bs) {
  1033. if (decode_blocks_ind(ctx, ra_frame, c, div_blocks, js_blocks))
  1034. return -1;
  1035. independent_bs--;
  1036. } else {
  1037. if (decode_blocks(ctx, ra_frame, c, div_blocks, js_blocks))
  1038. return -1;
  1039. c++;
  1040. }
  1041. // store carryover raw samples
  1042. memmove(ctx->raw_samples[c] - sconf->max_order,
  1043. ctx->raw_samples[c] - sconf->max_order + sconf->frame_length,
  1044. sizeof(*ctx->raw_samples[c]) * sconf->max_order);
  1045. }
  1046. } else { // multi-channel coding
  1047. ALSBlockData bd;
  1048. int b;
  1049. int *reverted_channels = ctx->reverted_channels;
  1050. unsigned int offset = 0;
  1051. for (c = 0; c < avctx->channels; c++)
  1052. if (ctx->chan_data[c] < ctx->chan_data_buffer) {
  1053. av_log(ctx->avctx, AV_LOG_ERROR, "Invalid channel data!\n");
  1054. return -1;
  1055. }
  1056. memset(&bd, 0, sizeof(ALSBlockData));
  1057. memset(reverted_channels, 0, sizeof(*reverted_channels) * avctx->channels);
  1058. bd.ra_block = ra_frame;
  1059. bd.prev_raw_samples = ctx->prev_raw_samples;
  1060. get_block_sizes(ctx, div_blocks, &bs_info);
  1061. for (b = 0; b < ctx->num_blocks; b++) {
  1062. bd.shift_lsbs = 0;
  1063. bd.block_length = div_blocks[b];
  1064. for (c = 0; c < avctx->channels; c++) {
  1065. bd.use_ltp = ctx->use_ltp + c;
  1066. bd.ltp_lag = ctx->ltp_lag + c;
  1067. bd.ltp_gain = ctx->ltp_gain[c];
  1068. bd.lpc_cof = ctx->lpc_cof[c];
  1069. bd.quant_cof = ctx->quant_cof[c];
  1070. bd.raw_samples = ctx->raw_samples[c] + offset;
  1071. bd.raw_other = NULL;
  1072. read_block(ctx, &bd);
  1073. if (read_channel_data(ctx, ctx->chan_data[c], c))
  1074. return -1;
  1075. }
  1076. for (c = 0; c < avctx->channels; c++)
  1077. if (revert_channel_correlation(ctx, &bd, ctx->chan_data,
  1078. reverted_channels, offset, c))
  1079. return -1;
  1080. for (c = 0; c < avctx->channels; c++) {
  1081. bd.use_ltp = ctx->use_ltp + c;
  1082. bd.ltp_lag = ctx->ltp_lag + c;
  1083. bd.ltp_gain = ctx->ltp_gain[c];
  1084. bd.lpc_cof = ctx->lpc_cof[c];
  1085. bd.quant_cof = ctx->quant_cof[c];
  1086. bd.raw_samples = ctx->raw_samples[c] + offset;
  1087. decode_block(ctx, &bd);
  1088. }
  1089. memset(reverted_channels, 0, avctx->channels * sizeof(*reverted_channels));
  1090. offset += div_blocks[b];
  1091. bd.ra_block = 0;
  1092. }
  1093. // store carryover raw samples
  1094. for (c = 0; c < avctx->channels; c++)
  1095. memmove(ctx->raw_samples[c] - sconf->max_order,
  1096. ctx->raw_samples[c] - sconf->max_order + sconf->frame_length,
  1097. sizeof(*ctx->raw_samples[c]) * sconf->max_order);
  1098. }
  1099. // TODO: read_diff_float_data
  1100. return 0;
  1101. }
  1102. /** Decodes an ALS frame.
  1103. */
  1104. static int decode_frame(AVCodecContext *avctx,
  1105. void *data, int *data_size,
  1106. AVPacket *avpkt)
  1107. {
  1108. ALSDecContext *ctx = avctx->priv_data;
  1109. ALSSpecificConfig *sconf = &ctx->sconf;
  1110. const uint8_t *buffer = avpkt->data;
  1111. int buffer_size = avpkt->size;
  1112. int invalid_frame, size;
  1113. unsigned int c, sample, ra_frame, bytes_read, shift;
  1114. init_get_bits(&ctx->gb, buffer, buffer_size * 8);
  1115. // In the case that the distance between random access frames is set to zero
  1116. // (sconf->ra_distance == 0) no frame is treated as a random access frame.
  1117. // For the first frame, if prediction is used, all samples used from the
  1118. // previous frame are assumed to be zero.
  1119. ra_frame = sconf->ra_distance && !(ctx->frame_id % sconf->ra_distance);
  1120. // the last frame to decode might have a different length
  1121. if (sconf->samples != 0xFFFFFFFF)
  1122. ctx->cur_frame_length = FFMIN(sconf->samples - ctx->frame_id * (uint64_t) sconf->frame_length,
  1123. sconf->frame_length);
  1124. else
  1125. ctx->cur_frame_length = sconf->frame_length;
  1126. // decode the frame data
  1127. if ((invalid_frame = read_frame_data(ctx, ra_frame) < 0))
  1128. av_log(ctx->avctx, AV_LOG_WARNING,
  1129. "Reading frame data failed. Skipping RA unit.\n");
  1130. ctx->frame_id++;
  1131. // check for size of decoded data
  1132. size = ctx->cur_frame_length * avctx->channels *
  1133. (av_get_bits_per_sample_format(avctx->sample_fmt) >> 3);
  1134. if (size > *data_size) {
  1135. av_log(avctx, AV_LOG_ERROR, "Decoded data exceeds buffer size.\n");
  1136. return -1;
  1137. }
  1138. *data_size = size;
  1139. // transform decoded frame into output format
  1140. #define INTERLEAVE_OUTPUT(bps) \
  1141. { \
  1142. int##bps##_t *dest = (int##bps##_t*) data; \
  1143. shift = bps - ctx->avctx->bits_per_raw_sample; \
  1144. for (sample = 0; sample < ctx->cur_frame_length; sample++) \
  1145. for (c = 0; c < avctx->channels; c++) \
  1146. *dest++ = ctx->raw_samples[c][sample] << shift; \
  1147. }
  1148. if (ctx->avctx->bits_per_raw_sample <= 16) {
  1149. INTERLEAVE_OUTPUT(16)
  1150. } else {
  1151. INTERLEAVE_OUTPUT(32)
  1152. }
  1153. bytes_read = invalid_frame ? buffer_size :
  1154. (get_bits_count(&ctx->gb) + 7) >> 3;
  1155. return bytes_read;
  1156. }
  1157. /** Uninitializes the ALS decoder.
  1158. */
  1159. static av_cold int decode_end(AVCodecContext *avctx)
  1160. {
  1161. ALSDecContext *ctx = avctx->priv_data;
  1162. av_freep(&ctx->sconf.chan_pos);
  1163. ff_bgmc_end(&ctx->bgmc_lut, &ctx->bgmc_lut_status);
  1164. av_freep(&ctx->use_ltp);
  1165. av_freep(&ctx->ltp_lag);
  1166. av_freep(&ctx->ltp_gain);
  1167. av_freep(&ctx->ltp_gain_buffer);
  1168. av_freep(&ctx->quant_cof);
  1169. av_freep(&ctx->lpc_cof);
  1170. av_freep(&ctx->quant_cof_buffer);
  1171. av_freep(&ctx->lpc_cof_buffer);
  1172. av_freep(&ctx->lpc_cof_reversed_buffer);
  1173. av_freep(&ctx->prev_raw_samples);
  1174. av_freep(&ctx->raw_samples);
  1175. av_freep(&ctx->raw_buffer);
  1176. av_freep(&ctx->chan_data);
  1177. av_freep(&ctx->chan_data_buffer);
  1178. av_freep(&ctx->reverted_channels);
  1179. return 0;
  1180. }
  1181. /** Initializes the ALS decoder.
  1182. */
  1183. static av_cold int decode_init(AVCodecContext *avctx)
  1184. {
  1185. unsigned int c;
  1186. unsigned int channel_size;
  1187. int num_buffers;
  1188. ALSDecContext *ctx = avctx->priv_data;
  1189. ALSSpecificConfig *sconf = &ctx->sconf;
  1190. ctx->avctx = avctx;
  1191. if (!avctx->extradata) {
  1192. av_log(avctx, AV_LOG_ERROR, "Missing required ALS extradata.\n");
  1193. return -1;
  1194. }
  1195. if (read_specific_config(ctx)) {
  1196. av_log(avctx, AV_LOG_ERROR, "Reading ALSSpecificConfig failed.\n");
  1197. decode_end(avctx);
  1198. return -1;
  1199. }
  1200. if (check_specific_config(ctx)) {
  1201. decode_end(avctx);
  1202. return -1;
  1203. }
  1204. if (sconf->bgmc)
  1205. ff_bgmc_init(avctx, &ctx->bgmc_lut, &ctx->bgmc_lut_status);
  1206. if (sconf->floating) {
  1207. avctx->sample_fmt = SAMPLE_FMT_FLT;
  1208. avctx->bits_per_raw_sample = 32;
  1209. } else {
  1210. avctx->sample_fmt = sconf->resolution > 1
  1211. ? SAMPLE_FMT_S32 : SAMPLE_FMT_S16;
  1212. avctx->bits_per_raw_sample = (sconf->resolution + 1) * 8;
  1213. }
  1214. // set maximum Rice parameter for progressive decoding based on resolution
  1215. // This is not specified in 14496-3 but actually done by the reference
  1216. // codec RM22 revision 2.
  1217. ctx->s_max = sconf->resolution > 1 ? 31 : 15;
  1218. // set lag value for long-term prediction
  1219. ctx->ltp_lag_length = 8 + (avctx->sample_rate >= 96000) +
  1220. (avctx->sample_rate >= 192000);
  1221. // allocate quantized parcor coefficient buffer
  1222. num_buffers = sconf->mc_coding ? avctx->channels : 1;
  1223. ctx->quant_cof = av_malloc(sizeof(*ctx->quant_cof) * num_buffers);
  1224. ctx->lpc_cof = av_malloc(sizeof(*ctx->lpc_cof) * num_buffers);
  1225. ctx->quant_cof_buffer = av_malloc(sizeof(*ctx->quant_cof_buffer) *
  1226. num_buffers * sconf->max_order);
  1227. ctx->lpc_cof_buffer = av_malloc(sizeof(*ctx->lpc_cof_buffer) *
  1228. num_buffers * sconf->max_order);
  1229. ctx->lpc_cof_reversed_buffer = av_malloc(sizeof(*ctx->lpc_cof_buffer) *
  1230. sconf->max_order);
  1231. if (!ctx->quant_cof || !ctx->lpc_cof ||
  1232. !ctx->quant_cof_buffer || !ctx->lpc_cof_buffer ||
  1233. !ctx->lpc_cof_reversed_buffer) {
  1234. av_log(avctx, AV_LOG_ERROR, "Allocating buffer memory failed.\n");
  1235. return AVERROR(ENOMEM);
  1236. }
  1237. // assign quantized parcor coefficient buffers
  1238. for (c = 0; c < num_buffers; c++) {
  1239. ctx->quant_cof[c] = ctx->quant_cof_buffer + c * sconf->max_order;
  1240. ctx->lpc_cof[c] = ctx->lpc_cof_buffer + c * sconf->max_order;
  1241. }
  1242. // allocate and assign lag and gain data buffer for ltp mode
  1243. ctx->use_ltp = av_mallocz(sizeof(*ctx->use_ltp) * num_buffers);
  1244. ctx->ltp_lag = av_malloc (sizeof(*ctx->ltp_lag) * num_buffers);
  1245. ctx->ltp_gain = av_malloc (sizeof(*ctx->ltp_gain) * num_buffers);
  1246. ctx->ltp_gain_buffer = av_malloc (sizeof(*ctx->ltp_gain_buffer) *
  1247. num_buffers * 5);
  1248. if (!ctx->use_ltp || !ctx->ltp_lag ||
  1249. !ctx->ltp_gain || !ctx->ltp_gain_buffer) {
  1250. av_log(avctx, AV_LOG_ERROR, "Allocating buffer memory failed.\n");
  1251. decode_end(avctx);
  1252. return AVERROR(ENOMEM);
  1253. }
  1254. for (c = 0; c < num_buffers; c++)
  1255. ctx->ltp_gain[c] = ctx->ltp_gain_buffer + c * 5;
  1256. // allocate and assign channel data buffer for mcc mode
  1257. if (sconf->mc_coding) {
  1258. ctx->chan_data_buffer = av_malloc(sizeof(*ctx->chan_data_buffer) *
  1259. num_buffers);
  1260. ctx->chan_data = av_malloc(sizeof(ALSChannelData) *
  1261. num_buffers);
  1262. ctx->reverted_channels = av_malloc(sizeof(*ctx->reverted_channels) *
  1263. num_buffers);
  1264. if (!ctx->chan_data_buffer || !ctx->chan_data || !ctx->reverted_channels) {
  1265. av_log(avctx, AV_LOG_ERROR, "Allocating buffer memory failed.\n");
  1266. decode_end(avctx);
  1267. return AVERROR(ENOMEM);
  1268. }
  1269. for (c = 0; c < num_buffers; c++)
  1270. ctx->chan_data[c] = ctx->chan_data_buffer + c;
  1271. } else {
  1272. ctx->chan_data = NULL;
  1273. ctx->chan_data_buffer = NULL;
  1274. ctx->reverted_channels = NULL;
  1275. }
  1276. avctx->frame_size = sconf->frame_length;
  1277. channel_size = sconf->frame_length + sconf->max_order;
  1278. ctx->prev_raw_samples = av_malloc (sizeof(*ctx->prev_raw_samples) * sconf->max_order);
  1279. ctx->raw_buffer = av_mallocz(sizeof(*ctx-> raw_buffer) * avctx->channels * channel_size);
  1280. ctx->raw_samples = av_malloc (sizeof(*ctx-> raw_samples) * avctx->channels);
  1281. // allocate previous raw sample buffer
  1282. if (!ctx->prev_raw_samples || !ctx->raw_buffer|| !ctx->raw_samples) {
  1283. av_log(avctx, AV_LOG_ERROR, "Allocating buffer memory failed.\n");
  1284. decode_end(avctx);
  1285. return AVERROR(ENOMEM);
  1286. }
  1287. // assign raw samples buffers
  1288. ctx->raw_samples[0] = ctx->raw_buffer + sconf->max_order;
  1289. for (c = 1; c < avctx->channels; c++)
  1290. ctx->raw_samples[c] = ctx->raw_samples[c - 1] + channel_size;
  1291. return 0;
  1292. }
  1293. /** Flushes (resets) the frame ID after seeking.
  1294. */
  1295. static av_cold void flush(AVCodecContext *avctx)
  1296. {
  1297. ALSDecContext *ctx = avctx->priv_data;
  1298. ctx->frame_id = 0;
  1299. }
  1300. AVCodec als_decoder = {
  1301. "als",
  1302. CODEC_TYPE_AUDIO,
  1303. CODEC_ID_MP4ALS,
  1304. sizeof(ALSDecContext),
  1305. decode_init,
  1306. NULL,
  1307. decode_end,
  1308. decode_frame,
  1309. .flush = flush,
  1310. .capabilities = CODEC_CAP_SUBFRAMES,
  1311. .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 Audio Lossless Coding (ALS)"),
  1312. };