indent
[libav.git] / libavcodec / alac.c
1 /*
2 * ALAC (Apple Lossless Audio Codec) decoder
3 * Copyright (c) 2005 David Hammerton
4 *
5 * This file is part of FFmpeg.
6 *
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.
11 *
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.
16 *
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
20 */
21
22 /**
23 * @file alac.c
24 * ALAC (Apple Lossless Audio Codec) decoder
25 * @author 2005 David Hammerton
26 *
27 * For more information on the ALAC format, visit:
28 * http://crazney.net/programs/itunes/alac.html
29 *
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
36 *
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
52 */
53
54
55 #include "avcodec.h"
56 #include "bitstream.h"
57 #include "bytestream.h"
58 #include "unary.h"
59
60 #define ALAC_EXTRADATA_SIZE 36
61 #define MAX_CHANNELS 2
62
63 typedef struct {
64
65 AVCodecContext *avctx;
66 GetBitContext gb;
67 /* init to 0; first frame decode should initialize from extradata and
68 * set this to 1 */
69 int context_initialized;
70
71 int samplesize;
72 int numchannels;
73 int bytespersample;
74
75 /* buffers */
76 int32_t *predicterror_buffer[MAX_CHANNELS];
77
78 int32_t *outputsamples_buffer[MAX_CHANNELS];
79
80 /* stuff from setinfo */
81 uint32_t setinfo_max_samples_per_frame; /* 0x1000 = 4096 */ /* max samples per frame? */
82 uint8_t setinfo_7a; /* 0x00 */
83 uint8_t setinfo_sample_size; /* 0x10 */
84 uint8_t setinfo_rice_historymult; /* 0x28 */
85 uint8_t setinfo_rice_initialhistory; /* 0x0a */
86 uint8_t setinfo_rice_kmodifier; /* 0x0e */
87 uint8_t setinfo_7f; /* 0x02 */
88 uint16_t setinfo_80; /* 0x00ff */
89 uint32_t setinfo_82; /* 0x000020e7 */ /* max sample size?? */
90 uint32_t setinfo_86; /* 0x00069fe4 */ /* bit rate (average)?? */
91 uint32_t setinfo_8a_rate; /* 0x0000ac44 */
92 /* end setinfo stuff */
93
94 } ALACContext;
95
96 static void allocate_buffers(ALACContext *alac)
97 {
98 int chan;
99 for (chan = 0; chan < MAX_CHANNELS; chan++) {
100 alac->predicterror_buffer[chan] =
101 av_malloc(alac->setinfo_max_samples_per_frame * 4);
102
103 alac->outputsamples_buffer[chan] =
104 av_malloc(alac->setinfo_max_samples_per_frame * 4);
105 }
106 }
107
108 static int alac_set_info(ALACContext *alac)
109 {
110 const unsigned char *ptr = alac->avctx->extradata;
111
112 ptr += 4; /* size */
113 ptr += 4; /* alac */
114 ptr += 4; /* 0 ? */
115
116 if(AV_RB32(ptr) >= UINT_MAX/4){
117 av_log(alac->avctx, AV_LOG_ERROR, "setinfo_max_samples_per_frame too large\n");
118 return -1;
119 }
120
121 /* buffer size / 2 ? */
122 alac->setinfo_max_samples_per_frame = bytestream_get_be32(&ptr);
123 alac->setinfo_7a = *ptr++;
124 alac->setinfo_sample_size = *ptr++;
125 alac->setinfo_rice_historymult = *ptr++;
126 alac->setinfo_rice_initialhistory = *ptr++;
127 alac->setinfo_rice_kmodifier = *ptr++;
128 /* channels? */
129 alac->setinfo_7f = *ptr++;
130 alac->setinfo_80 = bytestream_get_be16(&ptr);
131 /* max coded frame size */
132 alac->setinfo_82 = bytestream_get_be32(&ptr);
133 /* bitrate ? */
134 alac->setinfo_86 = bytestream_get_be32(&ptr);
135 /* samplerate */
136 alac->setinfo_8a_rate = bytestream_get_be32(&ptr);
137
138 allocate_buffers(alac);
139
140 return 0;
141 }
142
143 static inline int count_leading_zeros(int32_t input)
144 {
145 return 31-av_log2(input);
146 }
147
148
149 static inline int decode_scalar(GetBitContext *gb, int k, int limit, int readsamplesize){
150 /* read x - number of 1s before 0 represent the rice */
151 int x = get_unary_0_9(gb);
152
153 if (x > 8) { /* RICE THRESHOLD */
154 /* use alternative encoding */
155 x = get_bits(gb, readsamplesize);
156 } else {
157 if (k >= limit)
158 k = limit;
159
160 if (k != 1) {
161 int extrabits = show_bits(gb, k);
162
163 /* multiply x by 2^k - 1, as part of their strange algorithm */
164 x = (x << k) - x;
165
166 if (extrabits > 1) {
167 x += extrabits - 1;
168 skip_bits(gb, k);
169 } else
170 skip_bits(gb, k - 1);
171 }
172 }
173 return x;
174 }
175
176 static void bastardized_rice_decompress(ALACContext *alac,
177 int32_t *output_buffer,
178 int output_size,
179 int readsamplesize, /* arg_10 */
180 int rice_initialhistory, /* arg424->b */
181 int rice_kmodifier, /* arg424->d */
182 int rice_historymult, /* arg424->c */
183 int rice_kmodifier_mask /* arg424->e */
184 )
185 {
186 int output_count;
187 unsigned int history = rice_initialhistory;
188 int sign_modifier = 0;
189
190 for (output_count = 0; output_count < output_size; output_count++) {
191 int32_t x;
192 int32_t x_modified;
193 int32_t final_val;
194
195 /* standard rice encoding */
196 int k; /* size of extra bits */
197
198 /* read k, that is bits as is */
199 k = 31 - count_leading_zeros((history >> 9) + 3);
200 x= decode_scalar(&alac->gb, k, rice_kmodifier, readsamplesize);
201
202 x_modified = sign_modifier + x;
203 final_val = (x_modified + 1) / 2;
204 if (x_modified & 1) final_val *= -1;
205
206 output_buffer[output_count] = final_val;
207
208 sign_modifier = 0;
209
210 /* now update the history */
211 history += x_modified * rice_historymult
212 - ((history * rice_historymult) >> 9);
213
214 if (x_modified > 0xffff)
215 history = 0xffff;
216
217 /* special case: there may be compressed blocks of 0 */
218 if ((history < 128) && (output_count+1 < output_size)) {
219 int block_size, k;
220
221 sign_modifier = 1;
222
223 k = count_leading_zeros(history) + ((history + 16) >> 6 /* / 64 */) - 24;
224
225 block_size= decode_scalar(&alac->gb, k, rice_kmodifier, 16);
226
227 if (block_size > 0) {
228 memset(&output_buffer[output_count+1], 0, block_size * 4);
229 output_count += block_size;
230 }
231
232 if (block_size > 0xffff)
233 sign_modifier = 0;
234
235 history = 0;
236 }
237 }
238 }
239
240 static inline int32_t extend_sign32(int32_t val, int bits)
241 {
242 return (val << (32 - bits)) >> (32 - bits);
243 }
244
245 static inline int sign_only(int v)
246 {
247 return v ? FFSIGN(v) : 0;
248 }
249
250 static void predictor_decompress_fir_adapt(int32_t *error_buffer,
251 int32_t *buffer_out,
252 int output_size,
253 int readsamplesize,
254 int16_t *predictor_coef_table,
255 int predictor_coef_num,
256 int predictor_quantitization)
257 {
258 int i;
259
260 /* first sample always copies */
261 *buffer_out = *error_buffer;
262
263 if (!predictor_coef_num) {
264 if (output_size <= 1)
265 return;
266
267 memcpy(buffer_out+1, error_buffer+1, (output_size-1) * 4);
268 return;
269 }
270
271 if (predictor_coef_num == 0x1f) { /* 11111 - max value of predictor_coef_num */
272 /* second-best case scenario for fir decompression,
273 * error describes a small difference from the previous sample only
274 */
275 if (output_size <= 1)
276 return;
277 for (i = 0; i < output_size - 1; i++) {
278 int32_t prev_value;
279 int32_t error_value;
280
281 prev_value = buffer_out[i];
282 error_value = error_buffer[i+1];
283 buffer_out[i+1] =
284 extend_sign32((prev_value + error_value), readsamplesize);
285 }
286 return;
287 }
288
289 /* read warm-up samples */
290 if (predictor_coef_num > 0)
291 for (i = 0; i < predictor_coef_num; i++) {
292 int32_t val;
293
294 val = buffer_out[i] + error_buffer[i+1];
295 val = extend_sign32(val, readsamplesize);
296 buffer_out[i+1] = val;
297 }
298
299 #if 0
300 /* 4 and 8 are very common cases (the only ones i've seen). these
301 * should be unrolled and optimized
302 */
303 if (predictor_coef_num == 4) {
304 /* FIXME: optimized general case */
305 return;
306 }
307
308 if (predictor_coef_table == 8) {
309 /* FIXME: optimized general case */
310 return;
311 }
312 #endif
313
314 /* general case */
315 if (predictor_coef_num > 0) {
316 for (i = predictor_coef_num + 1; i < output_size; i++) {
317 int j;
318 int sum = 0;
319 int outval;
320 int error_val = error_buffer[i];
321
322 for (j = 0; j < predictor_coef_num; j++) {
323 sum += (buffer_out[predictor_coef_num-j] - buffer_out[0]) *
324 predictor_coef_table[j];
325 }
326
327 outval = (1 << (predictor_quantitization-1)) + sum;
328 outval = outval >> predictor_quantitization;
329 outval = outval + buffer_out[0] + error_val;
330 outval = extend_sign32(outval, readsamplesize);
331
332 buffer_out[predictor_coef_num+1] = outval;
333
334 if (error_val > 0) {
335 int predictor_num = predictor_coef_num - 1;
336
337 while (predictor_num >= 0 && error_val > 0) {
338 int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
339 int sign = sign_only(val);
340
341 predictor_coef_table[predictor_num] -= sign;
342
343 val *= sign; /* absolute value */
344
345 error_val -= ((val >> predictor_quantitization) *
346 (predictor_coef_num - predictor_num));
347
348 predictor_num--;
349 }
350 } else if (error_val < 0) {
351 int predictor_num = predictor_coef_num - 1;
352
353 while (predictor_num >= 0 && error_val < 0) {
354 int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
355 int sign = - sign_only(val);
356
357 predictor_coef_table[predictor_num] -= sign;
358
359 val *= sign; /* neg value */
360
361 error_val -= ((val >> predictor_quantitization) *
362 (predictor_coef_num - predictor_num));
363
364 predictor_num--;
365 }
366 }
367
368 buffer_out++;
369 }
370 }
371 }
372
373 static void reconstruct_stereo_16(int32_t *buffer[MAX_CHANNELS],
374 int16_t *buffer_out,
375 int numchannels, int numsamples,
376 uint8_t interlacing_shift,
377 uint8_t interlacing_leftweight)
378 {
379 int i;
380 if (numsamples <= 0)
381 return;
382
383 /* weighted interlacing */
384 if (interlacing_leftweight) {
385 for (i = 0; i < numsamples; i++) {
386 int32_t a, b;
387
388 a = buffer[0][i];
389 b = buffer[1][i];
390
391 a -= (b * interlacing_leftweight) >> interlacing_shift;
392 b += a;
393
394 buffer_out[i*numchannels] = b;
395 buffer_out[i*numchannels + 1] = a;
396 }
397
398 return;
399 }
400
401 /* otherwise basic interlacing took place */
402 for (i = 0; i < numsamples; i++) {
403 int16_t left, right;
404
405 left = buffer[0][i];
406 right = buffer[1][i];
407
408 buffer_out[i*numchannels] = left;
409 buffer_out[i*numchannels + 1] = right;
410 }
411 }
412
413 static int alac_decode_frame(AVCodecContext *avctx,
414 void *outbuffer, int *outputsize,
415 const uint8_t *inbuffer, int input_buffer_size)
416 {
417 ALACContext *alac = avctx->priv_data;
418
419 int channels;
420 int32_t outputsamples;
421 int hassize;
422 int readsamplesize;
423 int wasted_bytes;
424 int isnotcompressed;
425 uint8_t interlacing_shift;
426 uint8_t interlacing_leftweight;
427
428 /* short-circuit null buffers */
429 if (!inbuffer || !input_buffer_size)
430 return input_buffer_size;
431
432 /* initialize from the extradata */
433 if (!alac->context_initialized) {
434 if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
435 av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
436 ALAC_EXTRADATA_SIZE);
437 return input_buffer_size;
438 }
439 if (alac_set_info(alac)) {
440 av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
441 return input_buffer_size;
442 }
443 alac->context_initialized = 1;
444 }
445
446 init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
447
448 channels = get_bits(&alac->gb, 3) + 1;
449 if (channels > MAX_CHANNELS) {
450 av_log(avctx, AV_LOG_ERROR, "channels > %d not supported\n",
451 MAX_CHANNELS);
452 return input_buffer_size;
453 }
454
455 /* 2^result = something to do with output waiting.
456 * perhaps matters if we read > 1 frame in a pass?
457 */
458 skip_bits(&alac->gb, 4);
459
460 skip_bits(&alac->gb, 12); /* unknown, skip 12 bits */
461
462 /* the output sample size is stored soon */
463 hassize = get_bits1(&alac->gb);
464
465 wasted_bytes = get_bits(&alac->gb, 2); /* unknown ? */
466
467 /* whether the frame is compressed */
468 isnotcompressed = get_bits1(&alac->gb);
469
470 if (hassize) {
471 /* now read the number of samples as a 32bit integer */
472 outputsamples = get_bits(&alac->gb, 32);
473 } else
474 outputsamples = alac->setinfo_max_samples_per_frame;
475
476 *outputsize = outputsamples * alac->bytespersample;
477 readsamplesize = alac->setinfo_sample_size - (wasted_bytes * 8) + channels - 1;
478
479 if (!isnotcompressed) {
480 /* so it is compressed */
481 int16_t predictor_coef_table[channels][32];
482 int predictor_coef_num[channels];
483 int prediction_type[channels];
484 int prediction_quantitization[channels];
485 int ricemodifier[channels];
486 int i, chan;
487
488 interlacing_shift = get_bits(&alac->gb, 8);
489 interlacing_leftweight = get_bits(&alac->gb, 8);
490
491 for (chan = 0; chan < channels; chan++) {
492 prediction_type[chan] = get_bits(&alac->gb, 4);
493 prediction_quantitization[chan] = get_bits(&alac->gb, 4);
494
495 ricemodifier[chan] = get_bits(&alac->gb, 3);
496 predictor_coef_num[chan] = get_bits(&alac->gb, 5);
497
498 /* read the predictor table */
499 for (i = 0; i < predictor_coef_num[chan]; i++)
500 predictor_coef_table[chan][i] = (int16_t)get_bits(&alac->gb, 16);
501 }
502
503 if (wasted_bytes)
504 av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented, unhandling of wasted_bytes\n");
505
506 for (chan = 0; chan < channels; chan++) {
507 bastardized_rice_decompress(alac,
508 alac->predicterror_buffer[chan],
509 outputsamples,
510 readsamplesize,
511 alac->setinfo_rice_initialhistory,
512 alac->setinfo_rice_kmodifier,
513 ricemodifier[chan] * alac->setinfo_rice_historymult / 4,
514 (1 << alac->setinfo_rice_kmodifier) - 1);
515
516 if (prediction_type[chan] == 0) {
517 /* adaptive fir */
518 predictor_decompress_fir_adapt(alac->predicterror_buffer[chan],
519 alac->outputsamples_buffer[chan],
520 outputsamples,
521 readsamplesize,
522 predictor_coef_table[chan],
523 predictor_coef_num[chan],
524 prediction_quantitization[chan]);
525 } else {
526 av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type[chan]);
527 /* I think the only other prediction type (or perhaps this is
528 * just a boolean?) runs adaptive fir twice.. like:
529 * predictor_decompress_fir_adapt(predictor_error, tempout, ...)
530 * predictor_decompress_fir_adapt(predictor_error, outputsamples ...)
531 * little strange..
532 */
533 }
534 }
535 } else {
536 /* not compressed, easy case */
537 if (alac->setinfo_sample_size <= 16) {
538 int i, chan;
539 for (chan = 0; chan < channels; chan++)
540 for (i = 0; i < outputsamples; i++) {
541 int32_t audiobits;
542
543 audiobits = get_bits(&alac->gb, alac->setinfo_sample_size);
544 audiobits = extend_sign32(audiobits, readsamplesize);
545
546 alac->outputsamples_buffer[chan][i] = audiobits;
547 }
548 } else {
549 int i, chan;
550 for (chan = 0; chan < channels; chan++)
551 for (i = 0; i < outputsamples; i++) {
552 int32_t audiobits;
553
554 audiobits = get_bits(&alac->gb, 16);
555 /* special case of sign extension..
556 * as we'll be ORing the low 16bits into this */
557 audiobits = audiobits << 16;
558 audiobits = audiobits >> (32 - alac->setinfo_sample_size);
559 audiobits |= get_bits(&alac->gb, alac->setinfo_sample_size - 16);
560
561 alac->outputsamples_buffer[chan][i] = audiobits;
562 }
563 }
564 /* wasted_bytes = 0; */
565 interlacing_shift = 0;
566 interlacing_leftweight = 0;
567 }
568
569 switch(alac->setinfo_sample_size) {
570 case 16:
571 if (channels == 2) {
572 reconstruct_stereo_16(alac->outputsamples_buffer,
573 (int16_t*)outbuffer,
574 alac->numchannels,
575 outputsamples,
576 interlacing_shift,
577 interlacing_leftweight);
578 } else {
579 int i;
580 for (i = 0; i < outputsamples; i++) {
581 int16_t sample = alac->outputsamples_buffer[0][i];
582 ((int16_t*)outbuffer)[i * alac->numchannels] = sample;
583 }
584 }
585 break;
586 case 20:
587 case 24:
588 // It is not clear if there exist any encoder that creates 24 bit ALAC
589 // files. iTunes convert 24 bit raw files to 16 bit before encoding.
590 case 32:
591 av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
592 break;
593 default:
594 break;
595 }
596
597 return input_buffer_size;
598 }
599
600 static av_cold int alac_decode_init(AVCodecContext * avctx)
601 {
602 ALACContext *alac = avctx->priv_data;
603 alac->avctx = avctx;
604 alac->context_initialized = 0;
605
606 alac->samplesize = alac->avctx->bits_per_sample;
607 alac->numchannels = alac->avctx->channels;
608 alac->bytespersample = (alac->samplesize / 8) * alac->numchannels;
609
610 return 0;
611 }
612
613 static av_cold int alac_decode_close(AVCodecContext *avctx)
614 {
615 ALACContext *alac = avctx->priv_data;
616
617 int chan;
618 for (chan = 0; chan < MAX_CHANNELS; chan++) {
619 av_free(alac->predicterror_buffer[chan]);
620 av_free(alac->outputsamples_buffer[chan]);
621 }
622
623 return 0;
624 }
625
626 AVCodec alac_decoder = {
627 "alac",
628 CODEC_TYPE_AUDIO,
629 CODEC_ID_ALAC,
630 sizeof(ALACContext),
631 alac_decode_init,
632 NULL,
633 alac_decode_close,
634 alac_decode_frame,
635 };