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
26 * @see http://crazney.net/programs/itunes/alac.html
28 * Note: This decoder expects a 36-byte QuickTime atom to be
29 * passed through the extradata[_size] fields. This atom is tacked onto
30 * the end of an 'alac' stsd atom and has the following format:
34 * 32bit tag version (0)
35 * 32bit samples per frame (used when not set explicitly in the frames)
36 * 8bit compatible version (0)
38 * 8bit history mult (40)
39 * 8bit initial history (14)
43 * 32bit max coded frame size (0 means unknown)
44 * 32bit average bitrate (0 means unknown)
51 #include "bytestream.h"
55 #define ALAC_EXTRADATA_SIZE 36
56 #define MAX_CHANNELS 2
60 AVCodecContext *avctx;
67 int32_t *predicterror_buffer[MAX_CHANNELS];
69 int32_t *outputsamples_buffer[MAX_CHANNELS];
71 int32_t *extra_bits_buffer[MAX_CHANNELS];
73 /* stuff from setinfo */
74 uint32_t setinfo_max_samples_per_frame; /* 0x1000 = 4096 */ /* max samples per frame? */
75 uint8_t setinfo_sample_size; /* 0x10 */
76 uint8_t setinfo_rice_historymult; /* 0x28 */
77 uint8_t setinfo_rice_initialhistory; /* 0x0a */
78 uint8_t setinfo_rice_kmodifier; /* 0x0e */
79 /* end setinfo stuff */
81 int extra_bits; /**< number of extra bits beyond 16-bit */
84 static inline int decode_scalar(GetBitContext *gb, int k, int limit, int readsamplesize){
85 /* read x - number of 1s before 0 represent the rice */
86 int x = get_unary_0_9(gb);
88 if (x > 8) { /* RICE THRESHOLD */
89 /* use alternative encoding */
90 x = get_bits(gb, readsamplesize);
96 int extrabits = show_bits(gb, k);
98 /* multiply x by 2^k - 1, as part of their strange algorithm */
105 skip_bits(gb, k - 1);
111 static int bastardized_rice_decompress(ALACContext *alac,
112 int32_t *output_buffer,
114 int readsamplesize, /* arg_10 */
115 int rice_initialhistory, /* arg424->b */
116 int rice_kmodifier, /* arg424->d */
117 int rice_historymult, /* arg424->c */
118 int rice_kmodifier_mask /* arg424->e */
122 unsigned int history = rice_initialhistory;
123 int sign_modifier = 0;
125 for (output_count = 0; output_count < output_size; output_count++) {
130 /* standard rice encoding */
131 int k; /* size of extra bits */
133 if(get_bits_left(&alac->gb) <= 0)
136 /* read k, that is bits as is */
137 k = av_log2((history >> 9) + 3);
138 x= decode_scalar(&alac->gb, k, rice_kmodifier, readsamplesize);
140 x_modified = sign_modifier + x;
141 final_val = (x_modified + 1) / 2;
142 if (x_modified & 1) final_val *= -1;
144 output_buffer[output_count] = final_val;
148 /* now update the history */
149 history += x_modified * rice_historymult
150 - ((history * rice_historymult) >> 9);
152 if (x_modified > 0xffff)
155 /* special case: there may be compressed blocks of 0 */
156 if ((history < 128) && (output_count+1 < output_size)) {
158 unsigned int block_size;
162 k = 7 - av_log2(history) + ((history + 16) >> 6 /* / 64 */);
164 block_size= decode_scalar(&alac->gb, k, rice_kmodifier, 16);
166 if (block_size > 0) {
167 if(block_size >= output_size - output_count){
168 av_log(alac->avctx, AV_LOG_ERROR, "invalid zero block size of %d %d %d\n", block_size, output_size, output_count);
169 block_size= output_size - output_count - 1;
171 memset(&output_buffer[output_count+1], 0, block_size * 4);
172 output_count += block_size;
175 if (block_size > 0xffff)
184 static inline int sign_only(int v)
186 return v ? FFSIGN(v) : 0;
189 static void predictor_decompress_fir_adapt(int32_t *error_buffer,
193 int16_t *predictor_coef_table,
194 int predictor_coef_num,
195 int predictor_quantitization)
199 /* first sample always copies */
200 *buffer_out = *error_buffer;
202 if (!predictor_coef_num) {
203 if (output_size <= 1)
206 memcpy(buffer_out+1, error_buffer+1, (output_size-1) * 4);
210 if (predictor_coef_num == 0x1f) { /* 11111 - max value of predictor_coef_num */
211 /* second-best case scenario for fir decompression,
212 * error describes a small difference from the previous sample only
214 if (output_size <= 1)
216 for (i = 0; i < output_size - 1; i++) {
220 prev_value = buffer_out[i];
221 error_value = error_buffer[i+1];
223 sign_extend((prev_value + error_value), readsamplesize);
228 /* read warm-up samples */
229 if (predictor_coef_num > 0)
230 for (i = 0; i < predictor_coef_num; i++) {
233 val = buffer_out[i] + error_buffer[i+1];
234 val = sign_extend(val, readsamplesize);
235 buffer_out[i+1] = val;
238 /* 4 and 8 are very common cases (the only ones i've seen). these
239 * should be unrolled and optimized
243 if (predictor_coef_num > 0) {
244 for (i = predictor_coef_num + 1; i < output_size; i++) {
248 int error_val = error_buffer[i];
250 for (j = 0; j < predictor_coef_num; j++) {
251 sum += (buffer_out[predictor_coef_num-j] - buffer_out[0]) *
252 predictor_coef_table[j];
255 outval = (1 << (predictor_quantitization-1)) + sum;
256 outval = outval >> predictor_quantitization;
257 outval = outval + buffer_out[0] + error_val;
258 outval = sign_extend(outval, readsamplesize);
260 buffer_out[predictor_coef_num+1] = outval;
263 int predictor_num = predictor_coef_num - 1;
265 while (predictor_num >= 0 && error_val > 0) {
266 int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
267 int sign = sign_only(val);
269 predictor_coef_table[predictor_num] -= sign;
271 val *= sign; /* absolute value */
273 error_val -= ((val >> predictor_quantitization) *
274 (predictor_coef_num - predictor_num));
278 } else if (error_val < 0) {
279 int predictor_num = predictor_coef_num - 1;
281 while (predictor_num >= 0 && error_val < 0) {
282 int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
283 int sign = - sign_only(val);
285 predictor_coef_table[predictor_num] -= sign;
287 val *= sign; /* neg value */
289 error_val -= ((val >> predictor_quantitization) *
290 (predictor_coef_num - predictor_num));
301 static void decorrelate_stereo(int32_t *buffer[MAX_CHANNELS],
302 int numsamples, uint8_t interlacing_shift,
303 uint8_t interlacing_leftweight)
307 for (i = 0; i < numsamples; i++) {
313 a -= (b * interlacing_leftweight) >> interlacing_shift;
321 static void append_extra_bits(int32_t *buffer[MAX_CHANNELS],
322 int32_t *extra_bits_buffer[MAX_CHANNELS],
323 int extra_bits, int numchannels, int numsamples)
327 for (ch = 0; ch < numchannels; ch++)
328 for (i = 0; i < numsamples; i++)
329 buffer[ch][i] = (buffer[ch][i] << extra_bits) | extra_bits_buffer[ch][i];
332 static void interleave_stereo_16(int32_t *buffer[MAX_CHANNELS],
333 int16_t *buffer_out, int numsamples)
337 for (i = 0; i < numsamples; i++) {
338 *buffer_out++ = buffer[0][i];
339 *buffer_out++ = buffer[1][i];
343 static void interleave_stereo_24(int32_t *buffer[MAX_CHANNELS],
344 int32_t *buffer_out, int numsamples)
348 for (i = 0; i < numsamples; i++) {
349 *buffer_out++ = buffer[0][i] << 8;
350 *buffer_out++ = buffer[1][i] << 8;
354 static int alac_decode_frame(AVCodecContext *avctx, void *data,
355 int *got_frame_ptr, AVPacket *avpkt)
357 const uint8_t *inbuffer = avpkt->data;
358 int input_buffer_size = avpkt->size;
359 ALACContext *alac = avctx->priv_data;
362 unsigned int outputsamples;
364 unsigned int readsamplesize;
366 uint8_t interlacing_shift;
367 uint8_t interlacing_leftweight;
370 init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
372 channels = get_bits(&alac->gb, 3) + 1;
373 if (channels != avctx->channels) {
374 av_log(avctx, AV_LOG_ERROR, "frame header channel count mismatch\n");
375 return AVERROR_INVALIDDATA;
378 /* 2^result = something to do with output waiting.
379 * perhaps matters if we read > 1 frame in a pass?
381 skip_bits(&alac->gb, 4);
383 skip_bits(&alac->gb, 12); /* unknown, skip 12 bits */
385 /* the output sample size is stored soon */
386 hassize = get_bits1(&alac->gb);
388 alac->extra_bits = get_bits(&alac->gb, 2) << 3;
390 /* whether the frame is compressed */
391 isnotcompressed = get_bits1(&alac->gb);
394 /* now read the number of samples as a 32bit integer */
395 outputsamples = get_bits_long(&alac->gb, 32);
396 if(outputsamples > alac->setinfo_max_samples_per_frame){
397 av_log(avctx, AV_LOG_ERROR, "outputsamples %d > %d\n", outputsamples, alac->setinfo_max_samples_per_frame);
401 outputsamples = alac->setinfo_max_samples_per_frame;
403 /* get output buffer */
404 if (outputsamples > INT32_MAX) {
405 av_log(avctx, AV_LOG_ERROR, "unsupported block size: %u\n", outputsamples);
406 return AVERROR_INVALIDDATA;
408 alac->frame.nb_samples = outputsamples;
409 if ((ret = avctx->get_buffer(avctx, &alac->frame)) < 0) {
410 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
414 readsamplesize = alac->setinfo_sample_size - alac->extra_bits + channels - 1;
415 if (readsamplesize > MIN_CACHE_BITS) {
416 av_log(avctx, AV_LOG_ERROR, "readsamplesize too big (%d)\n", readsamplesize);
420 if (!isnotcompressed) {
421 /* so it is compressed */
422 int16_t predictor_coef_table[MAX_CHANNELS][32];
423 int predictor_coef_num[MAX_CHANNELS];
424 int prediction_type[MAX_CHANNELS];
425 int prediction_quantitization[MAX_CHANNELS];
426 int ricemodifier[MAX_CHANNELS];
428 interlacing_shift = get_bits(&alac->gb, 8);
429 interlacing_leftweight = get_bits(&alac->gb, 8);
431 for (ch = 0; ch < channels; ch++) {
432 prediction_type[ch] = get_bits(&alac->gb, 4);
433 prediction_quantitization[ch] = get_bits(&alac->gb, 4);
435 ricemodifier[ch] = get_bits(&alac->gb, 3);
436 predictor_coef_num[ch] = get_bits(&alac->gb, 5);
438 /* read the predictor table */
439 for (i = 0; i < predictor_coef_num[ch]; i++)
440 predictor_coef_table[ch][i] = (int16_t)get_bits(&alac->gb, 16);
443 if (alac->extra_bits) {
444 for (i = 0; i < outputsamples; i++) {
445 if(get_bits_left(&alac->gb) <= 0)
447 for (ch = 0; ch < channels; ch++)
448 alac->extra_bits_buffer[ch][i] = get_bits(&alac->gb, alac->extra_bits);
451 for (ch = 0; ch < channels; ch++) {
452 int ret = bastardized_rice_decompress(alac,
453 alac->predicterror_buffer[ch],
456 alac->setinfo_rice_initialhistory,
457 alac->setinfo_rice_kmodifier,
458 ricemodifier[ch] * alac->setinfo_rice_historymult / 4,
459 (1 << alac->setinfo_rice_kmodifier) - 1);
463 /* adaptive FIR filter */
464 if (prediction_type[ch] == 15) {
465 /* Prediction type 15 runs the adaptive FIR twice.
466 * The first pass uses the special-case coef_num = 31, while
467 * the second pass uses the coefs from the bitstream.
469 * However, this prediction type is not currently used by the
472 predictor_decompress_fir_adapt(alac->predicterror_buffer[ch],
473 alac->predicterror_buffer[ch],
474 outputsamples, readsamplesize,
476 } else if (prediction_type[ch] > 0) {
477 av_log(avctx, AV_LOG_WARNING, "unknown prediction type: %i\n",
478 prediction_type[ch]);
480 predictor_decompress_fir_adapt(alac->predicterror_buffer[ch],
481 alac->outputsamples_buffer[ch],
482 outputsamples, readsamplesize,
483 predictor_coef_table[ch],
484 predictor_coef_num[ch],
485 prediction_quantitization[ch]);
488 /* not compressed, easy case */
489 for (i = 0; i < outputsamples; i++) {
490 if(get_bits_left(&alac->gb) <= 0)
492 for (ch = 0; ch < channels; ch++) {
493 alac->outputsamples_buffer[ch][i] = get_sbits_long(&alac->gb,
494 alac->setinfo_sample_size);
497 alac->extra_bits = 0;
498 interlacing_shift = 0;
499 interlacing_leftweight = 0;
501 if (get_bits(&alac->gb, 3) != 7)
502 av_log(avctx, AV_LOG_ERROR, "Error : Wrong End Of Frame\n");
504 if (channels == 2 && interlacing_leftweight) {
505 decorrelate_stereo(alac->outputsamples_buffer, outputsamples,
506 interlacing_shift, interlacing_leftweight);
509 if (alac->extra_bits) {
510 append_extra_bits(alac->outputsamples_buffer, alac->extra_bits_buffer,
511 alac->extra_bits, alac->numchannels, outputsamples);
514 switch(alac->setinfo_sample_size) {
517 interleave_stereo_16(alac->outputsamples_buffer,
518 (int16_t *)alac->frame.data[0], outputsamples);
520 int16_t *outbuffer = (int16_t *)alac->frame.data[0];
521 for (i = 0; i < outputsamples; i++) {
522 outbuffer[i] = alac->outputsamples_buffer[0][i];
528 interleave_stereo_24(alac->outputsamples_buffer,
529 (int32_t *)alac->frame.data[0], outputsamples);
531 int32_t *outbuffer = (int32_t *)alac->frame.data[0];
532 for (i = 0; i < outputsamples; i++)
533 outbuffer[i] = alac->outputsamples_buffer[0][i] << 8;
538 if (input_buffer_size * 8 - get_bits_count(&alac->gb) > 8)
539 av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n", input_buffer_size * 8 - get_bits_count(&alac->gb));
542 *(AVFrame *)data = alac->frame;
544 return input_buffer_size;
547 static av_cold int alac_decode_close(AVCodecContext *avctx)
549 ALACContext *alac = avctx->priv_data;
552 for (ch = 0; ch < alac->numchannels; ch++) {
553 av_freep(&alac->predicterror_buffer[ch]);
554 av_freep(&alac->outputsamples_buffer[ch]);
555 av_freep(&alac->extra_bits_buffer[ch]);
561 static int allocate_buffers(ALACContext *alac)
564 for (ch = 0; ch < alac->numchannels; ch++) {
565 int buf_size = alac->setinfo_max_samples_per_frame * sizeof(int32_t);
567 FF_ALLOC_OR_GOTO(alac->avctx, alac->predicterror_buffer[ch],
568 buf_size, buf_alloc_fail);
570 FF_ALLOC_OR_GOTO(alac->avctx, alac->outputsamples_buffer[ch],
571 buf_size, buf_alloc_fail);
573 FF_ALLOC_OR_GOTO(alac->avctx, alac->extra_bits_buffer[ch],
574 buf_size, buf_alloc_fail);
578 alac_decode_close(alac->avctx);
579 return AVERROR(ENOMEM);
582 static int alac_set_info(ALACContext *alac)
584 const unsigned char *ptr = alac->avctx->extradata;
588 ptr += 4; /* version */
590 if(AV_RB32(ptr) >= UINT_MAX/4){
591 av_log(alac->avctx, AV_LOG_ERROR, "setinfo_max_samples_per_frame too large\n");
595 /* buffer size / 2 ? */
596 alac->setinfo_max_samples_per_frame = bytestream_get_be32(&ptr);
597 ptr++; /* compatible version */
598 alac->setinfo_sample_size = *ptr++;
599 alac->setinfo_rice_historymult = *ptr++;
600 alac->setinfo_rice_initialhistory = *ptr++;
601 alac->setinfo_rice_kmodifier = *ptr++;
602 alac->numchannels = *ptr++;
603 bytestream_get_be16(&ptr); /* maxRun */
604 bytestream_get_be32(&ptr); /* max coded frame size */
605 bytestream_get_be32(&ptr); /* average bitrate */
606 bytestream_get_be32(&ptr); /* samplerate */
611 static av_cold int alac_decode_init(AVCodecContext * avctx)
614 ALACContext *alac = avctx->priv_data;
617 /* initialize from the extradata */
618 if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
619 av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
620 ALAC_EXTRADATA_SIZE);
623 if (alac_set_info(alac)) {
624 av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
628 switch (alac->setinfo_sample_size) {
629 case 16: avctx->sample_fmt = AV_SAMPLE_FMT_S16;
631 case 24: avctx->sample_fmt = AV_SAMPLE_FMT_S32;
633 default: av_log_ask_for_sample(avctx, "Sample depth %d is not supported.\n",
634 alac->setinfo_sample_size);
635 return AVERROR_PATCHWELCOME;
638 if (alac->numchannels < 1) {
639 av_log(avctx, AV_LOG_WARNING, "Invalid channel count\n");
640 alac->numchannels = avctx->channels;
642 if (alac->numchannels > MAX_CHANNELS)
643 alac->numchannels = avctx->channels;
645 avctx->channels = alac->numchannels;
647 if (avctx->channels > MAX_CHANNELS) {
648 av_log(avctx, AV_LOG_ERROR, "Unsupported channel count: %d\n",
650 return AVERROR_PATCHWELCOME;
653 if ((ret = allocate_buffers(alac)) < 0) {
654 av_log(avctx, AV_LOG_ERROR, "Error allocating buffers\n");
658 avcodec_get_frame_defaults(&alac->frame);
659 avctx->coded_frame = &alac->frame;
664 AVCodec ff_alac_decoder = {
666 .type = AVMEDIA_TYPE_AUDIO,
668 .priv_data_size = sizeof(ALACContext),
669 .init = alac_decode_init,
670 .close = alac_decode_close,
671 .decode = alac_decode_frame,
672 .capabilities = CODEC_CAP_DR1,
673 .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),