]> git.sesse.net Git - ffmpeg/blob - libavcodec/shorten.c
cosmetics: remove some needless commented-out stuff
[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     void *tmp_ptr;
120
121     for (chan=0; chan<s->channels; chan++) {
122         if(FFMAX(1, s->nmean) >= UINT_MAX/sizeof(int32_t)){
123             av_log(s->avctx, AV_LOG_ERROR, "nmean too large\n");
124             return -1;
125         }
126         if(s->blocksize + s->nwrap >= UINT_MAX/sizeof(int32_t) || s->blocksize + s->nwrap <= (unsigned)s->nwrap){
127             av_log(s->avctx, AV_LOG_ERROR, "s->blocksize + s->nwrap too large\n");
128             return -1;
129         }
130
131         tmp_ptr = av_realloc(s->offset[chan], sizeof(int32_t)*FFMAX(1, s->nmean));
132         if (!tmp_ptr)
133             return AVERROR(ENOMEM);
134         s->offset[chan] = tmp_ptr;
135
136         tmp_ptr = av_realloc(s->decoded[chan], sizeof(int32_t)*(s->blocksize + s->nwrap));
137         if (!tmp_ptr)
138             return AVERROR(ENOMEM);
139         s->decoded[chan] = tmp_ptr;
140         for (i=0; i<s->nwrap; i++)
141             s->decoded[chan][i] = 0;
142         s->decoded[chan] += s->nwrap;
143     }
144
145     coeffs = av_realloc(s->coeffs, s->nwrap * sizeof(*s->coeffs));
146     if (!coeffs)
147         return AVERROR(ENOMEM);
148     s->coeffs = coeffs;
149
150     return 0;
151 }
152
153
154 static inline unsigned int get_uint(ShortenContext *s, int k)
155 {
156     if (s->version != 0)
157         k = get_ur_golomb_shorten(&s->gb, ULONGSIZE);
158     return get_ur_golomb_shorten(&s->gb, k);
159 }
160
161
162 static void fix_bitshift(ShortenContext *s, int32_t *buffer)
163 {
164     int i;
165
166     if (s->bitshift != 0)
167         for (i = 0; i < s->blocksize; i++)
168             buffer[i] <<= s->bitshift;
169 }
170
171
172 static void init_offset(ShortenContext *s)
173 {
174     int32_t mean = 0;
175     int  chan, i;
176     int nblock = FFMAX(1, s->nmean);
177     /* initialise offset */
178     switch (s->internal_ftype)
179     {
180         case TYPE_S16HL:
181         case TYPE_S16LH:
182             mean = 0;
183             break;
184         default:
185             av_log(s->avctx, AV_LOG_ERROR, "unknown audio type");
186             abort();
187     }
188
189     for (chan = 0; chan < s->channels; chan++)
190         for (i = 0; i < nblock; i++)
191             s->offset[chan][i] = mean;
192 }
193
194 static inline int get_le32(GetBitContext *gb)
195 {
196     return av_bswap32(get_bits_long(gb, 32));
197 }
198
199 static inline short get_le16(GetBitContext *gb)
200 {
201     return av_bswap16(get_bits_long(gb, 16));
202 }
203
204 static int decode_wave_header(AVCodecContext *avctx, uint8_t *header, int header_size)
205 {
206     GetBitContext hb;
207     int len;
208     short wave_format;
209
210     init_get_bits(&hb, header, header_size*8);
211     if (get_le32(&hb) != MKTAG('R','I','F','F')) {
212         av_log(avctx, AV_LOG_ERROR, "missing RIFF tag\n");
213         return -1;
214     }
215
216     skip_bits_long(&hb, 32);    /* chunk_size */
217
218     if (get_le32(&hb) != MKTAG('W','A','V','E')) {
219         av_log(avctx, AV_LOG_ERROR, "missing WAVE tag\n");
220         return -1;
221     }
222
223     while (get_le32(&hb) != MKTAG('f','m','t',' ')) {
224         len = get_le32(&hb);
225         skip_bits(&hb, 8*len);
226     }
227     len = get_le32(&hb);
228
229     if (len < 16) {
230         av_log(avctx, AV_LOG_ERROR, "fmt chunk was too short\n");
231         return -1;
232     }
233
234     wave_format = get_le16(&hb);
235
236     switch (wave_format) {
237         case WAVE_FORMAT_PCM:
238             break;
239         default:
240             av_log(avctx, AV_LOG_ERROR, "unsupported wave format\n");
241             return -1;
242     }
243
244     skip_bits(&hb, 16); // skip channels    (already got from shorten header)
245     avctx->sample_rate = get_le32(&hb);
246     skip_bits(&hb, 32); // skip bit rate    (represents original uncompressed bit rate)
247     skip_bits(&hb, 16); // skip block align (not needed)
248     avctx->bits_per_coded_sample = get_le16(&hb);
249
250     if (avctx->bits_per_coded_sample != 16) {
251         av_log(avctx, AV_LOG_ERROR, "unsupported number of bits per sample\n");
252         return -1;
253     }
254
255     len -= 16;
256     if (len > 0)
257         av_log(avctx, AV_LOG_INFO, "%d header bytes unparsed\n", len);
258
259     return 0;
260 }
261
262 static int16_t * interleave_buffer(int16_t *samples, int nchan, int blocksize, int32_t **buffer) {
263     int i, chan;
264     for (i=0; i<blocksize; i++)
265         for (chan=0; chan < nchan; chan++)
266             *samples++ = FFMIN(buffer[chan][i], 32768);
267     return samples;
268 }
269
270 static int decode_subframe_lpc(ShortenContext *s, int channel,
271                                int residual_size, int32_t coffset)
272 {
273     int pred_order, sum, i, j;
274     int *coeffs = s->coeffs;
275
276     /* read/validate prediction order */
277     pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
278     if (pred_order > s->nwrap) {
279         av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n", pred_order);
280         return AVERROR(EINVAL);
281     }
282     /* read LPC coefficients */
283     for (i=0; i<pred_order; i++)
284         coeffs[i] = get_sr_golomb_shorten(&s->gb, LPCQUANT);
285
286     /* subtract offset from previous samples to use in prediction */
287     if (coffset)
288         for (i = -pred_order; i < 0; i++)
289             s->decoded[channel][i] -= coffset;
290
291     /* decode residual and do LPC prediction */
292     for (i=0; i < s->blocksize; i++) {
293         sum = s->lpcqoffset;
294         for (j=0; j<pred_order; j++)
295             sum += coeffs[j] * s->decoded[channel][i-j-1];
296         s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + (sum >> LPCQUANT);
297     }
298
299     /* add offset to current samples */
300     if (coffset != 0)
301         for (i = 0; i < s->blocksize; i++)
302             s->decoded[channel][i] += coffset;
303
304     return 0;
305 }
306
307 static int read_header(ShortenContext *s)
308 {
309     int i, ret;
310     int maxnlpc = 0;
311     /* shorten signature */
312     if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {
313         av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
314         return -1;
315     }
316
317     s->lpcqoffset = 0;
318     s->blocksize = DEFAULT_BLOCK_SIZE;
319     s->channels = 1;
320     s->nmean = -1;
321     s->version = get_bits(&s->gb, 8);
322     s->internal_ftype = get_uint(s, TYPESIZE);
323
324     s->channels = get_uint(s, CHANSIZE);
325     if (s->channels > MAX_CHANNELS) {
326         av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
327         return -1;
328     }
329     s->avctx->channels = s->channels;
330
331     /* get blocksize if version > 0 */
332     if (s->version > 0) {
333         int skip_bytes, blocksize;
334
335         blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
336         if (!blocksize || blocksize > MAX_BLOCKSIZE) {
337             av_log(s->avctx, AV_LOG_ERROR, "invalid or unsupported block size: %d\n",
338                    blocksize);
339             return AVERROR(EINVAL);
340         }
341         s->blocksize = blocksize;
342
343         maxnlpc = get_uint(s, LPCQSIZE);
344         s->nmean = get_uint(s, 0);
345
346         skip_bytes = get_uint(s, NSKIPSIZE);
347         for (i=0; i<skip_bytes; i++) {
348             skip_bits(&s->gb, 8);
349         }
350     }
351     s->nwrap = FFMAX(NWRAP, maxnlpc);
352
353     if ((ret = allocate_buffers(s)) < 0)
354         return ret;
355
356     init_offset(s);
357
358     if (s->version > 1)
359         s->lpcqoffset = V2LPCQOFFSET;
360
361     if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
362         av_log(s->avctx, AV_LOG_ERROR, "missing verbatim section at beginning of stream\n");
363         return -1;
364     }
365
366     s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
367     if (s->header_size >= OUT_BUFFER_SIZE || s->header_size < CANONICAL_HEADER_SIZE) {
368         av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n", s->header_size);
369         return -1;
370     }
371
372     for (i=0; i<s->header_size; i++)
373         s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
374
375     if (decode_wave_header(s->avctx, s->header, s->header_size) < 0)
376         return -1;
377
378     s->cur_chan = 0;
379     s->bitshift = 0;
380
381     return 0;
382 }
383
384 static int shorten_decode_frame(AVCodecContext *avctx,
385         void *data, int *data_size,
386         AVPacket *avpkt)
387 {
388     const uint8_t *buf = avpkt->data;
389     int buf_size = avpkt->size;
390     ShortenContext *s = avctx->priv_data;
391     int i, input_buf_size = 0;
392     int16_t *samples = data;
393     int ret;
394
395     if(s->max_framesize == 0){
396         void *tmp_ptr;
397         s->max_framesize= 1024; // should hopefully be enough for the first header
398         tmp_ptr = av_fast_realloc(s->bitstream, &s->allocated_bitstream_size,
399                                   s->max_framesize);
400         if (!tmp_ptr) {
401             av_log(avctx, AV_LOG_ERROR, "error allocating bitstream buffer\n");
402             return AVERROR(ENOMEM);
403         }
404         s->bitstream = tmp_ptr;
405     }
406
407     if(1 && s->max_framesize){//FIXME truncated
408         buf_size= FFMIN(buf_size, s->max_framesize - s->bitstream_size);
409         input_buf_size= buf_size;
410
411         if(s->bitstream_index + s->bitstream_size + buf_size > s->allocated_bitstream_size){
412             memmove(s->bitstream, &s->bitstream[s->bitstream_index], s->bitstream_size);
413             s->bitstream_index=0;
414         }
415         memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size], buf, buf_size);
416         buf= &s->bitstream[s->bitstream_index];
417         buf_size += s->bitstream_size;
418         s->bitstream_size= buf_size;
419
420         if(buf_size < s->max_framesize){
421             *data_size = 0;
422             return input_buf_size;
423         }
424     }
425     init_get_bits(&s->gb, buf, buf_size*8);
426     skip_bits(&s->gb, s->bitindex);
427     if (!s->blocksize)
428     {
429         if ((ret = read_header(s)) < 0)
430             return ret;
431         *data_size = 0;
432     }
433     else
434     {
435         int cmd;
436         int len;
437         cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
438
439         if (cmd > FN_VERBATIM) {
440             av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);
441             if (s->bitstream_size > 0) {
442                 s->bitstream_index++;
443                 s->bitstream_size--;
444             }
445             return -1;
446         }
447
448         if (!is_audio_command[cmd]) {
449             /* process non-audio command */
450             switch (cmd) {
451                 case FN_VERBATIM:
452                     len = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
453                     while (len--) {
454                         get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
455                     }
456                     break;
457                 case FN_BITSHIFT:
458                     s->bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);
459                     break;
460                 case FN_BLOCKSIZE: {
461                     int blocksize = get_uint(s, av_log2(s->blocksize));
462                     if (blocksize > s->blocksize) {
463                         av_log(avctx, AV_LOG_ERROR, "Increasing block size is not supported\n");
464                         return AVERROR_PATCHWELCOME;
465                     }
466                     if (!blocksize || blocksize > MAX_BLOCKSIZE) {
467                         av_log(avctx, AV_LOG_ERROR, "invalid or unsupported "
468                                "block size: %d\n", blocksize);
469                         return AVERROR(EINVAL);
470                     }
471                     s->blocksize = blocksize;
472                     break;
473                 }
474                 case FN_QUIT:
475                     break;
476             }
477             *data_size = 0;
478         } else {
479             /* process audio command */
480             int residual_size = 0;
481             int channel = s->cur_chan;
482             int32_t coffset;
483             if (cmd != FN_ZERO) {
484                 residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);
485                 /* this is a hack as version 0 differed in defintion of get_sr_golomb_shorten */
486                 if (s->version == 0)
487                     residual_size--;
488             }
489
490             if (s->nmean == 0)
491                 coffset = s->offset[channel][0];
492             else {
493                 int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;
494                 for (i=0; i<s->nmean; i++)
495                     sum += s->offset[channel][i];
496                 coffset = sum / s->nmean;
497                 if (s->version >= 2)
498                     coffset >>= FFMIN(1, s->bitshift);
499             }
500             switch (cmd) {
501                 case FN_ZERO:
502                     for (i=0; i<s->blocksize; i++)
503                         s->decoded[channel][i] = 0;
504                     break;
505                 case FN_DIFF0:
506                     for (i=0; i<s->blocksize; i++)
507                         s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + coffset;
508                     break;
509                 case FN_DIFF1:
510                     for (i=0; i<s->blocksize; i++)
511                         s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + s->decoded[channel][i - 1];
512                     break;
513                 case FN_DIFF2:
514                     for (i=0; i<s->blocksize; i++)
515                         s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + 2*s->decoded[channel][i-1]
516                                                                                               -   s->decoded[channel][i-2];
517                     break;
518                 case FN_DIFF3:
519                     for (i=0; i<s->blocksize; i++)
520                         s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + 3*s->decoded[channel][i-1]
521                                                                                               - 3*s->decoded[channel][i-2]
522                                                                                               +   s->decoded[channel][i-3];
523                     break;
524                 case FN_QLPC:
525                     if ((ret = decode_subframe_lpc(s, channel, residual_size, coffset)) < 0)
526                         return ret;
527                     break;
528             }
529             if (s->nmean > 0) {
530                 int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2;
531                 for (i=0; i<s->blocksize; i++)
532                     sum += s->decoded[channel][i];
533
534                 for (i=1; i<s->nmean; i++)
535                     s->offset[channel][i-1] = s->offset[channel][i];
536
537                 if (s->version < 2)
538                     s->offset[channel][s->nmean - 1] = sum / s->blocksize;
539                 else
540                     s->offset[channel][s->nmean - 1] = (sum / s->blocksize) << s->bitshift;
541             }
542             for (i=-s->nwrap; i<0; i++)
543                 s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];
544
545             fix_bitshift(s, s->decoded[channel]);
546
547             s->cur_chan++;
548             if (s->cur_chan == s->channels) {
549                 samples = interleave_buffer(samples, s->channels, s->blocksize, s->decoded);
550                 s->cur_chan = 0;
551                 *data_size = (int8_t *)samples - (int8_t *)data;
552             } else {
553                 *data_size = 0;
554             }
555         }
556     }
557
558     s->bitindex = get_bits_count(&s->gb) - 8*((get_bits_count(&s->gb))/8);
559     i= (get_bits_count(&s->gb))/8;
560     if (i > buf_size) {
561         av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
562         s->bitstream_size=0;
563         s->bitstream_index=0;
564         return -1;
565     }
566     if (s->bitstream_size) {
567         s->bitstream_index += i;
568         s->bitstream_size  -= i;
569         return input_buf_size;
570     } else
571         return i;
572 }
573
574 static av_cold int shorten_decode_close(AVCodecContext *avctx)
575 {
576     ShortenContext *s = avctx->priv_data;
577     int i;
578
579     for (i = 0; i < s->channels; i++) {
580         s->decoded[i] -= s->nwrap;
581         av_freep(&s->decoded[i]);
582         av_freep(&s->offset[i]);
583     }
584     av_freep(&s->bitstream);
585     av_freep(&s->coeffs);
586     return 0;
587 }
588
589 AVCodec ff_shorten_decoder = {
590     .name           = "shorten",
591     .type           = AVMEDIA_TYPE_AUDIO,
592     .id             = CODEC_ID_SHORTEN,
593     .priv_data_size = sizeof(ShortenContext),
594     .init           = shorten_decode_init,
595     .close          = shorten_decode_close,
596     .decode         = shorten_decode_frame,
597     .long_name= NULL_IF_CONFIG_SMALL("Shorten"),
598 };