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
56 #include "bitstream.h"
57 #include "bytestream.h"
59 #define ALAC_EXTRADATA_SIZE 36
60 #define MAX_CHANNELS 2
64 AVCodecContext *avctx;
66 /* init to 0; first frame decode should initialize from extradata and
68 int context_initialized;
75 int32_t *predicterror_buffer[MAX_CHANNELS];
77 int32_t *outputsamples_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_7a; /* 0x00 */
82 uint8_t setinfo_sample_size; /* 0x10 */
83 uint8_t setinfo_rice_historymult; /* 0x28 */
84 uint8_t setinfo_rice_initialhistory; /* 0x0a */
85 uint8_t setinfo_rice_kmodifier; /* 0x0e */
86 uint8_t setinfo_7f; /* 0x02 */
87 uint16_t setinfo_80; /* 0x00ff */
88 uint32_t setinfo_82; /* 0x000020e7 */ /* max sample size?? */
89 uint32_t setinfo_86; /* 0x00069fe4 */ /* bit rate (average)?? */
90 uint32_t setinfo_8a_rate; /* 0x0000ac44 */
91 /* end setinfo stuff */
95 static void allocate_buffers(ALACContext *alac)
98 for (chan = 0; chan < MAX_CHANNELS; chan++) {
99 alac->predicterror_buffer[chan] =
100 av_malloc(alac->setinfo_max_samples_per_frame * 4);
102 alac->outputsamples_buffer[chan] =
103 av_malloc(alac->setinfo_max_samples_per_frame * 4);
107 static int alac_set_info(ALACContext *alac)
109 unsigned char *ptr = alac->avctx->extradata;
115 if(AV_RB32(ptr) >= UINT_MAX/4){
116 av_log(alac->avctx, AV_LOG_ERROR, "setinfo_max_samples_per_frame too large\n");
120 /* buffer size / 2 ? */
121 alac->setinfo_max_samples_per_frame = bytestream_get_be32(&ptr);
122 alac->setinfo_7a = *ptr++;
123 alac->setinfo_sample_size = *ptr++;
124 alac->setinfo_rice_historymult = *ptr++;
125 alac->setinfo_rice_initialhistory = *ptr++;
126 alac->setinfo_rice_kmodifier = *ptr++;
128 alac->setinfo_7f = *ptr++;
129 alac->setinfo_80 = bytestream_get_be16(&ptr);
130 /* max coded frame size */
131 alac->setinfo_82 = bytestream_get_be32(&ptr);
133 alac->setinfo_86 = bytestream_get_be32(&ptr);
135 alac->setinfo_8a_rate = bytestream_get_be32(&ptr);
137 allocate_buffers(alac);
142 /* hideously inefficient. could use a bitmask search,
143 * alternatively bsr on x86,
145 static int count_leading_zeros(int32_t input)
148 while (!(0x80000000 & input) && i < 32) {
155 static void bastardized_rice_decompress(ALACContext *alac,
156 int32_t *output_buffer,
158 int readsamplesize, /* arg_10 */
159 int rice_initialhistory, /* arg424->b */
160 int rice_kmodifier, /* arg424->d */
161 int rice_historymult, /* arg424->c */
162 int rice_kmodifier_mask /* arg424->e */
166 unsigned int history = rice_initialhistory;
167 int sign_modifier = 0;
169 for (output_count = 0; output_count < output_size; output_count++) {
174 /* read x - number of 1s before 0 represent the rice */
175 while (x <= 8 && get_bits1(&alac->gb)) {
180 if (x > 8) { /* RICE THRESHOLD */
181 /* use alternative encoding */
184 value = get_bits(&alac->gb, readsamplesize);
186 /* mask value to readsamplesize size */
187 if (readsamplesize != 32)
188 value &= (0xffffffff >> (32 - readsamplesize));
192 /* standard rice encoding */
194 int k; /* size of extra bits */
196 /* read k, that is bits as is */
197 k = 31 - rice_kmodifier - count_leading_zeros((history >> 9) + 3);
205 extrabits = show_bits(&alac->gb, k);
207 /* multiply x by 2^k - 1, as part of their strange algorithm */
212 get_bits(&alac->gb, k);
214 get_bits(&alac->gb, k - 1);
219 x_modified = sign_modifier + x;
220 final_val = (x_modified + 1) / 2;
221 if (x_modified & 1) final_val *= -1;
223 output_buffer[output_count] = final_val;
227 /* now update the history */
228 history += (x_modified * rice_historymult)
229 - ((history * rice_historymult) >> 9);
231 if (x_modified > 0xffff)
234 /* special case: there may be compressed blocks of 0 */
235 if ((history < 128) && (output_count+1 < output_size)) {
241 while (x <= 8 && get_bits1(&alac->gb)) {
246 block_size = get_bits(&alac->gb, 16);
247 block_size &= 0xffff;
252 k = count_leading_zeros(history) + ((history + 16) >> 6 /* / 64 */) - 24;
254 extrabits = show_bits(&alac->gb, k);
256 block_size = (((1 << k) - 1) & rice_kmodifier_mask) * x
262 get_bits(&alac->gb, k - 1);
264 get_bits(&alac->gb, k);
268 if (block_size > 0) {
269 memset(&output_buffer[output_count+1], 0, block_size * 4);
270 output_count += block_size;
274 if (block_size > 0xffff)
282 #define SIGN_EXTENDED32(val, bits) ((val << (32 - bits)) >> (32 - bits))
284 #define SIGN_ONLY(v) \
289 static void predictor_decompress_fir_adapt(int32_t *error_buffer,
293 int16_t *predictor_coef_table,
294 int predictor_coef_num,
295 int predictor_quantitization)
299 /* first sample always copies */
300 *buffer_out = *error_buffer;
302 if (!predictor_coef_num) {
303 if (output_size <= 1) return;
304 memcpy(buffer_out+1, error_buffer+1, (output_size-1) * 4);
308 if (predictor_coef_num == 0x1f) { /* 11111 - max value of predictor_coef_num */
309 /* second-best case scenario for fir decompression,
310 * error describes a small difference from the previous sample only
312 if (output_size <= 1) return;
313 for (i = 0; i < output_size - 1; i++) {
317 prev_value = buffer_out[i];
318 error_value = error_buffer[i+1];
319 buffer_out[i+1] = SIGN_EXTENDED32((prev_value + error_value), readsamplesize);
324 /* read warm-up samples */
325 if (predictor_coef_num > 0) {
327 for (i = 0; i < predictor_coef_num; i++) {
330 val = buffer_out[i] + error_buffer[i+1];
332 val = SIGN_EXTENDED32(val, readsamplesize);
334 buffer_out[i+1] = val;
339 /* 4 and 8 are very common cases (the only ones i've seen). these
340 * should be unrolled and optimised
342 if (predictor_coef_num == 4) {
343 /* FIXME: optimised general case */
347 if (predictor_coef_table == 8) {
348 /* FIXME: optimised general case */
355 if (predictor_coef_num > 0) {
356 for (i = predictor_coef_num + 1;
362 int error_val = error_buffer[i];
364 for (j = 0; j < predictor_coef_num; j++) {
365 sum += (buffer_out[predictor_coef_num-j] - buffer_out[0]) *
366 predictor_coef_table[j];
369 outval = (1 << (predictor_quantitization-1)) + sum;
370 outval = outval >> predictor_quantitization;
371 outval = outval + buffer_out[0] + error_val;
372 outval = SIGN_EXTENDED32(outval, readsamplesize);
374 buffer_out[predictor_coef_num+1] = outval;
377 int predictor_num = predictor_coef_num - 1;
379 while (predictor_num >= 0 && error_val > 0) {
380 int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
381 int sign = SIGN_ONLY(val);
383 predictor_coef_table[predictor_num] -= sign;
385 val *= sign; /* absolute value */
387 error_val -= ((val >> predictor_quantitization) *
388 (predictor_coef_num - predictor_num));
392 } else if (error_val < 0) {
393 int predictor_num = predictor_coef_num - 1;
395 while (predictor_num >= 0 && error_val < 0) {
396 int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
397 int sign = - SIGN_ONLY(val);
399 predictor_coef_table[predictor_num] -= sign;
401 val *= sign; /* neg value */
403 error_val -= ((val >> predictor_quantitization) *
404 (predictor_coef_num - predictor_num));
415 static void deinterlace_16(int32_t *buffer_a, int32_t *buffer_b,
417 int numchannels, int numsamples,
418 uint8_t interlacing_shift,
419 uint8_t interlacing_leftweight)
422 if (numsamples <= 0) return;
424 /* weighted interlacing */
425 if (interlacing_leftweight) {
426 for (i = 0; i < numsamples; i++) {
427 int32_t difference, midright;
431 midright = buffer_a[i];
432 difference = buffer_b[i];
435 right = midright - ((difference * interlacing_leftweight) >> interlacing_shift);
436 left = (midright - ((difference * interlacing_leftweight) >> interlacing_shift))
439 buffer_out[i*numchannels] = left;
440 buffer_out[i*numchannels + 1] = right;
446 /* otherwise basic interlacing took place */
447 for (i = 0; i < numsamples; i++) {
453 buffer_out[i*numchannels] = left;
454 buffer_out[i*numchannels + 1] = right;
458 static int alac_decode_frame(AVCodecContext *avctx,
459 void *outbuffer, int *outputsize,
460 uint8_t *inbuffer, int input_buffer_size)
462 ALACContext *alac = avctx->priv_data;
465 int32_t outputsamples;
470 uint8_t interlacing_shift;
471 uint8_t interlacing_leftweight;
473 /* short-circuit null buffers */
474 if (!inbuffer || !input_buffer_size)
475 return input_buffer_size;
477 /* initialize from the extradata */
478 if (!alac->context_initialized) {
479 if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
480 av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
481 ALAC_EXTRADATA_SIZE);
482 return input_buffer_size;
484 if (alac_set_info(alac)) {
485 av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
486 return input_buffer_size;
488 alac->context_initialized = 1;
491 init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
493 channels = get_bits(&alac->gb, 3) + 1;
494 if (channels > MAX_CHANNELS) {
495 av_log(avctx, AV_LOG_ERROR, "channels > %d not supported\n",
497 return input_buffer_size;
500 /* 2^result = something to do with output waiting.
501 * perhaps matters if we read > 1 frame in a pass?
503 get_bits(&alac->gb, 4);
505 get_bits(&alac->gb, 12); /* unknown, skip 12 bits */
507 /* the output sample size is stored soon */
508 hassize = get_bits(&alac->gb, 1);
510 wasted_bytes = get_bits(&alac->gb, 2); /* unknown ? */
512 /* whether the frame is compressed */
513 isnotcompressed = get_bits(&alac->gb, 1);
516 /* now read the number of samples as a 32bit integer */
517 outputsamples = get_bits(&alac->gb, 32);
519 outputsamples = alac->setinfo_max_samples_per_frame;
521 *outputsize = outputsamples * alac->bytespersample;
522 readsamplesize = alac->setinfo_sample_size - (wasted_bytes * 8) + channels - 1;
524 if (!isnotcompressed) {
525 /* so it is compressed */
526 int16_t predictor_coef_table[channels][32];
527 int predictor_coef_num[channels];
528 int prediction_type[channels];
529 int prediction_quantitization[channels];
530 int ricemodifier[channels];
533 interlacing_shift = get_bits(&alac->gb, 8);
534 interlacing_leftweight = get_bits(&alac->gb, 8);
536 for (chan = 0; chan < channels; chan++) {
537 prediction_type[chan] = get_bits(&alac->gb, 4);
538 prediction_quantitization[chan] = get_bits(&alac->gb, 4);
540 ricemodifier[chan] = get_bits(&alac->gb, 3);
541 predictor_coef_num[chan] = get_bits(&alac->gb, 5);
543 /* read the predictor table */
544 for (i = 0; i < predictor_coef_num[chan]; i++) {
545 predictor_coef_table[chan][i] = (int16_t)get_bits(&alac->gb, 16);
550 av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented, unhandling of wasted_bytes\n");
553 for (chan = 0; chan < channels; chan++) {
554 bastardized_rice_decompress(alac,
555 alac->predicterror_buffer[chan],
558 alac->setinfo_rice_initialhistory,
559 alac->setinfo_rice_kmodifier,
560 ricemodifier[chan] * alac->setinfo_rice_historymult / 4,
561 (1 << alac->setinfo_rice_kmodifier) - 1);
563 if (prediction_type[chan] == 0) {
565 predictor_decompress_fir_adapt(alac->predicterror_buffer[chan],
566 alac->outputsamples_buffer[chan],
569 predictor_coef_table[chan],
570 predictor_coef_num[chan],
571 prediction_quantitization[chan]);
573 av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type[chan]);
574 /* i think the only other prediction type (or perhaps this is just a
575 * boolean?) runs adaptive fir twice.. like:
576 * predictor_decompress_fir_adapt(predictor_error, tempout, ...)
577 * predictor_decompress_fir_adapt(predictor_error, outputsamples ...)
583 /* not compressed, easy case */
584 if (alac->setinfo_sample_size <= 16) {
586 for (chan = 0; chan < channels; chan++) {
587 for (i = 0; i < outputsamples; i++) {
590 audiobits = get_bits(&alac->gb, alac->setinfo_sample_size);
591 audiobits = SIGN_EXTENDED32(audiobits, readsamplesize);
593 alac->outputsamples_buffer[chan][i] = audiobits;
598 for (chan = 0; chan < channels; chan++) {
599 for (i = 0; i < outputsamples; i++) {
602 audiobits = get_bits(&alac->gb, 16);
603 /* special case of sign extension..
604 * as we'll be ORing the low 16bits into this */
605 audiobits = audiobits << 16;
606 audiobits = audiobits >> (32 - alac->setinfo_sample_size);
607 audiobits |= get_bits(&alac->gb, alac->setinfo_sample_size - 16);
609 alac->outputsamples_buffer[chan][i] = audiobits;
613 /* wasted_bytes = 0; */
614 interlacing_shift = 0;
615 interlacing_leftweight = 0;
618 switch(alac->setinfo_sample_size) {
621 deinterlace_16(alac->outputsamples_buffer[0],
622 alac->outputsamples_buffer[1],
627 interlacing_leftweight);
630 for (i = 0; i < outputsamples; i++) {
631 int16_t sample = alac->outputsamples_buffer[0][i];
632 ((int16_t*)outbuffer)[i * alac->numchannels] = sample;
640 av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
646 return input_buffer_size;
649 static int alac_decode_init(AVCodecContext * avctx)
651 ALACContext *alac = avctx->priv_data;
653 alac->context_initialized = 0;
655 alac->samplesize = alac->avctx->bits_per_sample;
656 alac->numchannels = alac->avctx->channels;
657 alac->bytespersample = (alac->samplesize / 8) * alac->numchannels;
662 static int alac_decode_close(AVCodecContext *avctx)
664 ALACContext *alac = avctx->priv_data;
667 for (chan = 0; chan < MAX_CHANNELS; chan++) {
668 av_free(alac->predicterror_buffer[chan]);
669 av_free(alac->outputsamples_buffer[chan]);
675 AVCodec alac_decoder = {