encode.c 24.7 KB
Newer Older
1
/**
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
2
 * @file encode.c
3
 *
4
 * @author Mathis Rosenhauer, Deutsches Klimarechenzentrum
5 6 7 8 9
 * @author Moritz Hanke, Deutsches Klimarechenzentrum
 * @author Joerg Behrens, Deutsches Klimarechenzentrum
 * @author Luis Kornblueh, Max-Planck-Institut fuer Meteorologie
 *
 * @section LICENSE
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
10
 * Copyright 2012 - 2014
11 12 13 14 15 16 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 44 45 46
 *
 * Mathis Rosenhauer,                 Luis Kornblueh
 * Moritz Hanke,
 * Joerg Behrens
 *
 * Deutsches Klimarechenzentrum GmbH  Max-Planck-Institut fuer Meteorologie
 * Bundesstr. 45a                     Bundesstr. 53
 * 20146 Hamburg                      20146 Hamburg
 * Germany                            Germany
 *
 * 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.
 *
47 48 49
 * @section DESCRIPTION
 *
 * Adaptive Entropy Encoder
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
50
 * Based on CCSDS documents 121.0-B-2 and 120.0-G-3
51 52
 *
 */
53

54 55 56 57 58 59
#include <config.h>

#if HAVE_STDINT_H
# include <stdint.h>
#endif

60 61 62 63
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
64 65 66
#include "libaec.h"
#include "encode.h"
#include "encode_accessors.h"
67

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
68 69 70 71
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
72
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
73 74 75 76
    /**
       Emit sequence of bits.
     */

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
77 78 79
    if (bits <= state->bits) {
        state->bits -= bits;
        *state->cds += data << state->bits;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
80
    } else {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
81 82
        bits -= state->bits;
        *state->cds++ += (uint64_t)data >> bits;
83

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
84
        while (bits > 8) {
85
            bits -= 8;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
86
            *state->cds++ = data >> bits;
87
        }
88

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
89 90
        state->bits = 8 - bits;
        *state->cds = data << state->bits;
91
    }
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
92 93
}

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
94
static inline void emitfs(struct internal_state *state, int fs)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
95
{
96 97
    /**
       Emits a fundamental sequence.
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
98

99 100
       fs zero bits followed by one 1 bit.
     */
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
101

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
102
    for(;;) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
103 104 105
        if (fs < state->bits) {
            state->bits -= fs + 1;
            *state->cds += 1U << state->bits;
106
            break;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
107
        } else {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
108 109 110
            fs -= state->bits;
            *++state->cds = 0;
            state->bits = 8;
111 112
        }
    }
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
113
}
114

115 116 117 118 119 120 121 122 123 124 125 126
static inline void copy64(uint8_t *dst, uint64_t src)
{
    dst[0] = src >> 56;
    dst[1] = src >> 48;
    dst[2] = src >> 40;
    dst[3] = src >> 32;
    dst[4] = src >> 24;
    dst[5] = src >> 16;
    dst[6] = src >> 8;
    dst[7] = src;
}

127 128 129 130 131 132 133 134 135 136 137 138
static inline void emitblock_fs(struct aec_stream *strm, int k, int ref)
{
    int i;
    int used; /* used bits in 64 bit accumulator */
    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;
139
        while (used > 63) {
140 141 142
            copy64(state->cds, acc);
            state->cds += 8;
            acc = 0;
143
            used -= 64;
144 145
        }
        acc |= 1ULL << (63 - used);
146 147
    }

148 149 150 151
    copy64(state->cds, acc);
    state->cds += used >> 3;
    state->bits = 7 - (used & 7);
}
152

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
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;
    uint64_t mask = (1ULL << k) - 1;
    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
