shorten.c
Go to the documentation of this file.
1 /*
2  * Shorten decoder
3  * Copyright (c) 2005 Jeff Muizelaar
4  *
5  * This file is part of Libav.
6  *
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.
11  *
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.
16  *
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
20  */
21 
29 #include <limits.h>
30 #include "avcodec.h"
31 #include "bytestream.h"
32 #include "get_bits.h"
33 #include "golomb.h"
34 
35 #define MAX_CHANNELS 8
36 #define MAX_BLOCKSIZE 65535
37 
38 #define OUT_BUFFER_SIZE 16384
39 
40 #define ULONGSIZE 2
41 
42 #define WAVE_FORMAT_PCM 0x0001
43 
44 #define DEFAULT_BLOCK_SIZE 256
45 
46 #define TYPESIZE 4
47 #define CHANSIZE 0
48 #define LPCQSIZE 2
49 #define ENERGYSIZE 3
50 #define BITSHIFTSIZE 2
51 
52 #define TYPE_S16HL 3
53 #define TYPE_S16LH 5
54 
55 #define NWRAP 3
56 #define NSKIPSIZE 1
57 
58 #define LPCQUANT 5
59 #define V2LPCQOFFSET (1 << LPCQUANT)
60 
61 #define FNSIZE 2
62 #define FN_DIFF0 0
63 #define FN_DIFF1 1
64 #define FN_DIFF2 2
65 #define FN_DIFF3 3
66 #define FN_QUIT 4
67 #define FN_BLOCKSIZE 5
68 #define FN_BITSHIFT 6
69 #define FN_QLPC 7
70 #define FN_ZERO 8
71 #define FN_VERBATIM 9
72 
74 static const uint8_t is_audio_command[10] = { 1, 1, 1, 1, 0, 0, 0, 1, 1, 0 };
75 
76 #define VERBATIM_CKSIZE_SIZE 5
77 #define VERBATIM_BYTE_SIZE 8
78 #define CANONICAL_HEADER_SIZE 44
79 
80 typedef struct ShortenContext {
84 
86  unsigned channels;
87 
88  int32_t *decoded[MAX_CHANNELS];
90  int32_t *offset[MAX_CHANNELS];
91  int *coeffs;
92  uint8_t *bitstream;
98  int version;
99  int cur_chan;
100  int bitshift;
101  int nmean;
103  int nwrap;
105  int bitindex;
106  int32_t lpcqoffset;
110 
112 {
113  ShortenContext *s = avctx->priv_data;
114  s->avctx = avctx;
115  avctx->sample_fmt = AV_SAMPLE_FMT_S16;
116 
118  avctx->coded_frame = &s->frame;
119 
120  return 0;
121 }
122 
124 {
125  int i, chan;
126  int *coeffs;
127  void *tmp_ptr;
128 
129  for (chan = 0; chan < s->channels; chan++) {
130  if (FFMAX(1, s->nmean) >= UINT_MAX / sizeof(int32_t)) {
131  av_log(s->avctx, AV_LOG_ERROR, "nmean too large\n");
132  return AVERROR_INVALIDDATA;
133  }
134  if (s->blocksize + s->nwrap >= UINT_MAX / sizeof(int32_t) ||
135  s->blocksize + s->nwrap <= (unsigned)s->nwrap) {
137  "s->blocksize + s->nwrap too large\n");
138  return AVERROR_INVALIDDATA;
139  }
140 
141  tmp_ptr =
142  av_realloc(s->offset[chan], sizeof(int32_t) * FFMAX(1, s->nmean));
143  if (!tmp_ptr)
144  return AVERROR(ENOMEM);
145  s->offset[chan] = tmp_ptr;
146 
147  tmp_ptr = av_realloc(s->decoded_base[chan], (s->blocksize + s->nwrap) *
148  sizeof(s->decoded_base[0][0]));
149  if (!tmp_ptr)
150  return AVERROR(ENOMEM);
151  s->decoded_base[chan] = tmp_ptr;
152  for (i = 0; i < s->nwrap; i++)
153  s->decoded_base[chan][i] = 0;
154  s->decoded[chan] = s->decoded_base[chan] + s->nwrap;
155  }
156 
157  coeffs = av_realloc(s->coeffs, s->nwrap * sizeof(*s->coeffs));
158  if (!coeffs)
159  return AVERROR(ENOMEM);
160  s->coeffs = coeffs;
161 
162  return 0;
163 }
164 
165 static inline unsigned int get_uint(ShortenContext *s, int k)
166 {
167  if (s->version != 0)
169  return get_ur_golomb_shorten(&s->gb, k);
170 }
171 
172 static void fix_bitshift(ShortenContext *s, int32_t *buffer)
173 {
174  int i;
175 
176  if (s->bitshift != 0)
177  for (i = 0; i < s->blocksize; i++)
178  buffer[i] <<= s->bitshift;
179 }
180 
182 {
183  int32_t mean = 0;
184  int chan, i;
185  int nblock = FFMAX(1, s->nmean);
186  /* initialise offset */
187  switch (s->internal_ftype) {
188  case TYPE_S16HL:
189  case TYPE_S16LH:
190  mean = 0;
191  break;
192  default:
193  av_log(s->avctx, AV_LOG_ERROR, "unknown audio type");
194  return AVERROR_INVALIDDATA;
195  }
196 
197  for (chan = 0; chan < s->channels; chan++)
198  for (i = 0; i < nblock; i++)
199  s->offset[chan][i] = mean;
200  return 0;
201 }
202 
203 static int decode_wave_header(AVCodecContext *avctx, const uint8_t *header,
204  int header_size)
205 {
206  int len;
207  short wave_format;
208  GetByteContext gb;
209 
210  bytestream2_init(&gb, header, header_size);
211 
212  if (bytestream2_get_le32(&gb) != MKTAG('R', 'I', 'F', 'F')) {
213  av_log(avctx, AV_LOG_ERROR, "missing RIFF tag\n");
214  return AVERROR_INVALIDDATA;
215  }
216 
217  bytestream2_skip(&gb, 4); /* chunk size */
218 
219  if (bytestream2_get_le32(&gb) != MKTAG('W', 'A', 'V', 'E')) {
220  av_log(avctx, AV_LOG_ERROR, "missing WAVE tag\n");
221  return AVERROR_INVALIDDATA;
222  }
223 
224  while (bytestream2_get_le32(&gb) != MKTAG('f', 'm', 't', ' ')) {
225  len = bytestream2_get_le32(&gb);
226  bytestream2_skip(&gb, len);
227  if (bytestream2_get_bytes_left(&gb) < 16) {
228  av_log(avctx, AV_LOG_ERROR, "no fmt chunk found\n");
229  return AVERROR_INVALIDDATA;
230  }
231  }
232  len = bytestream2_get_le32(&gb);
233 
234  if (len < 16) {
235  av_log(avctx, AV_LOG_ERROR, "fmt chunk was too short\n");
236  return AVERROR_INVALIDDATA;
237  }
238 
239  wave_format = bytestream2_get_le16(&gb);
240 
241  switch (wave_format) {
242  case WAVE_FORMAT_PCM:
243  break;
244  default:
245  av_log(avctx, AV_LOG_ERROR, "unsupported wave format\n");
246  return AVERROR(ENOSYS);
247  }
248 
249  bytestream2_skip(&gb, 2); // skip channels (already got from shorten header)
250  avctx->sample_rate = bytestream2_get_le32(&gb);
251  bytestream2_skip(&gb, 4); // skip bit rate (represents original uncompressed bit rate)
252  bytestream2_skip(&gb, 2); // skip block align (not needed)
253  avctx->bits_per_coded_sample = bytestream2_get_le16(&gb);
254 
255  if (avctx->bits_per_coded_sample != 16) {
256  av_log(avctx, AV_LOG_ERROR, "unsupported number of bits per sample\n");
257  return AVERROR(ENOSYS);
258  }
259 
260  len -= 16;
261  if (len > 0)
262  av_log(avctx, AV_LOG_INFO, "%d header bytes unparsed\n", len);
263 
264  return 0;
265 }
266 
267 static void interleave_buffer(int16_t *samples, int nchan, int blocksize,
268  int32_t **buffer)
269 {
270  int i, chan;
271  for (i=0; i<blocksize; i++)
272  for (chan=0; chan < nchan; chan++)
273  *samples++ = av_clip_int16(buffer[chan][i]);
274 }
275 
276 static const int fixed_coeffs[3][3] = {
277  { 1, 0, 0 },
278  { 2, -1, 0 },
279  { 3, -3, 1 }
280 };
281 
282 static int decode_subframe_lpc(ShortenContext *s, int command, int channel,
283  int residual_size, int32_t coffset)
284 {
285  int pred_order, sum, qshift, init_sum, i, j;
286  const int *coeffs;
287 
288  if (command == FN_QLPC) {
289  /* read/validate prediction order */
290  pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
291  if (pred_order > s->nwrap) {
292  av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n",
293  pred_order);
294  return AVERROR(EINVAL);
295  }
296  /* read LPC coefficients */
297  for (i = 0; i < pred_order; i++)
298  s->coeffs[i] = get_sr_golomb_shorten(&s->gb, LPCQUANT);
299  coeffs = s->coeffs;
300 
301  qshift = LPCQUANT;
302  } else {
303  /* fixed LPC coeffs */
304  pred_order = command;
305  coeffs = fixed_coeffs[pred_order - 1];
306  qshift = 0;
307  }
308 
309  /* subtract offset from previous samples to use in prediction */
310  if (command == FN_QLPC && coffset)
311  for (i = -pred_order; i < 0; i++)
312  s->decoded[channel][i] -= coffset;
313 
314  /* decode residual and do LPC prediction */
315  init_sum = pred_order ? (command == FN_QLPC ? s->lpcqoffset : 0) : coffset;
316  for (i = 0; i < s->blocksize; i++) {
317  sum = init_sum;
318  for (j = 0; j < pred_order; j++)
319  sum += coeffs[j] * s->decoded[channel][i - j - 1];
320  s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) +
321  (sum >> qshift);
322  }
323 
324  /* add offset to current samples */
325  if (command == FN_QLPC && coffset)
326  for (i = 0; i < s->blocksize; i++)
327  s->decoded[channel][i] += coffset;
328 
329  return 0;
330 }
331 
333 {
334  int i, ret;
335  int maxnlpc = 0;
336  /* shorten signature */
337  if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {
338  av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
339  return AVERROR_INVALIDDATA;
340  }
341 
342  s->lpcqoffset = 0;
344  s->nmean = -1;
345  s->version = get_bits(&s->gb, 8);
347 
348  s->channels = get_uint(s, CHANSIZE);
349  if (!s->channels) {
350  av_log(s->avctx, AV_LOG_ERROR, "No channels reported\n");
351  return AVERROR_INVALIDDATA;
352  }
353  if (s->channels > MAX_CHANNELS) {
354  av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
355  s->channels = 0;
356  return AVERROR_INVALIDDATA;
357  }
358  s->avctx->channels = s->channels;
359 
360  /* get blocksize if version > 0 */
361  if (s->version > 0) {
362  int skip_bytes;
363  unsigned blocksize;
364 
365  blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
366  if (!blocksize || blocksize > MAX_BLOCKSIZE) {
368  "invalid or unsupported block size: %d\n",
369  blocksize);
370  return AVERROR(EINVAL);
371  }
372  s->blocksize = blocksize;
373 
374  maxnlpc = get_uint(s, LPCQSIZE);
375  s->nmean = get_uint(s, 0);
376 
377  skip_bytes = get_uint(s, NSKIPSIZE);
378  for (i = 0; i < skip_bytes; i++)
379  skip_bits(&s->gb, 8);
380  }
381  s->nwrap = FFMAX(NWRAP, maxnlpc);
382 
383  if ((ret = allocate_buffers(s)) < 0)
384  return ret;
385 
386  if ((ret = init_offset(s)) < 0)
387  return ret;
388 
389  if (s->version > 1)
391 
394  "missing verbatim section at beginning of stream\n");
395  return AVERROR_INVALIDDATA;
396  }
397 
399  if (s->header_size >= OUT_BUFFER_SIZE ||
401  av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n",
402  s->header_size);
403  return AVERROR_INVALIDDATA;
404  }
405 
406  for (i = 0; i < s->header_size; i++)
408 
409  if ((ret = decode_wave_header(s->avctx, s->header, s->header_size)) < 0)
410  return ret;
411 
412  s->cur_chan = 0;
413  s->bitshift = 0;
414 
415  s->got_header = 1;
416 
417  return 0;
418 }
419 
420 static int shorten_decode_frame(AVCodecContext *avctx, void *data,
421  int *got_frame_ptr, AVPacket *avpkt)
422 {
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;
427  int ret;
428 
429  /* allocate internal bitstream buffer */
430  if (s->max_framesize == 0) {
431  void *tmp_ptr;
432  s->max_framesize = 1024; // should hopefully be enough for the first header
435  if (!tmp_ptr) {
436  av_log(avctx, AV_LOG_ERROR, "error allocating bitstream buffer\n");
437  return AVERROR(ENOMEM);
438  }
439  s->bitstream = tmp_ptr;
440  }
441 
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;
446 
447  if (s->bitstream_index + s->bitstream_size + buf_size >
449  memmove(s->bitstream, &s->bitstream[s->bitstream_index],
450  s->bitstream_size);
451  s->bitstream_index = 0;
452  }
453  if (buf)
454  memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size], buf,
455  buf_size);
456  buf = &s->bitstream[s->bitstream_index];
457  buf_size += s->bitstream_size;
458  s->bitstream_size = buf_size;
459 
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) {
463  *got_frame_ptr = 0;
464  return input_buf_size;
465  }
466  }
467  /* init and position bitstream reader */
468  init_get_bits(&s->gb, buf, buf_size * 8);
469  skip_bits(&s->gb, s->bitindex);
470 
471  /* process header or next subblock */
472  if (!s->got_header) {
473  if ((ret = read_header(s)) < 0)
474  return ret;
475  *got_frame_ptr = 0;
476  goto finish_frame;
477  }
478 
479  /* if quit command was read previously, don't decode anything */
480  if (s->got_quit_command) {
481  *got_frame_ptr = 0;
482  return avpkt->size;
483  }
484 
485  s->cur_chan = 0;
486  while (s->cur_chan < s->channels) {
487  int cmd;
488  int len;
489 
490  if (get_bits_left(&s->gb) < 3 + FNSIZE) {
491  *got_frame_ptr = 0;
492  break;
493  }
494 
495  cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
496 
497  if (cmd > FN_VERBATIM) {
498  av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);
499  *got_frame_ptr = 0;
500  break;
501  }
502 
503  if (!is_audio_command[cmd]) {
504  /* process non-audio command */
505  switch (cmd) {
506  case FN_VERBATIM:
508  while (len--)
510  break;
511  case FN_BITSHIFT:
513  break;
514  case FN_BLOCKSIZE: {
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;
520  }
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);
525  }
526  s->blocksize = blocksize;
527  break;
528  }
529  case FN_QUIT:
530  s->got_quit_command = 1;
531  break;
532  }
533  if (cmd == FN_BLOCKSIZE || cmd == FN_QUIT) {
534  *got_frame_ptr = 0;
535  break;
536  }
537  } else {
538  /* process audio command */
539  int residual_size = 0;
540  int channel = s->cur_chan;
541  int32_t coffset;
542 
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 defintion of get_sr_golomb_shorten */
547  if (s->version == 0)
548  residual_size--;
549  }
550 
551  /* calculate sample offset using means from previous blocks */
552  if (s->nmean == 0)
553  coffset = s->offset[channel][0];
554  else {
555  int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;
556  for (i = 0; i < s->nmean; i++)
557  sum += s->offset[channel][i];
558  coffset = sum / s->nmean;
559  if (s->version >= 2)
560  coffset >>= FFMIN(1, s->bitshift);
561  }
562 
563  /* decode samples for this channel */
564  if (cmd == FN_ZERO) {
565  for (i = 0; i < s->blocksize; i++)
566  s->decoded[channel][i] = 0;
567  } else {
568  if ((ret = decode_subframe_lpc(s, cmd, channel,
569  residual_size, coffset)) < 0)
570  return ret;
571  }
572 
573  /* update means with info from the current block */
574  if (s->nmean > 0) {
575  int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2;
576  for (i = 0; i < s->blocksize; i++)
577  sum += s->decoded[channel][i];
578 
579  for (i = 1; i < s->nmean; i++)
580  s->offset[channel][i - 1] = s->offset[channel][i];
581 
582  if (s->version < 2)
583  s->offset[channel][s->nmean - 1] = sum / s->blocksize;
584  else
585  s->offset[channel][s->nmean - 1] = (sum / s->blocksize) << s->bitshift;
586  }
587 
588  /* copy wrap samples for use with next block */
589  for (i = -s->nwrap; i < 0; i++)
590  s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];
591 
592  /* shift samples to add in unused zero bits which were removed
593  * during encoding */
594  fix_bitshift(s, s->decoded[channel]);
595 
596  /* if this is the last channel in the block, output the samples */
597  s->cur_chan++;
598  if (s->cur_chan == s->channels) {
599  /* get output buffer */
600  s->frame.nb_samples = s->blocksize;
601  if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
602  av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
603  return ret;
604  }
605  /* interleave output */
606  interleave_buffer((int16_t *)s->frame.data[0], s->channels,
607  s->blocksize, s->decoded);
608 
609  *got_frame_ptr = 1;
610  *(AVFrame *)data = s->frame;
611  }
612  }
613  }
614  if (s->cur_chan < s->channels)
615  *got_frame_ptr = 0;
616 
618  s->bitindex = get_bits_count(&s->gb) - 8 * (get_bits_count(&s->gb) / 8);
619  i = get_bits_count(&s->gb) / 8;
620  if (i > buf_size) {
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;
625  }
626  if (s->bitstream_size) {
627  s->bitstream_index += i;
628  s->bitstream_size -= i;
629  return input_buf_size;
630  } else
631  return i;
632 }
633 
635 {
636  ShortenContext *s = avctx->priv_data;
637  int i;
638 
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]);
643  }
644  av_freep(&s->bitstream);
645  av_freep(&s->coeffs);
646 
647  return 0;
648 }
649 
651  .name = "shorten",
652  .type = AVMEDIA_TYPE_AUDIO,
653  .id = CODEC_ID_SHORTEN,
654  .priv_data_size = sizeof(ShortenContext),
658  .capabilities = CODEC_CAP_DELAY | CODEC_CAP_DR1,
659  .long_name= NULL_IF_CONFIG_SMALL("Shorten"),
660 };