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