2 * ALAC (Apple Lossless Audio Codec) decoder
3 * Copyright (c) 2005 David Hammerton
6 * This file is part of FFmpeg.
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 * ALAC (Apple Lossless Audio Codec) decoder
26 * @author 2005 David Hammerton
28 * For more information on the ALAC format, visit:
29 * http://crazney.net/programs/itunes/alac.html
31 * Note: This decoder expects a 36- (0x24-)byte QuickTime atom to be
32 * passed through the extradata[_size] fields. This atom is tacked onto
33 * the end of an 'alac' stsd atom and has the following format:
34 * bytes 0-3 atom size (0x24), big-endian
35 * bytes 4-7 atom type ('alac', not the 'alac' tag from start of stsd)
36 * bytes 8-35 data bytes needed by decoder
42 * 32bit max sample per frame
46 * 8bit initial history
50 * 32bit max coded frame size
57 #include "bitstream.h"
59 #define ALAC_EXTRADATA_SIZE 36
63 AVCodecContext *avctx;
65 /* init to 0; first frame decode should initialize from extradata and
67 int context_initialized;
74 int32_t *predicterror_buffer_a;
75 int32_t *predicterror_buffer_b;
77 int32_t *outputsamples_buffer_a;
78 int32_t *outputsamples_buffer_b;
80 /* stuff from setinfo */
81 uint32_t setinfo_max_samples_per_frame; /* 0x1000 = 4096 */ /* max samples per frame? */
82 uint8_t setinfo_7a; /* 0x00 */
83 uint8_t setinfo_sample_size; /* 0x10 */
84 uint8_t setinfo_rice_historymult; /* 0x28 */
85 uint8_t setinfo_rice_initialhistory; /* 0x0a */
86 uint8_t setinfo_rice_kmodifier; /* 0x0e */
87 uint8_t setinfo_7f; /* 0x02 */
88 uint16_t setinfo_80; /* 0x00ff */
89 uint32_t setinfo_82; /* 0x000020e7 */
90 uint32_t setinfo_86; /* 0x00069fe4 */
91 uint32_t setinfo_8a_rate; /* 0x0000ac44 */
92 /* end setinfo stuff */
96 static void allocate_buffers(ALACContext *alac)
98 alac->predicterror_buffer_a = av_malloc(alac->setinfo_max_samples_per_frame * 4);
99 alac->predicterror_buffer_b = av_malloc(alac->setinfo_max_samples_per_frame * 4);
101 alac->outputsamples_buffer_a = av_malloc(alac->setinfo_max_samples_per_frame * 4);
102 alac->outputsamples_buffer_b = av_malloc(alac->setinfo_max_samples_per_frame * 4);
105 static int alac_set_info(ALACContext *alac)
107 unsigned char *ptr = alac->avctx->extradata;
113 if(BE_32(ptr) >= UINT_MAX/4){
114 av_log(alac->avctx, AV_LOG_ERROR, "setinfo_max_samples_per_frame too large\n");
117 alac->setinfo_max_samples_per_frame = BE_32(ptr); /* buffer size / 2 ? */
119 alac->setinfo_7a = *ptr++;
120 alac->setinfo_sample_size = *ptr++;
121 alac->setinfo_rice_historymult = *ptr++;
122 alac->setinfo_rice_initialhistory = *ptr++;
123 alac->setinfo_rice_kmodifier = *ptr++;
124 alac->setinfo_7f = *ptr++; // channels?
125 alac->setinfo_80 = BE_16(ptr);
127 alac->setinfo_82 = BE_32(ptr); // max coded frame size
129 alac->setinfo_86 = BE_32(ptr); // bitrate ?
131 alac->setinfo_8a_rate = BE_32(ptr); // samplerate
134 allocate_buffers(alac);
139 /* hideously inefficient. could use a bitmask search,
140 * alternatively bsr on x86,
142 static int count_leading_zeros(int32_t input)
145 while (!(0x80000000 & input) && i < 32) {
152 static void bastardized_rice_decompress(ALACContext *alac,
153 int32_t *output_buffer,
155 int readsamplesize, /* arg_10 */
156 int rice_initialhistory, /* arg424->b */
157 int rice_kmodifier, /* arg424->d */
158 int rice_historymult, /* arg424->c */
159 int rice_kmodifier_mask /* arg424->e */
163 unsigned int history = rice_initialhistory;
164 int sign_modifier = 0;
166 for (output_count = 0; output_count < output_size; output_count++) {
171 /* read x - number of 1s before 0 represent the rice */
172 while (x <= 8 && get_bits1(&alac->gb)) {
177 if (x > 8) { /* RICE THRESHOLD */
178 /* use alternative encoding */
181 value = get_bits(&alac->gb, readsamplesize);
183 /* mask value to readsamplesize size */
184 if (readsamplesize != 32)
185 value &= (0xffffffff >> (32 - readsamplesize));
189 /* standard rice encoding */
191 int k; /* size of extra bits */
193 /* read k, that is bits as is */
194 k = 31 - rice_kmodifier - count_leading_zeros((history >> 9) + 3);
202 extrabits = show_bits(&alac->gb, k);
204 /* multiply x by 2^k - 1, as part of their strange algorithm */
209 get_bits(&alac->gb, k);
211 get_bits(&alac->gb, k - 1);
216 x_modified = sign_modifier + x;
217 final_val = (x_modified + 1) / 2;
218 if (x_modified & 1) final_val *= -1;
220 output_buffer[output_count] = final_val;
224 /* now update the history */
225 history += (x_modified * rice_historymult)
226 - ((history * rice_historymult) >> 9);
228 if (x_modified > 0xffff)
231 /* special case: there may be compressed blocks of 0 */
232 if ((history < 128) && (output_count+1 < output_size)) {
238 while (x <= 8 && get_bits1(&alac->gb)) {
243 block_size = get_bits(&alac->gb, 16);
244 block_size &= 0xffff;
249 k = count_leading_zeros(history) + ((history + 16) >> 6 /* / 64 */) - 24;
251 extrabits = show_bits(&alac->gb, k);
253 block_size = (((1 << k) - 1) & rice_kmodifier_mask) * x
259 get_bits(&alac->gb, k - 1);
261 get_bits(&alac->gb, k);
265 if (block_size > 0) {
266 memset(&output_buffer[output_count+1], 0, block_size * 4);
267 output_count += block_size;
271 if (block_size > 0xffff)
279 #define SIGN_EXTENDED32(val, bits) ((val << (32 - bits)) >> (32 - bits))
281 #define SIGN_ONLY(v) \
286 static void predictor_decompress_fir_adapt(int32_t *error_buffer,
290 int16_t *predictor_coef_table,
291 int predictor_coef_num,
292 int predictor_quantitization)
296 /* first sample always copies */
297 *buffer_out = *error_buffer;
299 if (!predictor_coef_num) {
300 if (output_size <= 1) return;
301 memcpy(buffer_out+1, error_buffer+1, (output_size-1) * 4);
305 if (predictor_coef_num == 0x1f) { /* 11111 - max value of predictor_coef_num */
306 /* second-best case scenario for fir decompression,
307 * error describes a small difference from the previous sample only
309 if (output_size <= 1) return;
310 for (i = 0; i < output_size - 1; i++) {
314 prev_value = buffer_out[i];
315 error_value = error_buffer[i+1];
316 buffer_out[i+1] = SIGN_EXTENDED32((prev_value + error_value), readsamplesize);
321 /* read warm-up samples */
322 if (predictor_coef_num > 0) {
324 for (i = 0; i < predictor_coef_num; i++) {
327 val = buffer_out[i] + error_buffer[i+1];
329 val = SIGN_EXTENDED32(val, readsamplesize);
331 buffer_out[i+1] = val;
336 /* 4 and 8 are very common cases (the only ones i've seen). these
337 * should be unrolled and optimised
339 if (predictor_coef_num == 4) {
340 /* FIXME: optimised general case */
344 if (predictor_coef_table == 8) {
345 /* FIXME: optimised general case */
352 if (predictor_coef_num > 0) {
353 for (i = predictor_coef_num + 1;
359 int error_val = error_buffer[i];
361 for (j = 0; j < predictor_coef_num; j++) {
362 sum += (buffer_out[predictor_coef_num-j] - buffer_out[0]) *
363 predictor_coef_table[j];
366 outval = (1 << (predictor_quantitization-1)) + sum;
367 outval = outval >> predictor_quantitization;
368 outval = outval + buffer_out[0] + error_val;
369 outval = SIGN_EXTENDED32(outval, readsamplesize);
371 buffer_out[predictor_coef_num+1] = outval;
374 int predictor_num = predictor_coef_num - 1;
376 while (predictor_num >= 0 && error_val > 0) {
377 int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
378 int sign = SIGN_ONLY(val);
380 predictor_coef_table[predictor_num] -= sign;
382 val *= sign; /* absolute value */
384 error_val -= ((val >> predictor_quantitization) *
385 (predictor_coef_num - predictor_num));
389 } else if (error_val < 0) {
390 int predictor_num = predictor_coef_num - 1;
392 while (predictor_num >= 0 && error_val < 0) {
393 int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
394 int sign = - SIGN_ONLY(val);
396 predictor_coef_table[predictor_num] -= sign;
398 val *= sign; /* neg value */
400 error_val -= ((val >> predictor_quantitization) *
401 (predictor_coef_num - predictor_num));
412 static void deinterlace_16(int32_t *buffer_a, int32_t *buffer_b,
414 int numchannels, int numsamples,
415 uint8_t interlacing_shift,
416 uint8_t interlacing_leftweight)
419 if (numsamples <= 0) return;
421 /* weighted interlacing */
422 if (interlacing_leftweight) {
423 for (i = 0; i < numsamples; i++) {
424 int32_t difference, midright;
428 midright = buffer_a[i];
429 difference = buffer_b[i];
432 right = midright - ((difference * interlacing_leftweight) >> interlacing_shift);
433 left = (midright - ((difference * interlacing_leftweight) >> interlacing_shift))
436 buffer_out[i*numchannels] = left;
437 buffer_out[i*numchannels + 1] = right;
443 /* otherwise basic interlacing took place */
444 for (i = 0; i < numsamples; i++) {
450 buffer_out[i*numchannels] = left;
451 buffer_out[i*numchannels + 1] = right;
455 static int alac_decode_frame(AVCodecContext *avctx,
456 void *outbuffer, int *outputsize,
457 uint8_t *inbuffer, int input_buffer_size)
459 ALACContext *alac = avctx->priv_data;
462 int32_t outputsamples;
464 /* short-circuit null buffers */
465 if (!inbuffer || !input_buffer_size)
466 return input_buffer_size;
468 /* initialize from the extradata */
469 if (!alac->context_initialized) {
470 if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
471 av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
472 ALAC_EXTRADATA_SIZE);
473 return input_buffer_size;
476 alac->context_initialized = 1;
479 outputsamples = alac->setinfo_max_samples_per_frame;
481 init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
483 channels = get_bits(&alac->gb, 3);
485 *outputsize = outputsamples * alac->bytespersample;
488 case 0: { /* 1 channel */
497 /* 2^result = something to do with output waiting.
498 * perhaps matters if we read > 1 frame in a pass?
500 get_bits(&alac->gb, 4);
502 get_bits(&alac->gb, 12); /* unknown, skip 12 bits */
504 hassize = get_bits(&alac->gb, 1); /* the output sample size is stored soon */
506 wasted_bytes = get_bits(&alac->gb, 2); /* unknown ? */
508 isnotcompressed = get_bits(&alac->gb, 1); /* whether the frame is compressed */
511 /* now read the number of samples,
512 * as a 32bit integer */
513 outputsamples = get_bits(&alac->gb, 32);
514 *outputsize = outputsamples * alac->bytespersample;
517 readsamplesize = alac->setinfo_sample_size - (wasted_bytes * 8);
519 if (!isnotcompressed) {
520 /* so it is compressed */
521 int16_t predictor_coef_table[32];
522 int predictor_coef_num;
524 int prediction_quantitization;
527 /* FIXME: skip 16 bits, not sure what they are. seem to be used in
528 * two channel case */
529 get_bits(&alac->gb, 8);
530 get_bits(&alac->gb, 8);
532 prediction_type = get_bits(&alac->gb, 4);
533 prediction_quantitization = get_bits(&alac->gb, 4);
535 ricemodifier = get_bits(&alac->gb, 3);
536 predictor_coef_num = get_bits(&alac->gb, 5);
538 /* read the predictor table */
539 for (i = 0; i < predictor_coef_num; i++) {
540 predictor_coef_table[i] = (int16_t)get_bits(&alac->gb, 16);
544 /* these bytes seem to have something to do with
547 av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented, unhandling of wasted_bytes\n");
550 bastardized_rice_decompress(alac,
551 alac->predicterror_buffer_a,
554 alac->setinfo_rice_initialhistory,
555 alac->setinfo_rice_kmodifier,
556 ricemodifier * alac->setinfo_rice_historymult / 4,
557 (1 << alac->setinfo_rice_kmodifier) - 1);
559 if (prediction_type == 0) {
561 predictor_decompress_fir_adapt(alac->predicterror_buffer_a,
562 alac->outputsamples_buffer_a,
565 predictor_coef_table,
567 prediction_quantitization);
569 av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type);
570 /* i think the only other prediction type (or perhaps this is just a
571 * boolean?) runs adaptive fir twice.. like:
572 * predictor_decompress_fir_adapt(predictor_error, tempout, ...)
573 * predictor_decompress_fir_adapt(predictor_error, outputsamples ...)
579 /* not compressed, easy case */
580 if (readsamplesize <= 16) {
582 for (i = 0; i < outputsamples; i++) {
583 int32_t audiobits = get_bits(&alac->gb, readsamplesize);
585 audiobits = SIGN_EXTENDED32(audiobits, readsamplesize);
587 alac->outputsamples_buffer_a[i] = audiobits;
591 for (i = 0; i < outputsamples; i++) {
594 audiobits = get_bits(&alac->gb, 16);
595 /* special case of sign extension..
596 * as we'll be ORing the low 16bits into this */
597 audiobits = audiobits << 16;
598 audiobits = audiobits >> (32 - readsamplesize);
600 audiobits |= get_bits(&alac->gb, readsamplesize - 16);
602 alac->outputsamples_buffer_a[i] = audiobits;
605 /* wasted_bytes = 0; // unused */
608 switch(alac->setinfo_sample_size) {
611 for (i = 0; i < outputsamples; i++) {
612 int16_t sample = alac->outputsamples_buffer_a[i];
613 ((int16_t*)outbuffer)[i * alac->numchannels] = sample;
620 av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
627 case 1: { /* 2 channels */
634 uint8_t interlacing_shift;
635 uint8_t interlacing_leftweight;
637 /* 2^result = something to do with output waiting.
638 * perhaps matters if we read > 1 frame in a pass?
640 get_bits(&alac->gb, 4);
642 get_bits(&alac->gb, 12); /* unknown, skip 12 bits */
644 hassize = get_bits(&alac->gb, 1); /* the output sample size is stored soon */
646 wasted_bytes = get_bits(&alac->gb, 2); /* unknown ? */
648 isnotcompressed = get_bits(&alac->gb, 1); /* whether the frame is compressed */
651 /* now read the number of samples,
652 * as a 32bit integer */
653 outputsamples = get_bits(&alac->gb, 32);
654 *outputsize = outputsamples * alac->bytespersample;
657 readsamplesize = alac->setinfo_sample_size - (wasted_bytes * 8) + 1;
659 if (!isnotcompressed) {
661 int16_t predictor_coef_table_a[32];
662 int predictor_coef_num_a;
663 int prediction_type_a;
664 int prediction_quantitization_a;
667 int16_t predictor_coef_table_b[32];
668 int predictor_coef_num_b;
669 int prediction_type_b;
670 int prediction_quantitization_b;
675 interlacing_shift = get_bits(&alac->gb, 8);
676 interlacing_leftweight = get_bits(&alac->gb, 8);
678 /******** channel 1 ***********/
679 prediction_type_a = get_bits(&alac->gb, 4);
680 prediction_quantitization_a = get_bits(&alac->gb, 4);
682 ricemodifier_a = get_bits(&alac->gb, 3);
683 predictor_coef_num_a = get_bits(&alac->gb, 5);
685 /* read the predictor table */
686 for (i = 0; i < predictor_coef_num_a; i++) {
687 predictor_coef_table_a[i] = (int16_t)get_bits(&alac->gb, 16);
690 /******** channel 2 *********/
691 prediction_type_b = get_bits(&alac->gb, 4);
692 prediction_quantitization_b = get_bits(&alac->gb, 4);
694 ricemodifier_b = get_bits(&alac->gb, 3);
695 predictor_coef_num_b = get_bits(&alac->gb, 5);
697 /* read the predictor table */
698 for (i = 0; i < predictor_coef_num_b; i++) {
699 predictor_coef_table_b[i] = (int16_t)get_bits(&alac->gb, 16);
702 /*********************/
705 av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented, unhandling of wasted_bytes\n");
709 bastardized_rice_decompress(alac,
710 alac->predicterror_buffer_a,
713 alac->setinfo_rice_initialhistory,
714 alac->setinfo_rice_kmodifier,
715 ricemodifier_a * alac->setinfo_rice_historymult / 4,
716 (1 << alac->setinfo_rice_kmodifier) - 1);
718 if (prediction_type_a == 0) {
720 predictor_decompress_fir_adapt(alac->predicterror_buffer_a,
721 alac->outputsamples_buffer_a,
724 predictor_coef_table_a,
725 predictor_coef_num_a,
726 prediction_quantitization_a);
729 av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type_a);
733 bastardized_rice_decompress(alac,
734 alac->predicterror_buffer_b,
737 alac->setinfo_rice_initialhistory,
738 alac->setinfo_rice_kmodifier,
739 ricemodifier_b * alac->setinfo_rice_historymult / 4,
740 (1 << alac->setinfo_rice_kmodifier) - 1);
742 if (prediction_type_b == 0) {
744 predictor_decompress_fir_adapt(alac->predicterror_buffer_b,
745 alac->outputsamples_buffer_b,
748 predictor_coef_table_b,
749 predictor_coef_num_b,
750 prediction_quantitization_b);
752 av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type_b);
755 /* not compressed, easy case */
756 if (alac->setinfo_sample_size <= 16) {
758 for (i = 0; i < outputsamples; i++) {
759 int32_t audiobits_a, audiobits_b;
761 audiobits_a = get_bits(&alac->gb, alac->setinfo_sample_size);
762 audiobits_b = get_bits(&alac->gb, alac->setinfo_sample_size);
764 audiobits_a = SIGN_EXTENDED32(audiobits_a, alac->setinfo_sample_size);
765 audiobits_b = SIGN_EXTENDED32(audiobits_b, alac->setinfo_sample_size);
767 alac->outputsamples_buffer_a[i] = audiobits_a;
768 alac->outputsamples_buffer_b[i] = audiobits_b;
772 for (i = 0; i < outputsamples; i++) {
773 int32_t audiobits_a, audiobits_b;
775 audiobits_a = get_bits(&alac->gb, 16);
776 audiobits_a = audiobits_a << 16;
777 audiobits_a = audiobits_a >> (32 - alac->setinfo_sample_size);
778 audiobits_a |= get_bits(&alac->gb, alac->setinfo_sample_size - 16);
780 audiobits_b = get_bits(&alac->gb, 16);
781 audiobits_b = audiobits_b << 16;
782 audiobits_b = audiobits_b >> (32 - alac->setinfo_sample_size);
783 audiobits_b |= get_bits(&alac->gb, alac->setinfo_sample_size - 16);
785 alac->outputsamples_buffer_a[i] = audiobits_a;
786 alac->outputsamples_buffer_b[i] = audiobits_b;
789 /* wasted_bytes = 0; */
790 interlacing_shift = 0;
791 interlacing_leftweight = 0;
794 switch(alac->setinfo_sample_size) {
796 deinterlace_16(alac->outputsamples_buffer_a,
797 alac->outputsamples_buffer_b,
802 interlacing_leftweight);
808 av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
818 return input_buffer_size;
821 static int alac_decode_init(AVCodecContext * avctx)
823 ALACContext *alac = avctx->priv_data;
825 alac->context_initialized = 0;
827 alac->samplesize = alac->avctx->bits_per_sample;
828 alac->numchannels = alac->avctx->channels;
829 alac->bytespersample = (alac->samplesize / 8) * alac->numchannels;
834 static int alac_decode_close(AVCodecContext *avctx)
836 ALACContext *alac = avctx->priv_data;
838 av_free(alac->predicterror_buffer_a);
839 av_free(alac->predicterror_buffer_b);
841 av_free(alac->outputsamples_buffer_a);
842 av_free(alac->outputsamples_buffer_b);
847 AVCodec alac_decoder = {