shorten: separate processing of audio commands from non-audio commands
[ffmpeg.git] / 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     }
389     else
390     {
391         int cmd;
392         int len;
393         cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
394
395         if (cmd > FN_VERBATIM) {
396             av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);
397             if (s->bitstream_size > 0) {
398                 s->bitstream_index++;
399                 s->bitstream_size--;
400             }
401             return -1;
402         }
403
404         if (!is_audio_command[cmd]) {
405             /* process non-audio command */
406             switch (cmd) {
407                 case FN_VERBATIM:
408                     len = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
409                     while (len--) {
410                         get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
411                     }
412                     break;
413                 case FN_BITSHIFT:
414                     s->bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);
415                     break;
416                 case FN_BLOCKSIZE: {
417                     int blocksize = get_uint(s, av_log2(s->blocksize));
418                     if (blocksize > s->blocksize) {
419                         av_log(avctx, AV_LOG_ERROR, "Increasing block size is not supported\n");
420                         return AVERROR_PATCHWELCOME;
421                     }
422                     s->blocksize = blocksize;
423                     break;
424                 }
425                 case FN_QUIT:
426                     goto frame_done;
427             }
428         } else {
429             /* process audio command */
430                     int residual_size = 0;
431                     int channel = s->cur_chan;
432                     int32_t coffset;
433                     if (cmd != FN_ZERO) {
434                         residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);
435                         /* this is a hack as version 0 differed in defintion of get_sr_golomb_shorten */
436                         if (s->version == 0)
437                             residual_size--;
438                     }
439
440                     if (s->nmean == 0)
441                         coffset = s->offset[channel][0];
442                     else {
443                         int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;
444                         for (i=0; i<s->nmean; i++)
445                             sum += s->offset[channel][i];
446                         coffset = sum / s->nmean;
447                         if (s->version >= 2)
448                             coffset >>= FFMIN(1, s->bitshift);
449                     }
450                     switch (cmd) {
451                         case FN_ZERO:
452                             for (i=0; i<s->blocksize; i++)
453                                 s->decoded[channel][i] = 0;
454                             break;
455                         case FN_DIFF0:
456                             for (i=0; i<s->blocksize; i++)
457                                 s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + coffset;
458                             break;
459                         case FN_DIFF1:
460                             for (i=0; i<s->blocksize; i++)
461                                 s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + s->decoded[channel][i - 1];
462                             break;
463                         case FN_DIFF2:
464                             for (i=0; i<s->blocksize; i++)
465                                 s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + 2*s->decoded[channel][i-1]
466                                                                                                       -   s->decoded[channel][i-2];
467                             break;
468                         case FN_DIFF3:
469                             for (i=0; i<s->blocksize; i++)
470                                 s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + 3*s->decoded[channel][i-1]
471                                                                                                       - 3*s->decoded[channel][i-2]
472                                                                                                       +   s->decoded[channel][i-3];
473                             break;
474                         case FN_QLPC:
475                             {
476                                 int pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
477                                 if (pred_order > s->nwrap) {
478                                     av_log(avctx, AV_LOG_ERROR,
479                                            "invalid pred_order %d\n",
480                                            pred_order);
481                                     return -1;
482                                 }
483                                 for (i=0; i<pred_order; i++)
484                                     s->decoded[channel][i - pred_order] -= coffset;
485                                 decode_subframe_lpc(s, channel, residual_size, pred_order);
486                                 if (coffset != 0)
487                                     for (i=0; i < s->blocksize; i++)
488                                         s->decoded[channel][i] += coffset;
489                             }
490                     }
491                     if (s->nmean > 0) {
492                         int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2;
493                         for (i=0; i<s->blocksize; i++)
494                             sum += s->decoded[channel][i];
495
496                         for (i=1; i<s->nmean; i++)
497                             s->offset[channel][i-1] = s->offset[channel][i];
498
499                         if (s->version < 2)
500                             s->offset[channel][s->nmean - 1] = sum / s->blocksize;
501                         else
502                             s->offset[channel][s->nmean - 1] = (sum / s->blocksize) << s->bitshift;
503                     }
504                     for (i=-s->nwrap; i<0; i++)
505                         s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];
506
507                     fix_bitshift(s, s->decoded[channel]);
508
509                     s->cur_chan++;
510                     if (s->cur_chan == s->channels) {
511                         samples = interleave_buffer(samples, s->channels, s->blocksize, s->decoded);
512                         s->cur_chan = 0;
513                         goto frame_done;
514                     }
515         }
516     }
517 frame_done:
518     *data_size = (int8_t *)samples - (int8_t *)data;
519
520     //    s->last_blocksize = s->blocksize;
521     s->bitindex = get_bits_count(&s->gb) - 8*((get_bits_count(&s->gb))/8);
522     i= (get_bits_count(&s->gb))/8;
523     if (i > buf_size) {
524         av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
525         s->bitstream_size=0;
526         s->bitstream_index=0;
527         return -1;
528     }
529     if (s->bitstream_size) {
530         s->bitstream_index += i;
531         s->bitstream_size  -= i;
532         return input_buf_size;
533     } else
534         return i;
535 }
536
537 static av_cold int shorten_decode_close(AVCodecContext *avctx)
538 {
539     ShortenContext *s = avctx->priv_data;
540     int i;
541
542     for (i = 0; i < s->channels; i++) {
543         s->decoded[i] -= s->nwrap;
544         av_freep(&s->decoded[i]);
545         av_freep(&s->offset[i]);
546     }
547     av_freep(&s->bitstream);
548     av_freep(&s->coeffs);
549     return 0;
550 }
551
552 AVCodec ff_shorten_decoder = {
553     .name           = "shorten",
554     .type           = AVMEDIA_TYPE_AUDIO,
555     .id             = CODEC_ID_SHORTEN,
556     .priv_data_size = sizeof(ShortenContext),
557     .init           = shorten_decode_init,
558     .close          = shorten_decode_close,
559     .decode         = shorten_decode_frame,
560     .long_name= NULL_IF_CONFIG_SMALL("Shorten"),
561 };