]> git.sesse.net Git - ffmpeg/blob - libavcodec/shorten.c
Merge remote-tracking branch 'qatar/master'
[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
35 #define MAX_CHANNELS 8
36 #define MAX_BLOCKSIZE 65535
37
38 #define OUT_BUFFER_SIZE 16384
39
40 #define ULONGSIZE 2
41
42 #define WAVE_FORMAT_PCM 0x0001
43
44 #define DEFAULT_BLOCK_SIZE 256
45
46 #define TYPESIZE 4
47 #define CHANSIZE 0
48 #define LPCQSIZE 2
49 #define ENERGYSIZE 3
50 #define BITSHIFTSIZE 2
51
52 #define TYPE_S16HL 3
53 #define TYPE_S16LH 5
54
55 #define NWRAP 3
56 #define NSKIPSIZE 1
57
58 #define LPCQUANT 5
59 #define V2LPCQOFFSET (1 << LPCQUANT)
60
61 #define FNSIZE 2
62 #define FN_DIFF0        0
63 #define FN_DIFF1        1
64 #define FN_DIFF2        2
65 #define FN_DIFF3        3
66 #define FN_QUIT         4
67 #define FN_BLOCKSIZE    5
68 #define FN_BITSHIFT     6
69 #define FN_QLPC         7
70 #define FN_ZERO         8
71 #define FN_VERBATIM     9
72
73 /** indicates if the FN_* command is audio or non-audio */
74 static const uint8_t is_audio_command[10] = { 1, 1, 1, 1, 0, 0, 0, 1, 1, 0 };
75
76 #define VERBATIM_CKSIZE_SIZE 5
77 #define VERBATIM_BYTE_SIZE 8
78 #define CANONICAL_HEADER_SIZE 44
79
80 typedef struct ShortenContext {
81     AVCodecContext *avctx;
82     AVFrame frame;
83     GetBitContext gb;
84
85     int min_framesize, max_framesize;
86     int channels;
87
88     int32_t *decoded[MAX_CHANNELS];
89     int32_t *decoded_base[MAX_CHANNELS];
90     int32_t *offset[MAX_CHANNELS];
91     int *coeffs;
92     uint8_t *bitstream;
93     int bitstream_size;
94     int bitstream_index;
95     unsigned int allocated_bitstream_size;
96     int header_size;
97     uint8_t header[OUT_BUFFER_SIZE];
98     int version;
99     int cur_chan;
100     int bitshift;
101     int nmean;
102     int internal_ftype;
103     int nwrap;
104     int blocksize;
105     int bitindex;
106     int32_t lpcqoffset;
107     int got_header;
108     int got_quit_command;
109 } ShortenContext;
110
111 static av_cold int shorten_decode_init(AVCodecContext * avctx)
112 {
113     ShortenContext *s = avctx->priv_data;
114     s->avctx = avctx;
115     avctx->sample_fmt = AV_SAMPLE_FMT_S16;
116
117     avcodec_get_frame_defaults(&s->frame);
118     avctx->coded_frame = &s->frame;
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 -1;
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 -1;
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_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     const uint8_t *end= header + header_size;
210
211     if (bytestream_get_le32(&header) != MKTAG('R','I','F','F')) {
212         av_log(avctx, AV_LOG_ERROR, "missing RIFF tag\n");
213         return -1;
214     }
215
216     header += 4; /* chunk size */;
217
218     if (bytestream_get_le32(&header) != MKTAG('W','A','V','E')) {
219         av_log(avctx, AV_LOG_ERROR, "missing WAVE tag\n");
220         return -1;
221     }
222
223     while (bytestream_get_le32(&header) != MKTAG('f','m','t',' ')) {
224         len = bytestream_get_le32(&header);
225         if(len<0 || end - header - 8 < len)
226             return AVERROR_INVALIDDATA;
227         header += len;
228     }
229     len = bytestream_get_le32(&header);
230
231     if (len < 16) {
232         av_log(avctx, AV_LOG_ERROR, "fmt chunk was too short\n");
233         return -1;
234     }
235
236     wave_format = bytestream_get_le16(&header);
237
238     switch (wave_format) {
239         case WAVE_FORMAT_PCM:
240             break;
241         default:
242             av_log(avctx, AV_LOG_ERROR, "unsupported wave format\n");
243             return -1;
244     }
245
246     header += 2;        // skip channels    (already got from shorten header)
247     avctx->sample_rate = bytestream_get_le32(&header);
248     header += 4;        // skip bit rate    (represents original uncompressed bit rate)
249     header += 2;        // skip block align (not needed)
250     avctx->bits_per_coded_sample = bytestream_get_le16(&header);
251
252     if (avctx->bits_per_coded_sample != 16) {
253         av_log(avctx, AV_LOG_ERROR, "unsupported number of bits per sample\n");
254         return -1;
255     }
256
257     len -= 16;
258     if (len > 0)
259         av_log(avctx, AV_LOG_INFO, "%d header bytes unparsed\n", len);
260
261     return 0;
262 }
263
264 static void interleave_buffer(int16_t *samples, int nchan, int blocksize,
265                               int32_t **buffer)
266 {
267     int i, chan;
268     for (i=0; i<blocksize; i++)
269         for (chan=0; chan < nchan; chan++)
270             *samples++ = av_clip_int16(buffer[chan][i]);
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", pred_order);
290             return AVERROR(EINVAL);
291         }
292         /* read LPC coefficients */
293         for (i=0; i<pred_order; i++)
294             s->coeffs[i] = get_sr_golomb_shorten(&s->gb, LPCQUANT);
295         coeffs = s->coeffs;
296
297         qshift = LPCQUANT;
298     } else {
299         /* fixed LPC coeffs */
300         pred_order = command;
301         coeffs     = fixed_coeffs[pred_order-1];
302         qshift     = 0;
303     }
304
305     /* subtract offset from previous samples to use in prediction */
306     if (command == FN_QLPC && coffset)
307         for (i = -pred_order; i < 0; i++)
308             s->decoded[channel][i] -= coffset;
309
310     /* decode residual and do LPC prediction */
311     init_sum = pred_order ? (command == FN_QLPC ? s->lpcqoffset : 0) : coffset;
312     for (i=0; i < s->blocksize; i++) {
313         sum = init_sum;
314         for (j=0; j<pred_order; j++)
315             sum += coeffs[j] * s->decoded[channel][i-j-1];
316         s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + (sum >> qshift);
317     }
318
319     /* add offset to current samples */
320     if (command == FN_QLPC && coffset)
321         for (i = 0; i < s->blocksize; i++)
322             s->decoded[channel][i] += coffset;
323
324     return 0;
325 }
326
327 static int read_header(ShortenContext *s)
328 {
329     int i, ret;
330     int maxnlpc = 0;
331     /* shorten signature */
332     if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {
333         av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
334         return -1;
335     }
336
337     s->lpcqoffset = 0;
338     s->blocksize = DEFAULT_BLOCK_SIZE;
339     s->nmean = -1;
340     s->version = get_bits(&s->gb, 8);
341     s->internal_ftype = get_uint(s, TYPESIZE);
342
343     s->channels = get_uint(s, CHANSIZE);
344     if (s->channels > MAX_CHANNELS) {
345         av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
346         return -1;
347     }
348     s->avctx->channels = s->channels;
349
350     /* get blocksize if version > 0 */
351     if (s->version > 0) {
352         int skip_bytes, blocksize;
353
354         blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
355         if (!blocksize || blocksize > MAX_BLOCKSIZE) {
356             av_log(s->avctx, AV_LOG_ERROR, "invalid or unsupported block size: %d\n",
357                    blocksize);
358             return AVERROR(EINVAL);
359         }
360         s->blocksize = blocksize;
361
362         maxnlpc = get_uint(s, LPCQSIZE);
363         s->nmean = get_uint(s, 0);
364
365         skip_bytes = get_uint(s, NSKIPSIZE);
366         for (i=0; i<skip_bytes; i++) {
367             skip_bits(&s->gb, 8);
368         }
369     }
370     s->nwrap = FFMAX(NWRAP, maxnlpc);
371
372     if ((ret = allocate_buffers(s)) < 0)
373         return ret;
374
375     if ((ret = init_offset(s)) < 0)
376         return ret;
377
378     if (s->version > 1)
379         s->lpcqoffset = V2LPCQOFFSET;
380
381     if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
382         av_log(s->avctx, AV_LOG_ERROR, "missing verbatim section at beginning of stream\n");
383         return -1;
384     }
385
386     s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
387     if (s->header_size >= OUT_BUFFER_SIZE || s->header_size < CANONICAL_HEADER_SIZE) {
388         av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n", s->header_size);
389         return -1;
390     }
391
392     for (i=0; i<s->header_size; i++)
393         s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
394
395     if (decode_wave_header(s->avctx, s->header, s->header_size) < 0)
396         return -1;
397
398     s->cur_chan = 0;
399     s->bitshift = 0;
400
401     s->got_header = 1;
402
403     return 0;
404 }
405
406 static int shorten_decode_frame(AVCodecContext *avctx, void *data,
407                                 int *got_frame_ptr, AVPacket *avpkt)
408 {
409     const uint8_t *buf = avpkt->data;
410     int buf_size = avpkt->size;
411     ShortenContext *s = avctx->priv_data;
412     int i, input_buf_size = 0;
413     int ret;
414
415     /* allocate internal bitstream buffer */
416     if(s->max_framesize == 0){
417         void *tmp_ptr;
418         s->max_framesize= 1024; // should hopefully be enough for the first header
419         tmp_ptr = av_fast_realloc(s->bitstream, &s->allocated_bitstream_size,
420                                   s->max_framesize);
421         if (!tmp_ptr) {
422             av_log(avctx, AV_LOG_ERROR, "error allocating bitstream buffer\n");
423             return AVERROR(ENOMEM);
424         }
425         s->bitstream = tmp_ptr;
426     }
427
428     /* append current packet data to bitstream buffer */
429     if(1 && s->max_framesize){//FIXME truncated
430         buf_size= FFMIN(buf_size, s->max_framesize - s->bitstream_size);
431         input_buf_size= buf_size;
432
433         if(s->bitstream_index + s->bitstream_size + buf_size > s->allocated_bitstream_size){
434             memmove(s->bitstream, &s->bitstream[s->bitstream_index], s->bitstream_size);
435             s->bitstream_index=0;
436         }
437         if (buf)
438             memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size], buf, buf_size);
439         buf= &s->bitstream[s->bitstream_index];
440         buf_size += s->bitstream_size;
441         s->bitstream_size= buf_size;
442
443         /* do not decode until buffer has at least max_framesize bytes or
444            the end of the file has been reached */
445         if (buf_size < s->max_framesize && avpkt->data) {
446             *got_frame_ptr = 0;
447             return input_buf_size;
448         }
449     }
450     /* init and position bitstream reader */
451     init_get_bits(&s->gb, buf, buf_size*8);
452     skip_bits(&s->gb, s->bitindex);
453
454     /* process header or next subblock */
455     if (!s->got_header) {
456         if ((ret = read_header(s)) < 0)
457             return ret;
458         *got_frame_ptr = 0;
459         goto finish_frame;
460     }
461
462     /* if quit command was read previously, don't decode anything */
463     if (s->got_quit_command) {
464         *got_frame_ptr = 0;
465         return avpkt->size;
466     }
467
468     s->cur_chan = 0;
469     while (s->cur_chan < s->channels) {
470         int cmd;
471         int len;
472
473         if (get_bits_left(&s->gb) < 3+FNSIZE) {
474             *got_frame_ptr = 0;
475             break;
476         }
477
478         cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
479
480         if (cmd > FN_VERBATIM) {
481             av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);
482             *got_frame_ptr = 0;
483             break;
484         }
485
486         if (!is_audio_command[cmd]) {
487             /* process non-audio command */
488             switch (cmd) {
489                 case FN_VERBATIM:
490                     len = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
491                     while (len--) {
492                         get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
493                     }
494                     break;
495                 case FN_BITSHIFT:
496                     s->bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);
497                     break;
498                 case FN_BLOCKSIZE: {
499                     int blocksize = get_uint(s, av_log2(s->blocksize));
500                     if (blocksize > s->blocksize) {
501                         av_log(avctx, AV_LOG_ERROR, "Increasing block size is not supported\n");
502                         return AVERROR_PATCHWELCOME;
503                     }
504                     if (!blocksize || blocksize > MAX_BLOCKSIZE) {
505                         av_log(avctx, AV_LOG_ERROR, "invalid or unsupported "
506                                "block size: %d\n", blocksize);
507                         return AVERROR(EINVAL);
508                     }
509                     s->blocksize = blocksize;
510                     break;
511                 }
512                 case FN_QUIT:
513                     s->got_quit_command = 1;
514                     break;
515             }
516             if (cmd == FN_BLOCKSIZE || cmd == FN_QUIT) {
517                 *got_frame_ptr = 0;
518                 break;
519             }
520         } else {
521             /* process audio command */
522             int residual_size = 0;
523             int channel = s->cur_chan;
524             int32_t coffset;
525
526             /* get Rice code for residual decoding */
527             if (cmd != FN_ZERO) {
528                 residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);
529                 /* this is a hack as version 0 differed in defintion of get_sr_golomb_shorten */
530                 if (s->version == 0)
531                     residual_size--;
532             }
533
534             /* calculate sample offset using means from previous blocks */
535             if (s->nmean == 0)
536                 coffset = s->offset[channel][0];
537             else {
538                 int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;
539                 for (i=0; i<s->nmean; i++)
540                     sum += s->offset[channel][i];
541                 coffset = sum / s->nmean;
542                 if (s->version >= 2)
543                     coffset >>= FFMIN(1, s->bitshift);
544             }
545
546             /* decode samples for this channel */
547             if (cmd == FN_ZERO) {
548                 for (i=0; i<s->blocksize; i++)
549                     s->decoded[channel][i] = 0;
550             } else {
551                 if ((ret = decode_subframe_lpc(s, cmd, channel, residual_size, coffset)) < 0)
552                     return ret;
553             }
554
555             /* update means with info from the current block */
556             if (s->nmean > 0) {
557                 int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2;
558                 for (i=0; i<s->blocksize; i++)
559                     sum += s->decoded[channel][i];
560
561                 for (i=1; i<s->nmean; i++)
562                     s->offset[channel][i-1] = s->offset[channel][i];
563
564                 if (s->version < 2)
565                     s->offset[channel][s->nmean - 1] = sum / s->blocksize;
566                 else
567                     s->offset[channel][s->nmean - 1] = (sum / s->blocksize) << s->bitshift;
568             }
569
570             /* copy wrap samples for use with next block */
571             for (i=-s->nwrap; i<0; i++)
572                 s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];
573
574             /* shift samples to add in unused zero bits which were removed
575                during encoding */
576             fix_bitshift(s, s->decoded[channel]);
577
578             /* if this is the last channel in the block, output the samples */
579             s->cur_chan++;
580             if (s->cur_chan == s->channels) {
581                 /* get output buffer */
582                 s->frame.nb_samples = s->blocksize;
583                 if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
584                     av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
585                     return ret;
586                 }
587                 /* interleave output */
588                 interleave_buffer((int16_t *)s->frame.data[0], s->channels,
589                                   s->blocksize, s->decoded);
590
591                 *got_frame_ptr   = 1;
592                 *(AVFrame *)data = s->frame;
593             }
594         }
595     }
596     if (s->cur_chan < s->channels)
597         *got_frame_ptr = 0;
598
599 finish_frame:
600     s->bitindex = get_bits_count(&s->gb) - 8*((get_bits_count(&s->gb))/8);
601     i= (get_bits_count(&s->gb))/8;
602     if (i > buf_size) {
603         av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
604         s->bitstream_size=0;
605         s->bitstream_index=0;
606         return -1;
607     }
608     if (s->bitstream_size) {
609         s->bitstream_index += i;
610         s->bitstream_size  -= i;
611         return input_buf_size;
612     } else
613         return i;
614 }
615
616 static av_cold int shorten_decode_close(AVCodecContext *avctx)
617 {
618     ShortenContext *s = avctx->priv_data;
619     int i;
620
621     for (i = 0; i < s->channels; i++) {
622         s->decoded[i] = NULL;
623         av_freep(&s->decoded_base[i]);
624         av_freep(&s->offset[i]);
625     }
626     av_freep(&s->bitstream);
627     av_freep(&s->coeffs);
628
629     return 0;
630 }
631
632 AVCodec ff_shorten_decoder = {
633     .name           = "shorten",
634     .type           = AVMEDIA_TYPE_AUDIO,
635     .id             = CODEC_ID_SHORTEN,
636     .priv_data_size = sizeof(ShortenContext),
637     .init           = shorten_decode_init,
638     .close          = shorten_decode_close,
639     .decode         = shorten_decode_frame,
640     .capabilities   = CODEC_CAP_DELAY | CODEC_CAP_DR1,
641     .long_name= NULL_IF_CONFIG_SMALL("Shorten"),
642 };