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
27 * For more information on the ALAC format, visit:
28 * http://crazney.net/programs/itunes/alac.html
30 * Note: This decoder expects a 36- (0x24-)byte QuickTime atom to be
31 * passed through the extradata[_size] fields. This atom is tacked onto
32 * the end of an 'alac' stsd atom and has the following format:
33 * bytes 0-3 atom size (0x24), big-endian
34 * bytes 4-7 atom type ('alac', not the 'alac' tag from start of stsd)
35 * bytes 8-35 data bytes needed by decoder
41 * 32bit max sample per frame
45 * 8bit initial history
49 * 32bit max coded frame size
57 #include "bytestream.h"
61 #define ALAC_EXTRADATA_SIZE 36
62 #define MAX_CHANNELS 2
66 AVCodecContext *avctx;
73 int32_t *predicterror_buffer[MAX_CHANNELS];
75 int32_t *outputsamples_buffer[MAX_CHANNELS];
77 int32_t *wasted_bits_buffer[MAX_CHANNELS];
79 /* stuff from setinfo */
80 uint32_t setinfo_max_samples_per_frame; /* 0x1000 = 4096 */ /* max samples per frame? */
81 uint8_t setinfo_sample_size; /* 0x10 */
82 uint8_t setinfo_rice_historymult; /* 0x28 */
83 uint8_t setinfo_rice_initialhistory; /* 0x0a */
84 uint8_t setinfo_rice_kmodifier; /* 0x0e */
85 /* end setinfo stuff */
90 static void allocate_buffers(ALACContext *alac)
93 for (chan = 0; chan < MAX_CHANNELS; chan++) {
94 alac->predicterror_buffer[chan] =
95 av_malloc(alac->setinfo_max_samples_per_frame * 4);
97 alac->outputsamples_buffer[chan] =
98 av_malloc(alac->setinfo_max_samples_per_frame * 4);
100 alac->wasted_bits_buffer[chan] = av_malloc(alac->setinfo_max_samples_per_frame * 4);
104 static int alac_set_info(ALACContext *alac)
106 const unsigned char *ptr = alac->avctx->extradata;
112 if(AV_RB32(ptr) >= UINT_MAX/4){
113 av_log(alac->avctx, AV_LOG_ERROR, "setinfo_max_samples_per_frame too large\n");
117 /* buffer size / 2 ? */
118 alac->setinfo_max_samples_per_frame = bytestream_get_be32(&ptr);
120 alac->setinfo_sample_size = *ptr++;
121 if (alac->setinfo_sample_size > 32) {
122 av_log(alac->avctx, AV_LOG_ERROR, "setinfo_sample_size too large\n");
125 alac->setinfo_rice_historymult = *ptr++;
126 alac->setinfo_rice_initialhistory = *ptr++;
127 alac->setinfo_rice_kmodifier = *ptr++;
128 ptr++; /* channels? */
129 bytestream_get_be16(&ptr); /* ??? */
130 bytestream_get_be32(&ptr); /* max coded frame size */
131 bytestream_get_be32(&ptr); /* bitrate ? */
132 bytestream_get_be32(&ptr); /* samplerate */
134 allocate_buffers(alac);
139 static inline int decode_scalar(GetBitContext *gb, int k, int limit, int readsamplesize){
140 /* read x - number of 1s before 0 represent the rice */
141 int x = get_unary_0_9(gb);
143 if (x > 8) { /* RICE THRESHOLD */
144 /* use alternative encoding */
145 x = get_bits(gb, readsamplesize);
151 int extrabits = show_bits(gb, k);
153 /* multiply x by 2^k - 1, as part of their strange algorithm */
160 skip_bits(gb, k - 1);
166 static void bastardized_rice_decompress(ALACContext *alac,
167 int32_t *output_buffer,
169 int readsamplesize, /* arg_10 */
170 int rice_initialhistory, /* arg424->b */
171 int rice_kmodifier, /* arg424->d */
172 int rice_historymult, /* arg424->c */
173 int rice_kmodifier_mask /* arg424->e */
177 unsigned int history = rice_initialhistory;
178 int sign_modifier = 0;
180 for (output_count = 0; output_count < output_size; output_count++) {
185 /* standard rice encoding */
186 int k; /* size of extra bits */
188 /* read k, that is bits as is */
189 k = av_log2((history >> 9) + 3);
190 x= decode_scalar(&alac->gb, k, rice_kmodifier, readsamplesize);
192 x_modified = sign_modifier + x;
193 final_val = (x_modified + 1) / 2;
194 if (x_modified & 1) final_val *= -1;
196 output_buffer[output_count] = final_val;
200 /* now update the history */
201 history += x_modified * rice_historymult
202 - ((history * rice_historymult) >> 9);
204 if (x_modified > 0xffff)
207 /* special case: there may be compressed blocks of 0 */
208 if ((history < 128) && (output_count+1 < output_size)) {
210 unsigned int block_size;
214 k = 7 - av_log2(history) + ((history + 16) >> 6 /* / 64 */);
216 block_size= decode_scalar(&alac->gb, k, rice_kmodifier, 16);
218 if (block_size > 0) {
219 if(block_size >= output_size - output_count){
220 av_log(alac->avctx, AV_LOG_ERROR, "invalid zero block size of %d %d %d\n", block_size, output_size, output_count);
221 block_size= output_size - output_count - 1;
223 memset(&output_buffer[output_count+1], 0, block_size * 4);
224 output_count += block_size;
227 if (block_size > 0xffff)
235 static inline int sign_only(int v)
237 return v ? FFSIGN(v) : 0;
240 static void predictor_decompress_fir_adapt(int32_t *error_buffer,
244 int16_t *predictor_coef_table,
245 int predictor_coef_num,
246 int predictor_quantitization)
250 /* first sample always copies */
251 *buffer_out = *error_buffer;
253 if (!predictor_coef_num) {
254 if (output_size <= 1)
257 memcpy(buffer_out+1, error_buffer+1, (output_size-1) * 4);
261 if (predictor_coef_num == 0x1f) { /* 11111 - max value of predictor_coef_num */
262 /* second-best case scenario for fir decompression,
263 * error describes a small difference from the previous sample only
265 if (output_size <= 1)
267 for (i = 0; i < output_size - 1; i++) {
271 prev_value = buffer_out[i];
272 error_value = error_buffer[i+1];
274 sign_extend((prev_value + error_value), readsamplesize);
279 /* read warm-up samples */
280 if (predictor_coef_num > 0)
281 for (i = 0; i < predictor_coef_num; i++) {
284 val = buffer_out[i] + error_buffer[i+1];
285 val = sign_extend(val, readsamplesize);
286 buffer_out[i+1] = val;
290 /* 4 and 8 are very common cases (the only ones i've seen). these
291 * should be unrolled and optimized
293 if (predictor_coef_num == 4) {
294 /* FIXME: optimized general case */
298 if (predictor_coef_table == 8) {
299 /* FIXME: optimized general case */
305 if (predictor_coef_num > 0) {
306 for (i = predictor_coef_num + 1; i < output_size; i++) {
310 int error_val = error_buffer[i];
312 for (j = 0; j < predictor_coef_num; j++) {
313 sum += (buffer_out[predictor_coef_num-j] - buffer_out[0]) *
314 predictor_coef_table[j];
317 outval = (1 << (predictor_quantitization-1)) + sum;
318 outval = outval >> predictor_quantitization;
319 outval = outval + buffer_out[0] + error_val;
320 outval = sign_extend(outval, readsamplesize);
322 buffer_out[predictor_coef_num+1] = outval;
325 int predictor_num = predictor_coef_num - 1;
327 while (predictor_num >= 0 && error_val > 0) {
328 int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
329 int sign = sign_only(val);
331 predictor_coef_table[predictor_num] -= sign;
333 val *= sign; /* absolute value */
335 error_val -= ((val >> predictor_quantitization) *
336 (predictor_coef_num - predictor_num));
340 } else if (error_val < 0) {
341 int predictor_num = predictor_coef_num - 1;
343 while (predictor_num >= 0 && error_val < 0) {
344 int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
345 int sign = - sign_only(val);
347 predictor_coef_table[predictor_num] -= sign;
349 val *= sign; /* neg value */
351 error_val -= ((val >> predictor_quantitization) *
352 (predictor_coef_num - predictor_num));
363 static void reconstruct_stereo_16(int32_t *buffer[MAX_CHANNELS],
365 int numchannels, int numsamples,
366 uint8_t interlacing_shift,
367 uint8_t interlacing_leftweight)
373 /* weighted interlacing */
374 if (interlacing_leftweight) {
375 for (i = 0; i < numsamples; i++) {
381 a -= (b * interlacing_leftweight) >> interlacing_shift;
384 buffer_out[i*numchannels] = b;
385 buffer_out[i*numchannels + 1] = a;
391 /* otherwise basic interlacing took place */
392 for (i = 0; i < numsamples; i++) {
396 right = buffer[1][i];
398 buffer_out[i*numchannels] = left;
399 buffer_out[i*numchannels + 1] = right;
403 static void decorrelate_stereo_24(int32_t *buffer[MAX_CHANNELS],
405 int32_t *wasted_bits_buffer[MAX_CHANNELS],
407 int numchannels, int numsamples,
408 uint8_t interlacing_shift,
409 uint8_t interlacing_leftweight)
416 /* weighted interlacing */
417 if (interlacing_leftweight) {
418 for (i = 0; i < numsamples; i++) {
424 a -= (b * interlacing_leftweight) >> interlacing_shift;
428 b = (b << wasted_bits) | wasted_bits_buffer[0][i];
429 a = (a << wasted_bits) | wasted_bits_buffer[1][i];
432 buffer_out[i * numchannels] = b << 8;
433 buffer_out[i * numchannels + 1] = a << 8;
436 for (i = 0; i < numsamples; i++) {
440 right = buffer[1][i];
443 left = (left << wasted_bits) | wasted_bits_buffer[0][i];
444 right = (right << wasted_bits) | wasted_bits_buffer[1][i];
447 buffer_out[i * numchannels] = left << 8;
448 buffer_out[i * numchannels + 1] = right << 8;
453 static int alac_decode_frame(AVCodecContext *avctx,
454 void *outbuffer, int *outputsize,
457 const uint8_t *inbuffer = avpkt->data;
458 int input_buffer_size = avpkt->size;
459 ALACContext *alac = avctx->priv_data;
462 unsigned int outputsamples;
464 unsigned int readsamplesize;
466 uint8_t interlacing_shift;
467 uint8_t interlacing_leftweight;
469 /* short-circuit null buffers */
470 if (!inbuffer || !input_buffer_size)
473 init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
475 channels = get_bits(&alac->gb, 3) + 1;
476 if (channels > MAX_CHANNELS) {
477 av_log(avctx, AV_LOG_ERROR, "channels > %d not supported\n",
482 /* 2^result = something to do with output waiting.
483 * perhaps matters if we read > 1 frame in a pass?
485 skip_bits(&alac->gb, 4);
487 skip_bits(&alac->gb, 12); /* unknown, skip 12 bits */
489 /* the output sample size is stored soon */
490 hassize = get_bits1(&alac->gb);
492 alac->wasted_bits = get_bits(&alac->gb, 2) << 3;
494 /* whether the frame is compressed */
495 isnotcompressed = get_bits1(&alac->gb);
498 /* now read the number of samples as a 32bit integer */
499 outputsamples = get_bits_long(&alac->gb, 32);
500 if(outputsamples > alac->setinfo_max_samples_per_frame){
501 av_log(avctx, AV_LOG_ERROR, "outputsamples %d > %d\n", outputsamples, alac->setinfo_max_samples_per_frame);
505 outputsamples = alac->setinfo_max_samples_per_frame;
507 switch (alac->setinfo_sample_size) {
508 case 16: avctx->sample_fmt = AV_SAMPLE_FMT_S16;
509 alac->bytespersample = channels << 1;
511 case 24: avctx->sample_fmt = AV_SAMPLE_FMT_S32;
512 alac->bytespersample = channels << 2;
514 default: av_log(avctx, AV_LOG_ERROR, "Sample depth %d is not supported.\n",
515 alac->setinfo_sample_size);
519 if(outputsamples > *outputsize / alac->bytespersample){
520 av_log(avctx, AV_LOG_ERROR, "sample buffer too small\n");
524 *outputsize = outputsamples * alac->bytespersample;
525 readsamplesize = alac->setinfo_sample_size - (alac->wasted_bits) + channels - 1;
526 if (readsamplesize > MIN_CACHE_BITS) {
527 av_log(avctx, AV_LOG_ERROR, "readsamplesize too big (%d)\n", readsamplesize);
531 if (!isnotcompressed) {
532 /* so it is compressed */
533 int16_t predictor_coef_table[MAX_CHANNELS][32];
534 int predictor_coef_num[MAX_CHANNELS];
535 int prediction_type[MAX_CHANNELS];
536 int prediction_quantitization[MAX_CHANNELS];
537 int ricemodifier[MAX_CHANNELS];
540 interlacing_shift = get_bits(&alac->gb, 8);
541 interlacing_leftweight = get_bits(&alac->gb, 8);
543 for (chan = 0; chan < channels; chan++) {
544 prediction_type[chan] = get_bits(&alac->gb, 4);
545 prediction_quantitization[chan] = get_bits(&alac->gb, 4);
547 ricemodifier[chan] = get_bits(&alac->gb, 3);
548 predictor_coef_num[chan] = get_bits(&alac->gb, 5);
550 /* read the predictor table */
551 for (i = 0; i < predictor_coef_num[chan]; i++)
552 predictor_coef_table[chan][i] = (int16_t)get_bits(&alac->gb, 16);
555 if (alac->wasted_bits) {
557 for (i = 0; i < outputsamples; i++) {
558 for (ch = 0; ch < channels; ch++)
559 alac->wasted_bits_buffer[ch][i] = get_bits(&alac->gb, alac->wasted_bits);
562 for (chan = 0; chan < channels; chan++) {
563 bastardized_rice_decompress(alac,
564 alac->predicterror_buffer[chan],
567 alac->setinfo_rice_initialhistory,
568 alac->setinfo_rice_kmodifier,
569 ricemodifier[chan] * alac->setinfo_rice_historymult / 4,
570 (1 << alac->setinfo_rice_kmodifier) - 1);
572 if (prediction_type[chan] == 0) {
574 predictor_decompress_fir_adapt(alac->predicterror_buffer[chan],
575 alac->outputsamples_buffer[chan],
578 predictor_coef_table[chan],
579 predictor_coef_num[chan],
580 prediction_quantitization[chan]);
582 av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type[chan]);
583 /* I think the only other prediction type (or perhaps this is
584 * just a boolean?) runs adaptive fir twice.. like:
585 * predictor_decompress_fir_adapt(predictor_error, tempout, ...)
586 * predictor_decompress_fir_adapt(predictor_error, outputsamples ...)
592 /* not compressed, easy case */
594 if (alac->setinfo_sample_size <= 16) {
595 for (i = 0; i < outputsamples; i++)
596 for (chan = 0; chan < channels; chan++) {
599 audiobits = get_sbits_long(&alac->gb, alac->setinfo_sample_size);
601 alac->outputsamples_buffer[chan][i] = audiobits;
604 for (i = 0; i < outputsamples; i++) {
605 for (chan = 0; chan < channels; chan++) {
606 alac->outputsamples_buffer[chan][i] = get_bits(&alac->gb,
607 alac->setinfo_sample_size);
608 alac->outputsamples_buffer[chan][i] = sign_extend(alac->outputsamples_buffer[chan][i],
609 alac->setinfo_sample_size);
613 alac->wasted_bits = 0;
614 interlacing_shift = 0;
615 interlacing_leftweight = 0;
617 if (get_bits(&alac->gb, 3) != 7)
618 av_log(avctx, AV_LOG_ERROR, "Error : Wrong End Of Frame\n");
620 switch(alac->setinfo_sample_size) {
623 reconstruct_stereo_16(alac->outputsamples_buffer,
628 interlacing_leftweight);
631 for (i = 0; i < outputsamples; i++) {
632 ((int16_t*)outbuffer)[i] = alac->outputsamples_buffer[0][i];
638 decorrelate_stereo_24(alac->outputsamples_buffer,
640 alac->wasted_bits_buffer,
645 interlacing_leftweight);
648 for (i = 0; i < outputsamples; i++)
649 ((int32_t *)outbuffer)[i] = alac->outputsamples_buffer[0][i] << 8;
654 if (input_buffer_size * 8 - get_bits_count(&alac->gb) > 8)
655 av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n", input_buffer_size * 8 - get_bits_count(&alac->gb));
657 return input_buffer_size;
660 static av_cold int alac_decode_init(AVCodecContext * avctx)
662 ALACContext *alac = avctx->priv_data;
664 alac->numchannels = alac->avctx->channels;
666 /* initialize from the extradata */
667 if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
668 av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
669 ALAC_EXTRADATA_SIZE);
672 if (alac_set_info(alac)) {
673 av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
680 static av_cold int alac_decode_close(AVCodecContext *avctx)
682 ALACContext *alac = avctx->priv_data;
685 for (chan = 0; chan < MAX_CHANNELS; chan++) {
686 av_freep(&alac->predicterror_buffer[chan]);
687 av_freep(&alac->outputsamples_buffer[chan]);
688 av_freep(&alac->wasted_bits_buffer[chan]);
694 AVCodec ff_alac_decoder = {
703 .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),