lavc: add a wrapper for AVCodecContext.get_buffer().
[libav.git] / libavcodec / shorten.c
1 /*
2 * Shorten decoder
3 * Copyright (c) 2005 Jeff Muizelaar
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 * Shorten decoder
25 * @author Jeff Muizelaar
26 *
27 */
28
29 #include <limits.h>
30 #include "avcodec.h"
31 #include "bytestream.h"
32 #include "get_bits.h"
33 #include "golomb.h"
34 #include "internal.h"
35
36 #define MAX_CHANNELS 8
37 #define MAX_BLOCKSIZE 65535
38
39 #define OUT_BUFFER_SIZE 16384
40
41 #define ULONGSIZE 2
42
43 #define WAVE_FORMAT_PCM 0x0001
44
45 #define DEFAULT_BLOCK_SIZE 256
46
47 #define TYPESIZE 4
48 #define CHANSIZE 0
49 #define LPCQSIZE 2
50 #define ENERGYSIZE 3
51 #define BITSHIFTSIZE 2
52
53 #define TYPE_S16HL 3
54 #define TYPE_S16LH 5
55
56 #define NWRAP 3
57 #define NSKIPSIZE 1
58
59 #define LPCQUANT 5
60 #define V2LPCQOFFSET (1 << LPCQUANT)
61
62 #define FNSIZE 2
63 #define FN_DIFF0 0
64 #define FN_DIFF1 1
65 #define FN_DIFF2 2
66 #define FN_DIFF3 3
67 #define FN_QUIT 4
68 #define FN_BLOCKSIZE 5
69 #define FN_BITSHIFT 6
70 #define FN_QLPC 7
71 #define FN_ZERO 8
72 #define FN_VERBATIM 9
73
74 /** indicates if the FN_* command is audio or non-audio */
75 static const uint8_t is_audio_command[10] = { 1, 1, 1, 1, 0, 0, 0, 1, 1, 0 };
76
77 #define VERBATIM_CKSIZE_SIZE 5
78 #define VERBATIM_BYTE_SIZE 8
79 #define CANONICAL_HEADER_SIZE 44
80
81 typedef struct ShortenContext {
82 AVCodecContext *avctx;
83 AVFrame frame;
84 GetBitContext gb;
85
86 int min_framesize, max_framesize;
87 int channels;
88
89 int32_t *decoded[MAX_CHANNELS];
90 int32_t *decoded_base[MAX_CHANNELS];
91 int32_t *offset[MAX_CHANNELS];
92 int *coeffs;
93 uint8_t *bitstream;
94 int bitstream_size;
95 int bitstream_index;
96 unsigned int allocated_bitstream_size;
97 int header_size;
98 uint8_t header[OUT_BUFFER_SIZE];
99 int version;
100 int cur_chan;
101 int bitshift;
102 int nmean;
103 int internal_ftype;
104 int nwrap;
105 int blocksize;
106 int bitindex;
107 int32_t lpcqoffset;
108 int got_header;
109 int got_quit_command;
110 } ShortenContext;
111
112 static av_cold int shorten_decode_init(AVCodecContext * avctx)
113 {
114 ShortenContext *s = avctx->priv_data;
115 s->avctx = avctx;
116 avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
117
118 avcodec_get_frame_defaults(&s->frame);
119 avctx->coded_frame = &s->frame;
120
121 return 0;
122 }
123
124 static int allocate_buffers(ShortenContext *s)
125 {
126 int i, chan;
127 int *coeffs;
128 void *tmp_ptr;
129
130 for (chan=0; chan<s->channels; chan++) {
131 if(FFMAX(1, s->nmean) >= UINT_MAX/sizeof(int32_t)){
132 av_log(s->avctx, AV_LOG_ERROR, "nmean too large\n");
133 return -1;
134 }
135 if(s->blocksize + s->nwrap >= UINT_MAX/sizeof(int32_t) || s->blocksize + s->nwrap <= (unsigned)s->nwrap){
136 av_log(s->avctx, AV_LOG_ERROR, "s->blocksize + s->nwrap too large\n");
137 return -1;
138 }
139
140 tmp_ptr = av_realloc(s->offset[chan], sizeof(int32_t)*FFMAX(1, s->nmean));
141 if (!tmp_ptr)
142 return AVERROR(ENOMEM);
143 s->offset[chan] = tmp_ptr;
144
145 tmp_ptr = av_realloc(s->decoded_base[chan], (s->blocksize + s->nwrap) *
146 sizeof(s->decoded_base[0][0]));
147 if (!tmp_ptr)
148 return AVERROR(ENOMEM);
149 s->decoded_base[chan] = tmp_ptr;
150 for (i=0; i<s->nwrap; i++)
151 s->decoded_base[chan][i] = 0;
152 s->decoded[chan] = s->decoded_base[chan] + s->nwrap;
153 }
154
155 coeffs = av_realloc(s->coeffs, s->nwrap * sizeof(*s->coeffs));
156 if (!coeffs)
157 return AVERROR(ENOMEM);
158 s->coeffs = coeffs;
159
160 return 0;
161 }
162
163
164 static inline unsigned int get_uint(ShortenContext *s, int k)
165 {
166 if (s->version != 0)
167 k = get_ur_golomb_shorten(&s->gb, ULONGSIZE);
168 return get_ur_golomb_shorten(&s->gb, k);
169 }
170
171
172 static void fix_bitshift(ShortenContext *s, int32_t *buffer)
173 {
174 int i;
175
176 if (s->bitshift != 0)
177 for (i = 0; i < s->blocksize; i++)
178 buffer[i] <<= s->bitshift;
179 }
180
181
182 static int init_offset(ShortenContext *s)
183 {
184 int32_t mean = 0;
185 int chan, i;
186 int nblock = FFMAX(1, s->nmean);
187 /* initialise offset */
188 switch (s->internal_ftype)
189 {
190 case TYPE_S16HL:
191 case TYPE_S16LH:
192 mean = 0;
193 break;
194 default:
195 av_log(s->avctx, AV_LOG_ERROR, "unknown audio type");
196 return AVERROR_INVALIDDATA;
197 }
198
199 for (chan = 0; chan < s->channels; chan++)
200 for (i = 0; i < nblock; i++)
201 s->offset[chan][i] = mean;
202 return 0;
203 }
204
205 static int decode_wave_header(AVCodecContext *avctx, const uint8_t *header,
206 int header_size)
207 {
208 int len;
209 short wave_format;
210
211
212 if (bytestream_get_le32(&header) != MKTAG('R','I','F','F')) {
213 av_log(avctx, AV_LOG_ERROR, "missing RIFF tag\n");
214 return -1;
215 }
216
217 header += 4; /* chunk size */;
218
219 if (bytestream_get_le32(&header) != MKTAG('W','A','V','E')) {
220 av_log(avctx, AV_LOG_ERROR, "missing WAVE tag\n");
221 return -1;
222 }
223
224 while (bytestream_get_le32(&header) != MKTAG('f','m','t',' ')) {
225 len = bytestream_get_le32(&header);
226 header += len;
227 }
228 len = bytestream_get_le32(&header);
229
230 if (len < 16) {
231 av_log(avctx, AV_LOG_ERROR, "fmt chunk was too short\n");
232 return -1;
233 }
234
235 wave_format = bytestream_get_le16(&header);
236
237 switch (wave_format) {
238 case WAVE_FORMAT_PCM:
239 break;
240 default:
241 av_log(avctx, AV_LOG_ERROR, "unsupported wave format\n");
242 return -1;
243 }
244
245 header += 2; // skip channels (already got from shorten header)
246 avctx->sample_rate = bytestream_get_le32(&header);
247 header += 4; // skip bit rate (represents original uncompressed bit rate)
248 header += 2; // skip block align (not needed)
249 avctx->bits_per_coded_sample = bytestream_get_le16(&header);
250
251 if (avctx->bits_per_coded_sample != 16) {
252 av_log(avctx, AV_LOG_ERROR, "unsupported number of bits per sample\n");
253 return -1;
254 }
255
256 len -= 16;
257 if (len > 0)
258 av_log(avctx, AV_LOG_INFO, "%d header bytes unparsed\n", len);
259
260 return 0;
261 }
262
263 static void output_buffer(int16_t **samples, int nchan, int blocksize,
264 int32_t **buffer)
265 {
266 int i, ch;
267 for (ch = 0; ch < nchan; ch++) {
268 int32_t *in = buffer[ch];
269 int16_t *out = samples[ch];
270 for (i = 0; i < blocksize; i++)
271 out[i] = av_clip_int16(in[i]);
272 }
273 }
274
275 static const int fixed_coeffs[3][3] = {
276 { 1, 0, 0 },
277 { 2, -1, 0 },
278 { 3, -3, 1 }
279 };
280
281 static int decode_subframe_lpc(ShortenContext *s, int command, int channel,
282 int residual_size, int32_t coffset)
283 {
284 int pred_order, sum, qshift, init_sum, i, j;
285 const int *coeffs;
286
287 if (command == FN_QLPC) {
288 /* read/validate prediction order */
289 pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
290 if (pred_order > s->nwrap) {
291 av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n", pred_order);
292 return AVERROR(EINVAL);
293 }
294 /* read LPC coefficients */
295 for (i=0; i<pred_order; i++)
296 s->coeffs[i] = get_sr_golomb_shorten(&s->gb, LPCQUANT);
297 coeffs = s->coeffs;
298
299 qshift = LPCQUANT;
300 } else {
301 /* fixed LPC coeffs */
302 pred_order = command;
303 coeffs = fixed_coeffs[pred_order-1];
304 qshift = 0;
305 }
306
307 /* subtract offset from previous samples to use in prediction */
308 if (command == FN_QLPC && coffset)
309 for (i = -pred_order; i < 0; i++)
310 s->decoded[channel][i] -= coffset;
311
312 /* decode residual and do LPC prediction */
313 init_sum = pred_order ? (command == FN_QLPC ? s->lpcqoffset : 0) : coffset;
314 for (i=0; i < s->blocksize; i++) {
315 sum = init_sum;
316 for (j=0; j<pred_order; j++)
317 sum += coeffs[j] * s->decoded[channel][i-j-1];
318 s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + (sum >> qshift);
319 }
320
321 /* add offset to current samples */
322 if (command == FN_QLPC && coffset)
323 for (i = 0; i < s->blocksize; i++)
324 s->decoded[channel][i] += coffset;
325
326 return 0;
327 }
328
329 static int read_header(ShortenContext *s)
330 {
331 int i, ret;
332 int maxnlpc = 0;
333 /* shorten signature */
334 if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {
335 av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
336 return -1;
337 }
338
339 s->lpcqoffset = 0;
340 s->blocksize = DEFAULT_BLOCK_SIZE;
341 s->nmean = -1;
342 s->version = get_bits(&s->gb, 8);
343 s->internal_ftype = get_uint(s, TYPESIZE);
344
345 s->channels = get_uint(s, CHANSIZE);
346 if (s->channels <= 0 || s->channels > MAX_CHANNELS) {
347 av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
348 return -1;
349 }
350 s->avctx->channels = s->channels;
351
352 /* get blocksize if version > 0 */
353 if (s->version > 0) {
354 int skip_bytes, blocksize;
355
356 blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
357 if (!blocksize || blocksize > MAX_BLOCKSIZE) {
358 av_log(s->avctx, AV_LOG_ERROR, "invalid or unsupported block size: %d\n",
359 blocksize);
360 return AVERROR(EINVAL);
361 }
362 s->blocksize = blocksize;
363
364 maxnlpc = get_uint(s, LPCQSIZE);
365 s->nmean = get_uint(s, 0);
366
367 skip_bytes = get_uint(s, NSKIPSIZE);
368 for (i=0; i<skip_bytes; i++) {
369 skip_bits(&s->gb, 8);
370 }
371 }
372 s->nwrap = FFMAX(NWRAP, maxnlpc);
373
374 if ((ret = allocate_buffers(s)) < 0)
375 return ret;
376
377 if ((ret = init_offset(s)) < 0)
378 return ret;
379
380 if (s->version > 1)
381 s->lpcqoffset = V2LPCQOFFSET;
382
383 if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
384 av_log(s->avctx, AV_LOG_ERROR, "missing verbatim section at beginning of stream\n");
385 return -1;
386 }
387
388 s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
389 if (s->header_size >= OUT_BUFFER_SIZE || s->header_size < CANONICAL_HEADER_SIZE) {
390 av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n", s->header_size);
391 return -1;
392 }
393
394 for (i=0; i<s->header_size; i++)
395 s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
396
397 if (decode_wave_header(s->avctx, s->header, s->header_size) < 0)
398 return -1;
399
400 s->cur_chan = 0;
401 s->bitshift = 0;
402
403 s->got_header = 1;
404
405 return 0;
406 }
407
408 static int shorten_decode_frame(AVCodecContext *avctx, void *data,
409 int *got_frame_ptr, AVPacket *avpkt)
410 {
411 const uint8_t *buf = avpkt->data;
412 int buf_size = avpkt->size;
413 ShortenContext *s = avctx->priv_data;
414 int i, input_buf_size = 0;
415 int ret;
416
417 /* allocate internal bitstream buffer */
418 if(s->max_framesize == 0){
419 void *tmp_ptr;
420 s->max_framesize= 1024; // should hopefully be enough for the first header
421 tmp_ptr = av_fast_realloc(s->bitstream, &s->allocated_bitstream_size,
422 s->max_framesize);
423 if (!tmp_ptr) {
424 av_log(avctx, AV_LOG_ERROR, "error allocating bitstream buffer\n");
425 return AVERROR(ENOMEM);
426 }
427 s->bitstream = tmp_ptr;
428 }
429
430 /* append current packet data to bitstream buffer */
431 if(1 && s->max_framesize){//FIXME truncated
432 buf_size= FFMIN(buf_size, s->max_framesize - s->bitstream_size);
433 input_buf_size= buf_size;
434
435 if(s->bitstream_index + s->bitstream_size + buf_size > s->allocated_bitstream_size){
436 memmove(s->bitstream, &s->bitstream[s->bitstream_index], s->bitstream_size);
437 s->bitstream_index=0;
438 }
439 if (buf)
440 memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size], buf, buf_size);
441 buf= &s->bitstream[s->bitstream_index];
442 buf_size += s->bitstream_size;
443 s->bitstream_size= buf_size;
444
445 /* do not decode until buffer has at least max_framesize bytes or
446 the end of the file has been reached */
447 if (buf_size < s->max_framesize && avpkt->data) {
448 *got_frame_ptr = 0;
449 return input_buf_size;
450 }
451 }
452 /* init and position bitstream reader */
453 init_get_bits(&s->gb, buf, buf_size*8);
454 skip_bits(&s->gb, s->bitindex);
455
456 /* process header or next subblock */
457 if (!s->got_header) {
458 if ((ret = read_header(s)) < 0)
459 return ret;
460 *got_frame_ptr = 0;
461 goto finish_frame;
462 }
463
464 /* if quit command was read previously, don't decode anything */
465 if (s->got_quit_command) {
466 *got_frame_ptr = 0;
467 return avpkt->size;
468 }
469
470 s->cur_chan = 0;
471 while (s->cur_chan < s->channels) {
472 int cmd;
473 int len;
474
475 if (get_bits_left(&s->gb) < 3+FNSIZE) {
476 *got_frame_ptr = 0;
477 break;
478 }
479
480 cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
481
482 if (cmd > FN_VERBATIM) {
483 av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);
484 *got_frame_ptr = 0;
485 break;
486 }
487
488 if (!is_audio_command[cmd]) {
489 /* process non-audio command */
490 switch (cmd) {
491 case FN_VERBATIM:
492 len = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
493 while (len--) {
494 get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
495 }
496 break;
497 case FN_BITSHIFT:
498 s->bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);
499 break;
500 case FN_BLOCKSIZE: {
501 int blocksize = get_uint(s, av_log2(s->blocksize));
502 if (blocksize > s->blocksize) {
503 av_log(avctx, AV_LOG_ERROR, "Increasing block size is not supported\n");
504 return AVERROR_PATCHWELCOME;
505 }
506 if (!blocksize || blocksize > MAX_BLOCKSIZE) {
507 av_log(avctx, AV_LOG_ERROR, "invalid or unsupported "
508 "block size: %d\n", blocksize);
509 return AVERROR(EINVAL);
510 }
511 s->blocksize = blocksize;
512 break;
513 }
514 case FN_QUIT:
515 s->got_quit_command = 1;
516 break;
517 }
518 if (cmd == FN_BLOCKSIZE || cmd == FN_QUIT) {
519 *got_frame_ptr = 0;
520 break;
521 }
522 } else {
523 /* process audio command */
524 int residual_size = 0;
525 int channel = s->cur_chan;
526 int32_t coffset;
527
528 /* get Rice code for residual decoding */
529 if (cmd != FN_ZERO) {
530 residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);
531 /* this is a hack as version 0 differed in defintion of get_sr_golomb_shorten */
532 if (s->version == 0)
533 residual_size--;
534 }
535
536 /* calculate sample offset using means from previous blocks */
537 if (s->nmean == 0)
538 coffset = s->offset[channel][0];
539 else {
540 int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;
541 for (i=0; i<s->nmean; i++)
542 sum += s->offset[channel][i];
543 coffset = sum / s->nmean;
544 if (s->version >= 2)
545 coffset >>= FFMIN(1, s->bitshift);
546 }
547
548 /* decode samples for this channel */
549 if (cmd == FN_ZERO) {
550 for (i=0; i<s->blocksize; i++)
551 s->decoded[channel][i] = 0;
552 } else {
553 if ((ret = decode_subframe_lpc(s, cmd, channel, residual_size, coffset)) < 0)
554 return ret;
555 }
556
557 /* update means with info from the current block */
558 if (s->nmean > 0) {
559 int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2;
560 for (i=0; i<s->blocksize; i++)
561 sum += s->decoded[channel][i];
562
563 for (i=1; i<s->nmean; i++)
564 s->offset[channel][i-1] = s->offset[channel][i];
565
566 if (s->version < 2)
567 s->offset[channel][s->nmean - 1] = sum / s->blocksize;
568 else
569 s->offset[channel][s->nmean - 1] = (sum / s->blocksize) << s->bitshift;
570 }
571
572 /* copy wrap samples for use with next block */
573 for (i=-s->nwrap; i<0; i++)
574 s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];
575
576 /* shift samples to add in unused zero bits which were removed
577 during encoding */
578 fix_bitshift(s, s->decoded[channel]);
579
580 /* if this is the last channel in the block, output the samples */
581 s->cur_chan++;
582 if (s->cur_chan == s->channels) {
583 /* get output buffer */
584 s->frame.nb_samples = s->blocksize;
585 if ((ret = ff_get_buffer(avctx, &s->frame)) < 0) {
586 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
587 return ret;
588 }
589 /* interleave output */
590 output_buffer((int16_t **)s->frame.extended_data, s->channels,
591 s->blocksize, s->decoded);
592
593 *got_frame_ptr = 1;
594 *(AVFrame *)data = s->frame;
595 }
596 }
597 }
598 if (s->cur_chan < s->channels)
599 *got_frame_ptr = 0;
600
601 finish_frame:
602 s->bitindex = get_bits_count(&s->gb) - 8*((get_bits_count(&s->gb))/8);
603 i= (get_bits_count(&s->gb))/8;
604 if (i > buf_size) {
605 av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
606 s->bitstream_size=0;
607 s->bitstream_index=0;
608 return -1;
609 }
610 if (s->bitstream_size) {
611 s->bitstream_index += i;
612 s->bitstream_size -= i;
613 return input_buf_size;
614 } else
615 return i;
616 }
617
618 static av_cold int shorten_decode_close(AVCodecContext *avctx)
619 {
620 ShortenContext *s = avctx->priv_data;
621 int i;
622
623 for (i = 0; i < s->channels; i++) {
624 s->decoded[i] = NULL;
625 av_freep(&s->decoded_base[i]);
626 av_freep(&s->offset[i]);
627 }
628 av_freep(&s->bitstream);
629 av_freep(&s->coeffs);
630
631 return 0;
632 }
633
634 AVCodec ff_shorten_decoder = {
635 .name = "shorten",
636 .type = AVMEDIA_TYPE_AUDIO,
637 .id = AV_CODEC_ID_SHORTEN,
638 .priv_data_size = sizeof(ShortenContext),
639 .init = shorten_decode_init,
640 .close = shorten_decode_close,
641 .decode = shorten_decode_frame,
642 .capabilities = CODEC_CAP_DELAY | CODEC_CAP_DR1,
643 .long_name = NULL_IF_CONFIG_SMALL("Shorten"),
644 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
645 AV_SAMPLE_FMT_NONE },
646 };