-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpucr.c
2025 lines (1640 loc) · 62.3 KB
/
pucr.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// #include "pucr.h"
// #include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#include <string.h>
#include <limits.h> // rotl
#include <time.h>
#define likely(x) __builtin_expect((x),1)
#define unlikely(x) __builtin_expect((x),0)
static clock_t start, end;
static double cpu_time_used;
#define NO_MAX_GAMMA 0xFF
#define MAX_RLE_RANKS 31
#define LZ 0x0003
#define LIT 0x0002
#define RLE 0x0004
#define MARKED 0x0080
#define LZ_LEN_MAX_GAMMA 15
#define MAX_ESC 9
#define MAX_MTF 9
#define FAST_LANE 0
#define OUT_SIZE 65536
#define DECODE_ITERATIONS 10000
// pthread_mutex_t mutex_mtf;
struct pucr_node {
uint16_t rle_count;
uint16_t lz_count;
uint16_t lz_max_offset;
uint16_t lz_cur_offset;
uint32_t lz_cost;
uint16_t dict_min_offset;
uint16_t dict_count;
uint16_t seen_before;
uint16_t see_next;
uint16_t way_to_go;
uint16_t next_node;
uint32_t bits_to_end;
uint8_t new_esc;
uint8_t cur_lit;
};
// --== GENERAL ==--
// DONE: implement speed checks using CPU ticks
// TODO: streamline datatypes
// TODO: handle return value of 'init' function
// --== SPEED ==--
// DONE: allow selection of a simpler alternative which uses sane
// in_len-dependant defaults gaining speed by not searching
// for the optimum settings
// TODO: check opportunities to speed up string matching,
// keep in mind especially short block sizes:
// O(n³) might be less less expensive than O(n) for small n,
// do the original hash tables help?
// TODO: make data structures thread safe, especially outbuffer related
// TODO: implement pthread support for linux & co.
// definetly for optimize_path which requires more memory then,
// maybe for string & rle matching
// DONE: rework int_log2 -- maybe include LUT for 0x0000 <= x <= 0xFFFF
// TODO: squeeze formulas after prooved correctness
// TODO: RLE ranking seems to be expensive performancewise, its effectiveness
// should be inspected
// --== FUNCTION ==--
// TODO: check if there is a need for max E. Gamma length mechanism, maybe
// implemented seperately for lz count, lz offset, rle rank pointer,
// rle length; put according information in header
// TODO: implement an optimization step to find out if rle rank table makes sense
// for that particular block to compress, i.e. if more bites are saved if
// not using a rle rank table (if no_esc > 1 and '1111' is indicating unranked
// rle character, common rle runs of 2 would take 16 or more bits and thus
// unfortunately too expensive)
// DONE: implement a shorter 'code' for LZ2, i.e. 'ESC00' instead of 'ESC000'.
// at least as long as 'ESC001' is not used, would save one bit per LZ2
void start_clock(void) {
start = clock();
}
double print_clock(void) {
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
fprintf (stderr,"CPU TIME USED: %f\n", cpu_time_used);
return (cpu_time_used);
}
// https://hbfs.wordpress.com/2008/08/05/branchless-equivalents-of-simple-functions/
// Steven Pigeon
inline unsigned int sign_extension (int x)
{
return x >> (CHAR_BIT*sizeof(int)-1);
}
/* inline int sign_extension (int32_t x) // only works on LE machine !!!
{
union
{
// let us suppose long is twice as wide as int
int64_t w;
// should be hi,lo on a big endian machine
struct { int32_t lo, hi; }
} z = { .w=x };
return z.hi; // lo on BE machine !!!
}*/
/* int32_t sign_extension (int32_t x)
{
return ~((x<0)-1);
}*/
inline int32_t abs_bl(int32_t x)
{
return (x + sign_extension(x)) ^ sign_extension(x);
}
inline int32_t sign(int32_t x) {
return sign_extension(x) - sign_extension(-x);
}
inline int min(int a, int b)
{
return b + ((a-b) & sign_extension(a-b));
}
inline int max(int a, int b)
{
return a + ((b-a) & ~sign_extension(b-a));
}
static uint8_t int_log2_lut [65536];
static int8_t lz_offset_encoded_length[16][16];
uint32_t pucr_init (void) {
// pthread_mutex_init(&mutex_mtf, NULL);
// initialize LUT for log2
uint16_t i;
int16_t v = -1;
uint16_t mask = 0xFFFF;
int_log2_lut[0] = 0; // special definition here
for (i=1; i < 65535; i ++) {
if ( (i & mask) != 0 ) {
mask <<= 1;
v++;
}
int_log2_lut[i] = v;
}
// precalculate LUT for lz-bitcount (p = no of real bits) for different lsb-msb length (m = no of pure LSB bits) encodings
for (int m=0;m<16;m++) {
for (int p=0; p<16; p++) {
lz_offset_encoded_length[m][p]=m + ((p<m?0:p-m+1))*2+1 ; // !!! easier to understand, could be shortened for performance
}
}
}
// #define int_log2(x) (x?31-__builtin_clz(x):0)
static uint8_t inline int_log2 (uint16_t x) { // uint16_t x
// if (x < 65535) {
return (int_log2_lut[x]);
// } else {
/* taken from Henry S. Warren Jr.'s 2nd edition of Hacker's Delight */
/* uint8_t n = 0;
if (x <= 0x0000FFFF) { n = n + 16; x = x << 16;}
if (x <= 0x00FFFFFF) { n = n + 8; x = x << 8;}
if (x <= 0x0FFFFFFF) { n = n + 4; x = x << 4;}
if (x <= 0x3FFFFFFF) { n = n + 2; x = x << 2;}
n = n - (x >> 31);
return (30 - n);
}*/
}
// ---=== MOVE TO FRONT MOVE TO FRONT MOVE TO FRONT MOVE TO FRONT ===---
static inline uint8_t move_to_front_encode (uint8_t in_char,
uint8_t alphabet[],
uint8_t second_line) {
// search letter in alphabet
uint16_t j= 0;
for (;; j++) if (unlikely(alphabet[j]==in_char)) break;
uint8_t new = (j >> second_line);
// move letter more towards the front of the alphabet
for (uint8_t k=j; k>new; k--) alphabet[k]=alphabet[k-1];
alphabet[new]=in_char;
return(j);
}
static inline uint8_t move_to_front_decode (uint8_t in_char,
uint8_t alphabet[],
uint8_t second_line) {
uint8_t ret = alphabet[in_char];
// pthread_mutex_lock (&mutex_mtf);
// move letter more towards the front of the alphabet
uint8_t new = (in_char >> second_line);
for (uint8_t k=in_char; k>new; k--) alphabet[k]=alphabet[k-1];
alphabet[new]=ret;
// pthread_mutex_unlock (&mutex_mtf);
return(ret);
}
// ---=== LIT LIT LIT LIT LIT LIT LIT LIT LIT LIT LIT LIT LIT LIT LIT ===---
static uint32_t update_lit_occ_from_graph (struct pucr_node graph[], uint16_t in_len,
uint16_t lit_occ[]) {
uint16_t i;
for (i=0; i<256; i++) lit_occ[i] = 0;
for (i=0; i < in_len; i=graph[i].next_node)
if (graph[i].way_to_go == LIT) {
lit_occ[graph[i].cur_lit]++;
}
return (0);
}
// does not give exact result as it does not take the 'divides' into account, TODO !!!
static int32_t huffiness (uint16_t occ[], uint16_t first, uint16_t last, uint8_t *opt_level, uint8_t cost, uint8_t lit_cost[]) {
// how 'huffy' are the values? does it make sense to encode them with an implicit huffman tree?
uint16_t i;
int32_t sum = 0;
if (cost) for (i=0; i < 256; i++) lit_cost[i] = 8;
uint8_t huff_level = 0;
int32_t max_sum = sum;
uint16_t q;
uint16_t j;
for (i=last-first+1; i>=4; i=q) {
q = i >> 2;
for (j=first;j<(first+q);j++) { sum += occ[j]; if (cost) lit_cost[j]--; }// one bit less
for (j=first+(q<<1);j<first+i;j++) { sum -= occ[j]; if (cost) lit_cost[j]++; } // one bit more
if (sum > max_sum) {
max_sum = sum;
huff_level++;
} else {
break; // no need to go any further
}
}
*opt_level = huff_level;
return (max_sum);
}
// ---=== RLE RLE RLE RLE RLE RLE RLE RLE RLE RLE RLE RLE RLE RLE RLE RLE ===---
static uint32_t generate_rle_ranks (uint16_t rle_occ[], uint8_t rle_rank[], uint8_t *rle_rank_len) {
uint16_t max_index, max_value;
int16_t i;
for (i=0;i<MAX_RLE_RANKS;i++) {
/* find characters with highest number of occurences
* but not below 2 for ranks 3 and following */
max_value = (i < 3)?1:(i < 16)?2:4;
max_index = 0xFFFF;
for (uint16_t j=0; j < 256 ; j++) {
if (rle_occ[j] > max_value) {
/* check that candidate J is not already in list */
uint16_t k;
for (k=0;k<i;k++) if ( j==rle_rank[k] ) break;
if (k == i) {
max_value = rle_occ[j];
max_index = j;
}
}
}
if ( max_index != 0xFFFF ) {
rle_rank[i] = max_index;
*rle_rank_len = *rle_rank_len + 1;
} else {
break;
}
}
// find optimal length for ranked RLE table
uint32_t min = 0; // 0xFFFFFFFF;
for (uint16_t g=0;g<i;g++) min += rle_occ[rle_rank[g]] * 8;
uint16_t idx = 0xFFFF;
for (uint16_t ranked=0;ranked<i;ranked++) {
uint32_t sum = 0;
for (uint16_t g=0;g<ranked;g++) sum += 8 + rle_occ[rle_rank[g]] * (int_log2(g+1)*2+1);
for (uint16_t g=ranked;g<i;g++) sum += rle_occ[rle_rank[g]] * ((ranked==0?0:int_log2(ranked)+1) +8);
if (sum < min) {
min=sum;
idx=ranked;
}
}
*rle_rank_len = idx+1;
// *rle_rank_len = i;
return (0);
}
static uint32_t update_rle_occ_from_graph (struct pucr_node graph[], const uint8_t *inbuf, uint16_t in_len,
uint16_t rle_occ[]) {
uint16_t i;
for (i=0; i<256; i++) rle_occ[i] = 0;
for (i=0; i < in_len; i=graph[i].next_node)
if (graph[i].way_to_go == RLE)
rle_occ[inbuf[i]]++;
return (0);
}
static uint32_t count_rle_and_generate_occ_from_inbuf (struct pucr_node graph[], const uint8_t *inbuf, uint16_t in_len,
uint16_t rle_occ[]) {
uint8_t character = inbuf [in_len-1];
uint16_t rle_count = 0;
int32_t i; // required (as file size is 16 bit and i may fall below 0); also needed outside loop -- really !!! ???
for (i=255; i>=0; i--) rle_occ[i] = 0;
for (i=in_len-1; i >= 0; i--) {
if (inbuf[i] == character) {
rle_count++;
} else {
// !!! the following line are for creating occurances table, for optimizing later
/* count number of occuring (real) RLE runs (>1) per character */
if (rle_count > 1) rle_occ[inbuf[i+1]]++;
rle_count = 1;
character = inbuf[i];
}
graph[i].rle_count = rle_count;
}
// first position
if (rle_count > 1) rle_occ[inbuf[i+1]]++;
}
// ---=== LZ LZ LZ LZ LZ LZ LZ LZ LZ LZ LZ LZ LZ LZ LZ LZ LZ LZ LZ LZ LZ ===---
static uint32_t find_closer_match (struct pucr_node graph[], const uint8_t *inbuf, uint16_t in_len,
uint16_t pattern_start, uint16_t pattern_length, uint16_t min_match_start) {
uint16_t j,k ;
// we will be able to skip at least 2 characters when comparing
// because we know we already have a 2-byte match.
// even more if rle is longer in that position !!!
uint16_t off = (graph[pattern_start].rle_count -1);
off = off<=2?2:off;
// off=0;
// graph[pattern_start].lz_cur_offset = graph[pattern_start].lz_max_offset; // 0xFFFF;
for (j=graph[pattern_start].seen_before; (j >= min_match_start) && (j != 0xFFFF); j=graph[j].seen_before) { // check at offset J for a match ...
if (graph[pattern_start].rle_count != graph[j].rle_count) continue;
k = j + off;
for (k=j+off; (k-j)<pattern_length; k++) { // ... of length (K-J)
if (inbuf[k] != inbuf[pattern_start+(k-j)]) break; // no match
}
if (k > pattern_start) k = j; // even beyond pattern
k -= j; // match length
if (k >= pattern_length) {
// treatment of a match found
graph[pattern_start].lz_cur_offset = pattern_start-j; // store the 'real' offset
break;
}
}
}
static uint32_t prepare_last_seen_from_graph (struct pucr_node graph[], const uint8_t *inbuf, uint16_t in_len) {
uint16_t last_occ [65536];
memset (last_occ, 0xFF, 0x20000);
for (uint16_t i=0; i < in_len;i++ ) {
// if (inbuf[i] == inbuf[i+1]) continue; // !!! fast_lane candidate,
uint16_t idx = (inbuf[i] << 8) | inbuf[i+1];
graph[i].seen_before = last_occ[idx];
last_occ[idx] = i;
if (inbuf[i] == inbuf[i+1]) continue; // !!! fast_lane candidate,
}
}
static uint32_t find_matches (struct pucr_node graph[], const uint8_t *inbuf, uint16_t in_len,
uint16_t first_pos, uint16_t last_pos,
uint8_t recursive, uint8_t fast_lane, uint8_t lz_length_max_gamma, uint8_t lz2_bits, uint8_t lz_lsb) {
// a block should not be much shorter than 256...512 bytes
if ( (recursive > 0) && ((last_pos - first_pos) > 512) ) {
uint16_t sep = (last_pos - first_pos) * 43 / 64;
find_matches (graph, inbuf, in_len, first_pos, first_pos+sep, recursive-1, fast_lane, lz_length_max_gamma, lz2_bits, lz_lsb);
find_matches (graph, inbuf, in_len, first_pos+sep+1, last_pos, recursive-1, fast_lane, lz_length_max_gamma, lz2_bits, lz_lsb);
} else {
uint64_t *pattern;
uint64_t *match;
uint16_t i,j,k, off;
// for (i=first_pos; i <= last_pos; i +=fast_lane?graph[i].rle_count:1) {// i+=graph[i].rle_count) {
// for (i=first_pos; i <= last_pos; i+=graph[i].rle_count) {
for (i=first_pos; i <= last_pos; i+=(fast_lane?graph[i].rle_count:1) ) {
graph[i].lz_max_offset = 0xFFFF; // !!! neccessary for msb-lsb-offset calculation of number of bits
graph[i].lz_count = 0x0000; // = no match yet
graph[i].lz_cost = 0;
// we will be able to skip at least 2 characters when comparing
// because we know we already have a 2-byte match.
// even more if rle is longer in that position
off = (graph[i].rle_count -1);
off = off<=2?2:off;
// off = 0;
// uint16_t cnt = 2;
// pattern = &inbuf[i+off];
for (j=graph[i].seen_before; (uint16_t)(j+1) ; j=graph[j].seen_before) { // check at offset J for a match ...
// cnt++;
if (graph[i].rle_count != graph[j].rle_count) continue;
k = j + off;
// if a match crosses last_pos, "< in_len" would be advantageous to "<=last_pos" ... !!! may be consider for fast_lane
// for (k = j+off; (k < i) && (i+(k-j)) <in_len ; k+=4) { // ... of length (K-J)
for (; (k < i) && ((i+(k-j))<in_len) && ( (k-j) < (3<<(lz_length_max_gamma-1)) ); k++) { // ... of length (K-J)
if (inbuf[k] != inbuf[i+(k-j)]) break;
// match = &inbuf[k];
// if (*pattern ^ *match) break;
}
if (k <= i) { // we always have a match of at least 2
k -= j; // match length
//k -= (j+ int_log2(notbe64()>>3))
// treatment of a match found
// naive weighting function: the longer the better // replace with weighting/boundary conditions later on !!!
// experimental: try to calculate cost.
// WHY does it result in a compression gain?!
uint32_t gain = (k==2)?16-(3+(lz2_bits>3)?lz2_bits-1:lz2_bits): // '-1' includes some implied huffyness gains
//// k*8-(1 + int_log2(k-1)*2+1 + 10 + int_log2((i-j-3)>>10)*2+1);
// k*8-(1 + int_log2(k-1)*2+1 + lz_lsb + int_log2((i-j-3)>>lz_lsb)*2+1);
// k*8-(1 + int_log2(k-1)*2+1 + (i-j-k)<1024?11:10+int_log2((i-j-k)>>10)*2+1);
k*8-(1 + int_log2(k-1)*2+1 + (i-j-3)<1024?11:10+int_log2((i-j-3)>>10)*2+1);
// k*8-(1 + int_log2(k-1)*2+1 + (i-graph[i].seen_before-3)<1024?11:10+int_log2((i-graph[i].seen_before-3)>>10)*2+1);
// the ranked could be taken care of? the dynamic max-gamma could be taken care of? !!!
// if (k > graph[i].lz_count) {
if (gain > graph[i].lz_cost) {
//graph[i].lz_max_offset = i-graph[i].seen_before; // store the 'real' offset
// graph[i].lz_max_offset = cnt; // store the 'real' offset
graph[i].lz_max_offset = i-j; // store the 'real' offset
graph[i].lz_count=k; // ; -(off2-i); // k
graph[i].lz_cost = gain;
}
}
// if ( k >= (in_len >> (7+fast_lane))) break; // long enough
}
}
fprintf (stderr, "--- FINDING MATCHES %5u ... %5u: ",first_pos,last_pos);
print_clock(); start_clock();
}
}
struct lz_offset_entry {
uint16_t offset;
uint16_t count;
uint16_t bits_used;
};
int compare_lz_offset( const void * a, const void * b) {
struct lz_offset_entry *entryA = (struct lz_offset_entry *)a;
struct lz_offset_entry *entryB = (struct lz_offset_entry *)b;
return ( (entryB->count*entryB->bits_used) - (entryA->count*entryA->bits_used) );
}
static uint32_t find_optimal_lz_offset_no_lsb (struct pucr_node graph[], uint16_t in_len,
uint8_t no_esc,
uint8_t *no_lz_offset_lsb, uint8_t *no_lz2_offset_bits,
uint8_t *lz2_opt_huff_level,
uint8_t *lz_rank_prefix_len, uint8_t *lz_rank_prefix,
uint8_t *lz_rank_len, uint16_t lz_rank[]) {
uint32_t lz_occ[16] = {0};
uint16_t lz2_occ[16] = {0};
//uint32_t lz_offset[65536]= {0};
struct lz_offset_entry lz_offset[65536];
for (uint i=0; i<65536; i++) {
lz_offset[i].offset=i;
lz_offset[i].count=0;
}
uint16_t lz2_full_occ[65536] = {0};
// after all matches are finally determined, calculate the optimum of lsb-msb coding ratio
// first step: count them, especially the bits their offsets need
for (uint16_t i=0; i != in_len; i=graph[i].next_node) {
if (graph[i].way_to_go == LZ) {
// lz_length is not necessarily the real way to go,
// but next_node is
if ((graph[i].next_node - i) >= 3) {
lz_offset[graph[i].lz_cur_offset].count++;
// for the 3-byte and longer matches: calculate the case with "p" pure LSB and the rest E.Gamma-coded
for (int p=0; p <16; p++) // 0 = 1-bit offset, 1 = 2-bit offset, ...
lz_occ[p] += (p+1) + int_log2( ((graph[i].lz_cur_offset-3)>>(p+1))+1 )*2+1;
// lz_occ[p] += (p+1) + int_log2( ((graph[i].lz_cur_offset-(graph[i].next_node-i))>>(p+1))+1 )*2+1;
} else {
lz2_full_occ[graph[i].lz_cur_offset-2]++;
int p = int_log2 (graph[i].lz_cur_offset - 2);
p = p<=15?p:15;
lz2_occ[p]++;
}
}
}
uint32_t min_sum = 0xFFFFFFFF;
uint8_t min_no_lsb = 0;
for (uint8_t m=15; m!=0xFF; m--) {
if (lz_occ[m] < min_sum) {
min_no_lsb = m;
min_sum = lz_occ[m];
}
}
*no_lz_offset_lsb = min_no_lsb + 1;
uint8_t max_p = 16 - 2 - no_esc - 1;
uint16_t min_lz2_bits = int_log2 (in_len);
min_lz2_bits = (min_lz2_bits <= 8)?min_lz2_bits:8;
int32_t max_saving = 0;
for (uint8_t p=0; p<max_p; p++) {
// count the bits saved for each LZ2 possible (i.e. if offset fits in p bits)
int32_t gained = 0;
for (uint8_t q=0; q<=p; q++) gained += (lz2_occ[q] * (16 - (p+1 + no_esc +2)));
// lost bits due to unused LZ2 opportunities as offset length is longer than p bits
int32_t lost = 0;
for (uint8_t q=p+1; q<max_p; q++) lost += (lz2_occ[q] * (16 - (p+1 + no_esc +2)));
// weigh against each other and store if minimum
if ((gained-lost) > max_saving) {
max_saving = gained-lost;
min_lz2_bits = p + 1;
}
}
*no_lz2_offset_bits = min_lz2_bits;
// !!! should those be taken in account during the loop above??? !!!
uint8_t lit_cost[256]={8};
uint32_t lz2_huff_savings = huffiness (lz2_full_occ,0,(1<<(min_lz2_bits))-1, lz2_opt_huff_level,0, lit_cost);
if (*lz_rank_prefix_len) {
uint16_t min_prefix[min_no_lsb+1];
uint16_t prefix_occ[min_no_lsb+1];
if (min_no_lsb != -1) {
uint16_t prefix_sum;
for (uint8_t prefix_len=0; prefix_len <= min_no_lsb; prefix_len++) {
prefix_occ[prefix_len] = 0xFFFF;
min_prefix[prefix_len] = 0xFFFF;
for (uint16_t prefix=0; prefix < (1<<prefix_len); prefix++) {
uint16_t prefix_sum = 0;
for (uint32_t i=3; i < in_len; i += (1<<(min_no_lsb+1)) )
for (uint32_t j=prefix<<(min_no_lsb+1-prefix_len);(j<((prefix+1)<<(min_no_lsb+1-prefix_len))); j++)
prefix_sum += lz_offset[i+j-3].count;
if (prefix_sum < prefix_occ[prefix_len]) {
min_prefix[prefix_len] = prefix;
prefix_occ[prefix_len] = prefix_sum;
}
}
}
}
// !!! couldn't this be done in parallel to the prefix_sum determination (requires min_no_lsb) ??? !!!
for (uint16_t i=0;i < in_len;i++)
// use the offset to be encoded, i.e. '-3'
lz_offset[i].bits_used = (min_no_lsb+1) + int_log2( ((i-3)>>(min_no_lsb+1))+1 )*2+1;
qsort( lz_offset, in_len, 3*sizeof(uint16_t), compare_lz_offset );
// !!! couldn't this all be drawn into the lz_prefix loop above to be accounted for when chiosing min_no_lsb ??? !!!
int32_t min_total = 0x7FFFFFFF, local_min, total;
for (uint8_t prefix_len=0; prefix_len < min_no_lsb; prefix_len++) {
local_min = 0x7FFFFFFF;
for (uint8_t enum_bits=1; enum_bits < 8; enum_bits++) { // !!! upper bound 8 ??? !!!
// costs vs. saved
uint32_t cost = prefix_occ[prefix_len]*enum_bits + ((1<<enum_bits)-1)*(min_no_lsb+5) + 6; // !!! +5 is some default for MSB, +6 (roughly) for header
uint32_t save = 0;
for (uint8_t i=0; i < (1<<enum_bits)-1; i++)
// before the additional qsort and preceeding reduction of bits_used (see below)the following line was
// save += lz_offset[i].count * (lz_offset[i].bits_used - prefix_len - enum_bits);
save += lz_offset[i].count * (lz_offset[i].bits_used - enum_bits);
total = cost - save;
if (total < local_min)
local_min = total;
else
break; // if rising again, don't look further, it won't get better
if ( (total < 0) && (total < min_total) ) {
min_total = total;
*lz_rank_prefix_len = prefix_len;
*lz_rank_prefix = min_prefix[prefix_len];
*lz_rank_len = (1<<enum_bits)-1;
for (uint8_t i=0; i < (1<<enum_bits)-1; i++)
lz_rank[i] = lz_offset[i].offset;
}
}
for (uint8_t i=0;i < 255; i++)
lz_offset[i].bits_used = (lz_offset[i].bits_used<=1)?0:(lz_offset[i].bits_used-1);
qsort( lz_offset, 255, 3*sizeof(uint16_t), compare_lz_offset );
}
if (min_total > 0)
*lz_rank_len = 0;
}
return (0);
}
// ---=== ESC ESC ESC ESC ESC ESC ESC ESC ESC ESC ESC ESC ESC ESC ESC ===---
/*
The algorithm in the OptimizeEscape() works as follows:
1) Only unpacked bytes are processed, they are marked
with MMARK. We proceed from the end to the beginning.
Variable A (old/new length) is updated.
2) At each unpacked byte, one and only one possible
escape matches. A new escape code must be selected
for this case. The optimal selection is the one which
provides the shortest number of escapes to the end
of the file,
i.e. A[esc] = 1+min(A[0], A[1], .. A[states-1]).
For other states A[esc] = A[esc];
If we change escape in this byte, the new escape is
the one with the smallest value in A.
3) The starting escape is selected from the possibilities
and mode 0 is restored to all mode 3 locations.
*/
static uint32_t optimize_esc (struct pucr_node graph[], const uint8_t *inbuf, uint16_t in_len,
uint8_t no_esc, uint8_t *startEscape,
uint8_t mtf, uint8_t mtf_second_line) {
uint16_t i;
int16_t j;
uint8_t esc8 = 8-no_esc;
uint16_t states = (1<<no_esc);
int32_t minp = 0, minv = 0, other = 0;
int32_t a[256]; /* needs int/long */
int32_t b[256]; /* Remembers the # of escaped for each */
for (i=0; i<256; i++)
b[i] = a[i] = -1;
uint8_t alphabet[256]; for (i=0; i<256;i++) alphabet[i]=i;
for (i=0; i != in_len; i = graph[i].next_node)
if (graph[i].way_to_go == LIT) {
graph[i].way_to_go = MARKED;
// store the (maybe to be mtf-encoded) literal in the graph to preserve inbuf
graph[i].cur_lit = move_to_front_encode (inbuf[i], alphabet, mtf_second_line);
}
for (i=in_len-1; i != 0xFFFF; i--) {
if (graph[i].way_to_go == MARKED) {
graph[i].way_to_go = LIT;
// use mtf-encoded literal for ESCape code evaluation
int16_t k = graph[i].cur_lit >> esc8;
/*
k are the matching bytes,
minv is the minimum value of neccessary following escapes
minp is the minimum index, i.e. the esc code that currently delivers the least escapes
*/
graph[i].new_esc = (minp << esc8);
/* with k as esc code, there would be needed one more escape than the so-far minimum.
not for the others, though. */
a[k] = minv + 1;
/* escapes happened so far. as long as k != minp, b[k] remains stuck at b[minp]+1.
if we see a hit (k == minp), counting continues in the new b[k] track (with minp := k) */
b[k] = b[minp] + 1;
if (k==minp) {
/* this is a hit, it requires an escape */
minv++;
/* Minimum changed -> need to find a new minimum */
/* a[k] may still be the minimum */
for (k=states-1; k>=0; k--) {
if (a[k] < minv) {
minv = a[k];
minp = k;
/*
There may be others, but the first one that
is smaller than the old minimum is equal to
any other new minimum (because minv was
incremented by 1 only).
*/
break;
}
}
}
}
}
/* Select the best value for the initial escape */
/* find smallest a[j] with smallest "largest" escape code value */
if (startEscape) {
i = in_len; /* make it big enough */
for (j=0; j < states; j++) {
if (a[j] <= i) {
*startEscape = (j << esc8);
i = a[j];
}
}
}
return b[startEscape ? (*startEscape>>esc8) : 0] + 1;
}
// ---=== PATH FINDER PATH FINDER PATH FINDER PATH FINDER PATH FINDER ===---
static uint32_t find_best_path (struct pucr_node graph[], const uint8_t *inbuf, uint16_t in_len,
uint16_t rle_occ[], uint8_t rle_rank[], uint8_t rle_rank_len,
uint8_t no_esc,
uint8_t lz_lsb, uint8_t lz2_bits,
uint8_t lit_cost_arr[],
uint8_t fast_lane) {
// !!! not for empty input -- sure ???
/* create rle cost (per character) table w/o cost for following length value */
uint16_t rle_cost_table[256];
for (uint16_t j=0; j < 256; j++) {
/* is it a ranked character? */
uint8_t k;
for (k=0; k < rle_rank_len; k++) if ( j == rle_rank[k] ) break;
if (k != rle_rank_len) {
// ranked
rle_cost_table[j] = 3 + int_log2(k+1)*2+1; // + (32 / (3 * rle_occ[j] + 1)); // this is a try to take table costs into account !!!
} else {
// not ranked
rle_cost_table[j] = 3 + int_log2(rle_rank_len)+1 + 8;
if (rle_rank_len == 0) rle_cost_table[j]--;
}
}
/* however, it is some blur left here: depending on choices in the following optimizer loop, rle occurences and their
cost may change again, which could affect optimizer choices again, which might change costs again, which might ... */
// graph[in_len] is the (virtual) EOF symbol
graph[in_len].bits_to_end = 0;
/* check for each node the best way to go */
for (uint16_t i=in_len-1; i!=0xFFFF ; i--) {
uint32_t rle_cost, lz_cost, dict_cost, lit_cost;
uint32_t min = 0xFFFFFFFF;
uint16_t rle_way, lz_way, dict_way;
/* determine possible rle costs */
/* this loops also checks for all shorter lengths */
/* !!! ref org line 1044: only shorter ones that are a power of two? */
for (uint16_t j=graph[i].rle_count; j > 1; j=fast_lane?1<<(int_log2(j)-1):j-1 ) {
rle_cost = rle_cost_table[inbuf[i]] + int_log2(j-1)*2+1;
rle_cost += graph[i+j].bits_to_end;
if (rle_cost < min) {
min = rle_cost;
rle_way = i+j;
}
}
// only if a new minimum was found, add no_esc
// otherwise, keep up the high cost of 0xFFFFFFFF
// !!! (min+1) == 0 is a bit hacky and relies on data type properties
rle_cost = (min+1)?min+no_esc:min;
/* determine possible LZ cost */
min = 0xFFFFFFFF;
/* !!! ref org line 1044: only shorters that are a power of two? */
for (uint16_t j=graph[i].lz_count; j > 1; j=fast_lane?1<<(int_log2(j)-1):j-1) {
// in case j == 2, the offset to be encoded may not be larger than 2^lz2_bits; otherwise lz is no option
if ( (j == 2) && ((graph[i].lz_max_offset-2) >= (0x01 << lz2_bits)) ) break;
lz_cost = (j==2)?2+lz2_bits:
// lz_lsb + int_log2(((graph[i].lz_max_offset-3)>>lz_lsb)+1)*2+1 + int_log2( graph[i-graph[i].lz_cur_offset].next_node - (i-graph[i].lz_cur_offset) +1 -1 +1)*2+1;
int_log2(j-1)*2+1 + lz_lsb + int_log2(((graph[i].lz_max_offset-3)>>lz_lsb)+1)*2+1;
//// int_log2(j-1)*2+1 + lz_lsb + int_log2(((graph[i].lz_max_offset-j)>>lz_lsb)+1)*2+1;
lz_cost += graph[i+j].bits_to_end;
if (lz_cost < min) {
min = lz_cost;
lz_way = i+j;
}
}
// only if a minimum was found in the loop, add the number of ESCape bits
// otherwise, keep up the high cost of 0xFFFFFFFF
// !!! (min+1) != 0 is a bit hacky and relies on data type properties
if (min+1) {
lz_cost = min + no_esc;
graph[i].lz_cur_offset = graph[i].lz_max_offset;
// if using a shorter-than-max match, we might find a closer one
// this will keep the output of the encoded current offset smaller
// and also might lead to a lower number of bits used for encoding LZ2/LZ offsets
if (fast_lane == 0) { // only in fast_lane 0
uint16_t used_match_length = lz_way-i;
if (used_match_length<graph[i].lz_count) {
find_closer_match (graph, inbuf, in_len, i, used_match_length,i-graph[i].lz_max_offset+1);
// recalculate costs
lz_cost = (used_match_length==2)?2+lz2_bits:
int_log2(used_match_length-1)*2+1 + lz_lsb + int_log2(((graph[i].lz_cur_offset-3)>>lz_lsb)+1)*2+1;
// int_log2(used_match_length-1)*2+1 + lz_lsb + int_log2(((graph[i].lz_cur_offset-used_match_length)>>lz_lsb)+1)*2+1;
lz_cost += graph[i+used_match_length].bits_to_end+no_esc;
}
}
} else {
lz_cost = min;
}
// lit_cost = lit_cost_arr[graph[i].cur_lit] +graph[i+1].bits_to_end ; // + 1 ??? !!! ;
// lit_cost = 7 +graph[i+1].bits_to_end ; // 7 to repect entropy encoding ??? !!! ;
lit_cost = 8 +graph[i+1].bits_to_end ; // + 1 ??? !!! ;
if ( (rle_cost < lz_cost) && (rle_cost < lit_cost) ) {
graph[i].way_to_go = RLE;
graph[i].next_node = rle_way;
graph[i].bits_to_end = rle_cost;
} else if ( (lz_cost <= rle_cost) && (lz_cost < lit_cost) ) {
graph[i].way_to_go = LZ;
graph[i].next_node = lz_way;
graph[i].bits_to_end = lz_cost;
} else {
graph[i].way_to_go = LIT;
graph[i].next_node = i+1;
graph[i].bits_to_end = lit_cost;
}
}
fprintf (stderr, "--- PATH FINDER BITS TO END: %u \n",graph[0].bits_to_end);
}
// ---=== OUTPUT OUTPUT OUTPUT OUTPUT OUTPUT OUTPUT OUTPUT OUTPUT OUTPUT ===---
static uint16_t outPointer = 0;
static uint8_t bitMask = 0x80;
static uint32_t bitCount = 0;
static int8_t out_buffer [OUT_SIZE];
static void flush_bits (void) {
if (bitMask != 0x80) outPointer++;
}
static void put_bit (int bit) {
bitCount++;
if (bit && outPointer < OUT_SIZE)
out_buffer[outPointer] |= bitMask;
bitMask >>= 1;
if (!bitMask) {
bitMask = 0x80;
outPointer++;
}
}
static void put_value (int value, int maxGamma) {
int bits = 0, count = 0;
// !!! not working properly for maxGamma == 00 (output '0' or '1') !!! ???
while (value>1) {
bits = (bits<<1) | (value & 1); /* is reversed compared to value */
value >>= 1;
count++;
put_bit (0);
}
if (count<maxGamma)
put_bit (1);
while (count--) {
put_bit ((bits & 1)); /* output is reversed again -> same as value */
bits >>= 1;
}
}
static void put_n_bits (int byte, int bits) {
while (bits--)
put_bit ((byte & (1<<bits)));
}
static void put_huffed_value (int value, int bits, uint8_t rec) {
if (rec == 0) {
put_n_bits(value, bits);
return;
}
uint16_t mask = 1<<(bits-1);
mask |= mask >> 1;
if ((value & mask) == 0) {
put_bit(0);
put_huffed_value (value, bits-2, rec-1);
return;
}
else if ((value & mask) == (01<<bits-2)) {
put_bit (1);
put_bit (0);
put_n_bits (value, bits-2);
} else {
put_bit (1);
put_bit (1);
put_n_bits (value, bits-1);
}
}
static void put_huffed_value_org (int value, int bits, uint8_t rec) {
if (rec == 0) {
put_n_bits(value, bits);
return;
}
uint16_t mask = 1<<(bits-1);
mask |= mask >> 1;
if ((value & mask) == 0)
if (rec == 1) {
} else {
put_bit(0);
put_huffed_value (value, bits-2, rec-1);
return;
}
else if ((value & mask) == (1<<bits-2)) {
put_bit (1);
} else {
put_bit (1);
put_bit (0);
}
put_n_bits (value, bits-1);
}