encode.c 25.6 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 - 2017
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
#include "encode.h"
#include "encode_accessors.h"
57
#include "libaec.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
120
121
static inline void emitblock_fs(struct aec_stream *strm, int k, int ref)
{
    struct internal_state *state = strm->state;

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
122
123
    uint64_t acc = (uint64_t)*state->cds << 56;
    uint32_t used = 7 - state->bits; /* used bits in 64 bit accumulator */
124

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

136
137
138
139
    copy64(state->cds, acc);
    state->cds += used >> 3;
    state->bits = 7 - (used & 7);
}
140

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

    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
150
    uint64_t mask = (UINT64_C(1) << k) - 1;
151
    uint8_t *o = state->cds;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
152
    uint64_t a = *o;
153
154
155
156
157
158
159
160
161
162
163
    int p = state->bits;

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

225
    *o = (uint8_t)a;
226
227
228
    state->cds = o;
    state->bits = p % 8;
}
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
229

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
230
static void preprocess_unsigned(struct aec_stream *strm)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
231
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
232
233
    /**
       Preprocess RSI of unsigned samples.
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
234
235
236

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

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
239
    uint32_t D;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
240
    struct internal_state *state = strm->state;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
241
242
    const uint32_t *restrict x = state->data_raw;
    uint32_t *restrict d = state->data_pp;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
243
    uint32_t xmax = state->xmax;
244
    uint32_t rsi = strm->rsi * strm->block_size - 1;
245

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

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
267
static void preprocess_signed(struct aec_stream *strm)
268
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
269
270
271
272
    /**
       Preprocess RSI of signed samples.
    */

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
273
    uint32_t D;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
274
    struct internal_state *state = strm->state;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
275
    int32_t *restrict x = (int32_t *)state->data_raw;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
276
277
278
    uint32_t *restrict d = state->data_pp;
    int32_t xmax = (int32_t)state->xmax;
    int32_t xmin = (int32_t)state->xmin;
279
    uint32_t rsi = strm->rsi * strm->block_size - 1;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
280
    uint32_t m = UINT64_C(1) << (strm->bits_per_sample - 1);
281

282
283
284
    state->ref = 1;
    state->ref_sample = x[0];
    d[0] = 0;
285
286
    x[0] = (x[0] ^ m) - m;

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
287
    for (size_t i = 0; i < rsi; i++) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
288
289
        x[i + 1] = (x[i + 1] ^ m) - m;
        if (x[i + 1] < x[i]) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
290
291
292
            D = (uint32_t)(x[i] - x[i + 1]);
            if (D <= (uint32_t)(xmax - x[i]))
                d[i + 1] = 2 * D - 1;
293
            else
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
294
                d[i + 1] = xmax - x[i + 1];
295
        } else {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
296
297
298
            D = (uint32_t)(x[i + 1] - x[i]);
            if (D <= (uint32_t)(x[i] - xmin))
                d[i + 1] = 2 * D;
299
            else
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
300
                d[i + 1] = x[i + 1] - xmin;
301
        }
302
    }
303
    state->uncomp_len = (strm->block_size - 1) * strm->bits_per_sample;
304
}
305

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
306
static inline uint64_t block_fs(struct aec_stream *strm, int k)
307
308
309
310
311
312
{
    /**
       Sum FS of all samples in block for given splitting position.
    */

    struct internal_state *state = strm->state;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
313
    uint64_t fs = 0;
314

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
315
    for (size_t i = 0; i < strm->block_size; i++)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
316
        fs += (uint64_t)(state->block[i] >> k);
317
318
319
320

    return fs;
}

