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