]> git.sesse.net Git - ffmpeg/blob - libavcodec/alac.c
257ad1c119ddd7f6f30f85930e5df47af09b4ac6
[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
59 #define ALAC_EXTRADATA_SIZE 36
60 #define MAX_CHANNELS 2
61
62 typedef struct {
63
64     AVCodecContext *avctx;
65     GetBitContext gb;
66     /* init to 0; first frame decode should initialize from extradata and
67      * set this to 1 */
68     int context_initialized;
69
70     int samplesize;
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_7a; /* 0x00 */
82     uint8_t setinfo_sample_size; /* 0x10 */
83     uint8_t setinfo_rice_historymult; /* 0x28 */
84     uint8_t setinfo_rice_initialhistory; /* 0x0a */
85     uint8_t setinfo_rice_kmodifier; /* 0x0e */
86     uint8_t setinfo_7f; /* 0x02 */
87     uint16_t setinfo_80; /* 0x00ff */
88     uint32_t setinfo_82; /* 0x000020e7 */ /* max sample size?? */
89     uint32_t setinfo_86; /* 0x00069fe4 */ /* bit rate (average)?? */
90     uint32_t setinfo_8a_rate; /* 0x0000ac44 */
91     /* end setinfo stuff */
92
93 } ALACContext;
94
95 static void allocate_buffers(ALACContext *alac)
96 {
97     int chan;
98     for (chan = 0; chan < MAX_CHANNELS; chan++) {
99         alac->predicterror_buffer[chan] =
100             av_malloc(alac->setinfo_max_samples_per_frame * 4);
101
102         alac->outputsamples_buffer[chan] =
103             av_malloc(alac->setinfo_max_samples_per_frame * 4);
104     }
105 }
106
107 static int alac_set_info(ALACContext *alac)
108 {
109     unsigned char *ptr = alac->avctx->extradata;
110
111     ptr += 4; /* size */
112     ptr += 4; /* alac */
113     ptr += 4; /* 0 ? */
114
115     if(AV_RB32(ptr) >= UINT_MAX/4){
116         av_log(alac->avctx, AV_LOG_ERROR, "setinfo_max_samples_per_frame too large\n");
117         return -1;
118     }
119
120     /* buffer size / 2 ? */
121     alac->setinfo_max_samples_per_frame = bytestream_get_be32(&ptr);
122     alac->setinfo_7a                    = *ptr++;
123     alac->setinfo_sample_size           = *ptr++;
124     alac->setinfo_rice_historymult      = *ptr++;
125     alac->setinfo_rice_initialhistory   = *ptr++;
126     alac->setinfo_rice_kmodifier        = *ptr++;
127     /* channels? */
128     alac->setinfo_7f                    = *ptr++;
129     alac->setinfo_80                    = bytestream_get_be16(&ptr);
130     /* max coded frame size */
131     alac->setinfo_82                    = bytestream_get_be32(&ptr);
132     /* bitrate ? */
133     alac->setinfo_86                    = bytestream_get_be32(&ptr);
134     /* samplerate */
135     alac->setinfo_8a_rate               = bytestream_get_be32(&ptr);
136
137     allocate_buffers(alac);
138
139     return 0;
140 }
141
142 static inline int count_leading_zeros(int32_t input)
143 {
144     return 31-av_log2(input);
145 }
146
147 static void bastardized_rice_decompress(ALACContext *alac,
148                                  int32_t *output_buffer,
149                                  int output_size,
150                                  int readsamplesize, /* arg_10 */
151                                  int rice_initialhistory, /* arg424->b */
152                                  int rice_kmodifier, /* arg424->d */
153                                  int rice_historymult, /* arg424->c */
154                                  int rice_kmodifier_mask /* arg424->e */
155         )
156 {
157     int output_count;
158     unsigned int history = rice_initialhistory;
159     int sign_modifier = 0;
160
161     for (output_count = 0; output_count < output_size; output_count++) {
162         int32_t x = 0;
163         int32_t x_modified;
164         int32_t final_val;
165
166         /* read x - number of 1s before 0 represent the rice */
167         while (x <= 8 && get_bits1(&alac->gb)) {
168             x++;
169         }
170
171         if (x > 8) { /* RICE THRESHOLD */
172             /* use alternative encoding */
173             int32_t value;
174
175             value = get_bits(&alac->gb, readsamplesize);
176
177             /* mask value to readsamplesize size */
178             if (readsamplesize != 32)
179                 value &= (0xffffffff >> (32 - readsamplesize));
180
181             x = value;
182         } else {
183             /* standard rice encoding */
184             int extrabits;
185             int k; /* size of extra bits */
186
187             /* read k, that is bits as is */
188             k = 31 - rice_kmodifier - count_leading_zeros((history >> 9) + 3);
189
190             if (k < 0)
191                 k += rice_kmodifier;
192             else
193                 k = rice_kmodifier;
194
195             if (k != 1) {
196                 extrabits = show_bits(&alac->gb, k);
197
198                 /* multiply x by 2^k - 1, as part of their strange algorithm */
199                 x = (x << k) - x;
200
201                 if (extrabits > 1) {
202                     x += extrabits - 1;
203                     skip_bits(&alac->gb, k);
204                 } else
205                     skip_bits(&alac->gb, k - 1);
206             }
207         }
208
209         x_modified = sign_modifier + x;
210         final_val = (x_modified + 1) / 2;
211         if (x_modified & 1) final_val *= -1;
212
213         output_buffer[output_count] = final_val;
214
215         sign_modifier = 0;
216
217         /* now update the history */
218         history += x_modified * rice_historymult
219                    - ((history * rice_historymult) >> 9);
220
221         if (x_modified > 0xffff)
222             history = 0xffff;
223
224         /* special case: there may be compressed blocks of 0 */
225         if ((history < 128) && (output_count+1 < output_size)) {
226             int block_size;
227
228             sign_modifier = 1;
229
230             x = 0;
231             while (x <= 8 && get_bits1(&alac->gb)) {
232                 x++;
233             }
234
235             if (x > 8) {
236                 block_size = get_bits(&alac->gb, 16);
237                 block_size &= 0xffff;
238             } else {
239                 int k;
240                 int extrabits;
241
242                 k = count_leading_zeros(history) + ((history + 16) >> 6 /* / 64 */) - 24;
243
244                 extrabits = show_bits(&alac->gb, k);
245
246                 block_size = (((1 << k) - 1) & rice_kmodifier_mask) * x
247                            + extrabits - 1;
248
249                 if (extrabits < 2) {
250                     x = 1 - extrabits;
251                     block_size += x;
252                     skip_bits(&alac->gb, k - 1);
253                 } else {
254                     skip_bits(&alac->gb, k);
255                 }
256             }
257
258             if (block_size > 0) {
259                 memset(&output_buffer[output_count+1], 0, block_size * 4);
260                 output_count += block_size;
261             }
262
263             if (block_size > 0xffff)
264                 sign_modifier = 0;
265
266             history = 0;
267         }
268     }
269 }
270
271 static inline int32_t extend_sign32(int32_t val, int bits)
272 {
273     return (val << (32 - bits)) >> (32 - bits);
274 }
275
276 static inline int sign_only(int v)
277 {
278     return v ? FFSIGN(v) : 0;
279 }
280
281 static void predictor_decompress_fir_adapt(int32_t *error_buffer,
282                                            int32_t *buffer_out,
283                                            int output_size,
284                                            int readsamplesize,
285                                            int16_t *predictor_coef_table,
286                                            int predictor_coef_num,
287                                            int predictor_quantitization)
288 {
289     int i;
290
291     /* first sample always copies */
292     *buffer_out = *error_buffer;
293
294     if (!predictor_coef_num) {
295         if (output_size <= 1)
296             return;
297
298         memcpy(buffer_out+1, error_buffer+1, (output_size-1) * 4);
299         return;
300     }
301
302     if (predictor_coef_num == 0x1f) { /* 11111 - max value of predictor_coef_num */
303       /* second-best case scenario for fir decompression,
304        * error describes a small difference from the previous sample only
305        */
306         if (output_size <= 1)
307             return;
308         for (i = 0; i < output_size - 1; i++) {
309             int32_t prev_value;
310             int32_t error_value;
311
312             prev_value = buffer_out[i];
313             error_value = error_buffer[i+1];
314             buffer_out[i+1] =
315                 extend_sign32((prev_value + error_value), readsamplesize);
316         }
317         return;
318     }
319
320     /* read warm-up samples */
321     if (predictor_coef_num > 0)
322         for (i = 0; i < predictor_coef_num; i++) {
323             int32_t val;
324
325             val = buffer_out[i] + error_buffer[i+1];
326             val = extend_sign32(val, readsamplesize);
327             buffer_out[i+1] = val;
328         }
329
330 #if 0
331     /* 4 and 8 are very common cases (the only ones i've seen). these
332      * should be unrolled and optimised
333      */
334     if (predictor_coef_num == 4) {
335         /* FIXME: optimised general case */
336         return;
337     }
338
339     if (predictor_coef_table == 8) {
340         /* FIXME: optimised general case */
341         return;
342     }
343 #endif
344
345     /* general case */
346     if (predictor_coef_num > 0) {
347         for (i = predictor_coef_num + 1; i < output_size; i++) {
348             int j;
349             int sum = 0;
350             int outval;
351             int error_val = error_buffer[i];
352
353             for (j = 0; j < predictor_coef_num; j++) {
354                 sum += (buffer_out[predictor_coef_num-j] - buffer_out[0]) *
355                        predictor_coef_table[j];
356             }
357
358             outval = (1 << (predictor_quantitization-1)) + sum;
359             outval = outval >> predictor_quantitization;
360             outval = outval + buffer_out[0] + error_val;
361             outval = extend_sign32(outval, readsamplesize);
362
363             buffer_out[predictor_coef_num+1] = outval;
364
365             if (error_val > 0) {
366                 int predictor_num = predictor_coef_num - 1;
367
368                 while (predictor_num >= 0 && error_val > 0) {
369                     int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
370                     int sign = sign_only(val);
371
372                     predictor_coef_table[predictor_num] -= sign;
373
374                     val *= sign; /* absolute value */
375
376                     error_val -= ((val >> predictor_quantitization) *
377                                   (predictor_coef_num - predictor_num));
378
379                     predictor_num--;
380                 }
381             } else if (error_val < 0) {
382                 int predictor_num = predictor_coef_num - 1;
383
384                 while (predictor_num >= 0 && error_val < 0) {
385                     int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
386                     int sign = - sign_only(val);
387
388                     predictor_coef_table[predictor_num] -= sign;
389
390                     val *= sign; /* neg value */
391
392                     error_val -= ((val >> predictor_quantitization) *
393                                   (predictor_coef_num - predictor_num));
394
395                     predictor_num--;
396                 }
397             }
398
399             buffer_out++;
400         }
401     }
402 }
403
404 static void reconstruct_stereo_16(int32_t *buffer[MAX_CHANNELS],
405                                   int16_t *buffer_out,
406                                   int numchannels, int numsamples,
407                                   uint8_t interlacing_shift,
408                                   uint8_t interlacing_leftweight)
409 {
410     int i;
411     if (numsamples <= 0)
412         return;
413
414     /* weighted interlacing */
415     if (interlacing_leftweight) {
416         for (i = 0; i < numsamples; i++) {
417             int32_t a, b;
418
419             a = buffer[0][i];
420             b = buffer[1][i];
421
422             a -= (b * interlacing_leftweight) >> interlacing_shift;
423             b += a;
424
425             buffer_out[i*numchannels] = b;
426             buffer_out[i*numchannels + 1] = a;
427         }
428
429         return;
430     }
431
432     /* otherwise basic interlacing took place */
433     for (i = 0; i < numsamples; i++) {
434         int16_t left, right;
435
436         left = buffer[0][i];
437         right = buffer[1][i];
438
439         buffer_out[i*numchannels] = left;
440         buffer_out[i*numchannels + 1] = right;
441     }
442 }
443
444 static int alac_decode_frame(AVCodecContext *avctx,
445                              void *outbuffer, int *outputsize,
446                              uint8_t *inbuffer, int input_buffer_size)
447 {
448     ALACContext *alac = avctx->priv_data;
449
450     int channels;
451     int32_t outputsamples;
452     int hassize;
453     int readsamplesize;
454     int wasted_bytes;
455     int isnotcompressed;
456     uint8_t interlacing_shift;
457     uint8_t interlacing_leftweight;
458
459     /* short-circuit null buffers */
460     if (!inbuffer || !input_buffer_size)
461         return input_buffer_size;
462
463     /* initialize from the extradata */
464     if (!alac->context_initialized) {
465         if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
466             av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
467                 ALAC_EXTRADATA_SIZE);
468             return input_buffer_size;
469         }
470         if (alac_set_info(alac)) {
471             av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
472             return input_buffer_size;
473         }
474         alac->context_initialized = 1;
475     }
476
477     init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
478
479     channels = get_bits(&alac->gb, 3) + 1;
480     if (channels > MAX_CHANNELS) {
481         av_log(avctx, AV_LOG_ERROR, "channels > %d not supported\n",
482                MAX_CHANNELS);
483         return input_buffer_size;
484     }
485
486     /* 2^result = something to do with output waiting.
487      * perhaps matters if we read > 1 frame in a pass?
488      */
489     skip_bits(&alac->gb, 4);
490
491     skip_bits(&alac->gb, 12); /* unknown, skip 12 bits */
492
493     /* the output sample size is stored soon */
494     hassize = get_bits1(&alac->gb);
495
496     wasted_bytes = get_bits(&alac->gb, 2); /* unknown ? */
497
498     /* whether the frame is compressed */
499     isnotcompressed = get_bits1(&alac->gb);
500
501     if (hassize) {
502         /* now read the number of samples as a 32bit integer */
503         outputsamples = get_bits(&alac->gb, 32);
504     } else
505         outputsamples = alac->setinfo_max_samples_per_frame;
506
507     *outputsize = outputsamples * alac->bytespersample;
508     readsamplesize = alac->setinfo_sample_size - (wasted_bytes * 8) + channels - 1;
509
510     if (!isnotcompressed) {
511         /* so it is compressed */
512         int16_t predictor_coef_table[channels][32];
513         int predictor_coef_num[channels];
514         int prediction_type[channels];
515         int prediction_quantitization[channels];
516         int ricemodifier[channels];
517         int i, chan;
518
519         interlacing_shift = get_bits(&alac->gb, 8);
520         interlacing_leftweight = get_bits(&alac->gb, 8);
521
522         for (chan = 0; chan < channels; chan++) {
523             prediction_type[chan] = get_bits(&alac->gb, 4);
524             prediction_quantitization[chan] = get_bits(&alac->gb, 4);
525
526             ricemodifier[chan] = get_bits(&alac->gb, 3);
527             predictor_coef_num[chan] = get_bits(&alac->gb, 5);
528
529             /* read the predictor table */
530             for (i = 0; i < predictor_coef_num[chan]; i++)
531                 predictor_coef_table[chan][i] = (int16_t)get_bits(&alac->gb, 16);
532         }
533
534         if (wasted_bytes)
535             av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented, unhandling of wasted_bytes\n");
536
537         for (chan = 0; chan < channels; chan++) {
538             bastardized_rice_decompress(alac,
539                                         alac->predicterror_buffer[chan],
540                                         outputsamples,
541                                         readsamplesize,
542                                         alac->setinfo_rice_initialhistory,
543                                         alac->setinfo_rice_kmodifier,
544                                         ricemodifier[chan] * alac->setinfo_rice_historymult / 4,
545                                         (1 << alac->setinfo_rice_kmodifier) - 1);
546
547             if (prediction_type[chan] == 0) {
548                 /* adaptive fir */
549                 predictor_decompress_fir_adapt(alac->predicterror_buffer[chan],
550                                                alac->outputsamples_buffer[chan],
551                                                outputsamples,
552                                                readsamplesize,
553                                                predictor_coef_table[chan],
554                                                predictor_coef_num[chan],
555                                                prediction_quantitization[chan]);
556             } else {
557                 av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type[chan]);
558                 /* I think the only other prediction type (or perhaps this is
559                  * just a boolean?) runs adaptive fir twice.. like:
560                  * predictor_decompress_fir_adapt(predictor_error, tempout, ...)
561                  * predictor_decompress_fir_adapt(predictor_error, outputsamples ...)
562                  * little strange..
563                  */
564             }
565         }
566     } else {
567         /* not compressed, easy case */
568         if (alac->setinfo_sample_size <= 16) {
569             int i, chan;
570             for (chan = 0; chan < channels; chan++)
571                 for (i = 0; i < outputsamples; i++) {
572                     int32_t audiobits;
573
574                     audiobits = get_bits(&alac->gb, alac->setinfo_sample_size);
575                     audiobits = extend_sign32(audiobits, readsamplesize);
576
577                     alac->outputsamples_buffer[chan][i] = audiobits;
578                 }
579         } else {
580             int i, chan;
581             for (chan = 0; chan < channels; chan++)
582                 for (i = 0; i < outputsamples; i++) {
583                     int32_t audiobits;
584
585                     audiobits = get_bits(&alac->gb, 16);
586                     /* special case of sign extension..
587                      * as we'll be ORing the low 16bits into this */
588                     audiobits = audiobits << 16;
589                     audiobits = audiobits >> (32 - alac->setinfo_sample_size);
590                     audiobits |= get_bits(&alac->gb, alac->setinfo_sample_size - 16);
591
592                     alac->outputsamples_buffer[chan][i] = audiobits;
593                 }
594         }
595         /* wasted_bytes = 0; */
596         interlacing_shift = 0;
597         interlacing_leftweight = 0;
598     }
599
600     switch(alac->setinfo_sample_size) {
601     case 16:
602         if (channels == 2) {
603             reconstruct_stereo_16(alac->outputsamples_buffer,
604                                   (int16_t*)outbuffer,
605                                   alac->numchannels,
606                                   outputsamples,
607                                   interlacing_shift,
608                                   interlacing_leftweight);
609         } else {
610             int i;
611             for (i = 0; i < outputsamples; i++) {
612                 int16_t sample = alac->outputsamples_buffer[0][i];
613                 ((int16_t*)outbuffer)[i * alac->numchannels] = sample;
614             }
615         }
616         break;
617     case 20:
618     case 24:
619         // It is not clear if there exist any encoder that creates 24 bit ALAC
620         // files. iTunes convert 24 bit raw files to 16 bit before encoding.
621     case 32:
622         av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
623         break;
624     default:
625         break;
626     }
627
628     return input_buffer_size;
629 }
630
631 static int alac_decode_init(AVCodecContext * avctx)
632 {
633     ALACContext *alac = avctx->priv_data;
634     alac->avctx = avctx;
635     alac->context_initialized = 0;
636
637     alac->samplesize = alac->avctx->bits_per_sample;
638     alac->numchannels = alac->avctx->channels;
639     alac->bytespersample = (alac->samplesize / 8) * alac->numchannels;
640
641     return 0;
642 }
643
644 static int alac_decode_close(AVCodecContext *avctx)
645 {
646     ALACContext *alac = avctx->priv_data;
647
648     int chan;
649     for (chan = 0; chan < MAX_CHANNELS; chan++) {
650         av_free(alac->predicterror_buffer[chan]);
651         av_free(alac->outputsamples_buffer[chan]);
652     }
653
654     return 0;
655 }
656
657 AVCodec alac_decoder = {
658     "alac",
659     CODEC_TYPE_AUDIO,
660     CODEC_ID_ALAC,
661     sizeof(ALACContext),
662     alac_decode_init,
663     NULL,
664     alac_decode_close,
665     alac_decode_frame,
666 };