321
static uint32_t assess_splitting_option(struct aec_stream *strm)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
322
323
324
325
326
{
    /**
       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
327
       the same position into k LSB and bits_per_sample - k MSB. The
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
       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.
     */

    struct internal_state *state = strm->state;

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
350
351
352
353
354
355
356
357
358
359
360
361
362
363
    /* Block size of current block */
    int this_bs = strm->block_size - state->ref;

    /* CDS length minimum so far */
    uint64_t len_min = UINT64_MAX;

    int k = state->k;
    int k_min = k;

    /* 1 if we shouldn't reverse */
    int no_turn = (k == 0);

    /* Direction, 1 means increasing k, 0 decreasing k */
    int dir = 1;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
364
365

    for (;;) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
366
367
368
369
370
        /* Length of FS part (not including 1s) */
        uint64_t fs_len = block_fs(strm, k);

        /* CDS length for current k */
        uint64_t len = fs_len + this_bs * (k + 1);
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
371
372
373
374
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

        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;

404
    return (uint32_t)len_min;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
405
406
}

407
static uint32_t assess_se_option(struct aec_stream *strm)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
408
409
410
411
{
    /**
       Length of CDS encoded with Second Extension option.

412
       If length is above limit just return UINT32_MAX.
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
413
414
415
    */

    struct internal_state *state = strm->state;
416
    uint32_t *block = state->block;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
417
    uint64_t len = 1;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
418

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
419
420
    for (size_t i = 0; i < strm->block_size; i += 2) {
        uint64_t d = (uint64_t)block[i] + (uint64_t)block[i + 1];
421
422
423
        len += d * (d + 1) / 2 + block[i + 1] + 1;
        if (len > state->uncomp_len)
            return UINT32_MAX;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
424
    }
425
    return (uint32_t)len;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
426
427
}

428
429
430
431
432
433
434
435
436
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;

437
    if (strm->avail_out > CDSLEN) {
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
        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;
    }
}

453
454
455
456
457
458
/*
 *
 * FSM functions
 *
 */

459
static int m_flush_block_resumable(struct aec_stream *strm)
460
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
461
    /**
462
       Slow and restartable flushing
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
463
    */
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
464
    struct internal_state *state = strm->state;
465

466
467
    int n = (int)MIN((size_t)(state->cds - state->cds_buf - state->i),
                     strm->avail_out);
468
469
470
471
472
473
474
475
476
477
    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;
478
479
480
    }
}

481
static int m_flush_block(struct aec_stream *strm)
482
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
483
    /**
484
       Flush block in direct_out mode by updating counters.
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
485

486
       Fall back to slow flushing if in buffered mode.
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
487
    */
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
488
    struct internal_state *state = strm->state;
489

490
#ifdef ENABLE_RSI_PADDING
491
492
493
494
495
    if (state->blocks_avail == 0
        && strm->flags & AEC_PAD_RSI
        && state->block_nonzero == 0
        )
        emit(state, 0, state->bits % 8);
496
#endif
497

498
    if (state->direct_out) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
499
        int n = (int)(state->cds - strm->next_out);
500
501
        strm->next_out += n;
        strm->avail_out -= n;
502
503
        state->mode = m_get_block;
        return M_CONTINUE;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
504
    }
505

506
507
508
    state->i = 0;
    state->mode = m_flush_block_resumable;
    return M_CONTINUE;
509
}
510

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
511
static int m_encode_splitting(struct aec_stream *strm)
512
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
513
    struct internal_state *state = strm->state;
514
    int k = state->k;
515

516
517
    emit(state, k + 1, state->id_len);
    if (state->ref)
518
        emit(state, state->ref_sample, strm->bits_per_sample);
519
520
521
522

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

524
525
    return m_flush_block(strm);
}
526

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
527
static int m_encode_uncomp(struct aec_stream *strm)
528
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
529
    struct internal_state *state = strm->state;
530

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
531
    emit(state, (1U << state->id_len) - 1, state->id_len);
532
533
    if (state->ref)
        state->block[0] = state->ref_sample;
534
    emitblock(strm, strm->bits_per_sample, 0);
535
536
    return m_flush_block(strm);
}
537

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

542
    emit(state, 1, state->id_len + 1);
543
544
    if (state->ref)
        emit(state, state->ref_sample, strm->bits_per_sample);
545

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
546
547
    for (size_t i = 0; i < strm->block_size; i+= 2) {
        uint32_t d = state->block[i] + state->block[i + 1];
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
548
        emitfs(state, d * (d + 1) / 2 + state->block[i + 1]);
549
    }
