Add chirp Move sync sweep receipts

This commit is contained in:
Meta Vens 2026-05-31 22:30:57 +01:00
commit 00ac2e50a6
7 changed files with 1841 additions and 0 deletions

View file

@ -286,3 +286,4 @@
{"ts":"2026-05-31T21:48:00+01:00","type":"implementation","status":"ok","note":"Mimir's Eve/CultUI editor surface now uses editor anatomy instead of dashboard columns: Scene Graph left, Scene View center, thin Asset Browser below the view, and Inspector right. The old Program/Sync rail was removed from the inspector side so telemetry no longer steals editor hierarchy. Headless empty-runtime capture verified the shell at 1280x720 with no sibling overlap.","files":["src/Mimir.Runtime/MimirRuntime.cs"],"source":"dotnet build src/Mimir.App/Mimir.App.csproj --no-restore; Mimir.App --headless --headless-width 1280 --headless-height 720 --capture-frame artifacts/runtime/mimir-editor-shell-final-headless.png"}
{"ts":"2026-05-31T22:06:00+01:00","type":"implementation","status":"ok","note":"Mimir's editor scene view now behaves as a compositor/program preview rather than a dashboard readout: SceneEditorState owns normalized program-frame placement for visible nodes, the CultUI preview renders those rectangles, inspector X/Y/W/H controls mutate the same node transforms as mouse-drag input, and video surface intents carry that placement into Fensalir field support. This makes outgoing element arrangement an editor-owned state path instead of a presentationControls-only opacity/layer list.","files":["src/Mimir.Runtime/MimirRuntime.cs","src/Mimir.Runtime/Synchronization/MimirSceneEditorState.cs","src/Mimir.Runtime/Synchronization/MimirFensalirBridgeContracts.cs","src/Mimir.Runtime/Synchronization/MimirFensalirFieldLowering.cs"],"source":"dotnet build src/Mimir.App/Mimir.App.csproj --no-restore; Mimir.App --headless --headless-width 1280 --headless-height 720 --capture-frame artifacts/runtime/mimir-editor-compositor-preview-headless.png"}
{"ts":"2026-05-31T22:18:00+01:00","type":"implementation","status":"ok","note":"Mimir editor scene view no longer carries sync/spectrum telemetry; Odin's Nightwing TUI is the telemetry surface over CultMesh. The center panel now prioritizes compositor affordance surface: the program preview consumes the scene-view body, with only viewport actions below it and asset browsing in the thin lower shelf.","files":["src/Mimir.Runtime/MimirRuntime.cs"],"source":"dotnet build src/Mimir.App/Mimir.App.csproj --no-restore; Mimir.App --headless --headless-width 1280 --headless-height 720 --capture-frame artifacts/runtime/mimir-editor-preview-maximized-headless.png"}
{"ts": "2026-05-31T22:30:36+01:00", "type": "verification", "status": "partial", "note": "Added sync_sweep.py plus stdlib-only Nightwing witness helpers. Live receipt artifacts/runtime/sync-sweep-hints-live proved Nightwing owns Eye/Move localization locally: nw-eye-0 and nw-eye-1 each captured about 1874 frames at 320x240@187 with zero sequence gaps and emitted 8/8 compact mimir.move_controller_observation_state.v1 hints, while Starfire analyzed its own ASIO/DShow/Kiyo streams. Nightwing builtin mic capture works but the cheap local chirp hint is not yet reliable enough to score as a timing witness."}

View file

