lib functions for simple buffer encoding/decoding
[platform/upstream/libaec.git] / src / encode.c
1 /**
2  * @file encode.c
3  * @author Mathis Rosenhauer, Deutsches Klimarechenzentrum
4  * @section DESCRIPTION
5  *
6  * Adaptive Entropy Encoder
7  * Based on CCSDS documents 121.0-B-2 and 120.0-G-2
8  *
9  */
10
11 #include <config.h>
12
13 #if HAVE_STDINT_H
14 # include <stdint.h>
15 #endif
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <unistd.h>
20 #include <string.h>
21
22 #include "libaec.h"
23 #include "encode.h"
24 #include "encode_accessors.h"
25
26 /* Marker for Remainder Of Segment condition in zero block encoding */
27 #define ROS -1
28
29 static int m_get_block(struct aec_stream *strm);
30 static int m_get_block_cautious(struct aec_stream *strm);
31 static int m_check_zero_block(struct aec_stream *strm);
32 static int m_select_code_option(struct aec_stream *strm);
33 static int m_flush_block(struct aec_stream *strm);
34 static int m_flush_block_cautious(struct aec_stream *strm);
35 static int m_encode_splitting(struct aec_stream *strm);
36 static int m_encode_uncomp(struct aec_stream *strm);
37 static int m_encode_se(struct aec_stream *strm);
38 static int m_encode_zero(struct aec_stream *strm);
39
40 static inline void emit(struct internal_state *state,
41                         uint32_t data, int bits)
42 {
43     /**
44        Emit sequence of bits.
45      */
46
47     if (bits <= state->bit_p) {
48         state->bit_p -= bits;
49         *state->cds_p += data << state->bit_p;
50     } else {
51         bits -= state->bit_p;
52         *state->cds_p++ += (uint64_t)data >> bits;
53
54         while (bits & ~7) {
55             bits -= 8;
56             *state->cds_p++ = data >> bits;
57         }
58
59         state->bit_p = 8 - bits;
60         *state->cds_p = data << state->bit_p;
61     }
62 }
63
64 static inline void emitfs(struct internal_state *state, int fs)
65 {
66     /**
67        Emits a fundamental sequence.
68
69        fs zero bits followed by one 1 bit.
70      */
71
72     for(;;) {
73         if (fs < state->bit_p) {
74             state->bit_p -= fs + 1;
75             *state->cds_p += 1 << state->bit_p;
76             break;
77         } else {
78             fs -= state->bit_p;
79             *++state->cds_p = 0;
80             state->bit_p = 8;
81         }
82     }
83 }
84
85 #define EMITBLOCK(ref)                                          \
86     static inline void emitblock_##ref(struct aec_stream *strm, \
87                                        int k)                   \
88     {                                                           \
89         int b;                                                  \
90         uint64_t a;                                             \
91         struct internal_state *state = strm->state;             \
92         uint32_t *in = state->block_p + ref;                    \
93         uint32_t *in_end = state->block_p + strm->block_size;   \
94         uint64_t mask = (1ULL << k) - 1;                        \
95         uint8_t *o = state->cds_p;                              \
96         int p = state->bit_p;                                   \
97                                                                 \
98         a = *o;                                                 \
99                                                                 \
100         while(in < in_end) {                                    \
101             a <<= 56;                                           \
102             p = (p % 8) + 56;                                   \
103                                                                 \
104             while (p > k && in < in_end) {                      \
105                 p -= k;                                         \
106                 a += ((uint64_t)(*in++) & mask) << p;           \
107             }                                                   \
108                                                                 \
109             for (b = 56; b > (p & ~7); b -= 8)                  \
110                 *o++ = a >> b;                                  \
111             a >>= b;                                            \
112         }                                                       \
113                                                                 \
114         *o = a;                                                 \
115         state->cds_p = o;                                       \
116         state->bit_p = p % 8;                                   \
117     }
118
119 EMITBLOCK(0);
120 EMITBLOCK(1);
121
122 static void preprocess_unsigned(struct aec_stream *strm)
123 {
124     int64_t d;
125     int64_t t;
126     uint32_t s;
127     struct internal_state *state = strm->state;
128     uint32_t *buf = state->block_buf;
129     int64_t prev = *buf++;
130     uint32_t xmax = state->xmax;
131     uint32_t rsi = strm->rsi * strm->block_size - 1;
132
133     while (rsi--) {
134         s = *buf < prev;
135         if (s) {
136             d = prev - *buf;
137             t = xmax - prev;
138         } else {
139             d = *buf - prev;
140             t = prev;
141         }
142
143         prev = *buf;
144         if (d <= t)
145             *buf = 2 * d - s;
146         else
147             *buf = t + d;
148         buf++;
149     }
150 }
151
152 static void preprocess_signed(struct aec_stream *strm)
153 {
154     int64_t d;
155     int64_t t;
156     int64_t v;
157     uint32_t s;
158     struct internal_state *state = strm->state;
159     uint32_t *buf = state->block_buf;
160     uint32_t m = 1ULL << (strm->bit_per_sample - 1);
161     int64_t prev = (((int64_t)*buf++) ^ m) - m;
162     int64_t xmax = state->xmax;
163     int64_t xmin = state->xmin;
164     uint32_t rsi = strm->rsi * strm->block_size - 1;
165
166     while (rsi--) {
167         v = (((int64_t)*buf) ^ m) - m;
168         s = v < prev;
169         if (s) {
170             d = prev - v;
171             t = xmax - prev;
172         } else {
173             d = v - prev;
174             t = prev - xmin;
175         }
176
177         prev = v;
178         if (d <= t)
179             *buf = 2 * d - s;
180         else
181             *buf = t + d;
182         buf++;
183     }
184 }
185
186 /*
187  *
188  * FSM functions
189  *
190  */
191
192 static int m_get_block(struct aec_stream *strm)
193 {
194     struct internal_state *state = strm->state;
195
196     if (strm->avail_out > state->cds_len) {
197         if (!state->direct_out) {
198             state->direct_out = 1;
199             *strm->next_out = *state->cds_p;
200             state->cds_p = strm->next_out;
201         }
202     } else {
203         if (state->zero_blocks == 0 || state->direct_out) {
204             /* copy leftover from last block */
205             *state->cds_buf = *state->cds_p;
206             state->cds_p = state->cds_buf;
207         }
208         state->direct_out = 0;
209     }
210
211     if (state->blocks_avail == 0) {
212         state->ref = 1;
213         state->block_p = state->block_buf;
214
215         if (strm->avail_in >= state->block_len * strm->rsi) {
216             state->get_rsi(strm);
217             state->blocks_avail = strm->rsi - 1;
218
219             if (strm->flags & AEC_DATA_PREPROCESS)
220                 state->preprocess(strm);
221
222             return m_check_zero_block(strm);
223         } else {
224             state->i = 0;
225             state->mode = m_get_block_cautious;
226         }
227     } else {
228         state->ref = 0;
229         state->block_p += strm->block_size;
230         state->blocks_avail--;
231         return m_check_zero_block(strm);
232     }
233     return M_CONTINUE;
234 }
235
236 static int m_get_block_cautious(struct aec_stream *strm)
237 {
238     int j;
239     struct internal_state *state = strm->state;
240
241     do {
242         if (strm->avail_in > 0) {
243             state->block_buf[state->i] = state->get_sample(strm);
244         } else {
245             if (state->flush == AEC_FLUSH) {
246                 if (state->i > 0) {
247                     for (j = state->i; j < strm->rsi * strm->block_size; j++)
248                         state->block_buf[j] = state->block_buf[state->i - 1];
249                     state->i = strm->rsi * strm->block_size;
250                 } else {
251                     if (state->zero_blocks) {
252                         state->mode = m_encode_zero;
253                         return M_CONTINUE;
254                     }
255
256                     emit(state, 0, state->bit_p);
257                     if (state->direct_out == 0)
258                         *strm->next_out++ = *state->cds_p;
259                     strm->avail_out--;
260                     strm->total_out++;
261
262                     return M_EXIT;
263                 }
264             } else {
265                 return M_EXIT;
266             }
267         }
268     } while (++state->i < strm->rsi * strm->block_size);
269
270     state->blocks_avail = strm->rsi - 1;
271     if (strm->flags & AEC_DATA_PREPROCESS)
272         state->preprocess(strm);
273
274     return m_check_zero_block(strm);
275 }
276
277 static int m_check_zero_block(struct aec_stream *strm)
278 {
279     struct internal_state *state = strm->state;
280     uint32_t *p = state->block_p + state->ref;
281     uint32_t *end = state->block_p + strm->block_size;
282
283     while(*p == 0 && p < end)
284         p++;
285
286     if (p < end) {
287         if (state->zero_blocks) {
288             /* The current block isn't zero but we have to emit a
289              * previous zero block first. The current block will be
290              * handled later.
291              */
292             state->block_p -= strm->block_size;
293             state->blocks_avail++;
294             state->mode = m_encode_zero;
295             return M_CONTINUE;
296         }
297         state->mode = m_select_code_option;
298         return M_CONTINUE;
299     } else {
300         state->zero_blocks++;
301         if (state->zero_blocks == 1) {
302             state->zero_ref = state->ref;
303             state->zero_ref_sample = state->block_p[0];
304         }
305         if ((strm->rsi - state->blocks_avail) % 64 == 0) {
306             if (state->zero_blocks > 4)
307                 state->zero_blocks = ROS;
308             state->mode = m_encode_zero;
309             return M_CONTINUE;
310         }
311         state->mode = m_get_block;
312         return M_CONTINUE;
313     }
314 }
315
316 static uint64_t block_fs(struct aec_stream *strm, int k)
317 {
318     int j;
319     uint64_t fs;
320     struct internal_state *state = strm->state;
321
322     fs = (uint64_t)(state->block_p[1] >> k)
323         + (uint64_t)(state->block_p[2] >> k)
324         + (uint64_t)(state->block_p[3] >> k)
325         + (uint64_t)(state->block_p[4] >> k)
326         + (uint64_t)(state->block_p[5] >> k)
327         + (uint64_t)(state->block_p[6] >> k)
328         + (uint64_t)(state->block_p[7] >> k);
329
330     if (strm->block_size > 8)
331         for (j = 1; j < strm->block_size / 8; j++)
332             fs +=
333                 (uint64_t)(state->block_p[j * 8 + 0] >> k)
334                 + (uint64_t)(state->block_p[j * 8 + 1] >> k)
335                 + (uint64_t)(state->block_p[j * 8 + 2] >> k)
336                 + (uint64_t)(state->block_p[j * 8 + 3] >> k)
337                 + (uint64_t)(state->block_p[j * 8 + 4] >> k)
338                 + (uint64_t)(state->block_p[j * 8 + 5] >> k)
339                 + (uint64_t)(state->block_p[j * 8 + 6] >> k)
340                 + (uint64_t)(state->block_p[j * 8 + 7] >> k);
341
342     if (state->ref == 0)
343         fs += (uint64_t)(state->block_p[0] >> k);
344
345     return fs;
346 }
347
348 static int count_splitting_option(struct aec_stream *strm)
349 {
350     /**
351        Find the best point for splitting samples in a block.
352
353        In Rice coding each sample in a block of samples is split at
354        the same position into k LSB and bit_per_sample - k MSB. The
355        LSB part is left binary and the MSB part is coded as a
356        fundamental sequence a.k.a. unary (see CCSDS 121.0-B-2). The
357        function of the length of the Coded Data Set (CDS) depending on
358        k has exactly one minimum (see A. Kiely, IPN Progress Report
359        42-159).
360
361        To find that minimum with only a few costly evaluations of the
362        CDS length, we start with the k of the previous CDS. K is
363        increased and the CDS length evaluated. If the CDS length gets
364        smaller, then we are moving towards the minimum. If the length
365        increases, then the minimum will be found with smaller k.
366
367        For increasing k we know that we will gain block_size bits in
368        length through the larger binary part. If the FS lenth is less
369        than the block size then a reduced FS part can't compensate the
370        larger binary part. So we know that the CDS for k+1 will be
371        larger than for k without actually computing the length. An
372        analogue check can be done for decreasing k.
373      */
374
375     int k, k_min;
376     int this_bs; /* Block size of current block */
377     int no_turn; /* 1 if we shouldn't reverse */
378     int dir; /* Direction, 1 means increasing k, 0 decreasing k */
379     uint64_t len; /* CDS length for current k */
380     uint64_t len_min; /* CDS length minimum so far */
381     uint64_t fs_len; /* Length of FS part (not including 1s) */
382
383     struct internal_state *state = strm->state;
384
385     this_bs = strm->block_size - state->ref;
386     len_min = UINT64_MAX;
387     k = k_min = state->k;
388     no_turn = (k == 0) ? 1 : 0;
389     dir = 1;
390
391     for (;;) {
392         fs_len = block_fs(strm, k);
393         len = fs_len + this_bs * (k + 1);
394
395         if (len < len_min) {
396             if (len_min < UINT64_MAX)
397                 no_turn = 1;
398
399             len_min = len;
400             k_min = k;
401
402             if (dir) {
403                 if (fs_len < this_bs || k >= state->kmax) {
404                     if (no_turn)
405                         break;
406                     k = state->k - 1;
407                     dir = 0;
408                     no_turn = 1;
409                 } else {
410                     k++;
411                 }
412             } else {
413                 if (fs_len >= this_bs || k == 0)
414                     break;
415                 k--;
416             }
417         } else {
418             if (no_turn)
419                 break;
420             k = state->k - 1;
421             dir = 0;
422             no_turn = 1;
423         }
424     }
425     state->k = k_min;
426
427     return len_min;
428 }
429
430 static int count_se_option(uint64_t limit, struct aec_stream *strm)
431 {
432     int i;
433     uint64_t d, len;
434     struct internal_state *state = strm->state;
435
436     len = 1;
437
438     for (i = 0; i < strm->block_size; i+= 2) {
439         d = (uint64_t)state->block_p[i]
440             + (uint64_t)state->block_p[i + 1];
441         /* we have to worry about overflow here */
442         if (d > limit) {
443             len = UINT64_MAX;
444             break;
445         } else {
446             len += d * (d + 1) / 2
447                 + (uint64_t)state->block_p[i + 1];
448         }
449     }
450     return len;
451 }
452
453 static int m_select_code_option(struct aec_stream *strm)
454 {
455     uint64_t uncomp_len, split_len, se_len;
456     struct internal_state *state = strm->state;
457
458     uncomp_len = (strm->block_size - state->ref)
459         * strm->bit_per_sample;
460     split_len = count_splitting_option(strm);
461     se_len = count_se_option(split_len, strm);
462
463     if (split_len < uncomp_len) {
464         if (split_len < se_len)
465             return m_encode_splitting(strm);
466         else
467             return m_encode_se(strm);
468     } else {
469         if (uncomp_len <= se_len)
470             return m_encode_uncomp(strm);
471         else
472             return m_encode_se(strm);
473     }
474 }
475
476 static int m_encode_splitting(struct aec_stream *strm)
477 {
478     int i;
479     struct internal_state *state = strm->state;
480     int k = state->k;
481
482     emit(state, k + 1, state->id_len);
483
484     if (state->ref)
485     {
486         emit(state, state->block_p[0], strm->bit_per_sample);
487         for (i = 1; i < strm->block_size; i++)
488             emitfs(state, state->block_p[i] >> k);
489         if (k) emitblock_1(strm, k);
490     }
491     else
492     {
493         for (i = 0; i < strm->block_size; i++)
494             emitfs(state, state->block_p[i] >> k);
495         if (k) emitblock_0(strm, k);
496     }
497
498     return m_flush_block(strm);
499 }
500
501 static int m_encode_uncomp(struct aec_stream *strm)
502 {
503     struct internal_state *state = strm->state;
504
505     emit(state, (1 << state->id_len) - 1, state->id_len);
506     emitblock_0(strm, strm->bit_per_sample);
507
508     return m_flush_block(strm);
509 }
510
511 static int m_encode_se(struct aec_stream *strm)
512 {
513     int i;
514     uint32_t d;
515     struct internal_state *state = strm->state;
516
517     emit(state, 1, state->id_len + 1);
518     if (state->ref)
519         emit(state, state->block_p[0], strm->bit_per_sample);
520
521     for (i = 0; i < strm->block_size; i+= 2) {
522         d = state->block_p[i] + state->block_p[i + 1];
523         emitfs(state, d * (d + 1) / 2 + state->block_p[i + 1]);
524     }
525
526     return m_flush_block(strm);
527 }
528
529 static int m_encode_zero(struct aec_stream *strm)
530 {
531     struct internal_state *state = strm->state;
532
533     emit(state, 0, state->id_len + 1);
534
535     if (state->zero_ref)
536         emit(state, state->zero_ref_sample, strm->bit_per_sample);
537
538     if (state->zero_blocks == ROS)
539         emitfs(state, 4);
540     else if (state->zero_blocks >= 5)
541         emitfs(state, state->zero_blocks);
542     else
543         emitfs(state, state->zero_blocks - 1);
544
545     state->zero_blocks = 0;
546     return m_flush_block(strm);
547 }
548
549 static int m_flush_block(struct aec_stream *strm)
550 {
551     /**
552        Flush block in direct_out mode by updating counters.
553
554        Fall back to slow flushing if in buffered mode.
555     */
556     int n;
557     struct internal_state *state = strm->state;
558
559     if (state->direct_out) {
560         n = state->cds_p - strm->next_out;
561         strm->next_out += n;
562         strm->avail_out -= n;
563         strm->total_out += n;
564         state->mode = m_get_block;
565         return M_CONTINUE;
566     }
567
568     state->i = 0;
569     state->mode = m_flush_block_cautious;
570     return M_CONTINUE;
571 }
572
573 static int m_flush_block_cautious(struct aec_stream *strm)
574 {
575     /**
576        Slow and restartable flushing
577     */
578     struct internal_state *state = strm->state;
579
580     while(state->cds_buf + state->i < state->cds_p) {
581         if (strm->avail_out == 0)
582             return M_EXIT;
583
584         *strm->next_out++ = state->cds_buf[state->i];
585         strm->avail_out--;
586         strm->total_out++;
587         state->i++;
588     }
589     state->mode = m_get_block;
590     return M_CONTINUE;
591 }
592
593 /*
594  *
595  * API functions
596  *
597  */
598
599 int aec_encode_init(struct aec_stream *strm)
600 {
601     struct internal_state *state;
602
603     if (strm->bit_per_sample > 32 || strm->bit_per_sample == 0)
604         return AEC_CONF_ERROR;
605
606     if (strm->block_size != 8
607         && strm->block_size != 16
608         && strm->block_size != 32
609         && strm->block_size != 64)
610         return AEC_CONF_ERROR;
611
612     if (strm->rsi > 4096)
613         return AEC_CONF_ERROR;
614
615     state = (struct internal_state *)malloc(sizeof(struct internal_state));
616     if (state == NULL)
617         return AEC_MEM_ERROR;
618
619     memset(state, 0, sizeof(struct internal_state));
620     strm->state = state;
621
622     if (strm->bit_per_sample > 16) {
623         /* 24/32 input bit settings */
624         state->id_len = 5;
625
626         if (strm->bit_per_sample <= 24
627             && strm->flags & AEC_DATA_3BYTE) {
628             state->block_len = 3 * strm->block_size;
629             if (strm->flags & AEC_DATA_MSB) {
630                 state->get_sample = get_msb_24;
631                 state->get_rsi = get_rsi_msb_24;
632             } else {
633                 state->get_sample = get_lsb_24;
634                 state->get_rsi = get_rsi_lsb_24;
635             }
636         } else {
637             state->block_len = 4 * strm->block_size;
638             if (strm->flags & AEC_DATA_MSB) {
639                 state->get_sample = get_msb_32;
640                 state->get_rsi = get_rsi_msb_32;
641             } else {
642                 state->get_sample = get_lsb_32;
643                 state->get_rsi = get_rsi_lsb_32;
644             }
645         }
646     }
647     else if (strm->bit_per_sample > 8) {
648         /* 16 bit settings */
649         state->id_len = 4;
650         state->block_len = 2 * strm->block_size;
651
652         if (strm->flags & AEC_DATA_MSB) {
653             state->get_sample = get_msb_16;
654             state->get_rsi = get_rsi_msb_16;
655         } else {
656             state->get_sample = get_lsb_16;
657             state->get_rsi = get_rsi_lsb_16;
658         }
659     } else {
660         /* 8 bit settings */
661         state->id_len = 3;
662         state->block_len = strm->block_size;
663
664         state->get_sample = get_8;
665         state->get_rsi = get_rsi_8;
666     }
667
668     if (strm->flags & AEC_DATA_SIGNED) {
669         state->xmin = -(1ULL << (strm->bit_per_sample - 1));
670         state->xmax = (1ULL << (strm->bit_per_sample - 1)) - 1;
671         state->preprocess = preprocess_signed;
672     } else {
673         state->xmin = 0;
674         state->xmax = (1ULL << strm->bit_per_sample) - 1;
675         state->preprocess = preprocess_unsigned;
676     }
677
678     state->kmax = (1U << state->id_len) - 3;
679
680     state->block_buf = (uint32_t *)malloc(strm->rsi
681                                          * strm->block_size
682                                          * sizeof(uint32_t));
683     if (state->block_buf == NULL)
684         return AEC_MEM_ERROR;
685
686     state->block_p = state->block_buf;
687
688     /* Largest possible CDS according to specs */
689     state->cds_len = (5 + 64 * 32) / 8 + 3;
690     state->cds_buf = (uint8_t *)malloc(state->cds_len);
691     if (state->cds_buf == NULL)
692         return AEC_MEM_ERROR;
693
694     strm->total_in = 0;
695     strm->total_out = 0;
696
697     state->cds_p = state->cds_buf;
698     *state->cds_p = 0;
699     state->bit_p = 8;
700     state->mode = m_get_block;
701
702     return AEC_OK;
703 }
704
705 int aec_encode(struct aec_stream *strm, int flush)
706 {
707     /**
708        Finite-state machine implementation of the adaptive entropy
709        encoder.
710     */
711     int n;
712     struct internal_state *state;
713     state = strm->state;
714     state->flush = flush;
715
716     while (state->mode(strm) == M_CONTINUE);
717
718     if (state->direct_out) {
719         n = state->cds_p - strm->next_out;
720         strm->next_out += n;
721         strm->avail_out -= n;
722         strm->total_out += n;
723
724         *state->cds_buf = *state->cds_p;
725         state->cds_p = state->cds_buf;
726         state->direct_out = 0;
727     }
728     return AEC_OK;
729 }
730
731 int aec_encode_end(struct aec_stream *strm)
732 {
733     struct internal_state *state = strm->state;
734
735     free(state->block_buf);
736     free(state->cds_buf);
737     free(state);
738     return AEC_OK;
739 }
740
741 int aec_buf_encode(struct aec_stream *strm)
742 {
743     int status;
744
745     status = aec_encode_init(strm);
746     if (status != AEC_OK)
747         return status;
748     status = aec_encode(strm, AEC_FLUSH);
749     if (strm->avail_in > 0 || strm->avail_out == 0)
750         status = AEC_DATA_ERROR;
751
752     aec_encode_end(strm);
753     return status;
754 }