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