550

551
552
    return m_flush_block(strm);
}
553

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
554
static int m_encode_zero(struct aec_stream *strm)
555
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
556
    struct internal_state *state = strm->state;
557

558
    emit(state, 0, state->id_len + 1);
559

560
    if (state->zero_ref)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
561
        emit(state, state->zero_ref_sample, strm->bits_per_sample);
562

563
564
565
566
567
568
    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);
569

570
571
572
    state->zero_blocks = 0;
    return m_flush_block(strm);
}
573

574
static int m_select_code_option(struct aec_stream *strm)
575
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
576
    /**
577
578
       Decide which code option to use.
    */
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
579

580
581
    struct internal_state *state = strm->state;

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
582
    uint32_t split_len;
583
584
585
586
    if (state->id_len > 1)
        split_len = assess_splitting_option(strm);
    else
        split_len = UINT32_MAX;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
587
    uint32_t se_len = assess_se_option(strm);
588

589
    if (split_len < state->uncomp_len) {
590
591
592
593
594
        if (split_len < se_len)
            return m_encode_splitting(strm);
        else
            return m_encode_se(strm);
    } else {
595
        if (state->uncomp_len <= se_len)
596
597
598
599
600
601
602
603
604
605
606
607
608
            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
609
    */
610

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
611
    struct internal_state *state = strm->state;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
612
    uint32_t *p = state->block;
613

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
614
    size_t i;
615
    for (i = 0; i < strm->block_size; i++)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
616
617
        if (p[i] != 0)
            break;
618

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
619
    if (i < strm->block_size) {
620
621
622
        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
623
             * flagged and handled later.
624
             */
625
            state->block_nonzero = 1;
626
627
628
629
630
631
632
633
634
            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;
635
            state->zero_ref_sample = state->ref_sample;
636
        }
637
        if (state->blocks_avail == 0 || state->blocks_dispensed % 64 == 0) {
638
639
            if (state->zero_blocks > 4)
                state->zero_blocks = ROS;
640

641
642
643
            state->mode = m_encode_zero;
            return M_CONTINUE;
        }
644
645
646
        state->mode = m_get_block;
        return M_CONTINUE;
    }
647
}
648

649
650
651
652
653
654
655
656
657
658
659
660
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 {
661
        if (strm->avail_in >= state->bytes_per_sample) {
662
663
664
665
            state->data_raw[state->i] = state->get_sample(strm);
        } else {
            if (state->flush == AEC_FLUSH) {
                if (state->i > 0) {
666
667
668
                    state->blocks_avail = state->i / strm->block_size - 1;
                    if (state->i % strm->block_size)
                        state->blocks_avail++;
669
670
671
672
                    do
                        state->data_raw[state->i] =
                            state->data_raw[state->i - 1];
                    while(++state->i < strm->rsi * strm->block_size);
673
                } else {
674
675
                    /* Finish encoding by padding the last byte with
                     * zero bits. */
676
                    emit(state, 0, state->bits);
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
677
                    if (strm->avail_out > 0) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
678
                        if (!state->direct_out)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
679
680
                            *strm->next_out++ = *state->cds;
                        strm->avail_out--;
681
                        state->flushed = 1;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
682
                    }
683
684
685
686
687
688
689
690
                    return M_EXIT;
                }
            } else {
                return M_EXIT;
            }
        }
    } while (++state->i < strm->rsi * strm->block_size);

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
691
    if (strm->flags & AEC_DATA_PREPROCESS)
692
693
694
        state->preprocess(strm);

    return m_check_zero_block(strm);
695
696
}

697
static int m_get_block(struct aec_stream *strm)
698
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
699
    /**
700
701
702
703
       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
704
    */
705

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
706
    struct internal_state *state = strm->state;
707

708
709
710
711
712
713
    init_output(strm);

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

716
    if (state->blocks_avail == 0) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
717
        state->blocks_avail = strm->rsi - 1;
718
        state->block = state->data_pp;
719
        state->blocks_dispensed = 1;
