encode.c 25.7 KB
Newer Older
1
/**
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
2
 * @file encode.c
3 4
 *
 * @section LICENSE
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
5
 * Copyright 2012 - 2015
6
 *
7 8 9 10
 * Mathis Rosenhauer, Moritz Hanke, Joerg Behrens
 * Deutsches Klimarechenzentrum GmbH
 * Bundesstr. 45a
 * 20146 Hamburg Germany
11
 *
12 13 14 15 16
 * Luis Kornblueh
 * Max-Planck-Institut fuer Meteorologie
 * Bundesstr. 53
 * 20146 Hamburg
 * Germany
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above
 *    copyright notice, this list of conditions and the following
 *    disclaimer in the documentation and/or other materials provided
 *    with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
44 45 46
 * @section DESCRIPTION
 *
 * Adaptive Entropy Encoder
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
47
 * Based on CCSDS documents 121.0-B-2 and 120.0-G-3
48 49
 *
 */
50 51 52 53 54

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
55 56 57
#include "libaec.h"
#include "encode.h"
#include "encode_accessors.h"
58

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
59 60 61 62
static int m_get_block(struct aec_stream *strm);

static inline void emit(struct internal_state *state,
                        uint32_t data, int bits)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
63
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
64 65 66 67
    /**
       Emit sequence of bits.
     */

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
68 69
    if (bits <= state->bits) {
        state->bits -= bits;
70
        *state->cds += (uint8_t)(data << state->bits);
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
71
    } else {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
72
        bits -= state->bits;
73
        *state->cds++ += (uint8_t)((uint64_t)data >> bits);
74

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
75
        while (bits > 8) {
76
            bits -= 8;
77
            *state->cds++ = (uint8_t)(data >> bits);
78
        }
79

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
80
        state->bits = 8 - bits;
81
        *state->cds = (uint8_t)(data << state->bits);
82
    }
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
83 84
}

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
85
static inline void emitfs(struct internal_state *state, int fs)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
86
{
87 88
    /**
       Emits a fundamental sequence.
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
89

90 91
       fs zero bits followed by one 1 bit.
     */
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
92

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
93
    for(;;) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
94 95 96
        if (fs < state->bits) {
            state->bits -= fs + 1;
            *state->cds += 1U << state->bits;
97
            break;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
98
        } else {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
99 100 101
            fs -= state->bits;
            *++state->cds = 0;
            state->bits = 8;
102 103
        }
    }
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
104
}
105

106 107
static inline void copy64(uint8_t *dst, uint64_t src)
{
108 109 110 111 112 113 114 115
    dst[0] = (uint8_t)(src >> 56);
    dst[1] = (uint8_t)(src >> 48);
    dst[2] = (uint8_t)(src >> 40);
    dst[3] = (uint8_t)(src >> 32);
    dst[4] = (uint8_t)(src >> 24);
    dst[5] = (uint8_t)(src >> 16);
    dst[6] = (uint8_t)(src >> 8);
    dst[7] = (uint8_t)src;
116 117
}

118 119
static inline void emitblock_fs(struct aec_stream *strm, int k, int ref)
{
120 121
    uint32_t i;
    uint32_t used; /* used bits in 64 bit accumulator */
122 123 124 125 126 127 128 129
    uint64_t acc; /* accumulator */
    struct internal_state *state = strm->state;

    acc = (uint64_t)*state->cds << 56;
    used = 7 - state->bits;

    for (i = ref; i < strm->block_size; i++) {
        used += (state->block[i] >> k) + 1;
130
        while (used > 63) {
131 132 133
            copy64(state->cds, acc);
            state->cds += 8;
            acc = 0;
134
            used -= 64;
135
        }
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
136
        acc |= UINT64_C(1) << (63 - used);
137 138
    }

139 140 141 142
    copy64(state->cds, acc);
    state->cds += used >> 3;
    state->bits = 7 - (used & 7);
}
143

