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