219dcefab2116e65832fb1789e32e134ff63e327
[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 static void bastardized_rice_decompress(ALACContext *alac,
149 int32_t *output_buffer,
150 int output_size,
151 int readsamplesize, /* arg_10 */
152 int rice_initialhistory, /* arg424->b */
153 int rice_kmodifier, /* arg424->d */
154 int rice_historymult, /* arg424->c */
155 int rice_kmodifier_mask /* arg424->e */
156 )
157 {
158 int output_count;
159 unsigned int history = rice_initialhistory;
160 int sign_modifier = 0;
161
162 for (output_count = 0; output_count < output_size; output_count++) {
163 int32_t x;
164 int32_t x_modified;
165 int32_t final_val;
166
167 /* read x - number of 1s before 0 represent the rice */
168 x = get_unary_0_9(&alac->gb);
169
170 if (x > 8) { /* RICE THRESHOLD */
171 /* use alternative encoding */
172 x = get_bits(&alac->gb, readsamplesize);
173 } else {
174 /* standard rice encoding */
175 int extrabits;
176 int k; /* size of extra bits */
177
178 /* read k, that is bits as is */
179 k = 31 - count_leading_zeros((history >> 9) + 3);
180
181 if (k >= rice_kmodifier)
182 k = rice_kmodifier;
183
184 if (k != 1) {
185 extrabits = show_bits(&alac->gb, k);
186
187 /* multiply x by 2^k - 1, as part of their strange algorithm */
188 x = (x << k) - x;
189
190 if (extrabits > 1) {
191 x += extrabits - 1;
192 skip_bits(&alac->gb, k);
193 } else
194 skip_bits(&alac->gb, k - 1);
195 }
196 }
197
198 x_modified = sign_modifier + x;
199 final_val = (x_modified + 1) / 2;
200 if (x_modified & 1) final_val *= -1;
201
202 output_buffer[output_count] = final_val;
203
204 sign_modifier = 0;
205
206 /* now update the history */
207 history += x_modified * rice_historymult
208 - ((history * rice_historymult) >> 9);
209
210 if (x_modified > 0xffff)
211 history = 0xffff;
212
213 /* special case: there may be compressed blocks of 0 */
214 if ((history < 128) && (output_count+1 < output_size)) {
215 int block_size;
216
217 sign_modifier = 1;
218
219 x = get_unary_0_9(&alac->gb);
220
221 if (x > 8) {
222 block_size = get_bits(&alac->gb, 16);
223 block_size &= 0xffff;
224 } else {
225 int k;
226 int extrabits;
227
228 k = count_leading_zeros(history) + ((history + 16) >> 6 /* / 64 */) - 24;
229
230 extrabits = show_bits(&alac->gb, k);
231
232 block_size = (((1 << k) - 1) & rice_kmodifier_mask) * x
233 + extrabits - 1;
234
235 if (extrabits < 2) {
236 x = 1 - extrabits;
237 block_size += x;
238 skip_bits(&alac->gb, k - 1);
239 } else {
240 skip_bits(&alac->gb, k);
241 }
242 }
243
244 if (block_size > 0) {
245 memset(&output_buffer[output_count+1], 0, block_size * 4);
246 output_count += block_size;
247 }
248
249 if (block_size > 0xffff)
250 sign_modifier = 0;
251
252 history = 0;
253 }
254 }
255 }
256
257 static inline int32_t extend_sign32(int32_t val, int bits)
258 {
259 return (val << (32 - bits)) >> (32 - bits);
260 }
261
262 static inline int sign_only(int v)
263 {
264 return v ? FFSIGN(v) : 0;
265 }
266
267 static void predictor_decompress_fir_adapt(int32_t *error_buffer,
268 int32_t *buffer_out,
269 int output_size,
270 int readsamplesize,
271 int16_t *predictor_coef_table,
272 int predictor_coef_num,
273 int predictor_quantitization)
274 {
275 int i;
276
277 /* first sample always copies */
278 *buffer_out = *error_buffer;
279
280 if (!predictor_coef_num) {
281 if (output_size <= 1)
282 return;
283
284 memcpy(buffer_out+1, error_buffer+1, (output_size-1) * 4);
285 return;
286 }
287
288 if (predictor_coef_num == 0x1f) { /* 11111 - max value of predictor_coef_num */
289 /* second-best case scenario for fir decompression,
290 * error describes a small difference from the previous sample only
291 */
292 if (output_size <= 1)
293 return;
294 for (i = 0; i < output_size - 1; i++) {
295 int32_t prev_value;
296 int32_t error_value;
297
298 prev_value = buffer_out[i];
299 error_value = error_buffer[i+1];
300 buffer_out[i+1] =
301 extend_sign32((prev_value + error_value), readsamplesize);
302 }
303 return;
304 }
305
306 /* read warm-up samples */
307 if (predictor_coef_num > 0)
308 for (i = 0; i < predictor_coef_num; i++) {
309 int32_t val;
310
311 val = buffer_out[i] + error_buffer[i+1];
312 val = extend_sign32(val, readsamplesize);
313 buffer_out[i+1] = val;
314 }
315
316 #if 0
317 /* 4 and 8 are very common cases (the only ones i've seen). these
318 * should be unrolled and optimized
319 */
320 if (predictor_coef_num == 4) {
321 /* FIXME: optimized general case */
322 return;
323 }
324
325 if (predictor_coef_table == 8) {
326 /* FIXME: optimized general case */
327 return;
328 }
329 #endif
330
331 /* general case */
332 if (predictor_coef_num > 0) {
333 for (i = predictor_coef_num + 1; i < output_size; i++) {
334 int j;
335 int sum = 0;
336 int outval;
337 int error_val = error_buffer[i];
338
339 for (j = 0; j < predictor_coef_num; j++) {
340 sum += (buffer_out[predictor_coef_num-j] - buffer_out[0]) *
341 predictor_coef_table[j];
342 }
343
344 outval = (1 << (predictor_quantitization-1)) + sum;
345 outval = outval >> predictor_quantitization;
346 outval = outval + buffer_out[0] + error_val;
347 outval = extend_sign32(outval, readsamplesize);
348
349 buffer_out[predictor_coef_num+1] = outval;
350
351 if (error_val > 0) {
352 int predictor_num = predictor_coef_num - 1;
353
354 while (predictor_num >= 0 && error_val > 0) {
355 int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
356 int sign = sign_only(val);
357
358 predictor_coef_table[predictor_num] -= sign;
359
360 val *= sign; /* absolute value */
361
362 error_val -= ((val >> predictor_quantitization) *
363 (predictor_coef_num - predictor_num));
364
365 predictor_num--;
366 }
367 } else if (error_val < 0) {
368 int predictor_num = predictor_coef_num - 1;
369
370 while (predictor_num >= 0 && error_val < 0) {
371 int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
372 int sign = - sign_only(val);
373
374 predictor_coef_table[predictor_num] -= sign;
375
376 val *= sign; /* neg value */
377
378 error_val -= ((val >> predictor_quantitization) *
379 (predictor_coef_num - predictor_num));
380
381 predictor_num--;
382 }
383 }
384
385 buffer_out++;
386 }
387 }
388 }
389
390 static void reconstruct_stereo_16(int32_t *buffer[MAX_CHANNELS],
391 int16_t *buffer_out,
392 int numchannels, int numsamples,
393 uint8_t interlacing_shift,
394 uint8_t interlacing_leftweight)
395 {
396 int i;
397 if (numsamples <= 0)
398 return;
399
400 /* weighted interlacing */
401 if (interlacing_leftweight) {
402 for (i = 0; i < numsamples; i++) {
403 int32_t a, b;
404
405 a = buffer[0][i];
406 b = buffer[1][i];
407
408 a -= (b * interlacing_leftweight) >> interlacing_shift;
409 b += a;
410
411 buffer_out[i*numchannels] = b;
412 buffer_out[i*numchannels + 1] = a;
413 }
414
415 return;
416 }
417
418 /* otherwise basic interlacing took place */
419 for (i = 0; i < numsamples; i++) {
420 int16_t left, right;
421
422 left = buffer[0][i];
423 right = buffer[1][i];
424
425 buffer_out[i*numchannels] = left;
426 buffer_out[i*numchannels + 1] = right;
427 }
428 }
429
430 static int alac_decode_frame(AVCodecContext *avctx,
431 void *outbuffer, int *outputsize,
432 const uint8_t *inbuffer, int input_buffer_size)
433 {
434 ALACContext *alac = avctx->priv_data;
435
436 int channels;
437 int32_t outputsamples;
438 int hassize;
439 int readsamplesize;
440 int wasted_bytes;
441 int isnotcompressed;
442 uint8_t interlacing_shift;
443 uint8_t interlacing_leftweight;
444
445 /* short-circuit null buffers */
446 if (!inbuffer || !input_buffer_size)
447 return input_buffer_size;
448
449 /* initialize from the extradata */
450 if (!alac->context_initialized) {
451 if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
452 av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
453 ALAC_EXTRADATA_SIZE);
454 return input_buffer_size;
455 }
456 if (alac_set_info(alac)) {
457 av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
458 return input_buffer_size;
459 }
460 alac->context_initialized = 1;
461 }
462
463 init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
464
465 channels = get_bits(&alac->gb, 3) + 1;
466 if (channels > MAX_CHANNELS) {
467 av_log(avctx, AV_LOG_ERROR, "channels > %d not supported\n",
468 MAX_CHANNELS);
469 return input_buffer_size;
470 }
471
472 /* 2^result = something to do with output waiting.
473 * perhaps matters if we read > 1 frame in a pass?
474 */
475 skip_bits(&alac->gb, 4);
476
477 skip_bits(&alac->gb, 12); /* unknown, skip 12 bits */
478
479 /* the output sample size is stored soon */
480 hassize = get_bits1(&alac->gb);
481
482 wasted_bytes = get_bits(&alac->gb, 2); /* unknown ? */
483
484 /* whether the frame is compressed */
485 isnotcompressed = get_bits1(&alac->gb);
486
487 if (hassize) {
488 /* now read the number of samples as a 32bit integer */
489 outputsamples = get_bits(&alac->gb, 32);
490 } else
491 outputsamples = alac->setinfo_max_samples_per_frame;
492
493 *outputsize = outputsamples * alac->bytespersample;
494 readsamplesize = alac->setinfo_sample_size - (wasted_bytes * 8) + channels - 1;
495
496 if (!isnotcompressed) {
497 /* so it is compressed */
498 int16_t predictor_coef_table[channels][32];
499 int predictor_coef_num[channels];
500 int prediction_type[channels];
501 int prediction_quantitization[channels];
502 int ricemodifier[channels];
503 int i, chan;
504
505 interlacing_shift = get_bits(&alac->gb, 8);
506 interlacing_leftweight = get_bits(&alac->gb, 8);
507
508 for (chan = 0; chan < channels; chan++) {
509 prediction_type[chan] = get_bits(&alac->gb, 4);
510 prediction_quantitization[chan] = get_bits(&alac->gb, 4);
511
512 ricemodifier[chan] = get_bits(&alac->gb, 3);
513 predictor_coef_num[chan] = get_bits(&alac->gb, 5);
514
515 /* read the predictor table */
516 for (i = 0; i < predictor_coef_num[chan]; i++)
517 predictor_coef_table[chan][i] = (int16_t)get_bits(&alac->gb, 16);
518 }
519
520 if (wasted_bytes)
521 av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented, unhandling of wasted_bytes\n");
522
523 for (chan = 0; chan < channels; chan++) {
524 bastardized_rice_decompress(alac,
525 alac->predicterror_buffer[chan],
526 outputsamples,
527 readsamplesize,
528 alac->setinfo_rice_initialhistory,
529 alac->setinfo_rice_kmodifier,
530 ricemodifier[chan] * alac->setinfo_rice_historymult / 4,
531 (1 << alac->setinfo_rice_kmodifier) - 1);
532
533 if (prediction_type[chan] == 0) {
534 /* adaptive fir */
535 predictor_decompress_fir_adapt(alac->predicterror_buffer[chan],
536 alac->outputsamples_buffer[chan],
537 outputsamples,
538 readsamplesize,
539 predictor_coef_table[chan],
540 predictor_coef_num[chan],
541 prediction_quantitization[chan]);
542 } else {
543 av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type[chan]);
544 /* I think the only other prediction type (or perhaps this is
545 * just a boolean?) runs adaptive fir twice.. like:
546 * predictor_decompress_fir_adapt(predictor_error, tempout, ...)
547 * predictor_decompress_fir_adapt(predictor_error, outputsamples ...)
548 * little strange..
549 */
550 }
551 }
552 } else {
553 /* not compressed, easy case */
554 if (alac->setinfo_sample_size <= 16) {
555 int i, chan;
556 for (chan = 0; chan < channels; chan++)
557 for (i = 0; i < outputsamples; i++) {
558 int32_t audiobits;
559
560 audiobits = get_bits(&alac->gb, alac->setinfo_sample_size);
561 audiobits = extend_sign32(audiobits, readsamplesize);
562
563 alac->outputsamples_buffer[chan][i] = audiobits;
564 }
565 } else {
566 int i, chan;
567 for (chan = 0; chan < channels; chan++)
568 for (i = 0; i < outputsamples; i++) {
569 int32_t audiobits;
570
571 audiobits = get_bits(&alac->gb, 16);
572 /* special case of sign extension..
573 * as we'll be ORing the low 16bits into this */
574 audiobits = audiobits << 16;
575 audiobits = audiobits >> (32 - alac->setinfo_sample_size);
576 audiobits |= get_bits(&alac->gb, alac->setinfo_sample_size - 16);
577
578 alac->outputsamples_buffer[chan][i] = audiobits;
579 }
580 }
581 /* wasted_bytes = 0; */
582 interlacing_shift = 0;
583 interlacing_leftweight = 0;
584 }
585
586 switch(alac->setinfo_sample_size) {
587 case 16:
588 if (channels == 2) {
589 reconstruct_stereo_16(alac->outputsamples_buffer,
590 (int16_t*)outbuffer,
591 alac->numchannels,
592 outputsamples,
593 interlacing_shift,
594 interlacing_leftweight);
595 } else {
596 int i;
597 for (i = 0; i < outputsamples; i++) {
598 int16_t sample = alac->outputsamples_buffer[0][i];
599 ((int16_t*)outbuffer)[i * alac->numchannels] = sample;
600 }
601 }
602 break;
603 case 20:
604 case 24:
605 // It is not clear if there exist any encoder that creates 24 bit ALAC
606 // files. iTunes convert 24 bit raw files to 16 bit before encoding.
607 case 32:
608 av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
609 break;
610 default:
611 break;
612 }
613
614 return input_buffer_size;
615 }
616
617 static av_cold int alac_decode_init(AVCodecContext * avctx)
618 {
619 ALACContext *alac = avctx->priv_data;
620 alac->avctx = avctx;
621 alac->context_initialized = 0;
622
623 alac->samplesize = alac->avctx->bits_per_sample;
624 alac->numchannels = alac->avctx->channels;
625 alac->bytespersample = (alac->samplesize / 8) * alac->numchannels;
626
627 return 0;
628 }
629
630 static av_cold int alac_decode_close(AVCodecContext *avctx)
631 {
632 ALACContext *alac = avctx->priv_data;
633
634 int chan;
635 for (chan = 0; chan < MAX_CHANNELS; chan++) {
636 av_free(alac->predicterror_buffer[chan]);
637 av_free(alac->outputsamples_buffer[chan]);
638 }
639
640 return 0;
641 }
642
643 AVCodec alac_decoder = {
644 "alac",
645 CODEC_TYPE_AUDIO,
646 CODEC_ID_ALAC,
647 sizeof(ALACContext),
648 alac_decode_init,
649 NULL,
650 alac_decode_close,
651 alac_decode_frame,
652 };