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