Set ID3v1 genre to 0xFF (unknown) by default instead of 0 (Blues).
[FFMpeg-mirror/lagarith.git] / libavcodec / alac.c
blob5c48a4b28f4a105a8a34dcc602e8bddf788ef90a
1 /*
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
22 /**
23 * @file libavcodec/alac.c
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
37 * Extradata:
38 * 32bit size
39 * 32bit tag (=alac)
40 * 32bit zero?
41 * 32bit max sample per frame
42 * 8bit ?? (zero?)
43 * 8bit sample size
44 * 8bit history mult
45 * 8bit initial history
46 * 8bit kmodifier
47 * 8bit channels?
48 * 16bit ??
49 * 32bit max coded frame size
50 * 32bit bitrate?
51 * 32bit samplerate
55 #include "avcodec.h"
56 #include "get_bits.h"
57 #include "bytestream.h"
58 #include "unary.h"
59 #include "mathops.h"
61 #define ALAC_EXTRADATA_SIZE 36
62 #define MAX_CHANNELS 2
64 typedef struct {
66 AVCodecContext *avctx;
67 GetBitContext gb;
68 /* init to 0; first frame decode should initialize from extradata and
69 * set this to 1 */
70 int context_initialized;
72 int numchannels;
73 int bytespersample;
75 /* buffers */
76 int32_t *predicterror_buffer[MAX_CHANNELS];
78 int32_t *outputsamples_buffer[MAX_CHANNELS];
80 /* stuff from setinfo */
81 uint32_t setinfo_max_samples_per_frame; /* 0x1000 = 4096 */ /* max samples per frame? */
82 uint8_t setinfo_sample_size; /* 0x10 */
83 uint8_t setinfo_rice_historymult; /* 0x28 */
84 uint8_t setinfo_rice_initialhistory; /* 0x0a */
85 uint8_t setinfo_rice_kmodifier; /* 0x0e */
86 /* end setinfo stuff */
88 } ALACContext;
90 static void allocate_buffers(ALACContext *alac)
92 int chan;
93 for (chan = 0; chan < MAX_CHANNELS; chan++) {
94 alac->predicterror_buffer[chan] =
95 av_malloc(alac->setinfo_max_samples_per_frame * 4);
97 alac->outputsamples_buffer[chan] =
98 av_malloc(alac->setinfo_max_samples_per_frame * 4);
102 static int alac_set_info(ALACContext *alac)
104 const unsigned char *ptr = alac->avctx->extradata;
106 ptr += 4; /* size */
107 ptr += 4; /* alac */
108 ptr += 4; /* 0 ? */
110 if(AV_RB32(ptr) >= UINT_MAX/4){
111 av_log(alac->avctx, AV_LOG_ERROR, "setinfo_max_samples_per_frame too large\n");
112 return -1;
115 /* buffer size / 2 ? */
116 alac->setinfo_max_samples_per_frame = bytestream_get_be32(&ptr);
117 ptr++; /* ??? */
118 alac->setinfo_sample_size = *ptr++;
119 if (alac->setinfo_sample_size > 32) {
120 av_log(alac->avctx, AV_LOG_ERROR, "setinfo_sample_size too large\n");
121 return -1;
123 alac->setinfo_rice_historymult = *ptr++;
124 alac->setinfo_rice_initialhistory = *ptr++;
125 alac->setinfo_rice_kmodifier = *ptr++;
126 ptr++; /* channels? */
127 bytestream_get_be16(&ptr); /* ??? */
128 bytestream_get_be32(&ptr); /* max coded frame size */
129 bytestream_get_be32(&ptr); /* bitrate ? */
130 bytestream_get_be32(&ptr); /* samplerate */
132 allocate_buffers(alac);
134 return 0;
137 static inline int decode_scalar(GetBitContext *gb, int k, int limit, int readsamplesize){
138 /* read x - number of 1s before 0 represent the rice */
139 int x = get_unary_0_9(gb);
141 if (x > 8) { /* RICE THRESHOLD */
142 /* use alternative encoding */
143 x = get_bits(gb, readsamplesize);
144 } else {
145 if (k >= limit)
146 k = limit;
148 if (k != 1) {
149 int extrabits = show_bits(gb, k);
151 /* multiply x by 2^k - 1, as part of their strange algorithm */
152 x = (x << k) - x;
154 if (extrabits > 1) {
155 x += extrabits - 1;
156 skip_bits(gb, k);
157 } else
158 skip_bits(gb, k - 1);
161 return x;
164 static void bastardized_rice_decompress(ALACContext *alac,
165 int32_t *output_buffer,
166 int output_size,
167 int readsamplesize, /* arg_10 */
168 int rice_initialhistory, /* arg424->b */
169 int rice_kmodifier, /* arg424->d */
170 int rice_historymult, /* arg424->c */
171 int rice_kmodifier_mask /* arg424->e */
174 int output_count;
175 unsigned int history = rice_initialhistory;
176 int sign_modifier = 0;
178 for (output_count = 0; output_count < output_size; output_count++) {
179 int32_t x;
180 int32_t x_modified;
181 int32_t final_val;
183 /* standard rice encoding */
184 int k; /* size of extra bits */
186 /* read k, that is bits as is */
187 k = av_log2((history >> 9) + 3);
188 x= decode_scalar(&alac->gb, k, rice_kmodifier, readsamplesize);
190 x_modified = sign_modifier + x;
191 final_val = (x_modified + 1) / 2;
192 if (x_modified & 1) final_val *= -1;
194 output_buffer[output_count] = final_val;
196 sign_modifier = 0;
198 /* now update the history */
199 history += x_modified * rice_historymult
200 - ((history * rice_historymult) >> 9);
202 if (x_modified > 0xffff)
203 history = 0xffff;
205 /* special case: there may be compressed blocks of 0 */
206 if ((history < 128) && (output_count+1 < output_size)) {
207 int k;
208 unsigned int block_size;
210 sign_modifier = 1;
212 k = 7 - av_log2(history) + ((history + 16) >> 6 /* / 64 */);
214 block_size= decode_scalar(&alac->gb, k, rice_kmodifier, 16);
216 if (block_size > 0) {
217 if(block_size >= output_size - output_count){
218 av_log(alac->avctx, AV_LOG_ERROR, "invalid zero block size of %d %d %d\n", block_size, output_size, output_count);
219 block_size= output_size - output_count - 1;
221 memset(&output_buffer[output_count+1], 0, block_size * 4);
222 output_count += block_size;
225 if (block_size > 0xffff)
226 sign_modifier = 0;
228 history = 0;
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,
239 int32_t *buffer_out,
240 int output_size,
241 int readsamplesize,
242 int16_t *predictor_coef_table,
243 int predictor_coef_num,
244 int predictor_quantitization)
246 int i;
248 /* first sample always copies */
249 *buffer_out = *error_buffer;
251 if (!predictor_coef_num) {
252 if (output_size <= 1)
253 return;
255 memcpy(buffer_out+1, error_buffer+1, (output_size-1) * 4);
256 return;
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)
264 return;
265 for (i = 0; i < output_size - 1; i++) {
266 int32_t prev_value;
267 int32_t error_value;
269 prev_value = buffer_out[i];
270 error_value = error_buffer[i+1];
271 buffer_out[i+1] =
272 sign_extend((prev_value + error_value), readsamplesize);
274 return;
277 /* read warm-up samples */
278 if (predictor_coef_num > 0)
279 for (i = 0; i < predictor_coef_num; i++) {
280 int32_t val;
282 val = buffer_out[i] + error_buffer[i+1];
283 val = sign_extend(val, readsamplesize);
284 buffer_out[i+1] = val;
287 #if 0
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 */
293 return;
296 if (predictor_coef_table == 8) {
297 /* FIXME: optimized general case */
298 return;
300 #endif
302 /* general case */
303 if (predictor_coef_num > 0) {
304 for (i = predictor_coef_num + 1; i < output_size; i++) {
305 int j;
306 int sum = 0;
307 int outval;
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 = sign_extend(outval, readsamplesize);
320 buffer_out[predictor_coef_num+1] = outval;
322 if (error_val > 0) {
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));
336 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));
352 predictor_num--;
356 buffer_out++;
361 static void reconstruct_stereo_16(int32_t *buffer[MAX_CHANNELS],
362 int16_t *buffer_out,
363 int numchannels, int numsamples,
364 uint8_t interlacing_shift,
365 uint8_t interlacing_leftweight)
367 int i;
368 if (numsamples <= 0)
369 return;
371 /* weighted interlacing */
372 if (interlacing_leftweight) {
373 for (i = 0; i < numsamples; i++) {
374 int32_t a, b;
376 a = buffer[0][i];
377 b = buffer[1][i];
379 a -= (b * interlacing_leftweight) >> interlacing_shift;
380 b += a;
382 buffer_out[i*numchannels] = b;
383 buffer_out[i*numchannels + 1] = a;
386 return;
389 /* otherwise basic interlacing took place */
390 for (i = 0; i < numsamples; i++) {
391 int16_t left, right;
393 left = buffer[0][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 AVPacket *avpkt)
405 const uint8_t *inbuffer = avpkt->data;
406 int input_buffer_size = avpkt->size;
407 ALACContext *alac = avctx->priv_data;
409 int channels;
410 unsigned int outputsamples;
411 int hassize;
412 unsigned int readsamplesize;
413 int wasted_bytes;
414 int isnotcompressed;
415 uint8_t interlacing_shift;
416 uint8_t interlacing_leftweight;
418 /* short-circuit null buffers */
419 if (!inbuffer || !input_buffer_size)
420 return input_buffer_size;
422 /* initialize from the extradata */
423 if (!alac->context_initialized) {
424 if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
425 av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
426 ALAC_EXTRADATA_SIZE);
427 return input_buffer_size;
429 if (alac_set_info(alac)) {
430 av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
431 return input_buffer_size;
433 alac->context_initialized = 1;
436 init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
438 channels = get_bits(&alac->gb, 3) + 1;
439 if (channels > MAX_CHANNELS) {
440 av_log(avctx, AV_LOG_ERROR, "channels > %d not supported\n",
441 MAX_CHANNELS);
442 return input_buffer_size;
445 /* 2^result = something to do with output waiting.
446 * perhaps matters if we read > 1 frame in a pass?
448 skip_bits(&alac->gb, 4);
450 skip_bits(&alac->gb, 12); /* unknown, skip 12 bits */
452 /* the output sample size is stored soon */
453 hassize = get_bits1(&alac->gb);
455 wasted_bytes = get_bits(&alac->gb, 2); /* unknown ? */
457 /* whether the frame is compressed */
458 isnotcompressed = get_bits1(&alac->gb);
460 if (hassize) {
461 /* now read the number of samples as a 32bit integer */
462 outputsamples = get_bits_long(&alac->gb, 32);
463 if(outputsamples > alac->setinfo_max_samples_per_frame){
464 av_log(avctx, AV_LOG_ERROR, "outputsamples %d > %d\n", outputsamples, alac->setinfo_max_samples_per_frame);
465 return -1;
467 } else
468 outputsamples = alac->setinfo_max_samples_per_frame;
470 if(outputsamples > *outputsize / alac->bytespersample){
471 av_log(avctx, AV_LOG_ERROR, "sample buffer too small\n");
472 return -1;
475 *outputsize = outputsamples * alac->bytespersample;
476 readsamplesize = alac->setinfo_sample_size - (wasted_bytes * 8) + channels - 1;
477 if (readsamplesize > MIN_CACHE_BITS) {
478 av_log(avctx, AV_LOG_ERROR, "readsamplesize too big (%d)\n", readsamplesize);
479 return -1;
482 if (!isnotcompressed) {
483 /* so it is compressed */
484 int16_t predictor_coef_table[channels][32];
485 int predictor_coef_num[channels];
486 int prediction_type[channels];
487 int prediction_quantitization[channels];
488 int ricemodifier[channels];
489 int i, chan;
491 interlacing_shift = get_bits(&alac->gb, 8);
492 interlacing_leftweight = get_bits(&alac->gb, 8);
494 for (chan = 0; chan < channels; chan++) {
495 prediction_type[chan] = get_bits(&alac->gb, 4);
496 prediction_quantitization[chan] = get_bits(&alac->gb, 4);
498 ricemodifier[chan] = get_bits(&alac->gb, 3);
499 predictor_coef_num[chan] = get_bits(&alac->gb, 5);
501 /* read the predictor table */
502 for (i = 0; i < predictor_coef_num[chan]; i++)
503 predictor_coef_table[chan][i] = (int16_t)get_bits(&alac->gb, 16);
506 if (wasted_bytes)
507 av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented, unhandling of wasted_bytes\n");
509 for (chan = 0; chan < channels; chan++) {
510 bastardized_rice_decompress(alac,
511 alac->predicterror_buffer[chan],
512 outputsamples,
513 readsamplesize,
514 alac->setinfo_rice_initialhistory,
515 alac->setinfo_rice_kmodifier,
516 ricemodifier[chan] * alac->setinfo_rice_historymult / 4,
517 (1 << alac->setinfo_rice_kmodifier) - 1);
519 if (prediction_type[chan] == 0) {
520 /* adaptive fir */
521 predictor_decompress_fir_adapt(alac->predicterror_buffer[chan],
522 alac->outputsamples_buffer[chan],
523 outputsamples,
524 readsamplesize,
525 predictor_coef_table[chan],
526 predictor_coef_num[chan],
527 prediction_quantitization[chan]);
528 } else {
529 av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type[chan]);
530 /* I think the only other prediction type (or perhaps this is
531 * just a boolean?) runs adaptive fir twice.. like:
532 * predictor_decompress_fir_adapt(predictor_error, tempout, ...)
533 * predictor_decompress_fir_adapt(predictor_error, outputsamples ...)
534 * little strange..
538 } else {
539 /* not compressed, easy case */
540 int i, chan;
541 for (i = 0; i < outputsamples; i++)
542 for (chan = 0; chan < channels; chan++) {
543 int32_t audiobits;
545 audiobits = get_sbits_long(&alac->gb, alac->setinfo_sample_size);
547 alac->outputsamples_buffer[chan][i] = audiobits;
549 /* wasted_bytes = 0; */
550 interlacing_shift = 0;
551 interlacing_leftweight = 0;
553 if (get_bits(&alac->gb, 3) != 7)
554 av_log(avctx, AV_LOG_ERROR, "Error : Wrong End Of Frame\n");
556 switch(alac->setinfo_sample_size) {
557 case 16:
558 if (channels == 2) {
559 reconstruct_stereo_16(alac->outputsamples_buffer,
560 (int16_t*)outbuffer,
561 alac->numchannels,
562 outputsamples,
563 interlacing_shift,
564 interlacing_leftweight);
565 } else {
566 int i;
567 for (i = 0; i < outputsamples; i++) {
568 int16_t sample = alac->outputsamples_buffer[0][i];
569 ((int16_t*)outbuffer)[i * alac->numchannels] = sample;
572 break;
573 case 20:
574 case 24:
575 // It is not clear if there exist any encoder that creates 24 bit ALAC
576 // files. iTunes convert 24 bit raw files to 16 bit before encoding.
577 case 32:
578 av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
579 break;
580 default:
581 break;
584 if (input_buffer_size * 8 - get_bits_count(&alac->gb) > 8)
585 av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n", input_buffer_size * 8 - get_bits_count(&alac->gb));
587 return input_buffer_size;
590 static av_cold int alac_decode_init(AVCodecContext * avctx)
592 ALACContext *alac = avctx->priv_data;
593 alac->avctx = avctx;
594 alac->context_initialized = 0;
596 alac->numchannels = alac->avctx->channels;
597 alac->bytespersample = 2 * alac->numchannels;
598 avctx->sample_fmt = SAMPLE_FMT_S16;
600 return 0;
603 static av_cold int alac_decode_close(AVCodecContext *avctx)
605 ALACContext *alac = avctx->priv_data;
607 int chan;
608 for (chan = 0; chan < MAX_CHANNELS; chan++) {
609 av_free(alac->predicterror_buffer[chan]);
610 av_free(alac->outputsamples_buffer[chan]);
613 return 0;
616 AVCodec alac_decoder = {
617 "alac",
618 CODEC_TYPE_AUDIO,
619 CODEC_ID_ALAC,
620 sizeof(ALACContext),
621 alac_decode_init,
622 NULL,
623 alac_decode_close,
624 alac_decode_frame,
625 .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),