3 * Copyright (c) 2005 Jeff Muizelaar
5 * This file is part of Libav.
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.
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.
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
25 * @author Jeff Muizelaar
31 #include "bytestream.h"
35 #define MAX_CHANNELS 8
36 #define MAX_BLOCKSIZE 65535
38 #define OUT_BUFFER_SIZE 16384
42 #define WAVE_FORMAT_PCM 0x0001
44 #define DEFAULT_BLOCK_SIZE 256
50 #define BITSHIFTSIZE 2
59 #define V2LPCQOFFSET (1 << LPCQUANT)
67 #define FN_BLOCKSIZE 5
73 /** indicates if the FN_* command is audio or non-audio */
74 static const uint8_t is_audio_command[10] = { 1, 1, 1, 1, 0, 0, 0, 1, 1, 0 };
76 #define VERBATIM_CKSIZE_SIZE 5
77 #define VERBATIM_BYTE_SIZE 8
78 #define CANONICAL_HEADER_SIZE 44
80 typedef struct ShortenContext {
81 AVCodecContext *avctx;
85 int min_framesize, max_framesize;
88 int32_t *decoded[MAX_CHANNELS];
89 int32_t *decoded_base[MAX_CHANNELS];
90 int32_t *offset[MAX_CHANNELS];
95 unsigned int allocated_bitstream_size;
97 uint8_t header[OUT_BUFFER_SIZE];
108 int got_quit_command;
111 static av_cold int shorten_decode_init(AVCodecContext * avctx)
113 ShortenContext *s = avctx->priv_data;
115 avctx->sample_fmt = AV_SAMPLE_FMT_S16;
117 avcodec_get_frame_defaults(&s->frame);
118 avctx->coded_frame = &s->frame;
123 static int allocate_buffers(ShortenContext *s)
129 for (chan=0; chan<s->channels; chan++) {
130 if(FFMAX(1, s->nmean) >= UINT_MAX/sizeof(int32_t)){
131 av_log(s->avctx, AV_LOG_ERROR, "nmean too large\n");
134 if(s->blocksize + s->nwrap >= UINT_MAX/sizeof(int32_t) || s->blocksize + s->nwrap <= (unsigned)s->nwrap){
135 av_log(s->avctx, AV_LOG_ERROR, "s->blocksize + s->nwrap too large\n");
139 tmp_ptr = av_realloc(s->offset[chan], sizeof(int32_t)*FFMAX(1, s->nmean));
141 return AVERROR(ENOMEM);
142 s->offset[chan] = tmp_ptr;
144 tmp_ptr = av_realloc(s->decoded_base[chan], (s->blocksize + s->nwrap) *
145 sizeof(s->decoded_base[0][0]));
147 return AVERROR(ENOMEM);
148 s->decoded_base[chan] = tmp_ptr;
149 for (i=0; i<s->nwrap; i++)
150 s->decoded_base[chan][i] = 0;
151 s->decoded[chan] = s->decoded_base[chan] + s->nwrap;
154 coeffs = av_realloc(s->coeffs, s->nwrap * sizeof(*s->coeffs));
156 return AVERROR(ENOMEM);
163 static inline unsigned int get_uint(ShortenContext *s, int k)
166 k = get_ur_golomb_shorten(&s->gb, ULONGSIZE);
167 return get_ur_golomb_shorten(&s->gb, k);
171 static void fix_bitshift(ShortenContext *s, int32_t *buffer)
175 if (s->bitshift != 0)
176 for (i = 0; i < s->blocksize; i++)
177 buffer[i] <<= s->bitshift;
181 static int init_offset(ShortenContext *s)
185 int nblock = FFMAX(1, s->nmean);
186 /* initialise offset */
187 switch (s->internal_ftype)
194 av_log(s->avctx, AV_LOG_ERROR, "unknown audio type");
195 return AVERROR_INVALIDDATA;
198 for (chan = 0; chan < s->channels; chan++)
199 for (i = 0; i < nblock; i++)
200 s->offset[chan][i] = mean;
204 static int decode_wave_header(AVCodecContext *avctx, const uint8_t *header,
211 if (bytestream_get_le32(&header) != MKTAG('R','I','F','F')) {
212 av_log(avctx, AV_LOG_ERROR, "missing RIFF tag\n");
216 header += 4; /* chunk size */;
218 if (bytestream_get_le32(&header) != MKTAG('W','A','V','E')) {
219 av_log(avctx, AV_LOG_ERROR, "missing WAVE tag\n");
223 while (bytestream_get_le32(&header) != MKTAG('f','m','t',' ')) {
224 len = bytestream_get_le32(&header);
227 len = bytestream_get_le32(&header);
230 av_log(avctx, AV_LOG_ERROR, "fmt chunk was too short\n");
234 wave_format = bytestream_get_le16(&header);
236 switch (wave_format) {
237 case WAVE_FORMAT_PCM:
240 av_log(avctx, AV_LOG_ERROR, "unsupported wave format\n");
244 header += 2; // skip channels (already got from shorten header)
245 avctx->sample_rate = bytestream_get_le32(&header);
246 header += 4; // skip bit rate (represents original uncompressed bit rate)
247 header += 2; // skip block align (not needed)
248 avctx->bits_per_coded_sample = bytestream_get_le16(&header);
250 if (avctx->bits_per_coded_sample != 16) {
251 av_log(avctx, AV_LOG_ERROR, "unsupported number of bits per sample\n");
257 av_log(avctx, AV_LOG_INFO, "%d header bytes unparsed\n", len);
262 static void interleave_buffer(int16_t *samples, int nchan, int blocksize,
266 for (i=0; i<blocksize; i++)
267 for (chan=0; chan < nchan; chan++)
268 *samples++ = av_clip_int16(buffer[chan][i]);
271 static const int fixed_coeffs[3][3] = {
277 static int decode_subframe_lpc(ShortenContext *s, int command, int channel,
278 int residual_size, int32_t coffset)
280 int pred_order, sum, qshift, init_sum, i, j;
283 if (command == FN_QLPC) {
284 /* read/validate prediction order */
285 pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
286 if (pred_order > s->nwrap) {
287 av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n", pred_order);
288 return AVERROR(EINVAL);
290 /* read LPC coefficients */
291 for (i=0; i<pred_order; i++)
292 s->coeffs[i] = get_sr_golomb_shorten(&s->gb, LPCQUANT);
297 /* fixed LPC coeffs */
298 pred_order = command;
299 coeffs = fixed_coeffs[pred_order-1];
303 /* subtract offset from previous samples to use in prediction */
304 if (command == FN_QLPC && coffset)
305 for (i = -pred_order; i < 0; i++)
306 s->decoded[channel][i] -= coffset;
308 /* decode residual and do LPC prediction */
309 init_sum = pred_order ? (command == FN_QLPC ? s->lpcqoffset : 0) : coffset;
310 for (i=0; i < s->blocksize; i++) {
312 for (j=0; j<pred_order; j++)
313 sum += coeffs[j] * s->decoded[channel][i-j-1];
314 s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + (sum >> qshift);
317 /* add offset to current samples */
318 if (command == FN_QLPC && coffset)
319 for (i = 0; i < s->blocksize; i++)
320 s->decoded[channel][i] += coffset;
325 static int read_header(ShortenContext *s)
329 /* shorten signature */
330 if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {
331 av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
336 s->blocksize = DEFAULT_BLOCK_SIZE;
338 s->version = get_bits(&s->gb, 8);
339 s->internal_ftype = get_uint(s, TYPESIZE);
341 s->channels = get_uint(s, CHANSIZE);
342 if (s->channels > MAX_CHANNELS) {
343 av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
346 s->avctx->channels = s->channels;
348 /* get blocksize if version > 0 */
349 if (s->version > 0) {
350 int skip_bytes, blocksize;
352 blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
353 if (!blocksize || blocksize > MAX_BLOCKSIZE) {
354 av_log(s->avctx, AV_LOG_ERROR, "invalid or unsupported block size: %d\n",
356 return AVERROR(EINVAL);
358 s->blocksize = blocksize;
360 maxnlpc = get_uint(s, LPCQSIZE);
361 s->nmean = get_uint(s, 0);
363 skip_bytes = get_uint(s, NSKIPSIZE);
364 for (i=0; i<skip_bytes; i++) {
365 skip_bits(&s->gb, 8);
368 s->nwrap = FFMAX(NWRAP, maxnlpc);
370 if ((ret = allocate_buffers(s)) < 0)
373 if ((ret = init_offset(s)) < 0)
377 s->lpcqoffset = V2LPCQOFFSET;
379 if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
380 av_log(s->avctx, AV_LOG_ERROR, "missing verbatim section at beginning of stream\n");
384 s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
385 if (s->header_size >= OUT_BUFFER_SIZE || s->header_size < CANONICAL_HEADER_SIZE) {
386 av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n", s->header_size);
390 for (i=0; i<s->header_size; i++)
391 s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
393 if (decode_wave_header(s->avctx, s->header, s->header_size) < 0)
404 static int shorten_decode_frame(AVCodecContext *avctx, void *data,
405 int *got_frame_ptr, AVPacket *avpkt)
407 const uint8_t *buf = avpkt->data;
408 int buf_size = avpkt->size;
409 ShortenContext *s = avctx->priv_data;
410 int i, input_buf_size = 0;
413 /* allocate internal bitstream buffer */
414 if(s->max_framesize == 0){
416 s->max_framesize= 1024; // should hopefully be enough for the first header
417 tmp_ptr = av_fast_realloc(s->bitstream, &s->allocated_bitstream_size,
420 av_log(avctx, AV_LOG_ERROR, "error allocating bitstream buffer\n");
421 return AVERROR(ENOMEM);
423 s->bitstream = tmp_ptr;
426 /* append current packet data to bitstream buffer */
427 if(1 && s->max_framesize){//FIXME truncated
428 buf_size= FFMIN(buf_size, s->max_framesize - s->bitstream_size);
429 input_buf_size= buf_size;
431 if(s->bitstream_index + s->bitstream_size + buf_size > s->allocated_bitstream_size){
432 memmove(s->bitstream, &s->bitstream[s->bitstream_index], s->bitstream_size);
433 s->bitstream_index=0;
436 memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size], buf, buf_size);
437 buf= &s->bitstream[s->bitstream_index];
438 buf_size += s->bitstream_size;
439 s->bitstream_size= buf_size;
441 /* do not decode until buffer has at least max_framesize bytes or
442 the end of the file has been reached */
443 if (buf_size < s->max_framesize && avpkt->data) {
445 return input_buf_size;
448 /* init and position bitstream reader */
449 init_get_bits(&s->gb, buf, buf_size*8);
450 skip_bits(&s->gb, s->bitindex);
452 /* process header or next subblock */
453 if (!s->got_header) {
454 if ((ret = read_header(s)) < 0)
460 /* if quit command was read previously, don't decode anything */
461 if (s->got_quit_command) {
467 while (s->cur_chan < s->channels) {
471 if (get_bits_left(&s->gb) < 3+FNSIZE) {
476 cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
478 if (cmd > FN_VERBATIM) {
479 av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);
484 if (!is_audio_command[cmd]) {
485 /* process non-audio command */
488 len = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
490 get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
494 s->bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);
497 int blocksize = get_uint(s, av_log2(s->blocksize));
498 if (blocksize > s->blocksize) {
499 av_log(avctx, AV_LOG_ERROR, "Increasing block size is not supported\n");
500 return AVERROR_PATCHWELCOME;
502 if (!blocksize || blocksize > MAX_BLOCKSIZE) {
503 av_log(avctx, AV_LOG_ERROR, "invalid or unsupported "
504 "block size: %d\n", blocksize);
505 return AVERROR(EINVAL);
507 s->blocksize = blocksize;
511 s->got_quit_command = 1;
514 if (cmd == FN_BLOCKSIZE || cmd == FN_QUIT) {
519 /* process audio command */
520 int residual_size = 0;
521 int channel = s->cur_chan;
524 /* get Rice code for residual decoding */
525 if (cmd != FN_ZERO) {
526 residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);
527 /* this is a hack as version 0 differed in defintion of get_sr_golomb_shorten */
532 /* calculate sample offset using means from previous blocks */
534 coffset = s->offset[channel][0];
536 int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;
537 for (i=0; i<s->nmean; i++)
538 sum += s->offset[channel][i];
539 coffset = sum / s->nmean;
541 coffset >>= FFMIN(1, s->bitshift);
544 /* decode samples for this channel */
545 if (cmd == FN_ZERO) {
546 for (i=0; i<s->blocksize; i++)
547 s->decoded[channel][i] = 0;
549 if ((ret = decode_subframe_lpc(s, cmd, channel, residual_size, coffset)) < 0)
553 /* update means with info from the current block */
555 int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2;
556 for (i=0; i<s->blocksize; i++)
557 sum += s->decoded[channel][i];
559 for (i=1; i<s->nmean; i++)
560 s->offset[channel][i-1] = s->offset[channel][i];
563 s->offset[channel][s->nmean - 1] = sum / s->blocksize;
565 s->offset[channel][s->nmean - 1] = (sum / s->blocksize) << s->bitshift;
568 /* copy wrap samples for use with next block */
569 for (i=-s->nwrap; i<0; i++)
570 s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];
572 /* shift samples to add in unused zero bits which were removed
574 fix_bitshift(s, s->decoded[channel]);
576 /* if this is the last channel in the block, output the samples */
578 if (s->cur_chan == s->channels) {
579 /* get output buffer */
580 s->frame.nb_samples = s->blocksize;
581 if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
582 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
585 /* interleave output */
586 interleave_buffer((int16_t *)s->frame.data[0], s->channels,
587 s->blocksize, s->decoded);
590 *(AVFrame *)data = s->frame;
594 if (s->cur_chan < s->channels)
598 s->bitindex = get_bits_count(&s->gb) - 8*((get_bits_count(&s->gb))/8);
599 i= (get_bits_count(&s->gb))/8;
601 av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
603 s->bitstream_index=0;
606 if (s->bitstream_size) {
607 s->bitstream_index += i;
608 s->bitstream_size -= i;
609 return input_buf_size;
614 static av_cold int shorten_decode_close(AVCodecContext *avctx)
616 ShortenContext *s = avctx->priv_data;
619 for (i = 0; i < s->channels; i++) {
620 s->decoded[i] = NULL;
621 av_freep(&s->decoded_base[i]);
622 av_freep(&s->offset[i]);
624 av_freep(&s->bitstream);
625 av_freep(&s->coeffs);
630 AVCodec ff_shorten_decoder = {
632 .type = AVMEDIA_TYPE_AUDIO,
633 .id = CODEC_ID_SHORTEN,
634 .priv_data_size = sizeof(ShortenContext),
635 .init = shorten_decode_init,
636 .close = shorten_decode_close,
637 .decode = shorten_decode_frame,
638 .capabilities = CODEC_CAP_DELAY | CODEC_CAP_DR1,
639 .long_name = NULL_IF_CONFIG_SMALL("Shorten"),