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