]> git.sesse.net Git - ffmpeg/blob - libavcodec/shorten.c
h264: Fix parameters to ff_er_add_slice() call
[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 "bytestream.h"
32 #include "get_bits.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 /** indicates if the FN_* command is audio or non-audio */
74 static const uint8_t is_audio_command[10] = { 1, 1, 1, 1, 0, 0, 0, 1, 1, 0 };
75
76 #define VERBATIM_CKSIZE_SIZE 5
77 #define VERBATIM_BYTE_SIZE 8
78 #define CANONICAL_HEADER_SIZE 44
79
80 typedef struct ShortenContext {
81     AVCodecContext *avctx;
82     AVFrame frame;
83     GetBitContext gb;
84
85     int min_framesize, max_framesize;
86     int channels;
87
88     int32_t *decoded[MAX_CHANNELS];
89     int32_t *decoded_base[MAX_CHANNELS];
90     int32_t *offset[MAX_CHANNELS];
91     int *coeffs;
92     uint8_t *bitstream;
93     int bitstream_size;
94     int bitstream_index;
95     unsigned int allocated_bitstream_size;
96     int header_size;
97     uint8_t header[OUT_BUFFER_SIZE];
98     int version;
99     int cur_chan;
100     int bitshift;
101     int nmean;
102     int internal_ftype;
103     int nwrap;
104     int blocksize;
105     int bitindex;
106     int32_t lpcqoffset;
107     int got_header;
108     int got_quit_command;
109 } ShortenContext;
110
111 static av_cold int shorten_decode_init(AVCodecContext * avctx)
112 {
113     ShortenContext *s = avctx->priv_data;
114     s->avctx = avctx;
115     avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
116
117     avcodec_get_frame_defaults(&s->frame);
118     avctx->coded_frame = &s->frame;
119
120     return 0;
121 }
122
123 static int allocate_buffers(ShortenContext *s)
124 {
125     int i, chan;
126     int *coeffs;
127     void *tmp_ptr;
128
129     for (chan=0; chan<s->channels; chan++) {
130         if(FFMAX(1, s->nmean) >= UINT_MAX/sizeof(int32_t)){
131             av_log(s->avctx, AV_LOG_ERROR, "nmean too large\n");
132             return -1;
133         }
134         if(s->blocksize + s->nwrap >= UINT_MAX/sizeof(int32_t) || s->blocksize + s->nwrap <= (unsigned)s->nwrap){
135             av_log(s->avctx, AV_LOG_ERROR, "s->blocksize + s->nwrap too large\n");
136             return -1;
137         }
138
139         tmp_ptr = av_realloc(s->offset[chan], sizeof(int32_t)*FFMAX(1, s->nmean));
140         if (!tmp_ptr)
141             return AVERROR(ENOMEM);
142         s->offset[chan] = tmp_ptr;
143
144         tmp_ptr = av_realloc(s->decoded_base[chan], (s->blocksize + s->nwrap) *
145                              sizeof(s->decoded_base[0][0]));
146         if (!tmp_ptr)
147             return AVERROR(ENOMEM);
148         s->decoded_base[chan] = tmp_ptr;
149         for (i=0; i<s->nwrap; i++)
150             s->decoded_base[chan][i] = 0;
151         s->decoded[chan] = s->decoded_base[chan] + s->nwrap;
152     }
153
154     coeffs = av_realloc(s->coeffs, s->nwrap * sizeof(*s->coeffs));
155     if (!coeffs)
156         return AVERROR(ENOMEM);
157     s->coeffs = coeffs;
158
159     return 0;
160 }
161
162
163 static inline unsigned int get_uint(ShortenContext *s, int k)
164 {
165     if (s->version != 0)
166         k = get_ur_golomb_shorten(&s->gb, ULONGSIZE);
167     return get_ur_golomb_shorten(&s->gb, k);
168 }
169
170
171 static void fix_bitshift(ShortenContext *s, int32_t *buffer)
172 {
173     int i;
174
175     if (s->bitshift != 0)
176         for (i = 0; i < s->blocksize; i++)
177             buffer[i] <<= s->bitshift;
178 }
179
180
181 static int init_offset(ShortenContext *s)
182 {
183     int32_t mean = 0;
184     int  chan, i;
185     int nblock = FFMAX(1, s->nmean);
186     /* initialise offset */
187     switch (s->internal_ftype)
188     {
189         case TYPE_S16HL:
190         case TYPE_S16LH:
191             mean = 0;
192             break;
193         default:
194             av_log(s->avctx, AV_LOG_ERROR, "unknown audio type");
195             return AVERROR_INVALIDDATA;
196     }
197
198     for (chan = 0; chan < s->channels; chan++)
199         for (i = 0; i < nblock; i++)
200             s->offset[chan][i] = mean;
201     return 0;
202 }
203
204 static int decode_wave_header(AVCodecContext *avctx, const uint8_t *header,
205                               int header_size)
206 {
207     int len;
208     short wave_format;
209
210
211     if (bytestream_get_le32(&header) != MKTAG('R','I','F','F')) {
212         av_log(avctx, AV_LOG_ERROR, "missing RIFF tag\n");
213         return -1;
214     }
215
216     header += 4; /* chunk size */;
217
218     if (bytestream_get_le32(&header) != MKTAG('W','A','V','E')) {
219         av_log(avctx, AV_LOG_ERROR, "missing WAVE tag\n");
220         return -1;
221     }
222
223     while (bytestream_get_le32(&header) != MKTAG('f','m','t',' ')) {
224         len = bytestream_get_le32(&header);
225         header += len;
226     }
227     len = bytestream_get_le32(&header);
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 = bytestream_get_le16(&header);
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     header += 2;        // skip channels    (already got from shorten header)
245     avctx->sample_rate = bytestream_get_le32(&header);
246     header += 4;        // skip bit rate    (represents original uncompressed bit rate)
247     header += 2;        // skip block align (not needed)
248     avctx->bits_per_coded_sample = bytestream_get_le16(&header);
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 void output_buffer(int16_t **samples, int nchan, int blocksize,
263                           int32_t **buffer)
264 {
265     int i, ch;
266     for (ch = 0; ch < nchan; ch++) {
267         int32_t *in  = buffer[ch];
268         int16_t *out = samples[ch];
269         for (i = 0; i < blocksize; i++)
270             out[i] = av_clip_int16(in[i]);
271     }
272 }
273
274 static const int fixed_coeffs[3][3] = {
275     { 1,  0,  0 },
276     { 2, -1,  0 },
277     { 3, -3,  1 }
278 };
279
280 static int decode_subframe_lpc(ShortenContext *s, int command, int channel,
281                                int residual_size, int32_t coffset)
282 {
283     int pred_order, sum, qshift, init_sum, i, j;
284     const int *coeffs;
285
286     if (command == FN_QLPC) {
287         /* read/validate prediction order */
288         pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
289         if (pred_order > s->nwrap) {
290             av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n", pred_order);
291             return AVERROR(EINVAL);
292         }
293         /* read LPC coefficients */
294         for (i=0; i<pred_order; i++)
295             s->coeffs[i] = get_sr_golomb_shorten(&s->gb, LPCQUANT);
296         coeffs = s->coeffs;
297
298         qshift = LPCQUANT;
299     } else {
300         /* fixed LPC coeffs */
301         pred_order = command;
302         coeffs     = fixed_coeffs[pred_order-1];
303         qshift     = 0;
304     }
305
306     /* subtract offset from previous samples to use in prediction */
307     if (command == FN_QLPC && coffset)
308         for (i = -pred_order; i < 0; i++)
309             s->decoded[channel][i] -= coffset;
310
311     /* decode residual and do LPC prediction */
312     init_sum = pred_order ? (command == FN_QLPC ? s->lpcqoffset : 0) : coffset;
313     for (i=0; i < s->blocksize; i++) {
314         sum = init_sum;
315         for (j=0; j<pred_order; j++)
316             sum += coeffs[j] * s->decoded[channel][i-j-1];
317         s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + (sum >> qshift);
318     }
319
320     /* add offset to current samples */
321     if (command == FN_QLPC && coffset)
322         for (i = 0; i < s->blocksize; i++)
323             s->decoded[channel][i] += coffset;
324
325     return 0;
326 }
327
328 static int read_header(ShortenContext *s)
329 {
330     int i, ret;
331     int maxnlpc = 0;
332     /* shorten signature */
333     if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {
334         av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
335         return -1;
336     }
337
338     s->lpcqoffset = 0;
339     s->blocksize = DEFAULT_BLOCK_SIZE;
340     s->nmean = -1;
341     s->version = get_bits(&s->gb, 8);
342     s->internal_ftype = get_uint(s, TYPESIZE);
343
344     s->channels = get_uint(s, CHANSIZE);
345     if (s->channels <= 0 || s->channels > MAX_CHANNELS) {
346         av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
347         return -1;
348     }
349     s->avctx->channels = s->channels;
350
351     /* get blocksize if version > 0 */
352     if (s->version > 0) {
353         int skip_bytes, blocksize;
354
355         blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
356         if (!blocksize || blocksize > MAX_BLOCKSIZE) {
357             av_log(s->avctx, AV_LOG_ERROR, "invalid or unsupported block size: %d\n",
358                    blocksize);
359             return AVERROR(EINVAL);
360         }
361         s->blocksize = blocksize;
362
363         maxnlpc = get_uint(s, LPCQSIZE);
364         s->nmean = get_uint(s, 0);
365
366         skip_bytes = get_uint(s, NSKIPSIZE);
367         for (i=0; i<skip_bytes; i++) {
368             skip_bits(&s->gb, 8);
369         }
370     }
371     s->nwrap = FFMAX(NWRAP, maxnlpc);
372
373     if ((ret = allocate_buffers(s)) < 0)
374         return ret;
375
376     if ((ret = init_offset(s)) < 0)
377         return ret;
378
379     if (s->version > 1)
380         s->lpcqoffset = V2LPCQOFFSET;
381
382     if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
383         av_log(s->avctx, AV_LOG_ERROR, "missing verbatim section at beginning of stream\n");
384         return -1;
385     }
386
387     s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
388     if (s->header_size >= OUT_BUFFER_SIZE || s->header_size < CANONICAL_HEADER_SIZE) {
389         av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n", s->header_size);
390         return -1;
391     }
392
393     for (i=0; i<s->header_size; i++)
394         s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
395
396     if (decode_wave_header(s->avctx, s->header, s->header_size) < 0)
397         return -1;
398
399     s->cur_chan = 0;
400     s->bitshift = 0;
401
402     s->got_header = 1;
403
404     return 0;
405 }
406
407 static int shorten_decode_frame(AVCodecContext *avctx, void *data,
408                                 int *got_frame_ptr, AVPacket *avpkt)
409 {
410     const uint8_t *buf = avpkt->data;
411     int buf_size = avpkt->size;
412     ShortenContext *s = avctx->priv_data;
413     int i, input_buf_size = 0;
414     int ret;
415
416     /* allocate internal bitstream buffer */
417     if(s->max_framesize == 0){
418         void *tmp_ptr;
419         s->max_framesize= 1024; // should hopefully be enough for the first header
420         tmp_ptr = av_fast_realloc(s->bitstream, &s->allocated_bitstream_size,
421                                   s->max_framesize);
422         if (!tmp_ptr) {
423             av_log(avctx, AV_LOG_ERROR, "error allocating bitstream buffer\n");
424             return AVERROR(ENOMEM);
425         }
426         s->bitstream = tmp_ptr;
427     }
428
429     /* append current packet data to bitstream buffer */
430     if(1 && s->max_framesize){//FIXME truncated
431         buf_size= FFMIN(buf_size, s->max_framesize - s->bitstream_size);
432         input_buf_size= buf_size;
433
434         if(s->bitstream_index + s->bitstream_size + buf_size > s->allocated_bitstream_size){
435             memmove(s->bitstream, &s->bitstream[s->bitstream_index], s->bitstream_size);
436             s->bitstream_index=0;
437         }
438         if (buf)
439             memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size], buf, buf_size);
440         buf= &s->bitstream[s->bitstream_index];
441         buf_size += s->bitstream_size;
442         s->bitstream_size= buf_size;
443
444         /* do not decode until buffer has at least max_framesize bytes or
445            the end of the file has been reached */
446         if (buf_size < s->max_framesize && avpkt->data) {
447             *got_frame_ptr = 0;
448             return input_buf_size;
449         }
450     }
451     /* init and position bitstream reader */
452     init_get_bits(&s->gb, buf, buf_size*8);
453     skip_bits(&s->gb, s->bitindex);
454
455     /* process header or next subblock */
456     if (!s->got_header) {
457         if ((ret = read_header(s)) < 0)
458             return ret;
459         *got_frame_ptr = 0;
460         goto finish_frame;
461     }
462
463     /* if quit command was read previously, don't decode anything */
464     if (s->got_quit_command) {
465         *got_frame_ptr = 0;
466         return avpkt->size;
467     }
468
469     s->cur_chan = 0;
470     while (s->cur_chan < s->channels) {
471         int cmd;
472         int len;
473
474         if (get_bits_left(&s->gb) < 3+FNSIZE) {
475             *got_frame_ptr = 0;
476             break;
477         }
478
479         cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
480
481         if (cmd > FN_VERBATIM) {
482             av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);
483             *got_frame_ptr = 0;
484             break;
485         }
486
487         if (!is_audio_command[cmd]) {
488             /* process non-audio command */
489             switch (cmd) {
490                 case FN_VERBATIM:
491                     len = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
492                     while (len--) {
493                         get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
494                     }
495                     break;
496                 case FN_BITSHIFT:
497                     s->bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);
498                     break;
499                 case FN_BLOCKSIZE: {
500                     int blocksize = get_uint(s, av_log2(s->blocksize));
501                     if (blocksize > s->blocksize) {
502                         av_log(avctx, AV_LOG_ERROR, "Increasing block size is not supported\n");
503                         return AVERROR_PATCHWELCOME;
504                     }
505                     if (!blocksize || blocksize > MAX_BLOCKSIZE) {
506                         av_log(avctx, AV_LOG_ERROR, "invalid or unsupported "
507                                "block size: %d\n", blocksize);
508                         return AVERROR(EINVAL);
509                     }
510                     s->blocksize = blocksize;
511                     break;
512                 }
513                 case FN_QUIT:
514                     s->got_quit_command = 1;
515                     break;
516             }
517             if (cmd == FN_BLOCKSIZE || cmd == FN_QUIT) {
518                 *got_frame_ptr = 0;
519                 break;
520             }
521         } else {
522             /* process audio command */
523             int residual_size = 0;
524             int channel = s->cur_chan;
525             int32_t coffset;
526
527             /* get Rice code for residual decoding */
528             if (cmd != FN_ZERO) {
529                 residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);
530                 /* this is a hack as version 0 differed in defintion of get_sr_golomb_shorten */
531                 if (s->version == 0)
532                     residual_size--;
533             }
534
535             /* calculate sample offset using means from previous blocks */
536             if (s->nmean == 0)
537                 coffset = s->offset[channel][0];
538             else {
539                 int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;
540                 for (i=0; i<s->nmean; i++)
541                     sum += s->offset[channel][i];
542                 coffset = sum / s->nmean;
543                 if (s->version >= 2)
544                     coffset >>= FFMIN(1, s->bitshift);
545             }
546
547             /* decode samples for this channel */
548             if (cmd == FN_ZERO) {
549                 for (i=0; i<s->blocksize; i++)
550                     s->decoded[channel][i] = 0;
551             } else {
552                 if ((ret = decode_subframe_lpc(s, cmd, channel, residual_size, coffset)) < 0)
553                     return ret;
554             }
555
556             /* update means with info from the current block */
557             if (s->nmean > 0) {
558                 int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2;
559                 for (i=0; i<s->blocksize; i++)
560                     sum += s->decoded[channel][i];
561
562                 for (i=1; i<s->nmean; i++)
563                     s->offset[channel][i-1] = s->offset[channel][i];
564
565                 if (s->version < 2)
566                     s->offset[channel][s->nmean - 1] = sum / s->blocksize;
567                 else
568                     s->offset[channel][s->nmean - 1] = (sum / s->blocksize) << s->bitshift;
569             }
570
571             /* copy wrap samples for use with next block */
572             for (i=-s->nwrap; i<0; i++)
573                 s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];
574
575             /* shift samples to add in unused zero bits which were removed
576                during encoding */
577             fix_bitshift(s, s->decoded[channel]);
578
579             /* if this is the last channel in the block, output the samples */
580             s->cur_chan++;
581             if (s->cur_chan == s->channels) {
582                 /* get output buffer */
583                 s->frame.nb_samples = s->blocksize;
584                 if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
585                     av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
586                     return ret;
587                 }
588                 /* interleave output */
589                 output_buffer((int16_t **)s->frame.extended_data, s->channels,
590                               s->blocksize, s->decoded);
591
592                 *got_frame_ptr   = 1;
593                 *(AVFrame *)data = s->frame;
594             }
595         }
596     }
597     if (s->cur_chan < s->channels)
598         *got_frame_ptr = 0;
599
600 finish_frame:
601     s->bitindex = get_bits_count(&s->gb) - 8*((get_bits_count(&s->gb))/8);
602     i= (get_bits_count(&s->gb))/8;
603     if (i > buf_size) {
604         av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
605         s->bitstream_size=0;
606         s->bitstream_index=0;
607         return -1;
608     }
609     if (s->bitstream_size) {
610         s->bitstream_index += i;
611         s->bitstream_size  -= i;
612         return input_buf_size;
613     } else
614         return i;
615 }
616
617 static av_cold int shorten_decode_close(AVCodecContext *avctx)
618 {
619     ShortenContext *s = avctx->priv_data;
620     int i;
621
622     for (i = 0; i < s->channels; i++) {
623         s->decoded[i] = NULL;
624         av_freep(&s->decoded_base[i]);
625         av_freep(&s->offset[i]);
626     }
627     av_freep(&s->bitstream);
628     av_freep(&s->coeffs);
629
630     return 0;
631 }
632
633 AVCodec ff_shorten_decoder = {
634     .name           = "shorten",
635     .type           = AVMEDIA_TYPE_AUDIO,
636     .id             = AV_CODEC_ID_SHORTEN,
637     .priv_data_size = sizeof(ShortenContext),
638     .init           = shorten_decode_init,
639     .close          = shorten_decode_close,
640     .decode         = shorten_decode_frame,
641     .capabilities   = CODEC_CAP_DELAY | CODEC_CAP_DR1,
642     .long_name      = NULL_IF_CONFIG_SMALL("Shorten"),
643     .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
644                                                       AV_SAMPLE_FMT_NONE },
645 };