178
        switch (p & ~7) {
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
        case 0:
            o[0] = a >> 56;
            o[1] = a >> 48;
            o[2] = a >> 40;
            o[3] = a >> 32;
            o[4] = a >> 24;
            o[5] = a >> 16;
            o[6] = a >> 8;
            o += 7;
            break;
        case 8:
            o[0] = a >> 56;
            o[1] = a >> 48;
            o[2] = a >> 40;
            o[3] = a >> 32;
            o[4] = a >> 24;
            o[5] = a >> 16;
            a >>= 8;
            o += 6;
            break;
        case 16:
            o[0] = a >> 56;
            o[1] = a >> 48;
            o[2] = a >> 40;
            o[3] = a >> 32;
            o[4] = a >> 24;
            a >>= 16;
            o += 5;
            break;
        case 24:
            o[0] = a >> 56;
            o[1] = a >> 48;
            o[2] = a >> 40;
            o[3] = a >> 32;
            a >>= 24;
            o += 4;
            break;
        case 32:
            o[0] = a >> 56;
            o[1] = a >> 48;
            o[2] = a >> 40;
            a >>= 32;
            o += 3;
            break;
        case 40:
            o[0] = a >> 56;
            o[1] = a >> 48;
            a >>= 40;
            o += 2;
            break;
        case 48:
            *o++ = a >> 56;
            a >>= 48;
            break;
        default:
            a >>= 56;
            break;
        }
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
237 238
    }

239 240 241 242
    *o = a;
    state->cds = o;
    state->bits = p % 8;
}
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
243

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
244
static void preprocess_unsigned(struct aec_stream *strm)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
245
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
246 247
    /**
       Preprocess RSI of unsigned samples.
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
248 249 250

       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
251 252
    */

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
253
    uint32_t D;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
254
    struct internal_state *state = strm->state;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
255 256
    const uint32_t *restrict x = state->data_raw;
    uint32_t *restrict d = state->data_pp;
257 258
    uint32_t xmax = state->xmax;
    uint32_t rsi = strm->rsi * strm->block_size - 1;
259
    int i;
260

261 262
    d[0] = x[0];
    for (i = 0; i < rsi; i++) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
263 264
        if (x[i + 1] >= x[i]) {
            D = x[i + 1] - x[i];
265
            if (D <= x[i])
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
266
                d[i + 1] = 2 * D;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
267
            else
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
268
                d[i + 1] = x[i + 1];
269
        } else {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
270
            D = x[i] - x[i + 1];
271
            if (D <= xmax - x[i])
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
272
                d[i + 1] = 2 * D - 1;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
273
            else
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
274
                d[i + 1] = xmax - x[i + 1];
275
        }
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
276
    }
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
277
    state->ref = 1;
278
    state->uncomp_len = (strm->block_size - 1) * strm->bits_per_sample;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
279 280
}

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
281
static void preprocess_signed(struct aec_stream *strm)
282
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
283 284 285 286
    /**
       Preprocess RSI of signed samples.
    */

287
    int64_t D;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
288
    struct internal_state *state = strm->state;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
289 290
    uint32_t *restrict d = state->data_pp;
    int32_t *restrict x = (int32_t *)state->data_raw;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
291
    uint64_t m = 1ULL << (strm->bits_per_sample - 1);
292 293 294
    int64_t xmax = state->xmax;
    int64_t xmin = state->xmin;
    uint32_t rsi = strm->rsi * strm->block_size - 1;
295
    int i;
296

297
    d[0] = (uint32_t)x[0];
298 299
    x[0] = (x[0] ^ m) - m;

300
    for (i = 0; i < rsi; i++) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
301 302 303
        x[i + 1] = (x[i + 1] ^ m) - m;
        if (x[i + 1] < x[i]) {
            D = (int64_t)x[i] - x[i + 1];
304 305
            if (D <= xmax - x[i])
                d[i + 1] = 2 * D - 1;
306
            else
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
307
                d[i + 1] = xmax - x[i + 1];
308
        } else {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
309
            D = (int64_t)x[i + 1] - x[i];
310 311
            if (D <= x[i] - xmin)
                d[i + 1] = 2 * D;
312
            else
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
313
                d[i + 1] = x[i + 1] - xmin;
314
        }
315
    }
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
316
    state->ref = 1;
317
    state->uncomp_len = (strm->block_size - 1) * strm->bits_per_sample;
318
}
319

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
320
static inline uint64_t block_fs(struct aec_stream *strm, int k)
321 322 323 324 325 326 327 328 329
{
    /**
       Sum FS of all samples in block for given splitting position.
    */

    int i;
    uint64_t fs = 0;
    struct internal_state *state = strm->state;

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
330 331
    for (i = 0; i < strm->block_size; i++)
        fs += (uint64_t)(state->block[i] >> k);
332 333 334 335 336 337 338

    if (state->ref)
        fs -= (uint64_t)(state->block[0] >> k);

    return fs;
}

