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)
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 *predicterror_buffer[MAX_CHANNELS];
69 int32_t *outputsamples_buffer[MAX_CHANNELS];
71 int32_t *extra_bits_buffer[MAX_CHANNELS];
73 /* stuff from setinfo */
74 uint32_t setinfo_max_samples_per_frame; /* 0x1000 = 4096 */ /* max samples per frame? */
75 uint8_t setinfo_sample_size; /* 0x10 */
76 uint8_t setinfo_rice_historymult; /* 0x28 */
77 uint8_t setinfo_rice_initialhistory; /* 0x0a */
78 uint8_t setinfo_rice_kmodifier; /* 0x0e */
79 /* end setinfo stuff */
81 int extra_bits; /**< number of extra bits beyond 16-bit */
84 static inline int decode_scalar(GetBitContext *gb, int k, int limit, int readsamplesize){
85 /* read x - number of 1s before 0 represent the rice */
86 int x = get_unary_0_9(gb);
88 if (x > 8) { /* RICE THRESHOLD */
89 /* use alternative encoding */
90 x = get_bits(gb, readsamplesize);
96 int extrabits = show_bits(gb, k);
98 /* multiply x by 2^k - 1, as part of their strange algorithm */
105 skip_bits(gb, k - 1);
111 static void bastardized_rice_decompress(ALACContext *alac,
112 int32_t *output_buffer,
114 int readsamplesize, /* arg_10 */
115 int rice_initialhistory, /* arg424->b */
116 int rice_kmodifier, /* arg424->d */
117 int rice_historymult, /* arg424->c */
118 int rice_kmodifier_mask /* arg424->e */
122 unsigned int history = rice_initialhistory;
123 int sign_modifier = 0;
125 for (output_count = 0; output_count < output_size; output_count++) {
130 /* standard rice encoding */
131 int k; /* size of extra bits */
133 /* read k, that is bits as is */
134 k = av_log2((history >> 9) + 3);
135 x= decode_scalar(&alac->gb, k, rice_kmodifier, readsamplesize);
137 x_modified = sign_modifier + x;
138 final_val = (x_modified + 1) / 2;
139 if (x_modified & 1) final_val *= -1;
141 output_buffer[output_count] = final_val;
145 /* now update the history */
146 history += x_modified * rice_historymult
147 - ((history * rice_historymult) >> 9);
149 if (x_modified > 0xffff)
152 /* special case: there may be compressed blocks of 0 */
153 if ((history < 128) && (output_count+1 < output_size)) {
155 unsigned int block_size;
159 k = 7 - av_log2(history) + ((history + 16) >> 6 /* / 64 */);
161 block_size= decode_scalar(&alac->gb, k, rice_kmodifier, 16);
163 if (block_size > 0) {
164 if(block_size >= output_size - output_count){
165 av_log(alac->avctx, AV_LOG_ERROR, "invalid zero block size of %d %d %d\n", block_size, output_size, output_count);
166 block_size= output_size - output_count - 1;
168 memset(&output_buffer[output_count+1], 0, block_size * 4);
169 output_count += block_size;
172 if (block_size > 0xffff)
180 static inline int sign_only(int v)
182 return v ? FFSIGN(v) : 0;
185 static void predictor_decompress_fir_adapt(int32_t *error_buffer,
189 int16_t *predictor_coef_table,
190 int predictor_coef_num,
191 int predictor_quantitization)
195 /* first sample always copies */
196 *buffer_out = *error_buffer;
198 if (!predictor_coef_num) {
199 if (output_size <= 1)
202 memcpy(buffer_out+1, error_buffer+1, (output_size-1) * 4);
206 if (predictor_coef_num == 0x1f) { /* 11111 - max value of predictor_coef_num */
207 /* second-best case scenario for fir decompression,
208 * error describes a small difference from the previous sample only
210 if (output_size <= 1)
212 for (i = 0; i < output_size - 1; i++) {
216 prev_value = buffer_out[i];
217 error_value = error_buffer[i+1];
219 sign_extend((prev_value + error_value), readsamplesize);
224 /* read warm-up samples */
225 if (predictor_coef_num > 0)
226 for (i = 0; i < predictor_coef_num; i++) {
229 val = buffer_out[i] + error_buffer[i+1];
230 val = sign_extend(val, readsamplesize);
231 buffer_out[i+1] = val;
234 /* 4 and 8 are very common cases (the only ones i've seen). these
235 * should be unrolled and optimized
239 if (predictor_coef_num > 0) {
240 for (i = predictor_coef_num + 1; i < output_size; i++) {
244 int error_val = error_buffer[i];
246 for (j = 0; j < predictor_coef_num; j++) {
247 sum += (buffer_out[predictor_coef_num-j] - buffer_out[0]) *
248 predictor_coef_table[j];
251 outval = (1 << (predictor_quantitization-1)) + sum;
252 outval = outval >> predictor_quantitization;
253 outval = outval + buffer_out[0] + error_val;
254 outval = sign_extend(outval, readsamplesize);
256 buffer_out[predictor_coef_num+1] = outval;
259 int predictor_num = predictor_coef_num - 1;
261 while (predictor_num >= 0 && error_val > 0) {
262 int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
263 int sign = sign_only(val);
265 predictor_coef_table[predictor_num] -= sign;
267 val *= sign; /* absolute value */
269 error_val -= ((val >> predictor_quantitization) *
270 (predictor_coef_num - predictor_num));
274 } else if (error_val < 0) {
275 int predictor_num = predictor_coef_num - 1;
277 while (predictor_num >= 0 && error_val < 0) {
278 int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
279 int sign = - sign_only(val);
281 predictor_coef_table[predictor_num] -= sign;
283 val *= sign; /* neg value */
285 error_val -= ((val >> predictor_quantitization) *
286 (predictor_coef_num - predictor_num));
297 static void decorrelate_stereo(int32_t *buffer[MAX_CHANNELS],
298 int numsamples, uint8_t interlacing_shift,
299 uint8_t interlacing_leftweight)
303 for (i = 0; i < numsamples; i++) {
309 a -= (b * interlacing_leftweight) >> interlacing_shift;
317 static void append_extra_bits(int32_t *buffer[MAX_CHANNELS],
318 int32_t *extra_bits_buffer[MAX_CHANNELS],
319 int extra_bits, int numchannels, int numsamples)
323 for (ch = 0; ch < numchannels; ch++)
324 for (i = 0; i < numsamples; i++)
325 buffer[ch][i] = (buffer[ch][i] << extra_bits) | extra_bits_buffer[ch][i];
328 static void interleave_stereo_16(int32_t *buffer[MAX_CHANNELS],
329 int16_t *buffer_out, int numsamples)
333 for (i = 0; i < numsamples; i++) {
334 *buffer_out++ = buffer[0][i];
335 *buffer_out++ = buffer[1][i];
339 static void interleave_stereo_24(int32_t *buffer[MAX_CHANNELS],
340 int32_t *buffer_out, int numsamples)
344 for (i = 0; i < numsamples; i++) {
345 *buffer_out++ = buffer[0][i] << 8;
346 *buffer_out++ = buffer[1][i] << 8;
350 static int alac_decode_frame(AVCodecContext *avctx, void *data,
351 int *got_frame_ptr, AVPacket *avpkt)
353 const uint8_t *inbuffer = avpkt->data;
354 int input_buffer_size = avpkt->size;
355 ALACContext *alac = avctx->priv_data;
358 unsigned int outputsamples;
360 unsigned int readsamplesize;
362 uint8_t interlacing_shift;
363 uint8_t interlacing_leftweight;
366 init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
368 channels = get_bits(&alac->gb, 3) + 1;
369 if (channels != avctx->channels) {
370 av_log(avctx, AV_LOG_ERROR, "frame header channel count mismatch\n");
371 return AVERROR_INVALIDDATA;
374 /* 2^result = something to do with output waiting.
375 * perhaps matters if we read > 1 frame in a pass?
377 skip_bits(&alac->gb, 4);
379 skip_bits(&alac->gb, 12); /* unknown, skip 12 bits */
381 /* the output sample size is stored soon */
382 hassize = get_bits1(&alac->gb);
384 alac->extra_bits = get_bits(&alac->gb, 2) << 3;
386 /* whether the frame is compressed */
387 isnotcompressed = get_bits1(&alac->gb);
390 /* now read the number of samples as a 32bit integer */
391 outputsamples = get_bits_long(&alac->gb, 32);
392 if(outputsamples > alac->setinfo_max_samples_per_frame){
393 av_log(avctx, AV_LOG_ERROR, "outputsamples %d > %d\n", outputsamples, alac->setinfo_max_samples_per_frame);
397 outputsamples = alac->setinfo_max_samples_per_frame;
399 /* get output buffer */
400 if (outputsamples > INT32_MAX) {
401 av_log(avctx, AV_LOG_ERROR, "unsupported block size: %u\n", outputsamples);
402 return AVERROR_INVALIDDATA;
404 alac->frame.nb_samples = outputsamples;
405 if ((ret = avctx->get_buffer(avctx, &alac->frame)) < 0) {
406 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
410 readsamplesize = alac->setinfo_sample_size - alac->extra_bits + channels - 1;
411 if (readsamplesize > MIN_CACHE_BITS) {
412 av_log(avctx, AV_LOG_ERROR, "readsamplesize too big (%d)\n", readsamplesize);
416 if (!isnotcompressed) {
417 /* so it is compressed */
418 int16_t predictor_coef_table[MAX_CHANNELS][32];
419 int predictor_coef_num[MAX_CHANNELS];
420 int prediction_type[MAX_CHANNELS];
421 int prediction_quantitization[MAX_CHANNELS];
422 int ricemodifier[MAX_CHANNELS];
424 interlacing_shift = get_bits(&alac->gb, 8);
425 interlacing_leftweight = get_bits(&alac->gb, 8);
427 for (ch = 0; ch < channels; ch++) {
428 prediction_type[ch] = get_bits(&alac->gb, 4);
429 prediction_quantitization[ch] = get_bits(&alac->gb, 4);
431 ricemodifier[ch] = get_bits(&alac->gb, 3);
432 predictor_coef_num[ch] = get_bits(&alac->gb, 5);
434 /* read the predictor table */
435 for (i = 0; i < predictor_coef_num[ch]; i++)
436 predictor_coef_table[ch][i] = (int16_t)get_bits(&alac->gb, 16);
439 if (alac->extra_bits) {
440 for (i = 0; i < outputsamples; i++) {
441 for (ch = 0; ch < channels; ch++)
442 alac->extra_bits_buffer[ch][i] = get_bits(&alac->gb, alac->extra_bits);
445 for (ch = 0; ch < channels; ch++) {
446 bastardized_rice_decompress(alac,
447 alac->predicterror_buffer[ch],
450 alac->setinfo_rice_initialhistory,
451 alac->setinfo_rice_kmodifier,
452 ricemodifier[ch] * alac->setinfo_rice_historymult / 4,
453 (1 << alac->setinfo_rice_kmodifier) - 1);
455 /* adaptive FIR filter */
456 if (prediction_type[ch] == 15) {
457 /* Prediction type 15 runs the adaptive FIR twice.
458 * The first pass uses the special-case coef_num = 31, while
459 * the second pass uses the coefs from the bitstream.
461 * However, this prediction type is not currently used by the
464 predictor_decompress_fir_adapt(alac->predicterror_buffer[ch],
465 alac->predicterror_buffer[ch],
466 outputsamples, readsamplesize,
468 } else if (prediction_type[ch] > 0) {
469 av_log(avctx, AV_LOG_WARNING, "unknown prediction type: %i\n",
470 prediction_type[ch]);
472 predictor_decompress_fir_adapt(alac->predicterror_buffer[ch],
473 alac->outputsamples_buffer[ch],
474 outputsamples, readsamplesize,
475 predictor_coef_table[ch],
476 predictor_coef_num[ch],
477 prediction_quantitization[ch]);
480 /* not compressed, easy case */
481 for (i = 0; i < outputsamples; i++) {
482 for (ch = 0; ch < channels; ch++) {
483 alac->outputsamples_buffer[ch][i] = get_sbits_long(&alac->gb,
484 alac->setinfo_sample_size);
487 alac->extra_bits = 0;
488 interlacing_shift = 0;
489 interlacing_leftweight = 0;
491 if (get_bits(&alac->gb, 3) != 7)
492 av_log(avctx, AV_LOG_ERROR, "Error : Wrong End Of Frame\n");
494 if (channels == 2 && interlacing_leftweight) {
495 decorrelate_stereo(alac->outputsamples_buffer, outputsamples,
496 interlacing_shift, interlacing_leftweight);
499 if (alac->extra_bits) {
500 append_extra_bits(alac->outputsamples_buffer, alac->extra_bits_buffer,
501 alac->extra_bits, alac->numchannels, outputsamples);
504 switch(alac->setinfo_sample_size) {
507 interleave_stereo_16(alac->outputsamples_buffer,
508 (int16_t *)alac->frame.data[0], outputsamples);
510 int16_t *outbuffer = (int16_t *)alac->frame.data[0];
511 for (i = 0; i < outputsamples; i++) {
512 outbuffer[i] = alac->outputsamples_buffer[0][i];
518 interleave_stereo_24(alac->outputsamples_buffer,
519 (int32_t *)alac->frame.data[0], outputsamples);
521 int32_t *outbuffer = (int32_t *)alac->frame.data[0];
522 for (i = 0; i < outputsamples; i++)
523 outbuffer[i] = alac->outputsamples_buffer[0][i] << 8;
528 if (input_buffer_size * 8 - get_bits_count(&alac->gb) > 8)
529 av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n", input_buffer_size * 8 - get_bits_count(&alac->gb));
532 *(AVFrame *)data = alac->frame;
534 return input_buffer_size;
537 static av_cold int alac_decode_close(AVCodecContext *avctx)
539 ALACContext *alac = avctx->priv_data;
542 for (ch = 0; ch < alac->numchannels; ch++) {
543 av_freep(&alac->predicterror_buffer[ch]);
544 av_freep(&alac->outputsamples_buffer[ch]);
545 av_freep(&alac->extra_bits_buffer[ch]);
551 static int allocate_buffers(ALACContext *alac)
554 for (ch = 0; ch < alac->numchannels; ch++) {
555 int buf_size = alac->setinfo_max_samples_per_frame * sizeof(int32_t);
557 FF_ALLOC_OR_GOTO(alac->avctx, alac->predicterror_buffer[ch],
558 buf_size, buf_alloc_fail);
560 FF_ALLOC_OR_GOTO(alac->avctx, alac->outputsamples_buffer[ch],
561 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 /* buffer size / 2 ? */
582 alac->setinfo_max_samples_per_frame = bytestream2_get_be32u(&gb);
583 if (alac->setinfo_max_samples_per_frame >= UINT_MAX/4){
584 av_log(alac->avctx, AV_LOG_ERROR,
585 "setinfo_max_samples_per_frame too large\n");
586 return AVERROR_INVALIDDATA;
588 bytestream2_skipu(&gb, 1); // compatible version
589 alac->setinfo_sample_size = bytestream2_get_byteu(&gb);
590 alac->setinfo_rice_historymult = bytestream2_get_byteu(&gb);
591 alac->setinfo_rice_initialhistory = bytestream2_get_byteu(&gb);
592 alac->setinfo_rice_kmodifier = bytestream2_get_byteu(&gb);
593 alac->numchannels = bytestream2_get_byteu(&gb);
594 bytestream2_get_be16u(&gb); // maxRun
595 bytestream2_get_be32u(&gb); // max coded frame size
596 bytestream2_get_be32u(&gb); // average bitrate
597 bytestream2_get_be32u(&gb); // samplerate
602 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, "alac: expected %d extradata bytes\n",
611 ALAC_EXTRADATA_SIZE);
614 if (alac_set_info(alac)) {
615 av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
619 switch (alac->setinfo_sample_size) {
620 case 16: avctx->sample_fmt = AV_SAMPLE_FMT_S16;
622 case 24: avctx->sample_fmt = AV_SAMPLE_FMT_S32;
624 default: av_log_ask_for_sample(avctx, "Sample depth %d is not supported.\n",
625 alac->setinfo_sample_size);
626 return AVERROR_PATCHWELCOME;
629 if (alac->numchannels < 1) {
630 av_log(avctx, AV_LOG_WARNING, "Invalid channel count\n");
631 alac->numchannels = avctx->channels;
633 if (alac->numchannels > MAX_CHANNELS)
634 alac->numchannels = avctx->channels;
636 avctx->channels = alac->numchannels;
638 if (avctx->channels > MAX_CHANNELS) {
639 av_log(avctx, AV_LOG_ERROR, "Unsupported channel count: %d\n",
641 return AVERROR_PATCHWELCOME;
644 if ((ret = allocate_buffers(alac)) < 0) {
645 av_log(avctx, AV_LOG_ERROR, "Error allocating buffers\n");
649 avcodec_get_frame_defaults(&alac->frame);
650 avctx->coded_frame = &alac->frame;
655 AVCodec ff_alac_decoder = {
657 .type = AVMEDIA_TYPE_AUDIO,
659 .priv_data_size = sizeof(ALACContext),
660 .init = alac_decode_init,
661 .close = alac_decode_close,
662 .decode = alac_decode_frame,
663 .capabilities = CODEC_CAP_DR1,
664 .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),