lavc: use designated initialisers for all codecs.
[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 Libav.
6 *
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.
11 *
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.
16 *
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
20 */
21
22 /**
23 * @file
24 * ALAC (Apple Lossless Audio Codec) decoder
25 * @author 2005 David Hammerton
26 * @see http://crazney.net/programs/itunes/alac.html
27 *
28 * Note: This decoder expects a 36- (0x24-)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:
31 * bytes 0-3 atom size (0x24), big-endian
32 * bytes 4-7 atom type ('alac', not the 'alac' tag from start of stsd)
33 * bytes 8-35 data bytes needed by decoder
34 *
35 * Extradata:
36 * 32bit size
37 * 32bit tag (=alac)
38 * 32bit zero?
39 * 32bit max sample per frame
40 * 8bit ?? (zero?)
41 * 8bit sample size
42 * 8bit history mult
43 * 8bit initial history
44 * 8bit kmodifier
45 * 8bit channels?
46 * 16bit ??
47 * 32bit max coded frame size
48 * 32bit bitrate?
49 * 32bit samplerate
50 */
51
52
53 #include "avcodec.h"
54 #include "get_bits.h"
55 #include "bytestream.h"
56 #include "unary.h"
57 #include "mathops.h"
58
59 #define ALAC_EXTRADATA_SIZE 36
60 #define MAX_CHANNELS 2
61
62 typedef struct {
63
64 AVCodecContext *avctx;
65 GetBitContext gb;
66
67 int numchannels;
68 int bytespersample;
69
70 /* buffers */
71 int32_t *predicterror_buffer[MAX_CHANNELS];
72
73 int32_t *outputsamples_buffer[MAX_CHANNELS];
74
75 int32_t *wasted_bits_buffer[MAX_CHANNELS];
76
77 /* stuff from setinfo */
78 uint32_t setinfo_max_samples_per_frame; /* 0x1000 = 4096 */ /* max samples per frame? */
79 uint8_t setinfo_sample_size; /* 0x10 */
80 uint8_t setinfo_rice_historymult; /* 0x28 */
81 uint8_t setinfo_rice_initialhistory; /* 0x0a */
82 uint8_t setinfo_rice_kmodifier; /* 0x0e */
83 /* end setinfo stuff */
84
85 int wasted_bits;
86 } ALACContext;
87
88 static void allocate_buffers(ALACContext *alac)
89 {
90 int chan;
91 for (chan = 0; chan < MAX_CHANNELS; chan++) {
92 alac->predicterror_buffer[chan] =
93 av_malloc(alac->setinfo_max_samples_per_frame * 4);
94
95 alac->outputsamples_buffer[chan] =
96 av_malloc(alac->setinfo_max_samples_per_frame * 4);
97
98 alac->wasted_bits_buffer[chan] = av_malloc(alac->setinfo_max_samples_per_frame * 4);
99 }
100 }
101
102 static int alac_set_info(ALACContext *alac)
103 {
104 const unsigned char *ptr = alac->avctx->extradata;
105
106 ptr += 4; /* size */
107 ptr += 4; /* alac */
108 ptr += 4; /* 0 ? */
109
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;
113 }
114
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;
122 }
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 */
131
132 allocate_buffers(alac);
133
134 return 0;
135 }
136
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);
140
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;
147
148 if (k != 1) {
149 int extrabits = show_bits(gb, k);
150
151 /* multiply x by 2^k - 1, as part of their strange algorithm */
152 x = (x << k) - x;
153
154 if (extrabits > 1) {
155 x += extrabits - 1;
156 skip_bits(gb, k);
157 } else
158 skip_bits(gb, k - 1);
159 }
160 }
161 return x;
162 }
163
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 */
172 )
173 {
174 int output_count;
175 unsigned int history = rice_initialhistory;
176 int sign_modifier = 0;
177
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;
182
183 /* standard rice encoding */
184 int k; /* size of extra bits */
185
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);
189
190 x_modified = sign_modifier + x;
191 final_val = (x_modified + 1) / 2;
192 if (x_modified & 1) final_val *= -1;
193
194 output_buffer[output_count] = final_val;
195
196 sign_modifier = 0;
197
198 /* now update the history */
199 history += x_modified * rice_historymult
200 - ((history * rice_historymult) >> 9);
201
202 if (x_modified > 0xffff)
203 history = 0xffff;
204
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;
209
210 sign_modifier = 1;
211
212 k = 7 - av_log2(history) + ((history + 16) >> 6 /* / 64 */);
213
214 block_size= decode_scalar(&alac->gb, k, rice_kmodifier, 16);
215
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;
220 }
221 memset(&output_buffer[output_count+1], 0, block_size * 4);
222 output_count += block_size;
223 }
224
225 if (block_size > 0xffff)
226 sign_modifier = 0;
227
228 history = 0;
229 }
230 }
231 }
232
233 static inline int sign_only(int v)
234 {
235 return v ? FFSIGN(v) : 0;
236 }
237
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)
245 {
246 int i;
247
248 /* first sample always copies */
249 *buffer_out = *error_buffer;
250
251 if (!predictor_coef_num) {
252 if (output_size <= 1)
253 return;
254
255 memcpy(buffer_out+1, error_buffer+1, (output_size-1) * 4);
256 return;
257 }
258
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
262 */
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;
268
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);
273 }
274 return;
275 }
276
277 /* read warm-up samples */
278 if (predictor_coef_num > 0)
279 for (i = 0; i < predictor_coef_num; i++) {
280 int32_t val;
281
282 val = buffer_out[i] + error_buffer[i+1];
283 val = sign_extend(val, readsamplesize);
284 buffer_out[i+1] = val;
285 }
286
287 /* 4 and 8 are very common cases (the only ones i've seen). these
288 * should be unrolled and optimized
289 */
290
291 /* general case */
292 if (predictor_coef_num > 0) {
293 for (i = predictor_coef_num + 1; i < output_size; i++) {
294 int j;
295 int sum = 0;
296 int outval;
297 int error_val = error_buffer[i];
298
299 for (j = 0; j < predictor_coef_num; j++) {
300 sum += (buffer_out[predictor_coef_num-j] - buffer_out[0]) *
301 predictor_coef_table[j];
302 }
303
304 outval = (1 << (predictor_quantitization-1)) + sum;
305 outval = outval >> predictor_quantitization;
306 outval = outval + buffer_out[0] + error_val;
307 outval = sign_extend(outval, readsamplesize);
308
309 buffer_out[predictor_coef_num+1] = outval;
310
311 if (error_val > 0) {
312 int predictor_num = predictor_coef_num - 1;
313
314 while (predictor_num >= 0 && error_val > 0) {
315 int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
316 int sign = sign_only(val);
317
318 predictor_coef_table[predictor_num] -= sign;
319
320 val *= sign; /* absolute value */
321
322 error_val -= ((val >> predictor_quantitization) *
323 (predictor_coef_num - predictor_num));
324
325 predictor_num--;
326 }
327 } else if (error_val < 0) {
328 int predictor_num = predictor_coef_num - 1;
329
330 while (predictor_num >= 0 && error_val < 0) {
331 int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
332 int sign = - sign_only(val);
333
334 predictor_coef_table[predictor_num] -= sign;
335
336 val *= sign; /* neg value */
337
338 error_val -= ((val >> predictor_quantitization) *
339 (predictor_coef_num - predictor_num));
340
341 predictor_num--;
342 }
343 }
344
345 buffer_out++;
346 }
347 }
348 }
349
350 static void reconstruct_stereo_16(int32_t *buffer[MAX_CHANNELS],
351 int16_t *buffer_out,
352 int numchannels, int numsamples,
353 uint8_t interlacing_shift,
354 uint8_t interlacing_leftweight)
355 {
356 int i;
357 if (numsamples <= 0)
358 return;
359
360 /* weighted interlacing */
361 if (interlacing_leftweight) {
362 for (i = 0; i < numsamples; i++) {
363 int32_t a, b;
364
365 a = buffer[0][i];
366 b = buffer[1][i];
367
368 a -= (b * interlacing_leftweight) >> interlacing_shift;
369 b += a;
370
371 buffer_out[i*numchannels] = b;
372 buffer_out[i*numchannels + 1] = a;
373 }
374
375 return;
376 }
377
378 /* otherwise basic interlacing took place */
379 for (i = 0; i < numsamples; i++) {
380 int16_t left, right;
381
382 left = buffer[0][i];
383 right = buffer[1][i];
384
385 buffer_out[i*numchannels] = left;
386 buffer_out[i*numchannels + 1] = right;
387 }
388 }
389
390 static void decorrelate_stereo_24(int32_t *buffer[MAX_CHANNELS],
391 int32_t *buffer_out,
392 int32_t *wasted_bits_buffer[MAX_CHANNELS],
393 int wasted_bits,
394 int numchannels, int numsamples,
395 uint8_t interlacing_shift,
396 uint8_t interlacing_leftweight)
397 {
398 int i;
399
400 if (numsamples <= 0)
401 return;
402
403 /* weighted interlacing */
404 if (interlacing_leftweight) {
405 for (i = 0; i < numsamples; i++) {
406 int32_t a, b;
407
408 a = buffer[0][i];
409 b = buffer[1][i];
410
411 a -= (b * interlacing_leftweight) >> interlacing_shift;
412 b += a;
413
414 if (wasted_bits) {
415 b = (b << wasted_bits) | wasted_bits_buffer[0][i];
416 a = (a << wasted_bits) | wasted_bits_buffer[1][i];
417 }
418
419 buffer_out[i * numchannels] = b << 8;
420 buffer_out[i * numchannels + 1] = a << 8;
421 }
422 } else {
423 for (i = 0; i < numsamples; i++) {
424 int32_t left, right;
425
426 left = buffer[0][i];
427 right = buffer[1][i];
428
429 if (wasted_bits) {
430 left = (left << wasted_bits) | wasted_bits_buffer[0][i];
431 right = (right << wasted_bits) | wasted_bits_buffer[1][i];
432 }
433
434 buffer_out[i * numchannels] = left << 8;
435 buffer_out[i * numchannels + 1] = right << 8;
436 }
437 }
438 }
439
440 static int alac_decode_frame(AVCodecContext *avctx,
441 void *outbuffer, int *outputsize,
442 AVPacket *avpkt)
443 {
444 const uint8_t *inbuffer = avpkt->data;
445 int input_buffer_size = avpkt->size;
446 ALACContext *alac = avctx->priv_data;
447
448 int channels;
449 unsigned int outputsamples;
450 int hassize;
451 unsigned int readsamplesize;
452 int isnotcompressed;
453 uint8_t interlacing_shift;
454 uint8_t interlacing_leftweight;
455
456 /* short-circuit null buffers */
457 if (!inbuffer || !input_buffer_size)
458 return -1;
459
460 init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
461
462 channels = get_bits(&alac->gb, 3) + 1;
463 if (channels > MAX_CHANNELS) {
464 av_log(avctx, AV_LOG_ERROR, "channels > %d not supported\n",
465 MAX_CHANNELS);
466 return -1;
467 }
468
469 /* 2^result = something to do with output waiting.
470 * perhaps matters if we read > 1 frame in a pass?
471 */
472 skip_bits(&alac->gb, 4);
473
474 skip_bits(&alac->gb, 12); /* unknown, skip 12 bits */
475
476 /* the output sample size is stored soon */
477 hassize = get_bits1(&alac->gb);
478
479 alac->wasted_bits = get_bits(&alac->gb, 2) << 3;
480
481 /* whether the frame is compressed */
482 isnotcompressed = get_bits1(&alac->gb);
483
484 if (hassize) {
485 /* now read the number of samples as a 32bit integer */
486 outputsamples = get_bits_long(&alac->gb, 32);
487 if(outputsamples > alac->setinfo_max_samples_per_frame){
488 av_log(avctx, AV_LOG_ERROR, "outputsamples %d > %d\n", outputsamples, alac->setinfo_max_samples_per_frame);
489 return -1;
490 }
491 } else
492 outputsamples = alac->setinfo_max_samples_per_frame;
493
494 switch (alac->setinfo_sample_size) {
495 case 16: avctx->sample_fmt = AV_SAMPLE_FMT_S16;
496 alac->bytespersample = channels << 1;
497 break;
498 case 24: avctx->sample_fmt = AV_SAMPLE_FMT_S32;
499 alac->bytespersample = channels << 2;
500 break;
501 default: av_log(avctx, AV_LOG_ERROR, "Sample depth %d is not supported.\n",
502 alac->setinfo_sample_size);
503 return -1;
504 }
505
506 if(outputsamples > *outputsize / alac->bytespersample){
507 av_log(avctx, AV_LOG_ERROR, "sample buffer too small\n");
508 return -1;
509 }
510
511 *outputsize = outputsamples * alac->bytespersample;
512 readsamplesize = alac->setinfo_sample_size - (alac->wasted_bits) + channels - 1;
513 if (readsamplesize > MIN_CACHE_BITS) {
514 av_log(avctx, AV_LOG_ERROR, "readsamplesize too big (%d)\n", readsamplesize);
515 return -1;
516 }
517
518 if (!isnotcompressed) {
519 /* so it is compressed */
520 int16_t predictor_coef_table[MAX_CHANNELS][32];
521 int predictor_coef_num[MAX_CHANNELS];
522 int prediction_type[MAX_CHANNELS];
523 int prediction_quantitization[MAX_CHANNELS];
524 int ricemodifier[MAX_CHANNELS];
525 int i, chan;
526
527 interlacing_shift = get_bits(&alac->gb, 8);
528 interlacing_leftweight = get_bits(&alac->gb, 8);
529
530 for (chan = 0; chan < channels; chan++) {
531 prediction_type[chan] = get_bits(&alac->gb, 4);
532 prediction_quantitization[chan] = get_bits(&alac->gb, 4);
533
534 ricemodifier[chan] = get_bits(&alac->gb, 3);
535 predictor_coef_num[chan] = get_bits(&alac->gb, 5);
536
537 /* read the predictor table */
538 for (i = 0; i < predictor_coef_num[chan]; i++)
539 predictor_coef_table[chan][i] = (int16_t)get_bits(&alac->gb, 16);
540 }
541
542 if (alac->wasted_bits) {
543 int i, ch;
544 for (i = 0; i < outputsamples; i++) {
545 for (ch = 0; ch < channels; ch++)
546 alac->wasted_bits_buffer[ch][i] = get_bits(&alac->gb, alac->wasted_bits);
547 }
548 }
549 for (chan = 0; chan < channels; chan++) {
550 bastardized_rice_decompress(alac,
551 alac->predicterror_buffer[chan],
552 outputsamples,
553 readsamplesize,
554 alac->setinfo_rice_initialhistory,
555 alac->setinfo_rice_kmodifier,
556 ricemodifier[chan] * alac->setinfo_rice_historymult / 4,
557 (1 << alac->setinfo_rice_kmodifier) - 1);
558
559 if (prediction_type[chan] == 0) {
560 /* adaptive fir */
561 predictor_decompress_fir_adapt(alac->predicterror_buffer[chan],
562 alac->outputsamples_buffer[chan],
563 outputsamples,
564 readsamplesize,
565 predictor_coef_table[chan],
566 predictor_coef_num[chan],
567 prediction_quantitization[chan]);
568 } else {
569 av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type[chan]);
570 /* I think the only other prediction type (or perhaps this is
571 * just a boolean?) runs adaptive fir twice.. like:
572 * predictor_decompress_fir_adapt(predictor_error, tempout, ...)
573 * predictor_decompress_fir_adapt(predictor_error, outputsamples ...)
574 * little strange..
575 */
576 }
577 }
578 } else {
579 /* not compressed, easy case */
580 int i, chan;
581 if (alac->setinfo_sample_size <= 16) {
582 for (i = 0; i < outputsamples; i++)
583 for (chan = 0; chan < channels; chan++) {
584 int32_t audiobits;
585
586 audiobits = get_sbits_long(&alac->gb, alac->setinfo_sample_size);
587
588 alac->outputsamples_buffer[chan][i] = audiobits;
589 }
590 } else {
591 for (i = 0; i < outputsamples; i++) {
592 for (chan = 0; chan < channels; chan++) {
593 alac->outputsamples_buffer[chan][i] = get_bits(&alac->gb,
594 alac->setinfo_sample_size);
595 alac->outputsamples_buffer[chan][i] = sign_extend(alac->outputsamples_buffer[chan][i],
596 alac->setinfo_sample_size);
597 }
598 }
599 }
600 alac->wasted_bits = 0;
601 interlacing_shift = 0;
602 interlacing_leftweight = 0;
603 }
604 if (get_bits(&alac->gb, 3) != 7)
605 av_log(avctx, AV_LOG_ERROR, "Error : Wrong End Of Frame\n");
606
607 switch(alac->setinfo_sample_size) {
608 case 16:
609 if (channels == 2) {
610 reconstruct_stereo_16(alac->outputsamples_buffer,
611 (int16_t*)outbuffer,
612 alac->numchannels,
613 outputsamples,
614 interlacing_shift,
615 interlacing_leftweight);
616 } else {
617 int i;
618 for (i = 0; i < outputsamples; i++) {
619 ((int16_t*)outbuffer)[i] = alac->outputsamples_buffer[0][i];
620 }
621 }
622 break;
623 case 24:
624 if (channels == 2) {
625 decorrelate_stereo_24(alac->outputsamples_buffer,
626 outbuffer,
627 alac->wasted_bits_buffer,
628 alac->wasted_bits,
629 alac->numchannels,
630 outputsamples,
631 interlacing_shift,
632 interlacing_leftweight);
633 } else {
634 int i;
635 for (i = 0; i < outputsamples; i++)
636 ((int32_t *)outbuffer)[i] = alac->outputsamples_buffer[0][i] << 8;
637 }
638 break;
639 }
640
641 if (input_buffer_size * 8 - get_bits_count(&alac->gb) > 8)
642 av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n", input_buffer_size * 8 - get_bits_count(&alac->gb));
643
644 return input_buffer_size;
645 }
646
647 static av_cold int alac_decode_init(AVCodecContext * avctx)
648 {
649 ALACContext *alac = avctx->priv_data;
650 alac->avctx = avctx;
651 alac->numchannels = alac->avctx->channels;
652
653 /* initialize from the extradata */
654 if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
655 av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
656 ALAC_EXTRADATA_SIZE);
657 return -1;
658 }
659 if (alac_set_info(alac)) {
660 av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
661 return -1;
662 }
663
664 return 0;
665 }
666
667 static av_cold int alac_decode_close(AVCodecContext *avctx)
668 {
669 ALACContext *alac = avctx->priv_data;
670
671 int chan;
672 for (chan = 0; chan < MAX_CHANNELS; chan++) {
673 av_freep(&alac->predicterror_buffer[chan]);
674 av_freep(&alac->outputsamples_buffer[chan]);
675 av_freep(&alac->wasted_bits_buffer[chan]);
676 }
677
678 return 0;
679 }
680
681 AVCodec ff_alac_decoder = {
682 .name = "alac",
683 .type = AVMEDIA_TYPE_AUDIO,
684 .id = CODEC_ID_ALAC,
685 .priv_data_size = sizeof(ALACContext),
686 .init = alac_decode_init,
687 .close = alac_decode_close,
688 .decode = alac_decode_frame,
689 .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),
690 };