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