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 #include "internal.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 
92  int *coeffs;
99  int version;
100  int cur_chan;
101  int bitshift;
102  int nmean;
104  int nwrap;
106  int bitindex;
111 
113 {
114  ShortenContext *s = avctx->priv_data;
115  s->avctx = avctx;
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 
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 output_buffer(int16_t **samples, int nchan, int blocksize,
269  int32_t **buffer)
270 {
271  int i, ch;
272  for (ch = 0; ch < nchan; ch++) {
273  int32_t *in = buffer[ch];
274  int16_t *out = samples[ch];
275  for (i = 0; i < blocksize; i++)
276  out[i] = av_clip_int16(in[i]);
277  }
278 }
279 
280 static const int fixed_coeffs[][3] = {
281  { 0, 0, 0 },
282  { 1, 0, 0 },
283  { 2, -1, 0 },
284  { 3, -3, 1 }
285 };
286 
287 static int decode_subframe_lpc(ShortenContext *s, int command, int channel,
288  int residual_size, int32_t coffset)
289 {
290  int pred_order, sum, qshift, init_sum, i, j;
291  const int *coeffs;
292 
293  if (command == FN_QLPC) {
294  /* read/validate prediction order */
295  pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
296  if (pred_order > s->nwrap) {
297  av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n",
298  pred_order);
299  return AVERROR(EINVAL);
300  }
301  /* read LPC coefficients */
302  for (i = 0; i < pred_order; i++)
303  s->coeffs[i] = get_sr_golomb_shorten(&s->gb, LPCQUANT);
304  coeffs = s->coeffs;
305 
306  qshift = LPCQUANT;
307  } else {
308  /* fixed LPC coeffs */
309  pred_order = command;
310  if (pred_order >= FF_ARRAY_ELEMS(fixed_coeffs)) {
311  av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n",
312  pred_order);
313  return AVERROR_INVALIDDATA;
314  }
315  coeffs = fixed_coeffs[pred_order];
316  qshift = 0;
317  }
318 
319  /* subtract offset from previous samples to use in prediction */
320  if (command == FN_QLPC && coffset)
321  for (i = -pred_order; i < 0; i++)
322  s->decoded[channel][i] -= coffset;
323 
324  /* decode residual and do LPC prediction */
325  init_sum = pred_order ? (command == FN_QLPC ? s->lpcqoffset : 0) : coffset;
326  for (i = 0; i < s->blocksize; i++) {
327  sum = init_sum;
328  for (j = 0; j < pred_order; j++)
329  sum += coeffs[j] * s->decoded[channel][i - j - 1];
330  s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) +
331  (sum >> qshift);
332  }
333 
334  /* add offset to current samples */
335  if (command == FN_QLPC && coffset)
336  for (i = 0; i < s->blocksize; i++)
337  s->decoded[channel][i] += coffset;
338 
339  return 0;
340 }
341 
343 {
344  int i, ret;
345  int maxnlpc = 0;
346  /* shorten signature */
347  if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {
348  av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
349  return AVERROR_INVALIDDATA;
350  }
351 
352  s->lpcqoffset = 0;
354  s->nmean = -1;
355  s->version = get_bits(&s->gb, 8);
357 
358  s->channels = get_uint(s, CHANSIZE);
359  if (!s->channels) {
360  av_log(s->avctx, AV_LOG_ERROR, "No channels reported\n");
361  return AVERROR_INVALIDDATA;
362  }
363  if (s->channels > MAX_CHANNELS) {
364  av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
365  s->channels = 0;
366  return AVERROR_INVALIDDATA;
367  }
368  s->avctx->channels = s->channels;
369 
370  /* get blocksize if version > 0 */
371  if (s->version > 0) {
372  int skip_bytes;
373  unsigned blocksize;
374 
375  blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
376  if (!blocksize || blocksize > MAX_BLOCKSIZE) {
378  "invalid or unsupported block size: %d\n",
379  blocksize);
380  return AVERROR(EINVAL);
381  }
382  s->blocksize = blocksize;
383 
384  maxnlpc = get_uint(s, LPCQSIZE);
385  s->nmean = get_uint(s, 0);
386 
387  skip_bytes = get_uint(s, NSKIPSIZE);
388  for (i = 0; i < skip_bytes; i++)
389  skip_bits(&s->gb, 8);
390  }
391  s->nwrap = FFMAX(NWRAP, maxnlpc);
392 
393  if ((ret = allocate_buffers(s)) < 0)
394  return ret;
395 
396  if ((ret = init_offset(s)) < 0)
397  return ret;
398 
399  if (s->version > 1)
401 
404  "missing verbatim section at beginning of stream\n");
405  return AVERROR_INVALIDDATA;
406  }
407 
409  if (s->header_size >= OUT_BUFFER_SIZE ||
411  av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n",
412  s->header_size);
413  return AVERROR_INVALIDDATA;
414  }
415 
416  for (i = 0; i < s->header_size; i++)
418 
419  if ((ret = decode_wave_header(s->avctx, s->header, s->header_size)) < 0)
420  return ret;
421 
422  s->cur_chan = 0;
423  s->bitshift = 0;
424 
425  s->got_header = 1;
426 
427  return 0;
428 }
429 
430 static int shorten_decode_frame(AVCodecContext *avctx, void *data,
431  int *got_frame_ptr, AVPacket *avpkt)
432 {
433  const uint8_t *buf = avpkt->data;
434  int buf_size = avpkt->size;
435  ShortenContext *s = avctx->priv_data;
436  int i, input_buf_size = 0;
437  int ret;
438 
439  /* allocate internal bitstream buffer */
440  if (s->max_framesize == 0) {
441  void *tmp_ptr;
442  s->max_framesize = 1024; // should hopefully be enough for the first header
445  if (!tmp_ptr) {
446  av_log(avctx, AV_LOG_ERROR, "error allocating bitstream buffer\n");
447  return AVERROR(ENOMEM);
448  }
449  s->bitstream = tmp_ptr;
450  }
451 
452  /* append current packet data to bitstream buffer */
453  if (1 && s->max_framesize) { //FIXME truncated
454  buf_size = FFMIN(buf_size, s->max_framesize - s->bitstream_size);
455  input_buf_size = buf_size;
456 
457  if (s->bitstream_index + s->bitstream_size + buf_size >
459  memmove(s->bitstream, &s->bitstream[s->bitstream_index],
460  s->bitstream_size);
461  s->bitstream_index = 0;
462  }
463  if (buf)
464  memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size], buf,
465  buf_size);
466  buf = &s->bitstream[s->bitstream_index];
467  buf_size += s->bitstream_size;
468  s->bitstream_size = buf_size;
469 
470  /* do not decode until buffer has at least max_framesize bytes or
471  * the end of the file has been reached */
472  if (buf_size < s->max_framesize && avpkt->data) {
473  *got_frame_ptr = 0;
474  return input_buf_size;
475  }
476  }
477  /* init and position bitstream reader */
478  init_get_bits(&s->gb, buf, buf_size * 8);
479  skip_bits(&s->gb, s->bitindex);
480 
481  /* process header or next subblock */
482  if (!s->got_header) {
483  if ((ret = read_header(s)) < 0)
484  return ret;
485  *got_frame_ptr = 0;
486  goto finish_frame;
487  }
488 
489  /* if quit command was read previously, don't decode anything */
490  if (s->got_quit_command) {
491  *got_frame_ptr = 0;
492  return avpkt->size;
493  }
494 
495  s->cur_chan = 0;
496  while (s->cur_chan < s->channels) {
497  int cmd;
498  int len;
499 
500  if (get_bits_left(&s->gb) < 3 + FNSIZE) {
501  *got_frame_ptr = 0;
502  break;
503  }
504 
505  cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
506 
507  if (cmd > FN_VERBATIM) {
508  av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);
509  *got_frame_ptr = 0;
510  break;
511  }
512 
513  if (!is_audio_command[cmd]) {
514  /* process non-audio command */
515  switch (cmd) {
516  case FN_VERBATIM:
518  while (len--)
520  break;
521  case FN_BITSHIFT:
523  break;
524  case FN_BLOCKSIZE: {
525  unsigned blocksize = get_uint(s, av_log2(s->blocksize));
526  if (blocksize > s->blocksize) {
527  av_log(avctx, AV_LOG_ERROR,
528  "Increasing block size is not supported\n");
529  return AVERROR_PATCHWELCOME;
530  }
531  if (!blocksize || blocksize > MAX_BLOCKSIZE) {
532  av_log(avctx, AV_LOG_ERROR, "invalid or unsupported "
533  "block size: %d\n", blocksize);
534  return AVERROR(EINVAL);
535  }
536  s->blocksize = blocksize;
537  break;
538  }
539  case FN_QUIT:
540  s->got_quit_command = 1;
541  break;
542  }
543  if (cmd == FN_BLOCKSIZE || cmd == FN_QUIT) {
544  *got_frame_ptr = 0;
545  break;
546  }
547  } else {
548  /* process audio command */
549  int residual_size = 0;
550  int channel = s->cur_chan;
551  int32_t coffset;
552 
553  /* get Rice code for residual decoding */
554  if (cmd != FN_ZERO) {
555  residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);
556  /* This is a hack as version 0 differed in the definition
557  * of get_sr_golomb_shorten(). */
558  if (s->version == 0)
559  residual_size--;
560  }
561 
562  /* calculate sample offset using means from previous blocks */
563  if (s->nmean == 0)
564  coffset = s->offset[channel][0];
565  else {
566  int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;
567  for (i = 0; i < s->nmean; i++)
568  sum += s->offset[channel][i];
569  coffset = sum / s->nmean;
570  if (s->version >= 2)
571  coffset >>= FFMIN(1, s->bitshift);
572  }
573 
574  /* decode samples for this channel */
575  if (cmd == FN_ZERO) {
576  for (i = 0; i < s->blocksize; i++)
577  s->decoded[channel][i] = 0;
578  } else {
579  if ((ret = decode_subframe_lpc(s, cmd, channel,
580  residual_size, coffset)) < 0)
581  return ret;
582  }
583 
584  /* update means with info from the current block */
585  if (s->nmean > 0) {
586  int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2;
587  for (i = 0; i < s->blocksize; i++)
588  sum += s->decoded[channel][i];
589 
590  for (i = 1; i < s->nmean; i++)
591  s->offset[channel][i - 1] = s->offset[channel][i];
592 
593  if (s->version < 2)
594  s->offset[channel][s->nmean - 1] = sum / s->blocksize;
595  else
596  s->offset[channel][s->nmean - 1] = (sum / s->blocksize) << s->bitshift;
597  }
598 
599  /* copy wrap samples for use with next block */
600  for (i = -s->nwrap; i < 0; i++)
601  s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];
602 
603  /* shift samples to add in unused zero bits which were removed
604  * during encoding */
605  fix_bitshift(s, s->decoded[channel]);
606 
607  /* if this is the last channel in the block, output the samples */
608  s->cur_chan++;
609  if (s->cur_chan == s->channels) {
610  /* get output buffer */
611  s->frame.nb_samples = s->blocksize;
612  if ((ret = ff_get_buffer(avctx, &s->frame)) < 0) {
613  av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
614  return ret;
615  }
616  /* interleave output */
617  output_buffer((int16_t **)s->frame.extended_data, s->channels,
618  s->blocksize, s->decoded);
619 
620  *got_frame_ptr = 1;
621  *(AVFrame *)data = s->frame;
622  }
623  }
624  }
625  if (s->cur_chan < s->channels)
626  *got_frame_ptr = 0;
627 
629  s->bitindex = get_bits_count(&s->gb) - 8 * (get_bits_count(&s->gb) / 8);
630  i = get_bits_count(&s->gb) / 8;
631  if (i > buf_size) {
632  av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
633  s->bitstream_size = 0;
634  s->bitstream_index = 0;
635  return AVERROR_INVALIDDATA;
636  }
637  if (s->bitstream_size) {
638  s->bitstream_index += i;
639  s->bitstream_size -= i;
640  return input_buf_size;
641  } else
642  return i;
643 }
644 
646 {
647  ShortenContext *s = avctx->priv_data;
648  int i;
649 
650  for (i = 0; i < s->channels; i++) {
651  s->decoded[i] = NULL;
652  av_freep(&s->decoded_base[i]);
653  av_freep(&s->offset[i]);
654  }
655  av_freep(&s->bitstream);
656  av_freep(&s->coeffs);
657 
658  return 0;
659 }
660 
662  .name = "shorten",
663  .type = AVMEDIA_TYPE_AUDIO,
664  .id = AV_CODEC_ID_SHORTEN,
665  .priv_data_size = sizeof(ShortenContext),
669  .capabilities = CODEC_CAP_DELAY | CODEC_CAP_DR1,
670  .long_name = NULL_IF_CONFIG_SMALL("Shorten"),
671  .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
673 };