2 * ALAC (Apple Lossless Audio Codec) decoder
3 * Copyright (c) 2005 David Hammerton
5 * This file is part of FFmpeg.
7 * FFmpeg 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.
12 * FFmpeg 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.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * ALAC (Apple Lossless Audio Codec) decoder
25 * @author 2005 David Hammerton
26 * @see http://crazney.net/programs/itunes/alac.html
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:
34 * 32bit tag version (0)
35 * 32bit samples per frame (used when not set explicitly in the frames)
36 * 8bit compatible version (0)
38 * 8bit history mult (40)
39 * 8bit initial history (14)
40 * 8bit rice param limit (10)
43 * 32bit max coded frame size (0 means unknown)
44 * 32bit average bitrate (0 means unknown)
48 #include "libavutil/channel_layout.h"
51 #include "bytestream.h"
55 #define ALAC_EXTRADATA_SIZE 36
56 #define MAX_CHANNELS 8
59 AVCodecContext *avctx;
64 int32_t *predict_error_buffer[2];
65 int32_t *output_samples_buffer[2];
66 int32_t *extra_bits_buffer[2];
68 uint32_t max_samples_per_frame;
70 uint8_t rice_history_mult;
71 uint8_t rice_initial_history;
74 int extra_bits; /**< number of extra bits beyond 16-bit */
75 int nb_samples; /**< number of samples in the current frame */
80 enum RawDataBlockType {
81 /* At the moment, only SCE, CPE, LFE, and END are recognized. */
92 static const uint8_t alac_channel_layout_offsets[8][8] = {
99 { 2, 0, 1, 4, 5, 6, 3 },
100 { 2, 6, 7, 0, 1, 4, 5, 3 }
103 static const uint16_t alac_channel_layouts[8] = {
106 AV_CH_LAYOUT_SURROUND,
107 AV_CH_LAYOUT_4POINT0,
108 AV_CH_LAYOUT_5POINT0_BACK,
109 AV_CH_LAYOUT_5POINT1_BACK,
110 AV_CH_LAYOUT_6POINT1_BACK,
111 AV_CH_LAYOUT_7POINT1_WIDE_BACK
114 static inline unsigned int decode_scalar(GetBitContext *gb, int k, int bps)
116 unsigned int x = get_unary_0_9(gb);
118 if (x > 8) { /* RICE THRESHOLD */
119 /* use alternative encoding */
120 x = get_bits_long(gb, bps);
122 int extrabits = show_bits(gb, k);
124 /* multiply x by 2^k - 1, as part of their strange algorithm */
131 skip_bits(gb, k - 1);
136 static int rice_decompress(ALACContext *alac, int32_t *output_buffer,
137 int nb_samples, int bps, int rice_history_mult)
140 unsigned int history = alac->rice_initial_history;
141 int sign_modifier = 0;
143 for (i = 0; i < nb_samples; i++) {
147 if(get_bits_left(&alac->gb) <= 0)
150 /* calculate rice param and decode next value */
151 k = av_log2((history >> 9) + 3);
152 k = FFMIN(k, alac->rice_limit);
153 x = decode_scalar(&alac->gb, k, bps);
156 output_buffer[i] = (x >> 1) ^ -(x & 1);
158 /* update the history */
162 history += x * rice_history_mult -
163 ((history * rice_history_mult) >> 9);
165 /* special case: there may be compressed blocks of 0 */
166 if ((history < 128) && (i + 1 < nb_samples)) {
169 /* calculate rice param and decode block size */
170 k = 7 - av_log2(history) + ((history + 16) >> 6);
171 k = FFMIN(k, alac->rice_limit);
172 block_size = decode_scalar(&alac->gb, k, 16);
174 if (block_size > 0) {
175 if (block_size >= nb_samples - i) {
176 av_log(alac->avctx, AV_LOG_ERROR,
177 "invalid zero block size of %d %d %d\n", block_size,
179 block_size = nb_samples - i - 1;
181 memset(&output_buffer[i + 1], 0,
182 block_size * sizeof(*output_buffer));
185 if (block_size <= 0xffff)
193 static inline int sign_only(int v)
195 return v ? FFSIGN(v) : 0;
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)
203 int32_t *pred = buffer_out;
205 /* first sample always copies */
206 *buffer_out = *error_buffer;
212 memcpy(&buffer_out[1], &error_buffer[1],
213 (nb_samples - 1) * sizeof(*buffer_out));
217 if (lpc_order == 31) {
218 /* simple 1st-order prediction */
219 for (i = 1; i < nb_samples; i++) {
220 buffer_out[i] = sign_extend(buffer_out[i - 1] + error_buffer[i],
226 /* read warm-up samples */
227 for (i = 1; i <= lpc_order && i < nb_samples; i++)
228 buffer_out[i] = sign_extend(buffer_out[i - 1] + error_buffer[i], bps);
230 /* NOTE: 4 and 8 are very common cases that could be optimized. */
232 for (; i < nb_samples; i++) {
235 int error_val = error_buffer[i];
240 for (j = 0; j < lpc_order; j++)
241 val += (pred[j] - d) * lpc_coefs[j];
242 val = (val + (1 << (lpc_quant - 1))) >> lpc_quant;
243 val += d + error_val;
244 buffer_out[i] = sign_extend(val, bps);
246 /* adapt LPC coefficients */
247 error_sign = sign_only(error_val);
249 for (j = 0; j < lpc_order && error_val * error_sign > 0; j++) {
252 sign = sign_only(val) * error_sign;
253 lpc_coefs[j] -= sign;
255 error_val -= (val >> lpc_quant) * (j + 1);
261 static void decorrelate_stereo(int32_t *buffer[2], int nb_samples,
262 int decorr_shift, int decorr_left_weight)
266 for (i = 0; i < nb_samples; i++) {
272 a -= (b * decorr_left_weight) >> decorr_shift;
280 static void append_extra_bits(int32_t *buffer[2], int32_t *extra_bits_buffer[2],
281 int extra_bits, int channels, int nb_samples)
285 for (ch = 0; ch < channels; ch++)
286 for (i = 0; i < nb_samples; i++)
287 buffer[ch][i] = (buffer[ch][i] << extra_bits) | extra_bits_buffer[ch][i];
290 static int decode_element(AVCodecContext *avctx, void *data, int ch_index,
293 ALACContext *alac = avctx->priv_data;
294 int has_size, bps, is_compressed, decorr_shift, decorr_left_weight, ret;
295 uint32_t output_samples;
298 skip_bits(&alac->gb, 4); /* element instance tag */
299 skip_bits(&alac->gb, 12); /* unused header bits */
301 /* the number of output samples is stored in the frame */
302 has_size = get_bits1(&alac->gb);
304 alac->extra_bits = get_bits(&alac->gb, 2) << 3;
305 bps = alac->sample_size - alac->extra_bits + channels - 1;
307 av_log(avctx, AV_LOG_ERROR, "bps is unsupported: %d\n", bps);
308 return AVERROR_PATCHWELCOME;
311 /* whether the frame is compressed */
312 is_compressed = !get_bits1(&alac->gb);
315 output_samples = get_bits_long(&alac->gb, 32);
317 output_samples = alac->max_samples_per_frame;
318 if (!output_samples || output_samples > alac->max_samples_per_frame) {
319 av_log(avctx, AV_LOG_ERROR, "invalid samples per frame: %d\n",
321 return AVERROR_INVALIDDATA;
323 if (!alac->nb_samples) {
324 /* get output buffer */
325 alac->frame.nb_samples = output_samples;
326 if ((ret = avctx->get_buffer(avctx, &alac->frame)) < 0) {
327 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
330 } else if (output_samples != alac->nb_samples) {
331 av_log(avctx, AV_LOG_ERROR, "sample count mismatch: %u != %d\n",
332 output_samples, alac->nb_samples);
333 return AVERROR_INVALIDDATA;
335 alac->nb_samples = output_samples;
336 if (alac->direct_output) {
337 for (ch = 0; ch < channels; ch++)
338 alac->output_samples_buffer[ch] = (int32_t *)alac->frame.extended_data[ch_index + ch];
342 int16_t lpc_coefs[2][32];
344 int prediction_type[2];
346 int rice_history_mult[2];
348 decorr_shift = get_bits(&alac->gb, 8);
349 decorr_left_weight = get_bits(&alac->gb, 8);
351 for (ch = 0; ch < channels; ch++) {
352 prediction_type[ch] = get_bits(&alac->gb, 4);
353 lpc_quant[ch] = get_bits(&alac->gb, 4);
354 rice_history_mult[ch] = get_bits(&alac->gb, 3);
355 lpc_order[ch] = get_bits(&alac->gb, 5);
357 /* read the predictor table */
358 for (i = lpc_order[ch] - 1; i >= 0; i--)
359 lpc_coefs[ch][i] = get_sbits(&alac->gb, 16);
362 if (alac->extra_bits) {
363 for (i = 0; i < alac->nb_samples; i++) {
364 if(get_bits_left(&alac->gb) <= 0)
366 for (ch = 0; ch < channels; ch++)
367 alac->extra_bits_buffer[ch][i] = get_bits(&alac->gb, alac->extra_bits);
370 for (ch = 0; ch < channels; ch++) {
371 int ret=rice_decompress(alac, alac->predict_error_buffer[ch],
372 alac->nb_samples, bps,
373 rice_history_mult[ch] * alac->rice_history_mult / 4);
377 /* adaptive FIR filter */
378 if (prediction_type[ch] == 15) {
379 /* Prediction type 15 runs the adaptive FIR twice.
380 * The first pass uses the special-case coef_num = 31, while
381 * the second pass uses the coefs from the bitstream.
383 * However, this prediction type is not currently used by the
386 lpc_prediction(alac->predict_error_buffer[ch],
387 alac->predict_error_buffer[ch],
388 alac->nb_samples, bps, NULL, 31, 0);
389 } else if (prediction_type[ch] > 0) {
390 av_log(avctx, AV_LOG_WARNING, "unknown prediction type: %i\n",
391 prediction_type[ch]);
393 lpc_prediction(alac->predict_error_buffer[ch],
394 alac->output_samples_buffer[ch], alac->nb_samples,
395 bps, lpc_coefs[ch], lpc_order[ch], lpc_quant[ch]);
398 /* not compressed, easy case */
399 for (i = 0; i < alac->nb_samples; i++) {
400 if(get_bits_left(&alac->gb) <= 0)
402 for (ch = 0; ch < channels; ch++) {
403 alac->output_samples_buffer[ch][i] =
404 get_sbits_long(&alac->gb, alac->sample_size);
407 alac->extra_bits = 0;
409 decorr_left_weight = 0;
412 if (channels == 2 && decorr_left_weight) {
413 decorrelate_stereo(alac->output_samples_buffer, alac->nb_samples,
414 decorr_shift, decorr_left_weight);
417 if (alac->extra_bits) {
418 append_extra_bits(alac->output_samples_buffer, alac->extra_bits_buffer,
419 alac->extra_bits, channels, alac->nb_samples);
422 if(av_sample_fmt_is_planar(avctx->sample_fmt)) {
423 switch(alac->sample_size) {
425 for (ch = 0; ch < channels; ch++) {
426 int16_t *outbuffer = (int16_t *)alac->frame.extended_data[ch_index + ch];
427 for (i = 0; i < alac->nb_samples; i++)
428 *outbuffer++ = alac->output_samples_buffer[ch][i];
432 for (ch = 0; ch < channels; ch++) {
433 for (i = 0; i < alac->nb_samples; i++)
434 alac->output_samples_buffer[ch][i] <<= 8;
439 switch(alac->sample_size) {
441 int16_t *outbuffer = ((int16_t *)alac->frame.extended_data[0]) + ch_index;
442 for (i = 0; i < alac->nb_samples; i++) {
443 for (ch = 0; ch < channels; ch++)
444 *outbuffer++ = alac->output_samples_buffer[ch][i];
445 outbuffer += alac->channels - channels;
450 int32_t *outbuffer = ((int32_t *)alac->frame.extended_data[0]) + ch_index;
451 for (i = 0; i < alac->nb_samples; i++) {
452 for (ch = 0; ch < channels; ch++)
453 *outbuffer++ = alac->output_samples_buffer[ch][i] << 8;
454 outbuffer += alac->channels - channels;
459 int32_t *outbuffer = ((int32_t *)alac->frame.extended_data[0]) + ch_index;
460 for (i = 0; i < alac->nb_samples; i++) {
461 for (ch = 0; ch < channels; ch++)
462 *outbuffer++ = alac->output_samples_buffer[ch][i];
463 outbuffer += alac->channels - channels;
473 static int alac_decode_frame(AVCodecContext *avctx, void *data,
474 int *got_frame_ptr, AVPacket *avpkt)
476 ALACContext *alac = avctx->priv_data;
477 enum RawDataBlockType element;
479 int ch, ret, got_end;
481 init_get_bits(&alac->gb, avpkt->data, avpkt->size * 8);
484 alac->nb_samples = 0;
486 while (get_bits_left(&alac->gb) >= 3) {
487 element = get_bits(&alac->gb, 3);
488 if (element == TYPE_END) {
492 if (element > TYPE_CPE && element != TYPE_LFE) {
493 av_log(avctx, AV_LOG_ERROR, "syntax element unsupported: %d\n", element);
494 return AVERROR_PATCHWELCOME;
497 channels = (element == TYPE_CPE) ? 2 : 1;
498 if ( ch + channels > alac->channels
499 || alac_channel_layout_offsets[alac->channels - 1][ch] + channels > alac->channels
501 av_log(avctx, AV_LOG_ERROR, "invalid element channel count\n");
502 return AVERROR_INVALIDDATA;
505 ret = decode_element(avctx, data,
506 alac_channel_layout_offsets[alac->channels - 1][ch],
508 if (ret < 0 && get_bits_left(&alac->gb))
514 av_log(avctx, AV_LOG_ERROR, "no end tag found. incomplete packet.\n");
515 return AVERROR_INVALIDDATA;
518 if (avpkt->size * 8 - get_bits_count(&alac->gb) > 8) {
519 av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n",
520 avpkt->size * 8 - get_bits_count(&alac->gb));
524 *(AVFrame *)data = alac->frame;
529 static av_cold int alac_decode_close(AVCodecContext *avctx)
531 ALACContext *alac = avctx->priv_data;
534 for (ch = 0; ch < FFMIN(alac->channels, 2); ch++) {
535 av_freep(&alac->predict_error_buffer[ch]);
536 if (!alac->direct_output)
537 av_freep(&alac->output_samples_buffer[ch]);
538 av_freep(&alac->extra_bits_buffer[ch]);
544 static int allocate_buffers(ALACContext *alac)
549 if (alac->max_samples_per_frame > INT_MAX / sizeof(int32_t))
551 buf_size = alac->max_samples_per_frame * sizeof(int32_t);
553 for (ch = 0; ch < FFMIN(alac->channels, 2); ch++) {
554 FF_ALLOC_OR_GOTO(alac->avctx, alac->predict_error_buffer[ch],
555 buf_size, buf_alloc_fail);
557 alac->direct_output = alac->sample_size > 16 && av_sample_fmt_is_planar(alac->avctx->sample_fmt);
558 if (!alac->direct_output) {
559 FF_ALLOC_OR_GOTO(alac->avctx, alac->output_samples_buffer[ch],
560 buf_size, buf_alloc_fail);
563 FF_ALLOC_OR_GOTO(alac->avctx, alac->extra_bits_buffer[ch],
564 buf_size, buf_alloc_fail);
568 alac_decode_close(alac->avctx);
569 return AVERROR(ENOMEM);
572 static int alac_set_info(ALACContext *alac)
576 bytestream2_init(&gb, alac->avctx->extradata,
577 alac->avctx->extradata_size);
579 bytestream2_skipu(&gb, 12); // size:4, alac:4, version:4
581 alac->max_samples_per_frame = bytestream2_get_be32u(&gb);
582 if (!alac->max_samples_per_frame || alac->max_samples_per_frame > INT_MAX) {
583 av_log(alac->avctx, AV_LOG_ERROR, "max samples per frame invalid: %u\n",
584 alac->max_samples_per_frame);
585 return AVERROR_INVALIDDATA;
587 bytestream2_skipu(&gb, 1); // compatible version
588 alac->sample_size = bytestream2_get_byteu(&gb);
589 alac->rice_history_mult = bytestream2_get_byteu(&gb);
590 alac->rice_initial_history = bytestream2_get_byteu(&gb);
591 alac->rice_limit = bytestream2_get_byteu(&gb);
592 alac->channels = bytestream2_get_byteu(&gb);
593 bytestream2_get_be16u(&gb); // maxRun
594 bytestream2_get_be32u(&gb); // max coded frame size
595 bytestream2_get_be32u(&gb); // average bitrate
596 bytestream2_get_be32u(&gb); // samplerate
601 static av_cold int alac_decode_init(AVCodecContext * avctx)
605 ALACContext *alac = avctx->priv_data;
608 /* initialize from the extradata */
609 if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
610 av_log(avctx, AV_LOG_ERROR, "expected %d extradata bytes\n",
611 ALAC_EXTRADATA_SIZE);
614 if (alac_set_info(alac)) {
615 av_log(avctx, AV_LOG_ERROR, "set_info failed\n");
619 req_packed = LIBAVCODEC_VERSION_MAJOR < 55 && !av_sample_fmt_is_planar(avctx->request_sample_fmt);
620 switch (alac->sample_size) {
621 case 16: avctx->sample_fmt = req_packed ? AV_SAMPLE_FMT_S16 : AV_SAMPLE_FMT_S16P;
624 case 32: avctx->sample_fmt = req_packed ? AV_SAMPLE_FMT_S32 : AV_SAMPLE_FMT_S32P;
626 default: av_log_ask_for_sample(avctx, "Sample depth %d is not supported.\n",
628 return AVERROR_PATCHWELCOME;
630 avctx->bits_per_raw_sample = alac->sample_size;
632 if (alac->channels < 1) {
633 av_log(avctx, AV_LOG_WARNING, "Invalid channel count\n");
634 alac->channels = avctx->channels;
636 if (alac->channels > MAX_CHANNELS)
637 alac->channels = avctx->channels;
639 avctx->channels = alac->channels;
641 if (avctx->channels > MAX_CHANNELS) {
642 av_log(avctx, AV_LOG_ERROR, "Unsupported channel count: %d\n",
644 return AVERROR_PATCHWELCOME;
646 avctx->channel_layout = alac_channel_layouts[alac->channels - 1];
648 if ((ret = allocate_buffers(alac)) < 0) {
649 av_log(avctx, AV_LOG_ERROR, "Error allocating buffers\n");
653 avcodec_get_frame_defaults(&alac->frame);
654 avctx->coded_frame = &alac->frame;
659 AVCodec ff_alac_decoder = {
661 .type = AVMEDIA_TYPE_AUDIO,
662 .id = AV_CODEC_ID_ALAC,
663 .priv_data_size = sizeof(ALACContext),
664 .init = alac_decode_init,
665 .close = alac_decode_close,
666 .decode = alac_decode_frame,
667 .capabilities = CODEC_CAP_DR1,
668 .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),