@ -0,0 +1,211 @@
#!/usr/bin/env python3
"""Probe Nightwing ALSA capture devices without external recorder tools."""
from __future__ import annotations
import argparse
import ctypes
import ctypes.util
import json
import math
import os
import sys
import time
import wave
from pathlib import Path
SND_PCM_STREAM_CAPTURE = 1
SND_PCM_FORMAT_S16_LE = 2
SND_PCM_ACCESS_RW_INTERLEAVED = 3
_libasound_name = ctypes.util.find_library("asound")
if not _libasound_name:
raise SystemExit("libasound.so not found")
alsa = ctypes.CDLL(_libasound_name, use_errno=True)
alsa.snd_pcm_open.argtypes = [ctypes.POINTER(ctypes.c_void_p), ctypes.c_char_p, ctypes.c_int, ctypes.c_int]
alsa.snd_pcm_open.restype = ctypes.c_int
alsa.snd_pcm_set_params.argtypes = [
ctypes.c_void_p,
ctypes.c_int,
ctypes.c_int,
ctypes.c_uint,
ctypes.c_uint,
ctypes.c_int,
ctypes.c_uint,
]
alsa.snd_pcm_set_params.restype = ctypes.c_int
alsa.snd_pcm_readi.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_ulong]
alsa.snd_pcm_readi.restype = ctypes.c_long
alsa.snd_pcm_prepare.argtypes = [ctypes.c_void_p]
alsa.snd_pcm_prepare.restype = ctypes.c_int
alsa.snd_pcm_recover.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int]
alsa.snd_pcm_recover.restype = ctypes.c_int
alsa.snd_pcm_close.argtypes = [ctypes.c_void_p]
alsa.snd_pcm_close.restype = ctypes.c_int
alsa.snd_strerror.argtypes = [ctypes.c_int]
alsa.snd_strerror.restype = ctypes.c_char_p
def alsa_error(code: int) -> str:
raw = alsa.snd_strerror(code)
return raw.decode("utf-8", errors="replace") if raw else f"ALSA error {code}"
def read_proc_cards() -> str:
path = Path("/proc/asound/cards")
return path.read_text(encoding="utf-8", errors="replace") if path.exists() else ""
def capture(device: str, rate: int, channels: int, seconds: float, latency_us: int) -> tuple[bytes, dict[str, object]]:
handle = ctypes.c_void_p()
open_wall_ns = time.time_ns()
open_monotonic = time.monotonic()
code = alsa.snd_pcm_open(ctypes.byref(handle), device.encode("utf-8"), SND_PCM_STREAM_CAPTURE, 0)
if code < 0:
raise RuntimeError(f"open failed: {alsa_error(code)}")
try:
code = alsa.snd_pcm_set_params(
handle,
SND_PCM_FORMAT_S16_LE,
SND_PCM_ACCESS_RW_INTERLEAVED,
int(channels),
int(rate),
1,
int(latency_us),
)
if code < 0:
raise RuntimeError(f"set_params failed: {alsa_error(code)}")
frames_per_read = max(128, min(4096, int(rate // 20)))
sample_count = frames_per_read * channels
buffer = (ctypes.c_int16 * sample_count)()
deadline = time.monotonic() + seconds
chunks: list[bytes] = []
frames = 0
read_calls = 0
recoveries = 0
first_read_monotonic: float | None = None
first_read_wall_ns: int | None = None
while time.monotonic() < deadline:
got = int(alsa.snd_pcm_readi(handle, ctypes.byref(buffer), frames_per_read))
if got < 0:
recovered = int(alsa.snd_pcm_recover(handle, got, 1))
if recovered < 0:
raise RuntimeError(f"read failed: {alsa_error(got)} / recover {alsa_error(recovered)}")
recoveries += 1
continue
if got == 0:
time.sleep(0.001)
continue
if first_read_monotonic is None:
first_read_monotonic = time.monotonic()
first_read_wall_ns = time.time_ns()
read_calls += 1
frames += got
byte_count = got * channels * 2
chunks.append(bytes(ctypes.string_at(ctypes.byref(buffer), byte_count)))
pcm = b"".join(chunks)
stats = pcm_stats(pcm, channels)
stats.update(
{
"device": device,
"rate": rate,
"channels": channels,
"frames": frames,
"duration_s": frames / rate if rate > 0 else 0.0,
"read_calls": read_calls,
"recoveries": recoveries,
"open_wall_ns": open_wall_ns,
"open_monotonic_s": open_monotonic,
"first_read_monotonic_s": first_read_monotonic,
"first_read_wall_ns": first_read_wall_ns,
"end_wall_ns": time.time_ns(),
}
)
return pcm, stats
finally:
alsa.snd_pcm_close(handle)
def pcm_stats(pcm: bytes, channels: int) -> dict[str, object]:
if not pcm:
return {"rms": [], "peak": [], "mean_abs": []}
values = memoryview(pcm).cast("h")
frames = len(values) // max(1, channels)
rms: list[float] = []
peak: list[float] = []
mean_abs: list[float] = []
for channel in range(channels):
total = 0.0
abs_total = 0.0
max_abs = 0
for frame in range(frames):
sample = int(values[frame * channels + channel])
total += sample * sample
abs_total += abs(sample)
max_abs = max(max_abs, abs(sample))
denom = max(1, frames)
rms.append(math.sqrt(total / denom) / 32768.0)
peak.append(max_abs / 32768.0)
mean_abs.append(abs_total / denom / 32768.0)
return {"rms": rms, "peak": peak, "mean_abs": mean_abs}
def write_wav(path: Path, pcm: bytes, rate: int, channels: int) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with wave.open(str(path), "wb") as wav:
wav.setnchannels(channels)
wav.setsampwidth(2)
wav.setframerate(rate)
wav.writeframes(pcm)
def append_visible_log(message: str) -> None:
path = Path.home() / ".local/state/gamecult/codex-ssh-activity.log"
path.parent.mkdir(parents=True, exist_ok=True)
stamp = time.strftime("%Y-%m-%dT%H:%M:%S%z")
with path.open("a", encoding="utf-8") as log:
log.write(f"{stamp} Codex: {message}\n")
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--device", default="hw:0,0")
parser.add_argument("--rate", type=int, default=48000)
parser.add_argument("--channels", type=int, default=2)
parser.add_argument("--seconds", type=float, default=2.0)
parser.add_argument("--latency-us", type=int, default=50_000)
parser.add_argument("--wav")
parser.add_argument("--json")
parser.add_argument("--visible-log", action="store_true")
args = parser.parse_args()
if args.visible_log:
append_visible_log(
f"ALSA mic probe starting device={args.device} rate={args.rate} channels={args.channels} seconds={args.seconds:.2f}"
)
print("alsa-cards")
print(read_proc_cards().rstrip())
pcm, stats = capture(args.device, args.rate, args.channels, args.seconds, args.latency_us)
if args.wav:
write_wav(Path(args.wav), pcm, args.rate, args.channels)
stats["wav"] = args.wav
print("alsa-capture " + json.dumps(stats, sort_keys=True))
if args.json:
Path(args.json).parent.mkdir(parents=True, exist_ok=True)
Path(args.json).write_text(json.dumps(stats, indent=2, sort_keys=True), encoding="utf-8")
if args.visible_log:
append_visible_log(
"ALSA mic probe complete "
f"device={args.device} frames={stats['frames']} rms={stats['rms']} peak={stats['peak']}"
)
return 0 if stats.get("frames", 0) else 1
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -0,0 +1,326 @@
#!/usr/bin/env python3
"""Compare Nightwing integrated mic chirp timing against Starfire Scarlett loopback."""
from __future__ import annotations
import argparse
import ctypes
import json
import os
import shutil
import subprocess
import sys
import threading
import time
import wave
from pathlib import Path
import numpy as np
from move_latency_probe import build_events, detect_audio_peaks, fit_schedule, generate_chirp
DEFAULT_ASIO_DLL = Path(__file__).resolve().parents[1] / "native" / "asio_capture" / "build" / "Release" / "mimir_asio_capture.dll"
DEFAULT_ASIO_CLSID = "{AC4D0455-50D7-4498-B3CD-9A41D130B759}"
DEFAULT_FFPLAY = (
Path.home()
/ "AppData/Local/Microsoft/WinGet/Packages/Gyan.FFmpeg_Microsoft.Winget.Source_8wekyb3d8bbwe"
/ "ffmpeg-8.1.1-full_build/bin/ffplay.exe"
)
class AsioRecorder:
def __init__(self, dll_path: Path, clsid: str, sample_rate: int, channels: set[int]) -> None:
self.dll = ctypes.WinDLL(str(dll_path))
self.dll.mimir_asio_create.argtypes = [
ctypes.c_char_p,
ctypes.c_double,
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_int),
]
self.dll.mimir_asio_create.restype = ctypes.c_void_p
self.dll.mimir_asio_start.argtypes = [ctypes.c_void_p]
self.dll.mimir_asio_start.restype = ctypes.c_int
self.dll.mimir_asio_read.argtypes = [
ctypes.c_void_p,
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_longlong),
ctypes.POINTER(ctypes.c_ulonglong),
ctypes.POINTER(ctypes.c_int),
ctypes.POINTER(ctypes.c_float),
ctypes.c_int,
]
self.dll.mimir_asio_read.restype = ctypes.c_int
self.dll.mimir_asio_destroy.argtypes = [ctypes.c_void_p]
self.dll.mimir_asio_destroy.restype = None
actual_rate = ctypes.c_int()
input_count = ctypes.c_int()
max_frames = ctypes.c_int()
self.handle = self.dll.mimir_asio_create(
clsid.encode("utf-8"),
float(sample_rate),
ctypes.byref(actual_rate),
ctypes.byref(input_count),
ctypes.byref(max_frames),
)
if not self.handle:
raise RuntimeError("Could not create ASIO capture")
self.sample_rate = int(actual_rate.value)
self.input_count = int(input_count.value)
self.max_frames = int(max_frames.value)
self.channels = channels
self.buffer = (ctypes.c_float * self.max_frames)()
self.samples: dict[int, list[float]] = {channel: [] for channel in sorted(channels)}
self.first_read_wall_ns: int | None = None
self.open_wall_ns = time.time_ns()
self.read_calls = 0
self.running = False
if not self.dll.mimir_asio_start(self.handle):
self.close()
raise RuntimeError("Could not start ASIO capture")
def record_for(self, seconds: float) -> None:
self.running = True
deadline = time.monotonic() + seconds
channel = ctypes.c_int()
timestamp_ns = ctypes.c_longlong()
sequence = ctypes.c_ulonglong()
frame_count = ctypes.c_int()
while time.monotonic() < deadline:
ok = self.dll.mimir_asio_read(
self.handle,
ctypes.byref(channel),
ctypes.byref(timestamp_ns),
ctypes.byref(sequence),
ctypes.byref(frame_count),
self.buffer,
self.max_frames,
)
if not ok:
time.sleep(0.001)
continue
self.read_calls += 1
if self.first_read_wall_ns is None:
self.first_read_wall_ns = time.time_ns()
ch = int(channel.value)
frames = max(0, min(int(frame_count.value), self.max_frames))
if ch not in self.samples or frames == 0:
continue
self.samples[ch].extend(float(self.buffer[index]) for index in range(frames))
self.running = False
def mono(self) -> np.ndarray:
arrays = [np.asarray(values, dtype=np.float32) for values in self.samples.values() if values]
if not arrays:
return np.zeros(0, dtype=np.float32)
length = min(array.size for array in arrays)
if length <= 0:
return np.zeros(0, dtype=np.float32)
stacked = np.stack([array[:length] for array in arrays])
return np.mean(stacked, axis=0).astype(np.float32)
def write_wav(self, path: Path) -> None:
samples = np.clip(self.mono(), -1.0, 1.0)
path.parent.mkdir(parents=True, exist_ok=True)
with wave.open(str(path), "wb") as wav:
wav.setnchannels(1)
wav.setsampwidth(2)
wav.setframerate(self.sample_rate)
wav.writeframes((samples * 32767.0).astype("<i2").tobytes())
def close(self) -> None:
if self.handle:
self.dll.mimir_asio_destroy(self.handle)
self.handle = None
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--ssh-target", default="nightwing")
parser.add_argument("--remote-device", default="hw:0,0")
parser.add_argument("--remote-rate", type=int, default=48000)
parser.add_argument("--remote-channels", type=int, default=2)
parser.add_argument("--asio-dll", default=str(DEFAULT_ASIO_DLL))
parser.add_argument("--asio-clsid", default=DEFAULT_ASIO_CLSID)
parser.add_argument("--asio-channels", default="2,3")
parser.add_argument("--ffplay", default=str(DEFAULT_FFPLAY))
parser.add_argument("--out-dir", default="artifacts/runtime/nightwing-audio-sync")
parser.add_argument("--duration", type=float, default=8.0)
parser.add_argument("--capture-pad", type=float, default=2.0)
parser.add_argument("--lead", type=float, default=1.2)
parser.add_argument("--interval", type=float, default=0.8)
parser.add_argument("--pulses", type=int, default=8)
parser.add_argument("--schedule", choices=("uniform", "debruijn"), default="debruijn")
parser.add_argument("--alphabet-size", type=int, default=8)
parser.add_argument("--order", type=int, default=3)
parser.add_argument("--chirp-ms", type=float, default=80.0)
parser.add_argument("--sample-rate", type=int, default=48000)
return parser.parse_args()
def mono_copy_wav(src: Path, dst: Path) -> None:
with wave.open(str(src), "rb") as wav:
rate = wav.getframerate()
channels = wav.getnchannels()
pcm = wav.readframes(wav.getnframes())
samples = np.frombuffer(pcm, dtype="<i2").reshape((-1, channels)).astype(np.float32)
mono = np.mean(samples, axis=1)
dst.parent.mkdir(parents=True, exist_ok=True)
with wave.open(str(dst), "wb") as wav:
wav.setnchannels(1)
wav.setsampwidth(2)
wav.setframerate(rate)
wav.writeframes(np.clip(mono, -32768, 32767).astype("<i2").tobytes())
def estimate_clock_offset_ns(ssh_target: str, samples: int = 5) -> dict[str, float | int]:
offsets: list[float] = []
rtts: list[float] = []
for _ in range(samples):
start = time.time_ns()
proc = subprocess.run(
["ssh", ssh_target, "python3 -c 'import time; print(time.time_ns())'"],
check=True,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
end = time.time_ns()
remote = int(proc.stdout.strip())
midpoint = (start + end) / 2.0
offsets.append(remote - midpoint)
rtts.append(end - start)
best = min(range(len(rtts)), key=lambda index: rtts[index])
return {
"remote_minus_local_clock_offset_ns": offsets[best],
"best_rtt_ns": int(rtts[best]),
"median_offset_ns": float(np.median(offsets)),
"median_rtt_ns": float(np.median(rtts)),
}
def remote_log(ssh_target: str, message: str) -> None:
script = (
"from pathlib import Path\n"
"import datetime\n"
"p=Path.home()/'.local/state/gamecult/codex-ssh-activity.log'\n"
"p.parent.mkdir(parents=True, exist_ok=True)\n"
f"p.open('a', encoding='utf-8').write(datetime.datetime.now().astimezone().isoformat() + ' Codex: {message}\\n')\n"
)
subprocess.run(["ssh", ssh_target, "python3", "-"], input=script, text=True, check=False)
def main() -> int:
args = parse_args()
out_dir = Path(args.out_dir)
if out_dir.exists():
suffix = time.strftime("%Y%m%d-%H%M%S")
out_dir = out_dir.with_name(out_dir.name + "-" + suffix)
out_dir.mkdir(parents=True, exist_ok=True)
events = build_events(args)
chirp_path = out_dir / "chirp-train.wav"
prototype = generate_chirp(chirp_path, args, events)
(out_dir / "event-schedule.json").write_text(json.dumps(events, indent=2), encoding="utf-8")
shutil.copy2(Path(__file__).with_name("nightwing_alsa_capture_probe.py"), out_dir / "nightwing_alsa_capture_probe.py")
clock = estimate_clock_offset_ns(args.ssh_target)
remote_log(args.ssh_target, "Nightwing audio sync chirp probe arming integrated mic recorder.")
remote_wav = "/tmp/nightwing-audio-sync-mic.wav"
remote_json = "/tmp/nightwing-audio-sync-mic.json"
remote_seconds = args.duration + args.capture_pad
remote_cmd = [
"ssh",
args.ssh_target,
"python3",
"/tmp/nightwing_alsa_capture_probe.py",
"--device",
args.remote_device,
"--rate",
str(args.remote_rate),
"--channels",
str(args.remote_channels),
"--seconds",
f"{remote_seconds:.3f}",
"--wav",
remote_wav,
"--json",
remote_json,
"--visible-log",
]
remote = subprocess.Popen(remote_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
time.sleep(0.5)
channels = {int(part.strip()) for part in args.asio_channels.split(",") if part.strip()}
asio = AsioRecorder(Path(args.asio_dll), args.asio_clsid, args.sample_rate, channels)
asio_thread = threading.Thread(target=asio.record_for, args=(remote_seconds,), daemon=True)
asio_thread.start()
time.sleep(0.2)
play_wall_ns = time.time_ns()
play = subprocess.run(
[args.ffplay, "-nodisp", "-autoexit", "-loglevel", "quiet", str(chirp_path)],
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
asio_thread.join(timeout=remote_seconds + 2.0)
asio.write_wav(out_dir / "starfire-loopback.wav")
local_first_wall_ns = asio.first_read_wall_ns
asio.close()
remote_stdout, remote_stderr = remote.communicate(timeout=remote_seconds + 5.0)
(out_dir / "nightwing-recorder.out.log").write_text(remote_stdout, encoding="utf-8", errors="replace")
(out_dir / "nightwing-recorder.err.log").write_text(remote_stderr, encoding="utf-8", errors="replace")
subprocess.run(["scp", f"{args.ssh_target}:{remote_wav}", str(out_dir / "nightwing-integrated-mic.wav")], check=True)
subprocess.run(["scp", f"{args.ssh_target}:{remote_json}", str(out_dir / "nightwing-integrated-mic.json")], check=True)
mono_copy_wav(out_dir / "nightwing-integrated-mic.wav", out_dir / "nightwing-integrated-mic-mono.wav")
local_peaks = detect_audio_peaks(out_dir / "starfire-loopback.wav", prototype, args, events)
remote_peaks = detect_audio_peaks(out_dir / "nightwing-integrated-mic-mono.wav", prototype, args, events)
local_shift, local_matches = fit_schedule(local_peaks, events, args)
remote_shift, remote_matches = fit_schedule(remote_peaks, events, args)
remote_stats = json.loads((out_dir / "nightwing-integrated-mic.json").read_text(encoding="utf-8"))
remote_first_wall_ns = remote_stats.get("first_read_wall_ns")
offset_ns = clock["remote_minus_local_clock_offset_ns"]
schedule_delta_ms = None
wall_delta_ms = None
if local_shift is not None and remote_shift is not None:
schedule_delta_ms = (remote_shift - local_shift) * 1000.0
if local_shift is not None and remote_shift is not None and local_first_wall_ns is not None and remote_first_wall_ns is not None:
local_event_ns = int(local_first_wall_ns + local_shift * 1_000_000_000.0)
remote_event_local_ns = int(remote_first_wall_ns - float(offset_ns) + remote_shift * 1_000_000_000.0)
wall_delta_ms = (remote_event_local_ns - local_event_ns) / 1_000_000.0
summary = {
"receipt_valid": len(local_peaks) >= 3 and len(remote_peaks) >= 3 and local_shift is not None and remote_shift is not None,
"out_dir": str(out_dir),
"play_wall_ns": play_wall_ns,
"ffplay_returncode": play.returncode,
"clock": clock,
"local_first_read_wall_ns": local_first_wall_ns,
"remote_first_read_wall_ns": remote_first_wall_ns,
"local_peaks_s": local_peaks,
"remote_peaks_s": remote_peaks,
"local_schedule_shift_ms": local_shift * 1000.0 if local_shift is not None else None,
"remote_schedule_shift_ms": remote_shift * 1000.0 if remote_shift is not None else None,
"schedule_remote_minus_loopback_ms": schedule_delta_ms,
"wall_remote_minus_loopback_ms": wall_delta_ms,
"local_matches": local_matches,
"remote_matches": remote_matches,
"remote_stats": remote_stats,
"events": events,
}
(out_dir / "summary.json").write_text(json.dumps(summary, indent=2, sort_keys=True), encoding="utf-8")
remote_log(
args.ssh_target,
"Nightwing audio sync chirp probe complete "
f"valid={summary['receipt_valid']} remoteMinusLoopbackMs={wall_delta_ms} artifact={out_dir}",
)
print(json.dumps(summary, indent=2, sort_keys=True))
return 0 if summary["receipt_valid"] else 1
if __name__ == "__main__":
raise SystemExit(main())

155
tools/nw_chirp_hint.py Normal file
View file

@ -0,0 +1,155 @@
#!/usr/bin/env python3
"""Nightwing-local builtin mic chirp schedule fitter.
Stdlib-only. Nightwing analyzes its own builtin mic and sends schedule-fit
state back to Starfire; it does not stream raw audio as authority.
"""
from __future__ import annotations
import argparse
import json
import wave
from pathlib import Path
import nightwing_alsa_capture_probe as alsa_probe
def mono_wav(path: Path) -> tuple[int, list[float]]:
with wave.open(str(path), "rb") as wav:
rate = wav.getframerate()
channels = wav.getnchannels()
pcm = wav.readframes(wav.getnframes())
values = memoryview(pcm).cast("h")
frames = len(values) // max(1, channels)
samples: list[float] = []
for frame in range(frames):
total = 0
for channel in range(channels):
total += int(values[frame * channels + channel])
samples.append((total / channels) / 32768.0)
return rate, samples
def percentile(values: list[float], q: float) -> float:
if not values:
return 0.0
ordered = sorted(values)
index = max(0, min(len(ordered) - 1, int(round((len(ordered) - 1) * q))))
return ordered[index]
def detect(samples: list[float], sample_rate: int, events: list[dict], _chirp_ms: float, interval: float) -> list[float]:
window = max(64, int(sample_rate * 0.006))
hop = max(32, int(sample_rate * 0.003))
envelope: list[float] = []
times: list[float] = []
previous = 0.0
for start in range(0, max(0, len(samples) - window), hop):
block = samples[start:start + window]
energy = sum(value * value for value in block) / len(block)
rise = max(0.0, energy - previous)
previous = previous * 0.92 + energy * 0.08
envelope.append(rise)
times.append((start + window * 0.5) / sample_rate)
if not envelope:
return []
threshold = max(percentile(envelope, 0.965), max(envelope) * 0.32)
min_gap_s = max(0.18, interval * 0.45)
peaks: list[float] = []
work = envelope[:]
for _ in events:
index = max(range(len(work)), key=lambda item: work[item])
if work[index] <= threshold:
break
peak_time = times[index]
peaks.append(peak_time)
for item, value_time in enumerate(times):
if abs(value_time - peak_time) <= min_gap_s:
work[item] = 0.0
return sorted(peaks)
def median(values: list[float]) -> float:
if not values:
return 0.0
ordered = sorted(values)
mid = len(ordered) // 2
if len(ordered) % 2:
return ordered[mid]
return (ordered[mid - 1] + ordered[mid]) * 0.5
def fit(peaks: list[float], events: list[dict], interval: float) -> tuple[float | None, list[dict]]:
if not peaks:
return None, []
offsets = [float(event["offset"]) for event in events]
tolerance = max(0.08, interval * 0.18)
best_shift = None
best_key = None
for candidate in sorted(peak - offset for peak in peaks for offset in offsets):
residuals = [min(abs((offset + candidate) - peak) for peak in peaks) for offset in offsets]
inliers = [residual for residual in residuals if residual <= tolerance]
if not inliers:
continue
key = (len(inliers), -median(inliers), -abs(candidate))
if best_key is None or key > best_key:
best_key = key
best_shift = candidate
if best_shift is None:
return None, []
used: set[int] = set()
matches = []
for event in events:
expected = float(event["offset"]) + best_shift
candidates = [index for index in range(len(peaks)) if index not in used]
nearest = min(candidates, key=lambda index: abs(peaks[index] - expected), default=None)
if nearest is None or abs(peaks[nearest] - expected) > tolerance:
matches.append({"index": int(event["index"]), "symbol": int(event["symbol"]), "observed_s": None, "residual_ms": None})
continue
used.add(nearest)
matches.append({"index": int(event["index"]), "symbol": int(event["symbol"]), "observed_s": peaks[nearest], "residual_ms": (peaks[nearest] - expected) * 1000.0})
return best_shift, matches
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--device", default="hw:0,0")
parser.add_argument("--rate", type=int, default=48000)
parser.add_argument("--channels", type=int, default=2)
parser.add_argument("--seconds", type=float, default=8.0)
parser.add_argument("--events-json", required=True)
parser.add_argument("--chirp-ms", type=float, default=70.0)
parser.add_argument("--interval", type=float, default=0.72)
parser.add_argument("--out", required=True)
args = parser.parse_args()
wav_path = Path(args.out).with_suffix(".wav")
stats_path = Path(args.out).with_suffix(".capture.json")
pcm, stats = alsa_probe.capture(args.device, args.rate, args.channels, args.seconds, 50_000)
alsa_probe.write_wav(wav_path, pcm, args.rate, args.channels)
stats_path.write_text(json.dumps(stats, indent=2, sort_keys=True), encoding="utf-8")
rate, samples = mono_wav(wav_path)
events = json.loads(Path(args.events_json).read_text(encoding="utf-8"))
peaks = detect(samples, rate, events, args.chirp_ms, args.interval)
shift, matches = fit(peaks, events, args.interval)
residuals = [abs(float(match["residual_ms"])) for match in matches if match.get("residual_ms") is not None]
result = {
"kind": "mimir.audio_chirp_witness_state.v1",
"source_id": "nightwing-builtin-mic",
"device": args.device,
"capture": stats,
"peaks_s": peaks,
"schedule_shift_ms": shift * 1000.0 if shift is not None else None,
"matched": len(residuals),
"median_abs_residual_ms": median(residuals) if residuals else None,
"matches": matches,
}
Path(args.out).write_text(json.dumps(result, indent=2, sort_keys=True), encoding="utf-8")
wav_path.unlink(missing_ok=True)
print(json.dumps(result, sort_keys=True))
return 0 if result["matched"] >= 2 else 1
if __name__ == "__main__":
raise SystemExit(main())

266
tools/nw_eye_cap.py Normal file
View file

@ -0,0 +1,266 @@
#!/usr/bin/env python3
"""Capture raw luma frames from Nightwing V4L2 cameras for sync receipts."""
from __future__ import annotations
import argparse
import ctypes
import ctypes.util
import fcntl
import json
import mmap
import os
import select
import time
from pathlib import Path
V4L2_BUF_TYPE_VIDEO_CAPTURE = 1
V4L2_FIELD_NONE = 1
V4L2_MEMORY_MMAP = 1
VIDIOC_G_FMT = 0xC0D05604
VIDIOC_S_FMT = 0xC0D05605
VIDIOC_REQBUFS = 0xC0145608
VIDIOC_QUERYBUF = 0xC0585609
VIDIOC_QBUF = 0xC058560F
VIDIOC_DQBUF = 0xC0585611
VIDIOC_STREAMON = 0x40045612
VIDIOC_STREAMOFF = 0x40045613
VIDIOC_G_PARM = 0xC0CC5615
VIDIOC_S_PARM = 0xC0CC5616
_libc = ctypes.CDLL(ctypes.util.find_library("c") or "libc.so.6", use_errno=True)
_libc.ioctl.argtypes = [ctypes.c_int, ctypes.c_ulong, ctypes.c_void_p]
_libc.ioctl.restype = ctypes.c_int
def fourcc(text: str) -> int:
raw = text.encode("ascii")
return raw[0] | (raw[1] << 8) | (raw[2] << 16) | (raw[3] << 24)
class V4L2PixFormat(ctypes.Structure):
_fields_ = [
("width", ctypes.c_uint32),
("height", ctypes.c_uint32),
("pixelformat", ctypes.c_uint32),
("field", ctypes.c_uint32),
("bytesperline", ctypes.c_uint32),
("sizeimage", ctypes.c_uint32),
("colorspace", ctypes.c_uint32),
("priv", ctypes.c_uint32),
("flags", ctypes.c_uint32),
("ycbcr_enc", ctypes.c_uint32),
("quantization", ctypes.c_uint32),
("xfer_func", ctypes.c_uint32),
]
class V4L2FormatUnion(ctypes.Union):
_fields_ = [("pix", V4L2PixFormat), ("raw", ctypes.c_uint8 * 200), ("_align", ctypes.c_uint64)]
class V4L2Format(ctypes.Structure):
_fields_ = [("type", ctypes.c_uint32), ("fmt", V4L2FormatUnion)]
class V4L2RequestBuffers(ctypes.Structure):
_fields_ = [
("count", ctypes.c_uint32),
("type", ctypes.c_uint32),
("memory", ctypes.c_uint32),
("capabilities", ctypes.c_uint32),
("flags", ctypes.c_uint8),
("reserved", ctypes.c_uint8 * 3),
]
class V4L2Fract(ctypes.Structure):
_fields_ = [("numerator", ctypes.c_uint32), ("denominator", ctypes.c_uint32)]
class V4L2CaptureParm(ctypes.Structure):
_fields_ = [
("capability", ctypes.c_uint32),
("capturemode", ctypes.c_uint32),
("timeperframe", V4L2Fract),
("extendedmode", ctypes.c_uint32),
("readbuffers", ctypes.c_uint32),
("reserved", ctypes.c_uint32 * 4),
]
class V4L2StreamParmUnion(ctypes.Union):
_fields_ = [("capture", V4L2CaptureParm), ("raw", ctypes.c_uint8 * 200)]
class V4L2StreamParm(ctypes.Structure):
_fields_ = [("type", ctypes.c_uint32), ("parm", V4L2StreamParmUnion)]
class Timeval(ctypes.Structure):
_fields_ = [("tv_sec", ctypes.c_long), ("tv_usec", ctypes.c_long)]
class V4L2Timecode(ctypes.Structure):
_fields_ = [
("type", ctypes.c_uint32),
("flags", ctypes.c_uint32),
("frames", ctypes.c_uint8),
("seconds", ctypes.c_uint8),
("minutes", ctypes.c_uint8),
("hours", ctypes.c_uint8),
("userbits", ctypes.c_uint8 * 4),
]
class V4L2BufferUnion(ctypes.Union):
_fields_ = [("offset", ctypes.c_uint32), ("userptr", ctypes.c_ulong), ("planes", ctypes.c_void_p), ("fd", ctypes.c_int32)]
class V4L2Buffer(ctypes.Structure):
_fields_ = [
("index", ctypes.c_uint32),
("type", ctypes.c_uint32),
("bytesused", ctypes.c_uint32),
("flags", ctypes.c_uint32),
("field", ctypes.c_uint32),
("timestamp", Timeval),
("timecode", V4L2Timecode),
("sequence", ctypes.c_uint32),
("memory", ctypes.c_uint32),
("m", V4L2BufferUnion),
("length", ctypes.c_uint32),
("reserved2", ctypes.c_uint32),
("request_fd", ctypes.c_int32),
]
def xioctl(fd: int, request: int, obj: ctypes.Structure) -> None:
if _libc.ioctl(fd, request, ctypes.byref(obj)) != 0:
error = ctypes.get_errno()
raise OSError(error, os.strerror(error))
def set_frame_interval(fd: int, fps: int) -> None:
parm = V4L2StreamParm()
parm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE
try:
xioctl(fd, VIDIOC_G_PARM, parm)
except OSError:
pass
parm.parm.capture.timeperframe.numerator = 1
parm.parm.capture.timeperframe.denominator = fps
xioctl(fd, VIDIOC_S_PARM, parm)
def yuyv_to_luma(raw: bytes, width: int, height: int, stride: int) -> bytes:
rows = []
for row in range(height):
start = row * stride
line = raw[start:start + width * 2]
rows.append(line[0::2])
return b"".join(rows)
def capture(args: argparse.Namespace) -> dict:
fd = os.open(args.device, os.O_RDWR | os.O_NONBLOCK)
maps: list[mmap.mmap] = []
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
frames_path = out.with_suffix(".y8")
try:
set_frame_interval(fd, args.fps)
fmt = V4L2Format()
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE
xioctl(fd, VIDIOC_G_FMT, fmt)
fmt.fmt.pix.width = args.width
fmt.fmt.pix.height = args.height
fmt.fmt.pix.pixelformat = fourcc(args.format)
fmt.fmt.pix.field = V4L2_FIELD_NONE
xioctl(fd, VIDIOC_S_FMT, fmt)
actual = fmt.fmt.pix
req = V4L2RequestBuffers()
req.count = args.buffers
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE
req.memory = V4L2_MEMORY_MMAP
xioctl(fd, VIDIOC_REQBUFS, req)
for index in range(req.count):
buf = V4L2Buffer()
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE
buf.memory = V4L2_MEMORY_MMAP
buf.index = index
xioctl(fd, VIDIOC_QUERYBUF, buf)
maps.append(mmap.mmap(fd, buf.length, mmap.MAP_SHARED, mmap.PROT_READ | mmap.PROT_WRITE, offset=buf.m.offset))
xioctl(fd, VIDIOC_QBUF, buf)
stream_type = ctypes.c_int(V4L2_BUF_TYPE_VIDEO_CAPTURE)
fcntl.ioctl(fd, VIDIOC_STREAMON, stream_type)
start = time.monotonic()
deadline = start + args.seconds
timestamps = []
sequences = []
with frames_path.open("wb") as frames:
while time.monotonic() < deadline:
ready, _, _ = select.select([fd], [], [], 0.25)
if not ready:
continue
buf = V4L2Buffer()
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE
buf.memory = V4L2_MEMORY_MMAP
try:
xioctl(fd, VIDIOC_DQBUF, buf)
except OSError:
continue
raw = maps[buf.index][:buf.bytesused]
frames.write(yuyv_to_luma(raw, int(actual.width), int(actual.height), int(actual.bytesperline)))
timestamps.append(float(buf.timestamp.tv_sec) + float(buf.timestamp.tv_usec) / 1_000_000.0)
sequences.append(int(buf.sequence))
xioctl(fd, VIDIOC_QBUF, buf)
try:
fcntl.ioctl(fd, VIDIOC_STREAMOFF, stream_type)
except OSError:
pass
first_ts = timestamps[0] if timestamps else None
rel = [(ts - first_ts) for ts in timestamps] if first_ts is not None else []
gap = max(0, (sequences[-1] - sequences[0] + 1) - len(sequences)) if len(sequences) >= 2 else 0
stats = {
"device": args.device,
"frames_path": str(frames_path),
"width": int(actual.width),
"height": int(actual.height),
"stride": int(actual.bytesperline),
"format": args.format,
"frames": len(timestamps),
"timestamps_s": rel,
"first_device_timestamp_s": first_ts,
"sequence_gap": gap,
"duration_s": (rel[-1] - rel[0]) if len(rel) >= 2 else 0.0,
}
out.write_text(json.dumps(stats, indent=2, sort_keys=True), encoding="utf-8")
return stats
finally:
for mapping in maps:
mapping.close()
os.close(fd)
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--device", required=True)
parser.add_argument("--width", type=int, default=320)
parser.add_argument("--height", type=int, default=240)
parser.add_argument("--format", default="YUYV")
parser.add_argument("--fps", type=int, default=187)
parser.add_argument("--seconds", type=float, default=8.0)
parser.add_argument("--buffers", type=int, default=8)
parser.add_argument("--out", required=True)
args = parser.parse_args()
stats = capture(args)
print(json.dumps(stats, sort_keys=True))
return 0 if stats["frames"] else 1
if __name__ == "__main__":
raise SystemExit(main())

170
tools/nw_move_hint.py Normal file
View file

@ -0,0 +1,170 @@
#!/usr/bin/env python3
"""Nightwing-local PS Eye / PS Move localization hint extractor.
Stdlib-only on purpose. Nightwing owns Eye frames and Move observations; the
wire format back to Starfire is compact witness state, not raw media.
"""
from __future__ import annotations
import argparse
import json
import math
from pathlib import Path
import nw_eye_cap
def percentile(values: list[float], q: float) -> float:
if not values:
return 0.0
ordered = sorted(values)
index = max(0, min(len(ordered) - 1, int(round((len(ordered) - 1) * q))))
return float(ordered[index])
def best_blob(frame: bytes, width: int, height: int) -> dict | None:
sampled = [frame[index] for index in range(0, len(frame), max(1, len(frame) // 4000))]
threshold = max(40, int(percentile([float(v) for v in sampled], 0.995)))
seen = bytearray(width * height)
best: dict | None = None
for y in range(height):
row = y * width
for x in range(width):
start = row + x
if seen[start] or frame[start] < threshold:
continue
stack = [start]
seen[start] = 1
count = 0
sx = 0.0
sy = 0.0
sw = 0.0
total = 0.0
peak = 0
while stack:
index = stack.pop()
yy, xx = divmod(index, width)
value = int(frame[index])
weight = max(1.0, float(value - threshold + 1))
count += 1
sx += xx * weight
sy += yy * weight
sw += weight
total += value
peak = max(peak, value)
for nx, ny in ((xx - 1, yy), (xx + 1, yy), (xx, yy - 1), (xx, yy + 1)):
if 0 <= nx < width and 0 <= ny < height:
ni = ny * width + nx
if not seen[ni] and frame[ni] >= threshold:
seen[ni] = 1
stack.append(ni)
if count < 3 or sw <= 0.0:
continue
cx = sx / sw
cy = sy / sw
mean_luma = total / count
confidence = min(1.0, (mean_luma / 255.0) * min(1.0, count / 80.0) * 1.6)
blob = {
"x_px": cx,
"y_px": cy,
"clip_x": (cx / max(1, width - 1)) * 2.0 - 1.0,
"clip_y": 1.0 - (cy / max(1, height - 1)) * 2.0,
"area_px": count,
"radius_px": math.sqrt(count / math.pi),
"mean_luma": mean_luma,
"peak_luma": peak,
"confidence": confidence,
}
if best is None or (blob["confidence"], blob["area_px"], blob["peak_luma"]) > (best["confidence"], best["area_px"], best["peak_luma"]):
best = blob
return best
def analyze(raw_path: Path, stats: dict, events: list[dict], moves: list[str], pulse_seconds: float, source_id: str) -> dict:
width = int(stats["width"])
height = int(stats["height"])
frame_bytes = width * height
raw = raw_path.read_bytes()
count = min(len(raw) // frame_bytes, len(stats.get("timestamps_s", [])))
timestamps = [float(value) for value in stats.get("timestamps_s", [])[:count]]
observations = []
for event in events:
event_index = int(event["index"])
expected = float(event["offset"])
move_id = moves[event_index % len(moves)] if moves else "move"
best: dict | None = None
for frame_index, timestamp in enumerate(timestamps):
if timestamp < expected - 0.18 or timestamp > expected + max(0.25, pulse_seconds + 0.18):
continue
frame = raw[frame_index * frame_bytes:(frame_index + 1) * frame_bytes]
blob = best_blob(frame, width, height)
if blob is None:
continue
blob.update({
"event_index": event_index,
"symbol": int(event["symbol"]),
"controller_id": move_id,
"source_id": source_id,
"observed_time_s": timestamp,
"schedule_offset_s": expected,
"schedule_residual_ms": (timestamp - expected) * 1000.0,
})
if best is None or blob["confidence"] > best["confidence"]:
best = blob
if best is not None:
observations.append(best)
return {
"kind": "mimir.move_controller_observation_state.v1",
"source_id": source_id,
"width": width,
"height": height,
"frame_count": count,
"first_device_timestamp_s": stats.get("first_device_timestamp_s"),
"duration_s": stats.get("duration_s"),
"sequence_gap": stats.get("sequence_gap"),
"observations": observations,
"observation_count": len(observations),
"stable_event_count": len([item for item in observations if float(item["confidence"]) >= 0.25]),
"mean_confidence": sum(float(item["confidence"]) for item in observations) / len(observations) if observations else 0.0,
}
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--device", required=True)
parser.add_argument("--source-id", required=True)
parser.add_argument("--width", type=int, default=320)
parser.add_argument("--height", type=int, default=240)
parser.add_argument("--fps", type=int, default=187)
parser.add_argument("--seconds", type=float, default=8.0)
parser.add_argument("--events-json", required=True)
parser.add_argument("--moves", default="move-a,move-b")
parser.add_argument("--pulse-ms", type=float, default=95.0)
parser.add_argument("--out", required=True)
args = parser.parse_args()
out = Path(args.out)
raw_stats_path = out.with_suffix(".capture.json")
cap_args = argparse.Namespace(
device=args.device,
width=args.width,
height=args.height,
format="YUYV",
fps=args.fps,
seconds=args.seconds,
buffers=8,
out=str(raw_stats_path),
)
stats = nw_eye_cap.capture(cap_args)
events = json.loads(Path(args.events_json).read_text(encoding="utf-8"))
moves = [part for part in args.moves.split(",") if part]
result = analyze(Path(stats["frames_path"]), stats, events, moves, args.pulse_ms * 0.001, args.source_id)
out.write_text(json.dumps(result, indent=2, sort_keys=True), encoding="utf-8")
Path(stats["frames_path"]).unlink(missing_ok=True)
print(json.dumps(result, sort_keys=True))
return 0 if result["observation_count"] else 1
if __name__ == "__main__":
raise SystemExit(main())

712
tools/sync_sweep.py Normal file
View file

@ -0,0 +1,712 @@
#!/usr/bin/env python3
"""Capture a chirp/PS Move pulse sweep and score every available witness.
This is a receipt harness, not runtime calibration authority. It owns one
event schedule, emits chirps through the speakers, pulses the Nightwing PS Move
controllers with unique colors, records the configured cameras and mics, then
fits each detected signal back to the same schedule.
"""
from __future__ import annotations
import argparse
import base64
import ctypes
import json
import math
import shutil
import subprocess
import sys
import threading
import time
import wave
from dataclasses import dataclass
from pathlib import Path
import numpy as np
from PIL import Image
from move_latency_probe import build_events, detect_audio_peaks, fit_schedule, generate_chirp
from nightwing_audio_sync_probe import AsioRecorder, estimate_clock_offset_ns, mono_copy_wav, remote_log
DEFAULT_FFMPEG = (
Path.home()
/ "AppData/Local/Microsoft/WinGet/Packages/Gyan.FFmpeg_Microsoft.Winget.Source_8wekyb3d8bbwe"
/ "ffmpeg-8.1.1-full_build/bin/ffmpeg.exe"
)
DEFAULT_FFPLAY = DEFAULT_FFMPEG.with_name("ffplay.exe")
DEFAULT_FFPROBE = DEFAULT_FFMPEG.with_name("ffprobe.exe")
DEFAULT_KIYO_PRO_VIDEO = (
r"@device_pnp_\\?\usb#vid_1532&pid_0e05&mi_00#9&3c07f79&0&0000"
r"#{65e8773d-8f56-11d0-a3b9-00a0c9223196}\global"
)
DEFAULT_KIYO_VIDEO = (
r"@device_pnp_\\?\usb#vid_1532&pid_0e03&mi_00#a&3ba76de&0&0000"
r"#{65e8773d-8f56-11d0-a3b9-00a0c9223196}\global"
)
DEFAULT_ASIO_DLL = Path(__file__).resolve().parents[1] / "native" / "asio_capture" / "build" / "Release" / "mimir_asio_capture.dll"
DEFAULT_ASIO_CLSID = "{AC4D0455-50D7-4498-B3CD-9A41D130B759}"
REMOTE_MULTI_MOVE = r"""
import os
import sys
import time
moves = {}
for spec in sys.argv[1].split(","):
if not spec:
continue
name, path = spec.split("=", 1)
moves[name] = path
events = []
for line in sys.stdin:
line = line.strip()
if not line:
continue
if line == "go":
break
offset, name, r, g, b = line.split()
events.append((float(offset), name, int(r), int(g), int(b)))
log = os.path.expanduser("~/.local/state/gamecult/codex-ssh-activity.log")
os.makedirs(os.path.dirname(log), exist_ok=True)
with open(log, "a", encoding="utf-8") as f:
f.write(f"{time.strftime('%Y-%m-%dT%H:%M:%S%z')} Codex: Mimir sync sweep Move receiver armed for {len(moves)} Moves.\n")
def write_rgb(path, r, g, b):
with open(path, "wb", buffering=0) as device:
device.write(bytes([0x06, 0, max(0, min(255, r)), max(0, min(255, g)), max(0, min(255, b)), 0, 0, 0, 0]))
for path in moves.values():
write_rgb(path, 0, 0, 0)
start = time.perf_counter()
for offset, name, r, g, b in events:
wait = start + offset - time.perf_counter()
if wait > 0:
time.sleep(wait)
path = moves.get(name)
if path:
write_rgb(path, r, g, b)
time.sleep(0.10)
for path in moves.values():
write_rgb(path, 0, 0, 0)
"""
@dataclass(frozen=True)
class VideoSensor:
name: str
device: str
width: int
height: int
fps: int
@dataclass(frozen=True)
class AudioSensor:
name: str
device: str
@dataclass(frozen=True)
class NightwingEye:
name: str
device: str
width: int
height: int
fps: int
def parse_video(value: str) -> VideoSensor:
name, rest = value.split("=", 1)
device, mode = rest.rsplit(":", 1)
size, fps = mode.split("@", 1)
width, height = size.lower().split("x", 1)
return VideoSensor(name, device, int(width), int(height), int(float(fps)))
def parse_audio(value: str) -> AudioSensor:
name, device = value.split("=", 1)
return AudioSensor(name, device)
def parse_nw_eye(value: str) -> NightwingEye:
name, rest = value.split("=", 1)
device, mode = rest.rsplit(":", 1)
size, fps = mode.split("@", 1)
width, height = size.lower().split("x", 1)
return NightwingEye(name, device, int(width), int(height), int(float(fps)))
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--out-dir", default="artifacts/runtime/sync-sweep")
parser.add_argument("--ffmpeg", default=str(DEFAULT_FFMPEG))
parser.add_argument("--ffplay", default=str(DEFAULT_FFPLAY))
parser.add_argument("--ffprobe", default=str(DEFAULT_FFPROBE))
parser.add_argument("--ssh-target", default="nightwing")
parser.add_argument("--nightwing-mic-device", default="hw:0,0")
parser.add_argument("--nightwing-rate", type=int, default=48000)
parser.add_argument("--nightwing-channels", type=int, default=2)
parser.add_argument("--skip-nightwing-mic", action="store_true")
parser.add_argument("--move", action="append", default=[
"move-a=/dev/hidraw2:#ff2a00",
"move-b=/dev/hidraw3:#00a8ff",
])
parser.add_argument("--video", action="append", default=[
f"kiyo-pro={DEFAULT_KIYO_PRO_VIDEO}:640x480@30",
f"kiyo={DEFAULT_KIYO_VIDEO}:640x480@30",
])
parser.add_argument("--nightwing-eye", action="append", default=[
"nw-builtin-cam=/dev/video0:640x480@30",
"nw-eye-0=/dev/video2:320x240@187",
"nw-eye-1=/dev/video3:320x240@187",
])
parser.add_argument("--audio", action="append", default=[
"kiyo-pro-mic=Microphone (7- Razer Kiyo Pro)",
"kiyo-mic=Microphone (4- Razer Kiyo)",
"focusrite-dshow=Analogue 1 + 2 (2- Focusrite USB Audio)",
])
parser.add_argument("--asio-dll", default=str(DEFAULT_ASIO_DLL))
parser.add_argument("--asio-clsid", default=DEFAULT_ASIO_CLSID)
parser.add_argument("--asio-channels", default="0,1,2,3")
parser.add_argument("--skip-asio", action="store_true")
parser.add_argument("--duration", type=float, default=9.0)
parser.add_argument("--capture-pad", type=float, default=2.0)
parser.add_argument("--lead", type=float, default=1.2)
parser.add_argument("--interval", type=float, default=0.72)
parser.add_argument("--pulses", type=int, default=10)
parser.add_argument("--schedule", choices=("uniform", "debruijn"), default="debruijn")
parser.add_argument("--alphabet-size", type=int, default=8)
parser.add_argument("--order", type=int, default=3)
parser.add_argument("--chirp-ms", type=float, default=70.0)
parser.add_argument("--pulse-ms", type=float, default=95.0)
parser.add_argument("--sample-rate", type=int, default=48000)
parser.add_argument("--dry-run", action="store_true")
return parser.parse_args()
def move_specs_and_events(args: argparse.Namespace, events: list[dict]) -> tuple[str, str]:
moves: list[tuple[str, str, tuple[int, int, int]]] = []
for spec in args.move:
name_path, color_text = spec.split(":", 1)
name, path = name_path.split("=", 1)
color_text = color_text.lstrip("#")
color = tuple(int(color_text[index:index + 2], 16) for index in (0, 2, 4))
moves.append((name, path, color)) # type: ignore[arg-type]
move_specs = ",".join(f"{name}={path}" for name, path, _color in moves)
lines: list[str] = []
pulse_s = args.pulse_ms * 0.001
for event_index, event in enumerate(events):
offset = float(event["offset"])
for move_index, (name, _path, color) in enumerate(moves):
scale = 1.0 if move_index == event_index % max(1, len(moves)) else 0.45
r, g, b = (int(channel * scale) for channel in color)
lines.append(f"{offset:.6f} {name} {r} {g} {b}")
lines.append(f"{offset + pulse_s:.6f} {name} 0 0 0")
return move_specs, "\n".join(lines) + "\ngo\n"
def start_move_receiver(args: argparse.Namespace, events: list[dict]) -> subprocess.Popen | None:
if not args.move:
return None
move_specs, stdin_text = move_specs_and_events(args, events)
remote_b64 = base64.b64encode(REMOTE_MULTI_MOVE.encode("utf-8")).decode("ascii")
remote_cmd = (
"tmp=$(mktemp); "
f"printf '%s' '{remote_b64}' | base64 -d > \"$tmp\"; "
f"python3 \"$tmp\" '{move_specs}'; "
"status=$?; rm -f \"$tmp\"; exit $status"
)
proc = subprocess.Popen(["ssh", "-o", "BatchMode=yes", args.ssh_target, remote_cmd], stdin=subprocess.PIPE, text=True)
assert proc.stdin is not None
proc.stdin.write(stdin_text)
proc.stdin.flush()
proc.stdin.close()
return proc
def start_video_capture(args: argparse.Namespace, sensor: VideoSensor, out_dir: Path) -> subprocess.Popen:
log = out_dir / f"{sensor.name}.ffmpeg.err.log"
path = out_dir / f"{sensor.name}.mkv"
cmd = [
args.ffmpeg,
"-hide_banner",
"-y",
"-thread_queue_size",
"1024",
"-rtbufsize",
"512M",
"-f",
"dshow",
"-video_size",
f"{sensor.width}x{sensor.height}",
"-framerate",
str(sensor.fps),
"-i",
f"video={sensor.device}",
"-t",
f"{args.duration + args.capture_pad:.3f}",
"-an",
"-c:v",
"ffv1",
"-level",
"3",
str(path),
]
return subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=log.open("w", encoding="utf-8", errors="replace"))
def start_audio_capture(args: argparse.Namespace, sensor: AudioSensor, out_dir: Path) -> subprocess.Popen:
log = out_dir / f"{sensor.name}.ffmpeg.err.log"
path = out_dir / f"{sensor.name}.wav"
cmd = [
args.ffmpeg,
"-hide_banner",
"-y",
"-thread_queue_size",
"1024",
"-f",
"dshow",
"-i",
f"audio={sensor.device}",
"-t",
f"{args.duration + args.capture_pad:.3f}",
"-ac",
"1",
"-ar",
str(args.sample_rate),
str(path),
]
return subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=log.open("w", encoding="utf-8", errors="replace"))
def start_nightwing_mic(args: argparse.Namespace, out_dir: Path) -> subprocess.Popen:
remote_log(args.ssh_target, "Mimir sync sweep arming Nightwing mic recorder.")
return subprocess.Popen(
[
"ssh",
args.ssh_target,
"python3",
"/tmp/nw_chirp_hint.py",
"--device",
args.nightwing_mic_device,
"--rate",
str(args.nightwing_rate),
"--channels",
str(args.nightwing_channels),
"--seconds",
f"{args.duration + args.capture_pad:.3f}",
"--events-json",
"/tmp/mimir-sync-sweep-events.json",
"--chirp-ms",
str(args.chirp_ms),
"--interval",
str(args.interval),
"--out",
"/tmp/mimir-sync-sweep-nightwing-mic.json",
],
stdout=(out_dir / "nightwing-mic.out.log").open("w", encoding="utf-8", errors="replace"),
stderr=(out_dir / "nightwing-mic.err.log").open("w", encoding="utf-8", errors="replace"),
text=True,
)
def start_nightwing_eye(args: argparse.Namespace, sensor: NightwingEye, out_dir: Path) -> subprocess.Popen:
remote_json = f"/tmp/mimir-sync-sweep-{sensor.name}.json"
move_names = ",".join(spec.split("=", 1)[0] for spec in args.move)
return subprocess.Popen(
[
"ssh",
args.ssh_target,
"python3",
"/tmp/nw_move_hint.py",
"--device",
sensor.device,
"--source-id",
sensor.name,
"--width",
str(sensor.width),
"--height",
str(sensor.height),
"--fps",
str(sensor.fps),
"--seconds",
f"{args.duration + args.capture_pad:.3f}",
"--events-json",
"/tmp/mimir-sync-sweep-events.json",
"--moves",
move_names,
"--pulse-ms",
str(args.pulse_ms),
"--out",
remote_json,
],
stdout=(out_dir / f"{sensor.name}.out.log").open("w", encoding="utf-8", errors="replace"),
stderr=(out_dir / f"{sensor.name}.err.log").open("w", encoding="utf-8", errors="replace"),
text=True,
)
def stage_nightwing_tools(args: argparse.Namespace, out_dir: Path) -> None:
tool_names = ["nightwing_alsa_capture_probe.py", "nw_eye_cap.py", "nw_move_hint.py", "nw_chirp_hint.py"]
for name in tool_names:
shutil.copy2(Path(__file__).with_name(name), out_dir / name)
files = [str(out_dir / name) for name in tool_names] + [str(out_dir / "event-schedule.json")]
subprocess.run(["scp", *files, f"{args.ssh_target}:/tmp/"], check=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
subprocess.run(["ssh", args.ssh_target, "cp /tmp/event-schedule.json /tmp/mimir-sync-sweep-events.json"], check=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
def write_asio_channels(recorder: AsioRecorder, out_dir: Path) -> list[Path]:
paths: list[Path] = []
for channel, values in recorder.samples.items():
samples = np.clip(np.asarray(values, dtype=np.float32), -1.0, 1.0)
path = out_dir / f"asio-ch{channel}.wav"
with wave.open(str(path), "wb") as wav:
wav.setnchannels(1)
wav.setsampwidth(2)
wav.setframerate(recorder.sample_rate)
wav.writeframes((samples * 32767.0).astype("<i2").tobytes())
paths.append(path)
return paths
def extract_video_frames(args: argparse.Namespace, out_dir: Path, sensor: VideoSensor) -> tuple[Path, list[float]]:
video_path = out_dir / f"{sensor.name}.mkv"
frames_dir = out_dir / f"{sensor.name}-frames"
if frames_dir.exists():
shutil.rmtree(frames_dir)
frames_dir.mkdir(parents=True)
subprocess.run(
[args.ffmpeg, "-hide_banner", "-y", "-i", str(video_path), "-map", "0:v:0", "-vsync", "0", str(frames_dir / "frame_%06d.png")],
stdout=subprocess.PIPE,
stderr=(out_dir / f"{sensor.name}.extract.err.log").open("w", encoding="utf-8", errors="replace"),
text=True,
check=True,
)
probe = subprocess.run(
[
args.ffprobe,
"-v",
"error",
"-select_streams",
"v:0",
"-show_entries",
"frame=best_effort_timestamp_time",
"-of",
"json",
str(video_path),
],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
data = json.loads(probe.stdout)
times = [float(frame["best_effort_timestamp_time"]) for frame in data.get("frames", []) if "best_effort_timestamp_time" in frame]
return frames_dir, times
def detect_video_peaks(frames_dir: Path, frame_times: list[float], interval: float, fps: int, pulses: int) -> tuple[list[float], dict]:
frame_paths = sorted(frames_dir.glob("frame_*.png"))
scores: list[float] = []
previous: np.ndarray | None = None
for path in frame_paths:
arr = np.asarray(Image.open(path).convert("L"), dtype=np.float32)
if previous is None:
scores.append(0.0)
else:
positive_delta = np.maximum(arr - previous, 0.0)
hot_delta = float(np.percentile(positive_delta, 99.92))
bright_tail = float(np.percentile(arr, 99.90))
scores.append(hot_delta + 0.025 * bright_tail)
previous = arr
if not scores:
return [], {"frames": 0, "score_max": None}
times = frame_times[: len(scores)] or [index / max(1, fps) for index in range(len(scores))]
signal = np.maximum(np.asarray(scores, dtype=np.float32) - float(np.percentile(scores, 20)), 0.0)
threshold = max(float(np.percentile(signal, 92)), float(np.max(signal)) * 0.38)
min_gap = max(1, int(interval * 0.50 * fps))
peaks: list[int] = []
work = signal.copy()
for _ in range(pulses):
index = int(np.argmax(work))
if work[index] <= threshold:
break
peaks.append(index)
lo = max(0, index - min_gap)
hi = min(work.size, index + min_gap)
work[lo:hi] = 0.0
return sorted(times[index] for index in peaks), {
"frames": len(scores),
"score_min": float(np.min(scores)),
"score_max": float(np.max(scores)),
"threshold": threshold,
}
def detect_raw_luma_peaks(raw_path: Path, frame_times: list[float], width: int, height: int, interval: float, fps: int, pulses: int) -> tuple[list[float], dict]:
raw = raw_path.read_bytes()
frame_bytes = width * height
frame_count = len(raw) // frame_bytes
if frame_count <= 0:
return [], {"frames": 0, "score_max": None}
scores: list[float] = []
previous: np.ndarray | None = None
for index in range(frame_count):
frame = np.frombuffer(raw[index * frame_bytes:(index + 1) * frame_bytes], dtype=np.uint8).astype(np.float32)
if previous is None:
scores.append(0.0)
else:
positive_delta = np.maximum(frame - previous, 0.0)
scores.append(float(np.percentile(positive_delta, 99.95)) + 0.03 * float(np.percentile(frame, 99.92)))
previous = frame
times = frame_times[:frame_count] or [index / max(1, fps) for index in range(frame_count)]
signal = np.maximum(np.asarray(scores, dtype=np.float32) - float(np.percentile(scores, 20)), 0.0)
threshold = max(float(np.percentile(signal, 96)), float(np.max(signal)) * 0.44)
min_gap = max(1, int(interval * 0.50 * fps))
peaks: list[int] = []
work = signal.copy()
for _ in range(pulses):
index = int(np.argmax(work))
if work[index] <= threshold:
break
peaks.append(index)
lo = max(0, index - min_gap)
hi = min(work.size, index + min_gap)
work[lo:hi] = 0.0
return sorted(times[index] for index in peaks), {
"frames": frame_count,
"score_min": float(np.min(scores)),
"score_max": float(np.max(scores)),
"threshold": threshold,
"raw_path": str(raw_path),
}
def score_sensor(name: str, kind: str, peaks: list[float], events: list[dict], args: argparse.Namespace, extra: dict | None = None) -> dict:
shift, matches = fit_schedule(peaks, events, args)
residuals = [float(match["residual_ms"]) for match in matches if match.get("residual_ms") is not None]
matched = len(residuals)
required = max(2, int(math.ceil(args.pulses * 0.45)))
summary = {
"name": name,
"kind": kind,
"ok": shift is not None and matched >= required,
"peaks": len(peaks),
"matched": matched,
"schedule_shift_ms": shift * 1000.0 if shift is not None else None,
"median_abs_residual_ms": float(np.median(np.abs(residuals))) if residuals else None,
"peak_times_s": peaks,
"matches": matches,
}
if extra:
summary.update(extra)
return summary
def main() -> int:
args = parse_args()
out_dir = Path(args.out_dir)
if not out_dir.is_absolute():
out_dir = Path.cwd() / out_dir
if out_dir.exists() and any(out_dir.iterdir()):
out_dir = out_dir.with_name(out_dir.name + "-" + time.strftime("%Y%m%d-%H%M%S"))
out_dir.mkdir(parents=True, exist_ok=True)
videos = [parse_video(value) for value in args.video]
nw_eyes = [parse_nw_eye(value) for value in args.nightwing_eye]
audios = [parse_audio(value) for value in args.audio]
events = build_events(args)
chirp_path = out_dir / "chirp-train.wav"
prototype = generate_chirp(chirp_path, args, events)
(out_dir / "event-schedule.json").write_text(json.dumps(events, indent=2), encoding="utf-8")
if args.dry_run:
print(json.dumps({"out_dir": str(out_dir), "events": events}, indent=2))
return 0
if nw_eyes or not args.skip_nightwing_mic:
stage_nightwing_tools(args, out_dir)
sensor_results: list[dict] = []
started: list[tuple[str, subprocess.Popen]] = []
for sensor in videos:
try:
started.append((sensor.name, start_video_capture(args, sensor, out_dir)))
except Exception as ex:
sensor_results.append({"name": sensor.name, "kind": "video", "ok": False, "error": str(ex)})
for sensor in audios:
try:
started.append((sensor.name, start_audio_capture(args, sensor, out_dir)))
except Exception as ex:
sensor_results.append({"name": sensor.name, "kind": "audio", "ok": False, "error": str(ex)})
nw_proc: subprocess.Popen | None = None
if not args.skip_nightwing_mic:
try:
nw_proc = start_nightwing_mic(args, out_dir)
except Exception as ex:
sensor_results.append({"name": "nightwing-mic", "kind": "audio", "ok": False, "error": str(ex)})
nw_eye_procs: list[tuple[NightwingEye, subprocess.Popen]] = []
for sensor in nw_eyes:
try:
nw_eye_procs.append((sensor, start_nightwing_eye(args, sensor, out_dir)))
except Exception as ex:
sensor_results.append({"name": sensor.name, "kind": "nightwing-video", "ok": False, "error": str(ex)})
asio: AsioRecorder | None = None
asio_thread: threading.Thread | None = None
if not args.skip_asio:
try:
channels = {int(part.strip()) for part in args.asio_channels.split(",") if part.strip()}
asio = AsioRecorder(Path(args.asio_dll), args.asio_clsid, args.sample_rate, channels)
asio_thread = threading.Thread(target=asio.record_for, args=(args.duration + args.capture_pad,), daemon=True)
asio_thread.start()
except Exception as ex:
sensor_results.append({"name": "asio", "kind": "audio", "ok": False, "error": str(ex)})
asio = None
time.sleep(0.8)
move_proc = start_move_receiver(args, events)
play_started_ns = time.time_ns()
play = subprocess.run([args.ffplay, "-nodisp", "-autoexit", "-loglevel", "quiet", str(chirp_path)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
for name, proc in started:
try:
proc.wait(timeout=args.duration + args.capture_pad + 5.0)
except subprocess.TimeoutExpired:
proc.kill()
sensor_results.append({"name": name, "kind": "capture", "ok": False, "error": "capture timeout"})
if move_proc is not None:
try:
move_proc.wait(timeout=args.duration + 5.0)
except subprocess.TimeoutExpired:
move_proc.kill()
if asio_thread is not None:
asio_thread.join(timeout=args.duration + args.capture_pad + 2.0)
if nw_proc is not None:
try:
nw_proc.wait(timeout=args.duration + args.capture_pad + 5.0)
except subprocess.TimeoutExpired:
nw_proc.kill()
for sensor, proc in nw_eye_procs:
try:
proc.wait(timeout=args.duration + args.capture_pad + 5.0)
except subprocess.TimeoutExpired:
proc.kill()
sensor_results.append({"name": sensor.name, "kind": "nightwing-video", "ok": False, "error": "remote capture timeout"})
if asio is not None:
try:
for path in write_asio_channels(asio, out_dir):
peaks = detect_audio_peaks(path, prototype, args, events)
sensor_results.append(score_sensor(path.stem, "asio-audio", peaks, events, args, {"path": str(path)}))
finally:
asio.close()
if nw_proc is not None:
subprocess.run(["scp", f"{args.ssh_target}:/tmp/mimir-sync-sweep-nightwing-mic.json", str(out_dir / "nightwing-mic.json")], check=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if (out_dir / "nightwing-mic.json").exists():
try:
hint = json.loads((out_dir / "nightwing-mic.json").read_text(encoding="utf-8"))
enough = int(hint.get("matched", 0)) >= max(2, int(math.ceil(args.pulses * 0.35)))
sensor_results.append({
"name": "nightwing-mic",
"kind": "nightwing-audio-hint",
"ok": nw_proc.returncode == 0 and enough,
"matched": hint.get("matched", 0),
"schedule_shift_ms": hint.get("schedule_shift_ms"),
"median_abs_residual_ms": hint.get("median_abs_residual_ms"),
"path": str(out_dir / "nightwing-mic.json"),
"hint": hint,
"error": None if nw_proc.returncode == 0 and enough else f"remote recorder exited {nw_proc.returncode}; insufficient matched pulses",
})
except Exception as ex:
sensor_results.append({"name": "nightwing-mic", "kind": "nightwing-audio-hint", "ok": False, "error": str(ex)})
else:
sensor_results.append({"name": "nightwing-mic", "kind": "nightwing-audio-hint", "ok": False, "error": f"remote recorder exited {nw_proc.returncode}; no hint json"})
for sensor, proc in nw_eye_procs:
if proc.returncode != 0:
sensor_results.append({"name": sensor.name, "kind": "nightwing-video", "ok": False, "error": f"remote capture exited {proc.returncode}"})
continue
remote_base = f"/tmp/mimir-sync-sweep-{sensor.name}"
local_json = out_dir / f"{sensor.name}.json"
subprocess.run(["scp", f"{args.ssh_target}:{remote_base}.json", str(local_json)], check=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
try:
hint = json.loads(local_json.read_text(encoding="utf-8"))
stable = int(hint.get("stable_event_count", 0))
observations = hint.get("observations", [])
residuals = [abs(float(item["schedule_residual_ms"])) for item in observations if "schedule_residual_ms" in item]
sensor_results.append({
"name": sensor.name,
"kind": "nightwing-move-hint",
"ok": stable >= max(2, int(math.ceil(args.pulses * 0.35))),
"matched": stable,
"schedule_shift_ms": float(np.median([float(item["observed_time_s"]) - float(item["schedule_offset_s"]) for item in observations])) * 1000.0 if observations else None,
"median_abs_residual_ms": float(np.median(residuals)) if residuals else None,
"path": str(local_json),
"hint": hint,
})
except Exception as ex:
sensor_results.append({"name": sensor.name, "kind": "nightwing-move-hint", "ok": False, "error": str(ex)})
for sensor in audios:
path = out_dir / f"{sensor.name}.wav"
if not path.exists():
sensor_results.append({"name": sensor.name, "kind": "dshow-audio", "ok": False, "error": "wav missing"})
continue
try:
peaks = detect_audio_peaks(path, prototype, args, events)
sensor_results.append(score_sensor(sensor.name, "dshow-audio", peaks, events, args, {"path": str(path)}))
except Exception as ex:
sensor_results.append({"name": sensor.name, "kind": "dshow-audio", "ok": False, "error": str(ex)})
for sensor in videos:
path = out_dir / f"{sensor.name}.mkv"
if not path.exists():
sensor_results.append({"name": sensor.name, "kind": "video", "ok": False, "error": "capture missing"})
continue
try:
frames_dir, times = extract_video_frames(args, out_dir, sensor)
peaks, stats = detect_video_peaks(frames_dir, times, args.interval, sensor.fps, args.pulses)
sensor_results.append(score_sensor(sensor.name, "video", peaks, events, args, {"path": str(path), "stats": stats}))
except Exception as ex:
sensor_results.append({"name": sensor.name, "kind": "video", "ok": False, "error": str(ex)})
reference = next((item for item in sensor_results if item.get("ok") and item.get("name") == "asio-ch2"), None)
if reference is None:
reference = next((item for item in sensor_results if item.get("ok") and item.get("kind") == "asio-audio"), None)
reference_shift = reference.get("schedule_shift_ms") if reference else None
for item in sensor_results:
shift = item.get("schedule_shift_ms")
item["offset_from_reference_ms"] = (float(shift) - float(reference_shift)) if shift is not None and reference_shift is not None else None
summary = {
"kind": "mimir.chirp_move_sync_sweep.v1",
"out_dir": str(out_dir),
"created_unix": time.time(),
"play_started_wall_ns": play_started_ns,
"ffplay_returncode": play.returncode,
"reference": reference.get("name") if reference else None,
"reference_schedule_shift_ms": reference_shift,
"events": events,
"sensors": sensor_results,
"valid_sensor_count": sum(1 for item in sensor_results if item.get("ok")),
"note": "Schedule shifts are per-witness receipt fits. Offsets are relative to the selected ASIO witness when available; final runtime calibration still belongs in native timestamped Mimir/Fensalir paths.",
}
(out_dir / "summary.json").write_text(json.dumps(summary, indent=2, sort_keys=True), encoding="utf-8")
print(json.dumps(summary, indent=2, sort_keys=True))
return 0 if summary["valid_sensor_count"] > 0 else 1
if __name__ == "__main__":
raise SystemExit(main())