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