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