339
static uint32_t assess_splitting_option(struct aec_stream *strm)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
340 341 342 343 344
{
    /**
       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
345
       the same position into k LSB and bits_per_sample - k MSB. The
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
       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.
     */

366
    int k;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
367 368 369 370 371 372 373 374 375 376 377 378 379
    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;
380
    no_turn = k == 0;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
381 382 383
    dir = 1;

    for (;;) {
384
        fs_len = block_fs(strm, k);
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
        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;

    return len_min;
}

422
static uint32_t assess_se_option(struct aec_stream *strm)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
423 424 425 426
{
    /**
       Length of CDS encoded with Second Extension option.

427
       If length is above limit just return UINT32_MAX.
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
428 429 430 431
    */

    int i;
    uint64_t d;
432
    uint32_t len;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
433 434 435 436 437 438 439 440
    struct internal_state *state = strm->state;

    len = 1;

    for (i = 0; i < strm->block_size; i+= 2) {
        d = (uint64_t)state->block[i]
            + (uint64_t)state->block[i + 1];
        /* we have to worry about overflow here */
441 442
        if (d > state->uncomp_len) {
            len = UINT32_MAX;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
443 444
            break;
        } else {
445
            len += d * (d + 1) / 2 + state->block[i + 1] + 1;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
446 447 448 449 450
        }
    }
    return len;
}

451 452 453 454 455 456 457 458 459
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;

460
    if (strm->avail_out > CDSLEN) {
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
        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;
    }
}

476 477 478 479 480 481
/*
 *
 * FSM functions
 *
 */

482
static int m_flush_block_resumable(struct aec_stream *strm)
483
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
484
    /**
485
       Slow and restartable flushing
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
486
    */
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
487
    struct internal_state *state = strm->state;
488

489 490 491 492 493 494 495 496 497 498 499
    int n = MIN(state->cds - state->cds_buf - state->i, strm->avail_out);
    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;
500 501 502
    }
}

503
static int m_flush_block(struct aec_stream *strm)
504
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
505
    /**
506
       Flush block in direct_out mode by updating counters.
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
507

508
       Fall back to slow flushing if in buffered mode.
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
509
    */
510
    int n;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
511
    struct internal_state *state = strm->state;
512

513
#ifdef ENABLE_RSI_PADDING
514 515 516 517 518
    if (state->blocks_avail == 0
        && strm->flags & AEC_PAD_RSI
        && state->block_nonzero == 0
        )
        emit(state, 0, state->bits % 8);
519
#endif
520

521 522 523 524
    if (state->direct_out) {
        n = state->cds - strm->next_out;
        strm->next_out += n;
        strm->avail_out -= n;
525 526
        state->mode = m_get_block;
        return M_CONTINUE;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
527
    }
528

529 530 531
    state->i = 0;
    state->mode = m_flush_block_resumable;
    return M_CONTINUE;
532
}
533

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

539
    emit(state, k + 1, state->id_len);
540

541
    if (state->ref)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
542
        emit(state, state->block[0], strm->bits_per_sample);
543 544 545 546

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

548 549
    return m_flush_block(strm);
}
550

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
551
static int m_encode_uncomp(struct aec_stream *strm)
552
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
553
    struct internal_state *state = strm->state;
554

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
555
    emit(state, (1U << state->id_len) - 1, state->id_len);
556
    emitblock(strm, strm->bits_per_sample, 0);
557

558 559
    return m_flush_block(strm);
}
560

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
561
static int m_encode_se(struct aec_stream *strm)
562 563
{
    int i;
564
    uint32_t d;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
565
    struct internal_state *state = strm->state;
566

567 568
    emit(state, 1, state->id_len + 1);
    if (state->ref)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
569
        emit(state, state->block[0], strm->bits_per_sample);
570

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
571
    for (i = 0; i < strm->block_size; i+= 2) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
572 573
        d = state->block[i] + state->block[i + 1];
        emitfs(state, d * (d + 1) / 2 + state->block[i + 1]);
574
    }
575

576 577
    return m_flush_block(strm);
}
578

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
579
static int m_encode_zero(struct aec_stream *strm)
580
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
581
    struct internal_state *state = strm->state;
582

583
    emit(state, 0, state->id_len + 1);
584

