~siretart/libav/trusty

« back to all changes in this revision

Viewing changes to libavcodec/alac.c

  • Committer: Reinhard Tartler
  • Date: 2013-10-23 03:04:17 UTC
  • mfrom: (1.3.36 sid)
  • Revision ID: siretart@tauware.de-20131023030417-1o6mpkl1l0raifjt
mergeĀ fromĀ debian

Show diffs side-by-side

added added

removed removed

Lines of Context:
37
37
 *  8bit  sample size
38
38
 *  8bit  history mult         (40)
39
39
 *  8bit  initial history      (14)
40
 
 *  8bit  kmodifier            (10)
 
40
 *  8bit  rice param limit     (10)
41
41
 *  8bit  channels
42
42
 * 16bit  maxRun               (255)
43
43
 * 32bit  max coded frame size (0 means unknown)
45
45
 * 32bit  samplerate
46
46
 */
47
47
 
48
 
 
 
48
#include "libavutil/channel_layout.h"
49
49
#include "avcodec.h"
50
50
#include "get_bits.h"
51
51
#include "bytestream.h"
 
52
#include "internal.h"
52
53
#include "unary.h"
53
54
#include "mathops.h"
 
55
#include "alac_data.h"
54
56
 
55
57
#define ALAC_EXTRADATA_SIZE 36
56
 
#define MAX_CHANNELS 2
57
58
 
58
59
typedef struct {
59
 
 
60
60
    AVCodecContext *avctx;
61
61
    AVFrame frame;
62
62
    GetBitContext gb;
63
 
 
64
 
    int numchannels;
65
 
 
66
 
    /* buffers */
67
 
    int32_t *predicterror_buffer[MAX_CHANNELS];
68
 
 
69
 
    int32_t *outputsamples_buffer[MAX_CHANNELS];
70
 
 
71
 
    int32_t *extra_bits_buffer[MAX_CHANNELS];
72
 
 
73
 
    /* stuff from setinfo */
74
 
    uint32_t setinfo_max_samples_per_frame; /* 0x1000 = 4096 */    /* max samples per frame? */
75
 
    uint8_t setinfo_sample_size; /* 0x10 */
76
 
    uint8_t setinfo_rice_historymult; /* 0x28 */
77
 
    uint8_t setinfo_rice_initialhistory; /* 0x0a */
78
 
    uint8_t setinfo_rice_kmodifier; /* 0x0e */
79
 
    /* end setinfo stuff */
80
 
 
81
 
    int extra_bits;                         /**< number of extra bits beyond 16-bit */
 
63
    int channels;
 
64
 
 
65
    int32_t *predict_error_buffer[2];
 
66
    int32_t *output_samples_buffer[2];
 
67
    int32_t *extra_bits_buffer[2];
 
68
 
 
69
    uint32_t max_samples_per_frame;
 
70
    uint8_t  sample_size;
 
71
    uint8_t  rice_history_mult;
 
72
    uint8_t  rice_initial_history;
 
73
    uint8_t  rice_limit;
 
74
 
 
75
    int extra_bits;     /**< number of extra bits beyond 16-bit */
 
76
    int nb_samples;     /**< number of samples in the current frame */
82
77
} ALACContext;
83
78
 
84
 
