]> git.sesse.net Git - ffmpeg/blob - libavcodec/adpcm.c
avcodec: add decoder for argonaut games' adpcm codec
[ffmpeg] / libavcodec / adpcm.c
1 /*
2  * Copyright (c) 2001-2003 The FFmpeg project
3  *
4  * first version by Francois Revol (revol@free.fr)
5  * fringe ADPCM codecs (e.g., DK3, DK4, Westwood)
6  *   by Mike Melanson (melanson@pcisys.net)
7  * CD-ROM XA ADPCM codec by BERO
8  * EA ADPCM decoder by Robin Kay (komadori@myrealbox.com)
9  * EA ADPCM R1/R2/R3 decoder by Peter Ross (pross@xvid.org)
10  * EA IMA EACS decoder by Peter Ross (pross@xvid.org)
11  * EA IMA SEAD decoder by Peter Ross (pross@xvid.org)
12  * EA ADPCM XAS decoder by Peter Ross (pross@xvid.org)
13  * MAXIS EA ADPCM decoder by Robert Marston (rmarston@gmail.com)
14  * THP ADPCM decoder by Marco Gerards (mgerards@xs4all.nl)
15  * Argonaut Games ADPCM decoder by Zane van Iperen (zane@zanevaniperen.com)
16  *
17  * This file is part of FFmpeg.
18  *
19  * FFmpeg is free software; you can redistribute it and/or
20  * modify it under the terms of the GNU Lesser General Public
21  * License as published by the Free Software Foundation; either
22  * version 2.1 of the License, or (at your option) any later version.
23  *
24  * FFmpeg is distributed in the hope that it will be useful,
25  * but WITHOUT ANY WARRANTY; without even the implied warranty of
26  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
27  * Lesser General Public License for more details.
28  *
29  * You should have received a copy of the GNU Lesser General Public
30  * License along with FFmpeg; if not, write to the Free Software
31  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
32  */
33 #include "avcodec.h"
34 #include "get_bits.h"
35 #include "bytestream.h"
36 #include "adpcm.h"
37 #include "adpcm_data.h"
38 #include "internal.h"
39
40 /**
41  * @file
42  * ADPCM decoders
43  * Features and limitations:
44  *
45  * Reference documents:
46  * http://wiki.multimedia.cx/index.php?title=Category:ADPCM_Audio_Codecs
47  * http://www.pcisys.net/~melanson/codecs/simpleaudio.html [dead]
48  * http://www.geocities.com/SiliconValley/8682/aud3.txt [dead]
49  * http://openquicktime.sourceforge.net/
50  * XAnim sources (xa_codec.c) http://xanim.polter.net/
51  * http://www.cs.ucla.edu/~leec/mediabench/applications.html [dead]
52  * SoX source code http://sox.sourceforge.net/
53  *
54  * CD-ROM XA:
55  * http://ku-www.ss.titech.ac.jp/~yatsushi/xaadpcm.html [dead]
56  * vagpack & depack http://homepages.compuserve.de/bITmASTER32/psx-index.html [dead]
57  * readstr http://www.geocities.co.jp/Playtown/2004/
58  */
59
60 /* These are for CD-ROM XA ADPCM */
61 static const int8_t xa_adpcm_table[5][2] = {
62     {   0,   0 },
63     {  60,   0 },
64     { 115, -52 },
65     {  98, -55 },
66     { 122, -60 }
67 };
68
69 static const int16_t ea_adpcm_table[] = {
70     0,  240,  460,  392,
71     0,    0, -208, -220,
72     0,    1,    3,    4,
73     7,    8,   10,   11,
74     0,   -1,   -3,   -4
75 };
76
77 // padded to zero where table size is less then 16
78 static const int8_t swf_index_tables[4][16] = {
79     /*2*/ { -1, 2 },
80     /*3*/ { -1, -1, 2, 4 },
81     /*4*/ { -1, -1, -1, -1, 2, 4, 6, 8 },
82     /*5*/ { -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 4, 6, 8, 10, 13, 16 }
83 };
84
85 /* end of tables */
86
87 typedef struct ADPCMDecodeContext {
88     ADPCMChannelStatus status[14];
89     int vqa_version;                /**< VQA version. Used for ADPCM_IMA_WS */
90     int has_status;
91 } ADPCMDecodeContext;
92
93 static av_cold int adpcm_decode_init(AVCodecContext * avctx)
94 {
95     ADPCMDecodeContext *c = avctx->priv_data;
96     unsigned int min_channels = 1;
97     unsigned int max_channels = 2;
98
99     switch(avctx->codec->id) {
100     case AV_CODEC_ID_ADPCM_DTK:
101     case AV_CODEC_ID_ADPCM_EA:
102         min_channels = 2;
103         break;
104     case AV_CODEC_ID_ADPCM_AFC:
105     case AV_CODEC_ID_ADPCM_EA_R1:
106     case AV_CODEC_ID_ADPCM_EA_R2:
107     case AV_CODEC_ID_ADPCM_EA_R3:
108     case AV_CODEC_ID_ADPCM_EA_XAS:
109     case AV_CODEC_ID_ADPCM_MS:
110         max_channels = 6;
111         break;
112     case AV_CODEC_ID_ADPCM_MTAF:
113         min_channels = 2;
114         max_channels = 8;
115         if (avctx->channels & 1) {
116             avpriv_request_sample(avctx, "channel count %d\n", avctx->channels);
117             return AVERROR_PATCHWELCOME;
118         }
119         break;
120     case AV_CODEC_ID_ADPCM_PSX:
121         max_channels = 8;
122         break;
123     case AV_CODEC_ID_ADPCM_IMA_DAT4:
124     case AV_CODEC_ID_ADPCM_THP:
125     case AV_CODEC_ID_ADPCM_THP_LE:
126         max_channels = 14;
127         break;
128     }
129     if (avctx->channels < min_channels || avctx->channels > max_channels) {
130         av_log(avctx, AV_LOG_ERROR, "Invalid number of channels\n");
131         return AVERROR(EINVAL);
132     }
133
134     switch(avctx->codec->id) {
135     case AV_CODEC_ID_ADPCM_CT:
136         c->status[0].step = c->status[1].step = 511;
137         break;
138     case AV_CODEC_ID_ADPCM_IMA_WAV:
139         if (avctx->bits_per_coded_sample < 2 || avctx->bits_per_coded_sample > 5)
140             return AVERROR_INVALIDDATA;
141         break;
142     case AV_CODEC_ID_ADPCM_IMA_APC:
143         if (avctx->extradata && avctx->extradata_size >= 8) {
144             c->status[0].predictor = av_clip_intp2(AV_RL32(avctx->extradata    ), 18);
145             c->status[1].predictor = av_clip_intp2(AV_RL32(avctx->extradata + 4), 18);
146         }
147         break;
148     case AV_CODEC_ID_ADPCM_IMA_WS:
149         if (avctx->extradata && avctx->extradata_size >= 2)
150             c->vqa_version = AV_RL16(avctx->extradata);
151         break;
152     case AV_CODEC_ID_ADPCM_ARGO:
153         if (avctx->bits_per_coded_sample != 4)
154             return AVERROR_INVALIDDATA;
155         break;
156     default:
157         break;
158     }
159
160     switch(avctx->codec->id) {
161         case AV_CODEC_ID_ADPCM_AICA:
162         case AV_CODEC_ID_ADPCM_IMA_DAT4:
163         case AV_CODEC_ID_ADPCM_IMA_QT:
164         case AV_CODEC_ID_ADPCM_IMA_WAV:
165         case AV_CODEC_ID_ADPCM_4XM:
166         case AV_CODEC_ID_ADPCM_XA:
167         case AV_CODEC_ID_ADPCM_EA_R1:
168         case AV_CODEC_ID_ADPCM_EA_R2:
169         case AV_CODEC_ID_ADPCM_EA_R3:
170         case AV_CODEC_ID_ADPCM_EA_XAS:
171         case AV_CODEC_ID_ADPCM_THP:
172         case AV_CODEC_ID_ADPCM_THP_LE:
173         case AV_CODEC_ID_ADPCM_AFC:
174         case AV_CODEC_ID_ADPCM_DTK:
175         case AV_CODEC_ID_ADPCM_PSX:
176         case AV_CODEC_ID_ADPCM_MTAF:
177         case AV_CODEC_ID_ADPCM_ARGO:
178             avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
179             break;
180         case AV_CODEC_ID_ADPCM_IMA_WS:
181             avctx->sample_fmt = c->vqa_version == 3 ? AV_SAMPLE_FMT_S16P :
182                                                       AV_SAMPLE_FMT_S16;
183             break;
184         case AV_CODEC_ID_ADPCM_MS:
185             avctx->sample_fmt = avctx->channels > 2 ? AV_SAMPLE_FMT_S16P :
186                                                       AV_SAMPLE_FMT_S16;
187             break;
188         default:
189             avctx->sample_fmt = AV_SAMPLE_FMT_S16;
190     }
191
192     return 0;
193 }
194
195 static inline int16_t adpcm_agm_expand_nibble(ADPCMChannelStatus *c, int8_t nibble)
196 {
197     int delta, pred, step, add;
198
199     pred = c->predictor;
200     delta = nibble & 7;
201     step = c->step;
202     add = (delta * 2 + 1) * step;
203     if (add < 0)
204         add = add + 7;
205
206     if ((nibble & 8) == 0)
207         pred = av_clip(pred + (add >> 3), -32767, 32767);
208     else
209         pred = av_clip(pred - (add >> 3), -32767, 32767);
210
211     switch (delta) {
212     case 7:
213         step *= 0x99;
214         break;
215     case 6:
216         c->step = av_clip(c->step * 2, 127, 24576);
217         c->predictor = pred;
218         return pred;
219     case 5:
220         step *= 0x66;
221         break;
222     case 4:
223         step *= 0x4d;
224         break;
225     default:
226         step *= 0x39;
227         break;
228     }
229
230     if (step < 0)
231         step += 0x3f;
232
233     c->step = step >> 6;
234     c->step = av_clip(c->step, 127, 24576);
235     c->predictor = pred;
236     return pred;
237 }
238
239 static inline int16_t adpcm_ima_expand_nibble(ADPCMChannelStatus *c, int8_t nibble, int shift)
240 {
241     int step_index;
242     int predictor;
243     int sign, delta, diff, step;
244
245     step = ff_adpcm_step_table[c->step_index];
246     step_index = c->step_index + ff_adpcm_index_table[(unsigned)nibble];
247     step_index = av_clip(step_index, 0, 88);
248
249     sign = nibble & 8;
250     delta = nibble & 7;
251     /* perform direct multiplication instead of series of jumps proposed by
252      * the reference ADPCM implementation since modern CPUs can do the mults
253      * quickly enough */
254     diff = ((2 * delta + 1) * step) >> shift;
255     predictor = c->predictor;
256     if (sign) predictor -= diff;
257     else predictor += diff;
258
259     c->predictor = av_clip_int16(predictor);
260     c->step_index = step_index;
261
262     return (int16_t)c->predictor;
263 }
264
265 static inline int16_t adpcm_ima_wav_expand_nibble(ADPCMChannelStatus *c, GetBitContext *gb, int bps)
266 {
267     int nibble, step_index, predictor, sign, delta, diff, step, shift;
268
269     shift = bps - 1;
270     nibble = get_bits_le(gb, bps),
271     step = ff_adpcm_step_table[c->step_index];
272     step_index = c->step_index + ff_adpcm_index_tables[bps - 2][nibble];
273     step_index = av_clip(step_index, 0, 88);
274
275     sign = nibble & (1 << shift);
276     delta = av_mod_uintp2(nibble, shift);
277     diff = ((2 * delta + 1) * step) >> shift;
278     predictor = c->predictor;
279     if (sign) predictor -= diff;
280     else predictor += diff;
281
282     c->predictor = av_clip_int16(predictor);
283     c->step_index = step_index;
284
285     return (int16_t)c->predictor;
286 }
287
288 static inline int adpcm_ima_qt_expand_nibble(ADPCMChannelStatus *c, int nibble, int shift)
289 {
290     int step_index;
291     int predictor;
292     int diff, step;
293
294     step = ff_adpcm_step_table[c->step_index];
295     step_index = c->step_index + ff_adpcm_index_table[nibble];
296     step_index = av_clip(step_index, 0, 88);
297
298     diff = step >> 3;
299     if (nibble & 4) diff += step;
300     if (nibble & 2) diff += step >> 1;
301     if (nibble & 1) diff += step >> 2;
302
303     if (nibble & 8)
304         predictor = c->predictor - diff;
305     else
306         predictor = c->predictor + diff;
307
308     c->predictor = av_clip_int16(predictor);
309     c->step_index = step_index;
310
311     return c->predictor;
312 }
313
314 static inline int16_t adpcm_ms_expand_nibble(ADPCMChannelStatus *c, int nibble)
315 {
316     int predictor;
317
318     predictor = (((c->sample1) * (c->coeff1)) + ((c->sample2) * (c->coeff2))) / 64;
319     predictor += ((nibble & 0x08)?(nibble - 0x10):(nibble)) * c->idelta;
320
321     c->sample2 = c->sample1;
322     c->sample1 = av_clip_int16(predictor);
323     c->idelta = (ff_adpcm_AdaptationTable[(int)nibble] * c->idelta) >> 8;
324     if (c->idelta < 16) c->idelta = 16;
325     if (c->idelta > INT_MAX/768) {
326         av_log(NULL, AV_LOG_WARNING, "idelta overflow\n");
327         c->idelta = INT_MAX/768;
328     }
329
330     return c->sample1;
331 }
332
333 static inline int16_t adpcm_ima_oki_expand_nibble(ADPCMChannelStatus *c, int nibble)
334 {
335     int step_index, predictor, sign, delta, diff, step;
336
337     step = ff_adpcm_oki_step_table[c->step_index];
338     step_index = c->step_index + ff_adpcm_index_table[(unsigned)nibble];
339     step_index = av_clip(step_index, 0, 48);
340
341     sign = nibble & 8;
342     delta = nibble & 7;
343     diff = ((2 * delta + 1) * step) >> 3;
344     predictor = c->predictor;
345     if (sign) predictor -= diff;
346     else predictor += diff;
347
348     c->predictor = av_clip_intp2(predictor, 11);
349     c->step_index = step_index;
350
351     return c->predictor * 16;
352 }
353
354 static inline int16_t adpcm_ct_expand_nibble(ADPCMChannelStatus *c, int8_t nibble)
355 {
356     int sign, delta, diff;
357     int new_step;
358
359     sign = nibble & 8;
360     delta = nibble & 7;
361     /* perform direct multiplication instead of series of jumps proposed by
362      * the reference ADPCM implementation since modern CPUs can do the mults
363      * quickly enough */
364     diff = ((2 * delta + 1) * c->step) >> 3;
365     /* predictor update is not so trivial: predictor is multiplied on 254/256 before updating */
366     c->predictor = ((c->predictor * 254) >> 8) + (sign ? -diff : diff);
367     c->predictor = av_clip_int16(c->predictor);
368     /* calculate new step and clamp it to range 511..32767 */
369     new_step = (ff_adpcm_AdaptationTable[nibble & 7] * c->step) >> 8;
370     c->step = av_clip(new_step, 511, 32767);
371
372     return (int16_t)c->predictor;
373 }
374
375 static inline int16_t adpcm_sbpro_expand_nibble(ADPCMChannelStatus *c, int8_t nibble, int size, int shift)
376 {
377     int sign, delta, diff;
378
379     sign = nibble & (1<<(size-1));
380     delta = nibble & ((1<<(size-1))-1);
381     diff = delta << (7 + c->step + shift);
382
383     /* clamp result */
384     c->predictor = av_clip(c->predictor + (sign ? -diff : diff), -16384,16256);
385
386     /* calculate new step */
387     if (delta >= (2*size - 3) && c->step < 3)
388         c->step++;
389     else if (delta == 0 && c->step > 0)
390         c->step--;
391
392     return (int16_t) c->predictor;
393 }
394
395 static inline int16_t adpcm_yamaha_expand_nibble(ADPCMChannelStatus *c, uint8_t nibble)
396 {
397     if(!c->step) {
398         c->predictor = 0;
399         c->step = 127;
400     }
401
402     c->predictor += (c->step * ff_adpcm_yamaha_difflookup[nibble]) / 8;
403     c->predictor = av_clip_int16(c->predictor);
404     c->step = (c->step * ff_adpcm_yamaha_indexscale[nibble]) >> 8;
405     c->step = av_clip(c->step, 127, 24576);
406     return c->predictor;
407 }
408
409 static inline int16_t adpcm_mtaf_expand_nibble(ADPCMChannelStatus *c, uint8_t nibble)
410 {
411     c->predictor += ff_adpcm_mtaf_stepsize[c->step][nibble];
412     c->predictor = av_clip_int16(c->predictor);
413     c->step += ff_adpcm_index_table[nibble];
414     c->step = av_clip_uintp2(c->step, 5);
415     return c->predictor;
416 }
417
418 static int xa_decode(AVCodecContext *avctx, int16_t *out0, int16_t *out1,
419                      const uint8_t *in, ADPCMChannelStatus *left,
420                      ADPCMChannelStatus *right, int channels, int sample_offset)
421 {
422     int i, j;
423     int shift,filter,f0,f1;
424     int s_1,s_2;
425     int d,s,t;
426
427     out0 += sample_offset;
428     if (channels == 1)
429         out1 = out0 + 28;
430     else
431         out1 += sample_offset;
432
433     for(i=0;i<4;i++) {
434         shift  = 12 - (in[4+i*2] & 15);
435         filter = in[4+i*2] >> 4;
436         if (filter >= FF_ARRAY_ELEMS(xa_adpcm_table)) {
437             avpriv_request_sample(avctx, "unknown XA-ADPCM filter %d", filter);
438             filter=0;
439         }
440         f0 = xa_adpcm_table[filter][0];
441         f1 = xa_adpcm_table[filter][1];
442
443         s_1 = left->sample1;
444         s_2 = left->sample2;
445
446         for(j=0;j<28;j++) {
447             d = in[16+i+j*4];
448
449             t = sign_extend(d, 4);
450             s = t*(1<<shift) + ((s_1*f0 + s_2*f1+32)>>6);
451             s_2 = s_1;
452             s_1 = av_clip_int16(s);
453             out0[j] = s_1;
454         }
455
456         if (channels == 2) {
457             left->sample1 = s_1;
458             left->sample2 = s_2;
459             s_1 = right->sample1;
460             s_2 = right->sample2;
461         }
462
463         shift  = 12 - (in[5+i*2] & 15);
464         filter = in[5+i*2] >> 4;
465         if (filter >= FF_ARRAY_ELEMS(xa_adpcm_table)) {
466             avpriv_request_sample(avctx, "unknown XA-ADPCM filter %d", filter);
467             filter=0;
468         }
469
470         f0 = xa_adpcm_table[filter][0];
471         f1 = xa_adpcm_table[filter][1];
472
473         for(j=0;j<28;j++) {
474             d = in[16+i+j*4];
475
476             t = sign_extend(d >> 4, 4);
477             s = t*(1<<shift) + ((s_1*f0 + s_2*f1+32)>>6);
478             s_2 = s_1;
479             s_1 = av_clip_int16(s);
480             out1[j] = s_1;
481         }
482
483         if (channels == 2) {
484             right->sample1 = s_1;
485             right->sample2 = s_2;
486         } else {
487             left->sample1 = s_1;
488             left->sample2 = s_2;
489         }
490
491         out0 += 28 * (3 - channels);
492         out1 += 28 * (3 - channels);
493     }
494
495     return 0;
496 }
497
498 static void adpcm_swf_decode(AVCodecContext *avctx, const uint8_t *buf, int buf_size, int16_t *samples)
499 {
500     ADPCMDecodeContext *c = avctx->priv_data;
501     GetBitContext gb;
502     const int8_t *table;
503     int k0, signmask, nb_bits, count;
504     int size = buf_size*8;
505     int i;
506
507     init_get_bits(&gb, buf, size);
508
509     //read bits & initial values
510     nb_bits = get_bits(&gb, 2)+2;
511     table = swf_index_tables[nb_bits-2];
512     k0 = 1 << (nb_bits-2);
513     signmask = 1 << (nb_bits-1);
514
515     while (get_bits_count(&gb) <= size - 22*avctx->channels) {
516         for (i = 0; i < avctx->channels; i++) {
517             *samples++ = c->status[i].predictor = get_sbits(&gb, 16);
518             c->status[i].step_index = get_bits(&gb, 6);
519         }
520
521         for (count = 0; get_bits_count(&gb) <= size - nb_bits*avctx->channels && count < 4095; count++) {
522             int i;
523
524             for (i = 0; i < avctx->channels; i++) {
525                 // similar to IMA adpcm
526                 int delta = get_bits(&gb, nb_bits);
527                 int step = ff_adpcm_step_table[c->status[i].step_index];
528                 int vpdiff = 0; // vpdiff = (delta+0.5)*step/4
529                 int k = k0;
530
531                 do {
532                     if (delta & k)
533                         vpdiff += step;
534                     step >>= 1;
535                     k >>= 1;
536                 } while(k);
537                 vpdiff += step;
538
539                 if (delta & signmask)
540                     c->status[i].predictor -= vpdiff;
541                 else
542                     c->status[i].predictor += vpdiff;
543
544                 c->status[i].step_index += table[delta & (~signmask)];
545
546                 c->status[i].step_index = av_clip(c->status[i].step_index, 0, 88);
547                 c->status[i].predictor = av_clip_int16(c->status[i].predictor);
548
549                 *samples++ = c->status[i].predictor;
550             }
551         }
552     }
553 }
554
555 static inline int16_t adpcm_argo_expand_nibble(int nibble, int shift, int16_t prev0, int16_t prev1)
556 {
557     return ((8 * prev0) - (4 * prev1) + (nibble * (1 << shift))) >> 2;
558 }
559
560 /**
561  * Get the number of samples that will be decoded from the packet.
562  * In one case, this is actually the maximum number of samples possible to
563  * decode with the given buf_size.
564  *
565  * @param[out] coded_samples set to the number of samples as coded in the
566  *                           packet, or 0 if the codec does not encode the
567  *                           number of samples in each frame.
568  * @param[out] approx_nb_samples set to non-zero if the number of samples
569  *                               returned is an approximation.
570  */
571 static int get_nb_samples(AVCodecContext *avctx, GetByteContext *gb,
572                           int buf_size, int *coded_samples, int *approx_nb_samples)
573 {
574     ADPCMDecodeContext *s = avctx->priv_data;
575     int nb_samples        = 0;
576     int ch                = avctx->channels;
577     int has_coded_samples = 0;
578     int header_size;
579
580     *coded_samples = 0;
581     *approx_nb_samples = 0;
582
583     if(ch <= 0)
584         return 0;
585
586     switch (avctx->codec->id) {
587     /* constant, only check buf_size */
588     case AV_CODEC_ID_ADPCM_EA_XAS:
589         if (buf_size < 76 * ch)
590             return 0;
591         nb_samples = 128;
592         break;
593     case AV_CODEC_ID_ADPCM_IMA_QT:
594         if (buf_size < 34 * ch)
595             return 0;
596         nb_samples = 64;
597         break;
598     case AV_CODEC_ID_ADPCM_ARGO:
599         if (buf_size < 17 * ch)
600             return 0;
601         nb_samples = 32;
602         break;
603     /* simple 4-bit adpcm */
604     case AV_CODEC_ID_ADPCM_CT:
605     case AV_CODEC_ID_ADPCM_IMA_APC:
606     case AV_CODEC_ID_ADPCM_IMA_EA_SEAD:
607     case AV_CODEC_ID_ADPCM_IMA_OKI:
608     case AV_CODEC_ID_ADPCM_IMA_WS:
609     case AV_CODEC_ID_ADPCM_YAMAHA:
610     case AV_CODEC_ID_ADPCM_AICA:
611         nb_samples = buf_size * 2 / ch;
612         break;
613     }
614     if (nb_samples)
615         return nb_samples;
616
617     /* simple 4-bit adpcm, with header */
618     header_size = 0;
619     switch (avctx->codec->id) {
620         case AV_CODEC_ID_ADPCM_4XM:
621         case AV_CODEC_ID_ADPCM_AGM:
622         case AV_CODEC_ID_ADPCM_IMA_DAT4:
623         case AV_CODEC_ID_ADPCM_IMA_ISS:     header_size = 4 * ch;      break;
624         case AV_CODEC_ID_ADPCM_IMA_AMV:     header_size = 8;           break;
625         case AV_CODEC_ID_ADPCM_IMA_SMJPEG:  header_size = 4 * ch;      break;
626     }
627     if (header_size > 0)
628         return (buf_size - header_size) * 2 / ch;
629
630     /* more complex formats */
631     switch (avctx->codec->id) {
632     case AV_CODEC_ID_ADPCM_EA:
633         has_coded_samples = 1;
634         *coded_samples  = bytestream2_get_le32(gb);
635         *coded_samples -= *coded_samples % 28;
636         nb_samples      = (buf_size - 12) / 30 * 28;
637         break;
638     case AV_CODEC_ID_ADPCM_IMA_EA_EACS:
639         has_coded_samples = 1;
640         *coded_samples = bytestream2_get_le32(gb);
641         nb_samples     = (buf_size - (4 + 8 * ch)) * 2 / ch;
642         break;
643     case AV_CODEC_ID_ADPCM_EA_MAXIS_XA:
644         nb_samples = (buf_size - ch) / ch * 2;
645         break;
646     case AV_CODEC_ID_ADPCM_EA_R1:
647     case AV_CODEC_ID_ADPCM_EA_R2:
648     case AV_CODEC_ID_ADPCM_EA_R3:
649         /* maximum number of samples */
650         /* has internal offsets and a per-frame switch to signal raw 16-bit */
651         has_coded_samples = 1;
652         switch (avctx->codec->id) {
653         case AV_CODEC_ID_ADPCM_EA_R1:
654             header_size    = 4 + 9 * ch;
655             *coded_samples = bytestream2_get_le32(gb);
656             break;
657         case AV_CODEC_ID_ADPCM_EA_R2:
658             header_size    = 4 + 5 * ch;
659             *coded_samples = bytestream2_get_le32(gb);
660             break;
661         case AV_CODEC_ID_ADPCM_EA_R3:
662             header_size    = 4 + 5 * ch;
663             *coded_samples = bytestream2_get_be32(gb);
664             break;
665         }
666         *coded_samples -= *coded_samples % 28;
667         nb_samples      = (buf_size - header_size) * 2 / ch;
668         nb_samples     -= nb_samples % 28;
669         *approx_nb_samples = 1;
670         break;
671     case AV_CODEC_ID_ADPCM_IMA_DK3:
672         if (avctx->block_align > 0)
673             buf_size = FFMIN(buf_size, avctx->block_align);
674         nb_samples = ((buf_size - 16) * 2 / 3 * 4) / ch;
675         break;
676     case AV_CODEC_ID_ADPCM_IMA_DK4:
677         if (avctx->block_align > 0)
678             buf_size = FFMIN(buf_size, avctx->block_align);
679         if (buf_size < 4 * ch)
680             return AVERROR_INVALIDDATA;
681         nb_samples = 1 + (buf_size - 4 * ch) * 2 / ch;
682         break;
683     case AV_CODEC_ID_ADPCM_IMA_RAD:
684         if (avctx->block_align > 0)
685             buf_size = FFMIN(buf_size, avctx->block_align);
686         nb_samples = (buf_size - 4 * ch) * 2 / ch;
687         break;
688     case AV_CODEC_ID_ADPCM_IMA_WAV:
689     {
690         int bsize = ff_adpcm_ima_block_sizes[avctx->bits_per_coded_sample - 2];
691         int bsamples = ff_adpcm_ima_block_samples[avctx->bits_per_coded_sample - 2];
692         if (avctx->block_align > 0)
693             buf_size = FFMIN(buf_size, avctx->block_align);
694         if (buf_size < 4 * ch)
695             return AVERROR_INVALIDDATA;
696         nb_samples = 1 + (buf_size - 4 * ch) / (bsize * ch) * bsamples;
697         break;
698     }
699     case AV_CODEC_ID_ADPCM_MS:
700         if (avctx->block_align > 0)
701             buf_size = FFMIN(buf_size, avctx->block_align);
702         nb_samples = (buf_size - 6 * ch) * 2 / ch;
703         break;
704     case AV_CODEC_ID_ADPCM_MTAF:
705         if (avctx->block_align > 0)
706             buf_size = FFMIN(buf_size, avctx->block_align);
707         nb_samples = (buf_size - 16 * (ch / 2)) * 2 / ch;
708         break;
709     case AV_CODEC_ID_ADPCM_SBPRO_2:
710     case AV_CODEC_ID_ADPCM_SBPRO_3:
711     case AV_CODEC_ID_ADPCM_SBPRO_4:
712     {
713         int samples_per_byte;
714         switch (avctx->codec->id) {
715         case AV_CODEC_ID_ADPCM_SBPRO_2: samples_per_byte = 4; break;
716         case AV_CODEC_ID_ADPCM_SBPRO_3: samples_per_byte = 3; break;
717         case AV_CODEC_ID_ADPCM_SBPRO_4: samples_per_byte = 2; break;
718         }
719         if (!s->status[0].step_index) {
720             if (buf_size < ch)
721                 return AVERROR_INVALIDDATA;
722             nb_samples++;
723             buf_size -= ch;
724         }
725         nb_samples += buf_size * samples_per_byte / ch;
726         break;
727     }
728     case AV_CODEC_ID_ADPCM_SWF:
729     {
730         int buf_bits       = buf_size * 8 - 2;
731         int nbits          = (bytestream2_get_byte(gb) >> 6) + 2;
732         int block_hdr_size = 22 * ch;
733         int block_size     = block_hdr_size + nbits * ch * 4095;
734         int nblocks        = buf_bits / block_size;
735         int bits_left      = buf_bits - nblocks * block_size;
736         nb_samples         = nblocks * 4096;
737         if (bits_left >= block_hdr_size)
738             nb_samples += 1 + (bits_left - block_hdr_size) / (nbits * ch);
739         break;
740     }
741     case AV_CODEC_ID_ADPCM_THP:
742     case AV_CODEC_ID_ADPCM_THP_LE:
743         if (avctx->extradata) {
744             nb_samples = buf_size * 14 / (8 * ch);
745             break;
746         }
747         has_coded_samples = 1;
748         bytestream2_skip(gb, 4); // channel size
749         *coded_samples  = (avctx->codec->id == AV_CODEC_ID_ADPCM_THP_LE) ?
750                           bytestream2_get_le32(gb) :
751                           bytestream2_get_be32(gb);
752         buf_size       -= 8 + 36 * ch;
753         buf_size       /= ch;
754         nb_samples      = buf_size / 8 * 14;
755         if (buf_size % 8 > 1)
756             nb_samples     += (buf_size % 8 - 1) * 2;
757         *approx_nb_samples = 1;
758         break;
759     case AV_CODEC_ID_ADPCM_AFC:
760         nb_samples = buf_size / (9 * ch) * 16;
761         break;
762     case AV_CODEC_ID_ADPCM_XA:
763         nb_samples = (buf_size / 128) * 224 / ch;
764         break;
765     case AV_CODEC_ID_ADPCM_DTK:
766     case AV_CODEC_ID_ADPCM_PSX:
767         nb_samples = buf_size / (16 * ch) * 28;
768         break;
769     }
770
771     /* validate coded sample count */
772     if (has_coded_samples && (*coded_samples <= 0 || *coded_samples > nb_samples))
773         return AVERROR_INVALIDDATA;
774
775     return nb_samples;
776 }
777
778 static int adpcm_decode_frame(AVCodecContext *avctx, void *data,
779                               int *got_frame_ptr, AVPacket *avpkt)
780 {
781     AVFrame *frame     = data;
782     const uint8_t *buf = avpkt->data;
783     int buf_size = avpkt->size;
784     ADPCMDecodeContext *c = avctx->priv_data;
785     ADPCMChannelStatus *cs;
786     int n, m, channel, i;
787     int16_t *samples;
788     int16_t **samples_p;
789     int st; /* stereo */
790     int count1, count2;
791     int nb_samples, coded_samples, approx_nb_samples, ret;
792     GetByteContext gb;
793
794     bytestream2_init(&gb, buf, buf_size);
795     nb_samples = get_nb_samples(avctx, &gb, buf_size, &coded_samples, &approx_nb_samples);
796     if (nb_samples <= 0) {
797         av_log(avctx, AV_LOG_ERROR, "invalid number of samples in packet\n");
798         return AVERROR_INVALIDDATA;
799     }
800
801     /* get output buffer */
802     frame->nb_samples = nb_samples;
803     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
804         return ret;
805     samples = (int16_t *)frame->data[0];
806     samples_p = (int16_t **)frame->extended_data;
807
808     /* use coded_samples when applicable */
809     /* it is always <= nb_samples, so the output buffer will be large enough */
810     if (coded_samples) {
811         if (!approx_nb_samples && coded_samples != nb_samples)
812             av_log(avctx, AV_LOG_WARNING, "mismatch in coded sample count\n");
813         frame->nb_samples = nb_samples = coded_samples;
814     }
815
816     st = avctx->channels == 2 ? 1 : 0;
817
818     switch(avctx->codec->id) {
819     case AV_CODEC_ID_ADPCM_IMA_QT:
820         /* In QuickTime, IMA is encoded by chunks of 34 bytes (=64 samples).
821            Channel data is interleaved per-chunk. */
822         for (channel = 0; channel < avctx->channels; channel++) {
823             int predictor;
824             int step_index;
825             cs = &(c->status[channel]);
826             /* (pppppp) (piiiiiii) */
827
828             /* Bits 15-7 are the _top_ 9 bits of the 16-bit initial predictor value */
829             predictor = sign_extend(bytestream2_get_be16u(&gb), 16);
830             step_index = predictor & 0x7F;
831             predictor &= ~0x7F;
832
833             if (cs->step_index == step_index) {
834                 int diff = predictor - cs->predictor;
835                 if (diff < 0)
836                     diff = - diff;
837                 if (diff > 0x7f)
838                     goto update;
839             } else {
840             update:
841                 cs->step_index = step_index;
842                 cs->predictor = predictor;
843             }
844
845             if (cs->step_index > 88u){
846                 av_log(avctx, AV_LOG_ERROR, "ERROR: step_index[%d] = %i\n",
847                        channel, cs->step_index);
848                 return AVERROR_INVALIDDATA;
849             }
850
851             samples = samples_p[channel];
852
853             for (m = 0; m < 64; m += 2) {
854                 int byte = bytestream2_get_byteu(&gb);
855                 samples[m    ] = adpcm_ima_qt_expand_nibble(cs, byte & 0x0F, 3);
856                 samples[m + 1] = adpcm_ima_qt_expand_nibble(cs, byte >> 4  , 3);
857             }
858         }
859         break;
860     case AV_CODEC_ID_ADPCM_IMA_WAV:
861         for(i=0; i<avctx->channels; i++){
862             cs = &(c->status[i]);
863             cs->predictor = samples_p[i][0] = sign_extend(bytestream2_get_le16u(&gb), 16);
864
865             cs->step_index = sign_extend(bytestream2_get_le16u(&gb), 16);
866             if (cs->step_index > 88u){
867                 av_log(avctx, AV_LOG_ERROR, "ERROR: step_index[%d] = %i\n",
868                        i, cs->step_index);
869                 return AVERROR_INVALIDDATA;
870             }
871         }
872
873         if (avctx->bits_per_coded_sample != 4) {
874             int samples_per_block = ff_adpcm_ima_block_samples[avctx->bits_per_coded_sample - 2];
875             int block_size = ff_adpcm_ima_block_sizes[avctx->bits_per_coded_sample - 2];
876             uint8_t temp[20 + AV_INPUT_BUFFER_PADDING_SIZE] = { 0 };
877             GetBitContext g;
878
879             for (n = 0; n < (nb_samples - 1) / samples_per_block; n++) {
880                 for (i = 0; i < avctx->channels; i++) {
881                     int j;
882
883                     cs = &c->status[i];
884                     samples = &samples_p[i][1 + n * samples_per_block];
885                     for (j = 0; j < block_size; j++) {
886                         temp[j] = buf[4 * avctx->channels + block_size * n * avctx->channels +
887                                         (j % 4) + (j / 4) * (avctx->channels * 4) + i * 4];
888                     }
889                     ret = init_get_bits8(&g, (const uint8_t *)&temp, block_size);
890                     if (ret < 0)
891                         return ret;
892                     for (m = 0; m < samples_per_block; m++) {
893                         samples[m] = adpcm_ima_wav_expand_nibble(cs, &g,
894                                           avctx->bits_per_coded_sample);
895                     }
896                 }
897             }
898             bytestream2_skip(&gb, avctx->block_align - avctx->channels * 4);
899         } else {
900         for (n = 0; n < (nb_samples - 1) / 8; n++) {
901             for (i = 0; i < avctx->channels; i++) {
902                 cs = &c->status[i];
903                 samples = &samples_p[i][1 + n * 8];
904                 for (m = 0; m < 8; m += 2) {
905                     int v = bytestream2_get_byteu(&gb);
906                     samples[m    ] = adpcm_ima_expand_nibble(cs, v & 0x0F, 3);
907                     samples[m + 1] = adpcm_ima_expand_nibble(cs, v >> 4  , 3);
908                 }
909             }
910         }
911         }
912         break;
913     case AV_CODEC_ID_ADPCM_4XM:
914         for (i = 0; i < avctx->channels; i++)
915             c->status[i].predictor = sign_extend(bytestream2_get_le16u(&gb), 16);
916
917         for (i = 0; i < avctx->channels; i++) {
918             c->status[i].step_index = sign_extend(bytestream2_get_le16u(&gb), 16);
919             if (c->status[i].step_index > 88u) {
920                 av_log(avctx, AV_LOG_ERROR, "ERROR: step_index[%d] = %i\n",
921                        i, c->status[i].step_index);
922                 return AVERROR_INVALIDDATA;
923             }
924         }
925
926         for (i = 0; i < avctx->channels; i++) {
927             samples = (int16_t *)frame->data[i];
928             cs = &c->status[i];
929             for (n = nb_samples >> 1; n > 0; n--) {
930                 int v = bytestream2_get_byteu(&gb);
931                 *samples++ = adpcm_ima_expand_nibble(cs, v & 0x0F, 4);
932                 *samples++ = adpcm_ima_expand_nibble(cs, v >> 4  , 4);
933             }
934         }
935         break;
936     case AV_CODEC_ID_ADPCM_AGM:
937         for (i = 0; i < avctx->channels; i++)
938             c->status[i].predictor = sign_extend(bytestream2_get_le16u(&gb), 16);
939         for (i = 0; i < avctx->channels; i++)
940             c->status[i].step = sign_extend(bytestream2_get_le16u(&gb), 16);
941
942         for (n = 0; n < nb_samples >> (1 - st); n++) {
943             int v = bytestream2_get_byteu(&gb);
944             *samples++ = adpcm_agm_expand_nibble(&c->status[0], v & 0xF);
945             *samples++ = adpcm_agm_expand_nibble(&c->status[st], v >> 4 );
946         }
947         break;
948     case AV_CODEC_ID_ADPCM_MS:
949     {
950         int block_predictor;
951
952         if (avctx->channels > 2) {
953             for (channel = 0; channel < avctx->channels; channel++) {
954                 samples = samples_p[channel];
955                 block_predictor = bytestream2_get_byteu(&gb);
956                 if (block_predictor > 6) {
957                     av_log(avctx, AV_LOG_ERROR, "ERROR: block_predictor[%d] = %d\n",
958                            channel, block_predictor);
959                     return AVERROR_INVALIDDATA;
960                 }
961                 c->status[channel].coeff1 = ff_adpcm_AdaptCoeff1[block_predictor];
962                 c->status[channel].coeff2 = ff_adpcm_AdaptCoeff2[block_predictor];
963                 c->status[channel].idelta = sign_extend(bytestream2_get_le16u(&gb), 16);
964                 c->status[channel].sample1 = sign_extend(bytestream2_get_le16u(&gb), 16);
965                 c->status[channel].sample2 = sign_extend(bytestream2_get_le16u(&gb), 16);
966                 *samples++ = c->status[channel].sample2;
967                 *samples++ = c->status[channel].sample1;
968                 for(n = (nb_samples - 2) >> 1; n > 0; n--) {
969                     int byte = bytestream2_get_byteu(&gb);
970                     *samples++ = adpcm_ms_expand_nibble(&c->status[channel], byte >> 4  );
971                     *samples++ = adpcm_ms_expand_nibble(&c->status[channel], byte & 0x0F);
972                 }
973             }
974         } else {
975             block_predictor = bytestream2_get_byteu(&gb);
976             if (block_predictor > 6) {
977                 av_log(avctx, AV_LOG_ERROR, "ERROR: block_predictor[0] = %d\n",
978                        block_predictor);
979                 return AVERROR_INVALIDDATA;
980             }
981             c->status[0].coeff1 = ff_adpcm_AdaptCoeff1[block_predictor];
982             c->status[0].coeff2 = ff_adpcm_AdaptCoeff2[block_predictor];
983             if (st) {
984                 block_predictor = bytestream2_get_byteu(&gb);
985                 if (block_predictor > 6) {
986                     av_log(avctx, AV_LOG_ERROR, "ERROR: block_predictor[1] = %d\n",
987                            block_predictor);
988                     return AVERROR_INVALIDDATA;
989                 }
990                 c->status[1].coeff1 = ff_adpcm_AdaptCoeff1[block_predictor];
991                 c->status[1].coeff2 = ff_adpcm_AdaptCoeff2[block_predictor];
992             }
993             c->status[0].idelta = sign_extend(bytestream2_get_le16u(&gb), 16);
994             if (st){
995                 c->status[1].idelta = sign_extend(bytestream2_get_le16u(&gb), 16);
996             }
997
998             c->status[0].sample1 = sign_extend(bytestream2_get_le16u(&gb), 16);
999             if (st) c->status[1].sample1 = sign_extend(bytestream2_get_le16u(&gb), 16);
1000             c->status[0].sample2 = sign_extend(bytestream2_get_le16u(&gb), 16);
1001             if (st) c->status[1].sample2 = sign_extend(bytestream2_get_le16u(&gb), 16);
1002
1003             *samples++ = c->status[0].sample2;
1004             if (st) *samples++ = c->status[1].sample2;
1005             *samples++ = c->status[0].sample1;
1006             if (st) *samples++ = c->status[1].sample1;
1007             for(n = (nb_samples - 2) >> (1 - st); n > 0; n--) {
1008                 int byte = bytestream2_get_byteu(&gb);
1009                 *samples++ = adpcm_ms_expand_nibble(&c->status[0 ], byte >> 4  );
1010                 *samples++ = adpcm_ms_expand_nibble(&c->status[st], byte & 0x0F);
1011             }
1012         }
1013         break;
1014     }
1015     case AV_CODEC_ID_ADPCM_MTAF:
1016         for (channel = 0; channel < avctx->channels; channel+=2) {
1017             bytestream2_skipu(&gb, 4);
1018             c->status[channel    ].step      = bytestream2_get_le16u(&gb) & 0x1f;
1019             c->status[channel + 1].step      = bytestream2_get_le16u(&gb) & 0x1f;
1020             c->status[channel    ].predictor = sign_extend(bytestream2_get_le16u(&gb), 16);
1021             bytestream2_skipu(&gb, 2);
1022             c->status[channel + 1].predictor = sign_extend(bytestream2_get_le16u(&gb), 16);
1023             bytestream2_skipu(&gb, 2);
1024             for (n = 0; n < nb_samples; n+=2) {
1025                 int v = bytestream2_get_byteu(&gb);
1026                 samples_p[channel][n    ] = adpcm_mtaf_expand_nibble(&c->status[channel], v & 0x0F);
1027                 samples_p[channel][n + 1] = adpcm_mtaf_expand_nibble(&c->status[channel], v >> 4  );
1028             }
1029             for (n = 0; n < nb_samples; n+=2) {
1030                 int v = bytestream2_get_byteu(&gb);
1031                 samples_p[channel + 1][n    ] = adpcm_mtaf_expand_nibble(&c->status[channel + 1], v & 0x0F);
1032                 samples_p[channel + 1][n + 1] = adpcm_mtaf_expand_nibble(&c->status[channel + 1], v >> 4  );
1033             }
1034         }
1035         break;
1036     case AV_CODEC_ID_ADPCM_IMA_DK4:
1037         for (channel = 0; channel < avctx->channels; channel++) {
1038             cs = &c->status[channel];
1039             cs->predictor  = *samples++ = sign_extend(bytestream2_get_le16u(&gb), 16);
1040             cs->step_index = sign_extend(bytestream2_get_le16u(&gb), 16);
1041             if (cs->step_index > 88u){
1042                 av_log(avctx, AV_LOG_ERROR, "ERROR: step_index[%d] = %i\n",
1043                        channel, cs->step_index);
1044                 return AVERROR_INVALIDDATA;
1045             }
1046         }
1047         for (n = (nb_samples - 1) >> (1 - st); n > 0; n--) {
1048             int v = bytestream2_get_byteu(&gb);
1049             *samples++ = adpcm_ima_expand_nibble(&c->status[0 ], v >> 4  , 3);
1050             *samples++ = adpcm_ima_expand_nibble(&c->status[st], v & 0x0F, 3);
1051         }
1052         break;
1053     case AV_CODEC_ID_ADPCM_IMA_DK3:
1054     {
1055         int last_byte = 0;
1056         int nibble;
1057         int decode_top_nibble_next = 0;
1058         int diff_channel;
1059         const int16_t *samples_end = samples + avctx->channels * nb_samples;
1060
1061         bytestream2_skipu(&gb, 10);
1062         c->status[0].predictor  = sign_extend(bytestream2_get_le16u(&gb), 16);
1063         c->status[1].predictor  = sign_extend(bytestream2_get_le16u(&gb), 16);
1064         c->status[0].step_index = bytestream2_get_byteu(&gb);
1065         c->status[1].step_index = bytestream2_get_byteu(&gb);
1066         if (c->status[0].step_index > 88u || c->status[1].step_index > 88u){
1067             av_log(avctx, AV_LOG_ERROR, "ERROR: step_index = %i/%i\n",
1068                    c->status[0].step_index, c->status[1].step_index);
1069             return AVERROR_INVALIDDATA;
1070         }
1071         /* sign extend the predictors */
1072         diff_channel = c->status[1].predictor;
1073
1074         /* DK3 ADPCM support macro */
1075 #define DK3_GET_NEXT_NIBBLE() \
1076     if (decode_top_nibble_next) { \
1077         nibble = last_byte >> 4; \
1078         decode_top_nibble_next = 0; \
1079     } else { \
1080         last_byte = bytestream2_get_byteu(&gb); \
1081         nibble = last_byte & 0x0F; \
1082         decode_top_nibble_next = 1; \
1083     }
1084
1085         while (samples < samples_end) {
1086
1087             /* for this algorithm, c->status[0] is the sum channel and
1088              * c->status[1] is the diff channel */
1089
1090             /* process the first predictor of the sum channel */
1091             DK3_GET_NEXT_NIBBLE();
1092             adpcm_ima_expand_nibble(&c->status[0], nibble, 3);
1093
1094             /* process the diff channel predictor */
1095             DK3_GET_NEXT_NIBBLE();
1096             adpcm_ima_expand_nibble(&c->status[1], nibble, 3);
1097
1098             /* process the first pair of stereo PCM samples */
1099             diff_channel = (diff_channel + c->status[1].predictor) / 2;
1100             *samples++ = c->status[0].predictor + c->status[1].predictor;
1101             *samples++ = c->status[0].predictor - c->status[1].predictor;
1102
1103             /* process the second predictor of the sum channel */
1104             DK3_GET_NEXT_NIBBLE();
1105             adpcm_ima_expand_nibble(&c->status[0], nibble, 3);
1106
1107             /* process the second pair of stereo PCM samples */
1108             diff_channel = (diff_channel + c->status[1].predictor) / 2;
1109             *samples++ = c->status[0].predictor + c->status[1].predictor;
1110             *samples++ = c->status[0].predictor - c->status[1].predictor;
1111         }
1112
1113         if ((bytestream2_tell(&gb) & 1))
1114             bytestream2_skip(&gb, 1);
1115         break;
1116     }
1117     case AV_CODEC_ID_ADPCM_IMA_ISS:
1118         for (channel = 0; channel < avctx->channels; channel++) {
1119             cs = &c->status[channel];
1120             cs->predictor  = sign_extend(bytestream2_get_le16u(&gb), 16);
1121             cs->step_index = sign_extend(bytestream2_get_le16u(&gb), 16);
1122             if (cs->step_index > 88u){
1123                 av_log(avctx, AV_LOG_ERROR, "ERROR: step_index[%d] = %i\n",
1124                        channel, cs->step_index);
1125                 return AVERROR_INVALIDDATA;
1126             }
1127         }
1128
1129         for (n = nb_samples >> (1 - st); n > 0; n--) {
1130             int v1, v2;
1131             int v = bytestream2_get_byteu(&gb);
1132             /* nibbles are swapped for mono */
1133             if (st) {
1134                 v1 = v >> 4;
1135                 v2 = v & 0x0F;
1136             } else {
1137                 v2 = v >> 4;
1138                 v1 = v & 0x0F;
1139             }
1140             *samples++ = adpcm_ima_expand_nibble(&c->status[0 ], v1, 3);
1141             *samples++ = adpcm_ima_expand_nibble(&c->status[st], v2, 3);
1142         }
1143         break;
1144     case AV_CODEC_ID_ADPCM_IMA_DAT4:
1145         for (channel = 0; channel < avctx->channels; channel++) {
1146             cs = &c->status[channel];
1147             samples = samples_p[channel];
1148             bytestream2_skip(&gb, 4);
1149             for (n = 0; n < nb_samples; n += 2) {
1150                 int v = bytestream2_get_byteu(&gb);
1151                 *samples++ = adpcm_ima_expand_nibble(cs, v >> 4  , 3);
1152                 *samples++ = adpcm_ima_expand_nibble(cs, v & 0x0F, 3);
1153             }
1154         }
1155         break;
1156     case AV_CODEC_ID_ADPCM_IMA_APC:
1157         while (bytestream2_get_bytes_left(&gb) > 0) {
1158             int v = bytestream2_get_byteu(&gb);
1159             *samples++ = adpcm_ima_expand_nibble(&c->status[0],  v >> 4  , 3);
1160             *samples++ = adpcm_ima_expand_nibble(&c->status[st], v & 0x0F, 3);
1161         }
1162         break;
1163     case AV_CODEC_ID_ADPCM_IMA_OKI:
1164         while (bytestream2_get_bytes_left(&gb) > 0) {
1165             int v = bytestream2_get_byteu(&gb);
1166             *samples++ = adpcm_ima_oki_expand_nibble(&c->status[0],  v >> 4  );
1167             *samples++ = adpcm_ima_oki_expand_nibble(&c->status[st], v & 0x0F);
1168         }
1169         break;
1170     case AV_CODEC_ID_ADPCM_IMA_RAD:
1171         for (channel = 0; channel < avctx->channels; channel++) {
1172             cs = &c->status[channel];
1173             cs->step_index = sign_extend(bytestream2_get_le16u(&gb), 16);
1174             cs->predictor  = sign_extend(bytestream2_get_le16u(&gb), 16);
1175             if (cs->step_index > 88u){
1176                 av_log(avctx, AV_LOG_ERROR, "ERROR: step_index[%d] = %i\n",
1177                        channel, cs->step_index);
1178                 return AVERROR_INVALIDDATA;
1179             }
1180         }
1181         for (n = 0; n < nb_samples / 2; n++) {
1182             int byte[2];
1183
1184             byte[0] = bytestream2_get_byteu(&gb);
1185             if (st)
1186                 byte[1] = bytestream2_get_byteu(&gb);
1187             for(channel = 0; channel < avctx->channels; channel++) {
1188                 *samples++ = adpcm_ima_expand_nibble(&c->status[channel], byte[channel] & 0x0F, 3);
1189             }
1190             for(channel = 0; channel < avctx->channels; channel++) {
1191                 *samples++ = adpcm_ima_expand_nibble(&c->status[channel], byte[channel] >> 4  , 3);
1192             }
1193         }
1194         break;
1195     case AV_CODEC_ID_ADPCM_IMA_WS:
1196         if (c->vqa_version == 3) {
1197             for (channel = 0; channel < avctx->channels; channel++) {
1198                 int16_t *smp = samples_p[channel];
1199
1200                 for (n = nb_samples / 2; n > 0; n--) {
1201                     int v = bytestream2_get_byteu(&gb);
1202                     *smp++ = adpcm_ima_expand_nibble(&c->status[channel], v >> 4  , 3);
1203                     *smp++ = adpcm_ima_expand_nibble(&c->status[channel], v & 0x0F, 3);
1204                 }
1205             }
1206         } else {
1207             for (n = nb_samples / 2; n > 0; n--) {
1208                 for (channel = 0; channel < avctx->channels; channel++) {
1209                     int v = bytestream2_get_byteu(&gb);
1210                     *samples++  = adpcm_ima_expand_nibble(&c->status[channel], v >> 4  , 3);
1211                     samples[st] = adpcm_ima_expand_nibble(&c->status[channel], v & 0x0F, 3);
1212                 }
1213                 samples += avctx->channels;
1214             }
1215         }
1216         bytestream2_seek(&gb, 0, SEEK_END);
1217         break;
1218     case AV_CODEC_ID_ADPCM_XA:
1219     {
1220         int16_t *out0 = samples_p[0];
1221         int16_t *out1 = samples_p[1];
1222         int samples_per_block = 28 * (3 - avctx->channels) * 4;
1223         int sample_offset = 0;
1224         int bytes_remaining;
1225         while (bytestream2_get_bytes_left(&gb) >= 128) {
1226             if ((ret = xa_decode(avctx, out0, out1, buf + bytestream2_tell(&gb),
1227                                  &c->status[0], &c->status[1],
1228                                  avctx->channels, sample_offset)) < 0)
1229                 return ret;
1230             bytestream2_skipu(&gb, 128);
1231             sample_offset += samples_per_block;
1232         }
1233         /* Less than a full block of data left, e.g. when reading from
1234          * 2324 byte per sector XA; the remainder is padding */
1235         bytes_remaining = bytestream2_get_bytes_left(&gb);
1236         if (bytes_remaining > 0) {
1237             bytestream2_skip(&gb, bytes_remaining);
1238         }
1239         break;
1240     }
1241     case AV_CODEC_ID_ADPCM_IMA_EA_EACS:
1242         for (i=0; i<=st; i++) {
1243             c->status[i].step_index = bytestream2_get_le32u(&gb);
1244             if (c->status[i].step_index > 88u) {
1245                 av_log(avctx, AV_LOG_ERROR, "ERROR: step_index[%d] = %i\n",
1246                        i, c->status[i].step_index);
1247                 return AVERROR_INVALIDDATA;
1248             }
1249         }
1250         for (i=0; i<=st; i++) {
1251             c->status[i].predictor  = bytestream2_get_le32u(&gb);
1252             if (FFABS((int64_t)c->status[i].predictor) > (1<<16))
1253                 return AVERROR_INVALIDDATA;
1254         }
1255
1256         for (n = nb_samples >> (1 - st); n > 0; n--) {
1257             int byte   = bytestream2_get_byteu(&gb);
1258             *samples++ = adpcm_ima_expand_nibble(&c->status[0],  byte >> 4,   3);
1259             *samples++ = adpcm_ima_expand_nibble(&c->status[st], byte & 0x0F, 3);
1260         }
1261         break;
1262     case AV_CODEC_ID_ADPCM_IMA_EA_SEAD:
1263         for (n = nb_samples >> (1 - st); n > 0; n--) {
1264             int byte = bytestream2_get_byteu(&gb);
1265             *samples++ = adpcm_ima_expand_nibble(&c->status[0],  byte >> 4,   6);
1266             *samples++ = adpcm_ima_expand_nibble(&c->status[st], byte & 0x0F, 6);
1267         }
1268         break;
1269     case AV_CODEC_ID_ADPCM_EA:
1270     {
1271         int previous_left_sample, previous_right_sample;
1272         int current_left_sample, current_right_sample;
1273         int next_left_sample, next_right_sample;
1274         int coeff1l, coeff2l, coeff1r, coeff2r;
1275         int shift_left, shift_right;
1276
1277         /* Each EA ADPCM frame has a 12-byte header followed by 30-byte pieces,
1278            each coding 28 stereo samples. */
1279
1280         if(avctx->channels != 2)
1281             return AVERROR_INVALIDDATA;
1282
1283         current_left_sample   = sign_extend(bytestream2_get_le16u(&gb), 16);
1284         previous_left_sample  = sign_extend(bytestream2_get_le16u(&gb), 16);
1285         current_right_sample  = sign_extend(bytestream2_get_le16u(&gb), 16);
1286         previous_right_sample = sign_extend(bytestream2_get_le16u(&gb), 16);
1287
1288         for (count1 = 0; count1 < nb_samples / 28; count1++) {
1289             int byte = bytestream2_get_byteu(&gb);
1290             coeff1l = ea_adpcm_table[ byte >> 4       ];
1291             coeff2l = ea_adpcm_table[(byte >> 4  ) + 4];
1292             coeff1r = ea_adpcm_table[ byte & 0x0F];
1293             coeff2r = ea_adpcm_table[(byte & 0x0F) + 4];
1294
1295             byte = bytestream2_get_byteu(&gb);
1296             shift_left  = 20 - (byte >> 4);
1297             shift_right = 20 - (byte & 0x0F);
1298
1299             for (count2 = 0; count2 < 28; count2++) {
1300                 byte = bytestream2_get_byteu(&gb);
1301                 next_left_sample  = sign_extend(byte >> 4, 4) * (1 << shift_left);
1302                 next_right_sample = sign_extend(byte,      4) * (1 << shift_right);
1303
1304                 next_left_sample = (next_left_sample +
1305                     (current_left_sample * coeff1l) +
1306                     (previous_left_sample * coeff2l) + 0x80) >> 8;
1307                 next_right_sample = (next_right_sample +
1308                     (current_right_sample * coeff1r) +
1309                     (previous_right_sample * coeff2r) + 0x80) >> 8;
1310
1311                 previous_left_sample = current_left_sample;
1312                 current_left_sample = av_clip_int16(next_left_sample);
1313                 previous_right_sample = current_right_sample;
1314                 current_right_sample = av_clip_int16(next_right_sample);
1315                 *samples++ = current_left_sample;
1316                 *samples++ = current_right_sample;
1317             }
1318         }
1319
1320         bytestream2_skip(&gb, 2); // Skip terminating 0x0000
1321
1322         break;
1323     }
1324     case AV_CODEC_ID_ADPCM_EA_MAXIS_XA:
1325     {
1326         int coeff[2][2], shift[2];
1327
1328         for(channel = 0; channel < avctx->channels; channel++) {
1329             int byte = bytestream2_get_byteu(&gb);
1330             for (i=0; i<2; i++)
1331                 coeff[channel][i] = ea_adpcm_table[(byte >> 4) + 4*i];
1332             shift[channel] = 20 - (byte & 0x0F);
1333         }
1334         for (count1 = 0; count1 < nb_samples / 2; count1++) {
1335             int byte[2];
1336
1337             byte[0] = bytestream2_get_byteu(&gb);
1338             if (st) byte[1] = bytestream2_get_byteu(&gb);
1339             for(i = 4; i >= 0; i-=4) { /* Pairwise samples LL RR (st) or LL LL (mono) */
1340                 for(channel = 0; channel < avctx->channels; channel++) {
1341                     int sample = sign_extend(byte[channel] >> i, 4) * (1 << shift[channel]);
1342                     sample = (sample +
1343                              c->status[channel].sample1 * coeff[channel][0] +
1344                              c->status[channel].sample2 * coeff[channel][1] + 0x80) >> 8;
1345                     c->status[channel].sample2 = c->status[channel].sample1;
1346                     c->status[channel].sample1 = av_clip_int16(sample);
1347                     *samples++ = c->status[channel].sample1;
1348                 }
1349             }
1350         }
1351         bytestream2_seek(&gb, 0, SEEK_END);
1352         break;
1353     }
1354     case AV_CODEC_ID_ADPCM_EA_R1:
1355     case AV_CODEC_ID_ADPCM_EA_R2:
1356     case AV_CODEC_ID_ADPCM_EA_R3: {
1357         /* channel numbering
1358            2chan: 0=fl, 1=fr
1359            4chan: 0=fl, 1=rl, 2=fr, 3=rr
1360            6chan: 0=fl, 1=c,  2=fr, 3=rl,  4=rr, 5=sub */
1361         const int big_endian = avctx->codec->id == AV_CODEC_ID_ADPCM_EA_R3;
1362         int previous_sample, current_sample, next_sample;
1363         int coeff1, coeff2;
1364         int shift;
1365         unsigned int channel;
1366         uint16_t *samplesC;
1367         int count = 0;
1368         int offsets[6];
1369
1370         for (channel=0; channel<avctx->channels; channel++)
1371             offsets[channel] = (big_endian ? bytestream2_get_be32(&gb) :
1372                                              bytestream2_get_le32(&gb)) +
1373                                (avctx->channels + 1) * 4;
1374
1375         for (channel=0; channel<avctx->channels; channel++) {
1376             bytestream2_seek(&gb, offsets[channel], SEEK_SET);
1377             samplesC = samples_p[channel];
1378
1379             if (avctx->codec->id == AV_CODEC_ID_ADPCM_EA_R1) {
1380                 current_sample  = sign_extend(bytestream2_get_le16(&gb), 16);
1381                 previous_sample = sign_extend(bytestream2_get_le16(&gb), 16);
1382             } else {
1383                 current_sample  = c->status[channel].predictor;
1384                 previous_sample = c->status[channel].prev_sample;
1385             }
1386
1387             for (count1 = 0; count1 < nb_samples / 28; count1++) {
1388                 int byte = bytestream2_get_byte(&gb);
1389                 if (byte == 0xEE) {  /* only seen in R2 and R3 */
1390                     current_sample  = sign_extend(bytestream2_get_be16(&gb), 16);
1391                     previous_sample = sign_extend(bytestream2_get_be16(&gb), 16);
1392
1393                     for (count2=0; count2<28; count2++)
1394                         *samplesC++ = sign_extend(bytestream2_get_be16(&gb), 16);
1395                 } else {
1396                     coeff1 = ea_adpcm_table[ byte >> 4     ];
1397                     coeff2 = ea_adpcm_table[(byte >> 4) + 4];
1398                     shift = 20 - (byte & 0x0F);
1399
1400                     for (count2=0; count2<28; count2++) {
1401                         if (count2 & 1)
1402                             next_sample = (unsigned)sign_extend(byte,    4) << shift;
1403                         else {
1404                             byte = bytestream2_get_byte(&gb);
1405                             next_sample = (unsigned)sign_extend(byte >> 4, 4) << shift;
1406                         }
1407
1408                         next_sample += (current_sample  * coeff1) +
1409                                        (previous_sample * coeff2);
1410                         next_sample = av_clip_int16(next_sample >> 8);
1411
1412                         previous_sample = current_sample;
1413                         current_sample  = next_sample;
1414                         *samplesC++ = current_sample;
1415                     }
1416                 }
1417             }
1418             if (!count) {
1419                 count = count1;
1420             } else if (count != count1) {
1421                 av_log(avctx, AV_LOG_WARNING, "per-channel sample count mismatch\n");
1422                 count = FFMAX(count, count1);
1423             }
1424
1425             if (avctx->codec->id != AV_CODEC_ID_ADPCM_EA_R1) {
1426                 c->status[channel].predictor   = current_sample;
1427                 c->status[channel].prev_sample = previous_sample;
1428             }
1429         }
1430
1431         frame->nb_samples = count * 28;
1432         bytestream2_seek(&gb, 0, SEEK_END);
1433         break;
1434     }
1435     case AV_CODEC_ID_ADPCM_EA_XAS:
1436         for (channel=0; channel<avctx->channels; channel++) {
1437             int coeff[2][4], shift[4];
1438             int16_t *s = samples_p[channel];
1439             for (n = 0; n < 4; n++, s += 32) {
1440                 int val = sign_extend(bytestream2_get_le16u(&gb), 16);
1441                 for (i=0; i<2; i++)
1442                     coeff[i][n] = ea_adpcm_table[(val&0x0F)+4*i];
1443                 s[0] = val & ~0x0F;
1444
1445                 val = sign_extend(bytestream2_get_le16u(&gb), 16);
1446                 shift[n] = 20 - (val & 0x0F);
1447                 s[1] = val & ~0x0F;
1448             }
1449
1450             for (m=2; m<32; m+=2) {
1451                 s = &samples_p[channel][m];
1452                 for (n = 0; n < 4; n++, s += 32) {
1453                     int level, pred;
1454                     int byte = bytestream2_get_byteu(&gb);
1455
1456                     level = sign_extend(byte >> 4, 4) * (1 << shift[n]);
1457                     pred  = s[-1] * coeff[0][n] + s[-2] * coeff[1][n];
1458                     s[0]  = av_clip_int16((level + pred + 0x80) >> 8);
1459
1460                     level = sign_extend(byte, 4) * (1 << shift[n]);
1461                     pred  = s[0] * coeff[0][n] + s[-1] * coeff[1][n];
1462                     s[1]  = av_clip_int16((level + pred + 0x80) >> 8);
1463                 }
1464             }
1465         }
1466         break;
1467     case AV_CODEC_ID_ADPCM_IMA_AMV:
1468         c->status[0].predictor = sign_extend(bytestream2_get_le16u(&gb), 16);
1469         c->status[0].step_index = bytestream2_get_byteu(&gb);
1470         bytestream2_skipu(&gb, 5);
1471         if (c->status[0].step_index > 88u) {
1472             av_log(avctx, AV_LOG_ERROR, "ERROR: step_index = %i\n",
1473                    c->status[0].step_index);
1474             return AVERROR_INVALIDDATA;
1475         }
1476
1477         for (n = nb_samples >> (1 - st); n > 0; n--) {
1478             int v = bytestream2_get_byteu(&gb);
1479
1480             *samples++ = adpcm_ima_expand_nibble(&c->status[0], v >> 4, 3);
1481             *samples++ = adpcm_ima_expand_nibble(&c->status[0], v & 0xf, 3);
1482         }
1483         break;
1484     case AV_CODEC_ID_ADPCM_IMA_SMJPEG:
1485         for (i = 0; i < avctx->channels; i++) {
1486             c->status[i].predictor = sign_extend(bytestream2_get_be16u(&gb), 16);
1487             c->status[i].step_index = bytestream2_get_byteu(&gb);
1488             bytestream2_skipu(&gb, 1);
1489             if (c->status[i].step_index > 88u) {
1490                 av_log(avctx, AV_LOG_ERROR, "ERROR: step_index = %i\n",
1491                        c->status[i].step_index);
1492                 return AVERROR_INVALIDDATA;
1493             }
1494         }
1495
1496         for (n = nb_samples >> (1 - st); n > 0; n--) {
1497             int v = bytestream2_get_byteu(&gb);
1498
1499             *samples++ = adpcm_ima_qt_expand_nibble(&c->status[0 ], v >> 4, 3);
1500             *samples++ = adpcm_ima_qt_expand_nibble(&c->status[st], v & 0xf, 3);
1501         }
1502         break;
1503     case AV_CODEC_ID_ADPCM_CT:
1504         for (n = nb_samples >> (1 - st); n > 0; n--) {
1505             int v = bytestream2_get_byteu(&gb);
1506             *samples++ = adpcm_ct_expand_nibble(&c->status[0 ], v >> 4  );
1507             *samples++ = adpcm_ct_expand_nibble(&c->status[st], v & 0x0F);
1508         }
1509         break;
1510     case AV_CODEC_ID_ADPCM_SBPRO_4:
1511     case AV_CODEC_ID_ADPCM_SBPRO_3:
1512     case AV_CODEC_ID_ADPCM_SBPRO_2:
1513         if (!c->status[0].step_index) {
1514             /* the first byte is a raw sample */
1515             *samples++ = 128 * (bytestream2_get_byteu(&gb) - 0x80);
1516             if (st)
1517                 *samples++ = 128 * (bytestream2_get_byteu(&gb) - 0x80);
1518             c->status[0].step_index = 1;
1519             nb_samples--;
1520         }
1521         if (avctx->codec->id == AV_CODEC_ID_ADPCM_SBPRO_4) {
1522             for (n = nb_samples >> (1 - st); n > 0; n--) {
1523                 int byte = bytestream2_get_byteu(&gb);
1524                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
1525                                                        byte >> 4,   4, 0);
1526                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],
1527                                                        byte & 0x0F, 4, 0);
1528             }
1529         } else if (avctx->codec->id == AV_CODEC_ID_ADPCM_SBPRO_3) {
1530             for (n = (nb_samples<<st) / 3; n > 0; n--) {
1531                 int byte = bytestream2_get_byteu(&gb);
1532                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
1533                                                         byte >> 5        , 3, 0);
1534                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
1535                                                        (byte >> 2) & 0x07, 3, 0);
1536                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
1537                                                         byte & 0x03,       2, 0);
1538             }
1539         } else {
1540             for (n = nb_samples >> (2 - st); n > 0; n--) {
1541                 int byte = bytestream2_get_byteu(&gb);
1542                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
1543                                                         byte >> 6        , 2, 2);
1544                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],
1545                                                        (byte >> 4) & 0x03, 2, 2);
1546                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
1547                                                        (byte >> 2) & 0x03, 2, 2);
1548                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],
1549                                                         byte & 0x03,       2, 2);
1550             }
1551         }
1552         break;
1553     case AV_CODEC_ID_ADPCM_SWF:
1554         adpcm_swf_decode(avctx, buf, buf_size, samples);
1555         bytestream2_seek(&gb, 0, SEEK_END);
1556         break;
1557     case AV_CODEC_ID_ADPCM_YAMAHA:
1558         for (n = nb_samples >> (1 - st); n > 0; n--) {
1559             int v = bytestream2_get_byteu(&gb);
1560             *samples++ = adpcm_yamaha_expand_nibble(&c->status[0 ], v & 0x0F);
1561             *samples++ = adpcm_yamaha_expand_nibble(&c->status[st], v >> 4  );
1562         }
1563         break;
1564     case AV_CODEC_ID_ADPCM_AICA:
1565         if (!c->has_status) {
1566             for (channel = 0; channel < avctx->channels; channel++)
1567                 c->status[channel].step = 0;
1568             c->has_status = 1;
1569         }
1570         for (channel = 0; channel < avctx->channels; channel++) {
1571             samples = samples_p[channel];
1572             for (n = nb_samples >> 1; n > 0; n--) {
1573                 int v = bytestream2_get_byteu(&gb);
1574                 *samples++ = adpcm_yamaha_expand_nibble(&c->status[channel], v & 0x0F);
1575                 *samples++ = adpcm_yamaha_expand_nibble(&c->status[channel], v >> 4  );
1576             }
1577         }
1578         break;
1579     case AV_CODEC_ID_ADPCM_AFC:
1580     {
1581         int samples_per_block;
1582         int blocks;
1583
1584         if (avctx->extradata && avctx->extradata_size == 1 && avctx->extradata[0]) {
1585             samples_per_block = avctx->extradata[0] / 16;
1586             blocks = nb_samples / avctx->extradata[0];
1587         } else {
1588             samples_per_block = nb_samples / 16;
1589             blocks = 1;
1590         }
1591
1592         for (m = 0; m < blocks; m++) {
1593         for (channel = 0; channel < avctx->channels; channel++) {
1594             int prev1 = c->status[channel].sample1;
1595             int prev2 = c->status[channel].sample2;
1596
1597             samples = samples_p[channel] + m * 16;
1598             /* Read in every sample for this channel.  */
1599             for (i = 0; i < samples_per_block; i++) {
1600                 int byte = bytestream2_get_byteu(&gb);
1601                 int scale = 1 << (byte >> 4);
1602                 int index = byte & 0xf;
1603                 int factor1 = ff_adpcm_afc_coeffs[0][index];
1604                 int factor2 = ff_adpcm_afc_coeffs[1][index];
1605
1606                 /* Decode 16 samples.  */
1607                 for (n = 0; n < 16; n++) {
1608                     int32_t sampledat;
1609
1610                     if (n & 1) {
1611                         sampledat = sign_extend(byte, 4);
1612                     } else {
1613                         byte = bytestream2_get_byteu(&gb);
1614                         sampledat = sign_extend(byte >> 4, 4);
1615                     }
1616
1617                     sampledat = ((prev1 * factor1 + prev2 * factor2) >> 11) +
1618                                 sampledat * scale;
1619                     *samples = av_clip_int16(sampledat);
1620                     prev2 = prev1;
1621                     prev1 = *samples++;
1622                 }
1623             }
1624
1625             c->status[channel].sample1 = prev1;
1626             c->status[channel].sample2 = prev2;
1627         }
1628         }
1629         bytestream2_seek(&gb, 0, SEEK_END);
1630         break;
1631     }
1632     case AV_CODEC_ID_ADPCM_THP:
1633     case AV_CODEC_ID_ADPCM_THP_LE:
1634     {
1635         int table[14][16];
1636         int ch;
1637
1638 #define THP_GET16(g) \
1639     sign_extend( \
1640         avctx->codec->id == AV_CODEC_ID_ADPCM_THP_LE ? \
1641         bytestream2_get_le16u(&(g)) : \
1642         bytestream2_get_be16u(&(g)), 16)
1643
1644         if (avctx->extradata) {
1645             GetByteContext tb;
1646             if (avctx->extradata_size < 32 * avctx->channels) {
1647                 av_log(avctx, AV_LOG_ERROR, "Missing coeff table\n");
1648                 return AVERROR_INVALIDDATA;
1649             }
1650
1651             bytestream2_init(&tb, avctx->extradata, avctx->extradata_size);
1652             for (i = 0; i < avctx->channels; i++)
1653                 for (n = 0; n < 16; n++)
1654                     table[i][n] = THP_GET16(tb);
1655         } else {
1656             for (i = 0; i < avctx->channels; i++)
1657                 for (n = 0; n < 16; n++)
1658                     table[i][n] = THP_GET16(gb);
1659
1660             if (!c->has_status) {
1661                 /* Initialize the previous sample.  */
1662                 for (i = 0; i < avctx->channels; i++) {
1663                     c->status[i].sample1 = THP_GET16(gb);
1664                     c->status[i].sample2 = THP_GET16(gb);
1665                 }
1666                 c->has_status = 1;
1667             } else {
1668                 bytestream2_skip(&gb, avctx->channels * 4);
1669             }
1670         }
1671
1672         for (ch = 0; ch < avctx->channels; ch++) {
1673             samples = samples_p[ch];
1674
1675             /* Read in every sample for this channel.  */
1676             for (i = 0; i < (nb_samples + 13) / 14; i++) {
1677                 int byte = bytestream2_get_byteu(&gb);
1678                 int index = (byte >> 4) & 7;
1679                 unsigned int exp = byte & 0x0F;
1680                 int factor1 = table[ch][index * 2];
1681                 int factor2 = table[ch][index * 2 + 1];
1682
1683                 /* Decode 14 samples.  */
1684                 for (n = 0; n < 14 && (i * 14 + n < nb_samples); n++) {
1685                     int32_t sampledat;
1686
1687                     if (n & 1) {
1688                         sampledat = sign_extend(byte, 4);
1689                     } else {
1690                         byte = bytestream2_get_byteu(&gb);
1691                         sampledat = sign_extend(byte >> 4, 4);
1692                     }
1693
1694                     sampledat = ((c->status[ch].sample1 * factor1
1695                                 + c->status[ch].sample2 * factor2) >> 11) + sampledat * (1 << exp);
1696                     *samples = av_clip_int16(sampledat);
1697                     c->status[ch].sample2 = c->status[ch].sample1;
1698                     c->status[ch].sample1 = *samples++;
1699                 }
1700             }
1701         }
1702         break;
1703     }
1704     case AV_CODEC_ID_ADPCM_DTK:
1705         for (channel = 0; channel < avctx->channels; channel++) {
1706             samples = samples_p[channel];
1707
1708             /* Read in every sample for this channel.  */
1709             for (i = 0; i < nb_samples / 28; i++) {
1710                 int byte, header;
1711                 if (channel)
1712                     bytestream2_skipu(&gb, 1);
1713                 header = bytestream2_get_byteu(&gb);
1714                 bytestream2_skipu(&gb, 3 - channel);
1715
1716                 /* Decode 28 samples.  */
1717                 for (n = 0; n < 28; n++) {
1718                     int32_t sampledat, prev;
1719
1720                     switch (header >> 4) {
1721                     case 1:
1722                         prev = (c->status[channel].sample1 * 0x3c);
1723                         break;
1724                     case 2:
1725                         prev = (c->status[channel].sample1 * 0x73) - (c->status[channel].sample2 * 0x34);
1726                         break;
1727                     case 3:
1728                         prev = (c->status[channel].sample1 * 0x62) - (c->status[channel].sample2 * 0x37);
1729                         break;
1730                     default:
1731                         prev = 0;
1732                     }
1733
1734                     prev = av_clip_intp2((prev + 0x20) >> 6, 21);
1735
1736                     byte = bytestream2_get_byteu(&gb);
1737                     if (!channel)
1738                         sampledat = sign_extend(byte, 4);
1739                     else
1740                         sampledat = sign_extend(byte >> 4, 4);
1741
1742                     sampledat = ((sampledat * (1 << 12)) >> (header & 0xf)) * (1 << 6) + prev;
1743                     *samples++ = av_clip_int16(sampledat >> 6);
1744                     c->status[channel].sample2 = c->status[channel].sample1;
1745                     c->status[channel].sample1 = sampledat;
1746                 }
1747             }
1748             if (!channel)
1749                 bytestream2_seek(&gb, 0, SEEK_SET);
1750         }
1751         break;
1752     case AV_CODEC_ID_ADPCM_PSX:
1753         for (channel = 0; channel < avctx->channels; channel++) {
1754             samples = samples_p[channel];
1755
1756             /* Read in every sample for this channel.  */
1757             for (i = 0; i < nb_samples / 28; i++) {
1758                 int filter, shift, flag, byte;
1759
1760                 filter = bytestream2_get_byteu(&gb);
1761                 shift  = filter & 0xf;
1762                 filter = filter >> 4;
1763                 if (filter >= FF_ARRAY_ELEMS(xa_adpcm_table))
1764                     return AVERROR_INVALIDDATA;
1765                 flag   = bytestream2_get_byteu(&gb);
1766
1767                 /* Decode 28 samples.  */
1768                 for (n = 0; n < 28; n++) {
1769                     int sample = 0, scale;
1770
1771                     if (flag < 0x07) {
1772                         if (n & 1) {
1773                             scale = sign_extend(byte >> 4, 4);
1774                         } else {
1775                             byte  = bytestream2_get_byteu(&gb);
1776                             scale = sign_extend(byte, 4);
1777                         }
1778
1779                         scale  = scale << 12;
1780                         sample = (int)((scale >> shift) + (c->status[channel].sample1 * xa_adpcm_table[filter][0] + c->status[channel].sample2 * xa_adpcm_table[filter][1]) / 64);
1781                     }
1782                     *samples++ = av_clip_int16(sample);
1783                     c->status[channel].sample2 = c->status[channel].sample1;
1784                     c->status[channel].sample1 = sample;
1785                 }
1786             }
1787         }
1788         break;
1789     case AV_CODEC_ID_ADPCM_ARGO:
1790         /*
1791          * The format of each block:
1792          *   uint8_t left_control;
1793          *   uint4_t left_samples[nb_samples];
1794          *   ---- and if stereo ----
1795          *   uint8_t right_control;
1796          *   uint4_t right_samples[nb_samples];
1797          *
1798          * Format of the control byte:
1799          * MSB [SSSSDRRR] LSB
1800          *   S = (Shift Amount - 2)
1801          *   D = Decoder flag.
1802          *   R = Reserved
1803          *
1804          * Each block relies on the previous two samples of each channel.
1805          * They should be 0 initially.
1806          */
1807         for (channel = 0; channel < avctx->channels; channel++) {
1808             int control, shift, sample, nibble;
1809
1810             samples = samples_p[channel];
1811             cs = c->status + channel;
1812
1813             /* Get the control byte and decode the samples, 2 at a time. */
1814             control = bytestream2_get_byteu(&gb);
1815             shift = (control >> 4) + 2;
1816
1817             for (n = 0; n < nb_samples / 2; n++) {
1818                 sample = bytestream2_get_byteu(&gb);
1819
1820                 nibble = sign_extend(sample >> 4, 4);
1821                 if (control & 0x04)
1822                     *samples = adpcm_argo_expand_nibble(nibble, shift, cs->sample1, cs->sample2);
1823                 else
1824                     *samples = adpcm_argo_expand_nibble(nibble, shift, cs->sample1, cs->sample1);
1825
1826                 cs->sample2 = cs->sample1;
1827                 cs->sample1 = *samples++;
1828
1829                 nibble = sign_extend(sample >> 0, 4);
1830                 if (control & 0x04)
1831                     *samples = adpcm_argo_expand_nibble(nibble, shift, cs->sample1, cs->sample2);
1832                 else
1833                     *samples = adpcm_argo_expand_nibble(nibble, shift, cs->sample1, cs->sample1);
1834
1835                 cs->sample2 = cs->sample1;
1836                 cs->sample1 = *samples++;
1837             }
1838         }
1839         break;
1840     default:
1841         av_assert0(0); // unsupported codec_id should not happen
1842     }
1843
1844     if (avpkt->size && bytestream2_tell(&gb) == 0) {
1845         av_log(avctx, AV_LOG_ERROR, "Nothing consumed\n");
1846         return AVERROR_INVALIDDATA;
1847     }
1848
1849     *got_frame_ptr = 1;
1850
1851     if (avpkt->size < bytestream2_tell(&gb)) {
1852         av_log(avctx, AV_LOG_ERROR, "Overread of %d < %d\n", avpkt->size, bytestream2_tell(&gb));
1853         return avpkt->size;
1854     }
1855
1856     return bytestream2_tell(&gb);
1857 }
1858
1859 static void adpcm_flush(AVCodecContext *avctx)
1860 {
1861     ADPCMDecodeContext *c = avctx->priv_data;
1862     c->has_status = 0;
1863 }
1864
1865
1866 static const enum AVSampleFormat sample_fmts_s16[]  = { AV_SAMPLE_FMT_S16,
1867                                                         AV_SAMPLE_FMT_NONE };
1868 static const enum AVSampleFormat sample_fmts_s16p[] = { AV_SAMPLE_FMT_S16P,
1869                                                         AV_SAMPLE_FMT_NONE };
1870 static const enum AVSampleFormat sample_fmts_both[] = { AV_SAMPLE_FMT_S16,
1871                                                         AV_SAMPLE_FMT_S16P,
1872                                                         AV_SAMPLE_FMT_NONE };
1873
1874 #define ADPCM_DECODER(id_, sample_fmts_, name_, long_name_) \
1875 AVCodec ff_ ## name_ ## _decoder = {                        \
1876     .name           = #name_,                               \
1877     .long_name      = NULL_IF_CONFIG_SMALL(long_name_),     \
1878     .type           = AVMEDIA_TYPE_AUDIO,                   \
1879     .id             = id_,                                  \
1880     .priv_data_size = sizeof(ADPCMDecodeContext),           \
1881     .init           = adpcm_decode_init,                    \
1882     .decode         = adpcm_decode_frame,                   \
1883     .flush          = adpcm_flush,                          \
1884     .capabilities   = AV_CODEC_CAP_DR1,                     \
1885     .sample_fmts    = sample_fmts_,                         \
1886 }
1887
1888 /* Note: Do not forget to add new entries to the Makefile as well. */
1889 ADPCM_DECODER(AV_CODEC_ID_ADPCM_4XM,         sample_fmts_s16p, adpcm_4xm,         "ADPCM 4X Movie");
1890 ADPCM_DECODER(AV_CODEC_ID_ADPCM_AFC,         sample_fmts_s16p, adpcm_afc,         "ADPCM Nintendo Gamecube AFC");
1891 ADPCM_DECODER(AV_CODEC_ID_ADPCM_AGM,         sample_fmts_s16,  adpcm_agm,         "ADPCM AmuseGraphics Movie");
1892 ADPCM_DECODER(AV_CODEC_ID_ADPCM_AICA,        sample_fmts_s16p, adpcm_aica,        "ADPCM Yamaha AICA");
1893 ADPCM_DECODER(AV_CODEC_ID_ADPCM_ARGO,        sample_fmts_s16p, adpcm_argo,        "ADPCM Argonaut Games");
1894 ADPCM_DECODER(AV_CODEC_ID_ADPCM_CT,          sample_fmts_s16,  adpcm_ct,          "ADPCM Creative Technology");
1895 ADPCM_DECODER(AV_CODEC_ID_ADPCM_DTK,         sample_fmts_s16p, adpcm_dtk,         "ADPCM Nintendo Gamecube DTK");
1896 ADPCM_DECODER(AV_CODEC_ID_ADPCM_EA,          sample_fmts_s16,  adpcm_ea,          "ADPCM Electronic Arts");
1897 ADPCM_DECODER(AV_CODEC_ID_ADPCM_EA_MAXIS_XA, sample_fmts_s16,  adpcm_ea_maxis_xa, "ADPCM Electronic Arts Maxis CDROM XA");
1898 ADPCM_DECODER(AV_CODEC_ID_ADPCM_EA_R1,       sample_fmts_s16p, adpcm_ea_r1,       "ADPCM Electronic Arts R1");
1899 ADPCM_DECODER(AV_CODEC_ID_ADPCM_EA_R2,       sample_fmts_s16p, adpcm_ea_r2,       "ADPCM Electronic Arts R2");
1900 ADPCM_DECODER(AV_CODEC_ID_ADPCM_EA_R3,       sample_fmts_s16p, adpcm_ea_r3,       "ADPCM Electronic Arts R3");
1901 ADPCM_DECODER(AV_CODEC_ID_ADPCM_EA_XAS,      sample_fmts_s16p, adpcm_ea_xas,      "ADPCM Electronic Arts XAS");
1902 ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_AMV,     sample_fmts_s16,  adpcm_ima_amv,     "ADPCM IMA AMV");
1903 ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_APC,     sample_fmts_s16,  adpcm_ima_apc,     "ADPCM IMA CRYO APC");
1904 ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_DAT4,    sample_fmts_s16,  adpcm_ima_dat4,    "ADPCM IMA Eurocom DAT4");
1905 ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_DK3,     sample_fmts_s16,  adpcm_ima_dk3,     "ADPCM IMA Duck DK3");
1906 ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_DK4,     sample_fmts_s16,  adpcm_ima_dk4,     "ADPCM IMA Duck DK4");
1907 ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_EA_EACS, sample_fmts_s16,  adpcm_ima_ea_eacs, "ADPCM IMA Electronic Arts EACS");
1908 ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_EA_SEAD, sample_fmts_s16,  adpcm_ima_ea_sead, "ADPCM IMA Electronic Arts SEAD");
1909 ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_ISS,     sample_fmts_s16,  adpcm_ima_iss,     "ADPCM IMA Funcom ISS");
1910 ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_OKI,     sample_fmts_s16,  adpcm_ima_oki,     "ADPCM IMA Dialogic OKI");
1911 ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_QT,      sample_fmts_s16p, adpcm_ima_qt,      "ADPCM IMA QuickTime");
1912 ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_RAD,     sample_fmts_s16,  adpcm_ima_rad,     "ADPCM IMA Radical");
1913 ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_SMJPEG,  sample_fmts_s16,  adpcm_ima_smjpeg,  "ADPCM IMA Loki SDL MJPEG");
1914 ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_WAV,     sample_fmts_s16p, adpcm_ima_wav,     "ADPCM IMA WAV");
1915 ADPCM_DECODER(AV_CODEC_ID_ADPCM_IMA_WS,      sample_fmts_both, adpcm_ima_ws,      "ADPCM IMA Westwood");
1916 ADPCM_DECODER(AV_CODEC_ID_ADPCM_MS,          sample_fmts_both, adpcm_ms,          "ADPCM Microsoft");
1917 ADPCM_DECODER(AV_CODEC_ID_ADPCM_MTAF,        sample_fmts_s16p, adpcm_mtaf,        "ADPCM MTAF");
1918 ADPCM_DECODER(AV_CODEC_ID_ADPCM_PSX,         sample_fmts_s16p, adpcm_psx,         "ADPCM Playstation");
1919 ADPCM_DECODER(AV_CODEC_ID_ADPCM_SBPRO_2,     sample_fmts_s16,  adpcm_sbpro_2,     "ADPCM Sound Blaster Pro 2-bit");
1920 ADPCM_DECODER(AV_CODEC_ID_ADPCM_SBPRO_3,     sample_fmts_s16,  adpcm_sbpro_3,     "ADPCM Sound Blaster Pro 2.6-bit");
1921 ADPCM_DECODER(AV_CODEC_ID_ADPCM_SBPRO_4,     sample_fmts_s16,  adpcm_sbpro_4,     "ADPCM Sound Blaster Pro 4-bit");
1922 ADPCM_DECODER(AV_CODEC_ID_ADPCM_SWF,         sample_fmts_s16,  adpcm_swf,         "ADPCM Shockwave Flash");
1923 ADPCM_DECODER(AV_CODEC_ID_ADPCM_THP_LE,      sample_fmts_s16p, adpcm_thp_le,      "ADPCM Nintendo THP (little-endian)");
1924 ADPCM_DECODER(AV_CODEC_ID_ADPCM_THP,         sample_fmts_s16p, adpcm_thp,         "ADPCM Nintendo THP");
1925 ADPCM_DECODER(AV_CODEC_ID_ADPCM_XA,          sample_fmts_s16p, adpcm_xa,          "ADPCM CDROM XA");
1926 ADPCM_DECODER(AV_CODEC_ID_ADPCM_YAMAHA,      sample_fmts_s16,  adpcm_yamaha,      "ADPCM Yamaha");