adpcmenc.c 26.9 KB
Newer Older
1
/*
2
 * Copyright (c) 2001-2003 The FFmpeg Project
3
 *
4 5 6 7
 * first version by Francois Revol (revol@free.fr)
 * fringe ADPCM codecs (e.g., DK3, DK4, Westwood)
 *   by Mike Melanson (melanson@pcisys.net)
 *
8
 * This file is part of FFmpeg.
9
 *
10
 * FFmpeg is free software; you can redistribute it and/or
11 12 13 14
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
15
 * FFmpeg is distributed in the hope that it will be useful,
16 17 18 19 20
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
21
 * License along with FFmpeg; if not, write to the Free Software
22 23 24 25 26 27 28 29
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "avcodec.h"
#include "put_bits.h"
#include "bytestream.h"
#include "adpcm.h"
#include "adpcm_data.h"
30
#include "internal.h"
31 32 33 34

/**
 * @file
 * ADPCM encoders
35
 * See ADPCM decoder reference documents for codec information.
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
 */

typedef struct TrellisPath {
    int nibble;
    int prev;
} TrellisPath;

typedef struct TrellisNode {
    uint32_t ssd;
    int path;
    int sample1;
    int sample2;
    int step;
} TrellisNode;

typedef struct ADPCMEncodeContext {
    ADPCMChannelStatus status[6];
    TrellisPath *paths;
    TrellisNode *node_buf;
    TrellisNode **nodep_buf;
    uint8_t *trellis_hash;
} ADPCMEncodeContext;

#define FREEZE_INTERVAL 128

61 62
static av_cold int adpcm_encode_close(AVCodecContext *avctx);

63 64 65 66 67
static av_cold int adpcm_encode_init(AVCodecContext *avctx)
{
    ADPCMEncodeContext *s = avctx->priv_data;
    uint8_t *extradata;
    int i;
68 69 70 71 72 73
    int ret = AVERROR(ENOMEM);

    if (avctx->channels > 2) {
        av_log(avctx, AV_LOG_ERROR, "only stereo or mono is supported\n");
        return AVERROR(EINVAL);
    }
74

75
    if (avctx->trellis && (unsigned)avctx->trellis > 16U) {
76
        av_log(avctx, AV_LOG_ERROR, "invalid trellis size\n");
77
        return AVERROR(EINVAL);
78 79 80
    }

    if (avctx->trellis) {
81
        int frontier  = 1 << avctx->trellis;
82
        int max_paths =  frontier * FREEZE_INTERVAL;
83 84 85 86 87 88 89 90
        FF_ALLOC_OR_GOTO(avctx, s->paths,
                         max_paths * sizeof(*s->paths), error);
        FF_ALLOC_OR_GOTO(avctx, s->node_buf,
                         2 * frontier * sizeof(*s->node_buf),  error);
        FF_ALLOC_OR_GOTO(avctx, s->nodep_buf,
                         2 * frontier * sizeof(*s->nodep_buf), error);
        FF_ALLOC_OR_GOTO(avctx, s->trellis_hash,
                         65536 * sizeof(*s->trellis_hash), error);
91 92
    }

93 94
    avctx->bits_per_coded_sample = av_get_bits_per_sample(avctx->codec->id);

95
    switch (avctx->codec->id) {
96
    case AV_CODEC_ID_ADPCM_IMA_WAV:
97 98 99 100 101 102
        /* each 16 bits sample gives one nibble
           and we have 4 bytes per channel overhead */
        avctx->frame_size = (BLKSIZE - 4 * avctx->channels) * 8 /
                            (4 * avctx->channels) + 1;
        /* seems frame_size isn't taken into account...
           have to buffer the samples :-( */
103
        avctx->block_align = BLKSIZE;
104
        avctx->bits_per_coded_sample = 4;
105
        break;
106
    case AV_CODEC_ID_ADPCM_IMA_QT:
107
        avctx->frame_size  = 64;
108 109
        avctx->block_align = 34 * avctx->channels;
        break;
110
    case AV_CODEC_ID_ADPCM_MS:
111 112
        /* each 16 bits sample gives one nibble
           and we have 7 bytes per channel overhead */
113
        avctx->frame_size = (BLKSIZE - 7 * avctx->channels) * 2 / avctx->channels + 2;
114
        avctx->bits_per_coded_sample = 4;
115
        avctx->block_align    = BLKSIZE;
116
        if (!(avctx->extradata = av_malloc(32 + AV_INPUT_BUFFER_PADDING_SIZE)))
117
            goto error;
118
        avctx->extradata_size = 32;
119
        extradata = avctx->extradata;
120 121 122 123 124 125 126
        bytestream_put_le16(&extradata, avctx->frame_size);
        bytestream_put_le16(&extradata, 7); /* wNumCoef */
        for (i = 0; i < 7; i++) {
            bytestream_put_le16(&extradata, ff_adpcm_AdaptCoeff1[i] * 4);
            bytestream_put_le16(&extradata, ff_adpcm_AdaptCoeff2[i] * 4);
        }
        break;
127
    case AV_CODEC_ID_ADPCM_YAMAHA:
128
        avctx->frame_size  = BLKSIZE * 2 / avctx->channels;
129 130
        avctx->block_align = BLKSIZE;
        break;
131
    case AV_CODEC_ID_ADPCM_SWF:
132 133 134
        if (avctx->sample_rate != 11025 &&
            avctx->sample_rate != 22050 &&
            avctx->sample_rate != 44100) {
135 136
            av_log(avctx, AV_LOG_ERROR, "Sample rate must be 11025, "
                   "22050 or 44100\n");
137
            ret = AVERROR(EINVAL);
138 139 140 141 142
            goto error;
        }
        avctx->frame_size = 512 * (avctx->sample_rate / 11025);
        break;
    default:
143
        ret = AVERROR(EINVAL);
144 145 146 147 148
        goto error;
    }

    return 0;
error:
149
    adpcm_encode_close(avctx);
150
    return ret;
151 152 153 154 155 156 157 158 159 160 161 162 163 164
}

