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"
36 #define MAX_CHANNELS 8
37 #define MAX_BLOCKSIZE 65535
39 #define OUT_BUFFER_SIZE 16384
43 #define WAVE_FORMAT_PCM 0x0001
45 #define DEFAULT_BLOCK_SIZE 256
51 #define BITSHIFTSIZE 2
64 #define V2LPCQOFFSET (1 << LPCQUANT)
72 #define FN_BLOCKSIZE 5
78 /** indicates if the FN_* command is audio or non-audio */
79 static const uint8_t is_audio_command[10] = { 1, 1, 1, 1, 0, 0, 0, 1, 1, 0 };
81 #define VERBATIM_CKSIZE_SIZE 5
82 #define VERBATIM_BYTE_SIZE 8
83 #define CANONICAL_HEADER_SIZE 44
85 typedef struct ShortenContext {
86 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;
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");
132 return AVERROR_INVALIDDATA;
134 if (s->blocksize + s->nwrap >= UINT_MAX / sizeof(int32_t) ||
135 s->blocksize + s->nwrap <= (unsigned)s->nwrap) {
136 av_log(s->avctx, AV_LOG_ERROR,
137 "s->blocksize + s->nwrap too large\n");
138 return AVERROR_INVALIDDATA;
142 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);
165 static inline unsigned int get_uint(ShortenContext *s, int k)
168 k = get_ur_golomb_shorten(&s->gb, ULONGSIZE);
169 return get_ur_golomb_shorten(&s->gb, k);
172 static void fix_bitshift(ShortenContext *s, int32_t *buffer)
176 if (s->bitshift != 0)
177 for (i = 0; i < s->blocksize; i++)
178 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) {
189 s->avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
194 s->avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
197 av_log(s->avctx, AV_LOG_ERROR, "unknown audio type\n");
198 return AVERROR_PATCHWELCOME;
201 for (chan = 0; chan < s->channels; chan++)
202 for (i = 0; i < nblock; i++)
203 s->offset[chan][i] = mean;
207 static int decode_wave_header(AVCodecContext *avctx, const uint8_t *header,
214 bytestream2_init(&gb, header, header_size);
216 if (bytestream2_get_le32(&gb) != MKTAG('R', 'I', 'F', 'F')) {
217 av_log(avctx, AV_LOG_ERROR, "missing RIFF tag\n");
218 return AVERROR_INVALIDDATA;
221 bytestream2_skip(&gb, 4); /* chunk size */
223 if (bytestream2_get_le32(&gb) != MKTAG('W', 'A', 'V', 'E')) {
224 av_log(avctx, AV_LOG_ERROR, "missing WAVE tag\n");
225 return AVERROR_INVALIDDATA;
228 while (bytestream2_get_le32(&gb) != MKTAG('f', 'm', 't', ' ')) {
229 len = bytestream2_get_le32(&gb);
230 bytestream2_skip(&gb, len);
231 if (len < 0 || bytestream2_get_bytes_left(&gb) < 16) {
232 av_log(avctx, AV_LOG_ERROR, "no fmt chunk found\n");
233 return AVERROR_INVALIDDATA;
236 len = bytestream2_get_le32(&gb);
239 av_log(avctx, AV_LOG_ERROR, "fmt chunk was too short\n");
240 return AVERROR_INVALIDDATA;
243 wave_format = bytestream2_get_le16(&gb);
245 switch (wave_format) {
246 case WAVE_FORMAT_PCM:
249 av_log(avctx, AV_LOG_ERROR, "unsupported wave format\n");
250 return AVERROR(ENOSYS);
253 bytestream2_skip(&gb, 2); // skip channels (already got from shorten header)
254 avctx->sample_rate = bytestream2_get_le32(&gb);
255 bytestream2_skip(&gb, 4); // skip bit rate (represents original uncompressed bit rate)
256 bytestream2_skip(&gb, 2); // skip block align (not needed)
257 bps = bytestream2_get_le16(&gb);
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);
262 return AVERROR(ENOSYS);
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",
290 return AVERROR(EINVAL);
292 /* read LPC coefficients */
293 for (i = 0; i < pred_order; i++)
294 s->coeffs[i] = get_sr_golomb_shorten(&s->gb, LPCQUANT);
299 /* fixed LPC coeffs */
300 pred_order = command;
301 coeffs = fixed_coeffs[pred_order - 1];
305 /* subtract offset from previous samples to use in prediction */
306 if (command == FN_QLPC && coffset)
307 for (i = -pred_order; i < 0; i++)
308 s->decoded[channel][i] -= coffset;
310 /* decode residual and do LPC prediction */
311 init_sum = pred_order ? (command == FN_QLPC ? s->lpcqoffset : 0) : coffset;
312 for (i = 0; i < s->blocksize; i++) {
314 for (j = 0; j < pred_order; j++)
315 sum += coeffs[j] * s->decoded[channel][i - j - 1];
316 s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) +
320 /* add offset to current samples */
321 if (command == FN_QLPC && coffset)
322 for (i = 0; i < s->blocksize; i++)
323 s->decoded[channel][i] += coffset;
328 static int read_header(ShortenContext *s)
332 /* shorten signature */
333 if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {
334 av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
335 return AVERROR_INVALIDDATA;
339 s->blocksize = DEFAULT_BLOCK_SIZE;
341 s->version = get_bits(&s->gb, 8);
342 s->internal_ftype = get_uint(s, TYPESIZE);
344 s->channels = get_uint(s, CHANSIZE);
346 av_log(s->avctx, AV_LOG_ERROR, "No channels reported\n");
347 return AVERROR_INVALIDDATA;
349 if (s->channels > MAX_CHANNELS) {
350 av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
352 return AVERROR_INVALIDDATA;
354 s->avctx->channels = s->channels;
356 /* get blocksize if version > 0 */
357 if (s->version > 0) {
361 blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
362 if (!blocksize || blocksize > MAX_BLOCKSIZE) {
363 av_log(s->avctx, AV_LOG_ERROR,
364 "invalid or unsupported block size: %d\n",
366 return AVERROR(EINVAL);
368 s->blocksize = blocksize;
370 maxnlpc = get_uint(s, LPCQSIZE);
371 s->nmean = get_uint(s, 0);
373 skip_bytes = get_uint(s, NSKIPSIZE);
374 for (i = 0; i < skip_bytes; i++)
375 skip_bits(&s->gb, 8);
377 s->nwrap = FFMAX(NWRAP, maxnlpc);
379 if ((ret = allocate_buffers(s)) < 0)
382 if ((ret = init_offset(s)) < 0)
386 s->lpcqoffset = V2LPCQOFFSET;
388 if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
389 av_log(s->avctx, AV_LOG_ERROR,
390 "missing verbatim section at beginning of stream\n");
391 return AVERROR_INVALIDDATA;
394 s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
395 if (s->header_size >= OUT_BUFFER_SIZE ||
396 s->header_size < CANONICAL_HEADER_SIZE) {
397 av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n",
399 return AVERROR_INVALIDDATA;
402 for (i = 0; i < s->header_size; i++)
403 s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
405 if ((ret = decode_wave_header(s->avctx, s->header, s->header_size)) < 0)
416 static int shorten_decode_frame(AVCodecContext *avctx, void *data,
417 int *got_frame_ptr, AVPacket *avpkt)
419 AVFrame *frame = data;
420 const uint8_t *buf = avpkt->data;
421 int buf_size = avpkt->size;
422 ShortenContext *s = avctx->priv_data;
423 int i, input_buf_size = 0;
426 /* allocate internal bitstream buffer */
427 if (s->max_framesize == 0) {
429 s->max_framesize = 8192; // should hopefully be enough for the first header
430 tmp_ptr = av_fast_realloc(s->bitstream, &s->allocated_bitstream_size,
431 s->max_framesize + FF_INPUT_BUFFER_PADDING_SIZE);
433 av_log(avctx, AV_LOG_ERROR, "error allocating bitstream buffer\n");
434 return AVERROR(ENOMEM);
436 s->bitstream = tmp_ptr;
439 /* append current packet data to bitstream buffer */
440 if (1 && s->max_framesize) { //FIXME truncated
441 buf_size = FFMIN(buf_size, s->max_framesize - s->bitstream_size);
442 input_buf_size = buf_size;
444 if (s->bitstream_index + s->bitstream_size + buf_size + FF_INPUT_BUFFER_PADDING_SIZE >
445 s->allocated_bitstream_size) {
446 memmove(s->bitstream, &s->bitstream[s->bitstream_index],
448 s->bitstream_index = 0;
451 memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size], buf,
453 buf = &s->bitstream[s->bitstream_index];
454 buf_size += s->bitstream_size;
455 s->bitstream_size = buf_size;
457 /* do not decode until buffer has at least max_framesize bytes or
458 * the end of the file has been reached */
459 if (buf_size < s->max_framesize && avpkt->data) {
461 return input_buf_size;
464 /* init and position bitstream reader */
465 init_get_bits(&s->gb, buf, buf_size * 8);
466 skip_bits(&s->gb, s->bitindex);
468 /* process header or next subblock */
469 if (!s->got_header) {
470 if ((ret = read_header(s)) < 0)
476 /* if quit command was read previously, don't decode anything */
477 if (s->got_quit_command) {
483 while (s->cur_chan < s->channels) {
487 if (get_bits_left(&s->gb) < 3 + FNSIZE) {
492 cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
494 if (cmd > FN_VERBATIM) {
495 av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);
500 if (!is_audio_command[cmd]) {
501 /* process non-audio command */
504 len = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
506 get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
509 s->bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);
512 unsigned blocksize = get_uint(s, av_log2(s->blocksize));
513 if (blocksize > s->blocksize) {
514 av_log(avctx, AV_LOG_ERROR,
515 "Increasing block size is not supported\n");
516 return AVERROR_PATCHWELCOME;
518 if (!blocksize || blocksize > MAX_BLOCKSIZE) {
519 av_log(avctx, AV_LOG_ERROR, "invalid or unsupported "
520 "block size: %d\n", blocksize);
521 return AVERROR(EINVAL);
523 s->blocksize = blocksize;
527 s->got_quit_command = 1;
530 if (cmd == FN_BLOCKSIZE || cmd == FN_QUIT) {
535 /* process audio command */
536 int residual_size = 0;
537 int channel = s->cur_chan;
540 /* get Rice code for residual decoding */
541 if (cmd != FN_ZERO) {
542 residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);
543 /* This is a hack as version 0 differed in the definition
544 * of get_sr_golomb_shorten(). */
549 /* calculate sample offset using means from previous blocks */
551 coffset = s->offset[channel][0];
553 int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;
554 for (i = 0; i < s->nmean; i++)
555 sum += s->offset[channel][i];
556 coffset = sum / s->nmean;
558 coffset = s->bitshift == 0 ? coffset : coffset >> s->bitshift - 1 >> 1;
561 /* decode samples for this channel */
562 if (cmd == FN_ZERO) {
563 for (i = 0; i < s->blocksize; i++)
564 s->decoded[channel][i] = 0;
566 if ((ret = decode_subframe_lpc(s, cmd, channel,
567 residual_size, coffset)) < 0)
571 /* update means with info from the current block */
573 int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2;
574 for (i = 0; i < s->blocksize; i++)
575 sum += s->decoded[channel][i];
577 for (i = 1; i < s->nmean; i++)
578 s->offset[channel][i - 1] = s->offset[channel][i];
581 s->offset[channel][s->nmean - 1] = sum / s->blocksize;
583 s->offset[channel][s->nmean - 1] = (sum / s->blocksize) << s->bitshift;
586 /* copy wrap samples for use with next block */
587 for (i = -s->nwrap; i < 0; i++)
588 s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];
590 /* shift samples to add in unused zero bits which were removed
592 fix_bitshift(s, s->decoded[channel]);
594 /* if this is the last channel in the block, output the samples */
596 if (s->cur_chan == s->channels) {
598 int16_t *samples_s16;
601 /* get output buffer */
602 frame->nb_samples = s->blocksize;
603 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
606 for (chan = 0; chan < s->channels; chan++) {
607 samples_u8 = ((uint8_t **)frame->extended_data)[chan];
608 samples_s16 = ((int16_t **)frame->extended_data)[chan];
609 for (i = 0; i < s->blocksize; i++) {
610 switch (s->internal_ftype) {
612 *samples_u8++ = av_clip_uint8(s->decoded[chan][i]);
616 *samples_s16++ = av_clip_int16(s->decoded[chan][i]);
626 if (s->cur_chan < s->channels)
630 s->bitindex = get_bits_count(&s->gb) - 8 * (get_bits_count(&s->gb) / 8);
631 i = get_bits_count(&s->gb) / 8;
633 av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
634 s->bitstream_size = 0;
635 s->bitstream_index = 0;
636 return AVERROR_INVALIDDATA;
638 if (s->bitstream_size) {
639 s->bitstream_index += i;
640 s->bitstream_size -= i;
641 return input_buf_size;
646 static av_cold int shorten_decode_close(AVCodecContext *avctx)
648 ShortenContext *s = avctx->priv_data;
651 for (i = 0; i < s->channels; i++) {
652 s->decoded[i] = NULL;
653 av_freep(&s->decoded_base[i]);
654 av_freep(&s->offset[i]);
656 av_freep(&s->bitstream);
657 av_freep(&s->coeffs);
662 AVCodec ff_shorten_decoder = {
664 .type = AVMEDIA_TYPE_AUDIO,
665 .id = AV_CODEC_ID_SHORTEN,
666 .priv_data_size = sizeof(ShortenContext),
667 .init = shorten_decode_init,
668 .close = shorten_decode_close,
669 .decode = shorten_decode_frame,
670 .capabilities = CODEC_CAP_DELAY | CODEC_CAP_DR1,
671 .long_name = NULL_IF_CONFIG_SMALL("Shorten"),
672 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
674 AV_SAMPLE_FMT_NONE },