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"
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 *offset[MAX_CHANNELS];
93 unsigned int allocated_bitstream_size;
95 uint8_t header[OUT_BUFFER_SIZE];
106 int got_quit_command;
109 static av_cold int shorten_decode_init(AVCodecContext * avctx)
111 ShortenContext *s = avctx->priv_data;
113 avctx->sample_fmt = AV_SAMPLE_FMT_S16;
118 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");
129 if(s->blocksize + s->nwrap >= UINT_MAX/sizeof(int32_t) || s->blocksize + s->nwrap <= (unsigned)s->nwrap){
130 av_log(s->avctx, AV_LOG_ERROR, "s->blocksize + s->nwrap too large\n");
134 tmp_ptr = av_realloc(s->offset[chan], sizeof(int32_t)*FFMAX(1, s->nmean));
136 return AVERROR(ENOMEM);
137 s->offset[chan] = tmp_ptr;
139 tmp_ptr = av_realloc(s->decoded[chan], sizeof(int32_t)*(s->blocksize + s->nwrap));
141 return AVERROR(ENOMEM);
142 s->decoded[chan] = tmp_ptr;
143 for (i=0; i<s->nwrap; i++)
144 s->decoded[chan][i] = 0;
145 s->decoded[chan] += s->nwrap;
148 coeffs = av_realloc(s->coeffs, s->nwrap * sizeof(*s->coeffs));
150 return AVERROR(ENOMEM);
157 static inline unsigned int get_uint(ShortenContext *s, int k)
160 k = get_ur_golomb_shorten(&s->gb, ULONGSIZE);
161 return get_ur_golomb_shorten(&s->gb, k);
165 static void fix_bitshift(ShortenContext *s, int32_t *buffer)
169 if (s->bitshift != 0)
170 for (i = 0; i < s->blocksize; i++)
171 buffer[i] <<= s->bitshift;
175 static void init_offset(ShortenContext *s)
179 int nblock = FFMAX(1, s->nmean);
180 /* initialise offset */
181 switch (s->internal_ftype)
188 av_log(s->avctx, AV_LOG_ERROR, "unknown audio type");
192 for (chan = 0; chan < s->channels; chan++)
193 for (i = 0; i < nblock; i++)
194 s->offset[chan][i] = mean;
197 static int decode_wave_header(AVCodecContext *avctx, const uint8_t *header,
204 if (bytestream_get_le32(&header) != MKTAG('R','I','F','F')) {
205 av_log(avctx, AV_LOG_ERROR, "missing RIFF tag\n");
209 header += 4; /* chunk size */;
211 if (bytestream_get_le32(&header) != MKTAG('W','A','V','E')) {
212 av_log(avctx, AV_LOG_ERROR, "missing WAVE tag\n");
216 while (bytestream_get_le32(&header) != MKTAG('f','m','t',' ')) {
217 len = bytestream_get_le32(&header);
220 len = bytestream_get_le32(&header);
223 av_log(avctx, AV_LOG_ERROR, "fmt chunk was too short\n");
227 wave_format = bytestream_get_le16(&header);
229 switch (wave_format) {
230 case WAVE_FORMAT_PCM:
233 av_log(avctx, AV_LOG_ERROR, "unsupported wave format\n");
237 header += 2; // skip channels (already got from shorten header)
238 avctx->sample_rate = bytestream_get_le32(&header);
239 header += 4; // skip bit rate (represents original uncompressed bit rate)
240 header += 2; // skip block align (not needed)
241 avctx->bits_per_coded_sample = bytestream_get_le16(&header);
243 if (avctx->bits_per_coded_sample != 16) {
244 av_log(avctx, AV_LOG_ERROR, "unsupported number of bits per sample\n");
250 av_log(avctx, AV_LOG_INFO, "%d header bytes unparsed\n", len);
255 static void interleave_buffer(int16_t *samples, int nchan, int blocksize,
259 for (i=0; i<blocksize; i++)
260 for (chan=0; chan < nchan; chan++)
261 *samples++ = av_clip_int16(buffer[chan][i]);
264 static const int fixed_coeffs[3][3] = {
270 static int decode_subframe_lpc(ShortenContext *s, int command, int channel,
271 int residual_size, int32_t coffset)
273 int pred_order, sum, qshift, init_sum, i, j;
276 if (command == FN_QLPC) {
277 /* read/validate prediction order */
278 pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
279 if (pred_order > s->nwrap) {
280 av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n", pred_order);
281 return AVERROR(EINVAL);
283 /* read LPC coefficients */
284 for (i=0; i<pred_order; i++)
285 s->coeffs[i] = get_sr_golomb_shorten(&s->gb, LPCQUANT);
290 /* fixed LPC coeffs */
291 pred_order = command;
292 coeffs = fixed_coeffs[pred_order-1];
296 /* subtract offset from previous samples to use in prediction */
297 if (command == FN_QLPC && coffset)
298 for (i = -pred_order; i < 0; i++)
299 s->decoded[channel][i] -= coffset;
301 /* decode residual and do LPC prediction */
302 init_sum = pred_order ? (command == FN_QLPC ? s->lpcqoffset : 0) : coffset;
303 for (i=0; i < s->blocksize; i++) {
305 for (j=0; j<pred_order; j++)
306 sum += coeffs[j] * s->decoded[channel][i-j-1];
307 s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + (sum >> qshift);
310 /* add offset to current samples */
311 if (command == FN_QLPC && coffset)
312 for (i = 0; i < s->blocksize; i++)
313 s->decoded[channel][i] += coffset;
318 static int read_header(ShortenContext *s)
322 /* shorten signature */
323 if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {
324 av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
329 s->blocksize = DEFAULT_BLOCK_SIZE;
332 s->version = get_bits(&s->gb, 8);
333 s->internal_ftype = get_uint(s, TYPESIZE);
335 s->channels = get_uint(s, CHANSIZE);
336 if (s->channels > MAX_CHANNELS) {
337 av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
340 s->avctx->channels = s->channels;
342 /* get blocksize if version > 0 */
343 if (s->version > 0) {
344 int skip_bytes, blocksize;
346 blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
347 if (!blocksize || blocksize > MAX_BLOCKSIZE) {
348 av_log(s->avctx, AV_LOG_ERROR, "invalid or unsupported block size: %d\n",
350 return AVERROR(EINVAL);
352 s->blocksize = blocksize;
354 maxnlpc = get_uint(s, LPCQSIZE);
355 s->nmean = get_uint(s, 0);
357 skip_bytes = get_uint(s, NSKIPSIZE);
358 for (i=0; i<skip_bytes; i++) {
359 skip_bits(&s->gb, 8);
362 s->nwrap = FFMAX(NWRAP, maxnlpc);
364 if ((ret = allocate_buffers(s)) < 0)
370 s->lpcqoffset = V2LPCQOFFSET;
372 if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
373 av_log(s->avctx, AV_LOG_ERROR, "missing verbatim section at beginning of stream\n");
377 s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
378 if (s->header_size >= OUT_BUFFER_SIZE || s->header_size < CANONICAL_HEADER_SIZE) {
379 av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n", s->header_size);
383 for (i=0; i<s->header_size; i++)
384 s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
386 if (decode_wave_header(s->avctx, s->header, s->header_size) < 0)
397 static int shorten_decode_frame(AVCodecContext *avctx,
398 void *data, int *data_size,
401 const uint8_t *buf = avpkt->data;
402 int buf_size = avpkt->size;
403 ShortenContext *s = avctx->priv_data;
404 int i, input_buf_size = 0;
405 int16_t *samples = data;
408 /* allocate internal bitstream buffer */
409 if(s->max_framesize == 0){
411 s->max_framesize= 1024; // should hopefully be enough for the first header
412 tmp_ptr = av_fast_realloc(s->bitstream, &s->allocated_bitstream_size,
415 av_log(avctx, AV_LOG_ERROR, "error allocating bitstream buffer\n");
416 return AVERROR(ENOMEM);
418 s->bitstream = tmp_ptr;
421 /* append current packet data to bitstream buffer */
422 if(1 && s->max_framesize){//FIXME truncated
423 buf_size= FFMIN(buf_size, s->max_framesize - s->bitstream_size);
424 input_buf_size= buf_size;
426 if(s->bitstream_index + s->bitstream_size + buf_size > s->allocated_bitstream_size){
427 memmove(s->bitstream, &s->bitstream[s->bitstream_index], s->bitstream_size);
428 s->bitstream_index=0;
431 memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size], buf, buf_size);
432 buf= &s->bitstream[s->bitstream_index];
433 buf_size += s->bitstream_size;
434 s->bitstream_size= buf_size;
436 /* do not decode until buffer has at least max_framesize bytes or
437 the end of the file has been reached */
438 if (buf_size < s->max_framesize && avpkt->data) {
440 return input_buf_size;
443 /* init and position bitstream reader */
444 init_get_bits(&s->gb, buf, buf_size*8);
445 skip_bits(&s->gb, s->bitindex);
447 /* process header or next subblock */
448 if (!s->got_header) {
449 if ((ret = read_header(s)) < 0)
455 /* if quit command was read previously, don't decode anything */
456 if (s->got_quit_command) {
462 while (s->cur_chan < s->channels) {
466 if (get_bits_left(&s->gb) < 3+FNSIZE) {
471 cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
473 if (cmd > FN_VERBATIM) {
474 av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);
479 if (!is_audio_command[cmd]) {
480 /* process non-audio command */
483 len = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
485 get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
489 s->bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);
492 int blocksize = get_uint(s, av_log2(s->blocksize));
493 if (blocksize > s->blocksize) {
494 av_log(avctx, AV_LOG_ERROR, "Increasing block size is not supported\n");
495 return AVERROR_PATCHWELCOME;
497 if (!blocksize || blocksize > MAX_BLOCKSIZE) {
498 av_log(avctx, AV_LOG_ERROR, "invalid or unsupported "
499 "block size: %d\n", blocksize);
500 return AVERROR(EINVAL);
502 s->blocksize = blocksize;
506 s->got_quit_command = 1;
509 if (cmd == FN_BLOCKSIZE || cmd == FN_QUIT) {
514 /* process audio command */
515 int residual_size = 0;
516 int channel = s->cur_chan;
519 /* get Rice code for residual decoding */
520 if (cmd != FN_ZERO) {
521 residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);
522 /* this is a hack as version 0 differed in defintion of get_sr_golomb_shorten */
527 /* calculate sample offset using means from previous blocks */
529 coffset = s->offset[channel][0];
531 int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;
532 for (i=0; i<s->nmean; i++)
533 sum += s->offset[channel][i];
534 coffset = sum / s->nmean;
536 coffset >>= FFMIN(1, s->bitshift);
539 /* decode samples for this channel */
540 if (cmd == FN_ZERO) {
541 for (i=0; i<s->blocksize; i++)
542 s->decoded[channel][i] = 0;
544 if ((ret = decode_subframe_lpc(s, cmd, channel, residual_size, coffset)) < 0)
548 /* update means with info from the current block */
550 int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2;
551 for (i=0; i<s->blocksize; i++)
552 sum += s->decoded[channel][i];
554 for (i=1; i<s->nmean; i++)
555 s->offset[channel][i-1] = s->offset[channel][i];
558 s->offset[channel][s->nmean - 1] = sum / s->blocksize;
560 s->offset[channel][s->nmean - 1] = (sum / s->blocksize) << s->bitshift;
563 /* copy wrap samples for use with next block */
564 for (i=-s->nwrap; i<0; i++)
565 s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];
567 /* shift samples to add in unused zero bits which were removed
569 fix_bitshift(s, s->decoded[channel]);
571 /* if this is the last channel in the block, output the samples */
573 if (s->cur_chan == s->channels) {
574 int out_size = s->blocksize * s->channels *
575 av_get_bytes_per_sample(avctx->sample_fmt);
576 if (*data_size < out_size) {
577 av_log(avctx, AV_LOG_ERROR, "Output buffer is too small\n");
578 return AVERROR(EINVAL);
580 interleave_buffer(samples, s->channels, s->blocksize, s->decoded);
581 *data_size = out_size;
585 if (s->cur_chan < s->channels)
589 s->bitindex = get_bits_count(&s->gb) - 8*((get_bits_count(&s->gb))/8);
590 i= (get_bits_count(&s->gb))/8;
592 av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
594 s->bitstream_index=0;
597 if (s->bitstream_size) {
598 s->bitstream_index += i;
599 s->bitstream_size -= i;
600 return input_buf_size;
605 static av_cold int shorten_decode_close(AVCodecContext *avctx)
607 ShortenContext *s = avctx->priv_data;
610 for (i = 0; i < s->channels; i++) {
611 s->decoded[i] -= s->nwrap;
612 av_freep(&s->decoded[i]);
613 av_freep(&s->offset[i]);
615 av_freep(&s->bitstream);
616 av_freep(&s->coeffs);
620 AVCodec ff_shorten_decoder = {
622 .type = AVMEDIA_TYPE_AUDIO,
623 .id = CODEC_ID_SHORTEN,
624 .priv_data_size = sizeof(ShortenContext),
625 .init = shorten_decode_init,
626 .close = shorten_decode_close,
627 .decode = shorten_decode_frame,
628 .capabilities = CODEC_CAP_DELAY,
629 .long_name= NULL_IF_CONFIG_SMALL("Shorten"),