]> git.sesse.net Git - ffmpeg/blob - libavcodec/adpcm.c
adpcm_4xm: process planar packets sequentially rather than simultaneously.
[ffmpeg] / libavcodec / adpcm.c
1 /*
2  * Copyright (c) 2001-2003 The ffmpeg Project
3  *
4  * This file is part of Libav.
5  *
6  * Libav is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * Libav is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with Libav; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20 #include "avcodec.h"
21 #include "get_bits.h"
22 #include "put_bits.h"
23 #include "bytestream.h"
24 #include "adpcm.h"
25 #include "adpcm_data.h"
26
27 /**
28  * @file
29  * ADPCM decoders
30  * First version by Francois Revol (revol@free.fr)
31  * Fringe ADPCM codecs (e.g., DK3, DK4, Westwood)
32  *   by Mike Melanson (melanson@pcisys.net)
33  * CD-ROM XA ADPCM codec by BERO
34  * EA ADPCM decoder by Robin Kay (komadori@myrealbox.com)
35  * EA ADPCM R1/R2/R3 decoder by Peter Ross (pross@xvid.org)
36  * EA IMA EACS decoder by Peter Ross (pross@xvid.org)
37  * EA IMA SEAD decoder by Peter Ross (pross@xvid.org)
38  * EA ADPCM XAS decoder by Peter Ross (pross@xvid.org)
39  * MAXIS EA ADPCM decoder by Robert Marston (rmarston@gmail.com)
40  * THP ADPCM decoder by Marco Gerards (mgerards@xs4all.nl)
41  *
42  * Features and limitations:
43  *
44  * Reference documents:
45  * http://wiki.multimedia.cx/index.php?title=Category:ADPCM_Audio_Codecs
46  * http://www.pcisys.net/~melanson/codecs/simpleaudio.html [dead]
47  * http://www.geocities.com/SiliconValley/8682/aud3.txt [dead]
48  * http://openquicktime.sourceforge.net/
49  * XAnim sources (xa_codec.c) http://xanim.polter.net/
50  * http://www.cs.ucla.edu/~leec/mediabench/applications.html [dead]
51  * SoX source code http://sox.sourceforge.net/
52  *
53  * CD-ROM XA:
54  * http://ku-www.ss.titech.ac.jp/~yatsushi/xaadpcm.html [dead]
55  * vagpack & depack http://homepages.compuserve.de/bITmASTER32/psx-index.html [dead]
56  * readstr http://www.geocities.co.jp/Playtown/2004/
57  */
58
59 /* These are for CD-ROM XA ADPCM */
60 static const int xa_adpcm_table[5][2] = {
61     {   0,   0 },
62     {  60,   0 },
63     { 115, -52 },
64     {  98, -55 },
65     { 122, -60 }
66 };
67
68 static const int ea_adpcm_table[] = {
69     0,  240,  460,  392,
70     0,    0, -208, -220,
71     0,    1,    3,    4,
72     7,    8,   10,   11,
73     0,   -1,   -3,   -4
74 };
75
76 // padded to zero where table size is less then 16
77 static const int swf_index_tables[4][16] = {
78     /*2*/ { -1, 2 },
79     /*3*/ { -1, -1, 2, 4 },
80     /*4*/ { -1, -1, -1, -1, 2, 4, 6, 8 },
81     /*5*/ { -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 4, 6, 8, 10, 13, 16 }
82 };
83
84 /* end of tables */
85
86 typedef struct ADPCMDecodeContext {
87     ADPCMChannelStatus status[6];
88 } ADPCMDecodeContext;
89
90 static av_cold int adpcm_decode_init(AVCodecContext * avctx)
91 {
92     ADPCMDecodeContext *c = avctx->priv_data;
93     unsigned int max_channels = 2;
94
95     switch(avctx->codec->id) {
96     case CODEC_ID_ADPCM_EA_R1:
97     case CODEC_ID_ADPCM_EA_R2:
98     case CODEC_ID_ADPCM_EA_R3:
99     case CODEC_ID_ADPCM_EA_XAS:
100         max_channels = 6;
101         break;
102     }
103     if(avctx->channels > max_channels){
104         return -1;
105     }
106
107     switch(avctx->codec->id) {
108     case CODEC_ID_ADPCM_CT:
109         c->status[0].step = c->status[1].step = 511;
110         break;
111     case CODEC_ID_ADPCM_IMA_WAV:
112         if (avctx->bits_per_coded_sample != 4) {
113             av_log(avctx, AV_LOG_ERROR, "Only 4-bit ADPCM IMA WAV files are supported\n");
114             return -1;
115         }
116         break;
117     case CODEC_ID_ADPCM_IMA_WS:
118         if (avctx->extradata && avctx->extradata_size == 2 * 4) {
119             c->status[0].predictor = AV_RL32(avctx->extradata);
120             c->status[1].predictor = AV_RL32(avctx->extradata + 4);
121         }
122         break;
123     default:
124         break;
125     }
126     avctx->sample_fmt = AV_SAMPLE_FMT_S16;
127     return 0;
128 }
129
130 static inline short adpcm_ima_expand_nibble(ADPCMChannelStatus *c, char nibble, int shift)
131 {
132     int step_index;
133     int predictor;
134     int sign, delta, diff, step;
135
136     step = ff_adpcm_step_table[c->step_index];
137     step_index = c->step_index + ff_adpcm_index_table[(unsigned)nibble];
138     if (step_index < 0) step_index = 0;
139     else if (step_index > 88) step_index = 88;
140
141     sign = nibble & 8;
142     delta = nibble & 7;
143     /* perform direct multiplication instead of series of jumps proposed by
144      * the reference ADPCM implementation since modern CPUs can do the mults
145      * quickly enough */
146     diff = ((2 * delta + 1) * step) >> shift;
147     predictor = c->predictor;
148     if (sign) predictor -= diff;
149     else predictor += diff;
150
151     c->predictor = av_clip_int16(predictor);
152     c->step_index = step_index;
153
154     return (short)c->predictor;
155 }
156
157 static inline int adpcm_ima_qt_expand_nibble(ADPCMChannelStatus *c, int nibble, int shift)
158 {
159     int step_index;
160     int predictor;
161     int diff, step;
162
163     step = ff_adpcm_step_table[c->step_index];
164     step_index = c->step_index + ff_adpcm_index_table[nibble];
165     step_index = av_clip(step_index, 0, 88);
166
167     diff = step >> 3;
168     if (nibble & 4) diff += step;
169     if (nibble & 2) diff += step >> 1;
170     if (nibble & 1) diff += step >> 2;
171
172     if (nibble & 8)
173         predictor = c->predictor - diff;
174     else
175         predictor = c->predictor + diff;
176
177     c->predictor = av_clip_int16(predictor);
178     c->step_index = step_index;
179
180     return c->predictor;
181 }
182
183 static inline short adpcm_ms_expand_nibble(ADPCMChannelStatus *c, char nibble)
184 {
185     int predictor;
186
187     predictor = (((c->sample1) * (c->coeff1)) + ((c->sample2) * (c->coeff2))) / 64;
188     predictor += (signed)((nibble & 0x08)?(nibble - 0x10):(nibble)) * c->idelta;
189
190     c->sample2 = c->sample1;
191     c->sample1 = av_clip_int16(predictor);
192     c->idelta = (ff_adpcm_AdaptationTable[(int)nibble] * c->idelta) >> 8;
193     if (c->idelta < 16) c->idelta = 16;
194
195     return c->sample1;
196 }
197
198 static inline short adpcm_ct_expand_nibble(ADPCMChannelStatus *c, char nibble)
199 {
200     int sign, delta, diff;
201     int new_step;
202
203     sign = nibble & 8;
204     delta = nibble & 7;
205     /* perform direct multiplication instead of series of jumps proposed by
206      * the reference ADPCM implementation since modern CPUs can do the mults
207      * quickly enough */
208     diff = ((2 * delta + 1) * c->step) >> 3;
209     /* predictor update is not so trivial: predictor is multiplied on 254/256 before updating */
210     c->predictor = ((c->predictor * 254) >> 8) + (sign ? -diff : diff);
211     c->predictor = av_clip_int16(c->predictor);
212     /* calculate new step and clamp it to range 511..32767 */
213     new_step = (ff_adpcm_AdaptationTable[nibble & 7] * c->step) >> 8;
214     c->step = av_clip(new_step, 511, 32767);
215
216     return (short)c->predictor;
217 }
218
219 static inline short adpcm_sbpro_expand_nibble(ADPCMChannelStatus *c, char nibble, int size, int shift)
220 {
221     int sign, delta, diff;
222
223     sign = nibble & (1<<(size-1));
224     delta = nibble & ((1<<(size-1))-1);
225     diff = delta << (7 + c->step + shift);
226
227     /* clamp result */
228     c->predictor = av_clip(c->predictor + (sign ? -diff : diff), -16384,16256);
229
230     /* calculate new step */
231     if (delta >= (2*size - 3) && c->step < 3)
232         c->step++;
233     else if (delta == 0 && c->step > 0)
234         c->step--;
235
236     return (short) c->predictor;
237 }
238
239 static inline short adpcm_yamaha_expand_nibble(ADPCMChannelStatus *c, unsigned char nibble)
240 {
241     if(!c->step) {
242         c->predictor = 0;
243         c->step = 127;
244     }
245
246     c->predictor += (c->step * ff_adpcm_yamaha_difflookup[nibble]) / 8;
247     c->predictor = av_clip_int16(c->predictor);
248     c->step = (c->step * ff_adpcm_yamaha_indexscale[nibble]) >> 8;
249     c->step = av_clip(c->step, 127, 24567);
250     return c->predictor;
251 }
252
253 static void xa_decode(short *out, const unsigned char *in,
254     ADPCMChannelStatus *left, ADPCMChannelStatus *right, int inc)
255 {
256     int i, j;
257     int shift,filter,f0,f1;
258     int s_1,s_2;
259     int d,s,t;
260
261     for(i=0;i<4;i++) {
262
263         shift  = 12 - (in[4+i*2] & 15);
264         filter = in[4+i*2] >> 4;
265         f0 = xa_adpcm_table[filter][0];
266         f1 = xa_adpcm_table[filter][1];
267
268         s_1 = left->sample1;
269         s_2 = left->sample2;
270
271         for(j=0;j<28;j++) {
272             d = in[16+i+j*4];
273
274             t = (signed char)(d<<4)>>4;
275             s = ( t<<shift ) + ((s_1*f0 + s_2*f1+32)>>6);
276             s_2 = s_1;
277             s_1 = av_clip_int16(s);
278             *out = s_1;
279             out += inc;
280         }
281
282         if (inc==2) { /* stereo */
283             left->sample1 = s_1;
284             left->sample2 = s_2;
285             s_1 = right->sample1;
286             s_2 = right->sample2;
287             out = out + 1 - 28*2;
288         }
289
290         shift  = 12 - (in[5+i*2] & 15);
291         filter = in[5+i*2] >> 4;
292
293         f0 = xa_adpcm_table[filter][0];
294         f1 = xa_adpcm_table[filter][1];
295
296         for(j=0;j<28;j++) {
297             d = in[16+i+j*4];
298
299             t = (signed char)d >> 4;
300             s = ( t<<shift ) + ((s_1*f0 + s_2*f1+32)>>6);
301             s_2 = s_1;
302             s_1 = av_clip_int16(s);
303             *out = s_1;
304             out += inc;
305         }
306
307         if (inc==2) { /* stereo */
308             right->sample1 = s_1;
309             right->sample2 = s_2;
310             out -= 1;
311         } else {
312             left->sample1 = s_1;
313             left->sample2 = s_2;
314         }
315     }
316 }
317
318
319 /* DK3 ADPCM support macro */
320 #define DK3_GET_NEXT_NIBBLE() \
321     if (decode_top_nibble_next) \
322     { \
323         nibble = last_byte >> 4; \
324         decode_top_nibble_next = 0; \
325     } \
326     else \
327     { \
328         last_byte = *src++; \
329         if (src >= buf + buf_size) break; \
330         nibble = last_byte & 0x0F; \
331         decode_top_nibble_next = 1; \
332     }
333
334 static int adpcm_decode_frame(AVCodecContext *avctx,
335                             void *data, int *data_size,
336                             AVPacket *avpkt)
337 {
338     const uint8_t *buf = avpkt->data;
339     int buf_size = avpkt->size;
340     ADPCMDecodeContext *c = avctx->priv_data;
341     ADPCMChannelStatus *cs;
342     int n, m, channel, i;
343     int block_predictor[2];
344     short *samples;
345     short *samples_end;
346     const uint8_t *src;
347     int st; /* stereo */
348
349     /* DK3 ADPCM accounting variables */
350     unsigned char last_byte = 0;
351     unsigned char nibble;
352     int decode_top_nibble_next = 0;
353     int diff_channel;
354
355     /* EA ADPCM state variables */
356     uint32_t samples_in_chunk;
357     int32_t previous_left_sample, previous_right_sample;
358     int32_t current_left_sample, current_right_sample;
359     int32_t next_left_sample, next_right_sample;
360     int32_t coeff1l, coeff2l, coeff1r, coeff2r;
361     uint8_t shift_left, shift_right;
362     int count1, count2;
363     int coeff[2][2], shift[2];//used in EA MAXIS ADPCM
364
365     if (!buf_size)
366         return 0;
367
368     //should protect all 4bit ADPCM variants
369     //8 is needed for CODEC_ID_ADPCM_IMA_WAV with 2 channels
370     //
371     if(*data_size/4 < buf_size + 8)
372         return -1;
373
374     samples = data;
375     samples_end= samples + *data_size/2;
376     *data_size= 0;
377     src = buf;
378
379     st = avctx->channels == 2 ? 1 : 0;
380
381     switch(avctx->codec->id) {
382     case CODEC_ID_ADPCM_IMA_QT:
383         /* In QuickTime, IMA is encoded by chunks of 34 bytes (=64 samples).
384            Channel data is interleaved per-chunk. */
385         if (buf_size / 34 < avctx->channels) {
386             av_log(avctx, AV_LOG_ERROR, "packet is too small\n");
387             return AVERROR(EINVAL);
388         }
389         for (channel = 0; channel < avctx->channels; channel++) {
390             int16_t predictor;
391             int step_index;
392             cs = &(c->status[channel]);
393             /* (pppppp) (piiiiiii) */
394
395             /* Bits 15-7 are the _top_ 9 bits of the 16-bit initial predictor value */
396             predictor = AV_RB16(src);
397             step_index = predictor & 0x7F;
398             predictor &= 0xFF80;
399
400             src += 2;
401
402             if (cs->step_index == step_index) {
403                 int diff = (int)predictor - cs->predictor;
404                 if (diff < 0)
405                     diff = - diff;
406                 if (diff > 0x7f)
407                     goto update;
408             } else {
409             update:
410                 cs->step_index = step_index;
411                 cs->predictor = predictor;
412             }
413
414             if (cs->step_index > 88){
415                 av_log(avctx, AV_LOG_ERROR, "ERROR: step_index = %i\n", cs->step_index);
416                 cs->step_index = 88;
417             }
418
419             samples = (short*)data + channel;
420
421             for (m = 0; m < 32; m++) {
422                 *samples = adpcm_ima_qt_expand_nibble(cs, src[0] & 0x0F, 3);
423                 samples += avctx->channels;
424                 *samples = adpcm_ima_qt_expand_nibble(cs, src[0] >> 4  , 3);
425                 samples += avctx->channels;
426                 src ++;
427             }
428         }
429         if (st)
430             samples--;
431         break;
432     case CODEC_ID_ADPCM_IMA_WAV:
433         if (avctx->block_align != 0 && buf_size > avctx->block_align)
434             buf_size = avctx->block_align;
435
436 //        samples_per_block= (block_align-4*chanels)*8 / (bits_per_sample * chanels) + 1;
437
438         for(i=0; i<avctx->channels; i++){
439             cs = &(c->status[i]);
440             cs->predictor = *samples++ = (int16_t)bytestream_get_le16(&src);
441
442             cs->step_index = *src++;
443             if (cs->step_index > 88){
444                 av_log(avctx, AV_LOG_ERROR, "ERROR: step_index = %i\n", cs->step_index);
445                 cs->step_index = 88;
446             }
447             if (*src++) av_log(avctx, AV_LOG_ERROR, "unused byte should be null but is %d!!\n", src[-1]); /* unused */
448         }
449
450         while(src < buf + buf_size){
451             for (i = 0; i < avctx->channels; i++) {
452                 cs = &c->status[i];
453                 for (m = 0; m < 4; m++) {
454                     uint8_t v = *src++;
455                     *samples = adpcm_ima_expand_nibble(cs, v & 0x0F, 3);
456                     samples += avctx->channels;
457                     *samples = adpcm_ima_expand_nibble(cs, v >> 4  , 3);
458                     samples += avctx->channels;
459                 }
460                 samples -= 8 * avctx->channels - 1;
461             }
462             samples += 7 * avctx->channels;
463         }
464         break;
465     case CODEC_ID_ADPCM_4XM:
466         for (i = 0; i < avctx->channels; i++)
467             c->status[i].predictor= (int16_t)bytestream_get_le16(&src);
468
469         for (i = 0; i < avctx->channels; i++) {
470             c->status[i].step_index= (int16_t)bytestream_get_le16(&src);
471             c->status[i].step_index = av_clip(c->status[i].step_index, 0, 88);
472         }
473
474         m= (buf_size - (src - buf))>>st;
475
476         for (i = 0; i < avctx->channels; i++) {
477             samples = (short*)data + i;
478             cs = &c->status[i];
479             for (n = 0; n < m; n++) {
480                 uint8_t v = *src++;
481                 *samples = adpcm_ima_expand_nibble(cs, v & 0x0F, 4);
482                 samples += avctx->channels;
483                 *samples = adpcm_ima_expand_nibble(cs, v >> 4  , 4);
484                 samples += avctx->channels;
485             }
486         }
487         samples -= (avctx->channels - 1);
488         break;
489     case CODEC_ID_ADPCM_MS:
490         if (avctx->block_align != 0 && buf_size > avctx->block_align)
491             buf_size = avctx->block_align;
492         n = buf_size - 7 * avctx->channels;
493         if (n < 0)
494             return -1;
495         block_predictor[0] = av_clip(*src++, 0, 6);
496         block_predictor[1] = 0;
497         if (st)
498             block_predictor[1] = av_clip(*src++, 0, 6);
499         c->status[0].idelta = (int16_t)bytestream_get_le16(&src);
500         if (st){
501             c->status[1].idelta = (int16_t)bytestream_get_le16(&src);
502         }
503         c->status[0].coeff1 = ff_adpcm_AdaptCoeff1[block_predictor[0]];
504         c->status[0].coeff2 = ff_adpcm_AdaptCoeff2[block_predictor[0]];
505         c->status[1].coeff1 = ff_adpcm_AdaptCoeff1[block_predictor[1]];
506         c->status[1].coeff2 = ff_adpcm_AdaptCoeff2[block_predictor[1]];
507
508         c->status[0].sample1 = bytestream_get_le16(&src);
509         if (st) c->status[1].sample1 = bytestream_get_le16(&src);
510         c->status[0].sample2 = bytestream_get_le16(&src);
511         if (st) c->status[1].sample2 = bytestream_get_le16(&src);
512
513         *samples++ = c->status[0].sample2;
514         if (st) *samples++ = c->status[1].sample2;
515         *samples++ = c->status[0].sample1;
516         if (st) *samples++ = c->status[1].sample1;
517         for(;n>0;n--) {
518             *samples++ = adpcm_ms_expand_nibble(&c->status[0 ], src[0] >> 4  );
519             *samples++ = adpcm_ms_expand_nibble(&c->status[st], src[0] & 0x0F);
520             src ++;
521         }
522         break;
523     case CODEC_ID_ADPCM_IMA_DK4:
524         if (avctx->block_align != 0 && buf_size > avctx->block_align)
525             buf_size = avctx->block_align;
526
527         c->status[0].predictor  = (int16_t)bytestream_get_le16(&src);
528         c->status[0].step_index = *src++;
529         src++;
530         *samples++ = c->status[0].predictor;
531         if (st) {
532             c->status[1].predictor  = (int16_t)bytestream_get_le16(&src);
533             c->status[1].step_index = *src++;
534             src++;
535             *samples++ = c->status[1].predictor;
536         }
537         while (src < buf + buf_size) {
538             uint8_t v = *src++;
539             *samples++ = adpcm_ima_expand_nibble(&c->status[0 ], v >> 4  , 3);
540             *samples++ = adpcm_ima_expand_nibble(&c->status[st], v & 0x0F, 3);
541         }
542         break;
543     case CODEC_ID_ADPCM_IMA_DK3:
544         if (avctx->block_align != 0 && buf_size > avctx->block_align)
545             buf_size = avctx->block_align;
546
547         if(buf_size + 16 > (samples_end - samples)*3/8)
548             return -1;
549
550         c->status[0].predictor  = (int16_t)AV_RL16(src + 10);
551         c->status[1].predictor  = (int16_t)AV_RL16(src + 12);
552         c->status[0].step_index = src[14];
553         c->status[1].step_index = src[15];
554         /* sign extend the predictors */
555         src += 16;
556         diff_channel = c->status[1].predictor;
557
558         /* the DK3_GET_NEXT_NIBBLE macro issues the break statement when
559          * the buffer is consumed */
560         while (1) {
561
562             /* for this algorithm, c->status[0] is the sum channel and
563              * c->status[1] is the diff channel */
564
565             /* process the first predictor of the sum channel */
566             DK3_GET_NEXT_NIBBLE();
567             adpcm_ima_expand_nibble(&c->status[0], nibble, 3);
568
569             /* process the diff channel predictor */
570             DK3_GET_NEXT_NIBBLE();
571             adpcm_ima_expand_nibble(&c->status[1], nibble, 3);
572
573             /* process the first pair of stereo PCM samples */
574             diff_channel = (diff_channel + c->status[1].predictor) / 2;
575             *samples++ = c->status[0].predictor + c->status[1].predictor;
576             *samples++ = c->status[0].predictor - c->status[1].predictor;
577
578             /* process the second predictor of the sum channel */
579             DK3_GET_NEXT_NIBBLE();
580             adpcm_ima_expand_nibble(&c->status[0], nibble, 3);
581
582             /* process the second pair of stereo PCM samples */
583             diff_channel = (diff_channel + c->status[1].predictor) / 2;
584             *samples++ = c->status[0].predictor + c->status[1].predictor;
585             *samples++ = c->status[0].predictor - c->status[1].predictor;
586         }
587         break;
588     case CODEC_ID_ADPCM_IMA_ISS:
589         c->status[0].predictor  = (int16_t)AV_RL16(src + 0);
590         c->status[0].step_index = src[2];
591         src += 4;
592         if(st) {
593             c->status[1].predictor  = (int16_t)AV_RL16(src + 0);
594             c->status[1].step_index = src[2];
595             src += 4;
596         }
597
598         while (src < buf + buf_size) {
599             uint8_t v1, v2;
600             uint8_t v = *src++;
601             /* nibbles are swapped for mono */
602             if (st) {
603                 v1 = v >> 4;
604                 v2 = v & 0x0F;
605             } else {
606                 v2 = v >> 4;
607                 v1 = v & 0x0F;
608             }
609             *samples++ = adpcm_ima_expand_nibble(&c->status[0 ], v1, 3);
610             *samples++ = adpcm_ima_expand_nibble(&c->status[st], v2, 3);
611         }
612         break;
613     case CODEC_ID_ADPCM_IMA_WS:
614         while (src < buf + buf_size) {
615             uint8_t v = *src++;
616             *samples++ = adpcm_ima_expand_nibble(&c->status[0],  v >> 4  , 3);
617             *samples++ = adpcm_ima_expand_nibble(&c->status[st], v & 0x0F, 3);
618         }
619         break;
620     case CODEC_ID_ADPCM_XA:
621         while (buf_size >= 128) {
622             xa_decode(samples, src, &c->status[0], &c->status[1],
623                 avctx->channels);
624             src += 128;
625             samples += 28 * 8;
626             buf_size -= 128;
627         }
628         break;
629     case CODEC_ID_ADPCM_IMA_EA_EACS:
630         samples_in_chunk = bytestream_get_le32(&src) >> (1-st);
631
632         if (samples_in_chunk > buf_size-4-(8<<st)) {
633             src += buf_size - 4;
634             break;
635         }
636
637         for (i=0; i<=st; i++)
638             c->status[i].step_index = bytestream_get_le32(&src);
639         for (i=0; i<=st; i++)
640             c->status[i].predictor  = bytestream_get_le32(&src);
641
642         for (; samples_in_chunk; samples_in_chunk--, src++) {
643             *samples++ = adpcm_ima_expand_nibble(&c->status[0],  *src>>4,   3);
644             *samples++ = adpcm_ima_expand_nibble(&c->status[st], *src&0x0F, 3);
645         }
646         break;
647     case CODEC_ID_ADPCM_IMA_EA_SEAD:
648         for (; src < buf+buf_size; src++) {
649             *samples++ = adpcm_ima_expand_nibble(&c->status[0], src[0] >> 4, 6);
650             *samples++ = adpcm_ima_expand_nibble(&c->status[st],src[0]&0x0F, 6);
651         }
652         break;
653     case CODEC_ID_ADPCM_EA:
654         /* Each EA ADPCM frame has a 12-byte header followed by 30-byte pieces,
655            each coding 28 stereo samples. */
656         if (buf_size < 12) {
657             av_log(avctx, AV_LOG_ERROR, "frame too small\n");
658             return AVERROR(EINVAL);
659         }
660         samples_in_chunk = AV_RL32(src);
661         if (samples_in_chunk / 28 > (buf_size - 12) / 30) {
662             av_log(avctx, AV_LOG_ERROR, "invalid frame\n");
663             return AVERROR(EINVAL);
664         }
665         src += 4;
666         current_left_sample   = (int16_t)bytestream_get_le16(&src);
667         previous_left_sample  = (int16_t)bytestream_get_le16(&src);
668         current_right_sample  = (int16_t)bytestream_get_le16(&src);
669         previous_right_sample = (int16_t)bytestream_get_le16(&src);
670
671         for (count1 = 0; count1 < samples_in_chunk/28;count1++) {
672             coeff1l = ea_adpcm_table[ *src >> 4       ];
673             coeff2l = ea_adpcm_table[(*src >> 4  ) + 4];
674             coeff1r = ea_adpcm_table[*src & 0x0F];
675             coeff2r = ea_adpcm_table[(*src & 0x0F) + 4];
676             src++;
677
678             shift_left  = (*src >> 4  ) + 8;
679             shift_right = (*src & 0x0F) + 8;
680             src++;
681
682             for (count2 = 0; count2 < 28; count2++) {
683                 next_left_sample  = (int32_t)((*src & 0xF0) << 24) >> shift_left;
684                 next_right_sample = (int32_t)((*src & 0x0F) << 28) >> shift_right;
685                 src++;
686
687                 next_left_sample = (next_left_sample +
688                     (current_left_sample * coeff1l) +
689                     (previous_left_sample * coeff2l) + 0x80) >> 8;
690                 next_right_sample = (next_right_sample +
691                     (current_right_sample * coeff1r) +
692                     (previous_right_sample * coeff2r) + 0x80) >> 8;
693
694                 previous_left_sample = current_left_sample;
695                 current_left_sample = av_clip_int16(next_left_sample);
696                 previous_right_sample = current_right_sample;
697                 current_right_sample = av_clip_int16(next_right_sample);
698                 *samples++ = (unsigned short)current_left_sample;
699                 *samples++ = (unsigned short)current_right_sample;
700             }
701         }
702
703         if (src - buf == buf_size - 2)
704             src += 2; // Skip terminating 0x0000
705
706         break;
707     case CODEC_ID_ADPCM_EA_MAXIS_XA:
708         for(channel = 0; channel < avctx->channels; channel++) {
709             for (i=0; i<2; i++)
710                 coeff[channel][i] = ea_adpcm_table[(*src >> 4) + 4*i];
711             shift[channel] = (*src & 0x0F) + 8;
712             src++;
713         }
714         for (count1 = 0; count1 < (buf_size - avctx->channels) / avctx->channels; count1++) {
715             for(i = 4; i >= 0; i-=4) { /* Pairwise samples LL RR (st) or LL LL (mono) */
716                 for(channel = 0; channel < avctx->channels; channel++) {
717                     int32_t sample = (int32_t)(((*(src+channel) >> i) & 0x0F) << 0x1C) >> shift[channel];
718                     sample = (sample +
719                              c->status[channel].sample1 * coeff[channel][0] +
720                              c->status[channel].sample2 * coeff[channel][1] + 0x80) >> 8;
721                     c->status[channel].sample2 = c->status[channel].sample1;
722                     c->status[channel].sample1 = av_clip_int16(sample);
723                     *samples++ = c->status[channel].sample1;
724                 }
725             }
726             src+=avctx->channels;
727         }
728         break;
729     case CODEC_ID_ADPCM_EA_R1:
730     case CODEC_ID_ADPCM_EA_R2:
731     case CODEC_ID_ADPCM_EA_R3: {
732         /* channel numbering
733            2chan: 0=fl, 1=fr
734            4chan: 0=fl, 1=rl, 2=fr, 3=rr
735            6chan: 0=fl, 1=c,  2=fr, 3=rl,  4=rr, 5=sub */
736         const int big_endian = avctx->codec->id == CODEC_ID_ADPCM_EA_R3;
737         int32_t previous_sample, current_sample, next_sample;
738         int32_t coeff1, coeff2;
739         uint8_t shift;
740         unsigned int channel;
741         uint16_t *samplesC;
742         const uint8_t *srcC;
743         const uint8_t *src_end = buf + buf_size;
744
745         samples_in_chunk = (big_endian ? bytestream_get_be32(&src)
746                                        : bytestream_get_le32(&src)) / 28;
747         if (samples_in_chunk > UINT32_MAX/(28*avctx->channels) ||
748             28*samples_in_chunk*avctx->channels > samples_end-samples) {
749             src += buf_size - 4;
750             break;
751         }
752
753         for (channel=0; channel<avctx->channels; channel++) {
754             int32_t offset = (big_endian ? bytestream_get_be32(&src)
755                                          : bytestream_get_le32(&src))
756                            + (avctx->channels-channel-1) * 4;
757
758             if ((offset < 0) || (offset >= src_end - src - 4)) break;
759             srcC  = src + offset;
760             samplesC = samples + channel;
761
762             if (avctx->codec->id == CODEC_ID_ADPCM_EA_R1) {
763                 current_sample  = (int16_t)bytestream_get_le16(&srcC);
764                 previous_sample = (int16_t)bytestream_get_le16(&srcC);
765             } else {
766                 current_sample  = c->status[channel].predictor;
767                 previous_sample = c->status[channel].prev_sample;
768             }
769
770             for (count1=0; count1<samples_in_chunk; count1++) {
771                 if (*srcC == 0xEE) {  /* only seen in R2 and R3 */
772                     srcC++;
773                     if (srcC > src_end - 30*2) break;
774                     current_sample  = (int16_t)bytestream_get_be16(&srcC);
775                     previous_sample = (int16_t)bytestream_get_be16(&srcC);
776
777                     for (count2=0; count2<28; count2++) {
778                         *samplesC = (int16_t)bytestream_get_be16(&srcC);
779                         samplesC += avctx->channels;
780                     }
781                 } else {
782                     coeff1 = ea_adpcm_table[ *srcC>>4     ];
783                     coeff2 = ea_adpcm_table[(*srcC>>4) + 4];
784                     shift = (*srcC++ & 0x0F) + 8;
785
786                     if (srcC > src_end - 14) break;
787                     for (count2=0; count2<28; count2++) {
788                         if (count2 & 1)
789                             next_sample = (int32_t)((*srcC++ & 0x0F) << 28) >> shift;
790                         else
791                             next_sample = (int32_t)((*srcC   & 0xF0) << 24) >> shift;
792
793                         next_sample += (current_sample  * coeff1) +
794                                        (previous_sample * coeff2);
795                         next_sample = av_clip_int16(next_sample >> 8);
796
797                         previous_sample = current_sample;
798                         current_sample  = next_sample;
799                         *samplesC = current_sample;
800                         samplesC += avctx->channels;
801                     }
802                 }
803             }
804
805             if (avctx->codec->id != CODEC_ID_ADPCM_EA_R1) {
806                 c->status[channel].predictor   = current_sample;
807                 c->status[channel].prev_sample = previous_sample;
808             }
809         }
810
811         src = src + buf_size - (4 + 4*avctx->channels);
812         samples += 28 * samples_in_chunk * avctx->channels;
813         break;
814     }
815     case CODEC_ID_ADPCM_EA_XAS:
816         if (samples_end-samples < 32*4*avctx->channels
817             || buf_size < (4+15)*4*avctx->channels) {
818             src += buf_size;
819             break;
820         }
821         for (channel=0; channel<avctx->channels; channel++) {
822             int coeff[2][4], shift[4];
823             short *s2, *s = &samples[channel];
824             for (n=0; n<4; n++, s+=32*avctx->channels) {
825                 for (i=0; i<2; i++)
826                     coeff[i][n] = ea_adpcm_table[(src[0]&0x0F)+4*i];
827                 shift[n] = (src[2]&0x0F) + 8;
828                 for (s2=s, i=0; i<2; i++, src+=2, s2+=avctx->channels)
829                     s2[0] = (src[0]&0xF0) + (src[1]<<8);
830             }
831
832             for (m=2; m<32; m+=2) {
833                 s = &samples[m*avctx->channels + channel];
834                 for (n=0; n<4; n++, src++, s+=32*avctx->channels) {
835                     for (s2=s, i=0; i<8; i+=4, s2+=avctx->channels) {
836                         int level = (int32_t)((*src & (0xF0>>i)) << (24+i)) >> shift[n];
837                         int pred  = s2[-1*avctx->channels] * coeff[0][n]
838                                   + s2[-2*avctx->channels] * coeff[1][n];
839                         s2[0] = av_clip_int16((level + pred + 0x80) >> 8);
840                     }
841                 }
842             }
843         }
844         samples += 32*4*avctx->channels;
845         break;
846     case CODEC_ID_ADPCM_IMA_AMV:
847     case CODEC_ID_ADPCM_IMA_SMJPEG:
848         c->status[0].predictor = (int16_t)bytestream_get_le16(&src);
849         c->status[0].step_index = bytestream_get_le16(&src);
850
851         if (avctx->codec->id == CODEC_ID_ADPCM_IMA_AMV)
852             src+=4;
853
854         while (src < buf + buf_size) {
855             char hi, lo;
856             lo = *src & 0x0F;
857             hi = *src >> 4;
858
859             if (avctx->codec->id == CODEC_ID_ADPCM_IMA_AMV)
860                 FFSWAP(char, hi, lo);
861
862             *samples++ = adpcm_ima_expand_nibble(&c->status[0],
863                 lo, 3);
864             *samples++ = adpcm_ima_expand_nibble(&c->status[0],
865                 hi, 3);
866             src++;
867         }
868         break;
869     case CODEC_ID_ADPCM_CT:
870         while (src < buf + buf_size) {
871             uint8_t v = *src++;
872             *samples++ = adpcm_ct_expand_nibble(&c->status[0 ], v >> 4  );
873             *samples++ = adpcm_ct_expand_nibble(&c->status[st], v & 0x0F);
874         }
875         break;
876     case CODEC_ID_ADPCM_SBPRO_4:
877     case CODEC_ID_ADPCM_SBPRO_3:
878     case CODEC_ID_ADPCM_SBPRO_2:
879         if (!c->status[0].step_index) {
880             /* the first byte is a raw sample */
881             *samples++ = 128 * (*src++ - 0x80);
882             if (st)
883               *samples++ = 128 * (*src++ - 0x80);
884             c->status[0].step_index = 1;
885         }
886         if (avctx->codec->id == CODEC_ID_ADPCM_SBPRO_4) {
887             while (src < buf + buf_size) {
888                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
889                     src[0] >> 4, 4, 0);
890                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],
891                     src[0] & 0x0F, 4, 0);
892                 src++;
893             }
894         } else if (avctx->codec->id == CODEC_ID_ADPCM_SBPRO_3) {
895             while (src < buf + buf_size && samples + 2 < samples_end) {
896                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
897                      src[0] >> 5        , 3, 0);
898                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
899                     (src[0] >> 2) & 0x07, 3, 0);
900                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
901                     src[0] & 0x03, 2, 0);
902                 src++;
903             }
904         } else {
905             while (src < buf + buf_size && samples + 3 < samples_end) {
906                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
907                      src[0] >> 6        , 2, 2);
908                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],
909                     (src[0] >> 4) & 0x03, 2, 2);
910                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[0],
911                     (src[0] >> 2) & 0x03, 2, 2);
912                 *samples++ = adpcm_sbpro_expand_nibble(&c->status[st],
913                     src[0] & 0x03, 2, 2);
914                 src++;
915             }
916         }
917         break;
918     case CODEC_ID_ADPCM_SWF:
919     {
920         GetBitContext gb;
921         const int *table;
922         int k0, signmask, nb_bits, count;
923         int size = buf_size*8;
924
925         init_get_bits(&gb, buf, size);
926
927         //read bits & initial values
928         nb_bits = get_bits(&gb, 2)+2;
929         //av_log(NULL,AV_LOG_INFO,"nb_bits: %d\n", nb_bits);
930         table = swf_index_tables[nb_bits-2];
931         k0 = 1 << (nb_bits-2);
932         signmask = 1 << (nb_bits-1);
933
934         while (get_bits_count(&gb) <= size - 22*avctx->channels) {
935             for (i = 0; i < avctx->channels; i++) {
936                 *samples++ = c->status[i].predictor = get_sbits(&gb, 16);
937                 c->status[i].step_index = get_bits(&gb, 6);
938             }
939
940             for (count = 0; get_bits_count(&gb) <= size - nb_bits*avctx->channels && count < 4095; count++) {
941                 int i;
942
943                 for (i = 0; i < avctx->channels; i++) {
944                     // similar to IMA adpcm
945                     int delta = get_bits(&gb, nb_bits);
946                     int step = ff_adpcm_step_table[c->status[i].step_index];
947                     long vpdiff = 0; // vpdiff = (delta+0.5)*step/4
948                     int k = k0;
949
950                     do {
951                         if (delta & k)
952                             vpdiff += step;
953                         step >>= 1;
954                         k >>= 1;
955                     } while(k);
956                     vpdiff += step;
957
958                     if (delta & signmask)
959                         c->status[i].predictor -= vpdiff;
960                     else
961                         c->status[i].predictor += vpdiff;
962
963                     c->status[i].step_index += table[delta & (~signmask)];
964
965                     c->status[i].step_index = av_clip(c->status[i].step_index, 0, 88);
966                     c->status[i].predictor = av_clip_int16(c->status[i].predictor);
967
968                     *samples++ = c->status[i].predictor;
969                     if (samples >= samples_end) {
970                         av_log(avctx, AV_LOG_ERROR, "allocated output buffer is too small\n");
971                         return -1;
972                     }
973                 }
974             }
975         }
976         src += buf_size;
977         break;
978     }
979     case CODEC_ID_ADPCM_YAMAHA:
980         while (src < buf + buf_size) {
981             uint8_t v = *src++;
982             *samples++ = adpcm_yamaha_expand_nibble(&c->status[0 ], v & 0x0F);
983             *samples++ = adpcm_yamaha_expand_nibble(&c->status[st], v >> 4  );
984         }
985         break;
986     case CODEC_ID_ADPCM_THP:
987     {
988         int table[2][16];
989         unsigned int samplecnt;
990         int prev[2][2];
991         int ch;
992
993         if (buf_size < 80) {
994             av_log(avctx, AV_LOG_ERROR, "frame too small\n");
995             return -1;
996         }
997
998         src+=4;
999         samplecnt = bytestream_get_be32(&src);
1000
1001         for (i = 0; i < 32; i++)
1002             table[0][i] = (int16_t)bytestream_get_be16(&src);
1003
1004         /* Initialize the previous sample.  */
1005         for (i = 0; i < 4; i++)
1006             prev[0][i] = (int16_t)bytestream_get_be16(&src);
1007
1008         if (samplecnt >= (samples_end - samples) /  (st + 1)) {
1009             av_log(avctx, AV_LOG_ERROR, "allocated output buffer is too small\n");
1010             return -1;
1011         }
1012
1013         for (ch = 0; ch <= st; ch++) {
1014             samples = (unsigned short *) data + ch;
1015
1016             /* Read in every sample for this channel.  */
1017             for (i = 0; i < samplecnt / 14; i++) {
1018                 int index = (*src >> 4) & 7;
1019                 unsigned int exp = 28 - (*src++ & 15);
1020                 int factor1 = table[ch][index * 2];
1021                 int factor2 = table[ch][index * 2 + 1];
1022
1023                 /* Decode 14 samples.  */
1024                 for (n = 0; n < 14; n++) {
1025                     int32_t sampledat;
1026                     if(n&1) sampledat=  *src++    <<28;
1027                     else    sampledat= (*src&0xF0)<<24;
1028
1029                     sampledat = ((prev[ch][0]*factor1
1030                                 + prev[ch][1]*factor2) >> 11) + (sampledat>>exp);
1031                     *samples = av_clip_int16(sampledat);
1032                     prev[ch][1] = prev[ch][0];
1033                     prev[ch][0] = *samples++;
1034
1035                     /* In case of stereo, skip one sample, this sample
1036                        is for the other channel.  */
1037                     samples += st;
1038                 }
1039             }
1040         }
1041
1042         /* In the previous loop, in case stereo is used, samples is
1043            increased exactly one time too often.  */
1044         samples -= st;
1045         break;
1046     }
1047
1048     default:
1049         return -1;
1050     }
1051     *data_size = (uint8_t *)samples - (uint8_t *)data;
1052     return src - buf;
1053 }
1054
1055
1056 #define ADPCM_DECODER(id_, name_, long_name_)               \
1057 AVCodec ff_ ## name_ ## _decoder = {                        \
1058     .name           = #name_,                               \
1059     .type           = AVMEDIA_TYPE_AUDIO,                   \
1060     .id             = id_,                                  \
1061     .priv_data_size = sizeof(ADPCMDecodeContext),           \
1062     .init           = adpcm_decode_init,                    \
1063     .decode         = adpcm_decode_frame,                   \
1064     .long_name      = NULL_IF_CONFIG_SMALL(long_name_),     \
1065 }
1066
1067 /* Note: Do not forget to add new entries to the Makefile as well. */
1068 ADPCM_DECODER(CODEC_ID_ADPCM_4XM, adpcm_4xm, "ADPCM 4X Movie");
1069 ADPCM_DECODER(CODEC_ID_ADPCM_CT, adpcm_ct, "ADPCM Creative Technology");
1070 ADPCM_DECODER(CODEC_ID_ADPCM_EA, adpcm_ea, "ADPCM Electronic Arts");
1071 ADPCM_DECODER(CODEC_ID_ADPCM_EA_MAXIS_XA, adpcm_ea_maxis_xa, "ADPCM Electronic Arts Maxis CDROM XA");
1072 ADPCM_DECODER(CODEC_ID_ADPCM_EA_R1, adpcm_ea_r1, "ADPCM Electronic Arts R1");
1073 ADPCM_DECODER(CODEC_ID_ADPCM_EA_R2, adpcm_ea_r2, "ADPCM Electronic Arts R2");
1074 ADPCM_DECODER(CODEC_ID_ADPCM_EA_R3, adpcm_ea_r3, "ADPCM Electronic Arts R3");
1075 ADPCM_DECODER(CODEC_ID_ADPCM_EA_XAS, adpcm_ea_xas, "ADPCM Electronic Arts XAS");
1076 ADPCM_DECODER(CODEC_ID_ADPCM_IMA_AMV, adpcm_ima_amv, "ADPCM IMA AMV");
1077 ADPCM_DECODER(CODEC_ID_ADPCM_IMA_DK3, adpcm_ima_dk3, "ADPCM IMA Duck DK3");
1078 ADPCM_DECODER(CODEC_ID_ADPCM_IMA_DK4, adpcm_ima_dk4, "ADPCM IMA Duck DK4");
1079 ADPCM_DECODER(CODEC_ID_ADPCM_IMA_EA_EACS, adpcm_ima_ea_eacs, "ADPCM IMA Electronic Arts EACS");
1080 ADPCM_DECODER(CODEC_ID_ADPCM_IMA_EA_SEAD, adpcm_ima_ea_sead, "ADPCM IMA Electronic Arts SEAD");
1081 ADPCM_DECODER(CODEC_ID_ADPCM_IMA_ISS, adpcm_ima_iss, "ADPCM IMA Funcom ISS");
1082 ADPCM_DECODER(CODEC_ID_ADPCM_IMA_QT, adpcm_ima_qt, "ADPCM IMA QuickTime");
1083 ADPCM_DECODER(CODEC_ID_ADPCM_IMA_SMJPEG, adpcm_ima_smjpeg, "ADPCM IMA Loki SDL MJPEG");
1084 ADPCM_DECODER(CODEC_ID_ADPCM_IMA_WAV, adpcm_ima_wav, "ADPCM IMA WAV");
1085 ADPCM_DECODER(CODEC_ID_ADPCM_IMA_WS, adpcm_ima_ws, "ADPCM IMA Westwood");
1086 ADPCM_DECODER(CODEC_ID_ADPCM_MS, adpcm_ms, "ADPCM Microsoft");
1087 ADPCM_DECODER(CODEC_ID_ADPCM_SBPRO_2, adpcm_sbpro_2, "ADPCM Sound Blaster Pro 2-bit");
1088 ADPCM_DECODER(CODEC_ID_ADPCM_SBPRO_3, adpcm_sbpro_3, "ADPCM Sound Blaster Pro 2.6-bit");
1089 ADPCM_DECODER(CODEC_ID_ADPCM_SBPRO_4, adpcm_sbpro_4, "ADPCM Sound Blaster Pro 4-bit");
1090 ADPCM_DECODER(CODEC_ID_ADPCM_SWF, adpcm_swf, "ADPCM Shockwave Flash");
1091 ADPCM_DECODER(CODEC_ID_ADPCM_THP, adpcm_thp, "ADPCM Nintendo Gamecube THP");
1092 ADPCM_DECODER(CODEC_ID_ADPCM_XA, adpcm_xa, "ADPCM CDROM XA");
1093 ADPCM_DECODER(CODEC_ID_ADPCM_YAMAHA, adpcm_yamaha, "ADPCM Yamaha");