static av_cold int adpcm_encode_close(AVCodecContext *avctx)
{
    ADPCMEncodeContext *s = avctx->priv_data;
    av_freep(&s->paths);
    av_freep(&s->node_buf);
    av_freep(&s->nodep_buf);
    av_freep(&s->trellis_hash);

    return 0;
}


165 166
static inline uint8_t adpcm_ima_compress_sample(ADPCMChannelStatus *c,
                                                int16_t sample)
167
{
168 169 170 171 172
    int delta  = sample - c->prev_sample;
    int nibble = FFMIN(7, abs(delta) * 4 /
                       ff_adpcm_step_table[c->step_index]) + (delta < 0) * 8;
    c->prev_sample += ((ff_adpcm_step_table[c->step_index] *
                        ff_adpcm_yamaha_difflookup[nibble]) / 8);
173
    c->prev_sample = av_clip_int16(c->prev_sample);
174
    c->step_index  = av_clip(c->step_index + ff_adpcm_index_table[nibble], 0, 88);
175 176 177
    return nibble;
}

178 179
static inline uint8_t adpcm_ima_qt_compress_sample(ADPCMChannelStatus *c,
                                                   int16_t sample)
180
{
181
    int delta  = sample - c->prev_sample;
182 183 184 185 186 187 188 189
    int diff, step = ff_adpcm_step_table[c->step_index];
    int nibble = 8*(delta < 0);

    delta= abs(delta);
    diff = delta + (step >> 3);

    if (delta >= step) {
        nibble |= 4;
190
        delta  -= step;
191 192 193 194
    }
    step >>= 1;
    if (delta >= step) {
        nibble |= 2;
195
        delta  -= step;
196 197 198 199
    }
    step >>= 1;
    if (delta >= step) {
        nibble |= 1;
200
        delta  -= step;
201 202 203 204 205 206 207 208 209
    }
    diff -= delta;

    if (nibble & 8)
        c->prev_sample -= diff;
    else
        c->prev_sample += diff;

    c->prev_sample = av_clip_int16(c->prev_sample);
210
    c->step_index  = av_clip(c->step_index + ff_adpcm_index_table[nibble], 0, 88);
211 212 213 214

    return nibble;
}

