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