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