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
30 #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;
84 int min_framesize, max_framesize;
87 int32_t *decoded[MAX_CHANNELS];
88 int32_t *decoded_base[MAX_CHANNELS];
89 int32_t *offset[MAX_CHANNELS];
94 unsigned int allocated_bitstream_size;
96 uint8_t header[OUT_BUFFER_SIZE];
107 int got_quit_command;
110 static av_cold int shorten_decode_init(AVCodecContext *avctx)
112 ShortenContext *s = avctx->priv_data;
114 avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
119 static int allocate_buffers(ShortenContext *s)
123 for (chan = 0; chan < s->channels; chan++) {
124 if (FFMAX(1, s->nmean) >= UINT_MAX / sizeof(int32_t)) {
125 av_log(s->avctx, AV_LOG_ERROR, "nmean too large\n");
126 return AVERROR_INVALIDDATA;
128 if (s->blocksize + s->nwrap >= UINT_MAX / sizeof(int32_t) ||
129 s->blocksize + s->nwrap <= (unsigned)s->nwrap) {
130 av_log(s->avctx, AV_LOG_ERROR,
131 "s->blocksize + s->nwrap too large\n");
132 return AVERROR_INVALIDDATA;
135 if ((err = av_reallocp(&s->offset[chan],
137 FFMAX(1, s->nmean))) < 0)
140 if ((err = av_reallocp(&s->decoded_base[chan], (s->blocksize + s->nwrap) *
141 sizeof(s->decoded_base[0][0]))) < 0)
143 for (i = 0; i < s->nwrap; i++)
144 s->decoded_base[chan][i] = 0;
145 s->decoded[chan] = s->decoded_base[chan] + s->nwrap;
148 if ((err = av_reallocp(&s->coeffs, s->nwrap * sizeof(*s->coeffs))) < 0)
154 static inline unsigned int get_uint(ShortenContext *s, int k)
157 k = get_ur_golomb_shorten(&s->gb, ULONGSIZE);
158 return get_ur_golomb_shorten(&s->gb, k);
161 static void fix_bitshift(ShortenContext *s, int32_t *buffer)
165 if (s->bitshift != 0)
166 for (i = 0; i < s->blocksize; i++)
167 buffer[i] <<= s->bitshift;
170 static int init_offset(ShortenContext *s)
174 int nblock = FFMAX(1, s->nmean);
175 /* initialise offset */
176 switch (s->internal_ftype) {
182 av_log(s->avctx, AV_LOG_ERROR, "unknown audio type");
183 return AVERROR_INVALIDDATA;
186 for (chan = 0; chan < s->channels; chan++)
187 for (i = 0; i < nblock; i++)
188 s->offset[chan][i] = mean;
192 static int decode_wave_header(AVCodecContext *avctx, const uint8_t *header,
199 bytestream2_init(&gb, header, header_size);
201 if (bytestream2_get_le32(&gb) != MKTAG('R', 'I', 'F', 'F')) {
202 av_log(avctx, AV_LOG_ERROR, "missing RIFF tag\n");
203 return AVERROR_INVALIDDATA;
206 bytestream2_skip(&gb, 4); /* chunk size */
208 if (bytestream2_get_le32(&gb) != MKTAG('W', 'A', 'V', 'E')) {
209 av_log(avctx, AV_LOG_ERROR, "missing WAVE tag\n");
210 return AVERROR_INVALIDDATA;
213 while (bytestream2_get_le32(&gb) != MKTAG('f', 'm', 't', ' ')) {
214 len = bytestream2_get_le32(&gb);
215 bytestream2_skip(&gb, len);
216 if (bytestream2_get_bytes_left(&gb) < 16) {
217 av_log(avctx, AV_LOG_ERROR, "no fmt chunk found\n");
218 return AVERROR_INVALIDDATA;
221 len = bytestream2_get_le32(&gb);
224 av_log(avctx, AV_LOG_ERROR, "fmt chunk was too short\n");
225 return AVERROR_INVALIDDATA;
228 wave_format = bytestream2_get_le16(&gb);
230 switch (wave_format) {
231 case WAVE_FORMAT_PCM:
234 av_log(avctx, AV_LOG_ERROR, "unsupported wave format\n");
235 return AVERROR(ENOSYS);
238 bytestream2_skip(&gb, 2); // skip channels (already got from shorten header)
239 avctx->sample_rate = bytestream2_get_le32(&gb);
240 bytestream2_skip(&gb, 4); // skip bit rate (represents original uncompressed bit rate)
241 bytestream2_skip(&gb, 2); // skip block align (not needed)
242 avctx->bits_per_coded_sample = bytestream2_get_le16(&gb);
244 if (avctx->bits_per_coded_sample != 16) {
245 av_log(avctx, AV_LOG_ERROR, "unsupported number of bits per sample\n");
246 return AVERROR(ENOSYS);
251 av_log(avctx, AV_LOG_INFO, "%d header bytes unparsed\n", len);
256 static void output_buffer(int16_t **samples, int nchan, int blocksize,
260 for (ch = 0; ch < nchan; ch++) {
261 int32_t *in = buffer[ch];
262 int16_t *out = samples[ch];
263 for (i = 0; i < blocksize; i++)
264 out[i] = av_clip_int16(in[i]);
268 static const int fixed_coeffs[][3] = {
275 static int decode_subframe_lpc(ShortenContext *s, int command, int channel,
276 int residual_size, int32_t coffset)
278 int pred_order, sum, qshift, init_sum, i, j;
281 if (command == FN_QLPC) {
282 /* read/validate prediction order */
283 pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
284 if (pred_order > s->nwrap) {
285 av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n",
287 return AVERROR(EINVAL);
289 /* read LPC coefficients */
290 for (i = 0; i < pred_order; i++)
291 s->coeffs[i] = get_sr_golomb_shorten(&s->gb, LPCQUANT);
296 /* fixed LPC coeffs */
297 pred_order = command;
298 if (pred_order >= FF_ARRAY_ELEMS(fixed_coeffs)) {
299 av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n",
301 return AVERROR_INVALIDDATA;
303 coeffs = fixed_coeffs[pred_order];
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;
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++) {
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) +
322 /* add offset to current samples */
323 if (command == FN_QLPC && coffset)
324 for (i = 0; i < s->blocksize; i++)
325 s->decoded[channel][i] += coffset;
330 static int read_header(ShortenContext *s)
334 /* shorten signature */
335 if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {
336 av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
337 return AVERROR_INVALIDDATA;
341 s->blocksize = DEFAULT_BLOCK_SIZE;
343 s->version = get_bits(&s->gb, 8);
344 s->internal_ftype = get_uint(s, TYPESIZE);
346 s->channels = get_uint(s, CHANSIZE);
348 av_log(s->avctx, AV_LOG_ERROR, "No channels reported\n");
349 return AVERROR_INVALIDDATA;
351 if (s->channels > MAX_CHANNELS) {
352 av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
354 return AVERROR_INVALIDDATA;
356 s->avctx->channels = s->channels;
358 /* get blocksize if version > 0 */
359 if (s->version > 0) {
363 blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
364 if (!blocksize || blocksize > MAX_BLOCKSIZE) {
365 av_log(s->avctx, AV_LOG_ERROR,
366 "invalid or unsupported block size: %d\n",
368 return AVERROR(EINVAL);
370 s->blocksize = blocksize;
372 maxnlpc = get_uint(s, LPCQSIZE);
373 s->nmean = get_uint(s, 0);
375 skip_bytes = get_uint(s, NSKIPSIZE);
376 for (i = 0; i < skip_bytes; i++)
377 skip_bits(&s->gb, 8);
379 s->nwrap = FFMAX(NWRAP, maxnlpc);
381 if ((ret = allocate_buffers(s)) < 0)
384 if ((ret = init_offset(s)) < 0)
388 s->lpcqoffset = V2LPCQOFFSET;
390 if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
391 av_log(s->avctx, AV_LOG_ERROR,
392 "missing verbatim section at beginning of stream\n");
393 return AVERROR_INVALIDDATA;
396 s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
397 if (s->header_size >= OUT_BUFFER_SIZE ||
398 s->header_size < CANONICAL_HEADER_SIZE) {
399 av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n",
401 return AVERROR_INVALIDDATA;
404 for (i = 0; i < s->header_size; i++)
405 s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
407 if ((ret = decode_wave_header(s->avctx, s->header, s->header_size)) < 0)
418 static int shorten_decode_frame(AVCodecContext *avctx, void *data,
419 int *got_frame_ptr, AVPacket *avpkt)
421 AVFrame *frame = data;
422 const uint8_t *buf = avpkt->data;
423 int buf_size = avpkt->size;
424 ShortenContext *s = avctx->priv_data;
425 int i, input_buf_size = 0;
428 /* allocate internal bitstream buffer */
429 if (s->max_framesize == 0) {
431 s->max_framesize = 1024; // should hopefully be enough for the first header
432 tmp_ptr = av_fast_realloc(s->bitstream, &s->allocated_bitstream_size,
433 s->max_framesize + AV_INPUT_BUFFER_PADDING_SIZE);
435 av_log(avctx, AV_LOG_ERROR, "error allocating bitstream buffer\n");
436 return AVERROR(ENOMEM);
438 s->bitstream = tmp_ptr;
441 /* append current packet data to bitstream buffer */
442 if (1 && s->max_framesize) { //FIXME truncated
443 buf_size = FFMIN(buf_size, s->max_framesize - s->bitstream_size);
444 input_buf_size = buf_size;
446 if (s->bitstream_index + s->bitstream_size + buf_size >
447 s->allocated_bitstream_size) {
448 memmove(s->bitstream, &s->bitstream[s->bitstream_index],
450 s->bitstream_index = 0;
453 memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size], buf,
455 buf = &s->bitstream[s->bitstream_index];
456 buf_size += s->bitstream_size;
457 s->bitstream_size = buf_size;
459 /* do not decode until buffer has at least max_framesize bytes or
460 * the end of the file has been reached */
461 if (buf_size < s->max_framesize && avpkt->data) {
463 return input_buf_size;
466 /* init and position bitstream reader */
467 init_get_bits(&s->gb, buf, buf_size * 8);
468 skip_bits(&s->gb, s->bitindex);
470 /* process header or next subblock */
471 if (!s->got_header) {
472 if ((ret = read_header(s)) < 0)
478 /* if quit command was read previously, don't decode anything */
479 if (s->got_quit_command) {
485 while (s->cur_chan < s->channels) {
489 if (get_bits_left(&s->gb) < 3 + FNSIZE) {
494 cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
496 if (cmd > FN_VERBATIM) {
497 av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);
502 if (!is_audio_command[cmd]) {
503 /* process non-audio command */
506 len = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
508 get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
511 s->bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);
513 return AVERROR_INVALIDDATA;
516 unsigned blocksize = get_uint(s, av_log2(s->blocksize));
517 if (blocksize > s->blocksize) {
518 av_log(avctx, AV_LOG_ERROR,
519 "Increasing block size is not supported\n");
520 return AVERROR_PATCHWELCOME;
522 if (!blocksize || blocksize > MAX_BLOCKSIZE) {
523 av_log(avctx, AV_LOG_ERROR, "invalid or unsupported "
524 "block size: %d\n", blocksize);
525 return AVERROR(EINVAL);
527 s->blocksize = blocksize;
531 s->got_quit_command = 1;
534 if (cmd == FN_BLOCKSIZE || cmd == FN_QUIT) {
539 /* process audio command */
540 int residual_size = 0;
541 int channel = s->cur_chan;
544 /* get Rice code for residual decoding */
545 if (cmd != FN_ZERO) {
546 residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);
547 /* This is a hack as version 0 differed in the definition
548 * of get_sr_golomb_shorten(). */
553 /* calculate sample offset using means from previous blocks */
555 coffset = s->offset[channel][0];
557 int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;
558 for (i = 0; i < s->nmean; i++)
559 sum += s->offset[channel][i];
560 coffset = sum / s->nmean;
562 coffset >>= FFMIN(1, s->bitshift);
565 /* decode samples for this channel */
566 if (cmd == FN_ZERO) {
567 for (i = 0; i < s->blocksize; i++)
568 s->decoded[channel][i] = 0;
570 if ((ret = decode_subframe_lpc(s, cmd, channel,
571 residual_size, coffset)) < 0)
575 /* update means with info from the current block */
577 int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2;
578 for (i = 0; i < s->blocksize; i++)
579 sum += s->decoded[channel][i];
581 for (i = 1; i < s->nmean; i++)
582 s->offset[channel][i - 1] = s->offset[channel][i];
585 s->offset[channel][s->nmean - 1] = sum / s->blocksize;
587 s->offset[channel][s->nmean - 1] = (sum / s->blocksize) << s->bitshift;
590 /* copy wrap samples for use with next block */
591 for (i = -s->nwrap; i < 0; i++)
592 s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];
594 /* shift samples to add in unused zero bits which were removed
596 fix_bitshift(s, s->decoded[channel]);
598 /* if this is the last channel in the block, output the samples */
600 if (s->cur_chan == s->channels) {
601 /* get output buffer */
602 frame->nb_samples = s->blocksize;
603 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
604 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
607 /* interleave output */
608 output_buffer((int16_t **)frame->extended_data, s->channels,
609 s->blocksize, s->decoded);
615 if (s->cur_chan < s->channels)
619 s->bitindex = get_bits_count(&s->gb) - 8 * (get_bits_count(&s->gb) / 8);
620 i = get_bits_count(&s->gb) / 8;
622 av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
623 s->bitstream_size = 0;
624 s->bitstream_index = 0;
625 return AVERROR_INVALIDDATA;
627 if (s->bitstream_size) {
628 s->bitstream_index += i;
629 s->bitstream_size -= i;
630 return input_buf_size;
635 static av_cold int shorten_decode_close(AVCodecContext *avctx)
637 ShortenContext *s = avctx->priv_data;
640 for (i = 0; i < s->channels; i++) {
641 s->decoded[i] = NULL;
642 av_freep(&s->decoded_base[i]);
643 av_freep(&s->offset[i]);
645 av_freep(&s->bitstream);
646 av_freep(&s->coeffs);
651 AVCodec ff_shorten_decoder = {
653 .long_name = NULL_IF_CONFIG_SMALL("Shorten"),
654 .type = AVMEDIA_TYPE_AUDIO,
655 .id = AV_CODEC_ID_SHORTEN,
656 .priv_data_size = sizeof(ShortenContext),
657 .init = shorten_decode_init,
658 .close = shorten_decode_close,
659 .decode = shorten_decode_frame,
660 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_DR1,
661 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
662 AV_SAMPLE_FMT_NONE },