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