]> git.sesse.net Git - ffmpeg/blob - libavcodec/adpcmenc.c
avcodec/adpcmenc: remove FF_ALLOC_OR_GOTO macros and gotos lable
[ffmpeg] / libavcodec / adpcmenc.c
1 /*
2  * Copyright (c) 2001-2003 The FFmpeg project
3  *
4  * first version by Francois Revol (revol@free.fr)
5  * fringe ADPCM codecs (e.g., DK3, DK4, Westwood)
6  *   by Mike Melanson (melanson@pcisys.net)
7  *
8  * This file is part of FFmpeg.
9  *
10  * FFmpeg is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * FFmpeg is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with FFmpeg; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23  */
24
25 #include "avcodec.h"
26 #include "put_bits.h"
27 #include "bytestream.h"
28 #include "adpcm.h"
29 #include "adpcm_data.h"
30 #include "internal.h"
31
32 /**
33  * @file
34  * ADPCM encoders
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
69     if (avctx->channels > 2) {
70         av_log(avctx, AV_LOG_ERROR, "only stereo or mono is supported\n");
71         return AVERROR(EINVAL);
72     }
73
74     if (avctx->trellis && (unsigned)avctx->trellis > 16U) {
75         av_log(avctx, AV_LOG_ERROR, "invalid trellis size\n");
76         return AVERROR(EINVAL);
77     }
78
79     if (avctx->trellis && avctx->codec->id == AV_CODEC_ID_ADPCM_IMA_SSI) {
80         /*
81          * The current trellis implementation doesn't work for extended
82          * runs of samples without periodic resets. Disallow it.
83          */
84         av_log(avctx, AV_LOG_ERROR, "trellis not supported\n");
85         return AVERROR_PATCHWELCOME;
86     }
87
88     if (avctx->trellis) {
89         int frontier  = 1 << avctx->trellis;
90         int max_paths =  frontier * FREEZE_INTERVAL;
91         if (!FF_ALLOC_TYPED_ARRAY(s->paths,        max_paths)    ||
92             !FF_ALLOC_TYPED_ARRAY(s->node_buf,     2 * frontier) ||
93             !FF_ALLOC_TYPED_ARRAY(s->nodep_buf,    2 * frontier) ||
94             !FF_ALLOC_TYPED_ARRAY(s->trellis_hash, 65536))
95             return AVERROR(ENOMEM);
96     }
97
98     avctx->bits_per_coded_sample = av_get_bits_per_sample(avctx->codec->id);
99
100     switch (avctx->codec->id) {
101     case AV_CODEC_ID_ADPCM_IMA_WAV:
102         /* each 16 bits sample gives one nibble
103            and we have 4 bytes per channel overhead */
104         avctx->frame_size = (BLKSIZE - 4 * avctx->channels) * 8 /
105                             (4 * avctx->channels) + 1;
106         /* seems frame_size isn't taken into account...
107            have to buffer the samples :-( */
108         avctx->block_align = BLKSIZE;
109         avctx->bits_per_coded_sample = 4;
110         break;
111     case AV_CODEC_ID_ADPCM_IMA_QT:
112         avctx->frame_size  = 64;
113         avctx->block_align = 34 * avctx->channels;
114         break;
115     case AV_CODEC_ID_ADPCM_MS:
116         /* each 16 bits sample gives one nibble
117            and we have 7 bytes per channel overhead */
118         avctx->frame_size = (BLKSIZE - 7 * avctx->channels) * 2 / avctx->channels + 2;
119         avctx->bits_per_coded_sample = 4;
120         avctx->block_align    = BLKSIZE;
121         if (!(avctx->extradata = av_malloc(32 + AV_INPUT_BUFFER_PADDING_SIZE)))
122             return AVERROR(ENOMEM);
123         avctx->extradata_size = 32;
124         extradata = avctx->extradata;
125         bytestream_put_le16(&extradata, avctx->frame_size);
126         bytestream_put_le16(&extradata, 7); /* wNumCoef */
127         for (i = 0; i < 7; i++) {
128             bytestream_put_le16(&extradata, ff_adpcm_AdaptCoeff1[i] * 4);
129             bytestream_put_le16(&extradata, ff_adpcm_AdaptCoeff2[i] * 4);
130         }
131         break;
132     case AV_CODEC_ID_ADPCM_YAMAHA:
133         avctx->frame_size  = BLKSIZE * 2 / avctx->channels;
134         avctx->block_align = BLKSIZE;
135         break;
136     case AV_CODEC_ID_ADPCM_SWF:
137         if (avctx->sample_rate != 11025 &&
138             avctx->sample_rate != 22050 &&
139             avctx->sample_rate != 44100) {
140             av_log(avctx, AV_LOG_ERROR, "Sample rate must be 11025, "
141                    "22050 or 44100\n");
142             return AVERROR(EINVAL);
143         }
144         avctx->frame_size = 512 * (avctx->sample_rate / 11025);
145         break;
146     case AV_CODEC_ID_ADPCM_IMA_SSI:
147         avctx->frame_size = BLKSIZE * 2 / avctx->channels;
148         avctx->block_align = BLKSIZE;
149         break;
150     default:
151         return AVERROR(EINVAL);
152     }
153
154     return 0;
155 }
156
157 static av_cold int adpcm_encode_close(AVCodecContext *avctx)
158 {
159     ADPCMEncodeContext *s = avctx->priv_data;
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_intp2(nibble, 3) & 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, 24576);
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, int stride)
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 version  = avctx->codec->id;
278     TrellisPath *paths       = s->paths, *p;
279     TrellisNode *node_buf    = s->node_buf;
280     TrellisNode **nodep_buf  = s->nodep_buf;
281     TrellisNode **nodes      = nodep_buf; // nodes[] is always sorted by .ssd
282     TrellisNode **nodes_next = nodep_buf + frontier;
283     int pathn = 0, froze = -1, i, j, k, generation = 0;
284     uint8_t *hash = s->trellis_hash;
285     memset(hash, 0xff, 65536 * sizeof(*hash));
286
287     memset(nodep_buf, 0, 2 * frontier * sizeof(*nodep_buf));
288     nodes[0]          = node_buf + frontier;
289     nodes[0]->ssd     = 0;
290     nodes[0]->path    = 0;
291     nodes[0]->step    = c->step_index;
292     nodes[0]->sample1 = c->sample1;
293     nodes[0]->sample2 = c->sample2;
294     if (version == AV_CODEC_ID_ADPCM_IMA_WAV ||
295         version == AV_CODEC_ID_ADPCM_IMA_QT  ||
296         version == AV_CODEC_ID_ADPCM_SWF)
297         nodes[0]->sample1 = c->prev_sample;
298     if (version == AV_CODEC_ID_ADPCM_MS)
299         nodes[0]->step = c->idelta;
300     if (version == AV_CODEC_ID_ADPCM_YAMAHA) {
301         if (c->step == 0) {
302             nodes[0]->step    = 127;
303             nodes[0]->sample1 = 0;
304         } else {
305             nodes[0]->step    = c->step;
306             nodes[0]->sample1 = c->predictor;
307         }
308     }
309
310     for (i = 0; i < n; i++) {
311         TrellisNode *t = node_buf + frontier*(i&1);
312         TrellisNode **u;
313         int sample   = samples[i * stride];
314         int heap_pos = 0;
315         memset(nodes_next, 0, frontier * sizeof(TrellisNode*));
316         for (j = 0; j < frontier && nodes[j]; j++) {
317             // higher j have higher ssd already, so they're likely
318             // to yield a suboptimal next sample too
319             const int range = (j < frontier / 2) ? 1 : 0;
320             const int step  = nodes[j]->step;
321             int nidx;
322             if (version == AV_CODEC_ID_ADPCM_MS) {
323                 const int predictor = ((nodes[j]->sample1 * c->coeff1) +
324                                        (nodes[j]->sample2 * c->coeff2)) / 64;
325                 const int div  = (sample - predictor) / step;
326                 const int nmin = av_clip(div-range, -8, 6);
327                 const int nmax = av_clip(div+range, -7, 7);
328                 for (nidx = nmin; nidx <= nmax; nidx++) {
329                     const int nibble = nidx & 0xf;
330                     int dec_sample   = predictor + nidx * step;
331 #define STORE_NODE(NAME, STEP_INDEX)\
332                     int d;\
333                     uint32_t ssd;\
334                     int pos;\
335                     TrellisNode *u;\
336                     uint8_t *h;\
337                     dec_sample = av_clip_int16(dec_sample);\
338                     d = sample - dec_sample;\
339                     ssd = nodes[j]->ssd + d*(unsigned)d;\
340                     /* Check for wraparound, skip such samples completely. \
341                      * Note, changing ssd to a 64 bit variable would be \
342                      * simpler, avoiding this check, but it's slower on \
343                      * x86 32 bit at the moment. */\
344                     if (ssd < nodes[j]->ssd)\
345                         goto next_##NAME;\
346                     /* Collapse any two states with the same previous sample value. \
347                      * One could also distinguish states by step and by 2nd to last
348                      * sample, but the effects of that are negligible.
349                      * Since nodes in the previous generation are iterated
350                      * through a heap, they're roughly ordered from better to
351                      * worse, but not strictly ordered. Therefore, an earlier
352                      * node with the same sample value is better in most cases
353                      * (and thus the current is skipped), but not strictly
354                      * in all cases. Only skipping samples where ssd >=
355                      * ssd of the earlier node with the same sample gives
356                      * slightly worse quality, though, for some reason. */ \
357                     h = &hash[(uint16_t) dec_sample];\
358                     if (*h == generation)\
359                         goto next_##NAME;\
360                     if (heap_pos < frontier) {\
361                         pos = heap_pos++;\
362                     } else {\
363                         /* Try to replace one of the leaf nodes with the new \
364                          * one, but try a different slot each time. */\
365                         pos = (frontier >> 1) +\
366                               (heap_pos & ((frontier >> 1) - 1));\
367                         if (ssd > nodes_next[pos]->ssd)\
368                             goto next_##NAME;\
369                         heap_pos++;\
370                     }\
371                     *h = generation;\
372                     u  = nodes_next[pos];\
373                     if (!u) {\
374                         av_assert1(pathn < FREEZE_INTERVAL << avctx->trellis);\
375                         u = t++;\
376                         nodes_next[pos] = u;\
377                         u->path = pathn++;\
378                     }\
379                     u->ssd  = ssd;\
380                     u->step = STEP_INDEX;\
381                     u->sample2 = nodes[j]->sample1;\
382                     u->sample1 = dec_sample;\
383                     paths[u->path].nibble = nibble;\
384                     paths[u->path].prev   = nodes[j]->path;\
385                     /* Sift the newly inserted node up in the heap to \
386                      * restore the heap property. */\
387                     while (pos > 0) {\
388                         int parent = (pos - 1) >> 1;\
389                         if (nodes_next[parent]->ssd <= ssd)\
390                             break;\
391                         FFSWAP(TrellisNode*, nodes_next[parent], nodes_next[pos]);\
392                         pos = parent;\
393                     }\
394                     next_##NAME:;
395                     STORE_NODE(ms, FFMAX(16,
396                                (ff_adpcm_AdaptationTable[nibble] * step) >> 8));
397                 }
398             } else if (version == AV_CODEC_ID_ADPCM_IMA_WAV ||
399                        version == AV_CODEC_ID_ADPCM_IMA_QT  ||
400                        version == AV_CODEC_ID_ADPCM_SWF) {
401 #define LOOP_NODES(NAME, STEP_TABLE, STEP_INDEX)\
402                 const int predictor = nodes[j]->sample1;\
403                 const int div = (sample - predictor) * 4 / STEP_TABLE;\
404                 int nmin = av_clip(div - range, -7, 6);\
405                 int nmax = av_clip(div + range, -6, 7);\
406                 if (nmin <= 0)\
407                     nmin--; /* distinguish -0 from +0 */\
408                 if (nmax < 0)\
409                     nmax--;\
410                 for (nidx = nmin; nidx <= nmax; nidx++) {\
411                     const int nibble = nidx < 0 ? 7 - nidx : nidx;\
412                     int dec_sample = predictor +\
413                                     (STEP_TABLE *\
414                                      ff_adpcm_yamaha_difflookup[nibble]) / 8;\
415                     STORE_NODE(NAME, STEP_INDEX);\
416                 }
417                 LOOP_NODES(ima, ff_adpcm_step_table[step],
418                            av_clip(step + ff_adpcm_index_table[nibble], 0, 88));
419             } else { //AV_CODEC_ID_ADPCM_YAMAHA
420                 LOOP_NODES(yamaha, step,
421                            av_clip((step * ff_adpcm_yamaha_indexscale[nibble]) >> 8,
422                                    127, 24576));
423 #undef LOOP_NODES
424 #undef STORE_NODE
425             }
426         }
427
428         u = nodes;
429         nodes = nodes_next;
430         nodes_next = u;
431
432         generation++;
433         if (generation == 255) {
434             memset(hash, 0xff, 65536 * sizeof(*hash));
435             generation = 0;
436         }
437
438         // prevent overflow
439         if (nodes[0]->ssd > (1 << 28)) {
440             for (j = 1; j < frontier && nodes[j]; j++)
441                 nodes[j]->ssd -= nodes[0]->ssd;
442             nodes[0]->ssd = 0;
443         }
444
445         // merge old paths to save memory
446         if (i == froze + FREEZE_INTERVAL) {
447             p = &paths[nodes[0]->path];
448             for (k = i; k > froze; k--) {
449                 dst[k] = p->nibble;
450                 p = &paths[p->prev];
451             }
452             froze = i;
453             pathn = 0;
454             // other nodes might use paths that don't coincide with the frozen one.
455             // checking which nodes do so is too slow, so just kill them all.
456             // this also slightly improves quality, but I don't know why.
457             memset(nodes + 1, 0, (frontier - 1) * sizeof(TrellisNode*));
458         }
459     }
460
461     p = &paths[nodes[0]->path];
462     for (i = n - 1; i > froze; i--) {
463         dst[i] = p->nibble;
464         p = &paths[p->prev];
465     }
466
467     c->predictor  = nodes[0]->sample1;
468     c->sample1    = nodes[0]->sample1;
469     c->sample2    = nodes[0]->sample2;
470     c->step_index = nodes[0]->step;
471     c->step       = nodes[0]->step;
472     c->idelta     = nodes[0]->step;
473 }
474
475 static int adpcm_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
476                               const AVFrame *frame, int *got_packet_ptr)
477 {
478     int n, i, ch, st, pkt_size, ret;
479     const int16_t *samples;
480     int16_t **samples_p;
481     uint8_t *dst;
482     ADPCMEncodeContext *c = avctx->priv_data;
483     uint8_t *buf;
484
485     samples = (const int16_t *)frame->data[0];
486     samples_p = (int16_t **)frame->extended_data;
487     st = avctx->channels == 2;
488
489     if (avctx->codec_id == AV_CODEC_ID_ADPCM_SWF)
490         pkt_size = (2 + avctx->channels * (22 + 4 * (frame->nb_samples - 1)) + 7) / 8;
491     else if (avctx->codec_id == AV_CODEC_ID_ADPCM_IMA_SSI)
492         pkt_size = (frame->nb_samples * avctx->channels) / 2;
493     else
494         pkt_size = avctx->block_align;
495     if ((ret = ff_alloc_packet2(avctx, avpkt, pkt_size, 0)) < 0)
496         return ret;
497     dst = avpkt->data;
498
499     switch(avctx->codec->id) {
500     case AV_CODEC_ID_ADPCM_IMA_WAV:
501     {
502         int blocks, j;
503
504         blocks = (frame->nb_samples - 1) / 8;
505
506         for (ch = 0; ch < avctx->channels; ch++) {
507             ADPCMChannelStatus *status = &c->status[ch];
508             status->prev_sample = samples_p[ch][0];
509             /* status->step_index = 0;
510                XXX: not sure how to init the state machine */
511             bytestream_put_le16(&dst, status->prev_sample);
512             *dst++ = status->step_index;
513             *dst++ = 0; /* unknown */
514         }
515
516         /* stereo: 4 bytes (8 samples) for left, 4 bytes for right */
517         if (avctx->trellis > 0) {
518             if (!FF_ALLOC_TYPED_ARRAY(buf, avctx->channels * blocks * 8))
519                 return AVERROR(ENOMEM);
520             for (ch = 0; ch < avctx->channels; ch++) {
521                 adpcm_compress_trellis(avctx, &samples_p[ch][1],
522                                        buf + ch * blocks * 8, &c->status[ch],
523                                        blocks * 8, 1);
524             }
525             for (i = 0; i < blocks; i++) {
526                 for (ch = 0; ch < avctx->channels; ch++) {
527                     uint8_t *buf1 = buf + ch * blocks * 8 + i * 8;
528                     for (j = 0; j < 8; j += 2)
529                         *dst++ = buf1[j] | (buf1[j + 1] << 4);
530                 }
531             }
532             av_free(buf);
533         } else {
534             for (i = 0; i < blocks; i++) {
535                 for (ch = 0; ch < avctx->channels; ch++) {
536                     ADPCMChannelStatus *status = &c->status[ch];
537                     const int16_t *smp = &samples_p[ch][1 + i * 8];
538                     for (j = 0; j < 8; j += 2) {
539                         uint8_t v = adpcm_ima_compress_sample(status, smp[j    ]);
540                         v        |= adpcm_ima_compress_sample(status, smp[j + 1]) << 4;
541                         *dst++ = v;
542                     }
543                 }
544             }
545         }
546         break;
547     }
548     case AV_CODEC_ID_ADPCM_IMA_QT:
549     {
550         PutBitContext pb;
551         init_put_bits(&pb, dst, pkt_size);
552
553         for (ch = 0; ch < avctx->channels; ch++) {
554             ADPCMChannelStatus *status = &c->status[ch];
555             put_bits(&pb, 9, (status->prev_sample & 0xFFFF) >> 7);
556             put_bits(&pb, 7,  status->step_index);
557             if (avctx->trellis > 0) {
558                 uint8_t buf[64];
559                 adpcm_compress_trellis(avctx, &samples_p[ch][0], buf, status,
560                                        64, 1);
561                 for (i = 0; i < 64; i++)
562                     put_bits(&pb, 4, buf[i ^ 1]);
563                 status->prev_sample = status->predictor;
564             } else {
565                 for (i = 0; i < 64; i += 2) {
566                     int t1, t2;
567                     t1 = adpcm_ima_qt_compress_sample(status, samples_p[ch][i    ]);
568                     t2 = adpcm_ima_qt_compress_sample(status, samples_p[ch][i + 1]);
569                     put_bits(&pb, 4, t2);
570                     put_bits(&pb, 4, t1);
571                 }
572             }
573         }
574
575         flush_put_bits(&pb);
576         break;
577     }
578     case AV_CODEC_ID_ADPCM_IMA_SSI:
579     {
580         PutBitContext pb;
581         init_put_bits(&pb, dst, pkt_size);
582
583         av_assert0(avctx->trellis == 0);
584
585         for (i = 0; i < frame->nb_samples; i++) {
586             for (ch = 0; ch < avctx->channels; ch++) {
587                 put_bits(&pb, 4, adpcm_ima_qt_compress_sample(c->status + ch, *samples++));
588             }
589         }
590
591         flush_put_bits(&pb);
592         break;
593     }
594     case AV_CODEC_ID_ADPCM_SWF:
595     {
596         PutBitContext pb;
597         init_put_bits(&pb, dst, pkt_size);
598
599         n = frame->nb_samples - 1;
600
601         // store AdpcmCodeSize
602         put_bits(&pb, 2, 2);    // set 4-bit flash adpcm format
603
604         // init the encoder state
605         for (i = 0; i < avctx->channels; i++) {
606             // clip step so it fits 6 bits
607             c->status[i].step_index = av_clip_uintp2(c->status[i].step_index, 6);
608             put_sbits(&pb, 16, samples[i]);
609             put_bits(&pb, 6, c->status[i].step_index);
610             c->status[i].prev_sample = samples[i];
611         }
612
613         if (avctx->trellis > 0) {
614             if (!(buf = av_malloc(2 * n)))
615                 return AVERROR(ENOMEM);
616             adpcm_compress_trellis(avctx, samples + avctx->channels, buf,
617                                    &c->status[0], n, avctx->channels);
618             if (avctx->channels == 2)
619                 adpcm_compress_trellis(avctx, samples + avctx->channels + 1,
620                                        buf + n, &c->status[1], n,
621                                        avctx->channels);
622             for (i = 0; i < n; i++) {
623                 put_bits(&pb, 4, buf[i]);
624                 if (avctx->channels == 2)
625                     put_bits(&pb, 4, buf[n + i]);
626             }
627             av_free(buf);
628         } else {
629             for (i = 1; i < frame->nb_samples; i++) {
630                 put_bits(&pb, 4, adpcm_ima_compress_sample(&c->status[0],
631                          samples[avctx->channels * i]));
632                 if (avctx->channels == 2)
633                     put_bits(&pb, 4, adpcm_ima_compress_sample(&c->status[1],
634                              samples[2 * i + 1]));
635             }
636         }
637         flush_put_bits(&pb);
638         break;
639     }
640     case AV_CODEC_ID_ADPCM_MS:
641         for (i = 0; i < avctx->channels; i++) {
642             int predictor = 0;
643             *dst++ = predictor;
644             c->status[i].coeff1 = ff_adpcm_AdaptCoeff1[predictor];
645             c->status[i].coeff2 = ff_adpcm_AdaptCoeff2[predictor];
646         }
647         for (i = 0; i < avctx->channels; i++) {
648             if (c->status[i].idelta < 16)
649                 c->status[i].idelta = 16;
650             bytestream_put_le16(&dst, c->status[i].idelta);
651         }
652         for (i = 0; i < avctx->channels; i++)
653             c->status[i].sample2= *samples++;
654         for (i = 0; i < avctx->channels; i++) {
655             c->status[i].sample1 = *samples++;
656             bytestream_put_le16(&dst, c->status[i].sample1);
657         }
658         for (i = 0; i < avctx->channels; i++)
659             bytestream_put_le16(&dst, c->status[i].sample2);
660
661         if (avctx->trellis > 0) {
662             n = avctx->block_align - 7 * avctx->channels;
663             if (!(buf = av_malloc(2 * n)))
664                 return AVERROR(ENOMEM);
665             if (avctx->channels == 1) {
666                 adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n,
667                                        avctx->channels);
668                 for (i = 0; i < n; i += 2)
669                     *dst++ = (buf[i] << 4) | buf[i + 1];
670             } else {
671                 adpcm_compress_trellis(avctx, samples,     buf,
672                                        &c->status[0], n, avctx->channels);
673                 adpcm_compress_trellis(avctx, samples + 1, buf + n,
674                                        &c->status[1], n, avctx->channels);
675                 for (i = 0; i < n; i++)
676                     *dst++ = (buf[i] << 4) | buf[n + i];
677             }
678             av_free(buf);
679         } else {
680             for (i = 7 * avctx->channels; i < avctx->block_align; i++) {
681                 int nibble;
682                 nibble  = adpcm_ms_compress_sample(&c->status[ 0], *samples++) << 4;
683                 nibble |= adpcm_ms_compress_sample(&c->status[st], *samples++);
684                 *dst++  = nibble;
685             }
686         }
687         break;
688     case AV_CODEC_ID_ADPCM_YAMAHA:
689         n = frame->nb_samples / 2;
690         if (avctx->trellis > 0) {
691             if (!(buf = av_malloc(2 * n * 2)))
692                 return AVERROR(ENOMEM);
693             n *= 2;
694             if (avctx->channels == 1) {
695                 adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n,
696                                        avctx->channels);
697                 for (i = 0; i < n; i += 2)
698                     *dst++ = buf[i] | (buf[i + 1] << 4);
699             } else {
700                 adpcm_compress_trellis(avctx, samples,     buf,
701                                        &c->status[0], n, avctx->channels);
702                 adpcm_compress_trellis(avctx, samples + 1, buf + n,
703                                        &c->status[1], n, avctx->channels);
704                 for (i = 0; i < n; i++)
705                     *dst++ = buf[i] | (buf[n + i] << 4);
706             }
707             av_free(buf);
708         } else
709             for (n *= avctx->channels; n > 0; n--) {
710                 int nibble;
711                 nibble  = adpcm_yamaha_compress_sample(&c->status[ 0], *samples++);
712                 nibble |= adpcm_yamaha_compress_sample(&c->status[st], *samples++) << 4;
713                 *dst++  = nibble;
714             }
715         break;
716     default:
717         return AVERROR(EINVAL);
718     }
719
720     avpkt->size = pkt_size;
721     *got_packet_ptr = 1;
722     return 0;
723 }
724
725 static const enum AVSampleFormat sample_fmts[] = {
726     AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
727 };
728
729 static const enum AVSampleFormat sample_fmts_p[] = {
730     AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_NONE
731 };
732
733 #define ADPCM_ENCODER(id_, name_, sample_fmts_, capabilities_, long_name_) \
734 AVCodec ff_ ## name_ ## _encoder = {                                       \
735     .name           = #name_,                                              \
736     .long_name      = NULL_IF_CONFIG_SMALL(long_name_),                    \
737     .type           = AVMEDIA_TYPE_AUDIO,                                  \
738     .id             = id_,                                                 \
739     .priv_data_size = sizeof(ADPCMEncodeContext),                          \
740     .init           = adpcm_encode_init,                                   \
741     .encode2        = adpcm_encode_frame,                                  \
742     .close          = adpcm_encode_close,                                  \
743     .sample_fmts    = sample_fmts_,                                        \
744     .capabilities   = capabilities_,                                       \
745     .caps_internal  = FF_CODEC_CAP_INIT_CLEANUP,                           \
746 }
747
748 ADPCM_ENCODER(AV_CODEC_ID_ADPCM_IMA_QT,  adpcm_ima_qt,  sample_fmts_p, 0,                             "ADPCM IMA QuickTime");
749 ADPCM_ENCODER(AV_CODEC_ID_ADPCM_IMA_SSI, adpcm_ima_ssi, sample_fmts,   AV_CODEC_CAP_SMALL_LAST_FRAME, "ADPCM IMA Simon & Schuster Interactive");
750 ADPCM_ENCODER(AV_CODEC_ID_ADPCM_IMA_WAV, adpcm_ima_wav, sample_fmts_p, 0,                             "ADPCM IMA WAV");
751 ADPCM_ENCODER(AV_CODEC_ID_ADPCM_MS,      adpcm_ms,      sample_fmts,   0,                             "ADPCM Microsoft");
752 ADPCM_ENCODER(AV_CODEC_ID_ADPCM_SWF,     adpcm_swf,     sample_fmts,   0,                             "ADPCM Shockwave Flash");
753 ADPCM_ENCODER(AV_CODEC_ID_ADPCM_YAMAHA,  adpcm_yamaha,  sample_fmts,   0,                             "ADPCM Yamaha");