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