encode.c 25.8 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

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

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
58
59
60
#include "libaec.h"
#include "encode.h"
#include "encode_accessors.h"
61

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
62
63
64
65
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
66
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
67
68
69
70
    /**
       Emit sequence of bits.
     */

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

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

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
83
        state->bits = 8 - bits;
84
        *state->cds = (uint8_t)(data << state->bits);
85
    }
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
86
87
}

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

93
94
       fs zero bits followed by one 1 bit.
     */
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
95

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

109
110
static inline void copy64(uint8_t *dst, uint64_t src)
{
111
112
113
114
115
116
117
118
    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;
119
120
}

121
122
static inline void emitblock_fs(struct aec_stream *strm, int k, int ref)
{
123
124
    uint32_t i;
    uint32_t used; /* used bits in 64 bit accumulator */
125
126
127
128
129
130
131
132
    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;
133
        while (used > 63) {
134
135
136
            copy64(state->cds, acc);
            state->cds += 8;
            acc = 0;
137
            used -= 64;
138
        }
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
139
        acc |= UINT64_C(1) << (63 - used);
140
141
    }

142
143
144
145
    copy64(state->cds, acc);
    state->cds += used >> 3;
    state->bits = 7 - (used & 7);
}
146

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

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

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

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

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
247
    uint32_t D;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
248
    struct internal_state *state = strm->state;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
249
250
    const uint32_t *restrict x = state->data_raw;
    uint32_t *restrict d = state->data_pp;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
251
    uint32_t xmax = state->xmax;
252
    uint32_t rsi = strm->rsi * strm->block_size - 1;
253
    unsigned int i;
254

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

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

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

292
293
294
    state->ref = 1;
    state->ref_sample = x[0];
    d[0] = 0;
295
296
    x[0] = (x[0] ^ m) - m;

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

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

322
    uint32_t i;
323
324
325
    uint64_t fs = 0;
    struct internal_state *state = strm->state;

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

    return fs;
}

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

359
    int k;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
360
361
362
363
364
365
366
367
368
369
370
371
372
    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;
373
    no_turn = k == 0;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
374
375
376
    dir = 1;

    for (;;) {
377
        fs_len = block_fs(strm, k);
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
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
409
410
411
        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;

412
    return (uint32_t)len_min;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
413
414
}

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

420
       If length is above limit just return UINT32_MAX.
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
421
422
    */

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

428
    len = 1;
429

430
    for (i = 0; i < strm->block_size; i += 2) {
431
432
433
434
        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
435
    }
436
    return (uint32_t)len;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
437
438
}

439
440
441
442
443
444
445
446
447
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;

448
    if (strm->avail_out > CDSLEN) {
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
        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;
    }
}

464
465
466
467
468
469
/*
 *
 * FSM functions
 *
 */

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

477
478
    int n = (int)MIN((size_t)(state->cds - state->cds_buf - state->i),
                     strm->avail_out);
479
480
481
482
483
484
485
486
487
488
    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;
489
490
491
    }
}

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

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

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

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

518
519
520
    state->i = 0;
    state->mode = m_flush_block_resumable;
    return M_CONTINUE;
521
}
522

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

528
529
    emit(state, k + 1, state->id_len);
    if (state->ref)
530
        emit(state, state->ref_sample, strm->bits_per_sample);
531
532
533
534

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

536
537
    return m_flush_block(strm);
}
538

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
539
static int m_encode_uncomp(struct aec_stream *strm)
540
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
541
    struct internal_state *state = strm->state;
542

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

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

556
    emit(state, 1, state->id_len + 1);
557
558
    if (state->ref)
        emit(state, state->ref_sample, strm->bits_per_sample);
559

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

565
566
    return m_flush_block(strm);
}
567

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
568
static int m_encode_zero(struct aec_stream *strm)
569
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
570
    struct internal_state *state = strm->state;
571

572
    emit(state, 0, state->id_len + 1);
573

574
    if (state->zero_ref)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
575
        emit(state, state->zero_ref_sample, strm->bits_per_sample);
576

577
578
579
580
581
582
    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);
583

584
585
586
    state->zero_blocks = 0;
    return m_flush_block(strm);
}
587

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

594
595
    uint32_t split_len;
    uint32_t se_len;
596
597
    struct internal_state *state = strm->state;

598
599
600
601
    if (state->id_len > 1)
        split_len = assess_splitting_option(strm);
    else
        split_len = UINT32_MAX;
602
    se_len = assess_se_option(strm);
603

604
    if (split_len < state->uncomp_len) {
605
606
607
608
609
        if (split_len < se_len)
            return m_encode_splitting(strm);
        else
            return m_encode_se(strm);
    } else {
610
        if (state->uncomp_len <= se_len)
611
612
613
614
615
616
617
618
619
620
621
622
623
            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
624
    */
625

626
    uint32_t i;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
627
    struct internal_state *state = strm->state;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
628
    uint32_t *p = state->block;
629

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

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
634
    if (i < strm->block_size) {
635
636
637
        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
638
             * flagged and handled later.
639
             */
640
            state->block_nonzero = 1;
641
642
643
644
645
646
647
648
649
            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;
650
            state->zero_ref_sample = state->ref_sample;
651
652
653
654
655
656
657
658
        }
        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;
        }
