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
|
"""DirectStorage BCPack bitstream inspection, decoding and profiling tool.
Provides CLI inspection, diagnostics, statistical frequency profiling and
decompression for Xbox Series BCPack streams (codecs BC1, BC3, BC4, BC5, BC6H, BC7).
Usage:
python -I tools/bcpack_tool.py inspect <in.bin> --codec <1..7> --size <uncompressed_bytes> [--json]
python -I tools/bcpack_tool.py decode <in.bin> <out.bin> --codec <1..7> --size <uncompressed_bytes> [--provisional]
python -I tools/bcpack_tool.py profile <in.bin> --codec <1..7> --size <uncompressed_bytes>
"""
from __future__ import annotations
import argparse
from contextlib import suppress
import errno
import json
import os
import sys
import tempfile
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import bcpack
from file_mode import published_mode
from report_paths import same_report_path
def _inspect_decoded_lanes(raw: bytes, codec: int, out_size: int) -> tuple[dict, list[list[int]]]:
"""Decode lanes once and build the inspection report alongside the decoded lanes."""
if codec not in bcpack.ALL_CODECS:
raise ValueError(f"unsupported BCPack codec id: {codec}")
block_size = bcpack.BLOCK_BYTES[codec]
if out_size <= 0 or out_size % block_size != 0:
raise ValueError(
f"output size {out_size} is not a valid multiple of {bcpack.CODEC_NAMES[codec]} block size ({block_size})"
)
nblocks = out_size // block_size
lanes, used = bcpack.decode_lanes(raw, codec, out_size)
lane_widths = bcpack.LANE_WIDTHS[codec]
lane_reports = []
total_symbols = 0
for idx, lane in enumerate(lanes):
count = len(lane)
total_symbols += count
w = lane_widths[idx]
zeros = lane.count(0)
min_val = min(lane) if count else 0
max_val = max(lane) if count else 0
avg_val = (sum(lane) / count) if count else 0.0
lane_reports.append({
"lane": idx,
"bit_width": w,
"symbols": count,
"zeros": zeros,
"zero_percent": round(100.0 * zeros / count, 2) if count else 0.0,
"min": min_val,
"max": max_val,
"avg": round(avg_val, 2),
})
trailing_bytes = len(raw) - used
ratio = round(len(raw) / out_size, 4) if out_size else 0.0
info = {
"codec": bcpack.CODEC_NAMES[codec],
"codec_id": codec,
"compressed_bytes": len(raw),
"bytes_used": used,
"trailing_zeros": trailing_bytes,
"uncompressed_bytes": out_size,
"blocks": nblocks,
"compression_ratio": ratio,
"total_symbols": total_symbols,
"lanes": lane_reports,
}
return info, lanes
def inspect_stream(raw: bytes, codec: int, out_size: int) -> dict:
"""Analyze stream structure, compression ratio and per-lane statistics."""
info, _ = _inspect_decoded_lanes(raw, codec, out_size)
return info
def profile_stream(raw: bytes, codec: int, out_size: int) -> dict:
"""Generate symbol frequency distribution profile across all lanes."""
info, lanes = _inspect_decoded_lanes(raw, codec, out_size)
histograms = []
for idx, lane in enumerate(lanes):
counts: dict[int, int] = {}
for sym in lane:
counts[sym] = counts.get(sym, 0) + 1
sorted_top = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:8]
histograms.append({
"lane": idx,
"unique_symbols": len(counts),
"top_symbols": [{"sym": s, "count": c} for s, c in sorted_top],
})
info["histograms"] = histograms
return info
def _history_paths(history: object, codec: int) -> tuple[str | None, list[str]]:
"""Return `(display_path, protected_paths)` for an on-disk `history` argument, or `(None, [])`."""
if history is None or isinstance(history, dict):
return None, []
hist_path = os.fsdecode(os.fspath(history))
protected = [hist_path]
display = os.path.normpath(hist_path)
if os.path.isdir(hist_path):
codec_name = bcpack.CODEC_NAMES.get(codec)
if codec_name is not None:
candidate = os.path.join(display, f"{codec_name.lower()}.json")
if os.path.exists(candidate):
protected.append(candidate)
if os.path.isfile(candidate):
display = candidate
return display, protected
def _write_output_atomic(destination: str, data: bytes) -> None:
"""Publish decoded bytes to `destination` without truncating an existing file on error."""
parent = os.path.dirname(os.path.abspath(destination))
if parent:
os.makedirs(parent, exist_ok=True)
# Special non-regular files (e.g. /dev/null or NUL) cannot be replaced by rename.
if os.path.exists(destination) and not os.path.isfile(destination):
with open(destination, "wb") as f:
f.write(data)
return
staged = None
try:
with tempfile.NamedTemporaryFile(
mode="wb",
dir=parent or ".",
prefix=".bcpack_tool-",
suffix=".tmp",
delete=False,
) as f:
staged = f.name
f.write(data)
os.chmod(staged, published_mode(destination))
os.replace(staged, destination)
staged = None
finally:
if staged is not None:
with suppress(OSError):
os.chmod(staged, 0o600)
os.unlink(staged)
def decode_file(
in_path: str,
out_path: str,
codec: int,
out_size: int,
allow_provisional: bool = False,
history: str | None = None,
) -> int:
"""Decode compressed file and write decompressed blocks to disk."""
if same_report_path(in_path, out_path):
raise ValueError(
f"output path '{out_path}' names the compressed input '{in_path}'; "
f"refusing to overwrite it"
)
hist_label, hist_protected = _history_paths(history, codec)
for target in hist_protected:
if same_report_path(target, out_path):
raise ValueError(
f"output path '{out_path}' names the history path '{target}'; "
f"refusing to overwrite it"
)
destination = os.path.realpath(out_path)
if os.path.islink(destination):
raise OSError(errno.ELOOP, os.strerror(errno.ELOOP), out_path)
if os.path.isdir(destination):
raise IsADirectoryError(errno.EISDIR, os.strerror(errno.EISDIR), out_path)
with open(in_path, "rb") as f:
raw = f.read()
try:
data, prov = bcpack.decode_with_info(
raw, codec, out_size, allow_provisional=allow_provisional, history=history
)
except bcpack.BcpackError:
raise # stream failures are already attributed to the stream, never to --history
except ValueError as e:
# json.JSONDecodeError from a --history file carries no filename; attribute it,
# but do not double-prefix messages that already name the history path.
if hist_label is not None:
base = os.path.basename(os.path.normpath(hist_label))
if not base or base not in str(e):
raise ValueError(f"{hist_label}: {e}") from e
raise
_write_output_atomic(destination, data)
return len(data)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description="DirectStorage BCPack bitstream inspection, decoding and profiling tool."
)
sub = parser.add_subparsers(dest="command", required=True)
# inspect
p_insp = sub.add_parser("inspect", help="Inspect BCPack stream structure and lane statistics")
p_insp.add_argument("file", help="Path to raw BCPack compressed file")
p_insp.add_argument(
"--codec",
type=int,
required=True,
choices=sorted(bcpack.ALL_CODECS),
help="BCPack codec ID (1=BC1, 3=BC3, 4=BC4, 5=BC5, 6=BC6H, 7=BC7)",
)
p_insp.add_argument(
"--size",
type=int,
required=True,
help="Expected uncompressed size in bytes",
)
p_insp.add_argument(
"--json",
action="store_true",
help="Print machine-readable JSON output",
)
# profile
p_prof = sub.add_parser("profile", help="Generate detailed symbol frequency distribution")
p_prof.add_argument("file", help="Path to raw BCPack compressed file")
p_prof.add_argument(
"--codec",
type=int,
required=True,
choices=sorted(bcpack.ALL_CODECS),
help="BCPack codec ID",
)
p_prof.add_argument(
"--size",
type=int,
required=True,
help="Expected uncompressed size in bytes",
)
# decode
p_dec = sub.add_parser("decode", help="Decompress BCPack file to raw BCn blocks")
p_dec.add_argument("in_file", help="Path to input BCPack compressed file")
p_dec.add_argument("out_file", help="Path to output decompressed file")
p_dec.add_argument(
"--codec",
type=int,
required=True,
choices=sorted(bcpack.ALL_CODECS),
help="BCPack codec ID",
)
p_dec.add_argument(
"--size",
type=int,
required=True,
help="Expected uncompressed size in bytes",
)
p_dec.add_argument(
"--provisional",
action="store_true",
help="Allow provisional history and signatures",
)
p_dec.add_argument(
"--history",
type=str,
default=None,
help="Path to optional BC6H/BC7 history JSON or directory",
)
args = parser.parse_args(argv)
# CLI-level guard: a missing/unreadable input or history file (OSError), a stream that fails
# structural or rANS validation (bcpack.BcpackError, a ValueError), or a malformed --history
# JSON (ValueError) must be one named line on stderr with exit status 2, not a traceback.
# bcpack.py's library-level behavior is unchanged.
src = args.in_file if args.command == "decode" else args.file
try:
return _run(args)
except (ValueError, OSError, bcpack.BcpackUnsupportedCodec) as e:
print(f"ERROR: {src}: {e}", file=sys.stderr)
return 2
def _run(args: argparse.Namespace) -> int:
if args.command == "inspect":
with open(args.file, "rb") as f:
raw = f.read()
info = inspect_stream(raw, args.codec, args.size)
if args.json:
print(json.dumps(info, indent=2))
else:
print(
f"BCPack {info['codec']} stream: {info['compressed_bytes']} bytes -> "
f"{info['uncompressed_bytes']} bytes ({info['blocks']} blocks, ratio {info['compression_ratio']:.3f})"
)
print(f"Lanes ({len(info['lanes'])} active):")
for l in info['lanes']:
print(
f" lane {l['lane']:2d} (w={l['bit_width']:2d}b): {l['symbols']} syms, "
f"{l['zeros']} zeros ({l['zero_percent']}%), min {l['min']}, max {l['max']}, avg {l['avg']}"
)
return 0
elif args.command == "profile":
with open(args.file, "rb") as f:
raw = f.read()
prof = profile_stream(raw, args.codec, args.size)
print(json.dumps(prof, indent=2))
return 0
elif args.command == "decode":
written = decode_file(
args.in_file,
args.out_file,
args.codec,
args.size,
allow_provisional=args.provisional,
history=args.history,
)
print(f"Successfully decoded {written} bytes to {args.out_file}")
return 0
return 1
if __name__ == "__main__":
try:
sys.stdout.reconfigure(errors="replace")
except (AttributeError, ValueError, OSError):
pass
sys.exit(main())
|