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