]> git.sesse.net Git - ffmpeg/blob - libavcodec/adpcmenc.c
avcodec/adpcm_ima_apm: support custom block size for encoding
[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 "libavutil/opt.h"
26
27 #include "avcodec.h"
28 #include "put_bits.h"
29 #include "bytestream.h"
30 #include "adpcm.h"
31 #include "adpcm_data.h"
32 #include "internal.h"
33
34 /**
35  * @file
36  * ADPCM encoders
37  * See ADPCM decoder reference documents for codec information.
38  */
39
40 typedef struct TrellisPath {
41     int nibble;
42     int prev;
43 } TrellisPath;
44
45 typedef struct TrellisNode {
46     uint32_t ssd;
47     int path;
48     int sample1;
49     int sample2;
50     int step;
51 } TrellisNode;
52
53 typedef struct ADPCMEncodeContext {
54     AVClass *class;
55     int block_size;
56
57     ADPCMChannelStatus status[6];
58     TrellisPath *paths;
59     TrellisNode *node_buf;
60     TrellisNode **nodep_buf;
61     uint8_t *trellis_hash;
62 } ADPCMEncodeContext;
63
64 #define FREEZE_INTERVAL 128
65
66 static av_cold int adpcm_encode_init(AVCodecContext *avctx)
67 {
68     ADPCMEncodeContext *s = avctx->priv_data;
69     uint8_t *extradata;
70     int i;
71
72     if (avctx->channels > 2) {
73         av_log(avctx, AV_LOG_ERROR, "only stereo or mono is supported\n");
74         return AVERROR(EINVAL);
75     }
76
77     if (s->block_size & (s->block_size - 1)) {
78         av_log(avctx, AV_LOG_ERROR, "block size must be power of 2\n");
79         return AVERROR(EINVAL);
80     }
81
82     if (avctx->trellis) {
83         int frontier, max_paths;
84
85         if ((unsigned)avctx->trellis > 16U) {
86             av_log(avctx, AV_LOG_ERROR, "invalid trellis size\n");
87             return AVERROR(EINVAL);
88         }
89
90         if (avctx->codec->id == AV_CODEC_ID_ADPCM_IMA_SSI ||
91             avctx->codec->id == AV_CODEC_ID_ADPCM_IMA_APM ||
92             avctx->codec->id == AV_CODEC_ID_ADPCM_ARGO) {
93             /*
94              * The current trellis implementation doesn't work for extended
95              * runs of samples without periodic resets. Disallow it.
96              */
97             av_log(avctx, AV_LOG_ERROR, "trellis not supported\n");
98             return AVERROR_PATCHWELCOME;
99         }
100
101         frontier  = 1 << avctx->trellis;
102         max_paths =  frontier * FREEZE_INTERVAL;
103         if (!FF_ALLOC_TYPED_ARRAY(s->paths,        max_paths)    ||
104             !FF_ALLOC_TYPED_ARRAY(s->node_buf,     2 * frontier) ||
105             !FF_ALLOC_TYPED_ARRAY(s->nodep_buf,    2 * frontier) ||
106             !FF_ALLOC_TYPED_ARRAY(s->trellis_hash, 65536))
107             return AVERROR(ENOMEM);
108     }
109
110     avctx->bits_per_coded_sample = av_get_bits_per_sample(avctx->codec->id);
111
112     switch (avctx->codec->id) {
113     case AV_CODEC_ID_ADPCM_IMA_WAV:
114         /* each 16 bits sample gives one nibble
115            and we have 4 bytes per channel overhead */
116         avctx->frame_size = (BLKSIZE - 4 * avctx->channels) * 8 /
117                             (4 * avctx->channels) + 1;
118         /* seems frame_size isn't taken into account...
119            have to buffer the samples :-( */
120         avctx->block_align = BLKSIZE;
121         avctx->bits_per_coded_sample = 4;
122         break;
123     case AV_CODEC_ID_ADPCM_IMA_QT:
124         avctx->frame_size  = 64;
125         avctx->block_align = 34 * avctx->channels;
126         break;
127     case AV_CODEC_ID_ADPCM_MS:
128         /* each 16 bits sample gives one nibble
129            and we have 7 bytes per channel overhead */
130         avctx->frame_size = (s->block_size - 7 * avctx->channels) * 2 / avctx->channels + 2;
131         avctx->bits_per_coded_sample = 4;
132         avctx->block_align     = s->block_size;
133         if (!(avctx->extradata = av_malloc(32 + AV_INPUT_BUFFER_PADDING_SIZE)))
134             return AVERROR(ENOMEM);
135         avctx->extradata_size = 32;
136         extradata = avctx->extradata;
137         bytestream_put_le16(&extradata, avctx->frame_size);
138         bytestream_put_le16(&extradata, 7); /* wNumCoef */
139         for (i = 0; i < 7; i++) {
140             bytestream_put_le16(&extradata, ff_adpcm_AdaptCoeff1[i] * 4);
141             bytestream_put_le16(&extradata, ff_adpcm_AdaptCoeff2[i] * 4);
142         }
143         break;
144     case AV_CODEC_ID_ADPCM_YAMAHA:
145         avctx->frame_size  = BLKSIZE * 2 / avctx->channels;
146         avctx->block_align = BLKSIZE;
147         break;
148     case AV_CODEC_ID_ADPCM_SWF:
149         if (avctx->sample_rate != 11025 &&
150             avctx->sample_rate != 22050 &&
151             avctx->sample_rate != 44100) {
152             av_log(avctx, AV_LOG_ERROR, "Sample rate must be 11025, "
153                    "22050 or 44100\n");
154             return AVERROR(EINVAL);
155         }
156         avctx->frame_size = 512 * (avctx->sample_rate / 11025);
157         break;
158     case AV_CODEC_ID_ADPCM_IMA_SSI:
159         avctx->frame_size  = s->block_size * 2 / avctx->channels;
160         avctx->block_align = s->block_size;
161         break;
162     case AV_CODEC_ID_ADPCM_IMA_APM:
163         avctx->frame_size  = s->block_size * 2 / avctx->channels;
164         avctx->block_align = s->block_size;
165
166         if (!(avctx->extradata = av_mallocz(28 + AV_INPUT_BUFFER_PADDING_SIZE)))
167             return AVERROR(ENOMEM);
168         avctx->extradata_size = 28;
169         break;
170     case AV_CODEC_ID_ADPCM_ARGO:
171         avctx->frame_size = 32;
172         avctx->block_align = 17 * avctx->channels;
173         break;
174     default:
175         return AVERROR(EINVAL);
176     }
177
178     return 0;
179 }
180
181 static av_cold int adpcm_encode_close(AVCodecContext *avctx)
182 {
183     ADPCMEncodeContext *s = avctx->priv_data;
184     av_freep(&s->paths);
185     av_freep(&s->node_buf);
186     av_freep(&s->nodep_buf);
187     av_freep(&s->trellis_hash);
188
189     return 0;
190 }
191
192
193 static inline uint8_t adpcm_ima_compress_sample(ADPCMChannelStatus *c,
194                                                 int16_t sample)
195 {
196     int delta  = sample - c->prev_sample;
197     int nibble = FFMIN(7, abs(delta) * 4 /
198                        ff_adpcm_step_table[c->step_index]) + (delta < 0) * 8;
199     c->prev_sample += ((ff_adpcm_step_table[c->step_index] *
200                         ff_adpcm_yamaha_difflookup[nibble]) / 8);
201     c->prev_sample = av_clip_int16(c->prev_sample);
202     c->step_index  = av_clip(c->step_index + ff_adpcm_index_table[nibble], 0, 88);
203     return nibble;
204 }
205
206 static inline uint8_t adpcm_ima_qt_compress_sample(ADPCMChannelStatus *c,
207                                                    int16_t sample)
208 {
209     int delta  = sample - c->prev_sample;
210     int diff, step = ff_adpcm_step_table[c->step_index];
211     int nibble = 8*(delta < 0);
212
213     delta= abs(delta);
214     diff = delta + (step >> 3);
215
216     if (delta >= step) {
217         nibble |= 4;
218         delta  -= step;
219     }
220     step >>= 1;
221     if (delta >= step) {
222         nibble |= 2;
223         delta  -= step;
224     }
225     step >>= 1;
226     if (delta >= step) {
227         nibble |= 1;
228         delta  -= step;
229     }
230     diff -= delta;
231
232     if (nibble & 8)
233         c->prev_sample -= diff;
234     else
235         c->prev_sample += diff;
236
237     c->prev_sample = av_clip_int16(c->prev_sample);
238     c->step_index  = av_clip(c->step_index + ff_adpcm_index_table[nibble], 0, 88);
239
240     return nibble;
241 }
242
243 static inline uint8_t adpcm_ms_compress_sample(ADPCMChannelStatus *c,
244                                                int16_t sample)
245 {
246     int predictor, nibble, bias;
247
248     predictor = (((c->sample1) * (c->coeff1)) +
249                 (( c->sample2) * (c->coeff2))) / 64;
250
251     nibble = sample - predictor;
252     if (nibble >= 0)
253         bias =  c->idelta / 2;
254     else
255         bias = -c->idelta / 2;
256
257     nibble = (nibble + bias) / c->idelta;
258     nibble = av_clip_intp2(nibble, 3) & 0x0F;
259
260     predictor += ((nibble & 0x08) ? (nibble - 0x10) : nibble) * c->idelta;
261
262     c->sample2 = c->sample1;
263     c->sample1 = av_clip_int16(predictor);
264
265     c->idelta = (ff_adpcm_AdaptationTable[nibble] * c->idelta) >> 8;
266     if (c->idelta < 16)
267         c->idelta = 16;
268
269     return nibble;
270 }
271
272 static inline uint8_t adpcm_yamaha_compress_sample(ADPCMChannelStatus *c,
273                                                    int16_t sample)
274 {
275     int nibble, delta;
276
277     if (!c->step) {
278         c->predictor = 0;
279         c->step      = 127;
280     }
281
282     delta = sample - c->predictor;
283
284     nibble = FFMIN(7, abs(delta) * 4 / c->step) + (delta < 0) * 8;
285
286     c->predictor += ((c->step * ff_adpcm_yamaha_difflookup[nibble]) / 8);
287     c->predictor = av_clip_int16(c->predictor);
288     c->step = (c->step * ff_adpcm_yamaha_indexscale[nibble]) >> 8;
289     c->step = av_clip(c->step, 127, 24576);
290
291     return nibble;
292 }
293
294 static void adpcm_compress_trellis(AVCodecContext *avctx,
295                                    const int16_t *samples, uint8_t *dst,
296                                    ADPCMChannelStatus *c, int n, int stride)
297 {
298     //FIXME 6% faster if frontier is a compile-time constant
299     ADPCMEncodeContext *s = avctx->priv_data;
300     const int frontier = 1 << avctx->trellis;
301     const int version  = avctx->codec->id;
302     TrellisPath *paths       = s->paths, *p;
303     TrellisNode *node_buf    = s->node_buf;
304     TrellisNode **nodep_buf  = s->nodep_buf;
305     TrellisNode **nodes      = nodep_buf; // nodes[] is always sorted by .ssd
306     TrellisNode **nodes_next = nodep_buf + frontier;
307     int pathn = 0, froze = -1, i, j, k, generation = 0;
308     uint8_t *hash = s->trellis_hash;
309     memset(hash, 0xff, 65536 * sizeof(*hash));
310
311     memset(nodep_buf, 0, 2 * frontier * sizeof(*nodep_buf));
312     nodes[0]          = node_buf + frontier;
313     nodes[0]->ssd     = 0;
314     nodes[0]->path    = 0;
315     nodes[0]->step    = c->step_index;
316     nodes[0]->sample1 = c->sample1;
317     nodes[0]->sample2 = c->sample2;
318     if (version == AV_CODEC_ID_ADPCM_IMA_WAV ||
319         version == AV_CODEC_ID_ADPCM_IMA_QT  ||
320         version == AV_CODEC_ID_ADPCM_SWF)
321         nodes[0]->sample1 = c->prev_sample;
322     if (version == AV_CODEC_ID_ADPCM_MS)
323         nodes[0]->step = c->idelta;
324     if (version == AV_CODEC_ID_ADPCM_YAMAHA) {
325         if (c->step == 0) {
326             nodes[0]->step    = 127;
327             nodes[0]->sample1 = 0;
328         } else {
329             nodes[0]->step    = c->step;
330             nodes[0]->sample1 = c->predictor;
331         }
332     }
333
334     for (i = 0; i < n; i++) {
335         TrellisNode *t = node_buf + frontier*(i&1);
336         TrellisNode **u;
337         int sample   = samples[i * stride];
338         int heap_pos = 0;
339         memset(nodes_next, 0, frontier * sizeof(TrellisNode*));
340         for (j = 0; j < frontier && nodes[j]; j++) {
341             // higher j have higher ssd already, so they're likely
342             // to yield a suboptimal next sample too
343             const int range = (j < frontier / 2) ? 1 : 0;
344             const int step  = nodes[j]->step;
345             int nidx;
346             if (version == AV_CODEC_ID_ADPCM_MS) {
347                 const int predictor = ((nodes[j]->sample1 * c->coeff1) +
348                                        (nodes[j]->sample2 * c->coeff2)) / 64;
349                 const int div  = (sample - predictor) / step;
350                 const int nmin = av_clip(div-range, -8, 6);
351                 const int nmax = av_clip(div+range, -7, 7);
352                 for (nidx = nmin; nidx <= nmax; nidx++) {
353                     const int nibble = nidx & 0xf;
354                     int dec_sample   = predictor + nidx * step;
355 #define STORE_NODE(NAME, STEP_INDEX)\
356                     int d;\
357                     uint32_t ssd;\
358                     int pos;\
359                     TrellisNode *u;\
360                     uint8_t *h;\
361                     dec_sample = av_clip_int16(dec_sample);\
362                     d = sample - dec_sample;\
363                     ssd = nodes[j]->ssd + d*(unsigned)d;\
364                     /* Check for wraparound, skip such samples completely. \
365                      * Note, changing ssd to a 64 bit variable would be \
366                      * simpler, avoiding this check, but it's slower on \
367                      * x86 32 bit at the moment. */\
368                     if (ssd < nodes[j]->ssd)\
369                         goto next_##NAME;\
370                     /* Collapse any two states with the same previous sample value. \
371                      * One could also distinguish states by step and by 2nd to last
372                      * sample, but the effects of that are negligible.
373                      * Since nodes in the previous generation are iterated
374                      * through a heap, they're roughly ordered from better to
375                      * worse, but not strictly ordered. Therefore, an earlier
376                      * node with the same sample value is better in most cases
377                      * (and thus the current is skipped), but not strictly
378                      * in all cases. Only skipping samples where ssd >=
379                      * ssd of the earlier node with the same sample gives
380                      * slightly worse quality, though, for some reason. */ \
381                     h = &hash[(uint16_t) dec_sample];\
382                     if (*h == generation)\
383                         goto next_##NAME;\
384                     if (heap_pos < frontier) {\
385                         pos = heap_pos++;\
386                     } else {\
387                         /* Try to replace one of the leaf nodes with the new \
388                          * one, but try a different slot each time. */\
389                         pos = (frontier >> 1) +\
390                               (heap_pos & ((frontier >> 1) - 1));\
391                         if (ssd > nodes_next[pos]->ssd)\
392                             goto next_##NAME;\
393                         heap_pos++;\
394                     }\
395                     *h = generation;\
396                     u  = nodes_next[pos];\
397                     if (!u) {\
398                         av_assert1(pathn < FREEZE_INTERVAL << avctx->trellis);\
399                         u = t++;\
400                         nodes_next[pos] = u;\
401                         u->path = pathn++;\
402                     }\
403                     u->ssd  = ssd;\
404                     u->step = STEP_INDEX;\
405                     u->sample2 = nodes[j]->sample1;\
406                     u->sample1 = dec_sample;\
407                     paths[u->path].nibble = nibble;\
408                     paths[u->path].prev   = nodes[j]->path;\
409                     /* Sift the newly inserted node up in the heap to \
410                      * restore the heap property. */\
411                     while (pos > 0) {\
412                         int parent = (pos - 1) >> 1;\
413                         if (nodes_next[parent]->ssd <= ssd)\
414                             break;\
415                         FFSWAP(TrellisNode*, nodes_next[parent], nodes_next[pos]);\
416                         pos = parent;\
417                     }\
418                     next_##NAME:;
419                     STORE_NODE(ms, FFMAX(16,
420                                (ff_adpcm_AdaptationTable[nibble] * step) >> 8));
421                 }
422             } else if (version == AV_CODEC_ID_ADPCM_IMA_WAV ||
423                        version == AV_CODEC_ID_ADPCM_IMA_QT  ||
424                        version == AV_CODEC_ID_ADPCM_SWF) {
425 #define LOOP_NODES(NAME, STEP_TABLE, STEP_INDEX)\
426                 const int predictor = nodes[j]->sample1;\
427                 const int div = (sample - predictor) * 4 / STEP_TABLE;\
428                 int nmin = av_clip(div - range, -7, 6);\
429                 int nmax = av_clip(div + range, -6, 7);\
430                 if (nmin <= 0)\
431                     nmin--; /* distinguish -0 from +0 */\
432                 if (nmax < 0)\
433                     nmax--;\
434                 for (nidx = nmin; nidx <= nmax; nidx++) {\
435                     const int nibble = nidx < 0 ? 7 - nidx : nidx;\
436                     int dec_sample = predictor +\
437                                     (STEP_TABLE *\
438                                      ff_adpcm_yamaha_difflookup[nibble]) / 8;\
439                     STORE_NODE(NAME, STEP_INDEX);\
440                 }
441                 LOOP_NODES(ima, ff_adpcm_step_table[step],
442                            av_clip(step + ff_adpcm_index_table[nibble], 0, 88));
443             } else { //AV_CODEC_ID_ADPCM_YAMAHA
444                 LOOP_NODES(yamaha, step,
445                            av_clip((step * ff_adpcm_yamaha_indexscale[nibble]) >> 8,
446                                    127, 24576));
447 #undef LOOP_NODES
448 #undef STORE_NODE
449             }
450         }
451
452         u = nodes;
453         nodes = nodes_next;
454         nodes_next = u;
455
456         generation++;
457         if (generation == 255) {
458             memset(hash, 0xff, 65536 * sizeof(*hash));
459             generation = 0;
460         }
461
462         // prevent overflow
463         if (nodes[0]->ssd > (1 << 28)) {
464             for (j = 1; j < frontier && nodes[j]; j++)
465                 nodes[j]->ssd -= nodes[0]->ssd;
466             nodes[0]->ssd = 0;
467         }
468
469         // merge old paths to save memory
470         if (i == froze + FREEZE_INTERVAL) {
471             p = &paths[nodes[0]->path];
472             for (k = i; k > froze; k--) {
473                 dst[k] = p->nibble;
474                 p = &paths[p->prev];
475             }
476             froze = i;
477             pathn = 0;
478             // other nodes might use paths that don't coincide with the frozen one.
479             // checking which nodes do so is too slow, so just kill them all.
480             // this also slightly improves quality, but I don't know why.
481             memset(nodes + 1, 0, (frontier - 1) * sizeof(TrellisNode*));
482         }
483     }
484
485     p = &paths[nodes[0]->path];
486     for (i = n - 1; i > froze; i--) {
487         dst[i] = p->nibble;
488         p = &paths[p->prev];
489     }
490
491     c->predictor  = nodes[0]->sample1;
492     c->sample1    = nodes[0]->sample1;
493     c->sample2    = nodes[0]->sample2;
494     c->step_index = nodes[0]->step;
495     c->step       = nodes[0]->step;
496     c->idelta     = nodes[0]->step;
497 }
498
499 static inline int adpcm_argo_compress_nibble(const ADPCMChannelStatus *cs, int16_t s,
500                                              int shift, int flag)
501 {
502     int nibble;
503
504     if (flag)
505         nibble = 4 * s - 8 * cs->sample1 + 4 * cs->sample2;
506     else
507         nibble = 4 * s - 4 * cs->sample1;
508
509     return (nibble >> shift) & 0x0F;
510 }
511
512 static int64_t adpcm_argo_compress_block(ADPCMChannelStatus *cs, PutBitContext *pb,
513                                          const int16_t *samples, int nsamples,
514                                          int shift, int flag)
515 {
516     int64_t error = 0;
517
518     if (pb) {
519         put_bits(pb, 4, shift - 2);
520         put_bits(pb, 1, 0);
521         put_bits(pb, 1, !!flag);
522         put_bits(pb, 2, 0);
523     }
524
525     for (int n = 0; n < nsamples; n++) {
526         /* Compress the nibble, then expand it to see how much precision we've lost. */
527         int nibble = adpcm_argo_compress_nibble(cs, samples[n], shift, flag);
528         int16_t sample = ff_adpcm_argo_expand_nibble(cs, nibble, shift, flag);
529
530         error += abs(samples[n] - sample);
531
532         if (pb)
533             put_bits(pb, 4, nibble);
534     }
535
536     return error;
537 }
538
539 static int adpcm_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
540                               const AVFrame *frame, int *got_packet_ptr)
541 {
542     int n, i, ch, st, pkt_size, ret;
543     const int16_t *samples;
544     int16_t **samples_p;
545     uint8_t *dst;
546     ADPCMEncodeContext *c = avctx->priv_data;
547     uint8_t *buf;
548
549     samples = (const int16_t *)frame->data[0];
550     samples_p = (int16_t **)frame->extended_data;
551     st = avctx->channels == 2;
552
553     if (avctx->codec_id == AV_CODEC_ID_ADPCM_SWF)
554         pkt_size = (2 + avctx->channels * (22 + 4 * (frame->nb_samples - 1)) + 7) / 8;
555     else if (avctx->codec_id == AV_CODEC_ID_ADPCM_IMA_SSI ||
556              avctx->codec_id == AV_CODEC_ID_ADPCM_IMA_APM)
557         pkt_size = (frame->nb_samples * avctx->channels) / 2;
558     else
559         pkt_size = avctx->block_align;
560     if ((ret = ff_alloc_packet2(avctx, avpkt, pkt_size, 0)) < 0)
561         return ret;
562     dst = avpkt->data;
563
564     switch(avctx->codec->id) {
565     case AV_CODEC_ID_ADPCM_IMA_WAV:
566     {
567         int blocks, j;
568
569         blocks = (frame->nb_samples - 1) / 8;
570
571         for (ch = 0; ch < avctx->channels; ch++) {
572             ADPCMChannelStatus *status = &c->status[ch];
573             status->prev_sample = samples_p[ch][0];
574             /* status->step_index = 0;
575                XXX: not sure how to init the state machine */
576             bytestream_put_le16(&dst, status->prev_sample);
577             *dst++ = status->step_index;
578             *dst++ = 0; /* unknown */
579         }
580
581         /* stereo: 4 bytes (8 samples) for left, 4 bytes for right */
582         if (avctx->trellis > 0) {
583             if (!FF_ALLOC_TYPED_ARRAY(buf, avctx->channels * blocks * 8))
584                 return AVERROR(ENOMEM);
585             for (ch = 0; ch < avctx->channels; ch++) {
586                 adpcm_compress_trellis(avctx, &samples_p[ch][1],
587                                        buf + ch * blocks * 8, &c->status[ch],
588                                        blocks * 8, 1);
589             }
590             for (i = 0; i < blocks; i++) {
591                 for (ch = 0; ch < avctx->channels; ch++) {
592                     uint8_t *buf1 = buf + ch * blocks * 8 + i * 8;
593                     for (j = 0; j < 8; j += 2)
594                         *dst++ = buf1[j] | (buf1[j + 1] << 4);
595                 }
596             }
597             av_free(buf);
598         } else {
599             for (i = 0; i < blocks; i++) {
600                 for (ch = 0; ch < avctx->channels; ch++) {
601                     ADPCMChannelStatus *status = &c->status[ch];
602                     const int16_t *smp = &samples_p[ch][1 + i * 8];
603                     for (j = 0; j < 8; j += 2) {
604                         uint8_t v = adpcm_ima_compress_sample(status, smp[j    ]);
605                         v        |= adpcm_ima_compress_sample(status, smp[j + 1]) << 4;
606                         *dst++ = v;
607                     }
608                 }
609             }
610         }
611         break;
612     }
613     case AV_CODEC_ID_ADPCM_IMA_QT:
614     {
615         PutBitContext pb;
616         init_put_bits(&pb, dst, pkt_size);
617
618         for (ch = 0; ch < avctx->channels; ch++) {
619             ADPCMChannelStatus *status = &c->status[ch];
620             put_bits(&pb, 9, (status->prev_sample & 0xFFFF) >> 7);
621             put_bits(&pb, 7,  status->step_index);
622             if (avctx->trellis > 0) {
623                 uint8_t buf[64];
624                 adpcm_compress_trellis(avctx, &samples_p[ch][0], buf, status,
625                                        64, 1);
626                 for (i = 0; i < 64; i++)
627                     put_bits(&pb, 4, buf[i ^ 1]);
628                 status->prev_sample = status->predictor;
629             } else {
630                 for (i = 0; i < 64; i += 2) {
631                     int t1, t2;
632                     t1 = adpcm_ima_qt_compress_sample(status, samples_p[ch][i    ]);
633                     t2 = adpcm_ima_qt_compress_sample(status, samples_p[ch][i + 1]);
634                     put_bits(&pb, 4, t2);
635                     put_bits(&pb, 4, t1);
636                 }
637             }
638         }
639
640         flush_put_bits(&pb);
641         break;
642     }
643     case AV_CODEC_ID_ADPCM_IMA_SSI:
644     {
645         PutBitContext pb;
646         init_put_bits(&pb, dst, pkt_size);
647
648         av_assert0(avctx->trellis == 0);
649
650         for (i = 0; i < frame->nb_samples; i++) {
651             for (ch = 0; ch < avctx->channels; ch++) {
652                 put_bits(&pb, 4, adpcm_ima_qt_compress_sample(c->status + ch, *samples++));
653             }
654         }
655
656         flush_put_bits(&pb);
657         break;
658     }
659     case AV_CODEC_ID_ADPCM_SWF:
660     {
661         PutBitContext pb;
662         init_put_bits(&pb, dst, pkt_size);
663
664         n = frame->nb_samples - 1;
665
666         // store AdpcmCodeSize
667         put_bits(&pb, 2, 2);    // set 4-bit flash adpcm format
668
669         // init the encoder state
670         for (i = 0; i < avctx->channels; i++) {
671             // clip step so it fits 6 bits
672             c->status[i].step_index = av_clip_uintp2(c->status[i].step_index, 6);
673             put_sbits(&pb, 16, samples[i]);
674             put_bits(&pb, 6, c->status[i].step_index);
675             c->status[i].prev_sample = samples[i];
676         }
677
678         if (avctx->trellis > 0) {
679             if (!(buf = av_malloc(2 * n)))
680                 return AVERROR(ENOMEM);
681             adpcm_compress_trellis(avctx, samples + avctx->channels, buf,
682                                    &c->status[0], n, avctx->channels);
683             if (avctx->channels == 2)
684                 adpcm_compress_trellis(avctx, samples + avctx->channels + 1,
685                                        buf + n, &c->status[1], n,
686                                        avctx->channels);
687             for (i = 0; i < n; i++) {
688                 put_bits(&pb, 4, buf[i]);
689                 if (avctx->channels == 2)
690                     put_bits(&pb, 4, buf[n + i]);
691             }
692             av_free(buf);
693         } else {
694             for (i = 1; i < frame->nb_samples; i++) {
695                 put_bits(&pb, 4, adpcm_ima_compress_sample(&c->status[0],
696                          samples[avctx->channels * i]));
697                 if (avctx->channels == 2)
698                     put_bits(&pb, 4, adpcm_ima_compress_sample(&c->status[1],
699                              samples[2 * i + 1]));
700             }
701         }
702         flush_put_bits(&pb);
703         break;
704     }
705     case AV_CODEC_ID_ADPCM_MS:
706         for (i = 0; i < avctx->channels; i++) {
707             int predictor = 0;
708             *dst++ = predictor;
709             c->status[i].coeff1 = ff_adpcm_AdaptCoeff1[predictor];
710             c->status[i].coeff2 = ff_adpcm_AdaptCoeff2[predictor];
711         }
712         for (i = 0; i < avctx->channels; i++) {
713             if (c->status[i].idelta < 16)
714                 c->status[i].idelta = 16;
715             bytestream_put_le16(&dst, c->status[i].idelta);
716         }
717         for (i = 0; i < avctx->channels; i++)
718             c->status[i].sample2= *samples++;
719         for (i = 0; i < avctx->channels; i++) {
720             c->status[i].sample1 = *samples++;
721             bytestream_put_le16(&dst, c->status[i].sample1);
722         }
723         for (i = 0; i < avctx->channels; i++)
724             bytestream_put_le16(&dst, c->status[i].sample2);
725
726         if (avctx->trellis > 0) {
727             n = avctx->block_align - 7 * avctx->channels;
728             if (!(buf = av_malloc(2 * n)))
729                 return AVERROR(ENOMEM);
730             if (avctx->channels == 1) {
731                 adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n,
732                                        avctx->channels);
733                 for (i = 0; i < n; i += 2)
734                     *dst++ = (buf[i] << 4) | buf[i + 1];
735             } else {
736                 adpcm_compress_trellis(avctx, samples,     buf,
737                                        &c->status[0], n, avctx->channels);
738                 adpcm_compress_trellis(avctx, samples + 1, buf + n,
739                                        &c->status[1], n, avctx->channels);
740                 for (i = 0; i < n; i++)
741                     *dst++ = (buf[i] << 4) | buf[n + i];
742             }
743             av_free(buf);
744         } else {
745             for (i = 7 * avctx->channels; i < avctx->block_align; i++) {
746                 int nibble;
747                 nibble  = adpcm_ms_compress_sample(&c->status[ 0], *samples++) << 4;
748                 nibble |= adpcm_ms_compress_sample(&c->status[st], *samples++);
749                 *dst++  = nibble;
750             }
751         }
752         break;
753     case AV_CODEC_ID_ADPCM_YAMAHA:
754         n = frame->nb_samples / 2;
755         if (avctx->trellis > 0) {
756             if (!(buf = av_malloc(2 * n * 2)))
757                 return AVERROR(ENOMEM);
758             n *= 2;
759             if (avctx->channels == 1) {
760                 adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n,
761                                        avctx->channels);
762                 for (i = 0; i < n; i += 2)
763                     *dst++ = buf[i] | (buf[i + 1] << 4);
764             } else {
765                 adpcm_compress_trellis(avctx, samples,     buf,
766                                        &c->status[0], n, avctx->channels);
767                 adpcm_compress_trellis(avctx, samples + 1, buf + n,
768                                        &c->status[1], n, avctx->channels);
769                 for (i = 0; i < n; i++)
770                     *dst++ = buf[i] | (buf[n + i] << 4);
771             }
772             av_free(buf);
773         } else
774             for (n *= avctx->channels; n > 0; n--) {
775                 int nibble;
776                 nibble  = adpcm_yamaha_compress_sample(&c->status[ 0], *samples++);
777                 nibble |= adpcm_yamaha_compress_sample(&c->status[st], *samples++) << 4;
778                 *dst++  = nibble;
779             }
780         break;
781     case AV_CODEC_ID_ADPCM_IMA_APM:
782     {
783         PutBitContext pb;
784         init_put_bits(&pb, dst, pkt_size);
785
786         av_assert0(avctx->trellis == 0);
787
788         for (n = frame->nb_samples / 2; n > 0; n--) {
789             for (ch = 0; ch < avctx->channels; ch++) {
790                 put_bits(&pb, 4, adpcm_ima_qt_compress_sample(c->status + ch, *samples++));
791                 put_bits(&pb, 4, adpcm_ima_qt_compress_sample(c->status + ch, samples[st]));
792             }
793             samples += avctx->channels;
794         }
795
796         flush_put_bits(&pb);
797         break;
798     }
799     case AV_CODEC_ID_ADPCM_ARGO:
800     {
801         PutBitContext pb;
802         init_put_bits(&pb, dst, pkt_size);
803
804         av_assert0(frame->nb_samples == 32);
805
806         for (ch = 0; ch < avctx->channels; ch++) {
807             int64_t error  = INT64_MAX, tmperr = INT64_MAX;
808             int     shift  = 2, flag = 0;
809             int     saved1 = c->status[ch].sample1;
810             int     saved2 = c->status[ch].sample2;
811
812             /* Find the optimal coefficients, bail early if we find a perfect result. */
813             for (int s = 2; s < 18 && tmperr != 0; s++) {
814                 for (int f = 0; f < 2 && tmperr != 0; f++) {
815                     c->status[ch].sample1 = saved1;
816                     c->status[ch].sample2 = saved2;
817                     tmperr = adpcm_argo_compress_block(c->status + ch, NULL, samples_p[ch],
818                                                        frame->nb_samples, s, f);
819                     if (tmperr < error) {
820                         shift = s;
821                         flag  = f;
822                         error = tmperr;
823                     }
824                 }
825             }
826
827             /* Now actually do the encode. */
828             c->status[ch].sample1 = saved1;
829             c->status[ch].sample2 = saved2;
830             adpcm_argo_compress_block(c->status + ch, &pb, samples_p[ch],
831                                       frame->nb_samples, shift, flag);
832         }
833
834         flush_put_bits(&pb);
835         break;
836     }
837     default:
838         return AVERROR(EINVAL);
839     }
840
841     avpkt->size = pkt_size;
842     *got_packet_ptr = 1;
843     return 0;
844 }
845
846 static const enum AVSampleFormat sample_fmts[] = {
847     AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
848 };
849
850 static const enum AVSampleFormat sample_fmts_p[] = {
851     AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_NONE
852 };
853
854 static const AVOption options[] = {
855     {
856         .name        = "block_size",
857         .help        = "set the block size",
858         .offset      = offsetof(ADPCMEncodeContext, block_size),
859         .type        = AV_OPT_TYPE_INT,
860         .default_val = {.i64 = BLKSIZE},
861         .min         = 32,
862         .max         = 8192, /* Is this a reasonable upper limit? */
863         .flags       = AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
864     },
865     { NULL }
866 };
867
868 static const AVClass adpcm_encoder_class = {
869     .class_name = "ADPCM Encoder",
870     .item_name  = av_default_item_name,
871     .option     = options,
872     .version    = LIBAVUTIL_VERSION_INT,
873 };
874
875 #define ADPCM_ENCODER(id_, name_, sample_fmts_, capabilities_, long_name_) \
876 AVCodec ff_ ## name_ ## _encoder = {                                       \
877     .name           = #name_,                                              \
878     .long_name      = NULL_IF_CONFIG_SMALL(long_name_),                    \
879     .type           = AVMEDIA_TYPE_AUDIO,                                  \
880     .id             = id_,                                                 \
881     .priv_data_size = sizeof(ADPCMEncodeContext),                          \
882     .init           = adpcm_encode_init,                                   \
883     .encode2        = adpcm_encode_frame,                                  \
884     .close          = adpcm_encode_close,                                  \
885     .sample_fmts    = sample_fmts_,                                        \
886     .capabilities   = capabilities_,                                       \
887     .caps_internal  = FF_CODEC_CAP_INIT_CLEANUP,                           \
888     .priv_class     = &adpcm_encoder_class,                                \
889 }
890
891 ADPCM_ENCODER(AV_CODEC_ID_ADPCM_ARGO,    adpcm_argo,    sample_fmts_p, 0,                             "ADPCM Argonaut Games");
892 ADPCM_ENCODER(AV_CODEC_ID_ADPCM_IMA_APM, adpcm_ima_apm, sample_fmts,   AV_CODEC_CAP_SMALL_LAST_FRAME, "ADPCM IMA Ubisoft APM");
893 ADPCM_ENCODER(AV_CODEC_ID_ADPCM_IMA_QT,  adpcm_ima_qt,  sample_fmts_p, 0,                             "ADPCM IMA QuickTime");
894 ADPCM_ENCODER(AV_CODEC_ID_ADPCM_IMA_SSI, adpcm_ima_ssi, sample_fmts,   AV_CODEC_CAP_SMALL_LAST_FRAME, "ADPCM IMA Simon & Schuster Interactive");
895 ADPCM_ENCODER(AV_CODEC_ID_ADPCM_IMA_WAV, adpcm_ima_wav, sample_fmts_p, 0,                             "ADPCM IMA WAV");
896 ADPCM_ENCODER(AV_CODEC_ID_ADPCM_MS,      adpcm_ms,      sample_fmts,   0,                             "ADPCM Microsoft");
897 ADPCM_ENCODER(AV_CODEC_ID_ADPCM_SWF,     adpcm_swf,     sample_fmts,   0,                             "ADPCM Shockwave Flash");
898 ADPCM_ENCODER(AV_CODEC_ID_ADPCM_YAMAHA,  adpcm_yamaha,  sample_fmts,   0,                             "ADPCM Yamaha");