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