215 216
static inline uint8_t adpcm_ms_compress_sample(ADPCMChannelStatus *c,
                                               int16_t sample)
217 218 219
{
    int predictor, nibble, bias;

220 221
    predictor = (((c->sample1) * (c->coeff1)) +
                (( c->sample2) * (c->coeff2))) / 64;
222

223 224 225 226 227
    nibble = sample - predictor;
    if (nibble >= 0)
        bias =  c->idelta / 2;
    else
        bias = -c->idelta / 2;
228

229
    nibble = (nibble + bias) / c->idelta;
230
    nibble = av_clip_intp2(nibble, 3) & 0x0F;
231

232
    predictor += ((nibble & 0x08) ? (nibble - 0x10) : nibble) * c->idelta;
233 234 235 236

    c->sample2 = c->sample1;
    c->sample1 = av_clip_int16(predictor);

237
    c->idelta = (ff_adpcm_AdaptationTable[nibble] * c->idelta) >> 8;
238 239
    if (c->idelta < 16)
        c->idelta = 16;
240 241 242 243

    return nibble;
}

244 245
static inline uint8_t adpcm_yamaha_compress_sample(ADPCMChannelStatus *c,
                                                   int16_t sample)
246 247 248
{
    int nibble, delta;

249
    if (!c->step) {
250
        c->predictor = 0;
251
        c->step      = 127;
252 253 254 255
    }

    delta = sample - c->predictor;

256
    nibble = FFMIN(7, abs(delta) * 4 / c->step) + (delta < 0) * 8;
257 258 259 260 261 262 263 264 265

    c->predictor += ((c->step * ff_adpcm_yamaha_difflookup[nibble]) / 8);
    c->predictor = av_clip_int16(c->predictor);
    c->step = (c->step * ff_adpcm_yamaha_indexscale[nibble]) >> 8;
    c->step = av_clip(c->step, 127, 24567);

    return nibble;
}

266 267
static void adpcm_compress_trellis(AVCodecContext *avctx,
                                   const int16_t *samples, uint8_t *dst,
268
                                   ADPCMChannelStatus *c, int n, int stride)