720

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
721
        if (strm->avail_in >= state->rsi_len) {
722
            state->get_rsi(strm);
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
723
            if (strm->flags & AEC_DATA_PREPROCESS)
724
                state->preprocess(strm);
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
725

726
727
728
729
730
731
            return m_check_zero_block(strm);
        } else {
            state->i = 0;
            state->mode = m_get_rsi_resumable;
        }
    } else {
732
733
734
735
        if (state->ref) {
            state->ref = 0;
            state->uncomp_len = strm->block_size * strm->bits_per_sample;
        }
736
        state->block += strm->block_size;
737
        state->blocks_dispensed++;
738
739
        state->blocks_avail--;
        return m_check_zero_block(strm);
740
741
742
743
    }
    return M_CONTINUE;
}

744
745
746
747
748
749
750
751
752
753
754
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);
}

755
756
757
758
759
/*
 *
 * API functions
 *
 */
760

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
761
int aec_encode_init(struct aec_stream *strm)
762
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
763
    struct internal_state *state;
764

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
765
    if (strm->bits_per_sample > 32 || strm->bits_per_sample == 0)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
766
        return AEC_CONF_ERROR;
767

768
769
770
771
772
773
774
775
776
777
778
779
    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;
    }
780
781

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

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
784
    state = malloc(sizeof(struct internal_state));
785
    if (state == NULL)
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
786
        return AEC_MEM_ERROR;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
787
788

    memset(state, 0, sizeof(struct internal_state));
789
    strm->state = state;
790
    state->uncomp_len = strm->block_size * strm->bits_per_sample;
791

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

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

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

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

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
850
    if (strm->flags & AEC_DATA_SIGNED) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
851
        state->xmax = UINT32_MAX >> (32 - strm->bits_per_sample + 1);
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
852
        state->xmin = ~state->xmax;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
853
        state->preprocess = preprocess_signed;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
854
    } else {
855
        state->xmin = 0;
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
856
        state->xmax = UINT32_MAX >> (32 - strm->bits_per_sample);
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
857
        state->preprocess = preprocess_unsigned;
858
859
    }

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

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
862
863
864
    state->data_pp = malloc(strm->rsi
                            * strm->block_size
                            * sizeof(uint32_t));
865
866
    if (state->data_pp == NULL) {
        cleanup(strm);
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
867
        return AEC_MEM_ERROR;
868
    }
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
        if (state->data_raw == NULL) {
            cleanup(strm);
876
            return AEC_MEM_ERROR;
877
        }
878
879
880
881
    } else {
        state->data_raw = state->data_pp;
    }

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

884
    state->ref = 0;
885
886
    strm->total_in = 0;
    strm->total_out = 0;
887
    state->flushed = 0;
888

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
889
890
891
    state->cds = state->cds_buf;
    *state->cds = 0;
    state->bits = 8;
892
893
    state->mode = m_get_block;

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
894
    return AEC_OK;
895
896
}

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

905
    state->flush = flush;
906
907
    strm->total_in += strm->avail_in;
    strm->total_out += strm->avail_out;
908
909
910

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

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
911
    if (state->direct_out) {
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
912
        int n = (int)(state->cds - strm->next_out);
913
914
915
        strm->next_out += n;
        strm->avail_out -= n;

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

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
925
int aec_encode_end(struct aec_stream *strm)
926
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
927
    struct internal_state *state = strm->state;
928

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
929
    int status = AEC_OK;
930
931
932
933
    if (state->flush == AEC_FLUSH && state->flushed == 0)
        status = AEC_STREAM_ERROR;
    cleanup(strm);
    return status;
934
}
935

Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
936
int aec_buffer_encode(struct aec_stream *strm)
937
{
Mathis Rosenhauer's avatar
Mathis Rosenhauer committed
938
    int status = aec_encode_init(strm);
939
940
941
    if (status != AEC_OK)
        return status;
    status = aec_encode(strm, AEC_FLUSH);
942
943
944
945
946
    if (status != AEC_OK) {
        cleanup(strm);
        return status;
    }
    return aec_encode_end(strm);
947
}