144 145 146 147 148 149 150 151 152 153
static inline void emitblock(struct aec_stream *strm, int k, int ref)
{
    /**
       Emit the k LSB of a whole block of input data.
    */

    uint64_t a;
    struct internal_state *state = strm->state;
    uint32_t *in = state->block + ref;
    uint32_t *in_end = state->block + strm->block_size;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
154
    uint64_t mask = (UINT64_C(1) << k) - 1;
155 156 157 158 159 160 161 162 163 164 165 166 167 168
    uint8_t *o = state->cds;
    int p = state->bits;

    a = *o;

    while(in < in_end) {
        a <<= 56;
        p = (p % 8) + 56;

        while (p > k && in < in_end) {
            p -= k;
            a += ((uint64_t)(*in++) & mask) << p;
        }

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
169
        switch (p & ~7) {
170
        case 0:
171 172 173 174 175 176 177
            o[0] = (uint8_t)(a >> 56);
            o[1] = (uint8_t)(a >> 48);
            o[2] = (uint8_t)(a >> 40);
            o[3] = (uint8_t)(a >> 32);
            o[4] = (uint8_t)(a >> 24);
            o[5] = (uint8_t)(a >> 16);
            o[6] = (uint8_t)(a >> 8);
178 179 180
            o += 7;
            break;
        case 8:
181 182 183 184 185 186
            o[0] = (uint8_t)(a >> 56);
            o[1] = (uint8_t)(a >> 48);
            o[2] = (uint8_t)(a >> 40);
            o[3] = (uint8_t)(a >> 32);
            o[4] = (uint8_t)(a >> 24);
            o[5] = (uint8_t)(a >> 16);
187 188 189 190
            a >>= 8;
            o += 6;
            break;
        case 16:
191 192 193 194 195
            o[0] = (uint8_t)(a >> 56);
            o[1] = (uint8_t)(a >> 48);
            o[2] = (uint8_t)(a >> 40);
            o[3] = (uint8_t)(a >> 32);
            o[4] = (uint8_t)(a >> 24);
196 197 198 199
            a >>= 16;
            o += 5;
            break;
        case 24:
200 201 202 203
            o[0] = (uint8_t)(a >> 56);
            o[1] = (uint8_t)(a >> 48);
            o[2] = (uint8_t)(a >> 40);
            o[3] = (uint8_t)(a >> 32);
204 205 206 207
            a >>= 24;
            o += 4;
            break;
        case 32:
208 209 210
            o[0] = (uint8_t)(a >> 56);
            o[1] = (uint8_t)(a >> 48);
            o[2] = (uint8_t)(a >> 40);
211 212 213 214
            a >>= 32;
            o += 3;
            break;
        case 40:
215 216
            o[0] = (uint8_t)(a >> 56);
            o[1] = (uint8_t)(a >> 48);
217 218 219 220
            a >>= 40;
            o += 2;
            break;
        case 48:
221
            *o++ = (uint8_t)(a >> 56);
222 223 224 225 226 227
            a >>= 48;
            break;
        default:
            a >>= 56;
            break;
        }
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
228 229
    }

230
    *o = (uint8_t)a;
231 232 233
    state->cds = o;
    state->bits = p % 8;
}
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
234

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
235
static void preprocess_unsigned(struct aec_stream *strm)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
236
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
237 238
    /**
       Preprocess RSI of unsigned samples.
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
239 240 241

       Combining preprocessing and converting to uint32_t in one loop
       is slower due to the data dependance on x_i-1.
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
242 243
    */

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
244
    uint32_t D;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
245
    struct internal_state *state = strm->state;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
246 247
    const uint32_t *restrict x = state->data_raw;
    uint32_t *restrict d = state->data_pp;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
248
    uint32_t xmax = state->xmax;
249 250
    int rsi = (int)strm->rsi * strm->block_size - 1;
    int i;
251

252 253 254
    state->ref = 1;
    state->ref_sample = x[0];
    d[0] = 0;
255
    for (i = 0; i < rsi; i++) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
