diff --git a/ci/tests/test_dataforge_imports.py b/ci/tests/test_dataforge_imports.py new file mode 100644 index 000000000..41857c17a --- /dev/null +++ b/ci/tests/test_dataforge_imports.py @@ -0,0 +1,57 @@ +"""dataforge layering: a dataset imports only its own modules and the shared ones; shared modules import no dataset. + +The review stack lands shared modules first and then one dataset per PR, so every +prefix of it must import cleanly; the datasets are therefore read off the files +present, never listed here. A dataset owns ``datasets/.py`` and every +``datasets/_*.py``; ``datasets/base.py`` is shared, and ``datasets/__init__.py`` +is the registry that imports them all. +""" + +import ast +from pathlib import Path + +REPO_ROOT: Path = Path(__file__).resolve().parents[2] +DATAFORGE_DIR: Path = REPO_ROOT / "packages" / "dataforge" / "dataforge" +DATASETS_DIR: Path = DATAFORGE_DIR / "datasets" +DATASETS_PACKAGE: str = "dataforge.datasets" +SHARED_DATASET_MODULES: frozenset[str] = frozenset({"base"}) + + +def _imported_dataset_modules(path: Path) -> set[str]: + """Stems of every dataforge.datasets. the file imports, at any depth (lazy imports included).""" + stems: set[str] = set() + for node in ast.walk(ast.parse(path.read_text(), filename=str(path))): + if isinstance(node, ast.Import): + modules = [alias.name for alias in node.names] + elif isinstance(node, ast.ImportFrom) and node.module is not None and node.level == 0: + modules = [node.module] if node.module != DATASETS_PACKAGE else [f"{DATASETS_PACKAGE}.{alias.name}" for alias in node.names] + else: + continue + stems.update(module.split(".")[2] for module in modules if module.startswith(f"{DATASETS_PACKAGE}.")) + return stems + + +def _dataset_owner(stem: str, datasets: set[str]) -> str: + return next(dataset for dataset in datasets if stem == dataset or stem.startswith(f"{dataset}_")) + + +def test_datasets_import_no_other_dataset() -> None: + stems: set[str] = {path.stem for path in DATASETS_DIR.glob("*.py")} - {"__init__"} - SHARED_DATASET_MODULES + datasets: set[str] = {stem for stem in stems if not any(stem.startswith(f"{other}_") for other in stems if other != stem)} + assert datasets, f"no dataset modules under {DATASETS_DIR}" + problems: list[str] = [] + for stem in sorted(stems): + owner: str = _dataset_owner(stem, datasets) + for imported in sorted(_imported_dataset_modules(DATASETS_DIR / f"{stem}.py") - SHARED_DATASET_MODULES): + if imported not in stems or _dataset_owner(imported, datasets) != owner: + problems.append(f"datasets/{stem}.py ({owner}) imports dataforge.datasets.{imported}") + assert not problems, "a dataset imports another dataset's module; move the shared code into dataforge/:\n" + "\n".join(problems) + + +def test_shared_modules_import_no_dataset() -> None: + problems: list[str] = [ + f"{path.name} imports dataforge.datasets.{imported}" + for path in sorted(DATAFORGE_DIR.glob("*.py")) + for imported in sorted(_imported_dataset_modules(path) - SHARED_DATASET_MODULES) + ] + assert not problems, "a shared dataforge module imports a dataset:\n" + "\n".join(problems) diff --git a/packages/dataforge/README.md b/packages/dataforge/README.md index 9d176975e..d830bb7dc 100644 --- a/packages/dataforge/README.md +++ b/packages/dataforge/README.md @@ -193,12 +193,13 @@ imu-left, 129 mm away and rotated. Aria Gen1 records its cameras sideways, so our frames and every pixel coordinate on them — the pinholes and the control-point detections alike — are turned **90° clockwise** from LaMAria's published files, and the calibration is turned with them -([`rotate_camera_calib_cw90deg`](https://facebookresearch.github.io/projectaria_tools/docs/data_utilities/core_code_snippets/calibration), -which swaps the image size, moves the principal point to `(h - 1 - cy, cx)` and +(simplecv's `fisheye624.rotate_cw90`, projectaria-tools' +[`rotate_camera_calib_cw90deg`](https://facebookresearch.github.io/projectaria_tools/docs/data_utilities/core_code_snippets/calibration) +repeated operation for operation, which swaps the image size, moves the principal point to `(h - 1 - cy, cx)` and turns `device_T_cam` about the optical axis), so the scene is upright and the calibration still describes it. The capture property `image_rotation_cw_deg` records the turn; the pGT is *not* turned, because it poses the published, -unrotated camera. Everything comes out of the VRS device calibration via projectaria-tools: the +unrotated camera. Everything comes out of the VRS device calibration (its `calib_json` tag, read by `dataforge.aria`): the published JSON has no RGB camera and no imu-left, and is used to cross-check the transform chain rather than to build it. @@ -289,7 +290,7 @@ are cleaned beneath its `work/` directory, including on failure. Consumers can leave `hand_mesh` unregistered to avoid its storage cost; a follow-up can coarsen its clock. HOT3D BOP models are renumbered across releases, so mesh IDs resolve by name. -Download discards `KHR_texture_transform` UV transforms so Rerun 0.37 can load +Download discards `KHR_texture_transform` UV transforms so Rerun 0.38.1 can load the GLBs, then deletes the raw GLBs after the stripped assets are saved. The keyboard golden requires `in_ego_fov_fraction < 0.05`; it is not always behind both cameras. Source poses remain unchanged. @@ -313,7 +314,7 @@ Each recording records the Hub commit it was built from as | variable | default | purpose | | --- | --- | --- | | `DATAFORGE_OUTPUT_ROOT` | `packages/dataforge/data/dataforge/rrd` | where rrds, blueprints and sidecars go; set it for convert **and** register | -| `DATAFORGE_RAW_ROOT` | `packages/dataforge/data/raw` | where raw corpora are fetched to | +| `DATAFORGE_RAW_ROOT` | `packages/dataforge/data/raw` | where raw corpora are fetched to; the exoego datasets default `--root` to `$DATAFORGE_RAW_ROOT/` (both HOT3D devices share `hot3d`), with source subfolders such as UmeTrack's `raw_data/` inside | | `DATAFORGE_FFMPEG` | the env's ffmpeg | an ffmpeg with hardware encoding, used both to re-encode B-frame sources (most phone HEVC) and to encode image sequences. Without `av1_nvenc` the encoder refuses to start rather than falling back to a software encode that looks like a hang. Check yours with `ffmpeg -hide_banner -encoders \| grep av1_nvenc` | Paths in `--root`/`--sequence` and the defaults above are relative to @@ -334,8 +335,11 @@ members out of a plain zip or an Info-ZIP volume set), `basalt.py` (basalt's `calibration.json` as one validated `CalibratedCamera` per camera: model, extrinsics, resolution, and the follow frame derived from them), `transports.py` (`local_verify`, `hf_fetch`, and the resuming `http_fetch` plus -its Apache index parser), and `aria.py` (the Aria Gen1 VRS and LaMAria -ground-truth readers). +its Apache index parser), `vrs.py` (one VRS header scan, then the JPEG, +H.265 and IMU readers seek to their records), and `aria.py` (the Aria device +calibration, frame and IMU readers and the full-lens projection that hot3d, the +Gen2 pilot and LaMAria share; LaMAria's rig and ground-truth readers are +`datasets/lamaria_source.py`). Two of those carry their weight for datasets that do not ship video. `encode_frames_to_mp4` pipes PNG or raw frames straight into ffmpeg's stdin, so @@ -383,19 +387,6 @@ layer is written with `send_properties=False` and carries only its own `property::*` beside its data, never a properties-only layer. Layers share nothing but the recording id, which is what stacks them onto one segment. -### The layer rule - -Every dataset follows it; `lamaria` is the reference implementation. **base** is a -faithful conversion of the raw source and the only layer that needs it: it skips on -its own rrd, and once it is published the bulk source is deleted, leaving only the -small sidecars (calibration, ground truth) on disk. A **derived** layer reads the -base rrd plus those sidecars — never the raw source — skips on its own rrd and -rebuilds under `--force`, so regenerating one across a corpus is `rm /*.rrd`, -a convert, and a `register --replace`. Capture properties live in base; a derived -layer is written with `send_properties=False` and carries only its own -`property::*` beside its data, never a properties-only layer. Layers share -nothing but the recording id, which is what stacks them onto one segment. - ## Blueprints Every dataset provides two (abstract on `DataforgeDataset`; missing one fails @@ -435,3 +426,30 @@ Conventions this package follows — beartype under `PIXI_DEV_MODE`, thin `tools shims, jaxtyping annotations, `pixi run -e dataforge-dev {lint,typecheck,deadcode,tests}` — are the monorepo ones in the root `AGENTS.md`. The logging schema is `packages/simplecv/docs/exoego_schema.md`. + +## Conventions for exoego ports + +Use the [dataset documentation template](docs/dataset-doc-template.md) for every +port. Apply these rules: + +- Present joints retain shipped confidence; if none is shipped, use 1.0. Missing + joints and uncovered COCO slots use NaN positions and confidence 0.0. +- `video_time` is the true timeline; `frame_index` is the second timeline. Keep + each stream's native rate and record its clock origin in + `property:capture:clock_source`. +- Write `/coco133_uv` only from shipped 2D measurements. +- Derived 2D goes to `/coco133_uv_projected` in the `projections` layer: + `coco133_xyz` through the camera's own lens model, with + `property:projections:derived_from` and `property:projections:camera_model`. +- Shared output helpers live in `dataforge.hands`, `dataforge.objects`, and + `dataforge.meshes`; skinning and source format adapters stay dataset-specific. +- Conversion and registration append typed timing records under `timing/`. + Converters time work with `self.timer.stage("fetch")` + and `self.timer.stage("write:")`; nested stages overlap and must not be summed. + Report the base `video_time` span in seconds through `self.timer.capture_s`. + Read either JSONL file with `dataforge.timing.load_records(path, ConvertRecord)` + or `load_records(path, RegisterRecord)`. +- Register review subsets with `--catalog-name -sample --sequences + `. File identities stay unchanged. +- Compare layer data with `python tools/dev/compare_layers.py ` + in the dataforge environment. Float tolerance defaults to 1e-6. diff --git a/packages/dataforge/dataforge/actions.py b/packages/dataforge/dataforge/actions.py new file mode 100644 index 000000000..fe4689785 --- /dev/null +++ b/packages/dataforge/dataforge/actions.py @@ -0,0 +1,55 @@ +"""Shipped action annotations as half-open intervals, logged as active-label text tracks. + +At every interval boundary the track holds all labels active there, joined by +newlines; an empty document clears the labels whose intervals ended. +""" + +from dataclasses import dataclass + +import numpy as np +import rerun as rr +from jaxtyping import Int64 +from numpy import ndarray + +from dataforge import schema +from dataforge.logging_toolkit import frame_index_column, time_column + + +@dataclass(frozen=True, slots=True, order=True) +class Segment: + """Half-open action interval on the dataset's annotation frame clock.""" + + start: int + """First active annotation frame.""" + end: int + """First inactive annotation frame.""" + text: str + """Label as shipped.""" + + def __post_init__(self) -> None: + if self.start < 0 or self.end < self.start: + raise ValueError("invalid action interval") + + +def active_labels(segments: list[Segment], *, stop: int | None = None) -> tuple[Int64[ndarray, "k"], list[str]]: + """Frame 0 and every segment boundary below ``stop``, each with the labels active there in segment order.""" + boundaries: list[int] = sorted({0, *(boundary for segment in segments for boundary in (segment.start, segment.end))}) + if stop is not None: + boundaries = [boundary for boundary in boundaries if boundary < stop] + ordered: list[Segment] = sorted(segments) + return ( + np.array(boundaries, dtype=np.int64), + ["\n".join(segment.text for segment in ordered if segment.start <= boundary < segment.end) for boundary in boundaries], + ) + + +def log_actions( + recording: rr.RecordingStream, level: str, *, times_ns: Int64[ndarray, "k"], frame_indices: Int64[ndarray, "k"], texts: list[str] +) -> None: + """One columnar text document per boundary at ``schema.actions_path(level)``.""" + rr.send_columns( + schema.actions_path(level), + indexes=[time_column(times_ns), frame_index_column(frame_indices)], + columns=rr.TextDocument.columns(text=texts), + recording=recording, + ) diff --git a/packages/dataforge/dataforge/apis/compare_layers.py b/packages/dataforge/dataforge/apis/compare_layers.py new file mode 100644 index 000000000..22c2ad2f0 --- /dev/null +++ b/packages/dataforge/dataforge/apis/compare_layers.py @@ -0,0 +1,156 @@ +"""Compare RRD data by entity, component and source clocks, independent of chunks. + +Generated row IDs, log_time/log_tick, store IDs and blueprints are excluded. +The build-time wall clock (/__properties, RecordingInfo:start_time) is also +ignored by default; --ignore accepts extra entity/component pairs. +All data components (including properties and video bytes) are compared. Float +values use absolute tolerance 1e-6, with NaNs equal. Row counts remain exact. +""" + +from collections import defaultdict +from pathlib import Path +from typing import Annotated, NamedTuple, TypeAlias + +import numpy as np +import pyarrow as pa +import pyarrow.compute as pc +import rerun.chunk as rrc +import tyro +from jaxtyping import Float +from numpy import ndarray + +ColumnKey: TypeAlias = tuple[str, str, tuple[str, ...]] + + +class Comparison(NamedTuple): + """Outcome of one layer comparison.""" + + tracks: int + """Component tracks read from ``a`` after the ignores.""" + mismatches: list[str] + """Every track/column mismatch; empty when the layers are equal.""" + + +def component_rows(path: Path) -> dict[ColumnKey, pa.Table]: + """Read per-component rows, retaining empty cells and removing absent cells.""" + parts: dict[ColumnKey, list[pa.Table]] = defaultdict(list) + reader: rrc.RrdReader = rrc.RrdReader(path) + if len(reader.recordings()) != 1: + raise ValueError(f"{path}: expected one data recording") + for chunk in reader.stream(): + batch: pa.RecordBatch = chunk.to_record_batch() + timelines: tuple[str, ...] = tuple(sorted(name for name in chunk.timeline_names if name not in {"log_time", "log_tick"})) + for field in batch.schema: + if (field.metadata or {}).get(b"rerun:kind") != b"data": + continue + key: ColumnKey = (str(chunk.entity_path), field.name, timelines) + table: pa.Table = pa.Table.from_batches([batch.select([*timelines, field.name])]).replace_schema_metadata(None) + parts[key].append(table.filter(table[field.name].is_valid())) + result: dict[ColumnKey, pa.Table] = {} + for key, tables in parts.items(): + combined: pa.Table = pa.concat_tables(tables) + result[key] = combined.sort_by([(name, "ascending") for name in key[2]]) if key[2] else combined + return result + + +def first_mismatch(left: pa.Array, right: pa.Array, *, atol: float) -> str | None: + """Compare Arrow nesting, nulls and exact non-floats without expanding video blobs.""" + if left.type != right.type: + return f"types differ: {left.type} != {right.type}" + if len(left) != len(right): + return f"length differs: {len(left)} != {len(right)}" + if not left.is_null().equals(right.is_null()): + return "null masks differ" + if pa.types.is_list(left.type) or pa.types.is_large_list(left.type) or pa.types.is_fixed_size_list(left.type): + if not pc.call_function("list_value_length", [left]).equals(pc.call_function("list_value_length", [right])): + return "cell lengths differ" + return first_mismatch(pc.call_function("list_flatten", [left]), pc.call_function("list_flatten", [right]), atol=atol) + if pa.types.is_struct(left.type): + for index in range(left.type.num_fields): + mismatch: str | None = first_mismatch(left.field(index), right.field(index), atol=atol) + if mismatch is not None: + return mismatch + elif pa.types.is_floating(left.type): + if not np.allclose(left.to_numpy(zero_copy_only=False), right.to_numpy(zero_copy_only=False), rtol=0.0, atol=atol, equal_nan=True): + return "values differ" + elif not left.equals(right): + return "values differ" + return None + + +def max_float_difference(left: pa.Array, right: pa.Array) -> float | None: + """Return the maximum comparable float delta, or None for non-float data.""" + if left.type != right.type or len(left) != len(right): + return None + if pa.types.is_list(left.type) or pa.types.is_large_list(left.type) or pa.types.is_fixed_size_list(left.type): + if not pc.call_function("list_value_length", [left]).equals(pc.call_function("list_value_length", [right])): + return None + return max_float_difference(pc.call_function("list_flatten", [left]), pc.call_function("list_flatten", [right])) + if pa.types.is_struct(left.type): + differences: list[float] = [ + value for index in range(left.type.num_fields) + if (value := max_float_difference(left.field(index), right.field(index))) is not None + ] + return max(differences, default=None) + if pa.types.is_floating(left.type): + with np.errstate(invalid="ignore"): + deltas: Float[ndarray, "n"] = np.abs(left.to_numpy(zero_copy_only=False) - right.to_numpy(zero_copy_only=False)) + return float(np.nanmax(deltas)) if np.any(~np.isnan(deltas)) else None + return None + + +def compare_layers(a: Path, b: Path, *, atol: float = 1e-6, ignore: list[tuple[str, str]] | None = None) -> Comparison: + """Return the compared track count and every track/column mismatch, without printing. + + Row indices are zero-based in source-clock order. Float deltas cover all + comparable values in the column; n/a means no aligned float values exist. + """ + ignored: set[tuple[str, str]] = {("/__properties", "RecordingInfo:start_time"), *(ignore or [])} + left: dict[ColumnKey, pa.Table] = {key: table for key, table in component_rows(a).items() if key[:2] not in ignored} + right: dict[ColumnKey, pa.Table] = {key: table for key, table in component_rows(b).items() if key[:2] not in ignored} + mismatches: list[str] = [] + for key in sorted(left.keys() - right.keys()): + mismatches.append(f"{key}: missing in b") + for key in sorted(right.keys() - left.keys()): + mismatches.append(f"{key}: extra in b") + for key in sorted(left.keys() & right.keys()): + table: pa.Table = left[key] + other: pa.Table = right[key] + if table.num_rows != other.num_rows: + mismatches.append(f"{key}: row counts differ: {table.num_rows} != {other.num_rows}") + count: int = min(table.num_rows, other.num_rows) + for name in table.column_names: + first: pa.Array = table[name].combine_chunks().slice(0, count) + second: pa.Array = other[name].combine_chunks().slice(0, count) + tolerance: float = atol if name == key[1] else 0.0 + if first_mismatch(first, second, atol=tolerance) is not None: + # Search prefixes to locate the first differing row without expanding blobs. + low: int = 0 + high: int = max(0, count - 1) + while low < high: + middle: int = (low + high) // 2 + if first_mismatch(first.slice(0, middle + 1), second.slice(0, middle + 1), atol=tolerance) is None: + low = middle + 1 + else: + high = middle + times_a: dict[str, object] = {clock: table[clock][low].as_py() for clock in key[2]} if count else {} + times_b: dict[str, object] = {clock: other[clock][low].as_py() for clock in key[2]} if count else {} + delta: float | None = max_float_difference(first, second) + mismatches.append( + f"{key}: {name} differs; first differing row {low}, time a={times_a}, b={times_b}; " + f"max abs float difference={delta if delta is not None else 'n/a'}" + ) + return Comparison(len(left), mismatches) + + +def main( + a: Annotated[Path, tyro.conf.Positional], b: Annotated[Path, tyro.conf.Positional], *, + atol: float = 1e-6, ignore: list[tuple[str, str]] | None = None, +) -> None: + """Compare two layer RRDs; --ignore takes extra entity/component pairs.""" + comparison: Comparison = compare_layers(a, b, atol=atol, ignore=ignore) + if comparison.mismatches: + for mismatch in comparison.mismatches: + print(mismatch) + raise SystemExit(f"{len(comparison.mismatches)} mismatch(es)") + print(f"equal: {a} == {b} ({comparison.tracks} component tracks, atol={atol})") diff --git a/packages/dataforge/dataforge/apis/convert.py b/packages/dataforge/dataforge/apis/convert.py index c58729846..5bc7264f5 100644 --- a/packages/dataforge/dataforge/apis/convert.py +++ b/packages/dataforge/dataforge/apis/convert.py @@ -2,14 +2,20 @@ from __future__ import annotations +import os +import subprocess from dataclasses import dataclass, field from pathlib import Path +from socket import gethostname from beartype.roar import BeartypeException +from dataforge import paths from dataforge.datasets import AnnotatedDatasetUnion, RobocapConfig from dataforge.datasets.base import DataforgeDataset, DataforgeDatasetConfig from dataforge.identity import SequenceIdentity +from dataforge.timing import ConvertRecord, SequenceTimer, append_record +from dataforge.writing import CONVERT_SCHEMA_VERSION @dataclass @@ -38,6 +44,63 @@ def select(discovered: list[tuple[SequenceIdentity, object]], sequence: str | No return matches +def converter_version() -> str: + """Identify the conversion schema and the checkout containing this source.""" + try: + commit: str = subprocess.check_output( + ["git", "-C", str(Path(__file__).resolve().parents[2]), "rev-parse", "--short=12", "HEAD"], + text=True, stderr=subprocess.DEVNULL, + ).strip() + except (subprocess.SubprocessError, OSError): + return CONVERT_SCHEMA_VERSION + return f"{CONVERT_SCHEMA_VERSION}+{commit}" + + +def file_stamps(targets: dict[str, Path]) -> dict[str, tuple[int, int]]: + """``(mtime_ns, size)`` of each existing layer file; a changed stamp means this run wrote it.""" + stamps: dict[str, tuple[int, int]] = {} + for layer, path in targets.items(): + if path.is_file(): + stat: os.stat_result = path.stat() + stamps[layer] = (stat.st_mtime_ns, stat.st_size) + return stamps + + +def convert_one( + dataset: DataforgeDataset, identity: SequenceIdentity, source: object, *, force: bool, version: str +) -> ConvertRecord: + """Convert one sequence and return its timing record, including an individual failure.""" + dataset.timer = SequenceTimer() + timer: SequenceTimer = dataset.timer + targets: dict[str, Path] = dataset.targets(identity) + before: dict[str, tuple[int, int]] = file_stamps(targets) + failure: str | None = None + try: + target: Path = dataset.convert(identity, source, force=force) + elapsed: float = timer.total_s + if not target.is_file(): + raise RuntimeError(f"convert produced no recording for {identity.sequence_key}") + except BeartypeException: + raise + except Exception as error: + elapsed = timer.total_s + failure = f"{type(error).__name__}: {error}" + written: dict[str, int] = {layer: stamp[1] for layer, stamp in file_stamps(targets).items() if before.get(layer) != stamp} + return ConvertRecord( + dataset=dataset.config.name, + recording_id=identity.recording_id, + converter_version=version, + started_at=timer.started_at, + stage_s=timer.stage_s, + total_s=elapsed, + capture_s=timer.capture_s, + layer_bytes=written, + host=gethostname(), + skipped=not written and failure is None, + error=failure, + ) + + def main(config: Config) -> None: """Convert every selected sequence serially, surviving individual failures. @@ -51,15 +114,13 @@ def main(config: Config) -> None: selected: list[tuple[SequenceIdentity, object]] = select(dataset.discover(), config.sequence) print(f"converting {len(selected)} sequence(s)") failed: list[str] = [] + source_version: str = converter_version() + root: Path = paths.output_root() for identity, source in selected: - try: - target: Path = dataset.convert(identity, source, force=config.force) - if not target.is_file(): - raise RuntimeError(f"convert produced no recording for {identity.sequence_key}") - except BeartypeException: - raise - except Exception as error: - print(f"FAILED {identity.sequence_key}: {type(error).__name__}: {error}") + record: ConvertRecord = convert_one(dataset, identity, source, force=config.force, version=source_version) + append_record(root / "timing/convert.jsonl", record) + if record.error is not None: + print(f"FAILED {identity.sequence_key}: {record.error}") failed.append(identity.sequence_key) if failed: raise SystemExit(f"{len(failed)} of {len(selected)} sequence(s) failed: {', '.join(failed)}") diff --git a/packages/dataforge/dataforge/apis/download.py b/packages/dataforge/dataforge/apis/download.py index 40c2293c8..0aeace514 100644 --- a/packages/dataforge/dataforge/apis/download.py +++ b/packages/dataforge/dataforge/apis/download.py @@ -4,8 +4,10 @@ from dataclasses import dataclass, field +from serde.json import to_json + from dataforge.datasets import AnnotatedDatasetUnion, RobocapConfig -from dataforge.datasets.base import DataforgeDatasetConfig +from dataforge.datasets.base import DataforgeDataset, DataforgeDatasetConfig @dataclass @@ -14,9 +16,16 @@ class Config: dataset: AnnotatedDatasetUnion = field(default_factory=RobocapConfig) """Dataset to download; the raw-tree location lives on the dataset config.""" + list_remote: bool = False + """Print the source's sequences as JSON lines (key, size_bytes, files) instead of downloading.""" def main(config: Config) -> None: """Run the dataset's download verb.""" dataset_config: DataforgeDatasetConfig = config.dataset - dataset_config.setup().download() + dataset: DataforgeDataset = dataset_config.setup() + if config.list_remote: + for sequence in dataset.remote_sequences(): + print(to_json(sequence)) + return + dataset.download() diff --git a/packages/dataforge/dataforge/apis/register.py b/packages/dataforge/dataforge/apis/register.py index a11e756f1..c289ceac5 100644 --- a/packages/dataforge/dataforge/apis/register.py +++ b/packages/dataforge/dataforge/apis/register.py @@ -11,6 +11,8 @@ from dataclasses import dataclass, field from datetime import datetime from pathlib import Path +from socket import gethostname +from time import perf_counter from typing import Any from urllib.parse import unquote, urlparse @@ -19,6 +21,7 @@ from dataforge import paths, schema, writing from dataforge.datasets import AnnotatedDatasetUnion, RobocapConfig from dataforge.datasets.base import DataforgeDataset, DataforgeDatasetConfig +from dataforge.timing import RegisterRecord, SequenceTimer, append_record @dataclass @@ -29,6 +32,10 @@ class Config: """Dataset whose rrds get registered; its registry key is the catalog dataset name.""" catalog_url: str = "rerun+http://127.0.0.1:51235" """gRPC URL of a locally running ``rerun server`` catalog.""" + catalog_name: str | None = None + """Override the catalog name without changing file identities.""" + sequences: tuple[str, ...] | None = None + """Register only these recording IDs.""" replace: bool = False """Re-register a layer the catalog already holds for a segment, instead of skipping it. @@ -42,22 +49,53 @@ class Config: def main(config: Config) -> None: """Create the dataset if needed, register every layer's rrds (idempotent), and republish its blueprints.""" + timer: SequenceTimer = SequenceTimer() dataset_config: DataforgeDatasetConfig = config.dataset dataset: DataforgeDataset = dataset_config.setup() name: str = dataset_config.name output_root: Path = paths.output_root() paths_by_layer: dict[str, list[Path]] = {layer: sorted((output_root / layer).glob(f"{name}__*.rrd")) for layer in dataset.layers} + if config.sequences is not None: + missing: set[str] = set(config.sequences) - {path.stem for path in paths_by_layer[paths.BASE_LAYER]} + if missing: + raise ValueError(f"Unknown recording IDs: {sorted(missing)}") + paths_by_layer = {layer: [path for path in files if path.stem in config.sequences] for layer, files in paths_by_layer.items()} if not paths_by_layer[paths.BASE_LAYER]: raise FileNotFoundError(f"no {paths.BASE_LAYER}-layer rrds for {name} under {output_root / paths.BASE_LAYER}") + catalog_name: str = config.catalog_name or dataset_config.name client: CatalogClient = CatalogClient(config.catalog_url) - entry: DatasetEntry = client.create_dataset(name, exist_ok=True) + entry: DatasetEntry = client.create_dataset(catalog_name, exist_ok=True) on_duplicate: OnDuplicateSegmentLayer = OnDuplicateSegmentLayer.REPLACE if config.replace else OnDuplicateSegmentLayer.SKIP for layer, rrd_paths in paths_by_layer.items(): if not rrd_paths: continue # a derived layer nobody has produced yet - entry.register([path.resolve().as_uri() for path in rrd_paths], layer_name=layer, on_duplicate=on_duplicate).wait() + with timer.stage(layer): + entry.register([path.resolve().as_uri() for path in rrd_paths], layer_name=layer, on_duplicate=on_duplicate).wait() + started: float = perf_counter() + republish_blueprints(entry, dataset, catalog_name, output_root) + blueprint_s: float = perf_counter() - started + counted: str = ", ".join(f"{len(found)} {layer}" for layer, found in paths_by_layer.items() if found) + how: str = "replacing duplicates" if config.replace else "skipping duplicates" + print(f"registered {counted} rrds into '{catalog_name}' at {config.catalog_url} ({how})") + + append_record( + output_root / "timing/register.jsonl", + RegisterRecord( + dataset=catalog_name, + started_at=timer.started_at, + layer_s=timer.stage_s, + blueprint_s=blueprint_s, + segment_count=len(paths_by_layer[paths.BASE_LAYER]), + total_s=timer.total_s, + host=gethostname(), + ), + ) + + +def republish_blueprints(entry: DatasetEntry, dataset: DataforgeDataset, catalog_name: str, output_root: Path) -> None: + """Publish fresh default blueprints and retire their previous catalog entries.""" # Every run republishes the blueprints from the current code, so a new layer's columns and a changed # layout both land without a separate step. register_blueprint only ever ADDS an entry, and a live # server holds registered files open (never overwrite them), so the run writes new stamped files, @@ -65,14 +103,16 @@ def main(config: Config) -> None: blueprint_entries: DatasetEntry | None = entry.blueprint_dataset() # None while the dataset has no blueprints retiring: dict[str, Path] = {} if blueprint_entries is not None: - listed: list[dict[str, Any]] = blueprint_entries.segment_table().select("rerun_segment_id", "rerun_storage_urls").to_arrow_table().to_pylist() + listed: list[dict[str, Any]] = ( + blueprint_entries.segment_table().select("rerun_segment_id", "rerun_storage_urls").to_arrow_table().to_pylist() + ) retiring = {row["rerun_segment_id"]: Path(unquote(urlparse(row["rerun_storage_urls"][0]).path)) for row in listed} stamp: str = datetime.now().strftime("%Y%m%d-%H%M%S-%f") # microseconds: back-to-back runs never share a file name - blueprint_path: Path = paths.blueprint_path(output_root, name, stamp=stamp).resolve() + blueprint_path: Path = paths.blueprint_path(output_root, catalog_name, stamp=stamp).resolve() with writing.atomic_write(blueprint_path) as temp_path: - dataset.default_blueprint().save(name, str(temp_path)) + dataset.default_blueprint().save(catalog_name, str(temp_path)) entry.register_blueprint(blueprint_path.as_uri(), set_default=True) - table_path: Path = paths.blueprint_path(output_root, name, segment_table=True, stamp=stamp).resolve() + table_path: Path = paths.blueprint_path(output_root, catalog_name, segment_table=True, stamp=stamp).resolve() columns: list[str] = entry.segment_table().schema().names writing.save_table_blueprint(dataset.table_blueprint(), table_path, timeline=schema.TIMELINE, fields=dataset.table_fields(), columns=columns) entry.register_blueprint(table_path.as_uri(), set_default=True, segment_table=True) @@ -81,7 +121,4 @@ def main(config: Config) -> None: ours: list[Path] = [path for path in retiring.values() if path.parent == blueprint_path.parent] # both resolved for path in ours: path.unlink(missing_ok=True) - print(f"retired {len(retiring)} older blueprint entries of '{name}' and deleted {len(ours)} of their files") - counted: str = ", ".join(f"{len(found)} {layer}" for layer, found in paths_by_layer.items() if found) - how: str = "replacing duplicates" if config.replace else "skipping duplicates" - print(f"registered {counted} rrds into '{name}' at {config.catalog_url} ({how})") + print(f"retired {len(retiring)} older blueprint entries of '{catalog_name}' and deleted {len(ours)} of their files") diff --git a/packages/dataforge/dataforge/apis/show3d_measure.py b/packages/dataforge/dataforge/apis/show3d_measure.py index d1877619c..87a8a59d1 100644 --- a/packages/dataforge/dataforge/apis/show3d_measure.py +++ b/packages/dataforge/dataforge/apis/show3d_measure.py @@ -18,10 +18,10 @@ from serde.json import to_json from dataforge import archives, paths, writing -from dataforge.datasets.show3d_layers import VIDEO_GOP -from dataforge.datasets.show3d_source import CAMERAS, RecordingInfo, read_json, validate_component +from dataforge.datasets.show3d_source import CAMERAS, RecordingInfo, validate_component from dataforge.logging_toolkit import log_video_stream -from dataforge.video_encoding import transcode_mp4_gray +from dataforge.records import read_json +from dataforge.video_encoding import AV1_GOP, transcode_mp4_gray @dataclass @@ -128,7 +128,7 @@ def main(config: Config) -> None: for entity, source in videos.items(): clip: Path = work / f"{source.stem}-{mode}.mp4" try: - transcode_mp4_gray(source, clip, fps=int(info.fps), gop=VIDEO_GOP, cq=cq, frames=info.num_frames) + transcode_mp4_gray(source, clip, fps=int(info.fps), gop=AV1_GOP, cq=cq, frames=info.num_frames) log_video_stream(recording, clip, entity) finally: clip.unlink(missing_ok=True) diff --git a/packages/dataforge/dataforge/aria.py b/packages/dataforge/dataforge/aria.py index 44bc1a851..10b3a5645 100644 --- a/packages/dataforge/dataforge/aria.py +++ b/packages/dataforge/dataforge/aria.py @@ -1,66 +1,50 @@ -"""Aria Gen1 VRS and LaMAria ground-truth readers, in the rig frame the schema wants. - -Everything here answers one question: what does a converter need in order to log -a LaMAria sequence as exoego:v2? Three shapes of answer live together because -they only make sense against each other: - -* **The rig.** LaMAria's published calibration uses the **right IMU** as its - body frame, so the rig frame is imu-right and every sensor pose is - ``rig_T_sensor = imuR_T_device @ device_T_sensor``. Cameras land in simplecv's - ``Fisheye62Parameters`` (Aria's FISHEYE624 minus the thin-prism terms, as in - ``simplecv.data.hot3d_utils``), which is what ``log_pinhole`` consumes. - Gen1 records its cameras sideways, so ``from_provider(rotate_cw90=True)`` - turns each of them a quarter turn clockwise for a converter that logs upright - frames, and ``rotate_uv_cw90`` turns published pixel coordinates the same way. -* **The streams.** Frames and IMU samples in VRS record order, on Aria's DEVICE - clock in nanoseconds — the clock the pGT and the control points are stamped - with, so nothing needs shifting anywhere downstream. -* **The ground truth.** The pGT is ``world_T_cam0`` at the slam-left frame - times; the sparse file holds surveyed control points in LV95/LN02, which are - 6-digit coordinates and are therefore translated by ``CUSTOM_ORIGIN_XYZ`` - exactly as the official tooling does. - -Reference: github.com/cvg/lamaria (``lamaria/utils/aria.py`` and -``lamaria/utils/constants.py``); the quaternion order and the transform chain -are cross-checked against a real VRS in ``tests/test_aria_vrs.py``. +"""What hot3d, the Aria Gen2 pilot and LaMAria share of an Aria recording: its device calibration, streams and projection. + +* **The device calibration.** The VRS ``calib_json`` file tag, read with + pyserde into simplecv's ``Fisheye624Parameters`` and ``SE3`` poses, the way + projectaria-tools reads it (its per-device camera defaults and its stream + rescale included), so every parameter and pose has the SDK's bits. +* **The streams.** Frames and IMU samples in VRS record order, read by + ``dataforge.vrs``, on Aria's DEVICE clock in nanoseconds. +* **The projection.** ``project_to_calibration`` sends world points through the + full FISHEYE624 model. + +LaMAria's rig convention (imu-right as the body frame) and its ground-truth +formats live in ``datasets/lamaria_source.py``. """ from __future__ import annotations -import json from collections.abc import Iterator from dataclasses import dataclass -from pathlib import Path from typing import Literal, TypeAlias import numpy as np -from jaxtyping import Float64, Int64, UInt8 +from jaxtyping import Bool, Float32, Float64, Int64, UInt8 from numpy import ndarray -from projectaria_tools.core import data_provider -from projectaria_tools.core.calibration import CameraCalibration, DeviceCalibration, ImuCalibration, rotate_camera_calib_cw90deg -from projectaria_tools.core.sensor_data import ImageData, ImageDataRecord, MotionData, TimeDomain -from projectaria_tools.core.stream_id import StreamId -from scipy.spatial.transform import Rotation -from serde import SerdeError, field, serde -from serde.json import from_json -from simplecv.camera_parameters import Extrinsics, Fisheye62Parameters, Intrinsics, KannalaBrandtDistortion +from serde import field, serde +from simplecv.camera_parameters import Fisheye624Parameters +from simplecv.se3 import SE3 +from simplecv.sensors.camera import fisheye624 from dataforge.logging_toolkit import ImuChannel +from dataforge.records import decode +from dataforge.vrs import ImuRecords, VrsFile, VrsImageReader # ── streams ─────────────────────────────────────────────────────────────── AriaStreamId: TypeAlias = Literal["1201-1", "1201-2", "214-1", "1202-1", "1202-2"] -"""The five Aria Gen1 streams a LaMAria recording carries; the rest (magnetometer, -barometer, GPS, WiFi, Bluetooth) are not part of the benchmark.""" +"""The five Aria Gen1 streams a converter reads (Gen2 reuses the ids); the rest (magnetometer, +barometer, GPS, WiFi, Bluetooth) are left in the file.""" SLAM_LEFT_STREAM_ID: AriaStreamId = "1201-1" -"""camera-slam-left: 640x480 gray at 20 fps, and the frame the pGT poses.""" +"""camera-slam-left: 640x480 gray at 20 fps.""" SLAM_RIGHT_STREAM_ID: AriaStreamId = "1201-2" """camera-slam-right: 640x480 gray at 20 fps.""" RGB_STREAM_ID: AriaStreamId = "214-1" """camera-rgb: 1408x1408 RGB at 10 fps, stored JPEG-compressed in the VRS.""" IMU_RIGHT_STREAM_ID: AriaStreamId = "1202-1" -"""imu-right at 1 kHz; its frame is the rig frame (LaMAria's body frame).""" +"""imu-right at 1 kHz (LaMAria's body frame).""" IMU_LEFT_STREAM_ID: AriaStreamId = "1202-2" """imu-left at 800 Hz.""" @@ -73,15 +57,8 @@ } """Stream id → the label the device calibration is keyed by.""" -CAMERA_STREAM_IDS: tuple[AriaStreamId, ...] = (SLAM_LEFT_STREAM_ID, SLAM_RIGHT_STREAM_ID, RGB_STREAM_ID) -"""Camera streams in the order they become ``cam_00``, ``cam_01``, ``cam_02``.""" - IMU_STREAM_IDS: tuple[AriaStreamId, ...] = (IMU_RIGHT_STREAM_ID, IMU_LEFT_STREAM_ID) -"""IMU streams in the order they become ``imu_00``, ``imu_01``; the first one *is* the rig.""" - -CUSTOM_ORIGIN_XYZ: Float64[ndarray, "3"] = np.array([2683594.412, 1247727.747, 417.307]) -"""LV95/LN02 origin the official tooling subtracts from every surveyed coordinate -(``lamaria.utils.constants.CUSTOM_ORIGIN_COORDINATES``), so metres stay small.""" +"""IMU streams in the order they become ``imu_00``, ``imu_01``.""" AriaImage: TypeAlias = UInt8[ndarray, "h w"] | UInt8[ndarray, "h w 3"] """One decoded frame: gray for the SLAM cameras, RGB for camera-rgb.""" @@ -93,232 +70,261 @@ """One IMU's gyro (rad/s) and accel (m/s^2) channels, in that order.""" -# ── the device calibration, as a rig ────────────────────────────────────── +# ── the device calibration ──────────────────────────────────────────── -def open_vrs(path: Path) -> data_provider.VrsDataProvider: - """Open one VRS file for reading. +@dataclass(frozen=True, slots=True) +class CameraConfig: + """A camera's image size and field of view, which Aria calibration JSON leaves to the reader.""" + + width: int + """Factory image width in pixels.""" + height: int + """Factory image height in pixels.""" + max_solid_angle: float + """Half-angle of the projectable cone, in radians.""" + valid_radius: float | None + """Pixel radius about the principal point that projections must fall inside; ``None`` for none.""" + + +CAMERA_CONFIGS: dict[str, dict[str, CameraConfig]] = { + "gen1": { + "camera-slam-left": CameraConfig(640, 480, 1.4, 330.0), + "camera-slam-right": CameraConfig(640, 480, 1.4, 330.0), + "camera-rgb": CameraConfig(2880, 2880, 1.0, 1415.0), + }, + "gen2": { + "slam-front-left": CameraConfig(512, 512, 1.4, 300.0), + "slam-front-right": CameraConfig(512, 512, 1.4, 300.0), + "slam-side-left": CameraConfig(512, 512, 1.4, 300.0), + "slam-side-right": CameraConfig(512, 512, 1.4, 300.0), + "camera-rgb": CameraConfig(4032, 3024, 1.4, 2202.0), + }, +} +"""FISHEYE624 camera defaults per device generation, from projectaria-tools 2.3 ``ConfigData.cpp``. - ``create_vrs_data_provider`` answers a missing, truncated or otherwise - unreadable file — the expected state after an interrupted download — with - ``None``, which would surface much later as an ``AttributeError``, so the - return is checked here. - """ - provider: data_provider.VrsDataProvider | None = data_provider.create_vrs_data_provider(str(path)) - if provider is None: - raise FileNotFoundError(f"no readable VRS at {path}; fetch it first (a resumed download leaves a partial file behind)") - return provider +The factory JSON only carries them under an optional ``ConfigData`` key, which +no Aria recording seen so far has.""" +GEN1_STREAM_RESCALES: dict[tuple[str, tuple[int, int], tuple[int, int]], tuple[float, tuple[float, float]]] = { + ("camera-rgb", (2880, 2880), (1408, 1408)): (0.5, (32.0, 32.0)), + ("camera-rgb", (2880, 2880), (704, 704)): (0.25, (32.0, 32.0)), +} +"""(label, factory size, stream size) → (scale, crop offset) for Gen1 streams recorded below +sensor resolution, as projectaria-tools' VRS provider applies them (``AriaCalibRescaleAndCrop.cpp``).""" -def fisheye62_from_aria(calibration: CameraCalibration, *, rig_T_cam: Float64[ndarray, "4 4"], name: str) -> Fisheye62Parameters: - """Convert one Aria FISHEYE624 camera into simplecv's Fisheye62 camera. - Aria's ``get_projection_params()`` is 15 long: - ``[f, cx, cy, k1..k6, p1, p2, s1..s4]`` — one focal length for both axes. The - four thin-prism terms have no Fisheye62 slot and are dropped, which - ``simplecv.data.hot3d_utils`` measured at under a pixel of reprojection error. +@serde +@dataclass(frozen=True, slots=True) +class _JsonPose: + """``T_Device_``: a translation and a ``[w, [x, y, z]]`` quaternion.""" - Extrinsics are stored as ``world_R_cam``/``world_t_cam`` holding - ``rig_T_cam``: ``log_pinhole`` logs ``cam_R_world``/``cam_t_world`` with - ``from_parent=True``, i.e. the parent-to-child ``cam_T_rig``, which is - exactly the inverse simplecv computes. + translation: tuple[float, float, float] = field(rename="Translation") + """Metres.""" + unit_quaternion: tuple[float, tuple[float, float, float]] = field(rename="UnitQuaternion") + """Scalar first, then the vector part.""" - Raises: - ValueError: If the camera is not a FISHEYE624 (no Gen1 Aria stream is not). - """ - model: str = calibration.get_model_name().name - if model != "FISHEYE624": - raise ValueError(f"{name} is a {model} camera; only Aria's FISHEYE624 maps onto Fisheye62") - params: Float64[ndarray, "15"] = np.asarray(calibration.get_projection_params(), dtype=np.float64) - size_wh: Int64[ndarray, "2"] = np.asarray(calibration.get_image_size(), dtype=np.int64) - return Fisheye62Parameters( - name=name, - extrinsics=Extrinsics(world_R_cam=rig_T_cam[:3, :3].copy(), world_t_cam=rig_T_cam[:3, 3].copy()), - intrinsics=Intrinsics.from_focal_principal_point( - camera_conventions="RDF", - fl_x=float(params[0]), - fl_y=float(params[0]), - cx=float(params[1]), - cy=float(params[2]), - width=int(size_wh[0]), - height=int(size_wh[1]), - ), - distortion=KannalaBrandtDistortion( - k1=float(params[3]), - k2=float(params[4]), - k3=float(params[5]), - k4=float(params[6]), - k5=float(params[7]), - k6=float(params[8]), - p1=float(params[9]), - p2=float(params[10]), - ), - ) + def se3(self) -> SE3: + """The pose, normalised as projectaria-tools does on load.""" + w, (x, y, z) = self.unit_quaternion + return SE3.from_quaternion(np.array([w, x, y, z], dtype=np.float64), np.array(self.translation, dtype=np.float64)) +@serde @dataclass(frozen=True, slots=True) -class AriaRig: - """One Aria Gen1's factory calibration, expressed in the rig frame. +class _JsonProjection: + """A camera's lens model name and its parameters.""" - The rig frame is **imu-right**, which is what LaMAria's published - calibration calls the body frame, so ``rig_T_cam`` here is directly - comparable with that file's ``T_b_s``. - """ - - cameras: dict[AriaStreamId, Fisheye62Parameters] - """Every camera stream the VRS carries, keyed by stream id; extrinsics hold ``rig_T_cam``.""" - rig_T_imu: dict[AriaStreamId, Float64[ndarray, "4 4"]] - """Every IMU stream's pose in the rig frame; imu-right is the identity by construction.""" + name: str = field(rename="Name") + """``FisheyeRadTanThinPrism`` is FISHEYE624; eye-tracking cameras are ``KannalaBrandtK3``.""" + params: list[float] = field(rename="Params") + """``[f, cx, cy, k1..k6, p1, p2, s1..s4]`` for FISHEYE624.""" - @classmethod - def from_provider(cls, provider: data_provider.VrsDataProvider, *, rotate_cw90: bool) -> AriaRig: - """Read the device calibration out of an open VRS and rebase it on imu-right. - - The result holds one entry per camera and IMU stream of a Gen1 Aria. - - Args: - provider: An open VRS. - rotate_cw90: Turn every camera a quarter turn clockwise, which a - converter that logs upright frames must, since Aria Gen1 records - its cameras sideways. ``rotate_camera_calib_cw90deg`` is what - keeps the pixels and their calibration describing the same rays: - the image size swaps, the principal point moves to - ``(h - 1 - cy, cx)``, the tangential and thin-prism terms swap - with it, and ``device_T_cam`` turns about the optical axis with - its translation untouched. Left False the calibration is the - factory's, which is what the published JSON describes and what - the published ground truth is posed in. - Raises: - ValueError: The file carries no factory calibration, or none for one - of those streams; every LaMAria sequence carries all of them. - """ - calibration: DeviceCalibration | None = provider.get_device_calibration() - if calibration is None: - raise ValueError("this VRS carries no device calibration") - reference: ImuCalibration | None = calibration.get_imu_calib(STREAM_LABELS[IMU_RIGHT_STREAM_ID]) - if reference is None: - raise ValueError(f"this VRS has no {STREAM_LABELS[IMU_RIGHT_STREAM_ID]} calibration, so it has no rig frame") - # ``to_matrix()``, never the neighbouring ``to_quat()``: that returns - # ``[[w, x, y, z]]`` while everything else here reads x, y, z, w. - device_T_imu_right: Float64[ndarray, "4 4"] = np.asarray(reference.get_transform_device_imu().to_matrix(), dtype=np.float64) - imu_right_T_device: Float64[ndarray, "4 4"] = np.linalg.inv(device_T_imu_right) - - cameras: dict[AriaStreamId, Fisheye62Parameters] = {} - for stream_id in CAMERA_STREAM_IDS: - factory: CameraCalibration | None = calibration.get_camera_calib(STREAM_LABELS[stream_id]) - if factory is None: - raise ValueError(f"this VRS has no {STREAM_LABELS[stream_id]} calibration, so {stream_id} has no rig pose") - # Rotated before anything is read off it, so the intrinsics and the - # pose that reach the rig both describe the frames a converter logs. - camera: CameraCalibration = rotate_camera_calib_cw90deg(factory) if rotate_cw90 else factory - device_T_cam: Float64[ndarray, "4 4"] = np.asarray(camera.get_transform_device_camera().to_matrix(), dtype=np.float64) - cameras[stream_id] = fisheye62_from_aria( - camera, - rig_T_cam=imu_right_T_device @ device_T_cam, - name=STREAM_LABELS[stream_id], - ) +@serde +@dataclass(frozen=True, slots=True) +class _JsonCameraConfig: + """The optional per-camera ``ConfigData`` that overrides ``CAMERA_CONFIGS``.""" - # imu-right *is* the rig frame, so its pose is the identity by construction: - # stated exactly rather than as inv(T) @ T, which leaves ~1e-17 of residue. - rig_T_imu: dict[AriaStreamId, Float64[ndarray, "4 4"]] = {IMU_RIGHT_STREAM_ID: np.eye(4, dtype=np.float64)} - for stream_id in IMU_STREAM_IDS: - if stream_id == IMU_RIGHT_STREAM_ID: - continue - imu: ImuCalibration | None = calibration.get_imu_calib(STREAM_LABELS[stream_id]) - if imu is None: - raise ValueError(f"this VRS has no {STREAM_LABELS[stream_id]} calibration, so {stream_id} has no rig pose") - device_T_imu: Float64[ndarray, "4 4"] = np.asarray(imu.get_transform_device_imu().to_matrix(), dtype=np.float64) - rig_T_imu[stream_id] = imu_right_T_device @ device_T_imu - return cls(cameras=cameras, rig_T_imu=rig_T_imu) + width: int = field(rename="ImageWidth") + """Image width in pixels.""" + height: int = field(rename="ImageHeight") + """Image height in pixels.""" + max_solid_angle: float = field(rename="MaxSolidAngle") + """Radians.""" + valid_radius: float | None = field(rename="ValidRadius", default=None) + """Pixels.""" @serde @dataclass(frozen=True, slots=True) -class PublishedTransform: - """A published rigid transform: a quaternion in x, y, z, w order and a translation.""" +class _JsonCamera: + """One ``CameraCalibrations`` entry, as far as a converter reads it.""" - qvec: tuple[float, float, float, float] - """Rotation as ``[x, y, z, w]`` — pycolmap's order, which the official tooling reads it with.""" - tvec: tuple[float, float, float] - """Translation in metres.""" + label: str = field(rename="Label") + """Sensor label.""" + projection: _JsonProjection = field(rename="Projection") + """Lens model.""" + device_T_camera: _JsonPose = field(rename="T_Device_Camera") + """Camera pose in the device frame.""" + config: _JsonCameraConfig | None = field(rename="ConfigData", default=None) + """Image size and field of view, when the file states them.""" + + +@serde +@dataclass(frozen=True, slots=True) +class _JsonImu: + """One ``ImuCalibrations`` entry, as far as a converter reads it (its pose, not its rectification).""" - def to_matrix(self) -> Float64[ndarray, "4 4"]: - """The same transform as a 4x4.""" - matrix: Float64[ndarray, "4 4"] = np.eye(4, dtype=np.float64) - matrix[:3, :3] = Rotation.from_quat(np.asarray(self.qvec, dtype=np.float64)).as_matrix() - matrix[:3, 3] = self.tvec - return matrix + label: str = field(rename="Label") + """Sensor label.""" + device_T_imu: _JsonPose = field(rename="T_Device_Imu") + """IMU pose in the device frame.""" @serde @dataclass(frozen=True, slots=True) -class _PublishedCameraPose: - """The one key of a ``cam0``/``cam1`` entry the gt layer reads; the rest is left to the file.""" +class _JsonDeviceClass: + """``DeviceClassInfo``: which Aria generation wrote the file.""" - rig_T_cam: PublishedTransform = field(rename="T_b_s") - """Published as ``T_b_s``; the body frame is imu-right, so this *is* ``rig_T_cam``.""" + device_class: str = field(rename="DeviceClass") + """``Ariane``/``Aria…`` for Gen1, ``Oatmeal`` for Gen2.""" @serde @dataclass(frozen=True, slots=True) -class _PublishedCalibration: - """An ``aria_calibrations/.json``, read only as far as camera-slam-left's pose.""" +class _JsonDeviceCalibration: + """A VRS ``calib_json`` tag; magnetometer, barometer, microphone and the rest are the file's own.""" - cam0: _PublishedCameraPose - """camera-slam-left, the frame the pseudo ground truth poses.""" + device_class: _JsonDeviceClass = field(rename="DeviceClassInfo") + """Device generation.""" + cameras: list[_JsonCamera] = field(rename="CameraCalibrations") + """Every camera, eye tracking included.""" + imus: list[_JsonImu] = field(rename="ImuCalibrations") + """Every IMU.""" -def read_rig_T_cam0(path: Path) -> Float64[ndarray, "4 4"]: - """Read camera-slam-left's rig pose out of a published ``aria_calibrations/.json``. +@dataclass(frozen=True, slots=True) +class DeviceCalibration: + """An Aria factory calibration: its FISHEYE624 cameras and its IMU poses, in the device frame.""" - The published body frame is imu-right, which *is* the rig, so that file's - ``cam0.T_b_s`` is ``rig_T_cam0`` as it stands — the one thing a gt layer - needs from the file, and the one thing it can be had without the VRS. The - intrinsics are read out of the VRS device calibration instead, which - ``tests/test_aria_vrs.py`` cross-checks against this same file. + cameras: dict[str, Fisheye624Parameters] + """FISHEYE624 cameras by label, at factory resolution; ``rig_T_cam`` is ``device_T_camera``.""" + device_T_imu: dict[str, SE3] + """IMU poses by label.""" - Args: - path: The sequence's published calibration JSON. + @classmethod + def from_json(cls, document: str, where: str) -> DeviceCalibration: + """Read a ``calib_json`` document, taking image sizes and fields of view from ``CAMERA_CONFIGS``. - Returns: - ``rig_T_cam0``, from the entry's x, y, z, w quaternion and its - translation in metres. + Raises: + ValueError: The document is not a device calibration, or names a + device generation or a FISHEYE624 camera with no known defaults. + """ + parsed: _JsonDeviceCalibration = decode(_JsonDeviceCalibration, document, source=f"{where}: invalid Aria device calibration") + device_class: str = parsed.device_class.device_class + generation: str | None = "gen1" if device_class[:4].lower() == "aria" else "gen2" if device_class.lower() == "oatmeal" else None + if generation is None: + raise ValueError(f"{where}: unknown Aria device class {device_class}") + cameras: dict[str, Fisheye624Parameters] = {} + for camera in parsed.cameras: + if camera.projection.name != "FisheyeRadTanThinPrism": + continue + if len(camera.projection.params) != 15: + raise ValueError(f"{where}: {camera.label} has {len(camera.projection.params)} FISHEYE624 parameters, not 15") + config: CameraConfig | None = ( + CAMERA_CONFIGS[generation].get(camera.label) + if camera.config is None + else CameraConfig(camera.config.width, camera.config.height, camera.config.max_solid_angle, camera.config.valid_radius) + ) + if config is None: + raise ValueError(f"{where}: no {generation} camera defaults for {camera.label}") + cameras[camera.label] = Fisheye624Parameters( + name=camera.label, + width=config.width, + height=config.height, + params=np.array(camera.projection.params, dtype=np.float64), + rig_T_cam=camera.device_T_camera.se3(), + max_solid_angle=config.max_solid_angle, + valid_radius=config.valid_radius, + ) + return cls(cameras=cameras, device_T_imu={imu.label: imu.device_T_imu.se3() for imu in parsed.imus}) + + def camera(self, label: str) -> Fisheye624Parameters: + """One FISHEYE624 camera; raises ValueError naming the label when the file has none.""" + if label not in self.cameras: + raise ValueError(f"no FISHEYE624 {label} calibration in this device calibration") + return self.cameras[label] + + def imu(self, label: str) -> SE3: + """One IMU's ``device_T_imu``; raises ValueError naming the label when the file has none.""" + if label not in self.device_T_imu: + raise ValueError(f"no {label} calibration in this device calibration") + return self.device_T_imu[label] + + +def read_device_calibration(vrs: VrsFile) -> DeviceCalibration: + """The factory calibration a VRS carries in its ``calib_json`` file tag. Raises: - ValueError: The file is not JSON, or holds no ``cam0.T_b_s`` of that shape. + ValueError: The file carries none (HOT3D's Quest 3 recordings, for one). """ - try: - published: _PublishedCalibration = from_json(_PublishedCalibration, path.read_text()) - except (SerdeError, json.JSONDecodeError) as error: - raise ValueError(f"{path}: {error}") from error - return published.cam0.rig_T_cam.to_matrix() + if "calib_json" not in vrs.file_tags: + raise ValueError(f"{vrs.path}: this VRS carries no device calibration") + return DeviceCalibration.from_json(vrs.file_tags["calib_json"], str(vrs.path)) -def rotate_uv_cw90(uv_px: Float64[ndarray, "n_points 2"], *, native_height_px: int) -> Float64[ndarray, "n_points 2"]: - """Turn pixel coordinates a quarter turn clockwise, with the image they name. +def rescale_to_stream(camera: Fisheye624Parameters, width: int, height: int) -> Fisheye624Parameters: + """Fit a Gen1 factory camera to a stream recorded below sensor resolution, as the SDK's VRS provider does. - ``np.rot90(image, -1)`` puts the pixel at row ``v``, column ``u`` at row - ``u``, column ``h - 1 - v``, so this is that same map on ``(u, v)`` pairs. - It is what keeps a published detection on its tag once the frames are logged - upright, and it moves a native principal point onto the one - ``from_provider(rotate_cw90=True)`` reports. + Raises: + ValueError: The sizes differ in a way ``GEN1_STREAM_RESCALES`` has no entry for. + """ + if (camera.width, camera.height) == (width, height): + return camera + key: tuple[str, tuple[int, int], tuple[int, int]] = (camera.name, (camera.width, camera.height), (width, height)) + if key not in GEN1_STREAM_RESCALES: + raise ValueError(f"{camera.name}: no rescale from {camera.width}x{camera.height} to the {width}x{height} stream") + scale, origin_offset = GEN1_STREAM_RESCALES[key] + return fisheye624.rescale(camera, width=width, height=height, scale=scale, origin_offset=origin_offset) + + +def project_to_calibration( + calibration: Fisheye624Parameters, + world_T_device: Float64[ndarray, "n 4 4"], + positions: Float32[ndarray, "n 133 3"], +) -> Float64[ndarray, "n 133 2"]: + """Project dense world joints through the shipped camera model. Args: - uv_px: Coordinates in the camera's native image, ``[u, v]`` per row. - native_height_px: Height of that native image, in pixels. + calibration: Full lens model in the logged image orientation; ``rig_T_cam`` is ``device_T_camera``. + world_T_device: Float64[ndarray, "n 4 4"] GT poses, NaN when missing. + positions: Float32[ndarray, "n 133 3"] world metres. Returns: - The same coordinates in the rotated image, ``[u, v]`` per row. + Float64[ndarray, "n 133 2"] pixels, with NaN for invalid joints. """ - return np.stack([native_height_px - 1.0 - uv_px[:, 1], uv_px[:, 0]], axis=1) + pixels: Float64[ndarray, "n 133 2"] = np.full((*positions.shape[:2], 2), np.nan) + device_T_camera: Float64[ndarray, "4 4"] = calibration.rig_T_cam.matrix() + # Loop locals stay unannotated: beartype would rebuild a jaxtyping checker per frame in the dev env. + for index, pose in enumerate(world_T_device): + if not np.isfinite(pose).all(): + continue + cam_T_world = np.linalg.inv(pose @ device_T_camera) + joints = np.flatnonzero(np.isfinite(positions[index]).all(axis=1)) + # One joint at a time, as a 3-vector: a batched matmul sums in another order. + points = np.array([cam_T_world[:3, :3] @ positions[index, joint] + cam_T_world[:3, 3] for joint in joints]).reshape(-1, 3) + in_front = points[:, 2] > 0.0 + pixels[index, joints[in_front]] = fisheye624.project(calibration, points[in_front]) + pixels[~np.isfinite(pixels).all(axis=-1)] = np.nan + return pixels # ── streams ─────────────────────────────────────────────────────────────── -def iter_frames(provider: data_provider.VrsDataProvider, stream_id: AriaStreamId) -> Iterator[TimedImage]: - """Yield every frame of one camera stream in VRS record order. +def iter_frames(vrs: VrsFile, stream_id: AriaStreamId) -> Iterator[TimedImage]: + """Yield every frame of one camera stream in VRS record order, decoded from its JPEG record. Record order is presentation order (verified strictly increasing on the real sequences), which is what an encoder needs: the mp4's Nth sample and @@ -332,238 +338,62 @@ def iter_frames(provider: data_provider.VrsDataProvider, stream_id: AriaStreamId ``(capture_timestamp_ns, image)``: a ``uint8`` gray ``h w`` frame for the SLAM cameras, a ``uint8`` ``h w 3`` one for camera-rgb. """ - stream: StreamId = StreamId(stream_id) + # PyTurboJPEG is in the dataforge envs only; other envs import this module through the dataset registry. + from turbojpeg import TJCS_GRAY, TJPF_GRAY, TJPF_RGB, TurboJPEG + + decoder: TurboJPEG = TurboJPEG() first_hw: tuple[int, ...] | None = None - for index in range(provider.get_num_data(stream)): - frame: tuple[ImageData, ImageDataRecord] = provider.get_image_data_by_index(stream, index) + for index, record in enumerate(VrsImageReader(vrs, stream_id).images()): + gray: bool = decoder.decode_header(record.image)[3] == TJCS_GRAY # ``AriaImage`` on purpose, not an inline jaxtyping subscript: a subscript # is re-evaluated on every annotated assignment, and beartype then # compiles and caches a fresh checker per frame (see AGENTS.md). - image: AriaImage = frame[0].to_numpy_array() + image: AriaImage = decoder.decode(record.image, pixel_format=TJPF_GRAY)[:, :, 0] if gray else decoder.decode(record.image, pixel_format=TJPF_RGB) if first_hw is None: first_hw = image.shape[:2] if image.dtype != np.uint8 or image.shape[:2] != first_hw: raise ValueError(f"{stream_id} frame {index} is {image.shape} {image.dtype}, not a uint8 {first_hw[0]}x{first_hw[1]} frame") - yield int(frame[1].capture_timestamp_ns), image + yield record.capture_timestamp_ns, image -def frame_timestamps_ns(provider: data_provider.VrsDataProvider, stream_id: AriaStreamId) -> Int64[ndarray, "n_frames"]: - """Capture timestamps of one stream, in record order, on Aria's device clock. +def frame_timestamps_ns(vrs: VrsFile, stream_id: AriaStreamId) -> Int64[ndarray, "n_frames"]: + """Capture timestamps of one JPEG camera stream, in record order, on Aria's device clock. Raises: ValueError: If they are not strictly increasing, which would break the 1:1 mapping of a timestamp onto its video sample. """ - times_ns: Int64[ndarray, "n_frames"] = np.asarray( - provider.get_timestamps_ns(StreamId(stream_id), TimeDomain.DEVICE_TIME), dtype=np.int64 - ) + times_ns: Int64[ndarray, "n_frames"] = VrsImageReader(vrs, stream_id).capture_timestamps() if times_ns.size > 1 and not bool((np.diff(times_ns) > 0).all()): raise ValueError(f"{stream_id} timestamps are not strictly increasing; record order is not presentation order") return times_ns -def read_imu(provider: data_provider.VrsDataProvider, stream_id: AriaStreamId) -> ImuSamples: +def read_imu(vrs: VrsFile, stream_id: AriaStreamId, *, stop_ns: int | None = None) -> ImuSamples: """Read one IMU stream whole, at its native rate, without rectifying anything. Raw samples on purpose: rectification needs a per-timestamp online - calibration that a base layer has no business inventing, and a consumer that - wants it can apply ``ImuCalibration.raw_to_rectified_*`` to these. + calibration that a base layer has no business inventing, and a consumer + that wants it can apply the factory rectification to these. A record whose accel or gyro is flagged invalid is dropped from both channels, so the two share one timestamp vector (none of the LaMAria sequences examined so far contains one). + Args: + vrs: The open recording. + stream_id: IMU stream to read. + stop_ns: Last capture stamp to keep (a preview); ``None`` keeps every sample. + Returns: The gyro channel in rad/s and the accel channel in m/s^2, in that order. """ - stream: StreamId = StreamId(stream_id) - times: list[int] = [] - gyro_radsec: list[list[float]] = [] - accel_msec2: list[list[float]] = [] - for index in range(provider.get_num_data(stream)): - sample: MotionData = provider.get_imu_data_by_index(stream, index) - if not (sample.accel_valid and sample.gyro_valid): - continue - times.append(int(sample.capture_timestamp_ns)) - gyro_radsec.append(list(sample.gyro_radsec)) - accel_msec2.append(list(sample.accel_msec2)) - times_ns: Int64[ndarray, "n_samples"] = np.asarray(times, dtype=np.int64) + records: ImuRecords = vrs.imu(stream_id) + valid: Bool[ndarray, "n_records"] = records.accel_valid & records.gyro_valid + if stop_ns is not None: + valid &= records.capture_timestamp_ns <= stop_ns + times_ns: Int64[ndarray, "n_samples"] = records.capture_timestamp_ns[valid] return ( - ImuChannel(times_ns=times_ns, values_xyz=np.asarray(gyro_radsec, dtype=np.float64).reshape(times_ns.size, 3)), - ImuChannel(times_ns=times_ns, values_xyz=np.asarray(accel_msec2, dtype=np.float64).reshape(times_ns.size, 3)), + ImuChannel(times_ns=times_ns, values_xyz=records.gyro_radsec[valid].astype(np.float64)), + ImuChannel(times_ns=times_ns, values_xyz=records.accel_msec2[valid].astype(np.float64)), ) - - -# ── pseudo ground truth ─────────────────────────────────────────────────── - - -@dataclass(frozen=True, slots=True) -class PseudoGt: - """A sequence's pseudo ground-truth trajectory, as published. - - Rows are kept exactly as the file has them: the corpus repeats a pose - verbatim while the device is static, and dropping those would silently - change how a viewer draws (and how the official evaluator scores) a stop. - """ - - times_ns: Int64[ndarray, "n_poses"] - """Device-clock timestamps, matching the slam-left frame times one for one.""" - world_T_cam0: Float64[ndarray, "n_poses 4 4"] - """Pose of camera-slam-left in the GT world frame (LV95/LN02-aligned, or MPS's for R_01..R_10).""" - - -def read_pseudo_gt(path: Path) -> PseudoGt: - """Read a ``ground_truth/pseudo_dense/.txt`` trajectory. - - Each line is ``ts_ns tx ty tz qx qy qz qw`` — a translation in metres and a - quaternion in x, y, z, w order, the same convention the calibration files - use. Rows stay in file order. - """ - rows: Float64[ndarray, "n_poses 8"] = np.loadtxt(path, dtype=np.float64).reshape(-1, 8) - world_T_cam0: Float64[ndarray, "n_poses 4 4"] = np.tile(np.eye(4, dtype=np.float64), (rows.shape[0], 1, 1)) - world_T_cam0[:, :3, :3] = Rotation.from_quat(rows[:, 4:8]).as_matrix() - world_T_cam0[:, :3, 3] = rows[:, 1:4] - return PseudoGt(times_ns=rows[:, 0].astype(np.int64), world_T_cam0=world_T_cam0) - - -# ── control points ──────────────────────────────────────────────────────── - - -@serde -@dataclass(frozen=True, slots=True) -class SurveyedPoint: - """One ``control_points`` entry as published, before the origin is subtracted. - - The entry's ``tag_id`` and ``image_names`` keys are left unread: the tag ids - are an artefact of the detection pipeline, and ``images`` already carries the - point-to-frame mapping the other way round. - """ - - measurement: tuple[float | None, float | None, float | None] - """LV95/LN02 easting, northing, height in metres; a ``None`` height was never levelled.""" - uncertainty: tuple[float | None, float | None, float | None] - """One-sigma survey uncertainty per axis in metres, ``None`` where the axis is unknown.""" - - -@serde -@dataclass(frozen=True, slots=True) -class DetectedPoint: - """One ``images`` entry as published: which point was seen in which frame, and where.""" - - timestamp: int - """Device-clock capture time of the frame, in nanoseconds.""" - control_point: str - """Name of the control point detected.""" - detection: tuple[float, float] - """Pixel coordinates of the detection, ``[u, v]``.""" - - -@serde -@dataclass(frozen=True, slots=True) -class _ControlPointFile: - """A ``ground_truth/sparse/.json`` as far as dataforge reads it; other keys are the file's own.""" - - control_points: dict[str, SurveyedPoint] - """Surveyed points by name.""" - images: dict[str, DetectedPoint] - """Detections by the extracted frame's file name, whose prefix names the stream.""" - - -@dataclass(frozen=True, slots=True) -class ControlPoint: - """One surveyed control point, in the translated metric world frame.""" - - name: str - """Survey name, e.g. ``"OB1878"``; unique within a sequence.""" - position_xyz_m: Float64[ndarray, "3"] - """LV95/LN02 minus ``CUSTOM_ORIGIN_XYZ``. An unlevelled point gets ``z = 0.0``, - i.e. the origin's height, and must be drawn as such rather than as a measurement.""" - has_height: bool - """False when the survey never levelled this point; its ``z`` is a placeholder.""" - uncertainty_xyz_m: Float64[ndarray, "3"] - """One-sigma survey uncertainty per axis in metres; ``NaN`` where unknown, never 0.""" - - -@dataclass(frozen=True, slots=True) -class ControlPointDetection: - """One control point seen in one frame.""" - - stream_id: AriaStreamId - """Camera that saw it, from the image name's prefix.""" - timestamp_ns: int - """Device-clock capture time of that frame.""" - uv_px: Float64[ndarray, "2"] - """Detection in pixels, in the camera's native (unrotated) image.""" - control_point: str - """Name of the control point, keying into ``ControlPointSet.points``.""" - - -@dataclass(frozen=True, slots=True) -class ControlPointSet: - """A sequence's sparse ground truth: surveyed points and their 2D detections.""" - - points: tuple[ControlPoint, ...] - """Every surveyed point, in the file's order.""" - detections: tuple[ControlPointDetection, ...] - """Every detection, sorted by stream then time, which is the order a columnar log wants.""" - - -def read_control_points(path: Path) -> ControlPointSet: - """Read a ``ground_truth/sparse/.json`` control-point file. - - The published coordinates are LV95/LN02, so they are six-digit numbers whose - float32 round-off is centimetres; every position is translated by - ``CUSTOM_ORIGIN_XYZ`` here, once, exactly as the official tooling does. The - file is also checked against itself here: a detection that names a point - the survey never published is an invariant of this one document, so it fails - at the door rather than in whichever writer reads the set next. - - Raises: - ValueError: The file is not JSON, does not hold the two maps, a point - has no horizontal measurement, or a detection names an unpublished point. - """ - try: - document: _ControlPointFile = from_json(_ControlPointFile, path.read_text()) - except (SerdeError, json.JSONDecodeError) as error: - raise ValueError(f"{path}: {error}") from error - points: list[ControlPoint] = [] - for name, surveyed in document.control_points.items(): - easting, northing, height = surveyed.measurement - if easting is None or northing is None: - raise ValueError(f"{path}: control point {name} has no horizontal measurement: {surveyed.measurement}") - # Substituting the origin's own height for an unlevelled point makes its - # translated z exactly 0.0, which is what ``has_height=False`` promises. - published_xyz_m: Float64[ndarray, "3"] = np.array( - [easting, northing, CUSTOM_ORIGIN_XYZ[2] if height is None else height], dtype=np.float64 - ) - points.append( - ControlPoint( - name=name, - position_xyz_m=published_xyz_m - CUSTOM_ORIGIN_XYZ, - has_height=height is not None, - uncertainty_xyz_m=np.array([np.nan if value is None else value for value in surveyed.uncertainty], dtype=np.float64), - ) - ) - - detections: list[ControlPointDetection] = [ - ControlPointDetection( - stream_id=stream_id_from_image_name(image_name), - timestamp_ns=detected.timestamp, - uv_px=np.asarray(detected.detection, dtype=np.float64), - control_point=detected.control_point, - ) - for image_name, detected in document.images.items() - ] - unknown: set[str] = {detection.control_point for detection in detections} - set(document.control_points) - if unknown: - raise ValueError(f"{path}: control point detection(s) name {', '.join(sorted(unknown))}, which the survey does not publish") - detections.sort(key=lambda detection: (detection.stream_id, detection.timestamp_ns)) - return ControlPointSet(points=tuple(points), detections=tuple(detections)) - - -def stream_id_from_image_name(image_name: str) -> AriaStreamId: - """The stream an extracted frame came from, e.g. ``1201-2-02100-1010.384.jpg`` → ``1201-2``.""" - for stream_id in CAMERA_STREAM_IDS: - if image_name.startswith(f"{stream_id}-"): - return stream_id - raise ValueError(f"{image_name} does not name an Aria camera stream") diff --git a/packages/dataforge/dataforge/blueprints.py b/packages/dataforge/dataforge/blueprints.py index 0ff0317e9..0a75d5720 100644 --- a/packages/dataforge/dataforge/blueprints.py +++ b/packages/dataforge/dataforge/blueprints.py @@ -17,7 +17,7 @@ from __future__ import annotations -from collections.abc import Sequence +from collections.abc import Iterable, Sequence import rerun as rr import rerun.blueprint as rrb @@ -130,6 +130,8 @@ def follow_eye_controls( back_m: float = FOLLOW_BACK_M, up_m: float = FOLLOW_UP_M, ahead_m: float = FOLLOW_AHEAD_M, + aim_down_m: float = 0.0, + side_m: float = 0.0, ) -> rrb.EyeControls3D: """A chase camera derived from the device's own forward and up. @@ -145,19 +147,75 @@ def follow_eye_controls( back_m: Distance behind the device, along ``forward``. up_m: Distance above it, along ``up``. ahead_m: Distance in front of it that the eye aims at. + aim_down_m: How far below the device the aim point sits (hands, for a headset). + side_m: Offset to the device's right, for a three-quarter view. Returns: The eye the Follow view of both blueprints uses. """ + right: tuple[float, float, float] = ( + forward[1] * up[2] - forward[2] * up[1], + forward[2] * up[0] - forward[0] * up[2], + forward[0] * up[1] - forward[1] * up[0], + ) position: tuple[float, float, float] = ( - -back_m * forward[0] + up_m * up[0], - -back_m * forward[1] + up_m * up[1], - -back_m * forward[2] + up_m * up[2], + -back_m * forward[0] + up_m * up[0] + side_m * right[0], + -back_m * forward[1] + up_m * up[1] + side_m * right[1], + -back_m * forward[2] + up_m * up[2] + side_m * right[2], + ) + look_target: tuple[float, float, float] = ( + ahead_m * forward[0] - aim_down_m * up[0], + ahead_m * forward[1] - aim_down_m * up[1], + ahead_m * forward[2] - aim_down_m * up[2], ) - look_target: tuple[float, float, float] = (ahead_m * forward[0], ahead_m * forward[1], ahead_m * forward[2]) return eye_controls_from_pose(position, look_target, up) +def headset_eye_controls(forward: tuple[float, float, float], up: tuple[float, float, float]) -> rrb.EyeControls3D: + """Three-quarter over-the-shoulder eye for a 3D view whose origin rides a moving headset. + + It rides the headset and aims below it at the hands, so a card or a scene view keeps the + headset cameras and the hands in shot however far the wearer walks. + + Args: + forward: Where the headset looks, in the view origin's frame (a camera's optical axis); unit length. + up: The headset's up, in the view origin's frame (the camera's shown image up); unit length. + """ + return follow_eye_controls(forward, up, back_m=0.4, up_m=0.45, ahead_m=0.5, aim_down_m=0.4, side_m=0.15) + + +def video_exclusions(slots: Iterable[tuple[int, int]]) -> list[str]: + """Content rules that drop each ``(rig, cam)`` video, and anything beneath it, from a view. + + A segment-table card excludes every video but the one its pane decodes: excluded, not + hidden, because a hidden entity is still decoded. + + Args: + slots: ``(rig, cam)`` of each camera whose video is dropped. + + Returns: + One ``-