3 * Copyright (c) 2005 Jeff Muizelaar
5 * This file is part of FFmpeg.
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.
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.
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
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
63 #define V2LPCQOFFSET (1 << LPCQUANT)
71 #define FN_BLOCKSIZE 5
77 /** indicates if the FN_* command is audio or non-audio */
78 static const uint8_t is_audio_command[10] = { 1, 1, 1, 1, 0, 0, 0, 1, 1, 0 };
80 #define VERBATIM_CKSIZE_SIZE 5
81 #define VERBATIM_BYTE_SIZE 8
82 #define CANONICAL_HEADER_SIZE 44
84 typedef struct ShortenContext {
85 AVCodecContext *avctx;
89 int min_framesize, max_framesize;
92 int32_t *decoded[MAX_CHANNELS];
93 int32_t *decoded_base[MAX_CHANNELS];
94 int32_t *offset[MAX_CHANNELS];
99 unsigned int allocated_bitstream_size;
101 uint8_t header[OUT_BUFFER_SIZE];
112 int got_quit_command;
115 static av_cold int shorten_decode_init(AVCodecContext * avctx)
117 ShortenContext *s = avctx->priv_data;
120 avcodec_get_frame_defaults(&s->frame);
121 avctx->coded_frame = &s->frame;
126 static int allocate_buffers(ShortenContext *s)
132 for (chan=0; chan<s->channels; chan++) {
133 if(FFMAX(1, s->nmean) >= UINT_MAX/sizeof(int32_t)){
134 av_log(s->avctx, AV_LOG_ERROR, "nmean too large\n");
137 if(s->blocksize + s->nwrap >= UINT_MAX/sizeof(int32_t) || s->blocksize + s->nwrap <= (unsigned)s->nwrap){
138 av_log(s->avctx, AV_LOG_ERROR, "s->blocksize + s->nwrap too large\n");
142 tmp_ptr = av_realloc(s->offset[chan], sizeof(int32_t)*FFMAX(1, s->nmean));
144 return AVERROR(ENOMEM);
145 s->offset[chan] = tmp_ptr;
147 tmp_ptr = av_realloc(s->decoded_base[chan], (s->blocksize + s->nwrap) *
148 sizeof(s->decoded_base[0][0]));
150 return AVERROR(ENOMEM);
151 s->decoded_base[chan] = tmp_ptr;
152 for (i=0; i<s->nwrap; i++)
153 s->decoded_base[chan][i] = 0;
154 s->decoded[chan] = s->decoded_base[chan] + s->nwrap;
157 coeffs = av_realloc(s->coeffs, s->nwrap * sizeof(*s->coeffs));
159 return AVERROR(ENOMEM);
166 static inline unsigned int get_uint(ShortenContext *s, int k)
169 k = get_ur_golomb_shorten(&s->gb, ULONGSIZE);
170 return get_ur_golomb_shorten(&s->gb, k);
174 static void fix_bitshift(ShortenContext *s, int32_t *buffer)
178 if (s->bitshift != 0)
179 for (i = 0; i < s->blocksize; i++)
180 buffer[i] <<= s->bitshift;
184 static int init_offset(ShortenContext *s)
188 int nblock = FFMAX(1, s->nmean);
189 /* initialise offset */
190 switch (s->internal_ftype)
193 s->avctx->sample_fmt = AV_SAMPLE_FMT_U8;
198 s->avctx->sample_fmt = AV_SAMPLE_FMT_S16;
201 av_log(s->avctx, AV_LOG_ERROR, "unknown audio type\n");
202 return AVERROR_INVALIDDATA;
205 for (chan = 0; chan < s->channels; chan++)
206 for (i = 0; i < nblock; i++)
207 s->offset[chan][i] = mean;
211 static int decode_wave_header(AVCodecContext *avctx, const uint8_t *header,
216 const uint8_t *end= header + header_size;
218 if (bytestream_get_le32(&header) != MKTAG('R','I','F','F')) {
219 av_log(avctx, AV_LOG_ERROR, "missing RIFF tag\n");
223 header += 4; /* chunk size */;
225 if (bytestream_get_le32(&header) != MKTAG('W','A','V','E')) {
226 av_log(avctx, AV_LOG_ERROR, "missing WAVE tag\n");
230 while (bytestream_get_le32(&header) != MKTAG('f','m','t',' ')) {
231 len = bytestream_get_le32(&header);
232 if(len<0 || end - header - 8 < len)
233 return AVERROR_INVALIDDATA;
236 len = bytestream_get_le32(&header);
239 av_log(avctx, AV_LOG_ERROR, "fmt chunk was too short\n");
243 wave_format = bytestream_get_le16(&header);
245 switch (wave_format) {
246 case WAVE_FORMAT_PCM:
249 av_log(avctx, AV_LOG_ERROR, "unsupported wave format\n");
253 header += 2; // skip channels (already got from shorten header)
254 avctx->sample_rate = bytestream_get_le32(&header);
255 header += 4; // skip bit rate (represents original uncompressed bit rate)
256 header += 2; // skip block align (not needed)
257 bps = bytestream_get_le16(&header);
258 avctx->bits_per_coded_sample = bps;
260 if (bps != 16 && bps != 8) {
261 av_log(avctx, AV_LOG_ERROR, "unsupported number of bits per sample: %d\n", bps);
267 av_log(avctx, AV_LOG_INFO, "%d header bytes unparsed\n", len);
272 static const int fixed_coeffs[3][3] = {
278 static int decode_subframe_lpc(ShortenContext *s, int command, int channel,
279 int residual_size, int32_t coffset)
281 int pred_order, sum, qshift, init_sum, i, j;
284 if (command == FN_QLPC) {
285 /* read/validate prediction order */
286 pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
287 if (pred_order > s->nwrap) {
288 av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n", pred_order);
289 return AVERROR(EINVAL);
291 /* read LPC coefficients */
292 for (i=0; i<pred_order; i++)
293 s->coeffs[i] = get_sr_golomb_shorten(&s->gb, LPCQUANT);
298 /* fixed LPC coeffs */
299 pred_order = command;
300 coeffs = fixed_coeffs[pred_order-1];
304 /* subtract offset from previous samples to use in prediction */
305 if (command == FN_QLPC && coffset)
306 for (i = -pred_order; i < 0; i++)
307 s->decoded[channel][i] -= coffset;
309 /* decode residual and do LPC prediction */
310 init_sum = pred_order ? (command == FN_QLPC ? s->lpcqoffset : 0) : coffset;
311 for (i=0; i < s->blocksize; i++) {
313 for (j=0; j<pred_order; j++)
314 sum += coeffs[j] * s->decoded[channel][i-j-1];
315 s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + (sum >> qshift);
318 /* add offset to current samples */
319 if (command == FN_QLPC && coffset)
320 for (i = 0; i < s->blocksize; i++)
321 s->decoded[channel][i] += coffset;
326 static int read_header(ShortenContext *s)
330 /* shorten signature */
331 if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {
332 av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
337 s->blocksize = DEFAULT_BLOCK_SIZE;
339 s->version = get_bits(&s->gb, 8);
340 s->internal_ftype = get_uint(s, TYPESIZE);
342 s->channels = get_uint(s, CHANSIZE);
343 if (s->channels > MAX_CHANNELS) {
344 av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
347 s->avctx->channels = s->channels;
349 /* get blocksize if version > 0 */
350 if (s->version > 0) {
351 int skip_bytes, blocksize;
353 blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
354 if (!blocksize || blocksize > MAX_BLOCKSIZE) {
355 av_log(s->avctx, AV_LOG_ERROR, "invalid or unsupported block size: %d\n",
357 return AVERROR(EINVAL);
359 s->blocksize = blocksize;
361 maxnlpc = get_uint(s, LPCQSIZE);
362 s->nmean = get_uint(s, 0);
364 skip_bytes = get_uint(s, NSKIPSIZE);
365 for (i=0; i<skip_bytes; i++) {
366 skip_bits(&s->gb, 8);
369 s->nwrap = FFMAX(NWRAP, maxnlpc);
371 if ((ret = allocate_buffers(s)) < 0)
374 if ((ret = init_offset(s)) < 0)
378 s->lpcqoffset = V2LPCQOFFSET;
380 if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
381 av_log(s->avctx, AV_LOG_ERROR, "missing verbatim section at beginning of stream\n");
385 s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
386 if (s->header_size >= OUT_BUFFER_SIZE || s->header_size < CANONICAL_HEADER_SIZE) {
387 av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n", s->header_size);
391 for (i=0; i<s->header_size; i++)
392 s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
394 if (decode_wave_header(s->avctx, s->header, s->header_size) < 0)
405 static int shorten_decode_frame(AVCodecContext *avctx, void *data,
406 int *got_frame_ptr, AVPacket *avpkt)
408 const uint8_t *buf = avpkt->data;
409 int buf_size = avpkt->size;
410 ShortenContext *s = avctx->priv_data;
411 int i, input_buf_size = 0;
414 /* allocate internal bitstream buffer */
415 if(s->max_framesize == 0){
417 s->max_framesize= 8192; // should hopefully be enough for the first header
418 tmp_ptr = av_fast_realloc(s->bitstream, &s->allocated_bitstream_size,
421 av_log(avctx, AV_LOG_ERROR, "error allocating bitstream buffer\n");
422 return AVERROR(ENOMEM);
424 s->bitstream = tmp_ptr;
427 /* append current packet data to bitstream buffer */
428 if(1 && s->max_framesize){//FIXME truncated
429 buf_size= FFMIN(buf_size, s->max_framesize - s->bitstream_size);
430 input_buf_size= buf_size;
432 if(s->bitstream_index + s->bitstream_size + buf_size > s->allocated_bitstream_size){
433 memmove(s->bitstream, &s->bitstream[s->bitstream_index], s->bitstream_size);
434 s->bitstream_index=0;
437 memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size], buf, buf_size);
438 buf= &s->bitstream[s->bitstream_index];
439 buf_size += s->bitstream_size;
440 s->bitstream_size= buf_size;
442 /* do not decode until buffer has at least max_framesize bytes or
443 the end of the file has been reached */
444 if (buf_size < s->max_framesize && avpkt->data) {
446 return input_buf_size;
449 /* init and position bitstream reader */
450 init_get_bits(&s->gb, buf, buf_size*8);
451 skip_bits(&s->gb, s->bitindex);
453 /* process header or next subblock */
454 if (!s->got_header) {
455 if ((ret = read_header(s)) < 0)
461 /* if quit command was read previously, don't decode anything */
462 if (s->got_quit_command) {
468 while (s->cur_chan < s->channels) {
472 if (get_bits_left(&s->gb) < 3+FNSIZE) {
477 cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
479 if (cmd > FN_VERBATIM) {
480 av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);
485 if (!is_audio_command[cmd]) {
486 /* process non-audio command */
489 len = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
491 get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
495 s->bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);
498 int blocksize = get_uint(s, av_log2(s->blocksize));
499 if (blocksize > s->blocksize) {
500 av_log(avctx, AV_LOG_ERROR, "Increasing block size is not supported\n");
501 return AVERROR_PATCHWELCOME;
503 if (!blocksize || blocksize > MAX_BLOCKSIZE) {
504 av_log(avctx, AV_LOG_ERROR, "invalid or unsupported "
505 "block size: %d\n", blocksize);
506 return AVERROR(EINVAL);
508 s->blocksize = blocksize;
512 s->got_quit_command = 1;
515 if (cmd == FN_BLOCKSIZE || cmd == FN_QUIT) {
520 /* process audio command */
521 int residual_size = 0;
522 int channel = s->cur_chan;
525 /* get Rice code for residual decoding */
526 if (cmd != FN_ZERO) {
527 residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);
528 /* this is a hack as version 0 differed in definition of get_sr_golomb_shorten */
533 /* calculate sample offset using means from previous blocks */
535 coffset = s->offset[channel][0];
537 int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;
538 for (i=0; i<s->nmean; i++)
539 sum += s->offset[channel][i];
540 coffset = sum / s->nmean;
542 coffset = s->bitshift == 0 ? coffset : coffset >> s->bitshift - 1 >> 1;
545 /* decode samples for this channel */
546 if (cmd == FN_ZERO) {
547 for (i=0; i<s->blocksize; i++)
548 s->decoded[channel][i] = 0;
550 if ((ret = decode_subframe_lpc(s, cmd, channel, residual_size, coffset)) < 0)
554 /* update means with info from the current block */
556 int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2;
557 for (i=0; i<s->blocksize; i++)
558 sum += s->decoded[channel][i];
560 for (i=1; i<s->nmean; i++)
561 s->offset[channel][i-1] = s->offset[channel][i];
564 s->offset[channel][s->nmean - 1] = sum / s->blocksize;
566 s->offset[channel][s->nmean - 1] = (sum / s->blocksize) << s->bitshift;
569 /* copy wrap samples for use with next block */
570 for (i=-s->nwrap; i<0; i++)
571 s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];
573 /* shift samples to add in unused zero bits which were removed
575 fix_bitshift(s, s->decoded[channel]);
577 /* if this is the last channel in the block, output the samples */
579 if (s->cur_chan == s->channels) {
581 int16_t *samples_s16;
584 /* get output buffer */
585 s->frame.nb_samples = s->blocksize;
586 if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
587 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
590 samples_u8 = (uint8_t *)s->frame.data[0];
591 samples_s16 = (int16_t *)s->frame.data[0];
592 /* interleave output */
593 for (i = 0; i < s->blocksize; i++) {
594 for (chan = 0; chan < s->channels; chan++) {
595 switch (s->internal_ftype) {
597 *samples_u8++ = av_clip_uint8(s->decoded[chan][i]);
601 *samples_s16++ = av_clip_int16(s->decoded[chan][i]);
608 *(AVFrame *)data = s->frame;
612 if (s->cur_chan < s->channels)
616 s->bitindex = get_bits_count(&s->gb) - 8*((get_bits_count(&s->gb))/8);
617 i= (get_bits_count(&s->gb))/8;
619 av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
621 s->bitstream_index=0;
624 if (s->bitstream_size) {
625 s->bitstream_index += i;
626 s->bitstream_size -= i;
627 return input_buf_size;
632 static av_cold int shorten_decode_close(AVCodecContext *avctx)
634 ShortenContext *s = avctx->priv_data;
637 for (i = 0; i < s->channels; i++) {
638 s->decoded[i] = NULL;
639 av_freep(&s->decoded_base[i]);
640 av_freep(&s->offset[i]);
642 av_freep(&s->bitstream);
643 av_freep(&s->coeffs);
648 AVCodec ff_shorten_decoder = {
650 .type = AVMEDIA_TYPE_AUDIO,
651 .id = CODEC_ID_SHORTEN,
652 .priv_data_size = sizeof(ShortenContext),
653 .init = shorten_decode_init,
654 .close = shorten_decode_close,
655 .decode = shorten_decode_frame,
656 .capabilities = CODEC_CAP_DELAY | CODEC_CAP_DR1,
657 .long_name = NULL_IF_CONFIG_SMALL("Shorten"),