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)
51 #include "bytestream.h"
55 #define ALAC_EXTRADATA_SIZE 36
56 #define MAX_CHANNELS 2
60 AVCodecContext *avctx;
67 int32_t *predict_error_buffer[MAX_CHANNELS];
68 int32_t *output_samples_buffer[MAX_CHANNELS];
69 int32_t *extra_bits_buffer[MAX_CHANNELS];
71 uint32_t max_samples_per_frame;
73 uint8_t rice_history_mult;
74 uint8_t rice_initial_history;
77 int extra_bits; /**< number of extra bits beyond 16-bit */
78 int nb_samples; /**< number of samples in the current frame */
81 static inline int decode_scalar(GetBitContext *gb, int k, int readsamplesize)
83 int x = get_unary_0_9(gb);
85 if (x > 8) { /* RICE THRESHOLD */
86 /* use alternative encoding */
87 x = get_bits(gb, readsamplesize);
89 int extrabits = show_bits(gb, k);
91 /* multiply x by 2^k - 1, as part of their strange algorithm */
103 static void bastardized_rice_decompress(ALACContext *alac,
104 int32_t *output_buffer,
107 int rice_history_mult)
110 unsigned int history = alac->rice_initial_history;
111 int sign_modifier = 0;
113 for (output_count = 0; output_count < output_size; output_count++) {
116 /* read k, that is bits as is */
117 k = av_log2((history >> 9) + 3);
118 k = FFMIN(k, alac->rice_limit);
119 x = decode_scalar(&alac->gb, k, readsamplesize);
123 output_buffer[output_count] = (x >> 1) ^ -(x & 1);
125 /* now update the history */
129 history += x * rice_history_mult -
130 ((history * rice_history_mult) >> 9);
132 /* special case: there may be compressed blocks of 0 */
133 if ((history < 128) && (output_count+1 < output_size)) {
136 k = 7 - av_log2(history) + ((history + 16) >> 6 /* / 64 */);
137 k = FFMIN(k, alac->rice_limit);
139 block_size = decode_scalar(&alac->gb, k, 16);
141 if (block_size > 0) {
142 if(block_size >= output_size - output_count){
143 av_log(alac->avctx, AV_LOG_ERROR, "invalid zero block size of %d %d %d\n", block_size, output_size, output_count);
144 block_size= output_size - output_count - 1;
146 memset(&output_buffer[output_count + 1], 0,
147 block_size * sizeof(*output_buffer));
148 output_count += block_size;
151 if (block_size <= 0xffff)
159 static inline int sign_only(int v)
161 return v ? FFSIGN(v) : 0;
164 static void predictor_decompress_fir_adapt(int32_t *error_buffer,
168 int16_t *predictor_coef_table,
169 int predictor_coef_num,
170 int predictor_quantitization)
174 /* first sample always copies */
175 *buffer_out = *error_buffer;
177 if (output_size <= 1)
180 if (!predictor_coef_num) {
181 memcpy(&buffer_out[1], &error_buffer[1],
182 (output_size - 1) * sizeof(*buffer_out));
186 if (predictor_coef_num == 31) {
187 /* simple 1st-order prediction */
188 for (i = 1; i < output_size; i++) {
189 buffer_out[i] = sign_extend(buffer_out[i - 1] + error_buffer[i],
195 /* read warm-up samples */
196 for (i = 0; i < predictor_coef_num; i++) {
197 buffer_out[i + 1] = sign_extend(buffer_out[i] + error_buffer[i + 1],
201 /* NOTE: 4 and 8 are very common cases that could be optimized. */
204 for (i = predictor_coef_num; i < output_size - 1; i++) {
207 int error_val = error_buffer[i + 1];
209 int d = buffer_out[i - predictor_coef_num];
211 for (j = 0; j < predictor_coef_num; j++) {
212 val += (buffer_out[i - j] - d) *
213 predictor_coef_table[j];
216 val = (val + (1 << (predictor_quantitization - 1))) >>
217 predictor_quantitization;
218 val += d + error_val;
220 buffer_out[i + 1] = sign_extend(val, readsamplesize);
222 /* adapt LPC coefficients */
223 error_sign = sign_only(error_val);
225 for (j = predictor_coef_num - 1; j >= 0 && error_val * error_sign > 0; j--) {
227 val = d - buffer_out[i - j];
228 sign = sign_only(val) * error_sign;
229 predictor_coef_table[j] -= sign;
231 error_val -= ((val >> predictor_quantitization) *
232 (predictor_coef_num - j));
238 static void decorrelate_stereo(int32_t *buffer[MAX_CHANNELS],
239 int numsamples, uint8_t interlacing_shift,
240 uint8_t interlacing_leftweight)
244 for (i = 0; i < numsamples; i++) {
250 a -= (b * interlacing_leftweight) >> interlacing_shift;
258 static void append_extra_bits(int32_t *buffer[MAX_CHANNELS],
259 int32_t *extra_bits_buffer[MAX_CHANNELS],
260 int extra_bits, int numchannels, int numsamples)
264 for (ch = 0; ch < numchannels; ch++)
265 for (i = 0; i < numsamples; i++)
266 buffer[ch][i] = (buffer[ch][i] << extra_bits) | extra_bits_buffer[ch][i];
269 static void interleave_stereo_16(int32_t *buffer[MAX_CHANNELS],
270 int16_t *buffer_out, int numsamples)
274 for (i = 0; i < numsamples; i++) {
275 *buffer_out++ = buffer[0][i];
276 *buffer_out++ = buffer[1][i];
280 static void interleave_stereo_24(int32_t *buffer[MAX_CHANNELS],
281 int32_t *buffer_out, int numsamples)
285 for (i = 0; i < numsamples; i++) {
286 *buffer_out++ = buffer[0][i] << 8;
287 *buffer_out++ = buffer[1][i] << 8;
291 static int alac_decode_frame(AVCodecContext *avctx, void *data,
292 int *got_frame_ptr, AVPacket *avpkt)
294 ALACContext *alac = avctx->priv_data;
298 unsigned int readsamplesize;
300 uint8_t interlacing_shift;
301 uint8_t interlacing_leftweight;
304 init_get_bits(&alac->gb, avpkt->data, avpkt->size * 8);
306 channels = get_bits(&alac->gb, 3) + 1;
307 if (channels != avctx->channels) {
308 av_log(avctx, AV_LOG_ERROR, "frame header channel count mismatch\n");
309 return AVERROR_INVALIDDATA;
312 skip_bits(&alac->gb, 4); /* element instance tag */
313 skip_bits(&alac->gb, 12); /* unused header bits */
315 /* the number of output samples is stored in the frame */
316 hassize = get_bits1(&alac->gb);
318 alac->extra_bits = get_bits(&alac->gb, 2) << 3;
320 /* whether the frame is compressed */
321 is_compressed = !get_bits1(&alac->gb);
324 /* now read the number of samples as a 32bit integer */
325 uint32_t output_samples = get_bits_long(&alac->gb, 32);
326 if (!output_samples || output_samples > alac->max_samples_per_frame) {
327 av_log(avctx, AV_LOG_ERROR, "invalid samples per frame: %d\n",
329 return AVERROR_INVALIDDATA;
331 alac->nb_samples = output_samples;
333 alac->nb_samples = alac->max_samples_per_frame;
335 /* get output buffer */
336 alac->frame.nb_samples = alac->nb_samples;
337 if ((ret = avctx->get_buffer(avctx, &alac->frame)) < 0) {
338 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
342 readsamplesize = alac->sample_size - alac->extra_bits + channels - 1;
343 if (readsamplesize > MIN_CACHE_BITS) {
344 av_log(avctx, AV_LOG_ERROR, "readsamplesize too big (%d)\n", readsamplesize);
349 int16_t predictor_coef_table[MAX_CHANNELS][32];
350 int predictor_coef_num[MAX_CHANNELS];
351 int prediction_type[MAX_CHANNELS];
352 int prediction_quantitization[MAX_CHANNELS];
353 int ricemodifier[MAX_CHANNELS];
355 interlacing_shift = get_bits(&alac->gb, 8);
356 interlacing_leftweight = get_bits(&alac->gb, 8);
358 for (ch = 0; ch < channels; ch++) {
359 prediction_type[ch] = get_bits(&alac->gb, 4);
360 prediction_quantitization[ch] = get_bits(&alac->gb, 4);
362 ricemodifier[ch] = get_bits(&alac->gb, 3);
363 predictor_coef_num[ch] = get_bits(&alac->gb, 5);
365 /* read the predictor table */
366 for (i = 0; i < predictor_coef_num[ch]; i++)
367 predictor_coef_table[ch][i] = get_sbits(&alac->gb, 16);
370 if (alac->extra_bits) {
371 for (i = 0; i < alac->nb_samples; i++) {
372 for (ch = 0; ch < channels; ch++)
373 alac->extra_bits_buffer[ch][i] = get_bits(&alac->gb, alac->extra_bits);
376 for (ch = 0; ch < channels; ch++) {
377 bastardized_rice_decompress(alac,
378 alac->predict_error_buffer[ch],
381 ricemodifier[ch] * alac->rice_history_mult / 4);
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.
389 * However, this prediction type is not currently used by the
392 predictor_decompress_fir_adapt(alac->predict_error_buffer[ch],
393 alac->predict_error_buffer[ch],
394 alac->nb_samples, readsamplesize,
396 } else if (prediction_type[ch] > 0) {
397 av_log(avctx, AV_LOG_WARNING, "unknown prediction type: %i\n",
398 prediction_type[ch]);
400 predictor_decompress_fir_adapt(alac->predict_error_buffer[ch],
401 alac->output_samples_buffer[ch],
402 alac->nb_samples, readsamplesize,
403 predictor_coef_table[ch],
404 predictor_coef_num[ch],
405 prediction_quantitization[ch]);
408 /* not compressed, easy case */
409 for (i = 0; i < alac->nb_samples; i++) {
410 for (ch = 0; ch < channels; ch++) {
411 alac->output_samples_buffer[ch][i] = get_sbits_long(&alac->gb,
415 alac->extra_bits = 0;
416 interlacing_shift = 0;
417 interlacing_leftweight = 0;
419 if (get_bits(&alac->gb, 3) != 7)
420 av_log(avctx, AV_LOG_ERROR, "Error : Wrong End Of Frame\n");
422 if (channels == 2 && interlacing_leftweight) {
423 decorrelate_stereo(alac->output_samples_buffer, alac->nb_samples,
424 interlacing_shift, interlacing_leftweight);
427 if (alac->extra_bits) {
428 append_extra_bits(alac->output_samples_buffer, alac->extra_bits_buffer,
429 alac->extra_bits, alac->channels, alac->nb_samples);
432 switch(alac->sample_size) {
435 interleave_stereo_16(alac->output_samples_buffer,
436 (int16_t *)alac->frame.data[0],
439 int16_t *outbuffer = (int16_t *)alac->frame.data[0];
440 for (i = 0; i < alac->nb_samples; i++) {
441 outbuffer[i] = alac->output_samples_buffer[0][i];
447 interleave_stereo_24(alac->output_samples_buffer,
448 (int32_t *)alac->frame.data[0],
451 int32_t *outbuffer = (int32_t *)alac->frame.data[0];
452 for (i = 0; i < alac->nb_samples; i++)
453 outbuffer[i] = alac->output_samples_buffer[0][i] << 8;
458 if (avpkt->size * 8 - get_bits_count(&alac->gb) > 8)
459 av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n",
460 avpkt->size * 8 - get_bits_count(&alac->gb));
463 *(AVFrame *)data = alac->frame;
468 static av_cold int alac_decode_close(AVCodecContext *avctx)
470 ALACContext *alac = avctx->priv_data;
473 for (ch = 0; ch < alac->channels; ch++) {
474 av_freep(&alac->predict_error_buffer[ch]);
475 av_freep(&alac->output_samples_buffer[ch]);
476 av_freep(&alac->extra_bits_buffer[ch]);
482 static int allocate_buffers(ALACContext *alac)
485 for (ch = 0; ch < alac->channels; ch++) {
486 int buf_size = alac->max_samples_per_frame * sizeof(int32_t);
488 FF_ALLOC_OR_GOTO(alac->avctx, alac->predict_error_buffer[ch],
489 buf_size, buf_alloc_fail);
491 FF_ALLOC_OR_GOTO(alac->avctx, alac->output_samples_buffer[ch],
492 buf_size, buf_alloc_fail);
494 FF_ALLOC_OR_GOTO(alac->avctx, alac->extra_bits_buffer[ch],
495 buf_size, buf_alloc_fail);
499 alac_decode_close(alac->avctx);
500 return AVERROR(ENOMEM);
503 static int alac_set_info(ALACContext *alac)
507 bytestream2_init(&gb, alac->avctx->extradata,
508 alac->avctx->extradata_size);
510 bytestream2_skipu(&gb, 12); // size:4, alac:4, version:4
512 alac->max_samples_per_frame = bytestream2_get_be32u(&gb);
513 if (!alac->max_samples_per_frame || alac->max_samples_per_frame > INT_MAX) {
514 av_log(alac->avctx, AV_LOG_ERROR, "max samples per frame invalid: %u\n",
515 alac->max_samples_per_frame);
516 return AVERROR_INVALIDDATA;
518 bytestream2_skipu(&gb, 1); // compatible version
519 alac->sample_size = bytestream2_get_byteu(&gb);
520 alac->rice_history_mult = bytestream2_get_byteu(&gb);
521 alac->rice_initial_history = bytestream2_get_byteu(&gb);
522 alac->rice_limit = bytestream2_get_byteu(&gb);
523 alac->channels = bytestream2_get_byteu(&gb);
524 bytestream2_get_be16u(&gb); // maxRun
525 bytestream2_get_be32u(&gb); // max coded frame size
526 bytestream2_get_be32u(&gb); // average bitrate
527 bytestream2_get_be32u(&gb); // samplerate
532 static av_cold int alac_decode_init(AVCodecContext * avctx)
535 ALACContext *alac = avctx->priv_data;
538 /* initialize from the extradata */
539 if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
540 av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
541 ALAC_EXTRADATA_SIZE);
544 if (alac_set_info(alac)) {
545 av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
549 switch (alac->sample_size) {
550 case 16: avctx->sample_fmt = AV_SAMPLE_FMT_S16;
552 case 24: avctx->sample_fmt = AV_SAMPLE_FMT_S32;
554 default: av_log_ask_for_sample(avctx, "Sample depth %d is not supported.\n",
556 return AVERROR_PATCHWELCOME;
559 if (alac->channels < 1) {
560 av_log(avctx, AV_LOG_WARNING, "Invalid channel count\n");
561 alac->channels = avctx->channels;
563 if (alac->channels > MAX_CHANNELS)
564 alac->channels = avctx->channels;
566 avctx->channels = alac->channels;
568 if (avctx->channels > MAX_CHANNELS) {
569 av_log(avctx, AV_LOG_ERROR, "Unsupported channel count: %d\n",
571 return AVERROR_PATCHWELCOME;
574 if ((ret = allocate_buffers(alac)) < 0) {
575 av_log(avctx, AV_LOG_ERROR, "Error allocating buffers\n");
579 avcodec_get_frame_defaults(&alac->frame);
580 avctx->coded_frame = &alac->frame;
585 AVCodec ff_alac_decoder = {
587 .type = AVMEDIA_TYPE_AUDIO,
589 .priv_data_size = sizeof(ALACContext),
590 .init = alac_decode_init,
591 .close = alac_decode_close,
592 .decode = alac_decode_frame,
593 .capabilities = CODEC_CAP_DR1,
594 .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),