256 257
        if (x[i + 1] >= x[i]) {
            D = x[i + 1] - x[i];
258
            if (D <= x[i])
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
259
                d[i + 1] = 2 * D;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
260
            else
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
261
                d[i + 1] = x[i + 1];
262
        } else {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
263
            D = x[i] - x[i + 1];
264
            if (D <= xmax - x[i])
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
265
                d[i + 1] = 2 * D - 1;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
266
            else
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
267
                d[i + 1] = xmax - x[i + 1];
268
        }
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
269
    }
270
    state->uncomp_len = (strm->block_size - 1) * strm->bits_per_sample;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
271 272
}

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
273
static void preprocess_signed(struct aec_stream *strm)
274
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
275 276 277 278
    /**
       Preprocess RSI of signed samples.
    */

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
279
    uint32_t D;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
280
    struct internal_state *state = strm->state;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
281
    int32_t *restrict x = (int32_t *)state->data_raw;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
282 283 284
    uint32_t *restrict d = state->data_pp;
    int32_t xmax = (int32_t)state->xmax;
    int32_t xmin = (int32_t)state->xmin;
285
    int rsi = (int)strm->rsi * strm->block_size - 1;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
286
    uint32_t m = UINT64_C(1) << (strm->bits_per_sample - 1);
287
    int i;
288

289 290 291
    state->ref = 1;
    state->ref_sample = x[0];
    d[0] = 0;
292 293
    x[0] = (x[0] ^ m) - m;

294
    for (i = 0; i < rsi; i++) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
295 296
        x[i + 1] = (x[i + 1] ^ m) - m;
        if (x[i + 1] < x[i]) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
297 298 299
            D = (uint32_t)(x[i] - x[i + 1]);
            if (D <= (uint32_t)(xmax - x[i]))
                d[i + 1] = 2 * D - 1;
300
            else
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
301
                d[i + 1] = xmax - x[i + 1];
302
        } else {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
303 304 305
            D = (uint32_t)(x[i + 1] - x[i]);
            if (D <= (uint32_t)(x[i] - xmin))
                d[i + 1] = 2 * D;
306
            else
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
307
                d[i + 1] = x[i + 1] - xmin;
308
        }
309
    }
310
    state->uncomp_len = (strm->block_size - 1) * strm->bits_per_sample;
311
}
312

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
313
static inline uint64_t block_fs(struct aec_stream *strm, int k)
314 315 316 317 318
{
    /**
       Sum FS of all samples in block for given splitting position.
    */

319
    uint32_t i;
320 321 322
    uint64_t fs = 0;
    struct internal_state *state = strm->state;

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
323 324
    for (i = 0; i < strm->block_size; i++)
        fs += (uint64_t)(state->block[i] >> k);
325 326 327 328

    return fs;
}

329
static uint32_t assess_splitting_option(struct aec_stream *strm)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
330 331 332 333 334
{
    /**
       Length of CDS encoded with splitting option and optimal k.

       In Rice coding each sample in a block of samples is split at
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
335
       the same position into k LSB and bits_per_sample - k MSB. The
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
       LSB part is left binary and the MSB part is coded as a
       fundamental sequence a.k.a. unary (see CCSDS 121.0-B-2). The
       function of the length of the Coded Data Set (CDS) depending on
       k has exactly one minimum (see A. Kiely, IPN Progress Report
       42-159).

       To find that minimum with only a few costly evaluations of the
       CDS length, we start with the k of the previous CDS. K is
       increased and the CDS length evaluated. If the CDS length gets
       smaller, then we are moving towards the minimum. If the length
       increases, then the minimum will be found with smaller k.

       For increasing k we know that we will gain block_size bits in
       length through the larger binary part. If the FS lenth is less
       than the block size then a reduced FS part can't compensate the
       larger binary part. So we know that the CDS for k+1 will be
       larger than for k without actually computing the length. An
       analogue check can be done for decreasing k.
     */

356
    int k;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
357 358 359 360 361 362 363 364 365 366 367 368 369
    int k_min;
    int this_bs; /* Block size of current block */
    int no_turn; /* 1 if we shouldn't reverse */
    int dir; /* Direction, 1 means increasing k, 0 decreasing k */
    uint64_t len; /* CDS length for current k */
    uint64_t len_min; /* CDS length minimum so far */
    uint64_t fs_len; /* Length of FS part (not including 1s) */

    struct internal_state *state = strm->state;

    this_bs = strm->block_size - state->ref;
    len_min = UINT64_MAX;
    k = k_min = state->k;
370
    no_turn = k == 0;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
371 372 373
    dir = 1;

    for (;;) {
374
        fs_len = block_fs(strm, k);
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
        len = fs_len + this_bs * (k + 1);

        if (len < len_min) {
            if (len_min < UINT64_MAX)
                no_turn = 1;

            len_min = len;
            k_min = k;

            if (dir) {
                if (fs_len < this_bs || k >= state->kmax) {
                    if (no_turn)
                        break;
                    k = state->k - 1;
                    dir = 0;
                    no_turn = 1;
                } else {
                    k++;
                }
            } else {
                if (fs_len >= this_bs || k == 0)
                    break;
                k--;
            }
        } else {
            if (no_turn)
                break;
            k = state->k - 1;
            dir = 0;
            no_turn = 1;
        }
    }
    state->k = k_min;

409
    return (uint32_t)len_min;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
410 411
}

