]> rtime.felk.cvut.cz Git - frescor/ffmpeg.git/blob - libavcodec/adpcm.c
EA IMA SEAD decoder
[frescor/ffmpeg.git] / libavcodec / adpcm.c
1 /*
2  * ADPCM codecs
3  * Copyright (c) 2001-2003 The ffmpeg Project
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 #include "avcodec.h"
22 #include "bitstream.h"
23 #include "bytestream.h"
24
25 /**
26  * @file adpcm.c
27  * ADPCM codecs.
28  * First version by Francois Revol (revol@free.fr)
29  * Fringe ADPCM codecs (e.g., DK3, DK4, Westwood)
30  *   by Mike Melanson (melanson@pcisys.net)
31  * CD-ROM XA ADPCM codec by BERO
32  * EA ADPCM decoder by Robin Kay (komadori@myrealbox.com)
33  * EA ADPCM R1/R2/R3 decoder by Peter Ross (pross@xvid.org)
34  * EA IMA SEAD decoder by Peter Ross (pross@xvid.org)
35  * THP ADPCM decoder by Marco Gerards (mgerards@xs4all.nl)
36  *
37  * Features and limitations:
38  *
39  * Reference documents:
40  * http://www.pcisys.net/~melanson/codecs/simpleaudio.html
41  * http://www.geocities.com/SiliconValley/8682/aud3.txt
42  * http://openquicktime.sourceforge.net/plugins.htm
43  * XAnim sources (xa_codec.c) http://www.rasnaimaging.com/people/lapus/download.html
44  * http://www.cs.ucla.edu/~leec/mediabench/applications.html
45  * SoX source code http://home.sprynet.com/~cbagwell/sox.html
46  *
47  * CD-ROM XA:
48  * http://ku-www.ss.titech.ac.jp/~yatsushi/xaadpcm.html
49  * vagpack & depack http://homepages.compuserve.de/bITmASTER32/psx-index.html
50  * readstr http://www.geocities.co.jp/Playtown/2004/
51  */
52
53 #define BLKSIZE 1024
54
55 /* step_table[] and index_table[] are from the ADPCM reference source */
56 /* This is the index table: */
57 static const int index_table[16] = {
58     -1, -1, -1, -1, 2, 4, 6, 8,
59     -1, -1, -1, -1, 2, 4, 6, 8,
60 };
61
62 /**
63  * This is the step table. Note that many programs use slight deviations from
64  * this table, but such deviations are negligible:
65  */
66 static const int step_table[89] = {
67     7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
68     19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
69     50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
70     130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
71     337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
72     876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
73     2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
74     5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
75     15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
76 };
77
78 /* These are for MS-ADPCM */
79 /* AdaptationTable[], AdaptCoeff1[], and AdaptCoeff2[] are from libsndfile */
80 static const int AdaptationTable[] = {
81         230, 230, 230, 230, 307, 409, 512, 614,
82         768, 614, 512, 409, 307, 230, 230, 230
83 };
84
85 static const int AdaptCoeff1[] = {
86         256, 512, 0, 192, 240, 460, 392
87 };
88
89 static const int AdaptCoeff2[] = {
90         0, -256, 0, 64, 0, -208, -232
91 };
92
93 /* These are for CD-ROM XA ADPCM */
94 static const int xa_adpcm_table[5][2] = {
95    {   0,   0 },
96    {  60,   0 },
97    { 115, -52 },
98    {  98, -55 },
99    { 122, -60 }
100 };
101
102 static const int ea_adpcm_table[] = {
103     0, 240, 460, 392, 0, 0, -208, -220, 0, 1,
104     3, 4, 7, 8, 10, 11, 0, -1, -3, -4
105 };
106
107 static const int ct_adpcm_table[8] = {
108     0x00E6, 0x00E6, 0x00E6, 0x00E6,
109     0x0133, 0x0199, 0x0200, 0x0266
110 };
111
112 // padded to zero where table size is less then 16
113 static const int swf_index_tables[4][16] = {
114     /*2*/ { -1, 2 },
115     /*3*/ { -1, -1, 2, 4 },
116     /*4*/ { -1, -1, -1, -1, 2, 4, 6, 8 },
117     /*5*/ { -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 4, 6, 8, 10, 13, 16 }
118 };
119
120 static const int yamaha_indexscale[] = {
121     230, 230, 230, 230, 307, 409, 512, 614,
122     230, 230, 230, 230, 307, 409, 512, 614
123 };
124
125 static const int yamaha_difflookup[] = {
126     1, 3, 5, 7, 9, 11, 13, 15,
127     -1, -3, -5, -7, -9, -11, -13, -15
128 };
129
130 /* end of tables */
131
132 typedef struct ADPCMChannelStatus {
133     int predictor;
134     short int step_index;
135     int step;
136     /* for encoding */
137     int prev_sample;
138
139     /* MS version */
140     short sample1;
141     short sample2;
142     int coeff1;
143     int coeff2;
144     int idelta;
145 } ADPCMChannelStatus;
146
147 typedef struct ADPCMContext {
148     int channel; /* for stereo MOVs, decode left, then decode right, then tell it's decoded */
149     ADPCMChannelStatus status[6];
150 } ADPCMContext;
151
152 /* XXX: implement encoding */
153
154 #ifdef CONFIG_ENCODERS
155 static int adpcm_encode_init(AVCodecContext *avctx)
156 {
157     if (avctx->channels > 2)
158         return -1; /* only stereo or mono =) */
159     switch(avctx->codec->id) {
160     case CODEC_ID_ADPCM_IMA_QT:
161         av_log(avctx, AV_LOG_ERROR, "ADPCM: codec adpcm_ima_qt unsupported for encoding !\n");
162         avctx->frame_size = 64; /* XXX: can multiple of avctx->channels * 64 (left and right blocks are interleaved) */
163         return -1;
164         break;
165     case CODEC_ID_ADPCM_IMA_WAV:
166         avctx->frame_size = (BLKSIZE - 4 * avctx->channels) * 8 / (4 * avctx->channels) + 1; /* each 16 bits sample gives one nibble */
167                                                              /* and we have 4 bytes per channel overhead */
168         avctx->block_align = BLKSIZE;
169         /* seems frame_size isn't taken into account... have to buffer the samples :-( */
170         break;
171     case CODEC_ID_ADPCM_MS:
172         avctx->frame_size = (BLKSIZE - 7 * avctx->channels) * 2 / avctx->channels + 2; /* each 16 bits sample gives one nibble */
173                                                              /* and we have 7 bytes per channel overhead */
174         avctx->block_align = BLKSIZE;
175         break;
176     case CODEC_ID_ADPCM_YAMAHA:
177         avctx->frame_size = BLKSIZE * avctx->channels;
178         avctx->block_align = BLKSIZE;
179         break;
180     case CODEC_ID_ADPCM_SWF:
181         if (avctx->sample_rate != 11025 &&
182             avctx->sample_rate != 22050 &&
183             avctx->sample_rate != 44100) {
184             av_log(avctx, AV_LOG_ERROR, "Sample rate must be 11025, 22050 or 44100\n");
185             return -1;
186         }
187         avctx->frame_size = 512 * (avctx->sample_rate / 11025);
188         break;
189     default:
190         return -1;
191         break;
192     }
193
194     avctx->coded_frame= avcodec_alloc_frame();
195     avctx->coded_frame->key_frame= 1;
196
197     return 0;
198 }
199
200 static int adpcm_encode_close(AVCodecContext *avctx)
201 {
202     av_freep(&avctx->coded_frame);
203
204     return 0;
205 }
206
207
208 static inline unsigned char adpcm_ima_compress_sample(ADPCMChannelStatus *c, short sample)
209 {
210     int delta = sample - c->prev_sample;
211     int nibble = FFMIN(7, abs(delta)*4/step_table[c->step_index]) + (delta<0)*8;
212     c->prev_sample += ((step_table[c->step_index] * yamaha_difflookup[nibble]) / 8);
213     c->prev_sample = av_clip_int16(c->prev_sample);
214     c->step_index = av_clip(c->step_index + index_table[nibble], 0, 88);
215     return nibble;
216 }
217
218 static inline unsigned char adpcm_ms_compress_sample(ADPCMChannelStatus *c, short sample)
219 {
220     int predictor, nibble, bias;
221
222     predictor = (((c->sample1) * (c->coeff1)) + ((c->sample2) * (c->coeff2))) / 256;
223
224     nibble= sample - predictor;
225     if(nibble>=0) bias= c->idelta/2;
226     else          bias=-c->idelta/2;
227
228     nibble= (nibble + bias) / c->idelta;
229     nibble= av_clip(nibble, -8, 7)&0x0F;
230
231     predictor += (signed)((nibble & 0x08)?(nibble - 0x10):(nibble)) * c->idelta;
232
233     c->sample2 = c->sample1;
234     c->sample1 = av_clip_int16(predictor);
235
236     c->idelta = (AdaptationTable[(int)nibble] * c->idelta) >> 8;
237     if (c->idelta < 16) c->idelta = 16;
238
239     return nibble;
240 }
241
242 static inline unsigned char adpcm_yamaha_compress_sample(ADPCMChannelStatus *c, short sample)
243 {
244     int nibble, delta;
245
246     if(!c->step) {
247         c->predictor = 0;
248         c->step = 127;
249     }
250
251     delta = sample - c->predictor;
252
253     nibble = FFMIN(7, abs(delta)*4/c->step) + (delta<0)*8;
254
255     c->predictor += ((c->step * yamaha_difflookup[nibble]) / 8);
256     c->predictor = av_clip_int16(c->predictor);
257     c->step = (c->step * yamaha_indexscale[nibble]) >> 8;
258     c->step = av_clip(c->step, 127, 24567);
259
260     return nibble;
261 }
262
263 typedef struct TrellisPath {
264     int nibble;
265     int prev;
266 } TrellisPath;
267
268 typedef struct TrellisNode {
269     uint32_t ssd;
270     int path;
271     int sample1;
272     int sample2;
273     int step;
274 } TrellisNode;
275
276 static void adpcm_compress_trellis(AVCodecContext *avctx, const short *samples,
277                                    uint8_t *dst, ADPCMChannelStatus *c, int n)
278 {
279 #define FREEZE_INTERVAL 128
280     //FIXME 6% faster if frontier is a compile-time constant
281     const int frontier = 1 << avctx->trellis;
282     const int stride = avctx->channels;
283     const int version = avctx->codec->id;
284     const int max_paths = frontier*FREEZE_INTERVAL;
285     TrellisPath paths[max_paths], *p;
286     TrellisNode node_buf[2][frontier];
287     TrellisNode *nodep_buf[2][frontier];
288     TrellisNode **nodes = nodep_buf[0]; // nodes[] is always sorted by .ssd
289     TrellisNode **nodes_next = nodep_buf[1];
290     int pathn = 0, froze = -1, i, j, k;
291
292     assert(!(max_paths&(max_paths-1)));
293
294     memset(nodep_buf, 0, sizeof(nodep_buf));
295     nodes[0] = &node_buf[1][0];
296     nodes[0]->ssd = 0;
297     nodes[0]->path = 0;
298     nodes[0]->step = c->step_index;
299     nodes[0]->sample1 = c->sample1;
300     nodes[0]->sample2 = c->sample2;
301     if((version == CODEC_ID_ADPCM_IMA_WAV) || (version == CODEC_ID_ADPCM_SWF))
302         nodes[0]->sample1 = c->prev_sample;
303     if(version == CODEC_ID_ADPCM_MS)
304         nodes[0]->step = c->idelta;
305     if(version == CODEC_ID_ADPCM_YAMAHA) {
306         if(c->step == 0) {
307             nodes[0]->step = 127;
308             nodes[0]->sample1 = 0;
309         } else {
310             nodes[0]->step = c->step;
311             nodes[0]->sample1 = c->predictor;
312         }
313     }
314
315     for(i=0; i<n; i++) {
316         TrellisNode *t = node_buf[i&1];
317         TrellisNode **u;
318         int sample = samples[i*stride];
319         memset(nodes_next, 0, frontier*sizeof(TrellisNode*));
320         for(j=0; j<frontier && nodes[j]; j++) {
321             // higher j have higher ssd already, so they're unlikely to use a suboptimal next sample too
322             const int range = (j < frontier/2) ? 1 : 0;
323             const int step = nodes[j]->step;
324             int nidx;
325             if(version == CODEC_ID_ADPCM_MS) {
326                 const int predictor = ((nodes[j]->sample1 * c->coeff1) + (nodes[j]->sample2 * c->coeff2)) / 256;
327                 const int div = (sample - predictor) / step;
328                 const int nmin = av_clip(div-range, -8, 6);
329                 const int nmax = av_clip(div+range, -7, 7);
330                 for(nidx=nmin; nidx<=nmax; nidx++) {
331                     const int nibble = nidx & 0xf;
332                     int dec_sample = predictor + nidx * step;
333 #define STORE_NODE(NAME, STEP_INDEX)\
334                     int d;\
335                     uint32_t ssd;\
336                     dec_sample = av_clip_int16(dec_sample);\
337                     d = sample - dec_sample;\
338                     ssd = nodes[j]->ssd + d*d;\
339                     if(nodes_next[frontier-1] && ssd >= nodes_next[frontier-1]->ssd)\
340                         continue;\
341                     /* Collapse any two states with the same previous sample value. \
342                      * One could also distinguish states by step and by 2nd to last
343                      * sample, but the effects of that are negligible. */\
344                     for(k=0; k<frontier && nodes_next[k]; k++) {\
345                         if(dec_sample == nodes_next[k]->sample1) {\
346                             assert(ssd >= nodes_next[k]->ssd);\
347                             goto next_##NAME;\
348                         }\
349                     }\
350                     for(k=0; k<frontier; k++) {\
351                         if(!nodes_next[k] || ssd < nodes_next[k]->ssd) {\
352                             TrellisNode *u = nodes_next[frontier-1];\
353                             if(!u) {\
354                                 assert(pathn < max_paths);\
355                                 u = t++;\
356                                 u->path = pathn++;\
357                             }\
358                             u->ssd = ssd;\
359                             u->step = STEP_INDEX;\
360                             u->sample2 = nodes[j]->sample1;\
361                             u->sample1 = dec_sample;\
362                             paths[u->path].nibble = nibble;\
363                             paths[u->path].prev = nodes[j]->path;\
364                             memmove(&nodes_next[k+1], &nodes_next[k], (frontier-k-1)*sizeof(TrellisNode*));\
365                             nodes_next[k] = u;\
366                             break;\
367                         }\
368                     }\
369                     next_##NAME:;
370                     STORE_NODE(ms, FFMAX(16, (AdaptationTable[nibble] * step) >> 8));
371                 }
372             } else if((version == CODEC_ID_ADPCM_IMA_WAV)|| (version == CODEC_ID_ADPCM_SWF)) {
373 #define LOOP_NODES(NAME, STEP_TABLE, STEP_INDEX)\
374                 const int predictor = nodes[j]->sample1;\
375                 const int div = (sample - predictor) * 4 / STEP_TABLE;\
376                 int nmin = av_clip(div-range, -7, 6);\
377                 int nmax = av_clip(div+range, -6, 7);\
378                 if(nmin<=0) nmin--; /* distinguish -0 from +0 */\
379                 if(nmax<0) nmax--;\
380                 for(nidx=nmin; nidx<=nmax; nidx++) {\
381                     const int nibble = nidx<0 ? 7-nidx : nidx;\
382                     int dec_sample = predictor + (STEP_TABLE * yamaha_difflookup[nibble]) / 8;\
383                     STORE_NODE(NAME, STEP_INDEX);\
384                 }
385                 LOOP_NODES(ima, step_table[step], av_clip(step + index_table[nibble], 0, 88));
386             } else { //CODEC_ID_ADPCM_YAMAHA
387                 LOOP_NODES(yamaha, step, av_clip((step * yamaha_indexscale[nibble]) >> 8, 127, 24567));
388 #undef LOOP_NODES
389 #undef STORE_NODE
390             }
391         }
392
393         u = nodes;
394         nodes = nodes_next;
395         nodes_next = u;
396
397         // prevent overflow
398         if(nodes[0]->ssd > (1<<28)) {
399             for(j=1; j<frontier && nodes[j]; j++)
400                 nodes[j]->ssd -= nodes[0]->ssd;
401             nodes[0]->ssd = 0;
402         }
403
404         // merge old paths to save memory
405         if(i == froze + FREEZE_INTERVAL) {
406             p = &paths[nodes[0]->path];
407             for(k=i; k>froze; k--) {
408                 dst[k] = p->nibble;
409                 p = &paths[p->prev];
410             }
411             froze = i;
412             pathn = 0;
413             // other nodes might use paths that don't coincide with the frozen one.
414             // checking which nodes do so is too slow, so just kill them all.
415             // this also slightly improves quality, but I don't know why.
416             memset(nodes+1, 0, (frontier-1)*sizeof(TrellisNode*));
417         }
418     }
419
420     p = &paths[nodes[0]->path];
421     for(i=n-1; i>froze; i--) {
422         dst[i] = p->nibble;
423         p = &paths[p->prev];
424     }
425
426     c->predictor = nodes[0]->sample1;
427     c->sample1 = nodes[0]->sample1;
428     c->sample2 = nodes[0]->sample2;
429     c->step_index = nodes[0]->step;
430     c->step = nodes[0]->step;
431     c->idelta = nodes[0]->step;
432 }
433
434 static int adpcm_encode_frame(AVCodecContext *avctx,
435                             unsigned char *frame, int buf_size, void *data)
436 {
437     int n, i, st;
438     short *samples;
439     unsigned char *dst;
440     ADPCMContext *c = avctx->priv_data;
441
442     dst = frame;
443     samples = (short *)data;
444     st= avctx->channels == 2;
445 /*    n = (BLKSIZE - 4 * avctx->channels) / (2 * 8 * avctx->channels); */
446
447     switch(avctx->codec->id) {
448     case CODEC_ID_ADPCM_IMA_QT: /* XXX: can't test until we get .mov writer */
449         break;
450     case CODEC_ID_ADPCM_IMA_WAV:
451         n = avctx->frame_size / 8;
452             c->status[0].prev_sample = (signed short)samples[0]; /* XXX */
453 /*            c->status[0].step_index = 0; *//* XXX: not sure how to init the state machine */
454             bytestream_put_le16(&dst, c->status[0].prev_sample);
455             *dst++ = (unsigned char)c->status[0].step_index;
456             *dst++ = 0; /* unknown */
457             samples++;
458             if (avctx->channels == 2) {
459                 c->status[1].prev_sample = (signed short)samples[1];
460 /*                c->status[1].step_index = 0; */
461                 bytestream_put_le16(&dst, c->status[1].prev_sample);
462                 *dst++ = (unsigned char)c->status[1].step_index;
463                 *dst++ = 0;
464                 samples++;
465             }
466
467             /* stereo: 4 bytes (8 samples) for left, 4 bytes for right, 4 bytes left, ... */
468             if(avctx->trellis > 0) {
469                 uint8_t buf[2][n*8];
470                 adpcm_compress_trellis(avctx, samples, buf[0], &c->status[0], n*8);
471                 if(avctx->channels == 2)
472                     adpcm_compress_trellis(avctx, samples+1, buf[1], &c->status[1], n*8);
473                 for(i=0; i<n; i++) {
474                     *dst++ = buf[0][8*i+0] | (buf[0][8*i+1] << 4);
475                     *dst++ = buf[0][8*i+2] | (buf[0][8*i+3] << 4);
476                     *dst++ = buf[0][8*i+4] | (buf[0][8*i+5] << 4);
477                     *dst++ = buf[0][8*i+6] | (buf[0][8*i+7] << 4);
478                     if (avctx->channels == 2) {
479                         *dst++ = buf[1][8*i+0] | (buf[1][8*i+1] << 4);
480                         *dst++ = buf[1][8*i+2] | (buf[1][8*i+3] << 4);
481                         *dst++ = buf[1][8*i+4] | (buf[1][8*i+5] << 4);
482                         *dst++ = buf[1][8*i+6] | (buf[1][8*i+7] << 4);
483                     }
484                 }
485             } else
486             for (; n>0; n--) {
487                 *dst = adpcm_ima_compress_sample(&c->status[0], samples[0]);
488                 *dst |= adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels]) << 4;
489                 dst++;
490                 *dst = adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 2]);
491                 *dst |= adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 3]) << 4;
492                 dst++;
493                 *dst = adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 4]);
494                 *dst |= adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 5]) << 4;
495                 dst++;
496                 *dst = adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 6]);
497                 *dst |= adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 7]) << 4;
498                 dst++;
499                 /* right channel */
500                 if (avctx->channels == 2) {
501                     *dst = adpcm_ima_compress_sample(&c->status[1], samples[1]);
502                     *dst |= adpcm_ima_compress_sample(&c->status[1], samples[3]) << 4;
503                     dst++;
504                     *dst = adpcm_ima_compress_sample(&c->status[1], samples[5]);
505                     *dst |= adpcm_ima_compress_sample(&c->status[1], samples[7]) << 4;
506                     dst++;
507                     *dst = adpcm_ima_compress_sample(&c->status[1], samples[9]);
508                     *dst |= adpcm_ima_compress_sample(&c->status[1], samples[11]) << 4;
509                     dst++;
510                     *dst = adpcm_ima_compress_sample(&c->status[1], samples[13]);
511                     *dst |= adpcm_ima_compress_sample(&c->status[1], samples[15]) << 4;
512                     dst++;
513                 }
514                 samples += 8 * avctx->channels;
515             }
516         break;
517     case CODEC_ID_ADPCM_SWF:
518     {
519         int i;
520         PutBitContext pb;
521         init_put_bits(&pb, dst, buf_size*8);
522
523         n = avctx->frame_size-1;
524
525         //Store AdpcmCodeSize
526         put_bits(&pb, 2, 2);                //Set 4bits flash adpcm format
527
528         //Init the encoder state
529         for(i=0; i<avctx->channels; i++){
530             c->status[i].step_index = av_clip(c->status[i].step_index, 0, 63); // clip step so it fits 6 bits
531             put_bits(&pb, 16, samples[i] & 0xFFFF);
532             put_bits(&pb, 6, c->status[i].step_index);
533             c->status[i].prev_sample = (signed short)samples[i];
534         }
535
536         if(avctx->trellis > 0) {
537             uint8_t buf[2][n];
538             adpcm_compress_trellis(avctx, samples+2, buf[0], &c->status[0], n);
539             if (avctx->channels == 2)
540                 adpcm_compress_trellis(avctx, samples+3, buf[1], &c->status[1], n);
541             for(i=0; i<n; i++) {
542                 put_bits(&pb, 4, buf[0][i]);
543                 if (avctx->channels == 2)
544                     put_bits(&pb, 4, buf[1][i]);
545             }
546         } else {
547             for (i=1; i<avctx->frame_size; i++) {
548                 put_bits(&pb, 4, adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels*i]));
549                 if (avctx->channels == 2)
550                     put_bits(&pb, 4, adpcm_ima_compress_sample(&c->status[1], samples[2*i+1]));
551             }
552         }
553         flush_put_bits(&pb);
554         dst += put_bits_count(&pb)>>3;
555         break;
556     }
557     case CODEC_ID_ADPCM_MS:
558         for(i=0; i<avctx->channels; i++){
559             int predictor=0;
560
561             *dst++ = predictor;
562             c->status[i].coeff1 = AdaptCoeff1[predictor];
563             c->status[i].coeff2 = AdaptCoeff2[predictor];
564         }
565         for(i=0; i<avctx->channels; i++){
566             if (c->status[i].idelta < 16)
567                 c->status[i].idelta = 16;
568
569             bytestream_put_le16(&dst, c->status[i].idelta);
570         }
571         for(i=0; i<avctx->channels; i++){
572             c->status[i].sample1= *samples++;
573
574             bytestream_put_le16(&dst, c->status[i].sample1);
575         }
576         for(i=0; i<avctx->channels; i++){
577             c->status[i].sample2= *samples++;
578
579             bytestream_put_le16(&dst, c->status[i].sample2);
580         }
581
582         if(avctx->trellis > 0) {
583             int n = avctx->block_align - 7*avctx->channels;
584             uint8_t buf[2][n];
585             if(avctx->channels == 1) {
586                 n *= 2;
587                 adpcm_compress_trellis(avctx, samples, buf[0], &c->status[0], n);
588                 for(i=0; i<n; i+=2)
589                     *dst++ = (buf[0][i] << 4) | buf[0][i+1];
590             } else {
591                 adpcm_compress_trellis(avctx, samples, buf[0], &c->status[0], n);
592                 adpcm_compress_trellis(avctx, samples+1, buf[1], &c->status[1], n);
593                 for(i=0; i<n; i++)
594                     *dst++ = (buf[0][i] << 4) | buf[1][i];
595             }
596         } else
597         for(i=7*avctx->channels; i<avctx->block_align; i++) {
598             int nibble;
599             nibble = adpcm_ms_compress_sample(&c->status[ 0], *samples++)<<4;
600             nibble|= adpcm_ms_compress_sample(&c->status[st], *samples++);
601             *dst++ = nibble;
602         }
603         break;
604     case CODEC_ID_ADPCM_YAMAHA:
605         n = avctx->frame_size / 2;
606         if(avctx->trellis > 0) {
607             uint8_t buf[2][n*2];
608             n *= 2;
609             if(avctx->channels == 1) {
610                 adpcm_compress_trellis(avctx, samples, buf[0], &c->status[0], n);
611                 for(i=0; i<n; i+=2)
612                     *dst++ = buf[0][i] | (buf[0][i+1] << 4);
613             } else {
614                 adpcm_compress_trellis(avctx, samples, buf[0], &c->status[0], n);
615                 adpcm_compress_trellis(avctx, samples+1, buf[1], &c->status[1], n);
616                 for(i=0; i<n; i++)
617                     *dst++ = buf[0][i] | (buf[1][i] << 4);
618             }
619         } else
620         for (; n>0; n--) {
621             for(i = 0; i < avctx->channels; i++) {
622                 int nibble;
623                 nibble  = adpcm_yamaha_compress_sample(&c->status[i], samples[i]);
624                 nibble |= adpcm_yamaha_compress_sample(&c->status[i], samples[i+avctx->channels]) << 4;
625                 *dst++ = nibble;
626             }
627             samples += 2 * avctx->channels;
628         }
629         break;
630     default:
631         return -1;
632     }
633     return dst - frame;
634 }
635 #endif //CONFIG_ENCODERS
636
637 static int adpcm_decode_init(AVCodecContext * avctx)
638 {
639     ADPCMContext *c = avctx->priv_data;
640     unsigned int max_channels = 2;
641
642     switch(avctx->codec->id) {
643     case CODEC_ID_ADPCM_EA_R1:
644     case CODEC_ID_ADPCM_EA_R2:
645     case CODEC_ID_ADPCM_EA_R3:
646         max_channels = 6;
647         break;
648     }
649     if(avctx->channels > max_channels){
650         return -1;
651     }
652
653     switch(avctx->codec->id) {
654     case CODEC_ID_ADPCM_CT:
655         c->status[0].step = c->status[1].step = 511;
656         break;
657     case CODEC_ID_ADPCM_IMA_WS:
658         if (avctx->extradata && avctx->extradata_size == 2 * 4) {
659             c->status[0].predictor = AV_RL32(avctx->extradata);
660             c->status[1].predictor = AV_RL32(avctx->extradata + 4);
661         }
662         break;
663     default:
664         break;
665     }
666     return 0;
667 }
668
669 static inline short adpcm_ima_expand_nibble(ADPCMChannelStatus *c, char nibble, int shift)
670 {
671     int step_index;
672     int predictor;
673     int sign, delta, diff, step;
674
675     step = step_table[c->step_index];
676     step_index = c->step_index + index_table[(unsigned)nibble];
677     if (step_index < 0) step_index = 0;
678     else if (step_index > 88) step_index = 88;
679
680     sign = nibble & 8;
681     delta = nibble & 7;
682     /* perform direct multiplication instead of series of jumps proposed by
683      * the reference ADPCM implementation since modern CPUs can do the mults
684      * quickly enough */
685     diff = ((2 * delta + 1) * step) >> shift;
686     predictor = c->predictor;
687     if (sign) predictor -= diff;
688     else predictor += diff;
689
690     c->predictor = av_clip_int16(predictor);
691     c->step_index = step_index;
692
693     return (short)c->predictor;
694 }
695
696 static inline short adpcm_ms_expand_nibble(ADPCMChannelStatus *c, char nibble)
697 {
698     int predictor;
699
700     predictor = (((c->sample1) * (c->coeff1)) + ((c->sample2) * (c->coeff2))) / 256;
701     predictor += (signed)((nibble & 0x08)?(nibble - 0x10):(nibble)) * c->idelta;
702
703     c->sample2 = c->sample1;
704     c->sample1 = av_clip_int16(predictor);
705     c->idelta = (AdaptationTable[(int)nibble] * c->idelta) >> 8;
706     if (c->idelta < 16) c->idelta = 16;
707
708     return c->sample1;
709 }
710
711 static inline short adpcm_ct_expand_nibble(ADPCMChannelStatus *c, char nibble)
712 {
713     int sign, delta, diff;
714     int new_step;
715
716     sign = nibble & 8;
717     delta = nibble & 7;
718     /* perform direct multiplication instead of series of jumps proposed by
719      * the reference ADPCM implementation since modern CPUs can do the mults
720      * quickly enough */
721     diff = ((2 * delta + 1) * c->step) >> 3;
722     /* predictor update is not so trivial: predictor is multiplied on 254/256 before updating */
723     c->predictor = ((c->predictor * 254) >> 8) + (sign ? -diff : diff);
724     c->predictor = av_clip_int16(c->predictor);
725     /* calculate new step and clamp it to range 511..32767 */
726     new_step = (ct_adpcm_table[nibble & 7] * c->step) >> 8;
727     c->step = av_clip(new_step, 511, 32767);
728
729     return (short)c->predictor;
730 }
731
732 static inline short adpcm_sbpro_expand_nibble(ADPCMChannelStatus *c, char nibble, int size, int shift)
733 {
734     int sign, delta, diff;
735
736     sign = nibble & (1<<(size-1));
737     delta = nibble & ((1<<(size-1))-1);
738     diff = delta << (7 + c->step + shift);
739
740     /* clamp result */
741     c->predictor = av_clip(c->predictor + (sign ? -diff : diff), -16384,16256);
742
743     /* calculate new step */
744     if (delta >= (2*size - 3) && c->step < 3)
745         c->step++;
746     else if (delta == 0 && c->step > 0)
747         c->step--;
748
749     return (short) c->predictor;
750 }
751
752 static inline short adpcm_yamaha_expand_nibble(ADPCMChannelStatus *c, unsigned char nibble)
753 {
754     if(!c->step) {
755         c->predictor = 0;
756         c->step = 127;
757     }
758
759     c->predictor += (c->step * yamaha_difflookup[nibble]) / 8;
760     c->predictor = av_clip_int16(c->predictor);
761     c->step = (c->step * yamaha_indexscale[nibble]) >> 8;
762     c->step = av_clip(c->step, 127, 24567);
763     return c->predictor;
764 }
765
766 static void xa_decode(short *out, const unsigned char *in,
767     ADPCMChannelStatus *left, ADPCMChannelStatus *right, int inc)
768 {
769     int i, j;
770     int shift,filter,f0,f1;
771     int s_1,s_2;
772     int d,s,t;
773
774     for(i=0;i<4;i++) {
775
776         shift  = 12 - (in[4+i*2] & 15);
777         filter = in[4+i*2] >> 4;
778         f0 = xa_adpcm_table[filter][0];
779         f1 = xa_adpcm_table[filter][1];
780
781         s_1 = left->sample1;
782         s_2 = left->sample2;
783
784         for(j=0;j<28;j++) {
785             d = in[16+i+j*4];
786
787             t = (signed char)(d<<4)>>4;
788             s = ( t<<shift ) + ((s_1*f0 + s_2*f1+32)>>6);
789             s_2 = s_1;
790             s_1 = av_clip_int16(s);
791             *out = s_1;
792             out += inc;
793         }
794
795         if (inc==2) { /* stereo */
796             left->sample1 = s_1;
797             left->sample2 = s_2;
798             s_1 = right->sample1;
799             s_2 = right->sample2;
800             out = out + 1 - 28*2;
801         }
802
803         shift  = 12 - (in[5+i*2] & 15);
804         filter = in[5+i*2] >> 4;
805
806         f0 = xa_adpcm_table[filter][0];
807         f1 = xa_adpcm_table[filter][1];
808
809         for(j=0;j<28;j++) {
810             d = in[16+i+j*4];
811
812             t = (signed char)d >> 4;
813             s = ( t<<shift ) + ((s_1*f0 + s_2*f1+32)>>6);
814             s_2 = s_1;
815             s_1 = av_clip_int16(s);
816             *out = s_1;
817             out += inc;
818         }
819
820         if (inc==2) { /* stereo */
821             right->sample1 = s_1;
822             right->sample2 = s_2;
823             out -= 1;
824         } else {
825             left->sample1 = s_1;
826             left->sample2 = s_2;
827         }
828     }
829 }
830
831
832 /* DK3 ADPCM support macro */
833 #define DK3_GET_NEXT_NIBBLE() \
834     if (decode_top_nibble_next) \
835     { \
836         nibble = (last_byte >> 4) & 0x0F; \
837         decode_top_nibble_next = 0; \
838     } \
839     else \
840     { \
841         last_byte = *src++; \
842         if (src >= buf + buf_size) break; \
843         nibble = last_byte & 0x0F; \
844         decode_top_nibble_next = 1; \
845     }
846
847 static int adpcm_decode_frame(AVCodecContext *avctx,
848                             void *data, int *data_size,
849                             uint8_t *buf, int buf_size)
850 {
851     ADPCMContext *c = avctx->priv_data;
852     ADPCMChannelStatus *cs;
853     int n, m, channel, i;
854     int block_predictor[2];
855     short *samples;
856     short *samples_end;
857     uint8_t *src;
858     int st; /* stereo */
859
860     /* DK3 ADPCM accounting variables */
861     unsigned char last_byte = 0;
862     unsigned char nibble;
863     int decode_top_nibble_next = 0;
864     int diff_channel;
865
866     /* EA ADPCM state variables */
867     uint32_t samples_in_chunk;
868     int32_t previous_left_sample, previous_right_sample;
869     int32_t current_left_sample, current_right_sample;
870     int32_t next_left_sample, next_right_sample;
871     int32_t coeff1l, coeff2l, coeff1r, coeff2r;
872     uint8_t shift_left, shift_right;
873     int count1, count2;
874
875     if (!buf_size)
876         return 0;
877
878     //should protect all 4bit ADPCM variants
879     //8 is needed for CODEC_ID_ADPCM_IMA_WAV with 2 channels
880     //
881     if(*data_size/4 < buf_size + 8)
882         return -1;
883
884     samples = data;
885     samples_end= samples + *data_size/2;
886     *data_size= 0;
887     src = buf;
888
889     st = avctx->channels == 2 ? 1 : 0;
890
891     switch(avctx->codec->id) {
892     case CODEC_ID_ADPCM_IMA_QT:
893         n = (buf_size - 2);/* >> 2*avctx->channels;*/
894         channel = c->channel;
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         cs->predictor = (*src++) << 8;
900         cs->predictor |= (*src & 0x80);
901         cs->predictor &= 0xFF80;
902
903         /* sign extension */
904         if(cs->predictor & 0x8000)
905             cs->predictor -= 0x10000;
906
907         cs->predictor = av_clip_int16(cs->predictor);
908
909         cs->step_index = (*src++) & 0x7F;
910
911         if (cs->step_index > 88){
912             av_log(avctx, AV_LOG_ERROR, "ERROR: step_index = %i\n", cs->step_index);
913             cs->step_index = 88;
914         }
915
916         cs->step = step_table[cs->step_index];
917
918         if (st && channel)
919             samples++;
920
921         for(m=32; n>0 && m>0; n--, m--) { /* in QuickTime, IMA is encoded by chuncks of 34 bytes (=64 samples) */
922             *samples = adpcm_ima_expand_nibble(cs, src[0] & 0x0F, 3);
923             samples += avctx->channels;
924             *samples = adpcm_ima_expand_nibble(cs, (src[0] >> 4) & 0x0F, 3);
925             samples += avctx->channels;
926             src ++;
927         }
928
929         if(st) { /* handle stereo interlacing */
930             c->channel = (channel + 1) % 2; /* we get one packet for left, then one for right data */
931             if(channel == 1) { /* wait for the other packet before outputing anything */
932                 return src - buf;
933             }
934         }
935         break;
936     case CODEC_ID_ADPCM_IMA_WAV:
937         if (avctx->block_align != 0 && buf_size > avctx->block_align)
938             buf_size = avctx->block_align;
939
940 //        samples_per_block= (block_align-4*chanels)*8 / (bits_per_sample * chanels) + 1;
941
942         for(i=0; i<avctx->channels; i++){
943             cs = &(c->status[i]);
944             cs->predictor = (int16_t)(src[0] + (src[1]<<8));
945             src+=2;
946
947         // XXX: is this correct ??: *samples++ = cs->predictor;
948
949             cs->step_index = *src++;
950             if (cs->step_index > 88){
951                 av_log(avctx, AV_LOG_ERROR, "ERROR: step_index = %i\n", cs->step_index);
952                 cs->step_index = 88;
953             }
954             if (*src++) av_log(avctx, AV_LOG_ERROR, "unused byte should be null but is %d!!\n", src[-1]); /* unused */
955         }
956
957         while(src < buf + buf_size){
958             for(m=0; m<4; m++){
959                 for(i=0; i<=st; i++)
960                     *samples++ = adpcm_ima_expand_nibble(&c->status[i], src[4*i] & 0x0F, 3);
961                 for(i=0; i<=st; i++)
962                     *samples++ = adpcm_ima_expand_nibble(&c->status[i], src[4*i] >> 4  , 3);
963                 src++;
964             }
965             src += 4*st;
966         }
967         break;
968     case CODEC_ID_ADPCM_4XM:
969         cs = &(c->status[0]);
970         c->status[0].predictor= (int16_t)(src[0] + (src[1]<<8)); src+=2;
971         if(st){
972             c->status[1].predictor= (int16_t)(src[0] + (src[1]<<8)); src+=2;
973         }
974         c->status[0].step_index= (int16_t)(src[0] + (src[1]<<8)); src+=2;
975         if(st){
976             c->status[1].step_index= (int16_t)(src[0] + (src[1]<<8)); src+=2;
977         }
978         if (cs->step_index < 0) cs->step_index = 0;
979         if (cs->step_index > 88) cs->step_index = 88;
980
981         m= (buf_size - (src - buf))>>st;
982         for(i=0; i<m; i++) {
983             *samples++ = adpcm_ima_expand_nibble(&c->status[0], src[i] & 0x0F, 4);
984             if (st)
985                 *samples++ = adpcm_ima_expand_nibble(&c->status[1], src[i+m] & 0x0F, 4);
986             *samples++ = adpcm_ima_expand_nibble(&c->status[0], src[i] >> 4, 4);
987             if (st)
988                 *samples++ = adpcm_ima_expand_nibble(&c->status[1], src[i+m] >> 4, 4);
989         }
990
991         src += m<<st;
992
993         break;
994     case CODEC_ID_ADPCM_MS:
995         if (avctx->block_align != 0 && buf_size > avctx->block_align)
996             buf_size = avctx->block_align;
997         n = buf_size - 7 * avctx->channels;
998         if (n < 0)
999             return -1;
1000         block_predictor[0] = av_clip(*src++, 0, 7);
1001         block_predictor[1] = 0;
1002         if (st)
1003             block_predictor[1] = av_clip(*src++, 0, 7);
1004         c->status[0].idelta = (int16_t)((*src & 0xFF) | ((src[1] << 8) & 0xFF00));
1005         src+=2;
1006         if (st){
1007             c->status[1].idelta = (int16_t)((*src & 0xFF) | ((src[1] << 8) & 0xFF00));
1008             src+=2;
1009         }
1010         c->status[0].coeff1 = AdaptCoeff1[block_predictor[0]];
1011         c->status[0].coeff2 = AdaptCoeff2[block_predictor[0]];
1012         c->status[1].coeff1 = AdaptCoeff1[block_predictor[1]];
1013         c->status[1].coeff2 = AdaptCoeff2[block_predictor[1]];
1014
1015         c->status[0].sample1 = ((*src & 0xFF) | ((src[1] << 8) & 0xFF00));
1016         src+=2;
1017         if (st) c->status[1].sample1 = ((*src & 0xFF) | ((src[1] << 8) & 0xFF00));
1018         if (st) src+=2;
1019         c->status[0].sample2 = ((*src & 0xFF) | ((src[1] << 8) & 0xFF00));
1020         src+=2;
1021         if (st) c->status[1].sample2 = ((*src & 0xFF) | ((src[1] << 8) & 0xFF00));
1022         if (st) src+=2;
1023
1024         *samples++ = c->status[0].sample1;
1025         if (st) *samples++ = c->status[1].sample1;
1026         *samples++ = c->status[0].sample2;
1027         if (st) *samples++ = c->status[1].sample2;
1028         for(;n>0;n--) {
1029             *samples++ = adpcm_ms_expand_nibble(&c->status[0], (src[0] >> 4) & 0x0F);
1030             *samples++ = adpcm_ms_expand_nibble(&c->status[st], src[0] & 0x0F);
1031             src ++;
1032         }
1033         break;
1034     case CODEC_ID_ADPCM_IMA_DK4:
1035         if (avctx->block_align != 0 && buf_size > avctx->block_align)
1036             buf_size = avctx->block_align;
1037
1038         c->status[0].predictor = (int16_t)(src[0] | (src[1] << 8));
1039         c->status[0].step_index = src[2];
1040         src += 4;
1041         *samples++ = c->status[0].predictor;
1042         if (st) {
1043             c->status[1].predictor = (int16_t)(src[0] | (src[1] << 8));
1044             c->status[1].step_index = src[2];
1045             src += 4;
1046             *samples++ = c->status[1].predictor;
1047         }
1048         while (src < buf + buf_size) {
1049
1050             /* take care of the top nibble (always left or mono channel) */
1051             *samples++ = adpcm_ima_expand_nibble(&c->status[0],
1052                 (src[0] >> 4) & 0x0F, 3);
1053
1054             /* take care of the bottom nibble, which is right sample for
1055              * stereo, or another mono sample */
1056             if (st)
1057                 *samples++ = adpcm_ima_expand_nibble(&c->status[1],
1058                     src[0] & 0x0F, 3);
1059             else
1060                 *samples++ = adpcm_ima_expand_nibble(&c->status[0],
1061                     src[0] & 0x0F, 3);
1062
1063             src++;
1064         }
1065         break;
1066     case CODEC_ID_ADPCM_IMA_DK3:
1067         if (avctx->block_align != 0 && buf_size > avctx->block_align)
1068             buf_size = avctx->block_align;
1069
1070         if(buf_size + 16 > (samples_end - samples)*3/8)
1071             return -1;
1072
1073         c->status[0].predictor = (int16_t)(src[10] | (src[11] << 8));
1074         c->status[1].predictor = (int16_t)(src[12] | (src[13] << 8));
1075         c->status[0].step_index = src[14];
1076         c->status[1].step_index = src[15];
1077         /* sign extend the predictors */
1078         src += 16;
1079         diff_channel = c->status[1].predictor;
1080
1081         /* the DK3_GET_NEXT_NIBBLE macro issues the break statement when
1082          * the buffer is consumed */
1083         while (1) {
1084
1085             /* for this algorithm, c->status[0] is the sum channel and
1086              * c->status[1] is the diff channel */
1087
1088             /* process the first predictor of the sum channel */
1089             DK3_GET_NEXT_NIBBLE();
1090             adpcm_ima_expand_nibble(&c->status[0], nibble, 3);
1091
1092             /* process the diff channel predictor */
1093             DK3_GET_NEXT_NIBBLE();
1094             adpcm_ima_expand_nibble(&c->status[1], nibble, 3);
1095
1096             /* process the first pair of stereo PCM samples */
1097             diff_channel = (diff_channel + c->status[1].predictor) / 2;
1098             *samples++ = c->status[0].predictor + c->status[1].predictor;
1099             *samples++ = c->status[0].predictor - c->status[1].predictor;
1100
1101             /* process the second predictor of the sum channel */
1102             DK3_GET_NEXT_NIBBLE();
1103             adpcm_ima_expand_nibble(&c->status[0], nibble, 3);
1104
1105             /* process the second pair of stereo PCM samples */
1106             diff_channel = (diff_channel + c->status[1].predictor) / 2;
1107             *samples++ = c->status[0].predictor + c->status[1].predictor;
1108             *samples++ = c->status[0].predictor - c->status[1].predictor;
1109         }
1110         break;
1111     case CODEC_ID_ADPCM_IMA_WS:
1112         /* no per-block initialization; just start decoding the data */
1113         while (src < buf + buf_size) {
1114
1115             if (st) {
1116                 *samples++ = adpcm_ima_expand_nibble(&c->status[0],
1117                     (src[0] >> 4) & 0x0F, 3);
1118                 *samples++ = adpcm_ima_expand_nibble(&c->status[1],
1119                     src[0] & 0x0F, 3);
1120             } else {
1121                 *samples++ = adpcm_ima_expand_nibble(&c->status[0],
1122                     (src[0] >> 4) & 0x0F, 3);
1123                 *samples++ = adpcm_ima_expand_nibble(&c->status[0],
1124                     src[0] & 0x0F, 3);
1125             }
1126
1127             src++;
1128         }
1129         break;
1130     case CODEC_ID_ADPCM_XA:
1131         c->status[0].sample1 = c->status[0].sample2 =
1132         c->status[1].sample1 = c->status[1].sample2 = 0;
1133         while (buf_size >= 128) {
1134             xa_decode(samples, src, &c->status[0], &c->status[1],
1135                 avctx->channels);
1136             src += 128;
1137             samples += 28 * 8;
1138             buf_size -= 128;
1139         }
1140         break;
1141     case CODEC_ID_ADPCM_IMA_EA_SEAD:
1142         for (; src < buf+buf_size; src++) {
1143             *samples++ = adpcm_ima_expand_nibble(&c->status[0], src[0] >> 4, 6);
1144             *samples++ = adpcm_ima_expand_nibble(&c->status[st],src[0]&0x0F, 6);
1145         }
1146         break;
1147     case CODEC_ID_ADPCM_EA:
1148         samples_in_chunk = AV_RL32(src);
1149         if (samples_in_chunk >= ((buf_size - 12) * 2)) {
1150             src += buf_size;
1151             break;
1152         }
1153         src += 4;
1154         current_left_sample = (int16_t)AV_RL16(src);
1155         src += 2;
1156         previous_left_sample = (int16_t)AV_RL16(src);
1157         src += 2;
1158         current_right_sample = (int16_t)AV_RL16(src);
1159         src += 2;
1160         previous_right_sample = (int16_t)AV_RL16(src);
1161         src += 2;
1162
1163         for (count1 = 0; count1 < samples_in_chunk/28;count1++) {
1164             coeff1l = ea_adpcm_table[(*src >> 4) & 0x0F];
1165             coeff2l = ea_adpcm_table[((*src >> 4) & 0x0F) + 4];
1166             coeff1r = ea_adpcm_table[*src & 0x0F];
1167             coeff2r = ea_adpcm_table[(*src & 0x0F) + 4];
1168             src++;
1169
1170             shift_left = ((*src >> 4) & 0x0F) + 8;
1171             shift_right = (*src & 0x0F) + 8;
1172             src++;
1173
1174             for (count2 = 0; count2 < 28; count2++) {
1175                 next_left_sample = (((*src & 0xF0) << 24) >> shift_left);
1176                 next_right_sample = (((*src & 0x0F) << 28) >> shift_right);
1177                 src++;
1178
1179                 next_left_sample = (next_left_sample +
1180                     (current_left_sample * coeff1l) +
1181                     (previous_left_sample * coeff2l) + 0x80) >> 8;
1182                 next_right_sample = (next_right_sample +
1183                     (current_right_sample * coeff1r) +
1184                     (previous_right_sample * coeff2r) + 0x80) >> 8;
1185
1186                 previous_left_sample = current_left_sample;
1187                 current_left_sample = av_clip_int16(next_left_sample);
1188                 previous_right_sample = current_right_sample;
1189                 current_right_sample = av_clip_int16(next_right_sample);
1190                 *samples++ = (unsigned short)current_left_sample;
1191                 *samples++ = (unsigned short)current_right_sample;
1192             }
1193         }
1194         break;
1195     case CODEC_ID_ADPCM_EA_R1:
1196     case CODEC_ID_ADPCM_EA_R2:
1197     case CODEC_ID_ADPCM_EA_R3: {
1198         /* channel numbering
1199            2chan: 0=fl, 1=fr
1200            4chan: 0=fl, 1=rl, 2=fr, 3=rr
1201            6chan: 0=fl, 1=c,  2=fr, 3=rl,  4=rr, 5=sub */
1202         const int big_endian = avctx->codec->id == CODEC_ID_ADPCM_EA_R3;
1203         int32_t previous_sample, current_sample, next_sample;
1204         int32_t coeff1, coeff2;
1205         uint8_t shift;
1206         unsigned int channel;
1207         uint16_t *samplesC;
1208         uint8_t *srcC;
1209
1210         samples_in_chunk = (big_endian ? bytestream_get_be32(&src)
1211                                        : bytestream_get_le32(&src)) / 28;
1212         if (samples_in_chunk > UINT32_MAX/(28*avctx->channels) ||
1213             28*samples_in_chunk*avctx->channels > samples_end-samples) {
1214             src += buf_size - 4;
1215             break;
1216         }
1217
1218         for (channel=0; channel<avctx->channels; channel++) {
1219             srcC = src + (big_endian ? bytestream_get_be32(&src)
1220                                      : bytestream_get_le32(&src))
1221                        + (avctx->channels-channel-1) * 4;
1222             samplesC = samples + channel;
1223
1224             if (avctx->codec->id == CODEC_ID_ADPCM_EA_R1) {
1225                 current_sample  = (int16_t)bytestream_get_le16(&srcC);
1226                 previous_sample = (int16_t)bytestream_get_le16(&srcC);
1227             } else {
1228                 current_sample  = c->status[channel].predictor;
1229                 previous_sample = c->status[channel].prev_sample;
1230             }
1231
1232             for (count1=0; count1<samples_in_chunk; count1++) {
1233                 if (*srcC == 0xEE) {  /* only seen in R2 and R3 */
1234                     srcC++;
1235                     current_sample  = (int16_t)bytestream_get_be16(&srcC);
1236                     previous_sample = (int16_t)bytestream_get_be16(&srcC);
1237
1238                     for (count2=0; count2<28; count2++) {
1239                         *samplesC = (int16_t)bytestream_get_be16(&srcC);
1240                         samplesC += avctx->channels;
1241                     }
1242                 } else {
1243                     coeff1 = ea_adpcm_table[ (*srcC>>4) & 0x0F     ];
1244                     coeff2 = ea_adpcm_table[((*srcC>>4) & 0x0F) + 4];
1245                     shift = (*srcC++ & 0x0F) + 8;
1246
1247                     for (count2=0; count2<28; count2++) {
1248                         if (count2 & 1)
1249                             next_sample = ((*srcC++ & 0x0F) << 28) >> shift;
1250                         else
1251                             next_sample = ((*srcC   & 0xF0) << 24) >> shift;
1252
1253                         next_sample += (current_sample  * coeff1) +
1254                                        (previous_sample * coeff2);
1255                         next_sample = av_clip_int16(next_sample >> 8);
1256
1257                         previous_sample = current_sample;
1258                         current_sample  = next_sample;
1259                         *samplesC = current_sample;
1260                         samplesC += avctx->channels;
1261                     }
1262                 }
1263             }
1264
1265             if (avctx->codec->id != CODEC_ID_ADPCM_EA_R1) {
1266                 c->status[channel].predictor   = current_sample;
1267                 c->status[channel].prev_sample = previous_sample;
1268             }
1269         }
1270
1271         src = src + buf_size - (4 + 4*avctx->channels);
1272         samples += 28 * samples_in_chunk * avctx->channels;
1273         break;
1274     }
1275     case CODEC_ID_ADPCM_IMA_AMV:
1276     case CODEC_ID_ADPCM_IMA_SMJPEG:
1277         c->status[0].predictor = (int16_t)bytestream_get_le16(&src);
1278         c->status[0].step_index = bytestream_get_le16(&src);
1279
1280         if (avctx->codec->id == CODEC_ID_ADPCM_IMA_AMV)
1281             src+=4;
1282
1283         while (src < buf + buf_size) {
1284             char hi, lo;
1285             lo = *src & 0x0F;
1286             hi = (*src >> 4) & 0x0F;
1287
1288             if (avctx->codec->id == CODEC_ID_ADPCM_IMA_AMV)
1289                 FFSWAP(char, hi, lo);
1290
1291             *samples++ = adpcm_ima_expand_nibble(&c->status[0],
1292                 lo, 3);
1293             *samples++ = adpcm_ima_expand_nibble(&c->status[0],
1294                 hi, 3);
1295             src++;
1296         }
1297         break;
1298     case CODEC_ID_ADPCM_CT:
1299         while (src < buf + buf_size) {
1300             if (st) {
1301                 *samples++ = adpcm_ct_expand_nibble(&c->status[0],
1302                     (src[0] >> 4) & 0x0F);
1303                 *samples++ = adpcm_ct_expand_nibble(&c->status[1],
1304                     src[0] & 0x0F);
1305             } else {
1306                 *samples++ = adpcm_ct_expand_nibble(&c->status[0],
1307                     (src[0] >> 4) & 0x0F);
1308                 *samples++ = adpcm_ct_expand_nibble(&c->status[0],
1309                     src[0] & 0x0F);
1310             }
1311             src++;
1312         }
1313         break;
1314     case CODEC_ID_ADPCM_SBPRO_4:
1315     case CODEC_ID_ADPCM_SBPRO_3:
1316     case CODEC_ID_ADPCM_SBPRO_2:
1317         if (!c->status[0].step_index) {
1318             /* the first byte is a raw sample */
1319             *samples++ = 128 * (*src++ - 0x80);
1320             if (st)
1321               *samples++ = 128 * (*src++ - 0x80);
1322             c->status[0].step_index = 1;
1323         }
1324         if (avctx->codec->id == CODEC_ID_ADPCM_SBPRO_4) {
1325             while (src < buf + buf_size) {
1326                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
1327                     (src[0] >> 4) & 0x0F, 4, 0);
1328                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],
1329                     src[0] & 0x0F, 4, 0);
1330                 src++;
1331             }
1332         } else if (avctx->codec->id == CODEC_ID_ADPCM_SBPRO_3) {
1333             while (src < buf + buf_size && samples + 2 < samples_end) {
1334                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
1335                     (src[0] >> 5) & 0x07, 3, 0);
1336                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
1337                     (src[0] >> 2) & 0x07, 3, 0);
1338                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
1339                     src[0] & 0x03, 2, 0);
1340                 src++;
1341             }
1342         } else {
1343             while (src < buf + buf_size && samples + 3 < samples_end) {
1344                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
1345                     (src[0] >> 6) & 0x03, 2, 2);
1346                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],
1347                     (src[0] >> 4) & 0x03, 2, 2);
1348                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
1349                     (src[0] >> 2) & 0x03, 2, 2);
1350                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],
1351                     src[0] & 0x03, 2, 2);
1352                 src++;
1353             }
1354         }
1355         break;
1356     case CODEC_ID_ADPCM_SWF:
1357     {
1358         GetBitContext gb;
1359         const int *table;
1360         int k0, signmask, nb_bits, count;
1361         int size = buf_size*8;
1362
1363         init_get_bits(&gb, buf, size);
1364
1365         //read bits & initial values
1366         nb_bits = get_bits(&gb, 2)+2;
1367         //av_log(NULL,AV_LOG_INFO,"nb_bits: %d\n", nb_bits);
1368         table = swf_index_tables[nb_bits-2];
1369         k0 = 1 << (nb_bits-2);
1370         signmask = 1 << (nb_bits-1);
1371
1372         while (get_bits_count(&gb) <= size - 22*avctx->channels) {
1373             for (i = 0; i < avctx->channels; i++) {
1374                 *samples++ = c->status[i].predictor = get_sbits(&gb, 16);
1375                 c->status[i].step_index = get_bits(&gb, 6);
1376             }
1377
1378             for (count = 0; get_bits_count(&gb) <= size - nb_bits*avctx->channels && count < 4095; count++) {
1379                 int i;
1380
1381                 for (i = 0; i < avctx->channels; i++) {
1382                     // similar to IMA adpcm
1383                     int delta = get_bits(&gb, nb_bits);
1384                     int step = step_table[c->status[i].step_index];
1385                     long vpdiff = 0; // vpdiff = (delta+0.5)*step/4
1386                     int k = k0;
1387
1388                     do {
1389                         if (delta & k)
1390                             vpdiff += step;
1391                         step >>= 1;
1392                         k >>= 1;
1393                     } while(k);
1394                     vpdiff += step;
1395
1396                     if (delta & signmask)
1397                         c->status[i].predictor -= vpdiff;
1398                     else
1399                         c->status[i].predictor += vpdiff;
1400
1401                     c->status[i].step_index += table[delta & (~signmask)];
1402
1403                     c->status[i].step_index = av_clip(c->status[i].step_index, 0, 88);
1404                     c->status[i].predictor = av_clip_int16(c->status[i].predictor);
1405
1406                     *samples++ = c->status[i].predictor;
1407                     if (samples >= samples_end) {
1408                         av_log(avctx, AV_LOG_ERROR, "allocated output buffer is too small\n");
1409                         return -1;
1410                     }
1411                 }
1412             }
1413         }
1414         src += buf_size;
1415         break;
1416     }
1417     case CODEC_ID_ADPCM_YAMAHA:
1418         while (src < buf + buf_size) {
1419             if (st) {
1420                 *samples++ = adpcm_yamaha_expand_nibble(&c->status[0],
1421                         src[0] & 0x0F);
1422                 *samples++ = adpcm_yamaha_expand_nibble(&c->status[1],
1423                         (src[0] >> 4) & 0x0F);
1424             } else {
1425                 *samples++ = adpcm_yamaha_expand_nibble(&c->status[0],
1426                         src[0] & 0x0F);
1427                 *samples++ = adpcm_yamaha_expand_nibble(&c->status[0],
1428                         (src[0] >> 4) & 0x0F);
1429             }
1430             src++;
1431         }
1432         break;
1433     case CODEC_ID_ADPCM_THP:
1434     {
1435         int table[2][16];
1436         unsigned int samplecnt;
1437         int prev[2][2];
1438         int ch;
1439
1440         if (buf_size < 80) {
1441             av_log(avctx, AV_LOG_ERROR, "frame too small\n");
1442             return -1;
1443         }
1444
1445         src+=4;
1446         samplecnt = bytestream_get_be32(&src);
1447
1448         for (i = 0; i < 32; i++)
1449             table[0][i] = (int16_t)bytestream_get_be16(&src);
1450
1451         /* Initialize the previous sample.  */
1452         for (i = 0; i < 4; i++)
1453             prev[0][i] = (int16_t)bytestream_get_be16(&src);
1454
1455         if (samplecnt >= (samples_end - samples) /  (st + 1)) {
1456             av_log(avctx, AV_LOG_ERROR, "allocated output buffer is too small\n");
1457             return -1;
1458         }
1459
1460         for (ch = 0; ch <= st; ch++) {
1461             samples = (unsigned short *) data + ch;
1462
1463             /* Read in every sample for this channel.  */
1464             for (i = 0; i < samplecnt / 14; i++) {
1465                 int index = (*src >> 4) & 7;
1466                 unsigned int exp = 28 - (*src++ & 15);
1467                 int factor1 = table[ch][index * 2];
1468                 int factor2 = table[ch][index * 2 + 1];
1469
1470                 /* Decode 14 samples.  */
1471                 for (n = 0; n < 14; n++) {
1472                     int32_t sampledat;
1473                     if(n&1) sampledat=  *src++    <<28;
1474                     else    sampledat= (*src&0xF0)<<24;
1475
1476                     sampledat = ((prev[ch][0]*factor1
1477                                 + prev[ch][1]*factor2) >> 11) + (sampledat>>exp);
1478                     *samples = av_clip_int16(sampledat);
1479                     prev[ch][1] = prev[ch][0];
1480                     prev[ch][0] = *samples++;
1481
1482                     /* In case of stereo, skip one sample, this sample
1483                        is for the other channel.  */
1484                     samples += st;
1485                 }
1486             }
1487         }
1488
1489         /* In the previous loop, in case stereo is used, samples is
1490            increased exactly one time too often.  */
1491         samples -= st;
1492         break;
1493     }
1494
1495     default:
1496         return -1;
1497     }
1498     *data_size = (uint8_t *)samples - (uint8_t *)data;
1499     return src - buf;
1500 }
1501
1502
1503
1504 #ifdef CONFIG_ENCODERS
1505 #define ADPCM_ENCODER(id,name)                  \
1506 AVCodec name ## _encoder = {                    \
1507     #name,                                      \
1508     CODEC_TYPE_AUDIO,                           \
1509     id,                                         \
1510     sizeof(ADPCMContext),                       \
1511     adpcm_encode_init,                          \
1512     adpcm_encode_frame,                         \
1513     adpcm_encode_close,                         \
1514     NULL,                                       \
1515 };
1516 #else
1517 #define ADPCM_ENCODER(id,name)
1518 #endif
1519
1520 #ifdef CONFIG_DECODERS
1521 #define ADPCM_DECODER(id,name)                  \
1522 AVCodec name ## _decoder = {                    \
1523     #name,                                      \
1524     CODEC_TYPE_AUDIO,                           \
1525     id,                                         \
1526     sizeof(ADPCMContext),                       \
1527     adpcm_decode_init,                          \
1528     NULL,                                       \
1529     NULL,                                       \
1530     adpcm_decode_frame,                         \
1531 };
1532 #else
1533 #define ADPCM_DECODER(id,name)
1534 #endif
1535
1536 #define ADPCM_CODEC(id, name)                   \
1537 ADPCM_ENCODER(id,name) ADPCM_DECODER(id,name)
1538
1539 ADPCM_CODEC(CODEC_ID_ADPCM_4XM, adpcm_4xm);
1540 ADPCM_CODEC(CODEC_ID_ADPCM_CT, adpcm_ct);
1541 ADPCM_CODEC(CODEC_ID_ADPCM_EA, adpcm_ea);
1542 ADPCM_CODEC(CODEC_ID_ADPCM_IMA_AMV, adpcm_ima_amv);
1543 ADPCM_CODEC(CODEC_ID_ADPCM_IMA_DK3, adpcm_ima_dk3);
1544 ADPCM_CODEC(CODEC_ID_ADPCM_IMA_DK4, adpcm_ima_dk4);
1545 ADPCM_CODEC(CODEC_ID_ADPCM_IMA_EA_SEAD, adpcm_ima_ea_sead);
1546 ADPCM_CODEC(CODEC_ID_ADPCM_IMA_QT, adpcm_ima_qt);
1547 ADPCM_CODEC(CODEC_ID_ADPCM_IMA_SMJPEG, adpcm_ima_smjpeg);
1548 ADPCM_CODEC(CODEC_ID_ADPCM_IMA_WAV, adpcm_ima_wav);
1549 ADPCM_CODEC(CODEC_ID_ADPCM_IMA_WS, adpcm_ima_ws);
1550 ADPCM_CODEC(CODEC_ID_ADPCM_MS, adpcm_ms);
1551 ADPCM_CODEC(CODEC_ID_ADPCM_EA_R1, adpcm_ea_r1);
1552 ADPCM_CODEC(CODEC_ID_ADPCM_EA_R2, adpcm_ea_r2);
1553 ADPCM_CODEC(CODEC_ID_ADPCM_EA_R3, adpcm_ea_r3);
1554 ADPCM_CODEC(CODEC_ID_ADPCM_SBPRO_4, adpcm_sbpro_4);
1555 ADPCM_CODEC(CODEC_ID_ADPCM_SBPRO_3, adpcm_sbpro_3);
1556 ADPCM_CODEC(CODEC_ID_ADPCM_SBPRO_2, adpcm_sbpro_2);
1557 ADPCM_CODEC(CODEC_ID_ADPCM_SWF, adpcm_swf);
1558 ADPCM_CODEC(CODEC_ID_ADPCM_THP, adpcm_thp);
1559 ADPCM_CODEC(CODEC_ID_ADPCM_XA, adpcm_xa);
1560 ADPCM_CODEC(CODEC_ID_ADPCM_YAMAHA, adpcm_yamaha);
1561
1562 #undef ADPCM_CODEC