269 270 271 272
{
    //FIXME 6% faster if frontier is a compile-time constant
    ADPCMEncodeContext *s = avctx->priv_data;
    const int frontier = 1 << avctx->trellis;
273 274 275 276 277
    const int version  = avctx->codec->id;
    TrellisPath *paths       = s->paths, *p;
    TrellisNode *node_buf    = s->node_buf;
    TrellisNode **nodep_buf  = s->nodep_buf;
    TrellisNode **nodes      = nodep_buf; // nodes[] is always sorted by .ssd
278 279 280 281 282 283
    TrellisNode **nodes_next = nodep_buf + frontier;
    int pathn = 0, froze = -1, i, j, k, generation = 0;
    uint8_t *hash = s->trellis_hash;
    memset(hash, 0xff, 65536 * sizeof(*hash));

    memset(nodep_buf, 0, 2 * frontier * sizeof(*nodep_buf));
284 285 286 287
    nodes[0]          = node_buf + frontier;
    nodes[0]->ssd     = 0;
    nodes[0]->path    = 0;
    nodes[0]->step    = c->step_index;
288 289
    nodes[0]->sample1 = c->sample1;
    nodes[0]->sample2 = c->sample2;
290 291 292
    if (version == AV_CODEC_ID_ADPCM_IMA_WAV ||
        version == AV_CODEC_ID_ADPCM_IMA_QT  ||
        version == AV_CODEC_ID_ADPCM_SWF)
293
        nodes[0]->sample1 = c->prev_sample;
294
    if (version == AV_CODEC_ID_ADPCM_MS)
295
        nodes[0]->step = c->idelta;
296
    if (version == AV_CODEC_ID_ADPCM_YAMAHA) {
297 298
        if (c->step == 0) {
            nodes[0]->step    = 127;
299 300
            nodes[0]->sample1 = 0;
        } else {
301
            nodes[0]->step    = c->step;
302 303 304 305
            nodes[0]->sample1 = c->predictor;
        }
    }

306
    for (i = 0; i < n; i++) {
307 308
        TrellisNode *t = node_buf + frontier*(i&1);
        TrellisNode **u;
309
        int sample   = samples[i * stride];
310
        int heap_pos = 0;
311 312 313 314 315 316
        memset(nodes_next, 0, frontier * sizeof(TrellisNode*));
        for (j = 0; j < frontier && nodes[j]; j++) {
            // higher j have higher ssd already, so they're likely
            // to yield a suboptimal next sample too
            const int range = (j < frontier / 2) ? 1 : 0;
            const int step  = nodes[j]->step;
317
            int nidx;
318
            if (version == AV_CODEC_ID_ADPCM_MS) {
319 320 321
                const int predictor = ((nodes[j]->sample1 * c->coeff1) +
                                       (nodes[j]->sample2 * c->coeff2)) / 64;
                const int div  = (sample - predictor) / step;
322 323
                const int nmin = av_clip(div-range, -8, 6);
                const int nmax = av_clip(div+range, -7, 7);
324
                for (nidx = nmin; nidx <= nmax; nidx++) {
325
                    const int nibble = nidx & 0xf;
326
                    int dec_sample   = predictor + nidx * step;
327 328 329 330 331 332 333 334
#define STORE_NODE(NAME, STEP_INDEX)\
                    int d;\
                    uint32_t ssd;\
                    int pos;\
                    TrellisNode *u;\
                    uint8_t *h;\
                    dec_sample = av_clip_int16(dec_sample);\
                    d = sample - dec_sample;\
335
                    ssd = nodes[j]->ssd + d*(unsigned)d;\
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
                    /* Check for wraparound, skip such samples completely. \
                     * Note, changing ssd to a 64 bit variable would be \
                     * simpler, avoiding this check, but it's slower on \
                     * x86 32 bit at the moment. */\
                    if (ssd < nodes[j]->ssd)\
                        goto next_##NAME;\
                    /* Collapse any two states with the same previous sample value. \
                     * One could also distinguish states by step and by 2nd to last
                     * sample, but the effects of that are negligible.
                     * Since nodes in the previous generation are iterated
                     * through a heap, they're roughly ordered from better to
                     * worse, but not strictly ordered. Therefore, an earlier
                     * node with the same sample value is better in most cases
                     * (and thus the current is skipped), but not strictly
                     * in all cases. Only skipping samples where ssd >=
                     * ssd of the earlier node with the same sample gives
                     * slightly worse quality, though, for some reason. */ \
                    h = &hash[(uint16_t) dec_sample];\
                    if (*h == generation)\
                        goto next_##NAME;\
                    if (heap_pos < frontier) {\
                        pos = heap_pos++;\
                    } else {\
                        /* Try to replace one of the leaf nodes with the new \
                         * one, but try a different slot each time. */\
361 362
                        pos = (frontier >> 1) +\
                              (heap_pos & ((frontier >> 1) - 1));\
363 364 365 366 367
                        if (ssd > nodes_next[pos]->ssd)\
                            goto next_##NAME;\
                        heap_pos++;\
                    }\
                    *h = generation;\
368 369
                    u  = nodes_next[pos];\
                    if (!u) {\
370
                        av_assert1(pathn < FREEZE_INTERVAL << avctx->trellis);\
371 372 373 374
                        u = t++;\
                        nodes_next[pos] = u;\
                        u->path = pathn++;\
                    }\
375
                    u->ssd  = ssd;\
376 377 378 379
                    u->step = STEP_INDEX;\
                    u->sample2 = nodes[j]->sample1;\
                    u->sample1 = dec_sample;\
                    paths[u->path].nibble = nibble;\
380
                    paths[u->path].prev   = nodes[j]->path;\
381 382 383 384 385 386 387 388 389 390
                    /* Sift the newly inserted node up in the heap to \
                     * restore the heap property. */\
                    while (pos > 0) {\
                        int parent = (pos - 1) >> 1;\
                        if (nodes_next[parent]->ssd <= ssd)\
                            break;\
                        FFSWAP(TrellisNode*, nodes_next[parent], nodes_next[pos]);\
                        pos = parent;\
                    }\
                    next_##NAME:;
391 392
                    STORE_NODE(ms, FFMAX(16,
                               (ff_adpcm_AdaptationTable[nibble] * step) >> 8));
393
                }
394 395 396
            } else if (version == AV_CODEC_ID_ADPCM_IMA_WAV ||
                       version == AV_CODEC_ID_ADPCM_IMA_QT  ||
                       version == AV_CODEC_ID_ADPCM_SWF) {
397 398 399
#define LOOP_NODES(NAME, STEP_TABLE, STEP_INDEX)\
                const int predictor = nodes[j]->sample1;\
                const int div = (sample - predictor) * 4 / STEP_TABLE;\
400 401 402 403 404 405 406 407 408 409 410
                int nmin = av_clip(div - range, -7, 6);\
                int nmax = av_clip(div + range, -6, 7);\
                if (nmin <= 0)\
                    nmin--; /* distinguish -0 from +0 */\
                if (nmax < 0)\
                    nmax--;\
                for (nidx = nmin; nidx <= nmax; nidx++) {\
                    const int nibble = nidx < 0 ? 7 - nidx : nidx;\
                    int dec_sample = predictor +\
                                    (STEP_TABLE *\
                                     ff_adpcm_yamaha_difflookup[nibble]) / 8;\
411 412
                    STORE_NODE(NAME, STEP_INDEX);\
                }
413 414
                LOOP_NODES(ima, ff_adpcm_step_table[step],
                           av_clip(step + ff_adpcm_index_table[nibble], 0, 88));
415
            } else { //AV_CODEC_ID_ADPCM_YAMAHA
416 417 418
                LOOP_NODES(yamaha, step,
                           av_clip((step * ff_adpcm_yamaha_indexscale[nibble]) >> 8,
                                   127, 24567));
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
#undef LOOP_NODES
#undef STORE_NODE
            }
        }

        u = nodes;
        nodes = nodes_next;
        nodes_next = u;

        generation++;
        if (generation == 255) {
            memset(hash, 0xff, 65536 * sizeof(*hash));
            generation = 0;
        }

        // prevent overflow
435 436
        if (nodes[0]->ssd > (1 << 28)) {
            for (j = 1; j < frontier && nodes[j]; j++)
437 438 439 440 441
                nodes[j]->ssd -= nodes[0]->ssd;
            nodes[0]->ssd = 0;
        }

        // merge old paths to save memory
442
        if (i == froze + FREEZE_INTERVAL) {
443
            p = &paths[nodes[0]->path];
444
            for (k = i; k > froze; k--) {
445 446 447 448 449 450 451 452
                dst[k] = p->nibble;
                p = &paths[p->prev];
            }
            froze = i;
            pathn = 0;
            // other nodes might use paths that don't coincide with the frozen one.
            // checking which nodes do so is too slow, so just kill them all.
            // this also slightly improves quality, but I don't know why.
453
            memset(nodes + 1, 0, (frontier - 1) * sizeof(TrellisNode*));
454 455 456 457
        }
    }

    p = &paths[nodes[0]->path];
458
    for (i = n - 1; i > froze; i--) {
459 460 461 462
        dst[i] = p->nibble;
        p = &paths[p->prev];
    }

463 464 465
    c->predictor  = nodes[0]->sample1;
    c->sample1    = nodes[0]->sample1;
    c->sample2    = nodes[0]->sample2;
466
    c->step_index = nodes[0]->step;
467 468
    c->step       = nodes[0]->step;
    c->idelta     = nodes[0]->step;
469 470
}