412
static uint32_t assess_se_option(struct aec_stream *strm)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
413 414 415 416
{
    /**
       Length of CDS encoded with Second Extension option.

417
       If length is above limit just return UINT32_MAX.
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
418 419
    */

420
    uint32_t i;
421
    uint64_t len, d;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
422
    struct internal_state *state = strm->state;
423
    uint32_t *block = state->block;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
424

425
    len = 1;
426

427
    for (i = 0; i < strm->block_size; i += 2) {
428 429 430 431
        d = (uint64_t)block[i] + (uint64_t)block[i + 1];
        len += d * (d + 1) / 2 + block[i + 1] + 1;
        if (len > state->uncomp_len)
            return UINT32_MAX;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
432
    }
433
    return (uint32_t)len;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
434 435
}

436 437 438 439 440 441 442 443 444
static void init_output(struct aec_stream *strm)
{
    /**
       Direct output to next_out if next_out can hold a Coded Data
       Set, use internal buffer otherwise.
    */

    struct internal_state *state = strm->state;

445
    if (strm->avail_out > CDSLEN) {
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
        if (!state->direct_out) {
            state->direct_out = 1;
            *strm->next_out = *state->cds;
            state->cds = strm->next_out;
        }
    } else {
        if (state->zero_blocks == 0 || state->direct_out) {
            /* copy leftover from last block */
            *state->cds_buf = *state->cds;
            state->cds = state->cds_buf;
        }
        state->direct_out = 0;
    }
}

461 462 463 464 465 466
/*
 *
 * FSM functions
 *
 */

467
static int m_flush_block_resumable(struct aec_stream *strm)
468
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
469
    /**
470
       Slow and restartable flushing
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
471
    */
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
472
    struct internal_state *state = strm->state;
473

474 475
    int n = (int)MIN((size_t)(state->cds - state->cds_buf - state->i),
                     strm->avail_out);
476 477 478 479 480 481 482 483 484 485
    memcpy(strm->next_out, state->cds_buf + state->i, n);
    strm->next_out += n;
    strm->avail_out -= n;
    state->i += n;

    if (strm->avail_out == 0) {
        return M_EXIT;
    } else {
        state->mode = m_get_block;
        return M_CONTINUE;
486 487 488
    }
}

489
static int m_flush_block(struct aec_stream *strm)
490
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
491
    /**
492
       Flush block in direct_out mode by updating counters.
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
493

494
       Fall back to slow flushing if in buffered mode.
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
495
    */
496
    int n;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
497
    struct internal_state *state = strm->state;
498

499
#ifdef ENABLE_RSI_PADDING
500 501 502 503 504
    if (state->blocks_avail == 0
        && strm->flags & AEC_PAD_RSI
        && state->block_nonzero == 0
        )
        emit(state, 0, state->bits % 8);
