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