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
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
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;
88 int min_framesize, max_framesize;
91 int32_t *decoded[MAX_CHANNELS];
92 int32_t *decoded_base[MAX_CHANNELS];
93 int32_t *offset[MAX_CHANNELS];
98 unsigned int allocated_bitstream_size;
100 uint8_t header[OUT_BUFFER_SIZE];
111 int got_quit_command;
114 static av_cold int shorten_decode_init(AVCodecContext *avctx)
116 ShortenContext *s = avctx->priv_data;
122 static int allocate_buffers(ShortenContext *s)
126 for (chan = 0; chan < s->channels; chan++) {
127 if (FFMAX(1, s->nmean) >= UINT_MAX / sizeof(int32_t)) {
128 av_log(s->avctx, AV_LOG_ERROR, "nmean too large\n");
129 return AVERROR_INVALIDDATA;
131 if (s->blocksize + (uint64_t)s->nwrap >= UINT_MAX / sizeof(int32_t)) {
132 av_log(s->avctx, AV_LOG_ERROR,
133 "s->blocksize + s->nwrap too large\n");
134 return AVERROR_INVALIDDATA;
137 if ((err = av_reallocp_array(&s->offset[chan],
139 FFMAX(1, s->nmean))) < 0)
142 if ((err = av_reallocp_array(&s->decoded_base[chan], (s->blocksize + s->nwrap),
143 sizeof(s->decoded_base[0][0]))) < 0)
145 for (i = 0; i < s->nwrap; i++)
146 s->decoded_base[chan][i] = 0;
147 s->decoded[chan] = s->decoded_base[chan] + s->nwrap;
150 if ((err = av_reallocp_array(&s->coeffs, s->nwrap, sizeof(*s->coeffs))) < 0)
156 static inline unsigned int get_uint(ShortenContext *s, int k)
159 k = get_ur_golomb_shorten(&s->gb, ULONGSIZE);
160 return get_ur_golomb_shorten(&s->gb, k);
163 static void fix_bitshift(ShortenContext *s, int32_t *buffer)
167 if (s->bitshift == 32) {
168 for (i = 0; i < s->blocksize; i++)
170 } else if (s->bitshift != 0) {
171 for (i = 0; i < s->blocksize; i++)
172 buffer[i] <<= s->bitshift;
176 static int init_offset(ShortenContext *s)
180 int nblock = FFMAX(1, s->nmean);
181 /* initialise offset */
182 switch (s->internal_ftype) {
184 s->avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
189 s->avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
192 av_log(s->avctx, AV_LOG_ERROR, "unknown audio type\n");
193 return AVERROR_PATCHWELCOME;
196 for (chan = 0; chan < s->channels; chan++)
197 for (i = 0; i < nblock; i++)
198 s->offset[chan][i] = mean;
202 static int decode_aiff_header(AVCodecContext *avctx, const uint8_t *header,
210 bytestream2_init(&gb, header, header_size);
212 if (bytestream2_get_le32(&gb) != MKTAG('F', 'O', 'R', 'M')) {
213 av_log(avctx, AV_LOG_ERROR, "missing FORM tag\n");
214 return AVERROR_INVALIDDATA;
217 bytestream2_skip(&gb, 4); /* chunk size */
219 tag = bytestream2_get_le32(&gb);
220 if (tag != MKTAG('A', 'I', 'F', 'F')) {
221 av_log(avctx, AV_LOG_ERROR, "missing AIFF tag\n");
222 return AVERROR_INVALIDDATA;
225 while (bytestream2_get_le32(&gb) != MKTAG('C', 'O', 'M', 'M')) {
226 len = bytestream2_get_be32(&gb);
227 bytestream2_skip(&gb, len + (len & 1));
228 if (len < 0 || bytestream2_get_bytes_left(&gb) < 18) {
229 av_log(avctx, AV_LOG_ERROR, "no COMM chunk found\n");
230 return AVERROR_INVALIDDATA;
233 len = bytestream2_get_be32(&gb);
236 av_log(avctx, AV_LOG_ERROR, "COMM chunk was too short\n");
237 return AVERROR_INVALIDDATA;
240 bytestream2_skip(&gb, 6);
241 bps = bytestream2_get_be16(&gb);
242 avctx->bits_per_coded_sample = bps;
244 if (bps != 16 && bps != 8) {
245 av_log(avctx, AV_LOG_ERROR, "unsupported number of bits per sample: %d\n", bps);
246 return AVERROR(ENOSYS);
249 exp = bytestream2_get_be16(&gb) - 16383 - 63;
250 val = bytestream2_get_be64(&gb);
251 if (exp < -63 || exp > 63) {
252 av_log(avctx, AV_LOG_ERROR, "exp %d is out of range\n", exp);
253 return AVERROR_INVALIDDATA;
256 avctx->sample_rate = val << exp;
258 avctx->sample_rate = (val + (1ULL<<(-exp-1))) >> -exp;
261 av_log(avctx, AV_LOG_INFO, "%d header bytes unparsed\n", len);
266 static int decode_wave_header(AVCodecContext *avctx, const uint8_t *header,
273 bytestream2_init(&gb, header, header_size);
275 if (bytestream2_get_le32(&gb) != MKTAG('R', 'I', 'F', 'F')) {
276 av_log(avctx, AV_LOG_ERROR, "missing RIFF tag\n");
277 return AVERROR_INVALIDDATA;
280 bytestream2_skip(&gb, 4); /* chunk size */
282 if (bytestream2_get_le32(&gb) != MKTAG('W', 'A', 'V', 'E')) {
283 av_log(avctx, AV_LOG_ERROR, "missing WAVE tag\n");
284 return AVERROR_INVALIDDATA;
287 while (bytestream2_get_le32(&gb) != MKTAG('f', 'm', 't', ' ')) {
288 len = bytestream2_get_le32(&gb);
289 bytestream2_skip(&gb, len);
290 if (len < 0 || bytestream2_get_bytes_left(&gb) < 16) {
291 av_log(avctx, AV_LOG_ERROR, "no fmt chunk found\n");
292 return AVERROR_INVALIDDATA;
295 len = bytestream2_get_le32(&gb);
298 av_log(avctx, AV_LOG_ERROR, "fmt chunk was too short\n");
299 return AVERROR_INVALIDDATA;
302 wave_format = bytestream2_get_le16(&gb);
304 switch (wave_format) {
305 case WAVE_FORMAT_PCM:
308 av_log(avctx, AV_LOG_ERROR, "unsupported wave format\n");
309 return AVERROR(ENOSYS);
312 bytestream2_skip(&gb, 2); // skip channels (already got from shorten header)
313 avctx->sample_rate = bytestream2_get_le32(&gb);
314 bytestream2_skip(&gb, 4); // skip bit rate (represents original uncompressed bit rate)
315 bytestream2_skip(&gb, 2); // skip block align (not needed)
316 bps = bytestream2_get_le16(&gb);
317 avctx->bits_per_coded_sample = bps;
319 if (bps != 16 && bps != 8) {
320 av_log(avctx, AV_LOG_ERROR, "unsupported number of bits per sample: %d\n", bps);
321 return AVERROR(ENOSYS);
326 av_log(avctx, AV_LOG_INFO, "%d header bytes unparsed\n", len);
331 static const int fixed_coeffs[][3] = {
338 static int decode_subframe_lpc(ShortenContext *s, int command, int channel,
339 int residual_size, int32_t coffset)
341 int pred_order, sum, qshift, init_sum, i, j;
344 if (command == FN_QLPC) {
345 /* read/validate prediction order */
346 pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
347 if ((unsigned)pred_order > s->nwrap) {
348 av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n",
350 return AVERROR(EINVAL);
352 /* read LPC coefficients */
353 for (i = 0; i < pred_order; i++)
354 s->coeffs[i] = get_sr_golomb_shorten(&s->gb, LPCQUANT);
359 /* fixed LPC coeffs */
360 pred_order = command;
361 if (pred_order >= FF_ARRAY_ELEMS(fixed_coeffs)) {
362 av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n",
364 return AVERROR_INVALIDDATA;
366 coeffs = fixed_coeffs[pred_order];
370 /* subtract offset from previous samples to use in prediction */
371 if (command == FN_QLPC && coffset)
372 for (i = -pred_order; i < 0; i++)
373 s->decoded[channel][i] -= coffset;
375 /* decode residual and do LPC prediction */
376 init_sum = pred_order ? (command == FN_QLPC ? s->lpcqoffset : 0) : coffset;
377 for (i = 0; i < s->blocksize; i++) {
379 for (j = 0; j < pred_order; j++)
380 sum += coeffs[j] * s->decoded[channel][i - j - 1];
381 s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) +
385 /* add offset to current samples */
386 if (command == FN_QLPC && coffset)
387 for (i = 0; i < s->blocksize; i++)
388 s->decoded[channel][i] += coffset;
393 static int read_header(ShortenContext *s)
397 /* shorten signature */
398 if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {
399 av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
400 return AVERROR_INVALIDDATA;
404 s->blocksize = DEFAULT_BLOCK_SIZE;
406 s->version = get_bits(&s->gb, 8);
407 s->internal_ftype = get_uint(s, TYPESIZE);
409 s->channels = get_uint(s, CHANSIZE);
411 av_log(s->avctx, AV_LOG_ERROR, "No channels reported\n");
412 return AVERROR_INVALIDDATA;
414 if (s->channels > MAX_CHANNELS) {
415 av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
417 return AVERROR_INVALIDDATA;
419 s->avctx->channels = s->channels;
421 /* get blocksize if version > 0 */
422 if (s->version > 0) {
426 blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
427 if (!blocksize || blocksize > MAX_BLOCKSIZE) {
428 av_log(s->avctx, AV_LOG_ERROR,
429 "invalid or unsupported block size: %d\n",
431 return AVERROR(EINVAL);
433 s->blocksize = blocksize;
435 maxnlpc = get_uint(s, LPCQSIZE);
436 s->nmean = get_uint(s, 0);
438 skip_bytes = get_uint(s, NSKIPSIZE);
439 if ((unsigned)skip_bytes > get_bits_left(&s->gb)/8) {
440 av_log(s->avctx, AV_LOG_ERROR, "invalid skip_bytes: %d\n", skip_bytes);
441 return AVERROR_INVALIDDATA;
444 for (i = 0; i < skip_bytes; i++)
445 skip_bits(&s->gb, 8);
447 s->nwrap = FFMAX(NWRAP, maxnlpc);
449 if ((ret = allocate_buffers(s)) < 0)
452 if ((ret = init_offset(s)) < 0)
456 s->lpcqoffset = V2LPCQOFFSET;
458 if (s->avctx->extradata_size > 0)
461 if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
462 av_log(s->avctx, AV_LOG_ERROR,
463 "missing verbatim section at beginning of stream\n");
464 return AVERROR_INVALIDDATA;
467 s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
468 if (s->header_size >= OUT_BUFFER_SIZE ||
469 s->header_size < CANONICAL_HEADER_SIZE) {
470 av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n",
472 return AVERROR_INVALIDDATA;
475 for (i = 0; i < s->header_size; i++)
476 s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
478 if (AV_RL32(s->header) == MKTAG('R','I','F','F')) {
479 if ((ret = decode_wave_header(s->avctx, s->header, s->header_size)) < 0)
481 } else if (AV_RL32(s->header) == MKTAG('F','O','R','M')) {
482 if ((ret = decode_aiff_header(s->avctx, s->header, s->header_size)) < 0)
485 avpriv_report_missing_feature(s->avctx, "unsupported bit packing %X", AV_RL32(s->header));
486 return AVERROR_PATCHWELCOME;
498 static int shorten_decode_frame(AVCodecContext *avctx, void *data,
499 int *got_frame_ptr, AVPacket *avpkt)
501 AVFrame *frame = data;
502 const uint8_t *buf = avpkt->data;
503 int buf_size = avpkt->size;
504 ShortenContext *s = avctx->priv_data;
505 int i, input_buf_size = 0;
508 /* allocate internal bitstream buffer */
509 if (s->max_framesize == 0) {
511 s->max_framesize = 8192; // should hopefully be enough for the first header
512 tmp_ptr = av_fast_realloc(s->bitstream, &s->allocated_bitstream_size,
513 s->max_framesize + AV_INPUT_BUFFER_PADDING_SIZE);
515 s->max_framesize = 0;
516 av_log(avctx, AV_LOG_ERROR, "error allocating bitstream buffer\n");
517 return AVERROR(ENOMEM);
519 memset(tmp_ptr, 0, s->allocated_bitstream_size);
520 s->bitstream = tmp_ptr;
523 /* append current packet data to bitstream buffer */
524 buf_size = FFMIN(buf_size, s->max_framesize - s->bitstream_size);
525 input_buf_size = buf_size;
527 if (s->bitstream_index + s->bitstream_size + buf_size + AV_INPUT_BUFFER_PADDING_SIZE >
528 s->allocated_bitstream_size) {
529 memmove(s->bitstream, &s->bitstream[s->bitstream_index],
531 s->bitstream_index = 0;
534 memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size], buf,
536 buf = &s->bitstream[s->bitstream_index];
537 buf_size += s->bitstream_size;
538 s->bitstream_size = buf_size;
540 /* do not decode until buffer has at least max_framesize bytes or
541 * the end of the file has been reached */
542 if (buf_size < s->max_framesize && avpkt->data) {
544 return input_buf_size;
546 /* init and position bitstream reader */
547 if ((ret = init_get_bits8(&s->gb, buf, buf_size)) < 0)
549 skip_bits(&s->gb, s->bitindex);
551 /* process header or next subblock */
552 if (!s->got_header) {
554 if ((ret = read_header(s)) < 0)
561 max_framesize = FFMAX(s->max_framesize, s->blocksize * s->channels * 2);
562 tmp_ptr = av_fast_realloc(s->bitstream, &s->allocated_bitstream_size,
563 max_framesize + AV_INPUT_BUFFER_PADDING_SIZE);
565 av_log(avctx, AV_LOG_ERROR, "error allocating bitstream buffer\n");
566 return AVERROR(ENOMEM);
568 s->bitstream = tmp_ptr;
569 s->max_framesize = max_framesize;
575 /* if quit command was read previously, don't decode anything */
576 if (s->got_quit_command) {
582 while (s->cur_chan < s->channels) {
586 if (get_bits_left(&s->gb) < 3 + FNSIZE) {
591 cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
593 if (cmd > FN_VERBATIM) {
594 av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);
599 if (!is_audio_command[cmd]) {
600 /* process non-audio command */
603 len = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
605 get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
608 unsigned bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);
610 av_log(avctx, AV_LOG_ERROR, "bitshift %d is invalid\n",
612 return AVERROR_INVALIDDATA;
614 s->bitshift = bitshift;
618 unsigned blocksize = get_uint(s, av_log2(s->blocksize));
619 if (blocksize > s->blocksize) {
620 av_log(avctx, AV_LOG_ERROR,
621 "Increasing block size is not supported\n");
622 return AVERROR_PATCHWELCOME;
624 if (!blocksize || blocksize > MAX_BLOCKSIZE) {
625 av_log(avctx, AV_LOG_ERROR, "invalid or unsupported "
626 "block size: %d\n", blocksize);
627 return AVERROR(EINVAL);
629 s->blocksize = blocksize;
633 s->got_quit_command = 1;
639 /* process audio command */
640 int residual_size = 0;
641 int channel = s->cur_chan;
644 /* get Rice code for residual decoding */
645 if (cmd != FN_ZERO) {
646 residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);
647 /* This is a hack as version 0 differed in the definition
648 * of get_sr_golomb_shorten(). */
653 /* calculate sample offset using means from previous blocks */
655 coffset = s->offset[channel][0];
657 int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;
658 for (i = 0; i < s->nmean; i++)
659 sum += s->offset[channel][i];
660 coffset = sum / s->nmean;
662 coffset = s->bitshift == 0 ? coffset : coffset >> s->bitshift - 1 >> 1;
665 /* decode samples for this channel */
666 if (cmd == FN_ZERO) {
667 for (i = 0; i < s->blocksize; i++)
668 s->decoded[channel][i] = 0;
670 if ((ret = decode_subframe_lpc(s, cmd, channel,
671 residual_size, coffset)) < 0)
675 /* update means with info from the current block */
677 int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2;
678 for (i = 0; i < s->blocksize; i++)
679 sum += s->decoded[channel][i];
681 for (i = 1; i < s->nmean; i++)
682 s->offset[channel][i - 1] = s->offset[channel][i];
685 s->offset[channel][s->nmean - 1] = sum / s->blocksize;
687 s->offset[channel][s->nmean - 1] = s->bitshift == 32 ? 0 : (sum / s->blocksize) << s->bitshift;
690 /* copy wrap samples for use with next block */
691 for (i = -s->nwrap; i < 0; i++)
692 s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];
694 /* shift samples to add in unused zero bits which were removed
696 fix_bitshift(s, s->decoded[channel]);
698 /* if this is the last channel in the block, output the samples */
700 if (s->cur_chan == s->channels) {
702 int16_t *samples_s16;
705 /* get output buffer */
706 frame->nb_samples = s->blocksize;
707 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
710 for (chan = 0; chan < s->channels; chan++) {
711 samples_u8 = ((uint8_t **)frame->extended_data)[chan];
712 samples_s16 = ((int16_t **)frame->extended_data)[chan];
713 for (i = 0; i < s->blocksize; i++) {
714 switch (s->internal_ftype) {
716 *samples_u8++ = av_clip_uint8(s->decoded[chan][i]);
720 *samples_s16++ = av_clip_int16(s->decoded[chan][i]);
730 if (s->cur_chan < s->channels)
734 s->bitindex = get_bits_count(&s->gb) - 8 * (get_bits_count(&s->gb) / 8);
735 i = get_bits_count(&s->gb) / 8;
737 av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
738 s->bitstream_size = 0;
739 s->bitstream_index = 0;
740 return AVERROR_INVALIDDATA;
742 if (s->bitstream_size) {
743 s->bitstream_index += i;
744 s->bitstream_size -= i;
745 return input_buf_size;
750 static av_cold int shorten_decode_close(AVCodecContext *avctx)
752 ShortenContext *s = avctx->priv_data;
755 for (i = 0; i < s->channels; i++) {
756 s->decoded[i] = NULL;
757 av_freep(&s->decoded_base[i]);
758 av_freep(&s->offset[i]);
760 av_freep(&s->bitstream);
761 av_freep(&s->coeffs);
766 AVCodec ff_shorten_decoder = {
768 .long_name = NULL_IF_CONFIG_SMALL("Shorten"),
769 .type = AVMEDIA_TYPE_AUDIO,
770 .id = AV_CODEC_ID_SHORTEN,
771 .priv_data_size = sizeof(ShortenContext),
772 .init = shorten_decode_init,
773 .close = shorten_decode_close,
774 .decode = shorten_decode_frame,
775 .capabilities = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_DR1,
776 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
778 AV_SAMPLE_FMT_NONE },