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.

999 lines
33KB

  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 "als_data.h"
  33. enum RA_Flag {
  34. RA_FLAG_NONE,
  35. RA_FLAG_FRAMES,
  36. RA_FLAG_HEADER
  37. };
  38. typedef struct {
  39. uint32_t samples; ///< number of samples, 0xFFFFFFFF if unknown
  40. int resolution; ///< 000 = 8-bit; 001 = 16-bit; 010 = 24-bit; 011 = 32-bit
  41. int floating; ///< 1 = IEEE 32-bit floating-point, 0 = integer
  42. int frame_length; ///< frame length for each frame (last frame may differ)
  43. int ra_distance; ///< distance between RA frames (in frames, 0...255)
  44. enum RA_Flag ra_flag; ///< indicates where the size of ra units is stored
  45. int adapt_order; ///< adaptive order: 1 = on, 0 = off
  46. int coef_table; ///< table index of Rice code parameters
  47. int long_term_prediction; ///< long term prediction (LTP): 1 = on, 0 = off
  48. int max_order; ///< maximum prediction order (0..1023)
  49. int block_switching; ///< number of block switching levels
  50. int bgmc; ///< "Block Gilbert-Moore Code": 1 = on, 0 = off (Rice coding only)
  51. int sb_part; ///< sub-block partition
  52. int joint_stereo; ///< joint stereo: 1 = on, 0 = off
  53. int mc_coding; ///< extended inter-channel coding (multi channel coding): 1 = on, 0 = off
  54. int chan_config; ///< indicates that a chan_config_info field is present
  55. int chan_sort; ///< channel rearrangement: 1 = on, 0 = off
  56. int rlslms; ///< use "Recursive Least Square-Least Mean Square" predictor: 1 = on, 0 = off
  57. int chan_config_info; ///< mapping of channels to loudspeaker locations. Unused until setting channel configuration is implemented.
  58. int *chan_pos; ///< original channel positions
  59. uint32_t header_size; ///< header size of original audio file in bytes, provided for debugging
  60. uint32_t trailer_size; ///< trailer size of original audio file in bytes, provided for debugging
  61. } ALSSpecificConfig;
  62. typedef struct {
  63. AVCodecContext *avctx;
  64. ALSSpecificConfig sconf;
  65. GetBitContext gb;
  66. unsigned int cur_frame_length; ///< length of the current frame to decode
  67. unsigned int frame_id; ///< the frame ID / number of the current frame
  68. unsigned int js_switch; ///< if true, joint-stereo decoding is enforced
  69. unsigned int num_blocks; ///< number of blocks used in the current frame
  70. int32_t *quant_cof; ///< quantized parcor coefficients
  71. int32_t *lpc_cof; ///< coefficients of the direct form prediction filter
  72. int32_t *prev_raw_samples; ///< contains unshifted raw samples from the previous block
  73. int32_t **raw_samples; ///< decoded raw samples for each channel
  74. int32_t *raw_buffer; ///< contains all decoded raw samples including carryover samples
  75. } ALSDecContext;
  76. static av_cold void dprint_specific_config(ALSDecContext *ctx)
  77. {
  78. #ifdef DEBUG
  79. AVCodecContext *avctx = ctx->avctx;
  80. ALSSpecificConfig *sconf = &ctx->sconf;
  81. dprintf(avctx, "resolution = %i\n", sconf->resolution);
  82. dprintf(avctx, "floating = %i\n", sconf->floating);
  83. dprintf(avctx, "frame_length = %i\n", sconf->frame_length);
  84. dprintf(avctx, "ra_distance = %i\n", sconf->ra_distance);
  85. dprintf(avctx, "ra_flag = %i\n", sconf->ra_flag);
  86. dprintf(avctx, "adapt_order = %i\n", sconf->adapt_order);
  87. dprintf(avctx, "coef_table = %i\n", sconf->coef_table);
  88. dprintf(avctx, "long_term_prediction = %i\n", sconf->long_term_prediction);
  89. dprintf(avctx, "max_order = %i\n", sconf->max_order);
  90. dprintf(avctx, "block_switching = %i\n", sconf->block_switching);
  91. dprintf(avctx, "bgmc = %i\n", sconf->bgmc);
  92. dprintf(avctx, "sb_part = %i\n", sconf->sb_part);
  93. dprintf(avctx, "joint_stereo = %i\n", sconf->joint_stereo);
  94. dprintf(avctx, "mc_coding = %i\n", sconf->mc_coding);
  95. dprintf(avctx, "chan_config = %i\n", sconf->chan_config);
  96. dprintf(avctx, "chan_sort = %i\n", sconf->chan_sort);
  97. dprintf(avctx, "RLSLMS = %i\n", sconf->rlslms);
  98. dprintf(avctx, "chan_config_info = %i\n", sconf->chan_config_info);
  99. dprintf(avctx, "header_size = %i\n", sconf->header_size);
  100. dprintf(avctx, "trailer_size = %i\n", sconf->trailer_size);
  101. #endif
  102. }
  103. /** Reads an ALSSpecificConfig from a buffer into the output struct.
  104. */
  105. static av_cold int read_specific_config(ALSDecContext *ctx)
  106. {
  107. GetBitContext gb;
  108. uint64_t ht_size;
  109. int i, config_offset, crc_enabled;
  110. MPEG4AudioConfig m4ac;
  111. ALSSpecificConfig *sconf = &ctx->sconf;
  112. AVCodecContext *avctx = ctx->avctx;
  113. uint32_t als_id;
  114. init_get_bits(&gb, avctx->extradata, avctx->extradata_size * 8);
  115. config_offset = ff_mpeg4audio_get_config(&m4ac, avctx->extradata,
  116. avctx->extradata_size);
  117. if (config_offset < 0)
  118. return -1;
  119. skip_bits_long(&gb, config_offset);
  120. if (get_bits_left(&gb) < (30 << 3))
  121. return -1;
  122. // read the fixed items
  123. als_id = get_bits_long(&gb, 32);
  124. avctx->sample_rate = m4ac.sample_rate;
  125. skip_bits_long(&gb, 32); // sample rate already known
  126. sconf->samples = get_bits_long(&gb, 32);
  127. avctx->channels = m4ac.channels;
  128. skip_bits(&gb, 16); // number of channels already knwon
  129. skip_bits(&gb, 3); // skip file_type
  130. sconf->resolution = get_bits(&gb, 3);
  131. sconf->floating = get_bits1(&gb);
  132. skip_bits1(&gb); // skip msb_first
  133. sconf->frame_length = get_bits(&gb, 16) + 1;
  134. sconf->ra_distance = get_bits(&gb, 8);
  135. sconf->ra_flag = get_bits(&gb, 2);
  136. sconf->adapt_order = get_bits1(&gb);
  137. sconf->coef_table = get_bits(&gb, 2);
  138. sconf->long_term_prediction = get_bits1(&gb);
  139. sconf->max_order = get_bits(&gb, 10);
  140. sconf->block_switching = get_bits(&gb, 2);
  141. sconf->bgmc = get_bits1(&gb);
  142. sconf->sb_part = get_bits1(&gb);
  143. sconf->joint_stereo = get_bits1(&gb);
  144. sconf->mc_coding = get_bits1(&gb);
  145. sconf->chan_config = get_bits1(&gb);
  146. sconf->chan_sort = get_bits1(&gb);
  147. crc_enabled = get_bits1(&gb);
  148. sconf->rlslms = get_bits1(&gb);
  149. skip_bits(&gb, 5); // skip 5 reserved bits
  150. skip_bits1(&gb); // skip aux_data_enabled
  151. // check for ALSSpecificConfig struct
  152. if (als_id != MKBETAG('A','L','S','\0'))
  153. return -1;
  154. ctx->cur_frame_length = sconf->frame_length;
  155. // allocate quantized parcor coefficient buffer
  156. if (!(ctx->quant_cof = av_malloc(sizeof(*ctx->quant_cof) * sconf->max_order)) ||
  157. !(ctx->lpc_cof = av_malloc(sizeof(*ctx->lpc_cof) * sconf->max_order))) {
  158. av_log(avctx, AV_LOG_ERROR, "Allocating buffer memory failed.\n");
  159. return AVERROR(ENOMEM);
  160. }
  161. // read channel config
  162. if (sconf->chan_config)
  163. sconf->chan_config_info = get_bits(&gb, 16);
  164. // TODO: use this to set avctx->channel_layout
  165. // read channel sorting
  166. if (sconf->chan_sort && avctx->channels > 1) {
  167. int chan_pos_bits = av_ceil_log2(avctx->channels);
  168. int bits_needed = avctx->channels * chan_pos_bits + 7;
  169. if (get_bits_left(&gb) < bits_needed)
  170. return -1;
  171. if (!(sconf->chan_pos = av_malloc(avctx->channels * sizeof(*sconf->chan_pos))))
  172. return AVERROR(ENOMEM);
  173. for (i = 0; i < avctx->channels; i++)
  174. sconf->chan_pos[i] = get_bits(&gb, chan_pos_bits);
  175. align_get_bits(&gb);
  176. // TODO: use this to actually do channel sorting
  177. } else {
  178. sconf->chan_sort = 0;
  179. }
  180. // read fixed header and trailer sizes,
  181. // if size = 0xFFFFFFFF then there is no data field!
  182. if (get_bits_left(&gb) < 64)
  183. return -1;
  184. sconf->header_size = get_bits_long(&gb, 32);
  185. sconf->trailer_size = get_bits_long(&gb, 32);
  186. if (sconf->header_size == 0xFFFFFFFF)
  187. sconf->header_size = 0;
  188. if (sconf->trailer_size == 0xFFFFFFFF)
  189. sconf->trailer_size = 0;
  190. ht_size = ((int64_t)(sconf->header_size) + (int64_t)(sconf->trailer_size)) << 3;
  191. // skip the header and trailer data
  192. if (get_bits_left(&gb) < ht_size)
  193. return -1;
  194. if (ht_size > INT32_MAX)
  195. return -1;
  196. skip_bits_long(&gb, ht_size);
  197. // skip the crc data
  198. if (crc_enabled) {
  199. if (get_bits_left(&gb) < 32)
  200. return -1;
  201. skip_bits_long(&gb, 32);
  202. }
  203. // no need to read the rest of ALSSpecificConfig (ra_unit_size & aux data)
  204. dprint_specific_config(ctx);
  205. return 0;
  206. }
  207. /** Checks the ALSSpecificConfig for unsupported features.
  208. */
  209. static int check_specific_config(ALSDecContext *ctx)
  210. {
  211. ALSSpecificConfig *sconf = &ctx->sconf;
  212. int error = 0;
  213. // report unsupported feature and set error value
  214. #define MISSING_ERR(cond, str, errval) \
  215. { \
  216. if (cond) { \
  217. av_log_missing_feature(ctx->avctx, str, 0); \
  218. error = errval; \
  219. } \
  220. }
  221. MISSING_ERR(sconf->floating, "Floating point decoding", -1);
  222. MISSING_ERR(sconf->long_term_prediction, "Long-term prediction", -1);
  223. MISSING_ERR(sconf->bgmc, "BGMC entropy decoding", -1);
  224. MISSING_ERR(sconf->mc_coding, "Multi-channel correlation", -1);
  225. MISSING_ERR(sconf->rlslms, "Adaptive RLS-LMS prediction", -1);
  226. MISSING_ERR(sconf->chan_sort, "Channel sorting", 0);
  227. return error;
  228. }
  229. /** Parses the bs_info field to extract the block partitioning used in
  230. * block switching mode, refer to ISO/IEC 14496-3, section 11.6.2.
  231. */
  232. static void parse_bs_info(const uint32_t bs_info, unsigned int n,
  233. unsigned int div, unsigned int **div_blocks,
  234. unsigned int *num_blocks)
  235. {
  236. if (n < 31 && ((bs_info << n) & 0x40000000)) {
  237. // if the level is valid and the investigated bit n is set
  238. // then recursively check both children at bits (2n+1) and (2n+2)
  239. n *= 2;
  240. div += 1;
  241. parse_bs_info(bs_info, n + 1, div, div_blocks, num_blocks);
  242. parse_bs_info(bs_info, n + 2, div, div_blocks, num_blocks);
  243. } else {
  244. // else the bit is not set or the last level has been reached
  245. // (bit implicitly not set)
  246. **div_blocks = div;
  247. (*div_blocks)++;
  248. (*num_blocks)++;
  249. }
  250. }
  251. /** Reads and decodes a Rice codeword.
  252. */
  253. static int32_t decode_rice(GetBitContext *gb, unsigned int k)
  254. {
  255. int max = gb->size_in_bits - get_bits_count(gb) - k;
  256. int q = get_unary(gb, 0, max);
  257. int r = k ? get_bits1(gb) : !(q & 1);
  258. if (k > 1) {
  259. q <<= (k - 1);
  260. q += get_bits_long(gb, k - 1);
  261. } else if (!k) {
  262. q >>= 1;
  263. }
  264. return r ? q : ~q;
  265. }
  266. /** Converts PARCOR coefficient k to direct filter coefficient.
  267. */
  268. static void parcor_to_lpc(unsigned int k, const int32_t *par, int32_t *cof)
  269. {
  270. int i, j;
  271. for (i = 0, j = k - 1; i < j; i++, j--) {
  272. int tmp1 = ((MUL64(par[k], cof[j]) + (1 << 19)) >> 20);
  273. cof[j] += ((MUL64(par[k], cof[i]) + (1 << 19)) >> 20);
  274. cof[i] += tmp1;
  275. }
  276. if (i == j)
  277. cof[i] += ((MUL64(par[k], cof[j]) + (1 << 19)) >> 20);
  278. cof[k] = par[k];
  279. }
  280. /** Reads block switching field if necessary and sets actual block sizes.
  281. * Also assures that the block sizes of the last frame correspond to the
  282. * actual number of samples.
  283. */
  284. static void get_block_sizes(ALSDecContext *ctx, unsigned int *div_blocks,
  285. uint32_t *bs_info)
  286. {
  287. ALSSpecificConfig *sconf = &ctx->sconf;
  288. GetBitContext *gb = &ctx->gb;
  289. unsigned int *ptr_div_blocks = div_blocks;
  290. unsigned int b;
  291. if (sconf->block_switching) {
  292. unsigned int bs_info_len = 1 << (sconf->block_switching + 2);
  293. *bs_info = get_bits_long(gb, bs_info_len);
  294. *bs_info <<= (32 - bs_info_len);
  295. }
  296. ctx->num_blocks = 0;
  297. parse_bs_info(*bs_info, 0, 0, &ptr_div_blocks, &ctx->num_blocks);
  298. // The last frame may have an overdetermined block structure given in
  299. // the bitstream. In that case the defined block structure would need
  300. // more samples than available to be consistent.
  301. // The block structure is actually used but the block sizes are adapted
  302. // to fit the actual number of available samples.
  303. // Example: 5 samples, 2nd level block sizes: 2 2 2 2.
  304. // This results in the actual block sizes: 2 2 1 0.
  305. // This is not specified in 14496-3 but actually done by the reference
  306. // codec RM22 revision 2.
  307. // This appears to happen in case of an odd number of samples in the last
  308. // frame which is actually not allowed by the block length switching part
  309. // of 14496-3.
  310. // The ALS conformance files feature an odd number of samples in the last
  311. // frame.
  312. for (b = 0; b < ctx->num_blocks; b++)
  313. div_blocks[b] = ctx->sconf.frame_length >> div_blocks[b];
  314. if (ctx->cur_frame_length != ctx->sconf.frame_length) {
  315. unsigned int remaining = ctx->cur_frame_length;
  316. for (b = 0; b < ctx->num_blocks; b++) {
  317. if (remaining < div_blocks[b]) {
  318. div_blocks[b] = remaining;
  319. ctx->num_blocks = b + 1;
  320. break;
  321. }
  322. remaining -= div_blocks[b];
  323. }
  324. }
  325. }
  326. /** Reads the block data for a constant block
  327. */
  328. static void read_const_block(ALSDecContext *ctx, int32_t *raw_samples,
  329. unsigned int block_length, unsigned int *js_blocks)
  330. {
  331. ALSSpecificConfig *sconf = &ctx->sconf;
  332. AVCodecContext *avctx = ctx->avctx;
  333. GetBitContext *gb = &ctx->gb;
  334. int32_t const_val = 0;
  335. unsigned int const_block, k;
  336. const_block = get_bits1(gb); // 1 = constant value, 0 = zero block (silence)
  337. *js_blocks = get_bits1(gb);
  338. // skip 5 reserved bits
  339. skip_bits(gb, 5);
  340. if (const_block) {
  341. unsigned int const_val_bits = sconf->floating ? 24 : avctx->bits_per_raw_sample;
  342. const_val = get_sbits_long(gb, const_val_bits);
  343. }
  344. // write raw samples into buffer
  345. for (k = 0; k < block_length; k++)
  346. raw_samples[k] = const_val;
  347. }
  348. /** Reads the block data for a non-constant block
  349. */
  350. static int read_var_block(ALSDecContext *ctx, unsigned int ra_block,
  351. int32_t *raw_samples, unsigned int block_length,
  352. unsigned int *js_blocks, int32_t *raw_other,
  353. unsigned int *shift_lsbs)
  354. {
  355. ALSSpecificConfig *sconf = &ctx->sconf;
  356. AVCodecContext *avctx = ctx->avctx;
  357. GetBitContext *gb = &ctx->gb;
  358. unsigned int k;
  359. unsigned int s[8];
  360. unsigned int sub_blocks, log2_sub_blocks, sb_length;
  361. unsigned int opt_order = 1;
  362. int32_t *quant_cof = ctx->quant_cof;
  363. int32_t *lpc_cof = ctx->lpc_cof;
  364. unsigned int start = 0;
  365. int smp = 0;
  366. int sb, store_prev_samples;
  367. int64_t y;
  368. *js_blocks = get_bits1(gb);
  369. // determine the number of subblocks for entropy decoding
  370. if (!sconf->bgmc && !sconf->sb_part) {
  371. log2_sub_blocks = 0;
  372. } else {
  373. if (sconf->bgmc && sconf->sb_part)
  374. log2_sub_blocks = get_bits(gb, 2);
  375. else
  376. log2_sub_blocks = 2 * get_bits1(gb);
  377. }
  378. sub_blocks = 1 << log2_sub_blocks;
  379. // do not continue in case of a damaged stream since
  380. // block_length must be evenly divisible by sub_blocks
  381. if (block_length & (sub_blocks - 1)) {
  382. av_log(avctx, AV_LOG_WARNING,
  383. "Block length is not evenly divisible by the number of subblocks.\n");
  384. return -1;
  385. }
  386. sb_length = block_length >> log2_sub_blocks;
  387. if (sconf->bgmc) {
  388. // TODO: BGMC mode
  389. } else {
  390. s[0] = get_bits(gb, 4 + (sconf->resolution > 1));
  391. for (k = 1; k < sub_blocks; k++)
  392. s[k] = s[k - 1] + decode_rice(gb, 0);
  393. }
  394. if (get_bits1(gb))
  395. *shift_lsbs = get_bits(gb, 4) + 1;
  396. store_prev_samples = (*js_blocks && raw_other) || *shift_lsbs;
  397. if (!sconf->rlslms) {
  398. if (sconf->adapt_order) {
  399. int opt_order_length = av_ceil_log2(av_clip((block_length >> 3) - 1,
  400. 2, sconf->max_order + 1));
  401. opt_order = get_bits(gb, opt_order_length);
  402. } else {
  403. opt_order = sconf->max_order;
  404. }
  405. if (opt_order) {
  406. int add_base;
  407. if (sconf->coef_table == 3) {
  408. add_base = 0x7F;
  409. // read coefficient 0
  410. quant_cof[0] = 32 * parcor_scaled_values[get_bits(gb, 7)];
  411. // read coefficient 1
  412. if (opt_order > 1)
  413. quant_cof[1] = -32 * parcor_scaled_values[get_bits(gb, 7)];
  414. // read coefficients 2 to opt_order
  415. for (k = 2; k < opt_order; k++)
  416. quant_cof[k] = get_bits(gb, 7);
  417. } else {
  418. int k_max;
  419. add_base = 1;
  420. // read coefficient 0 to 19
  421. k_max = FFMIN(opt_order, 20);
  422. for (k = 0; k < k_max; k++) {
  423. int rice_param = parcor_rice_table[sconf->coef_table][k][1];
  424. int offset = parcor_rice_table[sconf->coef_table][k][0];
  425. quant_cof[k] = decode_rice(gb, rice_param) + offset;
  426. }
  427. // read coefficients 20 to 126
  428. k_max = FFMIN(opt_order, 127);
  429. for (; k < k_max; k++)
  430. quant_cof[k] = decode_rice(gb, 2) + (k & 1);
  431. // read coefficients 127 to opt_order
  432. for (; k < opt_order; k++)
  433. quant_cof[k] = decode_rice(gb, 1);
  434. quant_cof[0] = 32 * parcor_scaled_values[quant_cof[0] + 64];
  435. if (opt_order > 1)
  436. quant_cof[1] = -32 * parcor_scaled_values[quant_cof[1] + 64];
  437. }
  438. for (k = 2; k < opt_order; k++)
  439. quant_cof[k] = (quant_cof[k] << 14) + (add_base << 13);
  440. }
  441. }
  442. // TODO: LTP mode
  443. // read first value and residuals in case of a random access block
  444. if (ra_block) {
  445. if (opt_order)
  446. raw_samples[0] = decode_rice(gb, avctx->bits_per_raw_sample - 4);
  447. if (opt_order > 1)
  448. raw_samples[1] = decode_rice(gb, s[0] + 3);
  449. if (opt_order > 2)
  450. raw_samples[2] = decode_rice(gb, s[0] + 1);
  451. start = FFMIN(opt_order, 3);
  452. }
  453. // read all residuals
  454. if (sconf->bgmc) {
  455. // TODO: BGMC mode
  456. } else {
  457. int32_t *current_res = raw_samples + start;
  458. for (sb = 0; sb < sub_blocks; sb++, start = 0)
  459. for (; start < sb_length; start++)
  460. *current_res++ = decode_rice(gb, s[sb]);
  461. }
  462. // reconstruct all samples from residuals
  463. if (ra_block) {
  464. for (smp = 0; smp < opt_order; smp++) {
  465. y = 1 << 19;
  466. for (sb = 0; sb < smp; sb++)
  467. y += MUL64(lpc_cof[sb],raw_samples[smp - (sb + 1)]);
  468. raw_samples[smp] -= y >> 20;
  469. parcor_to_lpc(smp, quant_cof, lpc_cof);
  470. }
  471. } else {
  472. for (k = 0; k < opt_order; k++)
  473. parcor_to_lpc(k, quant_cof, lpc_cof);
  474. // store previous samples in case that they have to be altered
  475. if (store_prev_samples)
  476. memcpy(ctx->prev_raw_samples, raw_samples - sconf->max_order,
  477. sizeof(*ctx->prev_raw_samples) * sconf->max_order);
  478. // reconstruct difference signal for prediction (joint-stereo)
  479. if (*js_blocks && raw_other) {
  480. int32_t *left, *right;
  481. if (raw_other > raw_samples) { // D = R - L
  482. left = raw_samples;
  483. right = raw_other;
  484. } else { // D = R - L
  485. left = raw_other;
  486. right = raw_samples;
  487. }
  488. for (sb = -1; sb >= -sconf->max_order; sb--)
  489. raw_samples[sb] = right[sb] - left[sb];
  490. }
  491. // reconstruct shifted signal
  492. if (*shift_lsbs)
  493. for (sb = -1; sb >= -sconf->max_order; sb--)
  494. raw_samples[sb] >>= *shift_lsbs;
  495. }
  496. // reconstruct raw samples
  497. for (; smp < block_length; smp++) {
  498. y = 1 << 19;
  499. for (sb = 0; sb < opt_order; sb++)
  500. y += MUL64(lpc_cof[sb],raw_samples[smp - (sb + 1)]);
  501. raw_samples[smp] -= y >> 20;
  502. }
  503. // restore previous samples in case that they have been altered
  504. if (store_prev_samples)
  505. memcpy(raw_samples - sconf->max_order, ctx->prev_raw_samples,
  506. sizeof(*raw_samples) * sconf->max_order);
  507. return 0;
  508. }
  509. /** Reads the block data.
  510. */
  511. static int read_block_data(ALSDecContext *ctx, unsigned int ra_block,
  512. int32_t *raw_samples, unsigned int block_length,
  513. unsigned int *js_blocks, int32_t *raw_other)
  514. {
  515. ALSSpecificConfig *sconf = &ctx->sconf;
  516. GetBitContext *gb = &ctx->gb;
  517. unsigned int shift_lsbs = 0;
  518. unsigned int k;
  519. // read block type flag and read the samples accordingly
  520. if (get_bits1(gb)) {
  521. if (read_var_block(ctx, ra_block, raw_samples, block_length, js_blocks,
  522. raw_other, &shift_lsbs))
  523. return -1;
  524. } else {
  525. read_const_block(ctx, raw_samples, block_length, js_blocks);
  526. }
  527. // TODO: read RLSLMS extension data
  528. if (!sconf->mc_coding || ctx->js_switch)
  529. align_get_bits(gb);
  530. if (shift_lsbs)
  531. for (k = 0; k < block_length; k++)
  532. raw_samples[k] <<= shift_lsbs;
  533. return 0;
  534. }
  535. /** Computes the number of samples left to decode for the current frame and
  536. * sets these samples to zero.
  537. */
  538. static void zero_remaining(unsigned int b, unsigned int b_max,
  539. const unsigned int *div_blocks, int32_t *buf)
  540. {
  541. unsigned int count = 0;
  542. while (b < b_max)
  543. count += div_blocks[b];
  544. if (count)
  545. memset(buf, 0, sizeof(*buf) * count);
  546. }
  547. /** Decodes blocks independently.
  548. */
  549. static int decode_blocks_ind(ALSDecContext *ctx, unsigned int ra_frame,
  550. unsigned int c, const unsigned int *div_blocks,
  551. unsigned int *js_blocks)
  552. {
  553. int32_t *raw_sample;
  554. unsigned int b;
  555. raw_sample = ctx->raw_samples[c];
  556. for (b = 0; b < ctx->num_blocks; b++) {
  557. if (read_block_data(ctx, ra_frame, raw_sample,
  558. div_blocks[b], &js_blocks[0], NULL)) {
  559. // damaged block, write zero for the rest of the frame
  560. zero_remaining(b, ctx->num_blocks, div_blocks, raw_sample);
  561. return -1;
  562. }
  563. raw_sample += div_blocks[b];
  564. ra_frame = 0;
  565. }
  566. return 0;
  567. }
  568. /** Decodes blocks dependently.
  569. */
  570. static int decode_blocks(ALSDecContext *ctx, unsigned int ra_frame,
  571. unsigned int c, const unsigned int *div_blocks,
  572. unsigned int *js_blocks)
  573. {
  574. ALSSpecificConfig *sconf = &ctx->sconf;
  575. unsigned int offset = 0;
  576. int32_t *raw_samples_R;
  577. int32_t *raw_samples_L;
  578. unsigned int b;
  579. // decode all blocks
  580. for (b = 0; b < ctx->num_blocks; b++) {
  581. unsigned int s;
  582. raw_samples_L = ctx->raw_samples[c ] + offset;
  583. raw_samples_R = ctx->raw_samples[c + 1] + offset;
  584. if (read_block_data(ctx, ra_frame, raw_samples_L, div_blocks[b],
  585. &js_blocks[0], raw_samples_R) ||
  586. read_block_data(ctx, ra_frame, raw_samples_R, div_blocks[b],
  587. &js_blocks[1], raw_samples_L)) {
  588. // damaged block, write zero for the rest of the frame
  589. zero_remaining(b, ctx->num_blocks, div_blocks, raw_samples_L);
  590. zero_remaining(b, ctx->num_blocks, div_blocks, raw_samples_R);
  591. return -1;
  592. }
  593. // reconstruct joint-stereo blocks
  594. if (js_blocks[0]) {
  595. if (js_blocks[1])
  596. av_log(ctx->avctx, AV_LOG_WARNING, "Invalid channel pair!\n");
  597. for (s = 0; s < div_blocks[b]; s++)
  598. raw_samples_L[s] = raw_samples_R[s] - raw_samples_L[s];
  599. } else if (js_blocks[1]) {
  600. for (s = 0; s < div_blocks[b]; s++)
  601. raw_samples_R[s] = raw_samples_R[s] + raw_samples_L[s];
  602. }
  603. offset += div_blocks[b];
  604. ra_frame = 0;
  605. }
  606. // store carryover raw samples,
  607. // the others channel raw samples are stored by the calling function.
  608. memmove(ctx->raw_samples[c] - sconf->max_order,
  609. ctx->raw_samples[c] - sconf->max_order + sconf->frame_length,
  610. sizeof(*ctx->raw_samples[c]) * sconf->max_order);
  611. return 0;
  612. }
  613. /** Reads the frame data.
  614. */
  615. static int read_frame_data(ALSDecContext *ctx, unsigned int ra_frame)
  616. {
  617. ALSSpecificConfig *sconf = &ctx->sconf;
  618. AVCodecContext *avctx = ctx->avctx;
  619. GetBitContext *gb = &ctx->gb;
  620. unsigned int div_blocks[32]; ///< block sizes.
  621. unsigned int c;
  622. unsigned int js_blocks[2];
  623. uint32_t bs_info = 0;
  624. // skip the size of the ra unit if present in the frame
  625. if (sconf->ra_flag == RA_FLAG_FRAMES && ra_frame)
  626. skip_bits_long(gb, 32);
  627. if (sconf->mc_coding && sconf->joint_stereo) {
  628. ctx->js_switch = get_bits1(gb);
  629. align_get_bits(gb);
  630. }
  631. if (!sconf->mc_coding || ctx->js_switch) {
  632. int independent_bs = !sconf->joint_stereo;
  633. for (c = 0; c < avctx->channels; c++) {
  634. js_blocks[0] = 0;
  635. js_blocks[1] = 0;
  636. get_block_sizes(ctx, div_blocks, &bs_info);
  637. // if joint_stereo and block_switching is set, independent decoding
  638. // is signaled via the first bit of bs_info
  639. if (sconf->joint_stereo && sconf->block_switching)
  640. if (bs_info >> 31)
  641. independent_bs = 2;
  642. // if this is the last channel, it has to be decoded independently
  643. if (c == avctx->channels - 1)
  644. independent_bs = 1;
  645. if (independent_bs) {
  646. if (decode_blocks_ind(ctx, ra_frame, c, div_blocks, js_blocks))
  647. return -1;
  648. independent_bs--;
  649. } else {
  650. if (decode_blocks(ctx, ra_frame, c, div_blocks, js_blocks))
  651. return -1;
  652. c++;
  653. }
  654. // store carryover raw samples
  655. memmove(ctx->raw_samples[c] - sconf->max_order,
  656. ctx->raw_samples[c] - sconf->max_order + sconf->frame_length,
  657. sizeof(*ctx->raw_samples[c]) * sconf->max_order);
  658. }
  659. } else { // multi-channel coding
  660. get_block_sizes(ctx, div_blocks, &bs_info);
  661. // TODO: multi channel coding might use a temporary buffer instead as
  662. // the actual channel is not known when read_block-data is called
  663. if (decode_blocks_ind(ctx, ra_frame, 0, div_blocks, js_blocks))
  664. return -1;
  665. // TODO: read_channel_data
  666. }
  667. // TODO: read_diff_float_data
  668. return 0;
  669. }
  670. /** Decodes an ALS frame.
  671. */
  672. static int decode_frame(AVCodecContext *avctx,
  673. void *data, int *data_size,
  674. AVPacket *avpkt)
  675. {
  676. ALSDecContext *ctx = avctx->priv_data;
  677. ALSSpecificConfig *sconf = &ctx->sconf;
  678. const uint8_t *buffer = avpkt->data;
  679. int buffer_size = avpkt->size;
  680. int invalid_frame, size;
  681. unsigned int c, sample, ra_frame, bytes_read, shift;
  682. init_get_bits(&ctx->gb, buffer, buffer_size * 8);
  683. // In the case that the distance between random access frames is set to zero
  684. // (sconf->ra_distance == 0) no frame is treated as a random access frame.
  685. // For the first frame, if prediction is used, all samples used from the
  686. // previous frame are assumed to be zero.
  687. ra_frame = sconf->ra_distance && !(ctx->frame_id % sconf->ra_distance);
  688. // the last frame to decode might have a different length
  689. if (sconf->samples != 0xFFFFFFFF)
  690. ctx->cur_frame_length = FFMIN(sconf->samples - ctx->frame_id * (uint64_t) sconf->frame_length,
  691. sconf->frame_length);
  692. else
  693. ctx->cur_frame_length = sconf->frame_length;
  694. // decode the frame data
  695. if ((invalid_frame = read_frame_data(ctx, ra_frame) < 0))
  696. av_log(ctx->avctx, AV_LOG_WARNING,
  697. "Reading frame data failed. Skipping RA unit.\n");
  698. ctx->frame_id++;
  699. // check for size of decoded data
  700. size = ctx->cur_frame_length * avctx->channels *
  701. (av_get_bits_per_sample_format(avctx->sample_fmt) >> 3);
  702. if (size > *data_size) {
  703. av_log(avctx, AV_LOG_ERROR, "Decoded data exceeds buffer size.\n");
  704. return -1;
  705. }
  706. *data_size = size;
  707. // transform decoded frame into output format
  708. #define INTERLEAVE_OUTPUT(bps) \
  709. { \
  710. int##bps##_t *dest = (int##bps##_t*) data; \
  711. shift = bps - ctx->avctx->bits_per_raw_sample; \
  712. for (sample = 0; sample < ctx->cur_frame_length; sample++) \
  713. for (c = 0; c < avctx->channels; c++) \
  714. *dest++ = ctx->raw_samples[c][sample] << shift; \
  715. }
  716. if (ctx->avctx->bits_per_raw_sample <= 16) {
  717. INTERLEAVE_OUTPUT(16)
  718. } else {
  719. INTERLEAVE_OUTPUT(32)
  720. }
  721. bytes_read = invalid_frame ? buffer_size :
  722. (get_bits_count(&ctx->gb) + 7) >> 3;
  723. return bytes_read;
  724. }
  725. /** Uninitializes the ALS decoder.
  726. */
  727. static av_cold int decode_end(AVCodecContext *avctx)
  728. {
  729. ALSDecContext *ctx = avctx->priv_data;
  730. av_freep(&ctx->sconf.chan_pos);
  731. av_freep(&ctx->quant_cof);
  732. av_freep(&ctx->lpc_cof);
  733. av_freep(&ctx->prev_raw_samples);
  734. av_freep(&ctx->raw_samples);
  735. av_freep(&ctx->raw_buffer);
  736. return 0;
  737. }
  738. /** Initializes the ALS decoder.
  739. */
  740. static av_cold int decode_init(AVCodecContext *avctx)
  741. {
  742. unsigned int c;
  743. unsigned int channel_size;
  744. ALSDecContext *ctx = avctx->priv_data;
  745. ALSSpecificConfig *sconf = &ctx->sconf;
  746. ctx->avctx = avctx;
  747. if (!avctx->extradata) {
  748. av_log(avctx, AV_LOG_ERROR, "Missing required ALS extradata.\n");
  749. return -1;
  750. }
  751. if (read_specific_config(ctx)) {
  752. av_log(avctx, AV_LOG_ERROR, "Reading ALSSpecificConfig failed.\n");
  753. decode_end(avctx);
  754. return -1;
  755. }
  756. if (check_specific_config(ctx)) {
  757. decode_end(avctx);
  758. return -1;
  759. }
  760. if (sconf->floating) {
  761. avctx->sample_fmt = SAMPLE_FMT_FLT;
  762. avctx->bits_per_raw_sample = 32;
  763. } else {
  764. avctx->sample_fmt = sconf->resolution > 1
  765. ? SAMPLE_FMT_S32 : SAMPLE_FMT_S16;
  766. avctx->bits_per_raw_sample = (sconf->resolution + 1) * 8;
  767. }
  768. avctx->frame_size = sconf->frame_length;
  769. channel_size = sconf->frame_length + sconf->max_order;
  770. ctx->prev_raw_samples = av_malloc (sizeof(*ctx->prev_raw_samples) * sconf->max_order);
  771. ctx->raw_buffer = av_mallocz(sizeof(*ctx-> raw_buffer) * avctx->channels * channel_size);
  772. ctx->raw_samples = av_malloc (sizeof(*ctx-> raw_samples) * avctx->channels);
  773. // allocate previous raw sample buffer
  774. if (!ctx->prev_raw_samples || !ctx->raw_buffer|| !ctx->raw_samples) {
  775. av_log(avctx, AV_LOG_ERROR, "Allocating buffer memory failed.\n");
  776. decode_end(avctx);
  777. return AVERROR(ENOMEM);
  778. }
  779. // assign raw samples buffers
  780. ctx->raw_samples[0] = ctx->raw_buffer + sconf->max_order;
  781. for (c = 1; c < avctx->channels; c++)
  782. ctx->raw_samples[c] = ctx->raw_samples[c - 1] + channel_size;
  783. return 0;
  784. }
  785. /** Flushes (resets) the frame ID after seeking.
  786. */
  787. static av_cold void flush(AVCodecContext *avctx)
  788. {
  789. ALSDecContext *ctx = avctx->priv_data;
  790. ctx->frame_id = 0;
  791. }
  792. AVCodec als_decoder = {
  793. "als",
  794. CODEC_TYPE_AUDIO,
  795. CODEC_ID_MP4ALS,
  796. sizeof(ALSDecContext),
  797. decode_init,
  798. NULL,
  799. decode_end,
  800. decode_frame,
  801. .flush = flush,
  802. .capabilities = CODEC_CAP_SUBFRAMES,
  803. .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 Audio Lossless Coding (ALS)"),
  804. };