]> git.sesse.net Git - ffmpeg/blob - libavcodec/adpcmenc.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavcodec / adpcmenc.c
1 /*
2  * Copyright (c) 2001-2003 The ffmpeg Project
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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     avctx->bits_per_coded_sample = av_get_bits_per_sample(avctx->codec->id);
90
91     switch(avctx->codec->id) {
92     case CODEC_ID_ADPCM_IMA_WAV:
93         avctx->frame_size = (BLKSIZE - 4 * avctx->channels) * 8 / (4 * avctx->channels) + 1; /* each 16 bits sample gives one nibble */
94                                                              /* and we have 4 bytes per channel overhead */
95         avctx->block_align = BLKSIZE;
96         avctx->bits_per_coded_sample = 4;
97         /* seems frame_size isn't taken into account... have to buffer the samples :-( */
98         break;
99     case CODEC_ID_ADPCM_IMA_QT:
100         avctx->frame_size = 64;
101         avctx->block_align = 34 * avctx->channels;
102         break;
103     case CODEC_ID_ADPCM_MS:
104         avctx->frame_size = (BLKSIZE - 7 * avctx->channels) * 2 / avctx->channels + 2; /* each 16 bits sample gives one nibble */
105                                                              /* and we have 7 bytes per channel overhead */
106         avctx->block_align = BLKSIZE;
107         avctx->bits_per_coded_sample = 4;
108         avctx->extradata_size = 32;
109         extradata = avctx->extradata = av_malloc(avctx->extradata_size);
110         if (!extradata)
111             return AVERROR(ENOMEM);
112         bytestream_put_le16(&extradata, avctx->frame_size);
113         bytestream_put_le16(&extradata, 7); /* wNumCoef */
114         for (i = 0; i < 7; i++) {
115             bytestream_put_le16(&extradata, ff_adpcm_AdaptCoeff1[i] * 4);
116             bytestream_put_le16(&extradata, ff_adpcm_AdaptCoeff2[i] * 4);
117         }
118         break;
119     case CODEC_ID_ADPCM_YAMAHA:
120         avctx->frame_size = BLKSIZE * avctx->channels;
121         avctx->block_align = BLKSIZE;
122         break;
123     case CODEC_ID_ADPCM_SWF:
124         if (avctx->sample_rate != 11025 &&
125             avctx->sample_rate != 22050 &&
126             avctx->sample_rate != 44100) {
127             av_log(avctx, AV_LOG_ERROR, "Sample rate must be 11025, 22050 or 44100\n");
128             goto error;
129         }
130         avctx->frame_size = 512 * (avctx->sample_rate / 11025);
131         break;
132     default:
133         goto error;
134     }
135
136     avctx->coded_frame= avcodec_alloc_frame();
137     avctx->coded_frame->key_frame= 1;
138
139     return 0;
140 error:
141     av_freep(&s->paths);
142     av_freep(&s->node_buf);
143     av_freep(&s->nodep_buf);
144     av_freep(&s->trellis_hash);
145     return -1;
146 }
147
148 static av_cold int adpcm_encode_close(AVCodecContext *avctx)
149 {
150     ADPCMEncodeContext *s = avctx->priv_data;
151     av_freep(&avctx->coded_frame);
152     av_freep(&s->paths);
153     av_freep(&s->node_buf);
154     av_freep(&s->nodep_buf);
155     av_freep(&s->trellis_hash);
156
157     return 0;
158 }
159
160
161 static inline unsigned char adpcm_ima_compress_sample(ADPCMChannelStatus *c, short sample)
162 {
163     int delta = sample - c->prev_sample;
164     int nibble = FFMIN(7, abs(delta)*4/ff_adpcm_step_table[c->step_index]) + (delta<0)*8;
165     c->prev_sample += ((ff_adpcm_step_table[c->step_index] * ff_adpcm_yamaha_difflookup[nibble]) / 8);
166     c->prev_sample = av_clip_int16(c->prev_sample);
167     c->step_index = av_clip(c->step_index + ff_adpcm_index_table[nibble], 0, 88);
168     return nibble;
169 }
170
171 static inline unsigned char adpcm_ima_qt_compress_sample(ADPCMChannelStatus *c, short sample)
172 {
173     int delta = sample - c->prev_sample;
174     int diff, step = ff_adpcm_step_table[c->step_index];
175     int nibble = 8*(delta < 0);
176
177     delta= abs(delta);
178     diff = delta + (step >> 3);
179
180     if (delta >= step) {
181         nibble |= 4;
182         delta -= step;
183     }
184     step >>= 1;
185     if (delta >= step) {
186         nibble |= 2;
187         delta -= step;
188     }
189     step >>= 1;
190     if (delta >= step) {
191         nibble |= 1;
192         delta -= step;
193     }
194     diff -= delta;
195
196     if (nibble & 8)
197         c->prev_sample -= diff;
198     else
199         c->prev_sample += diff;
200
201     c->prev_sample = av_clip_int16(c->prev_sample);
202     c->step_index = av_clip(c->step_index + ff_adpcm_index_table[nibble], 0, 88);
203
204     return nibble;
205 }
206
207 static inline unsigned char adpcm_ms_compress_sample(ADPCMChannelStatus *c, short sample)
208 {
209     int predictor, nibble, bias;
210
211     predictor = (((c->sample1) * (c->coeff1)) + ((c->sample2) * (c->coeff2))) / 64;
212
213     nibble= sample - predictor;
214     if(nibble>=0) bias= c->idelta/2;
215     else          bias=-c->idelta/2;
216
217     nibble= (nibble + bias) / c->idelta;
218     nibble= av_clip(nibble, -8, 7)&0x0F;
219
220     predictor += (signed)((nibble & 0x08)?(nibble - 0x10):(nibble)) * c->idelta;
221
222     c->sample2 = c->sample1;
223     c->sample1 = av_clip_int16(predictor);
224
225     c->idelta = (ff_adpcm_AdaptationTable[(int)nibble] * c->idelta) >> 8;
226     if (c->idelta < 16) c->idelta = 16;
227
228     return nibble;
229 }
230
231 static inline unsigned char adpcm_yamaha_compress_sample(ADPCMChannelStatus *c, short sample)
232 {
233     int nibble, delta;
234
235     if(!c->step) {
236         c->predictor = 0;
237         c->step = 127;
238     }
239
240     delta = sample - c->predictor;
241
242     nibble = FFMIN(7, abs(delta)*4/c->step) + (delta<0)*8;
243
244     c->predictor += ((c->step * ff_adpcm_yamaha_difflookup[nibble]) / 8);
245     c->predictor = av_clip_int16(c->predictor);
246     c->step = (c->step * ff_adpcm_yamaha_indexscale[nibble]) >> 8;
247     c->step = av_clip(c->step, 127, 24567);
248
249     return nibble;
250 }
251
252 static void adpcm_compress_trellis(AVCodecContext *avctx, const short *samples,
253                                    uint8_t *dst, ADPCMChannelStatus *c, int n)
254 {
255     //FIXME 6% faster if frontier is a compile-time constant
256     ADPCMEncodeContext *s = avctx->priv_data;
257     const int frontier = 1 << avctx->trellis;
258     const int stride = avctx->channels;
259     const int version = avctx->codec->id;
260     TrellisPath *paths = s->paths, *p;
261     TrellisNode *node_buf = s->node_buf;
262     TrellisNode **nodep_buf = s->nodep_buf;
263     TrellisNode **nodes = nodep_buf; // nodes[] is always sorted by .ssd
264     TrellisNode **nodes_next = nodep_buf + frontier;
265     int pathn = 0, froze = -1, i, j, k, generation = 0;
266     uint8_t *hash = s->trellis_hash;
267     memset(hash, 0xff, 65536 * sizeof(*hash));
268
269     memset(nodep_buf, 0, 2 * frontier * sizeof(*nodep_buf));
270     nodes[0] = node_buf + frontier;
271     nodes[0]->ssd = 0;
272     nodes[0]->path = 0;
273     nodes[0]->step = c->step_index;
274     nodes[0]->sample1 = c->sample1;
275     nodes[0]->sample2 = c->sample2;
276     if((version == CODEC_ID_ADPCM_IMA_WAV) || (version == CODEC_ID_ADPCM_IMA_QT) || (version == CODEC_ID_ADPCM_SWF))
277         nodes[0]->sample1 = c->prev_sample;
278     if(version == CODEC_ID_ADPCM_MS)
279         nodes[0]->step = c->idelta;
280     if(version == CODEC_ID_ADPCM_YAMAHA) {
281         if(c->step == 0) {
282             nodes[0]->step = 127;
283             nodes[0]->sample1 = 0;
284         } else {
285             nodes[0]->step = c->step;
286             nodes[0]->sample1 = c->predictor;
287         }
288     }
289
290     for(i=0; i<n; i++) {
291         TrellisNode *t = node_buf + frontier*(i&1);
292         TrellisNode **u;
293         int sample = samples[i*stride];
294         int heap_pos = 0;
295         memset(nodes_next, 0, frontier*sizeof(TrellisNode*));
296         for(j=0; j<frontier && nodes[j]; j++) {
297             // higher j have higher ssd already, so they're likely to yield a suboptimal next sample too
298             const int range = (j < frontier/2) ? 1 : 0;
299             const int step = nodes[j]->step;
300             int nidx;
301             if(version == CODEC_ID_ADPCM_MS) {
302                 const int predictor = ((nodes[j]->sample1 * c->coeff1) + (nodes[j]->sample2 * c->coeff2)) / 64;
303                 const int div = (sample - predictor) / step;
304                 const int nmin = av_clip(div-range, -8, 6);
305                 const int nmax = av_clip(div+range, -7, 7);
306                 for(nidx=nmin; nidx<=nmax; nidx++) {
307                     const int nibble = nidx & 0xf;
308                     int dec_sample = predictor + nidx * step;
309 #define STORE_NODE(NAME, STEP_INDEX)\
310                     int d;\
311                     uint32_t ssd;\
312                     int pos;\
313                     TrellisNode *u;\
314                     uint8_t *h;\
315                     dec_sample = av_clip_int16(dec_sample);\
316                     d = sample - dec_sample;\
317                     ssd = nodes[j]->ssd + d*d;\
318                     /* Check for wraparound, skip such samples completely. \
319                      * Note, changing ssd to a 64 bit variable would be \
320                      * simpler, avoiding this check, but it's slower on \
321                      * x86 32 bit at the moment. */\
322                     if (ssd < nodes[j]->ssd)\
323                         goto next_##NAME;\
324                     /* Collapse any two states with the same previous sample value. \
325                      * One could also distinguish states by step and by 2nd to last
326                      * sample, but the effects of that are negligible.
327                      * Since nodes in the previous generation are iterated
328                      * through a heap, they're roughly ordered from better to
329                      * worse, but not strictly ordered. Therefore, an earlier
330                      * node with the same sample value is better in most cases
331                      * (and thus the current is skipped), but not strictly
332                      * in all cases. Only skipping samples where ssd >=
333                      * ssd of the earlier node with the same sample gives
334                      * slightly worse quality, though, for some reason. */ \
335                     h = &hash[(uint16_t) dec_sample];\
336                     if (*h == generation)\
337                         goto next_##NAME;\
338                     if (heap_pos < frontier) {\
339                         pos = heap_pos++;\
340                     } else {\
341                         /* Try to replace one of the leaf nodes with the new \
342                          * one, but try a different slot each time. */\
343                         pos = (frontier >> 1) + (heap_pos & ((frontier >> 1) - 1));\
344                         if (ssd > nodes_next[pos]->ssd)\
345                             goto next_##NAME;\
346                         heap_pos++;\
347                     }\
348                     *h = generation;\
349                     u = nodes_next[pos];\
350                     if(!u) {\
351                         assert(pathn < FREEZE_INTERVAL<<avctx->trellis);\
352                         u = t++;\
353                         nodes_next[pos] = u;\
354                         u->path = pathn++;\
355                     }\
356                     u->ssd = ssd;\
357                     u->step = STEP_INDEX;\
358                     u->sample2 = nodes[j]->sample1;\
359                     u->sample1 = dec_sample;\
360                     paths[u->path].nibble = nibble;\
361                     paths[u->path].prev = nodes[j]->path;\
362                     /* Sift the newly inserted node up in the heap to \
363                      * restore the heap property. */\
364                     while (pos > 0) {\
365                         int parent = (pos - 1) >> 1;\
366                         if (nodes_next[parent]->ssd <= ssd)\
367                             break;\
368                         FFSWAP(TrellisNode*, nodes_next[parent], nodes_next[pos]);\
369                         pos = parent;\
370                     }\
371                     next_##NAME:;
372                     STORE_NODE(ms, FFMAX(16, (ff_adpcm_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 * ff_adpcm_yamaha_difflookup[nibble]) / 8;\
385                     STORE_NODE(NAME, STEP_INDEX);\
386                 }
387                 LOOP_NODES(ima, ff_adpcm_step_table[step], av_clip(step + ff_adpcm_index_table[nibble], 0, 88));
388             } else { //CODEC_ID_ADPCM_YAMAHA
389                 LOOP_NODES(yamaha, step, av_clip((step * ff_adpcm_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         generation++;
400         if (generation == 255) {
401             memset(hash, 0xff, 65536 * sizeof(*hash));
402             generation = 0;
403         }
404
405         // prevent overflow
406         if(nodes[0]->ssd > (1<<28)) {
407             for(j=1; j<frontier && nodes[j]; j++)
408                 nodes[j]->ssd -= nodes[0]->ssd;
409             nodes[0]->ssd = 0;
410         }
411
412         // merge old paths to save memory
413         if(i == froze + FREEZE_INTERVAL) {
414             p = &paths[nodes[0]->path];
415             for(k=i; k>froze; k--) {
416                 dst[k] = p->nibble;
417                 p = &paths[p->prev];
418             }
419             froze = i;
420             pathn = 0;
421             // other nodes might use paths that don't coincide with the frozen one.
422             // checking which nodes do so is too slow, so just kill them all.
423             // this also slightly improves quality, but I don't know why.
424             memset(nodes+1, 0, (frontier-1)*sizeof(TrellisNode*));
425         }
426     }
427
428     p = &paths[nodes[0]->path];
429     for(i=n-1; i>froze; i--) {
430         dst[i] = p->nibble;
431         p = &paths[p->prev];
432     }
433
434     c->predictor = nodes[0]->sample1;
435     c->sample1 = nodes[0]->sample1;
436     c->sample2 = nodes[0]->sample2;
437     c->step_index = nodes[0]->step;
438     c->step = nodes[0]->step;
439     c->idelta = nodes[0]->step;
440 }
441
442 static int adpcm_encode_frame(AVCodecContext *avctx,
443                             unsigned char *frame, int buf_size, void *data)
444 {
445     int n, i, st;
446     short *samples;
447     unsigned char *dst;
448     ADPCMEncodeContext *c = avctx->priv_data;
449     uint8_t *buf;
450
451     dst = frame;
452     samples = (short *)data;
453     st= avctx->channels == 2;
454 /*    n = (BLKSIZE - 4 * avctx->channels) / (2 * 8 * avctx->channels); */
455
456     switch(avctx->codec->id) {
457     case CODEC_ID_ADPCM_IMA_WAV:
458         n = avctx->frame_size / 8;
459             c->status[0].prev_sample = (signed short)samples[0]; /* XXX */
460 /*            c->status[0].step_index = 0; *//* XXX: not sure how to init the state machine */
461             bytestream_put_le16(&dst, c->status[0].prev_sample);
462             *dst++ = (unsigned char)c->status[0].step_index;
463             *dst++ = 0; /* unknown */
464             samples++;
465             if (avctx->channels == 2) {
466                 c->status[1].prev_sample = (signed short)samples[0];
467 /*                c->status[1].step_index = 0; */
468                 bytestream_put_le16(&dst, c->status[1].prev_sample);
469                 *dst++ = (unsigned char)c->status[1].step_index;
470                 *dst++ = 0;
471                 samples++;
472             }
473
474             /* stereo: 4 bytes (8 samples) for left, 4 bytes for right, 4 bytes left, ... */
475             if(avctx->trellis > 0) {
476                 FF_ALLOC_OR_GOTO(avctx, buf, 2*n*8, error);
477                 adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n*8);
478                 if(avctx->channels == 2)
479                     adpcm_compress_trellis(avctx, samples+1, buf + n*8, &c->status[1], n*8);
480                 for(i=0; i<n; i++) {
481                     *dst++ = buf[8*i+0] | (buf[8*i+1] << 4);
482                     *dst++ = buf[8*i+2] | (buf[8*i+3] << 4);
483                     *dst++ = buf[8*i+4] | (buf[8*i+5] << 4);
484                     *dst++ = buf[8*i+6] | (buf[8*i+7] << 4);
485                     if (avctx->channels == 2) {
486                         uint8_t *buf1 = buf + n*8;
487                         *dst++ = buf1[8*i+0] | (buf1[8*i+1] << 4);
488                         *dst++ = buf1[8*i+2] | (buf1[8*i+3] << 4);
489                         *dst++ = buf1[8*i+4] | (buf1[8*i+5] << 4);
490                         *dst++ = buf1[8*i+6] | (buf1[8*i+7] << 4);
491                     }
492                 }
493                 av_free(buf);
494             } else
495             for (; n>0; n--) {
496                 *dst = adpcm_ima_compress_sample(&c->status[0], samples[0]);
497                 *dst |= adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels]) << 4;
498                 dst++;
499                 *dst = adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 2]);
500                 *dst |= adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 3]) << 4;
501                 dst++;
502                 *dst = adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 4]);
503                 *dst |= adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 5]) << 4;
504                 dst++;
505                 *dst = adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 6]);
506                 *dst |= adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 7]) << 4;
507                 dst++;
508                 /* right channel */
509                 if (avctx->channels == 2) {
510                     *dst = adpcm_ima_compress_sample(&c->status[1], samples[1]);
511                     *dst |= adpcm_ima_compress_sample(&c->status[1], samples[3]) << 4;
512                     dst++;
513                     *dst = adpcm_ima_compress_sample(&c->status[1], samples[5]);
514                     *dst |= adpcm_ima_compress_sample(&c->status[1], samples[7]) << 4;
515                     dst++;
516                     *dst = adpcm_ima_compress_sample(&c->status[1], samples[9]);
517                     *dst |= adpcm_ima_compress_sample(&c->status[1], samples[11]) << 4;
518                     dst++;
519                     *dst = adpcm_ima_compress_sample(&c->status[1], samples[13]);
520                     *dst |= adpcm_ima_compress_sample(&c->status[1], samples[15]) << 4;
521                     dst++;
522                 }
523                 samples += 8 * avctx->channels;
524             }
525         break;
526     case CODEC_ID_ADPCM_IMA_QT:
527     {
528         int ch, i;
529         PutBitContext pb;
530         init_put_bits(&pb, dst, buf_size*8);
531
532         for(ch=0; ch<avctx->channels; ch++){
533             put_bits(&pb, 9, (c->status[ch].prev_sample + 0x10000) >> 7);
534             put_bits(&pb, 7, c->status[ch].step_index);
535             if(avctx->trellis > 0) {
536                 uint8_t buf[64];
537                 adpcm_compress_trellis(avctx, samples+ch, buf, &c->status[ch], 64);
538                 for(i=0; i<64; i++)
539                     put_bits(&pb, 4, buf[i^1]);
540             } else {
541                 for (i=0; i<64; i+=2){
542                     int t1, t2;
543                     t1 = adpcm_ima_qt_compress_sample(&c->status[ch], samples[avctx->channels*(i+0)+ch]);
544                     t2 = adpcm_ima_qt_compress_sample(&c->status[ch], samples[avctx->channels*(i+1)+ch]);
545                     put_bits(&pb, 4, t2);
546                     put_bits(&pb, 4, t1);
547                 }
548             }
549         }
550
551         flush_put_bits(&pb);
552         dst += put_bits_count(&pb)>>3;
553         break;
554     }
555     case CODEC_ID_ADPCM_SWF:
556     {
557         int i;
558         PutBitContext pb;
559         init_put_bits(&pb, dst, buf_size*8);
560
561         n = avctx->frame_size-1;
562
563         //Store AdpcmCodeSize
564         put_bits(&pb, 2, 2);                //Set 4bits flash adpcm format
565
566         //Init the encoder state
567         for(i=0; i<avctx->channels; i++){
568             c->status[i].step_index = av_clip(c->status[i].step_index, 0, 63); // clip step so it fits 6 bits
569             put_sbits(&pb, 16, samples[i]);
570             put_bits(&pb, 6, c->status[i].step_index);
571             c->status[i].prev_sample = (signed short)samples[i];
572         }
573
574         if(avctx->trellis > 0) {
575             FF_ALLOC_OR_GOTO(avctx, buf, 2*n, error);
576             adpcm_compress_trellis(avctx, samples+2, buf, &c->status[0], n);
577             if (avctx->channels == 2)
578                 adpcm_compress_trellis(avctx, samples+3, buf+n, &c->status[1], n);
579             for(i=0; i<n; i++) {
580                 put_bits(&pb, 4, buf[i]);
581                 if (avctx->channels == 2)
582                     put_bits(&pb, 4, buf[n+i]);
583             }
584             av_free(buf);
585         } else {
586             for (i=1; i<avctx->frame_size; i++) {
587                 put_bits(&pb, 4, adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels*i]));
588                 if (avctx->channels == 2)
589                     put_bits(&pb, 4, adpcm_ima_compress_sample(&c->status[1], samples[2*i+1]));
590             }
591         }
592         flush_put_bits(&pb);
593         dst += put_bits_count(&pb)>>3;
594         break;
595     }
596     case CODEC_ID_ADPCM_MS:
597         for(i=0; i<avctx->channels; i++){
598             int predictor=0;
599
600             *dst++ = predictor;
601             c->status[i].coeff1 = ff_adpcm_AdaptCoeff1[predictor];
602             c->status[i].coeff2 = ff_adpcm_AdaptCoeff2[predictor];
603         }
604         for(i=0; i<avctx->channels; i++){
605             if (c->status[i].idelta < 16)
606                 c->status[i].idelta = 16;
607
608             bytestream_put_le16(&dst, c->status[i].idelta);
609         }
610         for(i=0; i<avctx->channels; i++){
611             c->status[i].sample2= *samples++;
612         }
613         for(i=0; i<avctx->channels; i++){
614             c->status[i].sample1= *samples++;
615
616             bytestream_put_le16(&dst, c->status[i].sample1);
617         }
618         for(i=0; i<avctx->channels; i++)
619             bytestream_put_le16(&dst, c->status[i].sample2);
620
621         if(avctx->trellis > 0) {
622             int n = avctx->block_align - 7*avctx->channels;
623             FF_ALLOC_OR_GOTO(avctx, buf, 2*n, error);
624             if(avctx->channels == 1) {
625                 adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n);
626                 for(i=0; i<n; i+=2)
627                     *dst++ = (buf[i] << 4) | buf[i+1];
628             } else {
629                 adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n);
630                 adpcm_compress_trellis(avctx, samples+1, buf+n, &c->status[1], n);
631                 for(i=0; i<n; i++)
632                     *dst++ = (buf[i] << 4) | buf[n+i];
633             }
634             av_free(buf);
635         } else
636         for(i=7*avctx->channels; i<avctx->block_align; i++) {
637             int nibble;
638             nibble = adpcm_ms_compress_sample(&c->status[ 0], *samples++)<<4;
639             nibble|= adpcm_ms_compress_sample(&c->status[st], *samples++);
640             *dst++ = nibble;
641         }
642         break;
643     case CODEC_ID_ADPCM_YAMAHA:
644         n = avctx->frame_size / 2;
645         if(avctx->trellis > 0) {
646             FF_ALLOC_OR_GOTO(avctx, buf, 2*n*2, error);
647             n *= 2;
648             if(avctx->channels == 1) {
649                 adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n);
650                 for(i=0; i<n; i+=2)
651                     *dst++ = buf[i] | (buf[i+1] << 4);
652             } else {
653                 adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n);
654                 adpcm_compress_trellis(avctx, samples+1, buf+n, &c->status[1], n);
655                 for(i=0; i<n; i++)
656                     *dst++ = buf[i] | (buf[n+i] << 4);
657             }
658             av_free(buf);
659         } else
660             for (n *= avctx->channels; n>0; n--) {
661                 int nibble;
662                 nibble  = adpcm_yamaha_compress_sample(&c->status[ 0], *samples++);
663                 nibble |= adpcm_yamaha_compress_sample(&c->status[st], *samples++) << 4;
664                 *dst++ = nibble;
665             }
666         break;
667     default:
668     error:
669         return -1;
670     }
671     return dst - frame;
672 }
673
674
675 #define ADPCM_ENCODER(id_, name_, long_name_)               \
676 AVCodec ff_ ## name_ ## _encoder = {                        \
677     .name           = #name_,                               \
678     .type           = AVMEDIA_TYPE_AUDIO,                   \
679     .id             = id_,                                  \
680     .priv_data_size = sizeof(ADPCMEncodeContext),           \
681     .init           = adpcm_encode_init,                    \
682     .encode         = adpcm_encode_frame,                   \
683     .close          = adpcm_encode_close,                   \
684     .sample_fmts    = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE}, \
685     .long_name      = NULL_IF_CONFIG_SMALL(long_name_),     \
686 }
687
688 ADPCM_ENCODER(CODEC_ID_ADPCM_IMA_QT, adpcm_ima_qt, "ADPCM IMA QuickTime");
689 ADPCM_ENCODER(CODEC_ID_ADPCM_IMA_WAV, adpcm_ima_wav, "ADPCM IMA WAV");
690 ADPCM_ENCODER(CODEC_ID_ADPCM_MS, adpcm_ms, "ADPCM Microsoft");
691 ADPCM_ENCODER(CODEC_ID_ADPCM_SWF, adpcm_swf, "ADPCM Shockwave Flash");
692 ADPCM_ENCODER(CODEC_ID_ADPCM_YAMAHA, adpcm_yamaha, "ADPCM Yamaha");