File size: 26,603 Bytes
2b01b59 | 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 | #!/usr/bin/env python3
"""Decode a recorded ZED SVO into left-camera images and exact frame timestamps.
Use a Python environment with pyzed.sl for native SDK decoding. Alternatively,
--timestamp-index uses CPU ffmpeg decoding with an exact, fingerprinted SDK
timestamp index and does not import pyzed. Input is always an existing SVO
file: this helper never opens a live camera. Progress is written to stderr.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import time
def _file_sha256(path):
digest = hashlib.sha256()
with Path(path).open("rb") as stream:
for block in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def decode_svo_cpu(input_path, output_path, timestamp_index, width=768, height=432, ffmpeg="ffmpeg",
image_format="jpg"):
"""Decode encoded left-eye pixels on CPU using a fingerprinted SDK time index.
SVO's HEVC frame-rate header does not give its saved frame timing. An exact
index from an earlier SDK read of this same file is therefore mandatory.
This branch never imports pyzed or requests GPU decoding.
"""
if image_format != "jpg":
raise ValueError("CPU decoding supports only jpg; PNG requires native ZED SDK decoding")
import numpy as np
source = Path(input_path).expanduser().resolve(strict=True)
destination = Path(output_path).expanduser().absolute()
index_path = Path(timestamp_index).expanduser().resolve(strict=True)
if not source.is_file() or source.suffix.lower() not in (".svo", ".svo2"):
raise ValueError("input must be an existing .svo or .svo2 file")
if width <= 0 or height <= 0:
raise ValueError("width and height must be positive")
if destination.exists() or destination.is_symlink():
raise FileExistsError("output must be a new directory: " + str(destination))
source_stat = source.stat()
index = json.loads(index_path.read_text(encoding="utf-8"))
matches = [entry for episode in index.get("episodes", {}).values() for entry in episode.values()
if Path(entry.get("source", "")).expanduser().resolve() == source]
if len(matches) != 1:
raise ValueError("timestamp index must identify this source exactly once")
entry = matches[0]
if entry.get("source_bytes") != source_stat.st_size:
raise ValueError("timestamp index source_bytes does not match SVO")
expected_sha = entry.get("source_sha256")
if (not isinstance(expected_sha, str) or len(expected_sha) != 64
or any(character not in "0123456789abcdefABCDEF" for character in expected_sha)):
raise ValueError("timestamp index requires source_sha256 for this SVO")
source_sha = _file_sha256(source)
if source_sha != expected_sha.lower():
raise ValueError("timestamp index source_sha256 does not match SVO")
timestamps = np.asarray(entry.get("image_timestamp_ns", []))
frame_indices = np.asarray(entry.get("frame_indices", []))
expected_count = entry.get("sdk_frame_count")
if (timestamps.ndim != 1 or frame_indices.ndim != 1
or timestamps.dtype.kind not in "iu" or frame_indices.dtype.kind not in "iu"
or len(timestamps) == 0 or len(timestamps) != expected_count
or len(timestamps) != entry.get("decoded_frame_count")
or not np.array_equal(frame_indices, np.arange(len(timestamps)))
or np.any(timestamps <= 0) or np.any(np.diff(timestamps) <= 0)):
raise ValueError("timestamp index has invalid frame counts, indices, or timestamps")
timestamps = timestamps.astype(np.int64)
frame_indices = frame_indices.astype(np.int64)
if np.any(timestamps <= 0):
raise ValueError("timestamp index exceeds signed 64-bit nanoseconds")
native_width, native_height = entry.get("width"), entry.get("height")
if (not isinstance(native_width, int) or not isinstance(native_height, int)
or native_width <= 0 or native_height <= 0):
raise ValueError("timestamp index lacks valid native dimensions")
destination.parent.mkdir(parents=True, exist_ok=True)
staging = Path(tempfile.mkdtemp(prefix="." + destination.name + ".partial-",
dir=str(destination.parent)))
started = time.monotonic()
try:
command = [os.fspath(ffmpeg), "-hide_banner", "-loglevel", "error", "-nostdin",
"-hwaccel", "none", "-threads", "2", "-i", str(source),
"-map", "0:v:0", "-vf",
"crop=iw/2:ih:0:0,scale={}:{}:flags=lanczos".format(width, height),
"-vsync", "0", "-threads", "2", "-q:v", "2", "-start_number", "0",
str(staging / "frame%06d.jpg")]
print("CPU decoding {}: {} indexed frames".format(source, expected_count), file=sys.stderr, flush=True)
process = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)
if process.returncode:
raise RuntimeError("ffmpeg CPU decoding failed: " + process.stderr.decode("utf-8", errors="replace")[-4000:])
images = sorted(staging.glob("frame*.jpg"))
expected_names = ["frame{:06d}.jpg".format(number) for number in range(len(timestamps))]
if [path.name for path in images] != expected_names or any(path.stat().st_size == 0 for path in images):
raise ValueError("CPU frame count/sequence mismatch: decoded {}, SDK index reports {}".format(
len(images), expected_count))
after = source.stat()
if (after.st_size, after.st_mtime_ns) != (source_stat.st_size, source_stat.st_mtime_ns):
raise RuntimeError("source SVO changed during decoding")
with (staging / "timestamps.npz").open("xb") as stream:
np.savez_compressed(stream, timestamp_ns=timestamps, frame_index=frame_indices)
metadata = {
"source": str(source), "source_size": int(source_stat.st_size),
"source_mtime_ns": int(source_stat.st_mtime_ns), "source_sha256": source_sha,
"width": int(width), "height": int(height), "frame_count": int(expected_count),
"native_width": native_width, "native_height": native_height,
"sdk_version": index.get("sdk_version", "unknown; supplied timestamp index"),
"serial": entry.get("serial"), "decoder": "ffmpeg",
"view": "encoded left half; SDK rectification not claimed",
"jpeg_quality": "ffmpeg -q:v 2", "color": "ffmpeg decoded color JPEG",
"image_format": "jpg", "lossless": False,
"timestamp_source": index.get("timestamp_source", "Recorded SVO SDK IMAGE timestamp index"),
"timestamp_index": str(index_path), "timestamp_index_sha256": _file_sha256(index_path),
"header_fps": entry.get("fps"),
"timing_note": "Use exact indexed timestamp_ns, not the HEVC frame-rate header.",
"first_timestamp_ns": int(timestamps[0]), "last_timestamp_ns": int(timestamps[-1]),
"recorded_duration_s": int(timestamps[-1] - timestamps[0]) / 1e9,
"decode_seconds": time.monotonic() - started, "complete": True,
}
(staging / "metadata.json").write_text(json.dumps(metadata, indent=2) + "\n", encoding="utf-8")
if destination.exists() or destination.is_symlink():
raise FileExistsError("output was created by another process: " + str(destination))
os.rename(str(staging), str(destination))
print("Saved {} CPU-decoded frames with exact indexed timestamps to {}".format(
len(timestamps), destination), file=sys.stderr, flush=True)
return metadata
except BaseException:
shutil.rmtree(str(staging), ignore_errors=True)
raise
def _calibration_metadata(info, width, height):
"""Serialize optional SDK calibration, scaling rectified K for saved pixels."""
import numpy as np
configuration = info.camera_configuration
native = configuration.resolution
native_size = [int(native.width), int(native.height)]
scale_x, scale_y = width / native_size[0], height / native_size[1]
result = {
"source": "ZED CameraInformation.camera_configuration",
"native_resolution": native_size,
"output_resolution": [int(width), int(height)],
"rectified_intrinsics_scale": [scale_x, scale_y],
}
for kind, attribute in (("rectified", "calibration_parameters"),
("raw", "calibration_parameters_raw")):
calibration = getattr(configuration, attribute, None)
if calibration is None:
continue
cameras = {}
for side in ("left", "right"):
camera = getattr(calibration, side + "_cam", None)
if camera is None or not all(hasattr(camera, name) for name in ("fx", "fy", "cx", "cy")):
continue
native_k = [[float(camera.fx), 0.0, float(camera.cx)],
[0.0, float(camera.fy), float(camera.cy)], [0.0, 0.0, 1.0]]
values = {"native_K": native_k}
if kind == "rectified":
values["K"] = [[native_k[0][0] * scale_x, 0.0, native_k[0][2] * scale_x],
[0.0, native_k[1][1] * scale_y, native_k[1][2] * scale_y],
[0.0, 0.0, 1.0]]
if hasattr(camera, "disto"):
values["distortion"] = np.asarray(camera.disto, dtype=float).reshape(-1).tolist()
cameras[side] = values
transform = getattr(calibration, "stereo_transform", None)
if transform is not None and hasattr(transform, "m"):
cameras["stereo_transform"] = np.asarray(transform.m, dtype=float).tolist()
if cameras:
result[kind] = cameras
return result if "rectified" in result or "raw" in result else None
def decode_svo(input_path, output_path, width=768, height=432, image_format="jpg"):
"""Create a new, complete frame cache; remove staging files on failure."""
if image_format not in ("jpg", "png"):
raise ValueError("image_format must be jpg or png")
source = Path(input_path).expanduser().resolve(strict=True)
destination = Path(output_path).expanduser().absolute()
if not source.is_file() or source.suffix.lower() not in (".svo", ".svo2"):
raise ValueError("input must be an existing .svo or .svo2 file")
if width <= 0 or height <= 0:
raise ValueError("width and height must be positive")
if destination.exists() or destination.is_symlink():
raise FileExistsError("output must be a new directory: " + str(destination))
# Lazy SDK import keeps --help usable without CUDA, pyzed, or camera SDKs.
import cv2
import numpy as np
import pyzed.sl as sl
source_stat = source.stat()
destination.parent.mkdir(parents=True, exist_ok=True)
staging = Path(tempfile.mkdtemp(prefix="." + destination.name + ".partial-",
dir=str(destination.parent)))
started = time.monotonic()
try:
init = sl.InitParameters()
init.set_from_svo_file(str(source))
init.svo_real_time_mode = False
init.depth_mode = sl.DEPTH_MODE.NONE
init.sdk_verbose = 0 # SDK 5.0.7 requires an int here, not Python bool.
# Do not set sdk_verbose_log_file: the SDK can redirect the process's
# entire stdout file descriptor when a log file is configured.
camera = sl.Camera()
timestamps = []
frame_indices = []
try:
status = camera.open(init)
if status != sl.ERROR_CODE.SUCCESS:
raise RuntimeError("SVO open failed: " + str(status))
info = camera.get_camera_information()
expected_count = int(camera.get_svo_number_of_frames())
if expected_count <= 0:
raise ValueError("SVO has no recorded frames")
native = info.camera_configuration.resolution
metadata = {
"source": str(source),
"source_size": int(source_stat.st_size),
"source_mtime_ns": int(source_stat.st_mtime_ns),
"width": int(width),
"height": int(height),
"native_width": int(native.width),
"native_height": int(native.height),
"sdk_version": str(sl.Camera.get_sdk_version()),
"serial": int(info.serial_number),
"frame_count": expected_count,
"sdk_reported_frame_count": expected_count,
"warnings": [],
"view": "sl.VIEW.LEFT (rectified)",
"image_format": image_format,
"lossless": image_format == "png",
"color": "RGB {}; SDK BGRA converted to BGR for cv2.imwrite".format(
"JPEG" if image_format == "jpg" else "PNG"),
"timestamp_source": "Recorded SVO sl.TIME_REFERENCE.IMAGE.get_nanoseconds()",
"header_fps": float(info.camera_configuration.fps),
"timing_note": "Use timestamp_ns, not header_fps: recorded frames can have gaps.",
"complete": False,
}
if image_format == "png":
metadata["png_compression"] = 1
metadata["lossless_scope"] = "PNG encoding of SDK decoded and resized RGB pixels"
write_options = [cv2.IMWRITE_PNG_COMPRESSION, 1]
else:
metadata["jpeg_quality"] = 95
write_options = [cv2.IMWRITE_JPEG_QUALITY, 95]
calibration = _calibration_metadata(info, width, height)
if calibration is not None:
if hasattr(init, "coordinate_units"):
calibration["stereo_transform_translation_units"] = str(init.coordinate_units)
metadata["calibration"] = calibration
image = sl.Mat()
runtime = sl.RuntimeParameters()
runtime.enable_depth = False
resolution = sl.Resolution(int(width), int(height))
print("Decoding {}: {} frames".format(source, expected_count), file=sys.stderr, flush=True)
while True:
status = camera.grab(runtime)
if status == sl.ERROR_CODE.END_OF_SVOFILE_REACHED:
# SDK 5.0.7 can intermittently report EOF one frame early
# on valid H265 SVOs. EOF itself exposes stale image/time
# buffers, so never retrieve it as a new frame. Retry only
# the single missing final frame through an explicit seek.
if timestamps and expected_count - len(timestamps) == 1:
missing_index = len(timestamps)
recovery_detail = "explicit seek"
for attempt in range(2):
camera.set_svo_position(missing_index)
status = camera.grab(runtime)
if status != sl.ERROR_CODE.END_OF_SVOFILE_REACHED:
break
if status == sl.ERROR_CODE.END_OF_SVOFILE_REACHED:
# Some H265 tails require decoding the preceding
# frame before the final one. A direct final-frame
# seek can return EOF despite a valid final image.
rewind_index = missing_index - 1
camera.set_svo_position(rewind_index)
for verified_index in range(rewind_index, missing_index + 1):
status = camera.grab(runtime)
if status != sl.ERROR_CODE.SUCCESS:
break
position = int(camera.get_svo_position())
recovered_time = int(camera.get_timestamp(sl.TIME_REFERENCE.IMAGE).get_nanoseconds())
if position != verified_index:
raise ValueError("SVO tail recovery returned an unexpected frame index")
if verified_index < missing_index:
if recovered_time != timestamps[verified_index]:
raise ValueError("SVO tail recovery changed a previously decoded timestamp")
status = camera.retrieve_image(image, sl.VIEW.LEFT, sl.MEM.CPU, resolution)
if status != sl.ERROR_CODE.SUCCESS:
raise RuntimeError("SVO overlap image retrieval failed during tail recovery")
recovery_detail = "preceding-frame seek with overlap timestamp verified"
for tail_attempt in range(2):
if status != sl.ERROR_CODE.END_OF_SVOFILE_REACHED:
break
# Full traversal can leave H265 tail decoding stuck.
# A fresh session started at the preceding frame
# avoids that state while verifying the overlap.
camera.close()
camera = sl.Camera()
status = camera.open(init)
if status != sl.ERROR_CODE.SUCCESS:
raise RuntimeError("SVO reopen failed during tail seek: " + str(status))
if int(camera.get_svo_number_of_frames()) != expected_count:
raise ValueError("SVO frame count changed after reopening")
camera.set_svo_position(missing_index - 1)
for verified_index in range(missing_index - 1, missing_index + 1):
status = camera.grab(runtime)
if status != sl.ERROR_CODE.SUCCESS:
break
position = int(camera.get_svo_position())
recovered_time = int(camera.get_timestamp(sl.TIME_REFERENCE.IMAGE).get_nanoseconds())
if position != verified_index:
raise ValueError("SVO tail recovery returned an unexpected frame index")
if verified_index < missing_index:
if recovered_time != timestamps[verified_index]:
raise ValueError("SVO tail recovery changed a previously decoded timestamp")
status = camera.retrieve_image(image, sl.VIEW.LEFT, sl.MEM.CPU, resolution)
if status != sl.ERROR_CODE.SUCCESS:
raise RuntimeError("SVO overlap image retrieval failed during tail recovery")
recovery_detail = "fresh decoder preceding-frame seek with overlap timestamp verified"
if status == sl.ERROR_CODE.END_OF_SVOFILE_REACHED:
# A decoder session may remain stuck at EOF. Reopen
# once and replay from the beginning: some SVOs
# still stop early after a short tail seek. Verify
# every overlap; never append or fabricate it.
camera.close()
camera = sl.Camera()
status = camera.open(init)
if status != sl.ERROR_CODE.SUCCESS:
raise RuntimeError("SVO reopen failed during tail recovery: " + str(status))
if int(camera.get_svo_number_of_frames()) != expected_count:
raise ValueError("SVO frame count changed after reopening")
rewind_index = 0
camera.set_svo_position(rewind_index)
for verified_index in range(rewind_index, missing_index + 1):
status = camera.grab(runtime)
if status != sl.ERROR_CODE.SUCCESS:
break
position = int(camera.get_svo_position())
recovered_time = int(camera.get_timestamp(sl.TIME_REFERENCE.IMAGE).get_nanoseconds())
if position != verified_index:
raise ValueError("SVO tail recovery returned an unexpected frame index")
if verified_index < missing_index and recovered_time != timestamps[verified_index]:
raise ValueError("SVO tail recovery changed a previously decoded timestamp")
recovery_detail = "fresh decoder session with all overlap frames verified from frame 0"
if status == sl.ERROR_CODE.SUCCESS:
metadata["warnings"].append(
"SDK reported premature EOF after {}/{} frames; recovered real final "
"frame {} by {} ({} direct seek attempt(s)).".format(
len(timestamps), expected_count, missing_index, recovery_detail, attempt + 1))
print(" WARNING: " + metadata["warnings"][-1], file=sys.stderr, flush=True)
if status == sl.ERROR_CODE.END_OF_SVOFILE_REACHED:
break
if status != sl.ERROR_CODE.SUCCESS:
raise RuntimeError("SVO grab failed after {} frames: {}".format(len(timestamps), status))
index = int(camera.get_svo_position())
timestamp = int(camera.get_timestamp(sl.TIME_REFERENCE.IMAGE).get_nanoseconds())
if index != len(frame_indices):
raise ValueError("SVO frame sequence is not contiguous: expected {}, got {}".format(
len(frame_indices), index))
if timestamp <= 0 or (timestamps and timestamp <= timestamps[-1]):
raise ValueError("SVO image timestamps are not strictly increasing at frame " + str(index))
status = camera.retrieve_image(image, sl.VIEW.LEFT, sl.MEM.CPU, resolution)
if status != sl.ERROR_CODE.SUCCESS:
raise RuntimeError("SVO image retrieval failed at frame {}: {}".format(index, status))
bgra = image.get_data()
if bgra.shape != (height, width, 4):
raise ValueError("unexpected SDK BGRA image shape: " + str(bgra.shape))
bgr = cv2.cvtColor(bgra, cv2.COLOR_BGRA2BGR)
image_path = staging / "frame{:06d}.{}".format(index, image_format)
if not cv2.imwrite(str(image_path), bgr, write_options):
raise OSError("could not write {}: {}".format(image_format.upper(), image_path))
timestamps.append(timestamp)
frame_indices.append(index)
if len(timestamps) % 100 == 0:
print(" {}: {}/{} frames".format(source.stem, len(timestamps), expected_count),
file=sys.stderr, flush=True)
if len(timestamps) != expected_count:
raise ValueError("SVO frame count mismatch: decoded {}, SDK reports {}".format(
len(timestamps), expected_count))
finally:
camera.close()
after = source.stat()
if (after.st_size, after.st_mtime_ns) != (source_stat.st_size, source_stat.st_mtime_ns):
raise RuntimeError("source SVO changed during decoding")
with (staging / "timestamps.npz").open("xb") as stream:
np.savez_compressed(stream, timestamp_ns=np.asarray(timestamps, dtype=np.int64),
frame_index=np.asarray(frame_indices, dtype=np.int64))
metadata.update({
"frame_count": len(timestamps),
"first_timestamp_ns": timestamps[0],
"last_timestamp_ns": timestamps[-1],
"recorded_duration_s": (timestamps[-1] - timestamps[0]) / 1e9,
"decode_seconds": time.monotonic() - started,
"complete": True,
})
(staging / "metadata.json").write_text(json.dumps(metadata, indent=2) + "\n", encoding="utf-8")
if destination.exists() or destination.is_symlink():
raise FileExistsError("output was created by another process: " + str(destination))
os.rename(str(staging), str(destination))
print("Saved {} frames with recorded timestamps to {}".format(len(timestamps), destination),
file=sys.stderr, flush=True)
return metadata
except BaseException:
shutil.rmtree(str(staging), ignore_errors=True)
raise
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--input", required=True, help="existing recorded .svo/.svo2 file")
parser.add_argument("--output", required=True, help="new directory for a complete frame cache")
parser.add_argument("--width", type=int, default=768)
parser.add_argument("--height", type=int, default=432)
parser.add_argument("--image-format", choices=("jpg", "png"), default="jpg",
help="saved image encoding (default: jpg; lossless PNG requires native SDK)")
parser.add_argument("--timestamp-index", help="fingerprinted exact SDK frame index; selects CPU ffmpeg decoding")
parser.add_argument("--ffmpeg", default="ffmpeg", help="ffmpeg executable for --timestamp-index mode")
args = parser.parse_args()
try:
if args.timestamp_index:
decode_svo_cpu(args.input, args.output, args.timestamp_index, args.width, args.height, args.ffmpeg,
image_format=args.image_format)
else:
decode_svo(args.input, args.output, args.width, args.height, image_format=args.image_format)
except (ImportError, OSError, RuntimeError, ValueError) as exc:
print("svo_decode: " + str(exc), file=sys.stderr, flush=True)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
|