-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvcomp_prototype.py
More file actions
5656 lines (4990 loc) · 203 KB
/
Copy pathvcomp_prototype.py
File metadata and controls
5656 lines (4990 loc) · 203 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
#!/usr/bin/env python3
"""
VCOMP prototype: multilevel lossless compressor with dynamic level-4 labels.
This is an engineering prototype (not "universal eternal compression").
It guarantees lossless roundtrip and uses data-dependent payload strategies.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import mmap
import random
import sqlite3
import struct
import sys
import tempfile
import uuid
import zlib
from concurrent.futures import ProcessPoolExecutor
from collections import deque
from array import array
from datetime import datetime, timezone
from pathlib import Path
MAGIC_V1 = b"VCOMP001" # old format, no metadata block
MAGIC_V2 = b"VCOMP002" # current format, metadata block
HEADER_V1_FMT = "<8sBQQ16s" # magic, mode, original_size, payload_size, checksum16
HEADER_V2_FMT = "<8sBQQI16s" # + metadata_size (u32)
HEADER_V1_SIZE = struct.calcsize(HEADER_V1_FMT)
HEADER_V2_SIZE = struct.calcsize(HEADER_V2_FMT)
CHECKSUM_OFFSET_V1 = struct.calcsize("<8sBQQ")
CHECKSUM_OFFSET_V2 = struct.calcsize("<8sBQQI")
# Payload modes
MODE_RAW_L4 = 0
MODE_ZLIB_RAW_L4 = 1
MODE_DICT_BITPACK = 2
MODE_ZLIB_DICT_BITPACK = 3
MODE_GLOBAL_DICT = 4
MODE_ZGLOBAL_DICT = 5
MODE_GLOBAL_DICT_MANIFEST = 6
MODE_ZGLOBAL_DICT_MANIFEST = 7
MODE_RANS_RAW_L4 = 8
MODE_RANS_DICT_BITPACK = 9
MODE_RANS_GLOBAL_DICT = 10
MODE_RANS_GLOBAL_DICT_MANIFEST = 11
MODE_RANS_BPE = 12
MODE_RANS_BPE_GLOBAL_DICT = 13
MODE_RANS_BPE_GLOBAL_DICT_MANIFEST = 14
MODE_NAME_TO_ID = {
"raw": MODE_RAW_L4,
"zraw": MODE_ZLIB_RAW_L4,
"dict": MODE_DICT_BITPACK,
"zdict": MODE_ZLIB_DICT_BITPACK,
"gdict": MODE_GLOBAL_DICT,
"zgdict": MODE_ZGLOBAL_DICT,
"gdictm": MODE_GLOBAL_DICT_MANIFEST,
"zgdictm": MODE_ZGLOBAL_DICT_MANIFEST,
"ansraw": MODE_RANS_RAW_L4,
"ansdict": MODE_RANS_DICT_BITPACK,
"ansgdict": MODE_RANS_GLOBAL_DICT,
"ansgdictm": MODE_RANS_GLOBAL_DICT_MANIFEST,
"ansbpe": MODE_RANS_BPE,
"ansbpegdict": MODE_RANS_BPE_GLOBAL_DICT,
"ansbpegdictm": MODE_RANS_BPE_GLOBAL_DICT_MANIFEST,
}
MODE_ID_TO_NAME = {v: k for k, v in MODE_NAME_TO_ID.items()}
GLOBAL_DICT_SCHEMA_VERSION = 1
RANS_SCALE_BITS = 12
RANS_TOTAL_FREQ = 1 << RANS_SCALE_BITS
RANS_L = 1 << 23
RANS_FRAME_MAGIC = b"RANSBLK1"
RANS_FRAME_HEADER_FMT = "<8sI"
RANS_FRAME_BLOCK_FMT = "<II"
RANS_FRAME_HEADER_SIZE = struct.calcsize(RANS_FRAME_HEADER_FMT)
RANS_FRAME_BLOCK_SIZE = struct.calcsize(RANS_FRAME_BLOCK_FMT)
RANS_DEFAULT_BLOCK_BYTES = 1 << 20
BPE_PAYLOAD_HEADER_FMT = "<IIIBI"
BPE_PAYLOAD_HEADER_SIZE = struct.calcsize(BPE_PAYLOAD_HEADER_FMT)
BPE_MAX_MERGES = 128
BPE_MIN_PAIR_COUNT = 4
BPE_GDICTM_PAYLOAD_HEADER_FMT = "<II"
BPE_GDICTM_PAYLOAD_HEADER_SIZE = struct.calcsize(BPE_GDICTM_PAYLOAD_HEADER_FMT)
GLOBAL_BPE_SEED_LIMIT = 64
GLOBAL_BPE_LEARN_LIMIT = 128
GLOBAL_BPE_PAIR_LIMIT = 8192
GLOBAL_BPE_VOCAB_LIMIT = 1024
def level_counts(original_size: int) -> tuple[int, int, int, int, int]:
"""
Returns (n0, n1, n2, n3, n4) symbol counts for levels 0..4.
"""
n0 = original_size * 4 # 2-bit symbols
n1 = n0 // 2
n2 = n1 // 2
n3 = (n2 + 1) // 2 # 16-bit symbols
n4 = (n3 + 1) // 2 # 32-bit symbols
return n0, n1, n2, n3, n4
def mode_name(mode_id: int) -> str:
return MODE_ID_TO_NAME.get(mode_id, f"unknown({mode_id})")
def serialize_metadata(metadata: dict | None) -> bytes:
if metadata is None:
metadata = {}
return json.dumps(metadata, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
def deserialize_metadata(blob: bytes) -> dict:
if not blob:
return {}
try:
obj = json.loads(blob.decode("utf-8"))
return obj if isinstance(obj, dict) else {}
except Exception:
return {}
def detect_image_dimensions(path: Path) -> tuple[str, int, int] | None:
try:
with path.open("rb") as f:
sig = f.read(32)
if sig.startswith(b"\x89PNG\r\n\x1a\n") and len(sig) >= 24:
w = struct.unpack(">I", sig[16:20])[0]
h = struct.unpack(">I", sig[20:24])[0]
return ("png", w, h)
if sig.startswith((b"GIF87a", b"GIF89a")) and len(sig) >= 10:
w = struct.unpack("<H", sig[6:8])[0]
h = struct.unpack("<H", sig[8:10])[0]
return ("gif", w, h)
if sig.startswith(b"BM"):
if len(sig) < 26:
f.seek(0)
sig = f.read(64)
if len(sig) >= 26:
w = struct.unpack("<I", sig[18:22])[0]
h_signed = struct.unpack("<i", sig[22:26])[0]
return ("bmp", w, abs(h_signed))
f.seek(0)
if f.read(2) == b"\xFF\xD8":
sof_markers = {
0xC0, 0xC1, 0xC2, 0xC3,
0xC5, 0xC6, 0xC7,
0xC9, 0xCA, 0xCB,
0xCD, 0xCE, 0xCF,
}
while True:
marker_prefix = f.read(1)
if not marker_prefix:
break
if marker_prefix != b"\xFF":
continue
marker = f.read(1)
while marker == b"\xFF":
marker = f.read(1)
if not marker:
break
m = marker[0]
if m in (0xD8, 0xD9) or (0xD0 <= m <= 0xD7) or m == 0x01:
continue
seg_len_bytes = f.read(2)
if len(seg_len_bytes) != 2:
break
seg_len = struct.unpack(">H", seg_len_bytes)[0]
if seg_len < 2:
break
if m in sof_markers:
seg = f.read(seg_len - 2)
if len(seg) >= 5:
h = struct.unpack(">H", seg[1:3])[0]
w = struct.unpack(">H", seg[3:5])[0]
return ("jpeg", w, h)
break
f.seek(seg_len - 2, 1)
except Exception:
return None
return None
def build_source_metadata(input_path: Path, original_size: int) -> dict:
meta = {
"source_name": input_path.name,
"source_ext": input_path.suffix.lower(),
"source_size": int(original_size),
}
img = detect_image_dimensions(input_path)
if img is not None:
fmt, w, h = img
meta["image"] = {"format": fmt, "width": int(w), "height": int(h)}
return meta
def pair_symbols(seq: list[int], base: int) -> list[int]:
out: list[int] = []
n = len(seq)
i = 0
while i < n:
a = seq[i]
b = seq[i + 1] if i + 1 < n else 0
out.append(a * base + b)
i += 2
return out
def unpair_symbols(seq: list[int], base: int, target_len: int) -> list[int]:
out: list[int] = []
out_extend = out.extend
for value in seq:
a = value // base
b = value % base
out_extend((a, b))
if len(out) > target_len:
out = out[:target_len]
return out
def build_level4_labels(data: bytes) -> list[int]:
"""
L2 (bytes) -> L3 (u16-like) -> L4 (u32-like).
L0/L1 are implied by this reversible chain.
"""
level2 = list(data)
level3 = pair_symbols(level2, 256)
level4 = pair_symbols(level3, 65536)
return level4
def restore_bytes_from_level4(level4: list[int], original_size: int) -> bytes:
_, _, n2, n3, _ = level_counts(original_size)
level3 = unpair_symbols(level4, 65536, n3)
level2 = unpair_symbols(level3, 256, n2)
return bytes(level2)
def pack_u32_list(values: list[int]) -> bytes:
arr = array("I", values)
if sys.byteorder != "little":
arr.byteswap()
return arr.tobytes()
def unpack_u32_list(blob: bytes) -> list[int]:
if len(blob) % 4 != 0:
raise ValueError("Invalid u32 blob length")
arr = array("I")
arr.frombytes(blob)
if sys.byteorder != "little":
arr.byteswap()
return arr.tolist()
def pack_u32_array(values: array) -> bytes:
if values.typecode != "I":
raise ValueError("Expected array('I')")
if sys.byteorder == "little":
return values.tobytes()
tmp = array("I", values)
tmp.byteswap()
return tmp.tobytes()
def bits_required(num_values: int) -> int:
if num_values <= 1:
return 1
return (num_values - 1).bit_length()
def bitpack(values: list[int], bit_width: int) -> bytes:
if not (1 <= bit_width <= 32):
raise ValueError(f"Invalid bit width: {bit_width}")
out = bytearray()
buf = 0
bits = 0
mask = (1 << bit_width) - 1
for v in values:
buf |= (v & mask) << bits
bits += bit_width
while bits >= 8:
out.append(buf & 0xFF)
buf >>= 8
bits -= 8
if bits:
out.append(buf & 0xFF)
return bytes(out)
def bitunpack(blob: bytes, count: int, bit_width: int) -> list[int]:
if not (1 <= bit_width <= 32):
raise ValueError(f"Invalid bit width: {bit_width}")
out: list[int] = []
buf = 0
bits = 0
mask = (1 << bit_width) - 1
for b in blob:
buf |= b << bits
bits += 8
while bits >= bit_width and len(out) < count:
out.append(buf & mask)
buf >>= bit_width
bits -= bit_width
if len(out) != count:
raise ValueError("Bit-unpack failed: not enough data")
return out
def bitpack_u32_file_to_writer(
idx_file,
index_count: int,
bit_width: int,
write_bytes,
chunk_words: int = 1 << 16,
) -> int:
"""
Stream-pack u32 indices from file into fixed-width bitstream.
Returns bytes written.
"""
if not (1 <= bit_width <= 32):
raise ValueError(f"Invalid bit width: {bit_width}")
idx_file.seek(0)
total_written = 0
produced = 0
bitbuf = 0
bits = 0
mask = (1 << bit_width) - 1
out = bytearray()
while produced < index_count:
need = min(chunk_words, index_count - produced)
raw = idx_file.read(need * 4)
if len(raw) != need * 4:
raise ValueError("Corrupted temporary index stream")
arr = array("I")
arr.frombytes(raw)
if sys.byteorder != "little":
arr.byteswap()
for v in arr:
bitbuf |= (v & mask) << bits
bits += bit_width
while bits >= 8:
out.append(bitbuf & 0xFF)
bitbuf >>= 8
bits -= 8
if len(out) >= (1 << 20):
write_bytes(out)
total_written += len(out)
out.clear()
produced += len(arr)
if bits:
out.append(bitbuf & 0xFF)
if out:
write_bytes(out)
total_written += len(out)
return total_written
def _read_exact(stream, size: int) -> bytes:
data = stream.read(size)
if len(data) != size:
raise ValueError("Unexpected end of stream")
return data
def _pack_big_endian_u32_chunk(chunk: bytes) -> bytes:
"""
Convert 4-byte aligned input chunk into little-endian u32 payload bytes,
where each u32 is interpreted from big-endian source order.
"""
if len(chunk) % 4 != 0:
raise ValueError("Chunk must be aligned to 4 bytes")
arr = array("I", (word[0] for word in struct.iter_unpack(">I", chunk)))
if sys.byteorder != "little":
arr.byteswap()
return arr.tobytes()
def _iter_l4_raw_chunks(input_stream, chunk_size: int, workers: int, hasher):
"""
Yield tuples: (raw_l4_bytes_le, l4_word_count) in strict input order.
raw_l4_bytes_le is a contiguous little-endian u32 stream.
"""
workers = max(1, int(workers))
if workers == 1:
encoder = L4EncoderState()
while True:
chunk = input_stream.read(chunk_size)
if not chunk:
break
hasher.update(chunk)
words = encoder.feed(chunk)
if words:
yield pack_u32_array(words), len(words)
tail_words = encoder.finalize()
if tail_words:
yield pack_u32_array(tail_words), len(tail_words)
return
if chunk_size < 4:
raise ValueError("For workers>1 chunk_size must be >= 4")
pending = deque()
carry = b""
max_pending = max(2, workers * 2)
with ProcessPoolExecutor(max_workers=workers) as pool:
while True:
chunk = input_stream.read(chunk_size)
if not chunk:
break
hasher.update(chunk)
buf = carry + chunk
aligned = (len(buf) // 4) * 4
if aligned:
piece = bytes(buf[:aligned])
future = pool.submit(_pack_big_endian_u32_chunk, piece)
pending.append((future, aligned // 4))
carry = buf[aligned:]
else:
carry = buf
while len(pending) >= max_pending:
fut, words_cnt = pending.popleft()
yield fut.result(), words_cnt
if carry:
pad = carry + b"\x00" * (4 - len(carry))
future = pool.submit(_pack_big_endian_u32_chunk, pad)
pending.append((future, 1))
while pending:
fut, words_cnt = pending.popleft()
yield fut.result(), words_cnt
def encode_dict_bitpack(level4: list[int]) -> bytes:
"""
Encode level4 labels using:
- dynamic dictionary (only seen labels)
- minimal-bit packed index stream
"""
dictionary: list[int] = []
lookup: dict[int, int] = {}
indices: list[int] = []
for label in level4:
idx = lookup.get(label)
if idx is None:
idx = len(dictionary)
lookup[label] = idx
dictionary.append(label)
indices.append(idx)
dict_count = len(dictionary)
bit_width = bits_required(dict_count)
packed_idx = bitpack(indices, bit_width)
dict_blob = pack_u32_list(dictionary)
# <I B I I> dict_count, bit_width, index_count, packed_size
head = struct.pack("<IBII", dict_count, bit_width, len(indices), len(packed_idx))
return head + dict_blob + packed_idx
def decode_dict_bitpack(blob: bytes) -> list[int]:
head_size = struct.calcsize("<IBII")
if len(blob) < head_size:
raise ValueError("Invalid dict-bitpack payload (too short)")
dict_count, bit_width, index_count, packed_size = struct.unpack("<IBII", blob[:head_size])
if not (1 <= bit_width <= 32):
raise ValueError("Invalid dict-bitpack payload (bad bit width)")
if dict_count == 0 and index_count > 0:
raise ValueError("Invalid dict-bitpack payload (empty dict with non-empty index stream)")
pos = head_size
dict_bytes = dict_count * 4
if len(blob) != pos + dict_bytes + packed_size:
raise ValueError("Invalid dict-bitpack payload (size mismatch)")
dictionary = unpack_u32_list(blob[pos : pos + dict_bytes])
pos += dict_bytes
packed_idx = blob[pos : pos + packed_size]
indices = bitunpack(packed_idx, index_count, bit_width)
try:
return [dictionary[i] for i in indices]
except IndexError as exc:
raise ValueError("Corrupted index stream: dictionary index out of range") from exc
def decode_global_manifest_bitpack(blob: bytes) -> list[int]:
head_size = struct.calcsize("<III")
if len(blob) < head_size:
raise ValueError("Invalid global-manifest payload (too short)")
manifest_count, index_count, packed_size = struct.unpack("<III", blob[:head_size])
pos = head_size
manifest_bytes = manifest_count * 8
if len(blob) != pos + manifest_bytes + packed_size:
raise ValueError("Invalid global-manifest payload (size mismatch)")
manifest: dict[int, int] = {}
max_gid = 0
end_manifest = pos + manifest_bytes
while pos < end_manifest:
gid, label = struct.unpack("<II", blob[pos : pos + 8])
if gid in manifest:
raise ValueError("Invalid global-manifest payload (duplicate gid)")
manifest[int(gid)] = int(label)
if gid > max_gid:
max_gid = int(gid)
pos += 8
if not manifest and index_count > 0:
raise ValueError("Invalid global-manifest payload (empty manifest with non-empty index stream)")
bit_width = max(1, max_gid.bit_length())
expected_packed_size = (index_count * bit_width + 7) // 8
if packed_size != expected_packed_size:
raise ValueError("Invalid global-manifest payload (packed size mismatch)")
gids = bitunpack(blob[pos : pos + packed_size], index_count, bit_width)
try:
return [manifest[int(gid)] for gid in gids]
except KeyError as exc:
raise ValueError("Corrupted global-manifest payload: gid missing from manifest") from exc
def _build_rans_frequencies(data: bytes) -> tuple[dict[int, int], dict[int, int]]:
counts = [0] * 256
for b in data:
counts[b] += 1
nonzero = [(sym, cnt) for sym, cnt in enumerate(counts) if cnt > 0]
if not nonzero:
return {}, {}
if len(nonzero) == 1:
sym = nonzero[0][0]
return {sym: RANS_TOTAL_FREQ}, {sym: 0}
total = len(data)
freqs: dict[int, int] = {}
for sym, cnt in nonzero:
freq = (cnt * RANS_TOTAL_FREQ) // total
if freq <= 0:
freq = 1
freqs[sym] = int(freq)
freq_sum = sum(freqs.values())
if freq_sum < RANS_TOTAL_FREQ:
best_sym = max(nonzero, key=lambda item: (item[1], -item[0]))[0]
freqs[best_sym] += RANS_TOTAL_FREQ - freq_sum
elif freq_sum > RANS_TOTAL_FREQ:
overflow = freq_sum - RANS_TOTAL_FREQ
for sym, _ in sorted(nonzero, key=lambda item: (-freqs[item[0]], item[0])):
if overflow <= 0:
break
removable = min(overflow, freqs[sym] - 1)
if removable > 0:
freqs[sym] -= removable
overflow -= removable
if overflow != 0:
raise ValueError("Failed to normalize rANS frequencies")
starts: dict[int, int] = {}
cum = 0
for sym in sorted(freqs):
starts[sym] = cum
cum += freqs[sym]
if cum != RANS_TOTAL_FREQ:
raise ValueError("Invalid rANS normalization total")
return freqs, starts
def _iter_file_bytes_reversed(path: Path, chunk_size: int = 1 << 20):
with path.open("rb") as f:
pos = path.stat().st_size
while pos > 0:
take = min(chunk_size, pos)
pos -= take
f.seek(pos)
chunk = f.read(take)
for b in reversed(chunk):
yield b
def _build_rans_frequencies_from_file(path: Path, chunk_size: int = 1 << 20) -> tuple[int, dict[int, int], dict[int, int]]:
counts = [0] * 256
total = 0
with path.open("rb") as f:
while True:
chunk = f.read(chunk_size)
if not chunk:
break
total += len(chunk)
for b in chunk:
counts[b] += 1
nonzero = [(sym, cnt) for sym, cnt in enumerate(counts) if cnt > 0]
if not nonzero:
return total, {}, {}
if len(nonzero) == 1:
sym = nonzero[0][0]
return total, {sym: RANS_TOTAL_FREQ}, {sym: 0}
freqs: dict[int, int] = {}
for sym, cnt in nonzero:
freq = (cnt * RANS_TOTAL_FREQ) // total
if freq <= 0:
freq = 1
freqs[sym] = int(freq)
freq_sum = sum(freqs.values())
if freq_sum < RANS_TOTAL_FREQ:
best_sym = max(nonzero, key=lambda item: (item[1], -item[0]))[0]
freqs[best_sym] += RANS_TOTAL_FREQ - freq_sum
elif freq_sum > RANS_TOTAL_FREQ:
overflow = freq_sum - RANS_TOTAL_FREQ
for sym, _ in sorted(nonzero, key=lambda item: (-freqs[item[0]], item[0])):
if overflow <= 0:
break
removable = min(overflow, freqs[sym] - 1)
if removable > 0:
freqs[sym] -= removable
overflow -= removable
if overflow != 0:
raise ValueError("Failed to normalize rANS frequencies")
starts: dict[int, int] = {}
cum = 0
for sym in sorted(freqs):
starts[sym] = cum
cum += freqs[sym]
if cum != RANS_TOTAL_FREQ:
raise ValueError("Invalid rANS normalization total")
return total, freqs, starts
def rans_encode_bytes(data: bytes) -> bytes:
head = bytearray()
head.extend(struct.pack("<QH", len(data), 0))
if not data:
return bytes(head)
freqs, starts = _build_rans_frequencies(data)
head = bytearray()
head.extend(struct.pack("<QH", len(data), len(freqs)))
for sym in sorted(freqs):
head.extend(struct.pack("<BH", sym, freqs[sym]))
state = RANS_L
out = bytearray()
x_max_base = (RANS_L >> RANS_SCALE_BITS) << 8
for sym in reversed(data):
freq = freqs[sym]
x_max = x_max_base * freq
while state >= x_max:
out.append(state & 0xFF)
state >>= 8
start = starts[sym]
state = ((state // freq) << RANS_SCALE_BITS) + (state % freq) + start
head.extend(struct.pack("<I", state))
head.extend(reversed(out))
return bytes(head)
def _rans_encode_block_worker(raw_block: bytes) -> bytes:
return rans_encode_bytes(raw_block)
def rans_decode_bytes(blob: bytes) -> bytes:
head_size = struct.calcsize("<QH")
if len(blob) < head_size:
raise ValueError("Invalid rANS payload (too short)")
raw_size, symbol_count = struct.unpack("<QH", blob[:head_size])
pos = head_size
if symbol_count == 0:
if raw_size != 0 or len(blob) != head_size:
raise ValueError("Invalid rANS payload (empty table mismatch)")
return b""
table_size = symbol_count * struct.calcsize("<BH")
if len(blob) < pos + table_size + 4:
raise ValueError("Invalid rANS payload (truncated header)")
freqs: dict[int, int] = {}
starts: dict[int, int] = {}
decode_table = bytearray(RANS_TOTAL_FREQ)
cum = 0
for _ in range(symbol_count):
sym, freq = struct.unpack("<BH", blob[pos : pos + 3])
pos += 3
if freq <= 0:
raise ValueError("Invalid rANS payload (zero frequency)")
if sym in freqs:
raise ValueError("Invalid rANS payload (duplicate symbol)")
freqs[int(sym)] = int(freq)
starts[int(sym)] = cum
decode_table[cum : cum + freq] = bytes([sym]) * freq
cum += freq
if cum != RANS_TOTAL_FREQ:
raise ValueError("Invalid rANS payload (frequency total mismatch)")
state = struct.unpack("<I", blob[pos : pos + 4])[0]
pos += 4
stream = blob[pos:]
stream_pos = 0
out = bytearray()
for i in range(raw_size):
slot = state & (RANS_TOTAL_FREQ - 1)
sym = decode_table[slot]
out.append(sym)
state = freqs[sym] * (state >> RANS_SCALE_BITS) + (slot - starts[sym])
while state < RANS_L and stream_pos < len(stream):
state = (state << 8) | stream[stream_pos]
stream_pos += 1
if state < RANS_L and stream_pos >= len(stream) and i + 1 < raw_size:
raise ValueError("Invalid rANS payload (unexpected end of renormalization stream)")
if stream_pos != len(stream):
raise ValueError("Invalid rANS payload (trailing bytes)")
return bytes(out)
def _rans_decode_block_worker(encoded_block: bytes) -> bytes:
return rans_decode_bytes(encoded_block)
class FramedRansEncoder:
def __init__(self, write_bytes, block_size: int = RANS_DEFAULT_BLOCK_BYTES):
if block_size <= 0:
raise ValueError("rANS framed block size must be positive")
self.write_bytes = write_bytes
self.block_size = int(block_size)
self._buf = bytearray()
self._header_written = False
self._closed = False
self._total = 0
self._block_count = 0
def _write_header(self) -> None:
if self._header_written:
return
header = struct.pack(RANS_FRAME_HEADER_FMT, RANS_FRAME_MAGIC, self.block_size)
self.write_bytes(header)
self._total += len(header)
self._header_written = True
def _emit_block(self, raw_block: bytes) -> None:
encoded = rans_encode_bytes(raw_block)
block_head = struct.pack(RANS_FRAME_BLOCK_FMT, len(raw_block), len(encoded))
self.write_bytes(block_head)
self.write_bytes(encoded)
self._total += len(block_head) + len(encoded)
self._block_count += 1
def feed(self, data: bytes | memoryview) -> None:
if self._closed:
raise ValueError("Framed rANS encoder already closed")
if not data:
return
self._write_header()
self._buf.extend(data)
while len(self._buf) >= self.block_size:
raw_block = bytes(self._buf[: self.block_size])
del self._buf[: self.block_size]
self._emit_block(raw_block)
def finish(self) -> int:
if self._closed:
raise ValueError("Framed rANS encoder already closed")
self._write_header()
if self._buf:
self._emit_block(bytes(self._buf))
self._buf.clear()
self._closed = True
return self._total
def rans_encode_framed_bytes(
data: bytes,
block_size: int = RANS_DEFAULT_BLOCK_BYTES,
workers: int = 1,
) -> bytes:
workers = max(1, int(workers))
if block_size <= 0:
raise ValueError("rANS framed block size must be positive")
if workers <= 1 or len(data) <= block_size:
out = bytearray()
encoder = FramedRansEncoder(out.extend, block_size=block_size)
encoder.feed(data)
encoder.finish()
return bytes(out)
blocks = [data[pos : pos + block_size] for pos in range(0, len(data), block_size)]
out = bytearray(struct.pack(RANS_FRAME_HEADER_FMT, RANS_FRAME_MAGIC, block_size))
with ProcessPoolExecutor(max_workers=min(workers, len(blocks))) as ex:
encoded_blocks = list(ex.map(_rans_encode_block_worker, blocks))
for raw_block, encoded in zip(blocks, encoded_blocks):
out.extend(struct.pack(RANS_FRAME_BLOCK_FMT, len(raw_block), len(encoded)))
out.extend(encoded)
return bytes(out)
def _parse_framed_rans_blocks(blob: bytes) -> tuple[int, list[tuple[int, bytes]]]:
if len(blob) < RANS_FRAME_HEADER_SIZE:
raise ValueError("Invalid framed rANS payload (too short)")
magic, block_size = struct.unpack(RANS_FRAME_HEADER_FMT, blob[:RANS_FRAME_HEADER_SIZE])
if magic != RANS_FRAME_MAGIC:
raise ValueError("Invalid framed rANS payload (bad magic)")
if block_size <= 0:
raise ValueError("Invalid framed rANS payload (bad block size)")
pos = RANS_FRAME_HEADER_SIZE
blocks: list[tuple[int, bytes]] = []
while pos < len(blob):
if len(blob) < pos + RANS_FRAME_BLOCK_SIZE:
raise ValueError("Invalid framed rANS payload (truncated block header)")
raw_size, encoded_size = struct.unpack(
RANS_FRAME_BLOCK_FMT,
blob[pos : pos + RANS_FRAME_BLOCK_SIZE],
)
pos += RANS_FRAME_BLOCK_SIZE
if len(blob) < pos + encoded_size:
raise ValueError("Invalid framed rANS payload (truncated block)")
blocks.append((raw_size, blob[pos : pos + encoded_size]))
pos += encoded_size
return block_size, blocks
def rans_decode_framed_bytes(blob: bytes, workers: int = 1) -> bytes:
_, blocks = _parse_framed_rans_blocks(blob)
if not blocks:
return b""
workers = max(1, int(workers))
encoded_blocks = [encoded for _, encoded in blocks]
raw_sizes = [raw_size for raw_size, _ in blocks]
if workers <= 1 or len(blocks) <= 1:
decoded_blocks = [rans_decode_bytes(encoded) for encoded in encoded_blocks]
else:
with ProcessPoolExecutor(max_workers=min(workers, len(blocks))) as ex:
decoded_blocks = list(ex.map(_rans_decode_block_worker, encoded_blocks))
out = bytearray()
for raw_size, raw in zip(raw_sizes, decoded_blocks):
if len(raw) != raw_size:
raise ValueError("Invalid framed rANS payload (block size mismatch)")
out.extend(raw)
return bytes(out)
def rans_decode_auto_bytes(blob: bytes, workers: int = 1) -> bytes:
if blob.startswith(RANS_FRAME_MAGIC):
return rans_decode_framed_bytes(blob, workers=workers)
return rans_decode_bytes(blob)
def _reverse_copy_file_to_writer(src_path: Path, write_bytes, chunk_size: int = 1 << 20) -> int:
total = 0
with src_path.open("rb") as f:
pos = src_path.stat().st_size
while pos > 0:
take = min(chunk_size, pos)
pos -= take
f.seek(pos)
chunk = f.read(take)
if chunk:
rev = chunk[::-1]
write_bytes(rev)
total += len(rev)
return total
def rans_encode_file_to_writer(
input_path: Path,
write_bytes,
scratch_dir: Path | None = None,
io_chunk_size: int = 1 << 20,
) -> int:
raw_size, freqs, starts = _build_rans_frequencies_from_file(input_path, chunk_size=io_chunk_size)
header = bytearray()
header.extend(struct.pack("<QH", raw_size, len(freqs)))
if not freqs:
write_bytes(header)
return len(header)
for sym in sorted(freqs):
header.extend(struct.pack("<BH", sym, freqs[sym]))
with tempfile.TemporaryDirectory(prefix="vcomp_rans_emit_", dir=scratch_dir) as td:
emit_path = Path(td) / "emit.bin"
state = RANS_L
x_max_base = (RANS_L >> RANS_SCALE_BITS) << 8
emitted_count = 0
with emit_path.open("wb") as emit_f:
for sym in _iter_file_bytes_reversed(input_path, chunk_size=io_chunk_size):
freq = freqs[sym]
x_max = x_max_base * freq
while state >= x_max:
emit_f.write(bytes([state & 0xFF]))
emitted_count += 1
state >>= 8
start = starts[sym]
state = ((state // freq) << RANS_SCALE_BITS) + (state % freq) + start
write_bytes(header)
write_bytes(struct.pack("<I", state))
total = len(header) + 4
total += _reverse_copy_file_to_writer(emit_path, write_bytes, chunk_size=io_chunk_size)
if total != len(header) + 4 + emitted_count:
raise ValueError("Internal error: rANS file encoding size mismatch")
return total
def rans_encode_framed_file_to_writer(
input_path: Path,
write_bytes,
block_size: int = RANS_DEFAULT_BLOCK_BYTES,
io_chunk_size: int = 1 << 20,
) -> int:
encoder = FramedRansEncoder(write_bytes, block_size=block_size)
with input_path.open("rb") as in_f:
while True:
chunk = in_f.read(io_chunk_size)
if not chunk:
break
encoder.feed(chunk)
return encoder.finish()
def _emit_temp_payload_file(
raw_payload_path: Path,
out_f,
entropy_mode: str,
io_chunk_size: int = 1 << 20,
) -> int:
if entropy_mode == "raw":
total = 0
with raw_payload_path.open("rb") as raw_f:
while True:
chunk = raw_f.read(io_chunk_size)
if not chunk:
break
out_f.write(chunk)
total += len(chunk)
return total
if entropy_mode == "zlib":
total = 0
compressor = zlib.compressobj(level=9)
with raw_payload_path.open("rb") as raw_f:
while True:
chunk = raw_f.read(io_chunk_size)
if not chunk:
break
comp = compressor.compress(chunk)
if comp:
out_f.write(comp)
total += len(comp)
tail = compressor.flush()
if tail:
out_f.write(tail)
total += len(tail)
return total
if entropy_mode == "rans":
return rans_encode_framed_file_to_writer(
raw_payload_path,
out_f.write,