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++) {
115 /* read k, that is bits as is */
116 k = av_log2((history >> 9) + 3);
117 k = FFMIN(k, alac->rice_limit);
118 x = decode_scalar(&alac->gb, k, readsamplesize);
122 output_buffer[output_count] = (x >> 1) ^ -(x & 1);
124 /* now update the history */
128 history += x * rice_history_mult -
129 ((history * rice_history_mult) >> 9);
131 /* special case: there may be compressed blocks of 0 */
132 if ((history < 128) && (output_count+1 < output_size)) {
133 unsigned int block_size;
135 k = 7 - av_log2(history) + ((history + 16) >> 6 /* / 64 */);
136 k = FFMIN(k, alac->rice_limit);
138 block_size = decode_scalar(&alac->gb, k, 16);
140 if (block_size > 0) {
141 if(block_size >= output_size - output_count){
142 av_log(alac->avctx, AV_LOG_ERROR, "invalid zero block size of %d %d %d\n", block_size, output_size, output_count);
143 block_size= output_size - output_count - 1;
145 memset(&output_buffer[output_count+1], 0, block_size * 4);
146 output_count += block_size;
149 if (block_size <= 0xffff)
157 static inline int sign_only(int v)
159 return v ? FFSIGN(v) : 0;
162 static void predictor_decompress_fir_adapt(int32_t *error_buffer,
166 int16_t *predictor_coef_table,
167 int predictor_coef_num,
168 int predictor_quantitization)
172 /* first sample always copies */
173 *buffer_out = *error_buffer;
175 if (!predictor_coef_num) {
176 if (output_size <= 1)
179 memcpy(buffer_out+1, error_buffer+1, (output_size-1) * 4);
183 if (predictor_coef_num == 31) {
184 /* simple 1st-order prediction */
185 if (output_size <= 1)
187 for (i = 0; i < output_size - 1; i++) {
191 prev_value = buffer_out[i];
192 error_value = error_buffer[i+1];
194 sign_extend((prev_value + error_value), readsamplesize);
199 /* read warm-up samples */
200 if (predictor_coef_num > 0)
201 for (i = 0; i < predictor_coef_num; i++) {
204 val = buffer_out[i] + error_buffer[i+1];
205 val = sign_extend(val, readsamplesize);
206 buffer_out[i+1] = val;
209 /* NOTE: 4 and 8 are very common cases that could be optimized. */
212 if (predictor_coef_num > 0) {
213 for (i = predictor_coef_num + 1; i < output_size; i++) {
217 int error_val = error_buffer[i];
219 for (j = 0; j < predictor_coef_num; j++) {
220 sum += (buffer_out[predictor_coef_num-j] - buffer_out[0]) *
221 predictor_coef_table[j];
224 outval = (1 << (predictor_quantitization-1)) + sum;
225 outval = outval >> predictor_quantitization;
226 outval = outval + buffer_out[0] + error_val;
227 outval = sign_extend(outval, readsamplesize);
229 buffer_out[predictor_coef_num+1] = outval;
232 int predictor_num = predictor_coef_num - 1;
234 while (predictor_num >= 0 && error_val > 0) {
235 int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
236 int sign = sign_only(val);
238 predictor_coef_table[predictor_num] -= sign;
240 val *= sign; /* absolute value */
242 error_val -= ((val >> predictor_quantitization) *
243 (predictor_coef_num - predictor_num));
247 } else if (error_val < 0) {
248 int predictor_num = predictor_coef_num - 1;
250 while (predictor_num >= 0 && error_val < 0) {
251 int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
252 int sign = - sign_only(val);
254 predictor_coef_table[predictor_num] -= sign;
256 val *= sign; /* neg value */
258 error_val -= ((val >> predictor_quantitization) *
259 (predictor_coef_num - predictor_num));
270 static void decorrelate_stereo(int32_t *buffer[MAX_CHANNELS],
271 int numsamples, uint8_t interlacing_shift,
272 uint8_t interlacing_leftweight)
276 for (i = 0; i < numsamples; i++) {
282 a -= (b * interlacing_leftweight) >> interlacing_shift;
290 static void append_extra_bits(int32_t *buffer[MAX_CHANNELS],
291 int32_t *extra_bits_buffer[MAX_CHANNELS],
292 int extra_bits, int numchannels, int numsamples)
296 for (ch = 0; ch < numchannels; ch++)
297 for (i = 0; i < numsamples; i++)
298 buffer[ch][i] = (buffer[ch][i] << extra_bits) | extra_bits_buffer[ch][i];
301 static void interleave_stereo_16(int32_t *buffer[MAX_CHANNELS],
302 int16_t *buffer_out, int numsamples)
306 for (i = 0; i < numsamples; i++) {
307 *buffer_out++ = buffer[0][i];
308 *buffer_out++ = buffer[1][i];
312 static void interleave_stereo_24(int32_t *buffer[MAX_CHANNELS],
313 int32_t *buffer_out, int numsamples)
317 for (i = 0; i < numsamples; i++) {
318 *buffer_out++ = buffer[0][i] << 8;
319 *buffer_out++ = buffer[1][i] << 8;
323 static int alac_decode_frame(AVCodecContext *avctx, void *data,
324 int *got_frame_ptr, AVPacket *avpkt)
326 const uint8_t *inbuffer = avpkt->data;
327 int input_buffer_size = avpkt->size;
328 ALACContext *alac = avctx->priv_data;
331 unsigned int outputsamples;
333 unsigned int readsamplesize;
335 uint8_t interlacing_shift;
336 uint8_t interlacing_leftweight;
339 init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
341 channels = get_bits(&alac->gb, 3) + 1;
342 if (channels != avctx->channels) {
343 av_log(avctx, AV_LOG_ERROR, "frame header channel count mismatch\n");
344 return AVERROR_INVALIDDATA;
347 skip_bits(&alac->gb, 4); /* element instance tag */
348 skip_bits(&alac->gb, 12); /* unused header bits */
350 /* the number of output samples is stored in the frame */
351 hassize = get_bits1(&alac->gb);
353 alac->extra_bits = get_bits(&alac->gb, 2) << 3;
355 /* whether the frame is compressed */
356 isnotcompressed = get_bits1(&alac->gb);
359 /* now read the number of samples as a 32bit integer */
360 outputsamples = get_bits_long(&alac->gb, 32);
361 if (outputsamples > alac->max_samples_per_frame) {
362 av_log(avctx, AV_LOG_ERROR, "outputsamples %d > %d\n",
363 outputsamples, alac->max_samples_per_frame);
367 outputsamples = alac->max_samples_per_frame;
369 /* get output buffer */
370 if (outputsamples > INT32_MAX) {
371 av_log(avctx, AV_LOG_ERROR, "unsupported block size: %u\n", outputsamples);
372 return AVERROR_INVALIDDATA;
374 alac->frame.nb_samples = outputsamples;
375 if ((ret = avctx->get_buffer(avctx, &alac->frame)) < 0) {
376 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
380 readsamplesize = alac->sample_size - alac->extra_bits + channels - 1;
381 if (readsamplesize > MIN_CACHE_BITS) {
382 av_log(avctx, AV_LOG_ERROR, "readsamplesize too big (%d)\n", readsamplesize);
386 if (!isnotcompressed) {
387 /* so it is compressed */
388 int16_t predictor_coef_table[MAX_CHANNELS][32];
389 int predictor_coef_num[MAX_CHANNELS];
390 int prediction_type[MAX_CHANNELS];
391 int prediction_quantitization[MAX_CHANNELS];
392 int ricemodifier[MAX_CHANNELS];
394 interlacing_shift = get_bits(&alac->gb, 8);
395 interlacing_leftweight = get_bits(&alac->gb, 8);
397 for (ch = 0; ch < channels; ch++) {
398 prediction_type[ch] = get_bits(&alac->gb, 4);
399 prediction_quantitization[ch] = get_bits(&alac->gb, 4);
401 ricemodifier[ch] = get_bits(&alac->gb, 3);
402 predictor_coef_num[ch] = get_bits(&alac->gb, 5);
404 /* read the predictor table */
405 for (i = 0; i < predictor_coef_num[ch]; i++)
406 predictor_coef_table[ch][i] = (int16_t)get_bits(&alac->gb, 16);
409 if (alac->extra_bits) {
410 for (i = 0; i < outputsamples; i++) {
411 for (ch = 0; ch < channels; ch++)
412 alac->extra_bits_buffer[ch][i] = get_bits(&alac->gb, alac->extra_bits);
415 for (ch = 0; ch < channels; ch++) {
416 bastardized_rice_decompress(alac,
417 alac->predict_error_buffer[ch],
420 ricemodifier[ch] * alac->rice_history_mult / 4);
422 /* adaptive FIR filter */
423 if (prediction_type[ch] == 15) {
424 /* Prediction type 15 runs the adaptive FIR twice.
425 * The first pass uses the special-case coef_num = 31, while
426 * the second pass uses the coefs from the bitstream.
428 * However, this prediction type is not currently used by the
431 predictor_decompress_fir_adapt(alac->predict_error_buffer[ch],
432 alac->predict_error_buffer[ch],
433 outputsamples, readsamplesize,
435 } else if (prediction_type[ch] > 0) {
436 av_log(avctx, AV_LOG_WARNING, "unknown prediction type: %i\n",
437 prediction_type[ch]);
439 predictor_decompress_fir_adapt(alac->predict_error_buffer[ch],
440 alac->output_samples_buffer[ch],
441 outputsamples, readsamplesize,
442 predictor_coef_table[ch],
443 predictor_coef_num[ch],
444 prediction_quantitization[ch]);
447 /* not compressed, easy case */
448 for (i = 0; i < outputsamples; i++) {
449 for (ch = 0; ch < channels; ch++) {
450 alac->output_samples_buffer[ch][i] = get_sbits_long(&alac->gb,
454 alac->extra_bits = 0;
455 interlacing_shift = 0;
456 interlacing_leftweight = 0;
458 if (get_bits(&alac->gb, 3) != 7)
459 av_log(avctx, AV_LOG_ERROR, "Error : Wrong End Of Frame\n");
461 if (channels == 2 && interlacing_leftweight) {
462 decorrelate_stereo(alac->output_samples_buffer, outputsamples,
463 interlacing_shift, interlacing_leftweight);
466 if (alac->extra_bits) {
467 append_extra_bits(alac->output_samples_buffer, alac->extra_bits_buffer,
468 alac->extra_bits, alac->channels, outputsamples);
471 switch(alac->sample_size) {
474 interleave_stereo_16(alac->output_samples_buffer,
475 (int16_t *)alac->frame.data[0], outputsamples);
477 int16_t *outbuffer = (int16_t *)alac->frame.data[0];
478 for (i = 0; i < outputsamples; i++) {
479 outbuffer[i] = alac->output_samples_buffer[0][i];
485 interleave_stereo_24(alac->output_samples_buffer,
486 (int32_t *)alac->frame.data[0], outputsamples);
488 int32_t *outbuffer = (int32_t *)alac->frame.data[0];
489 for (i = 0; i < outputsamples; i++)
490 outbuffer[i] = alac->output_samples_buffer[0][i] << 8;
495 if (input_buffer_size * 8 - get_bits_count(&alac->gb) > 8)
496 av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n", input_buffer_size * 8 - get_bits_count(&alac->gb));
499 *(AVFrame *)data = alac->frame;
501 return input_buffer_size;
504 static av_cold int alac_decode_close(AVCodecContext *avctx)
506 ALACContext *alac = avctx->priv_data;
509 for (ch = 0; ch < alac->channels; ch++) {
510 av_freep(&alac->predict_error_buffer[ch]);
511 av_freep(&alac->output_samples_buffer[ch]);
512 av_freep(&alac->extra_bits_buffer[ch]);
518 static int allocate_buffers(ALACContext *alac)
521 for (ch = 0; ch < alac->channels; ch++) {
522 int buf_size = alac->max_samples_per_frame * sizeof(int32_t);
524 FF_ALLOC_OR_GOTO(alac->avctx, alac->predict_error_buffer[ch],
525 buf_size, buf_alloc_fail);
527 FF_ALLOC_OR_GOTO(alac->avctx, alac->output_samples_buffer[ch],
528 buf_size, buf_alloc_fail);
530 FF_ALLOC_OR_GOTO(alac->avctx, alac->extra_bits_buffer[ch],
531 buf_size, buf_alloc_fail);
535 alac_decode_close(alac->avctx);
536 return AVERROR(ENOMEM);
539 static int alac_set_info(ALACContext *alac)
543 bytestream2_init(&gb, alac->avctx->extradata,
544 alac->avctx->extradata_size);
546 bytestream2_skipu(&gb, 12); // size:4, alac:4, version:4
548 alac->max_samples_per_frame = bytestream2_get_be32u(&gb);
549 if (alac->max_samples_per_frame >= UINT_MAX/4){
550 av_log(alac->avctx, AV_LOG_ERROR,
551 "max_samples_per_frame too large\n");
552 return AVERROR_INVALIDDATA;
554 bytestream2_skipu(&gb, 1); // compatible version
555 alac->sample_size = bytestream2_get_byteu(&gb);
556 alac->rice_history_mult = bytestream2_get_byteu(&gb);
557 alac->rice_initial_history = bytestream2_get_byteu(&gb);
558 alac->rice_limit = bytestream2_get_byteu(&gb);
559 alac->channels = bytestream2_get_byteu(&gb);
560 bytestream2_get_be16u(&gb); // maxRun
561 bytestream2_get_be32u(&gb); // max coded frame size
562 bytestream2_get_be32u(&gb); // average bitrate
563 bytestream2_get_be32u(&gb); // samplerate
568 static av_cold int alac_decode_init(AVCodecContext * avctx)
571 ALACContext *alac = avctx->priv_data;
574 /* initialize from the extradata */
575 if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
576 av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
577 ALAC_EXTRADATA_SIZE);
580 if (alac_set_info(alac)) {
581 av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
585 switch (alac->sample_size) {
586 case 16: avctx->sample_fmt = AV_SAMPLE_FMT_S16;
588 case 24: avctx->sample_fmt = AV_SAMPLE_FMT_S32;
590 default: av_log_ask_for_sample(avctx, "Sample depth %d is not supported.\n",
592 return AVERROR_PATCHWELCOME;
595 if (alac->channels < 1) {
596 av_log(avctx, AV_LOG_WARNING, "Invalid channel count\n");
597 alac->channels = avctx->channels;
599 if (alac->channels > MAX_CHANNELS)
600 alac->channels = avctx->channels;
602 avctx->channels = alac->channels;
604 if (avctx->channels > MAX_CHANNELS) {
605 av_log(avctx, AV_LOG_ERROR, "Unsupported channel count: %d\n",
607 return AVERROR_PATCHWELCOME;
610 if ((ret = allocate_buffers(alac)) < 0) {
611 av_log(avctx, AV_LOG_ERROR, "Error allocating buffers\n");
615 avcodec_get_frame_defaults(&alac->frame);
616 avctx->coded_frame = &alac->frame;
621 AVCodec ff_alac_decoder = {
623 .type = AVMEDIA_TYPE_AUDIO,
625 .priv_data_size = sizeof(ALACContext),
626 .init = alac_decode_init,
627 .close = alac_decode_close,
628 .decode = alac_decode_frame,
629 .capabilities = CODEC_CAP_DR1,
630 .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),