505
#endif
506

507
    if (state->direct_out) {
508
        n = (int)(state->cds - strm->next_out);
509 510
        strm->next_out += n;
        strm->avail_out -= n;
511 512
        state->mode = m_get_block;
        return M_CONTINUE;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
513
    }
514

515 516 517
    state->i = 0;
    state->mode = m_flush_block_resumable;
    return M_CONTINUE;
518
}
519

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
520
static int m_encode_splitting(struct aec_stream *strm)
521
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
522
    struct internal_state *state = strm->state;
523
    int k = state->k;
524

525 526
    emit(state, k + 1, state->id_len);
    if (state->ref)
527
        emit(state, state->ref_sample, strm->bits_per_sample);
528 529 530 531

    emitblock_fs(strm, k, state->ref);
    if (k)
        emitblock(strm, k, state->ref);
532

533 534
    return m_flush_block(strm);
}
535

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
536
static int m_encode_uncomp(struct aec_stream *strm)
537
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
538
    struct internal_state *state = strm->state;
539

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
540
    emit(state, (1U << state->id_len) - 1, state->id_len);
541 542
    if (state->ref)
        state->block[0] = state->ref_sample;
543
    emitblock(strm, strm->bits_per_sample, 0);
544 545
    return m_flush_block(strm);
}
546

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
547
static int m_encode_se(struct aec_stream *strm)
548
{
549
    uint32_t i;
550
    uint32_t d;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
551
    struct internal_state *state = strm->state;
552

553
    emit(state, 1, state->id_len + 1);
554 555
    if (state->ref)
        emit(state, state->ref_sample, strm->bits_per_sample);
556

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
557
    for (i = 0; i < strm->block_size; i+= 2) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
558 559
        d = state->block[i] + state->block[i + 1];
        emitfs(state, d * (d + 1) / 2 + state->block[i + 1]);
560
    }
561

562 563
    return m_flush_block(strm);
}
564

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
565
static int m_encode_zero(struct aec_stream *strm)
566
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
567
    struct internal_state *state = strm->state;
568

569
    emit(state, 0, state->id_len + 1);
570

571
    if (state->zero_ref)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
572
        emit(state, state->zero_ref_sample, strm->bits_per_sample);
573

574 575 576 577 578 579
    if (state->zero_blocks == ROS)
        emitfs(state, 4);
    else if (state->zero_blocks >= 5)
        emitfs(state, state->zero_blocks);
    else
        emitfs(state, state->zero_blocks - 1);
580

581 582 583
    state->zero_blocks = 0;
    return m_flush_block(strm);
}
584

585
static int m_select_code_option(struct aec_stream *strm)
586
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
587
    /**
588 589
       Decide which code option to use.
    */
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
590

591 592
    uint32_t split_len;
    uint32_t se_len;
593 594
    struct internal_state *state = strm->state;

595 596 597 598
    if (state->id_len > 1)
        split_len = assess_splitting_option(strm);
    else
        split_len = UINT32_MAX;
599
    se_len = assess_se_option(strm);
600

601
    if (split_len < state->uncomp_len) {
602 603 604 605 606
        if (split_len < se_len)
            return m_encode_splitting(strm);
        else
            return m_encode_se(strm);
    } else {
607
        if (state->uncomp_len <= se_len)
608 609 610 611 612 613 614 615 616 617 618 619 620
            return m_encode_uncomp(strm);
        else
            return m_encode_se(strm);
    }
}

