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"
60 #define ALAC_EXTRADATA_SIZE 36
61 #define MAX_CHANNELS 2
65 AVCodecContext *avctx;
67 /* init to 0; first frame decode should initialize from extradata and
69 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_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 */
89 static void allocate_buffers(ALACContext *alac)
92 for (chan = 0; chan < MAX_CHANNELS; chan++) {
93 alac->predicterror_buffer[chan] =
94 av_malloc(alac->setinfo_max_samples_per_frame * 4);
96 alac->outputsamples_buffer[chan] =
97 av_malloc(alac->setinfo_max_samples_per_frame * 4);
101 static int alac_set_info(ALACContext *alac)
103 const unsigned char *ptr = alac->avctx->extradata;
109 if(AV_RB32(ptr) >= UINT_MAX/4){
110 av_log(alac->avctx, AV_LOG_ERROR, "setinfo_max_samples_per_frame too large\n");
114 /* buffer size / 2 ? */
115 alac->setinfo_max_samples_per_frame = bytestream_get_be32(&ptr);
117 alac->setinfo_sample_size = *ptr++;
118 alac->setinfo_rice_historymult = *ptr++;
119 alac->setinfo_rice_initialhistory = *ptr++;
120 alac->setinfo_rice_kmodifier = *ptr++;
121 ptr++; /* channels? */
122 bytestream_get_be16(&ptr); /* ??? */
123 bytestream_get_be32(&ptr); /* max coded frame size */
124 bytestream_get_be32(&ptr); /* bitrate ? */
125 bytestream_get_be32(&ptr); /* samplerate */
127 allocate_buffers(alac);
132 static inline int decode_scalar(GetBitContext *gb, int k, int limit, int readsamplesize){
133 /* read x - number of 1s before 0 represent the rice */
134 int x = get_unary_0_9(gb);
136 if (x > 8) { /* RICE THRESHOLD */
137 /* use alternative encoding */
138 x = get_bits(gb, readsamplesize);
144 int extrabits = show_bits(gb, k);
146 /* multiply x by 2^k - 1, as part of their strange algorithm */
153 skip_bits(gb, k - 1);
159 static void bastardized_rice_decompress(ALACContext *alac,
160 int32_t *output_buffer,
162 int readsamplesize, /* arg_10 */
163 int rice_initialhistory, /* arg424->b */
164 int rice_kmodifier, /* arg424->d */
165 int rice_historymult, /* arg424->c */
166 int rice_kmodifier_mask /* arg424->e */
170 unsigned int history = rice_initialhistory;
171 int sign_modifier = 0;
173 for (output_count = 0; output_count < output_size; output_count++) {
178 /* standard rice encoding */
179 int k; /* size of extra bits */
181 /* read k, that is bits as is */
182 k = av_log2((history >> 9) + 3);
183 x= decode_scalar(&alac->gb, k, rice_kmodifier, readsamplesize);
185 x_modified = sign_modifier + x;
186 final_val = (x_modified + 1) / 2;
187 if (x_modified & 1) final_val *= -1;
189 output_buffer[output_count] = final_val;
193 /* now update the history */
194 history += x_modified * rice_historymult
195 - ((history * rice_historymult) >> 9);
197 if (x_modified > 0xffff)
200 /* special case: there may be compressed blocks of 0 */
201 if ((history < 128) && (output_count+1 < output_size)) {
203 unsigned int block_size;
207 k = 7 - av_log2(history) + ((history + 16) >> 6 /* / 64 */);
209 block_size= decode_scalar(&alac->gb, k, rice_kmodifier, 16);
211 if (block_size > 0) {
212 if(block_size >= output_size - output_count){
213 av_log(alac->avctx, AV_LOG_ERROR, "invalid zero block size of %d %d %d\n", block_size, output_size, output_count);
214 block_size= output_size - output_count - 1;
216 memset(&output_buffer[output_count+1], 0, block_size * 4);
217 output_count += block_size;
220 if (block_size > 0xffff)
228 static inline int32_t extend_sign32(int32_t val, int bits)
230 return (val << (32 - bits)) >> (32 - bits);
233 static inline int sign_only(int v)
235 return v ? FFSIGN(v) : 0;
238 static void predictor_decompress_fir_adapt(int32_t *error_buffer,
242 int16_t *predictor_coef_table,
243 int predictor_coef_num,
244 int predictor_quantitization)
248 /* first sample always copies */
249 *buffer_out = *error_buffer;
251 if (!predictor_coef_num) {
252 if (output_size <= 1)
255 memcpy(buffer_out+1, error_buffer+1, (output_size-1) * 4);
259 if (predictor_coef_num == 0x1f) { /* 11111 - max value of predictor_coef_num */
260 /* second-best case scenario for fir decompression,
261 * error describes a small difference from the previous sample only
263 if (output_size <= 1)
265 for (i = 0; i < output_size - 1; i++) {
269 prev_value = buffer_out[i];
270 error_value = error_buffer[i+1];
272 extend_sign32((prev_value + error_value), readsamplesize);
277 /* read warm-up samples */
278 if (predictor_coef_num > 0)
279 for (i = 0; i < predictor_coef_num; i++) {
282 val = buffer_out[i] + error_buffer[i+1];
283 val = extend_sign32(val, readsamplesize);
284 buffer_out[i+1] = val;
288 /* 4 and 8 are very common cases (the only ones i've seen). these
289 * should be unrolled and optimized
291 if (predictor_coef_num == 4) {
292 /* FIXME: optimized general case */
296 if (predictor_coef_table == 8) {
297 /* FIXME: optimized general case */
303 if (predictor_coef_num > 0) {
304 for (i = predictor_coef_num + 1; i < output_size; i++) {
308 int error_val = error_buffer[i];
310 for (j = 0; j < predictor_coef_num; j++) {
311 sum += (buffer_out[predictor_coef_num-j] - buffer_out[0]) *
312 predictor_coef_table[j];
315 outval = (1 << (predictor_quantitization-1)) + sum;
316 outval = outval >> predictor_quantitization;
317 outval = outval + buffer_out[0] + error_val;
318 outval = extend_sign32(outval, readsamplesize);
320 buffer_out[predictor_coef_num+1] = outval;
323 int predictor_num = predictor_coef_num - 1;
325 while (predictor_num >= 0 && error_val > 0) {
326 int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
327 int sign = sign_only(val);
329 predictor_coef_table[predictor_num] -= sign;
331 val *= sign; /* absolute value */
333 error_val -= ((val >> predictor_quantitization) *
334 (predictor_coef_num - predictor_num));
338 } else if (error_val < 0) {
339 int predictor_num = predictor_coef_num - 1;
341 while (predictor_num >= 0 && error_val < 0) {
342 int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
343 int sign = - sign_only(val);
345 predictor_coef_table[predictor_num] -= sign;
347 val *= sign; /* neg value */
349 error_val -= ((val >> predictor_quantitization) *
350 (predictor_coef_num - predictor_num));
361 static void reconstruct_stereo_16(int32_t *buffer[MAX_CHANNELS],
363 int numchannels, int numsamples,
364 uint8_t interlacing_shift,
365 uint8_t interlacing_leftweight)
371 /* weighted interlacing */
372 if (interlacing_leftweight) {
373 for (i = 0; i < numsamples; i++) {
379 a -= (b * interlacing_leftweight) >> interlacing_shift;
382 buffer_out[i*numchannels] = b;
383 buffer_out[i*numchannels + 1] = a;
389 /* otherwise basic interlacing took place */
390 for (i = 0; i < numsamples; i++) {
394 right = buffer[1][i];
396 buffer_out[i*numchannels] = left;
397 buffer_out[i*numchannels + 1] = right;
401 static int alac_decode_frame(AVCodecContext *avctx,
402 void *outbuffer, int *outputsize,
403 const uint8_t *inbuffer, int input_buffer_size)
405 ALACContext *alac = avctx->priv_data;
408 unsigned int outputsamples;
413 uint8_t interlacing_shift;
414 uint8_t interlacing_leftweight;
416 /* short-circuit null buffers */
417 if (!inbuffer || !input_buffer_size)
418 return input_buffer_size;
420 /* initialize from the extradata */
421 if (!alac->context_initialized) {
422 if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
423 av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
424 ALAC_EXTRADATA_SIZE);
425 return input_buffer_size;
427 if (alac_set_info(alac)) {
428 av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
429 return input_buffer_size;
431 alac->context_initialized = 1;
434 init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
436 channels = get_bits(&alac->gb, 3) + 1;
437 if (channels > MAX_CHANNELS) {
438 av_log(avctx, AV_LOG_ERROR, "channels > %d not supported\n",
440 return input_buffer_size;
443 /* 2^result = something to do with output waiting.
444 * perhaps matters if we read > 1 frame in a pass?
446 skip_bits(&alac->gb, 4);
448 skip_bits(&alac->gb, 12); /* unknown, skip 12 bits */
450 /* the output sample size is stored soon */
451 hassize = get_bits1(&alac->gb);
453 wasted_bytes = get_bits(&alac->gb, 2); /* unknown ? */
455 /* whether the frame is compressed */
456 isnotcompressed = get_bits1(&alac->gb);
459 /* now read the number of samples as a 32bit integer */
460 outputsamples = get_bits_long(&alac->gb, 32);
461 if(outputsamples > alac->setinfo_max_samples_per_frame){
462 av_log(avctx, AV_LOG_ERROR, "outputsamples %d > %d\n", outputsamples, alac->setinfo_max_samples_per_frame);
466 outputsamples = alac->setinfo_max_samples_per_frame;
468 if(outputsamples > *outputsize / alac->bytespersample){
469 av_log(avctx, AV_LOG_ERROR, "sample buffer too small\n");
473 *outputsize = outputsamples * alac->bytespersample;
474 readsamplesize = alac->setinfo_sample_size - (wasted_bytes * 8) + channels - 1;
476 if (!isnotcompressed) {
477 /* so it is compressed */
478 int16_t predictor_coef_table[channels][32];
479 int predictor_coef_num[channels];
480 int prediction_type[channels];
481 int prediction_quantitization[channels];
482 int ricemodifier[channels];
485 interlacing_shift = get_bits(&alac->gb, 8);
486 interlacing_leftweight = get_bits(&alac->gb, 8);
488 for (chan = 0; chan < channels; chan++) {
489 prediction_type[chan] = get_bits(&alac->gb, 4);
490 prediction_quantitization[chan] = get_bits(&alac->gb, 4);
492 ricemodifier[chan] = get_bits(&alac->gb, 3);
493 predictor_coef_num[chan] = get_bits(&alac->gb, 5);
495 /* read the predictor table */
496 for (i = 0; i < predictor_coef_num[chan]; i++)
497 predictor_coef_table[chan][i] = (int16_t)get_bits(&alac->gb, 16);
501 av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented, unhandling of wasted_bytes\n");
503 for (chan = 0; chan < channels; chan++) {
504 bastardized_rice_decompress(alac,
505 alac->predicterror_buffer[chan],
508 alac->setinfo_rice_initialhistory,
509 alac->setinfo_rice_kmodifier,
510 ricemodifier[chan] * alac->setinfo_rice_historymult / 4,
511 (1 << alac->setinfo_rice_kmodifier) - 1);
513 if (prediction_type[chan] == 0) {
515 predictor_decompress_fir_adapt(alac->predicterror_buffer[chan],
516 alac->outputsamples_buffer[chan],
519 predictor_coef_table[chan],
520 predictor_coef_num[chan],
521 prediction_quantitization[chan]);
523 av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type[chan]);
524 /* I think the only other prediction type (or perhaps this is
525 * just a boolean?) runs adaptive fir twice.. like:
526 * predictor_decompress_fir_adapt(predictor_error, tempout, ...)
527 * predictor_decompress_fir_adapt(predictor_error, outputsamples ...)
533 /* not compressed, easy case */
534 if (alac->setinfo_sample_size <= 16) {
536 for (chan = 0; chan < channels; chan++)
537 for (i = 0; i < outputsamples; i++) {
540 audiobits = get_bits(&alac->gb, alac->setinfo_sample_size);
541 audiobits = extend_sign32(audiobits, readsamplesize);
543 alac->outputsamples_buffer[chan][i] = audiobits;
547 for (chan = 0; chan < channels; chan++)
548 for (i = 0; i < outputsamples; i++) {
551 audiobits = get_bits(&alac->gb, 16);
552 /* special case of sign extension..
553 * as we'll be ORing the low 16bits into this */
554 audiobits = audiobits << 16;
555 audiobits = audiobits >> (32 - alac->setinfo_sample_size);
556 audiobits |= get_bits(&alac->gb, alac->setinfo_sample_size - 16);
558 alac->outputsamples_buffer[chan][i] = audiobits;
561 /* wasted_bytes = 0; */
562 interlacing_shift = 0;
563 interlacing_leftweight = 0;
565 if (get_bits(&alac->gb, 3) != 7)
566 av_log(avctx, AV_LOG_ERROR, "Error : Wrong End Of Frame\n");
568 switch(alac->setinfo_sample_size) {
571 reconstruct_stereo_16(alac->outputsamples_buffer,
576 interlacing_leftweight);
579 for (i = 0; i < outputsamples; i++) {
580 int16_t sample = alac->outputsamples_buffer[0][i];
581 ((int16_t*)outbuffer)[i * alac->numchannels] = sample;
587 // It is not clear if there exist any encoder that creates 24 bit ALAC
588 // files. iTunes convert 24 bit raw files to 16 bit before encoding.
590 av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
596 if (input_buffer_size * 8 - get_bits_count(&alac->gb) > 8)
597 av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n", input_buffer_size * 8 - get_bits_count(&alac->gb));
599 return input_buffer_size;
602 static av_cold int alac_decode_init(AVCodecContext * avctx)
604 ALACContext *alac = avctx->priv_data;
606 alac->context_initialized = 0;
608 alac->numchannels = alac->avctx->channels;
609 alac->bytespersample = (avctx->bits_per_sample / 8) * alac->numchannels;
614 static av_cold int alac_decode_close(AVCodecContext *avctx)
616 ALACContext *alac = avctx->priv_data;
619 for (chan = 0; chan < MAX_CHANNELS; chan++) {
620 av_free(alac->predicterror_buffer[chan]);
621 av_free(alac->outputsamples_buffer[chan]);
627 AVCodec alac_decoder = {
636 .long_name = "ALAC (Apple Lossless Audio Codec)",