Remove script-era Python stack
This commit is contained in:
parent
d1eca0776e
commit
6ca7915f2b
191 changed files with 442 additions and 126676 deletions
File diff suppressed because it is too large
Load diff
|
|
@ -1,363 +0,0 @@
|
|||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import multiprocessing as mp
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
RUNS = ROOT / "calibration" / "runs"
|
||||
|
||||
|
||||
def utc_stamp() -> str:
|
||||
return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S.%fZ")
|
||||
|
||||
|
||||
def run_dir(kind: str) -> Path:
|
||||
for suffix in ["", *[f"-{i}" for i in range(1, 100)]]:
|
||||
path = RUNS / f"{utc_stamp()}-{kind}{suffix}"
|
||||
try:
|
||||
path.mkdir(parents=True, exist_ok=False)
|
||||
return path
|
||||
except FileExistsError:
|
||||
continue
|
||||
raise RuntimeError(f"Could not create unique calibration run directory for {kind}")
|
||||
|
||||
|
||||
def write_json(path: Path, data) -> None:
|
||||
path.write_text(json.dumps(data, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
def powershell_json(script: str):
|
||||
completed = subprocess.run(
|
||||
["powershell", "-NoProfile", "-Command", script],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
)
|
||||
if completed.returncode != 0:
|
||||
return {
|
||||
"error": completed.stderr.strip(),
|
||||
"stdout": completed.stdout.strip(),
|
||||
"returncode": completed.returncode,
|
||||
}
|
||||
text = completed.stdout.strip()
|
||||
if not text:
|
||||
return []
|
||||
try:
|
||||
return json.loads(text)
|
||||
except json.JSONDecodeError:
|
||||
return {"raw": text}
|
||||
|
||||
|
||||
def pnp_devices():
|
||||
script = r"""
|
||||
$devices = Get-CimInstance Win32_PnPEntity |
|
||||
Where-Object { $_.Name -match 'Kiyo|Leap|Camera|Scarlett|USB Audio|Microphone|Speakers' } |
|
||||
Select-Object Name,PNPClass,Status,DeviceID
|
||||
$devices | ConvertTo-Json -Depth 4
|
||||
"""
|
||||
return powershell_json(script)
|
||||
|
||||
|
||||
def audio_devices():
|
||||
try:
|
||||
import sounddevice as sd
|
||||
except Exception as exc:
|
||||
return {"error": f"sounddevice unavailable: {exc!r}"}
|
||||
|
||||
return {
|
||||
"hostapis": sd.query_hostapis(),
|
||||
"devices": sd.query_devices(),
|
||||
}
|
||||
|
||||
|
||||
def camera_probe(max_index: int, apis: list[str], read_frames: int = 1):
|
||||
try:
|
||||
import cv2
|
||||
except Exception as exc:
|
||||
return [{"error": f"cv2 unavailable: {exc!r}"}]
|
||||
|
||||
api_map = cv2_api_map()
|
||||
results = []
|
||||
for api_name in apis:
|
||||
api = api_map[api_name]
|
||||
for index in range(max_index + 1):
|
||||
cap = cv2.VideoCapture(index, api)
|
||||
entry = {
|
||||
"api": api_name,
|
||||
"index": index,
|
||||
"opened": bool(cap.isOpened()),
|
||||
}
|
||||
if cap.isOpened():
|
||||
cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
|
||||
frames = []
|
||||
for _ in range(read_frames):
|
||||
ok, frame = cap.read()
|
||||
frames.append(bool(ok and frame is not None))
|
||||
entry["read_ok"] = any(frames)
|
||||
entry["read_attempts"] = frames
|
||||
entry["backend"] = cap.getBackendName()
|
||||
entry["width"] = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
|
||||
entry["height"] = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
|
||||
entry["fps"] = cap.get(cv2.CAP_PROP_FPS)
|
||||
entry["fourcc"] = int(cap.get(cv2.CAP_PROP_FOURCC))
|
||||
cap.release()
|
||||
results.append(entry)
|
||||
return results
|
||||
|
||||
|
||||
def cv2_api_map():
|
||||
import cv2
|
||||
|
||||
return {
|
||||
"any": 0,
|
||||
"dshow": cv2.CAP_DSHOW,
|
||||
"msmf": cv2.CAP_MSMF,
|
||||
}
|
||||
|
||||
|
||||
def api_value(name: str):
|
||||
return cv2_api_map()[name]
|
||||
|
||||
|
||||
def discover(args):
|
||||
out = run_dir("discover")
|
||||
manifest = {
|
||||
"created_utc": datetime.now(timezone.utc).isoformat(),
|
||||
"python": sys.version,
|
||||
"pnp_devices": pnp_devices(),
|
||||
"audio": audio_devices(),
|
||||
"cameras": camera_probe(args.max_index, args.api, read_frames=1),
|
||||
}
|
||||
write_json(out / "manifest.json", manifest)
|
||||
print(out)
|
||||
print(json.dumps(manifest["cameras"], indent=2))
|
||||
|
||||
|
||||
def snapshot(args):
|
||||
import cv2
|
||||
|
||||
out = run_dir("snapshot")
|
||||
manifest = {
|
||||
"created_utc": datetime.now(timezone.utc).isoformat(),
|
||||
"snapshots": [],
|
||||
}
|
||||
for probe in camera_probe(args.max_index, args.api, read_frames=1):
|
||||
if not probe.get("opened") or not probe.get("read_ok"):
|
||||
manifest["snapshots"].append({**probe, "snapshot": None})
|
||||
continue
|
||||
api_map = {"any": 0, "dshow": cv2.CAP_DSHOW, "msmf": cv2.CAP_MSMF}
|
||||
cap = cv2.VideoCapture(probe["index"], api_map[probe["api"]])
|
||||
ok, frame = cap.read()
|
||||
cap.release()
|
||||
snap_name = None
|
||||
if ok and frame is not None:
|
||||
snap_name = f"{probe['api']}-index{probe['index']}.png"
|
||||
cv2.imwrite(str(out / snap_name), frame)
|
||||
manifest["snapshots"].append({**probe, "snapshot": snap_name})
|
||||
write_json(out / "manifest.json", manifest)
|
||||
print(out)
|
||||
for item in manifest["snapshots"]:
|
||||
if item.get("snapshot"):
|
||||
print(f"{item['api']}:{item['index']} -> {item['snapshot']}")
|
||||
|
||||
|
||||
def mode_probe(args):
|
||||
out = run_dir(f"mode-probe-{args.api}{args.index}")
|
||||
result = {
|
||||
"created_utc": datetime.now(timezone.utc).isoformat(),
|
||||
"camera": {"api": args.api, "index": args.index},
|
||||
"profiles": [],
|
||||
}
|
||||
|
||||
profiles = []
|
||||
requested_profiles = args.profile or [
|
||||
"640x480x30",
|
||||
"640x480x60",
|
||||
"320x240x60",
|
||||
"320x240x120",
|
||||
]
|
||||
for item in requested_profiles:
|
||||
parts = item.lower().split("x")
|
||||
if len(parts) != 3:
|
||||
raise SystemExit(f"Profile must be WIDTHxHEIGHTxFPS, got {item}")
|
||||
profiles.append(tuple(int(part) for part in parts))
|
||||
|
||||
for width, height, fps in profiles:
|
||||
entry = run_profile_probe(args.api, args.index, width, height, fps, args.duration, args.profile_timeout)
|
||||
result["profiles"].append(entry)
|
||||
|
||||
write_json(out / "manifest.json", result)
|
||||
print(out)
|
||||
print(json.dumps(result["profiles"], indent=2))
|
||||
|
||||
|
||||
def _profile_probe_worker(queue, api, index, width, height, fps, duration):
|
||||
import cv2
|
||||
import time
|
||||
|
||||
cap = cv2.VideoCapture(index, api_value(api))
|
||||
if not cap.isOpened():
|
||||
queue.put(
|
||||
{
|
||||
"requested": {"width": width, "height": height, "fps": fps},
|
||||
"opened": False,
|
||||
}
|
||||
)
|
||||
return
|
||||
cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
|
||||
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
|
||||
cap.set(cv2.CAP_PROP_FPS, fps)
|
||||
cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
|
||||
start = time.perf_counter()
|
||||
count = 0
|
||||
shape = None
|
||||
first_ok = False
|
||||
while (time.perf_counter() - start) < duration:
|
||||
ok, frame = cap.read()
|
||||
if ok and frame is not None:
|
||||
count += 1
|
||||
first_ok = True
|
||||
shape = list(frame.shape)
|
||||
elapsed = time.perf_counter() - start
|
||||
entry = {
|
||||
"requested": {"width": width, "height": height, "fps": fps},
|
||||
"opened": True,
|
||||
"read_ok": first_ok,
|
||||
"frames": count,
|
||||
"measured_fps": count / elapsed if elapsed else 0.0,
|
||||
"reported_width": cap.get(cv2.CAP_PROP_FRAME_WIDTH),
|
||||
"reported_height": cap.get(cv2.CAP_PROP_FRAME_HEIGHT),
|
||||
"reported_fps": cap.get(cv2.CAP_PROP_FPS),
|
||||
"fourcc": int(cap.get(cv2.CAP_PROP_FOURCC)),
|
||||
"shape": shape,
|
||||
"backend": cap.getBackendName(),
|
||||
}
|
||||
cap.release()
|
||||
queue.put(entry)
|
||||
|
||||
|
||||
def run_profile_probe(api, index, width, height, fps, duration, timeout):
|
||||
queue = mp.Queue()
|
||||
proc = mp.Process(target=_profile_probe_worker, args=(queue, api, index, width, height, fps, duration))
|
||||
proc.start()
|
||||
proc.join(timeout)
|
||||
if proc.is_alive():
|
||||
proc.terminate()
|
||||
proc.join(2)
|
||||
return {
|
||||
"requested": {"width": width, "height": height, "fps": fps},
|
||||
"opened": None,
|
||||
"timeout": True,
|
||||
}
|
||||
if not queue.empty():
|
||||
return queue.get()
|
||||
return {
|
||||
"requested": {"width": width, "height": height, "fps": fps},
|
||||
"opened": None,
|
||||
"error": f"worker exited with code {proc.exitcode}",
|
||||
}
|
||||
|
||||
|
||||
def audio_smoke(args):
|
||||
import numpy as np
|
||||
import sounddevice as sd
|
||||
|
||||
out = run_dir("audio-smoke")
|
||||
devices = sd.query_devices()
|
||||
hostapis = sd.query_hostapis()
|
||||
targets = []
|
||||
for dev in devices:
|
||||
if dev["max_input_channels"] <= 0:
|
||||
continue
|
||||
hostapi = hostapis[dev["hostapi"]]["name"]
|
||||
if args.hostapi and hostapi.lower() != args.hostapi.lower():
|
||||
continue
|
||||
if args.name and args.name.lower() not in dev["name"].lower():
|
||||
continue
|
||||
targets.append(dev)
|
||||
|
||||
results = []
|
||||
for dev in targets:
|
||||
samplerate = int(args.samplerate or dev["default_samplerate"] or 48000)
|
||||
channels = min(int(dev["max_input_channels"]), args.channels)
|
||||
entry = {
|
||||
"index": dev["index"],
|
||||
"name": dev["name"],
|
||||
"hostapi": hostapis[dev["hostapi"]]["name"],
|
||||
"samplerate": samplerate,
|
||||
"channels": channels,
|
||||
}
|
||||
try:
|
||||
rec = sd.rec(
|
||||
int(args.duration * samplerate),
|
||||
samplerate=samplerate,
|
||||
channels=channels,
|
||||
dtype="float32",
|
||||
device=dev["index"],
|
||||
blocking=True,
|
||||
)
|
||||
entry["frames"] = int(rec.shape[0])
|
||||
entry["rms"] = [float(x) for x in np.sqrt(np.mean(rec * rec, axis=0))]
|
||||
entry["peak"] = [float(x) for x in np.max(np.abs(rec), axis=0)]
|
||||
entry["ok"] = True
|
||||
except Exception as exc:
|
||||
entry["ok"] = False
|
||||
entry["error"] = repr(exc)
|
||||
results.append(entry)
|
||||
|
||||
manifest = {
|
||||
"created_utc": datetime.now(timezone.utc).isoformat(),
|
||||
"duration": args.duration,
|
||||
"results": results,
|
||||
}
|
||||
write_json(out / "manifest.json", manifest)
|
||||
print(out)
|
||||
print(json.dumps(results, indent=2))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Probe Mimir calibration devices.")
|
||||
sub = parser.add_subparsers(required=True)
|
||||
|
||||
p = sub.add_parser("discover")
|
||||
p.add_argument("--max-index", type=int, default=10)
|
||||
p.add_argument("--api", action="append", choices=["any", "dshow", "msmf"], default=["dshow", "msmf"])
|
||||
p.set_defaults(func=discover)
|
||||
|
||||
p = sub.add_parser("snapshot")
|
||||
p.add_argument("--max-index", type=int, default=10)
|
||||
p.add_argument("--api", action="append", choices=["any", "dshow", "msmf"], default=["dshow", "msmf"])
|
||||
p.set_defaults(func=snapshot)
|
||||
|
||||
p = sub.add_parser("mode-probe")
|
||||
p.add_argument("--api", choices=["any", "dshow", "msmf"], default="dshow")
|
||||
p.add_argument("--index", type=int, required=True)
|
||||
p.add_argument("--duration", type=float, default=1.0)
|
||||
p.add_argument("--profile-timeout", type=float, default=6.0)
|
||||
p.add_argument(
|
||||
"--profile",
|
||||
action="append",
|
||||
default=None,
|
||||
help="WIDTHxHEIGHTxFPS, repeatable. Example: --profile 320x240x120",
|
||||
)
|
||||
p.set_defaults(func=mode_probe)
|
||||
|
||||
p = sub.add_parser("audio-smoke")
|
||||
p.add_argument("--duration", type=float, default=1.0)
|
||||
p.add_argument("--samplerate", type=int)
|
||||
p.add_argument("--channels", type=int, default=2)
|
||||
p.add_argument("--hostapi")
|
||||
p.add_argument("--name")
|
||||
p.set_defaults(func=audio_smoke)
|
||||
|
||||
args = parser.parse_args()
|
||||
args.func(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -1,316 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import subprocess
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from tempfile import NamedTemporaryFile
|
||||
|
||||
import numpy as np
|
||||
from scipy import signal
|
||||
from scipy.io import wavfile
|
||||
|
||||
|
||||
DEFAULT_RUN = Path("calibration/runs/audio-program-live-20260518-180226")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description=(
|
||||
"Capture the late-arriving co-streamer audio surfaces, align them to "
|
||||
"local loopback ground truth, and write synced OBS stem inputs."
|
||||
)
|
||||
)
|
||||
parser.add_argument("--run", type=Path, default=DEFAULT_RUN)
|
||||
parser.add_argument("--seconds", type=float, default=24.0)
|
||||
parser.add_argument("--sample-rate", type=int, default=48000)
|
||||
parser.add_argument("--ssh-target", default="madman's lullaby@192.168.1.84")
|
||||
parser.add_argument("--ffmpeg", default=r"C:\Users\Madman's Lullaby\AppData\Local\Microsoft\WinGet\Links\ffmpeg.exe")
|
||||
parser.add_argument("--remote-dir", default=r"C:\Meta\Mimir\calibration\remote-captures")
|
||||
parser.add_argument("--focusrite-device", default="Analogue 1 + 2 (Focusrite USB Audio)")
|
||||
parser.add_argument("--loopback-device", default="")
|
||||
parser.add_argument("--loopback-capture", choices=("wasapi", "dshow"), default="wasapi")
|
||||
parser.add_argument("--remote-wasapi-script", default=r"C:\Meta\Mimir\scripts\wasapi-loopback-capture.ps1")
|
||||
parser.add_argument("--remote-wasapi-role", choices=("Console", "Multimedia", "Communications"), default="Console")
|
||||
parser.add_argument("--local-loopback-query", default="Scarlett")
|
||||
parser.add_argument("--max-lag-ms", type=float, default=3000.0)
|
||||
parser.add_argument("--min-loopback-rms", type=float, default=1e-4)
|
||||
parser.add_argument("--min-loopback-score", type=float, default=0.01)
|
||||
parser.add_argument("--dry-run", action="store_true")
|
||||
args = parser.parse_args()
|
||||
|
||||
run = args.run.resolve()
|
||||
surface_dir = run / "co_streamer_surfaces"
|
||||
surface_dir.mkdir(parents=True, exist_ok=True)
|
||||
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S")
|
||||
|
||||
remote_focusrite = f"{args.remote_dir.rstrip('\\\\/')}\\co_streamer_focusrite-{stamp}.wav"
|
||||
remote_loopback_ext = "f32" if args.loopback_capture == "wasapi" else "wav"
|
||||
remote_loopback = f"{args.remote_dir.rstrip('\\\\/')}\\co_streamer_loopback-{stamp}.{remote_loopback_ext}"
|
||||
local_focusrite = surface_dir / "raw_focusrite.wav"
|
||||
local_remote_loopback = surface_dir / f"raw_loopback.{remote_loopback_ext}"
|
||||
local_reference = surface_dir / "local_loopback_reference.wav"
|
||||
|
||||
commands = [
|
||||
remote_ffmpeg_command(args, args.focusrite_device, remote_focusrite, channels=1),
|
||||
remote_loopback_command(args, remote_loopback),
|
||||
]
|
||||
if args.dry_run:
|
||||
for command in commands:
|
||||
print(command)
|
||||
return 0
|
||||
|
||||
print("starting remote co-streamer captures")
|
||||
procs = [subprocess.Popen(["ssh", args.ssh_target, command], text=True) for command in commands]
|
||||
time.sleep(0.2)
|
||||
local_loopback = record_local_loopback(
|
||||
query=args.local_loopback_query,
|
||||
seconds=float(args.seconds),
|
||||
sample_rate=int(args.sample_rate),
|
||||
channels=2,
|
||||
)
|
||||
wavfile.write(local_reference, int(args.sample_rate), local_loopback.astype(np.float32))
|
||||
|
||||
failures = []
|
||||
for proc in procs:
|
||||
rc = proc.wait()
|
||||
if rc:
|
||||
failures.append(rc)
|
||||
if failures:
|
||||
raise SystemExit(f"remote capture failed with exit codes {failures}")
|
||||
|
||||
sftp_get(args.ssh_target, remote_focusrite, local_focusrite)
|
||||
sftp_get(args.ssh_target, remote_loopback, local_remote_loopback)
|
||||
|
||||
sample_rate = int(args.sample_rate)
|
||||
_, reference = read_wav_float(local_reference, sample_rate)
|
||||
_, focusrite = read_wav_float(local_focusrite, sample_rate)
|
||||
remote_loop = read_loopback_capture(local_remote_loopback, sample_rate, args.loopback_capture)
|
||||
reference_mono = mono(reference)
|
||||
remote_loop_mono = mono(remote_loop)
|
||||
max_lag = int(float(args.max_lag_ms) * sample_rate / 1000.0)
|
||||
remote_loop_rms = rms(remote_loop_mono)
|
||||
focusrite_mono = mono(focusrite)
|
||||
focusrite_rms = rms(focusrite_mono)
|
||||
loopback_delay, loopback_score = normalized_delay(remote_loop_mono, reference_mono, max_lag=max_lag)
|
||||
focusrite_delay, focusrite_score = normalized_delay(focusrite_mono, reference_mono, max_lag=max_lag)
|
||||
if remote_loop_rms >= float(args.min_loopback_rms) and loopback_score >= float(args.min_loopback_score):
|
||||
delay_samples = loopback_delay
|
||||
score = loopback_score
|
||||
alignment_witness = "remote-loopback"
|
||||
else:
|
||||
delay_samples = focusrite_delay
|
||||
score = focusrite_score
|
||||
alignment_witness = "neighbor-focusrite-program-bleed"
|
||||
|
||||
aligned_focusrite = shift_by_delay(focusrite, delay_samples, len(reference))
|
||||
aligned_loopback = shift_by_delay(remote_loop, delay_samples, len(reference))
|
||||
wavfile.write(surface_dir / "aligned_focusrite.wav", sample_rate, aligned_focusrite.astype(np.float32))
|
||||
wavfile.write(surface_dir / "aligned_loopback.wav", sample_rate, aligned_loopback.astype(np.float32))
|
||||
|
||||
report = {
|
||||
"schema_version": "gamecult.localcast.co_streamer_surfaces.v1",
|
||||
"created_utc": datetime.now(timezone.utc).isoformat(),
|
||||
"sample_rate": sample_rate,
|
||||
"seconds": float(args.seconds),
|
||||
"alignment_witness": alignment_witness,
|
||||
"delay_samples": int(delay_samples),
|
||||
"delay_ms": 1000.0 * float(delay_samples) / sample_rate,
|
||||
"correlation_score": float(score),
|
||||
"remote_loopback": {
|
||||
"rms": remote_loop_rms,
|
||||
"delay_samples": int(loopback_delay),
|
||||
"delay_ms": 1000.0 * float(loopback_delay) / sample_rate,
|
||||
"correlation_score": float(loopback_score),
|
||||
},
|
||||
"neighbor_focusrite": {
|
||||
"rms": focusrite_rms,
|
||||
"delay_samples": int(focusrite_delay),
|
||||
"delay_ms": 1000.0 * float(focusrite_delay) / sample_rate,
|
||||
"correlation_score": float(focusrite_score),
|
||||
},
|
||||
"interpretation": (
|
||||
"positive delay means the remote loopback arrived later than local loopback "
|
||||
"and was advanced into the local presentation timeline"
|
||||
),
|
||||
"files": {
|
||||
"local_loopback_reference": str(local_reference),
|
||||
"raw_focusrite": str(local_focusrite),
|
||||
"raw_loopback": str(local_remote_loopback),
|
||||
"aligned_focusrite": str(surface_dir / "aligned_focusrite.wav"),
|
||||
"aligned_loopback": str(surface_dir / "aligned_loopback.wav"),
|
||||
},
|
||||
}
|
||||
(surface_dir / "alignment-report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps(report, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
def remote_ffmpeg_command(args: argparse.Namespace, device: str, output: str, *, channels: int) -> str:
|
||||
remote_dir = args.remote_dir.rstrip("\\/")
|
||||
return (
|
||||
f'cmd /c if not exist "{remote_dir}" mkdir "{remote_dir}" && '
|
||||
f'"{args.ffmpeg}" -y -hide_banner -nostdin -loglevel warning '
|
||||
f'-f dshow -t {float(args.seconds):.3f} -i audio="{device}" '
|
||||
f'-vn -ac {channels} -ar {int(args.sample_rate)} -c:a pcm_f32le "{output}"'
|
||||
)
|
||||
|
||||
|
||||
def remote_loopback_command(args: argparse.Namespace, output: str) -> str:
|
||||
if args.loopback_capture == "dshow":
|
||||
if not args.loopback_device:
|
||||
raise SystemExit("--loopback-device is required when --loopback-capture dshow")
|
||||
return remote_ffmpeg_command(args, args.loopback_device, output, channels=2)
|
||||
log = output.rsplit(".", 1)[0] + ".log"
|
||||
task = "MimirWasapiLoopbackCapture"
|
||||
return (
|
||||
"powershell -NoProfile -ExecutionPolicy Bypass -Command "
|
||||
+ quote_for_cmd(
|
||||
"$ErrorActionPreference='Stop'; "
|
||||
f"$out='{escape_ps(output)}'; $log='{escape_ps(log)}'; "
|
||||
"Remove-Item -LiteralPath $out,$log -ErrorAction SilentlyContinue; "
|
||||
f"$cmd='powershell.exe -NoProfile -ExecutionPolicy Bypass -File \"{escape_ps(args.remote_wasapi_script)}\" "
|
||||
f"-Output \"{escape_ps(output)}\" -Seconds {float(args.seconds):.3f} "
|
||||
f"-SampleRate {int(args.sample_rate)} -Channels 2 -Role {args.remote_wasapi_role} *> \"{escape_ps(log)}\"'; "
|
||||
"$bat=[IO.Path]::ChangeExtension($out,'.cmd'); "
|
||||
"Set-Content -LiteralPath $bat -Encoding ASCII -Value ('@echo off' + [Environment]::NewLine + $cmd + [Environment]::NewLine); "
|
||||
"$action=New-ScheduledTaskAction -Execute $bat; "
|
||||
"$trigger=New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(10); "
|
||||
"$principal=New-ScheduledTaskPrincipal -UserId ($env:COMPUTERNAME + '\\' + $env:USERNAME) -LogonType Interactive -RunLevel Limited; "
|
||||
f"Register-ScheduledTask -TaskName '{task}' -Action $action -Trigger $trigger -Principal $principal -Force | Out-Null; "
|
||||
f"Start-ScheduledTask -TaskName '{task}'; "
|
||||
f"$deadline=(Get-Date).AddSeconds({float(args.seconds) + 12.0:.3f}); "
|
||||
"while((Get-Date) -lt $deadline){ "
|
||||
" $info=Get-ScheduledTaskInfo -TaskName '" + task + "'; "
|
||||
" if((Test-Path -LiteralPath $out) -and ((Get-Item -LiteralPath $out).Length -gt 0) -and $info.LastTaskResult -eq 0){ break } "
|
||||
" Start-Sleep -Milliseconds 250 "
|
||||
"}; "
|
||||
"if(-not (Test-Path -LiteralPath $out)){ if(Test-Path -LiteralPath $log){Get-Content $log -Tail 40}; throw 'WASAPI loopback capture did not create output' }; "
|
||||
"Write-Host ('wasapiLoopbackBytes=' + (Get-Item -LiteralPath $out).Length)"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def quote_for_cmd(command: str) -> str:
|
||||
return '"' + command.replace('"', '\\"') + '"'
|
||||
|
||||
|
||||
def escape_ps(value: str) -> str:
|
||||
return value.replace("'", "''")
|
||||
|
||||
|
||||
def sftp_get(ssh_target: str, remote_file: str, local_file: Path) -> None:
|
||||
remote_sftp_path = "/C:/" + remote_file.replace("\\", "/").split("C:/", 1)[-1]
|
||||
batch = f'get "{remote_sftp_path}" "{local_file}"\n'
|
||||
with NamedTemporaryFile("w", encoding="ascii", delete=False, suffix=".sftp") as fh:
|
||||
fh.write(batch)
|
||||
batch_path = fh.name
|
||||
try:
|
||||
completed = subprocess.run(["sftp", "-b", batch_path, ssh_target], text=True, capture_output=True)
|
||||
if completed.returncode:
|
||||
raise SystemExit(completed.stderr or completed.stdout)
|
||||
finally:
|
||||
Path(batch_path).unlink(missing_ok=True)
|
||||
|
||||
|
||||
def record_local_loopback(query: str, seconds: float, sample_rate: int, channels: int) -> np.ndarray:
|
||||
try:
|
||||
import soundcard as sc
|
||||
except Exception as exc:
|
||||
raise SystemExit(f"soundcard loopback capture unavailable: {exc!r}") from exc
|
||||
matches = [
|
||||
mic
|
||||
for mic in sc.all_microphones(include_loopback=True)
|
||||
if "loopback" in repr(mic).lower() and query.lower() in mic.name.lower()
|
||||
]
|
||||
if not matches:
|
||||
raise SystemExit(f"No loopback device matching {query!r}")
|
||||
with matches[0].recorder(samplerate=sample_rate, channels=channels) as recorder:
|
||||
return recorder.record(numframes=int(seconds * sample_rate)).astype(np.float32)
|
||||
|
||||
|
||||
def read_wav_float(path: Path, target_rate: int) -> tuple[int, np.ndarray]:
|
||||
rate, samples = wavfile.read(path)
|
||||
samples = pcm_to_float(samples)
|
||||
if int(rate) != int(target_rate):
|
||||
gcd = math.gcd(int(rate), int(target_rate))
|
||||
samples = signal.resample_poly(samples, int(target_rate) // gcd, int(rate) // gcd, axis=0).astype(np.float32)
|
||||
rate = target_rate
|
||||
return int(rate), ensure_2d(samples)
|
||||
|
||||
|
||||
def read_loopback_capture(path: Path, target_rate: int, capture_kind: str) -> np.ndarray:
|
||||
if capture_kind == "wasapi":
|
||||
samples = np.fromfile(path, dtype=np.float32)
|
||||
if samples.size % 2:
|
||||
samples = samples[:-1]
|
||||
return samples.reshape(-1, 2).astype(np.float32)
|
||||
_, samples = read_wav_float(path, target_rate)
|
||||
return samples
|
||||
|
||||
|
||||
def pcm_to_float(samples: np.ndarray) -> np.ndarray:
|
||||
array = np.asarray(samples)
|
||||
if array.ndim == 1:
|
||||
array = array[:, None]
|
||||
if np.issubdtype(array.dtype, np.floating):
|
||||
return array.astype(np.float32, copy=False)
|
||||
if np.issubdtype(array.dtype, np.signedinteger):
|
||||
scale = float(max(abs(np.iinfo(array.dtype).min), np.iinfo(array.dtype).max))
|
||||
return (array.astype(np.float32) / scale).clip(-1.0, 1.0)
|
||||
raise TypeError(f"unsupported WAV dtype: {array.dtype}")
|
||||
|
||||
|
||||
def ensure_2d(samples: np.ndarray) -> np.ndarray:
|
||||
return samples[:, None] if samples.ndim == 1 else samples
|
||||
|
||||
|
||||
def mono(samples: np.ndarray) -> np.ndarray:
|
||||
samples = ensure_2d(samples)
|
||||
return np.mean(samples, axis=1, dtype=np.float32)
|
||||
|
||||
|
||||
def normalized_delay(signal_a: np.ndarray, signal_b: np.ndarray, max_lag: int) -> tuple[int, float]:
|
||||
count = min(len(signal_a), len(signal_b))
|
||||
if count <= 0:
|
||||
return 0, 0.0
|
||||
a = signal_a[:count].astype(np.float32)
|
||||
b = signal_b[:count].astype(np.float32)
|
||||
if float(np.std(a)) <= 1e-12 or float(np.std(b)) <= 1e-12:
|
||||
return 0, 0.0
|
||||
a = (a - float(np.mean(a))) / (float(np.std(a)) + 1e-9)
|
||||
b = (b - float(np.mean(b))) / (float(np.std(b)) + 1e-9)
|
||||
corr = signal.correlate(a, b, mode="full", method="fft")
|
||||
mid = len(b) - 1
|
||||
segment = corr[mid - max_lag : mid + max_lag + 1]
|
||||
index = int(np.argmax(np.abs(segment)))
|
||||
lag = index - max_lag
|
||||
score = float(abs(segment[index]) / max(1, len(a)))
|
||||
return lag, score
|
||||
|
||||
|
||||
def rms(samples: np.ndarray) -> float:
|
||||
samples = np.asarray(samples, dtype=np.float32)
|
||||
return float(np.sqrt(np.mean(samples * samples))) if samples.size else 0.0
|
||||
|
||||
|
||||
def shift_by_delay(samples: np.ndarray, delay_samples: int, frame_count: int) -> np.ndarray:
|
||||
samples = ensure_2d(samples)
|
||||
out = np.zeros((frame_count, samples.shape[1]), dtype=np.float32)
|
||||
if delay_samples >= 0:
|
||||
src_start = delay_samples
|
||||
dst_start = 0
|
||||
else:
|
||||
src_start = 0
|
||||
dst_start = -delay_samples
|
||||
count = min(frame_count - dst_start, samples.shape[0] - src_start)
|
||||
if count > 0:
|
||||
out[dst_start : dst_start + count] = samples[src_start : src_start + count]
|
||||
return out
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
|
@ -1,245 +0,0 @@
|
|||
import argparse
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
TARGETS = ROOT / "calibration" / "targets"
|
||||
RUNS = ROOT / "calibration" / "runs"
|
||||
|
||||
|
||||
def utc_stamp() -> str:
|
||||
return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||
|
||||
|
||||
def write_json(path: Path, data) -> None:
|
||||
path.write_text(json.dumps(data, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
def dictionary(name: str):
|
||||
if not hasattr(cv2.aruco, name):
|
||||
raise ValueError(f"Unknown ArUco dictionary: {name}")
|
||||
return cv2.aruco.getPredefinedDictionary(getattr(cv2.aruco, name))
|
||||
|
||||
|
||||
def make_board(args):
|
||||
TARGETS.mkdir(parents=True, exist_ok=True)
|
||||
aruco_dict = dictionary(args.dictionary)
|
||||
board = cv2.aruco.CharucoBoard(
|
||||
(args.squares_x, args.squares_y),
|
||||
args.square_length,
|
||||
args.marker_length,
|
||||
aruco_dict,
|
||||
)
|
||||
width = args.squares_x * args.pixels_per_square
|
||||
height = args.squares_y * args.pixels_per_square
|
||||
image = board.generateImage((width, height), marginSize=args.margin, borderBits=1)
|
||||
out = TARGETS / args.output
|
||||
cv2.imwrite(str(out), image)
|
||||
meta = {
|
||||
"created_utc": datetime.now(timezone.utc).isoformat(),
|
||||
"dictionary": args.dictionary,
|
||||
"squares_x": args.squares_x,
|
||||
"squares_y": args.squares_y,
|
||||
"square_length": args.square_length,
|
||||
"marker_length": args.marker_length,
|
||||
"pixels_per_square": args.pixels_per_square,
|
||||
"margin": args.margin,
|
||||
"image": str(out.relative_to(ROOT)),
|
||||
}
|
||||
write_json(out.with_suffix(".json"), meta)
|
||||
print(out)
|
||||
|
||||
|
||||
def api_value(name: str):
|
||||
return {
|
||||
"any": 0,
|
||||
"dshow": cv2.CAP_DSHOW,
|
||||
"msmf": cv2.CAP_MSMF,
|
||||
}[name]
|
||||
|
||||
|
||||
def open_camera(index: int, api: str, width: int | None, height: int | None, fps: int | None):
|
||||
cap = cv2.VideoCapture(index, api_value(api))
|
||||
if width:
|
||||
cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
|
||||
if height:
|
||||
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
|
||||
if fps:
|
||||
cap.set(cv2.CAP_PROP_FPS, fps)
|
||||
cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
|
||||
return cap
|
||||
|
||||
|
||||
def detect_charuco(gray, board, aruco_dict):
|
||||
corners, ids, _ = cv2.aruco.detectMarkers(gray, aruco_dict)
|
||||
if ids is None or len(ids) == 0:
|
||||
return None, None, corners, ids
|
||||
count, charuco_corners, charuco_ids = cv2.aruco.interpolateCornersCharuco(corners, ids, gray, board)
|
||||
if count is None or count < 1:
|
||||
return None, None, corners, ids
|
||||
return charuco_corners, charuco_ids, corners, ids
|
||||
|
||||
|
||||
def capture(args):
|
||||
aruco_dict = dictionary(args.dictionary)
|
||||
board = cv2.aruco.CharucoBoard(
|
||||
(args.squares_x, args.squares_y),
|
||||
args.square_length,
|
||||
args.marker_length,
|
||||
aruco_dict,
|
||||
)
|
||||
out = RUNS / f"{utc_stamp()}-charuco-capture-{args.api}{args.index}"
|
||||
out.mkdir(parents=True, exist_ok=False)
|
||||
cap = open_camera(args.index, args.api, args.width, args.height, args.fps)
|
||||
if not cap.isOpened():
|
||||
raise SystemExit(f"Could not open camera {args.api}:{args.index}")
|
||||
|
||||
accepted = []
|
||||
start = time.monotonic()
|
||||
last_save = 0.0
|
||||
attempts = 0
|
||||
while len(accepted) < args.frames and (time.monotonic() - start) < args.timeout:
|
||||
ok, frame = cap.read()
|
||||
attempts += 1
|
||||
if not ok or frame is None:
|
||||
continue
|
||||
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
||||
charuco_corners, charuco_ids, marker_corners, marker_ids = detect_charuco(gray, board, aruco_dict)
|
||||
corner_count = 0 if charuco_ids is None else int(len(charuco_ids))
|
||||
now = time.monotonic()
|
||||
if corner_count >= args.min_corners and (now - last_save) >= args.interval:
|
||||
filename = f"frame-{len(accepted):03d}-corners{corner_count}.png"
|
||||
cv2.imwrite(str(out / filename), frame)
|
||||
accepted.append(
|
||||
{
|
||||
"file": filename,
|
||||
"timestamp_monotonic": now,
|
||||
"charuco_corners": corner_count,
|
||||
"charuco_ids": [] if charuco_ids is None else [int(value) for value in charuco_ids.reshape(-1)],
|
||||
"charuco_image_points": []
|
||||
if charuco_corners is None
|
||||
else [[float(x), float(y)] for x, y in charuco_corners.reshape((-1, 2))],
|
||||
"marker_count": 0 if marker_ids is None else int(len(marker_ids)),
|
||||
}
|
||||
)
|
||||
last_save = now
|
||||
print(f"saved {filename}")
|
||||
cap.release()
|
||||
manifest = {
|
||||
"created_utc": datetime.now(timezone.utc).isoformat(),
|
||||
"camera": {"api": args.api, "index": args.index},
|
||||
"board": {
|
||||
"dictionary": args.dictionary,
|
||||
"squares_x": args.squares_x,
|
||||
"squares_y": args.squares_y,
|
||||
"square_length": args.square_length,
|
||||
"marker_length": args.marker_length,
|
||||
},
|
||||
"attempts": attempts,
|
||||
"accepted": accepted,
|
||||
}
|
||||
write_json(out / "manifest.json", manifest)
|
||||
print(out)
|
||||
|
||||
|
||||
def calibrate(args):
|
||||
aruco_dict = dictionary(args.dictionary)
|
||||
board = cv2.aruco.CharucoBoard(
|
||||
(args.squares_x, args.squares_y),
|
||||
args.square_length,
|
||||
args.marker_length,
|
||||
aruco_dict,
|
||||
)
|
||||
image_paths = sorted(Path(args.images).glob("*.png"))
|
||||
all_corners = []
|
||||
all_ids = []
|
||||
image_size = None
|
||||
used = []
|
||||
for path in image_paths:
|
||||
image = cv2.imread(str(path))
|
||||
if image is None:
|
||||
continue
|
||||
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
||||
image_size = gray.shape[::-1]
|
||||
charuco_corners, charuco_ids, _, _ = detect_charuco(gray, board, aruco_dict)
|
||||
if charuco_ids is None or len(charuco_ids) < args.min_corners:
|
||||
continue
|
||||
all_corners.append(charuco_corners)
|
||||
all_ids.append(charuco_ids)
|
||||
used.append(str(path))
|
||||
if len(all_corners) < args.min_frames:
|
||||
raise SystemExit(f"Need {args.min_frames} usable frames; found {len(all_corners)}")
|
||||
rms, camera_matrix, dist_coeffs, rvecs, tvecs = cv2.aruco.calibrateCameraCharuco(
|
||||
all_corners,
|
||||
all_ids,
|
||||
board,
|
||||
image_size,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
result = {
|
||||
"created_utc": datetime.now(timezone.utc).isoformat(),
|
||||
"rms_reprojection_error": float(rms),
|
||||
"image_size": image_size,
|
||||
"camera_matrix": camera_matrix.tolist(),
|
||||
"dist_coeffs": dist_coeffs.tolist(),
|
||||
"used_frames": used,
|
||||
}
|
||||
out = Path(args.output) if args.output else Path(args.images) / "intrinsics.json"
|
||||
write_json(out, result)
|
||||
print(out)
|
||||
print(json.dumps({"rms_reprojection_error": result["rms_reprojection_error"], "frames": len(used)}, indent=2))
|
||||
|
||||
|
||||
def add_board_args(parser):
|
||||
parser.add_argument("--dictionary", default="DICT_4X4_100")
|
||||
parser.add_argument("--squares-x", type=int, default=8)
|
||||
parser.add_argument("--squares-y", type=int, default=6)
|
||||
parser.add_argument("--square-length", type=float, default=0.035)
|
||||
parser.add_argument("--marker-length", type=float, default=0.026)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Generate and capture ChArUco calibration data.")
|
||||
sub = parser.add_subparsers(required=True)
|
||||
|
||||
p = sub.add_parser("board")
|
||||
add_board_args(p)
|
||||
p.add_argument("--pixels-per-square", type=int, default=180)
|
||||
p.add_argument("--margin", type=int, default=40)
|
||||
p.add_argument("--output", default="charuco-8x6-dict4x4-100.png")
|
||||
p.set_defaults(func=make_board)
|
||||
|
||||
p = sub.add_parser("capture")
|
||||
add_board_args(p)
|
||||
p.add_argument("--api", choices=["any", "dshow", "msmf"], default="dshow")
|
||||
p.add_argument("--index", type=int, required=True)
|
||||
p.add_argument("--width", type=int)
|
||||
p.add_argument("--height", type=int)
|
||||
p.add_argument("--fps", type=int)
|
||||
p.add_argument("--frames", type=int, default=25)
|
||||
p.add_argument("--timeout", type=float, default=60.0)
|
||||
p.add_argument("--interval", type=float, default=0.5)
|
||||
p.add_argument("--min-corners", type=int, default=12)
|
||||
p.set_defaults(func=capture)
|
||||
|
||||
p = sub.add_parser("calibrate")
|
||||
add_board_args(p)
|
||||
p.add_argument("--images", required=True)
|
||||
p.add_argument("--output")
|
||||
p.add_argument("--min-corners", type=int, default=12)
|
||||
p.add_argument("--min-frames", type=int, default=8)
|
||||
p.set_defaults(func=calibrate)
|
||||
|
||||
args = parser.parse_args()
|
||||
args.func(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -1,193 +0,0 @@
|
|||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
|
||||
def read_json(path: Path):
|
||||
if not path.exists():
|
||||
return None
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def read_last_jsonl(path: Path):
|
||||
if not path.exists():
|
||||
return None
|
||||
lines = [line for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
|
||||
if not lines:
|
||||
return None
|
||||
return json.loads(lines[-1])
|
||||
|
||||
|
||||
def msgpack_head(path: Path):
|
||||
if not path.exists():
|
||||
return None
|
||||
import msgpack
|
||||
|
||||
outer = msgpack.unpackb(path.read_bytes(), raw=False)
|
||||
if not outer:
|
||||
return None
|
||||
payload = msgpack.unpackb(outer[0]["payload"], raw=False)
|
||||
head = payload[:8] if isinstance(payload, list) else payload
|
||||
summary = {
|
||||
"key": outer[0].get("key"),
|
||||
"type": outer[0].get("type"),
|
||||
"storedAt": outer[0].get("storedAt"),
|
||||
}
|
||||
if not isinstance(payload, list):
|
||||
summary["payload"] = str(payload)[:120]
|
||||
return summary
|
||||
summary["schema"] = payload[0] if payload else None
|
||||
if summary["type"] == "localcast.visual.render_frame":
|
||||
points = payload[10] if len(payload) > 10 else []
|
||||
point_prefix_counts = {}
|
||||
for point in points:
|
||||
prefix = str(point[0]).split(":", 1)[0]
|
||||
point_prefix_counts[prefix] = point_prefix_counts.get(prefix, 0) + 1
|
||||
summary.update(
|
||||
{
|
||||
"frameId": payload[1],
|
||||
"presentTimeNs": payload[5],
|
||||
"audioAlignmentTimeNs": payload[6],
|
||||
"pointCount": len(points),
|
||||
"pointPrefixCounts": dict(sorted(point_prefix_counts.items())),
|
||||
}
|
||||
)
|
||||
elif summary["type"] == "localcast.audio.spatial_frame":
|
||||
summary.update(
|
||||
{
|
||||
"frameId": payload[1],
|
||||
"audioTimeNs": payload[3],
|
||||
"sampleRate": payload[4],
|
||||
"startSample": payload[5],
|
||||
"frameCount": payload[6],
|
||||
"channels": payload[9] if len(payload) > 9 else [],
|
||||
}
|
||||
)
|
||||
elif summary["type"] == "localcast.audio.source_events":
|
||||
summary.update(
|
||||
{
|
||||
"frameId": payload[1],
|
||||
"sampleRate": payload[3],
|
||||
"startSample": payload[4],
|
||||
"frameCount": payload[5],
|
||||
"eventCount": len(payload[6]) if len(payload) > 6 else 0,
|
||||
"focusCount": len(payload[7]) if len(payload) > 7 else 0,
|
||||
}
|
||||
)
|
||||
elif summary["type"] == "localcast.audio.phase_field":
|
||||
sources = payload[7] if len(payload) > 7 else []
|
||||
summary.update(
|
||||
{
|
||||
"frameId": payload[1],
|
||||
"sampleRate": payload[3],
|
||||
"startSample": payload[4],
|
||||
"frameCount": payload[5],
|
||||
"referenceId": payload[6],
|
||||
"sourceCount": len(sources),
|
||||
"globalConfidence": payload[8] if len(payload) > 8 else 0.0,
|
||||
"needsActiveProbe": payload[9] if len(payload) > 9 else True,
|
||||
"sources": [
|
||||
{
|
||||
"sourceId": source.get("sourceId"),
|
||||
"delayMs": source.get("delayMs"),
|
||||
"distanceDeltaMeters": source.get("distanceDeltaMeters"),
|
||||
"coherence": source.get("coherence"),
|
||||
"fitErrorRadians": source.get("fitErrorRadians"),
|
||||
"confidence": source.get("confidence"),
|
||||
"referenceBleed": source.get("referenceBleed"),
|
||||
"suppressionWeight": source.get("suppressionWeight"),
|
||||
}
|
||||
for source in sources
|
||||
],
|
||||
}
|
||||
)
|
||||
elif summary["type"] == "localcast.audio.mic_field":
|
||||
summary.update(
|
||||
{
|
||||
"frameId": payload[1],
|
||||
"audioTimeNs": payload[3],
|
||||
"sampleRate": payload[4],
|
||||
"startSample": payload[5],
|
||||
"frameCount": payload[6],
|
||||
"channels": payload[7] if len(payload) > 7 else [],
|
||||
"graphId": payload[9] if len(payload) > 9 else "",
|
||||
}
|
||||
)
|
||||
elif summary["type"] in ("localcast.visual.stream_status", "localcast.audio.stream_status"):
|
||||
summary["payloadHead"] = head
|
||||
elif summary["type"] == "localcast.calibration.clap_events":
|
||||
summary.update(
|
||||
{
|
||||
"frameId": payload[1],
|
||||
"eventCount": len(payload[3]) if len(payload) > 3 else 0,
|
||||
"latestEvent": None
|
||||
if len(payload) <= 3 or not payload[3]
|
||||
else {
|
||||
"stableKey": payload[3][-1][0],
|
||||
"positionM": payload[3][-1][1],
|
||||
"acousticOracleNs": payload[3][-1][2],
|
||||
"visualObservedNs": payload[3][-1][3],
|
||||
"timingUncertaintyUs": payload[3][-1][4],
|
||||
"cameraCount": len(payload[3][-1][7]) if len(payload[3][-1]) > 7 else 0,
|
||||
"cameraOffsetsNs": {
|
||||
str(peak.get("sensorId")): int(payload[3][-1][2]) - int(peak.get("timestampNs", payload[3][-1][2]))
|
||||
for peak in (payload[3][-1][7] if len(payload[3][-1]) > 7 else [])
|
||||
},
|
||||
},
|
||||
}
|
||||
)
|
||||
return summary
|
||||
|
||||
|
||||
def file_freshness(path: Path, now: float) -> dict:
|
||||
if not path.exists():
|
||||
return {"exists": False}
|
||||
age = max(0.0, now - path.stat().st_mtime)
|
||||
return {"exists": True, "ageSeconds": age, "bytes": path.stat().st_size}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
runs = ROOT / "calibration" / "runs"
|
||||
now = time.time()
|
||||
files = {
|
||||
name: file_freshness(runs / name, now)
|
||||
for name in [
|
||||
"visual-state.msgpack",
|
||||
"audio-state.msgpack",
|
||||
"audio-events.msgpack",
|
||||
"visual-stream-status.msgpack",
|
||||
"audio-stream-status.msgpack",
|
||||
"audio-phase-field.msgpack",
|
||||
"audio-phase-field-status.json",
|
||||
"audio-mic-field.msgpack",
|
||||
"clap-events.msgpack",
|
||||
"active-probes/active-probes.jsonl",
|
||||
"visual-lod-cache.json",
|
||||
"stream-spout-status.json",
|
||||
"av-sync-status.json",
|
||||
]
|
||||
}
|
||||
payload = {
|
||||
"createdWallTime": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
|
||||
"files": files,
|
||||
"avSync": read_json(runs / "av-sync-status.json"),
|
||||
"spout": read_json(runs / "stream-spout-status.json"),
|
||||
"visualHead": msgpack_head(runs / "visual-state.msgpack"),
|
||||
"audioHead": msgpack_head(runs / "audio-state.msgpack"),
|
||||
"eventsHead": msgpack_head(runs / "audio-events.msgpack"),
|
||||
"phaseFieldHead": msgpack_head(runs / "audio-phase-field.msgpack"),
|
||||
"phaseRuntime": read_json(runs / "audio-phase-field-status.json"),
|
||||
"micFieldHead": msgpack_head(runs / "audio-mic-field.msgpack"),
|
||||
"clapHead": msgpack_head(runs / "clap-events.msgpack"),
|
||||
"lastActiveProbe": read_last_jsonl(runs / "active-probes" / "active-probes.jsonl"),
|
||||
}
|
||||
print(json.dumps(payload, indent=2, default=str))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -1,62 +0,0 @@
|
|||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from localcast.obs_smoke import load_config_endpoints, read_events_jsonl, summarize_events, write_event_template
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Create the bounded OBS v1 smoke-test witness ledger.")
|
||||
parser.add_argument("--config", default="config/localcast.json")
|
||||
parser.add_argument("--events", default="calibration/runs/obs-v1-smoke-events.jsonl")
|
||||
parser.add_argument("--ledger", default="calibration/runs/obs-v1-smoke-ledger.json")
|
||||
parser.add_argument("--max-abs-drift-ppm", type=float, default=100.0)
|
||||
parser.add_argument("--max-latency-ms", type=float, default=500.0)
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
sub.add_parser("plan", help="Print planned OBS-facing endpoints from the Mimir config.")
|
||||
sub.add_parser("template-events", help="Write an editable JSONL event template for one smoke pass.")
|
||||
sub.add_parser("summarize", help="Summarize recorded events into the smoke-test ledger.")
|
||||
args = parser.parse_args()
|
||||
|
||||
config_path = Path(args.config)
|
||||
endpoints = load_config_endpoints(config_path)
|
||||
|
||||
if args.command == "plan":
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"config": str(config_path),
|
||||
"endpoints": [endpoint.__dict__ for endpoint in endpoints],
|
||||
"requiredStages": ["sender_capture", "srt_receive", "obs_present"],
|
||||
},
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
events_path = Path(args.events)
|
||||
if args.command == "template-events":
|
||||
write_event_template(events_path, endpoints)
|
||||
print(f"Wrote smoke event template: {events_path}")
|
||||
return
|
||||
|
||||
ledger_path = Path(args.ledger)
|
||||
events = read_events_jsonl(events_path)
|
||||
ledger = summarize_events(
|
||||
endpoints,
|
||||
events,
|
||||
max_abs_drift_ppm=args.max_abs_drift_ppm,
|
||||
max_latency_ms=args.max_latency_ms,
|
||||
)
|
||||
ledger_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
ledger_path.write_text(json.dumps(ledger, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
||||
print(json.dumps(ledger, indent=2, sort_keys=True))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -1,61 +0,0 @@
|
|||
import argparse
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from localcast.sensor_fusion.active_illumination import (
|
||||
ActiveIlluminationController,
|
||||
IlluminationPulsePlan,
|
||||
TinytuyaLightPort,
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Pulse a local Tuya light as active vision calibration telemetry.")
|
||||
parser.add_argument("--device-id", required=True)
|
||||
parser.add_argument("--address", required=True)
|
||||
parser.add_argument("--local-key", required=True)
|
||||
parser.add_argument("--version", default="3.3")
|
||||
parser.add_argument("--count", type=int, default=6)
|
||||
parser.add_argument("--bright-ms", type=int, default=90)
|
||||
parser.add_argument("--settle-ms", type=int, default=210)
|
||||
parser.add_argument("--brightness", type=int, default=100)
|
||||
parser.add_argument("--idle-brightness", type=int, default=18)
|
||||
parser.add_argument("--color-temp", type=int, default=50)
|
||||
parser.add_argument("--dps-power", default="20")
|
||||
parser.add_argument("--dps-brightness", default="22")
|
||||
parser.add_argument("--dps-color-temp", default="23")
|
||||
args = parser.parse_args()
|
||||
|
||||
light = TinytuyaLightPort(
|
||||
device_id=args.device_id,
|
||||
address=args.address,
|
||||
local_key=args.local_key,
|
||||
version=args.version,
|
||||
dps_power=args.dps_power,
|
||||
dps_brightness=args.dps_brightness,
|
||||
dps_color_temp=args.dps_color_temp,
|
||||
)
|
||||
plan = IlluminationPulsePlan(
|
||||
pulse_count=args.count,
|
||||
bright_ms=args.bright_ms,
|
||||
settle_ms=args.settle_ms,
|
||||
brightness_percent=args.brightness,
|
||||
idle_brightness_percent=args.idle_brightness,
|
||||
color_temp_percent=args.color_temp,
|
||||
)
|
||||
pulses = ActiveIlluminationController(light, plan).run()
|
||||
for pulse in pulses:
|
||||
print(
|
||||
f"pulse={pulse.pulse_index} "
|
||||
f"start_ns={pulse.start_monotonic_ns} "
|
||||
f"bright_until_ns={pulse.bright_until_monotonic_ns} "
|
||||
f"settle_until_ns={pulse.settle_until_monotonic_ns}"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -1,82 +0,0 @@
|
|||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from localcast.sensor_fusion import (
|
||||
Observation2D,
|
||||
PointCloud,
|
||||
RenderBridgeConfig,
|
||||
TrackCache,
|
||||
load_fusion_config,
|
||||
lower_points_to_render_frame,
|
||||
)
|
||||
from localcast.diagnostics.render_frame_json import write_render_frame_json
|
||||
|
||||
|
||||
|
||||
def load_observations(path: Path) -> list[Observation2D]:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
if isinstance(data, dict):
|
||||
data = data.get("observations", [])
|
||||
return [Observation2D.from_dict(item) for item in data]
|
||||
|
||||
|
||||
def fuse_file(args) -> None:
|
||||
config_path = Path(args.config)
|
||||
config_data = json.loads(config_path.read_text(encoding="utf-8"))
|
||||
rig = load_fusion_config(config_path)
|
||||
observations = load_observations(Path(args.observations))
|
||||
result = rig.fuse(observations)
|
||||
cache = TrackCache(ttl_ns=rig.config.cache_ttl_ns)
|
||||
for point in result.points:
|
||||
cache.update(point)
|
||||
if args.now_ns is not None:
|
||||
cache.expire(args.now_ns)
|
||||
cloud = PointCloud(cache.points())
|
||||
output = Path(args.output)
|
||||
cloud.write_ply(output)
|
||||
render_frame_output = None
|
||||
if args.render_frame_json:
|
||||
render_config = RenderBridgeConfig.from_dict(config_data.get("render_bridge", {}))
|
||||
frame = lower_points_to_render_frame(
|
||||
cloud.points,
|
||||
render_config,
|
||||
frame_id=args.frame_id,
|
||||
created_monotonic_ns=args.created_ns,
|
||||
)
|
||||
render_frame_output = Path(args.render_frame_json)
|
||||
write_render_frame_json(render_frame_output, frame)
|
||||
summary = {
|
||||
"output": str(output),
|
||||
"render_frame_json": None if render_frame_output is None else str(render_frame_output),
|
||||
"points": len(cloud.points),
|
||||
"dropped": list(result.dropped),
|
||||
}
|
||||
print(json.dumps(summary, indent=2))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Build sparse point clouds from calibrated sensor observations.")
|
||||
sub = parser.add_subparsers(required=True)
|
||||
|
||||
p = sub.add_parser("fuse-file")
|
||||
p.add_argument("--config", default=str(ROOT / "config" / "sensor-fusion.example.json"))
|
||||
p.add_argument("--observations", required=True)
|
||||
p.add_argument("--output", required=True)
|
||||
p.add_argument("--now-ns", type=int)
|
||||
p.add_argument("--render-frame-json")
|
||||
p.add_argument("--frame-id", type=int, default=0)
|
||||
p.add_argument("--created-ns", type=int, default=0)
|
||||
p.set_defaults(func=fuse_file)
|
||||
|
||||
args = parser.parse_args()
|
||||
args.func(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -1,415 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
from scipy.io import wavfile
|
||||
from scipy.signal import resample_poly
|
||||
|
||||
|
||||
DEFAULT_RUN = Path("calibration/runs/audio-program-live-20260518-180226")
|
||||
DEFAULT_SCENE = "Scene"
|
||||
RAW_UNSYNCED_INPUTS = (
|
||||
"Neighbor PC - Video",
|
||||
"Neighbor PC - Focusrite",
|
||||
"Neighbor PC - System Audio",
|
||||
"Desktop Audio",
|
||||
"Mic/Aux",
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description=(
|
||||
"Build synchronized Mimir OBS audio stems from the aligned "
|
||||
"program timeline and hide raw unsynchronized OBS inputs."
|
||||
)
|
||||
)
|
||||
parser.add_argument("--run", type=Path, default=DEFAULT_RUN)
|
||||
parser.add_argument("--scene", default=DEFAULT_SCENE)
|
||||
parser.add_argument("--host", default="127.0.0.1")
|
||||
parser.add_argument("--port", type=int, default=4455)
|
||||
parser.add_argument("--password", default="")
|
||||
parser.add_argument("--dry-run", action="store_true")
|
||||
parser.add_argument("--skip-obs", action="store_true")
|
||||
parser.add_argument(
|
||||
"--disable-other-scene-items",
|
||||
action="store_true",
|
||||
help="Disable every scene item except the synchronized Mimir program sources.",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
run = args.run.resolve()
|
||||
stem_dir = run / "stems"
|
||||
stem_dir.mkdir(parents=True, exist_ok=True)
|
||||
manifest = build_stems(run, stem_dir)
|
||||
manifest_path = stem_dir / "manifest.json"
|
||||
manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
|
||||
print(f"wrote {manifest_path}")
|
||||
|
||||
if args.skip_obs:
|
||||
return 0
|
||||
configure_obs(
|
||||
stem_manifest=manifest,
|
||||
scene=args.scene,
|
||||
host=args.host,
|
||||
port=args.port,
|
||||
password=args.password,
|
||||
dry_run=args.dry_run,
|
||||
disable_other_scene_items=args.disable_other_scene_items,
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
def build_stems(run: Path, stem_dir: Path) -> dict[str, Any]:
|
||||
field_rate, field = read_wav_float(run / "field-program-cleaned.wav")
|
||||
field = ensure_2d(field)
|
||||
frame_count = field.shape[0]
|
||||
events_path = run / "field-program-cleaned.source-events.json"
|
||||
events_doc = json.loads(events_path.read_text(encoding="utf-8")) if events_path.exists() else {}
|
||||
|
||||
witness_channels = [channel for channel in (0, 2, 3) if channel < field.shape[1]]
|
||||
witness_mix = mix_channels(field, witness_channels) if witness_channels else np.zeros(frame_count, dtype=np.float32)
|
||||
host_voice = channel_or_silence(field, 4)
|
||||
co_streamer_voice, co_streamer_voice_status = load_co_streamer_surface(
|
||||
run / "co_streamer_surfaces" / "aligned_focusrite.wav",
|
||||
field_rate,
|
||||
frame_count,
|
||||
channel_fallback=channel_or_silence(field, 5),
|
||||
placeholder_status="placeholder-silence-until-neighbor-focusrite-is-in-aligned-timeline",
|
||||
synced_status="synced-from-neighbor-focusrite-surface",
|
||||
)
|
||||
ambient = make_ambient_stem(witness_mix, host_voice, co_streamer_voice)
|
||||
transients = make_transient_stem(witness_mix, events_doc, frame_count)
|
||||
local_loopback = load_optional_program_audio(run / "ground_truth_loopback.wav", field_rate, frame_count)
|
||||
co_streamer_loopback, co_streamer_loopback_status = load_co_streamer_surface(
|
||||
run / "co_streamer_surfaces" / "aligned_loopback.wav",
|
||||
field_rate,
|
||||
frame_count,
|
||||
channel_fallback=np.zeros((frame_count, 2), dtype=np.float32),
|
||||
placeholder_status="placeholder-silence-until-neighbor-loopback-is-captured-and-aligned",
|
||||
synced_status="synced-from-neighbor-loopback-surface",
|
||||
low_signal_status="captured-but-low-confidence-neighbor-loopback-is-near-silent",
|
||||
min_rms=1e-4,
|
||||
)
|
||||
|
||||
stems = [
|
||||
stem_spec(
|
||||
"Mimir - Host Voice",
|
||||
"host_voice.wav",
|
||||
host_voice,
|
||||
field_rate,
|
||||
role="dialogue",
|
||||
status="synced-from-local-focusrite-anchor",
|
||||
position_m=[0.0, 0.0, 1.2],
|
||||
),
|
||||
stem_spec(
|
||||
"Mimir - CoStreamer Voice",
|
||||
"co_streamer_voice.wav",
|
||||
co_streamer_voice,
|
||||
field_rate,
|
||||
role="dialogue",
|
||||
status=co_streamer_voice_status,
|
||||
position_m=[0.0, 2.0, 1.2],
|
||||
),
|
||||
stem_spec(
|
||||
"Mimir - Ambient",
|
||||
"ambient.wav",
|
||||
ambient,
|
||||
field_rate,
|
||||
role="room",
|
||||
status="synced-context-mic-field-minus-dialogue-anchors",
|
||||
position_m=None,
|
||||
),
|
||||
stem_spec(
|
||||
"Mimir - Transients",
|
||||
"transients.wav",
|
||||
transients,
|
||||
field_rate,
|
||||
role="localized-transients",
|
||||
status="synced-event-gated-context-field",
|
||||
position_m=None,
|
||||
),
|
||||
stem_spec(
|
||||
"Mimir - CoStreamer Loopback",
|
||||
"co_streamer_loopback.wav",
|
||||
co_streamer_loopback,
|
||||
field_rate,
|
||||
role="program-loopback",
|
||||
status=co_streamer_loopback_status,
|
||||
position_m=None,
|
||||
),
|
||||
stem_spec(
|
||||
"Mimir - Local Loopback",
|
||||
"local_loopback.wav",
|
||||
local_loopback,
|
||||
field_rate,
|
||||
role="program-loopback",
|
||||
status="synced-ground-truth-local-loopback",
|
||||
position_m=None,
|
||||
),
|
||||
]
|
||||
|
||||
for stem in stems:
|
||||
path = stem_dir / stem["file"]
|
||||
wavfile.write(path, field_rate, np.asarray(stem.pop("_samples"), dtype=np.float32))
|
||||
stem["path"] = str(path.resolve())
|
||||
|
||||
return {
|
||||
"schema_version": "gamecult.localcast.obs_synced_program.v1",
|
||||
"run": str(run),
|
||||
"sample_rate": field_rate,
|
||||
"frame_count": frame_count,
|
||||
"duration_seconds": frame_count / field_rate,
|
||||
"timeline": "field-program-cleaned.wav",
|
||||
"unsynced_inputs_hidden": list(RAW_UNSYNCED_INPUTS),
|
||||
"stems": stems,
|
||||
}
|
||||
|
||||
|
||||
def stem_spec(
|
||||
obs_name: str,
|
||||
filename: str,
|
||||
samples: np.ndarray,
|
||||
sample_rate: int,
|
||||
*,
|
||||
role: str,
|
||||
status: str,
|
||||
position_m: list[float] | None,
|
||||
) -> dict[str, Any]:
|
||||
rendered = limit_peak(np.asarray(samples, dtype=np.float32))
|
||||
return {
|
||||
"obs_name": obs_name,
|
||||
"file": filename,
|
||||
"channels": 1 if rendered.ndim == 1 else int(rendered.shape[1]),
|
||||
"sample_rate": int(sample_rate),
|
||||
"role": role,
|
||||
"status": status,
|
||||
"position_m": position_m,
|
||||
"_samples": rendered,
|
||||
}
|
||||
|
||||
|
||||
def configure_obs(
|
||||
*,
|
||||
stem_manifest: dict[str, Any],
|
||||
scene: str,
|
||||
host: str,
|
||||
port: int,
|
||||
password: str,
|
||||
dry_run: bool,
|
||||
disable_other_scene_items: bool,
|
||||
) -> None:
|
||||
import obsws_python as obs
|
||||
|
||||
client = obs.ReqClient(host=host, port=port, password=password, timeout=3)
|
||||
existing_inputs = {item["inputName"] for item in client.get_input_list().inputs}
|
||||
scene_items = scene_item_ids(client, scene)
|
||||
|
||||
for raw_name in RAW_UNSYNCED_INPUTS:
|
||||
if dry_run:
|
||||
print(f"would disable/mute raw input: {raw_name}")
|
||||
continue
|
||||
mute_input(client, raw_name)
|
||||
disable_scene_item(client, scene, scene_items, raw_name)
|
||||
|
||||
allowed_scene_items = {"Mimir Point Cloud"} | {
|
||||
str(stem["obs_name"]) for stem in stem_manifest["stems"]
|
||||
}
|
||||
|
||||
for stem in stem_manifest["stems"]:
|
||||
settings = {
|
||||
"is_local_file": True,
|
||||
"local_file": stem["path"],
|
||||
"looping": True,
|
||||
"clear_on_media_end": False,
|
||||
"restart_on_activate": True,
|
||||
"buffering_mb": 2,
|
||||
}
|
||||
name = stem["obs_name"]
|
||||
if dry_run:
|
||||
print(f"would create/update OBS stem: {name} -> {stem['path']}")
|
||||
continue
|
||||
if name in existing_inputs:
|
||||
client.set_input_settings(name, settings, True)
|
||||
scene_items = scene_item_ids(client, scene)
|
||||
enable_scene_item(client, scene, scene_items, name)
|
||||
else:
|
||||
client.create_input(scene, name, "ffmpeg_source", settings, True)
|
||||
existing_inputs.add(name)
|
||||
scene_items = scene_item_ids(client, scene)
|
||||
client.set_input_mute(name, False)
|
||||
client.set_input_volume(name, vol_mul=1.0)
|
||||
restart_media_if_possible(client, name)
|
||||
if disable_other_scene_items:
|
||||
scene_items = scene_item_ids(client, scene)
|
||||
for source_name in sorted(scene_items):
|
||||
if source_name in allowed_scene_items:
|
||||
continue
|
||||
if dry_run:
|
||||
print(f"would disable non-program scene item: {source_name}")
|
||||
continue
|
||||
disable_scene_item(client, scene, scene_items, source_name)
|
||||
print("OBS synchronized program scene is configured")
|
||||
|
||||
|
||||
def read_wav_float(path: Path) -> tuple[int, np.ndarray]:
|
||||
sample_rate, samples = wavfile.read(path)
|
||||
return int(sample_rate), pcm_to_float(samples)
|
||||
|
||||
|
||||
def pcm_to_float(samples: np.ndarray) -> np.ndarray:
|
||||
array = np.asarray(samples)
|
||||
if np.issubdtype(array.dtype, np.floating):
|
||||
return array.astype(np.float32, copy=False)
|
||||
if np.issubdtype(array.dtype, np.signedinteger):
|
||||
scale = float(max(abs(np.iinfo(array.dtype).min), np.iinfo(array.dtype).max))
|
||||
return (array.astype(np.float32) / scale).clip(-1.0, 1.0)
|
||||
if np.issubdtype(array.dtype, np.unsignedinteger):
|
||||
midpoint = float(np.iinfo(array.dtype).max) / 2.0
|
||||
return ((array.astype(np.float32) - midpoint) / midpoint).clip(-1.0, 1.0)
|
||||
raise TypeError(f"unsupported WAV dtype: {array.dtype}")
|
||||
|
||||
|
||||
def ensure_2d(samples: np.ndarray) -> np.ndarray:
|
||||
if samples.ndim == 1:
|
||||
return samples[:, None]
|
||||
if samples.ndim != 2:
|
||||
raise ValueError("expected mono or interleaved WAV samples")
|
||||
return samples
|
||||
|
||||
|
||||
def channel_or_silence(field: np.ndarray, channel: int) -> np.ndarray:
|
||||
if channel < field.shape[1]:
|
||||
return field[:, channel].copy()
|
||||
return np.zeros(field.shape[0], dtype=np.float32)
|
||||
|
||||
|
||||
def mix_channels(field: np.ndarray, channels: list[int]) -> np.ndarray:
|
||||
if not channels:
|
||||
return np.zeros(field.shape[0], dtype=np.float32)
|
||||
return np.mean(field[:, channels], axis=1, dtype=np.float32)
|
||||
|
||||
|
||||
def make_ambient_stem(witness_mix: np.ndarray, *anchors: np.ndarray) -> np.ndarray:
|
||||
ambient = witness_mix.astype(np.float32, copy=True)
|
||||
for anchor in anchors:
|
||||
ambient -= 0.2 * np.asarray(anchor, dtype=np.float32)
|
||||
return ambient
|
||||
|
||||
|
||||
def make_transient_stem(witness_mix: np.ndarray, events_doc: dict[str, Any], frame_count: int) -> np.ndarray:
|
||||
stem = np.zeros(frame_count, dtype=np.float32)
|
||||
events = events_doc.get("events", [])
|
||||
fade = 128
|
||||
for event in events:
|
||||
start = max(0, int(event.get("start_sample", event.get("startSample", 0))) - 256)
|
||||
duration = int(event.get("duration_samples", event.get("durationSamples", 1024)))
|
||||
end = min(frame_count, start + max(duration + 512, 1))
|
||||
if end <= start:
|
||||
continue
|
||||
segment = witness_mix[start:end].copy()
|
||||
fade_len = min(fade, segment.shape[0] // 2)
|
||||
if fade_len > 0:
|
||||
ramp = np.linspace(0.0, 1.0, fade_len, endpoint=False, dtype=np.float32)
|
||||
segment[:fade_len] *= ramp
|
||||
segment[-fade_len:] *= ramp[::-1]
|
||||
stem[start:end] += segment
|
||||
return stem
|
||||
|
||||
|
||||
def load_optional_program_audio(path: Path, sample_rate: int, frame_count: int) -> np.ndarray:
|
||||
if not path.exists():
|
||||
return np.zeros((frame_count, 2), dtype=np.float32)
|
||||
source_rate, samples = read_wav_float(path)
|
||||
samples = ensure_2d(samples)
|
||||
if source_rate != sample_rate:
|
||||
divisor = math.gcd(source_rate, sample_rate)
|
||||
samples = resample_poly(samples, sample_rate // divisor, source_rate // divisor, axis=0).astype(np.float32)
|
||||
if samples.shape[0] < frame_count:
|
||||
pad = np.zeros((frame_count - samples.shape[0], samples.shape[1]), dtype=np.float32)
|
||||
samples = np.vstack([samples, pad])
|
||||
return samples[:frame_count]
|
||||
|
||||
|
||||
def load_co_streamer_surface(
|
||||
path: Path,
|
||||
sample_rate: int,
|
||||
frame_count: int,
|
||||
*,
|
||||
channel_fallback: np.ndarray,
|
||||
placeholder_status: str,
|
||||
synced_status: str,
|
||||
low_signal_status: str | None = None,
|
||||
min_rms: float = 0.0,
|
||||
) -> tuple[np.ndarray, str]:
|
||||
if not path.exists():
|
||||
return channel_fallback, placeholder_status
|
||||
loaded = load_optional_program_audio(path, sample_rate, frame_count)
|
||||
if np.asarray(channel_fallback).ndim == 1 and loaded.ndim == 2:
|
||||
loaded = np.mean(loaded, axis=1, dtype=np.float32)
|
||||
if min_rms > 0.0 and rms(loaded) < float(min_rms):
|
||||
return loaded, low_signal_status or placeholder_status
|
||||
return loaded, synced_status
|
||||
|
||||
|
||||
def rms(samples: np.ndarray) -> float:
|
||||
samples = np.asarray(samples, dtype=np.float32)
|
||||
return float(np.sqrt(np.mean(samples * samples))) if samples.size else 0.0
|
||||
|
||||
|
||||
def limit_peak(samples: np.ndarray, target: float = 0.98) -> np.ndarray:
|
||||
peak = float(np.max(np.abs(samples))) if samples.size else 0.0
|
||||
if peak <= target or peak <= 1e-9:
|
||||
return samples
|
||||
return samples * (target / peak)
|
||||
|
||||
|
||||
def mute_input(client: Any, input_name: str) -> None:
|
||||
try:
|
||||
client.set_input_mute(input_name, True)
|
||||
except Exception:
|
||||
return
|
||||
|
||||
|
||||
def scene_item_ids(client: Any, scene: str) -> dict[str, int]:
|
||||
try:
|
||||
items = client.get_scene_item_list(scene).scene_items
|
||||
except Exception:
|
||||
return {}
|
||||
return {str(item["sourceName"]): int(item["sceneItemId"]) for item in items}
|
||||
|
||||
|
||||
def disable_scene_item(client: Any, scene: str, scene_items: dict[str, int], source_name: str) -> None:
|
||||
item_id = scene_items.get(source_name)
|
||||
if item_id is None:
|
||||
return
|
||||
try:
|
||||
client.set_scene_item_enabled(scene, item_id, False)
|
||||
except Exception:
|
||||
return
|
||||
|
||||
|
||||
def enable_scene_item(client: Any, scene: str, scene_items: dict[str, int], source_name: str) -> None:
|
||||
item_id = scene_items.get(source_name)
|
||||
if item_id is None:
|
||||
return
|
||||
try:
|
||||
client.set_scene_item_enabled(scene, item_id, True)
|
||||
except Exception:
|
||||
return
|
||||
|
||||
|
||||
def restart_media_if_possible(client: Any, input_name: str) -> None:
|
||||
try:
|
||||
client.trigger_media_input_action(input_name, "OBS_WEBSOCKET_MEDIA_INPUT_ACTION_RESTART")
|
||||
except Exception:
|
||||
return
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
|
@ -1,96 +0,0 @@
|
|||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from localcast.sensor_fusion import (
|
||||
BoardObservation,
|
||||
BoardSpec,
|
||||
CameraIntrinsics,
|
||||
camera_models_to_config,
|
||||
solve_common_space_from_fixed_board,
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Solve camera extrinsics into one fixed-board world frame.")
|
||||
parser.add_argument("--input", required=True, help="JSON with board, intrinsics, and observations.")
|
||||
parser.add_argument("--output", default=str(ROOT / "config" / "sensor-fusion.json"))
|
||||
parser.add_argument("--max-reprojection-error-px", type=float, default=2.5)
|
||||
args = parser.parse_args()
|
||||
|
||||
data = json.loads(Path(args.input).read_text(encoding="utf-8"))
|
||||
board_data = data["board"]
|
||||
board = BoardSpec(
|
||||
squares_x=int(board_data["squares_x"]),
|
||||
squares_y=int(board_data["squares_y"]),
|
||||
square_length_m=float(board_data["square_length"]),
|
||||
)
|
||||
intrinsics = [
|
||||
CameraIntrinsics(
|
||||
sensor_id=item["id"],
|
||||
camera_matrix=np.asarray(item["camera_matrix"], dtype=np.float64),
|
||||
dist_coeffs=np.asarray(item.get("dist_coeffs", []), dtype=np.float64),
|
||||
width=int(item["width"]),
|
||||
height=int(item["height"]),
|
||||
role=item.get("role", "tracking"),
|
||||
latency_ms=float(item.get("latency_ms", 0.0)),
|
||||
)
|
||||
for item in data.get("intrinsics", [])
|
||||
]
|
||||
observations = [
|
||||
BoardObservation(
|
||||
sensor_id=item["sensor_id"],
|
||||
timestamp_ns=int(item.get("timestamp_ns", 0)),
|
||||
corner_ids=np.asarray(item["corner_ids"], dtype=np.int32),
|
||||
image_points=np.asarray(item["image_points"], dtype=np.float64),
|
||||
confidence=float(item.get("confidence", 1.0)),
|
||||
)
|
||||
for item in data.get("observations", [])
|
||||
]
|
||||
cameras, solves = solve_common_space_from_fixed_board(
|
||||
intrinsics,
|
||||
board,
|
||||
observations,
|
||||
max_reprojection_error_px=args.max_reprojection_error_px,
|
||||
)
|
||||
output = {
|
||||
"fusion": data.get(
|
||||
"fusion",
|
||||
{
|
||||
"max_pair_dt_ns": 25000000,
|
||||
"max_reprojection_error_px": 4.0,
|
||||
"min_confidence": 0.1,
|
||||
"cache_ttl_ns": 500000000,
|
||||
},
|
||||
),
|
||||
"render_bridge": data.get("render_bridge", {}),
|
||||
"cameras": camera_models_to_config(cameras.values()),
|
||||
"calibration_report": {
|
||||
"world_frame": "fixed ChArUco board coordinates",
|
||||
"solves": [
|
||||
{
|
||||
"sensor_id": solve.sensor_id,
|
||||
"timestamp_ns": solve.timestamp_ns,
|
||||
"corner_count": solve.corner_count,
|
||||
"reprojection_error_px": solve.reprojection_error_px,
|
||||
}
|
||||
for solve in solves
|
||||
],
|
||||
},
|
||||
}
|
||||
out = Path(args.output)
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps(output, indent=2), encoding="utf-8")
|
||||
print(out)
|
||||
print(json.dumps(output["calibration_report"], indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -1,68 +0,0 @@
|
|||
import argparse
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
import cv2
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from localcast.sensor_fusion import (
|
||||
PointCloud,
|
||||
load_fusion_config,
|
||||
match_surface_features,
|
||||
orb_surface_observations,
|
||||
triangulate_surface_tracks,
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Match surface features between two calibrated views and write a PLY.")
|
||||
parser.add_argument("--config", default=str(ROOT / "config" / "sensor-fusion.json"))
|
||||
parser.add_argument("--left-id", required=True)
|
||||
parser.add_argument("--right-id", required=True)
|
||||
parser.add_argument("--left-image", required=True)
|
||||
parser.add_argument("--right-image", required=True)
|
||||
parser.add_argument("--output", required=True)
|
||||
parser.add_argument("--max-features", type=int, default=2000)
|
||||
parser.add_argument("--max-descriptor-distance", type=float, default=44.0)
|
||||
parser.add_argument("--max-reprojection-error-px", type=float, default=4.0)
|
||||
args = parser.parse_args()
|
||||
|
||||
rig = load_fusion_config(Path(args.config))
|
||||
left = cv2.imread(args.left_image)
|
||||
right = cv2.imread(args.right_image)
|
||||
if left is None:
|
||||
raise SystemExit(f"Could not read {args.left_image}")
|
||||
if right is None:
|
||||
raise SystemExit(f"Could not read {args.right_image}")
|
||||
timestamp_ns = time.monotonic_ns()
|
||||
left_features = orb_surface_observations(args.left_id, left, timestamp_ns, max_features=args.max_features)
|
||||
right_features = orb_surface_observations(args.right_id, right, timestamp_ns, max_features=args.max_features)
|
||||
tracks = match_surface_features(
|
||||
left_features,
|
||||
right_features,
|
||||
max_descriptor_distance=args.max_descriptor_distance,
|
||||
max_dt_ns=25_000_000,
|
||||
)
|
||||
points = triangulate_surface_tracks(
|
||||
tracks,
|
||||
rig.cameras,
|
||||
max_reprojection_error_px=args.max_reprojection_error_px,
|
||||
)
|
||||
PointCloud(points).write_ply(Path(args.output))
|
||||
print(
|
||||
{
|
||||
"left_features": len(left_features),
|
||||
"right_features": len(right_features),
|
||||
"tracks": len(tracks),
|
||||
"points": len(points),
|
||||
"output": args.output,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Loading…
Reference in a new issue