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