static int m_check_zero_block(struct aec_stream *strm)
{
    /**
       Check if input block is all zero.

       Aggregate consecutive zero blocks until we find !0 or reach the
       end of a segment or RSI.
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
621
    */
622

623
    uint32_t i;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
624
    struct internal_state *state = strm->state;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
625
    uint32_t *p = state->block;
626

627
    for (i = 0; i < strm->block_size; i++)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
628 629
        if (p[i] != 0)
            break;
630

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
631
    if (i < strm->block_size) {
632 633 634
        if (state->zero_blocks) {
            /* The current block isn't zero but we have to emit a
             * previous zero block first. The current block will be
635
             * flagged and handled later.
636
             */
637
            state->block_nonzero = 1;
638 639 640 641 642 643 644 645 646
            state->mode = m_encode_zero;
            return M_CONTINUE;
        }
        state->mode = m_select_code_option;
        return M_CONTINUE;
    } else {
        state->zero_blocks++;
        if (state->zero_blocks == 1) {
            state->zero_ref = state->ref;
647
            state->zero_ref_sample = state->ref_sample;
648 649 650 651 652 653 654 655
        }
        if (state->blocks_avail == 0
            || (strm->rsi - state->blocks_avail) % 64 == 0) {
            if (state->zero_blocks > 4)
                state->zero_blocks = ROS;
            state->mode = m_encode_zero;
            return M_CONTINUE;
        }
656 657 658
        state->mode = m_get_block;
        return M_CONTINUE;
    }
659
}
660

661 662 663 664 665 666 667 668 669 670 671 672
static int m_get_rsi_resumable(struct aec_stream *strm)
{
    /**
       Get RSI while input buffer is short.

       Let user provide more input. Once we got all input pad buffer
       to full RSI.
    */

    struct internal_state *state = strm->state;

    do {
673
        if (strm->avail_in >= state->bytes_per_sample) {
674 675 676 677
            state->data_raw[state->i] = state->get_sample(strm);
        } else {
            if (state->flush == AEC_FLUSH) {
                if (state->i > 0) {
678 679 680
                    state->blocks_avail = state->i / strm->block_size - 1;
                    if (state->i % strm->block_size)
                        state->blocks_avail++;
681 682 683 684
                    do
                        state->data_raw[state->i] =
                            state->data_raw[state->i - 1];
                    while(++state->i < strm->rsi * strm->block_size);
685
                } else {
686 687
                    /* Finish encoding by padding the last byte with
                     * zero bits. */
688
                    emit(state, 0, state->bits);
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
689
                    if (strm->avail_out > 0) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
690
                        if (!state->direct_out)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
691 692
                            *strm->next_out++ = *state->cds;
                        strm->avail_out--;
693
                        state->flushed = 1;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
694
                    }
695 696 697 698 699 700 701 702
                    return M_EXIT;
                }
            } else {
                return M_EXIT;
            }
        }
    } while (++state->i < strm->rsi * strm->block_size);

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
703
    if (strm->flags & AEC_DATA_PREPROCESS)
704 705 706
        state->preprocess(strm);

    return m_check_zero_block(strm);
707 708
}

709
static int m_get_block(struct aec_stream *strm)
710
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
711
    /**
712 713 714 715
       Provide the next block of preprocessed input data.

       Pull in a whole Reference Sample Interval (RSI) of data if
       block buffer is empty.
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
716
    */
717

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
718
    struct internal_state *state = strm->state;
719

720 721 722 723 724 725
    init_output(strm);

    if (state->block_nonzero) {
        state->block_nonzero = 0;
        state->mode = m_select_code_option;
        return M_CONTINUE;
726
    }
727

728
    if (state->blocks_avail == 0) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
729
        state->blocks_avail = strm->rsi - 1;
730 731
        state->block = state->data_pp;

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
732
        if (strm->avail_in >= state->rsi_len) {
733
            state->get_rsi(strm);
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
734
            if (strm->flags & AEC_DATA_PREPROCESS)
735
                state->preprocess(strm);
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
736

737 738 739 740 741 742
            return m_check_zero_block(strm);
        } else {
            state->i = 0;
            state->mode = m_get_rsi_resumable;
        }
    } else {
743 744 745 746
        if (state->ref) {
            state->ref = 0;
            state->uncomp_len = strm->block_size * strm->bits_per_sample;
        }
747 748 749
        state->block += strm->block_size;
        state->blocks_avail--;
        return m_check_zero_block(strm);
750 751 752 753
    }
    return M_CONTINUE;
}