471 472
static int adpcm_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
                              const AVFrame *frame, int *got_packet_ptr)
473
{
474
    int n, i, ch, st, pkt_size, ret;
475
    const int16_t *samples;
476
    int16_t **samples_p;
477
    uint8_t *dst;
478 479 480
    ADPCMEncodeContext *c = avctx->priv_data;
    uint8_t *buf;

481
    samples = (const int16_t *)frame->data[0];
482
    samples_p = (int16_t **)frame->extended_data;
483
    st = avctx->channels == 2;
484

485
    if (avctx->codec_id == AV_CODEC_ID_ADPCM_SWF)
486 487 488
        pkt_size = (2 + avctx->channels * (22 + 4 * (frame->nb_samples - 1)) + 7) / 8;
    else
        pkt_size = avctx->block_align;
489
    if ((ret = ff_alloc_packet2(avctx, avpkt, pkt_size, 0)) < 0)
490 491
        return ret;
    dst = avpkt->data;
492 493

    switch(avctx->codec->id) {
494
    case AV_CODEC_ID_ADPCM_IMA_WAV:
495
    {
496
        int blocks, j;
497 498 499 500 501

        blocks = (frame->nb_samples - 1) / 8;

        for (ch = 0; ch < avctx->channels; ch++) {
            ADPCMChannelStatus *status = &c->status[ch];
502
            status->prev_sample = samples_p[ch][0];
503 504 505 506 507
            /* status->step_index = 0;
               XXX: not sure how to init the state machine */
            bytestream_put_le16(&dst, status->prev_sample);
            *dst++ = status->step_index;
            *dst++ = 0; /* unknown */
508
        }
509

510
        /* stereo: 4 bytes (8 samples) for left, 4 bytes for right */
511
        if (avctx->trellis > 0) {
512
            FF_ALLOC_ARRAY_OR_GOTO(avctx, buf, avctx->channels, blocks * 8, error);
513
            for (ch = 0; ch < avctx->channels; ch++) {
514
                adpcm_compress_trellis(avctx, &samples_p[ch][1],
515
                                       buf + ch * blocks * 8, &c->status[ch],
516
                                       blocks * 8, 1);
517 518 519 520 521 522
            }
            for (i = 0; i < blocks; i++) {
                for (ch = 0; ch < avctx->channels; ch++) {
                    uint8_t *buf1 = buf + ch * blocks * 8 + i * 8;
                    for (j = 0; j < 8; j += 2)
                        *dst++ = buf1[j] | (buf1[j + 1] << 4);
523
                }
524 525 526
            }
            av_free(buf);
        } else {
527 528 529
            for (i = 0; i < blocks; i++) {
                for (ch = 0; ch < avctx->channels; ch++) {
                    ADPCMChannelStatus *status = &c->status[ch];
530
                    const int16_t *smp = &samples_p[ch][1 + i * 8];
531
                    for (j = 0; j < 8; j += 2) {
532 533
                        uint8_t v = adpcm_ima_compress_sample(status, smp[j    ]);
                        v        |= adpcm_ima_compress_sample(status, smp[j + 1]) << 4;
534
                        *dst++ = v;
535
                    }
536 537
                }
            }
538
        }
539
        break;
540
    }
541
    case AV_CODEC_ID_ADPCM_IMA_QT:
542 543
    {
        PutBitContext pb;
544
        init_put_bits(&pb, dst, pkt_size);
545

546
        for (ch = 0; ch < avctx->channels; ch++) {
547 548 549
            ADPCMChannelStatus *status = &c->status[ch];
            put_bits(&pb, 9, (status->prev_sample & 0xFFFF) >> 7);
            put_bits(&pb, 7,  status->step_index);
550
            if (avctx->trellis > 0) {
551
                uint8_t buf[64];
552
                adpcm_compress_trellis(avctx, &samples_p[ch][0], buf, status,
553
                                       64, 1);
554 555
                for (i = 0; i < 64; i++)
                    put_bits(&pb, 4, buf[i ^ 1]);
556
                status->prev_sample = status->predictor;
557
            } else {
558
                for (i = 0; i < 64; i += 2) {
559
                    int t1, t2;
560 561
                    t1 = adpcm_ima_qt_compress_sample(status, samples_p[ch][i    ]);
                    t2 = adpcm_ima_qt_compress_sample(status, samples_p[ch][i + 1]);
562 563 564 565 566 567 568 569 570
                    put_bits(&pb, 4, t2);
                    put_bits(&pb, 4, t1);
                }
            }
        }

        flush_put_bits(&pb);
        break;
    }
571
    case AV_CODEC_ID_ADPCM_SWF:
572 573
    {
        PutBitContext pb;
574
        init_put_bits(&pb, dst, pkt_size);
575

576
        n = frame->nb_samples - 1;
577

578 579
        // store AdpcmCodeSize
        put_bits(&pb, 2, 2);    // set 4-bit flash adpcm format
580

581 582 583
        // init the encoder state
        for (i = 0; i < avctx->channels; i++) {
            // clip step so it fits 6 bits
584
            c->status[i].step_index = av_clip_uintp2(c->status[i].step_index, 6);
585 586
            put_sbits(&pb, 16, samples[i]);
            put_bits(&pb, 6, c->status[i].step_index);
587
            c->status[i].prev_sample = samples[i];
588 589
        }

590 591
        if (avctx->trellis > 0) {
            FF_ALLOC_OR_GOTO(avctx, buf, 2 * n, error);
592
            adpcm_compress_trellis(avctx, samples + avctx->channels, buf,
593
                                   &c->status[0], n, avctx->channels);
594
            if (avctx->channels == 2)
595
                adpcm_compress_trellis(avctx, samples + avctx->channels + 1,
596 597
                                       buf + n, &c->status[1], n,
                                       avctx->channels);
598
            for (i = 0; i < n; i++) {
599 600
                put_bits(&pb, 4, buf[i]);
                if (avctx->channels == 2)
601
                    put_bits(&pb, 4, buf[n + i]);
602 603 604
            }
            av_free(buf);
        } else {
605
            for (i = 1; i < frame->nb_samples; i++) {
606 607
                put_bits(&pb, 4, adpcm_ima_compress_sample(&c->status[0],
                         samples[avctx->channels * i]));
608
                if (avctx->channels == 2)
609 610
                    put_bits(&pb, 4, adpcm_ima_compress_sample(&c->status[1],
                             samples[2 * i + 1]));
611 612 613 614 615
            }
        }
        flush_put_bits(&pb);
        break;
    }
616
    case AV_CODEC_ID_ADPCM_MS:
617 618
        for (i = 0; i < avctx->channels; i++) {
            int predictor = 0;
619 620 621 622
            *dst++ = predictor;
            c->status[i].coeff1 = ff_adpcm_AdaptCoeff1[predictor];
            c->status[i].coeff2 = ff_adpcm_AdaptCoeff2[predictor];
        }
623
        for (i = 0; i < avctx->channels; i++) {
624 625 626 627
            if (c->status[i].idelta < 16)
                c->status[i].idelta = 16;
            bytestream_put_le16(&dst, c->status[i].idelta);
        }
628
        for (i = 0; i < avctx->channels; i++)
629
            c->status[i].sample2= *samples++;
630 631
        for (i = 0; i < avctx->channels; i++) {
            c->status[i].sample1 = *samples++;
632 633
            bytestream_put_le16(&dst, c->status[i].sample1);
        }
634
        for (i = 0; i < avctx->channels; i++)
635 636
            bytestream_put_le16(&dst, c->status[i].sample2);

637
        if (avctx->trellis > 0) {
638
            n = avctx->block_align - 7 * avctx->channels;
639 640
            FF_ALLOC_OR_GOTO(avctx, buf, 2 * n, error);
            if (avctx->channels == 1) {
641 642
                adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n,
                                       avctx->channels);
643 644
                for (i = 0; i < n; i += 2)
                    *dst++ = (buf[i] << 4) | buf[i + 1];
645
            } else {
646 647 648 649
                adpcm_compress_trellis(avctx, samples,     buf,
                                       &c->status[0], n, avctx->channels);
                adpcm_compress_trellis(avctx, samples + 1, buf + n,
                                       &c->status[1], n, avctx->channels);
650 651
                for (i = 0; i < n; i++)
                    *dst++ = (buf[i] << 4) | buf[n + i];
652 653
            }
            av_free(buf);
654 655 656 657 658 659 660
        } else {
            for (i = 7 * avctx->channels; i < avctx->block_align; i++) {
                int nibble;
                nibble  = adpcm_ms_compress_sample(&c->status[ 0], *samples++) << 4;
                nibble |= adpcm_ms_compress_sample(&c->status[st], *samples++);
                *dst++  = nibble;
            }
661 662
        }
        break;
663
    case AV_CODEC_ID_ADPCM_YAMAHA:
664
        n = frame->nb_samples / 2;
665 666
        if (avctx->trellis > 0) {
            FF_ALLOC_OR_GOTO(avctx, buf, 2 * n * 2, error);
667
            n *= 2;
668
            if (avctx->channels == 1) {
669 670
                adpcm_compress_trellis(avctx, samples, buf, &c->status[0], n,
                                       avctx->channels);
671 672
                for (i = 0; i < n; i += 2)
                    *dst++ = buf[i] | (buf[i + 1] << 4);
673
            } else {
674 675 676 677
                adpcm_compress_trellis(avctx, samples,     buf,
                                       &c->status[0], n, avctx->channels);
                adpcm_compress_trellis(avctx, samples + 1, buf + n,
                                       &c->status[1], n, avctx->channels);
678 679
                for (i = 0; i < n; i++)
                    *dst++ = buf[i] | (buf[n + i] << 4);
680 681 682
            }
            av_free(buf);
        } else
683
            for (n *= avctx->channels; n > 0; n--) {
684 685 686
                int nibble;
                nibble  = adpcm_yamaha_compress_sample(&c->status[ 0], *samples++);
                nibble |= adpcm_yamaha_compress_sample(&c->status[st], *samples++) << 4;
687
                *dst++  = nibble;
688 689 690
            }
        break;
    default:
691
        return AVERROR(EINVAL);
692
    }
