2 * ALAC (Apple Lossless Audio Codec) decoder
3 * Copyright (c) 2005 David Hammerton
5 * This file is part of Libav.
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.
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.
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
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 */
78 enum RawDataBlockType {
79 /* At the moment, only SCE, CPE, LFE, and END are recognized. */
90 static const uint8_t alac_channel_layout_offsets[8][8] = {
97 { 2, 0, 1, 4, 5, 6, 3 },
98 { 2, 6, 7, 0, 1, 4, 5, 3 }
101 static const uint16_t alac_channel_layouts[8] = {
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
112 static inline unsigned int decode_scalar(GetBitContext *gb, int k, int bps)
114 unsigned int x = get_unary_0_9(gb);
116 if (x > 8) { /* RICE THRESHOLD */
117 /* use alternative encoding */
118 x = get_bits_long(gb, bps);
120 int extrabits = show_bits(gb, k);
122 /* multiply x by 2^k - 1, as part of their strange algorithm */
129 skip_bits(gb, k - 1);
134 static void rice_decompress(ALACContext *alac, int32_t *output_buffer,
135 int nb_samples, int bps, int rice_history_mult)
138 unsigned int history = alac->rice_initial_history;
139 int sign_modifier = 0;
141 for (i = 0; i < nb_samples; i++) {
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);
151 output_buffer[i] = (x >> 1) ^ -(x & 1);
153 /* update the history */
157 history += x * rice_history_mult -
158 ((history * rice_history_mult) >> 9);
160 /* special case: there may be compressed blocks of 0 */
161 if ((history < 128) && (i + 1 < nb_samples)) {
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);
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,
174 block_size = nb_samples - i - 1;
176 memset(&output_buffer[i + 1], 0,
177 block_size * sizeof(*output_buffer));
180 if (block_size <= 0xffff)
187 static inline int sign_only(int v)
189 return v ? FFSIGN(v) : 0;
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)
198 /* first sample always copies */
199 *buffer_out = *error_buffer;
205 memcpy(&buffer_out[1], &error_buffer[1],
206 (nb_samples - 1) * sizeof(*buffer_out));
210 if (lpc_order == 31) {
211 /* simple 1st-order prediction */
212 for (i = 1; i < nb_samples; i++) {
213 buffer_out[i] = sign_extend(buffer_out[i - 1] + error_buffer[i],
219 /* read warm-up samples */
220 for (i = 0; i < lpc_order; i++) {
221 buffer_out[i + 1] = sign_extend(buffer_out[i] + error_buffer[i + 1],
225 /* NOTE: 4 and 8 are very common cases that could be optimized. */
227 for (i = lpc_order; i < nb_samples - 1; i++) {
230 int error_val = error_buffer[i + 1];
232 int d = buffer_out[i - lpc_order];
235 for (j = 0; j < lpc_order; j++)
236 val += (buffer_out[i - j] - d) * lpc_coefs[j];
237 val = (val + (1 << (lpc_quant - 1))) >> lpc_quant;
238 val += d + error_val;
239 buffer_out[i + 1] = sign_extend(val, bps);
241 /* adapt LPC coefficients */
242 error_sign = sign_only(error_val);
244 for (j = lpc_order - 1; j >= 0 && error_val * error_sign > 0; j--) {
246 val = d - buffer_out[i - j];
247 sign = sign_only(val) * error_sign;
248 lpc_coefs[j] -= sign;
250 error_val -= (val >> lpc_quant) * (lpc_order - j);
256 static void decorrelate_stereo(int32_t *buffer[2], int nb_samples,
257 int decorr_shift, int decorr_left_weight)
261 for (i = 0; i < nb_samples; i++) {
267 a -= (b * decorr_left_weight) >> decorr_shift;
275 static void append_extra_bits(int32_t *buffer[2], int32_t *extra_bits_buffer[2],
276 int extra_bits, int channels, int nb_samples)
280 for (ch = 0; ch < channels; ch++)
281 for (i = 0; i < nb_samples; i++)
282 buffer[ch][i] = (buffer[ch][i] << extra_bits) | extra_bits_buffer[ch][i];
285 static int decode_element(AVCodecContext *avctx, void *data, int ch_index,
288 ALACContext *alac = avctx->priv_data;
289 int has_size, bps, is_compressed, decorr_shift, decorr_left_weight, ret;
290 uint32_t output_samples;
293 skip_bits(&alac->gb, 4); /* element instance tag */
294 skip_bits(&alac->gb, 12); /* unused header bits */
296 /* the number of output samples is stored in the frame */
297 has_size = get_bits1(&alac->gb);
299 alac->extra_bits = get_bits(&alac->gb, 2) << 3;
300 bps = alac->sample_size - alac->extra_bits + channels - 1;
302 av_log(avctx, AV_LOG_ERROR, "bps is unsupported: %d\n", bps);
303 return AVERROR_PATCHWELCOME;
306 /* whether the frame is compressed */
307 is_compressed = !get_bits1(&alac->gb);
310 output_samples = get_bits_long(&alac->gb, 32);
312 output_samples = alac->max_samples_per_frame;
313 if (!output_samples || output_samples > alac->max_samples_per_frame) {
314 av_log(avctx, AV_LOG_ERROR, "invalid samples per frame: %d\n",
316 return AVERROR_INVALIDDATA;
318 if (!alac->nb_samples) {
319 /* get output buffer */
320 alac->frame.nb_samples = output_samples;
321 if ((ret = avctx->get_buffer(avctx, &alac->frame)) < 0) {
322 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
325 if (alac->sample_size > 16) {
326 for (ch = 0; ch < channels; ch++)
327 alac->output_samples_buffer[ch] = (int32_t *)alac->frame.extended_data[ch_index + ch];
329 } else if (output_samples != alac->nb_samples) {
330 av_log(avctx, AV_LOG_ERROR, "sample count mismatch: %u != %d\n",
331 output_samples, alac->nb_samples);
332 return AVERROR_INVALIDDATA;
334 alac->nb_samples = output_samples;
337 int16_t lpc_coefs[2][32];
339 int prediction_type[2];
341 int rice_history_mult[2];
343 decorr_shift = get_bits(&alac->gb, 8);
344 decorr_left_weight = get_bits(&alac->gb, 8);
346 for (ch = 0; ch < channels; ch++) {
347 prediction_type[ch] = get_bits(&alac->gb, 4);
348 lpc_quant[ch] = get_bits(&alac->gb, 4);
349 rice_history_mult[ch] = get_bits(&alac->gb, 3);
350 lpc_order[ch] = get_bits(&alac->gb, 5);
352 /* read the predictor table */
353 for (i = 0; i < lpc_order[ch]; i++)
354 lpc_coefs[ch][i] = get_sbits(&alac->gb, 16);
357 if (alac->extra_bits) {
358 for (i = 0; i < alac->nb_samples; i++) {
359 for (ch = 0; ch < channels; ch++)
360 alac->extra_bits_buffer[ch][i] = get_bits(&alac->gb, alac->extra_bits);
363 for (ch = 0; ch < channels; ch++) {
364 rice_decompress(alac, alac->predict_error_buffer[ch],
365 alac->nb_samples, bps,
366 rice_history_mult[ch] * alac->rice_history_mult / 4);
368 /* adaptive FIR filter */
369 if (prediction_type[ch] == 15) {
370 /* Prediction type 15 runs the adaptive FIR twice.
371 * The first pass uses the special-case coef_num = 31, while
372 * the second pass uses the coefs from the bitstream.
374 * However, this prediction type is not currently used by the
377 lpc_prediction(alac->predict_error_buffer[ch],
378 alac->predict_error_buffer[ch],
379 alac->nb_samples, bps, NULL, 31, 0);
380 } else if (prediction_type[ch] > 0) {
381 av_log(avctx, AV_LOG_WARNING, "unknown prediction type: %i\n",
382 prediction_type[ch]);
384 lpc_prediction(alac->predict_error_buffer[ch],
385 alac->output_samples_buffer[ch], alac->nb_samples,
386 bps, lpc_coefs[ch], lpc_order[ch], lpc_quant[ch]);
389 /* not compressed, easy case */
390 for (i = 0; i < alac->nb_samples; i++) {
391 for (ch = 0; ch < channels; ch++) {
392 alac->output_samples_buffer[ch][i] =
393 get_sbits_long(&alac->gb, alac->sample_size);
396 alac->extra_bits = 0;
398 decorr_left_weight = 0;
401 if (channels == 2 && decorr_left_weight) {
402 decorrelate_stereo(alac->output_samples_buffer, alac->nb_samples,
403 decorr_shift, decorr_left_weight);
406 if (alac->extra_bits) {
407 append_extra_bits(alac->output_samples_buffer, alac->extra_bits_buffer,
408 alac->extra_bits, channels, alac->nb_samples);
411 switch(alac->sample_size) {
413 for (ch = 0; ch < channels; ch++) {
414 int16_t *outbuffer = (int16_t *)alac->frame.extended_data[ch_index + ch];
415 for (i = 0; i < alac->nb_samples; i++)
416 *outbuffer++ = alac->output_samples_buffer[ch][i];
420 for (ch = 0; ch < channels; ch++) {
421 for (i = 0; i < alac->nb_samples; i++)
422 alac->output_samples_buffer[ch][i] <<= 8;
430 static int alac_decode_frame(AVCodecContext *avctx, void *data,
431 int *got_frame_ptr, AVPacket *avpkt)
433 ALACContext *alac = avctx->priv_data;
434 enum RawDataBlockType element;
438 init_get_bits(&alac->gb, avpkt->data, avpkt->size * 8);
440 alac->nb_samples = 0;
442 while (get_bits_left(&alac->gb)) {
443 element = get_bits(&alac->gb, 3);
444 if (element == TYPE_END)
446 if (element > TYPE_CPE && element != TYPE_LFE) {
447 av_log(avctx, AV_LOG_ERROR, "syntax element unsupported: %d", element);
448 return AVERROR_PATCHWELCOME;
451 channels = (element == TYPE_CPE) ? 2 : 1;
452 if (ch + channels > alac->channels) {
453 av_log(avctx, AV_LOG_ERROR, "invalid element channel count\n");
454 return AVERROR_INVALIDDATA;
457 ret = decode_element(avctx, data,
458 alac_channel_layout_offsets[alac->channels - 1][ch],
466 if (avpkt->size * 8 - get_bits_count(&alac->gb) > 8) {
467 av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n",
468 avpkt->size * 8 - get_bits_count(&alac->gb));
472 *(AVFrame *)data = alac->frame;
477 static av_cold int alac_decode_close(AVCodecContext *avctx)
479 ALACContext *alac = avctx->priv_data;
482 for (ch = 0; ch < FFMIN(alac->channels, 2); ch++) {
483 av_freep(&alac->predict_error_buffer[ch]);
484 if (alac->sample_size == 16)
485 av_freep(&alac->output_samples_buffer[ch]);
486 av_freep(&alac->extra_bits_buffer[ch]);
492 static int allocate_buffers(ALACContext *alac)
495 int buf_size = alac->max_samples_per_frame * sizeof(int32_t);
497 for (ch = 0; ch < FFMIN(alac->channels, 2); ch++) {
498 FF_ALLOC_OR_GOTO(alac->avctx, alac->predict_error_buffer[ch],
499 buf_size, buf_alloc_fail);
501 if (alac->sample_size == 16) {
502 FF_ALLOC_OR_GOTO(alac->avctx, alac->output_samples_buffer[ch],
503 buf_size, buf_alloc_fail);
506 FF_ALLOC_OR_GOTO(alac->avctx, alac->extra_bits_buffer[ch],
507 buf_size, buf_alloc_fail);
511 alac_decode_close(alac->avctx);
512 return AVERROR(ENOMEM);
515 static int alac_set_info(ALACContext *alac)
519 bytestream2_init(&gb, alac->avctx->extradata,
520 alac->avctx->extradata_size);
522 bytestream2_skipu(&gb, 12); // size:4, alac:4, version:4
524 alac->max_samples_per_frame = bytestream2_get_be32u(&gb);
525 if (!alac->max_samples_per_frame || alac->max_samples_per_frame > INT_MAX) {
526 av_log(alac->avctx, AV_LOG_ERROR, "max samples per frame invalid: %u\n",
527 alac->max_samples_per_frame);
528 return AVERROR_INVALIDDATA;
530 bytestream2_skipu(&gb, 1); // compatible version
531 alac->sample_size = bytestream2_get_byteu(&gb);
532 alac->rice_history_mult = bytestream2_get_byteu(&gb);
533 alac->rice_initial_history = bytestream2_get_byteu(&gb);
534 alac->rice_limit = bytestream2_get_byteu(&gb);
535 alac->channels = bytestream2_get_byteu(&gb);
536 bytestream2_get_be16u(&gb); // maxRun
537 bytestream2_get_be32u(&gb); // max coded frame size
538 bytestream2_get_be32u(&gb); // average bitrate
539 bytestream2_get_be32u(&gb); // samplerate
544 static av_cold int alac_decode_init(AVCodecContext * avctx)
547 ALACContext *alac = avctx->priv_data;
550 /* initialize from the extradata */
551 if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
552 av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
553 ALAC_EXTRADATA_SIZE);
556 if (alac_set_info(alac)) {
557 av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
561 switch (alac->sample_size) {
562 case 16: avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
565 case 32: avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
567 default: av_log_ask_for_sample(avctx, "Sample depth %d is not supported.\n",
569 return AVERROR_PATCHWELCOME;
572 if (alac->channels < 1) {
573 av_log(avctx, AV_LOG_WARNING, "Invalid channel count\n");
574 alac->channels = avctx->channels;
576 if (alac->channels > MAX_CHANNELS)
577 alac->channels = avctx->channels;
579 avctx->channels = alac->channels;
581 if (avctx->channels > MAX_CHANNELS) {
582 av_log(avctx, AV_LOG_ERROR, "Unsupported channel count: %d\n",
584 return AVERROR_PATCHWELCOME;
586 avctx->channel_layout = alac_channel_layouts[alac->channels - 1];
588 if ((ret = allocate_buffers(alac)) < 0) {
589 av_log(avctx, AV_LOG_ERROR, "Error allocating buffers\n");
593 avcodec_get_frame_defaults(&alac->frame);
594 avctx->coded_frame = &alac->frame;
599 AVCodec ff_alac_decoder = {
601 .type = AVMEDIA_TYPE_AUDIO,
603 .priv_data_size = sizeof(ALACContext),
604 .init = alac_decode_init,
605 .close = alac_decode_close,
606 .decode = alac_decode_frame,
607 .capabilities = CODEC_CAP_DR1,
608 .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),