FFmpeg  2.8.17
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Modules Pages
alsdec.c
Go to the documentation of this file.
1 /*
2  * MPEG-4 ALS decoder
3  * Copyright (c) 2009 Thilo Borgmann <thilo.borgmann _at_ mail.de>
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 /**
23  * @file
24  * MPEG-4 ALS decoder
25  * @author Thilo Borgmann <thilo.borgmann _at_ mail.de>
26  */
27 
28 #include <inttypes.h>
29 
30 #include "avcodec.h"
31 #include "get_bits.h"
32 #include "unary.h"
33 #include "mpeg4audio.h"
34 #include "bytestream.h"
35 #include "bgmc.h"
36 #include "bswapdsp.h"
37 #include "internal.h"
38 #include "libavutil/samplefmt.h"
39 #include "libavutil/crc.h"
40 
41 #include <stdint.h>
42 
43 /** Rice parameters and corresponding index offsets for decoding the
44  * indices of scaled PARCOR values. The table chosen is set globally
45  * by the encoder and stored in ALSSpecificConfig.
46  */
47 static const int8_t parcor_rice_table[3][20][2] = {
48  { {-52, 4}, {-29, 5}, {-31, 4}, { 19, 4}, {-16, 4},
49  { 12, 3}, { -7, 3}, { 9, 3}, { -5, 3}, { 6, 3},
50  { -4, 3}, { 3, 3}, { -3, 2}, { 3, 2}, { -2, 2},
51  { 3, 2}, { -1, 2}, { 2, 2}, { -1, 2}, { 2, 2} },
52  { {-58, 3}, {-42, 4}, {-46, 4}, { 37, 5}, {-36, 4},
53  { 29, 4}, {-29, 4}, { 25, 4}, {-23, 4}, { 20, 4},
54  {-17, 4}, { 16, 4}, {-12, 4}, { 12, 3}, {-10, 4},
55  { 7, 3}, { -4, 4}, { 3, 3}, { -1, 3}, { 1, 3} },
56  { {-59, 3}, {-45, 5}, {-50, 4}, { 38, 4}, {-39, 4},
57  { 32, 4}, {-30, 4}, { 25, 3}, {-23, 3}, { 20, 3},
58  {-20, 3}, { 16, 3}, {-13, 3}, { 10, 3}, { -7, 3},
59  { 3, 3}, { 0, 3}, { -1, 3}, { 2, 3}, { -1, 2} }
60 };
61 
62 
63 /** Scaled PARCOR values used for the first two PARCOR coefficients.
64  * To be indexed by the Rice coded indices.
65  * Generated by: parcor_scaled_values[i] = 32 + ((i * (i+1)) << 7) - (1 << 20)
66  * Actual values are divided by 32 in order to be stored in 16 bits.
67  */
68 static const int16_t parcor_scaled_values[] = {
69  -1048544 / 32, -1048288 / 32, -1047776 / 32, -1047008 / 32,
70  -1045984 / 32, -1044704 / 32, -1043168 / 32, -1041376 / 32,
71  -1039328 / 32, -1037024 / 32, -1034464 / 32, -1031648 / 32,
72  -1028576 / 32, -1025248 / 32, -1021664 / 32, -1017824 / 32,
73  -1013728 / 32, -1009376 / 32, -1004768 / 32, -999904 / 32,
74  -994784 / 32, -989408 / 32, -983776 / 32, -977888 / 32,
75  -971744 / 32, -965344 / 32, -958688 / 32, -951776 / 32,
76  -944608 / 32, -937184 / 32, -929504 / 32, -921568 / 32,
77  -913376 / 32, -904928 / 32, -896224 / 32, -887264 / 32,
78  -878048 / 32, -868576 / 32, -858848 / 32, -848864 / 32,
79  -838624 / 32, -828128 / 32, -817376 / 32, -806368 / 32,
80  -795104 / 32, -783584 / 32, -771808 / 32, -759776 / 32,
81  -747488 / 32, -734944 / 32, -722144 / 32, -709088 / 32,
82  -695776 / 32, -682208 / 32, -668384 / 32, -654304 / 32,
83  -639968 / 32, -625376 / 32, -610528 / 32, -595424 / 32,
84  -580064 / 32, -564448 / 32, -548576 / 32, -532448 / 32,
85  -516064 / 32, -499424 / 32, -482528 / 32, -465376 / 32,
86  -447968 / 32, -430304 / 32, -412384 / 32, -394208 / 32,
87  -375776 / 32, -357088 / 32, -338144 / 32, -318944 / 32,
88  -299488 / 32, -279776 / 32, -259808 / 32, -239584 / 32,
89  -219104 / 32, -198368 / 32, -177376 / 32, -156128 / 32,
90  -134624 / 32, -112864 / 32, -90848 / 32, -68576 / 32,
91  -46048 / 32, -23264 / 32, -224 / 32, 23072 / 32,
92  46624 / 32, 70432 / 32, 94496 / 32, 118816 / 32,
93  143392 / 32, 168224 / 32, 193312 / 32, 218656 / 32,
94  244256 / 32, 270112 / 32, 296224 / 32, 322592 / 32,
95  349216 / 32, 376096 / 32, 403232 / 32, 430624 / 32,
96  458272 / 32, 486176 / 32, 514336 / 32, 542752 / 32,
97  571424 / 32, 600352 / 32, 629536 / 32, 658976 / 32,
98  688672 / 32, 718624 / 32, 748832 / 32, 779296 / 32,
99  810016 / 32, 840992 / 32, 872224 / 32, 903712 / 32,
100  935456 / 32, 967456 / 32, 999712 / 32, 1032224 / 32
101 };
102 
103 
104 /** Gain values of p(0) for long-term prediction.
105  * To be indexed by the Rice coded indices.
106  */
107 static const uint8_t ltp_gain_values [4][4] = {
108  { 0, 8, 16, 24},
109  {32, 40, 48, 56},
110  {64, 70, 76, 82},
111  {88, 92, 96, 100}
112 };
113 
114 
115 /** Inter-channel weighting factors for multi-channel correlation.
116  * To be indexed by the Rice coded indices.
117  */
118 static const int16_t mcc_weightings[] = {
119  204, 192, 179, 166, 153, 140, 128, 115,
120  102, 89, 76, 64, 51, 38, 25, 12,
121  0, -12, -25, -38, -51, -64, -76, -89,
122  -102, -115, -128, -140, -153, -166, -179, -192
123 };
124 
125 
126 /** Tail codes used in arithmetic coding using block Gilbert-Moore codes.
127  */
128 static const uint8_t tail_code[16][6] = {
129  { 74, 44, 25, 13, 7, 3},
130  { 68, 42, 24, 13, 7, 3},
131  { 58, 39, 23, 13, 7, 3},
132  {126, 70, 37, 19, 10, 5},
133  {132, 70, 37, 20, 10, 5},
134  {124, 70, 38, 20, 10, 5},
135  {120, 69, 37, 20, 11, 5},
136  {116, 67, 37, 20, 11, 5},
137  {108, 66, 36, 20, 10, 5},
138  {102, 62, 36, 20, 10, 5},
139  { 88, 58, 34, 19, 10, 5},
140  {162, 89, 49, 25, 13, 7},
141  {156, 87, 49, 26, 14, 7},
142  {150, 86, 47, 26, 14, 7},
143  {142, 84, 47, 26, 14, 7},
144  {131, 79, 46, 26, 14, 7}
145 };
146 
147 
148 enum RA_Flag {
152 };
153 
154 
155 typedef struct ALSSpecificConfig {
156  uint32_t samples; ///< number of samples, 0xFFFFFFFF if unknown
157  int resolution; ///< 000 = 8-bit; 001 = 16-bit; 010 = 24-bit; 011 = 32-bit
158  int floating; ///< 1 = IEEE 32-bit floating-point, 0 = integer
159  int msb_first; ///< 1 = original CRC calculated on big-endian system, 0 = little-endian
160  int frame_length; ///< frame length for each frame (last frame may differ)
161  int ra_distance; ///< distance between RA frames (in frames, 0...255)
162  enum RA_Flag ra_flag; ///< indicates where the size of ra units is stored
163  int adapt_order; ///< adaptive order: 1 = on, 0 = off
164  int coef_table; ///< table index of Rice code parameters
165  int long_term_prediction; ///< long term prediction (LTP): 1 = on, 0 = off
166  int max_order; ///< maximum prediction order (0..1023)
167  int block_switching; ///< number of block switching levels
168  int bgmc; ///< "Block Gilbert-Moore Code": 1 = on, 0 = off (Rice coding only)
169  int sb_part; ///< sub-block partition
170  int joint_stereo; ///< joint stereo: 1 = on, 0 = off
171  int mc_coding; ///< extended inter-channel coding (multi channel coding): 1 = on, 0 = off
172  int chan_config; ///< indicates that a chan_config_info field is present
173  int chan_sort; ///< channel rearrangement: 1 = on, 0 = off
174  int rlslms; ///< use "Recursive Least Square-Least Mean Square" predictor: 1 = on, 0 = off
175  int chan_config_info; ///< mapping of channels to loudspeaker locations. Unused until setting channel configuration is implemented.
176  int *chan_pos; ///< original channel positions
177  int crc_enabled; ///< enable Cyclic Redundancy Checksum
179 
180 
181 typedef struct ALSChannelData {
187  int weighting[6];
189 
190 
191 typedef struct ALSDecContext {
196  const AVCRC *crc_table;
197  uint32_t crc_org; ///< CRC value of the original input data
198  uint32_t crc; ///< CRC value calculated from decoded data
199  unsigned int cur_frame_length; ///< length of the current frame to decode
200  unsigned int frame_id; ///< the frame ID / number of the current frame
201  unsigned int js_switch; ///< if true, joint-stereo decoding is enforced
202  unsigned int cs_switch; ///< if true, channel rearrangement is done
203  unsigned int num_blocks; ///< number of blocks used in the current frame
204  unsigned int s_max; ///< maximum Rice parameter allowed in entropy coding
205  uint8_t *bgmc_lut; ///< pointer at lookup tables used for BGMC
206  int *bgmc_lut_status; ///< pointer at lookup table status flags used for BGMC
207  int ltp_lag_length; ///< number of bits used for ltp lag value
208  int *const_block; ///< contains const_block flags for all channels
209  unsigned int *shift_lsbs; ///< contains shift_lsbs flags for all channels
210  unsigned int *opt_order; ///< contains opt_order flags for all channels
211  int *store_prev_samples; ///< contains store_prev_samples flags for all channels
212  int *use_ltp; ///< contains use_ltp flags for all channels
213  int *ltp_lag; ///< contains ltp lag values for all channels
214  int **ltp_gain; ///< gain values for ltp 5-tap filter for a channel
215  int *ltp_gain_buffer; ///< contains all gain values for ltp 5-tap filter
216  int32_t **quant_cof; ///< quantized parcor coefficients for a channel
217  int32_t *quant_cof_buffer; ///< contains all quantized parcor coefficients
218  int32_t **lpc_cof; ///< coefficients of the direct form prediction filter for a channel
219  int32_t *lpc_cof_buffer; ///< contains all coefficients of the direct form prediction filter
220  int32_t *lpc_cof_reversed_buffer; ///< temporary buffer to set up a reversed versio of lpc_cof_buffer
221  ALSChannelData **chan_data; ///< channel data for multi-channel correlation
222  ALSChannelData *chan_data_buffer; ///< contains channel data for all channels
223  int *reverted_channels; ///< stores a flag for each reverted channel
224  int32_t *prev_raw_samples; ///< contains unshifted raw samples from the previous block
225  int32_t **raw_samples; ///< decoded raw samples for each channel
226  int32_t *raw_buffer; ///< contains all decoded raw samples including carryover samples
227  uint8_t *crc_buffer; ///< buffer of byte order corrected samples used for CRC check
228 } ALSDecContext;
229 
230 
231 typedef struct ALSBlockData {
232  unsigned int block_length; ///< number of samples within the block
233  unsigned int ra_block; ///< if true, this is a random access block
234  int *const_block; ///< if true, this is a constant value block
235  int js_blocks; ///< true if this block contains a difference signal
236  unsigned int *shift_lsbs; ///< shift of values for this block
237  unsigned int *opt_order; ///< prediction order of this block
238  int *store_prev_samples;///< if true, carryover samples have to be stored
239  int *use_ltp; ///< if true, long-term prediction is used
240  int *ltp_lag; ///< lag value for long-term prediction
241  int *ltp_gain; ///< gain values for ltp 5-tap filter
242  int32_t *quant_cof; ///< quantized parcor coefficients
243  int32_t *lpc_cof; ///< coefficients of the direct form prediction
244  int32_t *raw_samples; ///< decoded raw samples / residuals for this block
245  int32_t *prev_raw_samples; ///< contains unshifted raw samples from the previous block
246  int32_t *raw_other; ///< decoded raw samples of the other channel of a channel pair
247 } ALSBlockData;
248 
249 
251 {
252 #ifdef DEBUG
253  AVCodecContext *avctx = ctx->avctx;
254  ALSSpecificConfig *sconf = &ctx->sconf;
255 
256  ff_dlog(avctx, "resolution = %i\n", sconf->resolution);
257  ff_dlog(avctx, "floating = %i\n", sconf->floating);
258  ff_dlog(avctx, "frame_length = %i\n", sconf->frame_length);
259  ff_dlog(avctx, "ra_distance = %i\n", sconf->ra_distance);
260  ff_dlog(avctx, "ra_flag = %i\n", sconf->ra_flag);
261  ff_dlog(avctx, "adapt_order = %i\n", sconf->adapt_order);
262  ff_dlog(avctx, "coef_table = %i\n", sconf->coef_table);
263  ff_dlog(avctx, "long_term_prediction = %i\n", sconf->long_term_prediction);
264  ff_dlog(avctx, "max_order = %i\n", sconf->max_order);
265  ff_dlog(avctx, "block_switching = %i\n", sconf->block_switching);
266  ff_dlog(avctx, "bgmc = %i\n", sconf->bgmc);
267  ff_dlog(avctx, "sb_part = %i\n", sconf->sb_part);
268  ff_dlog(avctx, "joint_stereo = %i\n", sconf->joint_stereo);
269  ff_dlog(avctx, "mc_coding = %i\n", sconf->mc_coding);
270  ff_dlog(avctx, "chan_config = %i\n", sconf->chan_config);
271  ff_dlog(avctx, "chan_sort = %i\n", sconf->chan_sort);
272  ff_dlog(avctx, "RLSLMS = %i\n", sconf->rlslms);
273  ff_dlog(avctx, "chan_config_info = %i\n", sconf->chan_config_info);
274 #endif
275 }
276 
277 
278 /** Read an ALSSpecificConfig from a buffer into the output struct.
279  */
281 {
282  GetBitContext gb;
283  uint64_t ht_size;
284  int i, config_offset;
285  MPEG4AudioConfig m4ac = {0};
286  ALSSpecificConfig *sconf = &ctx->sconf;
287  AVCodecContext *avctx = ctx->avctx;
288  uint32_t als_id, header_size, trailer_size;
289  int ret;
290 
291  if ((ret = init_get_bits8(&gb, avctx->extradata, avctx->extradata_size)) < 0)
292  return ret;
293 
294  config_offset = avpriv_mpeg4audio_get_config(&m4ac, avctx->extradata,
295  avctx->extradata_size * 8, 1);
296 
297  if (config_offset < 0)
298  return AVERROR_INVALIDDATA;
299 
300  skip_bits_long(&gb, config_offset);
301 
302  if (get_bits_left(&gb) < (30 << 3))
303  return AVERROR_INVALIDDATA;
304 
305  // read the fixed items
306  als_id = get_bits_long(&gb, 32);
307  avctx->sample_rate = m4ac.sample_rate;
308  skip_bits_long(&gb, 32); // sample rate already known
309  sconf->samples = get_bits_long(&gb, 32);
310  avctx->channels = m4ac.channels;
311  skip_bits(&gb, 16); // number of channels already known
312  skip_bits(&gb, 3); // skip file_type
313  sconf->resolution = get_bits(&gb, 3);
314  sconf->floating = get_bits1(&gb);
315  sconf->msb_first = get_bits1(&gb);
316  sconf->frame_length = get_bits(&gb, 16) + 1;
317  sconf->ra_distance = get_bits(&gb, 8);
318  sconf->ra_flag = get_bits(&gb, 2);
319  sconf->adapt_order = get_bits1(&gb);
320  sconf->coef_table = get_bits(&gb, 2);
321  sconf->long_term_prediction = get_bits1(&gb);
322  sconf->max_order = get_bits(&gb, 10);
323  sconf->block_switching = get_bits(&gb, 2);
324  sconf->bgmc = get_bits1(&gb);
325  sconf->sb_part = get_bits1(&gb);
326  sconf->joint_stereo = get_bits1(&gb);
327  sconf->mc_coding = get_bits1(&gb);
328  sconf->chan_config = get_bits1(&gb);
329  sconf->chan_sort = get_bits1(&gb);
330  sconf->crc_enabled = get_bits1(&gb);
331  sconf->rlslms = get_bits1(&gb);
332  skip_bits(&gb, 5); // skip 5 reserved bits
333  skip_bits1(&gb); // skip aux_data_enabled
334 
335 
336  // check for ALSSpecificConfig struct
337  if (als_id != MKBETAG('A','L','S','\0'))
338  return AVERROR_INVALIDDATA;
339 
340  if (avctx->channels > FF_SANE_NB_CHANNELS) {
341  avpriv_request_sample(avctx, "Huge number of channels\n");
342  return AVERROR_PATCHWELCOME;
343  }
344 
345  ctx->cur_frame_length = sconf->frame_length;
346 
347  // read channel config
348  if (sconf->chan_config)
349  sconf->chan_config_info = get_bits(&gb, 16);
350  // TODO: use this to set avctx->channel_layout
351 
352 
353  // read channel sorting
354  if (sconf->chan_sort && avctx->channels > 1) {
355  int chan_pos_bits = av_ceil_log2(avctx->channels);
356  int bits_needed = avctx->channels * chan_pos_bits + 7;
357  if (get_bits_left(&gb) < bits_needed)
358  return AVERROR_INVALIDDATA;
359 
360  if (!(sconf->chan_pos = av_malloc_array(avctx->channels, sizeof(*sconf->chan_pos))))
361  return AVERROR(ENOMEM);
362 
363  ctx->cs_switch = 1;
364 
365  for (i = 0; i < avctx->channels; i++) {
366  sconf->chan_pos[i] = -1;
367  }
368 
369  for (i = 0; i < avctx->channels; i++) {
370  int idx;
371 
372  idx = get_bits(&gb, chan_pos_bits);
373  if (idx >= avctx->channels || sconf->chan_pos[idx] != -1) {
374  av_log(avctx, AV_LOG_WARNING, "Invalid channel reordering.\n");
375  ctx->cs_switch = 0;
376  break;
377  }
378  sconf->chan_pos[idx] = i;
379  }
380 
381  align_get_bits(&gb);
382  }
383 
384 
385  // read fixed header and trailer sizes,
386  // if size = 0xFFFFFFFF then there is no data field!
387  if (get_bits_left(&gb) < 64)
388  return AVERROR_INVALIDDATA;
389 
390  header_size = get_bits_long(&gb, 32);
391  trailer_size = get_bits_long(&gb, 32);
392  if (header_size == 0xFFFFFFFF)
393  header_size = 0;
394  if (trailer_size == 0xFFFFFFFF)
395  trailer_size = 0;
396 
397  ht_size = ((int64_t)(header_size) + (int64_t)(trailer_size)) << 3;
398 
399 
400  // skip the header and trailer data
401  if (get_bits_left(&gb) < ht_size)
402  return AVERROR_INVALIDDATA;
403 
404  if (ht_size > INT32_MAX)
405  return AVERROR_PATCHWELCOME;
406 
407  skip_bits_long(&gb, ht_size);
408 
409 
410  // initialize CRC calculation
411  if (sconf->crc_enabled) {
412  if (get_bits_left(&gb) < 32)
413  return AVERROR_INVALIDDATA;
414 
417  ctx->crc = 0xFFFFFFFF;
418  ctx->crc_org = ~get_bits_long(&gb, 32);
419  } else
420  skip_bits_long(&gb, 32);
421  }
422 
423 
424  // no need to read the rest of ALSSpecificConfig (ra_unit_size & aux data)
425 
427 
428  return 0;
429 }
430 
431 
432 /** Check the ALSSpecificConfig for unsupported features.
433  */
435 {
436  ALSSpecificConfig *sconf = &ctx->sconf;
437  int error = 0;
438 
439  // report unsupported feature and set error value
440  #define MISSING_ERR(cond, str, errval) \
441  { \
442  if (cond) { \
443  avpriv_report_missing_feature(ctx->avctx, \
444  str); \
445  error = errval; \
446  } \
447  }
448 
449  MISSING_ERR(sconf->floating, "Floating point decoding", AVERROR_PATCHWELCOME);
450  MISSING_ERR(sconf->rlslms, "Adaptive RLS-LMS prediction", AVERROR_PATCHWELCOME);
451 
452  return error;
453 }
454 
455 
456 /** Parse the bs_info field to extract the block partitioning used in
457  * block switching mode, refer to ISO/IEC 14496-3, section 11.6.2.
458  */
459 static void parse_bs_info(const uint32_t bs_info, unsigned int n,
460  unsigned int div, unsigned int **div_blocks,
461  unsigned int *num_blocks)
462 {
463  if (n < 31 && ((bs_info << n) & 0x40000000)) {
464  // if the level is valid and the investigated bit n is set
465  // then recursively check both children at bits (2n+1) and (2n+2)
466  n *= 2;
467  div += 1;
468  parse_bs_info(bs_info, n + 1, div, div_blocks, num_blocks);
469  parse_bs_info(bs_info, n + 2, div, div_blocks, num_blocks);
470  } else {
471  // else the bit is not set or the last level has been reached
472  // (bit implicitly not set)
473  **div_blocks = div;
474  (*div_blocks)++;
475  (*num_blocks)++;
476  }
477 }
478 
479 
480 /** Read and decode a Rice codeword.
481  */
482 static int32_t decode_rice(GetBitContext *gb, unsigned int k)
483 {
484  int max = get_bits_left(gb) - k;
485  unsigned q = get_unary(gb, 0, max);
486  int r = k ? get_bits1(gb) : !(q & 1);
487 
488  if (k > 1) {
489  q <<= (k - 1);
490  q += get_bits_long(gb, k - 1);
491  } else if (!k) {
492  q >>= 1;
493  }
494  return r ? q : ~q;
495 }
496 
497 
498 /** Convert PARCOR coefficient k to direct filter coefficient.
499  */
500 static void parcor_to_lpc(unsigned int k, const int32_t *par, int32_t *cof)
501 {
502  int i, j;
503 
504  for (i = 0, j = k - 1; i < j; i++, j--) {
505  unsigned tmp1 = ((MUL64(par[k], cof[j]) + (1 << 19)) >> 20);
506  cof[j] += ((MUL64(par[k], cof[i]) + (1 << 19)) >> 20);
507  cof[i] += tmp1;
508  }
509  if (i == j)
510  cof[i] += ((MUL64(par[k], cof[j]) + (1 << 19)) >> 20);
511 
512  cof[k] = par[k];
513 }
514 
515 
516 /** Read block switching field if necessary and set actual block sizes.
517  * Also assure that the block sizes of the last frame correspond to the
518  * actual number of samples.
519  */
520 static void get_block_sizes(ALSDecContext *ctx, unsigned int *div_blocks,
521  uint32_t *bs_info)
522 {
523  ALSSpecificConfig *sconf = &ctx->sconf;
524  GetBitContext *gb = &ctx->gb;
525  unsigned int *ptr_div_blocks = div_blocks;
526  unsigned int b;
527 
528  if (sconf->block_switching) {
529  unsigned int bs_info_len = 1 << (sconf->block_switching + 2);
530  *bs_info = get_bits_long(gb, bs_info_len);
531  *bs_info <<= (32 - bs_info_len);
532  }
533 
534  ctx->num_blocks = 0;
535  parse_bs_info(*bs_info, 0, 0, &ptr_div_blocks, &ctx->num_blocks);
536 
537  // The last frame may have an overdetermined block structure given in
538  // the bitstream. In that case the defined block structure would need
539  // more samples than available to be consistent.
540  // The block structure is actually used but the block sizes are adapted
541  // to fit the actual number of available samples.
542  // Example: 5 samples, 2nd level block sizes: 2 2 2 2.
543  // This results in the actual block sizes: 2 2 1 0.
544  // This is not specified in 14496-3 but actually done by the reference
545  // codec RM22 revision 2.
546  // This appears to happen in case of an odd number of samples in the last
547  // frame which is actually not allowed by the block length switching part
548  // of 14496-3.
549  // The ALS conformance files feature an odd number of samples in the last
550  // frame.
551 
552  for (b = 0; b < ctx->num_blocks; b++)
553  div_blocks[b] = ctx->sconf.frame_length >> div_blocks[b];
554 
555  if (ctx->cur_frame_length != ctx->sconf.frame_length) {
556  unsigned int remaining = ctx->cur_frame_length;
557 
558  for (b = 0; b < ctx->num_blocks; b++) {
559  if (remaining <= div_blocks[b]) {
560  div_blocks[b] = remaining;
561  ctx->num_blocks = b + 1;
562  break;
563  }
564 
565  remaining -= div_blocks[b];
566  }
567  }
568 }
569 
570 
571 /** Read the block data for a constant block
572  */
574 {
575  ALSSpecificConfig *sconf = &ctx->sconf;
576  AVCodecContext *avctx = ctx->avctx;
577  GetBitContext *gb = &ctx->gb;
578 
579  if (bd->block_length <= 0)
580  return AVERROR_INVALIDDATA;
581 
582  *bd->raw_samples = 0;
583  *bd->const_block = get_bits1(gb); // 1 = constant value, 0 = zero block (silence)
584  bd->js_blocks = get_bits1(gb);
585 
586  // skip 5 reserved bits
587  skip_bits(gb, 5);
588 
589  if (*bd->const_block) {
590  unsigned int const_val_bits = sconf->floating ? 24 : avctx->bits_per_raw_sample;
591  *bd->raw_samples = get_sbits_long(gb, const_val_bits);
592  }
593 
594  // ensure constant block decoding by reusing this field
595  *bd->const_block = 1;
596 
597  return 0;
598 }
599 
600 
601 /** Decode the block data for a constant block
602  */
604 {
605  int smp = bd->block_length - 1;
606  int32_t val = *bd->raw_samples;
607  int32_t *dst = bd->raw_samples + 1;
608 
609  // write raw samples into buffer
610  for (; smp; smp--)
611  *dst++ = val;
612 }
613 
614 
615 /** Read the block data for a non-constant block
616  */
618 {
619  ALSSpecificConfig *sconf = &ctx->sconf;
620  AVCodecContext *avctx = ctx->avctx;
621  GetBitContext *gb = &ctx->gb;
622  unsigned int k;
623  unsigned int s[8];
624  unsigned int sx[8];
625  unsigned int sub_blocks, log2_sub_blocks, sb_length;
626  unsigned int start = 0;
627  unsigned int opt_order;
628  int sb;
629  int32_t *quant_cof = bd->quant_cof;
630  int32_t *current_res;
631 
632 
633  // ensure variable block decoding by reusing this field
634  *bd->const_block = 0;
635 
636  *bd->opt_order = 1;
637  bd->js_blocks = get_bits1(gb);
638 
639  opt_order = *bd->opt_order;
640 
641  // determine the number of subblocks for entropy decoding
642  if (!sconf->bgmc && !sconf->sb_part) {
643  log2_sub_blocks = 0;
644  } else {
645  if (sconf->bgmc && sconf->sb_part)
646  log2_sub_blocks = get_bits(gb, 2);
647  else
648  log2_sub_blocks = 2 * get_bits1(gb);
649  }
650 
651  sub_blocks = 1 << log2_sub_blocks;
652 
653  // do not continue in case of a damaged stream since
654  // block_length must be evenly divisible by sub_blocks
655  if (bd->block_length & (sub_blocks - 1) || bd->block_length <= 0) {
656  av_log(avctx, AV_LOG_WARNING,
657  "Block length is not evenly divisible by the number of subblocks.\n");
658  return AVERROR_INVALIDDATA;
659  }
660 
661  sb_length = bd->block_length >> log2_sub_blocks;
662 
663  if (sconf->bgmc) {
664  s[0] = get_bits(gb, 8 + (sconf->resolution > 1));
665  for (k = 1; k < sub_blocks; k++)
666  s[k] = s[k - 1] + decode_rice(gb, 2);
667 
668  for (k = 0; k < sub_blocks; k++) {
669  sx[k] = s[k] & 0x0F;
670  s [k] >>= 4;
671  }
672  } else {
673  s[0] = get_bits(gb, 4 + (sconf->resolution > 1));
674  for (k = 1; k < sub_blocks; k++)
675  s[k] = s[k - 1] + decode_rice(gb, 0);
676  }
677  for (k = 1; k < sub_blocks; k++)
678  if (s[k] > 32) {
679  av_log(avctx, AV_LOG_ERROR, "k invalid for rice code.\n");
680  return AVERROR_INVALIDDATA;
681  }
682 
683  if (get_bits1(gb))
684  *bd->shift_lsbs = get_bits(gb, 4) + 1;
685 
686  *bd->store_prev_samples = (bd->js_blocks && bd->raw_other) || *bd->shift_lsbs;
687 
688 
689  if (!sconf->rlslms) {
690  if (sconf->adapt_order && sconf->max_order) {
691  int opt_order_length = av_ceil_log2(av_clip((bd->block_length >> 3) - 1,
692  2, sconf->max_order + 1));
693  *bd->opt_order = get_bits(gb, opt_order_length);
694  if (*bd->opt_order > sconf->max_order) {
695  *bd->opt_order = sconf->max_order;
696  av_log(avctx, AV_LOG_ERROR, "Predictor order too large.\n");
697  return AVERROR_INVALIDDATA;
698  }
699  } else {
700  *bd->opt_order = sconf->max_order;
701  }
702  if (*bd->opt_order > bd->block_length) {
703  *bd->opt_order = bd->block_length;
704  av_log(avctx, AV_LOG_ERROR, "Predictor order too large.\n");
705  return AVERROR_INVALIDDATA;
706  }
707  opt_order = *bd->opt_order;
708 
709  if (opt_order) {
710  int add_base;
711 
712  if (sconf->coef_table == 3) {
713  add_base = 0x7F;
714 
715  // read coefficient 0
716  quant_cof[0] = 32 * parcor_scaled_values[get_bits(gb, 7)];
717 
718  // read coefficient 1
719  if (opt_order > 1)
720  quant_cof[1] = -32 * parcor_scaled_values[get_bits(gb, 7)];
721 
722  // read coefficients 2 to opt_order
723  for (k = 2; k < opt_order; k++)
724  quant_cof[k] = get_bits(gb, 7);
725  } else {
726  int k_max;
727  add_base = 1;
728 
729  // read coefficient 0 to 19
730  k_max = FFMIN(opt_order, 20);
731  for (k = 0; k < k_max; k++) {
732  int rice_param = parcor_rice_table[sconf->coef_table][k][1];
733  int offset = parcor_rice_table[sconf->coef_table][k][0];
734  quant_cof[k] = decode_rice(gb, rice_param) + offset;
735  if (quant_cof[k] < -64 || quant_cof[k] > 63) {
736  av_log(avctx, AV_LOG_ERROR,
737  "quant_cof %"PRIu32" is out of range.\n",
738  quant_cof[k]);
739  return AVERROR_INVALIDDATA;
740  }
741  }
742 
743  // read coefficients 20 to 126
744  k_max = FFMIN(opt_order, 127);
745  for (; k < k_max; k++)
746  quant_cof[k] = decode_rice(gb, 2) + (k & 1);
747 
748  // read coefficients 127 to opt_order
749  for (; k < opt_order; k++)
750  quant_cof[k] = decode_rice(gb, 1);
751 
752  quant_cof[0] = 32 * parcor_scaled_values[quant_cof[0] + 64];
753 
754  if (opt_order > 1)
755  quant_cof[1] = -32 * parcor_scaled_values[quant_cof[1] + 64];
756  }
757 
758  for (k = 2; k < opt_order; k++)
759  quant_cof[k] = (quant_cof[k] << 14) + (add_base << 13);
760  }
761  }
762 
763  // read LTP gain and lag values
764  if (sconf->long_term_prediction) {
765  *bd->use_ltp = get_bits1(gb);
766 
767  if (*bd->use_ltp) {
768  int r, c;
769 
770  bd->ltp_gain[0] = decode_rice(gb, 1) * 8;
771  bd->ltp_gain[1] = decode_rice(gb, 2) * 8;
772 
773  r = get_unary(gb, 0, 4);
774  c = get_bits(gb, 2);
775  if (r >= 4) {
776  av_log(avctx, AV_LOG_ERROR, "r overflow\n");
777  return AVERROR_INVALIDDATA;
778  }
779 
780  bd->ltp_gain[2] = ltp_gain_values[r][c];
781 
782  bd->ltp_gain[3] = decode_rice(gb, 2) * 8;
783  bd->ltp_gain[4] = decode_rice(gb, 1) * 8;
784 
785  *bd->ltp_lag = get_bits(gb, ctx->ltp_lag_length);
786  *bd->ltp_lag += FFMAX(4, opt_order + 1);
787  }
788  }
789 
790  // read first value and residuals in case of a random access block
791  if (bd->ra_block) {
792  start = FFMIN(opt_order, 3);
793  av_assert0(sb_length <= sconf->frame_length);
794  if (sb_length <= start) {
795  // opt_order or sb_length may be corrupted, either way this is unsupported and not well defined in the specification
796  av_log(avctx, AV_LOG_ERROR, "Sub block length smaller or equal start\n");
797  return AVERROR_PATCHWELCOME;
798  }
799 
800  if (opt_order)
801  bd->raw_samples[0] = decode_rice(gb, avctx->bits_per_raw_sample - 4);
802  if (opt_order > 1)
803  bd->raw_samples[1] = decode_rice(gb, FFMIN(s[0] + 3, ctx->s_max));
804  if (opt_order > 2)
805  bd->raw_samples[2] = decode_rice(gb, FFMIN(s[0] + 1, ctx->s_max));
806  }
807 
808  // read all residuals
809  if (sconf->bgmc) {
810  int delta[8];
811  unsigned int k [8];
812  unsigned int b = av_clip((av_ceil_log2(bd->block_length) - 3) >> 1, 0, 5);
813 
814  // read most significant bits
815  unsigned int high;
816  unsigned int low;
817  unsigned int value;
818 
819  int ret = ff_bgmc_decode_init(gb, &high, &low, &value);
820  if (ret < 0)
821  return ret;
822 
823  current_res = bd->raw_samples + start;
824 
825  for (sb = 0; sb < sub_blocks; sb++) {
826  unsigned int sb_len = sb_length - (sb ? 0 : start);
827 
828  k [sb] = s[sb] > b ? s[sb] - b : 0;
829  delta[sb] = 5 - s[sb] + k[sb];
830 
831  if (k[sb] >= 32)
832  return AVERROR_INVALIDDATA;
833 
834  ff_bgmc_decode(gb, sb_len, current_res,
835  delta[sb], sx[sb], &high, &low, &value, ctx->bgmc_lut, ctx->bgmc_lut_status);
836 
837  current_res += sb_len;
838  }
839 
840  ff_bgmc_decode_end(gb);
841 
842 
843  // read least significant bits and tails
844  current_res = bd->raw_samples + start;
845 
846  for (sb = 0; sb < sub_blocks; sb++, start = 0) {
847  unsigned int cur_tail_code = tail_code[sx[sb]][delta[sb]];
848  unsigned int cur_k = k[sb];
849  unsigned int cur_s = s[sb];
850 
851  for (; start < sb_length; start++) {
852  int32_t res = *current_res;
853 
854  if (res == cur_tail_code) {
855  unsigned int max_msb = (2 + (sx[sb] > 2) + (sx[sb] > 10))
856  << (5 - delta[sb]);
857 
858  res = decode_rice(gb, cur_s);
859 
860  if (res >= 0) {
861  res += (max_msb ) << cur_k;
862  } else {
863  res -= (max_msb - 1) << cur_k;
864  }
865  } else {
866  if (res > cur_tail_code)
867  res--;
868 
869  if (res & 1)
870  res = -res;
871 
872  res >>= 1;
873 
874  if (cur_k) {
875  res <<= cur_k;
876  res |= get_bits_long(gb, cur_k);
877  }
878  }
879 
880  *current_res++ = res;
881  }
882  }
883  } else {
884  current_res = bd->raw_samples + start;
885 
886  for (sb = 0; sb < sub_blocks; sb++, start = 0)
887  for (; start < sb_length; start++)
888  *current_res++ = decode_rice(gb, s[sb]);
889  }
890 
891  if (!sconf->mc_coding || ctx->js_switch)
892  align_get_bits(gb);
893 
894  return 0;
895 }
896 
897 
898 /** Decode the block data for a non-constant block
899  */
901 {
902  ALSSpecificConfig *sconf = &ctx->sconf;
903  unsigned int block_length = bd->block_length;
904  unsigned int smp = 0;
905  unsigned int k;
906  int opt_order = *bd->opt_order;
907  int sb;
908  int64_t y;
909  int32_t *quant_cof = bd->quant_cof;
910  int32_t *lpc_cof = bd->lpc_cof;
911  int32_t *raw_samples = bd->raw_samples;
912  int32_t *raw_samples_end = bd->raw_samples + bd->block_length;
913  int32_t *lpc_cof_reversed = ctx->lpc_cof_reversed_buffer;
914 
915  // reverse long-term prediction
916  if (*bd->use_ltp) {
917  int ltp_smp;
918 
919  for (ltp_smp = FFMAX(*bd->ltp_lag - 2, 0); ltp_smp < block_length; ltp_smp++) {
920  int center = ltp_smp - *bd->ltp_lag;
921  int begin = FFMAX(0, center - 2);
922  int end = center + 3;
923  int tab = 5 - (end - begin);
924  int base;
925 
926  y = 1 << 6;
927 
928  for (base = begin; base < end; base++, tab++)
929  y += (uint64_t)MUL64(bd->ltp_gain[tab], raw_samples[base]);
930 
931  raw_samples[ltp_smp] += y >> 7;
932  }
933  }
934 
935  // reconstruct all samples from residuals
936  if (bd->ra_block) {
937  for (smp = 0; smp < opt_order; smp++) {
938  y = 1 << 19;
939 
940  for (sb = 0; sb < smp; sb++)
941  y += (uint64_t)MUL64(lpc_cof[sb], raw_samples[-(sb + 1)]);
942 
943  *raw_samples++ -= y >> 20;
944  parcor_to_lpc(smp, quant_cof, lpc_cof);
945  }
946  } else {
947  for (k = 0; k < opt_order; k++)
948  parcor_to_lpc(k, quant_cof, lpc_cof);
949 
950  // store previous samples in case that they have to be altered
951  if (*bd->store_prev_samples)
952  memcpy(bd->prev_raw_samples, raw_samples - sconf->max_order,
953  sizeof(*bd->prev_raw_samples) * sconf->max_order);
954 
955  // reconstruct difference signal for prediction (joint-stereo)
956  if (bd->js_blocks && bd->raw_other) {
957  uint32_t *left, *right;
958 
959  if (bd->raw_other > raw_samples) { // D = R - L
960  left = raw_samples;
961  right = bd->raw_other;
962  } else { // D = R - L
963  left = bd->raw_other;
964  right = raw_samples;
965  }
966 
967  for (sb = -1; sb >= -sconf->max_order; sb--)
968  raw_samples[sb] = right[sb] - left[sb];
969  }
970 
971  // reconstruct shifted signal
972  if (*bd->shift_lsbs)
973  for (sb = -1; sb >= -sconf->max_order; sb--)
974  raw_samples[sb] >>= *bd->shift_lsbs;
975  }
976 
977  // reverse linear prediction coefficients for efficiency
978  lpc_cof = lpc_cof + opt_order;
979 
980  for (sb = 0; sb < opt_order; sb++)
981  lpc_cof_reversed[sb] = lpc_cof[-(sb + 1)];
982 
983  // reconstruct raw samples
984  raw_samples = bd->raw_samples + smp;
985  lpc_cof = lpc_cof_reversed + opt_order;
986 
987  for (; raw_samples < raw_samples_end; raw_samples++) {
988  y = 1 << 19;
989 
990  for (sb = -opt_order; sb < 0; sb++)
991  y += (uint64_t)MUL64(lpc_cof[sb], raw_samples[sb]);
992 
993  *raw_samples -= y >> 20;
994  }
995 
996  raw_samples = bd->raw_samples;
997 
998  // restore previous samples in case that they have been altered
999  if (*bd->store_prev_samples)
1000  memcpy(raw_samples - sconf->max_order, bd->prev_raw_samples,
1001  sizeof(*raw_samples) * sconf->max_order);
1002 
1003  return 0;
1004 }
1005 
1006 
1007 /** Read the block data.
1008  */
1010 {
1011  int ret;
1012  GetBitContext *gb = &ctx->gb;
1013 
1014  *bd->shift_lsbs = 0;
1015  // read block type flag and read the samples accordingly
1016  if (get_bits1(gb)) {
1017  ret = read_var_block_data(ctx, bd);
1018  } else {
1019  ret = read_const_block_data(ctx, bd);
1020  }
1021 
1022  return ret;
1023 }
1024 
1025 
1026 /** Decode the block data.
1027  */
1029 {
1030  unsigned int smp;
1031  int ret = 0;
1032 
1033  // read block type flag and read the samples accordingly
1034  if (*bd->const_block)
1035  decode_const_block_data(ctx, bd);
1036  else
1037  ret = decode_var_block_data(ctx, bd); // always return 0
1038 
1039  if (ret < 0)
1040  return ret;
1041 
1042  // TODO: read RLSLMS extension data
1043 
1044  if (*bd->shift_lsbs)
1045  for (smp = 0; smp < bd->block_length; smp++)
1046  bd->raw_samples[smp] = (unsigned)bd->raw_samples[smp] << *bd->shift_lsbs;
1047 
1048  return 0;
1049 }
1050 
1051 
1052 /** Read and decode block data successively.
1053  */
1055 {
1056  int ret;
1057 
1058  if ((ret = read_block(ctx, bd)) < 0)
1059  return ret;
1060 
1061  return decode_block(ctx, bd);
1062 }
1063 
1064 
1065 /** Compute the number of samples left to decode for the current frame and
1066  * sets these samples to zero.
1067  */
1068 static void zero_remaining(unsigned int b, unsigned int b_max,
1069  const unsigned int *div_blocks, int32_t *buf)
1070 {
1071  unsigned int count = 0;
1072 
1073  while (b < b_max)
1074  count += div_blocks[b++];
1075 
1076  if (count)
1077  memset(buf, 0, sizeof(*buf) * count);
1078 }
1079 
1080 
1081 /** Decode blocks independently.
1082  */
1083 static int decode_blocks_ind(ALSDecContext *ctx, unsigned int ra_frame,
1084  unsigned int c, const unsigned int *div_blocks,
1085  unsigned int *js_blocks)
1086 {
1087  int ret;
1088  unsigned int b;
1089  ALSBlockData bd = { 0 };
1090 
1091  bd.ra_block = ra_frame;
1092  bd.const_block = ctx->const_block;
1093  bd.shift_lsbs = ctx->shift_lsbs;
1094  bd.opt_order = ctx->opt_order;
1096  bd.use_ltp = ctx->use_ltp;
1097  bd.ltp_lag = ctx->ltp_lag;
1098  bd.ltp_gain = ctx->ltp_gain[0];
1099  bd.quant_cof = ctx->quant_cof[0];
1100  bd.lpc_cof = ctx->lpc_cof[0];
1102  bd.raw_samples = ctx->raw_samples[c];
1103 
1104 
1105  for (b = 0; b < ctx->num_blocks; b++) {
1106  bd.block_length = div_blocks[b];
1107 
1108  if ((ret = read_decode_block(ctx, &bd)) < 0) {
1109  // damaged block, write zero for the rest of the frame
1110  zero_remaining(b, ctx->num_blocks, div_blocks, bd.raw_samples);
1111  return ret;
1112  }
1113  bd.raw_samples += div_blocks[b];
1114  bd.ra_block = 0;
1115  }
1116 
1117  return 0;
1118 }
1119 
1120 
1121 /** Decode blocks dependently.
1122  */
1123 static int decode_blocks(ALSDecContext *ctx, unsigned int ra_frame,
1124  unsigned int c, const unsigned int *div_blocks,
1125  unsigned int *js_blocks)
1126 {
1127  ALSSpecificConfig *sconf = &ctx->sconf;
1128  unsigned int offset = 0;
1129  unsigned int b;
1130  int ret;
1131  ALSBlockData bd[2] = { { 0 } };
1132 
1133  bd[0].ra_block = ra_frame;
1134  bd[0].const_block = ctx->const_block;
1135  bd[0].shift_lsbs = ctx->shift_lsbs;
1136  bd[0].opt_order = ctx->opt_order;
1138  bd[0].use_ltp = ctx->use_ltp;
1139  bd[0].ltp_lag = ctx->ltp_lag;
1140  bd[0].ltp_gain = ctx->ltp_gain[0];
1141  bd[0].quant_cof = ctx->quant_cof[0];
1142  bd[0].lpc_cof = ctx->lpc_cof[0];
1143  bd[0].prev_raw_samples = ctx->prev_raw_samples;
1144  bd[0].js_blocks = *js_blocks;
1145 
1146  bd[1].ra_block = ra_frame;
1147  bd[1].const_block = ctx->const_block;
1148  bd[1].shift_lsbs = ctx->shift_lsbs;
1149  bd[1].opt_order = ctx->opt_order;
1151  bd[1].use_ltp = ctx->use_ltp;
1152  bd[1].ltp_lag = ctx->ltp_lag;
1153  bd[1].ltp_gain = ctx->ltp_gain[0];
1154  bd[1].quant_cof = ctx->quant_cof[0];
1155  bd[1].lpc_cof = ctx->lpc_cof[0];
1156  bd[1].prev_raw_samples = ctx->prev_raw_samples;
1157  bd[1].js_blocks = *(js_blocks + 1);
1158 
1159  // decode all blocks
1160  for (b = 0; b < ctx->num_blocks; b++) {
1161  unsigned int s;
1162 
1163  bd[0].block_length = div_blocks[b];
1164  bd[1].block_length = div_blocks[b];
1165 
1166  bd[0].raw_samples = ctx->raw_samples[c ] + offset;
1167  bd[1].raw_samples = ctx->raw_samples[c + 1] + offset;
1168 
1169  bd[0].raw_other = bd[1].raw_samples;
1170  bd[1].raw_other = bd[0].raw_samples;
1171 
1172  if ((ret = read_decode_block(ctx, &bd[0])) < 0 ||
1173  (ret = read_decode_block(ctx, &bd[1])) < 0)
1174  goto fail;
1175 
1176  // reconstruct joint-stereo blocks
1177  if (bd[0].js_blocks) {
1178  if (bd[1].js_blocks)
1179  av_log(ctx->avctx, AV_LOG_WARNING, "Invalid channel pair.\n");
1180 
1181  for (s = 0; s < div_blocks[b]; s++)
1182  bd[0].raw_samples[s] = bd[1].raw_samples[s] - (unsigned)bd[0].raw_samples[s];
1183  } else if (bd[1].js_blocks) {
1184  for (s = 0; s < div_blocks[b]; s++)
1185  bd[1].raw_samples[s] = bd[1].raw_samples[s] + (unsigned)bd[0].raw_samples[s];
1186  }
1187 
1188  offset += div_blocks[b];
1189  bd[0].ra_block = 0;
1190  bd[1].ra_block = 0;
1191  }
1192 
1193  // store carryover raw samples,
1194  // the others channel raw samples are stored by the calling function.
1195  memmove(ctx->raw_samples[c] - sconf->max_order,
1196  ctx->raw_samples[c] - sconf->max_order + sconf->frame_length,
1197  sizeof(*ctx->raw_samples[c]) * sconf->max_order);
1198 
1199  return 0;
1200 fail:
1201  // damaged block, write zero for the rest of the frame
1202  zero_remaining(b, ctx->num_blocks, div_blocks, bd[0].raw_samples);
1203  zero_remaining(b, ctx->num_blocks, div_blocks, bd[1].raw_samples);
1204  return ret;
1205 }
1206 
1207 static inline int als_weighting(GetBitContext *gb, int k, int off)
1208 {
1209  int idx = av_clip(decode_rice(gb, k) + off,
1210  0, FF_ARRAY_ELEMS(mcc_weightings) - 1);
1211  return mcc_weightings[idx];
1212 }
1213 
1214 /** Read the channel data.
1215  */
1217 {
1218  GetBitContext *gb = &ctx->gb;
1219  ALSChannelData *current = cd;
1220  unsigned int channels = ctx->avctx->channels;
1221  int entries = 0;
1222 
1223  while (entries < channels && !(current->stop_flag = get_bits1(gb))) {
1224  current->master_channel = get_bits_long(gb, av_ceil_log2(channels));
1225 
1226  if (current->master_channel >= channels) {
1227  av_log(ctx->avctx, AV_LOG_ERROR, "Invalid master channel.\n");
1228  return AVERROR_INVALIDDATA;
1229  }
1230 
1231  if (current->master_channel != c) {
1232  current->time_diff_flag = get_bits1(gb);
1233  current->weighting[0] = als_weighting(gb, 1, 16);
1234  current->weighting[1] = als_weighting(gb, 2, 14);
1235  current->weighting[2] = als_weighting(gb, 1, 16);
1236 
1237  if (current->time_diff_flag) {
1238  current->weighting[3] = als_weighting(gb, 1, 16);
1239  current->weighting[4] = als_weighting(gb, 1, 16);
1240  current->weighting[5] = als_weighting(gb, 1, 16);
1241 
1242  current->time_diff_sign = get_bits1(gb);
1243  current->time_diff_index = get_bits(gb, ctx->ltp_lag_length - 3) + 3;
1244  }
1245  }
1246 
1247  current++;
1248  entries++;
1249  }
1250 
1251  if (entries == channels) {
1252  av_log(ctx->avctx, AV_LOG_ERROR, "Damaged channel data.\n");
1253  return AVERROR_INVALIDDATA;
1254  }
1255 
1256  align_get_bits(gb);
1257  return 0;
1258 }
1259 
1260 
1261 /** Recursively reverts the inter-channel correlation for a block.
1262  */
1264  ALSChannelData **cd, int *reverted,
1265  unsigned int offset, int c)
1266 {
1267  ALSChannelData *ch = cd[c];
1268  unsigned int dep = 0;
1269  unsigned int channels = ctx->avctx->channels;
1270  unsigned int channel_size = ctx->sconf.frame_length + ctx->sconf.max_order;
1271 
1272  if (reverted[c])
1273  return 0;
1274 
1275  reverted[c] = 1;
1276 
1277  while (dep < channels && !ch[dep].stop_flag) {
1278  revert_channel_correlation(ctx, bd, cd, reverted, offset,
1279  ch[dep].master_channel);
1280 
1281  dep++;
1282  }
1283 
1284  if (dep == channels) {
1285  av_log(ctx->avctx, AV_LOG_WARNING, "Invalid channel correlation.\n");
1286  return AVERROR_INVALIDDATA;
1287  }
1288 
1289  bd->const_block = ctx->const_block + c;
1290  bd->shift_lsbs = ctx->shift_lsbs + c;
1291  bd->opt_order = ctx->opt_order + c;
1293  bd->use_ltp = ctx->use_ltp + c;
1294  bd->ltp_lag = ctx->ltp_lag + c;
1295  bd->ltp_gain = ctx->ltp_gain[c];
1296  bd->lpc_cof = ctx->lpc_cof[c];
1297  bd->quant_cof = ctx->quant_cof[c];
1298  bd->raw_samples = ctx->raw_samples[c] + offset;
1299 
1300  for (dep = 0; !ch[dep].stop_flag; dep++) {
1301  ptrdiff_t smp;
1302  ptrdiff_t begin = 1;
1303  ptrdiff_t end = bd->block_length - 1;
1304  int64_t y;
1305  int32_t *master = ctx->raw_samples[ch[dep].master_channel] + offset;
1306 
1307  if (ch[dep].master_channel == c)
1308  continue;
1309 
1310  if (ch[dep].time_diff_flag) {
1311  int t = ch[dep].time_diff_index;
1312 
1313  if (ch[dep].time_diff_sign) {
1314  t = -t;
1315  if (begin < t) {
1316  av_log(ctx->avctx, AV_LOG_ERROR, "begin %td smaller than time diff index %d.\n", begin, t);
1317  return AVERROR_INVALIDDATA;
1318  }
1319  begin -= t;
1320  } else {
1321  if (end < t) {
1322  av_log(ctx->avctx, AV_LOG_ERROR, "end %td smaller than time diff index %d.\n", end, t);
1323  return AVERROR_INVALIDDATA;
1324  }
1325  end -= t;
1326  }
1327 
1328  if (FFMIN(begin - 1, begin - 1 + t) < ctx->raw_buffer - master ||
1329  FFMAX(end + 1, end + 1 + t) > ctx->raw_buffer + channels * channel_size - master) {
1330  av_log(ctx->avctx, AV_LOG_ERROR,
1331  "sample pointer range [%p, %p] not contained in raw_buffer [%p, %p].\n",
1332  master + FFMIN(begin - 1, begin - 1 + t), master + FFMAX(end + 1, end + 1 + t),
1333  ctx->raw_buffer, ctx->raw_buffer + channels * channel_size);
1334  return AVERROR_INVALIDDATA;
1335  }
1336 
1337  for (smp = begin; smp < end; smp++) {
1338  y = (1 << 6) +
1339  MUL64(ch[dep].weighting[0], master[smp - 1 ]) +
1340  MUL64(ch[dep].weighting[1], master[smp ]) +
1341  MUL64(ch[dep].weighting[2], master[smp + 1 ]) +
1342  MUL64(ch[dep].weighting[3], master[smp - 1 + t]) +
1343  MUL64(ch[dep].weighting[4], master[smp + t]) +
1344  MUL64(ch[dep].weighting[5], master[smp + 1 + t]);
1345 
1346  bd->raw_samples[smp] += y >> 7;
1347  }
1348  } else {
1349 
1350  if (begin - 1 < ctx->raw_buffer - master ||
1351  end + 1 > ctx->raw_buffer + channels * channel_size - master) {
1352  av_log(ctx->avctx, AV_LOG_ERROR,
1353  "sample pointer range [%p, %p] not contained in raw_buffer [%p, %p].\n",
1354  master + begin - 1, master + end + 1,
1355  ctx->raw_buffer, ctx->raw_buffer + channels * channel_size);
1356  return AVERROR_INVALIDDATA;
1357  }
1358 
1359  for (smp = begin; smp < end; smp++) {
1360  y = (1 << 6) +
1361  MUL64(ch[dep].weighting[0], master[smp - 1]) +
1362  MUL64(ch[dep].weighting[1], master[smp ]) +
1363  MUL64(ch[dep].weighting[2], master[smp + 1]);
1364 
1365  bd->raw_samples[smp] += y >> 7;
1366  }
1367  }
1368  }
1369 
1370  return 0;
1371 }
1372 
1373 
1374 /** Read the frame data.
1375  */
1376 static int read_frame_data(ALSDecContext *ctx, unsigned int ra_frame)
1377 {
1378  ALSSpecificConfig *sconf = &ctx->sconf;
1379  AVCodecContext *avctx = ctx->avctx;
1380  GetBitContext *gb = &ctx->gb;
1381  unsigned int div_blocks[32]; ///< block sizes.
1382  unsigned int c;
1383  unsigned int js_blocks[2];
1384  uint32_t bs_info = 0;
1385  int ret;
1386 
1387  // skip the size of the ra unit if present in the frame
1388  if (sconf->ra_flag == RA_FLAG_FRAMES && ra_frame)
1389  skip_bits_long(gb, 32);
1390 
1391  if (sconf->mc_coding && sconf->joint_stereo) {
1392  ctx->js_switch = get_bits1(gb);
1393  align_get_bits(gb);
1394  }
1395 
1396  if (!sconf->mc_coding || ctx->js_switch) {
1397  int independent_bs = !sconf->joint_stereo;
1398 
1399  for (c = 0; c < avctx->channels; c++) {
1400  js_blocks[0] = 0;
1401  js_blocks[1] = 0;
1402 
1403  get_block_sizes(ctx, div_blocks, &bs_info);
1404 
1405  // if joint_stereo and block_switching is set, independent decoding
1406  // is signaled via the first bit of bs_info
1407  if (sconf->joint_stereo && sconf->block_switching)
1408  if (bs_info >> 31)
1409  independent_bs = 2;
1410 
1411  // if this is the last channel, it has to be decoded independently
1412  if (c == avctx->channels - 1)
1413  independent_bs = 1;
1414 
1415  if (independent_bs) {
1416  ret = decode_blocks_ind(ctx, ra_frame, c,
1417  div_blocks, js_blocks);
1418  if (ret < 0)
1419  return ret;
1420  independent_bs--;
1421  } else {
1422  ret = decode_blocks(ctx, ra_frame, c, div_blocks, js_blocks);
1423  if (ret < 0)
1424  return ret;
1425 
1426  c++;
1427  }
1428 
1429  // store carryover raw samples
1430  memmove(ctx->raw_samples[c] - sconf->max_order,
1431  ctx->raw_samples[c] - sconf->max_order + sconf->frame_length,
1432  sizeof(*ctx->raw_samples[c]) * sconf->max_order);
1433  }
1434  } else { // multi-channel coding
1435  ALSBlockData bd = { 0 };
1436  int b, ret;
1437  int *reverted_channels = ctx->reverted_channels;
1438  unsigned int offset = 0;
1439 
1440  for (c = 0; c < avctx->channels; c++)
1441  if (ctx->chan_data[c] < ctx->chan_data_buffer) {
1442  av_log(ctx->avctx, AV_LOG_ERROR, "Invalid channel data.\n");
1443  return AVERROR_INVALIDDATA;
1444  }
1445 
1446  memset(reverted_channels, 0, sizeof(*reverted_channels) * avctx->channels);
1447 
1448  bd.ra_block = ra_frame;
1450 
1451  get_block_sizes(ctx, div_blocks, &bs_info);
1452 
1453  for (b = 0; b < ctx->num_blocks; b++) {
1454  bd.block_length = div_blocks[b];
1455  if (bd.block_length <= 0) {
1456  av_log(ctx->avctx, AV_LOG_WARNING,
1457  "Invalid block length %u in channel data!\n",
1458  bd.block_length);
1459  continue;
1460  }
1461 
1462  for (c = 0; c < avctx->channels; c++) {
1463  bd.const_block = ctx->const_block + c;
1464  bd.shift_lsbs = ctx->shift_lsbs + c;
1465  bd.opt_order = ctx->opt_order + c;
1467  bd.use_ltp = ctx->use_ltp + c;
1468  bd.ltp_lag = ctx->ltp_lag + c;
1469  bd.ltp_gain = ctx->ltp_gain[c];
1470  bd.lpc_cof = ctx->lpc_cof[c];
1471  bd.quant_cof = ctx->quant_cof[c];
1472  bd.raw_samples = ctx->raw_samples[c] + offset;
1473  bd.raw_other = NULL;
1474 
1475  if ((ret = read_block(ctx, &bd)) < 0)
1476  return ret;
1477  if ((ret = read_channel_data(ctx, ctx->chan_data[c], c)) < 0)
1478  return ret;
1479  }
1480 
1481  for (c = 0; c < avctx->channels; c++) {
1482  ret = revert_channel_correlation(ctx, &bd, ctx->chan_data,
1483  reverted_channels, offset, c);
1484  if (ret < 0)
1485  return ret;
1486  }
1487  for (c = 0; c < avctx->channels; c++) {
1488  bd.const_block = ctx->const_block + c;
1489  bd.shift_lsbs = ctx->shift_lsbs + c;
1490  bd.opt_order = ctx->opt_order + c;
1492  bd.use_ltp = ctx->use_ltp + c;
1493  bd.ltp_lag = ctx->ltp_lag + c;
1494  bd.ltp_gain = ctx->ltp_gain[c];
1495  bd.lpc_cof = ctx->lpc_cof[c];
1496  bd.quant_cof = ctx->quant_cof[c];
1497  bd.raw_samples = ctx->raw_samples[c] + offset;
1498 
1499  if ((ret = decode_block(ctx, &bd)) < 0)
1500  return ret;
1501  }
1502 
1503  memset(reverted_channels, 0, avctx->channels * sizeof(*reverted_channels));
1504  offset += div_blocks[b];
1505  bd.ra_block = 0;
1506  }
1507 
1508  // store carryover raw samples
1509  for (c = 0; c < avctx->channels; c++)
1510  memmove(ctx->raw_samples[c] - sconf->max_order,
1511  ctx->raw_samples[c] - sconf->max_order + sconf->frame_length,
1512  sizeof(*ctx->raw_samples[c]) * sconf->max_order);
1513  }
1514 
1515  // TODO: read_diff_float_data
1516 
1517  if (get_bits_left(gb) < 0) {
1518  av_log(ctx->avctx, AV_LOG_ERROR, "Overread %d\n", -get_bits_left(gb));
1519  return AVERROR_INVALIDDATA;
1520  }
1521 
1522  return 0;
1523 }
1524 
1525 
1526 /** Decode an ALS frame.
1527  */
1528 static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame_ptr,
1529  AVPacket *avpkt)
1530 {
1531  ALSDecContext *ctx = avctx->priv_data;
1532  AVFrame *frame = data;
1533  ALSSpecificConfig *sconf = &ctx->sconf;
1534  const uint8_t *buffer = avpkt->data;
1535  int buffer_size = avpkt->size;
1536  int invalid_frame, ret;
1537  unsigned int c, sample, ra_frame, bytes_read, shift;
1538 
1539  if ((ret = init_get_bits8(&ctx->gb, buffer, buffer_size)) < 0)
1540  return ret;
1541 
1542  // In the case that the distance between random access frames is set to zero
1543  // (sconf->ra_distance == 0) no frame is treated as a random access frame.
1544  // For the first frame, if prediction is used, all samples used from the
1545  // previous frame are assumed to be zero.
1546  ra_frame = sconf->ra_distance && !(ctx->frame_id % sconf->ra_distance);
1547 
1548  // the last frame to decode might have a different length
1549  if (sconf->samples != 0xFFFFFFFF)
1550  ctx->cur_frame_length = FFMIN(sconf->samples - ctx->frame_id * (uint64_t) sconf->frame_length,
1551  sconf->frame_length);
1552  else
1553  ctx->cur_frame_length = sconf->frame_length;
1554 
1555  // decode the frame data
1556  if ((invalid_frame = read_frame_data(ctx, ra_frame)) < 0)
1557  av_log(ctx->avctx, AV_LOG_WARNING,
1558  "Reading frame data failed. Skipping RA unit.\n");
1559 
1560  ctx->frame_id++;
1561 
1562  /* get output buffer */
1563  frame->nb_samples = ctx->cur_frame_length;
1564  if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
1565  return ret;
1566 
1567  // transform decoded frame into output format
1568  #define INTERLEAVE_OUTPUT(bps) \
1569  { \
1570  int##bps##_t *dest = (int##bps##_t*)frame->data[0]; \
1571  int channels = avctx->channels; \
1572  int32_t **raw_samples = ctx->raw_samples; \
1573  shift = bps - ctx->avctx->bits_per_raw_sample; \
1574  if (!ctx->cs_switch) { \
1575  for (sample = 0; sample < ctx->cur_frame_length; sample++) \
1576  for (c = 0; c < channels; c++) \
1577  *dest++ = raw_samples[c][sample] * (1U << shift); \
1578  } else { \
1579  for (sample = 0; sample < ctx->cur_frame_length; sample++) \
1580  for (c = 0; c < channels; c++) \
1581  *dest++ = raw_samples[sconf->chan_pos[c]][sample] * (1U << shift);\
1582  } \
1583  }
1584 
1585  if (ctx->avctx->bits_per_raw_sample <= 16) {
1586  INTERLEAVE_OUTPUT(16)
1587  } else {
1588  INTERLEAVE_OUTPUT(32)
1589  }
1590 
1591  // update CRC
1592  if (sconf->crc_enabled && (avctx->err_recognition & (AV_EF_CRCCHECK|AV_EF_CAREFUL))) {
1593  int swap = HAVE_BIGENDIAN != sconf->msb_first;
1594 
1595  if (ctx->avctx->bits_per_raw_sample == 24) {
1596  int32_t *src = (int32_t *)frame->data[0];
1597 
1598  for (sample = 0;
1599  sample < ctx->cur_frame_length * avctx->channels;
1600  sample++) {
1601  int32_t v;
1602 
1603  if (swap)
1604  v = av_bswap32(src[sample]);
1605  else
1606  v = src[sample];
1607  if (!HAVE_BIGENDIAN)
1608  v >>= 8;
1609 
1610  ctx->crc = av_crc(ctx->crc_table, ctx->crc, (uint8_t*)(&v), 3);
1611  }
1612  } else {
1613  uint8_t *crc_source;
1614 
1615  if (swap) {
1616  if (ctx->avctx->bits_per_raw_sample <= 16) {
1617  int16_t *src = (int16_t*) frame->data[0];
1618  int16_t *dest = (int16_t*) ctx->crc_buffer;
1619  for (sample = 0;
1620  sample < ctx->cur_frame_length * avctx->channels;
1621  sample++)
1622  *dest++ = av_bswap16(src[sample]);
1623  } else {
1624  ctx->bdsp.bswap_buf((uint32_t *) ctx->crc_buffer,
1625  (uint32_t *) frame->data[0],
1626  ctx->cur_frame_length * avctx->channels);
1627  }
1628  crc_source = ctx->crc_buffer;
1629  } else {
1630  crc_source = frame->data[0];
1631  }
1632 
1633  ctx->crc = av_crc(ctx->crc_table, ctx->crc, crc_source,
1634  ctx->cur_frame_length * avctx->channels *
1636  }
1637 
1638 
1639  // check CRC sums if this is the last frame
1640  if (ctx->cur_frame_length != sconf->frame_length &&
1641  ctx->crc_org != ctx->crc) {
1642  av_log(avctx, AV_LOG_ERROR, "CRC error.\n");
1643  if (avctx->err_recognition & AV_EF_EXPLODE)
1644  return AVERROR_INVALIDDATA;
1645  }
1646  }
1647 
1648  *got_frame_ptr = 1;
1649 
1650  bytes_read = invalid_frame ? buffer_size :
1651  (get_bits_count(&ctx->gb) + 7) >> 3;
1652 
1653  return bytes_read;
1654 }
1655 
1656 
1657 /** Uninitialize the ALS decoder.
1658  */
1660 {
1661  ALSDecContext *ctx = avctx->priv_data;
1662 
1663  av_freep(&ctx->sconf.chan_pos);
1664 
1665  ff_bgmc_end(&ctx->bgmc_lut, &ctx->bgmc_lut_status);
1666 
1667  av_freep(&ctx->const_block);
1668  av_freep(&ctx->shift_lsbs);
1669  av_freep(&ctx->opt_order);
1671  av_freep(&ctx->use_ltp);
1672  av_freep(&ctx->ltp_lag);
1673  av_freep(&ctx->ltp_gain);
1674  av_freep(&ctx->ltp_gain_buffer);
1675  av_freep(&ctx->quant_cof);
1676  av_freep(&ctx->lpc_cof);
1677  av_freep(&ctx->quant_cof_buffer);
1678  av_freep(&ctx->lpc_cof_buffer);
1680  av_freep(&ctx->prev_raw_samples);
1681  av_freep(&ctx->raw_samples);
1682  av_freep(&ctx->raw_buffer);
1683  av_freep(&ctx->chan_data);
1684  av_freep(&ctx->chan_data_buffer);
1685  av_freep(&ctx->reverted_channels);
1686  av_freep(&ctx->crc_buffer);
1687 
1688  return 0;
1689 }
1690 
1691 
1692 /** Initialize the ALS decoder.
1693  */
1695 {
1696  unsigned int c;
1697  unsigned int channel_size;
1698  int num_buffers, ret;
1699  ALSDecContext *ctx = avctx->priv_data;
1700  ALSSpecificConfig *sconf = &ctx->sconf;
1701  ctx->avctx = avctx;
1702 
1703  if (!avctx->extradata) {
1704  av_log(avctx, AV_LOG_ERROR, "Missing required ALS extradata.\n");
1705  return AVERROR_INVALIDDATA;
1706  }
1707 
1708  if ((ret = read_specific_config(ctx)) < 0) {
1709  av_log(avctx, AV_LOG_ERROR, "Reading ALSSpecificConfig failed.\n");
1710  goto fail;
1711  }
1712 
1713  if ((ret = check_specific_config(ctx)) < 0) {
1714  goto fail;
1715  }
1716 
1717  if (sconf->bgmc) {
1718  ret = ff_bgmc_init(avctx, &ctx->bgmc_lut, &ctx->bgmc_lut_status);
1719  if (ret < 0)
1720  goto fail;
1721  }
1722  if (sconf->floating) {
1723  avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
1724  avctx->bits_per_raw_sample = 32;
1725  } else {
1726  avctx->sample_fmt = sconf->resolution > 1
1728  avctx->bits_per_raw_sample = (sconf->resolution + 1) * 8;
1729  if (avctx->bits_per_raw_sample > 32) {
1730  av_log(avctx, AV_LOG_ERROR, "Bits per raw sample %d larger than 32.\n",
1731  avctx->bits_per_raw_sample);
1732  ret = AVERROR_INVALIDDATA;
1733  goto fail;
1734  }
1735  }
1736 
1737  // set maximum Rice parameter for progressive decoding based on resolution
1738  // This is not specified in 14496-3 but actually done by the reference
1739  // codec RM22 revision 2.
1740  ctx->s_max = sconf->resolution > 1 ? 31 : 15;
1741 
1742  // set lag value for long-term prediction
1743  ctx->ltp_lag_length = 8 + (avctx->sample_rate >= 96000) +
1744  (avctx->sample_rate >= 192000);
1745 
1746  // allocate quantized parcor coefficient buffer
1747  num_buffers = sconf->mc_coding ? avctx->channels : 1;
1748  if (num_buffers * (uint64_t)num_buffers > INT_MAX) // protect chan_data_buffer allocation
1749  return AVERROR_INVALIDDATA;
1750 
1751  ctx->quant_cof = av_malloc_array(num_buffers, sizeof(*ctx->quant_cof));
1752  ctx->lpc_cof = av_malloc_array(num_buffers, sizeof(*ctx->lpc_cof));
1753  ctx->quant_cof_buffer = av_malloc_array(num_buffers * sconf->max_order,
1754  sizeof(*ctx->quant_cof_buffer));
1755  ctx->lpc_cof_buffer = av_malloc_array(num_buffers * sconf->max_order,
1756  sizeof(*ctx->lpc_cof_buffer));
1758  sizeof(*ctx->lpc_cof_buffer));
1759 
1760  if (!ctx->quant_cof || !ctx->lpc_cof ||
1761  !ctx->quant_cof_buffer || !ctx->lpc_cof_buffer ||
1762  !ctx->lpc_cof_reversed_buffer) {
1763  av_log(avctx, AV_LOG_ERROR, "Allocating buffer memory failed.\n");
1764  ret = AVERROR(ENOMEM);
1765  goto fail;
1766  }
1767 
1768  // assign quantized parcor coefficient buffers
1769  for (c = 0; c < num_buffers; c++) {
1770  ctx->quant_cof[c] = ctx->quant_cof_buffer + c * sconf->max_order;
1771  ctx->lpc_cof[c] = ctx->lpc_cof_buffer + c * sconf->max_order;
1772  }
1773 
1774  // allocate and assign lag and gain data buffer for ltp mode
1775  ctx->const_block = av_malloc_array(num_buffers, sizeof(*ctx->const_block));
1776  ctx->shift_lsbs = av_malloc_array(num_buffers, sizeof(*ctx->shift_lsbs));
1777  ctx->opt_order = av_malloc_array(num_buffers, sizeof(*ctx->opt_order));
1778  ctx->store_prev_samples = av_malloc_array(num_buffers, sizeof(*ctx->store_prev_samples));
1779  ctx->use_ltp = av_mallocz_array(num_buffers, sizeof(*ctx->use_ltp));
1780  ctx->ltp_lag = av_malloc_array(num_buffers, sizeof(*ctx->ltp_lag));
1781  ctx->ltp_gain = av_malloc_array(num_buffers, sizeof(*ctx->ltp_gain));
1782  ctx->ltp_gain_buffer = av_malloc_array(num_buffers * 5, sizeof(*ctx->ltp_gain_buffer));
1783 
1784  if (!ctx->const_block || !ctx->shift_lsbs ||
1785  !ctx->opt_order || !ctx->store_prev_samples ||
1786  !ctx->use_ltp || !ctx->ltp_lag ||
1787  !ctx->ltp_gain || !ctx->ltp_gain_buffer) {
1788  av_log(avctx, AV_LOG_ERROR, "Allocating buffer memory failed.\n");
1789  ret = AVERROR(ENOMEM);
1790  goto fail;
1791  }
1792 
1793  for (c = 0; c < num_buffers; c++)
1794  ctx->ltp_gain[c] = ctx->ltp_gain_buffer + c * 5;
1795 
1796  // allocate and assign channel data buffer for mcc mode
1797  if (sconf->mc_coding) {
1798  ctx->chan_data_buffer = av_mallocz_array(num_buffers * num_buffers,
1799  sizeof(*ctx->chan_data_buffer));
1800  ctx->chan_data = av_mallocz_array(num_buffers,
1801  sizeof(*ctx->chan_data));
1802  ctx->reverted_channels = av_malloc_array(num_buffers,
1803  sizeof(*ctx->reverted_channels));
1804 
1805  if (!ctx->chan_data_buffer || !ctx->chan_data || !ctx->reverted_channels) {
1806  av_log(avctx, AV_LOG_ERROR, "Allocating buffer memory failed.\n");
1807  ret = AVERROR(ENOMEM);
1808  goto fail;
1809  }
1810 
1811  for (c = 0; c < num_buffers; c++)
1812  ctx->chan_data[c] = ctx->chan_data_buffer + c * num_buffers;
1813  } else {
1814  ctx->chan_data = NULL;
1815  ctx->chan_data_buffer = NULL;
1816  ctx->reverted_channels = NULL;
1817  }
1818 
1819  channel_size = sconf->frame_length + sconf->max_order;
1820 
1821  ctx->prev_raw_samples = av_malloc_array(sconf->max_order, sizeof(*ctx->prev_raw_samples));
1822  ctx->raw_buffer = av_mallocz_array(avctx->channels * channel_size, sizeof(*ctx->raw_buffer));
1823  ctx->raw_samples = av_malloc_array(avctx->channels, sizeof(*ctx->raw_samples));
1824 
1825  // allocate previous raw sample buffer
1826  if (!ctx->prev_raw_samples || !ctx->raw_buffer|| !ctx->raw_samples) {
1827  av_log(avctx, AV_LOG_ERROR, "Allocating buffer memory failed.\n");
1828  ret = AVERROR(ENOMEM);
1829  goto fail;
1830  }
1831 
1832  // assign raw samples buffers
1833  ctx->raw_samples[0] = ctx->raw_buffer + sconf->max_order;
1834  for (c = 1; c < avctx->channels; c++)
1835  ctx->raw_samples[c] = ctx->raw_samples[c - 1] + channel_size;
1836 
1837  // allocate crc buffer
1838  if (HAVE_BIGENDIAN != sconf->msb_first && sconf->crc_enabled &&
1841  avctx->channels *
1843  sizeof(*ctx->crc_buffer));
1844  if (!ctx->crc_buffer) {
1845  av_log(avctx, AV_LOG_ERROR, "Allocating buffer memory failed.\n");
1846  ret = AVERROR(ENOMEM);
1847  goto fail;
1848  }
1849  }
1850 
1851  ff_bswapdsp_init(&ctx->bdsp);
1852 
1853  return 0;
1854 
1855 fail:
1856  return ret;
1857 }
1858 
1859 
1860 /** Flush (reset) the frame ID after seeking.
1861  */
1862 static av_cold void flush(AVCodecContext *avctx)
1863 {
1864  ALSDecContext *ctx = avctx->priv_data;
1865 
1866  ctx->frame_id = 0;
1867 }
1868 
1869 
1871  .name = "als",
1872  .long_name = NULL_IF_CONFIG_SMALL("MPEG-4 Audio Lossless Coding (ALS)"),
1873  .type = AVMEDIA_TYPE_AUDIO,
1874  .id = AV_CODEC_ID_MP4ALS,
1875  .priv_data_size = sizeof(ALSDecContext),
1876  .init = decode_init,
1877  .close = decode_end,
1878  .decode = decode_frame,
1879  .flush = flush,
1880  .capabilities = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DR1,
1881  .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,
1882 };
#define FF_CODEC_CAP_INIT_CLEANUP
The codec allows calling the close function for deallocation even if the init function returned a fai...
Definition: internal.h:48
#define MUL64(a, b)
Definition: mathops.h:52
#define FF_SANE_NB_CHANNELS
Definition: internal.h:62
void(* bswap_buf)(uint32_t *dst, const uint32_t *src, int w)
Definition: bswapdsp.h:25
AVCodec ff_als_decoder
Definition: alsdec.c:1870
static int als_weighting(GetBitContext *gb, int k, int off)
Definition: alsdec.c:1207
static int decode_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)
Decode the block data for a non-constant block.
Definition: alsdec.c:900
int msb_first
1 = original CRC calculated on big-endian system, 0 = little-endian
Definition: alsdec.c:159
#define NULL
Definition: coverity.c:32
const char const char void * val
Definition: avisynth_c.h:634
float v
const char * s
Definition: avisynth_c.h:631
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
static int shift(int a, int b)
Definition: sonic.c:82
This structure describes decoded (raw) audio or video data.
Definition: frame.h:171
int * use_ltp
contains use_ltp flags for all channels
Definition: alsdec.c:212
ptrdiff_t const GLvoid * data
Definition: opengl_enc.c:101
av_cold void ff_bgmc_end(uint8_t **cf_lut, int **cf_lut_status)
Release the lookup table arrays.
Definition: bgmc.c:480
int32_t ** raw_samples
decoded raw samples for each channel
Definition: alsdec.c:225
uint8_t * crc_buffer
buffer of byte order corrected samples used for CRC check
Definition: alsdec.c:227
static unsigned int get_bits(GetBitContext *s, int n)
Read 1-25 bits.
Definition: get_bits.h:261
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:182
static const int16_t mcc_weightings[]
Inter-channel weighting factors for multi-channel correlation.
Definition: alsdec.c:118
static void skip_bits_long(GetBitContext *s, int n)
Definition: get_bits.h:218
static av_cold int init(AVCodecContext *avctx)
Definition: avrndec.c:35
#define avpriv_request_sample(...)
int block_switching
number of block switching levels
Definition: alsdec.c:167
int rlslms
use "Recursive Least Square-Least Mean Square" predictor: 1 = on, 0 = off
Definition: alsdec.c:174
int size
Definition: avcodec.h:1434
const char * b
Definition: vf_curves.c:109
static int check_specific_config(ALSDecContext *ctx)
Check the ALSSpecificConfig for unsupported features.
Definition: alsdec.c:434
#define av_bswap16
Definition: bswap.h:31
int adapt_order
adaptive order: 1 = on, 0 = off
Definition: alsdec.c:163
static int read_frame_data(ALSDecContext *ctx, unsigned int ra_frame)
Read the frame data.
Definition: alsdec.c:1376
int32_t * lpc_cof_reversed_buffer
temporary buffer to set up a reversed versio of lpc_cof_buffer
Definition: alsdec.c:220
GetBitContext gb
Definition: alsdec.c:194
Block Gilbert-Moore decoder header.
const char * master
Definition: vf_curves.c:110
unsigned int js_switch
if true, joint-stereo decoding is enforced
Definition: alsdec.c:201
int bits_per_raw_sample
Bits per sample/pixel of internal libavcodec pixel/sample format.
Definition: avcodec.h:3013
static int read_decode_block(ALSDecContext *ctx, ALSBlockData *bd)
Read and decode block data successively.
Definition: alsdec.c:1054
#define INTERLEAVE_OUTPUT(bps)
#define sample
AVCodec.
Definition: avcodec.h:3482
static int32_t decode_rice(GetBitContext *gb, unsigned int k)
Read and decode a Rice codeword.
Definition: alsdec.c:482
static int get_sbits_long(GetBitContext *s, int n)
Read 0-32 bits as a signed integer.
Definition: get_bits.h:376
int * ltp_lag
contains ltp lag values for all channels
Definition: alsdec.c:213
int * const_block
contains const_block flags for all channels
Definition: alsdec.c:208
static const uint8_t ltp_gain_values[4][4]
Gain values of p(0) for long-term prediction.
Definition: alsdec.c:107
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
static av_cold int decode_init(AVCodecContext *avctx)
Initialize the ALS decoder.
Definition: alsdec.c:1694
BswapDSPContext bdsp
Definition: alsdec.c:195
int32_t * lpc_cof
coefficients of the direct form prediction
Definition: alsdec.c:243
enum AVSampleFormat sample_fmt
audio sample format
Definition: avcodec.h:2280
uint8_t
#define av_cold
Definition: attributes.h:74
static void decode_const_block_data(ALSDecContext *ctx, ALSBlockData *bd)
Decode the block data for a constant block.
Definition: alsdec.c:603
float delta
static av_cold int end(AVCodecContext *avctx)
Definition: avrndec.c:90
int ** ltp_gain
gain values for ltp 5-tap filter for a channel
Definition: alsdec.c:214
uint8_t * extradata
some codecs need / can use extradata like Huffman tables.
Definition: avcodec.h:1627
int chan_sort
channel rearrangement: 1 = on, 0 = off
Definition: alsdec.c:173
static AVFrame * frame
int joint_stereo
joint stereo: 1 = on, 0 = off
Definition: alsdec.c:170
uint8_t * data
Definition: avcodec.h:1433
static int get_bits_count(const GetBitContext *s)
Definition: get_bits.h:213
#define ff_dlog(a,...)
bitstream reader API header.
static int decode_blocks_ind(ALSDecContext *ctx, unsigned int ra_frame, unsigned int c, const unsigned int *div_blocks, unsigned int *js_blocks)
Decode blocks independently.
Definition: alsdec.c:1083
unsigned int block_length
number of samples within the block
Definition: alsdec.c:232
static void zero_remaining(unsigned int b, unsigned int b_max, const unsigned int *div_blocks, int32_t *buf)
Compute the number of samples left to decode for the current frame and sets these samples to zero...
Definition: alsdec.c:1068
int ra_distance
distance between RA frames (in frames, 0...255)
Definition: alsdec.c:161
int weighting[6]
Definition: alsdec.c:187
int32_t * quant_cof_buffer
contains all quantized parcor coefficients
Definition: alsdec.c:217
signed 32 bits
Definition: samplefmt.h:63
ALSChannelData * chan_data_buffer
contains channel data for all channels
Definition: alsdec.c:222
#define av_log(a,...)
int bgmc
"Block Gilbert-Moore Code": 1 = on, 0 = off (Rice coding only)
Definition: alsdec.c:168
unsigned int cs_switch
if true, channel rearrangement is done
Definition: alsdec.c:202
static int get_bits_left(GetBitContext *gb)
Definition: get_bits.h:594
int * use_ltp
if true, long-term prediction is used
Definition: alsdec.c:239
enum RA_Flag ra_flag
indicates where the size of ra units is stored
Definition: alsdec.c:162
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
int ltp_lag_length
number of bits used for ltp lag value
Definition: alsdec.c:207
#define AV_EF_EXPLODE
abort decoding on minor error detection
Definition: avcodec.h:2911
#define AVERROR(e)
Definition: error.h:43
static av_cold void dprint_specific_config(ALSDecContext *ctx)
Definition: alsdec.c:250
unsigned int * opt_order
prediction order of this block
Definition: alsdec.c:237
int * chan_pos
original channel positions
Definition: alsdec.c:176
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:178
AVCodecContext * avctx
Definition: alsdec.c:192
static const int16_t parcor_scaled_values[]
Scaled PARCOR values used for the first two PARCOR coefficients.
Definition: alsdec.c:68
const char * r
Definition: vf_curves.c:107
int32_t ** lpc_cof
coefficients of the direct form prediction filter for a channel
Definition: alsdec.c:218
int chan_config_info
mapping of channels to loudspeaker locations. Unused until setting channel configuration is implement...
Definition: alsdec.c:175
unsigned int num_blocks
number of blocks used in the current frame
Definition: alsdec.c:203
const char * name
Name of the codec implementation.
Definition: avcodec.h:3489
int32_t * prev_raw_samples
contains unshifted raw samples from the previous block
Definition: alsdec.c:224
static int decode_blocks(ALSDecContext *ctx, unsigned int ra_frame, unsigned int c, const unsigned int *div_blocks, unsigned int *js_blocks)
Decode blocks dependently.
Definition: alsdec.c:1123
void ff_bgmc_decode_end(GetBitContext *gb)
Finish decoding.
Definition: bgmc.c:503
const AVCRC * crc_table
Definition: alsdec.c:196
static const uint8_t offset[127][2]
Definition: vf_spp.c:92
GLsizei count
Definition: opengl_enc.c:109
#define FFMAX(a, b)
Definition: common.h:90
int * bgmc_lut_status
pointer at lookup table status flags used for BGMC
Definition: alsdec.c:206
Libavcodec external API header.
#define fail()
Definition: checkasm.h:57
ALSSpecificConfig sconf
Definition: alsdec.c:193
int * store_prev_samples
if true, carryover samples have to be stored
Definition: alsdec.c:238
unsigned int * shift_lsbs
contains shift_lsbs flags for all channels
Definition: alsdec.c:209
int err_recognition
Error recognition; may misdetect some more or less valid parts as errors.
Definition: avcodec.h:2900
#define FFMIN(a, b)
Definition: common.h:92
float y
static int read_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)
Read the block data for a non-constant block.
Definition: alsdec.c:617
GLsizei GLboolean const GLfloat * value
Definition: opengl_enc.c:109
int chan_config
indicates that a chan_config_info field is present
Definition: alsdec.c:172
int32_t
uint32_t av_crc(const AVCRC *ctx, uint32_t crc, const uint8_t *buffer, size_t length)
Calculate the CRC of a block.
Definition: crc.c:356
void ff_bgmc_decode(GetBitContext *gb, unsigned int num, int32_t *dst, int delta, unsigned int sx, unsigned int *h, unsigned int *l, unsigned int *v, uint8_t *cf_lut, int *cf_lut_status)
Read and decode a block Gilbert-Moore coded symbol.
Definition: bgmc.c:510
static av_cold int decode_end(AVCodecContext *avctx)
Uninitialize the ALS decoder.
Definition: alsdec.c:1659
int * const_block
if true, this is a constant value block
Definition: alsdec.c:234
int n
Definition: avisynth_c.h:547
int floating
1 = IEEE 32-bit floating-point, 0 = integer
Definition: alsdec.c:158
int time_diff_flag
Definition: alsdec.c:184
int master_channel
Definition: alsdec.c:183
uint32_t crc
CRC value calculated from decoded data.
Definition: alsdec.c:198
int coef_table
table index of Rice code parameters
Definition: alsdec.c:164
static int read_const_block_data(ALSDecContext *ctx, ALSBlockData *bd)
Read the block data for a constant block.
Definition: alsdec.c:573
#define FF_ARRAY_ELEMS(a)
int sb_part
sub-block partition
Definition: alsdec.c:169
int32_t * raw_other
decoded raw samples of the other channel of a channel pair
Definition: alsdec.c:246
uint8_t * bgmc_lut
pointer at lookup tables used for BGMC
Definition: alsdec.c:205
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition: error.h:62
int * ltp_gain
gain values for ltp 5-tap filter
Definition: alsdec.c:241
int js_blocks
true if this block contains a difference signal
Definition: alsdec.c:235
#define av_bswap32
Definition: bswap.h:33
unsigned int ra_block
if true, this is a random access block
Definition: alsdec.c:233
AVS_Value src
Definition: avisynth_c.h:482
static void parcor_to_lpc(unsigned int k, const int32_t *par, int32_t *cof)
Convert PARCOR coefficient k to direct filter coefficient.
Definition: alsdec.c:500
int sample_rate
samples per second
Definition: avcodec.h:2272
static int init_get_bits8(GetBitContext *s, const uint8_t *buffer, int byte_size)
Initialize GetBitContext.
Definition: get_bits.h:446
main external API structure.
Definition: avcodec.h:1512
ALSChannelData ** chan_data
channel data for multi-channel correlation
Definition: alsdec.c:221
static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame_ptr, AVPacket *avpkt)
Decode an ALS frame.
Definition: alsdec.c:1528
int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
Get a buffer for a frame.
Definition: utils.c:1048
#define MISSING_ERR(cond, str, errval)
void * buf
Definition: avisynth_c.h:553
int extradata_size
Definition: avcodec.h:1628
static unsigned int get_bits1(GetBitContext *s)
Definition: get_bits.h:305
static void skip_bits1(GetBitContext *s)
Definition: get_bits.h:330
unsigned int s_max
maximum Rice parameter allowed in entropy coding
Definition: alsdec.c:204
static void skip_bits(GetBitContext *s, int n)
Definition: get_bits.h:298
#define AV_CODEC_CAP_SUBFRAMES
Codec can output multiple frames per AVPacket Normally demuxers return one frame at a time...
Definition: avcodec.h:907
int * ltp_lag
lag value for long-term prediction
Definition: alsdec.c:240
int32_t * lpc_cof_buffer
contains all coefficients of the direct form prediction filter
Definition: alsdec.c:219
static const int8_t parcor_rice_table[3][20][2]
Rice parameters and corresponding index offsets for decoding the indices of scaled PARCOR values...
Definition: alsdec.c:47
RA_Flag
Definition: alsdec.c:148
static av_cold int read_specific_config(ALSDecContext *ctx)
Read an ALSSpecificConfig from a buffer into the output struct.
Definition: alsdec.c:280
static unsigned int get_bits_long(GetBitContext *s, int n)
Read 0-32 bits.
Definition: get_bits.h:338
int long_term_prediction
long term prediction (LTP): 1 = on, 0 = off
Definition: alsdec.c:165
int32_t * raw_samples
decoded raw samples / residuals for this block
Definition: alsdec.c:244
int * reverted_channels
stores a flag for each reverted channel
Definition: alsdec.c:223
int ff_bgmc_decode_init(GetBitContext *gb, unsigned int *h, unsigned int *l, unsigned int *v)
Initialize decoding and reads the first value.
Definition: bgmc.c:488
unsigned int * opt_order
contains opt_order flags for all channels
Definition: alsdec.c:210
int32_t * raw_buffer
contains all decoded raw samples including carryover samples
Definition: alsdec.c:226
int max_order
maximum prediction order (0..1023)
Definition: alsdec.c:166
uint32_t samples
number of samples, 0xFFFFFFFF if unknown
Definition: alsdec.c:156
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:182
int av_get_bytes_per_sample(enum AVSampleFormat sample_fmt)
Return number of bytes per sample.
Definition: samplefmt.c:104
const AVCRC * av_crc_get_table(AVCRCId crc_id)
Get an initialized standard CRC table.
Definition: crc.c:342
static int decode(AVCodecContext *avctx, void *data, int *got_sub, AVPacket *avpkt)
Definition: ccaption_dec.c:521
int mc_coding
extended inter-channel coding (multi channel coding): 1 = on, 0 = off
Definition: alsdec.c:171
static const uint8_t tail_code[16][6]
Tail codes used in arithmetic coding using block Gilbert-Moore codes.
Definition: alsdec.c:128
common internal api header.
if(ret< 0)
Definition: vf_mcdeint.c:280
int32_t * prev_raw_samples
contains unshifted raw samples from the previous block
Definition: alsdec.c:245
static int get_unary(GetBitContext *gb, int stop, int len)
Get unary code of limited length.
Definition: unary.h:46
static av_cold void flush(AVCodecContext *avctx)
Flush (reset) the frame ID after seeking.
Definition: alsdec.c:1862
signed 16 bits
Definition: samplefmt.h:62
static double c[64]
int time_diff_index
Definition: alsdec.c:186
int * ltp_gain_buffer
contains all gain values for ltp 5-tap filter
Definition: alsdec.c:215
int32_t * quant_cof
quantized parcor coefficients
Definition: alsdec.c:242
int avpriv_mpeg4audio_get_config(MPEG4AudioConfig *c, const uint8_t *buf, int bit_size, int sync_extension)
Parse MPEG-4 systems extradata to retrieve audio configuration.
Definition: mpeg4audio.c:81
#define AV_EF_CRCCHECK
Verify checksums embedded in the bitstream (could be of either encoded or decoded data...
Definition: avcodec.h:2908
#define MKBETAG(a, b, c, d)
Definition: common.h:342
static void parse_bs_info(const uint32_t bs_info, unsigned int n, unsigned int div, unsigned int **div_blocks, unsigned int *num_blocks)
Parse the bs_info field to extract the block partitioning used in block switching mode...
Definition: alsdec.c:459
av_cold void ff_bswapdsp_init(BswapDSPContext *c)
Definition: bswapdsp.c:49
void * priv_data
Definition: avcodec.h:1554
int32_t ** quant_cof
quantized parcor coefficients for a channel
Definition: alsdec.c:216
int channels
number of audio channels
Definition: avcodec.h:2273
int crc_enabled
enable Cyclic Redundancy Checksum
Definition: alsdec.c:177
uint32_t crc_org
CRC value of the original input data.
Definition: alsdec.c:197
static int decode_block(ALSDecContext *ctx, ALSBlockData *bd)
Decode the block data.
Definition: alsdec.c:1028
static int read_block(ALSDecContext *ctx, ALSBlockData *bd)
Read the block data.
Definition: alsdec.c:1009
int frame_length
frame length for each frame (last frame may differ)
Definition: alsdec.c:160
static const uint8_t * align_get_bits(GetBitContext *s)
Definition: get_bits.h:454
int stop_flag
Definition: alsdec.c:182
static const struct twinvq_data tab
unsigned int * shift_lsbs
shift of values for this block
Definition: alsdec.c:236
static void * av_mallocz_array(size_t nmemb, size_t size)
Definition: mem.h:228
#define av_freep(p)
void INT64 start
Definition: avisynth_c.h:553
av_cold int ff_bgmc_init(AVCodecContext *avctx, uint8_t **cf_lut, int **cf_lut_status)
Initialize the lookup table arrays.
Definition: bgmc.c:460
#define av_malloc_array(a, b)
#define HAVE_BIGENDIAN
Definition: config.h:186
static int read_channel_data(ALSDecContext *ctx, ALSChannelData *cd, int c)
Read the channel data.
Definition: alsdec.c:1216
static void get_block_sizes(ALSDecContext *ctx, unsigned int *div_blocks, uint32_t *bs_info)
Read block switching field if necessary and set actual block sizes.
Definition: alsdec.c:520
int * store_prev_samples
contains store_prev_samples flags for all channels
Definition: alsdec.c:211
unsigned int frame_id
the frame ID / number of the current frame
Definition: alsdec.c:200
static int revert_channel_correlation(ALSDecContext *ctx, ALSBlockData *bd, ALSChannelData **cd, int *reverted, unsigned int offset, int c)
Recursively reverts the inter-channel correlation for a block.
Definition: alsdec.c:1263
This structure stores compressed data.
Definition: avcodec.h:1410
int nb_samples
number of audio samples (per channel) described by this frame
Definition: frame.h:225
uint32_t AVCRC
Definition: crc.h:34
#define AV_CODEC_CAP_DR1
Codec uses get_buffer() for allocating buffers and supports custom allocators.
Definition: avcodec.h:857
for(j=16;j >0;--j)
unsigned int cur_frame_length
length of the current frame to decode
Definition: alsdec.c:199
GLuint buffer
Definition: opengl_enc.c:102
int resolution
000 = 8-bit; 001 = 16-bit; 010 = 24-bit; 011 = 32-bit
Definition: alsdec.c:157
int time_diff_sign
Definition: alsdec.c:185
#define AV_EF_CAREFUL
consider things that violate the spec, are fast to calculate and have not been seen in the wild as er...
Definition: avcodec.h:2914