693 694 695 696

    avpkt->size = pkt_size;
    *got_packet_ptr = 1;
    return 0;
697 698
error:
    return AVERROR(ENOMEM);
699 700
}

701 702 703
static const enum AVSampleFormat sample_fmts[] = {
    AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
};
704

705 706 707 708 709
static const enum AVSampleFormat sample_fmts_p[] = {
    AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_NONE
};

#define ADPCM_ENCODER(id_, name_, sample_fmts_, long_name_) \
710 711
AVCodec ff_ ## name_ ## _encoder = {                        \
    .name           = #name_,                               \
712
    .long_name      = NULL_IF_CONFIG_SMALL(long_name_),     \
713 714 715 716
    .type           = AVMEDIA_TYPE_AUDIO,                   \
    .id             = id_,                                  \
    .priv_data_size = sizeof(ADPCMEncodeContext),           \
    .init           = adpcm_encode_init,                    \
717
    .encode2        = adpcm_encode_frame,                   \
718
    .close          = adpcm_encode_close,                   \
719
    .sample_fmts    = sample_fmts_,                         \
720 721
}

722 723 724 725 726
ADPCM_ENCODER(AV_CODEC_ID_ADPCM_IMA_QT,  adpcm_ima_qt,  sample_fmts_p, "ADPCM IMA QuickTime");
ADPCM_ENCODER(AV_CODEC_ID_ADPCM_IMA_WAV, adpcm_ima_wav, sample_fmts_p, "ADPCM IMA WAV");
ADPCM_ENCODER(AV_CODEC_ID_ADPCM_MS,      adpcm_ms,      sample_fmts,   "ADPCM Microsoft");
ADPCM_ENCODER(AV_CODEC_ID_ADPCM_SWF,     adpcm_swf,     sample_fmts,   "ADPCM Shockwave Flash");
ADPCM_ENCODER(AV_CODEC_ID_ADPCM_YAMAHA,  adpcm_yamaha,  sample_fmts,   "ADPCM Yamaha");