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"
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
60 #define V2LPCQOFFSET (1 << LPCQUANT)
68 #define FN_BLOCKSIZE 5
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 };
77 #define VERBATIM_CKSIZE_SIZE 5
78 #define VERBATIM_BYTE_SIZE 8
79 #define CANONICAL_HEADER_SIZE 44
81 typedef struct ShortenContext {
82 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_S16P;
120 static int allocate_buffers(ShortenContext *s)
124 for (chan = 0; chan < s->channels; chan++) {
125 if (FFMAX(1, s->nmean) >= UINT_MAX / sizeof(int32_t)) {
126 av_log(s->avctx, AV_LOG_ERROR, "nmean too large\n");
127 return AVERROR_INVALIDDATA;
129 if (s->blocksize + s->nwrap >= UINT_MAX / sizeof(int32_t) ||
130 s->blocksize + s->nwrap <= (unsigned)s->nwrap) {
131 av_log(s->avctx, AV_LOG_ERROR,
132 "s->blocksize + s->nwrap too large\n");
133 return AVERROR_INVALIDDATA;
136 if ((err = av_reallocp(&s->offset[chan],
138 FFMAX(1, s->nmean))) < 0)
141 if ((err = av_reallocp(&s->decoded_base[chan], (s->blocksize + s->nwrap) *
142 sizeof(s->decoded_base[0][0]))) < 0)
144 for (i = 0; i < s->nwrap; i++)
145 s->decoded_base[chan][i] = 0;
146 s->decoded[chan] = s->decoded_base[chan] + s->nwrap;
149 if ((err = av_reallocp(&s->coeffs, s->nwrap * sizeof(*s->coeffs))) < 0)
155 static inline unsigned int get_uint(ShortenContext *s, int k)
158 k = get_ur_golomb_shorten(&s->gb, ULONGSIZE);
159 return get_ur_golomb_shorten(&s->gb, k);
162 static void fix_bitshift(ShortenContext *s, int32_t *buffer)
166 if (s->bitshift != 0)
167 for (i = 0; i < s->blocksize; i++)
168 buffer[i] <<= s->bitshift;
171 static int init_offset(ShortenContext *s)
175 int nblock = FFMAX(1, s->nmean);
176 /* initialise offset */
177 switch (s->internal_ftype) {
183 av_log(s->avctx, AV_LOG_ERROR, "unknown audio type");
184 return AVERROR_INVALIDDATA;
187 for (chan = 0; chan < s->channels; chan++)
188 for (i = 0; i < nblock; i++)
189 s->offset[chan][i] = mean;
193 static int decode_wave_header(AVCodecContext *avctx, const uint8_t *header,
200 bytestream2_init(&gb, header, header_size);
202 if (bytestream2_get_le32(&gb) != MKTAG('R', 'I', 'F', 'F')) {
203 av_log(avctx, AV_LOG_ERROR, "missing RIFF tag\n");
204 return AVERROR_INVALIDDATA;
207 bytestream2_skip(&gb, 4); /* chunk size */
209 if (bytestream2_get_le32(&gb) != MKTAG('W', 'A', 'V', 'E')) {
210 av_log(avctx, AV_LOG_ERROR, "missing WAVE tag\n");
211 return AVERROR_INVALIDDATA;
214 while (bytestream2_get_le32(&gb) != MKTAG('f', 'm', 't', ' ')) {
215 len = bytestream2_get_le32(&gb);
216 bytestream2_skip(&gb, len);
217 if (bytestream2_get_bytes_left(&gb) < 16) {
218 av_log(avctx, AV_LOG_ERROR, "no fmt chunk found\n");
219 return AVERROR_INVALIDDATA;
222 len = bytestream2_get_le32(&gb);
225 av_log(avctx, AV_LOG_ERROR, "fmt chunk was too short\n");
226 return AVERROR_INVALIDDATA;
229 wave_format = bytestream2_get_le16(&gb);
231 switch (wave_format) {
232 case WAVE_FORMAT_PCM:
235 av_log(avctx, AV_LOG_ERROR, "unsupported wave format\n");
236 return AVERROR(ENOSYS);
239 bytestream2_skip(&gb, 2); // skip channels (already got from shorten header)
240 avctx->sample_rate = bytestream2_get_le32(&gb);
241 bytestream2_skip(&gb, 4); // skip bit rate (represents original uncompressed bit rate)
242 bytestream2_skip(&gb, 2); // skip block align (not needed)
243 avctx->bits_per_coded_sample = bytestream2_get_le16(&gb);
245 if (avctx->bits_per_coded_sample != 16) {
246 av_log(avctx, AV_LOG_ERROR, "unsupported number of bits per sample\n");
247 return AVERROR(ENOSYS);
252 av_log(avctx, AV_LOG_INFO, "%d header bytes unparsed\n", len);
257 static void output_buffer(int16_t **samples, int nchan, int blocksize,
261 for (ch = 0; ch < nchan; ch++) {
262 int32_t *in = buffer[ch];
263 int16_t *out = samples[ch];
264 for (i = 0; i < blocksize; i++)
265 out[i] = av_clip_int16(in[i]);
269 static const int fixed_coeffs[][3] = {
276 static int decode_subframe_lpc(ShortenContext *s, int command, int channel,
277 int residual_size, int32_t coffset)
279 int pred_order, sum, qshift, init_sum, i, j;
282 if (command == FN_QLPC) {
283 /* read/validate prediction order */
284 pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
285 if (pred_order > s->nwrap) {
286 av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n",
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 if (pred_order >= FF_ARRAY_ELEMS(fixed_coeffs)) {
300 av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n",
302 return AVERROR_INVALIDDATA;
304 coeffs = fixed_coeffs[pred_order];
308 /* subtract offset from previous samples to use in prediction */
309 if (command == FN_QLPC && coffset)
310 for (i = -pred_order; i < 0; i++)
311 s->decoded[channel][i] -= coffset;
313 /* decode residual and do LPC prediction */
314 init_sum = pred_order ? (command == FN_QLPC ? s->lpcqoffset : 0) : coffset;
315 for (i = 0; i < s->blocksize; i++) {
317 for (j = 0; j < pred_order; j++)
318 sum += coeffs[j] * s->decoded[channel][i - j - 1];
319 s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) +
323 /* add offset to current samples */
324 if (command == FN_QLPC && coffset)
325 for (i = 0; i < s->blocksize; i++)
326 s->decoded[channel][i] += coffset;
331 static int read_header(ShortenContext *s)
335 /* shorten signature */
336 if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {
337 av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
338 return AVERROR_INVALIDDATA;
342 s->blocksize = DEFAULT_BLOCK_SIZE;
344 s->version = get_bits(&s->gb, 8);
345 s->internal_ftype = get_uint(s, TYPESIZE);
347 s->channels = get_uint(s, CHANSIZE);
349 av_log(s->avctx, AV_LOG_ERROR, "No channels reported\n");
350 return AVERROR_INVALIDDATA;
352 if (s->channels > MAX_CHANNELS) {
353 av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
355 return AVERROR_INVALIDDATA;
357 s->avctx->channels = s->channels;
359 /* get blocksize if version > 0 */
360 if (s->version > 0) {
364 blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
365 if (!blocksize || blocksize > MAX_BLOCKSIZE) {
366 av_log(s->avctx, AV_LOG_ERROR,
367 "invalid or unsupported block size: %d\n",
369 return AVERROR(EINVAL);
371 s->blocksize = blocksize;
373 maxnlpc = get_uint(s, LPCQSIZE);
374 s->nmean = get_uint(s, 0);
376 skip_bytes = get_uint(s, NSKIPSIZE);
377 for (i = 0; i < skip_bytes; i++)
378 skip_bits(&s->gb, 8);
380 s->nwrap = FFMAX(NWRAP, maxnlpc);
382 if ((ret = allocate_buffers(s)) < 0)
385 if ((ret = init_offset(s)) < 0)
389 s->lpcqoffset = V2LPCQOFFSET;
391 if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
392 av_log(s->avctx, AV_LOG_ERROR,
393 "missing verbatim section at beginning of stream\n");
394 return AVERROR_INVALIDDATA;
397 s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
398 if (s->header_size >= OUT_BUFFER_SIZE ||
399 s->header_size < CANONICAL_HEADER_SIZE) {
400 av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n",
402 return AVERROR_INVALIDDATA;
405 for (i = 0; i < s->header_size; i++)
406 s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
408 if ((ret = decode_wave_header(s->avctx, s->header, s->header_size)) < 0)
419 static int shorten_decode_frame(AVCodecContext *avctx, void *data,
420 int *got_frame_ptr, AVPacket *avpkt)
422 AVFrame *frame = data;
423 const uint8_t *buf = avpkt->data;
424 int buf_size = avpkt->size;
425 ShortenContext *s = avctx->priv_data;
426 int i, input_buf_size = 0;
429 /* allocate internal bitstream buffer */
430 if (s->max_framesize == 0) {
432 s->max_framesize = 1024; // should hopefully be enough for the first header
433 tmp_ptr = av_fast_realloc(s->bitstream, &s->allocated_bitstream_size,
434 s->max_framesize + FF_INPUT_BUFFER_PADDING_SIZE);
436 av_log(avctx, AV_LOG_ERROR, "error allocating bitstream buffer\n");
437 return AVERROR(ENOMEM);
439 s->bitstream = tmp_ptr;
442 /* append current packet data to bitstream buffer */
443 if (1 && s->max_framesize) { //FIXME truncated
444 buf_size = FFMIN(buf_size, s->max_framesize - s->bitstream_size);
445 input_buf_size = buf_size;
447 if (s->bitstream_index + s->bitstream_size + buf_size >
448 s->allocated_bitstream_size) {
449 memmove(s->bitstream, &s->bitstream[s->bitstream_index],
451 s->bitstream_index = 0;
454 memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size], buf,
456 buf = &s->bitstream[s->bitstream_index];
457 buf_size += s->bitstream_size;
458 s->bitstream_size = buf_size;
460 /* do not decode until buffer has at least max_framesize bytes or
461 * the end of the file has been reached */
462 if (buf_size < s->max_framesize && avpkt->data) {
464 return input_buf_size;
467 /* init and position bitstream reader */
468 init_get_bits(&s->gb, buf, buf_size * 8);
469 skip_bits(&s->gb, s->bitindex);
471 /* process header or next subblock */
472 if (!s->got_header) {
473 if ((ret = read_header(s)) < 0)
479 /* if quit command was read previously, don't decode anything */
480 if (s->got_quit_command) {
486 while (s->cur_chan < s->channels) {
490 if (get_bits_left(&s->gb) < 3 + FNSIZE) {
495 cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
497 if (cmd > FN_VERBATIM) {
498 av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);
503 if (!is_audio_command[cmd]) {
504 /* process non-audio command */
507 len = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
509 get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
512 s->bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);
515 unsigned blocksize = get_uint(s, av_log2(s->blocksize));
516 if (blocksize > s->blocksize) {
517 av_log(avctx, AV_LOG_ERROR,
518 "Increasing block size is not supported\n");
519 return AVERROR_PATCHWELCOME;
521 if (!blocksize || blocksize > MAX_BLOCKSIZE) {
522 av_log(avctx, AV_LOG_ERROR, "invalid or unsupported "
523 "block size: %d\n", blocksize);
524 return AVERROR(EINVAL);
526 s->blocksize = blocksize;
530 s->got_quit_command = 1;
533 if (cmd == FN_BLOCKSIZE || cmd == FN_QUIT) {
538 /* process audio command */
539 int residual_size = 0;
540 int channel = s->cur_chan;
543 /* get Rice code for residual decoding */
544 if (cmd != FN_ZERO) {
545 residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);
546 /* This is a hack as version 0 differed in the definition
547 * of get_sr_golomb_shorten(). */
552 /* calculate sample offset using means from previous blocks */
554 coffset = s->offset[channel][0];
556 int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;
557 for (i = 0; i < s->nmean; i++)
558 sum += s->offset[channel][i];
559 coffset = sum / s->nmean;
561 coffset >>= FFMIN(1, s->bitshift);
564 /* decode samples for this channel */
565 if (cmd == FN_ZERO) {
566 for (i = 0; i < s->blocksize; i++)
567 s->decoded[channel][i] = 0;
569 if ((ret = decode_subframe_lpc(s, cmd, channel,
570 residual_size, coffset)) < 0)
574 /* update means with info from the current block */
576 int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2;
577 for (i = 0; i < s->blocksize; i++)
578 sum += s->decoded[channel][i];
580 for (i = 1; i < s->nmean; i++)
581 s->offset[channel][i - 1] = s->offset[channel][i];
584 s->offset[channel][s->nmean - 1] = sum / s->blocksize;
586 s->offset[channel][s->nmean - 1] = (sum / s->blocksize) << s->bitshift;
589 /* copy wrap samples for use with next block */
590 for (i = -s->nwrap; i < 0; i++)
591 s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];
593 /* shift samples to add in unused zero bits which were removed
595 fix_bitshift(s, s->decoded[channel]);
597 /* if this is the last channel in the block, output the samples */
599 if (s->cur_chan == s->channels) {
600 /* get output buffer */
601 frame->nb_samples = s->blocksize;
602 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
603 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
606 /* interleave output */
607 output_buffer((int16_t **)frame->extended_data, s->channels,
608 s->blocksize, s->decoded);
614 if (s->cur_chan < s->channels)
618 s->bitindex = get_bits_count(&s->gb) - 8 * (get_bits_count(&s->gb) / 8);
619 i = get_bits_count(&s->gb) / 8;
621 av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
622 s->bitstream_size = 0;
623 s->bitstream_index = 0;
624 return AVERROR_INVALIDDATA;
626 if (s->bitstream_size) {
627 s->bitstream_index += i;
628 s->bitstream_size -= i;
629 return input_buf_size;
634 static av_cold int shorten_decode_close(AVCodecContext *avctx)
636 ShortenContext *s = avctx->priv_data;
639 for (i = 0; i < s->channels; i++) {
640 s->decoded[i] = NULL;
641 av_freep(&s->decoded_base[i]);
642 av_freep(&s->offset[i]);
644 av_freep(&s->bitstream);
645 av_freep(&s->coeffs);
650 AVCodec ff_shorten_decoder = {
652 .long_name = NULL_IF_CONFIG_SMALL("Shorten"),
653 .type = AVMEDIA_TYPE_AUDIO,
654 .id = AV_CODEC_ID_SHORTEN,
655 .priv_data_size = sizeof(ShortenContext),
656 .init = shorten_decode_init,
657 .close = shorten_decode_close,
658 .decode = shorten_decode_frame,
659 .capabilities = CODEC_CAP_DELAY | CODEC_CAP_DR1,
660 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
661 AV_SAMPLE_FMT_NONE },