fix some potential security issues, patch by Matthias Hopf, mat at mshopf dot de
[ffmpeg.git] / 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 shorten.c
24  * Shorten decoder
25  * @author Jeff Muizelaar
26  *
27  */
28
29 #define DEBUG
30 #include <limits.h>
31 #include "avcodec.h"
32 #include "bitstream.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 #define VERBATIM_CKSIZE_SIZE 5
74 #define VERBATIM_BYTE_SIZE 8
75 #define CANONICAL_HEADER_SIZE 44
76
77 typedef struct ShortenContext {
78     AVCodecContext *avctx;
79     GetBitContext gb;
80
81     int min_framesize, max_framesize;
82     int channels;
83
84     int32_t *decoded[MAX_CHANNELS];
85     int32_t *offset[MAX_CHANNELS];
86     uint8_t *bitstream;
87     int bitstream_size;
88     int bitstream_index;
89     unsigned int allocated_bitstream_size;
90     int header_size;
91     uint8_t header[OUT_BUFFER_SIZE];
92     int version;
93     int cur_chan;
94     int bitshift;
95     int nmean;
96     int internal_ftype;
97     int nwrap;
98     int blocksize;
99     int bitindex;
100     int32_t lpcqoffset;
101 } ShortenContext;
102
103 static int shorten_decode_init(AVCodecContext * avctx)
104 {
105     ShortenContext *s = avctx->priv_data;
106     s->avctx = avctx;
107
108     return 0;
109 }
110
111 static int allocate_buffers(ShortenContext *s)
112 {
113     int i, chan;
114     for (chan=0; chan<s->channels; chan++) {
115         if(FFMAX(1, s->nmean) >= UINT_MAX/sizeof(int32_t)){
116             av_log(s->avctx, AV_LOG_ERROR, "nmean too large\n");
117             return -1;
118         }
119         if(s->blocksize + s->nwrap >= UINT_MAX/sizeof(int32_t) || s->blocksize + s->nwrap <= (unsigned)s->nwrap){
120             av_log(s->avctx, AV_LOG_ERROR, "s->blocksize + s->nwrap too large\n");
121             return -1;
122         }
123
124         s->offset[chan] = av_realloc(s->offset[chan], sizeof(int32_t)*FFMAX(1, s->nmean));
125
126         s->decoded[chan] = av_realloc(s->decoded[chan], sizeof(int32_t)*(s->blocksize + s->nwrap));
127         for (i=0; i<s->nwrap; i++)
128             s->decoded[chan][i] = 0;
129         s->decoded[chan] += s->nwrap;
130     }
131     return 0;
132 }
133
134
135 static inline unsigned int get_uint(ShortenContext *s, int k)
136 {
137     if (s->version != 0)
138         k = get_ur_golomb_shorten(&s->gb, ULONGSIZE);
139     return get_ur_golomb_shorten(&s->gb, k);
140 }
141
142
143 static void fix_bitshift(ShortenContext *s, int32_t *buffer)
144 {
145     int i;
146
147     if (s->bitshift != 0)
148         for (i = 0; i < s->blocksize; i++)
149             buffer[s->nwrap + i] <<= s->bitshift;
150 }
151
152
153 static void init_offset(ShortenContext *s)
154 {
155     int32_t mean = 0;
156     int  chan, i;
157     int nblock = FFMAX(1, s->nmean);
158     /* initialise offset */
159     switch (s->internal_ftype)
160     {
161         case TYPE_S16HL:
162         case TYPE_S16LH:
163             mean = 0;
164             break;
165         default:
166             av_log(s->avctx, AV_LOG_ERROR, "unknown audio type");
167             abort();
168     }
169
170     for (chan = 0; chan < s->channels; chan++)
171         for (i = 0; i < nblock; i++)
172             s->offset[chan][i] = mean;
173 }
174
175 static int inline get_le32(GetBitContext *gb)
176 {
177     return bswap_32(get_bits_long(gb, 32));
178 }
179
180 static short inline get_le16(GetBitContext *gb)
181 {
182     return bswap_16(get_bits_long(gb, 16));
183 }
184
185 static int decode_wave_header(AVCodecContext *avctx, uint8_t *header, int header_size)
186 {
187     GetBitContext hb;
188     int len;
189     int chunk_size;
190     short wave_format;
191
192     init_get_bits(&hb, header, header_size*8);
193     if (get_le32(&hb) != MKTAG('R','I','F','F')) {
194         av_log(avctx, AV_LOG_ERROR, "missing RIFF tag\n");
195         return -1;
196     }
197
198     chunk_size = get_le32(&hb);
199
200     if (get_le32(&hb) != MKTAG('W','A','V','E')) {
201         av_log(avctx, AV_LOG_ERROR, "missing WAVE tag\n");
202         return -1;
203     }
204
205     while (get_le32(&hb) != MKTAG('f','m','t',' ')) {
206         len = get_le32(&hb);
207         skip_bits(&hb, 8*len);
208     }
209     len = get_le32(&hb);
210
211     if (len < 16) {
212         av_log(avctx, AV_LOG_ERROR, "fmt chunk was too short\n");
213         return -1;
214     }
215
216     wave_format = get_le16(&hb);
217
218     switch (wave_format) {
219         case WAVE_FORMAT_PCM:
220             break;
221         default:
222             av_log(avctx, AV_LOG_ERROR, "unsupported wave format\n");
223             return -1;
224     }
225
226     avctx->channels = get_le16(&hb);
227     avctx->sample_rate = get_le32(&hb);
228     avctx->bit_rate = get_le32(&hb) * 8;
229     avctx->block_align = get_le16(&hb);
230     avctx->bits_per_sample = get_le16(&hb);
231
232     if (avctx->bits_per_sample != 16) {
233         av_log(avctx, AV_LOG_ERROR, "unsupported number of bits per sample\n");
234         return -1;
235     }
236
237     len -= 16;
238     if (len > 0)
239         av_log(avctx, AV_LOG_INFO, "%d header bytes unparsed\n", len);
240
241     return 0;
242 }
243
244 static int16_t * interleave_buffer(int16_t *samples, int nchan, int blocksize, int32_t **buffer) {
245     int i, chan;
246     for (i=0; i<blocksize; i++)
247         for (chan=0; chan < nchan; chan++)
248             *samples++ = FFMIN(buffer[chan][i], 32768);
249     return samples;
250 }
251
252 static void decode_subframe_lpc(ShortenContext *s, int channel, int residual_size, int pred_order)
253 {
254     int sum, i, j;
255     int coeffs[pred_order];
256
257     for (i=0; i<pred_order; i++)
258         coeffs[i] = get_sr_golomb_shorten(&s->gb, LPCQUANT);
259
260     for (i=0; i < s->blocksize; i++) {
261         sum = s->lpcqoffset;
262         for (j=0; j<pred_order; j++)
263             sum += coeffs[j] * s->decoded[channel][i-j-1];
264         s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + (sum >> LPCQUANT);
265     }
266 }
267
268
269 static int shorten_decode_frame(AVCodecContext *avctx,
270         void *data, int *data_size,
271         uint8_t *buf, int buf_size)
272 {
273     ShortenContext *s = avctx->priv_data;
274     int i, input_buf_size = 0;
275     int16_t *samples = data;
276     if(s->max_framesize == 0){
277         s->max_framesize= 1024; // should hopefully be enough for the first header
278         s->bitstream= av_fast_realloc(s->bitstream, &s->allocated_bitstream_size, s->max_framesize);
279     }
280
281     if(1 && s->max_framesize){//FIXME truncated
282         buf_size= FFMIN(buf_size, s->max_framesize - s->bitstream_size);
283         input_buf_size= buf_size;
284
285         if(s->bitstream_index + s->bitstream_size + buf_size > s->allocated_bitstream_size){
286             //                printf("memmove\n");
287             memmove(s->bitstream, &s->bitstream[s->bitstream_index], s->bitstream_size);
288             s->bitstream_index=0;
289         }
290         memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size], buf, buf_size);
291         buf= &s->bitstream[s->bitstream_index];
292         buf_size += s->bitstream_size;
293         s->bitstream_size= buf_size;
294
295         if(buf_size < s->max_framesize){
296             //dprintf("wanna more data ... %d\n", buf_size);
297             return input_buf_size;
298         }
299     }
300     init_get_bits(&s->gb, buf, buf_size*8);
301     get_bits(&s->gb, s->bitindex);
302     if (!s->blocksize)
303     {
304         int maxnlpc = 0;
305         /* shorten signature */
306         if (get_bits_long(&s->gb, 32) != bswap_32(ff_get_fourcc("ajkg"))) {
307             av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
308             return -1;
309         }
310
311         s->lpcqoffset = 0;
312         s->blocksize = DEFAULT_BLOCK_SIZE;
313         s->channels = 1;
314         s->nmean = -1;
315         s->version = get_bits(&s->gb, 8);
316         s->internal_ftype = get_uint(s, TYPESIZE);
317
318         s->channels = get_uint(s, CHANSIZE);
319         if (s->channels > MAX_CHANNELS) {
320             av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
321             return -1;
322         }
323
324         /* get blocksize if version > 0 */
325         if (s->version > 0) {
326             int skip_bytes;
327             s->blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
328             maxnlpc = get_uint(s, LPCQSIZE);
329             s->nmean = get_uint(s, 0);
330
331             skip_bytes = get_uint(s, NSKIPSIZE);
332             for (i=0; i<skip_bytes; i++) {
333                 skip_bits(&s->gb, 8);
334             }
335         }
336         s->nwrap = FFMAX(NWRAP, maxnlpc);
337
338         if (allocate_buffers(s))
339             return -1;
340
341         init_offset(s);
342
343         if (s->version > 1)
344             s->lpcqoffset = V2LPCQOFFSET;
345
346         if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
347             av_log(s->avctx, AV_LOG_ERROR, "missing verbatim section at begining of stream\n");
348             return -1;
349         }
350
351         s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
352         if (s->header_size >= OUT_BUFFER_SIZE || s->header_size < CANONICAL_HEADER_SIZE) {
353             av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n", s->header_size);
354             return -1;
355         }
356
357         for (i=0; i<s->header_size; i++)
358             s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
359
360         if (decode_wave_header(avctx, s->header, s->header_size) < 0)
361             return -1;
362
363         s->cur_chan = 0;
364         s->bitshift = 0;
365     }
366     else
367     {
368         int cmd;
369         int len;
370         cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
371         switch (cmd) {
372             case FN_ZERO:
373             case FN_DIFF0:
374             case FN_DIFF1:
375             case FN_DIFF2:
376             case FN_DIFF3:
377             case FN_QLPC:
378                 {
379                     int residual_size = 0;
380                     int channel = s->cur_chan;
381                     int32_t coffset;
382                     if (cmd != FN_ZERO) {
383                         residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);
384                         /* this is a hack as version 0 differed in defintion of get_sr_golomb_shorten */
385                         if (s->version == 0)
386                             residual_size--;
387                     }
388
389                     if (s->nmean == 0)
390                         coffset = s->offset[channel][0];
391                     else {
392                         int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;
393                         for (i=0; i<s->nmean; i++)
394                             sum += s->offset[channel][i];
395                         coffset = sum / s->nmean;
396                         if (s->version >= 2)
397                             coffset >>= FFMIN(1, s->bitshift);
398                     }
399                     switch (cmd) {
400                         case FN_ZERO:
401                             for (i=0; i<s->blocksize; i++)
402                                 s->decoded[channel][i] = 0;
403                             break;
404                         case FN_DIFF0:
405                             for (i=0; i<s->blocksize; i++)
406                                 s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + coffset;
407                             break;
408                         case FN_DIFF1:
409                             for (i=0; i<s->blocksize; i++)
410                                 s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + s->decoded[channel][i - 1];
411                             break;
412                         case FN_DIFF2:
413                             for (i=0; i<s->blocksize; i++)
414                                 s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + 2*s->decoded[channel][i-1]
415                                                                                                       -   s->decoded[channel][i-2];
416                             break;
417                         case FN_DIFF3:
418                             for (i=0; i<s->blocksize; i++)
419                                 s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + 3*s->decoded[channel][i-1]
420                                                                                                       - 3*s->decoded[channel][i-2]
421                                                                                                       +   s->decoded[channel][i-3];
422                             break;
423                         case FN_QLPC:
424                             {
425                                 int pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
426                                 for (i=0; i<pred_order; i++)
427                                     s->decoded[channel][i - pred_order] -= coffset;
428                                 decode_subframe_lpc(s, channel, residual_size, pred_order);
429                                 if (coffset != 0)
430                                     for (i=0; i < s->blocksize; i++)
431                                         s->decoded[channel][i] += coffset;
432                             }
433                     }
434                     if (s->nmean > 0) {
435                         int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2;
436                         for (i=0; i<s->blocksize; i++)
437                             sum += s->decoded[channel][i];
438
439                         for (i=1; i<s->nmean; i++)
440                             s->offset[channel][i-1] = s->offset[channel][i];
441
442                         if (s->version < 2)
443                             s->offset[channel][s->nmean - 1] = sum / s->blocksize;
444                         else
445                             s->offset[channel][s->nmean - 1] = (sum / s->blocksize) << s->bitshift;
446                     }
447                     for (i=-s->nwrap; i<0; i++)
448                         s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];
449
450                     fix_bitshift(s, s->decoded[channel]);
451
452                     s->cur_chan++;
453                     if (s->cur_chan == s->channels) {
454                         samples = interleave_buffer(samples, s->channels, s->blocksize, s->decoded);
455                         s->cur_chan = 0;
456                         goto frame_done;
457                     }
458                     break;
459                 }
460                 break;
461             case FN_VERBATIM:
462                 len = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
463                 while (len--) {
464                     get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
465                 }
466                 break;
467             case FN_BITSHIFT:
468                 s->bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);
469                 break;
470             case FN_BLOCKSIZE:
471                 s->blocksize = get_uint(s, av_log2(s->blocksize));
472                 break;
473             case FN_QUIT:
474                 return buf_size;
475                 break;
476             default:
477                 av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);
478                 return -1;
479                 break;
480         }
481     }
482 frame_done:
483     *data_size = (int8_t *)samples - (int8_t *)data;
484
485     //    s->last_blocksize = s->blocksize;
486     s->bitindex = get_bits_count(&s->gb) - 8*((get_bits_count(&s->gb))/8);
487     i= (get_bits_count(&s->gb))/8;
488     if (i > buf_size) {
489         av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
490         s->bitstream_size=0;
491         s->bitstream_index=0;
492         return -1;
493     }
494     if (s->bitstream_size) {
495         s->bitstream_index += i;
496         s->bitstream_size  -= i;
497         return input_buf_size;
498     } else
499         return i;
500 }
501
502 static int shorten_decode_close(AVCodecContext *avctx)
503 {
504     ShortenContext *s = avctx->priv_data;
505     int i;
506
507     for (i = 0; i < s->channels; i++) {
508         s->decoded[i] -= s->nwrap;
509         av_freep(&s->decoded[i]);
510         av_freep(&s->offset[i]);
511     }
512     av_freep(&s->bitstream);
513     return 0;
514 }
515
516 static void shorten_flush(AVCodecContext *avctx){
517     ShortenContext *s = avctx->priv_data;
518
519     s->bitstream_size=
520         s->bitstream_index= 0;
521 }
522
523 AVCodec shorten_decoder = {
524     "shorten",
525     CODEC_TYPE_AUDIO,
526     CODEC_ID_SHORTEN,
527     sizeof(ShortenContext),
528     shorten_decode_init,
529     NULL,
530     shorten_decode_close,
531     shorten_decode_frame,
532     .flush= shorten_flush,
533 };