"""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=' 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('= 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=' 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=' 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)