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