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