adpcm.c

Go to the documentation of this file.
00001 /*
00002  * ADPCM codecs
00003  * Copyright (c) 2001-2003 The ffmpeg Project
00004  *
00005  * This file is part of FFmpeg.
00006  *
00007  * FFmpeg is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * FFmpeg is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with FFmpeg; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 #include "avcodec.h"
00022 #include "bitstream.h"
00023 #include "bytestream.h"
00024 
00025 /**
00026  * @file adpcm.c
00027  * ADPCM codecs.
00028  * First version by Francois Revol (revol@free.fr)
00029  * Fringe ADPCM codecs (e.g., DK3, DK4, Westwood)
00030  *   by Mike Melanson (melanson@pcisys.net)
00031  * CD-ROM XA ADPCM codec by BERO
00032  * EA ADPCM decoder by Robin Kay (komadori@myrealbox.com)
00033  * EA ADPCM R1/R2/R3 decoder by Peter Ross (pross@xvid.org)
00034  * EA IMA EACS decoder by Peter Ross (pross@xvid.org)
00035  * EA IMA SEAD decoder by Peter Ross (pross@xvid.org)
00036  * EA ADPCM XAS decoder by Peter Ross (pross@xvid.org)
00037  * MAXIS EA ADPCM decoder by Robert Marston (rmarston@gmail.com)
00038  * THP ADPCM decoder by Marco Gerards (mgerards@xs4all.nl)
00039  *
00040  * Features and limitations:
00041  *
00042  * Reference documents:
00043  * http://www.pcisys.net/~melanson/codecs/simpleaudio.html
00044  * http://www.geocities.com/SiliconValley/8682/aud3.txt
00045  * http://openquicktime.sourceforge.net/plugins.htm
00046  * XAnim sources (xa_codec.c) http://www.rasnaimaging.com/people/lapus/download.html
00047  * http://www.cs.ucla.edu/~leec/mediabench/applications.html
00048  * SoX source code http://home.sprynet.com/~cbagwell/sox.html
00049  *
00050  * CD-ROM XA:
00051  * http://ku-www.ss.titech.ac.jp/~yatsushi/xaadpcm.html
00052  * vagpack & depack http://homepages.compuserve.de/bITmASTER32/psx-index.html
00053  * readstr http://www.geocities.co.jp/Playtown/2004/
00054  */
00055 
00056 #define BLKSIZE 1024
00057 
00058 /* step_table[] and index_table[] are from the ADPCM reference source */
00059 /* This is the index table: */
00060 static const int index_table[16] = {
00061     -1, -1, -1, -1, 2, 4, 6, 8,
00062     -1, -1, -1, -1, 2, 4, 6, 8,
00063 };
00064 
00065 /**
00066  * This is the step table. Note that many programs use slight deviations from
00067  * this table, but such deviations are negligible:
00068  */
00069 static const int step_table[89] = {
00070     7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
00071     19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
00072     50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
00073     130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
00074     337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
00075     876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
00076     2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
00077     5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
00078     15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
00079 };
00080 
00081 /* These are for MS-ADPCM */
00082 /* AdaptationTable[], AdaptCoeff1[], and AdaptCoeff2[] are from libsndfile */
00083 static const int AdaptationTable[] = {
00084         230, 230, 230, 230, 307, 409, 512, 614,
00085         768, 614, 512, 409, 307, 230, 230, 230
00086 };
00087 
00088 static const uint8_t AdaptCoeff1[] = {
00089         64, 128, 0, 48, 60, 115, 98
00090 };
00091 
00092 static const int8_t AdaptCoeff2[] = {
00093         0, -64, 0, 16, 0, -52, -58
00094 };
00095 
00096 /* These are for CD-ROM XA ADPCM */
00097 static const int xa_adpcm_table[5][2] = {
00098    {   0,   0 },
00099    {  60,   0 },
00100    { 115, -52 },
00101    {  98, -55 },
00102    { 122, -60 }
00103 };
00104 
00105 static const int ea_adpcm_table[] = {
00106     0, 240, 460, 392, 0, 0, -208, -220, 0, 1,
00107     3, 4, 7, 8, 10, 11, 0, -1, -3, -4
00108 };
00109 
00110 static const int ct_adpcm_table[8] = {
00111     0x00E6, 0x00E6, 0x00E6, 0x00E6,
00112     0x0133, 0x0199, 0x0200, 0x0266
00113 };
00114 
00115 // padded to zero where table size is less then 16
00116 static const int swf_index_tables[4][16] = {
00117     /*2*/ { -1, 2 },
00118     /*3*/ { -1, -1, 2, 4 },
00119     /*4*/ { -1, -1, -1, -1, 2, 4, 6, 8 },
00120     /*5*/ { -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 4, 6, 8, 10, 13, 16 }
00121 };
00122 
00123 static const int yamaha_indexscale[] = {
00124     230, 230, 230, 230, 307, 409, 512, 614,
00125     230, 230, 230, 230, 307, 409, 512, 614
00126 };
00127 
00128 static const int yamaha_difflookup[] = {
00129     1, 3, 5, 7, 9, 11, 13, 15,
00130     -1, -3, -5, -7, -9, -11, -13, -15
00131 };
00132 
00133 /* end of tables */
00134 
00135 typedef struct ADPCMChannelStatus {
00136     int predictor;
00137     short int step_index;
00138     int step;
00139     /* for encoding */
00140     int prev_sample;
00141 
00142     /* MS version */
00143     short sample1;
00144     short sample2;
00145     int coeff1;
00146     int coeff2;
00147     int idelta;
00148 } ADPCMChannelStatus;
00149 
00150 typedef struct ADPCMContext {
00151     ADPCMChannelStatus status[6];
00152 } ADPCMContext;
00153 
00154 /* XXX: implement encoding */
00155 
00156 #ifdef CONFIG_ENCODERS
00157 static int adpcm_encode_init(AVCodecContext *avctx)
00158 {
00159     if (avctx->channels > 2)
00160         return -1; /* only stereo or mono =) */
00161 
00162     if(avctx->trellis && (unsigned)avctx->trellis > 16U){
00163         av_log(avctx, AV_LOG_ERROR, "invalid trellis size\n");
00164         return -1;
00165     }
00166 
00167     switch(avctx->codec->id) {
00168     case CODEC_ID_ADPCM_IMA_WAV:
00169         avctx->frame_size = (BLKSIZE - 4 * avctx->channels) * 8 / (4 * avctx->channels) + 1; /* each 16 bits sample gives one nibble */
00170                                                              /* and we have 4 bytes per channel overhead */
00171         avctx->block_align = BLKSIZE;
00172         /* seems frame_size isn't taken into account... have to buffer the samples :-( */
00173         break;
00174     case CODEC_ID_ADPCM_IMA_QT:
00175         avctx->frame_size = 64;
00176         avctx->block_align = 34 * avctx->channels;
00177         break;
00178     case CODEC_ID_ADPCM_MS:
00179         avctx->frame_size = (BLKSIZE - 7 * avctx->channels) * 2 / avctx->channels + 2; /* each 16 bits sample gives one nibble */
00180                                                              /* and we have 7 bytes per channel overhead */
00181         avctx->block_align = BLKSIZE;
00182         break;
00183     case CODEC_ID_ADPCM_YAMAHA:
00184         avctx->frame_size = BLKSIZE * avctx->channels;
00185         avctx->block_align = BLKSIZE;
00186         break;
00187     case CODEC_ID_ADPCM_SWF:
00188         if (avctx->sample_rate != 11025 &&
00189             avctx->sample_rate != 22050 &&
00190             avctx->sample_rate != 44100) {
00191             av_log(avctx, AV_LOG_ERROR, "Sample rate must be 11025, 22050 or 44100\n");
00192             return -1;
00193         }
00194         avctx->frame_size = 512 * (avctx->sample_rate / 11025);
00195         break;
00196     default:
00197         return -1;
00198         break;
00199     }
00200 
00201     avctx->coded_frame= avcodec_alloc_frame();
00202     avctx->coded_frame->key_frame= 1;
00203 
00204     return 0;
00205 }
00206 
00207 static int adpcm_encode_close(AVCodecContext *avctx)
00208 {
00209     av_freep(&avctx->coded_frame);
00210 
00211     return 0;
00212 }
00213 
00214 
00215 static inline unsigned char adpcm_ima_compress_sample(ADPCMChannelStatus *c, short sample)
00216 {
00217     int delta = sample - c->prev_sample;
00218     int nibble = FFMIN(7, abs(delta)*4/step_table[c->step_index]) + (delta<0)*8;
00219     c->prev_sample += ((step_table[c->step_index] * yamaha_difflookup[nibble]) / 8);
00220     c->prev_sample = av_clip_int16(c->prev_sample);
00221     c->step_index = av_clip(c->step_index + index_table[nibble], 0, 88);
00222     return nibble;
00223 }
00224 
00225 static inline unsigned char adpcm_ms_compress_sample(ADPCMChannelStatus *c, short sample)
00226 {
00227     int predictor, nibble, bias;
00228 
00229     predictor = (((c->sample1) * (c->coeff1)) + ((c->sample2) * (c->coeff2))) / 64;
00230 
00231     nibble= sample - predictor;
00232     if(nibble>=0) bias= c->idelta/2;
00233     else          bias=-c->idelta/2;
00234 
00235     nibble= (nibble + bias) / c->idelta;
00236     nibble= av_clip(nibble, -8, 7)&0x0F;
00237 
00238     predictor += (signed)((nibble & 0x08)?(nibble - 0x10):(nibble)) * c->idelta;
00239 
00240     c->sample2 = c->sample1;
00241     c->sample1 = av_clip_int16(predictor);
00242 
00243     c->idelta = (AdaptationTable[(int)nibble] * c->idelta) >> 8;
00244     if (c->idelta < 16) c->idelta = 16;
00245 
00246     return nibble;
00247 }
00248 
00249 static inline unsigned char adpcm_yamaha_compress_sample(ADPCMChannelStatus *c, short sample)
00250 {
00251     int nibble, delta;
00252 
00253     if(!c->step) {
00254         c->predictor = 0;
00255         c->step = 127;
00256     }
00257 
00258     delta = sample - c->predictor;
00259 
00260     nibble = FFMIN(7, abs(delta)*4/c->step) + (delta<0)*8;
00261 
00262     c->predictor += ((c->step * yamaha_difflookup[nibble]) / 8);
00263     c->predictor = av_clip_int16(c->predictor);
00264     c->step = (c->step * yamaha_indexscale[nibble]) >> 8;
00265     c->step = av_clip(c->step, 127, 24567);
00266 
00267     return nibble;
00268 }
00269 
00270 typedef struct TrellisPath {
00271     int nibble;
00272     int prev;
00273 } TrellisPath;
00274 
00275 typedef struct TrellisNode {
00276     uint32_t ssd;
00277     int path;
00278     int sample1;
00279     int sample2;
00280     int step;
00281 } TrellisNode;
00282 
00283 static void adpcm_compress_trellis(AVCodecContext *avctx, const short *samples,
00284                                    uint8_t *dst, ADPCMChannelStatus *c, int n)
00285 {
00286 #define FREEZE_INTERVAL 128
00287     //FIXME 6% faster if frontier is a compile-time constant
00288     const int frontier = 1 << avctx->trellis;
00289     const int stride = avctx->channels;
00290     const int version = avctx->codec->id;
00291     const int max_paths = frontier*FREEZE_INTERVAL;
00292     TrellisPath paths[max_paths], *p;
00293     TrellisNode node_buf[2][frontier];
00294     TrellisNode *nodep_buf[2][frontier];
00295     TrellisNode **nodes = nodep_buf[0]; // nodes[] is always sorted by .ssd
00296     TrellisNode **nodes_next = nodep_buf[1];
00297     int pathn = 0, froze = -1, i, j, k;
00298 
00299     assert(!(max_paths&(max_paths-1)));
00300 
00301     memset(nodep_buf, 0, sizeof(nodep_buf));
00302     nodes[0] = &node_buf[1][0];
00303     nodes[0]->ssd = 0;
00304     nodes[0]->path = 0;
00305     nodes[0]->step = c->step_index;
00306     nodes[0]->sample1 = c->sample1;
00307     nodes[0]->sample2 = c->sample2;
00308     if((version == CODEC_ID_ADPCM_IMA_WAV) || (version == CODEC_ID_ADPCM_IMA_QT) || (version == CODEC_ID_ADPCM_SWF))
00309         nodes[0]->sample1 = c->prev_sample;
00310     if(version == CODEC_ID_ADPCM_MS)
00311         nodes[0]->step = c->idelta;
00312     if(version == CODEC_ID_ADPCM_YAMAHA) {
00313         if(c->step == 0) {
00314             nodes[0]->step = 127;
00315             nodes[0]->sample1 = 0;
00316         } else {
00317             nodes[0]->step = c->step;
00318             nodes[0]->sample1 = c->predictor;
00319         }
00320     }
00321 
00322     for(i=0; i<n; i++) {
00323         TrellisNode *t = node_buf[i&1];
00324         TrellisNode **u;
00325         int sample = samples[i*stride];
00326         memset(nodes_next, 0, frontier*sizeof(TrellisNode*));
00327         for(j=0; j<frontier && nodes[j]; j++) {
00328             // higher j have higher ssd already, so they're unlikely to use a suboptimal next sample too
00329             const int range = (j < frontier/2) ? 1 : 0;
00330             const int step = nodes[j]->step;
00331             int nidx;
00332             if(version == CODEC_ID_ADPCM_MS) {
00333                 const int predictor = ((nodes[j]->sample1 * c->coeff1) + (nodes[j]->sample2 * c->coeff2)) / 64;
00334                 const int div = (sample - predictor) / step;
00335                 const int nmin = av_clip(div-range, -8, 6);
00336                 const int nmax = av_clip(div+range, -7, 7);
00337                 for(nidx=nmin; nidx<=nmax; nidx++) {
00338                     const int nibble = nidx & 0xf;
00339                     int dec_sample = predictor + nidx * step;
00340 #define STORE_NODE(NAME, STEP_INDEX)\
00341                     int d;\
00342                     uint32_t ssd;\
00343                     dec_sample = av_clip_int16(dec_sample);\
00344                     d = sample - dec_sample;\
00345                     ssd = nodes[j]->ssd + d*d;\
00346                     if(nodes_next[frontier-1] && ssd >= nodes_next[frontier-1]->ssd)\
00347                         continue;\
00348                     /* Collapse any two states with the same previous sample value. \
00349                      * One could also distinguish states by step and by 2nd to last
00350                      * sample, but the effects of that are negligible. */\
00351                     for(k=0; k<frontier && nodes_next[k]; k++) {\
00352                         if(dec_sample == nodes_next[k]->sample1) {\
00353                             assert(ssd >= nodes_next[k]->ssd);\
00354                             goto next_##NAME;\
00355                         }\
00356                     }\
00357                     for(k=0; k<frontier; k++) {\
00358                         if(!nodes_next[k] || ssd < nodes_next[k]->ssd) {\
00359                             TrellisNode *u = nodes_next[frontier-1];\
00360                             if(!u) {\
00361                                 assert(pathn < max_paths);\
00362                                 u = t++;\
00363                                 u->path = pathn++;\
00364                             }\
00365                             u->ssd = ssd;\
00366                             u->step = STEP_INDEX;\
00367                             u->sample2 = nodes[j]->sample1;\
00368                             u->sample1 = dec_sample;\
00369                             paths[u->path].nibble = nibble;\
00370                             paths[u->path].prev = nodes[j]->path;\
00371                             memmove(&nodes_next[k+1], &nodes_next[k], (frontier-k-1)*sizeof(TrellisNode*));\
00372                             nodes_next[k] = u;\
00373                             break;\
00374                         }\
00375                     }\
00376                     next_##NAME:;
00377                     STORE_NODE(ms, FFMAX(16, (AdaptationTable[nibble] * step) >> 8));
00378                 }
00379             } else if((version == CODEC_ID_ADPCM_IMA_WAV)|| (version == CODEC_ID_ADPCM_IMA_QT)|| (version == CODEC_ID_ADPCM_SWF)) {
00380 #define LOOP_NODES(NAME, STEP_TABLE, STEP_INDEX)\
00381                 const int predictor = nodes[j]->sample1;\
00382                 const int div = (sample - predictor) * 4 / STEP_TABLE;\
00383                 int nmin = av_clip(div-range, -7, 6);\
00384                 int nmax = av_clip(div+range, -6, 7);\
00385                 if(nmin<=0) nmin--; /* distinguish -0 from +0 */\
00386                 if(nmax<0) nmax--;\
00387                 for(nidx=nmin; nidx<=nmax; nidx++) {\
00388                     const int nibble = nidx<0 ? 7-nidx : nidx;\
00389                     int dec_sample = predictor + (STEP_TABLE * yamaha_difflookup[nibble]) / 8;\
00390                     STORE_NODE(NAME, STEP_INDEX);\
00391                 }
00392                 LOOP_NODES(ima, step_table[step], av_clip(step + index_table[nibble], 0, 88));
00393             } else { //CODEC_ID_ADPCM_YAMAHA
00394                 LOOP_NODES(yamaha, step, av_clip((step * yamaha_indexscale[nibble]) >> 8, 127, 24567));
00395 #undef LOOP_NODES
00396 #undef STORE_NODE
00397             }
00398         }
00399 
00400         u = nodes;
00401         nodes = nodes_next;
00402         nodes_next = u;
00403 
00404         // prevent overflow
00405         if(nodes[0]->ssd > (1<<28)) {
00406             for(j=1; j<frontier && nodes[j]; j++)
00407                 nodes[j]->ssd -= nodes[0]->ssd;
00408             nodes[0]->ssd = 0;
00409         }
00410 
00411         // merge old paths to save memory
00412         if(i == froze + FREEZE_INTERVAL) {
00413             p = &paths[nodes[0]->path];
00414             for(k=i; k>froze; k--) {
00415                 dst[k] = p->nibble;
00416                 p = &paths[p->prev];
00417             }
00418             froze = i;
00419             pathn = 0;
00420             // other nodes might use paths that don't coincide with the frozen one.
00421             // checking which nodes do so is too slow, so just kill them all.
00422             // this also slightly improves quality, but I don't know why.
00423             memset(nodes+1, 0, (frontier-1)*sizeof(TrellisNode*));
00424         }
00425     }
00426 
00427     p = &paths[nodes[0]->path];
00428     for(i=n-1; i>froze; i--) {
00429         dst[i] = p->nibble;
00430         p = &paths[p->prev];
00431     }
00432 
00433     c->predictor = nodes[0]->sample1;
00434     c->sample1 = nodes[0]->sample1;
00435     c->sample2 = nodes[0]->sample2;
00436     c->step_index = nodes[0]->step;
00437     c->step = nodes[0]->step;
00438     c->idelta = nodes[0]->step;
00439 }
00440 
00441 static int adpcm_encode_frame(AVCodecContext *avctx,
00442                             unsigned char *frame, int buf_size, void *data)
00443 {
00444     int n, i, st;
00445     short *samples;
00446     unsigned char *dst;
00447     ADPCMContext *c = avctx->priv_data;
00448 
00449     dst = frame;
00450     samples = (short *)data;
00451     st= avctx->channels == 2;
00452 /*    n = (BLKSIZE - 4 * avctx->channels) / (2 * 8 * avctx->channels); */
00453 
00454     switch(avctx->codec->id) {
00455     case CODEC_ID_ADPCM_IMA_WAV:
00456         n = avctx->frame_size / 8;
00457             c->status[0].prev_sample = (signed short)samples[0]; /* XXX */
00458 /*            c->status[0].step_index = 0; *//* XXX: not sure how to init the state machine */
00459             bytestream_put_le16(&dst, c->status[0].prev_sample);
00460             *dst++ = (unsigned char)c->status[0].step_index;
00461             *dst++ = 0; /* unknown */
00462             samples++;
00463             if (avctx->channels == 2) {
00464                 c->status[1].prev_sample = (signed short)samples[0];
00465 /*                c->status[1].step_index = 0; */
00466                 bytestream_put_le16(&dst, c->status[1].prev_sample);
00467                 *dst++ = (unsigned char)c->status[1].step_index;
00468                 *dst++ = 0;
00469                 samples++;
00470             }
00471 
00472             /* stereo: 4 bytes (8 samples) for left, 4 bytes for right, 4 bytes left, ... */
00473             if(avctx->trellis > 0) {
00474                 uint8_t buf[2][n*8];
00475                 adpcm_compress_trellis(avctx, samples, buf[0], &c->status[0], n*8);
00476                 if(avctx->channels == 2)
00477                     adpcm_compress_trellis(avctx, samples+1, buf[1], &c->status[1], n*8);
00478                 for(i=0; i<n; i++) {
00479                     *dst++ = buf[0][8*i+0] | (buf[0][8*i+1] << 4);
00480                     *dst++ = buf[0][8*i+2] | (buf[0][8*i+3] << 4);
00481                     *dst++ = buf[0][8*i+4] | (buf[0][8*i+5] << 4);
00482                     *dst++ = buf[0][8*i+6] | (buf[0][8*i+7] << 4);
00483                     if (avctx->channels == 2) {
00484                         *dst++ = buf[1][8*i+0] | (buf[1][8*i+1] << 4);
00485                         *dst++ = buf[1][8*i+2] | (buf[1][8*i+3] << 4);
00486                         *dst++ = buf[1][8*i+4] | (buf[1][8*i+5] << 4);
00487                         *dst++ = buf[1][8*i+6] | (buf[1][8*i+7] << 4);
00488                     }
00489                 }
00490             } else
00491             for (; n>0; n--) {
00492                 *dst = adpcm_ima_compress_sample(&c->status[0], samples[0]);
00493                 *dst |= adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels]) << 4;
00494                 dst++;
00495                 *dst = adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 2]);
00496                 *dst |= adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 3]) << 4;
00497                 dst++;
00498                 *dst = adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 4]);
00499                 *dst |= adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 5]) << 4;
00500                 dst++;
00501                 *dst = adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 6]);
00502                 *dst |= adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 7]) << 4;
00503                 dst++;
00504                 /* right channel */
00505                 if (avctx->channels == 2) {
00506                     *dst = adpcm_ima_compress_sample(&c->status[1], samples[1]);
00507                     *dst |= adpcm_ima_compress_sample(&c->status[1], samples[3]) << 4;
00508                     dst++;
00509                     *dst = adpcm_ima_compress_sample(&c->status[1], samples[5]);
00510                     *dst |= adpcm_ima_compress_sample(&c->status[1], samples[7]) << 4;
00511                     dst++;
00512                     *dst = adpcm_ima_compress_sample(&c->status[1], samples[9]);
00513                     *dst |= adpcm_ima_compress_sample(&c->status[1], samples[11]) << 4;
00514                     dst++;
00515                     *dst = adpcm_ima_compress_sample(&c->status[1], samples[13]);
00516                     *dst |= adpcm_ima_compress_sample(&c->status[1], samples[15]) << 4;
00517                     dst++;
00518                 }
00519                 samples += 8 * avctx->channels;
00520             }
00521         break;
00522     case CODEC_ID_ADPCM_IMA_QT:
00523     {
00524         int ch, i;
00525         PutBitContext pb;
00526         init_put_bits(&pb, dst, buf_size*8);
00527 
00528         for(ch=0; ch<avctx->channels; ch++){
00529             put_bits(&pb, 9, (c->status[ch].prev_sample + 0x10000) >> 7);
00530             put_bits(&pb, 7, c->status[ch].step_index);
00531             if(avctx->trellis > 0) {
00532                 uint8_t buf[64];
00533                 adpcm_compress_trellis(avctx, samples+ch, buf, &c->status[ch], 64);
00534                 for(i=0; i<64; i++)
00535                     put_bits(&pb, 4, buf[i^1]);
00536                 c->status[ch].prev_sample = c->status[ch].predictor & ~0x7F;
00537             } else {
00538                 for (i=0; i<64; i+=2){
00539                     int t1, t2;
00540                     t1 = adpcm_ima_compress_sample(&c->status[ch], samples[avctx->channels*(i+0)+ch]);
00541                     t2 = adpcm_ima_compress_sample(&c->status[ch], samples[avctx->channels*(i+1)+ch]);
00542                     put_bits(&pb, 4, t2);
00543                     put_bits(&pb, 4, t1);
00544                 }
00545                 c->status[ch].prev_sample &= ~0x7F;
00546             }
00547         }
00548 
00549         dst += put_bits_count(&pb)>>3;
00550         break;
00551     }
00552     case CODEC_ID_ADPCM_SWF:
00553     {
00554         int i;
00555         PutBitContext pb;
00556         init_put_bits(&pb, dst, buf_size*8);
00557 
00558         n = avctx->frame_size-1;
00559 
00560         //Store AdpcmCodeSize
00561         put_bits(&pb, 2, 2);                //Set 4bits flash adpcm format
00562 
00563         //Init the encoder state
00564         for(i=0; i<avctx->channels; i++){
00565             c->status[i].step_index = av_clip(c->status[i].step_index, 0, 63); // clip step so it fits 6 bits
00566             put_sbits(&pb, 16, samples[i]);
00567             put_bits(&pb, 6, c->status[i].step_index);
00568             c->status[i].prev_sample = (signed short)samples[i];
00569         }
00570 
00571         if(avctx->trellis > 0) {
00572             uint8_t buf[2][n];
00573             adpcm_compress_trellis(avctx, samples+2, buf[0], &c->status[0], n);
00574             if (avctx->channels == 2)
00575                 adpcm_compress_trellis(avctx, samples+3, buf[1], &c->status[1], n);
00576             for(i=0; i<n; i++) {
00577                 put_bits(&pb, 4, buf[0][i]);
00578                 if (avctx->channels == 2)
00579                     put_bits(&pb, 4, buf[1][i]);
00580             }
00581         } else {
00582             for (i=1; i<avctx->frame_size; i++) {
00583                 put_bits(&pb, 4, adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels*i]));
00584                 if (avctx->channels == 2)
00585                     put_bits(&pb, 4, adpcm_ima_compress_sample(&c->status[1], samples[2*i+1]));
00586             }
00587         }
00588         flush_put_bits(&pb);
00589         dst += put_bits_count(&pb)>>3;
00590         break;
00591     }
00592     case CODEC_ID_ADPCM_MS:
00593         for(i=0; i<avctx->channels; i++){
00594             int predictor=0;
00595 
00596             *dst++ = predictor;
00597             c->status[i].coeff1 = AdaptCoeff1[predictor];
00598             c->status[i].coeff2 = AdaptCoeff2[predictor];
00599         }
00600         for(i=0; i<avctx->channels; i++){
00601             if (c->status[i].idelta < 16)
00602                 c->status[i].idelta = 16;
00603 
00604             bytestream_put_le16(&dst, c->status[i].idelta);
00605         }
00606         for(i=0; i<avctx->channels; i++){
00607             c->status[i].sample2= *samples++;
00608         }
00609         for(i=0; i<avctx->channels; i++){
00610             c->status[i].sample1= *samples++;
00611 
00612             bytestream_put_le16(&dst, c->status[i].sample1);
00613         }
00614         for(i=0; i<avctx->channels; i++)
00615             bytestream_put_le16(&dst, c->status[i].sample2);
00616 
00617         if(avctx->trellis > 0) {
00618             int n = avctx->block_align - 7*avctx->channels;
00619             uint8_t buf[2][n];
00620             if(avctx->channels == 1) {
00621                 n *= 2;
00622                 adpcm_compress_trellis(avctx, samples, buf[0], &c->status[0], n);
00623                 for(i=0; i<n; i+=2)
00624                     *dst++ = (buf[0][i] << 4) | buf[0][i+1];
00625             } else {
00626                 adpcm_compress_trellis(avctx, samples, buf[0], &c->status[0], n);
00627                 adpcm_compress_trellis(avctx, samples+1, buf[1], &c->status[1], n);
00628                 for(i=0; i<n; i++)
00629                     *dst++ = (buf[0][i] << 4) | buf[1][i];
00630             }
00631         } else
00632         for(i=7*avctx->channels; i<avctx->block_align; i++) {
00633             int nibble;
00634             nibble = adpcm_ms_compress_sample(&c->status[ 0], *samples++)<<4;
00635             nibble|= adpcm_ms_compress_sample(&c->status[st], *samples++);
00636             *dst++ = nibble;
00637         }
00638         break;
00639     case CODEC_ID_ADPCM_YAMAHA:
00640         n = avctx->frame_size / 2;
00641         if(avctx->trellis > 0) {
00642             uint8_t buf[2][n*2];
00643             n *= 2;
00644             if(avctx->channels == 1) {
00645                 adpcm_compress_trellis(avctx, samples, buf[0], &c->status[0], n);
00646                 for(i=0; i<n; i+=2)
00647                     *dst++ = buf[0][i] | (buf[0][i+1] << 4);
00648             } else {
00649                 adpcm_compress_trellis(avctx, samples, buf[0], &c->status[0], n);
00650                 adpcm_compress_trellis(avctx, samples+1, buf[1], &c->status[1], n);
00651                 for(i=0; i<n; i++)
00652                     *dst++ = buf[0][i] | (buf[1][i] << 4);
00653             }
00654         } else
00655         for (; n>0; n--) {
00656             for(i = 0; i < avctx->channels; i++) {
00657                 int nibble;
00658                 nibble  = adpcm_yamaha_compress_sample(&c->status[i], samples[i]);
00659                 nibble |= adpcm_yamaha_compress_sample(&c->status[i], samples[i+avctx->channels]) << 4;
00660                 *dst++ = nibble;
00661             }
00662             samples += 2 * avctx->channels;
00663         }
00664         break;
00665     default:
00666         return -1;
00667     }
00668     return dst - frame;
00669 }
00670 #endif //CONFIG_ENCODERS
00671 
00672 static av_cold int adpcm_decode_init(AVCodecContext * avctx)
00673 {
00674     ADPCMContext *c = avctx->priv_data;
00675     unsigned int max_channels = 2;
00676 
00677     switch(avctx->codec->id) {
00678     case CODEC_ID_ADPCM_EA_R1:
00679     case CODEC_ID_ADPCM_EA_R2:
00680     case CODEC_ID_ADPCM_EA_R3:
00681         max_channels = 6;
00682         break;
00683     }
00684     if(avctx->channels > max_channels){
00685         return -1;
00686     }
00687 
00688     switch(avctx->codec->id) {
00689     case CODEC_ID_ADPCM_CT:
00690         c->status[0].step = c->status[1].step = 511;
00691         break;
00692     case CODEC_ID_ADPCM_IMA_WS:
00693         if (avctx->extradata && avctx->extradata_size == 2 * 4) {
00694             c->status[0].predictor = AV_RL32(avctx->extradata);
00695             c->status[1].predictor = AV_RL32(avctx->extradata + 4);
00696         }
00697         break;
00698     default:
00699         break;
00700     }
00701     return 0;
00702 }
00703 
00704 static inline short adpcm_ima_expand_nibble(ADPCMChannelStatus *c, char nibble, int shift)
00705 {
00706     int step_index;
00707     int predictor;
00708     int sign, delta, diff, step;
00709 
00710     step = step_table[c->step_index];
00711     step_index = c->step_index + index_table[(unsigned)nibble];
00712     if (step_index < 0) step_index = 0;
00713     else if (step_index > 88) step_index = 88;
00714 
00715     sign = nibble & 8;
00716     delta = nibble & 7;
00717     /* perform direct multiplication instead of series of jumps proposed by
00718      * the reference ADPCM implementation since modern CPUs can do the mults
00719      * quickly enough */
00720     diff = ((2 * delta + 1) * step) >> shift;
00721     predictor = c->predictor;
00722     if (sign) predictor -= diff;
00723     else predictor += diff;
00724 
00725     c->predictor = av_clip_int16(predictor);
00726     c->step_index = step_index;
00727 
00728     return (short)c->predictor;
00729 }
00730 
00731 static inline short adpcm_ms_expand_nibble(ADPCMChannelStatus *c, char nibble)
00732 {
00733     int predictor;
00734 
00735     predictor = (((c->sample1) * (c->coeff1)) + ((c->sample2) * (c->coeff2))) / 64;
00736     predictor += (signed)((nibble & 0x08)?(nibble - 0x10):(nibble)) * c->idelta;
00737 
00738     c->sample2 = c->sample1;
00739     c->sample1 = av_clip_int16(predictor);
00740     c->idelta = (AdaptationTable[(int)nibble] * c->idelta) >> 8;
00741     if (c->idelta < 16) c->idelta = 16;
00742 
00743     return c->sample1;
00744 }
00745 
00746 static inline short adpcm_ct_expand_nibble(ADPCMChannelStatus *c, char nibble)
00747 {
00748     int sign, delta, diff;
00749     int new_step;
00750 
00751     sign = nibble & 8;
00752     delta = nibble & 7;
00753     /* perform direct multiplication instead of series of jumps proposed by
00754      * the reference ADPCM implementation since modern CPUs can do the mults
00755      * quickly enough */
00756     diff = ((2 * delta + 1) * c->step) >> 3;
00757     /* predictor update is not so trivial: predictor is multiplied on 254/256 before updating */
00758     c->predictor = ((c->predictor * 254) >> 8) + (sign ? -diff : diff);
00759     c->predictor = av_clip_int16(c->predictor);
00760     /* calculate new step and clamp it to range 511..32767 */
00761     new_step = (ct_adpcm_table[nibble & 7] * c->step) >> 8;
00762     c->step = av_clip(new_step, 511, 32767);
00763 
00764     return (short)c->predictor;
00765 }
00766 
00767 static inline short adpcm_sbpro_expand_nibble(ADPCMChannelStatus *c, char nibble, int size, int shift)
00768 {
00769     int sign, delta, diff;
00770 
00771     sign = nibble & (1<<(size-1));
00772     delta = nibble & ((1<<(size-1))-1);
00773     diff = delta << (7 + c->step + shift);
00774 
00775     /* clamp result */
00776     c->predictor = av_clip(c->predictor + (sign ? -diff : diff), -16384,16256);
00777 
00778     /* calculate new step */
00779     if (delta >= (2*size - 3) && c->step < 3)
00780         c->step++;
00781     else if (delta == 0 && c->step > 0)
00782         c->step--;
00783 
00784     return (short) c->predictor;
00785 }
00786 
00787 static inline short adpcm_yamaha_expand_nibble(ADPCMChannelStatus *c, unsigned char nibble)
00788 {
00789     if(!c->step) {
00790         c->predictor = 0;
00791         c->step = 127;
00792     }
00793 
00794     c->predictor += (c->step * yamaha_difflookup[nibble]) / 8;
00795     c->predictor = av_clip_int16(c->predictor);
00796     c->step = (c->step * yamaha_indexscale[nibble]) >> 8;
00797     c->step = av_clip(c->step, 127, 24567);
00798     return c->predictor;
00799 }
00800 
00801 static void xa_decode(short *out, const unsigned char *in,
00802     ADPCMChannelStatus *left, ADPCMChannelStatus *right, int inc)
00803 {
00804     int i, j;
00805     int shift,filter,f0,f1;
00806     int s_1,s_2;
00807     int d,s,t;
00808 
00809     for(i=0;i<4;i++) {
00810 
00811         shift  = 12 - (in[4+i*2] & 15);
00812         filter = in[4+i*2] >> 4;
00813         f0 = xa_adpcm_table[filter][0];
00814         f1 = xa_adpcm_table[filter][1];
00815 
00816         s_1 = left->sample1;
00817         s_2 = left->sample2;
00818 
00819         for(j=0;j<28;j++) {
00820             d = in[16+i+j*4];
00821 
00822             t = (signed char)(d<<4)>>4;
00823             s = ( t<<shift ) + ((s_1*f0 + s_2*f1+32)>>6);
00824             s_2 = s_1;
00825             s_1 = av_clip_int16(s);
00826             *out = s_1;
00827             out += inc;
00828         }
00829 
00830         if (inc==2) { /* stereo */
00831             left->sample1 = s_1;
00832             left->sample2 = s_2;
00833             s_1 = right->sample1;
00834             s_2 = right->sample2;
00835             out = out + 1 - 28*2;
00836         }
00837 
00838         shift  = 12 - (in[5+i*2] & 15);
00839         filter = in[5+i*2] >> 4;
00840 
00841         f0 = xa_adpcm_table[filter][0];
00842         f1 = xa_adpcm_table[filter][1];
00843 
00844         for(j=0;j<28;j++) {
00845             d = in[16+i+j*4];
00846 
00847             t = (signed char)d >> 4;
00848             s = ( t<<shift ) + ((s_1*f0 + s_2*f1+32)>>6);
00849             s_2 = s_1;
00850             s_1 = av_clip_int16(s);
00851             *out = s_1;
00852             out += inc;
00853         }
00854 
00855         if (inc==2) { /* stereo */
00856             right->sample1 = s_1;
00857             right->sample2 = s_2;
00858             out -= 1;
00859         } else {
00860             left->sample1 = s_1;
00861             left->sample2 = s_2;
00862         }
00863     }
00864 }
00865 
00866 
00867 /* DK3 ADPCM support macro */
00868 #define DK3_GET_NEXT_NIBBLE() \
00869     if (decode_top_nibble_next) \
00870     { \
00871         nibble = last_byte >> 4; \
00872         decode_top_nibble_next = 0; \
00873     } \
00874     else \
00875     { \
00876         last_byte = *src++; \
00877         if (src >= buf + buf_size) break; \
00878         nibble = last_byte & 0x0F; \
00879         decode_top_nibble_next = 1; \
00880     }
00881 
00882 static int adpcm_decode_frame(AVCodecContext *avctx,
00883                             void *data, int *data_size,
00884                             const uint8_t *buf, int buf_size)
00885 {
00886     ADPCMContext *c = avctx->priv_data;
00887     ADPCMChannelStatus *cs;
00888     int n, m, channel, i;
00889     int block_predictor[2];
00890     short *samples;
00891     short *samples_end;
00892     const uint8_t *src;
00893     int st; /* stereo */
00894 
00895     /* DK3 ADPCM accounting variables */
00896     unsigned char last_byte = 0;
00897     unsigned char nibble;
00898     int decode_top_nibble_next = 0;
00899     int diff_channel;
00900 
00901     /* EA ADPCM state variables */
00902     uint32_t samples_in_chunk;
00903     int32_t previous_left_sample, previous_right_sample;
00904     int32_t current_left_sample, current_right_sample;
00905     int32_t next_left_sample, next_right_sample;
00906     int32_t coeff1l, coeff2l, coeff1r, coeff2r;
00907     uint8_t shift_left, shift_right;
00908     int count1, count2;
00909     int coeff[2][2], shift[2];//used in EA MAXIS ADPCM
00910 
00911     if (!buf_size)
00912         return 0;
00913 
00914     //should protect all 4bit ADPCM variants
00915     //8 is needed for CODEC_ID_ADPCM_IMA_WAV with 2 channels
00916     //
00917     if(*data_size/4 < buf_size + 8)
00918         return -1;
00919 
00920     samples = data;
00921     samples_end= samples + *data_size/2;
00922     *data_size= 0;
00923     src = buf;
00924 
00925     st = avctx->channels == 2 ? 1 : 0;
00926 
00927     switch(avctx->codec->id) {
00928     case CODEC_ID_ADPCM_IMA_QT:
00929         n = buf_size - 2*avctx->channels;
00930         for (channel = 0; channel < avctx->channels; channel++) {
00931             cs = &(c->status[channel]);
00932             /* (pppppp) (piiiiiii) */
00933 
00934             /* Bits 15-7 are the _top_ 9 bits of the 16-bit initial predictor value */
00935             cs->predictor = (*src++) << 8;
00936             cs->predictor |= (*src & 0x80);
00937             cs->predictor &= 0xFF80;
00938 
00939             /* sign extension */
00940             if(cs->predictor & 0x8000)
00941                 cs->predictor -= 0x10000;
00942 
00943             cs->predictor = av_clip_int16(cs->predictor);
00944 
00945             cs->step_index = (*src++) & 0x7F;
00946 
00947             if (cs->step_index > 88){
00948                 av_log(avctx, AV_LOG_ERROR, "ERROR: step_index = %i\n", cs->step_index);
00949                 cs->step_index = 88;
00950             }
00951 
00952             cs->step = step_table[cs->step_index];
00953 
00954             samples = (short*)data + channel;
00955 
00956             for(m=32; n>0 && m>0; n--, m--) { /* in QuickTime, IMA is encoded by chuncks of 34 bytes (=64 samples) */
00957                 *samples = adpcm_ima_expand_nibble(cs, src[0] & 0x0F, 3);
00958                 samples += avctx->channels;
00959                 *samples = adpcm_ima_expand_nibble(cs, src[0] >> 4  , 3);
00960                 samples += avctx->channels;
00961                 src ++;
00962             }
00963         }
00964         if (st)
00965             samples--;
00966         break;
00967     case CODEC_ID_ADPCM_IMA_WAV:
00968         if (avctx->block_align != 0 && buf_size > avctx->block_align)
00969             buf_size = avctx->block_align;
00970 
00971 //        samples_per_block= (block_align-4*chanels)*8 / (bits_per_sample * chanels) + 1;
00972 
00973         for(i=0; i<avctx->channels; i++){
00974             cs = &(c->status[i]);
00975             cs->predictor = *samples++ = (int16_t)bytestream_get_le16(&src);
00976 
00977             cs->step_index = *src++;
00978             if (cs->step_index > 88){
00979                 av_log(avctx, AV_LOG_ERROR, "ERROR: step_index = %i\n", cs->step_index);
00980                 cs->step_index = 88;
00981             }
00982             if (*src++) av_log(avctx, AV_LOG_ERROR, "unused byte should be null but is %d!!\n", src[-1]); /* unused */
00983         }
00984 
00985         while(src < buf + buf_size){
00986             for(m=0; m<4; m++){
00987                 for(i=0; i<=st; i++)
00988                     *samples++ = adpcm_ima_expand_nibble(&c->status[i], src[4*i] & 0x0F, 3);
00989                 for(i=0; i<=st; i++)
00990                     *samples++ = adpcm_ima_expand_nibble(&c->status[i], src[4*i] >> 4  , 3);
00991                 src++;
00992             }
00993             src += 4*st;
00994         }
00995         break;
00996     case CODEC_ID_ADPCM_4XM:
00997         cs = &(c->status[0]);
00998         c->status[0].predictor= (int16_t)bytestream_get_le16(&src);
00999         if(st){
01000             c->status[1].predictor= (int16_t)bytestream_get_le16(&src);
01001         }
01002         c->status[0].step_index= (int16_t)bytestream_get_le16(&src);
01003         if(st){
01004             c->status[1].step_index= (int16_t)bytestream_get_le16(&src);
01005         }
01006         if (cs->step_index < 0) cs->step_index = 0;
01007         if (cs->step_index > 88) cs->step_index = 88;
01008 
01009         m= (buf_size - (src - buf))>>st;
01010         for(i=0; i<m; i++) {
01011             *samples++ = adpcm_ima_expand_nibble(&c->status[0], src[i] & 0x0F, 4);
01012             if (st)
01013                 *samples++ = adpcm_ima_expand_nibble(&c->status[1], src[i+m] & 0x0F, 4);
01014             *samples++ = adpcm_ima_expand_nibble(&c->status[0], src[i] >> 4, 4);
01015             if (st)
01016                 *samples++ = adpcm_ima_expand_nibble(&c->status[1], src[i+m] >> 4, 4);
01017         }
01018 
01019         src += m<<st;
01020 
01021         break;
01022     case CODEC_ID_ADPCM_MS:
01023         if (avctx->block_align != 0 && buf_size > avctx->block_align)
01024             buf_size = avctx->block_align;
01025         n = buf_size - 7 * avctx->channels;
01026         if (n < 0)
01027             return -1;
01028         block_predictor[0] = av_clip(*src++, 0, 6);
01029         block_predictor[1] = 0;
01030         if (st)
01031             block_predictor[1] = av_clip(*src++, 0, 6);
01032         c->status[0].idelta = (int16_t)bytestream_get_le16(&src);
01033         if (st){
01034             c->status[1].idelta = (int16_t)bytestream_get_le16(&src);
01035         }
01036         c->status[0].coeff1 = AdaptCoeff1[block_predictor[0]];
01037