585
    if (state->zero_ref)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
586
        emit(state, state->zero_ref_sample, strm->bits_per_sample);
587

588 589 590 591 592 593
    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);
594

595 596 597
    state->zero_blocks = 0;
    return m_flush_block(strm);
}
598

599
static int m_select_code_option(struct aec_stream *strm)
600
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
601
    /**
602 603
       Decide which code option to use.
    */
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
604

605 606
    uint32_t split_len;
    uint32_t se_len;
607 608
    struct internal_state *state = strm->state;

609 610 611 612
    if (state->id_len > 1)
        split_len = assess_splitting_option(strm);
    else
        split_len = UINT32_MAX;
613
    se_len = assess_se_option(strm);
614

615
    if (split_len < state->uncomp_len) {
616 617 618 619 620
        if (split_len < se_len)
            return m_encode_splitting(strm);
        else
            return m_encode_se(strm);
    } else {
621
        if (state->uncomp_len <= se_len)
622 623 624 625 626 627 628 629 630 631 632 633 634
            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
635
    */
636

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
637
    int i;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
638
    struct internal_state *state = strm->state;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
639
    uint32_t *p = state->block;
640

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
641 642 643
    for (i = state->ref; i < strm->block_size; i++)
        if (p[i] != 0)
            break;
644

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
645
    if (i < strm->block_size) {
646 647 648
        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
649
             * flagged and handled later.
650
             */
651
            state->block_nonzero = 1;
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
            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;
            state->zero_ref_sample = state->block[0];
        }
        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;
        }
670 671 672
        state->mode = m_get_block;
        return M_CONTINUE;
    }
673
}
674

675 676 677 678 679 680 681 682 683 684 685 686
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 {
687
        if (strm->avail_in >= state->bytes_per_sample) {
688 689 690 691
            state->data_raw[state->i] = state->get_sample(strm);
        } else {
            if (state->flush == AEC_FLUSH) {
                if (state->i > 0) {
692 693 694
                    state->blocks_avail = state->i / strm->block_size - 1;
                    if (state->i % strm->block_size)
                        state->blocks_avail++;
695 696 697 698
                    do
                        state->data_raw[state->i] =
                            state->data_raw[state->i - 1];
                    while(++state->i < strm->rsi * strm->block_size);
699 700
                } else {
                    emit(state, 0, state->bits);
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
701
                    if (strm->avail_out > 0) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
702
                        if (!state->direct_out)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
703 704 705
                            *strm->next_out++ = *state->cds;
                        strm->avail_out--;
                    }
706 707 708 709 710 711 712 713
                    return M_EXIT;
                }
            } else {
                return M_EXIT;
            }
        }
    } while (++state->i < strm->rsi * strm->block_size);

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
714
    if (strm->flags & AEC_DATA_PREPROCESS)
715 716 717
        state->preprocess(strm);

    return m_check_zero_block(strm);
718 719
}

720
static int m_get_block(struct aec_stream *strm)
721
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
722
    /**
723 724 725 726
       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
727
    */
728

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
729
    struct internal_state *state = strm->state;
730

731 732 733 734 735 736
    init_output(strm);

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

739
    if (state->blocks_avail == 0) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
740
        state->blocks_avail = strm->rsi - 1;
741 742
        state->block = state->data_pp;

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
743
        if (strm->avail_in >= state->rsi_len) {
744
            state->get_rsi(strm);
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
745
            if (strm->flags & AEC_DATA_PREPROCESS)
746
                state->preprocess(strm);
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
747

748 749 750 751 752 753
            return m_check_zero_block(strm);
        } else {
            state->i = 0;
            state->mode = m_get_rsi_resumable;
        }
    } else {
754 755 756 757
        if (state->ref) {
            state->ref = 0;
            state->uncomp_len = strm->block_size * strm->bits_per_sample;
        }
758 759 760
        state->block += strm->block_size;
        state->blocks_avail--;
        return m_check_zero_block(strm);
761 762 763 764 765 766 767 768 769
    }
    return M_CONTINUE;
}

