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