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