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