]> git.sesse.net Git - ffmpeg/blob - libavcodec/alac.c
Add long names to many AVCodec declarations.
[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 FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file alac.c
24  * ALAC (Apple Lossless Audio Codec) decoder
25  * @author 2005 David Hammerton
26  *
27  * For more information on the ALAC format, visit:
28  *  http://crazney.net/programs/itunes/alac.html
29  *
30  * Note: This decoder expects a 36- (0x24-)byte QuickTime atom to be
31  * passed through the extradata[_size] fields. This atom is tacked onto
32  * the end of an 'alac' stsd atom and has the following format:
33  *  bytes 0-3   atom size (0x24), big-endian
34  *  bytes 4-7   atom type ('alac', not the 'alac' tag from start of stsd)
35  *  bytes 8-35  data bytes needed by decoder
36  *
37  * Extradata:
38  * 32bit  size
39  * 32bit  tag (=alac)
40  * 32bit  zero?
41  * 32bit  max sample per frame
42  *  8bit  ?? (zero?)
43  *  8bit  sample size
44  *  8bit  history mult
45  *  8bit  initial history
46  *  8bit  kmodifier
47  *  8bit  channels?
48  * 16bit  ??
49  * 32bit  max coded frame size
50  * 32bit  bitrate?
51  * 32bit  samplerate
52  */
53
54
55 #include "avcodec.h"
56 #include "bitstream.h"
57 #include "bytestream.h"
58 #include "unary.h"
59
60 #define ALAC_EXTRADATA_SIZE 36
61 #define MAX_CHANNELS 2
62
63 typedef struct {
64
65     AVCodecContext *avctx;
66     GetBitContext gb;
67     /* init to 0; first frame decode should initialize from extradata and
68      * set this to 1 */
69     int context_initialized;
70
71     int numchannels;
72     int bytespersample;
73
74     /* buffers */
75     int32_t *predicterror_buffer[MAX_CHANNELS];
76
77     int32_t *outputsamples_buffer[MAX_CHANNELS];
78
79     /* stuff from setinfo */
80     uint32_t setinfo_max_samples_per_frame; /* 0x1000 = 4096 */    /* max samples per frame? */
81     uint8_t setinfo_sample_size; /* 0x10 */
82     uint8_t setinfo_rice_historymult; /* 0x28 */
83     uint8_t setinfo_rice_initialhistory; /* 0x0a */
84     uint8_t setinfo_rice_kmodifier; /* 0x0e */
85     /* end setinfo stuff */
86
87 } ALACContext;
88
89 static void allocate_buffers(ALACContext *alac)
90 {
91     int chan;
92     for (chan = 0; chan < MAX_CHANNELS; chan++) {
93         alac->predicterror_buffer[chan] =
94             av_malloc(alac->setinfo_max_samples_per_frame * 4);
95
96         alac->outputsamples_buffer[chan] =
97             av_malloc(alac->setinfo_max_samples_per_frame * 4);
98     }
99 }
100
101 static int alac_set_info(ALACContext *alac)
102 {
103     const unsigned char *ptr = alac->avctx->extradata;
104
105     ptr += 4; /* size */
106     ptr += 4; /* alac */
107     ptr += 4; /* 0 ? */
108
109     if(AV_RB32(ptr) >= UINT_MAX/4){
110         av_log(alac->avctx, AV_LOG_ERROR, "setinfo_max_samples_per_frame too large\n");
111         return -1;
112     }
113
114     /* buffer size / 2 ? */
115     alac->setinfo_max_samples_per_frame = bytestream_get_be32(&ptr);
116     ptr++;                          /* ??? */
117     alac->setinfo_sample_size           = *ptr++;
118     alac->setinfo_rice_historymult      = *ptr++;
119     alac->setinfo_rice_initialhistory   = *ptr++;
120     alac->setinfo_rice_kmodifier        = *ptr++;
121     ptr++;                         /* channels? */
122     bytestream_get_be16(&ptr);      /* ??? */
123     bytestream_get_be32(&ptr);      /* max coded frame size */
124     bytestream_get_be32(&ptr);      /* bitrate ? */
125     bytestream_get_be32(&ptr);      /* samplerate */
126
127     allocate_buffers(alac);
128
129     return 0;
130 }
131
132 static inline int decode_scalar(GetBitContext *gb, int k, int limit, int readsamplesize){
133     /* read x - number of 1s before 0 represent the rice */
134     int x = get_unary_0_9(gb);
135
136     if (x > 8) { /* RICE THRESHOLD */
137         /* use alternative encoding */
138         x = get_bits(gb, readsamplesize);
139     } else {
140         if (k >= limit)
141             k = limit;
142
143         if (k != 1) {
144             int extrabits = show_bits(gb, k);
145
146             /* multiply x by 2^k - 1, as part of their strange algorithm */
147             x = (x << k) - x;
148
149             if (extrabits > 1) {
150                 x += extrabits - 1;
151                 skip_bits(gb, k);
152             } else
153                 skip_bits(gb, k - 1);
154         }
155     }
156     return x;
157 }
158
159 static void bastardized_rice_decompress(ALACContext *alac,
160                                  int32_t *output_buffer,
161                                  int output_size,
162                                  int readsamplesize, /* arg_10 */
163                                  int rice_initialhistory, /* arg424->b */
164                                  int rice_kmodifier, /* arg424->d */
165                                  int rice_historymult, /* arg424->c */
166                                  int rice_kmodifier_mask /* arg424->e */
167         )
168 {
169     int output_count;
170     unsigned int history = rice_initialhistory;
171     int sign_modifier = 0;
172
173     for (output_count = 0; output_count < output_size; output_count++) {
174         int32_t x;
175         int32_t x_modified;
176         int32_t final_val;
177
178         /* standard rice encoding */
179         int k; /* size of extra bits */
180
181         /* read k, that is bits as is */
182         k = av_log2((history >> 9) + 3);
183         x= decode_scalar(&alac->gb, k, rice_kmodifier, readsamplesize);
184
185         x_modified = sign_modifier + x;
186         final_val = (x_modified + 1) / 2;
187         if (x_modified & 1) final_val *= -1;
188
189         output_buffer[output_count] = final_val;
190
191         sign_modifier = 0;
192
193         /* now update the history */
194         history += x_modified * rice_historymult
195                    - ((history * rice_historymult) >> 9);
196
197         if (x_modified > 0xffff)
198             history = 0xffff;
199
200         /* special case: there may be compressed blocks of 0 */
201         if ((history < 128) && (output_count+1 < output_size)) {
202             int block_size, k;
203
204             sign_modifier = 1;
205
206             k = 7 - av_log2(history) + ((history + 16) >> 6 /* / 64 */);
207
208             block_size= decode_scalar(&alac->gb, k, rice_kmodifier, 16);
209
210             if (block_size > 0) {
211                 memset(&output_buffer[output_count+1], 0, block_size * 4);
212                 output_count += block_size;
213             }
214
215             if (block_size > 0xffff)
216                 sign_modifier = 0;
217
218             history = 0;
219         }
220     }
221 }
222
223 static inline int32_t extend_sign32(int32_t val, int bits)
224 {
225     return (val << (32 - bits)) >> (32 - bits);
226 }
227
228 static inline int sign_only(int v)
229 {
230     return v ? FFSIGN(v) : 0;
231 }
232
233 static void predictor_decompress_fir_adapt(int32_t *error_buffer,
234                                            int32_t *buffer_out,
235                                            int output_size,
236                                            int readsamplesize,
237                                            int16_t *predictor_coef_table,
238                                            int predictor_coef_num,
239                                            int predictor_quantitization)
240 {
241     int i;
242
243     /* first sample always copies */
244     *buffer_out = *error_buffer;
245
246     if (!predictor_coef_num) {
247         if (output_size <= 1)
248             return;
249
250         memcpy(buffer_out+1, error_buffer+1, (output_size-1) * 4);
251         return;
252     }
253
254     if (predictor_coef_num == 0x1f) { /* 11111 - max value of predictor_coef_num */
255       /* second-best case scenario for fir decompression,
256        * error describes a small difference from the previous sample only
257        */
258         if (output_size <= 1)
259             return;
260         for (i = 0; i < output_size - 1; i++) {
261             int32_t prev_value;
262             int32_t error_value;
263
264             prev_value = buffer_out[i];
265             error_value = error_buffer[i+1];
266             buffer_out[i+1] =
267                 extend_sign32((prev_value + error_value), readsamplesize);
268         }
269         return;
270     }
271
272     /* read warm-up samples */
273     if (predictor_coef_num > 0)
274         for (i = 0; i < predictor_coef_num; i++) {
275             int32_t val;
276
277             val = buffer_out[i] + error_buffer[i+1];
278             val = extend_sign32(val, readsamplesize);
279             buffer_out[i+1] = val;
280         }
281
282 #if 0
283     /* 4 and 8 are very common cases (the only ones i've seen). these
284      * should be unrolled and optimized
285      */
286     if (predictor_coef_num == 4) {
287         /* FIXME: optimized general case */
288         return;
289     }
290
291     if (predictor_coef_table == 8) {
292         /* FIXME: optimized general case */
293         return;
294     }
295 #endif
296
297     /* general case */
298     if (predictor_coef_num > 0) {
299         for (i = predictor_coef_num + 1; i < output_size; i++) {
300             int j;
301             int sum = 0;
302             int outval;
303             int error_val = error_buffer[i];
304
305             for (j = 0; j < predictor_coef_num; j++) {
306                 sum += (buffer_out[predictor_coef_num-j] - buffer_out[0]) *
307                        predictor_coef_table[j];
308             }
309
310             outval = (1 << (predictor_quantitization-1)) + sum;
311             outval = outval >> predictor_quantitization;
312             outval = outval + buffer_out[0] + error_val;
313             outval = extend_sign32(outval, readsamplesize);
314
315             buffer_out[predictor_coef_num+1] = outval;
316
317             if (error_val > 0) {
318                 int predictor_num = predictor_coef_num - 1;
319
320                 while (predictor_num >= 0 && error_val > 0) {
321                     int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
322                     int sign = sign_only(val);
323
324                     predictor_coef_table[predictor_num] -= sign;
325
326                     val *= sign; /* absolute value */
327
328                     error_val -= ((val >> predictor_quantitization) *
329                                   (predictor_coef_num - predictor_num));
330
331                     predictor_num--;
332                 }
333             } else if (error_val < 0) {
334                 int predictor_num = predictor_coef_num - 1;
335
336                 while (predictor_num >= 0 && error_val < 0) {
337                     int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
338                     int sign = - sign_only(val);
339
340                     predictor_coef_table[predictor_num] -= sign;
341
342                     val *= sign; /* neg value */
343
344                     error_val -= ((val >> predictor_quantitization) *
345                                   (predictor_coef_num - predictor_num));
346
347                     predictor_num--;
348                 }
349             }
350
351             buffer_out++;
352         }
353     }
354 }
355
356 static void reconstruct_stereo_16(int32_t *buffer[MAX_CHANNELS],
357                                   int16_t *buffer_out,
358                                   int numchannels, int numsamples,
359                                   uint8_t interlacing_shift,
360                                   uint8_t interlacing_leftweight)
361 {
362     int i;
363     if (numsamples <= 0)
364         return;
365
366     /* weighted interlacing */
367     if (interlacing_leftweight) {
368         for (i = 0; i < numsamples; i++) {
369             int32_t a, b;
370
371             a = buffer[0][i];
372             b = buffer[1][i];
373
374             a -= (b * interlacing_leftweight) >> interlacing_shift;
375             b += a;
376
377             buffer_out[i*numchannels] = b;
378             buffer_out[i*numchannels + 1] = a;
379         }
380
381         return;
382     }
383
384     /* otherwise basic interlacing took place */
385     for (i = 0; i < numsamples; i++) {
386         int16_t left, right;
387
388         left = buffer[0][i];
389         right = buffer[1][i];
390
391         buffer_out[i*numchannels] = left;
392         buffer_out[i*numchannels + 1] = right;
393     }
394 }
395
396 static int alac_decode_frame(AVCodecContext *avctx,
397                              void *outbuffer, int *outputsize,
398                              const uint8_t *inbuffer, int input_buffer_size)
399 {
400     ALACContext *alac = avctx->priv_data;
401
402     int channels;
403     int32_t outputsamples;
404     int hassize;
405     int readsamplesize;
406     int wasted_bytes;
407     int isnotcompressed;
408     uint8_t interlacing_shift;
409     uint8_t interlacing_leftweight;
410
411     /* short-circuit null buffers */
412     if (!inbuffer || !input_buffer_size)
413         return input_buffer_size;
414
415     /* initialize from the extradata */
416     if (!alac->context_initialized) {
417         if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
418             av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
419                 ALAC_EXTRADATA_SIZE);
420             return input_buffer_size;
421         }
422         if (alac_set_info(alac)) {
423             av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
424             return input_buffer_size;
425         }
426         alac->context_initialized = 1;
427     }
428
429     init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
430
431     channels = get_bits(&alac->gb, 3) + 1;
432     if (channels > MAX_CHANNELS) {
433         av_log(avctx, AV_LOG_ERROR, "channels > %d not supported\n",
434                MAX_CHANNELS);
435         return input_buffer_size;
436     }
437
438     /* 2^result = something to do with output waiting.
439      * perhaps matters if we read > 1 frame in a pass?
440      */
441     skip_bits(&alac->gb, 4);
442
443     skip_bits(&alac->gb, 12); /* unknown, skip 12 bits */
444
445     /* the output sample size is stored soon */
446     hassize = get_bits1(&alac->gb);
447
448     wasted_bytes = get_bits(&alac->gb, 2); /* unknown ? */
449
450     /* whether the frame is compressed */
451     isnotcompressed = get_bits1(&alac->gb);
452
453     if (hassize) {
454         /* now read the number of samples as a 32bit integer */
455         outputsamples = get_bits(&alac->gb, 32);
456     } else
457         outputsamples = alac->setinfo_max_samples_per_frame;
458
459     *outputsize = outputsamples * alac->bytespersample;
460     readsamplesize = alac->setinfo_sample_size - (wasted_bytes * 8) + channels - 1;
461
462     if (!isnotcompressed) {
463         /* so it is compressed */
464         int16_t predictor_coef_table[channels][32];
465         int predictor_coef_num[channels];
466         int prediction_type[channels];
467         int prediction_quantitization[channels];
468         int ricemodifier[channels];
469         int i, chan;
470
471         interlacing_shift = get_bits(&alac->gb, 8);
472         interlacing_leftweight = get_bits(&alac->gb, 8);
473
474         for (chan = 0; chan < channels; chan++) {
475             prediction_type[chan] = get_bits(&alac->gb, 4);
476             prediction_quantitization[chan] = get_bits(&alac->gb, 4);
477
478             ricemodifier[chan] = get_bits(&alac->gb, 3);
479             predictor_coef_num[chan] = get_bits(&alac->gb, 5);
480
481             /* read the predictor table */
482             for (i = 0; i < predictor_coef_num[chan]; i++)
483                 predictor_coef_table[chan][i] = (int16_t)get_bits(&alac->gb, 16);
484         }
485
486         if (wasted_bytes)
487             av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented, unhandling of wasted_bytes\n");
488
489         for (chan = 0; chan < channels; chan++) {
490             bastardized_rice_decompress(alac,
491                                         alac->predicterror_buffer[chan],
492                                         outputsamples,
493                                         readsamplesize,
494                                         alac->setinfo_rice_initialhistory,
495                                         alac->setinfo_rice_kmodifier,
496                                         ricemodifier[chan] * alac->setinfo_rice_historymult / 4,
497                                         (1 << alac->setinfo_rice_kmodifier) - 1);
498
499             if (prediction_type[chan] == 0) {
500                 /* adaptive fir */
501                 predictor_decompress_fir_adapt(alac->predicterror_buffer[chan],
502                                                alac->outputsamples_buffer[chan],
503                                                outputsamples,
504                                                readsamplesize,
505                                                predictor_coef_table[chan],
506                                                predictor_coef_num[chan],
507                                                prediction_quantitization[chan]);
508             } else {
509                 av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type[chan]);
510                 /* I think the only other prediction type (or perhaps this is
511                  * just a boolean?) runs adaptive fir twice.. like:
512                  * predictor_decompress_fir_adapt(predictor_error, tempout, ...)
513                  * predictor_decompress_fir_adapt(predictor_error, outputsamples ...)
514                  * little strange..
515                  */
516             }
517         }
518     } else {
519         /* not compressed, easy case */
520         if (alac->setinfo_sample_size <= 16) {
521             int i, chan;
522             for (chan = 0; chan < channels; chan++)
523                 for (i = 0; i < outputsamples; i++) {
524                     int32_t audiobits;
525
526                     audiobits = get_bits(&alac->gb, alac->setinfo_sample_size);
527                     audiobits = extend_sign32(audiobits, readsamplesize);
528
529                     alac->outputsamples_buffer[chan][i] = audiobits;
530                 }
531         } else {
532             int i, chan;
533             for (chan = 0; chan < channels; chan++)
534                 for (i = 0; i < outputsamples; i++) {
535                     int32_t audiobits;
536
537                     audiobits = get_bits(&alac->gb, 16);
538                     /* special case of sign extension..
539                      * as we'll be ORing the low 16bits into this */
540                     audiobits = audiobits << 16;
541                     audiobits = audiobits >> (32 - alac->setinfo_sample_size);
542                     audiobits |= get_bits(&alac->gb, alac->setinfo_sample_size - 16);
543
544                     alac->outputsamples_buffer[chan][i] = audiobits;
545                 }
546         }
547         /* wasted_bytes = 0; */
548         interlacing_shift = 0;
549         interlacing_leftweight = 0;
550     }
551     if (get_bits(&alac->gb, 3) != 7)
552         av_log(avctx, AV_LOG_ERROR, "Error : Wrong End Of Frame\n");
553
554     switch(alac->setinfo_sample_size) {
555     case 16:
556         if (channels == 2) {
557             reconstruct_stereo_16(alac->outputsamples_buffer,
558                                   (int16_t*)outbuffer,
559                                   alac->numchannels,
560                                   outputsamples,
561                                   interlacing_shift,
562                                   interlacing_leftweight);
563         } else {
564             int i;
565             for (i = 0; i < outputsamples; i++) {
566                 int16_t sample = alac->outputsamples_buffer[0][i];
567                 ((int16_t*)outbuffer)[i * alac->numchannels] = sample;
568             }
569         }
570         break;
571     case 20:
572     case 24:
573         // It is not clear if there exist any encoder that creates 24 bit ALAC
574         // files. iTunes convert 24 bit raw files to 16 bit before encoding.
575     case 32:
576         av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
577         break;
578     default:
579         break;
580     }
581
582     if (input_buffer_size * 8 - get_bits_count(&alac->gb) > 8)
583         av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n", input_buffer_size * 8 - get_bits_count(&alac->gb));
584
585     return input_buffer_size;
586 }
587
588 static av_cold int alac_decode_init(AVCodecContext * avctx)
589 {
590     ALACContext *alac = avctx->priv_data;
591     alac->avctx = avctx;
592     alac->context_initialized = 0;
593
594     alac->numchannels = alac->avctx->channels;
595     alac->bytespersample = (avctx->bits_per_sample / 8) * alac->numchannels;
596
597     return 0;
598 }
599
600 static av_cold int alac_decode_close(AVCodecContext *avctx)
601 {
602     ALACContext *alac = avctx->priv_data;
603
604     int chan;
605     for (chan = 0; chan < MAX_CHANNELS; chan++) {
606         av_free(alac->predicterror_buffer[chan]);
607         av_free(alac->outputsamples_buffer[chan]);
608     }
609
610     return 0;
611 }
612
613 AVCodec alac_decoder = {
614     "alac",
615     CODEC_TYPE_AUDIO,
616     CODEC_ID_ALAC,
617     sizeof(ALACContext),
618     alac_decode_init,
619     NULL,
620     alac_decode_close,
621     alac_decode_frame,
622     .long_name = "ALAC (Apple Lossless Audio Codec)",
623 };