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