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