]> git.sesse.net Git - ffmpeg/blob - libavcodec/shorten.c
avcodec/nvenc: Bring encoder names in line with other encoders
[ffmpeg] / 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
24  * Shorten decoder
25  * @author Jeff Muizelaar
26  */
27
28 #include <limits.h>
29 #include "avcodec.h"
30 #include "bytestream.h"
31 #include "get_bits.h"
32 #include "golomb.h"
33 #include "internal.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_S8    1
53 #define TYPE_U8    2
54 #define TYPE_S16HL 3
55 #define TYPE_U16HL 4
56 #define TYPE_S16LH 5
57 #define TYPE_U16LH 6
58
59 #define NWRAP 3
60 #define NSKIPSIZE 1
61
62 #define LPCQUANT 5
63 #define V2LPCQOFFSET (1 << LPCQUANT)
64
65 #define FNSIZE 2
66 #define FN_DIFF0        0
67 #define FN_DIFF1        1
68 #define FN_DIFF2        2
69 #define FN_DIFF3        3
70 #define FN_QUIT         4
71 #define FN_BLOCKSIZE    5
72 #define FN_BITSHIFT     6
73 #define FN_QLPC         7
74 #define FN_ZERO         8
75 #define FN_VERBATIM     9
76
77 /** indicates if the FN_* command is audio or non-audio */
78 static const uint8_t is_audio_command[10] = { 1, 1, 1, 1, 0, 0, 0, 1, 1, 0 };
79
80 #define VERBATIM_CKSIZE_SIZE 5
81 #define VERBATIM_BYTE_SIZE 8
82 #define CANONICAL_HEADER_SIZE 44
83
84 typedef struct ShortenContext {
85     AVCodecContext *avctx;
86     GetBitContext gb;
87
88     int min_framesize, max_framesize;
89     unsigned channels;
90
91     int32_t *decoded[MAX_CHANNELS];
92     int32_t *decoded_base[MAX_CHANNELS];
93     int32_t *offset[MAX_CHANNELS];
94     int *coeffs;
95     uint8_t *bitstream;
96     int bitstream_size;
97     int bitstream_index;
98     unsigned int allocated_bitstream_size;
99     int header_size;
100     uint8_t header[OUT_BUFFER_SIZE];
101     int version;
102     int cur_chan;
103     int bitshift;
104     int nmean;
105     int internal_ftype;
106     int nwrap;
107     int blocksize;
108     int bitindex;
109     int32_t lpcqoffset;
110     int got_header;
111     int got_quit_command;
112 } ShortenContext;
113
114 static av_cold int shorten_decode_init(AVCodecContext *avctx)
115 {
116     ShortenContext *s = avctx->priv_data;
117     s->avctx          = avctx;
118
119     return 0;
120 }
121
122 static int allocate_buffers(ShortenContext *s)
123 {
124     int i, chan, err;
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 AVERROR_INVALIDDATA;
130         }
131         if (s->blocksize + (uint64_t)s->nwrap >= UINT_MAX / sizeof(int32_t)) {
132             av_log(s->avctx, AV_LOG_ERROR,
133                    "s->blocksize + s->nwrap too large\n");
134             return AVERROR_INVALIDDATA;
135         }
136
137         if ((err = av_reallocp_array(&s->offset[chan],
138                                sizeof(int32_t),
139                                FFMAX(1, s->nmean))) < 0)
140             return err;
141
142         if ((err = av_reallocp_array(&s->decoded_base[chan], (s->blocksize + s->nwrap),
143                                sizeof(s->decoded_base[0][0]))) < 0)
144             return err;
145         for (i = 0; i < s->nwrap; i++)
146             s->decoded_base[chan][i] = 0;
147         s->decoded[chan] = s->decoded_base[chan] + s->nwrap;
148     }
149
150     if ((err = av_reallocp_array(&s->coeffs, s->nwrap, sizeof(*s->coeffs))) < 0)
151         return err;
152
153     return 0;
154 }
155
156 static inline unsigned int get_uint(ShortenContext *s, int k)
157 {
158     if (s->version != 0)
159         k = get_ur_golomb_shorten(&s->gb, ULONGSIZE);
160     return get_ur_golomb_shorten(&s->gb, k);
161 }
162
163 static void fix_bitshift(ShortenContext *s, int32_t *buffer)
164 {
165     int i;
166
167     if (s->bitshift == 32) {
168         for (i = 0; i < s->blocksize; i++)
169             buffer[i] = 0;
170     } else if (s->bitshift != 0) {
171         for (i = 0; i < s->blocksize; i++)
172             buffer[i] <<= s->bitshift;
173     }
174 }
175
176 static int init_offset(ShortenContext *s)
177 {
178     int32_t mean = 0;
179     int chan, i;
180     int nblock = FFMAX(1, s->nmean);
181     /* initialise offset */
182     switch (s->internal_ftype) {
183     case TYPE_U8:
184         s->avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
185         mean = 0x80;
186         break;
187     case TYPE_S16HL:
188     case TYPE_S16LH:
189         s->avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
190         break;
191     default:
192         av_log(s->avctx, AV_LOG_ERROR, "unknown audio type\n");
193         return AVERROR_PATCHWELCOME;
194     }
195
196     for (chan = 0; chan < s->channels; chan++)
197         for (i = 0; i < nblock; i++)
198             s->offset[chan][i] = mean;
199     return 0;
200 }
201
202 static int decode_aiff_header(AVCodecContext *avctx, const uint8_t *header,
203                               int header_size)
204 {
205     int len, bps, exp;
206     GetByteContext gb;
207     uint64_t val;
208     uint32_t tag;
209
210     bytestream2_init(&gb, header, header_size);
211
212     if (bytestream2_get_le32(&gb) != MKTAG('F', 'O', 'R', 'M')) {
213         av_log(avctx, AV_LOG_ERROR, "missing FORM tag\n");
214         return AVERROR_INVALIDDATA;
215     }
216
217     bytestream2_skip(&gb, 4); /* chunk size */
218
219     tag = bytestream2_get_le32(&gb);
220     if (tag != MKTAG('A', 'I', 'F', 'F')) {
221         av_log(avctx, AV_LOG_ERROR, "missing AIFF tag\n");
222         return AVERROR_INVALIDDATA;
223     }
224
225     while (bytestream2_get_le32(&gb) != MKTAG('C', 'O', 'M', 'M')) {
226         len = bytestream2_get_be32(&gb);
227         bytestream2_skip(&gb, len + (len & 1));
228         if (len < 0 || bytestream2_get_bytes_left(&gb) < 18) {
229             av_log(avctx, AV_LOG_ERROR, "no COMM chunk found\n");
230             return AVERROR_INVALIDDATA;
231         }
232     }
233     len = bytestream2_get_be32(&gb);
234
235     if (len < 18) {
236         av_log(avctx, AV_LOG_ERROR, "COMM chunk was too short\n");
237         return AVERROR_INVALIDDATA;
238     }
239
240     bytestream2_skip(&gb, 6);
241     bps = bytestream2_get_be16(&gb);
242     avctx->bits_per_coded_sample = bps;
243
244     if (bps != 16 && bps != 8) {
245         av_log(avctx, AV_LOG_ERROR, "unsupported number of bits per sample: %d\n", bps);
246         return AVERROR(ENOSYS);
247     }
248
249     exp = bytestream2_get_be16(&gb) - 16383 - 63;
250     val = bytestream2_get_be64(&gb);
251     if (exp < -63 || exp > 63) {
252         av_log(avctx, AV_LOG_ERROR, "exp %d is out of range\n", exp);
253         return AVERROR_INVALIDDATA;
254     }
255     if (exp >= 0)
256         avctx->sample_rate = val << exp;
257     else
258         avctx->sample_rate = (val + (1ULL<<(-exp-1))) >> -exp;
259     len -= 18;
260     if (len > 0)
261         av_log(avctx, AV_LOG_INFO, "%d header bytes unparsed\n", len);
262
263     return 0;
264 }
265
266 static int decode_wave_header(AVCodecContext *avctx, const uint8_t *header,
267                               int header_size)
268 {
269     int len, bps;
270     short wave_format;
271     GetByteContext gb;
272
273     bytestream2_init(&gb, header, header_size);
274
275     if (bytestream2_get_le32(&gb) != MKTAG('R', 'I', 'F', 'F')) {
276         av_log(avctx, AV_LOG_ERROR, "missing RIFF tag\n");
277         return AVERROR_INVALIDDATA;
278     }
279
280     bytestream2_skip(&gb, 4); /* chunk size */
281
282     if (bytestream2_get_le32(&gb) != MKTAG('W', 'A', 'V', 'E')) {
283         av_log(avctx, AV_LOG_ERROR, "missing WAVE tag\n");
284         return AVERROR_INVALIDDATA;
285     }
286
287     while (bytestream2_get_le32(&gb) != MKTAG('f', 'm', 't', ' ')) {
288         len = bytestream2_get_le32(&gb);
289         bytestream2_skip(&gb, len);
290         if (len < 0 || bytestream2_get_bytes_left(&gb) < 16) {
291             av_log(avctx, AV_LOG_ERROR, "no fmt chunk found\n");
292             return AVERROR_INVALIDDATA;
293         }
294     }
295     len = bytestream2_get_le32(&gb);
296
297     if (len < 16) {
298         av_log(avctx, AV_LOG_ERROR, "fmt chunk was too short\n");
299         return AVERROR_INVALIDDATA;
300     }
301
302     wave_format = bytestream2_get_le16(&gb);
303
304     switch (wave_format) {
305     case WAVE_FORMAT_PCM:
306         break;
307     default:
308         av_log(avctx, AV_LOG_ERROR, "unsupported wave format\n");
309         return AVERROR(ENOSYS);
310     }
311
312     bytestream2_skip(&gb, 2); // skip channels    (already got from shorten header)
313     avctx->sample_rate = bytestream2_get_le32(&gb);
314     bytestream2_skip(&gb, 4); // skip bit rate    (represents original uncompressed bit rate)
315     bytestream2_skip(&gb, 2); // skip block align (not needed)
316     bps = bytestream2_get_le16(&gb);
317     avctx->bits_per_coded_sample = bps;
318
319     if (bps != 16 && bps != 8) {
320         av_log(avctx, AV_LOG_ERROR, "unsupported number of bits per sample: %d\n", bps);
321         return AVERROR(ENOSYS);
322     }
323
324     len -= 16;
325     if (len > 0)
326         av_log(avctx, AV_LOG_INFO, "%d header bytes unparsed\n", len);
327
328     return 0;
329 }
330
331 static const int fixed_coeffs[][3] = {
332     { 0,  0,  0 },
333     { 1,  0,  0 },
334     { 2, -1,  0 },
335     { 3, -3,  1 }
336 };
337
338 static int decode_subframe_lpc(ShortenContext *s, int command, int channel,
339                                int residual_size, int32_t coffset)
340 {
341     int pred_order, sum, qshift, init_sum, i, j;
342     const int *coeffs;
343
344     if (command == FN_QLPC) {
345         /* read/validate prediction order */
346         pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
347         if ((unsigned)pred_order > s->nwrap) {
348             av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n",
349                    pred_order);
350             return AVERROR(EINVAL);
351         }
352         /* read LPC coefficients */
353         for (i = 0; i < pred_order; i++)
354             s->coeffs[i] = get_sr_golomb_shorten(&s->gb, LPCQUANT);
355         coeffs = s->coeffs;
356
357         qshift = LPCQUANT;
358     } else {
359         /* fixed LPC coeffs */
360         pred_order = command;
361         if (pred_order >= FF_ARRAY_ELEMS(fixed_coeffs)) {
362             av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n",
363                    pred_order);
364             return AVERROR_INVALIDDATA;
365         }
366         coeffs     = fixed_coeffs[pred_order];
367         qshift     = 0;
368     }
369
370     /* subtract offset from previous samples to use in prediction */
371     if (command == FN_QLPC && coffset)
372         for (i = -pred_order; i < 0; i++)
373             s->decoded[channel][i] -= coffset;
374
375     /* decode residual and do LPC prediction */
376     init_sum = pred_order ? (command == FN_QLPC ? s->lpcqoffset : 0) : coffset;
377     for (i = 0; i < s->blocksize; i++) {
378         sum = init_sum;
379         for (j = 0; j < pred_order; j++)
380             sum += coeffs[j] * s->decoded[channel][i - j - 1];
381         s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) +
382                                  (sum >> qshift);
383     }
384
385     /* add offset to current samples */
386     if (command == FN_QLPC && coffset)
387         for (i = 0; i < s->blocksize; i++)
388             s->decoded[channel][i] += coffset;
389
390     return 0;
391 }
392
393 static int read_header(ShortenContext *s)
394 {
395     int i, ret;
396     int maxnlpc = 0;
397     /* shorten signature */
398     if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {
399         av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
400         return AVERROR_INVALIDDATA;
401     }
402
403     s->lpcqoffset     = 0;
404     s->blocksize      = DEFAULT_BLOCK_SIZE;
405     s->nmean          = -1;
406     s->version        = get_bits(&s->gb, 8);
407     s->internal_ftype = get_uint(s, TYPESIZE);
408
409     s->channels = get_uint(s, CHANSIZE);
410     if (!s->channels) {
411         av_log(s->avctx, AV_LOG_ERROR, "No channels reported\n");
412         return AVERROR_INVALIDDATA;
413     }
414     if (s->channels > MAX_CHANNELS) {
415         av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
416         s->channels = 0;
417         return AVERROR_INVALIDDATA;
418     }
419     s->avctx->channels = s->channels;
420
421     /* get blocksize if version > 0 */
422     if (s->version > 0) {
423         int skip_bytes;
424         unsigned blocksize;
425
426         blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
427         if (!blocksize || blocksize > MAX_BLOCKSIZE) {
428             av_log(s->avctx, AV_LOG_ERROR,
429                    "invalid or unsupported block size: %d\n",
430                    blocksize);
431             return AVERROR(EINVAL);
432         }
433         s->blocksize = blocksize;
434
435         maxnlpc  = get_uint(s, LPCQSIZE);
436         s->nmean = get_uint(s, 0);
437
438         skip_bytes = get_uint(s, NSKIPSIZE);
439         if ((unsigned)skip_bytes > get_bits_left(&s->gb)/8) {
440             av_log(s->avctx, AV_LOG_ERROR, "invalid skip_bytes: %d\n", skip_bytes);
441             return AVERROR_INVALIDDATA;
442         }
443
444         for (i = 0; i < skip_bytes; i++)
445             skip_bits(&s->gb, 8);
446     }
447     s->nwrap = FFMAX(NWRAP, maxnlpc);
448
449     if ((ret = allocate_buffers(s)) < 0)
450         return ret;
451
452     if ((ret = init_offset(s)) < 0)
453         return ret;
454
455     if (s->version > 1)
456         s->lpcqoffset = V2LPCQOFFSET;
457
458     if (s->avctx->extradata_size > 0)
459         goto end;
460
461     if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
462         av_log(s->avctx, AV_LOG_ERROR,
463                "missing verbatim section at beginning of stream\n");
464         return AVERROR_INVALIDDATA;
465     }
466
467     s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
468     if (s->header_size >= OUT_BUFFER_SIZE ||
469         s->header_size < CANONICAL_HEADER_SIZE) {
470         av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n",
471                s->header_size);
472         return AVERROR_INVALIDDATA;
473     }
474
475     for (i = 0; i < s->header_size; i++)
476         s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
477
478     if (AV_RL32(s->header) == MKTAG('R','I','F','F')) {
479         if ((ret = decode_wave_header(s->avctx, s->header, s->header_size)) < 0)
480             return ret;
481     } else if (AV_RL32(s->header) == MKTAG('F','O','R','M')) {
482         if ((ret = decode_aiff_header(s->avctx, s->header, s->header_size)) < 0)
483             return ret;
484     } else {
485         avpriv_report_missing_feature(s->avctx, "unsupported bit packing %X", AV_RL32(s->header));
486         return AVERROR_PATCHWELCOME;
487     }
488
489 end:
490     s->cur_chan = 0;
491     s->bitshift = 0;
492
493     s->got_header = 1;
494
495     return 0;
496 }
497
498 static int shorten_decode_frame(AVCodecContext *avctx, void *data,
499                                 int *got_frame_ptr, AVPacket *avpkt)
500 {
501     AVFrame *frame     = data;
502     const uint8_t *buf = avpkt->data;
503     int buf_size       = avpkt->size;
504     ShortenContext *s  = avctx->priv_data;
505     int i, input_buf_size = 0;
506     int ret;
507
508     /* allocate internal bitstream buffer */
509     if (s->max_framesize == 0) {
510         void *tmp_ptr;
511         s->max_framesize = 8192; // should hopefully be enough for the first header
512         tmp_ptr = av_fast_realloc(s->bitstream, &s->allocated_bitstream_size,
513                                   s->max_framesize + AV_INPUT_BUFFER_PADDING_SIZE);
514         if (!tmp_ptr) {
515             s->max_framesize = 0;
516             av_log(avctx, AV_LOG_ERROR, "error allocating bitstream buffer\n");
517             return AVERROR(ENOMEM);
518         }
519         memset(tmp_ptr, 0, s->allocated_bitstream_size);
520         s->bitstream = tmp_ptr;
521     }
522
523     /* append current packet data to bitstream buffer */
524     buf_size       = FFMIN(buf_size, s->max_framesize - s->bitstream_size);
525     input_buf_size = buf_size;
526
527     if (s->bitstream_index + s->bitstream_size + buf_size + AV_INPUT_BUFFER_PADDING_SIZE >
528         s->allocated_bitstream_size) {
529         memmove(s->bitstream, &s->bitstream[s->bitstream_index],
530                 s->bitstream_size);
531         s->bitstream_index = 0;
532     }
533     if (buf)
534         memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size], buf,
535                buf_size);
536     buf               = &s->bitstream[s->bitstream_index];
537     buf_size         += s->bitstream_size;
538     s->bitstream_size = buf_size;
539
540     /* do not decode until buffer has at least max_framesize bytes or
541      * the end of the file has been reached */
542     if (buf_size < s->max_framesize && avpkt->data) {
543         *got_frame_ptr = 0;
544         return input_buf_size;
545     }
546     /* init and position bitstream reader */
547     if ((ret = init_get_bits8(&s->gb, buf, buf_size)) < 0)
548         return ret;
549     skip_bits(&s->gb, s->bitindex);
550
551     /* process header or next subblock */
552     if (!s->got_header) {
553
554         if ((ret = read_header(s)) < 0)
555             return ret;
556
557         if (avpkt->size) {
558             int max_framesize;
559             void *tmp_ptr;
560
561             max_framesize = FFMAX(s->max_framesize, s->blocksize * s->channels * 8);
562             tmp_ptr = av_fast_realloc(s->bitstream, &s->allocated_bitstream_size,
563                                       max_framesize + AV_INPUT_BUFFER_PADDING_SIZE);
564             if (!tmp_ptr) {
565                 av_log(avctx, AV_LOG_ERROR, "error allocating bitstream buffer\n");
566                 return AVERROR(ENOMEM);
567             }
568             s->bitstream = tmp_ptr;
569             s->max_framesize = max_framesize;
570             *got_frame_ptr = 0;
571             goto finish_frame;
572         }
573     }
574
575     /* if quit command was read previously, don't decode anything */
576     if (s->got_quit_command) {
577         *got_frame_ptr = 0;
578         return avpkt->size;
579     }
580
581     s->cur_chan = 0;
582     while (s->cur_chan < s->channels) {
583         unsigned cmd;
584         int len;
585
586         if (get_bits_left(&s->gb) < 3 + FNSIZE) {
587             *got_frame_ptr = 0;
588             break;
589         }
590
591         cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
592
593         if (cmd > FN_VERBATIM) {
594             av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);
595             *got_frame_ptr = 0;
596             break;
597         }
598
599         if (!is_audio_command[cmd]) {
600             /* process non-audio command */
601             switch (cmd) {
602             case FN_VERBATIM:
603                 len = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
604                 while (len--)
605                     get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
606                 break;
607             case FN_BITSHIFT: {
608                 unsigned bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);
609                 if (bitshift > 32) {
610                     av_log(avctx, AV_LOG_ERROR, "bitshift %d is invalid\n",
611                            bitshift);
612                     return AVERROR_INVALIDDATA;
613                 }
614                 s->bitshift = bitshift;
615                 break;
616             }
617             case FN_BLOCKSIZE: {
618                 unsigned blocksize = get_uint(s, av_log2(s->blocksize));
619                 if (blocksize > s->blocksize) {
620                     av_log(avctx, AV_LOG_ERROR,
621                            "Increasing block size is not supported\n");
622                     return AVERROR_PATCHWELCOME;
623                 }
624                 if (!blocksize || blocksize > MAX_BLOCKSIZE) {
625                     av_log(avctx, AV_LOG_ERROR, "invalid or unsupported "
626                                                 "block size: %d\n", blocksize);
627                     return AVERROR(EINVAL);
628                 }
629                 s->blocksize = blocksize;
630                 break;
631             }
632             case FN_QUIT:
633                 s->got_quit_command = 1;
634                 break;
635             }
636             if (cmd == FN_QUIT)
637                 break;
638         } else {
639             /* process audio command */
640             int residual_size = 0;
641             int channel = s->cur_chan;
642             int32_t coffset;
643
644             /* get Rice code for residual decoding */
645             if (cmd != FN_ZERO) {
646                 residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);
647                 /* This is a hack as version 0 differed in the definition
648                  * of get_sr_golomb_shorten(). */
649                 if (s->version == 0)
650                     residual_size--;
651             }
652
653             /* calculate sample offset using means from previous blocks */
654             if (s->nmean == 0)
655                 coffset = s->offset[channel][0];
656             else {
657                 int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;
658                 for (i = 0; i < s->nmean; i++)
659                     sum += s->offset[channel][i];
660                 coffset = sum / s->nmean;
661                 if (s->version >= 2)
662                     coffset = s->bitshift == 0 ? coffset : coffset >> s->bitshift - 1 >> 1;
663             }
664
665             /* decode samples for this channel */
666             if (cmd == FN_ZERO) {
667                 for (i = 0; i < s->blocksize; i++)
668                     s->decoded[channel][i] = 0;
669             } else {
670                 if ((ret = decode_subframe_lpc(s, cmd, channel,
671                                                residual_size, coffset)) < 0)
672                     return ret;
673             }
674
675             /* update means with info from the current block */
676             if (s->nmean > 0) {
677                 int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2;
678                 for (i = 0; i < s->blocksize; i++)
679                     sum += s->decoded[channel][i];
680
681                 for (i = 1; i < s->nmean; i++)
682                     s->offset[channel][i - 1] = s->offset[channel][i];
683
684                 if (s->version < 2)
685                     s->offset[channel][s->nmean - 1] = sum / s->blocksize;
686                 else
687                     s->offset[channel][s->nmean - 1] = s->bitshift == 32 ? 0 : (sum / s->blocksize) << s->bitshift;
688             }
689
690             /* copy wrap samples for use with next block */
691             for (i = -s->nwrap; i < 0; i++)
692                 s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];
693
694             /* shift samples to add in unused zero bits which were removed
695              * during encoding */
696             fix_bitshift(s, s->decoded[channel]);
697
698             /* if this is the last channel in the block, output the samples */
699             s->cur_chan++;
700             if (s->cur_chan == s->channels) {
701                 uint8_t *samples_u8;
702                 int16_t *samples_s16;
703                 int chan;
704
705                 /* get output buffer */
706                 frame->nb_samples = s->blocksize;
707                 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
708                     return ret;
709
710                 for (chan = 0; chan < s->channels; chan++) {
711                     samples_u8  = ((uint8_t **)frame->extended_data)[chan];
712                     samples_s16 = ((int16_t **)frame->extended_data)[chan];
713                     for (i = 0; i < s->blocksize; i++) {
714                         switch (s->internal_ftype) {
715                         case TYPE_U8:
716                             *samples_u8++ = av_clip_uint8(s->decoded[chan][i]);
717                             break;
718                         case TYPE_S16HL:
719                         case TYPE_S16LH:
720                             *samples_s16++ = av_clip_int16(s->decoded[chan][i]);
721                             break;
722                         }
723                     }
724                 }
725
726                 *got_frame_ptr = 1;
727             }
728         }
729     }
730     if (s->cur_chan < s->channels)
731         *got_frame_ptr = 0;
732
733 finish_frame:
734     s->bitindex = get_bits_count(&s->gb) - 8 * (get_bits_count(&s->gb) / 8);
735     i           = get_bits_count(&s->gb) / 8;
736     if (i > buf_size) {
737         av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
738         s->bitstream_size  = 0;
739         s->bitstream_index = 0;
740         return AVERROR_INVALIDDATA;
741     }
742     if (s->bitstream_size) {
743         s->bitstream_index += i;
744         s->bitstream_size  -= i;
745         return input_buf_size;
746     } else
747         return i;
748 }
749
750 static av_cold int shorten_decode_close(AVCodecContext *avctx)
751 {
752     ShortenContext *s = avctx->priv_data;
753     int i;
754
755     for (i = 0; i < s->channels; i++) {
756         s->decoded[i] = NULL;
757         av_freep(&s->decoded_base[i]);
758         av_freep(&s->offset[i]);
759     }
760     av_freep(&s->bitstream);
761     av_freep(&s->coeffs);
762
763     return 0;
764 }
765
766 AVCodec ff_shorten_decoder = {
767     .name           = "shorten",
768     .long_name      = NULL_IF_CONFIG_SMALL("Shorten"),
769     .type           = AVMEDIA_TYPE_AUDIO,
770     .id             = AV_CODEC_ID_SHORTEN,
771     .priv_data_size = sizeof(ShortenContext),
772     .init           = shorten_decode_init,
773     .close          = shorten_decode_close,
774     .decode         = shorten_decode_frame,
775     .capabilities   = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_DR1,
776     .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
777                                                       AV_SAMPLE_FMT_U8P,
778                                                       AV_SAMPLE_FMT_NONE },
779 };