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;
475 if (alac_set_info(alac)) {
476 av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
477 return input_buffer_size;
479 alac->context_initialized = 1;
482 outputsamples = alac->setinfo_max_samples_per_frame;
484 init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
486 channels = get_bits(&alac->gb, 3);
488 *outputsize = outputsamples * alac->bytespersample;
491 case 0: { /* 1 channel */
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 hassize = get_bits(&alac->gb, 1); /* the output sample size is stored soon */
509 wasted_bytes = get_bits(&alac->gb, 2); /* unknown ? */
511 isnotcompressed = get_bits(&alac->gb, 1); /* whether the frame is compressed */
514 /* now read the number of samples,
515 * as a 32bit integer */
516 outputsamples = get_bits(&alac->gb, 32);
517 *outputsize = outputsamples * alac->bytespersample;
520 readsamplesize = alac->setinfo_sample_size - (wasted_bytes * 8);
522 if (!isnotcompressed) {
523 /* so it is compressed */
524 int16_t predictor_coef_table[32];
525 int predictor_coef_num;
527 int prediction_quantitization;
530 /* FIXME: skip 16 bits, not sure what they are. seem to be used in
531 * two channel case */
532 get_bits(&alac->gb, 8);
533 get_bits(&alac->gb, 8);
535 prediction_type = get_bits(&alac->gb, 4);
536 prediction_quantitization = get_bits(&alac->gb, 4);
538 ricemodifier = get_bits(&alac->gb, 3);
539 predictor_coef_num = get_bits(&alac->gb, 5);
541 /* read the predictor table */
542 for (i = 0; i < predictor_coef_num; i++) {
543 predictor_coef_table[i] = (int16_t)get_bits(&alac->gb, 16);
547 /* these bytes seem to have something to do with
550 av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented, unhandling of wasted_bytes\n");
553 bastardized_rice_decompress(alac,
554 alac->predicterror_buffer_a,
557 alac->setinfo_rice_initialhistory,
558 alac->setinfo_rice_kmodifier,
559 ricemodifier * alac->setinfo_rice_historymult / 4,
560 (1 << alac->setinfo_rice_kmodifier) - 1);
562 if (prediction_type == 0) {
564 predictor_decompress_fir_adapt(alac->predicterror_buffer_a,
565 alac->outputsamples_buffer_a,
568 predictor_coef_table,
570 prediction_quantitization);
572 av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type);
573 /* i think the only other prediction type (or perhaps this is just a
574 * boolean?) runs adaptive fir twice.. like:
575 * predictor_decompress_fir_adapt(predictor_error, tempout, ...)
576 * predictor_decompress_fir_adapt(predictor_error, outputsamples ...)
582 /* not compressed, easy case */
583 if (readsamplesize <= 16) {
585 for (i = 0; i < outputsamples; i++) {
586 int32_t audiobits = get_bits(&alac->gb, readsamplesize);
588 audiobits = SIGN_EXTENDED32(audiobits, readsamplesize);
590 alac->outputsamples_buffer_a[i] = audiobits;
594 for (i = 0; i < outputsamples; i++) {
597 audiobits = get_bits(&alac->gb, 16);
598 /* special case of sign extension..
599 * as we'll be ORing the low 16bits into this */
600 audiobits = audiobits << 16;
601 audiobits = audiobits >> (32 - readsamplesize);
603 audiobits |= get_bits(&alac->gb, readsamplesize - 16);
605 alac->outputsamples_buffer_a[i] = audiobits;
608 /* wasted_bytes = 0; // unused */
611 switch(alac->setinfo_sample_size) {
614 for (i = 0; i < outputsamples; i++) {
615 int16_t sample = alac->outputsamples_buffer_a[i];
616 ((int16_t*)outbuffer)[i * alac->numchannels] = sample;
623 av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
630 case 1: { /* 2 channels */
637 uint8_t interlacing_shift;
638 uint8_t interlacing_leftweight;
640 /* 2^result = something to do with output waiting.
641 * perhaps matters if we read > 1 frame in a pass?
643 get_bits(&alac->gb, 4);
645 get_bits(&alac->gb, 12); /* unknown, skip 12 bits */
647 hassize = get_bits(&alac->gb, 1); /* the output sample size is stored soon */
649 wasted_bytes = get_bits(&alac->gb, 2); /* unknown ? */
651 isnotcompressed = get_bits(&alac->gb, 1); /* whether the frame is compressed */
654 /* now read the number of samples,
655 * as a 32bit integer */
656 outputsamples = get_bits(&alac->gb, 32);
657 *outputsize = outputsamples * alac->bytespersample;
660 readsamplesize = alac->setinfo_sample_size - (wasted_bytes * 8) + 1;
662 if (!isnotcompressed) {
664 int16_t predictor_coef_table_a[32];
665 int predictor_coef_num_a;
666 int prediction_type_a;
667 int prediction_quantitization_a;
670 int16_t predictor_coef_table_b[32];
671 int predictor_coef_num_b;
672 int prediction_type_b;
673 int prediction_quantitization_b;
678 interlacing_shift = get_bits(&alac->gb, 8);
679 interlacing_leftweight = get_bits(&alac->gb, 8);
681 /******** channel 1 ***********/
682 prediction_type_a = get_bits(&alac->gb, 4);
683 prediction_quantitization_a = get_bits(&alac->gb, 4);
685 ricemodifier_a = get_bits(&alac->gb, 3);
686 predictor_coef_num_a = get_bits(&alac->gb, 5);
688 /* read the predictor table */
689 for (i = 0; i < predictor_coef_num_a; i++) {
690 predictor_coef_table_a[i] = (int16_t)get_bits(&alac->gb, 16);
693 /******** channel 2 *********/
694 prediction_type_b = get_bits(&alac->gb, 4);
695 prediction_quantitization_b = get_bits(&alac->gb, 4);
697 ricemodifier_b = get_bits(&alac->gb, 3);
698 predictor_coef_num_b = get_bits(&alac->gb, 5);
700 /* read the predictor table */
701 for (i = 0; i < predictor_coef_num_b; i++) {
702 predictor_coef_table_b[i] = (int16_t)get_bits(&alac->gb, 16);
705 /*********************/
708 av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented, unhandling of wasted_bytes\n");
712 bastardized_rice_decompress(alac,
713 alac->predicterror_buffer_a,
716 alac->setinfo_rice_initialhistory,
717 alac->setinfo_rice_kmodifier,
718 ricemodifier_a * alac->setinfo_rice_historymult / 4,
719 (1 << alac->setinfo_rice_kmodifier) - 1);
721 if (prediction_type_a == 0) {
723 predictor_decompress_fir_adapt(alac->predicterror_buffer_a,
724 alac->outputsamples_buffer_a,
727 predictor_coef_table_a,
728 predictor_coef_num_a,
729 prediction_quantitization_a);
732 av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type_a);
736 bastardized_rice_decompress(alac,
737 alac->predicterror_buffer_b,
740 alac->setinfo_rice_initialhistory,
741 alac->setinfo_rice_kmodifier,
742 ricemodifier_b * alac->setinfo_rice_historymult / 4,
743 (1 << alac->setinfo_rice_kmodifier) - 1);
745 if (prediction_type_b == 0) {
747 predictor_decompress_fir_adapt(alac->predicterror_buffer_b,
748 alac->outputsamples_buffer_b,
751 predictor_coef_table_b,
752 predictor_coef_num_b,
753 prediction_quantitization_b);
755 av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type_b);
758 /* not compressed, easy case */
759 if (alac->setinfo_sample_size <= 16) {
761 for (i = 0; i < outputsamples; i++) {
762 int32_t audiobits_a, audiobits_b;
764 audiobits_a = get_bits(&alac->gb, alac->setinfo_sample_size);
765 audiobits_b = get_bits(&alac->gb, alac->setinfo_sample_size);
767 audiobits_a = SIGN_EXTENDED32(audiobits_a, alac->setinfo_sample_size);
768 audiobits_b = SIGN_EXTENDED32(audiobits_b, alac->setinfo_sample_size);
770 alac->outputsamples_buffer_a[i] = audiobits_a;
771 alac->outputsamples_buffer_b[i] = audiobits_b;
775 for (i = 0; i < outputsamples; i++) {
776 int32_t audiobits_a, audiobits_b;
778 audiobits_a = get_bits(&alac->gb, 16);
779 audiobits_a = audiobits_a << 16;
780 audiobits_a = audiobits_a >> (32 - alac->setinfo_sample_size);
781 audiobits_a |= get_bits(&alac->gb, alac->setinfo_sample_size - 16);
783 audiobits_b = get_bits(&alac->gb, 16);
784 audiobits_b = audiobits_b << 16;
785 audiobits_b = audiobits_b >> (32 - alac->setinfo_sample_size);
786 audiobits_b |= get_bits(&alac->gb, alac->setinfo_sample_size - 16);
788 alac->outputsamples_buffer_a[i] = audiobits_a;
789 alac->outputsamples_buffer_b[i] = audiobits_b;
792 /* wasted_bytes = 0; */
793 interlacing_shift = 0;
794 interlacing_leftweight = 0;
797 switch(alac->setinfo_sample_size) {
799 deinterlace_16(alac->outputsamples_buffer_a,
800 alac->outputsamples_buffer_b,
805 interlacing_leftweight);
811 av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
821 return input_buffer_size;
824 static int alac_decode_init(AVCodecContext * avctx)
826 ALACContext *alac = avctx->priv_data;
828 alac->context_initialized = 0;
830 alac->samplesize = alac->avctx->bits_per_sample;
831 alac->numchannels = alac->avctx->channels;
832 alac->bytespersample = (alac->samplesize / 8) * alac->numchannels;
837 static int alac_decode_close(AVCodecContext *avctx)
839 ALACContext *alac = avctx->priv_data;
841 av_free(alac->predicterror_buffer_a);
842 av_free(alac->predicterror_buffer_b);
844 av_free(alac->outputsamples_buffer_a);
845 av_free(alac->outputsamples_buffer_b);
850 AVCodec alac_decoder = {