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