]> git.sesse.net Git - ffmpeg/blob - libavcodec/adpcmenc.c
6295eedc55c064f910ddbb3c108e09e44005e8d2
[ffmpeg] / libavcodec / adpcmenc.c
1 /*
2  * Copyright (c) 2001-2003 The ffmpeg Project
3  *
4  * This file is part of Libav.
5  *
6  * Libav is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * Libav is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with Libav; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include "avcodec.h"
22 #include "get_bits.h"
23 #include "put_bits.h"
24 #include "bytestream.h"
25 #include "adpcm.h"
26 #include "adpcm_data.h"
27
28 /**
29  * @file
30  * ADPCM encoders
31  * First version by Francois Revol (revol@free.fr)
32  * Fringe ADPCM codecs (e.g., DK3, DK4, Westwood)
33  *   by Mike Melanson (melanson@pcisys.net)
34  *
35  * Reference documents:
36  * http://www.pcisys.net/~melanson/codecs/simpleaudio.html
37  * http://www.geocities.com/SiliconValley/8682/aud3.txt
38  * http://openquicktime.sourceforge.net/plugins.htm
39  * XAnim sources (xa_codec.c) http://www.rasnaimaging.com/people/lapus/download.html
40  * http://www.cs.ucla.edu/~leec/mediabench/applications.html
41  * SoX source code http://home.sprynet.com/~cbagwell/sox.html
42  */
43
44 typedef struct TrellisPath {
45     int nibble;
46     int prev;
47 } TrellisPath;
48
49 typedef struct TrellisNode {
50     uint32_t ssd;
51     int path;
52     int sample1;
53     int sample2;
54     int step;
55 } TrellisNode;
56
57 typedef struct ADPCMEncodeContext {
58     ADPCMChannelStatus status[6];
59     TrellisPath *paths;
60     TrellisNode *node_buf;
61     TrellisNode **nodep_buf;
62     uint8_t *trellis_hash;
63 } ADPCMEncodeContext;
64
65 #define FREEZE_INTERVAL 128
66
67 static av_cold int adpcm_encode_init(AVCodecContext *avctx)
68 {
69     ADPCMEncodeContext *s = avctx->priv_data;
70     uint8_t *extradata;
71     int i;
72     if (avctx->channels > 2)
73         return -1; /* only stereo or mono =) */
74
75     if(avctx->trellis && (unsigned)avctx->trellis > 16U){
76         av_log(avctx, AV_LOG_ERROR, "invalid trellis size\n");
77         return -1;
78     }
79
80     if (avctx->trellis) {
81         int frontier = 1 << avctx->trellis;
82         int max_paths =  frontier * FREEZE_INTERVAL;
83         FF_ALLOC_OR_GOTO(avctx, s->paths,     max_paths * sizeof(*s->paths), error);
84         FF_ALLOC_OR_GOTO(avctx, s->node_buf,  2 * frontier * sizeof(*s->node_buf), error);
85         FF_ALLOC_OR_GOTO(avctx, s->nodep_buf, 2 * frontier * sizeof(*s->nodep_buf), error);
86         FF_ALLOC_OR_GOTO(avctx, s->trellis_hash, 65536 * sizeof(*s->trellis_hash), error);
87     }
88
89     switch(avctx->codec->id) {
90     case CODEC_ID_ADPCM_IMA_WAV:
91         avctx->frame_size = (BLKSIZE - 4 * avctx->channels) * 8 / (4 * avctx->channels) + 1; /* each 16 bits sample gives one nibble */
92                                                              /* and we have 4 bytes per channel overhead */
93         avctx->block_align = BLKSIZE;
94         /* seems frame_size isn't taken into account... have to buffer the samples :-( */
95         break;
96     case CODEC_ID_ADPCM_IMA_QT:
97         avctx->frame_size = 64;
98         avctx->block_align = 34 * avctx->channels;
99         break;
100     case CODEC_ID_ADPCM_MS:
101         avctx->frame_size = (BLKSIZE - 7 * avctx->channels) * 2 / avctx->channels + 2; /* each 16 bits sample gives one nibble */
102                                                              /* and we have 7 bytes per channel overhead */
103         avctx->block_align = BLKSIZE;
104         avctx->extradata_size = 32;
105         extradata = avctx->extradata = av_malloc(avctx->extradata_size);
106         if (!extradata)
107             return AVERROR(ENOMEM);
108         bytestream_put_le16(&extradata, avctx->frame_size);
109         bytestream_put_le16(&extradata, 7); /* wNumCoef */
110         for (i = 0; i < 7; i++) {
111             bytestream_put_le16(&extradata, ff_adpcm_AdaptCoeff1[i] * 4);
112             bytestream_put_le16(&extradata, ff_adpcm_AdaptCoeff2[i] * 4);
113         }
114         break;
115     case CODEC_ID_ADPCM_YAMAHA:
116         avctx->frame_size = BLKSIZE * avctx->channels;
117         avctx->block_align = BLKSIZE;
118         break;
119     case CODEC_ID_ADPCM_SWF:
120         if (avctx->sample_rate != 11025 &&
121             avctx->sample_rate != 22050 &&
122             avctx->sample_rate != 44100) {
123             av_log(avctx, AV_LOG_ERROR, "Sample rate must be 11025, 22050 or 44100\n");
124             goto error;
125         }
126         avctx->frame_size = 512 * (avctx->sample_rate / 11025);
127         break;
128     default:
129         goto error;
130     }
131
132     avctx->coded_frame= avcodec_alloc_frame();
133     avctx->coded_frame->key_frame= 1;
134
135     return 0;
136 error:
137     av_freep(&s->paths);
138     av_freep(&s->node_buf);
139     av_freep(&s->nodep_buf);
140     av_freep(&s->trellis_hash);
141     return -1;
142 }
143
144 static av_cold int adpcm_encode_close(AVCodecContext *avctx)
145 {
146     ADPCMEncodeContext *s = avctx->priv_data;
147     av_freep(&avctx->coded_frame);
148     av_freep(&s->paths);
149     av_freep(&s->node_buf);
150     av_freep(&s->nodep_buf);
151     av_freep(&s->trellis_hash);
152
153     return 0;
154 }
155
156
157 static inline unsigned char adpcm_ima_compress_sample(ADPCMChannelStatus *c, short sample)
158 {
159     int delta = sample - c->prev_sample;
160     int nibble = FFMIN(7, abs(delta)*4/ff_adpcm_step_table[c->step_index]) + (delta<0)*8;
161     c->prev_sample += ((ff_adpcm_step_table[c->step_index] * ff_adpcm_yamaha_difflookup[nibble]) / 8);
162     c->prev_sample = av_clip_int16(c->prev_sample);
163     c->step_index = av_clip(c->step_index + ff_adpcm_index_table[nibble], 0, 88);
164     return nibble;
165 }
166
167 static inline unsigned char adpcm_ima_qt_compress_sample(ADPCMChannelStatus *c, short sample)
168 {
169     int delta = sample - c->prev_sample;
170     int mask, step = ff_adpcm_step_table[c->step_index];
171     int diff = step >> 3;
172     int nibble = 0;
173
174     if (delta < 0) {
175         nibble = 8;
176         delta = -delta;
177     }
178
179     for (mask = 4; mask;) {
180         if (delta >= step) {
181             nibble |= mask;
182             delta -= step;
183             diff += step;
184         }
185         step >>= 1;
186         mask >>= 1;
187     }
188
189     if (nibble & 8)
190         c->prev_sample -= diff;
191     else
192         c->prev_sample += diff;
193
194     c->prev_sample = av_clip_int16(c->prev_sample);
195     c->step_index = av_clip(c->step_index + ff_adpcm_index_table[nibble], 0, 88);
196
197     return nibble;
198 }
199
200 static inline unsigned char adpcm_ms_compress_sample(ADPCMChannelStatus *c, short sample)
201 {
202     int predictor, nibble, bias;
203
204     predictor = (((c->sample1) * (c->coeff1)) + ((c->sample2) * (c->coeff2))) / 64;
205
206     nibble= sample - predictor;
207     if(nibble>=0) bias= c->idelta/2;
208     else          bias=-c->idelta/2;
209
210     nibble= (nibble + bias) / c->idelta;
211     nibble= av_clip(nibble, -8, 7)&0x0F;
212
213     predictor += (signed)((nibble & 0x08)?(nibble - 0x10):(nibble)) * c->idelta;
214
215     c->sample2 = c->sample1;
216     c->sample1 = av_clip_int16(predictor);
217
218     c->idelta = (ff_adpcm_AdaptationTable[(int)nibble] * c->idelta) >> 8;
219     if (c->idelta < 16) c->idelta = 16;
220
221     return nibble;
222 }
223
224 static inline unsigned char adpcm_yamaha_compress_sample(ADPCMChannelStatus *c, short sample)
225 {
226     int nibble, delta;
227
228     if(!c->step) {
229         c->predictor = 0;
230         c->step = 127;
231     }
232
233     delta = sample - c->predictor;
234
235     nibble = FFMIN(7, abs(delta)*4/c->step) + (delta<0)*8;
236
237     c->predictor += ((c->step * ff_adpcm_yamaha_difflookup[nibble]) / 8);
238     c->predictor = av_clip_int16(c->predictor);
239     c->step = (c->step * ff_adpcm_yamaha_indexscale[nibble]) >> 8;
240     c->step = av_clip(c->step, 127, 24567);
241
242     return nibble;
243 }
244
245 static void adpcm_compress_trellis(AVCodecContext *avctx, const short *samples,
246                                    uint8_t *dst, ADPCMChannelStatus *c, int n)
247 {
248     //FIXME 6% faster if frontier is a compile-time constant
249     ADPCMEncodeContext *s = avctx->priv_data;
250     const int frontier = 1 << avctx->trellis;
251     const int stride = avctx->channels;
252     const int version = avctx->codec->id;
253     TrellisPath *paths = s->paths, *p;
254     TrellisNode *node_buf = s->node_buf;
255     TrellisNode **nodep_buf = s->nodep_buf;
256     TrellisNode **nodes = nodep_buf; // nodes[] is always sorted by .ssd
257     TrellisNode **nodes_next = nodep_buf + frontier;
258     int pathn = 0, froze = -1, i, j, k, generation = 0;
259     uint8_t *hash = s->trellis_hash;
260     memset(hash, 0xff, 65536 * sizeof(*hash));
261
262     memset(nodep_buf, 0, 2 * frontier * sizeof(*nodep_buf));
263     nodes[0] = node_buf + frontier;
264     nodes[0]->ssd = 0;
265     nodes[0]->path = 0;
266     nodes[0]->step = c->step_index;
267     nodes[0]->sample1 = c->sample1;
268     nodes[0]->sample2 = c->sample2;
269     if((version == CODEC_ID_ADPCM_IMA_WAV) || (version == CODEC_ID_ADPCM_IMA_QT) || (version == CODEC_ID_ADPCM_SWF))
270         nodes[0]->sample1 = c->prev_sample;
271     if(version == CODEC_ID_ADPCM_MS)
272         nodes[0]->step = c->idelta;
273     if(version == CODEC_ID_ADPCM_YAMAHA) {
274         if(c->step == 0) {
275             nodes[0]->step = 127;
276             nodes[0]->sample1 = 0;
277         } else {
278             nodes[0]->step = c->step;
279             nodes[0]->sample1 = c->predictor;
280         }
281     }
282
283     for(i=0; i<n; i++) {
284         TrellisNode *t = node_buf + frontier*(i&1);
285         TrellisNode **u;
286         int sample = samples[i*stride];
287         int heap_pos = 0;
288         memset(nodes_next, 0, frontier*sizeof(TrellisNode*));
289         for(j=0; j<frontier && nodes[j]; j++) {
290             // higher j have higher ssd already, so they're likely to yield a suboptimal next sample too
291             const int range = (j < frontier/2) ? 1 : 0;
292             const int step = nodes[j]->step;
293             int nidx;
294             if(version == CODEC_ID_ADPCM_MS) {
295                 const int predictor = ((nodes[j]->sample1 * c->coeff1) + (nodes[j]->sample2 * c->coeff2)) / 64;
296                 const int div = (sample - predictor) / step;
297                 const int nmin = av_clip(div-range, -8, 6);
298                 const int nmax = av_clip(div+range, -7, 7);
299                 for(nidx=nmin; nidx<=nmax; nidx++) {
300                     const int nibble = nidx & 0xf;
301                     int dec_sample = predictor + nidx * step;
302 #define STORE_NODE(NAME, STEP_INDEX)\
303                     int d;\
304                     uint32_t ssd;\
305                     int pos;\
306                     TrellisNode *u;\
307                     uint8_t *h;\
308                     dec_sample = av_clip_int16(dec_sample);\
309                     d = sample - dec_sample;\
310                     ssd = nodes[j]->ssd + d*d;\
311                     /* Check for wraparound, skip such samples completely. \
312                      * Note, changing ssd to a 64 bit variable would be \
313                      * simpler, avoiding this check, but it's slower on \
314                      * x86 32 bit at the moment. */\
315                     if (ssd < nodes[j]->ssd)\
316                         goto next_##NAME;\
317                     /* Collapse any two states with the same previous sample value. \
318                      * One could also distinguish states by step and by 2nd to last
319                      * sample, but the effects of that are negligible.
320                      * Since nodes in the previous generation are iterated
321                      * through a heap, they're roughly ordered from better to
322                      * worse, but not strictly ordered. Therefore, an earlier
323                      * node with the same sample value is better in most cases
324                      * (and thus the current is skipped), but not strictly
325                      * in all cases. Only skipping samples where ssd >=
326                      * ssd of the earlier node with the same sample gives
327                      * slightly worse quality, though, for some reason. */ \
328                     h = &hash[(uint16_t) dec_sample];\
329                     if (*h == generation)\
330                         goto next_##NAME;\
331                     if (heap_pos < frontier) {\
332                         pos = heap_pos++;\
333                     } else {\
334                         /* Try to replace one of the leaf nodes with the new \
335                          * one, but try a different slot each time. */\
336                         pos = (frontier >> 1) + (heap_pos & ((frontier >> 1) - 1));\
337                         if (ssd > nodes_next[pos]->ssd)\
338                             goto next_##NAME;\
339                         heap_pos++;\
340                     }\
341                     *h = generation;\
342                     u = nodes_next[pos];\
343                     if(!u) {\
344                         assert(pathn < FREEZE_INTERVAL<<avctx->trellis);\
345                         u = t++;\
346                         nodes_next[pos] = u;\
347                         u->path = pathn++;\
348                     }\
349                     u->ssd = ssd;\
350                     u->step = STEP_INDEX;\
351                     u->sample2 = nodes[j]->sample1;\
352                     u->sample1 = dec_sample;\
353                     paths[u->path].nibble = nibble;\
354                     paths[u->path].prev = nodes[j]->path;\
355                     /* Sift the newly inserted node up in the heap to \
356                      * restore the heap property. */\
357                     while (pos > 0) {\
358                         int parent = (pos - 1) >> 1;\
359                         if (nodes_next[parent]->ssd <= ssd)\
360                             break;\
361                         FFSWAP(TrellisNode*, nodes_next[parent], nodes_next[pos]);\
362                         pos = parent;\
363                     }\
364                     next_##NAME:;
365                     STORE_NODE(ms, FFMAX(16, (ff_adpcm_AdaptationTable[nibble] * step) >> 8));
366                 }
367             } else if((version == CODEC_ID_ADPCM_IMA_WAV)|| (version == CODEC_ID_ADPCM_IMA_QT)|| (version == CODEC_ID_ADPCM_SWF)) {
368 #define LOOP_NODES(NAME, STEP_TABLE, STEP_INDEX)\
369                 const int predictor = nodes[j]->sample1;\
370                 const int div = (sample - predictor) * 4 / STEP_TABLE;\
371                 int nmin = av_clip(div-range, -7, 6);\
372                 int nmax = av_clip(div+range, -6, 7);\
373                 if(nmin<=0) nmin--; /* distinguish -0 from +0 */\
374                 if(nmax<0) nmax--;\
375                 for(nidx=nmin; nidx<=nmax; nidx++) {\
376                     const int nibble = nidx<0 ? 7-nidx : nidx;\
377                     int dec_sample = predictor + (STEP_TABLE * ff_adpcm_yamaha_difflookup[nibble]) / 8;\
378                     STORE_NODE(NAME, STEP_INDEX);\
379                 }
380                 LOOP_NODES(ima, ff_adpcm_step_table[step], av_clip(step + ff_adpcm_index_table[nibble], 0, 88));
381             } else { //CODEC_ID_ADPCM_YAMAHA
382                 LOOP_NODES(yamaha, step, av_clip((step * ff_adpcm_yamaha_indexscale[nibble]) >> 8, 127, 24567));
383 #undef LOOP_NODES
384 #undef STORE_NODE
385             }
386         }
387
388         u = nodes;
389         nodes = nodes_next;
390         nodes_next = u;
391
392         generation++;
393         if (generation == 255) {
394             memset(hash, 0xff, 65536 * sizeof(*hash));
395             generation = 0;
396         }
397
398         // prevent overflow
399         if(nodes[0]->ssd > (1<<28)) {
400             for(j=1; j<frontier && nodes[j]; j++)
401                 nodes[j]->ssd -= nodes[0]->ssd;
402             nodes[0]->ssd = 0;
403         }
404
405         // merge old paths to save memory
406         if(i == froze + FREEZE_INTERVAL) {
407             p = &paths[nodes[0]->path];
408             for(k=i; k>froze; k--) {
409                 dst[k] = p->nibble;
410                 p = &paths[p->prev];
411             }
412             froze = i;
413             pathn = 0;
414             // other nodes might use paths that don't coincide with the frozen one.
415             // checking which nodes do so is too slow, so just kill them all.
416             // this also slightly improves quality, but I don't know why.
417             memset(nodes+1, 0, (frontier-1)*sizeof(TrellisNode*));
418         }
419     }
420
421     p = &paths[nodes[0]->path];
422     for(i=n-1; i>froze; i--) {
423         dst[i] = p->nibble;
424         p = &paths[p->prev];
425     }
426
427     c->predictor = nodes[0]->sample1;
428     c->sample1 = nodes[0]->sample1;
429     c->sample2 = nodes[0]->sample2;
430     c->step_index = nodes[0]->step;
431     c->step = nodes[0]->step;
432     c->idelta = nodes[0]->step;
433 }
434
435 static int adpcm_encode_frame(AVCodecContext *avctx,
436                             unsigned char *frame, int buf_size, void *data)
437 {
438     int n, i, st;
439     short *samples;
440     unsigned char *dst;
441     ADPCMEncodeContext *c = avctx->priv_data;
442     uint8_t *buf;
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                 FF_ALLOC_OR_GOTO(avctx, buf, 2*n*8, error);
470                 adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n*8);
471                 if(avctx->channels == 2)
472                     adpcm_compress_trellis(avctx, samples+1, buf + n*8, &c->status[1], n*8);
473                 for(i=0; i<n; i++) {
474                     *dst++ = buf[8*i+0] | (buf[8*i+1] << 4);
475                     *dst++ = buf[8*i+2] | (buf[8*i+3] << 4);
476                     *dst++ = buf[8*i+4] | (buf[8*i+5] << 4);
477                     *dst++ = buf[8*i+6] | (buf[8*i+7] << 4);
478                     if (avctx->channels == 2) {
479                         uint8_t *buf1 = buf + n*8;
480                         *dst++ = buf1[8*i+0] | (buf1[8*i+1] << 4);
481                         *dst++ = buf1[8*i+2] | (buf1[8*i+3] << 4);
482                         *dst++ = buf1[8*i+4] | (buf1[8*i+5] << 4);
483                         *dst++ = buf1[8*i+6] | (buf1[8*i+7] << 4);
484                     }
485                 }
486                 av_free(buf);
487             } else
488             for (; n>0; n--) {
489                 *dst = adpcm_ima_compress_sample(&c->status[0], samples[0]);
490                 *dst |= adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels]) << 4;
491                 dst++;
492                 *dst = adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 2]);
493                 *dst |= adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 3]) << 4;
494                 dst++;
495                 *dst = adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 4]);
496                 *dst |= adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 5]) << 4;
497                 dst++;
498                 *dst = adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 6]);
499                 *dst |= adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 7]) << 4;
500                 dst++;
501                 /* right channel */
502                 if (avctx->channels == 2) {
503                     *dst = adpcm_ima_compress_sample(&c->status[1], samples[1]);
504                     *dst |= adpcm_ima_compress_sample(&c->status[1], samples[3]) << 4;
505                     dst++;
506                     *dst = adpcm_ima_compress_sample(&c->status[1], samples[5]);
507                     *dst |= adpcm_ima_compress_sample(&c->status[1], samples[7]) << 4;
508                     dst++;
509                     *dst = adpcm_ima_compress_sample(&c->status[1], samples[9]);
510                     *dst |= adpcm_ima_compress_sample(&c->status[1], samples[11]) << 4;
511                     dst++;
512                     *dst = adpcm_ima_compress_sample(&c->status[1], samples[13]);
513                     *dst |= adpcm_ima_compress_sample(&c->status[1], samples[15]) << 4;
514                     dst++;
515                 }
516                 samples += 8 * avctx->channels;
517             }
518         break;
519     case CODEC_ID_ADPCM_IMA_QT:
520     {
521         int ch, i;
522         PutBitContext pb;
523         init_put_bits(&pb, dst, buf_size*8);
524
525         for(ch=0; ch<avctx->channels; ch++){
526             put_bits(&pb, 9, (c->status[ch].prev_sample + 0x10000) >> 7);
527             put_bits(&pb, 7, c->status[ch].step_index);
528             if(avctx->trellis > 0) {
529                 uint8_t buf[64];
530                 adpcm_compress_trellis(avctx, samples+ch, buf, &c->status[ch], 64);
531                 for(i=0; i<64; i++)
532                     put_bits(&pb, 4, buf[i^1]);
533             } else {
534                 for (i=0; i<64; i+=2){
535                     int t1, t2;
536                     t1 = adpcm_ima_qt_compress_sample(&c->status[ch], samples[avctx->channels*(i+0)+ch]);
537                     t2 = adpcm_ima_qt_compress_sample(&c->status[ch], samples[avctx->channels*(i+1)+ch]);
538                     put_bits(&pb, 4, t2);
539                     put_bits(&pb, 4, t1);
540                 }
541             }
542         }
543
544         flush_put_bits(&pb);
545         dst += put_bits_count(&pb)>>3;
546         break;
547     }
548     case CODEC_ID_ADPCM_SWF:
549     {
550         int i;
551         PutBitContext pb;
552         init_put_bits(&pb, dst, buf_size*8);
553
554         n = avctx->frame_size-1;
555
556         //Store AdpcmCodeSize
557         put_bits(&pb, 2, 2);                //Set 4bits flash adpcm format
558
559         //Init the encoder state
560         for(i=0; i<avctx->channels; i++){
561             c->status[i].step_index = av_clip(c->status[i].step_index, 0, 63); // clip step so it fits 6 bits
562             put_sbits(&pb, 16, samples[i]);
563             put_bits(&pb, 6, c->status[i].step_index);
564             c->status[i].prev_sample = (signed short)samples[i];
565         }
566
567         if(avctx->trellis > 0) {
568             FF_ALLOC_OR_GOTO(avctx, buf, 2*n, error);
569             adpcm_compress_trellis(avctx, samples+2, buf, &c->status[0], n);
570             if (avctx->channels == 2)
571                 adpcm_compress_trellis(avctx, samples+3, buf+n, &c->status[1], n);
572             for(i=0; i<n; i++) {
573                 put_bits(&pb, 4, buf[i]);
574                 if (avctx->channels == 2)
575                     put_bits(&pb, 4, buf[n+i]);
576             }
577             av_free(buf);
578         } else {
579             for (i=1; i<avctx->frame_size; i++) {
580                 put_bits(&pb, 4, adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels*i]));
581                 if (avctx->channels == 2)
582                     put_bits(&pb, 4, adpcm_ima_compress_sample(&c->status[1], samples[2*i+1]));
583             }
584         }
585         flush_put_bits(&pb);
586         dst += put_bits_count(&pb)>>3;
587         break;
588     }
589     case CODEC_ID_ADPCM_MS:
590         for(i=0; i<avctx->channels; i++){
591             int predictor=0;
592
593             *dst++ = predictor;
594             c->status[i].coeff1 = ff_adpcm_AdaptCoeff1[predictor];
595             c->status[i].coeff2 = ff_adpcm_AdaptCoeff2[predictor];
596         }
597         for(i=0; i<avctx->channels; i++){
598             if (c->status[i].idelta < 16)
599                 c->status[i].idelta = 16;
600
601             bytestream_put_le16(&dst, c->status[i].idelta);
602         }
603         for(i=0; i<avctx->channels; i++){
604             c->status[i].sample2= *samples++;
605         }
606         for(i=0; i<avctx->channels; i++){
607             c->status[i].sample1= *samples++;
608
609             bytestream_put_le16(&dst, c->status[i].sample1);
610         }
611         for(i=0; i<avctx->channels; i++)
612             bytestream_put_le16(&dst, c->status[i].sample2);
613
614         if(avctx->trellis > 0) {
615             int n = avctx->block_align - 7*avctx->channels;
616             FF_ALLOC_OR_GOTO(avctx, buf, 2*n, error);
617             if(avctx->channels == 1) {
618                 adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n);
619                 for(i=0; i<n; i+=2)
620                     *dst++ = (buf[i] << 4) | buf[i+1];
621             } else {
622                 adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n);
623                 adpcm_compress_trellis(avctx, samples+1, buf+n, &c->status[1], n);
624                 for(i=0; i<n; i++)
625                     *dst++ = (buf[i] << 4) | buf[n+i];
626             }
627             av_free(buf);
628         } else
629         for(i=7*avctx->channels; i<avctx->block_align; i++) {
630             int nibble;
631             nibble = adpcm_ms_compress_sample(&c->status[ 0], *samples++)<<4;
632             nibble|= adpcm_ms_compress_sample(&c->status[st], *samples++);
633             *dst++ = nibble;
634         }
635         break;
636     case CODEC_ID_ADPCM_YAMAHA:
637         n = avctx->frame_size / 2;
638         if(avctx->trellis > 0) {
639             FF_ALLOC_OR_GOTO(avctx, buf, 2*n*2, error);
640             n *= 2;
641             if(avctx->channels == 1) {
642                 adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n);
643                 for(i=0; i<n; i+=2)
644                     *dst++ = buf[i] | (buf[i+1] << 4);
645             } else {
646                 adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n);
647                 adpcm_compress_trellis(avctx, samples+1, buf+n, &c->status[1], n);
648                 for(i=0; i<n; i++)
649                     *dst++ = buf[i] | (buf[n+i] << 4);
650             }
651             av_free(buf);
652         } else
653             for (n *= avctx->channels; n>0; n--) {
654                 int nibble;
655                 nibble  = adpcm_yamaha_compress_sample(&c->status[ 0], *samples++);
656                 nibble |= adpcm_yamaha_compress_sample(&c->status[st], *samples++) << 4;
657                 *dst++ = nibble;
658             }
659         break;
660     default:
661     error:
662         return -1;
663     }
664     return dst - frame;
665 }
666
667
668 #define ADPCM_ENCODER(id,name,long_name_)       \
669 AVCodec ff_ ## name ## _encoder = {             \
670     #name,                                      \
671     AVMEDIA_TYPE_AUDIO,                         \
672     id,                                         \
673     sizeof(ADPCMEncodeContext),                 \
674     adpcm_encode_init,                          \
675     adpcm_encode_frame,                         \
676     adpcm_encode_close,                         \
677     NULL,                                       \
678     .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE}, \
679     .long_name = NULL_IF_CONFIG_SMALL(long_name_), \
680 }
681
682 ADPCM_ENCODER(CODEC_ID_ADPCM_IMA_QT, adpcm_ima_qt, "ADPCM IMA QuickTime");
683 ADPCM_ENCODER(CODEC_ID_ADPCM_IMA_WAV, adpcm_ima_wav, "ADPCM IMA WAV");
684 ADPCM_ENCODER(CODEC_ID_ADPCM_MS, adpcm_ms, "ADPCM Microsoft");
685 ADPCM_ENCODER(CODEC_ID_ADPCM_SWF, adpcm_swf, "ADPCM Shockwave Flash");
686 ADPCM_ENCODER(CODEC_ID_ADPCM_YAMAHA, adpcm_yamaha, "ADPCM Yamaha");