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