upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/tools/bcpack_tool.py
diff options
context:
space:
mode:
authorVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-22 19:07:53 +0100
committerVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-22 19:07:53 +0100
commit46a196cde9328e2a232ee15c19556eb962cda0ab (patch)
treed1cd03326530912d925ee1a7ba7fa735006f004f /tools/bcpack_tool.py
parentd3fab00a78967adf357596996190afdf33dc09d5 (diff)
parentec8ec4c9a46c6623f1a9c125afd3566da97f1e0c (diff)
Merge upstream main into first-light shader identity
Diffstat (limited to 'tools/bcpack_tool.py')
-rw-r--r--tools/bcpack_tool.py243
1 files changed, 243 insertions, 0 deletions
diff --git a/tools/bcpack_tool.py b/tools/bcpack_tool.py
new file mode 100644
index 000000000..101190189
--- /dev/null
+++ b/tools/bcpack_tool.py
@@ -0,0 +1,243 @@
1"""DirectStorage BCPack bitstream inspection, decoding and profiling tool.
2
3Provides CLI inspection, diagnostics, statistical frequency profiling and
4decompression for Xbox Series BCPack streams (codecs BC1, BC3, BC4, BC5, BC6H, BC7).
5
6Usage:
7 python -I tools/bcpack_tool.py inspect <in.bin> --codec <1..7> --size <uncompressed_bytes> [--json]
8 python -I tools/bcpack_tool.py decode <in.bin> <out.bin> --codec <1..7> --size <uncompressed_bytes> [--provisional]
9 python -I tools/bcpack_tool.py profile <in.bin> --codec <1..7> --size <uncompressed_bytes>
10"""
11from __future__ import annotations
12
13import argparse
14import json
15import os
16import sys
17
18sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
19import bcpack
20
21
22def inspect_stream(raw: bytes, codec: int, out_size: int) -> dict:
23 """Analyze stream structure, compression ratio and per-lane statistics."""
24 if codec not in bcpack.ALL_CODECS:
25 raise ValueError(f"unsupported BCPack codec id: {codec}")
26
27 block_size = bcpack.BLOCK_BYTES[codec]
28 if out_size <= 0 or out_size % block_size != 0:
29 raise ValueError(
30 f"output size {out_size} is not a valid multiple of {bcpack.CODEC_NAMES[codec]} block size ({block_size})"
31 )
32
33 nblocks = out_size // block_size
34 lanes, used = bcpack.decode_lanes(raw, codec, out_size)
35
36 lane_widths = bcpack.LANE_WIDTHS[codec]
37 lane_reports = []
38 total_symbols = 0
39
40 for idx, lane in enumerate(lanes):
41 count = len(lane)
42 total_symbols += count
43 w = lane_widths[idx]
44 zeros = lane.count(0)
45 min_val = min(lane) if count else 0
46 max_val = max(lane) if count else 0
47 avg_val = (sum(lane) / count) if count else 0.0
48
49 lane_reports.append({
50 "lane": idx,
51 "bit_width": w,
52 "symbols": count,
53 "zeros": zeros,
54 "zero_percent": round(100.0 * zeros / count, 2) if count else 0.0,
55 "min": min_val,
56 "max": max_val,
57 "avg": round(avg_val, 2),
58 })
59
60 trailing_bytes = len(raw) - used
61 ratio = round(len(raw) / out_size, 4) if out_size else 0.0
62
63 return {
64 "codec": bcpack.CODEC_NAMES[codec],
65 "codec_id": codec,
66 "compressed_bytes": len(raw),
67 "bytes_used": used,
68 "trailing_zeros": trailing_bytes,
69 "uncompressed_bytes": out_size,
70 "blocks": nblocks,
71 "compression_ratio": ratio,
72 "total_symbols": total_symbols,
73 "lanes": lane_reports,
74 }
75
76
77def profile_stream(raw: bytes, codec: int, out_size: int) -> dict:
78 """Generate symbol frequency distribution profile across all lanes."""
79 info = inspect_stream(raw, codec, out_size)
80 lanes, _ = bcpack.decode_lanes(raw, codec, out_size)
81
82 histograms = []
83 for idx, lane in enumerate(lanes):
84 counts: dict[int, int] = {}
85 for sym in lane:
86 counts[sym] = counts.get(sym, 0) + 1
87 sorted_top = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:8]
88 histograms.append({
89 "lane": idx,
90 "unique_symbols": len(counts),
91 "top_symbols": [{"sym": s, "count": c} for s, c in sorted_top],
92 })
93
94 info["histograms"] = histograms
95 return info
96
97
98def decode_file(
99 in_path: str,
100 out_path: str,
101 codec: int,
102 out_size: int,
103 allow_provisional: bool = False,
104 history: str | None = None,
105) -> int:
106 """Decode compressed file and write decompressed blocks to disk."""
107 with open(in_path, "rb") as f:
108 raw = f.read()
109
110 data, prov = bcpack.decode_with_info(
111 raw, codec, out_size, allow_provisional=allow_provisional, history=history
112 )
113
114 parent = os.path.dirname(os.path.abspath(out_path))
115 if parent:
116 os.makedirs(parent, exist_ok=True)
117
118 with open(out_path, "wb") as f:
119 f.write(data)
120
121 return len(data)
122
123
124def main(argv: list[str] | None = None) -> int:
125 parser = argparse.ArgumentParser(
126 description="DirectStorage BCPack bitstream inspection, decoding and profiling tool."
127 )
128 sub = parser.add_subparsers(dest="command", required=True)
129
130 # inspect
131 p_insp = sub.add_parser("inspect", help="Inspect BCPack stream structure and lane statistics")
132 p_insp.add_argument("file", help="Path to raw BCPack compressed file")
133 p_insp.add_argument(
134 "--codec",
135 type=int,
136 required=True,
137 choices=sorted(bcpack.ALL_CODECS),
138 help="BCPack codec ID (1=BC1, 3=BC3, 4=BC4, 5=BC5, 6=BC6H, 7=BC7)",
139 )
140 p_insp.add_argument(
141 "--size",
142 type=int,
143 required=True,
144 help="Expected uncompressed size in bytes",
145 )
146 p_insp.add_argument(
147 "--json",
148 action="store_true",
149 help="Print machine-readable JSON output",
150 )
151
152 # profile
153 p_prof = sub.add_parser("profile", help="Generate detailed symbol frequency distribution")
154 p_prof.add_argument("file", help="Path to raw BCPack compressed file")
155 p_prof.add_argument(
156 "--codec",
157 type=int,
158 required=True,
159 choices=sorted(bcpack.ALL_CODECS),
160 help="BCPack codec ID",
161 )
162 p_prof.add_argument(
163 "--size",
164 type=int,
165 required=True,
166 help="Expected uncompressed size in bytes",
167 )
168
169 # decode
170 p_dec = sub.add_parser("decode", help="Decompress BCPack file to raw BCn blocks")
171 p_dec.add_argument("in_file", help="Path to input BCPack compressed file")
172 p_dec.add_argument("out_file", help="Path to output decompressed file")
173 p_dec.add_argument(
174 "--codec",
175 type=int,
176 required=True,
177 choices=sorted(bcpack.ALL_CODECS),
178 help="BCPack codec ID",
179 )
180 p_dec.add_argument(
181 "--size",
182 type=int,
183 required=True,
184 help="Expected uncompressed size in bytes",
185 )
186 p_dec.add_argument(
187 "--provisional",
188 action="store_true",
189 help="Allow provisional history and signatures",
190 )
191 p_dec.add_argument(
192 "--history",
193 type=str,
194 default=None,
195 help="Path to optional BC6H/BC7 history JSON or directory",
196 )
197
198 args = parser.parse_args(argv)
199
200 if args.command == "inspect":
201 with open(args.file, "rb") as f:
202 raw = f.read()
203 info = inspect_stream(raw, args.codec, args.size)
204 if args.json:
205 print(json.dumps(info, indent=2))
206 else:
207 print(
208 f"BCPack {info['codec']} stream: {info['compressed_bytes']} bytes -> "
209 f"{info['uncompressed_bytes']} bytes ({info['blocks']} blocks, ratio {info['compression_ratio']:.3f})"
210 )
211 print(f"Lanes ({len(info['lanes'])} active):")
212 for l in info['lanes']:
213 print(
214 f" lane {l['lane']:2d} (w={l['bit_width']:2d}b): {l['symbols']} syms, "
215 f"{l['zeros']} zeros ({l['zero_percent']}%), min {l['min']}, max {l['max']}, avg {l['avg']}"
216 )
217 return 0
218
219 elif args.command == "profile":
220 with open(args.file, "rb") as f:
221 raw = f.read()
222 prof = profile_stream(raw, args.codec, args.size)
223 print(json.dumps(prof, indent=2))
224 return 0
225
226 elif args.command == "decode":
227 written = decode_file(
228 args.in_file,
229 args.out_file,
230 args.codec,
231 args.size,
232 allow_provisional=args.provisional,
233 history=args.history,
234 )
235 print(f"Successfully decoded {written} bytes to {args.out_file}")
236 return 0
237
238 return 1
239
240
241if __name__ == "__main__":
242 sys.stdout.reconfigure(errors="replace")
243 sys.exit(main())