659
660
661
        state->mode = m_get_block;
        return M_CONTINUE;
    }
662
}
663

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

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
706
    if (strm->flags & AEC_DATA_PREPROCESS)
707
708
709
        state->preprocess(strm);

    return m_check_zero_block(strm);
710
711
}

712
static int m_get_block(struct aec_stream *strm)
713
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
714
    /**
715
716
717
718
       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
719
    */
720

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
721
    struct internal_state *state = strm->state;
722

723
724
725
726
727
728
    init_output(strm);

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

731
    if (state->blocks_avail == 0) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
732
        state->blocks_avail = strm->rsi - 1;
733
734
        state->block = state->data_pp;

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

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

757
758
759
760
761
762
763
764
765
766
767
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);
}

768
769
770
771
772
/*
 *
 * API functions
 *
 */
773

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
774
int aec_encode_init(struct aec_stream *strm)
775
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
776
    struct internal_state *state;
777

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
778
    if (strm->bits_per_sample > 32 || strm->bits_per_sample == 0)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
779
        return AEC_CONF_ERROR;
780
781
782
783
784

    if (strm->block_size != 8
        && strm->block_size != 16
        && strm->block_size != 32
        && strm->block_size != 64)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
785
        return AEC_CONF_ERROR;
786
787

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

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
790
    state = malloc(sizeof(struct internal_state));
791
    if (state == NULL)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
792
        return AEC_MEM_ERROR;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
793
794

    memset(state, 0, sizeof(struct internal_state));
795
    strm->state = state;
796
    state->uncomp_len = strm->block_size * strm->bits_per_sample;
797

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
798
    if (strm->bits_per_sample > 16) {
799
        /* 24/32 input bit settings */
800
801
        state->id_len = 5;

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

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

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
851
852
        state->get_sample = aec_get_8;
        state->get_rsi = aec_get_rsi_8;
853
    }
854
    state->rsi_len = strm->rsi * strm->block_size * state->bytes_per_sample;
855

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
856
    if (strm->flags & AEC_DATA_SIGNED) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
857
        state->xmax = (UINT64_C(1) << (strm->bits_per_sample - 1)) - 1;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
858
        state->xmin = ~state->xmax;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
859
        state->preprocess = preprocess_signed;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
860
    } else {
861
        state->xmin = 0;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
862
        state->xmax = (UINT64_C(1) << strm->bits_per_sample) - 1;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
863
        state->preprocess = preprocess_unsigned;
864
865
    }

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

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
868
869
870
    state->data_pp = malloc(strm->rsi
                            * strm->block_size
                            * sizeof(uint32_t));
871
872
    if (state->data_pp == NULL) {
        cleanup(strm);
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
873
        return AEC_MEM_ERROR;
874
    }
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
875

876
    if (strm->flags & AEC_DATA_PREPROCESS) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
877
878
879
        state->data_raw = malloc(strm->rsi
                                 * strm->block_size
                                 * sizeof(uint32_t));
880
881
        if (state->data_raw == NULL) {
            cleanup(strm);
882
            return AEC_MEM_ERROR;
883
        }
884
885
886
887
    } else {
        state->data_raw = state->data_pp;
    }

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
888
    state->block = state->data_pp;
889

890
    state->ref = 0;
891
892
    strm->total_in = 0;
    strm->total_out = 0;
893
    state->flushed = 0;
894

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
895
896
897
    state->cds = state->cds_buf;
    *state->cds = 0;
    state->bits = 8;
898
899
    state->mode = m_get_block;

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
900
    return AEC_OK;
901
902
}

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
903
int aec_encode(struct aec_stream *strm, int flush)
904
905
906
907
908
{
    /**
       Finite-state machine implementation of the adaptive entropy
       encoder.
    */
909
    int n;
910
911
    struct internal_state *state = strm->state;

912
    state->flush = flush;
913
914
    strm->total_in += strm->avail_in;
    strm->total_out += strm->avail_out;
915
916
917

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

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
918
    if (state->direct_out) {
919
        n = (int)(state->cds - strm->next_out);
920
921
922
        strm->next_out += n;
        strm->avail_out -= n;

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
923
924
        *state->cds_buf = *state->cds;
        state->cds = state->cds_buf;
925
        state->direct_out = 0;
926
    }
927
928
    strm->total_in -= strm->avail_in;
    strm->total_out -= strm->avail_out;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
929
    return AEC_OK;
930
931
}

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
932
int aec_encode_end(struct aec_stream *strm)
933
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
934
    struct internal_state *state = strm->state;
935
    int status;
936

937
938
939
940
941
    status = AEC_OK;
    if (state->flush == AEC_FLUSH && state->flushed == 0)
        status = AEC_STREAM_ERROR;
    cleanup(strm);
    return status;
942
}
943

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
944
int aec_buffer_encode(struct aec_stream *strm)
945
946
947
948
949
950
951
{
    int status;

    status = aec_encode_init(strm);
    if (status != AEC_OK)
        return status;
    status = aec_encode(strm, AEC_FLUSH);
952
953
954
955
956
    if (status != AEC_OK) {
        cleanup(strm);
        return status;
    }
    return aec_encode_end(strm);
957
}