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;
90 int min_framesize, max_framesize;
93 int32_t *decoded[MAX_CHANNELS];
94 int32_t *decoded_base[MAX_CHANNELS];
95 int32_t *offset[MAX_CHANNELS];
100 unsigned int allocated_bitstream_size;
102 uint8_t header[OUT_BUFFER_SIZE];
113 int got_quit_command;
116 static av_cold int shorten_decode_init(AVCodecContext * avctx)
118 ShortenContext *s = avctx->priv_data;
121 avcodec_get_frame_defaults(&s->frame);
122 avctx->coded_frame = &s->frame;
127 static int allocate_buffers(ShortenContext *s)
133 for (chan=0; chan<s->channels; chan++) {
134 if(FFMAX(1, s->nmean) >= UINT_MAX/sizeof(int32_t)){
135 av_log(s->avctx, AV_LOG_ERROR, "nmean too large\n");
136 return AVERROR_INVALIDDATA;
138 if(s->blocksize + s->nwrap >= UINT_MAX/sizeof(int32_t) || s->blocksize + s->nwrap <= (unsigned)s->nwrap){
139 av_log(s->avctx, AV_LOG_ERROR, "s->blocksize + s->nwrap too large\n");
140 return AVERROR_INVALIDDATA;
143 tmp_ptr = av_realloc(s->offset[chan], sizeof(int32_t)*FFMAX(1, s->nmean));
145 return AVERROR(ENOMEM);
146 s->offset[chan] = tmp_ptr;
148 tmp_ptr = av_realloc(s->decoded_base[chan], (s->blocksize + s->nwrap) *
149 sizeof(s->decoded_base[0][0]));
151 return AVERROR(ENOMEM);
152 s->decoded_base[chan] = tmp_ptr;
153 for (i=0; i<s->nwrap; i++)
154 s->decoded_base[chan][i] = 0;
155 s->decoded[chan] = s->decoded_base[chan] + s->nwrap;
158 coeffs = av_realloc(s->coeffs, s->nwrap * sizeof(*s->coeffs));
160 return AVERROR(ENOMEM);
167 static inline unsigned int get_uint(ShortenContext *s, int k)
170 k = get_ur_golomb_shorten(&s->gb, ULONGSIZE);
171 return get_ur_golomb_shorten(&s->gb, k);
175 static void fix_bitshift(ShortenContext *s, int32_t *buffer)
179 if (s->bitshift != 0)
180 for (i = 0; i < s->blocksize; i++)
181 buffer[i] <<= s->bitshift;
185 static int init_offset(ShortenContext *s)
189 int nblock = FFMAX(1, s->nmean);
190 /* initialise offset */
191 switch (s->internal_ftype)
194 s->avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
199 s->avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
202 av_log(s->avctx, AV_LOG_ERROR, "unknown audio type\n");
203 return AVERROR_PATCHWELCOME;
206 for (chan = 0; chan < s->channels; chan++)
207 for (i = 0; i < nblock; i++)
208 s->offset[chan][i] = mean;
212 static int decode_wave_header(AVCodecContext *avctx, const uint8_t *header,
217 const uint8_t *end= header + header_size;
219 if (bytestream_get_le32(&header) != MKTAG('R','I','F','F')) {
220 av_log(avctx, AV_LOG_ERROR, "missing RIFF tag\n");
221 return AVERROR_INVALIDDATA;
224 header += 4; /* chunk size */;
226 if (bytestream_get_le32(&header) != MKTAG('W','A','V','E')) {
227 av_log(avctx, AV_LOG_ERROR, "missing WAVE tag\n");
228 return AVERROR_INVALIDDATA;
231 while (bytestream_get_le32(&header) != MKTAG('f','m','t',' ')) {
232 len = bytestream_get_le32(&header);
233 if(len<0 || end - header - 8 < len)
234 return AVERROR_INVALIDDATA;
237 len = bytestream_get_le32(&header);
240 av_log(avctx, AV_LOG_ERROR, "fmt chunk was too short\n");
241 return AVERROR_INVALIDDATA;
244 wave_format = bytestream_get_le16(&header);
246 switch (wave_format) {
247 case WAVE_FORMAT_PCM:
250 av_log(avctx, AV_LOG_ERROR, "unsupported wave format\n");
251 return AVERROR_PATCHWELCOME;
254 header += 2; // skip channels (already got from shorten header)
255 avctx->sample_rate = bytestream_get_le32(&header);
256 header += 4; // skip bit rate (represents original uncompressed bit rate)
257 header += 2; // skip block align (not needed)
258 bps = bytestream_get_le16(&header);
259 avctx->bits_per_coded_sample = bps;
261 if (bps != 16 && bps != 8) {
262 av_log(avctx, AV_LOG_ERROR, "unsupported number of bits per sample: %d\n", bps);
263 return AVERROR_INVALIDDATA;
268 av_log(avctx, AV_LOG_INFO, "%d header bytes unparsed\n", len);
273 static const int fixed_coeffs[3][3] = {
279 static int decode_subframe_lpc(ShortenContext *s, int command, int channel,
280 int residual_size, int32_t coffset)
282 int pred_order, sum, qshift, init_sum, i, j;
285 if (command == FN_QLPC) {
286 /* read/validate prediction order */
287 pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
288 if (pred_order > s->nwrap) {
289 av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n", pred_order);
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) + (sum >> qshift);
319 /* add offset to current samples */
320 if (command == FN_QLPC && coffset)
321 for (i = 0; i < s->blocksize; i++)
322 s->decoded[channel][i] += coffset;
327 static int read_header(ShortenContext *s)
331 /* shorten signature */
332 if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {
333 av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
334 return AVERROR_INVALIDDATA;
338 s->blocksize = DEFAULT_BLOCK_SIZE;
340 s->version = get_bits(&s->gb, 8);
341 s->internal_ftype = get_uint(s, TYPESIZE);
343 s->channels = get_uint(s, CHANSIZE);
344 if (s->channels <= 0 || s->channels > MAX_CHANNELS) {
345 av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
346 return AVERROR_INVALIDDATA;
348 s->avctx->channels = s->channels;
350 /* get blocksize if version > 0 */
351 if (s->version > 0) {
352 int skip_bytes, blocksize;
354 blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
355 if (!blocksize || blocksize > MAX_BLOCKSIZE) {
356 av_log(s->avctx, AV_LOG_ERROR, "invalid or unsupported block size: %d\n",
358 return AVERROR(EINVAL);
360 s->blocksize = blocksize;
362 maxnlpc = get_uint(s, LPCQSIZE);
363 s->nmean = get_uint(s, 0);
365 skip_bytes = get_uint(s, NSKIPSIZE);
366 for (i=0; i<skip_bytes; i++) {
367 skip_bits(&s->gb, 8);
370 s->nwrap = FFMAX(NWRAP, maxnlpc);
372 if ((ret = allocate_buffers(s)) < 0)
375 if ((ret = init_offset(s)) < 0)
379 s->lpcqoffset = V2LPCQOFFSET;
381 if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
382 av_log(s->avctx, AV_LOG_ERROR, "missing verbatim section at beginning of stream\n");
383 return AVERROR_INVALIDDATA;
386 s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
387 if (s->header_size >= OUT_BUFFER_SIZE || s->header_size < CANONICAL_HEADER_SIZE) {
388 av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n", s->header_size);
389 return AVERROR_INVALIDDATA;
392 for (i=0; i<s->header_size; i++)
393 s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
395 if ((ret = decode_wave_header(s->avctx, s->header, s->header_size)) < 0)
406 static int shorten_decode_frame(AVCodecContext *avctx, void *data,
407 int *got_frame_ptr, AVPacket *avpkt)
409 const uint8_t *buf = avpkt->data;
410 int buf_size = avpkt->size;
411 ShortenContext *s = avctx->priv_data;
412 int i, input_buf_size = 0;
415 /* allocate internal bitstream buffer */
416 if(s->max_framesize == 0){
418 s->max_framesize= 8192; // should hopefully be enough for the first header
419 tmp_ptr = av_fast_realloc(s->bitstream, &s->allocated_bitstream_size,
422 av_log(avctx, AV_LOG_ERROR, "error allocating bitstream buffer\n");
423 return AVERROR(ENOMEM);
425 s->bitstream = tmp_ptr;
428 /* append current packet data to bitstream buffer */
429 if(1 && s->max_framesize){//FIXME truncated
430 buf_size= FFMIN(buf_size, s->max_framesize - s->bitstream_size);
431 input_buf_size= buf_size;
433 if(s->bitstream_index + s->bitstream_size + buf_size > s->allocated_bitstream_size){
434 memmove(s->bitstream, &s->bitstream[s->bitstream_index], s->bitstream_size);
435 s->bitstream_index=0;
438 memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size], buf, buf_size);
439 buf= &s->bitstream[s->bitstream_index];
440 buf_size += s->bitstream_size;
441 s->bitstream_size= buf_size;
443 /* do not decode until buffer has at least max_framesize bytes or
444 the end of the file has been reached */
445 if (buf_size < s->max_framesize && avpkt->data) {
447 return input_buf_size;
450 /* init and position bitstream reader */
451 init_get_bits(&s->gb, buf, buf_size*8);
452 skip_bits(&s->gb, s->bitindex);
454 /* process header or next subblock */
455 if (!s->got_header) {
456 if ((ret = read_header(s)) < 0)
462 /* if quit command was read previously, don't decode anything */
463 if (s->got_quit_command) {
469 while (s->cur_chan < s->channels) {
473 if (get_bits_left(&s->gb) < 3+FNSIZE) {
478 cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
480 if (cmd > FN_VERBATIM) {
481 av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);
486 if (!is_audio_command[cmd]) {
487 /* process non-audio command */
490 len = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
492 get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
496 s->bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);
499 int blocksize = get_uint(s, av_log2(s->blocksize));
500 if (blocksize > s->blocksize) {
501 av_log(avctx, AV_LOG_ERROR, "Increasing block size is not supported\n");
502 return AVERROR_PATCHWELCOME;
504 if (!blocksize || blocksize > MAX_BLOCKSIZE) {
505 av_log(avctx, AV_LOG_ERROR, "invalid or unsupported "
506 "block size: %d\n", blocksize);
507 return AVERROR(EINVAL);
509 s->blocksize = blocksize;
513 s->got_quit_command = 1;
516 if (cmd == FN_BLOCKSIZE || cmd == FN_QUIT) {
521 /* process audio command */
522 int residual_size = 0;
523 int channel = s->cur_chan;
526 /* get Rice code for residual decoding */
527 if (cmd != FN_ZERO) {
528 residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);
529 /* This is a hack as version 0 differed in the definition
530 * of get_sr_golomb_shorten(). */
535 /* calculate sample offset using means from previous blocks */
537 coffset = s->offset[channel][0];
539 int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;
540 for (i=0; i<s->nmean; i++)
541 sum += s->offset[channel][i];
542 coffset = sum / s->nmean;
544 coffset = s->bitshift == 0 ? coffset : coffset >> s->bitshift - 1 >> 1;
547 /* decode samples for this channel */
548 if (cmd == FN_ZERO) {
549 for (i=0; i<s->blocksize; i++)
550 s->decoded[channel][i] = 0;
552 if ((ret = decode_subframe_lpc(s, cmd, channel, residual_size, coffset)) < 0)
556 /* update means with info from the current block */
558 int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2;
559 for (i=0; i<s->blocksize; i++)
560 sum += s->decoded[channel][i];
562 for (i=1; i<s->nmean; i++)
563 s->offset[channel][i-1] = s->offset[channel][i];
566 s->offset[channel][s->nmean - 1] = sum / s->blocksize;
568 s->offset[channel][s->nmean - 1] = (sum / s->blocksize) << s->bitshift;
571 /* copy wrap samples for use with next block */
572 for (i=-s->nwrap; i<0; i++)
573 s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];
575 /* shift samples to add in unused zero bits which were removed
577 fix_bitshift(s, s->decoded[channel]);
579 /* if this is the last channel in the block, output the samples */
581 if (s->cur_chan == s->channels) {
583 int16_t *samples_s16;
586 /* get output buffer */
587 s->frame.nb_samples = s->blocksize;
588 if ((ret = ff_get_buffer(avctx, &s->frame)) < 0) {
589 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
593 for (chan = 0; chan < s->channels; chan++) {
594 samples_u8 = ((uint8_t **)s->frame.extended_data)[chan];
595 samples_s16 = ((int16_t **)s->frame.extended_data)[chan];
596 for (i = 0; i < s->blocksize; i++) {
597 switch (s->internal_ftype) {
599 *samples_u8++ = av_clip_uint8(s->decoded[chan][i]);
603 *samples_s16++ = av_clip_int16(s->decoded[chan][i]);
611 *(AVFrame *)data = s->frame;
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);
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 .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 .long_name = NULL_IF_CONFIG_SMALL("Shorten"),
661 .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
663 AV_SAMPLE_FMT_NONE },