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