/*
 *
 * 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

    if (strm->block_size != 8
        && strm->block_size != 16
        && strm->block_size != 32
        && strm->block_size != 64)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
782
        return AEC_CONF_ERROR;
783 784

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

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
787
    state = malloc(sizeof(struct internal_state));
788
    if (state == NULL)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
789
        return AEC_MEM_ERROR;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
790 791

    memset(state, 0, sizeof(struct internal_state));
792 793
    strm->state = state;

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
794
    if (strm->bits_per_sample > 16) {
795
        /* 24/32 input bit settings */
796 797
        state->id_len = 5;

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

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
824
        if (strm->flags & AEC_DATA_MSB) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
825 826
            state->get_sample = aec_get_msb_16;
            state->get_rsi = aec_get_rsi_msb_16;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
827
        } else {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
828 829
            state->get_sample = aec_get_lsb_16;
            state->get_rsi = aec_get_rsi_lsb_16;
830
        }
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
831
    } else {
832
        /* 8 bit settings */
833
        if (strm->flags & AEC_RESTRICTED) {
834 835 836 837 838 839 840 841 842 843 844
            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;
        }
845
        state->bytes_per_sample = 1;
846

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
847 848
        state->get_sample = aec_get_8;
        state->get_rsi = aec_get_rsi_8;
849
    }
850
    state->rsi_len = strm->rsi * strm->block_size * state->bytes_per_sample;
851

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
852
    if (strm->flags & AEC_DATA_SIGNED) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
853 854
        state->xmin = -(1ULL << (strm->bits_per_sample - 1));
        state->xmax = (1ULL << (strm->bits_per_sample - 1)) - 1;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
855
        state->preprocess = preprocess_signed;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
856
    } else {
857
        state->xmin = 0;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
858
        state->xmax = (1ULL << strm->bits_per_sample) - 1;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
859
        state->preprocess = preprocess_unsigned;
860 861
    }

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
862 863
    state->kmax = (1U << state->id_len) - 3;

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
864 865 866
    state->data_pp = malloc(strm->rsi
                            * strm->block_size
                            * sizeof(uint32_t));
867
    if (state->data_pp == NULL)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
868
        return AEC_MEM_ERROR;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
869

870
    if (strm->flags & AEC_DATA_PREPROCESS) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
871 872 873
        state->data_raw = malloc(strm->rsi
                                 * strm->block_size
                                 * sizeof(uint32_t));
874 875 876 877 878 879
        if (state->data_raw == NULL)
            return AEC_MEM_ERROR;
    } else {
        state->data_raw = state->data_pp;
    }

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
880
    state->block = state->data_pp;
881 882 883 884

    strm->total_in = 0;
    strm->total_out = 0;

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
885 886 887
    state->cds = state->cds_buf;
    *state->cds = 0;
    state->bits = 8;
888 889
    state->mode = m_get_block;

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
890
    return AEC_OK;
891 892
}

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
893
int aec_encode(struct aec_stream *strm, int flush)
894 895 896 897 898
{
    /**
       Finite-state machine implementation of the adaptive entropy
       encoder.
    */
899
    int n;
900 901
    struct internal_state *state = strm->state;

902
    state->flush = flush;
903 904
    strm->total_in += strm->avail_in;
    strm->total_out += strm->avail_out;
905 906 907

    while (state->mode(strm) == M_CONTINUE);

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
908
    if (state->direct_out) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
909
        n = state->cds - strm->next_out;
910 911 912
        strm->next_out += n;
        strm->avail_out -= n;

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
913 914
        *state->cds_buf = *state->cds;
        state->cds = state->cds_buf;
915
        state->direct_out = 0;
916
    }
917 918
    strm->total_in -= strm->avail_in;
    strm->total_out -= strm->avail_out;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
919
    return AEC_OK;
920 921
}

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
922
int aec_encode_end(struct aec_stream *strm)
923
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
924
    struct internal_state *state = strm->state;
925

926 927 928
    if (strm->flags & AEC_DATA_PREPROCESS)
        free(state->data_raw);
    free(state->data_pp);
929
    free(state);
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
930
    return AEC_OK;
931
}
932

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
933
int aec_buffer_encode(struct aec_stream *strm)
934 935 936 937 938 939 940
{
    int status;

    status = aec_encode_init(strm);
    if (status != AEC_OK)
        return status;
    status = aec_encode(strm, AEC_FLUSH);
941
    if (strm->avail_in > 0)
942 943 944 945 946
        status = AEC_DATA_ERROR;

    aec_encode_end(strm);
    return status;
}