File size: 12,702 Bytes
60be9be | 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 | """Frame-independent log-u16, row delta, byte shuffle and Zstd depth codec.
The .dlog file concatenates independent Zstd frames. Its .index.json sidecar
contains byte ranges, dimensions and quantization parameters. Physical units
remain centimeters. Codes 1..65535 span [near_cm, far_cm]; 0 decodes to zero.
Nonzero values outside that range, signed zero and nonfinite values are stored
as exact float32 exceptions, so they are never silently clipped.
"""
from __future__ import annotations
import hashlib
import json
import math
from pathlib import Path
import numpy as np
import zstandard as zstd
MAGIC = b"HELIOS_DLOG_V1\n"
SCHEMA = "helios-depth-log-u16-v1"
def parameters(near_cm=10.0, far_cm=100_000_000.0):
if not (math.isfinite(near_cm) and math.isfinite(far_cm) and 0 < near_cm < far_cm):
raise ValueError("Require finite 0 < near_cm < far_cm")
return {"schema": SCHEMA, "unit": "centimeter", "near_cm": float(near_cm),
"far_cm": float(far_cm), "quantization": "log-nearest-u16",
"valid_codes": [1, 65535], "zero_code": 0,
"delta": "uint16-modular-horizontal-reset-every-row",
"shuffle": "two-byte-planes-per-frame", "compression": "zstd",
"compression_level": 3, "zstd_checksum": True,
"exceptions": "uint32-pixel-indices-followed-by-float32le-values",
"max_relative_quantization_error": math.expm1(math.log(far_cm/near_cm)/(2*65534))}
def encode_frame(depth, config, compressor=None):
x = np.asarray(depth, dtype='<f4')
if x.ndim != 2 or x.size > np.iinfo(np.uint32).max:
raise ValueError("Expected a 2D frame with uint32-addressable pixels")
lo, hi = config['near_cm'], config['far_cm']
valid = np.isfinite(x) & (x >= lo) & (x <= hi)
# Retain all exceptional nonzero values and the sign bit of negative zero.
exceptional = ~valid & ((x != 0) | np.signbit(x))
indices = np.flatnonzero(exceptional).astype('<u4')
values = x.ravel()[indices].astype('<f4', copy=False)
codes = np.zeros(x.shape, dtype='<u2')
codes[valid] = (1 + np.rint(65534 * np.log(x[valid].astype(np.float64)/lo)
/ math.log(hi/lo))).astype(np.uint16)
delta = codes.copy()
delta[:, 1:] = codes[:, 1:] - codes[:, :-1]
shuffled = delta.view(np.uint8).reshape(-1, 2).T.copy().tobytes()
raw = shuffled + indices.tobytes() + values.tobytes()
compressor = compressor or zstd.ZstdCompressor(level=3, write_checksum=True)
blob = compressor.compress(raw)
entry = {"length": len(blob), "uncompressed_bytes": len(raw),
"exception_count": len(indices)}
return blob, entry, codes
def decode_codes(blob, entry, height, width):
raw = zstd.ZstdDecompressor().decompress(blob, max_output_size=entry['uncompressed_bytes'])
n, count = height*width, entry['exception_count']
if len(raw) != 2*n + 8*count or len(raw) != entry['uncompressed_bytes']:
raise ValueError("Invalid decompressed frame size")
delta = np.frombuffer(raw, dtype=np.uint8, count=2*n).reshape(2, n).T.copy().view('<u2')
codes = np.cumsum(delta.reshape(height, width), axis=1, dtype=np.uint16)
indices = np.frombuffer(raw, dtype='<u4', count=count, offset=2*n)
values = np.frombuffer(raw, dtype='<f4', count=count, offset=2*n+4*count)
if count and (indices[-1] >= n or np.any(indices[1:] <= indices[:-1])):
raise ValueError("Invalid exception indices")
return codes, indices, values
def codes_to_depth(codes, indices, values, config):
out = np.zeros(codes.shape, dtype='<f4')
valid = codes > 0
out[valid] = config['near_cm'] * np.exp((codes[valid].astype(np.float64)-1)
* math.log(config['far_cm']/config['near_cm']) / 65534)
out.ravel()[indices] = values
return out
def decode_frame(blob, entry, height, width, config):
return codes_to_depth(*decode_codes(blob, entry, height, width), config)
def compress_hdf5(source, output, config, source_uri=None, source_info=None):
import h5py
source, output = Path(source), Path(output)
output.parent.mkdir(parents=True, exist_ok=True)
index = {"codec": config, "source_uri": source_uri or str(source),
"source_info": source_info or {}, "source_bytes": source.stat().st_size,
"source_sha256": file_sha256(source), "frames": []}
compressor = zstd.ZstdCompressor(level=3, write_checksum=True)
max_relative = 0.0
special_count = 0
with h5py.File(source, 'r') as f, output.open('wb') as out:
d = f['depth']
if d.ndim != 3 or d.dtype.kind != 'f' or d.dtype.itemsize != 4:
raise ValueError(f"Expected (frames, height, width) float32, got {d.shape} {d.dtype}")
encoding = d.attrs.get('depth_encoding', '')
unit = d.attrs.get('unit', '')
if isinstance(encoding, bytes): encoding = encoding.decode()
if isinstance(unit, bytes): unit = unit.decode()
if encoding != 'linear_scene_depth_cm' or unit != 'centimeter':
raise ValueError(f"Unsupported source depth encoding/unit: {encoding!r}/{unit!r}")
count, height, width = d.shape
if count < 1: raise ValueError('Cannot recompress an empty depth dataset')
index.update(frame_count=count, height=height, width=width,
original_attributes={k: str(v) for k,v in d.attrs.items()})
out.write(MAGIC)
for i in range(count):
x = np.asarray(d[i], dtype='<f4')
blob, entry, codes = encode_frame(x, config, compressor)
# Verify every compressed frame, including exact delta inversion.
recovered, indices, values = decode_codes(blob, entry, height, width)
if not np.array_equal(codes, recovered):
raise ValueError(f"Integer codec roundtrip failed at frame {i}")
y = codes_to_depth(recovered, indices, values, config)
if len(indices) and not np.array_equal(x.ravel()[indices].view('<u4'),
y.ravel()[indices].view('<u4')):
raise ValueError(f"Exception preservation failed at frame {i}")
valid = codes > 0
if valid.any():
err = float(np.max(np.abs(y[valid].astype(np.float64)/x[valid]-1)))
if err > config['max_relative_quantization_error'] + 2e-7:
raise ValueError(f"Quantization bound exceeded at frame {i}: {err}")
max_relative = max(max_relative, err)
entry.update(frame_index=i, offset=out.tell())
out.write(blob)
index['frames'].append(entry)
special_count += entry['exception_count']
index.update(compressed_bytes=output.stat().st_size, compressed_sha256=file_sha256(output),
verified=True, max_observed_relative_error=max_relative,
exception_pixel_count=special_count,
original_raw_bytes=count*height*width*4)
sidecar = Path(str(output)+'.index.json')
sidecar.write_text(json.dumps(index, ensure_ascii=False, separators=(',', ':')))
return index, sidecar
def file_sha256(path):
h = hashlib.sha256()
with Path(path).open('rb') as f:
for block in iter(lambda: f.read(8*1024*1024), b''): h.update(block)
return h.hexdigest()
def pack_into_hdf5(source, output, config, source_uri=None, source_info=None):
"""Keep a genuine .h5 container and original filename for in-place updates.
A contiguous byte dataset carries independent Zstd frames. The embedded
index makes the file self describing; the sidecar enables remote ranges.
Direct f['depth'] float32 access must be replaced with DepthLogReader.
"""
import h5py
import tempfile
output = Path(output)
output.parent.mkdir(parents=True,exist_ok=True)
with tempfile.TemporaryDirectory(prefix='depth-pack-', dir=output.parent) as tmp:
packed = Path(tmp)/'depth.dlog'
index, _ = compress_hdf5(source, packed, config, source_uri, source_info)
index.pop('compressed_sha256')
index.pop('compressed_bytes')
index['container'] = 'hdf5'
index['payload_dataset'] = 'depth_payload_zstd'
with h5py.File(output, 'w', libver='earliest') as f:
payload = f.create_dataset('depth_payload_zstd', shape=(packed.stat().st_size,),
dtype=np.uint8, chunks=None)
with packed.open('rb') as raw:
offset = 0
for chunk in iter(lambda: raw.read(8*1024*1024), b''):
payload[offset:offset+len(chunk)] = np.frombuffer(chunk, dtype=np.uint8)
offset += len(chunk)
f.flush()
base = payload.id.get_offset()
if base is None: raise ValueError('Payload dataset is not contiguous')
index['payload_file_offset'] = base
for frame in index['frames']: frame['offset'] += base
f.attrs['depth_codec_schema'] = SCHEMA
f.attrs['depth_encoding'] = 'log_u16'
f.attrs['decoded_depth_encoding'] = 'linear_scene_depth_cm'
f.attrs['unit'] = 'centimeter'
f.attrs['depth_log_index_json'] = json.dumps(index, ensure_ascii=False, separators=(',', ':'))
f.attrs['reader'] = 'tools.offload_data.depth_log_codec.DepthLogReader'
# Re-read every frame through the final HDF5 byte ranges before publishing.
reader = DepthLogReader(output)
with packed.open('rb') as original:
for i, entry in enumerate(index['frames']):
original.seek(entry['offset']-base)
expected = decode_codes(original.read(entry['length']),entry,index['height'],index['width'])
actual = reader.read_codes(i)
for a,b in zip(actual,expected):
if not np.array_equal(a.view(np.uint8),b.view(np.uint8)):
raise ValueError(f'HDF5 container roundtrip failed at frame {i}')
index['compressed_bytes'] = output.stat().st_size
index['compressed_sha256'] = file_sha256(output)
sidecar = Path(str(output)+'.index.json')
sidecar.write_text(json.dumps(index,ensure_ascii=False,separators=(',',':')))
return index,sidecar
def embedded_hdf5_index(path):
import h5py
with h5py.File(path,'r') as f:
if f.attrs.get('depth_codec_schema') != SCHEMA: return None
return json.loads(f.attrs['depth_log_index_json'])
class DepthLogReader:
"""Read a local packed frame, or use fetch_range(offset, length) remotely.
read_codes() retains uint16 for a compact cache. read() converts one frame
to float32 centimeters. RGB, poses and actions remain at source_uri.
"""
def __init__(self, path=None, index=None, fetch_range=None):
self.path = Path(path) if path is not None else None
self.index = index
if self.index is None:
with self.path.open('rb') as f: signature = f.read(8)
if signature == b'\x89HDF\r\n\x1a\n':
self.index = embedded_hdf5_index(self.path)
if self.index is None: raise ValueError('HDF5 does not use the log depth codec')
else:
self.index = json.loads(Path(str(path)+'.index.json').read_text())
if self.index['codec']['schema'] != SCHEMA: raise ValueError("Unsupported codec")
self.fetch_range = fetch_range
def read_codes(self, frame_index):
if not 0 <= frame_index < self.index['frame_count']: raise IndexError(frame_index)
entry = self.index['frames'][frame_index]
if self.fetch_range is not None:
blob = self.fetch_range(entry['offset'], entry['length'])
else:
with self.path.open('rb') as f:
f.seek(self.index.get('payload_file_offset',0))
if f.read(len(MAGIC)) != MAGIC: raise ValueError("Invalid depth file header")
f.seek(entry['offset'])
blob = f.read(entry['length'])
if len(blob) != entry['length']: raise ValueError("Truncated depth frame")
return decode_codes(blob, entry, self.index['height'], self.index['width'])
def read(self, frame_index):
return codes_to_depth(*self.read_codes(frame_index), self.index['codec'])
def read_depth_frame(path, frame_index):
"""Read either an original float32 HDF5 or a recompressed HDF5 during migration."""
import h5py
with h5py.File(path,'r') as f:
if f.attrs.get('depth_codec_schema') != SCHEMA:
return f['depth'][frame_index]
return DepthLogReader(path).read(frame_index)
|