754 755 756 757 758 759 760 761 762 763 764
static void cleanup(struct aec_stream *strm)
{
    struct internal_state *state = strm->state;

    if (strm->flags & AEC_DATA_PREPROCESS && state->data_raw)
        free(state->data_raw);
    if (state->data_pp)
        free(state->data_pp);
    free(state);
}

765 766 767 768 769
/*
 *
 * API functions
 *
 */
770

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
771
int aec_encode_init(struct aec_stream *strm)
772
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
773
    struct internal_state *state;
774

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
775
    if (strm->bits_per_sample > 32 || strm->bits_per_sample == 0)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
776
        return AEC_CONF_ERROR;
777

778 779 780 781 782 783 784 785 786 787 788 789
    if (strm->flags & AEC_NOT_ENFORCE) {
        /* All even block sizes are allowed. */
        if (strm->block_size & 1)
            return AEC_CONF_ERROR;
    } else {
        /* Only allow standard conforming block sizes */
        if (strm->block_size != 8
            && strm->block_size != 16
            && strm->block_size != 32
            && strm->block_size != 64)
            return AEC_CONF_ERROR;
    }
790 791

    if (strm->rsi > 4096)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
792
        return AEC_CONF_ERROR;
793

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
794
    state = malloc(sizeof(struct internal_state));
795
    if (state == NULL)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
796
        return AEC_MEM_ERROR;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
797 798

    memset(state, 0, sizeof(struct internal_state));
799
    strm->state = state;
800
    state->uncomp_len = strm->block_size * strm->bits_per_sample;
801

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
802
    if (strm->bits_per_sample > 16) {
803
        /* 24/32 input bit settings */
804 805
        state->id_len = 5;

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
806
        if (strm->bits_per_sample <= 24
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
807
            && strm->flags & AEC_DATA_3BYTE) {
808
            state->bytes_per_sample = 3;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
809
            if (strm->flags & AEC_DATA_MSB) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
810 811
                state->get_sample = aec_get_msb_24;
                state->get_rsi = aec_get_rsi_msb_24;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
812
            } else {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
813 814
                state->get_sample = aec_get_lsb_24;
                state->get_rsi = aec_get_rsi_lsb_24;
815
            }
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
816
        } else {
817
            state->bytes_per_sample = 4;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
818
            if (strm->flags & AEC_DATA_MSB) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
819 820
                state->get_sample = aec_get_msb_32;
                state->get_rsi = aec_get_rsi_msb_32;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
821
            } else {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
822 823
                state->get_sample = aec_get_lsb_32;
                state->get_rsi = aec_get_rsi_lsb_32;
824 825
            }
        }
826
    }
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
827
    else if (strm->bits_per_sample > 8) {
828 829
        /* 16 bit settings */
        state->id_len = 4;
830
        state->bytes_per_sample = 2;
831

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
832
        if (strm->flags & AEC_DATA_MSB) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
833 834
            state->get_sample = aec_get_msb_16;
            state->get_rsi = aec_get_rsi_msb_16;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
835
        } else {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
836 837
            state->get_sample = aec_get_lsb_16;
            state->get_rsi = aec_get_rsi_lsb_16;
838
        }
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
839
    } else {
840
        /* 8 bit settings */
841
        if (strm->flags & AEC_RESTRICTED) {
842 843 844 845 846 847 848 849 850 851 852
            if (strm->bits_per_sample <= 4) {
                if (strm->bits_per_sample <= 2)
                    state->id_len = 1;
                else
                    state->id_len = 2;
            } else {
                return AEC_CONF_ERROR;
            }
        } else {
            state->id_len = 3;
        }
853
        state->bytes_per_sample = 1;
854

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
855 856
        state->get_sample = aec_get_8;
        state->get_rsi = aec_get_rsi_8;
857
    }
858
    state->rsi_len = strm->rsi * strm->block_size * state->bytes_per_sample;
859

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
860
    if (strm->flags & AEC_DATA_SIGNED) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
861
        state->xmax = UINT32_MAX >> (32 - strm->bits_per_sample + 1);