static inline int decode_scalar(GetBitContext *gb, int k, int limit, int readsamplesize){
85
 
    /* read x - number of 1s before 0 represent the rice */
86
 
    int x = get_unary_0_9(gb);
 
79
static inline unsigned int decode_scalar(GetBitContext *gb, int k, int bps)
 
80
{
 
81
    unsigned int x = get_unary_0_9(gb);
87
82
 
88
83
    if (x > 8) { /* RICE THRESHOLD */
89
84
        /* use alternative encoding */
90
 
        x = get_bits(gb, readsamplesize);
91
 
    } else {
92
 
        if (k >= limit)
93
 
            k = limit;
94
 
 
95
 
        if (k != 1) {
96
 
            int extrabits = show_bits(gb, k);
97
 
 
98
 
            /* multiply x by 2^k - 1, as part of their strange algorithm */
99
 
            x = (x << k) - x;
100
 
 
101
 
            if (extrabits > 1) {
102
 
                x += extrabits - 1;
103
 
                skip_bits(gb, k);
104
 
            } else
105
 
                skip_bits(gb, k - 1);
106
 
        }
 
85
        x = get_bits_long(gb, bps);
 
86
    } else if (k != 1) {
 
87
        int extrabits = show_bits(gb, k);
 
88
 
 
89
        /* multiply x by 2^k - 1, as part of their strange algorithm */
 
90
        x = (x << k) - x;
 
91
 
 
92
        if (extrabits > 1) {
 
93
            x += extrabits - 1;
 
94
            skip_bits(gb, k);
 
95
        } else
 
96
            skip_bits(gb, k - 1);
107
97
    }
108
98
    return x;
109
99
}
110
100
 
111
 
static void bastardized_rice_decompress(ALACContext *alac,
112
 
                                 int32_t *output_buffer,
113
 
                                 int output_size,
114
 
                                 int readsamplesize, /* arg_10 */
115
 
                                 int rice_initialhistory, /* arg424->b */
116
 
                                 int rice_kmodifier, /* arg424->d */
117
 
                                 int rice_historymult, /* arg424->c */
118
 
                                 int rice_kmodifier_mask /* arg424->e */
119
 
        )
 
101
static void rice_decompress(ALACContext *alac, int32_t *output_buffer,
 
102
                            int nb_samples, int bps, int rice_history_mult)
120
103
{
121
 
    int output_count;
122
 
    unsigned int history = rice_initialhistory;
 
104
    int i;
 
105
    unsigned int history = alac->rice_initial_history;
123
106
    int sign_modifier = 0;
124
107
 
125
 
    for (output_count = 0; output_count < output_size; output_count++) {
126
 
        int32_t x;
127
 
        int32_t x_modified;
128
 
        int32_t final_val;
129
 
 
130
 
        /* standard rice encoding */
131
 
        int k; /* size of extra bits */
132
 
 
133
 
        /* read k, that is bits as is */
 
108
    for (i = 0; i < nb_samples; i++) {
 
109
        int k;
 
110
        unsigned int x;
 
111
 
 
112
        /* calculate rice param and decode next value */
134
113
        k = av_log2((history >> 9) + 3);
135
 
        x= decode_scalar(&alac->gb, k, rice_kmodifier, readsamplesize);
136
 
 
137
 
        x_modified = sign_modifier + x;
138
 
        final_val = (x_modified + 1) / 2;
139
 
        if (x_modified & 1) final_val *= -1;
140
 
 
141
 
        output_buffer[output_count] = final_val;
142
 
 
 
114
        k = FFMIN(k, alac->rice_limit);
 
115
        x = decode_scalar(&alac->gb, k, bps);
 
116
        x += sign_modifier;
143
117
        sign_modifier = 0;
144
 
 
145
 
        /* now update the history */
146
 
        history += x_modified * rice_historymult
147
 
                   - ((history * rice_historymult) >> 9);
148
 
 
149
 
        if (x_modified > 0xffff)
 
118
        output_buffer[i] = (x >> 1) ^ -(x & 1);
 
119
 
 
120
        /* update the history */
 
121
        if (x > 0xffff)
150
122
            history = 0xffff;
 
123
        else
 
124
            history +=         x * rice_history_mult -
 
125
                       ((history * rice_history_mult) >> 9);
151
126
 
152
127
        /* special case: there may be compressed blocks of 0 */
153
 
        if ((history < 128) && (output_count+1 < output_size)) {
154
 
            int k;
155
 
            unsigned int block_size;
156
 
 
157
 
            sign_modifier = 1;
158
 
 
159
 
            k = 7 - av_log2(history) + ((history + 16) >> 6 /* / 64 */);
160
 
 
161
 
            block_size= decode_scalar(&alac->gb, k, rice_kmodifier, 16);
 
128
        if ((history < 128) && (i + 1 < nb_samples)) {
 
129
            int block_size;
 
130
 
 
131
            /* calculate rice param and decode block size */
 
132
            k = 7 - av_log2(history) + ((history + 16) >> 6);
 
133
            k = FFMIN(k, alac->rice_limit);
 
134
            block_size = decode_scalar(&alac->gb, k, 16);
162
135
 
163
136
            if (block_size > 0) {
164
 
                if(block_size >= output_size - output_count){
165
 
                    av_log(alac->avctx, AV_LOG_ERROR, "invalid zero block size of %d %d %d\n", block_size, output_size, output_count);
166
 
                    block_size= output_size - output_count - 1;
 
137
                if (block_size >= nb_samples - i) {
 
138
                    av_log(alac->avctx, AV_LOG_ERROR,
 
139
                           "invalid zero block size of %d %d %d\n", block_size,
 
140
                           nb_samples, i);
 
141
                    block_size = nb_samples - i - 1;
167
142
                }
168
 
                memset(&output_buffer[output_count+1], 0, block_size * 4);
169
 
                output_count += block_size;
 
143
                memset(&output_buffer[i + 1], 0,
 
144
                       block_size * sizeof(*output_buffer));
 
145
                i += block_size;
170
146
            }
171
 
 
172
 
            if (block_size > 0xffff)
173
 
                sign_modifier = 0;
174
 
 
 
147
            if (block_size <= 0xffff)
 
148
                sign_modifier = 1;
175
149
            history = 0;
176
150
        }
177
151
    }
182
156
    return v ? FFSIGN(v) : 0;
183
157
}
184
158
 
185
 
static void predictor_decompress_fir_adapt(int32_t *error_buffer,
186
 
                                           int32_t *buffer_out,
187
 
                                           int output_size,
188
 
                                           int readsamplesize,
189
 
                                           int16_t *predictor_coef_table,
190
 
                                           int predictor_coef_num,
191
 
                                           int predictor_quantitization)
 
159
static void lpc_prediction(int32_t *error_buffer, int32_t *buffer_out,
 
160
                           int nb_samples, int bps, int16_t *lpc_coefs,
 
161
                           int lpc_order, int lpc_quant)
192
162
{
193
163
    int i;
 
164
    int32_t *pred = buffer_out;
194
165
 
195
166
    /* first sample always copies */
196
167
    *buffer_out = *error_buffer;
197
168
 
198
 
    if (!predictor_coef_num) {
199
 
        if (output_size <= 1)
200
 
            return;
 
169
    if (nb_samples <= 1)
 
170
        return;
201
171
 
202
 
        memcpy(buffer_out+1, error_buffer+1, (output_size-1) * 4);
 
172
    if (!lpc_order) {
 
173
        memcpy(&buffer_out[1], &error_buffer[1],
 
174
               (nb_samples - 1) * sizeof(*buffer_out));
203
175
        return;
204
176
    }
205
177
 
206
 
    if (predictor_coef_num == 0x1f) { /* 11111 - max value of predictor_coef_num */
207
 
      /* second-best case scenario for fir decompression,
208
 
       * error describes a small difference from the previous sample only
209
 
       */
210
 
        if (output_size <= 1)
211
 
            return;
212
 
        for (i = 0; i < output_size - 1; i++) {
213
 
            int32_t prev_value;
214
 
            int32_t error_value;
215
 
 
216
 
            prev_value = buffer_out[i];
217
 
            error_value = error_buffer[i+1];
218
 
            buffer_out[i+1] =
219
 
                sign_extend((prev_value + error_value), readsamplesize);
 
178
    if (lpc_order == 31) {
 
179
        /* simple 1st-order prediction */
 
180
        for (i = 1; i < nb_samples; i++) {
 
181
            buffer_out[i] = sign_extend(buffer_out[i - 1] + error_buffer[i],
 
182
                                        bps);
220
183
        }
221
184
        return;
222
185
    }
223
186
 
224
187
    /* read warm-up samples */
225
 
    if (predictor_coef_num > 0)
226
 
        for (i = 0; i < predictor_coef_num; i++) {
227
 
            int32_t val;
228
 
 
229
 
            val = buffer_out[i] + error_buffer[i+1];
230
 
            val = sign_extend(val, readsamplesize);
231
 
            buffer_out[i+1] = val;
232
 
        }
233
 
 
234
 
    /* 4 and 8 are very common cases (the only ones i've seen). these
235
 
     * should be unrolled and optimized
236
 
     */
237
 
 
238
 
    /* general case */
239
 
    if (predictor_coef_num > 0) {
240
 
        for (i = predictor_coef_num + 1; i < output_size; i++) {
241
 
            int j;
242
 
            int sum = 0;
243
 
            int outval;
244
 
            int error_val = error_buffer[i];
245
 
 
246
 
            for (j = 0; j < predictor_coef_num; j++) {
247
 
                sum += (buffer_out[predictor_coef_num-j] - buffer_out[0]) *
248
 
                       predictor_coef_table[j];
249
 
            }
250
 
 
251
 
            outval = (1 << (predictor_quantitization-1)) + sum;
252
 
            outval = outval >> predictor_quantitization;
253
 
            outval = outval + buffer_out[0] + error_val;
254
 
            outval = sign_extend(outval, readsamplesize);
255
 
 
256
 
            buffer_out[predictor_coef_num+1] = outval;
257
 
 
258
 
            if (error_val > 0) {
259
 
                int predictor_num = predictor_coef_num - 1;
260
 
 
261
 
                while (predictor_num >= 0 && error_val > 0) {
262
 
                    int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
263
 
                    int sign = sign_only(val);
264
 
 
265
 
                    predictor_coef_table[predictor_num] -= sign;
266
 
 
267
 
                    val *= sign; /* absolute value */
268
 
 
269
 
                    error_val -= ((val >> predictor_quantitization) *
270
 
                                  (predictor_coef_num - predictor_num));
271
 
 
272
 
                    predictor_num--;
273
 
                }
274
 
            } else if (error_val < 0) {
275
 
                int predictor_num = predictor_coef_num - 1;
276
 
 
277
 
                while (predictor_num >= 0 && error_val < 0) {
278
 
                    int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
279
 
                    int sign = - sign_only(val);
280
 
 
281
 
                    predictor_coef_table[predictor_num] -= sign;
282
 
 
283
 
                    val *= sign; /* neg value */
284
 
 
285
 
                    error_val -= ((val >> predictor_quantitization) *
286
 
                                  (predictor_coef_num - predictor_num));
287
 
 
288
 
                    predictor_num--;
289
 
                }
290
 
            }
291
 
 
292
 
            buffer_out++;
 
188
    for (i = 1; i <= lpc_order; i++)
 
189
        buffer_out[i] = sign_extend(buffer_out[i - 1] + error_buffer[i], bps);
 
190
 
 
191
    /* NOTE: 4 and 8 are very common cases that could be optimized. */
 
192
 
 
193
    for (; i < nb_samples; i++) {
 
194
        int j;
 
195
        int val = 0;
 
196
        int error_val = error_buffer[i];
 
197
        int error_sign;
 
198
        int d = *pred++;
 
199
 
 
200
        /* LPC prediction */
 
201
        for (j = 0; j < lpc_order; j++)
 
202
            val += (pred[j] - d) * lpc_coefs[j];
 
203
        val = (val + (1 << (lpc_quant - 1))) >> lpc_quant;
 
204
        val += d + error_val;
 
205
        buffer_out[i] = sign_extend(val, bps);
 
206
 
 
207
        /* adapt LPC coefficients */
 
208
        error_sign = sign_only(error_val);
 
209
        if (error_sign) {
 
210
            for (j = 0; j < lpc_order && error_val * error_sign > 0; j++) {
 
211
                int sign;
 
212
                val  = d - pred[j];
 
213
                sign = sign_only(val) * error_sign;
 
214
                lpc_coefs[j] -= sign;
 
215
                val *= sign;
 
216
                error_val -= (val >> lpc_quant) * (j + 1);
 
217
            }
293
218
        }
294
219
    }
295
220
}
296
221
 
297
 
static void decorrelate_stereo(int32_t *buffer[MAX_CHANNELS],
298
 
                               int numsamples, uint8_t interlacing_shift,
299
 
                               uint8_t interlacing_leftweight)
 
222
static void decorrelate_stereo(int32_t *buffer[2], int nb_samples,
 
223
                               int decorr_shift, int decorr_left_weight)
300
224
{
301
225
    int i;
302
226
 
303
 
    for (i = 0; i < numsamples; i++) {
 
227
    for (i = 0; i < nb_samples; i++) {
304
228
        int32_t a, b;
305
229
 
306
230
        a = buffer[0][i];
307
231
        b = buffer[1][i];
308
232
 
309
 
        a -= (b * interlacing_leftweight) >> interlacing_shift;
 
233
        a -= (b * decorr_left_weight) >> decorr_shift;
310
234
        b += a;
311
235
 
312
236
        buffer[0][i] = b;
314
238
    }
315
239
}
316
240
 
317
 
static void append_extra_bits(int32_t *buffer[MAX_CHANNELS],
318
 
                              int32_t *extra_bits_buffer[MAX_CHANNELS],
319
 
                              int extra_bits, int numchannels, int numsamples)
 
241
static void append_extra_bits(int32_t *buffer[2], int32_t *extra_bits_buffer[2],
 
242
                              int extra_bits, int channels, int nb_samples)
320
243
{
321
244
    int i, ch;
322
245
 
323
 
    for (ch = 0; ch < numchannels; ch++)
324
 
        for (i = 0; i < numsamples; i++)
 
246
    for (ch = 0; ch < channels; ch++)
 
247
        for (i = 0; i < nb_samples; i++)
325
248
            buffer[ch][i] = (buffer[ch][i] << extra_bits) | extra_bits_buffer[ch][i];
326
249
}
327
250
 
328
 
static void interleave_stereo_16(int32_t *buffer[MAX_CHANNELS],
329
 
                                 int16_t *buffer_out, int numsamples)
330
 
{
331
 
    int i;
332
 
 
333
 
    for (i = 0; i < numsamples; i++) {
334
 
        *buffer_out++ = buffer[0][i];
335
 
        *buffer_out++ = buffer[1][i];
336
 
    }
337
 
}
338
 
 
339
 
static void interleave_stereo_24(int32_t *buffer[MAX_CHANNELS],
340
 
                                 int32_t *buffer_out, int numsamples)
341
 
{
342
 
    int i;
343
 
 
344
 
    for (i = 0; i < numsamples; i++) {
345
 
        *buffer_out++ = buffer[0][i] << 8;
346
 
        *buffer_out++ = buffer[1][i] << 8;
347
 
    }
348
 
}
349
 
 
350
 
static int alac_decode_frame(AVCodecContext *avctx, void *data,
351
 
                             int *got_frame_ptr, AVPacket *avpkt)
352
 
{
353
 
    const uint8_t *inbuffer = avpkt->data;
354
 
    int input_buffer_size = avpkt->size;
 
251
static int decode_element(AVCodecContext *avctx, void *data, int ch_index,
 
252
                          int channels)
 
253
{
355
254
    ALACContext *alac = avctx->priv_data;
356
 
 
357
 
    int channels;
358
 
    unsigned int outputsamples;
359
 
    int hassize;
360
 
    unsigned int readsamplesize;
361
 
    int isnotcompressed;
362
 
    uint8_t interlacing_shift;
363
 
    uint8_t interlacing_leftweight;
364
 
    int i, ch, ret;
365
 
 
366
 
    init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
367
 
 
368
 
    channels = get_bits(&alac->gb, 3) + 1;
369
 
    if (channels != avctx->channels) {
370
 
        av_log(avctx, AV_LOG_ERROR, "frame header channel count mismatch\n");
371
 
        return AVERROR_INVALIDDATA;
372
 
    }
373
 
 
374
 
    /* 2^result = something to do with output waiting.
375
 
     * perhaps matters if we read > 1 frame in a pass?
376
 
     */
377
 
    skip_bits(&alac->gb, 4);
378
 
 
379
 
    skip_bits(&alac->gb, 12); /* unknown, skip 12 bits */
380
 
 
381
 
    /* the output sample size is stored soon */
382
 
    hassize = get_bits1(&alac->gb);
 
255
    int has_size, bps, is_compressed, decorr_shift, decorr_left_weight, ret;
 
256
    uint32_t output_samples;
 
257
    int i, ch;
 
258
 
 
259
    skip_bits(&alac->gb, 4);  /* element instance tag */
 
260
    skip_bits(&alac->gb, 12); /* unused header bits */
 
261
 
 
262
    /* the number of output samples is stored in the frame */
 
263
    has_size = get_bits1(&alac->gb);
383
264
 
384
265
    alac->extra_bits = get_bits(&alac->gb, 2) << 3;
 
266
    bps = alac->sample_size - alac->extra_bits + channels - 1;
 
267
    if (bps > 32) {
 
268
        av_log(avctx, AV_LOG_ERROR, "bps is unsupported: %d\n", bps);
 
269
        return AVERROR_PATCHWELCOME;
 
270
    }
385
271
 
386
272
    /* whether the frame is compressed */
387
 
    isnotcompressed = get_bits1(&alac->gb);
 
273
    is_compressed = !get_bits1(&alac->gb);
388
274
 
389
 
    if (hassize) {
390
 
        /* now read the number of samples as a 32bit integer */
391
 
        outputsamples = get_bits_long(&alac->gb, 32);
392
 
        if(outputsamples > alac->setinfo_max_samples_per_frame){
393
 
            av_log(avctx, AV_LOG_ERROR, "outputsamples %d > %d\n", outputsamples, alac->setinfo_max_samples_per_frame);
394
 
            return -1;
 
275
    if (has_size)
 
276
        output_samples = get_bits_long(&alac->gb, 32);
 
277
    else
 
278
        output_samples = alac->max_samples_per_frame;
 
279
    if (!output_samples || output_samples > alac->max_samples_per_frame) {
 
280
        av_log(avctx, AV_LOG_ERROR, "invalid samples per frame: %d\n",
 
281
               output_samples);
 
282
        return AVERROR_INVALIDDATA;
 
283
    }
 
284
    if (!alac->nb_samples) {
 
285
        /* get output buffer */
 
286
        alac->frame.nb_samples = output_samples;
 
287
        if ((ret = ff_get_buffer(avctx, &alac->frame)) < 0) {
 
288
            av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
 
289
            return ret;
395
290
        }
396
 
    } else
397
 
        outputsamples = alac->setinfo_max_samples_per_frame;
398
 
 
399
 
    /* get output buffer */
400
 
    if (outputsamples > INT32_MAX) {
401
 
        av_log(avctx, AV_LOG_ERROR, "unsupported block size: %u\n", outputsamples);
 
291
    } else if (output_samples != alac->nb_samples) {
 
292
        av_log(avctx, AV_LOG_ERROR, "sample count mismatch: %u != %d\n",
 
293
               output_samples, alac->nb_samples);
402
294
        return AVERROR_INVALIDDATA;
403
295
    }
404
 
    alac->frame.nb_samples = outputsamples;
405
 
    if ((ret = avctx->get_buffer(avctx, &alac->frame)) < 0) {
406
 
        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
407
 
        return ret;
408
 
    }
409
 
 
410
 
    readsamplesize = alac->setinfo_sample_size - alac->extra_bits + channels - 1;
411
 
    if (readsamplesize > MIN_CACHE_BITS) {
412
 
        av_log(avctx, AV_LOG_ERROR, "readsamplesize too big (%d)\n", readsamplesize);
413
 
        return -1;
414
 
    }
415
 
 
416
 
    if (!isnotcompressed) {
417
 
        /* so it is compressed */
418
 
        int16_t predictor_coef_table[MAX_CHANNELS][32];
419
 
        int predictor_coef_num[MAX_CHANNELS];
420
 
        int prediction_type[MAX_CHANNELS];
421
 
        int prediction_quantitization[MAX_CHANNELS];
422
 
        int ricemodifier[MAX_CHANNELS];
423
 
 
424
 
        interlacing_shift = get_bits(&alac->gb, 8);
425
 
        interlacing_leftweight = get_bits(&alac->gb, 8);
 
296
    alac->nb_samples = output_samples;
 
297
    if (alac->sample_size > 16) {
 
298
        for (ch = 0; ch < channels; ch++)
 
299
            alac->output_samples_buffer[ch] = (int32_t *)alac->frame.extended_data[ch_index + ch];
 
300
    }
 
301
 
 
302
    if (is_compressed) {
 
303
        int16_t lpc_coefs[2][32];
 
304
        int lpc_order[2];
 
305
        int prediction_type[2];
 
306
        int lpc_quant[2];
 
307
        int rice_history_mult[2];
 
308
 
 
309
        decorr_shift       = get_bits(&alac->gb, 8);
 
310
        decorr_left_weight = get_bits(&alac->gb, 8);
426
311
 
427
312
        for (ch = 0; ch < channels; ch++) {
428
 
            prediction_type[ch] = get_bits(&alac->gb, 4);
429
 
            prediction_quantitization[ch] = get_bits(&alac->gb, 4);
 
313
            prediction_type[ch]   = get_bits(&alac->gb, 4);
 
314
            lpc_quant[ch]         = get_bits(&alac->gb, 4);
 
315
            rice_history_mult[ch] = get_bits(&alac->gb, 3);
 
316
            lpc_order[ch]         = get_bits(&alac->gb, 5);
430
317
 
431
 
            ricemodifier[ch] = get_bits(&alac->gb, 3);
432
 
            predictor_coef_num[ch] = get_bits(&alac->gb, 5);
 
318
            if (lpc_order[ch] >= alac->max_samples_per_frame)
 
319
                return AVERROR_INVALIDDATA;
433
320
 
434
321
            /* read the predictor table */
435
 
            for (i = 0; i < predictor_coef_num[ch]; i++)
436
 
                predictor_coef_table[ch][i] = (int16_t)get_bits(&alac->gb, 16);
 
322
            for (i = lpc_order[ch] - 1; i >= 0; i--)
 
323
                lpc_coefs[ch][i] = get_sbits(&alac->gb, 16);
437
324
        }
438
325
 
439
326
        if (alac->extra_bits) {
440
 
            for (i = 0; i < outputsamples; i++) {
 
327
            for (i = 0; i < alac->nb_samples; i++) {
441
328
                for (ch = 0; ch < channels; ch++)
442
329
                    alac->extra_bits_buffer[ch][i] = get_bits(&alac->gb, alac->extra_bits);
443
330
            }
444
331
        }
445
332
        for (ch = 0; ch < channels; ch++) {
446
 
            bastardized_rice_decompress(alac,
447
 
                                        alac->predicterror_buffer[ch],
448
 
                                        outputsamples,
449
 
                                        readsamplesize,
450
 
                                        alac->setinfo_rice_initialhistory,
451
 
                                        alac->setinfo_rice_kmodifier,
452
 
                                        ricemodifier[ch] * alac->setinfo_rice_historymult / 4,
453
 
                                        (1 << alac->setinfo_rice_kmodifier) - 1);
 
333
            rice_decompress(alac, alac->predict_error_buffer[ch],
 
334
                            alac->nb_samples, bps,
 
335
                            rice_history_mult[ch] * alac->rice_history_mult / 4);
454
336
 
455
337
            /* adaptive FIR filter */
456
338
            if (prediction_type[ch] == 15) {
461
343
                 * However, this prediction type is not currently used by the
462
344
                 * reference encoder.
463
345
                 */
464
 
                predictor_decompress_fir_adapt(alac->predicterror_buffer[ch],
465
 
                                               alac->predicterror_buffer[ch],
466
 
                                               outputsamples, readsamplesize,
467
 
                                               NULL, 31, 0);
 
346
                lpc_prediction(alac->predict_error_buffer[ch],
 
347
                               alac->predict_error_buffer[ch],
 
348
                               alac->nb_samples, bps, NULL, 31, 0);
468
349
            } else if (prediction_type[ch] > 0) {
469
350
                av_log(avctx, AV_LOG_WARNING, "unknown prediction type: %i\n",
470
351
                       prediction_type[ch]);
471
352
            }
472
 
            predictor_decompress_fir_adapt(alac->predicterror_buffer[ch],
473
 
                                           alac->outputsamples_buffer[ch],
474
 
                                           outputsamples, readsamplesize,
475
 
                                           predictor_coef_table[ch],
476
 
                                           predictor_coef_num[ch],
477
 
                                           prediction_quantitization[ch]);
 
353
            lpc_prediction(alac->predict_error_buffer[ch],
 
354
                           alac->output_samples_buffer[ch], alac->nb_samples,
 
355
                           bps, lpc_coefs[ch], lpc_order[ch], lpc_quant[ch]);
478
356
        }
479
357
    } else {
480
358
        /* not compressed, easy case */
481
 
        for (i = 0; i < outputsamples; i++) {
 
359
        for (i = 0; i < alac->nb_samples; i++) {
482
360
            for (ch = 0; ch < channels; ch++) {
483
 
                alac->outputsamples_buffer[ch][i] = get_sbits_long(&alac->gb,
484
 
                                                                   alac->setinfo_sample_size);
 
361
                alac->output_samples_buffer[ch][i] =
 
362
                         get_sbits_long(&alac->gb, alac->sample_size);
485
363
            }
486
364
        }
487
 
        alac->extra_bits = 0;
488
 
        interlacing_shift = 0;
489
 
        interlacing_leftweight = 0;
 
365
        alac->extra_bits   = 0;
 
366
        decorr_shift       = 0;
 
367
        decorr_left_weight = 0;
490
368
    }
491
 
    if (get_bits(&alac->gb, 3) != 7)
492
 
        av_log(avctx, AV_LOG_ERROR, "Error : Wrong End Of Frame\n");
493
369
 
494
 
    if (channels == 2 && interlacing_leftweight) {
495
 
        decorrelate_stereo(alac->outputsamples_buffer, outputsamples,
496
 
                           interlacing_shift, interlacing_leftweight);
 
370
    if (channels == 2 && decorr_left_weight) {
 
371
        decorrelate_stereo(alac->output_samples_buffer, alac->nb_samples,
 
372
                           decorr_shift, decorr_left_weight);
497
373
    }
498
374
 
499
375
    if (alac->extra_bits) {
500
 
        append_extra_bits(alac->outputsamples_buffer, alac->extra_bits_buffer,
501
 
                          alac->extra_bits, alac->numchannels, outputsamples);
502
 
    }
503
 
 
504
 
    switch(alac->setinfo_sample_size) {
505
 
    case 16:
506
 
        if (channels == 2) {
507
 
            interleave_stereo_16(alac->outputsamples_buffer,
508
 
                                 (int16_t *)alac->frame.data[0], outputsamples);
509
 
        } else {
510
 
            int16_t *outbuffer = (int16_t *)alac->frame.data[0];
511
 
            for (i = 0; i < outputsamples; i++) {
512
 
                outbuffer[i] = alac->outputsamples_buffer[0][i];
513
 
            }
514
 
        }
515
 
        break;
516
 
    case 24:
517
 
        if (channels == 2) {
518
 
            interleave_stereo_24(alac->outputsamples_buffer,
519
 
                                 (int32_t *)alac->frame.data[0], outputsamples);
520
 
        } else {
521
 
            int32_t *outbuffer = (int32_t *)alac->frame.data[0];
522
 
            for (i = 0; i < outputsamples; i++)
523
 
                outbuffer[i] = alac->outputsamples_buffer[0][i] << 8;
524
 
        }
525
 
        break;
526
 
    }
527
 
 
528
 
    if (input_buffer_size * 8 - get_bits_count(&alac->gb) > 8)
529
 
        av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n", input_buffer_size * 8 - get_bits_count(&alac->gb));
 
376
        append_extra_bits(alac->output_samples_buffer, alac->extra_bits_buffer,
 
377
                          alac->extra_bits, channels, alac->nb_samples);
 
378
    }
 
379
 
 
380
    switch(alac->sample_size) {
 
381
    case 16: {
 
382
        for (ch = 0; ch < channels; ch++) {
 
383
            int16_t *outbuffer = (int16_t *)alac->frame.extended_data[ch_index + ch];
 
384
            for (i = 0; i < alac->nb_samples; i++)
 
385
                *outbuffer++ = alac->output_samples_buffer[ch][i];
 
386
        }}
 
387
        break;
 
388
    case 24: {
 
389
        for (ch = 0; ch < channels; ch++) {
 
390
            for (i = 0; i < alac->nb_samples; i++)
 
391
                alac->output_samples_buffer[ch][i] <<= 8;
 
392
        }}
 
393
        break;
 
394
    }
 
395
 
 
396
    return 0;
 
397
}
 
398
 
 
399
static int alac_decode_frame(AVCodecContext *avctx, void *data,
 
400
                             int *got_frame_ptr, AVPacket *avpkt)
 
401
{
 
402
    ALACContext *alac = avctx->priv_data;
 
403
    enum AlacRawDataBlockType element;
 
404
    int channels;
 
405
    int ch, ret, got_end;
 
406
 
 
407
    init_get_bits(&alac->gb, avpkt->data, avpkt->size * 8);
 
408
 
 
409
    got_end = 0;
 
410
    alac->nb_samples = 0;
 
411
    ch = 0;
 
412
    while (get_bits_left(&alac->gb) >= 3) {
 
413
        element = get_bits(&alac->gb, 3);
 
414
        if (element == TYPE_END) {
 
415
            got_end = 1;
 
416
            break;
 
417
        }
 
418
        if (element > TYPE_CPE && element != TYPE_LFE) {
 
419
            av_log(avctx, AV_LOG_ERROR, "syntax element unsupported: %d", element);
 
420
            return AVERROR_PATCHWELCOME;
 
421
        }
 
422
 
 
423
        channels = (element == TYPE_CPE) ? 2 : 1;
 
424
        if (ch + channels > alac->channels ||
 
425
            ff_alac_channel_layout_offsets[alac->channels - 1][ch] + channels > alac->channels) {
 
426
            av_log(avctx, AV_LOG_ERROR, "invalid element channel count\n");
 
427
            return AVERROR_INVALIDDATA;
 
428
        }
 
429
 
 
430
        ret = decode_element(avctx, data,
 
431
                             ff_alac_channel_layout_offsets[alac->channels - 1][ch],
 
432
                             channels);
 
433
        if (ret < 0 && get_bits_left(&alac->gb))
 
434
            return ret;
 
435
 
 
436
        ch += channels;
 
437
    }
 
438
    if (!got_end) {
 
439
        av_log(avctx, AV_LOG_ERROR, "no end tag found. incomplete packet.\n");
 
440
        return AVERROR_INVALIDDATA;
 
441
    }
 
442
 
 
443
    if (avpkt->size * 8 - get_bits_count(&alac->gb) > 8) {
 
444
        av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n",
 
445
               avpkt->size * 8 - get_bits_count(&alac->gb));
 
446
    }
530
447
 
531
448
    *got_frame_ptr   = 1;
532
449
    *(AVFrame *)data = alac->frame;
533
450
 
534
 
    return input_buffer_size;
 
451
    return avpkt->size;
535
452
}
536
453
 
537
454
static av_cold int alac_decode_close(AVCodecContext *avctx)
539
456
    ALACContext *alac = avctx->priv_data;
540
457
 
541
458
    int ch;
542
 
    for (ch = 0; ch < alac->numchannels; ch++) {
543
 
        av_freep(&alac->predicterror_buffer[ch]);
544
 
        av_freep(&alac->outputsamples_buffer[ch]);
 
459
    for (ch = 0; ch < FFMIN(alac->channels, 2); ch++) {
 
460
        av_freep(&alac->predict_error_buffer[ch]);
 
461
        if (alac->sample_size == 16)
 
462
            av_freep(&alac->output_samples_buffer[ch]);
545
463
        av_freep(&alac->extra_bits_buffer[ch]);
546
464
    }
547
465
 
551
469
static int allocate_buffers(ALACContext *alac)
552
470
{
553
471
    int ch;
554
 
    for (ch = 0; ch < alac->numchannels; ch++) {
555
 
        int buf_size = alac->setinfo_max_samples_per_frame * sizeof(int32_t);
556
 
 
557
 
        FF_ALLOC_OR_GOTO(alac->avctx, alac->predicterror_buffer[ch],
558
 
                         buf_size, buf_alloc_fail);
559
 
 
560
 
        FF_ALLOC_OR_GOTO(alac->avctx, alac->outputsamples_buffer[ch],
561
 
                         buf_size, buf_alloc_fail);
 
472
    int buf_size = alac->max_samples_per_frame * sizeof(int32_t);
 
473
 
 
474
    for (ch = 0; ch < FFMIN(alac->channels, 2); ch++) {
 
475
        FF_ALLOC_OR_GOTO(alac->avctx, alac->predict_error_buffer[ch],
 
476
                         buf_size, buf_alloc_fail);
 
477
 
 
478
        if (alac->sample_size == 16) {
 
479
            FF_ALLOC_OR_GOTO(alac->avctx, alac->output_samples_buffer[ch],
 
480
                             buf_size, buf_alloc_fail);
 
481
        }
562
482
 
563
483
        FF_ALLOC_OR_GOTO(alac->avctx, alac->extra_bits_buffer[ch],
564
484
                         buf_size, buf_alloc_fail);
571
491
 
572
492
static int alac_set_info(ALACContext *alac)
573
493
{
574
 
    const unsigned char *ptr = alac->avctx->extradata;
575
 
 
576
 
    ptr += 4; /* size */
577
 
    ptr += 4; /* alac */
578
 
    ptr += 4; /* version */
579
 
 
580
 
    if(AV_RB32(ptr) >= UINT_MAX/4){
581
 
        av_log(alac->avctx, AV_LOG_ERROR, "setinfo_max_samples_per_frame too large\n");
582
 
        return -1;
 
494
    GetByteContext gb;
 
495
 
 
496
    bytestream2_init(&gb, alac->avctx->extradata,
 
497
                     alac->avctx->extradata_size);
 
498
 
 
499
    bytestream2_skipu(&gb, 12); // size:4, alac:4, version:4
 
500
 
 
501
    alac->max_samples_per_frame = bytestream2_get_be32u(&gb);
 
502
    if (!alac->max_samples_per_frame ||
 
503
        alac->max_samples_per_frame > INT_MAX / sizeof(int32_t)) {
 
504
        av_log(alac->avctx, AV_LOG_ERROR, "max samples per frame invalid: %u\n",
 
505
               alac->max_samples_per_frame);
 
506
        return AVERROR_INVALIDDATA;
583
507
    }
584
 
 
585
 
    /* buffer size / 2 ? */
586
 
    alac->setinfo_max_samples_per_frame = bytestream_get_be32(&ptr);
587
 
    ptr++;                          /* compatible version */
588
 
    alac->setinfo_sample_size           = *ptr++;
589
 
    alac->setinfo_rice_historymult      = *ptr++;
590
 
    alac->setinfo_rice_initialhistory   = *ptr++;
591
 
    alac->setinfo_rice_kmodifier        = *ptr++;
592
 
    alac->numchannels                   = *ptr++;
593
 
    bytestream_get_be16(&ptr);      /* maxRun */
594
 
    bytestream_get_be32(&ptr);      /* max coded frame size */
595
 
    bytestream_get_be32(&ptr);      /* average bitrate */
596
 
    bytestream_get_be32(&ptr);      /* samplerate */
 
508
    bytestream2_skipu(&gb, 1);  // compatible version
 
509
    alac->sample_size          = bytestream2_get_byteu(&gb);
 
510
    alac->rice_history_mult    = bytestream2_get_byteu(&gb);
 
511
    alac->rice_initial_history = bytestream2_get_byteu(&gb);
 
512
    alac->rice_limit           = bytestream2_get_byteu(&gb);
 
513
    alac->channels             = bytestream2_get_byteu(&gb);
 
514
    bytestream2_get_be16u(&gb); // maxRun
 
515
    bytestream2_get_be32u(&gb); // max coded frame size
 
516
    bytestream2_get_be32u(&gb); // average bitrate
 
517
    bytestream2_get_be32u(&gb); // samplerate
597
518
 
598
519
    return 0;
599
520
}
614
535
        return -1;
615
536
    }
616
537
 
617
 
    switch (alac->setinfo_sample_size) {
618
 
    case 16: avctx->sample_fmt    = AV_SAMPLE_FMT_S16;
 
538
    switch (alac->sample_size) {
 
539
    case 16: avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
619
540
             break;
620
 
    case 24: avctx->sample_fmt    = AV_SAMPLE_FMT_S32;
 
541
    case 24:
 
542
    case 32: avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
621
543
             break;
622
544
    default: av_log_ask_for_sample(avctx, "Sample depth %d is not supported.\n",
623
 
                                   alac->setinfo_sample_size);
 
545
                                   alac->sample_size);
624
546
             return AVERROR_PATCHWELCOME;
625
547
    }
 
548
    avctx->bits_per_raw_sample = alac->sample_size;
626
549
 
627
 
    if (alac->numchannels < 1) {
 
550
    if (alac->channels < 1) {
628
551
        av_log(avctx, AV_LOG_WARNING, "Invalid channel count\n");
629
 
        alac->numchannels = avctx->channels;
 
552
        alac->channels = avctx->channels;
630
553
    } else {
631
 
        if (alac->numchannels > MAX_CHANNELS)
632
 
            alac->numchannels = avctx->channels;
 
554
        if (alac->channels > ALAC_MAX_CHANNELS)
 
555
            alac->channels = avctx->channels;
633
556
        else
634
 
            avctx->channels = alac->numchannels;
 
557
            avctx->channels = alac->channels;
635
558
    }
636
 
    if (avctx->channels > MAX_CHANNELS) {
 
559
    if (avctx->channels > ALAC_MAX_CHANNELS) {
637
560
        av_log(avctx, AV_LOG_ERROR, "Unsupported channel count: %d\n",
638
561
               avctx->channels);
639
562
        return AVERROR_PATCHWELCOME;
640
563
    }
 
564
    avctx->channel_layout = ff_alac_channel_layouts[alac->channels - 1];
641
565
 
642
566
    if ((ret = allocate_buffers(alac)) < 0) {
643
567
        av_log(avctx, AV_LOG_ERROR, "Error allocating buffers\n");
653
577
AVCodec ff_alac_decoder = {
654
578
    .name           = "alac",
655
579
    .type           = AVMEDIA_TYPE_AUDIO,
656
 
    .id             = CODEC_ID_ALAC,
 
580
    .id             = AV_CODEC_ID_ALAC,
657
581
    .priv_data_size = sizeof(ALACContext),
658
582
    .init           = alac_decode_init,
659
583
    .close          = alac_decode_close,
660
584
    .decode         = alac_decode_frame,
661
585
    .capabilities   = CODEC_CAP_DR1,
662
 
    .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),
 
586
    .long_name      = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),
663
587
};