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