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.

1720 lines
59KB

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