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;
114 BswapDSPContext bdsp;
117 static av_cold int shorten_decode_init(AVCodecContext *avctx)
119 ShortenContext *s = avctx->priv_data;
122 ff_bswapdsp_init(&s->bdsp);
127 static int allocate_buffers(ShortenContext *s)
131 for (chan = 0; chan < s->channels; chan++) {
132 if (FFMAX(1, s->nmean) >= UINT_MAX / sizeof(int32_t)) {
133 av_log(s->avctx, AV_LOG_ERROR, "nmean too large\n");
134 return AVERROR_INVALIDDATA;
136 if (s->blocksize + (uint64_t)s->nwrap >= UINT_MAX / sizeof(int32_t)) {
137 av_log(s->avctx, AV_LOG_ERROR,
138 "s->blocksize + s->nwrap too large\n");
139 return AVERROR_INVALIDDATA;
142 if ((err = av_reallocp_array(&s->offset[chan],
144 FFMAX(1, s->nmean))) < 0)
147 if ((err = av_reallocp_array(&s->decoded_base[chan], (s->blocksize + s->nwrap),
148 sizeof(s->decoded_base[0][0]))) < 0)
150 for (i = 0; i < s->nwrap; i++)
151 s->decoded_base[chan][i] = 0;
152 s->decoded[chan] = s->decoded_base[chan] + s->nwrap;
155 if ((err = av_reallocp_array(&s->coeffs, s->nwrap, sizeof(*s->coeffs))) < 0)
161 static inline unsigned int get_uint(ShortenContext *s, int k)
163 if (s->version != 0) {
164 k = get_ur_golomb_shorten(&s->gb, ULONGSIZE);
166 return AVERROR_INVALIDDATA;
168 return get_ur_golomb_shorten(&s->gb, k);
171 static void fix_bitshift(ShortenContext *s, int32_t *buffer)
175 if (s->bitshift == 32) {
176 for (i = 0; i < s->blocksize; i++)
178 } else if (s->bitshift != 0) {
179 for (i = 0; i < s->blocksize; i++)
180 buffer[i] *= 1U << s->bitshift;
184 static int init_offset(ShortenContext *s)
188 int nblock = FFMAX(1, s->nmean);
189 /* initialise offset */
190 switch (s->internal_ftype) {
192 s->avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
197 s->avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
200 av_log(s->avctx, AV_LOG_ERROR, "unknown audio type\n");
201 return AVERROR_PATCHWELCOME;
204 for (chan = 0; chan < s->channels; chan++)
205 for (i = 0; i < nblock; i++)
206 s->offset[chan][i] = mean;
210 static int decode_aiff_header(AVCodecContext *avctx, const uint8_t *header,
213 ShortenContext *s = avctx->priv_data;
219 bytestream2_init(&gb, header, header_size);
221 if (bytestream2_get_le32(&gb) != MKTAG('F', 'O', 'R', 'M')) {
222 av_log(avctx, AV_LOG_ERROR, "missing FORM tag\n");
223 return AVERROR_INVALIDDATA;
226 bytestream2_skip(&gb, 4); /* chunk size */
228 tag = bytestream2_get_le32(&gb);
229 if (tag != MKTAG('A', 'I', 'F', 'F') &&
230 tag != MKTAG('A', 'I', 'F', 'C')) {
231 av_log(avctx, AV_LOG_ERROR, "missing AIFF tag\n");
232 return AVERROR_INVALIDDATA;
235 while (bytestream2_get_le32(&gb) != MKTAG('C', 'O', 'M', 'M')) {
236 len = bytestream2_get_be32(&gb);
237 if (len < 0 || bytestream2_get_bytes_left(&gb) < 18LL + len + (len&1)) {
238 av_log(avctx, AV_LOG_ERROR, "no COMM chunk found\n");
239 return AVERROR_INVALIDDATA;
241 bytestream2_skip(&gb, len + (len & 1));
243 len = bytestream2_get_be32(&gb);
246 av_log(avctx, AV_LOG_ERROR, "COMM chunk was too short\n");
247 return AVERROR_INVALIDDATA;
250 bytestream2_skip(&gb, 6);
251 bps = bytestream2_get_be16(&gb);
252 avctx->bits_per_coded_sample = bps;
254 s->swap = tag == MKTAG('A', 'I', 'F', 'C');
256 if (bps != 16 && bps != 8) {
257 av_log(avctx, AV_LOG_ERROR, "unsupported number of bits per sample: %d\n", bps);
258 return AVERROR(ENOSYS);
261 exp = bytestream2_get_be16(&gb) - 16383 - 63;
262 val = bytestream2_get_be64(&gb);
263 if (exp < -63 || exp > 63) {
264 av_log(avctx, AV_LOG_ERROR, "exp %d is out of range\n", exp);
265 return AVERROR_INVALIDDATA;
268 avctx->sample_rate = val << exp;
270 avctx->sample_rate = (val + (1ULL<<(-exp-1))) >> -exp;
273 av_log(avctx, AV_LOG_INFO, "%d header bytes unparsed\n", len);
278 static int decode_wave_header(AVCodecContext *avctx, const uint8_t *header,
285 bytestream2_init(&gb, header, header_size);
287 if (bytestream2_get_le32(&gb) != MKTAG('R', 'I', 'F', 'F')) {
288 av_log(avctx, AV_LOG_ERROR, "missing RIFF tag\n");
289 return AVERROR_INVALIDDATA;
292 bytestream2_skip(&gb, 4); /* chunk size */
294 if (bytestream2_get_le32(&gb) != MKTAG('W', 'A', 'V', 'E')) {
295 av_log(avctx, AV_LOG_ERROR, "missing WAVE tag\n");
296 return AVERROR_INVALIDDATA;
299 while (bytestream2_get_le32(&gb) != MKTAG('f', 'm', 't', ' ')) {
300 len = bytestream2_get_le32(&gb);
301 bytestream2_skip(&gb, len);
302 if (len < 0 || bytestream2_get_bytes_left(&gb) < 16) {
303 av_log(avctx, AV_LOG_ERROR, "no fmt chunk found\n");
304 return AVERROR_INVALIDDATA;
307 len = bytestream2_get_le32(&gb);
310 av_log(avctx, AV_LOG_ERROR, "fmt chunk was too short\n");
311 return AVERROR_INVALIDDATA;
314 wave_format = bytestream2_get_le16(&gb);
316 switch (wave_format) {
317 case WAVE_FORMAT_PCM:
320 av_log(avctx, AV_LOG_ERROR, "unsupported wave format\n");
321 return AVERROR(ENOSYS);
324 bytestream2_skip(&gb, 2); // skip channels (already got from shorten header)
325 avctx->sample_rate = bytestream2_get_le32(&gb);
326 bytestream2_skip(&gb, 4); // skip bit rate (represents original uncompressed bit rate)
327 bytestream2_skip(&gb, 2); // skip block align (not needed)
328 bps = bytestream2_get_le16(&gb);
329 avctx->bits_per_coded_sample = bps;
331 if (bps != 16 && bps != 8) {
332 av_log(avctx, AV_LOG_ERROR, "unsupported number of bits per sample: %d\n", bps);
333 return AVERROR(ENOSYS);
338 av_log(avctx, AV_LOG_INFO, "%d header bytes unparsed\n", len);
343 static const int fixed_coeffs[][3] = {
350 static int decode_subframe_lpc(ShortenContext *s, int command, int channel,
351 int residual_size, int32_t coffset)
353 int pred_order, sum, qshift, init_sum, i, j;
356 if (command == FN_QLPC) {
357 /* read/validate prediction order */
358 pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
359 if ((unsigned)pred_order > s->nwrap) {
360 av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n",
362 return AVERROR(EINVAL);
364 /* read LPC coefficients */
365 for (i = 0; i < pred_order; i++)
366 s->coeffs[i] = get_sr_golomb_shorten(&s->gb, LPCQUANT);
371 /* fixed LPC coeffs */
372 pred_order = command;
373 if (pred_order >= FF_ARRAY_ELEMS(fixed_coeffs)) {
374 av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n",
376 return AVERROR_INVALIDDATA;
378 coeffs = fixed_coeffs[pred_order];
382 /* subtract offset from previous samples to use in prediction */
383 if (command == FN_QLPC && coffset)
384 for (i = -pred_order; i < 0; i++)
385 s->decoded[channel][i] -= coffset;
387 /* decode residual and do LPC prediction */
388 init_sum = pred_order ? (command == FN_QLPC ? s->lpcqoffset : 0) : coffset;
389 for (i = 0; i < s->blocksize; i++) {
391 for (j = 0; j < pred_order; j++)
392 sum += coeffs[j] * (unsigned)s->decoded[channel][i - j - 1];
393 s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) +
394 (unsigned)(sum >> qshift);
397 /* add offset to current samples */
398 if (command == FN_QLPC && coffset)
399 for (i = 0; i < s->blocksize; i++)
400 s->decoded[channel][i] += coffset;
405 static int read_header(ShortenContext *s)
409 /* shorten signature */
410 if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {
411 av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
412 return AVERROR_INVALIDDATA;
416 s->blocksize = DEFAULT_BLOCK_SIZE;
418 s->version = get_bits(&s->gb, 8);
419 s->internal_ftype = get_uint(s, TYPESIZE);
421 s->channels = get_uint(s, CHANSIZE);
423 av_log(s->avctx, AV_LOG_ERROR, "No channels reported\n");
424 return AVERROR_INVALIDDATA;
426 if (s->channels > MAX_CHANNELS) {
427 av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
429 return AVERROR_INVALIDDATA;
431 s->avctx->channels = s->channels;
433 /* get blocksize if version > 0 */
434 if (s->version > 0) {
438 blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
439 if (!blocksize || blocksize > MAX_BLOCKSIZE) {
440 av_log(s->avctx, AV_LOG_ERROR,
441 "invalid or unsupported block size: %d\n",
443 return AVERROR(EINVAL);
445 s->blocksize = blocksize;
447 maxnlpc = get_uint(s, LPCQSIZE);
448 if (maxnlpc > 1024U) {
449 av_log(s->avctx, AV_LOG_ERROR, "maxnlpc is: %d\n", maxnlpc);
450 return AVERROR_INVALIDDATA;
452 s->nmean = get_uint(s, 0);
453 if (s->nmean > 32768U) {
454 av_log(s->avctx, AV_LOG_ERROR, "nmean is: %d\n", s->nmean);
455 return AVERROR_INVALIDDATA;
458 skip_bytes = get_uint(s, NSKIPSIZE);
459 if ((unsigned)skip_bytes > get_bits_left(&s->gb)/8) {
460 av_log(s->avctx, AV_LOG_ERROR, "invalid skip_bytes: %d\n", skip_bytes);
461 return AVERROR_INVALIDDATA;
464 for (i = 0; i < skip_bytes; i++)
465 skip_bits(&s->gb, 8);
467 s->nwrap = FFMAX(NWRAP, maxnlpc);
470 s->lpcqoffset = V2LPCQOFFSET;
472 if (s->avctx->extradata_size > 0)
475 if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
476 av_log(s->avctx, AV_LOG_ERROR,
477 "missing verbatim section at beginning of stream\n");
478 return AVERROR_INVALIDDATA;
481 s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
482 if (s->header_size >= OUT_BUFFER_SIZE ||
483 s->header_size < CANONICAL_HEADER_SIZE) {
484 av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n",
486 return AVERROR_INVALIDDATA;
489 for (i = 0; i < s->header_size; i++)
490 s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
492 if (AV_RL32(s->header) == MKTAG('R','I','F','F')) {
493 if ((ret = decode_wave_header(s->avctx, s->header, s->header_size)) < 0)
495 } else if (AV_RL32(s->header) == MKTAG('F','O','R','M')) {
496 if ((ret = decode_aiff_header(s->avctx, s->header, s->header_size)) < 0)
499 avpriv_report_missing_feature(s->avctx, "unsupported bit packing %"
500 PRIX32, AV_RL32(s->header));
501 return AVERROR_PATCHWELCOME;
506 if ((ret = allocate_buffers(s)) < 0)
509 if ((ret = init_offset(s)) < 0)
520 static int shorten_decode_frame(AVCodecContext *avctx, void *data,
521 int *got_frame_ptr, AVPacket *avpkt)
523 AVFrame *frame = data;
524 const uint8_t *buf = avpkt->data;
525 int buf_size = avpkt->size;
526 ShortenContext *s = avctx->priv_data;
527 int i, input_buf_size = 0;
530 /* allocate internal bitstream buffer */
531 if (s->max_framesize == 0) {
533 s->max_framesize = 8192; // should hopefully be enough for the first header
534 tmp_ptr = av_fast_realloc(s->bitstream, &s->allocated_bitstream_size,
535 s->max_framesize + AV_INPUT_BUFFER_PADDING_SIZE);
537 s->max_framesize = 0;
538 av_log(avctx, AV_LOG_ERROR, "error allocating bitstream buffer\n");
539 return AVERROR(ENOMEM);
541 memset(tmp_ptr, 0, s->allocated_bitstream_size);
542 s->bitstream = tmp_ptr;
545 /* append current packet data to bitstream buffer */
546 buf_size = FFMIN(buf_size, s->max_framesize - s->bitstream_size);
547 input_buf_size = buf_size;
549 if (s->bitstream_index + s->bitstream_size + buf_size + AV_INPUT_BUFFER_PADDING_SIZE >
550 s->allocated_bitstream_size) {
551 memmove(s->bitstream, &s->bitstream[s->bitstream_index],
553 s->bitstream_index = 0;
556 memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size], buf,
558 buf = &s->bitstream[s->bitstream_index];
559 buf_size += s->bitstream_size;
560 s->bitstream_size = buf_size;
562 /* do not decode until buffer has at least max_framesize bytes or
563 * the end of the file has been reached */
564 if (buf_size < s->max_framesize && avpkt->data) {
566 return input_buf_size;
568 /* init and position bitstream reader */
569 if ((ret = init_get_bits8(&s->gb, buf, buf_size)) < 0)
571 skip_bits(&s->gb, s->bitindex);
573 /* process header or next subblock */
574 if (!s->got_header) {
576 if ((ret = read_header(s)) < 0)
583 max_framesize = FFMAX(s->max_framesize, s->blocksize * s->channels * 8);
584 tmp_ptr = av_fast_realloc(s->bitstream, &s->allocated_bitstream_size,
585 max_framesize + AV_INPUT_BUFFER_PADDING_SIZE);
587 av_log(avctx, AV_LOG_ERROR, "error allocating bitstream buffer\n");
588 return AVERROR(ENOMEM);
590 s->bitstream = tmp_ptr;
591 s->max_framesize = max_framesize;
597 /* if quit command was read previously, don't decode anything */
598 if (s->got_quit_command) {
604 while (s->cur_chan < s->channels) {
608 if (get_bits_left(&s->gb) < 3 + FNSIZE) {
613 cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
615 if (cmd > FN_VERBATIM) {
616 av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);
621 if (!is_audio_command[cmd]) {
622 /* process non-audio command */
625 len = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
626 if (len < 0 || len > get_bits_left(&s->gb)) {
627 av_log(avctx, AV_LOG_ERROR, "verbatim length %d invalid\n",
629 return AVERROR_INVALIDDATA;
632 get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
635 unsigned bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);
637 av_log(avctx, AV_LOG_ERROR, "bitshift %d is invalid\n",
639 return AVERROR_INVALIDDATA;
641 s->bitshift = bitshift;
645 unsigned blocksize = get_uint(s, av_log2(s->blocksize));
646 if (blocksize > s->blocksize) {
647 avpriv_report_missing_feature(avctx,
648 "Increasing block size");
649 return AVERROR_PATCHWELCOME;
651 if (!blocksize || blocksize > MAX_BLOCKSIZE) {
652 av_log(avctx, AV_LOG_ERROR, "invalid or unsupported "
653 "block size: %d\n", blocksize);
654 return AVERROR(EINVAL);
656 s->blocksize = blocksize;
660 s->got_quit_command = 1;
666 /* process audio command */
667 int residual_size = 0;
668 int channel = s->cur_chan;
671 /* get Rice code for residual decoding */
672 if (cmd != FN_ZERO) {
673 residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);
674 /* This is a hack as version 0 differed in the definition
675 * of get_sr_golomb_shorten(). */
678 if (residual_size > 30U) {
679 av_log(avctx, AV_LOG_ERROR, "residual size unsupportd: %d\n", residual_size);
680 return AVERROR_INVALIDDATA;
684 /* calculate sample offset using means from previous blocks */
686 coffset = s->offset[channel][0];
688 int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;
689 for (i = 0; i < s->nmean; i++)
690 sum += (unsigned)s->offset[channel][i];
691 coffset = sum / s->nmean;
693 coffset = s->bitshift == 0 ? coffset : coffset >> s->bitshift - 1 >> 1;
696 /* decode samples for this channel */
697 if (cmd == FN_ZERO) {
698 for (i = 0; i < s->blocksize; i++)
699 s->decoded[channel][i] = 0;
701 if ((ret = decode_subframe_lpc(s, cmd, channel,
702 residual_size, coffset)) < 0)
706 /* update means with info from the current block */
708 int64_t sum = (s->version < 2) ? 0 : s->blocksize / 2;
709 for (i = 0; i < s->blocksize; i++)
710 sum += s->decoded[channel][i];
712 for (i = 1; i < s->nmean; i++)
713 s->offset[channel][i - 1] = s->offset[channel][i];
716 s->offset[channel][s->nmean - 1] = sum / s->blocksize;
718 s->offset[channel][s->nmean - 1] = s->bitshift == 32 ? 0 : (sum / s->blocksize) * (1LL << s->bitshift);
721 /* copy wrap samples for use with next block */
722 for (i = -s->nwrap; i < 0; i++)
723 s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];
725 /* shift samples to add in unused zero bits which were removed
727 fix_bitshift(s, s->decoded[channel]);
729 /* if this is the last channel in the block, output the samples */
731 if (s->cur_chan == s->channels) {
733 int16_t *samples_s16;
736 /* get output buffer */
737 frame->nb_samples = s->blocksize;
738 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
741 for (chan = 0; chan < s->channels; chan++) {
742 samples_u8 = ((uint8_t **)frame->extended_data)[chan];
743 samples_s16 = ((int16_t **)frame->extended_data)[chan];
744 for (i = 0; i < s->blocksize; i++) {
745 switch (s->internal_ftype) {
747 *samples_u8++ = av_clip_uint8(s->decoded[chan][i]);
751 *samples_s16++ = av_clip_int16(s->decoded[chan][i]);
755 if (s->swap && s->internal_ftype != TYPE_U8)
756 s->bdsp.bswap16_buf(((uint16_t **)frame->extended_data)[chan],
757 ((uint16_t **)frame->extended_data)[chan],
766 if (s->cur_chan < s->channels)
770 s->bitindex = get_bits_count(&s->gb) - 8 * (get_bits_count(&s->gb) / 8);
771 i = get_bits_count(&s->gb) / 8;
773 av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
774 s->bitstream_size = 0;
775 s->bitstream_index = 0;
776 return AVERROR_INVALIDDATA;
778 if (s->bitstream_size) {
779 s->bitstream_index += i;
780 s->bitstream_size -= i;
781 return input_buf_size;
786 static av_cold int shorten_decode_close(AVCodecContext *avctx)
788 ShortenContext *s = avctx->priv_data;
791 for (i = 0; i < s->channels; i++) {
792 s->decoded[i] = NULL;
793 av_freep(&s->decoded_base[i]);
794 av_freep(&s->offset[i]);
796 av_freep(&s->bitstream);
797 av_freep(&s->coeffs);
802 AVCodec ff_shorten_decoder = {
804 .long_name = NULL_IF_CONFIG_SMALL("Shorten"),
805 .type = AVMEDIA_TYPE_AUDIO,
806 .id = AV_CODEC_ID_SHORTEN,
807 .priv_data_size = sizeof(ShortenContext),
808 .init = shorten_decode_init,
809 .close = shorten_decode_close,
810 .decode = shorten_decode_frame,
811 .capabilities = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_DR1,
812 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
814 AV_SAMPLE_FMT_NONE },