2f3a1fe168f810aa9e2d0a459a2ff2ea09a833f2
[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 av_cold 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 inline int get_le32(GetBitContext *gb)
176 {
177     return bswap_32(get_bits_long(gb, 32));
178 }
179
180 static inline short 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         const 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(avctx, "wanna more data ... %d\n", buf_size);
297             *data_size = 0;
298             return input_buf_size;
299         }
300     }
301     init_get_bits(&s->gb, buf, buf_size*8);
302     skip_bits(&s->gb, s->bitindex);
303     if (!s->blocksize)
304     {
305         int maxnlpc = 0;
306         /* shorten signature */
307         if (get_bits_long(&s->gb, 32) != bswap_32(ff_get_fourcc("ajkg"))) {
308             av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
309             return -1;
310         }
311
312         s->lpcqoffset = 0;
313         s->blocksize = DEFAULT_BLOCK_SIZE;
314         s->channels = 1;
315         s->nmean = -1;
316         s->version = get_bits(&s->gb, 8);
317         s->internal_ftype = get_uint(s, TYPESIZE);
318
319         s->channels = get_uint(s, CHANSIZE);
320         if (s->channels > MAX_CHANNELS) {
321             av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
322             return -1;
323         }
324
325         /* get blocksize if version > 0 */
326         if (s->version > 0) {
327             int skip_bytes;
328             s->blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
329             maxnlpc = get_uint(s, LPCQSIZE);
330             s->nmean = get_uint(s, 0);
331
332             skip_bytes = get_uint(s, NSKIPSIZE);
333             for (i=0; i<skip_bytes; i++) {
334                 skip_bits(&s->gb, 8);
335             }
336         }
337         s->nwrap = FFMAX(NWRAP, maxnlpc);
338
339         if (allocate_buffers(s))
340             return -1;
341
342         init_offset(s);
343
344         if (s->version > 1)
345             s->lpcqoffset = V2LPCQOFFSET;
346
347         if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
348             av_log(s->avctx, AV_LOG_ERROR, "missing verbatim section at beginning of stream\n");
349             return -1;
350         }
351
352         s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
353         if (s->header_size >= OUT_BUFFER_SIZE || s->header_size < CANONICAL_HEADER_SIZE) {
354             av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n", s->header_size);
355             return -1;
356         }
357
358         for (i=0; i<s->header_size; i++)
359             s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
360
361         if (decode_wave_header(avctx, s->header, s->header_size) < 0)
362             return -1;
363
364         s->cur_chan = 0;
365         s->bitshift = 0;
366     }
367     else
368     {
369         int cmd;
370         int len;
371         cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
372         switch (cmd) {
373             case FN_ZERO:
374             case FN_DIFF0:
375             case FN_DIFF1:
376             case FN_DIFF2:
377             case FN_DIFF3:
378             case FN_QLPC:
379                 {
380                     int residual_size = 0;
381                     int channel = s->cur_chan;
382                     int32_t coffset;
383                     if (cmd != FN_ZERO) {
384                         residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);
385                         /* this is a hack as version 0 differed in defintion of get_sr_golomb_shorten */
386                         if (s->version == 0)
387                             residual_size--;
388                     }
389
390                     if (s->nmean == 0)
391                         coffset = s->offset[channel][0];
392                     else {
393                         int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;
394                         for (i=0; i<s->nmean; i++)
395                             sum += s->offset[channel][i];
396                         coffset = sum / s->nmean;
397                         if (s->version >= 2)
398                             coffset >>= FFMIN(1, s->bitshift);
399                     }
400                     switch (cmd) {
401                         case FN_ZERO:
402                             for (i=0; i<s->blocksize; i++)
403                                 s->decoded[channel][i] = 0;
404                             break;
405                         case FN_DIFF0:
406                             for (i=0; i<s->blocksize; i++)
407                                 s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + coffset;
408                             break;
409                         case FN_DIFF1:
410                             for (i=0; i<s->blocksize; i++)
411                                 s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + s->decoded[channel][i - 1];
412                             break;
413                         case FN_DIFF2:
414                             for (i=0; i<s->blocksize; i++)
415                                 s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + 2*s->decoded[channel][i-1]
416                                                                                                       -   s->decoded[channel][i-2];
417                             break;
418                         case FN_DIFF3:
419                             for (i=0; i<s->blocksize; i++)
420                                 s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + 3*s->decoded[channel][i-1]
421                                                                                                       - 3*s->decoded[channel][i-2]
422                                                                                                       +   s->decoded[channel][i-3];
423                             break;
424                         case FN_QLPC:
425                             {
426                                 int pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
427                                 for (i=0; i<pred_order; i++)
428                                     s->decoded[channel][i - pred_order] -= coffset;
429                                 decode_subframe_lpc(s, channel, residual_size, pred_order);
430                                 if (coffset != 0)
431                                     for (i=0; i < s->blocksize; i++)
432                                         s->decoded[channel][i] += coffset;
433                             }
434                     }
435                     if (s->nmean > 0) {
436                         int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2;
437                         for (i=0; i<s->blocksize; i++)
438                             sum += s->decoded[channel][i];
439
440                         for (i=1; i<s->nmean; i++)
441                             s->offset[channel][i-1] = s->offset[channel][i];
442
443                         if (s->version < 2)
444                             s->offset[channel][s->nmean - 1] = sum / s->blocksize;
445                         else
446                             s->offset[channel][s->nmean - 1] = (sum / s->blocksize) << s->bitshift;
447                     }
448                     for (i=-s->nwrap; i<0; i++)
449                         s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];
450
451                     fix_bitshift(s, s->decoded[channel]);
452
453                     s->cur_chan++;
454                     if (s->cur_chan == s->channels) {
455                         samples = interleave_buffer(samples, s->channels, s->blocksize, s->decoded);
456                         s->cur_chan = 0;
457                         goto frame_done;
458                     }
459                     break;
460                 }
461                 break;
462             case FN_VERBATIM:
463                 len = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
464                 while (len--) {
465                     get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
466                 }
467                 break;
468             case FN_BITSHIFT:
469                 s->bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);
470                 break;
471             case FN_BLOCKSIZE:
472                 s->blocksize = get_uint(s, av_log2(s->blocksize));
473                 break;
474             case FN_QUIT:
475                 *data_size = 0;
476                 return buf_size;
477                 break;
478             default:
479                 av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);
480                 return -1;
481                 break;
482         }
483     }
484 frame_done:
485     *data_size = (int8_t *)samples - (int8_t *)data;
486
487     //    s->last_blocksize = s->blocksize;
488     s->bitindex = get_bits_count(&s->gb) - 8*((get_bits_count(&s->gb))/8);
489     i= (get_bits_count(&s->gb))/8;
490     if (i > buf_size) {
491         av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
492         s->bitstream_size=0;
493         s->bitstream_index=0;
494         return -1;
495     }
496     if (s->bitstream_size) {
497         s->bitstream_index += i;
498         s->bitstream_size  -= i;
499         return input_buf_size;
500     } else
501         return i;
502 }
503
504 static av_cold int shorten_decode_close(AVCodecContext *avctx)
505 {
506     ShortenContext *s = avctx->priv_data;
507     int i;
508
509     for (i = 0; i < s->channels; i++) {
510         s->decoded[i] -= s->nwrap;
511         av_freep(&s->decoded[i]);
512         av_freep(&s->offset[i]);
513     }
514     av_freep(&s->bitstream);
515     return 0;
516 }
517
518 static void shorten_flush(AVCodecContext *avctx){
519     ShortenContext *s = avctx->priv_data;
520
521     s->bitstream_size=
522         s->bitstream_index= 0;
523 }
524
525 AVCodec shorten_decoder = {
526     "shorten",
527     CODEC_TYPE_AUDIO,
528     CODEC_ID_SHORTEN,
529     sizeof(ShortenContext),
530     shorten_decode_init,
531     NULL,
532     shorten_decode_close,
533     shorten_decode_frame,
534     .flush= shorten_flush,
535 };