587c91991361d3a027f648f37afc3a093c8d9f2b
[platform/upstream/libaec.git] / src / encode.c
1 /**
2  * @file encode.c
3  *
4  * @author Mathis Rosenhauer, Deutsches Klimarechenzentrum
5  * @author Moritz Hanke, Deutsches Klimarechenzentrum
6  * @author Joerg Behrens, Deutsches Klimarechenzentrum
7  * @author Luis Kornblueh, Max-Planck-Institut fuer Meteorologie
8  *
9  * @section LICENSE
10  * Copyright 2012
11  *
12  * Mathis Rosenhauer,                 Luis Kornblueh
13  * Moritz Hanke,
14  * Joerg Behrens
15  *
16  * Deutsches Klimarechenzentrum GmbH  Max-Planck-Institut fuer Meteorologie
17  * Bundesstr. 45a                     Bundesstr. 53
18  * 20146 Hamburg                      20146 Hamburg
19  * Germany                            Germany
20  *
21  * All rights reserved.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  *
27  * 1. Redistributions of source code must retain the above copyright
28  *    notice, this list of conditions and the following disclaimer.
29  * 2. Redistributions in binary form must reproduce the above
30  *    copyright notice, this list of conditions and the following
31  *    disclaimer in the documentation and/or other materials provided
32  *    with the distribution.
33  *
34  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
35  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
36  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
37  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
38  * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
39  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
40  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
41  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
42  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
43  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
44  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
45  * OF THE POSSIBILITY OF SUCH DAMAGE.
46  *
47  * @section DESCRIPTION
48  *
49  * Adaptive Entropy Encoder
50  * Based on CCSDS documents 121.0-B-2 and 120.0-G-2
51  *
52  */
53
54 #include <config.h>
55
56 #if HAVE_STDINT_H
57 # include <stdint.h>
58 #endif
59
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <unistd.h>
63 #include <string.h>
64
65 #include "libaec.h"
66 #include "encode.h"
67 #include "encode_accessors.h"
68
69 /* Marker for Remainder Of Segment condition in zero block encoding */
70 #define ROS -1
71
72 static int m_get_block(struct aec_stream *strm);
73
74 static inline void emit(struct internal_state *state,
75                         uint32_t data, int bits)
76 {
77     /**
78        Emit sequence of bits.
79      */
80
81     if (bits <= state->bits) {
82         state->bits -= bits;
83         *state->cds += data << state->bits;
84     } else {
85         bits -= state->bits;
86         *state->cds++ += (uint64_t)data >> bits;
87
88         while (bits & ~7) {
89             bits -= 8;
90             *state->cds++ = data >> bits;
91         }
92
93         state->bits = 8 - bits;
94         *state->cds = data << state->bits;
95     }
96 }
97
98 static inline void emitfs(struct internal_state *state, int fs)
99 {
100     /**
101        Emits a fundamental sequence.
102
103        fs zero bits followed by one 1 bit.
104      */
105
106     for(;;) {
107         if (fs < state->bits) {
108             state->bits -= fs + 1;
109             *state->cds += 1U << state->bits;
110             break;
111         } else {
112             fs -= state->bits;
113             *++state->cds = 0;
114             state->bits = 8;
115         }
116     }
117 }
118
119 static inline void copy64(uint8_t *dst, uint64_t src)
120 {
121     dst[0] = src >> 56;
122     dst[1] = src >> 48;
123     dst[2] = src >> 40;
124     dst[3] = src >> 32;
125     dst[4] = src >> 24;
126     dst[5] = src >> 16;
127     dst[6] = src >> 8;
128     dst[7] = src;
129 }
130
131 static inline void emitblock_fs(struct aec_stream *strm, int k, int ref)
132 {
133     int i;
134     int used; /* used bits in 64 bit accumulator */
135     uint64_t acc; /* accumulator */
136     struct internal_state *state = strm->state;
137
138     acc = (uint64_t)*state->cds << 56;
139     used = 7 - state->bits;
140
141     for (i = ref; i < strm->block_size; i++) {
142         used += (state->block[i] >> k) + 1;
143         if (used > 63) {
144             copy64(state->cds, acc);
145             state->cds += 8;
146             acc = 0;
147             used &= 0x3f;
148         }
149         acc |= 1ULL << (63 - used);
150     }
151
152     copy64(state->cds, acc);
153     state->cds += used >> 3;
154     state->bits = 7 - (used & 7);
155 }
156
157 static inline void emitblock(struct aec_stream *strm, int k, int ref)
158 {
159     /**
160        Emit the k LSB of a whole block of input data.
161     */
162
163     uint64_t a;
164     struct internal_state *state = strm->state;
165     uint32_t *in = state->block + ref;
166     uint32_t *in_end = state->block + strm->block_size;
167     uint64_t mask = (1ULL << k) - 1;
168     uint8_t *o = state->cds;
169     int p = state->bits;
170
171     a = *o;
172
173     while(in < in_end) {
174         a <<= 56;
175         p = (p % 8) + 56;
176
177         while (p > k && in < in_end) {
178             p -= k;
179             a += ((uint64_t)(*in++) & mask) << p;
180         }
181
182         switch (p & ~ 7) {
183         case 0:
184             o[0] = a >> 56;
185             o[1] = a >> 48;
186             o[2] = a >> 40;
187             o[3] = a >> 32;
188             o[4] = a >> 24;
189             o[5] = a >> 16;
190             o[6] = a >> 8;
191             o += 7;
192             break;
193         case 8:
194             o[0] = a >> 56;
195             o[1] = a >> 48;
196             o[2] = a >> 40;
197             o[3] = a >> 32;
198             o[4] = a >> 24;
199             o[5] = a >> 16;
200             a >>= 8;
201             o += 6;
202             break;
203         case 16:
204             o[0] = a >> 56;
205             o[1] = a >> 48;
206             o[2] = a >> 40;
207             o[3] = a >> 32;
208             o[4] = a >> 24;
209             a >>= 16;
210             o += 5;
211             break;
212         case 24:
213             o[0] = a >> 56;
214             o[1] = a >> 48;
215             o[2] = a >> 40;
216             o[3] = a >> 32;
217             a >>= 24;
218             o += 4;
219             break;
220         case 32:
221             o[0] = a >> 56;
222             o[1] = a >> 48;
223             o[2] = a >> 40;
224             a >>= 32;
225             o += 3;
226             break;
227         case 40:
228             o[0] = a >> 56;
229             o[1] = a >> 48;
230             a >>= 40;
231             o += 2;
232             break;
233         case 48:
234             *o++ = a >> 56;
235             a >>= 48;
236             break;
237         default:
238             a >>= 56;
239             break;
240         }
241     }
242
243     *o = a;
244     state->cds = o;
245     state->bits = p % 8;
246 }
247
248 static void preprocess_unsigned(struct aec_stream *strm)
249 {
250     /**
251        Preprocess RSI of unsigned samples.
252
253        Combining preprocessing and converting to uint32_t in one loop
254        is slower due to the data dependance on x_i-1.
255     */
256
257     uint32_t D;
258     struct internal_state *state = strm->state;
259     const uint32_t *x = state->data_raw;
260     uint32_t *d = state->data_pp;
261     uint32_t xmax = state->xmax;
262     uint32_t rsi = strm->rsi * strm->block_size - 1;
263
264     *d++ = x[0];
265     while (rsi--) {
266         if (x[1] >= x[0]) {
267             D = x[1] - x[0];
268             if (D <= x[0])
269                 *d = 2 * D;
270             else
271                 *d = x[1];
272         } else {
273             D = x[0] - x[1];
274             if (D <= xmax - x[0])
275                 *d = 2 * D - 1;
276             else
277                 *d = xmax - x[1];
278         }
279         d++;
280         x++;
281     }
282     state->ref = 1;
283     state->uncomp_len = (strm->block_size - 1) * strm->bits_per_sample;
284 }
285
286 static void preprocess_signed(struct aec_stream *strm)
287 {
288     /**
289        Preprocess RSI of signed samples.
290     */
291
292     int64_t D;
293     struct internal_state *state = strm->state;
294     uint32_t *d = state->data_pp;
295     int32_t *x = (int32_t *)state->data_raw;
296     uint64_t m = 1ULL << (strm->bits_per_sample - 1);
297     int64_t xmax = state->xmax;
298     int64_t xmin = state->xmin;
299     uint32_t rsi = strm->rsi * strm->block_size - 1;
300
301     *d++ = (uint32_t)x[0];
302     x[0] = (x[0] ^ m) - m;
303
304     while (rsi--) {
305         x[1] = (x[1] ^ m) - m;
306         if (x[1] < x[0]) {
307             D = (int64_t)x[0] - x[1];
308             if (D <= xmax - x[0])
309                 *d = 2 * D - 1;
310             else
311                 *d = xmax - x[1];
312         } else {
313             D = (int64_t)x[1] - x[0];
314             if (D <= x[0] - xmin)
315                 *d = 2 * D;
316             else
317                 *d = x[1] - xmin;
318         }
319         x++;
320         d++;
321     }
322     state->ref = 1;
323     state->uncomp_len = (strm->block_size - 1) * strm->bits_per_sample;
324 }
325
326 static uint64_t block_fs(struct aec_stream *strm, int k)
327 {
328     /**
329        Sum FS of all samples in block for given splitting position.
330     */
331
332     int i;
333     uint64_t fs = 0;
334     struct internal_state *state = strm->state;
335
336     for (i = 0; i < strm->block_size; i += 8)
337         fs +=
338             (uint64_t)(state->block[i + 0] >> k)
339             + (uint64_t)(state->block[i + 1] >> k)
340             + (uint64_t)(state->block[i + 2] >> k)
341             + (uint64_t)(state->block[i + 3] >> k)
342             + (uint64_t)(state->block[i + 4] >> k)
343             + (uint64_t)(state->block[i + 5] >> k)
344             + (uint64_t)(state->block[i + 6] >> k)
345             + (uint64_t)(state->block[i + 7] >> k);
346
347     if (state->ref)
348         fs -= (uint64_t)(state->block[0] >> k);
349
350     return fs;
351 }
352
353 static uint32_t assess_splitting_option(struct aec_stream *strm)
354 {
355     /**
356        Length of CDS encoded with splitting option and optimal k.
357
358        In Rice coding each sample in a block of samples is split at
359        the same position into k LSB and bits_per_sample - k MSB. The
360        LSB part is left binary and the MSB part is coded as a
361        fundamental sequence a.k.a. unary (see CCSDS 121.0-B-2). The
362        function of the length of the Coded Data Set (CDS) depending on
363        k has exactly one minimum (see A. Kiely, IPN Progress Report
364        42-159).
365
366        To find that minimum with only a few costly evaluations of the
367        CDS length, we start with the k of the previous CDS. K is
368        increased and the CDS length evaluated. If the CDS length gets
369        smaller, then we are moving towards the minimum. If the length
370        increases, then the minimum will be found with smaller k.
371
372        For increasing k we know that we will gain block_size bits in
373        length through the larger binary part. If the FS lenth is less
374        than the block size then a reduced FS part can't compensate the
375        larger binary part. So we know that the CDS for k+1 will be
376        larger than for k without actually computing the length. An
377        analogue check can be done for decreasing k.
378      */
379
380     int k;
381     int k_min;
382     int this_bs; /* Block size of current block */
383     int no_turn; /* 1 if we shouldn't reverse */
384     int dir; /* Direction, 1 means increasing k, 0 decreasing k */
385     uint64_t len; /* CDS length for current k */
386     uint64_t len_min; /* CDS length minimum so far */
387     uint64_t fs_len; /* Length of FS part (not including 1s) */
388
389     struct internal_state *state = strm->state;
390
391     this_bs = strm->block_size - state->ref;
392     len_min = UINT64_MAX;
393     k = k_min = state->k;
394     no_turn = k == 0;
395     dir = 1;
396
397     for (;;) {
398         fs_len = block_fs(strm, k);
399         len = fs_len + this_bs * (k + 1);
400
401         if (len < len_min) {
402             if (len_min < UINT64_MAX)
403                 no_turn = 1;
404
405             len_min = len;
406             k_min = k;
407
408             if (dir) {
409                 if (fs_len < this_bs || k >= state->kmax) {
410                     if (no_turn)
411                         break;
412                     k = state->k - 1;
413                     dir = 0;
414                     no_turn = 1;
415                 } else {
416                     k++;
417                 }
418             } else {
419                 if (fs_len >= this_bs || k == 0)
420                     break;
421                 k--;
422             }
423         } else {
424             if (no_turn)
425                 break;
426             k = state->k - 1;
427             dir = 0;
428             no_turn = 1;
429         }
430     }
431     state->k = k_min;
432
433     return len_min;
434 }
435
436 static uint32_t assess_se_option(struct aec_stream *strm)
437 {
438     /**
439        Length of CDS encoded with Second Extension option.
440
441        If length is above limit just return UINT32_MAX.
442     */
443
444     int i;
445     uint64_t d;
446     uint32_t len;
447     struct internal_state *state = strm->state;
448
449     len = 1;
450
451     for (i = 0; i < strm->block_size; i+= 2) {
452         d = (uint64_t)state->block[i]
453             + (uint64_t)state->block[i + 1];
454         /* we have to worry about overflow here */
455         if (d > state->uncomp_len) {
456             len = UINT32_MAX;
457             break;
458         } else {
459             len += d * (d + 1) / 2 + state->block[i + 1];
460         }
461     }
462     return len;
463 }
464
465 static void init_output(struct aec_stream *strm)
466 {
467     /**
468        Direct output to next_out if next_out can hold a Coded Data
469        Set, use internal buffer otherwise.
470     */
471
472     struct internal_state *state = strm->state;
473
474     if (strm->avail_out > state->cds_len) {
475         if (!state->direct_out) {
476             state->direct_out = 1;
477             *strm->next_out = *state->cds;
478             state->cds = strm->next_out;
479         }
480     } else {
481         if (state->zero_blocks == 0 || state->direct_out) {
482             /* copy leftover from last block */
483             *state->cds_buf = *state->cds;
484             state->cds = state->cds_buf;
485         }
486         state->direct_out = 0;
487     }
488 }
489
490 /*
491  *
492  * FSM functions
493  *
494  */
495
496 static int m_flush_block_resumable(struct aec_stream *strm)
497 {
498     /**
499        Slow and restartable flushing
500     */
501     struct internal_state *state = strm->state;
502
503     int n = MIN(state->cds - state->cds_buf - state->i, strm->avail_out);
504     memcpy(strm->next_out, state->cds_buf + state->i, n);
505     strm->next_out += n;
506     strm->avail_out -= n;
507     state->i += n;
508
509     if (strm->avail_out == 0) {
510         return M_EXIT;
511     } else {
512         state->mode = m_get_block;
513         return M_CONTINUE;
514     }
515 }
516
517 static int m_flush_block(struct aec_stream *strm)
518 {
519     /**
520        Flush block in direct_out mode by updating counters.
521
522        Fall back to slow flushing if in buffered mode.
523     */
524     int n;
525     struct internal_state *state = strm->state;
526
527     if (state->direct_out) {
528         n = state->cds - strm->next_out;
529         strm->next_out += n;
530         strm->avail_out -= n;
531         state->mode = m_get_block;
532         return M_CONTINUE;
533     }
534
535     state->i = 0;
536     state->mode = m_flush_block_resumable;
537     return M_CONTINUE;
538 }
539
540 static int m_encode_splitting(struct aec_stream *strm)
541 {
542     struct internal_state *state = strm->state;
543     int k = state->k;
544
545     emit(state, k + 1, state->id_len);
546
547     if (state->ref)
548         emit(state, state->block[0], strm->bits_per_sample);
549
550     emitblock_fs(strm, k, state->ref);
551     if (k)
552         emitblock(strm, k, state->ref);
553
554     return m_flush_block(strm);
555 }
556
557 static int m_encode_uncomp(struct aec_stream *strm)
558 {
559     struct internal_state *state = strm->state;
560
561     emit(state, (1U << state->id_len) - 1, state->id_len);
562     emitblock(strm, strm->bits_per_sample, 0);
563
564     return m_flush_block(strm);
565 }
566
567 static int m_encode_se(struct aec_stream *strm)
568 {
569     int i;
570     uint32_t d;
571     struct internal_state *state = strm->state;
572
573     emit(state, 1, state->id_len + 1);
574     if (state->ref)
575         emit(state, state->block[0], strm->bits_per_sample);
576
577     for (i = 0; i < strm->block_size; i+= 2) {
578         d = state->block[i] + state->block[i + 1];
579         emitfs(state, d * (d + 1) / 2 + state->block[i + 1]);
580     }
581
582     return m_flush_block(strm);
583 }
584
585 static int m_encode_zero(struct aec_stream *strm)
586 {
587     struct internal_state *state = strm->state;
588
589     emit(state, 0, state->id_len + 1);
590
591     if (state->zero_ref)
592         emit(state, state->zero_ref_sample, strm->bits_per_sample);
593
594     if (state->zero_blocks == ROS)
595         emitfs(state, 4);
596     else if (state->zero_blocks >= 5)
597         emitfs(state, state->zero_blocks);
598     else
599         emitfs(state, state->zero_blocks - 1);
600
601     state->zero_blocks = 0;
602     return m_flush_block(strm);
603 }
604
605 static int m_select_code_option(struct aec_stream *strm)
606 {
607     /**
608        Decide which code option to use.
609     */
610
611     uint32_t split_len;
612     uint32_t se_len;
613     struct internal_state *state = strm->state;
614
615     split_len = assess_splitting_option(strm);
616     se_len = assess_se_option(strm);
617
618     if (split_len < state->uncomp_len) {
619         if (split_len < se_len)
620             return m_encode_splitting(strm);
621         else
622             return m_encode_se(strm);
623     } else {
624         if (state->uncomp_len <= se_len)
625             return m_encode_uncomp(strm);
626         else
627             return m_encode_se(strm);
628     }
629 }
630
631 static int m_check_zero_block(struct aec_stream *strm)
632 {
633     /**
634        Check if input block is all zero.
635
636        Aggregate consecutive zero blocks until we find !0 or reach the
637        end of a segment or RSI.
638     */
639
640     struct internal_state *state = strm->state;
641     uint32_t *p = state->block + state->ref;
642     uint32_t *end = state->block + strm->block_size;
643
644     while(p < end && *p == 0)
645         p++;
646
647     if (p < end) {
648         if (state->zero_blocks) {
649             /* The current block isn't zero but we have to emit a
650              * previous zero block first. The current block will be
651              * flagged and handled later.
652              */
653             state->block_nonzero = 1;
654             state->mode = m_encode_zero;
655             return M_CONTINUE;
656         }
657         state->mode = m_select_code_option;
658         return M_CONTINUE;
659     } else {
660         state->zero_blocks++;
661         if (state->zero_blocks == 1) {
662             state->zero_ref = state->ref;
663             state->zero_ref_sample = state->block[0];
664         }
665         if (state->blocks_avail == 0
666             || (strm->rsi - state->blocks_avail) % 64 == 0) {
667             if (state->zero_blocks > 4)
668                 state->zero_blocks = ROS;
669             state->mode = m_encode_zero;
670             return M_CONTINUE;
671         }
672         state->mode = m_get_block;
673         return M_CONTINUE;
674     }
675 }
676
677 static int m_get_rsi_resumable(struct aec_stream *strm)
678 {
679     /**
680        Get RSI while input buffer is short.
681
682        Let user provide more input. Once we got all input pad buffer
683        to full RSI.
684     */
685
686     struct internal_state *state = strm->state;
687
688     do {
689         if (strm->avail_in > 0) {
690             state->data_raw[state->i] = state->get_sample(strm);
691         } else {
692             if (state->flush == AEC_FLUSH) {
693                 if (state->i > 0) {
694                     do
695                         state->data_raw[state->i] =
696                             state->data_raw[state->i - 1];
697                     while(++state->i < strm->rsi * strm->block_size);
698                 } else {
699                     emit(state, 0, state->bits);
700                     if (strm->avail_out > 0) {
701                         if (!state->direct_out)
702                             *strm->next_out++ = *state->cds;
703                         strm->avail_out--;
704                     }
705                     return M_EXIT;
706                 }
707             } else {
708                 return M_EXIT;
709             }
710         }
711     } while (++state->i < strm->rsi * strm->block_size);
712
713     if (strm->flags & AEC_DATA_PREPROCESS)
714         state->preprocess(strm);
715
716     return m_check_zero_block(strm);
717 }
718
719 static int m_get_block(struct aec_stream *strm)
720 {
721     /**
722        Provide the next block of preprocessed input data.
723
724        Pull in a whole Reference Sample Interval (RSI) of data if
725        block buffer is empty.
726     */
727
728     struct internal_state *state = strm->state;
729
730     init_output(strm);
731
732     if (state->block_nonzero) {
733         state->block_nonzero = 0;
734         state->mode = m_select_code_option;
735         return M_CONTINUE;
736     }
737
738     if (state->blocks_avail == 0) {
739         state->blocks_avail = strm->rsi - 1;
740         state->block = state->data_pp;
741
742         if (strm->avail_in >= state->rsi_len) {
743             state->get_rsi(strm);
744             if (strm->flags & AEC_DATA_PREPROCESS)
745                 state->preprocess(strm);
746
747             return m_check_zero_block(strm);
748         } else {
749             state->i = 0;
750             state->mode = m_get_rsi_resumable;
751         }
752     } else {
753         if (state->ref) {
754             state->ref = 0;
755             state->uncomp_len = strm->block_size * strm->bits_per_sample;
756         }
757         state->block += strm->block_size;
758         state->blocks_avail--;
759         return m_check_zero_block(strm);
760     }
761     return M_CONTINUE;
762 }
763
764 /*
765  *
766  * API functions
767  *
768  */
769
770 int aec_encode_init(struct aec_stream *strm)
771 {
772     struct internal_state *state;
773
774     if (strm->bits_per_sample > 32 || strm->bits_per_sample == 0)
775         return AEC_CONF_ERROR;
776
777     if (strm->block_size != 8
778         && strm->block_size != 16
779         && strm->block_size != 32
780         && strm->block_size != 64)
781         return AEC_CONF_ERROR;
782
783     if (strm->rsi > 4096)
784         return AEC_CONF_ERROR;
785
786     state = malloc(sizeof(struct internal_state));
787     if (state == NULL)
788         return AEC_MEM_ERROR;
789
790     memset(state, 0, sizeof(struct internal_state));
791     strm->state = state;
792
793     if (strm->bits_per_sample > 16) {
794         /* 24/32 input bit settings */
795         state->id_len = 5;
796
797         if (strm->bits_per_sample <= 24
798             && strm->flags & AEC_DATA_3BYTE) {
799             state->rsi_len = 3;
800             if (strm->flags & AEC_DATA_MSB) {
801                 state->get_sample = aec_get_msb_24;
802                 state->get_rsi = aec_get_rsi_msb_24;
803             } else {
804                 state->get_sample = aec_get_lsb_24;
805                 state->get_rsi = aec_get_rsi_lsb_24;
806             }
807         } else {
808             state->rsi_len = 4;
809             if (strm->flags & AEC_DATA_MSB) {
810                 state->get_sample = aec_get_msb_32;
811                 state->get_rsi = aec_get_rsi_msb_32;
812             } else {
813                 state->get_sample = aec_get_lsb_32;
814                 state->get_rsi = aec_get_rsi_lsb_32;
815             }
816         }
817     }
818     else if (strm->bits_per_sample > 8) {
819         /* 16 bit settings */
820         state->id_len = 4;
821         state->rsi_len = 2;
822
823         if (strm->flags & AEC_DATA_MSB) {
824             state->get_sample = aec_get_msb_16;
825             state->get_rsi = aec_get_rsi_msb_16;
826         } else {
827             state->get_sample = aec_get_lsb_16;
828             state->get_rsi = aec_get_rsi_lsb_16;
829         }
830     } else {
831         /* 8 bit settings */
832         state->id_len = 3;
833         state->rsi_len = 1;
834
835         state->get_sample = aec_get_8;
836         state->get_rsi = aec_get_rsi_8;
837     }
838     state->rsi_len *= strm->rsi * strm->block_size;
839
840     if (strm->flags & AEC_DATA_SIGNED) {
841         state->xmin = -(1ULL << (strm->bits_per_sample - 1));
842         state->xmax = (1ULL << (strm->bits_per_sample - 1)) - 1;
843         state->preprocess = preprocess_signed;
844     } else {
845         state->xmin = 0;
846         state->xmax = (1ULL << strm->bits_per_sample) - 1;
847         state->preprocess = preprocess_unsigned;
848     }
849
850     state->kmax = (1U << state->id_len) - 3;
851
852     state->data_pp = malloc(strm->rsi
853                             * strm->block_size
854                             * sizeof(uint32_t));
855     if (state->data_pp == NULL)
856         return AEC_MEM_ERROR;
857
858     if (strm->flags & AEC_DATA_PREPROCESS) {
859         state->data_raw = malloc(strm->rsi
860                                  * strm->block_size
861                                  * sizeof(uint32_t));
862         if (state->data_raw == NULL)
863             return AEC_MEM_ERROR;
864     } else {
865         state->data_raw = state->data_pp;
866     }
867
868     state->block = state->data_pp;
869
870     /* Largest possible CDS according to specs */
871     state->cds_len = (5 + 64 * 32) / 8 + 3;
872     state->cds_buf = malloc(state->cds_len);
873     if (state->cds_buf == NULL)
874         return AEC_MEM_ERROR;
875
876     strm->total_in = 0;
877     strm->total_out = 0;
878
879     state->cds = state->cds_buf;
880     *state->cds = 0;
881     state->bits = 8;
882     state->mode = m_get_block;
883
884     return AEC_OK;
885 }
886
887 int aec_encode(struct aec_stream *strm, int flush)
888 {
889     /**
890        Finite-state machine implementation of the adaptive entropy
891        encoder.
892     */
893     int n;
894     struct internal_state *state = strm->state;
895
896     state->flush = flush;
897     strm->total_in += strm->avail_in;
898     strm->total_out += strm->avail_out;
899
900     while (state->mode(strm) == M_CONTINUE);
901
902     if (state->direct_out) {
903         n = state->cds - strm->next_out;
904         strm->next_out += n;
905         strm->avail_out -= n;
906
907         *state->cds_buf = *state->cds;
908         state->cds = state->cds_buf;
909         state->direct_out = 0;
910     }
911     strm->total_in -= strm->avail_in;
912     strm->total_out -= strm->avail_out;
913     return AEC_OK;
914 }
915
916 int aec_encode_end(struct aec_stream *strm)
917 {
918     struct internal_state *state = strm->state;
919
920     if (strm->flags & AEC_DATA_PREPROCESS)
921         free(state->data_raw);
922     free(state->data_pp);
923     free(state->cds_buf);
924     free(state);
925     return AEC_OK;
926 }
927
928 int aec_buffer_encode(struct aec_stream *strm)
929 {
930     int status;
931
932     status = aec_encode_init(strm);
933     if (status != AEC_OK)
934         return status;
935     status = aec_encode(strm, AEC_FLUSH);
936     if (strm->avail_in > 0)
937         status = AEC_DATA_ERROR;
938
939     aec_encode_end(strm);
940     return status;
941 }