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