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 */
78 int nb_samples; /**< number of samples in the current frame */
81 static inline int decode_scalar(GetBitContext *gb, int k, int readsamplesize)
83 int x = get_unary_0_9(gb);
85 if (x > 8) { /* RICE THRESHOLD */
86 /* use alternative encoding */
87 x = get_bits(gb, readsamplesize);
89 int extrabits = show_bits(gb, k);
91 /* multiply x by 2^k - 1, as part of their strange algorithm */
103 static void bastardized_rice_decompress(ALACContext *alac,
104 int32_t *output_buffer,
107 int rice_history_mult)
110 unsigned int history = alac->rice_initial_history;
111 int sign_modifier = 0;
113 for (output_count = 0; output_count < output_size; output_count++) {
116 /* read k, that is bits as is */
117 k = av_log2((history >> 9) + 3);
118 k = FFMIN(k, alac->rice_limit);
119 x = decode_scalar(&alac->gb, k, readsamplesize);
123 output_buffer[output_count] = (x >> 1) ^ -(x & 1);
125 /* now update the history */
129 history += x * rice_history_mult -
130 ((history * rice_history_mult) >> 9);
132 /* special case: there may be compressed blocks of 0 */
133 if ((history < 128) && (output_count+1 < output_size)) {
136 k = 7 - av_log2(history) + ((history + 16) >> 6 /* / 64 */);
137 k = FFMIN(k, alac->rice_limit);
139 block_size = decode_scalar(&alac->gb, k, 16);
141 if (block_size > 0) {
142 if(block_size >= output_size - output_count){
143 av_log(alac->avctx, AV_LOG_ERROR, "invalid zero block size of %d %d %d\n", block_size, output_size, output_count);
144 block_size= output_size - output_count - 1;
146 memset(&output_buffer[output_count + 1], 0,
147 block_size * sizeof(*output_buffer));
148 output_count += block_size;
151 if (block_size <= 0xffff)
159 static inline int sign_only(int v)
161 return v ? FFSIGN(v) : 0;
164 static void predictor_decompress_fir_adapt(int32_t *error_buffer,
168 int16_t *predictor_coef_table,
169 int predictor_coef_num,
170 int predictor_quantitization)
174 /* first sample always copies */
175 *buffer_out = *error_buffer;
177 if (output_size <= 1)
180 if (!predictor_coef_num) {
181 memcpy(&buffer_out[1], &error_buffer[1],
182 (output_size - 1) * sizeof(*buffer_out));
186 if (predictor_coef_num == 31) {
187 /* simple 1st-order prediction */
188 for (i = 1; i < output_size; i++) {
189 buffer_out[i] = sign_extend(buffer_out[i - 1] + error_buffer[i],
195 /* read warm-up samples */
196 for (i = 0; i < predictor_coef_num; i++) {
197 buffer_out[i + 1] = sign_extend(buffer_out[i] + error_buffer[i + 1],
201 /* NOTE: 4 and 8 are very common cases that could be optimized. */
204 for (i = predictor_coef_num; i < output_size - 1; i++) {
207 int error_val = error_buffer[i + 1];
209 int d = buffer_out[i - predictor_coef_num];
211 for (j = 0; j < predictor_coef_num; j++) {
212 val += (buffer_out[i - j] - d) *
213 predictor_coef_table[j];
216 val = (val + (1 << (predictor_quantitization - 1))) >>
217 predictor_quantitization;
218 val += d + error_val;
220 buffer_out[i + 1] = sign_extend(val, readsamplesize);
222 /* adapt LPC coefficients */
223 error_sign = sign_only(error_val);
225 for (j = predictor_coef_num - 1; j >= 0 && error_val * error_sign > 0; j--) {
227 val = d - buffer_out[i - j];
228 sign = sign_only(val) * error_sign;
229 predictor_coef_table[j] -= sign;
231 error_val -= ((val >> predictor_quantitization) *
232 (predictor_coef_num - j));
238 static void decorrelate_stereo(int32_t *buffer[MAX_CHANNELS],
239 int numsamples, uint8_t interlacing_shift,
240 uint8_t interlacing_leftweight)
244 for (i = 0; i < numsamples; i++) {
250 a -= (b * interlacing_leftweight) >> interlacing_shift;
258 static void append_extra_bits(int32_t *buffer[MAX_CHANNELS],
259 int32_t *extra_bits_buffer[MAX_CHANNELS],
260 int extra_bits, int numchannels, int numsamples)
264 for (ch = 0; ch < numchannels; ch++)
265 for (i = 0; i < numsamples; i++)
266 buffer[ch][i] = (buffer[ch][i] << extra_bits) | extra_bits_buffer[ch][i];
269 static int alac_decode_frame(AVCodecContext *avctx, void *data,
270 int *got_frame_ptr, AVPacket *avpkt)
272 ALACContext *alac = avctx->priv_data;
276 unsigned int readsamplesize;
278 uint8_t interlacing_shift;
279 uint8_t interlacing_leftweight;
282 init_get_bits(&alac->gb, avpkt->data, avpkt->size * 8);
284 channels = get_bits(&alac->gb, 3) + 1;
285 if (channels != avctx->channels) {
286 av_log(avctx, AV_LOG_ERROR, "frame header channel count mismatch\n");
287 return AVERROR_INVALIDDATA;
290 skip_bits(&alac->gb, 4); /* element instance tag */
291 skip_bits(&alac->gb, 12); /* unused header bits */
293 /* the number of output samples is stored in the frame */
294 hassize = get_bits1(&alac->gb);
296 alac->extra_bits = get_bits(&alac->gb, 2) << 3;
298 /* whether the frame is compressed */
299 is_compressed = !get_bits1(&alac->gb);
302 /* now read the number of samples as a 32bit integer */
303 uint32_t output_samples = get_bits_long(&alac->gb, 32);
304 if (!output_samples || output_samples > alac->max_samples_per_frame) {
305 av_log(avctx, AV_LOG_ERROR, "invalid samples per frame: %d\n",
307 return AVERROR_INVALIDDATA;
309 alac->nb_samples = output_samples;
311 alac->nb_samples = alac->max_samples_per_frame;
313 /* get output buffer */
314 alac->frame.nb_samples = alac->nb_samples;
315 if ((ret = avctx->get_buffer(avctx, &alac->frame)) < 0) {
316 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
320 readsamplesize = alac->sample_size - alac->extra_bits + channels - 1;
321 if (readsamplesize > MIN_CACHE_BITS) {
322 av_log(avctx, AV_LOG_ERROR, "readsamplesize too big (%d)\n", readsamplesize);
327 int16_t predictor_coef_table[MAX_CHANNELS][32];
328 int predictor_coef_num[MAX_CHANNELS];
329 int prediction_type[MAX_CHANNELS];
330 int prediction_quantitization[MAX_CHANNELS];
331 int ricemodifier[MAX_CHANNELS];
333 interlacing_shift = get_bits(&alac->gb, 8);
334 interlacing_leftweight = get_bits(&alac->gb, 8);
336 for (ch = 0; ch < channels; ch++) {
337 prediction_type[ch] = get_bits(&alac->gb, 4);
338 prediction_quantitization[ch] = get_bits(&alac->gb, 4);
340 ricemodifier[ch] = get_bits(&alac->gb, 3);
341 predictor_coef_num[ch] = get_bits(&alac->gb, 5);
343 /* read the predictor table */
344 for (i = 0; i < predictor_coef_num[ch]; i++)
345 predictor_coef_table[ch][i] = get_sbits(&alac->gb, 16);
348 if (alac->extra_bits) {
349 for (i = 0; i < alac->nb_samples; i++) {
350 for (ch = 0; ch < channels; ch++)
351 alac->extra_bits_buffer[ch][i] = get_bits(&alac->gb, alac->extra_bits);
354 for (ch = 0; ch < channels; ch++) {
355 bastardized_rice_decompress(alac,
356 alac->predict_error_buffer[ch],
359 ricemodifier[ch] * alac->rice_history_mult / 4);
361 /* adaptive FIR filter */
362 if (prediction_type[ch] == 15) {
363 /* Prediction type 15 runs the adaptive FIR twice.
364 * The first pass uses the special-case coef_num = 31, while
365 * the second pass uses the coefs from the bitstream.
367 * However, this prediction type is not currently used by the
370 predictor_decompress_fir_adapt(alac->predict_error_buffer[ch],
371 alac->predict_error_buffer[ch],
372 alac->nb_samples, readsamplesize,
374 } else if (prediction_type[ch] > 0) {
375 av_log(avctx, AV_LOG_WARNING, "unknown prediction type: %i\n",
376 prediction_type[ch]);
378 predictor_decompress_fir_adapt(alac->predict_error_buffer[ch],
379 alac->output_samples_buffer[ch],
380 alac->nb_samples, readsamplesize,
381 predictor_coef_table[ch],
382 predictor_coef_num[ch],
383 prediction_quantitization[ch]);
386 /* not compressed, easy case */
387 for (i = 0; i < alac->nb_samples; i++) {
388 for (ch = 0; ch < channels; ch++) {
389 alac->output_samples_buffer[ch][i] = get_sbits_long(&alac->gb,
393 alac->extra_bits = 0;
394 interlacing_shift = 0;
395 interlacing_leftweight = 0;
397 if (get_bits(&alac->gb, 3) != 7)
398 av_log(avctx, AV_LOG_ERROR, "Error : Wrong End Of Frame\n");
400 if (channels == 2 && interlacing_leftweight) {
401 decorrelate_stereo(alac->output_samples_buffer, alac->nb_samples,
402 interlacing_shift, interlacing_leftweight);
405 if (alac->extra_bits) {
406 append_extra_bits(alac->output_samples_buffer, alac->extra_bits_buffer,
407 alac->extra_bits, alac->channels, alac->nb_samples);
410 switch(alac->sample_size) {
412 int16_t *outbuffer = (int16_t *)alac->frame.data[0];
413 for (i = 0; i < alac->nb_samples; i++) {
414 *outbuffer++ = alac->output_samples_buffer[0][i];
416 *outbuffer++ = alac->output_samples_buffer[1][i];
420 int32_t *outbuffer = (int32_t *)alac->frame.data[0];
421 for (i = 0; i < alac->nb_samples; i++) {
422 *outbuffer++ = alac->output_samples_buffer[0][i] << 8;
424 *outbuffer++ = alac->output_samples_buffer[1][i] << 8;
429 if (avpkt->size * 8 - get_bits_count(&alac->gb) > 8)
430 av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n",
431 avpkt->size * 8 - get_bits_count(&alac->gb));
434 *(AVFrame *)data = alac->frame;
439 static av_cold int alac_decode_close(AVCodecContext *avctx)
441 ALACContext *alac = avctx->priv_data;
444 for (ch = 0; ch < alac->channels; ch++) {
445 av_freep(&alac->predict_error_buffer[ch]);
446 av_freep(&alac->output_samples_buffer[ch]);
447 av_freep(&alac->extra_bits_buffer[ch]);
453 static int allocate_buffers(ALACContext *alac)
456 for (ch = 0; ch < alac->channels; ch++) {
457 int buf_size = alac->max_samples_per_frame * sizeof(int32_t);
459 FF_ALLOC_OR_GOTO(alac->avctx, alac->predict_error_buffer[ch],
460 buf_size, buf_alloc_fail);
462 FF_ALLOC_OR_GOTO(alac->avctx, alac->output_samples_buffer[ch],
463 buf_size, buf_alloc_fail);
465 FF_ALLOC_OR_GOTO(alac->avctx, alac->extra_bits_buffer[ch],
466 buf_size, buf_alloc_fail);
470 alac_decode_close(alac->avctx);
471 return AVERROR(ENOMEM);
474 static int alac_set_info(ALACContext *alac)
478 bytestream2_init(&gb, alac->avctx->extradata,
479 alac->avctx->extradata_size);
481 bytestream2_skipu(&gb, 12); // size:4, alac:4, version:4
483 alac->max_samples_per_frame = bytestream2_get_be32u(&gb);
484 if (!alac->max_samples_per_frame || alac->max_samples_per_frame > INT_MAX) {
485 av_log(alac->avctx, AV_LOG_ERROR, "max samples per frame invalid: %u\n",
486 alac->max_samples_per_frame);
487 return AVERROR_INVALIDDATA;
489 bytestream2_skipu(&gb, 1); // compatible version
490 alac->sample_size = bytestream2_get_byteu(&gb);
491 alac->rice_history_mult = bytestream2_get_byteu(&gb);
492 alac->rice_initial_history = bytestream2_get_byteu(&gb);
493 alac->rice_limit = bytestream2_get_byteu(&gb);
494 alac->channels = bytestream2_get_byteu(&gb);
495 bytestream2_get_be16u(&gb); // maxRun
496 bytestream2_get_be32u(&gb); // max coded frame size
497 bytestream2_get_be32u(&gb); // average bitrate
498 bytestream2_get_be32u(&gb); // samplerate
503 static av_cold int alac_decode_init(AVCodecContext * avctx)
506 ALACContext *alac = avctx->priv_data;
509 /* initialize from the extradata */
510 if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
511 av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
512 ALAC_EXTRADATA_SIZE);
515 if (alac_set_info(alac)) {
516 av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
520 switch (alac->sample_size) {
521 case 16: avctx->sample_fmt = AV_SAMPLE_FMT_S16;
523 case 24: avctx->sample_fmt = AV_SAMPLE_FMT_S32;
525 default: av_log_ask_for_sample(avctx, "Sample depth %d is not supported.\n",
527 return AVERROR_PATCHWELCOME;
530 if (alac->channels < 1) {
531 av_log(avctx, AV_LOG_WARNING, "Invalid channel count\n");
532 alac->channels = avctx->channels;
534 if (alac->channels > MAX_CHANNELS)
535 alac->channels = avctx->channels;
537 avctx->channels = alac->channels;
539 if (avctx->channels > MAX_CHANNELS) {
540 av_log(avctx, AV_LOG_ERROR, "Unsupported channel count: %d\n",
542 return AVERROR_PATCHWELCOME;
545 if ((ret = allocate_buffers(alac)) < 0) {
546 av_log(avctx, AV_LOG_ERROR, "Error allocating buffers\n");
550 avcodec_get_frame_defaults(&alac->frame);
551 avctx->coded_frame = &alac->frame;
556 AVCodec ff_alac_decoder = {
558 .type = AVMEDIA_TYPE_AUDIO,
560 .priv_data_size = sizeof(ALACContext),
561 .init = alac_decode_init,
562 .close = alac_decode_close,
563 .decode = alac_decode_frame,
564 .capabilities = CODEC_CAP_DR1,
565 .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),