-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompressor.c
More file actions
1991 lines (1784 loc) · 78.8 KB
/
Copy pathcompressor.c
File metadata and controls
1991 lines (1784 loc) · 78.8 KB
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
/*
* PMC v4: Bit-Level Context-Mixing Compressor
*
* PAQ-inspired architecture: multiple context models combined via adaptive
* logistic mixing, APM correction, match model, BCJ filter, binary rANS.
*
* v4.8 changes vs v4.7:
* - Mixer learning rate fine-tuning: 24/24 → 28/28
* - Word-aware SSE (ISSE5) rate: 5 → 4 (faster adaptation for text)
* (~0.27% additional improvement across full Silesia corpus + specialized files)
*
* v4.7 changes vs v4.6:
* - Mixer learning rate tuning: divisors 10/12 → 24/24 for both mixers
* (~2.4% improvement across full Silesia corpus, zero regressions on files > 256 KB)
*
* v4.4 changes vs v4.3:
* - Word trigram context model (prev_prev_word + prev_word + position)
* - MTF word cache pre-filter for text files (replaces BCJ)
*
* v4.3 changes vs v4.2:
* - Block-level text detection with model gating (gates 36 noise models on text)
* - Previous-word context model for word-bigram prediction
*
* v4 changes vs v3:
* - 34 sparse context models using non-adjacent byte patterns (~90 KB gain)
* - Tuned mixer learning rates (10/12 vs 8/8) (~1.6 KB gain)
*
* Sparse models are the dominant source of compression gain. They capture
* correlations between non-adjacent bytes (e.g. structured fields at regular
* offsets in ELF/binary data). Each sparse model costs ~8 MB of memory
* (4M tagged entries x 2 bytes) and yields diminishing returns:
* - First 10 models: ~3-7 KB each
* - Models 10-20: ~1-3 KB each
* - Models 20-34: ~250-600 bytes each
*
* To squeeze further when memory is not a concern, more sparse models can be
* added by incrementing NUM_CM/NUM_MODELS, defining additional ctx[] entries
* with new byte-skip patterns, and adding corresponding cm_init() calls.
* Promising patterns to try: longer strides (pb[16]..pb[31] — requires
* expanding the pb[] history buffer), higher-order sparse combinations
* (4-5 non-adjacent bytes), or data-type-specific patterns. Each new model
* adds ~8 MB memory for ~200-500 bytes of compression gain at this point.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <math.h>
/* ---- Configuration ---- */
#define BLOCK_SIZE (1 << 23) /* 8 MB */
#define PROB_BITS 12
#define PROB_SCALE (1 << PROB_BITS) /* 4096 */
#define PROB_HALF (PROB_SCALE / 2)
#define RANS_L (1u << 23)
#define MAX_BIT_EVENTS (BLOCK_SIZE * 12)
/*
* Context model table sizes.
*
* 9 order-N models (o0..o4, o6, o8, o12, o16), 1 word model, 1 prev_word
* model, and NUM_SPARSE sparse models that use non-adjacent byte combinations.
*
* To add more sparse models for better compression (at ~8 MB each):
* 1. Increase NUM_SPARSE
* 2. Add the new ctx[] hash in process_block()
* 3. Add the corresponding cm_init() call in do_compress/do_decompress
* NUM_CM and NUM_MODELS are computed automatically.
*/
#define NUM_SPARSE 34
#define NUM_CM (12 + NUM_SPARSE) /* 11 fixed (o0-o4, o6, o8, o12, word, prev_word, word_trigram) + sparseN + o16 */
#define NUM_MODELS (NUM_CM + 6) /* CM + match + ICM + delta + stride + wpred + lzp */
#define CM_O0_BITS 8 /* 256 bytes */
#define CM_O1_BITS 20
#define CM_O2_BITS 22
#define CM_O3_BITS 23
#define CM_O4_BITS 24
#define CM_O6_BITS 24
#define CM_O8_BITS 24
#define CM_O12_BITS 24 /* 16M tagged entries */
#define CM_WORD_BITS 22 /* 4M tagged entries */
#define CM_SPARSE_BITS 22 /* 4M tagged entries — used for all sparse models */
#define CM_O16_BITS 24 /* 16M tagged entries */
/* ICM (Indirect Context Model) */
#define ICM_BITS 24 /* 16M entries */
#define ICM_TAB_SIZE (1u << ICM_BITS)
#define ICM_NCTR 256 /* shared adaptive counters */
#define ICM_RATE 5 /* counter += (target - counter) >> 5 */
/* Delta model */
#define DELTA_BITS 22 /* 4M entries */
#define DELTA_TAB_SIZE (1u << DELTA_BITS)
/* Stride/Record model */
#define STRIDE_BITS 22 /* 4M entries */
#define STRIDE_TAB_SIZE (1u << STRIDE_BITS)
#define MAX_STRIDE 128
/* Match model */
#define MATCH_BITS 22 /* 4M entries */
#define MATCH_TAB_SIZE (1u << MATCH_BITS)
/* LZP (Lempel-Ziv Prediction) model */
#define LZP_BITS 22 /* 4M entries */
#define LZP_SIZE (1u << LZP_BITS)
/* Mixer 1: bp + prev_byte + prev2_byte + text + match => up to 4096 slots */
#define MIXER_SLOTS 4096
/* Mixer 2: bit_ctx */
#define MIXER2_SLOTS 256
/* ISSE chain: 4 refinement stages */
#define ISSE1_CTX_BITS 8 /* 256 ctx */
#define ISSE1_PROB_BITS 9 /* 512 bins */
#define ISSE2_CTX_BITS 8 /* 256 ctx */
#define ISSE2_PROB_BITS 9 /* 512 bins */
#define ISSE3_CTX_BITS 7 /* 128 ctx */
#define ISSE3_PROB_BITS 9 /* 512 bins */
#define ISSE4_CTX_BITS 10 /* 1024 ctx (with match) */
#define ISSE4_PROB_BITS 6 /* 64 bins */
#define ISSE5_CTX_BITS 18 /* 262144 ctx (word + bp) */
#define ISSE5_PROB_BITS 5 /* 32 bins */
/* Stretch/squash table range */
#define LOGIT_SCALE 256
#define LOGIT_MIN (-2048)
#define LOGIT_MAX 2047
#define LOGIT_RANGE (LOGIT_MAX - LOGIT_MIN + 1)
/* Interleaved rANS */
#define RANS_INTERLEAVE 4
static const uint8_t MAGIC[4] = {'P','M','C','4'};
#define FLAG_BCJ 1
#define FLAG_IMG_DELTA 2
#define FLAG_WAV_DELTA 4
#define FLAG_TEXT_MTF 8
#define FLAG_TEXT 16 /* file is text — enables text gating in blocks */
#define FLAG_IMG_RAW 32 /* raw image detected — 2D delta filter applied */
/* ---- Mixer learning rate divisors (tunable via -DMIX1_LR=N -DMIX2_LR=N) ---- */
#ifndef MIX1_LR
#define MIX1_LR 28
#endif
#ifndef MIX2_LR
#define MIX2_LR 28
#endif
/* ---- ISSE/APM learning rate shifts (tunable via -DISSE1_LR=N etc.) ---- */
#ifndef ISSE1_LR
#define ISSE1_LR 7
#endif
#ifndef ISSE2_LR
#define ISSE2_LR 5
#endif
#ifndef ISSE3_LR
#define ISSE3_LR 5
#endif
#ifndef ISSE4_LR
#define ISSE4_LR 4
#endif
#ifndef ISSE5_LR
#define ISSE5_LR 4
#endif
#ifndef WPRED_BASE_CONF
#define WPRED_BASE_CONF 8
#endif
#ifndef MATCH_CONF_DIV
#define MATCH_CONF_DIV 16
#endif
/* ---- Profiling (entropy map of predictions) ---- */
static int profile_mode = 0;
/* ---- Ablation (silence model families via bitmask) ---- */
/* bit 1=order_low, 2=order_high, 3=sparse, 4=linguistic,
5=match, 6=icm, 7=delta, 8=stride, 9=wpred, 10=lzp */
static uint32_t ablate_mask = 0;
/* ---- Stretch / Squash Tables ---- */
static int16_t stretch_tab[PROB_SCALE];
static uint16_t squash_tab[LOGIT_RANGE];
static void init_stretch_squash(void) {
for (int i = 0; i < LOGIT_RANGE; i++) {
double x = (double)(i + LOGIT_MIN) / LOGIT_SCALE;
double p = 1.0 / (1.0 + exp(-x));
int v = (int)(p * PROB_SCALE + 0.5);
if (v < 1) v = 1;
if (v > PROB_SCALE - 1) v = PROB_SCALE - 1;
squash_tab[i] = (uint16_t)v;
}
for (int i = 0; i < PROB_SCALE; i++) {
double p = ((double)i + 0.5) / PROB_SCALE;
if (p < 0.001) p = 0.001;
if (p > 0.999) p = 0.999;
double logit = log(p / (1.0 - p)) * LOGIT_SCALE;
int v = (int)(logit + (logit >= 0 ? 0.5 : -0.5));
if (v < LOGIT_MIN) v = LOGIT_MIN;
if (v > LOGIT_MAX) v = LOGIT_MAX;
stretch_tab[i] = (int16_t)v;
}
}
static inline int16_t stretch(uint16_t p) {
return stretch_tab[p < PROB_SCALE ? p : PROB_SCALE - 1];
}
static inline uint16_t squash(int32_t logit) {
if (logit < LOGIT_MIN) logit = LOGIT_MIN;
if (logit > LOGIT_MAX) logit = LOGIT_MAX;
return squash_tab[logit - LOGIT_MIN];
}
/* ---- PAQ-Style State Table ---- */
static uint8_t next_state[256][2];
static uint16_t state_prob[256];
static int16_t state_stretch[256];
static void init_state_table(void) {
/* Improved state table: prioritize small counts for fast adaptation,
* but allow higher counts for stable contexts. Uses (n0,n1) pairs
* with a mapping that favors low counts and asymmetric distributions. */
uint8_t sn0[256], sn1[256];
int16_t state_map[42][42];
memset(state_map, -1, sizeof(state_map));
int idx = 0;
/* First: allocate states by total count, favoring low counts */
for (int sum = 0; sum <= 80 && idx < 256; sum++) {
for (int n1 = 0; n1 <= sum && idx < 256; n1++) {
int n0 = sum - n1;
if (n0 > 41 || n1 > 41) continue;
if (state_map[n0][n1] >= 0) continue;
state_map[n0][n1] = idx;
sn0[idx] = (uint8_t)n0;
sn1[idx] = (uint8_t)n1;
idx++;
}
}
for (int s = 0; s < 256; s++) {
for (int bit = 0; bit < 2; bit++) {
int n0 = sn0[s], n1 = sn1[s];
if (bit == 0) n0++; else n1++;
while (n0 + n1 > 41) { n0 = (n0 + 1) >> 1; n1 = (n1 + 1) >> 1; }
if (n0 > 41) n0 = 41;
if (n1 > 41) n1 = 41;
next_state[s][bit] = (state_map[n0][n1] >= 0) ?
(uint8_t)state_map[n0][n1] : 0;
}
}
for (int s = 0; s < 256; s++) {
double p = (sn1[s] + 0.5) / (sn0[s] + sn1[s] + 1.0);
int v = (int)(p * PROB_SCALE + 0.5);
if (v < 1) v = 1;
if (v > PROB_SCALE - 1) v = PROB_SCALE - 1;
state_prob[s] = (uint16_t)v;
state_stretch[s] = stretch_tab[v];
}
}
/* ---- Context Model ---- */
typedef struct {
union {
uint8_t *table8;
uint16_t *table16;
};
uint32_t mask;
int tagged;
} ContextModel;
static ContextModel models[NUM_CM];
static void cm_init(ContextModel *m, int bits, int tagged) {
m->mask = (1u << bits) - 1;
m->tagged = tagged;
if (tagged) {
m->table16 = (uint16_t *)calloc((size_t)(m->mask) + 1, sizeof(uint16_t));
if (!m->table16) { fprintf(stderr, "OOM cm\n"); exit(1); }
} else {
m->table8 = (uint8_t *)calloc((size_t)(m->mask) + 1, 1);
if (!m->table8) { fprintf(stderr, "OOM cm\n"); exit(1); }
}
}
static void cm_free(ContextModel *m) {
if (m->tagged)
free(m->table16);
else
free(m->table8);
m->table16 = NULL;
}
/* ---- Mixer ---- */
typedef struct {
int32_t w[NUM_MODELS];
} MixerSlot;
#define MIX_W_SCALE 2048
static MixerSlot mixer[MIXER_SLOTS];
static MixerSlot mixer2[MIXER2_SLOTS];
static void mixer_init(void) {
int init_w = MIX_W_SCALE / (NUM_MODELS - 4);
for (int i = 0; i < MIXER_SLOTS; i++)
for (int j = 0; j < NUM_MODELS; j++)
mixer[i].w[j] = (j >= NUM_CM || j == 9 + NUM_SPARSE || j == 10 + NUM_SPARSE) ? 0 : init_w;
for (int i = 0; i < MIXER2_SLOTS; i++)
for (int j = 0; j < NUM_MODELS; j++)
mixer2[i].w[j] = (j >= NUM_CM || j == 9 + NUM_SPARSE || j == 10 + NUM_SPARSE) ? 0 : init_w;
}
/* ---- APM (Adaptive Probability Map) ---- */
typedef struct {
uint16_t *table;
int ctx_count;
int prob_bins;
} APM;
static APM isse1, isse2, isse3, isse4, isse5;
static void apm_init(APM *a, int ctx_bits, int prob_bits) {
a->ctx_count = 1 << ctx_bits;
a->prob_bins = 1 << prob_bits;
a->table = (uint16_t *)malloc((size_t)a->ctx_count * a->prob_bins * sizeof(uint16_t));
if (!a->table) { fprintf(stderr, "OOM apm\n"); exit(1); }
for (int c = 0; c < a->ctx_count; c++)
for (int p = 0; p < a->prob_bins; p++) {
int v = (int)((p + 0.5) / a->prob_bins * PROB_SCALE);
if (v < 1) v = 1;
if (v > PROB_SCALE - 1) v = PROB_SCALE - 1;
a->table[c * a->prob_bins + p] = (uint16_t)v;
}
}
static void apm_free(APM *a) { free(a->table); a->table = NULL; }
static inline uint16_t apm_predict(APM *a, int ctx, uint16_t prob) {
int scaled = (int)prob * (a->prob_bins - 1);
int bin = scaled / PROB_SCALE;
int frac = scaled % PROB_SCALE;
if (bin >= a->prob_bins - 1) { bin = a->prob_bins - 2; frac = PROB_SCALE - 1; }
int base = ctx * a->prob_bins;
uint32_t p0 = a->table[base + bin];
uint32_t p1 = a->table[base + bin + 1];
uint32_t p = (p0 * (PROB_SCALE - frac) + p1 * frac) / PROB_SCALE;
if (p < 1) p = 1;
if (p > PROB_SCALE - 1) p = PROB_SCALE - 1;
return (uint16_t)p;
}
static inline void apm_update_rate(APM *a, int ctx, uint16_t prob, int bit, int rate) {
int scaled = (int)prob * (a->prob_bins - 1);
int bin = scaled / PROB_SCALE;
if (bin >= a->prob_bins - 1) bin = a->prob_bins - 2;
int base = ctx * a->prob_bins;
int target = bit ? PROB_SCALE : 0;
for (int d = 0; d < 2; d++) {
int idx = base + bin + d;
int err = target - (int)a->table[idx];
a->table[idx] = (uint16_t)((int)a->table[idx] + (err >> rate));
if (a->table[idx] < 1) a->table[idx] = 1;
if (a->table[idx] > PROB_SCALE - 1) a->table[idx] = PROB_SCALE - 1;
}
}
/* ---- Match Model ---- */
#define MATCH_CHAIN_DEPTH 16
typedef struct {
uint32_t *pos_table; /* hash -> head of chain (position, 1-based) */
uint32_t *prev; /* prev[pos] = previous pos in chain with same hash */
uint32_t match_pos;
int match_len; /* backward context match length (bytes), then +1 per matching bit */
int match_active;
uint32_t rep[3];
int rep_count;
} MatchModel;
static MatchModel mmatch;
static void match_init(void) {
mmatch.pos_table = (uint32_t *)calloc(MATCH_TAB_SIZE, sizeof(uint32_t));
mmatch.prev = (uint32_t *)calloc(BLOCK_SIZE + 1, sizeof(uint32_t));
if (!mmatch.pos_table || !mmatch.prev) { fprintf(stderr, "OOM match\n"); exit(1); }
mmatch.match_pos = 0;
mmatch.match_len = 0;
mmatch.match_active = 0;
mmatch.rep[0] = mmatch.rep[1] = mmatch.rep[2] = 0;
mmatch.rep_count = 0;
}
static void match_free(void) {
free(mmatch.pos_table); mmatch.pos_table = NULL;
free(mmatch.prev); mmatch.prev = NULL;
}
/* ---- Indirect Context Model (ICM) ---- */
static uint8_t *icm_table; /* context hash -> counter index */
static uint16_t icm_ctr[ICM_NCTR]; /* adaptive probabilities */
static void icm_init(void) {
icm_table = (uint8_t *)calloc(ICM_TAB_SIZE, 1);
if (!icm_table) { fprintf(stderr, "OOM icm\n"); exit(1); }
for (int i = 0; i < ICM_NCTR; i++) icm_ctr[i] = PROB_HALF;
}
static void icm_free(void) { free(icm_table); icm_table = NULL; }
/* ---- Delta Model ---- */
static uint16_t *delta_table;
static void delta_init(void) {
delta_table = (uint16_t *)calloc(DELTA_TAB_SIZE, sizeof(uint16_t));
if (!delta_table) { fprintf(stderr, "OOM delta\n"); exit(1); }
}
static void delta_free(void) { free(delta_table); delta_table = NULL; }
/* ---- Stride/Record Model ---- */
static uint16_t *stride_table;
static void stride_init(void) {
stride_table = (uint16_t *)calloc(STRIDE_TAB_SIZE, sizeof(uint16_t));
if (!stride_table) { fprintf(stderr, "OOM stride\n"); exit(1); }
}
static void stride_free(void) { free(stride_table); stride_table = NULL; }
/* ---- LZP (Lempel-Ziv Prediction) Model ---- */
static uint16_t *lzp_table; /* tag(8) | predicted_byte(8) */
static void lzp_init(void) {
lzp_table = (uint16_t *)calloc(LZP_SIZE, sizeof(uint16_t));
if (!lzp_table) { fprintf(stderr, "OOM lzp\n"); exit(1); }
}
static void lzp_free(void) { free(lzp_table); lzp_table = NULL; }
static int detect_stride(const uint8_t *blk, uint32_t bl) {
int best_p = 0, best_score = 0;
uint32_t limit = bl < 65536 ? bl : 65536;
for (int p = 2; p <= MAX_STRIDE && (uint32_t)p < bl; p++) {
int score = 0;
for (uint32_t i = p; i < limit; i += 7)
if (blk[i] == blk[i - p]) score++;
if (score > best_score) { best_score = score; best_p = p; }
}
int random_expect = (int)(limit / 7) / 256;
return (best_score > random_expect * 4) ? best_p : 0;
}
/* ---- Word Predictor (Shadow Dictionary) ---- */
#define WPRED_BITS 18 /* 256K entries */
#define WPRED_SIZE (1u << WPRED_BITS)
#define WPRED_MAX_WORD 24
typedef struct {
uint16_t tag;
uint8_t len;
uint8_t word[WPRED_MAX_WORD]; /* lowercase predicted bytes */
} WPredEntry;
static WPredEntry *wpred_table; /* unigram: prev_word → next_word */
static WPredEntry *wpred_table2; /* bigram: (prev_prev + prev) → next_word */
static void wpred_init(void) {
wpred_table = (WPredEntry *)calloc(WPRED_SIZE, sizeof(WPredEntry));
wpred_table2 = (WPredEntry *)calloc(WPRED_SIZE, sizeof(WPredEntry));
if (!wpred_table || !wpred_table2) { fprintf(stderr, "OOM wpred\n"); exit(1); }
}
static void wpred_free(void) {
free(wpred_table); wpred_table = NULL;
free(wpred_table2); wpred_table2 = NULL;
}
/* ---- BCJ x86 Filter ---- */
static void bcj_encode(uint8_t *buf, uint32_t len) {
if (len < 5) return;
for (uint32_t i = 0; i + 4 < len; i++) {
if (buf[i] == 0xE8) {
uint32_t rel = (uint32_t)buf[i+1] | ((uint32_t)buf[i+2] << 8) |
((uint32_t)buf[i+3] << 16) | ((uint32_t)buf[i+4] << 24);
uint32_t abs_addr = rel + i + 5;
buf[i+1] = (uint8_t)(abs_addr);
buf[i+2] = (uint8_t)(abs_addr >> 8);
buf[i+3] = (uint8_t)(abs_addr >> 16);
buf[i+4] = (uint8_t)(abs_addr >> 24);
i += 4;
}
}
}
static void bcj_decode(uint8_t *buf, uint32_t len) {
if (len < 5) return;
for (uint32_t i = 0; i + 4 < len; i++) {
if (buf[i] == 0xE8) {
uint32_t abs_addr = (uint32_t)buf[i+1] | ((uint32_t)buf[i+2] << 8) |
((uint32_t)buf[i+3] << 16) | ((uint32_t)buf[i+4] << 24);
uint32_t rel = abs_addr - i - 5;
buf[i+1] = (uint8_t)(rel);
buf[i+2] = (uint8_t)(rel >> 8);
buf[i+3] = (uint8_t)(rel >> 16);
buf[i+4] = (uint8_t)(rel >> 24);
i += 4;
}
}
}
/* ---- BMP Vertical Delta Filter ---- */
static void bmp_delta_encode(uint8_t *buf, uint32_t len, int data_offset, int row_bytes) {
if (row_bytes <= 0 || data_offset < 0) return;
int num_rows = (len - data_offset) / row_bytes;
if (num_rows < 2) return;
/* Subtract row above, working backward to preserve source rows */
for (int y = num_rows - 1; y >= 1; y--) {
uint8_t *row = buf + data_offset + y * row_bytes;
uint8_t *prev = row - row_bytes;
for (int x = 0; x < row_bytes; x++)
row[x] -= prev[x];
}
}
static void bmp_delta_decode(uint8_t *buf, uint32_t len, int data_offset, int row_bytes) {
if (row_bytes <= 0 || data_offset < 0) return;
int num_rows = (len - data_offset) / row_bytes;
if (num_rows < 2) return;
/* Add row above, working forward */
for (int y = 1; y < num_rows; y++) {
uint8_t *row = buf + data_offset + y * row_bytes;
uint8_t *prev = row - row_bytes;
for (int x = 0; x < row_bytes; x++)
row[x] += prev[x];
}
}
/* Raw image delta filter — uses 16-bit arithmetic when stride is even,
* byte-level otherwise. 16-bit subtraction handles carry across byte
* boundaries correctly for 16-bit grayscale/depth images. */
static void raw_delta_encode(uint8_t *buf, uint32_t len, int row_bytes) {
int num_rows = (int)(len / row_bytes);
if (num_rows < 2) return;
int use16 = (row_bytes % 2 == 0);
for (int y = num_rows - 1; y >= 1; y--) {
uint8_t *row = buf + y * row_bytes;
uint8_t *prev = row - row_bytes;
if (use16) {
for (int x = 0; x < row_bytes; x += 2) {
uint16_t cur = (uint16_t)(row[x] | (row[x + 1] << 8));
uint16_t prv = (uint16_t)(prev[x] | (prev[x + 1] << 8));
uint16_t d = cur - prv;
row[x] = (uint8_t)d;
row[x + 1] = (uint8_t)(d >> 8);
}
} else {
for (int x = 0; x < row_bytes; x++)
row[x] -= prev[x];
}
}
}
static void raw_delta_decode(uint8_t *buf, uint32_t len, int row_bytes) {
int num_rows = (int)(len / row_bytes);
if (num_rows < 2) return;
int use16 = (row_bytes % 2 == 0);
for (int y = 1; y < num_rows; y++) {
uint8_t *row = buf + y * row_bytes;
uint8_t *prev = row - row_bytes;
if (use16) {
for (int x = 0; x < row_bytes; x += 2) {
uint16_t cur = (uint16_t)(row[x] | (row[x + 1] << 8));
uint16_t prv = (uint16_t)(prev[x] | (prev[x + 1] << 8));
uint16_t d = cur + prv;
row[x] = (uint8_t)d;
row[x + 1] = (uint8_t)(d >> 8);
}
} else {
for (int x = 0; x < row_bytes; x++)
row[x] += prev[x];
}
}
}
/* Detect raw image geometry by finding the row width that minimizes
* vertical byte differences. Returns row_bytes (>= 128) or 0 if not an image. */
static int detect_image_geometry(const uint8_t *buf, uint32_t len) {
if (len < 65536) return 0;
uint32_t sample = len < 262144 ? len : 262144;
/* Baseline: average |buf[i] - buf[i-1]| */
int64_t base_diff = 0;
int base_n = 0;
for (uint32_t i = 1; i < sample; i += 7) {
base_diff += abs((int)buf[i] - (int)buf[i - 1]);
base_n++;
}
if (base_n == 0) return 0;
int64_t base_avg = base_diff / base_n;
if (base_avg < 8) return 0; /* data already very smooth */
int best_w = 0;
int64_t best_avg = base_avg;
/* Test candidate widths: multiples of 4 from 128 to 16384 */
for (int w = 128; w <= 16384 && (uint32_t)w < sample / 4; w += 4) {
int64_t diff = 0;
int n = 0;
for (uint32_t i = (uint32_t)w; i < sample; i += 31) {
diff += abs((int)buf[i] - (int)buf[i - w]);
n++;
}
if (n == 0) continue;
int64_t avg = diff / n;
if (avg < best_avg) {
best_avg = avg;
best_w = w;
}
}
/* Accept only if vertical diff is dramatically lower (< 50% of horizontal) */
if (best_w > 0 && best_avg * 2 < base_avg)
return best_w;
return 0;
}
/* Scan for "data" sub-chunk in RIFF/WAVE, return offset of audio data or -1 */
static int wav_find_data(const uint8_t *buf, uint32_t len) {
if (len < 44) return -1;
uint32_t off = 12; /* skip "RIFF" + size + "WAVE" */
while (off + 8 <= len) {
uint32_t chunk_size = buf[off+4] | (buf[off+5]<<8) | (buf[off+6]<<16) | (buf[off+7]<<24);
if (buf[off]=='d' && buf[off+1]=='a' && buf[off+2]=='t' && buf[off+3]=='a')
return (int)(off + 8);
off += 8 + ((chunk_size + 1) & ~1); /* chunks are word-aligned */
}
return -1;
}
/* ---- WAV Per-Channel Delta Filter ---- */
static void wav_delta_encode(uint8_t *buf, uint32_t len, int data_offset, int num_channels) {
if (num_channels < 1 || data_offset < 0 || (uint32_t)data_offset >= len) return;
int total_samples = (len - data_offset) / 2;
if (total_samples <= num_channels) return;
int16_t *samples = (int16_t *)(buf + data_offset);
for (int i = total_samples - 1; i >= num_channels; i--)
samples[i] -= samples[i - num_channels];
}
static void wav_delta_decode(uint8_t *buf, uint32_t len, int data_offset, int num_channels) {
if (num_channels < 1 || data_offset < 0 || (uint32_t)data_offset >= len) return;
int total_samples = (len - data_offset) / 2;
if (total_samples <= num_channels) return;
int16_t *samples = (int16_t *)(buf + data_offset);
for (int i = num_channels; i < total_samples; i++)
samples[i] += samples[i - num_channels];
}
/* ---- MTF Word Cache Pre-filter ---- */
#define MTF_CACHE_SIZE 128
#define MTF_MIN_WORD 3
#define MTF_MAX_WORD 63
typedef struct {
uint8_t words[MTF_CACHE_SIZE][MTF_MAX_WORD + 1];
int lens[MTF_CACHE_SIZE];
int count;
} MTFCache;
static void mtf_init(MTFCache *c) { c->count = 0; }
static int mtf_find(MTFCache *c, const uint8_t *word, int len) {
for (int i = 0; i < c->count; i++)
if (c->lens[i] == len && memcmp(c->words[i], word, len) == 0)
return i;
return -1;
}
static void mtf_promote(MTFCache *c, int idx) {
if (idx == 0) return;
uint8_t tmp[MTF_MAX_WORD + 1];
int tmp_len = c->lens[idx];
memcpy(tmp, c->words[idx], tmp_len);
memmove(&c->words[1], &c->words[0], idx * sizeof(c->words[0]));
memmove(&c->lens[1], &c->lens[0], idx * sizeof(c->lens[0]));
memcpy(c->words[0], tmp, tmp_len);
c->lens[0] = tmp_len;
}
static void mtf_insert(MTFCache *c, const uint8_t *word, int len) {
if (c->count < MTF_CACHE_SIZE) c->count++;
memmove(&c->words[1], &c->words[0], (c->count - 1) * sizeof(c->words[0]));
memmove(&c->lens[1], &c->lens[0], (c->count - 1) * sizeof(c->lens[0]));
memcpy(c->words[0], word, len);
c->lens[0] = len;
}
static inline int is_word_char(uint8_t c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '_';
}
/* 0=mixed, 1=all lower, 2=title (first upper rest lower), 3=all upper */
static int detect_word_case(const uint8_t *w, int len) {
int has_upper = 0, has_lower = 0, first_upper = 0;
int upper_after_first = 0;
for (int i = 0; i < len; i++) {
if (w[i] >= 'A' && w[i] <= 'Z') {
has_upper = 1;
if (i == 0) first_upper = 1;
else upper_after_first = 1;
}
if (w[i] >= 'a' && w[i] <= 'z') has_lower = 1;
}
if (!has_upper) return 1; /* all lower */
if (!has_lower) return 3; /* all upper */
if (first_upper && !upper_after_first) return 2; /* title */
return 0; /* mixed */
}
static void to_lower(const uint8_t *src, uint8_t *dst, int len) {
for (int i = 0; i < len; i++)
dst[i] = (src[i] >= 'A' && src[i] <= 'Z') ? (src[i] + 32) : src[i];
}
static uint32_t text_mtf_encode(const uint8_t *in, uint32_t in_len,
uint8_t *out, uint32_t out_cap) {
MTFCache cache;
mtf_init(&cache);
uint32_t ip = 0, op = 0;
uint8_t lower_buf[MTF_MAX_WORD + 1];
while (ip < in_len) {
/* Check for literal escape of 0x01-0x03 */
if (in[ip] >= 0x01 && in[ip] <= 0x03) {
if (op + 2 > out_cap) break;
out[op++] = in[ip];
out[op++] = 0x80;
ip++;
continue;
}
/* Not a word char — copy literally */
if (!is_word_char(in[ip])) {
if (op + 1 > out_cap) break;
out[op++] = in[ip++];
continue;
}
/* Accumulate word */
uint32_t wstart = ip;
while (ip < in_len && is_word_char(in[ip]) && (int)(ip - wstart) < MTF_MAX_WORD)
ip++;
int wlen = (int)(ip - wstart);
if (wlen < MTF_MIN_WORD) {
/* Too short — emit literally */
if (op + (uint32_t)wlen > out_cap) break;
memcpy(out + op, in + wstart, wlen);
op += wlen;
continue;
}
int wcase = detect_word_case(in + wstart, wlen);
if (wcase == 0) {
/* Mixed case — emit literally, do NOT update cache */
if (op + (uint32_t)wlen > out_cap) break;
memcpy(out + op, in + wstart, wlen);
op += wlen;
continue;
}
/* Lowercase for cache lookup */
to_lower(in + wstart, lower_buf, wlen);
int idx = mtf_find(&cache, lower_buf, wlen);
if (idx >= 0) {
/* Cache hit — emit reference */
if (op + 2 > out_cap) break;
out[op++] = (uint8_t)wcase; /* 1=lower, 2=title, 3=upper */
out[op++] = (uint8_t)idx;
mtf_promote(&cache, idx);
} else {
/* Cache miss — emit literally, insert */
if (op + (uint32_t)wlen > out_cap) break;
memcpy(out + op, in + wstart, wlen);
op += wlen;
mtf_insert(&cache, lower_buf, wlen);
}
}
return op;
}
static uint32_t text_mtf_decode(const uint8_t *in, uint32_t in_len,
uint8_t *out, uint32_t out_cap) {
MTFCache cache;
mtf_init(&cache);
uint32_t ip = 0, op = 0;
uint8_t lower_buf[MTF_MAX_WORD + 1];
while (ip < in_len) {
/* Check for escape bytes */
if (in[ip] >= 0x01 && in[ip] <= 0x03) {
if (ip + 1 >= in_len) break;
uint8_t esc = in[ip];
uint8_t next = in[ip + 1];
if (next == 0x80) {
/* Literal escape */
if (op + 1 > out_cap) break;
out[op++] = esc;
ip += 2;
continue;
}
/* Word reference */
int idx = (int)next;
if (idx >= cache.count) break; /* invalid ref */
int wlen = cache.lens[idx];
if (op + (uint32_t)wlen > out_cap) break;
/* Copy word with case applied */
const uint8_t *w = cache.words[idx];
if (esc == 1) {
/* lowercase */
memcpy(out + op, w, wlen);
} else if (esc == 2) {
/* title case */
out[op] = (w[0] >= 'a' && w[0] <= 'z') ? (w[0] - 32) : w[0];
if (wlen > 1) memcpy(out + op + 1, w + 1, wlen - 1);
} else {
/* all upper */
for (int j = 0; j < wlen; j++)
out[op + j] = (w[j] >= 'a' && w[j] <= 'z') ? (w[j] - 32) : w[j];
}
op += wlen;
mtf_promote(&cache, idx);
ip += 2;
continue;
}
/* Not a word char — copy literally */
if (!is_word_char(in[ip])) {
if (op + 1 > out_cap) break;
out[op++] = in[ip++];
continue;
}
/* Accumulate literal word */
uint32_t wstart = ip;
uint32_t ostart = op;
while (ip < in_len && is_word_char(in[ip]) && (int)(ip - wstart) < MTF_MAX_WORD) {
if (op + 1 > out_cap) break;
out[op++] = in[ip++];
}
int wlen = (int)(ip - wstart);
if (wlen >= MTF_MIN_WORD) {
/* Insert into cache only if word has valid case (not mixed) —
* must mirror the encoder, which skips mixed-case words */
int wcase = detect_word_case(out + ostart, wlen);
if (wcase != 0) {
to_lower(out + ostart, lower_buf, wlen);
if (mtf_find(&cache, lower_buf, wlen) < 0)
mtf_insert(&cache, lower_buf, wlen);
}
}
}
return op;
}
/* ---- Binary rANS ---- */
static inline uint32_t rans_enc_bit(uint32_t r, uint8_t **p, int bit, uint16_t prob) {
uint16_t f = bit ? prob : (PROB_SCALE - prob);
uint32_t xm = ((RANS_L >> PROB_BITS) << 8) * f;
while (r >= xm) { *(--(*p)) = (uint8_t)(r & 0xFF); r >>= 8; }
if (bit)
return ((r / f) << PROB_BITS) + (r % f) + (PROB_SCALE - prob);
else
return ((r / f) << PROB_BITS) + (r % f);
}
static inline void rans_flush(uint32_t r, uint8_t **p) {
*(--(*p)) = (uint8_t)(r >> 24);
*(--(*p)) = (uint8_t)(r >> 16);
*(--(*p)) = (uint8_t)(r >> 8);
*(--(*p)) = (uint8_t)(r);
}
static inline uint32_t rans_dec_init(const uint8_t **p) {
uint32_t r = (uint32_t)(*(*p)++);
r |= (uint32_t)(*(*p)++) << 8;
r |= (uint32_t)(*(*p)++) << 16;
r |= (uint32_t)(*(*p)++) << 24;
return r;
}
static inline int rans_dec_bit(uint32_t *r, const uint8_t **p, uint16_t prob) {
uint32_t x = *r;
uint32_t cumfreq = x & (PROB_SCALE - 1);
int bit;
uint16_t f;
if (cumfreq >= (uint32_t)(PROB_SCALE - prob)) {
bit = 1; f = prob;
x = f * (x >> PROB_BITS) + cumfreq - (PROB_SCALE - prob);
} else {
bit = 0; f = PROB_SCALE - prob;
x = f * (x >> PROB_BITS) + cumfreq;
}
while (x < RANS_L) x = (x << 8) | (uint32_t)(*(*p)++);
*r = x;
return bit;
}
/* ---- Event Buffer ---- */
static uint16_t *ev_buf;
static int32_t ev_cnt;
static inline void ev_emit(int bit, uint16_t prob) {
ev_buf[ev_cnt++] = (uint16_t)((bit << 15) | prob);
}
/* ---- Context Hashing ---- */
static inline uint32_t hmix(uint32_t h, uint32_t b) {
return (h + b + 1) * 2654435761u;
}
/* Finalize hash to reduce clustering */
static inline uint32_t hfin(uint32_t h) {
h ^= h >> 16;
h *= 0x45d9f3bu;
return h;
}
/* ---- File I/O ---- */
static void wr32(FILE *f, uint32_t v) {
uint8_t b[4] = {v, v>>8, v>>16, v>>24};
fwrite(b, 1, 4, f);
}
static uint32_t rd32(FILE *f) {
uint8_t b[4]; fread(b, 1, 4, f);
return (uint32_t)b[0]|((uint32_t)b[1]<<8)|((uint32_t)b[2]<<16)|((uint32_t)b[3]<<24);
}
/* ---- Shared Modeling Logic ---- */
static void process_block(uint8_t *blk, uint32_t bl, int mode,
uint32_t *rs, const uint8_t **dec_ptr, int32_t *ev_idx_p,
int stride, int force_text) {
/* Don't reset context model tables — let them learn across blocks */
match_init();
/* Text mode is determined at file level and stored in the header (FLAG_TEXT),
* ensuring encoder and decoder agree. Block-level detection was unreliable
* because the decoder's buffer starts as zeros before decoding. */
int is_text_block = force_text;
/* Text blocks have no meaningful stride — the detector gives false positives
* due to non-uniform byte distribution (spaces, common letters). */
if (is_text_block) stride = 0;
/* Deep match chain for text: literature has long-range repetitions */
int chain_depth = is_text_block ? 512 : MATCH_CHAIN_DEPTH;
/* Previous byte history for context building */
uint8_t pb[16] = {0}; /* pb[0]=prev, pb[1]=prev2, ... pb[15]=prev16 */
uint32_t word_hash = 0; /* rolling hash of current word */
uint32_t prev_word_hash = 0; /* hash of last completed word */
uint32_t prev_prev_word_hash = 0; /* hash of word before last completed word */
int word_pos = 0; /* character index within current word */
int32_t is_text = 0; /* text/binary detector: positive = text, negative = binary */
/* Word predictor state (shadow dictionary) */
uint8_t wpred_word[WPRED_MAX_WORD]; /* predicted next word (lowercase) */
int wpred_len = 0; /* length of predicted word */
int wpred_pos = 0; /* current char index within prediction */
int wpred_active = 0; /* whether prediction is active */
int wpred_was_active = 0; /* was prediction active at start of this word? */
int wpred_from_bigram = 0; /* was current prediction from bigram table? */
uint8_t cur_word_lc[WPRED_MAX_WORD]; /* current word accumulator (lowercase) */
int cur_word_len = 0;
/* wpred diagnostic counters (only used with --profile) */
uint32_t wp_lookups = 0, wp_bigram_hit = 0, wp_unigram_hit = 0, wp_miss = 0;
uint32_t wp_bigram_collision = 0, wp_unigram_collision = 0;
uint32_t wp_word_correct = 0, wp_word_partial = 0, wp_word_wrong = 0;
uint32_t wp_bi_correct = 0, wp_bi_partial = 0, wp_bi_wrong = 0;
uint32_t wp_uni_correct = 0, wp_uni_partial = 0, wp_uni_wrong = 0;
if (mode == 0) ev_cnt = 0;
for (uint32_t i = 0; i < bl; i++) {
/* Build context hashes from previous bytes */
uint32_t ctx[NUM_CM];
ctx[0] = 0; /* order-0: just bit_ctx, no byte context */
ctx[1] = hfin(hmix(0, pb[0])); /* order-1 */
ctx[2] = hfin(hmix(hmix(0, pb[1]), pb[0])); /* order-2 */
ctx[3] = hfin(hmix(hmix(hmix(0, pb[2]), pb[1]), pb[0])); /* order-3 */
ctx[4] = hfin(hmix(hmix(hmix(hmix(0, pb[3]), pb[2]), pb[1]), pb[0])); /* order-4 */