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/audioconvert.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)
204 /* first sample always copies */
205 *buffer_out = *error_buffer;
211 memcpy(&buffer_out[1], &error_buffer[1],
212 (nb_samples - 1) * sizeof(*buffer_out));
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],
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],
231 /* NOTE: 4 and 8 are very common cases that could be optimized. */
233 for (i = lpc_order; i < nb_samples - 1; i++) {
236 int error_val = error_buffer[i + 1];
238 int d = buffer_out[i - lpc_order];
241 for (j = 0; j < lpc_order; j++)
242 val += (buffer_out[i - j] - d) * lpc_coefs[j];
243 val = (val + (1 << (lpc_quant - 1))) >> lpc_quant;
244 val += d + error_val;
245 buffer_out[i + 1] = sign_extend(val, bps);
247 /* adapt LPC coefficients */
248 error_sign = sign_only(error_val);
250 for (j = lpc_order - 1; j >= 0 && error_val * error_sign > 0; j--) {
252 val = d - buffer_out[i - j];
253 sign = sign_only(val) * error_sign;
254 lpc_coefs[j] -= sign;
256 error_val -= (val >> lpc_quant) * (lpc_order - j);
262 static void decorrelate_stereo(int32_t *buffer[2], int nb_samples,
263 int decorr_shift, int decorr_left_weight)
267 for (i = 0; i < nb_samples; i++) {
273 a -= (b * decorr_left_weight) >> decorr_shift;
281 static void append_extra_bits(int32_t *buffer[2], int32_t *extra_bits_buffer[2],
282 int extra_bits, int channels, int nb_samples)
286 for (ch = 0; ch < channels; ch++)
287 for (i = 0; i < nb_samples; i++)
288 buffer[ch][i] = (buffer[ch][i] << extra_bits) | extra_bits_buffer[ch][i];
291 static int decode_element(AVCodecContext *avctx, void *data, int ch_index,
294 ALACContext *alac = avctx->priv_data;
295 int has_size, bps, is_compressed, decorr_shift, decorr_left_weight, ret;
296 uint32_t output_samples;
299 skip_bits(&alac->gb, 4); /* element instance tag */
300 skip_bits(&alac->gb, 12); /* unused header bits */
302 /* the number of output samples is stored in the frame */
303 has_size = get_bits1(&alac->gb);
305 alac->extra_bits = get_bits(&alac->gb, 2) << 3;
306 bps = alac->sample_size - alac->extra_bits + channels - 1;
308 av_log(avctx, AV_LOG_ERROR, "bps is unsupported: %d\n", bps);
309 return AVERROR_PATCHWELCOME;
312 /* whether the frame is compressed */
313 is_compressed = !get_bits1(&alac->gb);
316 output_samples = get_bits_long(&alac->gb, 32);
318 output_samples = alac->max_samples_per_frame;
319 if (!output_samples || output_samples > alac->max_samples_per_frame) {
320 av_log(avctx, AV_LOG_ERROR, "invalid samples per frame: %d\n",
322 return AVERROR_INVALIDDATA;
324 if (!alac->nb_samples) {
325 /* get output buffer */
326 alac->frame.nb_samples = output_samples;
327 if ((ret = avctx->get_buffer(avctx, &alac->frame)) < 0) {
328 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
331 } else if (output_samples != alac->nb_samples) {
332 av_log(avctx, AV_LOG_ERROR, "sample count mismatch: %u != %d\n",
333 output_samples, alac->nb_samples);
334 return AVERROR_INVALIDDATA;
336 alac->nb_samples = output_samples;
337 if (alac->direct_output) {
338 for (ch = 0; ch < channels; ch++)
339 alac->output_samples_buffer[ch] = (int32_t *)alac->frame.extended_data[ch_index + ch];
343 int16_t lpc_coefs[2][32];
345 int prediction_type[2];
347 int rice_history_mult[2];
349 decorr_shift = get_bits(&alac->gb, 8);
350 decorr_left_weight = get_bits(&alac->gb, 8);
352 for (ch = 0; ch < channels; ch++) {
353 prediction_type[ch] = get_bits(&alac->gb, 4);
354 lpc_quant[ch] = get_bits(&alac->gb, 4);
355 rice_history_mult[ch] = get_bits(&alac->gb, 3);
356 lpc_order[ch] = get_bits(&alac->gb, 5);
358 /* read the predictor table */
359 for (i = 0; i < lpc_order[ch]; i++)
360 lpc_coefs[ch][i] = get_sbits(&alac->gb, 16);
363 if (alac->extra_bits) {
364 for (i = 0; i < alac->nb_samples; i++) {
365 if(get_bits_left(&alac->gb) <= 0)
367 for (ch = 0; ch < channels; ch++)
368 alac->extra_bits_buffer[ch][i] = get_bits(&alac->gb, alac->extra_bits);
371 for (ch = 0; ch < channels; ch++) {
372 int ret=rice_decompress(alac, alac->predict_error_buffer[ch],
373 alac->nb_samples, bps,
374 rice_history_mult[ch] * alac->rice_history_mult / 4);
378 /* adaptive FIR filter */
379 if (prediction_type[ch] == 15) {
380 /* Prediction type 15 runs the adaptive FIR twice.
381 * The first pass uses the special-case coef_num = 31, while
382 * the second pass uses the coefs from the bitstream.
384 * However, this prediction type is not currently used by the
387 lpc_prediction(alac->predict_error_buffer[ch],
388 alac->predict_error_buffer[ch],
389 alac->nb_samples, bps, NULL, 31, 0);
390 } else if (prediction_type[ch] > 0) {
391 av_log(avctx, AV_LOG_WARNING, "unknown prediction type: %i\n",
392 prediction_type[ch]);
394 lpc_prediction(alac->predict_error_buffer[ch],
395 alac->output_samples_buffer[ch], alac->nb_samples,
396 bps, lpc_coefs[ch], lpc_order[ch], lpc_quant[ch]);
399 /* not compressed, easy case */
400 for (i = 0; i < alac->nb_samples; i++) {
401 if(get_bits_left(&alac->gb) <= 0)
403 for (ch = 0; ch < channels; ch++) {
404 alac->output_samples_buffer[ch][i] =
405 get_sbits_long(&alac->gb, alac->sample_size);
408 alac->extra_bits = 0;
410 decorr_left_weight = 0;
413 if (channels == 2 && decorr_left_weight) {
414 decorrelate_stereo(alac->output_samples_buffer, alac->nb_samples,
415 decorr_shift, decorr_left_weight);
418 if (alac->extra_bits) {
419 append_extra_bits(alac->output_samples_buffer, alac->extra_bits_buffer,
420 alac->extra_bits, channels, alac->nb_samples);
423 if(av_sample_fmt_is_planar(avctx->sample_fmt)) {
424 switch(alac->sample_size) {
426 for (ch = 0; ch < channels; ch++) {
427 int16_t *outbuffer = (int16_t *)alac->frame.extended_data[ch_index + ch];
428 for (i = 0; i < alac->nb_samples; i++)
429 *outbuffer++ = alac->output_samples_buffer[ch][i];
433 for (ch = 0; ch < channels; ch++) {
434 for (i = 0; i < alac->nb_samples; i++)
435 alac->output_samples_buffer[ch][i] <<= 8;
440 switch(alac->sample_size) {
442 int16_t *outbuffer = ((int16_t *)alac->frame.extended_data[0]) + ch_index;
443 for (i = 0; i < alac->nb_samples; i++) {
444 for (ch = 0; ch < channels; ch++)
445 *outbuffer++ = alac->output_samples_buffer[ch][i];
446 outbuffer += alac->channels - channels;
451 int32_t *outbuffer = ((int32_t *)alac->frame.extended_data[0]) + ch_index;
452 for (i = 0; i < alac->nb_samples; i++) {
453 for (ch = 0; ch < channels; ch++)
454 *outbuffer++ = alac->output_samples_buffer[ch][i] << 8;
455 outbuffer += alac->channels - channels;
460 int32_t *outbuffer = ((int32_t *)alac->frame.extended_data[0]) + ch_index;
461 for (i = 0; i < alac->nb_samples; i++) {
462 for (ch = 0; ch < channels; ch++)
463 *outbuffer++ = alac->output_samples_buffer[ch][i];
464 outbuffer += alac->channels - channels;
474 static int alac_decode_frame(AVCodecContext *avctx, void *data,
475 int *got_frame_ptr, AVPacket *avpkt)
477 ALACContext *alac = avctx->priv_data;
478 enum RawDataBlockType element;
482 init_get_bits(&alac->gb, avpkt->data, avpkt->size * 8);
484 alac->nb_samples = 0;
486 while (get_bits_left(&alac->gb)) {
487 element = get_bits(&alac->gb, 3);
488 if (element == TYPE_END)
490 if (element > TYPE_CPE && element != TYPE_LFE) {
491 av_log(avctx, AV_LOG_ERROR, "syntax element unsupported: %d", element);
492 return AVERROR_PATCHWELCOME;
495 channels = (element == TYPE_CPE) ? 2 : 1;
496 if (ch + channels > alac->channels) {
497 av_log(avctx, AV_LOG_ERROR, "invalid element channel count\n");
498 return AVERROR_INVALIDDATA;
501 ret = decode_element(avctx, data,
502 alac_channel_layout_offsets[alac->channels - 1][ch],
510 if (avpkt->size * 8 - get_bits_count(&alac->gb) > 8) {
511 av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n",
512 avpkt->size * 8 - get_bits_count(&alac->gb));
516 *(AVFrame *)data = alac->frame;
521 static av_cold int alac_decode_close(AVCodecContext *avctx)
523 ALACContext *alac = avctx->priv_data;
526 for (ch = 0; ch < FFMIN(alac->channels, 2); ch++) {
527 av_freep(&alac->predict_error_buffer[ch]);
528 if (!alac->direct_output)
529 av_freep(&alac->output_samples_buffer[ch]);
530 av_freep(&alac->extra_bits_buffer[ch]);
536 static int allocate_buffers(ALACContext *alac)
539 int buf_size = alac->max_samples_per_frame * sizeof(int32_t);
541 for (ch = 0; ch < FFMIN(alac->channels, 2); ch++) {
542 FF_ALLOC_OR_GOTO(alac->avctx, alac->predict_error_buffer[ch],
543 buf_size, buf_alloc_fail);
545 alac->direct_output = alac->sample_size > 16 && av_sample_fmt_is_planar(alac->avctx->sample_fmt);
546 if (!alac->direct_output) {
547 FF_ALLOC_OR_GOTO(alac->avctx, alac->output_samples_buffer[ch],
548 buf_size, buf_alloc_fail);
551 FF_ALLOC_OR_GOTO(alac->avctx, alac->extra_bits_buffer[ch],
552 buf_size, buf_alloc_fail);
556 alac_decode_close(alac->avctx);
557 return AVERROR(ENOMEM);
560 static int alac_set_info(ALACContext *alac)
564 bytestream2_init(&gb, alac->avctx->extradata,
565 alac->avctx->extradata_size);
567 bytestream2_skipu(&gb, 12); // size:4, alac:4, version:4
569 alac->max_samples_per_frame = bytestream2_get_be32u(&gb);
570 if (!alac->max_samples_per_frame || alac->max_samples_per_frame > INT_MAX) {
571 av_log(alac->avctx, AV_LOG_ERROR, "max samples per frame invalid: %u\n",
572 alac->max_samples_per_frame);
573 return AVERROR_INVALIDDATA;
575 bytestream2_skipu(&gb, 1); // compatible version
576 alac->sample_size = bytestream2_get_byteu(&gb);
577 alac->rice_history_mult = bytestream2_get_byteu(&gb);
578 alac->rice_initial_history = bytestream2_get_byteu(&gb);
579 alac->rice_limit = bytestream2_get_byteu(&gb);
580 alac->channels = bytestream2_get_byteu(&gb);
581 bytestream2_get_be16u(&gb); // maxRun
582 bytestream2_get_be32u(&gb); // max coded frame size
583 bytestream2_get_be32u(&gb); // average bitrate
584 bytestream2_get_be32u(&gb); // samplerate
589 static av_cold int alac_decode_init(AVCodecContext * avctx)
593 ALACContext *alac = avctx->priv_data;
596 /* initialize from the extradata */
597 if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
598 av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
599 ALAC_EXTRADATA_SIZE);
602 if (alac_set_info(alac)) {
603 av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
607 req_packed = LIBAVCODEC_VERSION_MAJOR < 55 && !av_sample_fmt_is_planar(avctx->request_sample_fmt);
608 switch (alac->sample_size) {
609 case 16: avctx->sample_fmt = req_packed ? AV_SAMPLE_FMT_S16 : AV_SAMPLE_FMT_S16P;
612 case 32: avctx->sample_fmt = req_packed ? AV_SAMPLE_FMT_S32 : AV_SAMPLE_FMT_S32P;
614 default: av_log_ask_for_sample(avctx, "Sample depth %d is not supported.\n",
616 return AVERROR_PATCHWELCOME;
619 if (alac->channels < 1) {
620 av_log(avctx, AV_LOG_WARNING, "Invalid channel count\n");
621 alac->channels = avctx->channels;
623 if (alac->channels > MAX_CHANNELS)
624 alac->channels = avctx->channels;
626 avctx->channels = alac->channels;
628 if (avctx->channels > MAX_CHANNELS) {
629 av_log(avctx, AV_LOG_ERROR, "Unsupported channel count: %d\n",
631 return AVERROR_PATCHWELCOME;
633 avctx->channel_layout = alac_channel_layouts[alac->channels - 1];
635 if ((ret = allocate_buffers(alac)) < 0) {
636 av_log(avctx, AV_LOG_ERROR, "Error allocating buffers\n");
640 avcodec_get_frame_defaults(&alac->frame);
641 avctx->coded_frame = &alac->frame;
646 AVCodec ff_alac_decoder = {
648 .type = AVMEDIA_TYPE_AUDIO,
650 .priv_data_size = sizeof(ALACContext),
651 .init = alac_decode_init,
652 .close = alac_decode_close,
653 .decode = alac_decode_frame,
654 .capabilities = CODEC_CAP_DR1,
655 .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),