2 * ALAC (Apple Lossless Audio Codec) decoder
3 * Copyright (c) 2005 David Hammerton
5 * This file is part of Libav.
7 * Libav 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 * Libav 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 Libav; 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)
40 * 8bit rice param limit (10)
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 *predict_error_buffer[MAX_CHANNELS];
68 int32_t *output_samples_buffer[MAX_CHANNELS];
69 int32_t *extra_bits_buffer[MAX_CHANNELS];
71 uint32_t max_samples_per_frame;
73 uint8_t rice_history_mult;
74 uint8_t rice_initial_history;
77 int extra_bits; /**< number of extra bits beyond 16-bit */
80 static inline int decode_scalar(GetBitContext *gb, int k, int readsamplesize)
82 int x = get_unary_0_9(gb);
84 if (x > 8) { /* RICE THRESHOLD */
85 /* use alternative encoding */
86 x = get_bits(gb, readsamplesize);
88 int extrabits = show_bits(gb, k);
90 /* multiply x by 2^k - 1, as part of their strange algorithm */
102 static void bastardized_rice_decompress(ALACContext *alac,
103 int32_t *output_buffer,
106 int rice_history_mult)
109 unsigned int history = alac->rice_initial_history;
110 int sign_modifier = 0;
112 for (output_count = 0; output_count < output_size; output_count++) {
117 /* standard rice encoding */
118 int k; /* size of extra bits */
120 /* read k, that is bits as is */
121 k = av_log2((history >> 9) + 3);
122 k = FFMIN(k, alac->rice_limit);
123 x = decode_scalar(&alac->gb, k, readsamplesize);
125 x_modified = sign_modifier + x;
126 final_val = (x_modified + 1) / 2;
127 if (x_modified & 1) final_val *= -1;
129 output_buffer[output_count] = final_val;
133 /* now update the history */
134 history += x_modified * rice_history_mult -
135 ((history * rice_history_mult) >> 9);
137 if (x_modified > 0xffff)
140 /* special case: there may be compressed blocks of 0 */
141 if ((history < 128) && (output_count+1 < output_size)) {
143 unsigned int block_size;
147 k = 7 - av_log2(history) + ((history + 16) >> 6 /* / 64 */);
148 k = FFMIN(k, alac->rice_limit);
150 block_size = decode_scalar(&alac->gb, k, 16);
152 if (block_size > 0) {
153 if(block_size >= output_size - output_count){
154 av_log(alac->avctx, AV_LOG_ERROR, "invalid zero block size of %d %d %d\n", block_size, output_size, output_count);
155 block_size= output_size - output_count - 1;
157 memset(&output_buffer[output_count+1], 0, block_size * 4);
158 output_count += block_size;
161 if (block_size > 0xffff)
169 static inline int sign_only(int v)
171 return v ? FFSIGN(v) : 0;
174 static void predictor_decompress_fir_adapt(int32_t *error_buffer,
178 int16_t *predictor_coef_table,
179 int predictor_coef_num,
180 int predictor_quantitization)
184 /* first sample always copies */
185 *buffer_out = *error_buffer;
187 if (!predictor_coef_num) {
188 if (output_size <= 1)
191 memcpy(buffer_out+1, error_buffer+1, (output_size-1) * 4);
195 if (predictor_coef_num == 31) {
196 /* simple 1st-order prediction */
197 if (output_size <= 1)
199 for (i = 0; i < output_size - 1; i++) {
203 prev_value = buffer_out[i];
204 error_value = error_buffer[i+1];
206 sign_extend((prev_value + error_value), readsamplesize);
211 /* read warm-up samples */
212 if (predictor_coef_num > 0)
213 for (i = 0; i < predictor_coef_num; i++) {
216 val = buffer_out[i] + error_buffer[i+1];
217 val = sign_extend(val, readsamplesize);
218 buffer_out[i+1] = val;
221 /* NOTE: 4 and 8 are very common cases that could be optimized. */
224 if (predictor_coef_num > 0) {
225 for (i = predictor_coef_num + 1; i < output_size; i++) {
229 int error_val = error_buffer[i];
231 for (j = 0; j < predictor_coef_num; j++) {
232 sum += (buffer_out[predictor_coef_num-j] - buffer_out[0]) *
233 predictor_coef_table[j];
236 outval = (1 << (predictor_quantitization-1)) + sum;
237 outval = outval >> predictor_quantitization;
238 outval = outval + buffer_out[0] + error_val;
239 outval = sign_extend(outval, readsamplesize);
241 buffer_out[predictor_coef_num+1] = outval;
244 int predictor_num = predictor_coef_num - 1;
246 while (predictor_num >= 0 && error_val > 0) {
247 int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
248 int sign = sign_only(val);
250 predictor_coef_table[predictor_num] -= sign;
252 val *= sign; /* absolute value */
254 error_val -= ((val >> predictor_quantitization) *
255 (predictor_coef_num - predictor_num));
259 } else if (error_val < 0) {
260 int predictor_num = predictor_coef_num - 1;
262 while (predictor_num >= 0 && error_val < 0) {
263 int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
264 int sign = - sign_only(val);
266 predictor_coef_table[predictor_num] -= sign;
268 val *= sign; /* neg value */
270 error_val -= ((val >> predictor_quantitization) *
271 (predictor_coef_num - predictor_num));
282 static void decorrelate_stereo(int32_t *buffer[MAX_CHANNELS],
283 int numsamples, uint8_t interlacing_shift,
284 uint8_t interlacing_leftweight)
288 for (i = 0; i < numsamples; i++) {
294 a -= (b * interlacing_leftweight) >> interlacing_shift;
302 static void append_extra_bits(int32_t *buffer[MAX_CHANNELS],
303 int32_t *extra_bits_buffer[MAX_CHANNELS],
304 int extra_bits, int numchannels, int numsamples)
308 for (ch = 0; ch < numchannels; ch++)
309 for (i = 0; i < numsamples; i++)
310 buffer[ch][i] = (buffer[ch][i] << extra_bits) | extra_bits_buffer[ch][i];
313 static void interleave_stereo_16(int32_t *buffer[MAX_CHANNELS],
314 int16_t *buffer_out, int numsamples)
318 for (i = 0; i < numsamples; i++) {
319 *buffer_out++ = buffer[0][i];
320 *buffer_out++ = buffer[1][i];
324 static void interleave_stereo_24(int32_t *buffer[MAX_CHANNELS],
325 int32_t *buffer_out, int numsamples)
329 for (i = 0; i < numsamples; i++) {
330 *buffer_out++ = buffer[0][i] << 8;
331 *buffer_out++ = buffer[1][i] << 8;
335 static int alac_decode_frame(AVCodecContext *avctx, void *data,
336 int *got_frame_ptr, AVPacket *avpkt)
338 const uint8_t *inbuffer = avpkt->data;
339 int input_buffer_size = avpkt->size;
340 ALACContext *alac = avctx->priv_data;
343 unsigned int outputsamples;
345 unsigned int readsamplesize;
347 uint8_t interlacing_shift;
348 uint8_t interlacing_leftweight;
351 init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
353 channels = get_bits(&alac->gb, 3) + 1;
354 if (channels != avctx->channels) {
355 av_log(avctx, AV_LOG_ERROR, "frame header channel count mismatch\n");
356 return AVERROR_INVALIDDATA;
359 skip_bits(&alac->gb, 4); /* element instance tag */
360 skip_bits(&alac->gb, 12); /* unused header bits */
362 /* the number of output samples is stored in the frame */
363 hassize = get_bits1(&alac->gb);
365 alac->extra_bits = get_bits(&alac->gb, 2) << 3;
367 /* whether the frame is compressed */
368 isnotcompressed = get_bits1(&alac->gb);
371 /* now read the number of samples as a 32bit integer */
372 outputsamples = get_bits_long(&alac->gb, 32);
373 if (outputsamples > alac->max_samples_per_frame) {
374 av_log(avctx, AV_LOG_ERROR, "outputsamples %d > %d\n",
375 outputsamples, alac->max_samples_per_frame);
379 outputsamples = alac->max_samples_per_frame;
381 /* get output buffer */
382 if (outputsamples > INT32_MAX) {
383 av_log(avctx, AV_LOG_ERROR, "unsupported block size: %u\n", outputsamples);
384 return AVERROR_INVALIDDATA;
386 alac->frame.nb_samples = outputsamples;
387 if ((ret = avctx->get_buffer(avctx, &alac->frame)) < 0) {
388 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
392 readsamplesize = alac->sample_size - alac->extra_bits + channels - 1;
393 if (readsamplesize > MIN_CACHE_BITS) {
394 av_log(avctx, AV_LOG_ERROR, "readsamplesize too big (%d)\n", readsamplesize);
398 if (!isnotcompressed) {
399 /* so it is compressed */
400 int16_t predictor_coef_table[MAX_CHANNELS][32];
401 int predictor_coef_num[MAX_CHANNELS];
402 int prediction_type[MAX_CHANNELS];
403 int prediction_quantitization[MAX_CHANNELS];
404 int ricemodifier[MAX_CHANNELS];
406 interlacing_shift = get_bits(&alac->gb, 8);
407 interlacing_leftweight = get_bits(&alac->gb, 8);
409 for (ch = 0; ch < channels; ch++) {
410 prediction_type[ch] = get_bits(&alac->gb, 4);
411 prediction_quantitization[ch] = get_bits(&alac->gb, 4);
413 ricemodifier[ch] = get_bits(&alac->gb, 3);
414 predictor_coef_num[ch] = get_bits(&alac->gb, 5);
416 /* read the predictor table */
417 for (i = 0; i < predictor_coef_num[ch]; i++)
418 predictor_coef_table[ch][i] = (int16_t)get_bits(&alac->gb, 16);
421 if (alac->extra_bits) {
422 for (i = 0; i < outputsamples; i++) {
423 for (ch = 0; ch < channels; ch++)
424 alac->extra_bits_buffer[ch][i] = get_bits(&alac->gb, alac->extra_bits);
427 for (ch = 0; ch < channels; ch++) {
428 bastardized_rice_decompress(alac,
429 alac->predict_error_buffer[ch],
432 ricemodifier[ch] * alac->rice_history_mult / 4);
434 /* adaptive FIR filter */
435 if (prediction_type[ch] == 15) {
436 /* Prediction type 15 runs the adaptive FIR twice.
437 * The first pass uses the special-case coef_num = 31, while
438 * the second pass uses the coefs from the bitstream.
440 * However, this prediction type is not currently used by the
443 predictor_decompress_fir_adapt(alac->predict_error_buffer[ch],
444 alac->predict_error_buffer[ch],
445 outputsamples, readsamplesize,
447 } else if (prediction_type[ch] > 0) {
448 av_log(avctx, AV_LOG_WARNING, "unknown prediction type: %i\n",
449 prediction_type[ch]);
451 predictor_decompress_fir_adapt(alac->predict_error_buffer[ch],
452 alac->output_samples_buffer[ch],
453 outputsamples, readsamplesize,
454 predictor_coef_table[ch],
455 predictor_coef_num[ch],
456 prediction_quantitization[ch]);
459 /* not compressed, easy case */
460 for (i = 0; i < outputsamples; i++) {
461 for (ch = 0; ch < channels; ch++) {
462 alac->output_samples_buffer[ch][i] = get_sbits_long(&alac->gb,
466 alac->extra_bits = 0;
467 interlacing_shift = 0;
468 interlacing_leftweight = 0;
470 if (get_bits(&alac->gb, 3) != 7)
471 av_log(avctx, AV_LOG_ERROR, "Error : Wrong End Of Frame\n");
473 if (channels == 2 && interlacing_leftweight) {
474 decorrelate_stereo(alac->output_samples_buffer, outputsamples,
475 interlacing_shift, interlacing_leftweight);
478 if (alac->extra_bits) {
479 append_extra_bits(alac->output_samples_buffer, alac->extra_bits_buffer,
480 alac->extra_bits, alac->channels, outputsamples);
483 switch(alac->sample_size) {
486 interleave_stereo_16(alac->output_samples_buffer,
487 (int16_t *)alac->frame.data[0], outputsamples);
489 int16_t *outbuffer = (int16_t *)alac->frame.data[0];
490 for (i = 0; i < outputsamples; i++) {
491 outbuffer[i] = alac->output_samples_buffer[0][i];
497 interleave_stereo_24(alac->output_samples_buffer,
498 (int32_t *)alac->frame.data[0], outputsamples);
500 int32_t *outbuffer = (int32_t *)alac->frame.data[0];
501 for (i = 0; i < outputsamples; i++)
502 outbuffer[i] = alac->output_samples_buffer[0][i] << 8;
507 if (input_buffer_size * 8 - get_bits_count(&alac->gb) > 8)
508 av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n", input_buffer_size * 8 - get_bits_count(&alac->gb));
511 *(AVFrame *)data = alac->frame;
513 return input_buffer_size;
516 static av_cold int alac_decode_close(AVCodecContext *avctx)
518 ALACContext *alac = avctx->priv_data;
521 for (ch = 0; ch < alac->channels; ch++) {
522 av_freep(&alac->predict_error_buffer[ch]);
523 av_freep(&alac->output_samples_buffer[ch]);
524 av_freep(&alac->extra_bits_buffer[ch]);
530 static int allocate_buffers(ALACContext *alac)
533 for (ch = 0; ch < alac->channels; ch++) {
534 int buf_size = alac->max_samples_per_frame * sizeof(int32_t);
536 FF_ALLOC_OR_GOTO(alac->avctx, alac->predict_error_buffer[ch],
537 buf_size, buf_alloc_fail);
539 FF_ALLOC_OR_GOTO(alac->avctx, alac->output_samples_buffer[ch],
540 buf_size, buf_alloc_fail);
542 FF_ALLOC_OR_GOTO(alac->avctx, alac->extra_bits_buffer[ch],
543 buf_size, buf_alloc_fail);
547 alac_decode_close(alac->avctx);
548 return AVERROR(ENOMEM);
551 static int alac_set_info(ALACContext *alac)
555 bytestream2_init(&gb, alac->avctx->extradata,
556 alac->avctx->extradata_size);
558 bytestream2_skipu(&gb, 12); // size:4, alac:4, version:4
560 alac->max_samples_per_frame = bytestream2_get_be32u(&gb);
561 if (alac->max_samples_per_frame >= UINT_MAX/4){
562 av_log(alac->avctx, AV_LOG_ERROR,
563 "max_samples_per_frame too large\n");
564 return AVERROR_INVALIDDATA;
566 bytestream2_skipu(&gb, 1); // compatible version
567 alac->sample_size = bytestream2_get_byteu(&gb);
568 alac->rice_history_mult = bytestream2_get_byteu(&gb);
569 alac->rice_initial_history = bytestream2_get_byteu(&gb);
570 alac->rice_limit = bytestream2_get_byteu(&gb);
571 alac->channels = bytestream2_get_byteu(&gb);
572 bytestream2_get_be16u(&gb); // maxRun
573 bytestream2_get_be32u(&gb); // max coded frame size
574 bytestream2_get_be32u(&gb); // average bitrate
575 bytestream2_get_be32u(&gb); // samplerate
580 static av_cold int alac_decode_init(AVCodecContext * avctx)
583 ALACContext *alac = avctx->priv_data;
586 /* initialize from the extradata */
587 if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
588 av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
589 ALAC_EXTRADATA_SIZE);
592 if (alac_set_info(alac)) {
593 av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
597 switch (alac->sample_size) {
598 case 16: avctx->sample_fmt = AV_SAMPLE_FMT_S16;
600 case 24: avctx->sample_fmt = AV_SAMPLE_FMT_S32;
602 default: av_log_ask_for_sample(avctx, "Sample depth %d is not supported.\n",
604 return AVERROR_PATCHWELCOME;
607 if (alac->channels < 1) {
608 av_log(avctx, AV_LOG_WARNING, "Invalid channel count\n");
609 alac->channels = avctx->channels;
611 if (alac->channels > MAX_CHANNELS)
612 alac->channels = avctx->channels;
614 avctx->channels = alac->channels;
616 if (avctx->channels > MAX_CHANNELS) {
617 av_log(avctx, AV_LOG_ERROR, "Unsupported channel count: %d\n",
619 return AVERROR_PATCHWELCOME;
622 if ((ret = allocate_buffers(alac)) < 0) {
623 av_log(avctx, AV_LOG_ERROR, "Error allocating buffers\n");
627 avcodec_get_frame_defaults(&alac->frame);
628 avctx->coded_frame = &alac->frame;
633 AVCodec ff_alac_decoder = {
635 .type = AVMEDIA_TYPE_AUDIO,
637 .priv_data_size = sizeof(ALACContext),
638 .init = alac_decode_init,
639 .close = alac_decode_close,
640 .decode = alac_decode_frame,
641 .capabilities = CODEC_CAP_DR1,
642 .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),