From b3f4370e3c5eeafd7289fd7c2eb7ad3746470d54 Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 08:37:34 -0800 Subject: [PATCH 01/24] egocap: an ffmpeg encoder listed with no capability flag is one the copy can use The corrected copy asks ffmpeg which encoders it has and refuses an encoder that is not listed. The legend of that listing was told from the encoders by its flags, "V.....", which are also the flags of every video encoder that has no capability flag set. An ffmpeg that lists libx264 that way was read as having no libx264, and the copy was refused with the default encoder. The legend's rows are now told by the "=" that stands where a name does, and a video encoder is one whatever its other flags are. Nothing else reads an ffmpeg listing. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- .../egocap/calibration/rectify_take.py | 5 +-- .../unit/test_calibration_rectify_take.py | 31 +++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/examples/egocap/recording/egocap/calibration/rectify_take.py b/examples/egocap/recording/egocap/calibration/rectify_take.py index a7d43e3f9c..c076f82d81 100644 --- a/examples/egocap/recording/egocap/calibration/rectify_take.py +++ b/examples/egocap/recording/egocap/calibration/rectify_take.py @@ -200,9 +200,10 @@ def _ffmpeg_encoders(program: str) -> frozenset[str] | None: ) except (OSError, subprocess.SubprocessError): return None - # One line an encoder, its kind in the first letter of the flags before its name. + # One line an encoder, its kind in the first letter of the flags before its name. The legend's rows have "=" + # where a name stands; their flags tell nothing apart, since an encoder with no capability flag has the same. rows = (line.split() for line in listed.stdout.splitlines()) - names = frozenset(row[1] for row in rows if len(row) >= 2 and row[0].startswith("V") and row[0] != "V.....") + names = frozenset(row[1] for row in rows if len(row) >= 2 and row[0].startswith("V") and row[1] != "=") # An ffmpeg that fails or lists nothing has not answered the question. return names if listed.returncode == 0 and names else None diff --git a/examples/egocap/tests/recording/unit/test_calibration_rectify_take.py b/examples/egocap/tests/recording/unit/test_calibration_rectify_take.py index b2a129eb09..7d31c9e930 100644 --- a/examples/egocap/tests/recording/unit/test_calibration_rectify_take.py +++ b/examples/egocap/tests/recording/unit/test_calibration_rectify_take.py @@ -1065,6 +1065,37 @@ def run(command, **options): assert encoder_problem("ffmpeg_h264") is None and encoder_problem("ffmpeg_h264_nvenc") is None +#: What an ffmpeg prints whose software encoders carry no capability flag: only the kind letter is set. +PLAIN_LISTING = """Encoders: + V..... = Video + A..... = Audio + S..... = Subtitle + .F.... = Frame-level multithreading + ..S... = Slice-level multithreading + ...X.. = Codec is experimental + ....B. = Supports draw_horiz_band + .....D = Supports direct rendering method 1 + ------ + V..... libx264 libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (codec h264) + V..... libx264rgb libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 RGB (codec h264) + V....D h264_nvenc NVIDIA NVENC H.264 encoder (codec h264) + VF.... mpeg4 MPEG-4 part 2 + A..... aac AAC (Advanced Audio Coding) + S..... ass ASS (Advanced SubStation Alpha) subtitle +""" + + +def test_an_encoder_listed_with_no_capability_flag_is_one_this_computers_ffmpeg_has(monkeypatch, ffmpeg_asked): + monkeypatch.setattr( + rectify_take.subprocess, + "run", + lambda command, **options: subprocess.CompletedProcess(command, 0, stdout=PLAIN_LISTING, stderr=""), + ) + # The legend's rows are no encoders, and a video encoder is one whatever its other flags are. + assert ASK_FFMPEG("/somewhere/bin/ffmpeg") == {"libx264", "libx264rgb", "h264_nvenc", "mpeg4"} + assert encoder_problem("ffmpeg_h264") is None and encoder_problem("ffmpeg_h264_nvenc") is None + + @pytest.mark.skipif(shutil.which("ffmpeg") is None, reason="needs the real ffmpeg") def test_the_real_ffmpeg_says_it_has_the_software_encoder_the_recorder_defaults_to(): ASK_FFMPEG.cache_clear() From 54e8972cfe662b508f6af528fb5b7c46c77fe30a Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 08:39:16 -0800 Subject: [PATCH 02/24] egocap: the calibration requirement's help line describes the position its box is in The line under "Require calibration files before recording" was one fixed sentence that began "Off:", so with the box ticked the page said the opposite of what the checklist above it showed. The line now has one sentence for each position and shows the one for the position the box is drawn in, a choice still on its way to the backend included. Both say what happens to recording, in the words the checklist's advisory rows use. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- .../egocap/frontend/src/DevicesTab.test.tsx | 28 +++++++++++++++++-- examples/egocap/frontend/src/DevicesTab.tsx | 12 ++++++-- 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/examples/egocap/frontend/src/DevicesTab.test.tsx b/examples/egocap/frontend/src/DevicesTab.test.tsx index 0d397475e7..66fc4cb9ff 100644 --- a/examples/egocap/frontend/src/DevicesTab.test.tsx +++ b/examples/egocap/frontend/src/DevicesTab.test.tsx @@ -6,7 +6,7 @@ import type { ComponentType, ReactNode } from "react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react"; -import { ADVISORY_NOTE, DEVICES_REFRESH_MS, DevicesTab, type DevicesTabProps } from "./DevicesTab"; +import { ADVISORY_NOTE, DEVICES_REFRESH_MS, DevicesTab, REQUIREMENT_HELP, type DevicesTabProps } from "./DevicesTab"; import { SettingsHttpError } from "./settingsApi"; import { OPERATOR_SETTINGS_FIXTURE, TOOLS_FIXTURE } from "./settingsTestDoubles"; import type { SetupStatus } from "./setupApi"; @@ -135,7 +135,31 @@ describe("the calibration requirement", () => { expect(within(card).getByLabelText("Require calibration files before recording")).toBe(requirement()); expect(requirement().checked).toBe(false); expect(requirement().disabled).toBe(false); - expect(within(card).getByText("Off: missing calibration files are shown as a warning and takes are allowed.").id).toBe(requirement().getAttribute("aria-describedby")); + expect(within(card).getByText(REQUIREMENT_HELP.off).id).toBe(requirement().getAttribute("aria-describedby")); + expect(REQUIREMENT_HELP.off).toBe("Off: missing calibration is shown as a warning and does not hold recording."); + }); + + it("says what On means once the choice is saved as on, and nothing of Off", async () => { + await renderTab(SETUP_UNCALIBRATED, { stationSetup: withRequirement(true) }); + expect(requirement().checked).toBe(true); + const help = document.getElementById(requirement().getAttribute("aria-describedby") ?? ""); + expect(help?.textContent).toBe(REQUIREMENT_HELP.on); + expect(REQUIREMENT_HELP.on).toBe("On: recording is held while calibration this station needs is missing."); + expect(screen.queryByText(REQUIREMENT_HELP.off)).toBeNull(); + }); + + it("describes the position the box shows while a new choice is on its way, and the saved one again if it is refused", async () => { + let refuse: (reason: Error) => void = () => undefined; + const saveRequireCalibration = vi.fn(() => new Promise((_resolve, reject) => (refuse = reject))); + await renderTab(SETUP_ADVISED, { saveRequireCalibration }); + fireEvent.click(requirement()); + expect(requirement().checked).toBe(true); + expect(screen.getByText(REQUIREMENT_HELP.on)).toBeTruthy(); + refuse(new SettingsHttpError("control token is invalid")); + await settle(); + expect(requirement().checked).toBe(false); + expect(screen.getByText(REQUIREMENT_HELP.off)).toBeTruthy(); + expect(screen.queryByText(REQUIREMENT_HELP.on)).toBeNull(); }); it("saves the new choice and reads the checklist again at once", async () => { diff --git a/examples/egocap/frontend/src/DevicesTab.tsx b/examples/egocap/frontend/src/DevicesTab.tsx index 7de7eb2773..406f5eda8e 100644 --- a/examples/egocap/frontend/src/DevicesTab.tsx +++ b/examples/egocap/frontend/src/DevicesTab.tsx @@ -102,6 +102,12 @@ function Checklist({ checks }: { checks: readonly CheckItem[] }) { ); } +/** What each position of the calibration requirement means, shown under its box for the position the box is in. */ +export const REQUIREMENT_HELP = { + on: "On: recording is held while calibration this station needs is missing.", + off: "Off: missing calibration is shown as a warning and does not hold recording.", +} as const; + /** The deployment's choice of whether a missing calibration file holds recording or only warns. */ function CalibrationRequirement({ required, @@ -122,14 +128,16 @@ function CalibrationRequirement({ setPending(next); run(() => save(next).finally(() => setPending(null))); }; + // The position the box is drawn in; the help line describes that one, so the two cannot disagree. + const shown = pending ?? required; return (

- Off: missing calibration files are shown as a warning and takes are allowed. + {shown ? REQUIREMENT_HELP.on : REQUIREMENT_HELP.off}

{failure !== null &&

Not saved: {failure}

} From 7d117b1f8cbc7b879e6aca4a623d25edd53fd226 Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 08:44:12 -0800 Subject: [PATCH 03/24] egocap: a settled session is known again by what its recorder wrote, not by its directory's number The reader of takes left behind stops opening a session once it holds nothing to resolve, and told such a session from a directory put in its place under the same name by the directory's inode number. A file system may hand the number of a removed directory to the next one made, so on such a disk a session restored under its old name with an unresolved take in it was never read again and the take never listed. The same memory also skipped a settled session that a recorder had opened again and left a take in, since the directory was still the same one. A settled session is now known again by what its last recorder left in its lock file: the token drawn for that one holding of the session and the count of its beats. Only a recorder writes that value and no later holder writes an earlier one's, so a replaced directory and a reopened session both differ and are read as new, and nothing the file system assigns (a number, a time) is compared. A session no recorder ever locked has no such value and is read every time. A repeated read now costs one small read of each settled session's lock file beside the one listing of the output. The tests give the reader a file system on which every directory has one number and every file one set of times, so they hold on any disk. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- .../recording_service/output_scan.py | 70 +++++++--- .../test_takes_left_behind.py | 131 ++++++++++++++++++ 2 files changed, 179 insertions(+), 22 deletions(-) diff --git a/examples/egocap/recording/recording_service/output_scan.py b/examples/egocap/recording/recording_service/output_scan.py index 60d160ae10..bcb3cd785f 100644 --- a/examples/egocap/recording/recording_service/output_scan.py +++ b/examples/egocap/recording/recording_service/output_scan.py @@ -6,7 +6,8 @@ A caller that shows an operator what earlier sessions left behind reads the whole output, and reads it again from time to time. :class:`OutputScan` keeps what it learned between reads, so a repeated read costs one listing of the -output plus the few sessions that can still change, however many sessions and takes the output holds. +output, one small read of each settled session's lock file, and the few sessions that can still change, however +many takes the output holds. A session some recorder has open is never listed and never remembered. Two things say so. Its lock, where the lock reaches. And its beat, which reaches wherever the directory can be seen: the recorder rewrites the lock @@ -95,13 +96,29 @@ class _Watch: since: float +def _last_holder(session_path: Path) -> bytes | None: + """What the last recorder to hold a session left in its lock file; None for a session without one. + + The written value alone, without the file's time: only a recorder writes it, and a new holder never writes + an earlier holder's. + """ + beat = session_beat(session_path) + return None if beat is None else beat[0] + + class OutputScan: """Reads what the sessions of one station left behind under a recording output, remembering between reads. A session is settled, and not opened again, when it was read with nothing left to resolve or when its ``config.yaml`` was read and names a station that is not this reader's. A session that still holds a take is - read again every time, and so is one that appeared since the last read, one that was replaced by another - directory of the same name, and one whose ``config.yaml`` could not be read yet. + read again every time, and so is one that appeared since the last read, one whose ``config.yaml`` could not + be read yet, and one no recorder ever locked. + + A settled session is known again by what its last recorder left in its lock file: a token drawn for that + one holding of the session and the count of its beats, which only a recorder writes. A directory put in + its place under the same name, and the session itself once a recorder has opened it again, hold another + value and are read as new. Nothing the file system assigns is compared: it may hand a directory's number + to the next one made, and stamp both within one tick of its clock. A session is listed only once two looks of this reader, :data:`BEAT_WATCH_SECONDS` apart or more, found its lock free and its beat unchanged; so a take first appears one look after its session is first seen. A @@ -118,9 +135,8 @@ def __init__(self, watch_seconds: float = BEAT_WATCH_SECONDS, clock: Callable[[] self._watch_seconds = watch_seconds self._clock = clock self._key: tuple[Path, frozenset[str]] | None = None - # Settled sessions by name, with the directory's own number so a directory that replaces another of the - # same name is read as the new one it is. - self._settled: dict[str, int] = {} + # Settled sessions by name, each with what its lock file held when it was read: see the class. + self._settled: dict[str, bytes] = {} self._watches: dict[str, _Watch] = {} self._reported: set[str] = set() self._first_looks = 0 @@ -150,16 +166,19 @@ def read( self._first_looks = 0 try: with os.scandir(output_root) as listing: - entries = sorted(((entry.name, entry.inode()) for entry in listing)) + entries = sorted(entry.name for entry in listing) except OSError: # no output yet, so nothing was left behind return [] found: list[LeftBehind] = [] - for name, inode in entries: + for name in entries: # Hidden entries are never sessions; the caller's own session is its own to report. - if name.startswith(".") or name == skip_session or self._settled.get(name) == inode: + if name.startswith(".") or name == skip_session: continue try: - left, settle = self._read_session(output_root / name, names) + # One small read tells a settled session that is as it was from anything else under its name. + if name in self._settled and self._settled[name] == _last_holder(output_root / name): + continue + left, settled_as = self._read_session(output_root / name, names) except OSError as exc: if name not in self._reported: self._reported.add(name) @@ -170,12 +189,12 @@ def read( ) continue found += left - if settle: - self._settled[name] = inode + if settled_as is not None: + self._settled[name] = settled_as self._watches.pop(name, None) - present = {name for name, _inode in entries} + present = set(entries) # A name that is gone could be used again for something else. - self._settled = {name: inode for name, inode in self._settled.items() if name in present} + self._settled = {name: held for name, held in self._settled.items() if name in present} self._watches = {name: watch for name, watch in self._watches.items() if name in present} return found @@ -267,31 +286,38 @@ def _look(self, session_path: Path) -> tuple[bool, float]: remaining = self._watch_seconds - (now - watch.since) return remaining <= 0, max(remaining, 0.0) - def _read_session(self, session_path: Path, names: frozenset[str]) -> tuple[list[LeftBehind], bool]: - """What one entry of the output left behind, and whether it can be settled for good.""" + def _read_session(self, session_path: Path, names: frozenset[str]) -> tuple[list[LeftBehind], bytes | None]: + """What one entry of the output left behind, and what its lock file held if it can be settled for good; + None when it must be read again.""" try: sidecar = os.stat(session_path / MANIFEST_DIR) except (FileNotFoundError, NotADirectoryError): # Not a session: a studio folder, the quarantine folder, a stray file. Not remembered, since a session # being created right now looks the same for an instant. - return [], False + return [], None if not stat.S_ISDIR(sidecar.st_mode): - return [], False + return [], None # Whether a recorder has it open comes before anything is concluded from its files. if not session_lock_is_free(session_path): self._watches[session_path.name] = _Watch(session_beat(session_path), self._clock()) - return [], False + return [], None first = session_path.name not in self._watches quiet, _wait = self._look(session_path) if not quiet: self._first_looks += first - return [], False + return [], None + # The value judged quiet, taken before the files are read: a recorder that opens the session while they + # are leaves another, and the session is then read again. None for a session no recorder ever locked, + # which holds nothing to know it by. + beat = self._watches[session_path.name].beat + held = None if beat is None else beat[0] read, station = frozen_station(session_path) if read and station is not None and station not in names: # Another station's session is that station's to resolve, and its name never changes. - return [], True + return [], held scan = scan_session(session_path) found = takes_left_behind(session_path, scan) # A session whose configuration could not be read is looked at again: it may still be written. So is # one whose records could not be listed: nothing says that no take waits in it. - return found, read and not found and RECORDS_UNLISTABLE not in scan.problems + settles = read and not found and RECORDS_UNLISTABLE not in scan.problems + return found, held if settles else None diff --git a/examples/egocap/tests/recording_service/test_takes_left_behind.py b/examples/egocap/tests/recording_service/test_takes_left_behind.py index a15e63f131..2771dc45c0 100644 --- a/examples/egocap/tests/recording_service/test_takes_left_behind.py +++ b/examples/egocap/tests/recording_service/test_takes_left_behind.py @@ -16,6 +16,7 @@ """ import asyncio +import contextlib import errno import logging import os @@ -580,6 +581,136 @@ async def test_a_directory_replaced_by_another_of_the_same_name_is_read_as_the_n assert left.episode_id == f"{restored.session_id}/episode_1" +class _FileSystemThatReuses: + """The reader's ``os`` on a file system that hands a new directory the number of the one it replaced and + stamps both within one tick of its clock: every entry has one number, and every file one set of times.""" + + NUMBER, TICK = 7, 1_700_000_000_000_000_000 + + def __getattr__(self, name): + return getattr(os, name) + + @contextlib.contextmanager + def scandir(self, path): + with os.scandir(path) as listing: + yield [SimpleNamespace(name=entry.name, inode=lambda: self.NUMBER) for entry in listing] + + def _same(self, found): + times = dict.fromkeys(("st_atime_ns", "st_mtime_ns", "st_ctime_ns"), self.TICK) + return SimpleNamespace(st_mode=found.st_mode, st_ino=self.NUMBER, st_dev=found.st_dev, **times) + + def stat(self, path, **kwargs): + return self._same(os.stat(path, **kwargs)) + + def fstat(self, descriptor): + return self._same(os.fstat(descriptor)) + + +@pytest.fixture +def numbers_and_times_are_reused(monkeypatch): + """Whatever the reader asks the file system, a directory's number and every time are the same before and + after it is replaced, as on a file system that frees and hands out a number at once.""" + reusing = _FileSystemThatReuses() + monkeypatch.setattr(output_scan, "os", reusing) + + def beat(session_path): + found = session_beat(session_path) + return None if found is None else (found[0], reusing.TICK) + + monkeypatch.setattr(output_scan, "session_beat", beat) + return reusing + + +async def test_a_replaced_directory_is_read_as_the_new_one_where_its_number_and_times_are_the_old_ones( + tmp_path, numbers_and_times_are_reused +): + root, side = tmp_path / "out", tmp_path / "side" + finished = RecordingService(_config(root)) + first = await finished.open_session() + assert (await record(finished)).disposition is Disposition.KEPT + await finished.close() + reader = _Reader(root) + reader.look() + assert reader.look(WATCH) == [] and reader.look(1.0) == [] # settled: nothing is left in it + restored, _left = await _left_by_a_recorder_that_is_gone(side) + shutil.rmtree(first.session_path) + shutil.copytree(restored.session_path, first.session_path) + for record_file in (first.session_path / ".recording").glob("episode_*.json"): + record_file.write_text(record_file.read_text().replace(restored.session_id, first.session_id)) + # The directory that took the name is watched as one first seen, then read. + assert reader.look(1.0) == [] and reader.scan.first_looks() == 1 + assert reader.look(WATCH) == [f"{first.session_id}/episode_1"] + + +async def test_a_settled_session_a_recorder_opens_again_and_leaves_a_take_in_is_read_again(tmp_path, own): + root = tmp_path / "out" + finished = RecordingService(_config(root)) + session = await finished.open_session() + assert (await record(finished)).disposition is Disposition.KEPT + await finished.close() + reader = _Reader(root, watch=0.0) + assert reader.look() == [] and reader.look() == [] # settled: nothing is left in it + again = own(RecordingService(_config(root))) + await again.open_session(session.session_id) + interrupted = await _interrupted_take(again) + assert reader.look() == [] # open: its recorder's to report + await again.close() + assert reader.look() == [interrupted.episode_id] + + +async def test_a_session_that_stays_as_it_was_settled_is_not_opened_again_though_its_beat_is_read( + tmp_path, monkeypatch +): + root = tmp_path / "out" + finished = RecordingService(_config(root)) + session = await finished.open_session() + assert (await record(finished)).disposition is Disposition.KEPT + await finished.close() + opened, beats = [], [] + real_scan, real_beat = output_scan.scan_session, output_scan.session_beat + monkeypatch.setattr(output_scan, "scan_session", lambda path: opened.append(path.name) or real_scan(path)) + monkeypatch.setattr(output_scan, "session_beat", lambda path: beats.append(path.name) or real_beat(path)) + reader = _Reader(root, watch=0.0) + assert reader.look() == [] and opened == [session.session_id] + beats.clear() + # A file of its own that is rewritten, or a time that moves, is not a recorder's doing. + os.utime(session.session_path / episode_layout.MANIFEST_DIR / episode_layout.SESSION_LOCK_FILE) + os.utime(session.session_path) + assert reader.look() == [] and opened == [session.session_id] and beats == [session.session_id] + + +async def test_a_settled_session_whose_lock_file_can_no_longer_be_read_is_passed_over_and_logged( + tmp_path, monkeypatch, caplog +): + root = tmp_path / "out" + finished = RecordingService(_config(root)) + session = await finished.open_session() + assert (await record(finished)).disposition is Disposition.KEPT + await finished.close() + reader = _Reader(root, watch=0.0) + assert reader.look() == [] + + def refuse(session_path): + raise PermissionError(errno.EACCES, "Permission denied", str(session_path)) + + monkeypatch.setattr(output_scan, "session_beat", refuse) + with caplog.at_level(logging.WARNING, logger="isaaccapture.egocap.output_scan"): + assert reader.look() == [] and reader.look() == [] + passed_over = "an entry of the recording output cannot be read and is passed over" + assert [r.getMessage() for r in caplog.records] == [f"{passed_over}: {session.session_id} (PermissionError)"] + + +def test_a_session_no_recorder_ever_locked_is_read_every_time(tmp_path, monkeypatch): + root = tmp_path / "out" + (root / "session_by_hand" / ".recording").mkdir(parents=True) + opened = [] + real_scan = output_scan.scan_session + monkeypatch.setattr(output_scan, "scan_session", lambda path: opened.append(path.name) or real_scan(path)) + reader = _Reader(root, watch=0.0) + # Nothing in it says who wrote it last, so nothing tells it from another put in its place. + assert reader.look() == [] and reader.look() == [] and opened == ["session_by_hand"] * 2 + + # --- the station: every name it has had, and sessions that carry none ------------------------- From 6d65c9bf6ff925e10de4277dd3cfaa18ea583051 Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 09:25:00 -0800 Subject: [PATCH 04/24] egocap: the late glove save's tests wait for the save's answer, not for its files Two tests of a calibration whose files the folder takes after the save was given up let the save go on, waited until the files were in place, and then asked the service once to act on them: its duty in one test, a take in the other. The service takes note of a late save when the folder's thread has come back with its answer, which is a moment after the last file is in place. Asked in that moment it finds nothing, and the tests then read the unchanged capture session as a failure. Under load that moment is long. The service is right: its duty runs again, and the next take asks again, once the answer is there. The tests now hold the folder's thread back while they look at the files, one of them showing that files in place alone start nothing, and wait for the answer itself before they ask, so neither depends on how fast the thread returns. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- .../tests/backend/test_glove_calibration.py | 43 +++++++++++++------ 1 file changed, 31 insertions(+), 12 deletions(-) diff --git a/examples/egocap/tests/backend/test_glove_calibration.py b/examples/egocap/tests/backend/test_glove_calibration.py index 04c611166c..73fa1ab19d 100644 --- a/examples/egocap/tests/backend/test_glove_calibration.py +++ b/examples/egocap/tests/backend/test_glove_calibration.py @@ -419,12 +419,14 @@ async def test_files_the_folder_takes_after_the_calibration_was_given_up_are_loa write_pair(folder, "Alex", b"old left", b"old right") first = await _capturing(rig) monkeypatch.setattr(service, "_SAVE_SECONDS", 0.1) - answering = threading.Event() + answering, returning = threading.Event(), threading.Event() real = service.save def save_into_a_folder_that_answers_late(folder, pair, made) -> None: answering.wait(20.0) real(folder, pair, made) + # The files are in place before the folder's thread is back with its answer. + returning.wait(20.0) monkeypatch.setattr(service, "save", save_into_a_folder_that_answers_late) try: @@ -435,16 +437,26 @@ def save_into_a_folder_that_answers_late(folder, pair, made) -> None: await rig.back() back = rig.session() assert back != first and rig.files() == ALEX and rig.rotations == 0 + # The save the service gave up, which it takes note of once the folder's thread has come back with it. + late, _pair = rig.gloves._late_save # While the save is still out the duty has nothing to act on. await rig.gloves.settle() assert rig.session() == back + # The folder answers after all: the files are in place though the calibration was not called saved. + answering.set() + await poll_until( + lambda: not any(entry.name.startswith("cal-") for entry in folder.iterdir()), timeout_s=10.0 + ) + await poll_until( + lambda: not [entry for entry in folder.iterdir() if entry.name.startswith(".")], timeout_s=10.0 + ) + # Files that are in place are not yet the save's answer: nothing is acted on before that is back. + await rig.gloves.settle() + assert rig.session() == back and not late.done() finally: answering.set() - # The folder answers after all: the files are in place though the calibration was not called saved. - await poll_until(lambda: not any(entry.name.startswith("cal-") for entry in folder.iterdir()), timeout_s=10.0) - await poll_until( - lambda: not [entry for entry in folder.iterdir() if entry.name.startswith(".")], timeout_s=10.0 - ) + returning.set() + await poll_until(late.done, timeout_s=10.0) rig.blocked = "finish the take being recorded first" await rig.gloves.settle() # Never under a take, as any change of what capture runs with. @@ -1359,12 +1371,14 @@ async def test_a_save_the_folder_took_late_is_taken_note_of_by_the_next_take_bef write_pair(folder, "Alex", b"old left", b"old right") await _capturing(rig) monkeypatch.setattr(service, "_SAVE_SECONDS", 0.1) - answering = threading.Event() + answering, returning = threading.Event(), threading.Event() real = service.save def save_into_a_folder_that_answers_late(folder, pair, made) -> None: answering.wait(20.0) real(folder, pair, made) + # The files are in place before the folder's thread is back with its answer. + returning.wait(20.0) monkeypatch.setattr(service, "save", save_into_a_folder_that_answers_late) try: @@ -1373,14 +1387,19 @@ def save_into_a_folder_that_answers_late(folder, pair, made) -> None: assert (await rig.phase("saved", "failed"))["message"] == service.SAVE_SLOW await rig.back() back = rig.session() + # The save the service gave up, which it takes note of once the folder's thread has come back with it. + late, _pair = rig.gloves._late_save assert await rig.take("Alex") is None + # The folder takes the files after all: Alex's two names hold the new calibration. + answering.set() + await poll_until(lambda: (folder / "Alex_left.mcal").read_bytes() == MADE["left"], timeout_s=10.0) + await poll_until( + lambda: not [entry for entry in folder.iterdir() if entry.name.startswith(".")], timeout_s=10.0 + ) finally: answering.set() - # The folder takes the files after all: Alex's two names hold the new calibration. - await poll_until(lambda: (folder / "Alex_left.mcal").read_bytes() == MADE["left"], timeout_s=10.0) - await poll_until( - lambda: not [entry for entry in folder.iterdir() if entry.name.startswith(".")], timeout_s=10.0 - ) + returning.set() + await poll_until(late.done, timeout_s=10.0) # Alex presses Record before the backend's duty has had a turn: capture, which still runs with what the # names held before, is restarted for that take, and the take's session copies what capture then runs with. assert await rig.take("Alex") is None From 2de97683399a7833e9248bbf36c2a62f43577068 Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 09:35:52 -0800 Subject: [PATCH 05/24] egocap: a copy that ends before the frame a test holds it at fails the test with the reason The tests of the corrected copy hold the library's copy at a frame and wait for it to get there. A copy that was refused before it wrote that frame never did, and the wait ran out its twenty seconds and failed with a bare "assert False". That is how the cancel test with the real h264 encoder failed where the encoder list was misread and the copy refused for a missing libx264: nothing in the failure named the refusal. The stand-in now notes when the copy is over and what it raised, and the wait ends at once with that as its message. A test pins it with the refusal an ffmpeg without the encoder gives. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- .../tests/backend/test_rectified_copy.py | 35 +++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/examples/egocap/tests/backend/test_rectified_copy.py b/examples/egocap/tests/backend/test_rectified_copy.py index 796f69ba6e..8f270b92b6 100644 --- a/examples/egocap/tests/backend/test_rectified_copy.py +++ b/examples/egocap/tests/backend/test_rectified_copy.py @@ -14,6 +14,7 @@ import os import shutil import threading +import time from pathlib import Path import cv2 @@ -91,6 +92,9 @@ def __init__(self, at: int = 2) -> None: self.at = at self.reached = threading.Event() self.go = threading.Event() + #: Set when the copy is over, with what it raised if it raised: it may never come to the held frame. + self.over = threading.Event() + self.raised: BaseException | None = None def __call__(self, episode, out, cameras, *, progress, **options): def held(camera, written, declared): @@ -99,10 +103,22 @@ def held(camera, written, declared): assert self.go.wait(20) progress(camera, written, declared) - return rectify_episode(episode, out, cameras, progress=held, **options) + try: + return rectify_episode(episode, out, cameras, progress=held, **options) + except BaseException as raised: + self.raised = raised + raise + finally: + self.over.set() async def wait(self) -> None: - assert await asyncio.to_thread(self.reached.wait, 20) + """Until the copy is held at its frame. A copy that ended before it fails the test at once, with what + the library raised: waited out, it would say only that the frame never came.""" + for _ in range(4000): + if self.reached.is_set() or self.over.is_set(): + break + await asyncio.sleep(0.005) + assert self.reached.is_set(), f"the copy was over before it wrote frame {self.at}: {self.raised!r}" #: Room on the recordings disk that no test of anything else is held for. @@ -589,6 +605,21 @@ async def test_cancelling_a_copy_written_by_the_real_h264_encoder_leaves_nothing await tool.aclose() +async def test_a_copy_that_ends_before_the_frame_a_test_holds_it_at_says_why_at_once(host, monkeypatch): + # What an ffmpeg without the encoder makes of a copy: refused by the library before a frame is written. + monkeypatch.setattr(rectify_take, "_ffmpeg_encoders", lambda program: frozenset({"mpeg4"})) + monkeypatch.setattr(shutil, "which", lambda program: f"/usr/bin/{program}") + held = Held(at=3) + tool = service(host, held) + await tool.start({**BODY, "encoder": "ffmpeg_h264", "quality": 30}) + started = time.monotonic() + with pytest.raises(AssertionError, match="the copy was over before it wrote frame 3: .*needs the libx264"): + await held.wait() + assert time.monotonic() - started < 10 + assert (await finished(tool))["state"] == FAILED + await tool.aclose() + + async def test_there_is_nothing_to_cancel_before_a_copy_or_after_one_has_ended(host): tool = service(host) await refused(tool.cancel(), 409, NO_COPY_RUNNING) From 52bcc37eae356b958e17941125fee8a87edd8b9f Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 09:37:50 -0800 Subject: [PATCH 06/24] egocap: a hand whose glove delivers nothing is not counted valid and not drawn The capture session goes on sending the last pose of a glove that was switched off or has no current data, every joint still flagged valid. The Tracking data rows counted those flags and the hand view drew the hand, so both showed a tracked hand beside a device listed as disconnected or degraded. Both now ask the capture status for the hand's device, by the rule the station checklist holds a required device to: it delivers while it is connected, or degraded only because its calibration file was refused. A hand whose device does not deliver reads "not delivered (glove disconnected)" in place of a joint count, its joints show no value, and the hand view draws it as a glove that sends nothing, in words and with its dashed outline. A hand the capture status reports no device for is judged on the sample alone, as before. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- examples/egocap/frontend/README.md | 6 +++ examples/egocap/frontend/src/App.test.tsx | 51 +++++++++++++++++++ examples/egocap/frontend/src/App.tsx | 9 ++-- examples/egocap/frontend/src/CaptureTree.tsx | 39 ++++++++++---- .../egocap/frontend/src/HandView.test.tsx | 18 +++++++ examples/egocap/frontend/src/HandView.tsx | 16 ++++-- .../egocap/frontend/src/deviceHealth.test.ts | 37 +++++++++++++- examples/egocap/frontend/src/deviceHealth.ts | 31 +++++++++++ 8 files changed, 186 insertions(+), 21 deletions(-) diff --git a/examples/egocap/frontend/README.md b/examples/egocap/frontend/README.md index 072a1d85eb..a0a3622069 100644 --- a/examples/egocap/frontend/README.md +++ b/examples/egocap/frontend/README.md @@ -694,6 +694,12 @@ panel of its own, never drawn over a camera picture, and it changes nothing in w - It draws from the tracking samples the Details tables list (`hand_left.*` and `hand_right.*`: the 26 OpenXR joints of each hand, as positions in metres in the stream's reference space with a validity flag per joint), and like them it shows nothing from a sample older than two seconds or from a feed that is not live. +- A hand is judged on its device too. The capture session goes on sending the last pose of a glove that was + switched off or has no current data, every joint still flagged valid. So a hand whose device the capture status + does not call delivering (`handDevices` in `deviceHealth.ts`: connected, or degraded only because its + calibration file was refused, the station checklist's rule for a required device) is drawn as a glove that + sends nothing, and the Details tables read *not delivered (glove disconnected)* in place of a joint count and + show no value for its joints. A hand the capture status reports no device for is judged on the sample alone. How a hand is laid flat (`handProjection.ts`): diff --git a/examples/egocap/frontend/src/App.test.tsx b/examples/egocap/frontend/src/App.test.tsx index 1dfc01fa1f..8a32b966ba 100644 --- a/examples/egocap/frontend/src/App.test.tsx +++ b/examples/egocap/frontend/src/App.test.tsx @@ -17,6 +17,8 @@ import App from "./App"; import { OPERATOR_SETTINGS_FIXTURE, SETTINGS_FIXTURE } from "./settingsTestDoubles"; import { useCaptureSession, type AcceptedTracking, type CaptureSessionState } from "./useCaptureSession"; import { Axes, HandJointOrder, PositionUnit, QuaternionOrder, type PreviewSnapshot } from "./captureProtocol"; +import { DeviceState, StatusReason } from "./captureStatus"; +import { handDisplay, syntheticHand } from "./handTestDoubles"; import type { ControllerDisplay, DecodedTracking, HandDisplay } from "./trackingDecoder"; vi.mock("./useCaptureSession", async (importOriginal) => { @@ -444,6 +446,55 @@ describe("CaptureTree staleness advances with wall-clock time alone", () => { }); }); +describe("a hand whose glove delivers nothing", () => { + /** A capture status with the two gloves in the given states; the sample beside it holds both hands whole. */ + function withGloves(left: [number, number], right: [number, number]) { + const glove = (side: string, [status, reason]: [number, number]) => ({ + id: `manus/hand/${side}`, + path: `/hand/${side}`, + type: "hand", + description: `${side} Manus glove`, + provider_id: "provider-manus", + status, + reason, + error: "", + }); + const status = { updated_at_ns: "1", providers: [], devices: [glove("left", left), glove("right", right)], cameras: [] }; + const hands = makeTracking({ handLeft: handDisplay(syntheticHand("left")), handRight: handDisplay(syntheticHand("right")) }); + mockState( + makeState({ + phase: "connected", + snapshot: makeSnapshot({ + status: { session_id: "s1", type: 3, running: true, startup_stage: null, message: null, status } as PreviewSnapshot["status"], + tracking: { sequence: "1", age_ms: 10, diagnostic: null }, + }), + trackingSample: makeTrackingSample(hands, { snapshotAgeMs: 10 }), + receivedAtMonotonic: performance.now(), + }), + ); + render(); + } + const captions = () => Array.from(document.querySelectorAll(".hand-view-caption")).map((caption) => caption.textContent); + + it("is not counted as valid in the tracking data, and is not drawn, though the sample still carries it whole", () => { + // Left switched off, right with no current skeleton data: the capture session goes on sending the last poses. + withGloves([DeviceState.DISCONNECTED, StatusReason.NO_HARDWARE_SIGNAL], [DeviceState.DEGRADED, StatusReason.NO_CURRENT_DATA]); + expect(branchValue(branchSummary("Hands"))).toBe("Left not delivered (glove disconnected) Right not delivered (glove degraded)"); + const left = branchSummary("Left hand"); + expect(branchValue(left)).toBe("not delivered (glove disconnected)"); + // No joint keeps the value that was left over. + expect(new Set(rowCells(left, "Wrist"))).toEqual(new Set(["—"])); + expect(captions()).toEqual(["✗No data from the left glove", "✗No data from the right glove"]); + }); + + it("is counted and drawn again once the glove delivers, a glove whose calibration file was refused included", () => { + withGloves([DeviceState.CONNECTED, StatusReason.NONE], [DeviceState.DEGRADED, StatusReason.CALIBRATION_FAILED]); + expect(branchValue(branchSummary("Hands"))).toBe("Left 26/26 valid Right 26/26 valid"); + expect(branchValue(branchSummary("Left hand"))).toBe("26/26 joints valid"); + expect(captions()).toEqual(["Left hand", "Right hand"]); + }); +}); + describe("CaptureTree diagnostic vs never-had-data", () => { it("shows the generic empty label when no tracking sample has ever arrived", () => { mockState(makeState({ snapshot: makeSnapshot({ tracking: null }) })); diff --git a/examples/egocap/frontend/src/App.tsx b/examples/egocap/frontend/src/App.tsx index c969e05022..4f10c060ce 100644 --- a/examples/egocap/frontend/src/App.tsx +++ b/examples/egocap/frontend/src/App.tsx @@ -2,7 +2,7 @@ // // SPDX-License-Identifier: Apache-2.0 -import { useCallback, useEffect, useId, useReducer, useRef, useState, type CSSProperties } from "react"; +import { useCallback, useEffect, useId, useMemo, useReducer, useRef, useState, type CSSProperties } from "react"; import { useCaptureSession, type ConnectionPhase } from "./useCaptureSession"; import type { PreviewSnapshot } from "./captureProtocol"; import { @@ -37,7 +37,7 @@ import { maxSidebarWidth, saveSidebarWidth, } from "./sidebarWidth"; -import { deviceTone, retainedTone, type Tone } from "./deviceHealth"; +import { deviceTone, handDevices, retainedTone, type Tone } from "./deviceHealth"; import { HandView } from "./HandView"; import { loadHandViewShown, saveHandViewShown } from "./handViewSetting"; import { PoseViserPanel } from "./PoseViserPanel"; @@ -501,6 +501,8 @@ export default function App() { } = useCaptureSession(); const feedHealth = feedHealthFromPhase(phase); const response = snapshot === null ? null : snapshotToLegacyStatus(snapshot); + // The hands' devices change with the capture status alone, so the hand view is redrawn for nothing else. + const hands = useMemo(() => handDevices(snapshot === null ? null : snapshotToLegacyStatus(snapshot)), [snapshot]); const presentation = derivePresentation(response, phase === "connected"); const recordingActions = buildRecordingActions(sendRecordingCommand); // A live take frames the cameras in red, so the state reads from across the room; never from a stale feed. @@ -793,7 +795,7 @@ export default function App() { <> {handViewShown && (
- +
)} {/* Always in the page, so a screen reader hears the change when the panel goes and learns where to bring it back. */} @@ -810,6 +812,7 @@ export default function App() { diff --git a/examples/egocap/frontend/src/CaptureTree.tsx b/examples/egocap/frontend/src/CaptureTree.tsx index dad887ef06..f7306e2f67 100644 --- a/examples/egocap/frontend/src/CaptureTree.tsx +++ b/examples/egocap/frontend/src/CaptureTree.tsx @@ -13,6 +13,7 @@ */ import { useEffect, useState } from "react"; import type { AcceptedTracking } from "./useCaptureSession"; +import { NO_HAND_DEVICES, type HandDevice, type HandDevices } from "./deviceHealth"; import { OPENXR_26_JOINT_NAMES } from "./handJoints"; import type { ControllerDisplay, DecodedTracking, HandDisplay, HeadDisplay } from "./trackingDecoder"; @@ -218,12 +219,21 @@ function ControllerBranch({ label, controller }: { label: string; controller: Co ); } +/** What a hand's row says in place of a joint count while its device delivers nothing: the sample still carries + * the last pose the capture session had, valid flags and all, and that is no measurement of the hand now. */ +function notDelivered(device: HandDevice): string { + return `not delivered (glove ${device.state})`; +} + /** One hand's nested branch: the full 26-joint table, grouped by - * Position/Orientation column headers. */ -function HandBranch({ label, hand }: { label: string; hand: HandDisplay | null }) { - const current = hand !== null && hand.present ? hand : null; + * Position/Orientation column headers. `device` is the hand's tracking device, null when the capture status + * reports none. */ +function HandBranch({ label, hand, device }: { label: string; hand: HandDisplay | null; device: HandDevice | null }) { + const held = hand !== null && device !== null && !device.delivering; + // A hand its device does not deliver is shown as no data, cell by cell, never as the pose that was left over. + const current = hand !== null && hand.present && !held ? hand : null; const validCount = current === null ? 0 : current.joints.filter((j) => j.valid).length; - const toggleLabel = hand === null ? "unavailable" : hand.present ? `${validCount}/26 joints valid` : "absent"; + const toggleLabel = hand === null ? "unavailable" : held ? notDelivered(device) : hand.present ? `${validCount}/26 joints valid` : "absent"; return (
@@ -303,11 +313,15 @@ function controllerSummary(tracking: DecodedTracking | null): string { } /** The top-level "Hands" branch's summary text: each side's valid-joint - * count, or its presence/availability when there is nothing to count. */ -function handSummary(tracking: DecodedTracking | null): string { + * count, or its presence/availability when there is nothing to count. A hand whose device delivers nothing is + * said to be not delivered, whatever the sample still counts as valid. */ +function handSummary(tracking: DecodedTracking | null, devices: HandDevices): string { if (tracking === null) return "Left unavailable Right unavailable"; - const side = (h: HandDisplay) => (h.present ? `${h.joints.filter((j) => j.valid).length}/26 valid` : "absent"); - return `Left ${side(tracking.handLeft)} Right ${side(tracking.handRight)}`; + const side = (h: HandDisplay, device: HandDevice | null) => { + if (device !== null && !device.delivering) return notDelivered(device); + return h.present ? `${h.joints.filter((j) => j.valid).length}/26 valid` : "absent"; + }; + return `Left ${side(tracking.handLeft, devices.left)} Right ${side(tracking.handRight, devices.right)}`; } /** The page's main tracking tree: Head, Controllers and Hands as @@ -316,8 +330,11 @@ function handSummary(tracking: DecodedTracking | null): string { export function CaptureTree({ trackingSample, diagnostic, + handDevices = NO_HAND_DEVICES, }: { trackingSample: AcceptedTracking | null; + /** The hands' tracking devices by the capture status; a hand whose device does not deliver is not counted. */ + handDevices?: HandDevices; /** Why no/an old sample is being served, e.g. an oversized sample the * backend dropped -- shown ahead of the generic empty/stale label when * present, distinct from simply never having received a sample. */ @@ -361,10 +378,10 @@ export function CaptureTree({
Hands - {handSummary(tracking)} + {handSummary(tracking, handDevices)} - - + +
); diff --git a/examples/egocap/frontend/src/HandView.test.tsx b/examples/egocap/frontend/src/HandView.test.tsx index 8c784509ff..e33d3a4724 100644 --- a/examples/egocap/frontend/src/HandView.test.tsx +++ b/examples/egocap/frontend/src/HandView.test.tsx @@ -93,6 +93,24 @@ describe("HandView with a glove that sends nothing", () => { } }); + it("draws no hand for a glove that delivers nothing, though the sample still carries its last pose", () => { + // What the capture session goes on sending for a glove that was switched off: a whole hand, every joint valid. + const devices = { left: { delivering: false, state: "disconnected" }, right: { delivering: true, state: "connected" } }; + const { container } = render(); + expect(spoken()).toBe("Both hands as the gloves report them. The left glove sends nothing; right hand tracked."); + expect(captions(container)).toEqual(["✗No data from the left glove", "Right hand"]); + expect(container.querySelector(".hand-view-hand--left")).toBeNull(); + expect(container.querySelectorAll(".hand-view-outline")).toHaveLength(1); + expect(container.querySelector(".hand-view-hand--right")).not.toBeNull(); + }); + + it("draws the hand of a glove that still delivers while degraded, and of a hand no device is reported for", () => { + const devices = { left: { delivering: true, state: "degraded" }, right: null }; + const { container } = render(); + expect(captions(container)).toEqual(["Left hand", "Right hand"]); + expect(container.querySelector(".hand-view-outline")).toBeNull(); + }); + it("says the same of the right glove", () => { const { container } = mount(handSample(LEFT, { ...RIGHT, present: false })); expect(spoken()).toBe("Both hands as the gloves report them. Left hand tracked; the right glove sends nothing."); diff --git a/examples/egocap/frontend/src/HandView.tsx b/examples/egocap/frontend/src/HandView.tsx index c11023070f..62f89ec937 100644 --- a/examples/egocap/frontend/src/HandView.tsx +++ b/examples/egocap/frontend/src/HandView.tsx @@ -13,6 +13,7 @@ */ import { memo, useEffect, useRef, useState } from "react"; import { currentTracking } from "./CaptureTree"; +import { NO_HAND_DEVICES, type HandDevice, type HandDevices } from "./deviceHealth"; import { DRAWN_JOINTS, fitScale, flattenHand, handBones, smoothReach, type FlatPoint, type HandCell, type HandSide } from "./handProjection"; import { HAND_WRIST, handJointIndex } from "./handJoints"; import type { HandDisplay } from "./trackingDecoder"; @@ -100,10 +101,13 @@ function fmt(value: number): string { return value.toFixed(1); } -/** Works out what one half shows from the hand in the current sample. */ -function drawHand(hand: HandDisplay | null, side: HandSide, previousReach: number | null): DrawnHand { +/** Works out what one half shows from the hand in the current sample and from the hand's tracking device, which + * is null when the capture status reports none. */ +function drawHand(hand: HandDisplay | null, side: HandSide, previousReach: number | null, device: HandDevice | null): DrawnHand { // A hand the sample marks absent can still carry leftover joint values; they are not a measurement. if (hand === null || !hand.present) return { state: "silent", points: null, reach: null }; + // Nor is the pose the capture session goes on sending for a glove that delivers nothing. + if (device !== null && !device.delivering) return { state: "silent", points: null, reach: null }; const flat = flattenHand(hand.joints, side); if (flat === null) return { state: "unusable", points: null, reach: null }; const reach = smoothReach(previousReach, flat.reach); @@ -177,11 +181,13 @@ export interface HandViewProps { trackingSample: AcceptedTracking | null; /** Switches the hand view off, exactly as the setting in Settings does. */ onHide: () => void; + /** The hands' tracking devices by the capture status; a hand whose device does not deliver is not drawn. */ + handDevices?: HandDevices; } /** The hand view panel. It redraws when a new tracking sample arrives and at no other time, apart from a slow * tick that lets a sample which has gone stale stop being shown as a live hand. */ -export const HandView = memo(function HandView({ trackingSample, onHide }: HandViewProps) { +export const HandView = memo(function HandView({ trackingSample, onHide, handDevices = NO_HAND_DEVICES }: HandViewProps) { const [, forceTick] = useState(0); useEffect(() => { // Staleness is a matter of elapsed time: without this, the last pose of a stream that stopped would stay up. @@ -193,8 +199,8 @@ export const HandView = memo(function HandView({ trackingSample, onHide }: HandV // committed after the render: a state update here would draw every sample twice. const reaches = useRef>({ left: null, right: null }); const tracking = currentTracking(trackingSample, performance.now()); - const left = drawHand(tracking?.handLeft ?? null, "left", reaches.current.left); - const right = drawHand(tracking?.handRight ?? null, "right", reaches.current.right); + const left = drawHand(tracking?.handLeft ?? null, "left", reaches.current.left, handDevices.left); + const right = drawHand(tracking?.handRight ?? null, "right", reaches.current.right, handDevices.right); useEffect(() => { reaches.current = { left: left.reach, right: right.reach }; }); diff --git a/examples/egocap/frontend/src/deviceHealth.test.ts b/examples/egocap/frontend/src/deviceHealth.test.ts index 6fa10d00a9..c26e23502d 100644 --- a/examples/egocap/frontend/src/deviceHealth.test.ts +++ b/examples/egocap/frontend/src/deviceHealth.test.ts @@ -4,9 +4,9 @@ /** The operator health chips: short names, tones, reasons only for problems, and a retained feed never looks healthy. */ import { describe, expect, it } from "vitest"; -import { DeviceState } from "./captureStatus"; +import { DeviceState, StatusReason } from "./captureStatus"; import type { CaptureStatusResponse } from "./captureStatus"; -import { chipsNeedingAttention, deriveHealthChips, deviceChipLabel, deviceTone, retainedTone } from "./deviceHealth"; +import { NO_HAND_DEVICES, chipsNeedingAttention, deriveHealthChips, deviceChipLabel, deviceTone, handDevices, retainedTone } from "./deviceHealth"; const device = (id: string, status: number, error = "", reason = 0) => ({ id, @@ -120,3 +120,36 @@ describe("tones", () => { expect(retainedTone("positive", true)).toBe("positive"); }); }); + +describe("handDevices", () => { + const hand = (side: string, status: number, reason = 0) => ({ ...device(`manus/hand/${side}`, status, "", reason), path: `/hand/${side}` }); + + it("finds each hand's device by the capture session's path and says whether it delivers", () => { + const found = handDevices(response([device("openxr/headset", DeviceState.CONNECTED), hand("left", DeviceState.DISCONNECTED, StatusReason.NO_HARDWARE_SIGNAL), hand("right", DeviceState.CONNECTED)], [])); + expect(found).toEqual({ left: { delivering: false, state: "disconnected" }, right: { delivering: true, state: "connected" } }); + }); + + it("takes a degraded glove to deliver only where the reason is a refused calibration file", () => { + const degraded = (reason: number) => handDevices(response([hand("left", DeviceState.DEGRADED, reason)], [])).left; + expect(degraded(StatusReason.CALIBRATION_FAILED)).toEqual({ delivering: true, state: "degraded" }); + // No current data, a device error, and a reason this page was told nothing about. + for (const reason of [StatusReason.NO_CURRENT_DATA, StatusReason.DEVICE_ERROR, StatusReason.NONE, 999]) { + expect(degraded(reason)).toEqual({ delivering: false, state: "degraded" }); + } + }); + + it("takes no other state to deliver", () => { + for (const status of [DeviceState.FAILED, DeviceState.UNAVAILABLE, DeviceState.INITIALIZING, DeviceState.UNKNOWN, DeviceState.DISABLED]) { + expect(handDevices(response([hand("right", status)], [])).right?.delivering).toBe(false); + } + }); + + it("knows nothing of a hand the capture status reports no device for, or before any status has arrived", () => { + expect(handDevices(response([device("openxr/headset", DeviceState.CONNECTED), hand("left", DeviceState.CONNECTED)], [])).right).toBeNull(); + expect(handDevices(null)).toEqual(NO_HAND_DEVICES); + // A device of another kind on a path that only looks alike is nobody's hand. + const both = { ...device("acme/hands", DeviceState.DISCONNECTED), path: "/hand/both" }; + const pathless = { ...device("acme/hand/left", DeviceState.DISCONNECTED), path: null }; + expect(handDevices(response([both, pathless], []))).toEqual(NO_HAND_DEVICES); + }); +}); diff --git a/examples/egocap/frontend/src/deviceHealth.ts b/examples/egocap/frontend/src/deviceHealth.ts index 307349346e..1b0e4fac0c 100644 --- a/examples/egocap/frontend/src/deviceHealth.ts +++ b/examples/egocap/frontend/src/deviceHealth.ts @@ -9,6 +9,7 @@ import { DeviceState, + StatusReason, deviceStateLabel, statusReasonLabel, type CameraStatus, @@ -65,6 +66,36 @@ export function deviceChipLabel(device: Pick return device.description || device.id; } +/** One hand's tracking device as the capture status has it. */ +export interface HandDevice { + /** Whether the device delivers its data now. A hand the tracking sample still carries is not a measurement + * while it does not: the capture session goes on sending the last pose it had. */ + delivering: boolean; + /** The device's state in words ("disconnected", "degraded"), for the line that says the hand is not delivered. */ + state: string; +} + +/** The device of each hand, or null for a hand the capture status reports no device for: its sample then stands + * by itself. */ +export type HandDevices = Record<"left" | "right", HandDevice | null>; + +/** What is known of the hands' devices before any capture status has arrived. */ +export const NO_HAND_DEVICES: HandDevices = { left: null, right: null }; + +/** The device of each hand and whether it delivers, by the rule the station checklist holds a required device to: + * connected, or degraded only because its calibration file was refused, under which a glove still streams. A hand + * is told by the capture session's path for its device (`/hand/left`), whatever provider reports it. */ +export function handDevices(response: CaptureStatusResponse | null): HandDevices { + const devices = response?.status?.devices ?? []; + const of = (side: "left" | "right"): HandDevice | null => { + const device = devices.find((d) => (d.path ?? "").replace(/^\/+|\/+$/g, "") === `hand/${side}`); + if (device === undefined) return null; + const delivering = device.status === DeviceState.CONNECTED || (device.status === DeviceState.DEGRADED && device.reason === StatusReason.CALIBRATION_FAILED); + return { delivering, state: deviceStateLabel(device.status).toLowerCase() }; + }; + return { left: of("left"), right: of("right") }; +} + /** The reason shown on a chip: nothing for a healthy device, otherwise its error text or its status reason. */ function detailOf(tone: Tone, error: string, reason: DeviceStatus["reason"]): string | null { if (tone === "positive") return null; From e85af980d947cc292b784da39ad09b90c1395b6f Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 09:40:04 -0800 Subject: [PATCH 07/24] egocap: the session details name the cameras that arrive over LiveKit The side panel's session details list the cameras of the capture status, which holds the capture server's own cameras only. At a station whose cameras all arrive over LiveKit the list was empty and read "No cameras selected." beside three live camera tiles. The details now count and name the cameras the started session offers over LiveKit and say where their state is shown: on the camera tiles and in the Devices checklist. "No cameras selected." is said only of a session with no camera of either kind. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- examples/egocap/frontend/README.md | 4 ++- examples/egocap/frontend/src/App.test.tsx | 42 +++++++++++++++++++++-- examples/egocap/frontend/src/App.tsx | 40 +++++++++++++++------ 3 files changed, 73 insertions(+), 13 deletions(-) diff --git a/examples/egocap/frontend/README.md b/examples/egocap/frontend/README.md index a0a3622069..13dc63dac3 100644 --- a/examples/egocap/frontend/README.md +++ b/examples/egocap/frontend/README.md @@ -469,7 +469,9 @@ The page is built for an operator mid-take: the cameras fill it, and everything - **Side panel (right).** Open until the operator closes it: the hand view on top while it is switched on, then the 3D tracking view, then the raw tracking tables and session details (Details scrolls inside itself, so it and the 3D view are never pushed off the screen; with the hand view above them a short window has no room for all three, and - the side panel scrolls to Details instead). + the side panel scrolls to Details instead). The session details list the capture server's own cameras with + their state; cameras that arrive over LiveKit are not in the capture status, so they are counted and named in + one line that points at the camera tiles and the Devices checklist for their state. - **Closing the side panel.** The button at the top of the divider, *Close side panel*, takes the panel and the divider out of the page, and the cameras, the status bar and the controls take the full width. The same button stays as a slim tab down the right edge of the page, now *Open side panel* (`SidebarToggle.tsx`); focus stays on diff --git a/examples/egocap/frontend/src/App.test.tsx b/examples/egocap/frontend/src/App.test.tsx index 8a32b966ba..9378d299c6 100644 --- a/examples/egocap/frontend/src/App.test.tsx +++ b/examples/egocap/frontend/src/App.test.tsx @@ -13,11 +13,11 @@ import type { ReactElement } from "react"; import { afterEach, describe, expect, it, vi, type Mock } from "vitest"; import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react"; -import App from "./App"; +import App, { SourceStatusList, liveKitCamerasLine } from "./App"; import { OPERATOR_SETTINGS_FIXTURE, SETTINGS_FIXTURE } from "./settingsTestDoubles"; import { useCaptureSession, type AcceptedTracking, type CaptureSessionState } from "./useCaptureSession"; import { Axes, HandJointOrder, PositionUnit, QuaternionOrder, type PreviewSnapshot } from "./captureProtocol"; -import { DeviceState, StatusReason } from "./captureStatus"; +import { DeviceState, StatusReason, type CaptureStatusResponse } from "./captureStatus"; import { handDisplay, syntheticHand } from "./handTestDoubles"; import type { ControllerDisplay, DecodedTracking, HandDisplay } from "./trackingDecoder"; @@ -495,6 +495,44 @@ describe("a hand whose glove delivers nothing", () => { }); }); +describe("the cameras of the session details", () => { + const cameraStatus = (name: string) => ({ name, stream_id: 1, status: DeviceState.CONNECTED, reason: StatusReason.NONE, error: "", intrinsics: null }); + const statusWith = (cameras: unknown[]) => ({ status: { providers: [], devices: [], cameras } }) as unknown as CaptureStatusResponse; + const camerasSection = () => screen.getByRole("heading", { name: "Cameras" }).closest("section") as HTMLElement; + const overLiveKit = "3 cameras arrive over LiveKit: head, left_wrist, right_wrist. Their state is on the camera tiles and in the Devices checklist."; + + it("names the cameras that arrive over LiveKit and never says that none is selected beside them", () => { + render(); + expect(within(camerasSection()).getByText(overLiveKit)).toBeTruthy(); + expect(screen.queryByText("No cameras selected.")).toBeNull(); + }); + + it("lists the capture server's cameras and the LiveKit ones together", () => { + render(); + expect(within(camerasSection()).getByText("cam_head")).toBeTruthy(); + expect(within(camerasSection()).getByText("1 camera arrives over LiveKit: left_wrist. Their state is on the camera tiles and in the Devices checklist.")).toBeTruthy(); + expect(screen.queryByText("No cameras selected.")).toBeNull(); + }); + + it("says no camera is selected only of a session with no camera of either kind", () => { + render(); + expect(within(camerasSection()).getByText("No cameras selected.")).toBeTruthy(); + expect(liveKitCamerasLine([])).toBeNull(); + }); + + it("is given the started session's LiveKit cameras by the page", () => { + const stream = (stream_id: number, name: string) => ({ kind: "livekit_camera", stream_id, name, url: "wss://lk", room: "r", publisher: "bridge", track: name, timestamp_basis: 4 }); + const streams = [stream(16, "head"), stream(17, "left_wrist"), stream(18, "right_wrist")] as never; + // The preview of these cameras is not what is looked at here: it is refused its token and stays out of the way. + vi.stubGlobal("fetch", vi.fn(async () => ({ status: 503, ok: false, json: async () => ({}) }))); + mockState(makeState({ phase: "connected", snapshot: makeSnapshot({ started: { session_id: "s1", running: true, mode: 0, streams } }) })); + render(); + // The camera grid has a heading of the same name; the details' own list is the one read. + expect(within(document.querySelector(".source-groups") as HTMLElement).getByText(overLiveKit)).toBeTruthy(); + expect(within(document.querySelector(".source-groups") as HTMLElement).queryByText("No cameras selected.")).toBeNull(); + }); +}); + describe("CaptureTree diagnostic vs never-had-data", () => { it("shows the generic empty label when no tracking sample has ever arrived", () => { mockState(makeState({ snapshot: makeSnapshot({ tracking: null }) })); diff --git a/examples/egocap/frontend/src/App.tsx b/examples/egocap/frontend/src/App.tsx index 4f10c060ce..15fbffd4d5 100644 --- a/examples/egocap/frontend/src/App.tsx +++ b/examples/egocap/frontend/src/App.tsx @@ -4,7 +4,7 @@ import { useCallback, useEffect, useId, useMemo, useReducer, useRef, useState, type CSSProperties } from "react"; import { useCaptureSession, type ConnectionPhase } from "./useCaptureSession"; -import type { PreviewSnapshot } from "./captureProtocol"; +import { liveKitStreams, type PreviewSnapshot } from "./captureProtocol"; import { CaptureMode, CaptureStatusType, @@ -357,20 +357,31 @@ function SourceRow({ ); } -/** `freshnessLabel` is appended to each group header (e.g. "Tracking — - * Last known") rather than duplicated per row -- the staleness applies to - * the whole snapshot, not individual entries within it. */ -function SourceStatusList({ +/** What the session details say of the cameras that arrive over LiveKit, which the capture status does not list: + * how many, their names, and where their state is shown. Null when the session offers none. */ +export function liveKitCamerasLine(names: readonly string[]): string | null { + if (names.length === 0) return null; + const arrive = names.length === 1 ? "1 camera arrives" : `${names.length} cameras arrive`; + return `${arrive} over LiveKit: ${names.join(", ")}. Their state is on the camera tiles and in the Devices checklist.`; +} + +/** The tracking devices and cameras of the session details. `freshnessLabel` is appended to each group header + * (e.g. "Tracking — Last known") rather than duplicated per row -- the staleness applies to the whole snapshot, + * not individual entries within it. `liveKitCameras` names the cameras the session offers over LiveKit. */ +export function SourceStatusList({ response, live, freshnessLabel, + liveKitCameras = [], }: { response: CaptureStatusResponse | null; live: boolean; freshnessLabel: string | null; + liveKitCameras?: readonly string[]; }) { const devices = response?.status?.devices ?? []; const cameras = response?.status?.cameras ?? []; + const liveKitLine = liveKitCamerasLine(liveKitCameras); const suffix = freshnessLabel !== null ? ` — ${freshnessLabel}` : ""; return (
@@ -388,15 +399,16 @@ function SourceStatusList({

Cameras{suffix}

- {cameras.length === 0 ? ( -

No cameras selected.

- ) : ( + {/* Said only of a session with no camera of either kind: LiveKit cameras are not in the capture status. */} + {cameras.length === 0 && liveKitLine === null &&

No cameras selected.

} + {cameras.length > 0 && (
    {cameras.map((c) => ( ))}
)} + {liveKitLine !== null &&

{liveKitLine}

}
); @@ -409,10 +421,13 @@ function SessionDetails({ response, live, freshnessLabel, + liveKitCameras, }: { response: CaptureStatusResponse | null; live: boolean; freshnessLabel: string | null; + /** The names of the cameras the session offers over LiveKit. */ + liveKitCameras: readonly string[]; }) { const detailsId = useId(); const providers = response?.status?.providers ?? []; @@ -457,7 +472,7 @@ function SessionDetails({ )} - +
Technical details
{JSON.stringify(response, null, 2)}
@@ -814,7 +829,12 @@ export default function App() { diagnostic={snapshot?.tracking?.diagnostic ?? null} handDevices={hands} /> - + stream.name)} + /> )} From 6e2672b4eedd1cc0e4c6244d5a6cc9c184a92f0b Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 09:54:28 -0800 Subject: [PATCH 08/24] egocap: the launcher's stop runs to its end, says what is left, and a start refuses a taken port Stopping the launcher could leave its children running, and the sender on the Orin with them: the children are in sessions of their own, so only the launcher's own stop ends them, and that stop could be cut off. A Ctrl-C that arrived while a child was being killed raised out of it, and so did a write to a terminal that had gone away (output piped into a program that Ctrl-C ends first). The next start then failed half way up on a port still held, with the Orin's sender already running. The stop - Nothing ends it before every child was dealt with. The first Ctrl-C, SIGTERM or SIGHUP asks for the stop, once, also when two arrive together; a later one hurries it (the children still running are killed without their grace) and any further one changes nothing. - Each child, and what is left of its process group, is waited for. One that is still there is named with the command that ends it. - The Orin is asked to stop its sender in a session of its own, which a Ctrl-C at the terminal does not reach. The deploy tool's stop succeeds only when no sender is left, and the launcher says which it was. - A run that left something running exits with 1. The output - What the launcher and its helpers print is also written to launcher.log in the run directory, named in its first line, so the output need not be piped to be kept. Helpers write through the launcher, never to a terminal that went away. - A stream that refuses a write is given up on; the line is still logged and nothing is raised. The start - Before anything is deployed or started, a port the stack listens on that is already taken refuses the start: the backend's, CaptureServer's and, with a LiveKit server, LiveKit's two TCP ports and its UDP port; with a local mock sender, the profile's video port. The refusal names each port, whose it is and, where ss or lsof tells, the program that holds it. Every command line and file of a one-stream and a three-stream start is unchanged. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- examples/egocap/README.md | 16 +- .../egocap/tests/tools/test_start_system.py | 332 ++++++++++- .../tools/test_start_system_three_cameras.py | 8 +- examples/egocap/tools/start_system.py | 559 +++++++++++++++--- 4 files changed, 817 insertions(+), 98 deletions(-) diff --git a/examples/egocap/README.md b/examples/egocap/README.md index c4650f4d8f..2a09518898 100644 --- a/examples/egocap/README.md +++ b/examples/egocap/README.md @@ -362,7 +362,8 @@ says at its top when a station runs with the rule off or weakened. uv run python tools/start_system.py --orin user@orin --deploy-script PATH --livekit-server PATH --bridge PATH --open ``` -It prints the page URL and the recording control token. CaptureServer runs real acquisition, which needs a built +It prints the page URL and the recording control token, and writes what it and its helpers print to +`launcher.log` in its run directory, which its first line names. CaptureServer runs real acquisition, which needs a built IsaacCapture checkout (`ISAAC_ROOT`) and tracking hardware, and it opens only the cameras it is given with `--capture-camera NAME=DEVICE_ID`. The default station file (`--station-config`) is the shipped example, which requests three cameras, so the launcher refuses to start unless each one is given; use a station file whose @@ -388,6 +389,19 @@ is printed, and a failure leaves the preview up with capture times unavailable ( the SIPL backend the launcher also stops `nvargus-daemon` on the Orin before starting the sender, since it holds the cameras; it does not restart it. +**Stopping.** Ctrl-C once stops everything: the children last started first, each given its time to finish (the +backend closes a take that is being recorded), then the sender on the Orin. The stop is carried out to its end +whatever happens to the terminal. A second Ctrl-C does not abort it: it hurries it, so the children still running +are killed at once without their time to finish; any further one changes nothing. The launcher waits for each +child to be gone, asks the Orin's deploy tool to stop the sender and says `the Orin sender is stopped` once that is +confirmed. Whatever is not known to have stopped is named with the command that ends it, and the exit status is +then 1: a child by its process group, the sender with the deploy tool's `check` and `stop`. + +**Before it starts anything** the launcher refuses a start while a port the stack listens on is taken: the +backend's (`--backend-port`, 8010), CaptureServer's (8082) and, with a LiveKit server, LiveKit's (7880 and 7881 over +TCP, 7882 over UDP). The refusal names each port, whose it is and, where the system tells, the program that holds +it, which is usually a program an earlier run left behind. + The page needs the frontend built once (`cd frontend && npm install && npm run build`); the launcher refuses to start without `frontend/dist`. For the default receiver, the launcher runs the receiver's `setup.sh` (venv, requirements, native decoder) when the venv or decoder is missing and the camera chain starts (`--orin`, or `--mock` with the diff --git a/examples/egocap/tests/tools/test_start_system.py b/examples/egocap/tests/tools/test_start_system.py index 769d8406a9..c6e51a4b57 100644 --- a/examples/egocap/tests/tools/test_start_system.py +++ b/examples/egocap/tests/tools/test_start_system.py @@ -14,6 +14,7 @@ import shlex import signal import stat +import subprocess import sys import threading import time @@ -183,8 +184,9 @@ def record_start(self, name, command, *_, **__): monkeypatch.setattr(ss, "FRONTEND_INDEX", index) monkeypatch.setattr(ss.Stack, "start", record_start) monkeypatch.setattr(ss.Stack, "wait_until", lambda *_, **__: None) - monkeypatch.setattr(ss.Stack, "stop_all", lambda *_: None) - monkeypatch.setattr(ss.subprocess, "run", lambda *_, **__: None) + monkeypatch.setattr(ss.Stack, "stop_all", lambda *_: []) + monkeypatch.setattr(ss, "port_taken", lambda kind, number: False) + monkeypatch.setattr(ss.subprocess, "run", lambda *_, **__: SimpleNamespace(returncode=0)) argv = ["--orin", "user@192.0.2.5", "--deploy-script", "x", "--bridge", "b", "--livekit-server", "l"] argv += ["--timesync-tool", str(timesync), "--host-lan-ip", "192.0.2.2", *CAMERA_ARGS] assert ss.main(argv) == 1 @@ -556,8 +558,10 @@ def interrupt(_seconds): monkeypatch.setattr(ss, "FRONTEND_INDEX", frontend) monkeypatch.setattr(ss.Stack, "start", fake_start) monkeypatch.setattr(ss.Stack, "wait_until", lambda *_, **__: None) - # The fake children are not real processes, so there is nothing to signal. - monkeypatch.setattr(ss.Stack, "stop_all", lambda self: None) + # The fake children are not real processes, so there is nothing to signal and nothing is left running. + monkeypatch.setattr(ss.Stack, "stop_all", lambda self: []) + # Whatever this machine happens to run on the stack's ports does not decide these tests. + monkeypatch.setattr(ss, "port_taken", lambda kind, number: False) monkeypatch.setattr(ss, "ensure_receiver_environment", lambda: None) # Every deploy, stop and timesync step is recorded and reports success. monkeypatch.setattr( @@ -764,7 +768,8 @@ def run(command, **kwargs): return real_run(command, **kwargs) monkeypatch.setattr(ss.subprocess, "run", run) - assert ss.main([*ORIN_ARGV, *CAMERA_ARGS]) == 0 + # Nothing is raised, and the run is not called a clean one: its sender may still hold the cameras. + assert ss.main([*ORIN_ARGV, *CAMERA_ARGS]) == 1 assert "could not confirm that the Orin sender stopped" in capsys.readouterr().err @@ -847,9 +852,16 @@ def test_main_installs_the_stop_handlers_and_starts_the_backend_leader_only(reco mock_sender.write_text("") argv = ["--mock", "--bridge", "b", "--livekit-server", "l", "--mock-sender", str(mock_sender)] assert ss.main(argv) == 0 - handlers = dict(recorded_main.installed) - assert handlers[signal.SIGTERM] is ss._raise_interrupt - assert handlers[signal.SIGHUP] is ss._raise_interrupt + # While the stack is up Ctrl-C and the signals that mean stop take one path, once; the stop then sets its own + # handlers, under which the same signals only hurry it. + first = {} + for sig, handler in recorded_main.installed: + first.setdefault(sig, handler) + request = first[signal.SIGINT] + assert isinstance(request, ss.StopRequest) + assert first[signal.SIGTERM] is request and first[signal.SIGHUP] is request + during_the_stop = [sig for sig, handler in recorded_main.installed if handler is not request] + assert set(during_the_stop) == {signal.SIGINT, signal.SIGTERM, signal.SIGHUP} leader_only = {c.name: c.leader_only for c in recorded_main.children} assert leader_only["backend"] is True @@ -1028,7 +1040,8 @@ class _Done: monkeypatch.setattr(ss, "FRONTEND_INDEX", index) monkeypatch.setattr(ss.Stack, "start", fake_start) monkeypatch.setattr(ss.Stack, "wait_until", lambda *_, **__: None) - monkeypatch.setattr(ss.Stack, "stop_all", lambda *_: None) + monkeypatch.setattr(ss.Stack, "stop_all", lambda *_: []) + monkeypatch.setattr(ss, "port_taken", lambda kind, number: False) monkeypatch.setattr(ss.subprocess, "run", lambda cmd, **__: runs.append(list(cmd)) or _Done()) monkeypatch.setattr(ss.time, "sleep", lambda *_: None) argv = ["--orin", "user@192.0.2.5", "--deploy-script", "x", "--bridge", "b", "--livekit-server", "l"] @@ -2119,3 +2132,304 @@ def test_a_run_started_without_rectification_says_so_to_the_reader_of_its_stream state = read_streams_state(recorded_main.workdir / ss.STREAMS_STATE_FILE) # Told apart from a plan that asked for nothing: started the same way again, the saved choice stays unused. assert state.no_rectify is True and not state.rectified("head") and state.camera("head").divisor == 2 + + +# --- the stop completes whatever happens to the terminal, and the start refuses a port that is taken ----------- + +# A launcher of its own in a child process: three children, then the launcher's own way down on Ctrl-C. It writes +# its children's pids for the test, and says so on its output like any launcher line. +STOP_DRIVER = """ +import signal, sys, time +from pathlib import Path +sys.path.insert(0, sys.argv[1]) +import start_system as ss +# Ctrl-C as a terminal gives it, also where the tests themselves were started with it ignored (in the background +# of a script), which a child would inherit. +signal.signal(signal.SIGINT, signal.default_int_handler) +work, pids, stubborn, grace = Path(sys.argv[2]), Path(sys.argv[3]), sys.argv[4], float(sys.argv[5]) +stack = ss.Stack(work) +log = ss.RunLog(work / ss.LAUNCHER_LOG) +log.open() +for name in "abc": + stack.start(name, [sys.executable, "-c", stubborn, str(work / f"{name}.ready")], grace_s=grace) +while not all((work / f"{name}.ready").exists() for name in "abc"): + time.sleep(0.02) +pids.write_text(" ".join(str(child.process.pid) for child in stack.children)) +try: + time.sleep(60) +except KeyboardInterrupt: + pass +# The launcher's own way down. A Ctrl-C between its return and the next line here is this script's to survive, +# not the launcher's: the stop is asked again, and finds everything gone. +left = [] +while not left: + try: + left.append(ss.shut_down(stack, None)) + signal.signal(signal.SIGINT, signal.SIG_IGN) + except KeyboardInterrupt: + left.clear() +log.close() +(work / "left").write_text(repr(left[0])) +ss.leave(1 if left[0] else 0) +""" + + +def _stop_driver(tmp_path: Path, grace: float, **popen): + """A launcher in a child process with three children that ignore the polite signal; (process, their pids).""" + pids = tmp_path / "pids" + driver = subprocess.Popen( + [sys.executable, "-c", STOP_DRIVER, str(EGOCAP / "tools"), str(tmp_path), str(pids), STUBBORN_CHILD] + + [str(grace)], + env={**os.environ, "PYTHONPATH": os.pathsep.join(sys.path)}, + **popen, + ) + _await_files([pids]) + return driver, [int(pid) for pid in pids.read_text().split()] + + +def _kill_leftovers(pids: list[int]) -> None: + for pid in pids: + try: + os.killpg(pid, signal.SIGKILL) + except ProcessLookupError: + pass + + +def test_a_stop_whose_terminal_went_away_mid_stop_leaves_no_child_alive(tmp_path: Path): + # Output and errors into one pipe, as under `2>&1 | tee`; the reader goes away as Ctrl-C arrives. + driver, pids = _stop_driver(tmp_path, 0.3, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + try: + driver.stdout.close() + driver.send_signal(signal.SIGINT) + assert driver.wait(timeout=30) == 0 + for pid in pids: + _assert_pid_gone(pid) + assert (tmp_path / "left").read_text() == "[]" + # What the terminal no longer took is in the launcher's own log, the stop's lines included. + said = (tmp_path / ss.LAUNCHER_LOG).read_text() + assert "c did not exit within 0 s; killing it" in said + assert "every program this run started has stopped" in said + finally: + _kill_leftovers(pids) + driver.kill() + driver.wait() + + +def test_ctrl_c_pressed_again_and_again_during_the_stop_only_hurries_it(tmp_path: Path): + driver, pids = _stop_driver(tmp_path, 30.0, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + try: + started = time.monotonic() + # The first asks for the stop; the rest land wherever the stop happens to be. + for _ in range(40): + if driver.poll() is not None: + break + driver.send_signal(signal.SIGINT) + time.sleep(0.02) + assert driver.wait(timeout=30) == 0 + # Hurried: nobody was given the thirty seconds a child may take to leave by itself. + assert time.monotonic() - started < 15 + for pid in pids: + _assert_pid_gone(pid) + assert (tmp_path / "left").read_text() == "[]" + finally: + _kill_leftovers(pids) + driver.kill() + driver.wait() + + +def test_a_ctrl_c_that_lands_while_a_child_is_being_killed_does_not_end_the_stop( + stack, tmp_path: Path, monkeypatch +): + ready = [_stubborn(stack, tmp_path, name, grace_s=30) for name in "abc"] + _await_files(ready) + last = stack.children[2].process + real_wait = last.wait + calls = [] + + def interrupted_wait(*args, **kwargs): + calls.append(1) + # Once while its grace is waited out, and once more inside the kill that follows. + if len(calls) <= 2: + raise KeyboardInterrupt + return real_wait(*args, **kwargs) + + monkeypatch.setattr(last, "wait", interrupted_wait) + assert stack.stop_all() == [] + assert [c.process.returncode for c in stack.children] == [-signal.SIGKILL] * 3 + + +def test_a_child_that_outlives_the_stop_is_reported_with_how_to_end_it(stack, tmp_path: Path, monkeypatch, capsys): + ready = [_stubborn(stack, tmp_path, "survivor", grace_s=0.2), _polite(stack, tmp_path, "polite")] + _await_files(ready) + survivor = stack.children[0] + group = survivor.process.pid + real_killpg = os.killpg + # Undone before the test ends, so that what it leaves running can be ended after it. + with monkeypatch.context() as held: + # Nothing this launcher sends ends it: a process it may not signal, or one stuck in the kernel. + held.setattr(ss.os, "killpg", lambda pgid, sig: None if pgid == group and sig else real_killpg(pgid, sig)) + held.setattr(ss, "KILL_WAIT_S", 0.3) + left = stack.stop_all() + assert [child.name for child in left] == ["survivor"] + assert ss.shut_down(stack, None) == [f"survivor (process group {group})"] + said = capsys.readouterr() + assert f"still running after the stop: survivor (process group {group})" in said.err + assert f"kill -KILL -- -{group}" in said.err + # Not said of a stop that left something behind. + assert "every program this run started has stopped" not in said.out + + +def test_the_first_signal_that_means_stop_takes_the_ctrl_c_path_and_one_that_follows_at_once_raises_nothing(): + request = ss.StopRequest() + with pytest.raises(KeyboardInterrupt): + request(signal.SIGINT, None) + # The same Ctrl-C passed on by a wrapper, or a second key press before the stop has set its own handlers. + request(signal.SIGINT, None) + request(signal.SIGTERM, None) + assert request.asked + + +def test_the_launcher_says_first_where_its_log_is_and_the_log_holds_what_it_and_its_helpers_print( + recorded_main, capsys +): + assert ss.main([*ORIN_ARGV, *CAMERA_ARGS]) == 0 + log = recorded_main.workdir / ss.LAUNCHER_LOG + printed = capsys.readouterr() + assert printed.out.splitlines()[0] == f"launcher log: {log} (everything printed here is written there too)" + written = log.read_text() + # Every line of its own, on either stream. + for line in (printed.out + printed.err).splitlines(): + assert line in written + assert "Ctrl-C stops everything." in written + + +def test_a_helpers_output_reaches_the_log_and_the_terminal_through_the_launcher(tmp_path: Path, capsys): + log = ss.RunLog(tmp_path / ss.LAUNCHER_LOG) + with log: + print("the launcher's own line") + subprocess.run( + [sys.executable, "-c", "import sys; print('said by a helper'); print('its error', file=sys.stderr)"], + check=True, + **log.for_helper(), + ) + written = (tmp_path / ss.LAUNCHER_LOG).read_text() + assert written.index("the launcher's own line") < written.index("said by a helper") + assert "its error" in written + printed = capsys.readouterr().out + assert "said by a helper" in printed and "its error" in printed + # Put back as it was found. + assert not isinstance(sys.stdout, ss._Passed) + + +def test_the_orin_senders_stop_is_confirmed_and_said_and_a_stop_that_is_not_confirmed_fails_the_run( + recorded_main, monkeypatch, capsys +): + assert ss.main([*ORIN_ARGV, *CAMERA_ARGS]) == 0 + assert "the Orin sender is stopped" in capsys.readouterr().out + stops: list[int] = [] + + def run(command, **kwargs): + recorded_main.deploys.append(list(command)) + if command[-1] == "stop": + stops.append(1) + # The deploy tool's stop on exit says the sender was still running when it gave up. + return SimpleNamespace(returncode=1 if command[-1] == "stop" and len(stops) == 2 else 0) + + monkeypatch.setattr(ss.subprocess, "run", run) + assert ss.main([*ORIN_ARGV, *CAMERA_ARGS]) == 1 + said = capsys.readouterr() + assert "the Orin sender is stopped" not in said.out + assert "could not confirm that the Orin sender stopped" in said.err + assert "x user@192.0.2.10 check" in said.err and "x user@192.0.2.10 stop" in said.err + + +# The launcher's own look at a port, kept from before any fixture stands in for it. +REAL_PORT_TAKEN = ss.port_taken + + +def _holder(tmp_path: Path, kind: str) -> tuple[subprocess.Popen, int]: + """A real process that holds a port of this machine until it is killed; (process, port).""" + told = tmp_path / f"{kind}.port" + program = ( + "import socket, sys, time\n" + "s = socket.socket(socket.AF_INET, socket.SOCK_STREAM if sys.argv[1] == 'tcp' else socket.SOCK_DGRAM)\n" + "s.bind(('127.0.0.1', 0))\n" + "if sys.argv[1] == 'tcp': s.listen()\n" + "open(sys.argv[2] + '.part', 'w').write(str(s.getsockname()[1]))\n" + "__import__('os').replace(sys.argv[2] + '.part', sys.argv[2])\n" + "time.sleep(60)\n" + ) + process = subprocess.Popen([sys.executable, "-c", program, kind, str(told)]) + _await_files([told]) + return process, int(told.read_text()) + + +@pytest.mark.parametrize("kind", ["tcp", "udp"]) +def test_a_port_another_process_holds_is_taken_and_free_again_once_that_process_is_gone(tmp_path: Path, kind): + process, port = _holder(tmp_path, kind) + try: + assert REAL_PORT_TAKEN(kind, port) + holder = ss.port_holder(kind, port) + # Named where this system has a tool that tells: then it is that process and no other. + assert holder is None or f"pid {process.pid}" in holder + finally: + process.kill() + process.wait() + assert not REAL_PORT_TAKEN(kind, port) + assert ss.port_holder(kind, port) is None + + +@pytest.fixture +def held_port(tmp_path: Path): + """A TCP port of this machine held by a real process for the length of a test; (process, port).""" + process, port = _holder(tmp_path, "tcp") + yield process, port + process.kill() + process.wait() + + +# Asked for before ``recorded_main``, which stops every sleep of the test that uses it. +def test_a_port_the_stack_needs_that_is_taken_refuses_the_start_before_anything_is_deployed_or_started( + held_port, recorded_main, monkeypatch, capsys +): + process, port = held_port + # The launcher's own look at the port and at who holds it. Only the backend's port is this test's: whatever + # else this machine runs on the stack's other ports does not decide it. + monkeypatch.setattr(ss, "port_taken", lambda kind, number: number == port and REAL_PORT_TAKEN(kind, number)) + assert ss.main([*ORIN_ARGV, *CAMERA_ARGS, "--backend-port", str(port)]) == 1 + said = capsys.readouterr().err + assert said.startswith(f"error: port {port} (the backend's, TCP) is already in use") + assert said.endswith( + ". An earlier run may still be up: stop that program, or choose another port with --backend-port, then " + "start again.\n" + ) + # Named where this system has a tool that tells; otherwise the commands that name it are given. + assert f"(pid {process.pid})" in said or f"lsof -nP -iTCP:{port}" in said + # Nothing was deployed, asked of the Orin or started. + assert recorded_main.children == [] and recorded_main.deploys == [] + + +def test_every_taken_port_is_named_with_whose_it_is_and_one_nobody_can_name_says_how_to_find_out(monkeypatch): + taken = {("tcp", 7880), ("udp", 7882)} + monkeypatch.setattr(ss, "port_taken", lambda kind, number: (kind, number) in taken) + monkeypatch.setattr(ss, "port_holder", lambda kind, _number: {"tcp": "livekit-server (pid 41)"}.get(kind)) + needed = ss.needed_ports(backend_port=8010, livekit=True, mock_sender_port=None) + assert [(port.number, port.kind) for port in needed] == [ + (8010, "tcp"), + (8082, "tcp"), + (7880, "tcp"), + (7881, "tcp"), + (7882, "udp"), + ] + with pytest.raises(ss.StartupError) as refused: + ss.refuse_taken_ports(needed) + assert str(refused.value) == ( + "port 7880 (LiveKit's, TCP) is already in use by livekit-server (pid 41); port 7882 (LiveKit's, UDP) is " + "already in use (`ss -lunp` or `lsof -nP -iUDP:7882` names the program). An earlier run may still be up: " + "stop those programs, then start again." + ) + # A start without the camera chain needs no LiveKit port; a mock sender listens on the profile's port here. + without = ss.needed_ports(backend_port=9000, livekit=False, mock_sender_port=5000) + assert [(port.number, port.kind) for port in without] == [(9000, "tcp"), (8082, "tcp"), (5000, "tcp")] + taken.clear() + ss.refuse_taken_ports(needed) diff --git a/examples/egocap/tests/tools/test_start_system_three_cameras.py b/examples/egocap/tests/tools/test_start_system_three_cameras.py index 245059a2ff..718ff1f649 100644 --- a/examples/egocap/tests/tools/test_start_system_three_cameras.py +++ b/examples/egocap/tests/tools/test_start_system_three_cameras.py @@ -1417,9 +1417,11 @@ def test_a_one_stream_start_writes_the_files_and_says_the_lines_it_did_before_th profile = yaml.safe_load(ss.DEFAULT_SENDER_CONFIG.read_text()) assert (workdir / "sender.yaml").read_text() == yaml.safe_dump(profile, sort_keys=False) out = capsys.readouterr().out.splitlines() - assert out[0] == "stream 'head': published as received; no rectification is switched on for it" - assert out[1] == f"sender config {ss.DEFAULT_SENDER_CONFIG}: 30 fps, 4 Mbit/s, release egocap-start" - assert out[2].startswith("the Orin sender stops after 3600 s (about ") + # Where the launcher's own log is comes first; what it says of the start follows as it always did. + assert out[0] == f"launcher log: {workdir / ss.LAUNCHER_LOG} (everything printed here is written there too)" + assert out[1] == "stream 'head': published as received; no rectification is switched on for it" + assert out[2] == f"sender config {ss.DEFAULT_SENDER_CONFIG}: 30 fps, 4 Mbit/s, release egocap-start" + assert out[3].startswith("the Orin sender stops after 3600 s (about ") # Nothing a several-stream start adds: no line for the stream's role and track. assert not any(line.startswith("stream 'head': ego") for line in out) diff --git a/examples/egocap/tools/start_system.py b/examples/egocap/tools/start_system.py index b2489339c4..16403b32a5 100644 --- a/examples/egocap/tools/start_system.py +++ b/examples/egocap/tools/start_system.py @@ -15,6 +15,13 @@ children are stopped, last started first, when this script ends on Ctrl-C, on SIGTERM or after an error. The Orin sender runs for ``--seconds``; when it ends the whole stack is stopped. +The stop is carried out to its end whatever happens to the terminal and whatever is pressed: a second Ctrl-C +only hurries it (the children still running are killed without their grace). Each child is waited for, the Orin +is asked to stop its sender, and anything not known to have stopped is named with the command that ends it; the +exit status is then 1. What the launcher and its helpers print is also written to ``launcher.log`` in the run +directory, named in its first line. A start is refused, before anything is deployed or started, while a port +the stack listens on is already taken. + The sender settings come from the checked-in profile ``configs/default-camera-settings.yaml`` (see CAMERA_SETTINGS.md). CaptureServer runs real acquisition (a built IsaacCapture checkout and tracking hardware) unless ``--mock`` gives it synthetic tracking and cameras. ``--mock`` also replaces the Orin sender with a local @@ -45,24 +52,28 @@ import argparse import base64 +import codecs import contextlib +import errno import hashlib import hmac import ipaddress import json import os +import re import shlex import signal import socket import subprocess import sys import tempfile +import threading import time import webbrowser -from collections.abc import Mapping, Sequence +from collections.abc import Callable, Iterator, Mapping, Sequence from dataclasses import dataclass from pathlib import Path -from typing import Any +from typing import Any, NoReturn, TextIO import yaml @@ -122,6 +133,16 @@ BACKEND_GRACE_S = 90.0 # Signals that mean "stop the stack"; while it is stopping they mean "stop faster". STOP_SIGNALS = tuple(sig for sig in (signal.SIGTERM, getattr(signal, "SIGHUP", None)) if sig is not None) +# Seconds a killed child, and whatever is left of its process group, is given to be gone before it is reported. +KILL_WAIT_S = 5.0 +# The launcher's own log in the run directory: what it and its helpers print, so its output need not be piped. +LAUNCHER_LOG = "launcher.log" +# Where CaptureServer listens: its own default port, which the backend's default address names too. +CAPTURE_SERVER_PORT = 8082 +# What `livekit-server --dev` listens on: signalling, then media over TCP and over UDP. +LIVEKIT_PORT = 7880 +LIVEKIT_RTC_TCP_PORT = 7881 +LIVEKIT_RTC_UDP_PORT = 7882 # The mock sender sends no capture time, so the bridge stamps the frame-ready time on its own clock instead. MOCK_TIMESTAMP_BASIS = "monotonic_us" # The bridge shrinks a picture it does not rectify by this integer factor before encoding, so the descriptor @@ -938,6 +959,240 @@ def port_open(host: str, port: int) -> bool: return False +@dataclass(frozen=True) +class NeededPort: + """A port of this PC that a program of the stack listens on.""" + + number: int + #: ``tcp`` or ``udp``. + kind: str + #: Whose it is, as a refusal says it: "the backend's". + whose: str + #: The option that chooses another port, where there is one. + option: str | None = None + + +def needed_ports(backend_port: int, livekit: bool, mock_sender_port: int | None) -> list[NeededPort]: + """The ports of this PC the programs about to be started listen on. + + ``livekit`` is whether a LiveKit server is started; ``mock_sender_port`` is the profile's video port when a + local mock sender listens on it, None when the sender is on the Orin or there is none. + """ + ports = [ + NeededPort(backend_port, "tcp", "the backend's", "--backend-port"), + NeededPort(CAPTURE_SERVER_PORT, "tcp", "CaptureServer's"), + ] + if livekit: + ports += [ + NeededPort(LIVEKIT_PORT, "tcp", "LiveKit's"), + NeededPort(LIVEKIT_RTC_TCP_PORT, "tcp", "LiveKit's"), + NeededPort(LIVEKIT_RTC_UDP_PORT, "udp", "LiveKit's"), + ] + if mock_sender_port is not None: + ports.append(NeededPort(mock_sender_port, "tcp", "the mock sender's", "--sender-port")) + return ports + + +def port_taken(kind: str, number: int) -> bool: + """Whether a program on this PC already holds the port, on any of its addresses. + + Asked on every address because LiveKit listens for media on the addresses of the network interfaces too, + whatever address it is told to bind. + """ + # A listener answers a connection whichever address it bound; a bind alone misses one on some systems. + if kind == "tcp" and port_open("127.0.0.1", number): + return True + with socket.socket(socket.AF_INET, socket.SOCK_STREAM if kind == "tcp" else socket.SOCK_DGRAM) as probe: + if kind == "tcp": + # As a server sets it: connections left closing by a run that has just ended hold nothing. + probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + try: + probe.bind(("", number)) + except OSError as error: + # Any other refusal (a port this user may not bind) is the program's own to report. + return error.errno == errno.EADDRINUSE + return False + + +def _said(command: Sequence[str]) -> str: + """What a short query tool printed; nothing when it is not installed or takes too long.""" + try: + tool = subprocess.Popen( # noqa: S603 -- a fixed tool name with a port number + list(command), stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True + ) + except OSError: + return "" + with tool: + try: + return tool.communicate(timeout=2.0)[0] + except subprocess.TimeoutExpired: + # Ended here, so that leaving the block does not wait for it after all. + tool.kill() + return "" + + +def port_holder(kind: str, number: int) -> str | None: + """The program that holds a port, as ``name (pid N)``, where a tool of this system tells; None where none + does. A process of another user is not named to this one.""" + letter = "t" if kind == "tcp" else "u" + found = re.search(r'users:\(\("([^"]+)",pid=(\d+)', _said(["ss", "-H", f"-l{letter}np", f"sport = :{number}"])) + if found is not None: + return f"{found[1]} (pid {found[2]})" + listening = ["-sTCP:LISTEN"] if kind == "tcp" else [] + found = re.search( + r"^p(\d+)\nc(.+)$", _said(["lsof", "-nP", f"-i{kind.upper()}:{number}", *listening, "-Fpc"]), re.MULTILINE + ) + return f"{found[2]} (pid {found[1]})" if found is not None else None + + +def refuse_taken_ports(ports: Sequence[NeededPort]) -> None: + """Stop the start when a port the stack needs is already held, naming each port, whose it is and, where + the system tells, the program that holds it. + + Asked before anything is deployed or started: a program left by an earlier run would otherwise stop this + one half way up, with the Orin's sender already running. + """ + taken = [port for port in ports if port_taken(port.kind, port.number)] + if not taken: + return + said = [] + for port in taken: + holder = port_holder(port.kind, port.number) + kind = port.kind.upper() + # Where no tool names the holder, the commands that do for whoever may run them. + how = f"`ss -l{port.kind[0]}np` or `lsof -nP -i{kind}:{port.number}` names the program" + by = f" by {holder}" if holder is not None else f" ({how})" + said.append(f"port {port.number} ({port.whose}, {kind}) is already in use{by}") + # Another port is offered only where one option answers the whole refusal. + other = f", or choose another port with {taken[0].option}" if len(taken) == 1 and taken[0].option else "" + programs = "that program" if len(taken) == 1 else "those programs" + remedy = f"An earlier run may still be up: stop {programs}{other}, then start again." + raise StartupError(f"{'; '.join(said)}. {remedy}") + + +class _Passed: + """One of the launcher's output streams while a run log is open: what is written to it goes to the stream + it stands for and into the log.""" + + def __init__(self, log: "RunLog", stream: TextIO) -> None: + """Stand for ``stream``, passing what is written on through ``log``.""" + self._log = log + self._stream = stream + + def write(self, text: str) -> int: + """Show and log ``text``; a stream that no longer takes it is not an error of the writer's.""" + self._log.record(text, self._stream) + return len(text) + + def flush(self) -> None: + """Nothing is held back: every write is passed on at once.""" + + def __getattr__(self, name: str) -> Any: + """Everything else (whether it is a terminal, its encoding) is the stream's own answer.""" + return getattr(self._stream, name) + + +class RunLog: + """What the launcher and its helpers print, kept in a file of the run directory as well as shown. + + While it is open the launcher's own output streams pass every line to the terminal and into the file, and + a helper started with ``for_helper()`` writes into a pipe that a thread of this log reads the same way. A + terminal that has gone away (a pipe whose reader ended) stops nothing: the line is still logged, and that + stream is written to no more. + """ + + def __init__(self, path: Path) -> None: + """Name the file; nothing is opened or changed until ``open``.""" + self.path = path + self._file: TextIO | None = None + self._streams: tuple[TextIO, TextIO] | None = None + # The streams that refused a write: trying each line again would only fail again. + self._gone: set[int] = set() + # The launcher's thread and the helpers' reader write through one door. + self._guard = threading.Lock() + self._helper_end: int | None = None + self._reader: threading.Thread | None = None + + def open(self) -> None: + """Start logging: take the place of the output streams and start reading the helpers' pipe.""" + self._file = self.path.open("a", encoding="utf-8", errors="replace") + self._streams = (sys.stdout, sys.stderr) + sys.stdout, sys.stderr = _Passed(self, sys.stdout), _Passed(self, sys.stderr) + read_end, self._helper_end = os.pipe() + # A daemon: a helper's child that keeps the pipe open must not keep the launcher from exiting. + self._reader = threading.Thread(target=self._relay, args=(read_end,), name="launcher-log", daemon=True) + self._reader.start() + + def close(self) -> None: + """Stop logging and give the output streams back. What helpers had written is read to its end, for a + bounded time.""" + if self._streams is None: + return + sys.stdout, sys.stderr = self._streams + os.close(self._helper_end) + self._reader.join(timeout=2.0) + with self._guard: + self._file.close() + self._file, self._streams = None, None + + def __enter__(self) -> "RunLog": + """Open for a block.""" + self.open() + return self + + def __exit__(self, *_exc: object) -> None: + """Close at the block's end, however it ended.""" + self.close() + + def for_helper(self) -> dict[str, int]: + """The output arguments for a helper process, whose lines then reach the terminal and the log through + this launcher and never a terminal that went away.""" + return {"stdout": self._helper_end, "stderr": self._helper_end} + + def record(self, text: str, stream: TextIO) -> None: + """Write ``text`` into the log and on to ``stream``, which is given up on once it refuses a write.""" + with self._guard: + if self._file is not None: + self._file.write(text) + self._file.flush() + if id(stream) in self._gone: + return + try: + stream.write(text) + stream.flush() + except (OSError, ValueError): + # The reader of a pipe ended, or the stream was closed: the stop this may be part of goes on. + self._gone.add(id(stream)) + + def _relay(self, read_end: int) -> None: + """Pass on what helpers write until every writer has closed the pipe; the reader thread's work.""" + decoder = codecs.getincrementaldecoder("utf-8")(errors="replace") + with os.fdopen(read_end, "rb", buffering=0) as pipe: + while chunk := pipe.read(65536): + self.record(decoder.decode(chunk), self._streams[0] if self._streams is not None else sys.stdout) + + +@contextlib.contextmanager +def stop_signals_noted(note: Callable[[], None]) -> Iterator[None]: + """While the block runs, Ctrl-C, SIGTERM and SIGHUP call ``note`` and raise nothing, so no step of a stop + is cut short by one. The handlers found are put back afterwards.""" + previous: dict[int, Any] = {} + + def noted(signum, frame) -> None: + """The handler: pass the signal on as a call and raise nothing.""" + note() + + try: + for sig in (signal.SIGINT, *STOP_SIGNALS): + previous[sig] = signal.signal(sig, noted) + yield + finally: + for sig, handler in previous.items(): + # None stands for a handler that was not set from Python, which cannot be put back from here. + if handler is not None: + signal.signal(sig, handler) + + @dataclass class Managed: """One child process and the log file its output goes to.""" @@ -969,7 +1224,7 @@ def run_supervised(stack: "Stack", command: list[str]) -> int: A required child that dies meanwhile stops the helper and raises, instead of going unnoticed until it returns. """ - process = subprocess.Popen(command) + process = subprocess.Popen(command, **stack.helper_output) try: while process.poll() is None: raise_if_a_child_exited(stack) @@ -1009,6 +1264,9 @@ def __init__(self, workdir: Path) -> None: """Keep each child's log under ``workdir`` so a failed step can point at the file to read.""" self.workdir = workdir self.children: list[Managed] = [] + #: The output arguments of a helper run beside the children (``RunLog.for_helper``); none sends its + #: output straight to the terminal. + self.helper_output: Mapping[str, int] = {} def start( self, @@ -1071,15 +1329,18 @@ def _signal_group(child: Managed, sig: int) -> bool: except ProcessLookupError: # The last process of the group exited after poll() looked, which is a stop, not an error. return False + except PermissionError: + # Nothing in the group takes a signal from this user. Some systems answer so for members that were + # killed and are not collected yet; whether anything is left is asked when the stop ends. + return False return True def _kill(self, child: Managed) -> None: - """Kill the child's group and reap it, so no zombie or orphan outlives this script.""" + """Kill the child's group and reap it, so no zombie or orphan outlives this script. One that is still + there afterwards is found, and reported, by ``stop_all``.""" self._signal_group(child, signal.SIGKILL) - try: - child.process.wait(timeout=5) - except subprocess.TimeoutExpired: - print(f"{child.name} did not die after SIGKILL; leaving it", file=sys.stderr) + with contextlib.suppress(subprocess.TimeoutExpired): + child.process.wait(timeout=KILL_WAIT_S) @staticmethod def _wait(child: Managed, timeout_s: float, hurry: list[bool]) -> bool: @@ -1093,63 +1354,172 @@ def _wait(child: Managed, timeout_s: float, hurry: list[bool]) -> bool: continue return child.process.poll() is not None - def stop_all(self) -> None: - """Stop the children last started first, waiting for each to exit before signalling the next. + @staticmethod + def _gone(child: Managed, timeout_s: float) -> bool: + """Whether the child and whatever was left of its process group are gone, giving what was killed up to + ``timeout_s`` to be collected by the system.""" + deadline = time.monotonic() + timeout_s + while True: + if child.process.poll() is not None: + try: + # Signal 0 sends nothing; it only asks whether the group still has a member. + os.killpg(child.process.pid, 0) + except ProcessLookupError: + return True + except PermissionError: + # A member this user may not signal is a member all the same. + pass + if time.monotonic() >= deadline: + return False + time.sleep(0.05) + + def _stop(self, child: Managed, hurry: list[bool]) -> None: + """Stop one child: the polite signal and its grace, unless hurried, then the kill for one still there.""" + if child.process.poll() is not None: + # The leader is gone already; anything it left in the group goes with it. + self._signal_group(child, signal.SIGKILL) + return + if not hurry[0]: + # SIGINT lets the receiver and sender drain and free the GPU and cameras. A leader-only child gets + # it alone, so its helper processes are not interrupted behind its back. + try: + if child.leader_only: + child.process.send_signal(signal.SIGINT) + else: + self._signal_group(child, signal.SIGINT) + except ProcessLookupError: + # The leader exited between poll() and the signal, which is a stop and not an error. + pass + if self._wait(child, child.grace_s, hurry): + self._signal_group(child, signal.SIGKILL) + return + if not hurry[0]: + print(f"{child.name} did not exit within {child.grace_s:.0f} s; killing it", file=sys.stderr) + self._kill(child) + + def stop_all(self) -> list[Managed]: + """Stop the children last started first, waiting for each to exit before signalling the next, and + return the ones that are still running afterwards. A child later in the start order depends on the ones before it (the backend needs CaptureServer's live connection to close a take), so it must be gone before its dependencies are signalled. Each child gets its own grace period before it is killed, and whatever is left of its process group once it has exited is - killed too. A second Ctrl-C, or a SIGTERM or SIGHUP, while waiting kills the rest at once instead of - aborting. + killed too. + + Nothing ends the stop before every child was dealt with. A second Ctrl-C, or a SIGTERM or SIGHUP, + while it runs hurries it: the children still running are killed at once, without their grace. Any + further one changes nothing. """ hurry = [False] - - def hurry_up(signum, frame) -> None: - hurry[0] = True - - # A signal while stopping must hurry the cleanup, not raise out of it and leave children running. - previous = {sig: signal.signal(sig, hurry_up) for sig in STOP_SIGNALS} - try: - for child in reversed(self.children): - if child.process.poll() is not None: - self._signal_group(child, signal.SIGKILL) - continue - if hurry[0]: - self._kill(child) - continue - # SIGINT lets the receiver and sender drain and free the GPU and cameras. A leader-only child gets - # it alone, so its helper processes are not interrupted behind its back. + stopped: set[int] = set() + with stop_signals_noted(lambda: hurry.__setitem__(0, True)): + while True: try: - if child.leader_only: - child.process.send_signal(signal.SIGINT) - else: - self._signal_group(child, signal.SIGINT) - except ProcessLookupError: - # The leader exited between poll() and the signal, which is a stop and not an error. - pass - try: - exited = self._wait(child, child.grace_s, hurry) + for child in reversed(self.children): + if id(child) not in stopped: + self._stop(child, hurry) + stopped.add(id(child)) + return [child for child in self.children if not self._gone(child, KILL_WAIT_S)] except KeyboardInterrupt: - # An impatient operator: stop waiting for this child and for every one after it. + # One that was already on its way when the handlers were set: it hurries like the rest, + # and the child it interrupted is taken up again. hurry[0] = True - exited = False - if exited: - # The leader is gone; anything it left in the group goes with it. - self._signal_group(child, signal.SIGKILL) - else: - if not hurry[0]: - print( - f"{child.name} did not exit within {child.grace_s:.0f} s; killing it", file=sys.stderr - ) - self._kill(child) - finally: - for sig, handler in previous.items(): - signal.signal(sig, handler) -def _raise_interrupt(signum, frame) -> None: - """Turn SIGTERM and SIGHUP into the Ctrl-C path, so a closed terminal stops the stack like Ctrl-C does.""" - raise KeyboardInterrupt +def shut_down(stack: Stack, stop_sender: Sequence[str] | None) -> list[str]: + """Stop everything this run started and say what became of it; returns what is not known to have stopped, + which is nothing when all of it has. + + ``stop_sender`` is the deploy tool's command that stops the sender on the Orin, None when the Orin was never + asked for anything. Every step is carried out whatever is pressed meanwhile: Ctrl-C, SIGTERM and SIGHUP + hurry the children's stop and cut nothing short, the Orin is asked in a session of its own that a Ctrl-C at + the terminal does not reach, and the wait for its answer is bounded. + """ + while True: + try: + with stop_signals_noted(lambda: None): + return _shut_down(stack, stop_sender) + except KeyboardInterrupt: + # Only one already on its way before the handlers were set gets here, before anything was done. + continue + + +def _shut_down(stack: Stack, stop_sender: Sequence[str] | None) -> list[str]: + """The steps of ``shut_down``, which keeps signals from cutting them short.""" + left = [] + for child in stack.stop_all(): + group = child.process.pid + left.append(f"{child.name} (process group {group})") + print( + f"still running after the stop: {child.name} (process group {group}); end it with " + f"`kill -KILL -- -{group}`", + file=sys.stderr, + ) + if stack.children and not left: + print("every program this run started has stopped") + if stop_sender is not None: + # Ending the local ssh does not end the remote sender; ask it to stop so it frees the cameras. The + # deploy tool's stop succeeds only when no sender is left running, which is what is then said. + try: + stopped = ( + subprocess.run( + list(stop_sender), + check=False, + timeout=ORIN_COMMAND_TIMEOUT_S, + start_new_session=True, + **stack.helper_output, + ).returncode + == 0 + ) + except (OSError, subprocess.SubprocessError): + stopped = False + if stopped: + print("the Orin sender is stopped") + else: + left.append("the sender on the Orin") + check = shlex.join([*stop_sender[:-1], "check"]) + print( + f"could not confirm that the Orin sender stopped; the cameras stay taken while it runs: " + f"`{check}` lists it and `{shlex.join(stop_sender)}` stops it", + file=sys.stderr, + ) + return left + + +def leave(status: int) -> NoReturn: + """Exit with ``status`` whatever became of the terminal and whatever is pressed on the way out. Output the + interpreter still holds for a reader that ended would otherwise fail its last flush and replace the status.""" + # Everything is stopped by now: a Ctrl-C has nothing left to do but spoil the exit. + signal.signal(signal.SIGINT, signal.SIG_IGN) + for stream in (sys.stdout, sys.stderr): + try: + stream.flush() + except (OSError, ValueError): + # Nothing reads it any more: what is left to flush goes nowhere, and says nothing on the way. + with contextlib.suppress(OSError, ValueError): + os.dup2(os.open(os.devnull, os.O_WRONLY), stream.fileno()) + sys.exit(status) + + +class StopRequest: + """What ``main`` does on Ctrl-C, SIGTERM and SIGHUP: the first of them takes the Ctrl-C path, so a closed + terminal stops the stack like Ctrl-C does, and any that follows raises nothing. + + Two can arrive together: a terminal's Ctrl-C reaches the launcher and a wrapper that runs it, which may pass + its own on. The second must not cut the stop off before it has begun; once the stop runs, its own handlers + take such a signal as a request to hurry. + """ + + def __init__(self) -> None: + """Nothing has asked for a stop yet.""" + self.asked = False + + def __call__(self, signum, frame) -> None: + """Ask for the stop once, by raising ``KeyboardInterrupt`` where the main thread is.""" + if self.asked: + return + self.asked = True + raise KeyboardInterrupt def control_token(log: Path) -> str | None: @@ -1310,16 +1680,26 @@ def main(argv: Sequence[str] | None = None) -> int: args = parse_args(argv) orin_host = args.orin.rsplit("@", 1)[-1] if args.orin else None room, publisher = "egocap-room", "egocap-bridge" - livekit_url = "ws://127.0.0.1:7880" + livekit_url = f"ws://127.0.0.1:{LIVEKIT_PORT}" workdir = Path(tempfile.mkdtemp(prefix="egocap-start-")) ipc_socket = str(workdir / "camera_receiver.sock") stack = Stack(workdir) orin_contacted = False - # Children run in their own sessions, so a signal to this script reaches none of them; turn the ones that mean - # stop into the Ctrl-C path so the finally below always runs stop_all(). - for sig in STOP_SIGNALS: - signal.signal(sig, _raise_interrupt) + status = 0 + log = RunLog(workdir / LAUNCHER_LOG) + stop_request = StopRequest() + # The handlers found, put back when this function returns. + found: dict[int, Any] = {} try: + # Children run in their own sessions, so a signal to this script reaches none of them; the signals that + # mean stop take the Ctrl-C path once, so the finally below always runs the stop, and runs it whole. + for sig in (signal.SIGINT, *STOP_SIGNALS): + found[sig] = signal.signal(sig, stop_request) + # From its first line on, what this launcher and its helpers print is also in a file of the run + # directory, so its output need not be piped to be kept. Opened inside the block that closes it. + log.open() + print(f"launcher log: {log.path} (everything printed here is written there too)") + helper = stack.helper_output = log.for_helper() # The deploy is checked first so a missing tool fails before anything is running. if args.orin and args.mock: raise StartupError("--mock replaces the Orin sender with a local mock sender; do not pass --orin") @@ -1412,6 +1792,10 @@ def main(argv: Sequence[str] | None = None) -> int: f"the frontend is not built ({FRONTEND_INDEX} is missing); run `npm install && npm run build` " f"in {EGOCAP_ROOT / 'frontend'}" ) + # Before anything is deployed or started: a program an earlier run left on a port would stop this run + # half way up. + mock_sender_port = sender.port if chain and args.mock else None + refuse_taken_ports(needed_ports(args.backend_port, bool(args.livekit_server), mock_sender_port)) token_file = workdir / "publisher-token.txt" token_file.write_text(publisher_token(LIVEKIT_DEV_KEY, LIVEKIT_DEV_SECRET, room, publisher)) token_file.chmod(0o600) @@ -1438,14 +1822,15 @@ def main(argv: Sequence[str] | None = None) -> int: deploy = [python, args.deploy_script, args.orin] # nvargus-daemon returns at boot and holds the cameras, which SIPL capture needs free; a sender left # by an earlier run outlives its ssh session. - subprocess.run([*deploy, "stop"], check=False, timeout=ORIN_COMMAND_TIMEOUT_S) + subprocess.run([*deploy, "stop"], check=False, timeout=ORIN_COMMAND_TIMEOUT_S, **helper) if sender.sipl: - subprocess.run([*deploy, "stop-daemon"], check=True, timeout=ORIN_COMMAND_TIMEOUT_S) + subprocess.run([*deploy, "stop-daemon"], check=True, timeout=ORIN_COMMAND_TIMEOUT_S, **helper) if not args.skip_deploy: print("deploying the sender to", args.orin) subprocess.run( [*deploy, "deploy", *(["--with-sipl"] if sender.sipl else []), "--name", args.release], check=True, + **helper, ) stack.start( "sender", @@ -1469,7 +1854,9 @@ def main(argv: Sequence[str] | None = None) -> int: # 2. LiveKit carries the video from the bridge to the browser and the recorder. if args.livekit_server: server = stack.start("livekit", [args.livekit_server, "--dev", "--bind", "127.0.0.1"]) - stack.wait_until(server, lambda: port_open("127.0.0.1", 7880), "listening on 7880", 30) + stack.wait_until( + server, lambda: port_open("127.0.0.1", LIVEKIT_PORT), f"listening on {LIVEKIT_PORT}", 30 + ) # 3. CaptureServer announces the streams and serves tracking. capture = stack.start( "capture-server", @@ -1487,7 +1874,12 @@ def main(argv: Sequence[str] | None = None) -> int: env={"PYTHONPATH": pythonpath}, cwd=EGOCAP_ROOT, ) - stack.wait_until(capture, lambda: port_open("127.0.0.1", 8082), "listening on 8082", 60) + stack.wait_until( + capture, + lambda: port_open("127.0.0.1", CAPTURE_SERVER_PORT), + f"listening on {CAPTURE_SERVER_PORT}", + 60, + ) # 4. The backend serves the page and runs the recorder. backend = stack.start( "backend", @@ -1582,6 +1974,7 @@ def main(argv: Sequence[str] | None = None) -> int: [python, str(args.timesync_tool), "ensure-local"], check=False, timeout=ENSURE_LOCAL_TIMEOUT_S, + **helper, ).returncode == 0 ) @@ -1622,6 +2015,7 @@ def main(argv: Sequence[str] | None = None) -> int: ], check=False, timeout=90, + **helper, ).returncode == 0 ) @@ -1655,36 +2049,31 @@ def main(argv: Sequence[str] | None = None) -> int: print("time sync: settled", flush=True) # Stay up until a child dies or the operator interrupts. dead = watch(stack) - if dead.name == "sender" and dead.process.returncode == 0: - # The sender runs for --seconds and then exits cleanly: that is the requested end, not a failure. - print(f"the Orin sender finished its {args.seconds} s run; stopping the stack") - return 0 - raise StartupError(f"{dead.name} exited with {dead.process.returncode}; see {dead.log}") + # The sender runs for --seconds and then exits cleanly: that is the requested end, not a failure. + if dead.name != "sender" or dead.process.returncode != 0: + raise StartupError(f"{dead.name} exited with {dead.process.returncode}; see {dead.log}") + print(f"the Orin sender finished its {args.seconds} s run; stopping the stack") except KeyboardInterrupt: - return 0 + # Ctrl-C, SIGTERM or SIGHUP: the stop that was asked for, carried out below. + pass except (StartupError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as error: print(f"error: {error}", file=sys.stderr) - return 1 + status = 1 finally: - stack.stop_all() + stop_sender = [sys.executable, args.deploy_script, args.orin, "stop"] if orin_contacted else None + left = shut_down(stack, stop_sender) # A remap table is tens of megabytes and nothing reads it once the bridge has stopped. The logs stay. for table in workdir.glob(f"*{REMAP_TABLE_SUFFIX}"): with contextlib.suppress(OSError): table.unlink() - if orin_contacted: - # Ending the local ssh does not end the remote sender; ask it to stop so it frees the cameras. - try: - subprocess.run( - [sys.executable, args.deploy_script, args.orin, "stop"], - check=False, - timeout=ORIN_COMMAND_TIMEOUT_S, - ) - except (subprocess.TimeoutExpired, KeyboardInterrupt): - print( - "could not confirm that the Orin sender stopped; check it with the deploy tool", - file=sys.stderr, - ) + log.close() + # Given back last, so that nothing pressed after the stop ends this function before it has returned. + for sig, handler in found.items(): + if handler is not None: + signal.signal(sig, handler) + # A run that left something running did not end well, however it was asked to end. + return 1 if left else status if __name__ == "__main__": - sys.exit(main()) + leave(main()) From 43cb20ba3869c44343d264b6c174ff2fa23c8395 Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 09:55:24 -0800 Subject: [PATCH 09/24] egocap: a tracking device has one name in the checklist, the Station tab's The checklist called a device what the Station tab calls it only when the station required it, and by the capture session's description otherwise. With one glove required and the other not, one list showed "Left Manus glove" beside "Right glove", and a row changed its name when its box was ticked. Every device a station can require now has the Station tab's name in every row, required or not. The capture session's own description is sent beside it as the item's reported_as and shown under the name, so the row can still be matched with the session's list of devices; it is null where the two are one name and for every other item. It is no part of the sentences made from an item's label and detail, which read as before for a required device. A device no station can require keeps the session's description as its name. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- examples/egocap/backend/README.md | 12 ++-- .../egocap/backend/egocap_web/setup_checks.py | 17 +++-- .../egocap/frontend/src/DevicesTab.test.tsx | 38 ++++++++++ examples/egocap/frontend/src/DevicesTab.tsx | 7 ++ examples/egocap/frontend/src/setupApi.ts | 3 + examples/egocap/frontend/src/styles.css | 7 ++ .../egocap/tests/backend/test_setup_checks.py | 69 ++++++++++++++----- .../tests/backend/test_setup_service.py | 1 + 8 files changed, 126 insertions(+), 28 deletions(-) diff --git a/examples/egocap/backend/README.md b/examples/egocap/backend/README.md index 6fb5536d05..8e7fdbee19 100644 --- a/examples/egocap/backend/README.md +++ b/examples/egocap/backend/README.md @@ -39,7 +39,7 @@ glove calibration or a guided glove calibration makes it do. | `GET`/`PUT /api/operator-settings` | The operator's station setup: the camera type (`sensing_gmsl` or `oak_d`), camera roles (`ego`, `wrist_left`, `wrist_right`), the task catalog the recording panel's picker offers (`task_file`), the task it preselects (`preselected_task`) and whether calibration files are required before recording (`require_calibration`, a boolean, `false` by default; see [Start-of-day flow](#start-of-day-flow)). Kept in `.egocap/operator_settings.json` under the recording output (hidden from the recordings browser) (`EGOCAP_OPERATOR_SETTINGS_FILE` overrides the path) so every browser sees the same values. `PUT` names only the fields it changes and uses `X-Control-Token`; legacy JSON `control_token` remains accepted. A wrong token is 403 and bodies above 16 KiB are rejected with 413 before parsing. | | `GET`/`POST /api/stations`, `PUT`/`DELETE /api/stations/{id}`, `POST /api/stations/select` | The station registry: the stations an operator chooses between and the one in use. A station is a name, a camera type, the camera filling each role, the tracking devices it requires (`required_devices`) and the capture host address last given to its headset. Kept in `stations.json` beside the operator settings. Every change uses `X-Control-Token` and answers with the new listing; a refusal is a 400 with the specific reason (a duplicate name, a camera in two roles, an unknown field), and an unknown id is 404. The station in use cannot be selected, edited or deleted while a take is being written, and a change that would start a new batch (selecting another station or none, renaming or deleting the station in use) is refused with `recover or discard the interrupted take first` while an interrupted take waits. A station's headset address is listed only when the `GET` carries the token. See [Stations](#stations). | | `GET`/`POST /api/station-uptime` | What the station in use is doing now (`ready`, `recording`, or `down` with the reason) and its active and down time between today's first and last take, with each down period as a blocker (`end` is `null` for one that has not ended). It is observed by the backend, never set: `POST` (`X-Control-Token`) only saves the day's notes, with the body `{"station": , "notes": }`; when that is no longer the station in use the reply is a 409 and nothing is written. `GET` is open, and returns `notes` as an empty string unless it carries `X-Control-Token`: the notes are the operator's free text, and the end-of-day report, which needs the token, is where the page reads them. See [Stations](#stations). | -| `GET /api/setup` | The start-of-day flow: the four steps' states, the live station checklist (`checks`, each with a `status` of `pass`, `fail`, `warn` or `skip`), `enforced` (whether the checklist gates recording or only advises), `blocked_reason` (why station setup holds a take; only a failed item does) and, when the request carries `X-Control-Token`, `headset`: the capture host address to enter in the headset, the one remembered for the station in use, and whether that one stopped being valid. Everything in one reply describes one station: if the station in use keeps changing while it is gathered the reply is a 503 (`the station in use is changing; try again`). Read-only. See [Start-of-day flow](#start-of-day-flow). | +| `GET /api/setup` | The start-of-day flow: the four steps' states, the live station checklist (`checks`, each with a `status` of `pass`, `fail`, `warn` or `skip`, and a tracking device's also with `reported_as`, the capture session's own name for it), `enforced` (whether the checklist gates recording or only advises), `blocked_reason` (why station setup holds a take; only a failed item does) and, when the request carries `X-Control-Token`, `headset`: the capture host address to enter in the headset, the one remembered for the station in use, and whether that one stopped being valid. Everything in one reply describes one station: if the station in use keeps changing while it is gathered the reply is a 503 (`the station in use is changing; try again`). Read-only. See [Start-of-day flow](#start-of-day-flow). | | `POST /api/setup/livekit-preview` | What the caller's preview receives of each LiveKit camera: `{"page": "", "streams": {"": "receiving" \| "silent" \| "no_track" \| "not_connected"}}`. Needs `X-Control-Token`; bodies above 8 KiB are refused with 413, a malformed one with 400 and the reason. Kept in memory per page for six seconds and read by the station checklist, which passes a LiveKit camera only while a report says its frames arrive; it holds no take. See [`../LIVEKIT_PREVIEW.md`](../LIVEKIT_PREVIEW.md#checked-before-a-take). | | `GET /api/day-report`, `POST /api/day-report/save`, `POST /api/day-report/correct`, `POST /api/day-report/studio` | The end-of-day report, all with `X-Control-Token`. `GET` returns today's takes for the station in use by session, with a count and duration per disposition (kept, flagged, quarantined, rejected, discarded, pending, recording) read from the recording service's manifests, plus the station's time (`uptime`). `save` writes `__report.json` beside the daily log and refreshes that log's recorded time. `correct` rewrites the task of one take or a range of a session's takes (`session`, `episodes`, `task`). `studio` relabels the studio of a whole session where it lies (`session`, `studio`) and answers with the label as stored; nothing is moved. A refused or failed correction is a 400 with the reason in `detail`, and with `left_changed` (a list of names) only when a failed correction of either kind could not put a label back. Each take carries `location`, where its data is under the recording output, `studio`, the label it carries now (null when none was recorded), its `reasons` and `warnings` as the sentences the page shows after the take, and `media_removed`. See [End-of-day report](#end-of-day-report). | | `POST /api/task-files/import`, `DELETE /api/task-files/{name}` | Import a task catalog the operator supplies — by `name` + `content` (text uploaded from the browser) — into the imported-catalog directory beside the operator settings, once it parses; and remove an imported one. `POST` and `DELETE` use the `X-Control-Token` header (legacy JSON tokens remain accepted for `POST`); `DELETE` refuses removal of the selected catalog (409); imports also refuse replacement of that catalog until it is deselected. Imports appear in `GET /api/task-files` (as `imported`) and shadow a shipped catalog of the same name. | @@ -245,10 +245,12 @@ The flow is station, devices, record, wrap-up ([`setup_service.py`](egocap_web/s a station replaces them`, or `Saved stations cannot be read. Check the registry file's permissions`) until a change from the Station tab succeeds; the Station step shows the same. A file that is absent is still "no stations", which holds nothing. -- **A row is renamed only where the station asks.** The checklist calls a device what the Station tab calls it - (`Headset`, `Left controller`, `Right controller`, `Left glove`, `Right glove`) only when the station requires - that kind. Every other row keeps the capture session's own description, so a station that requires nothing - shows exactly the rows it showed before requirements existed. +- **A device has one name in the checklist.** The checklist calls a device what the Station tab calls it + (`Headset`, `Left controller`, `Right controller`, `Left glove`, `Right glove`) whether or not the station + requires it, so a row does not change its name when its box is ticked. The capture session's own description + of the device is sent beside it as the item's `reported_as` and shown under the name; it is null where the two + are one name and for every other item. A device no station can require keeps the session's description as + its name. - **A calibration take is held only by the devices its tool uses.** The head-camera tool's take uses the headset and the controllers, the glove tool's all five (`calibration_service.TOOL_DEVICES`); a required device the tool does not use never holds that take, as the calibration item never does. The gloves' calibration goes by diff --git a/examples/egocap/backend/egocap_web/setup_checks.py b/examples/egocap/backend/egocap_web/setup_checks.py index 704ad48b0f..5bba9ad2fa 100644 --- a/examples/egocap/backend/egocap_web/setup_checks.py +++ b/examples/egocap/backend/egocap_web/setup_checks.py @@ -72,6 +72,10 @@ class CheckItem: #: The tracking device this item is about, by the name a station requires it under; None for any other #: item. Not sent: it lets a take that does not use the device leave the item out of what holds it. device: str | None = None + #: What the capture session calls a tracking device whose label is the station's name for it, so the row + #: can be matched with the session's own list of devices; None where the two are one name, and for any + #: other item. It is no part of a sentence made from the label and the detail. + reported_as: str | None = None def to_json(self) -> dict[str, Any]: """The wire form.""" @@ -81,6 +85,7 @@ def to_json(self) -> dict[str, Any]: "label": self.label, "status": self.status, "detail": self.detail, + "reported_as": self.reported_as, } @@ -193,6 +198,7 @@ def _tracking_items(facts: CaptureFacts, required: Collection[str]) -> list[Chec """One item per tracking device the session reports, one per requirement of the station that no reported device answers, and one for whether tracking data is arriving. + A device is named as the Station tab names it, with the capture session's own name sent beside it. A device that is not connected warns: recording readiness judges the tracking data, not the state each device reports, and a station may leave a controller or a glove unused. A device the station requires fails instead unless it is delivering its data when Record is pressed: connected, or degraded for a @@ -208,10 +214,13 @@ def _tracking_items(facts: CaptureFacts, required: Collection[str]) -> list[Chec # Said with the reason it holds a take, since the same state only warns at another station. state = f"{state}; {REQUIRED_HERE}" status = PASS if device.connected else (FAIL if holds else WARN) - # A device the station requires is called what the Station tab calls it, so the box that was ticked - # and the row that fails name one thing. Every other device keeps the capture session's description. - label = TRACKING_DEVICES[device.kind] if needed and device.kind is not None else device.label - items.append(CheckItem(f"device:{index}", TRACKING, label, status, state, device.kind)) + # A device a station can require has one name in every row, the Station tab's, whether or not this + # station requires it: the box that is ticked and the row name one thing, and a row does not change + # its name with the box. The capture session's description goes with it; a device no station can + # require has only that. + label = TRACKING_DEVICES.get(device.kind, device.label) + reported_as = device.label if device.label != label else None + items.append(CheckItem(f"device:{index}", TRACKING, label, status, state, device.kind, reported_as)) reported = {device.kind for device in facts.devices} # Every requirement no reported device answers fails under its own name: the devices in the order they are # listed to the operator, then whatever else the station names. A glove whose software is not running has diff --git a/examples/egocap/frontend/src/DevicesTab.test.tsx b/examples/egocap/frontend/src/DevicesTab.test.tsx index 66fc4cb9ff..7e04ebe7c6 100644 --- a/examples/egocap/frontend/src/DevicesTab.test.tsx +++ b/examples/egocap/frontend/src/DevicesTab.test.tsx @@ -86,6 +86,44 @@ describe("a tracking device the station requires", () => { }); }); +describe("a tracking device", () => { + const gloves = (required: boolean): SetupStatus => ({ + ...SETUP_READY, + checks: [ + { id: "device:0", group: "tracking", label: "Headset", status: "pass", detail: null, reported_as: "OpenXR headset" }, + { id: "device:1", group: "tracking", label: "Left glove", status: required ? "fail" : "warn", detail: required ? "disconnected; this station requires it" : "disconnected", reported_as: "Left Manus glove" }, + { id: "device:2", group: "tracking", label: "Right glove", status: "pass", detail: null, reported_as: "Right Manus glove" }, + { id: "device:3", group: "tracking", label: "Waist tracker", status: "pass", detail: null, reported_as: null }, + ], + }); + + it("has the station's name whether or not it is required, with the capture session's name beside it", async () => { + const { state } = await renderTab(gloves(false)); + const names = () => + within(screen.getByRole("region", { name: "Tracking" })) + .getAllByRole("listitem") + .map((row) => [row.querySelector(".check-label")?.firstChild?.textContent, row.querySelector(".check-source")?.lastChild?.textContent ?? null]); + const named = [ + ["Headset", "OpenXR headset"], + ["Left glove", "Left Manus glove"], + ["Right glove", "Right Manus glove"], + // A device the session alone names has one name, and no second line repeats it. + ["Waist tracker", null], + ]; + expect(names()).toEqual(named); + // Requiring the device changes its outcome and its reason, never what the row is called. + state.answer = gloves(true); + await settle(DEVICES_REFRESH_MS); + expect(names()).toEqual(named); + expect(rowsOf("Tracking")[1]).toBe("✗Left glove failed, which the capture session calls Left Manus gloveDisconnected; this station requires it"); + }); + + it("shows no second name for a check from a backend that sends none", async () => { + await renderTab(SETUP_DEVICE_REQUIRED); + expect(document.querySelector(".check-source")).toBeNull(); + }); +}); + describe("a check whose outcome this page does not know", () => { it("is shown as unrecognised with its reason, never as passed or not needed", async () => { const [first, ...rest] = SETUP_READY.checks.filter((check) => check.group === "system"); diff --git a/examples/egocap/frontend/src/DevicesTab.tsx b/examples/egocap/frontend/src/DevicesTab.tsx index 406f5eda8e..d69301e315 100644 --- a/examples/egocap/frontend/src/DevicesTab.tsx +++ b/examples/egocap/frontend/src/DevicesTab.tsx @@ -58,6 +58,13 @@ function CheckRow({ item }: { item: CheckItem }) { {/* An advisory row says so in view, below; said here as well it would be read out twice. */} {!advisory && {outcome.word}} + {/* The capture session's own name for the device, by which the side panel lists it. */} + {typeof item.reported_as === "string" && ( + + , which the capture session calls + {item.reported_as} + + )} {item.detail !== null && {sentence(item.detail)}} {advisory && {ADVISORY_NOTE}} diff --git a/examples/egocap/frontend/src/setupApi.ts b/examples/egocap/frontend/src/setupApi.ts index e2ff520885..5355ab6ab7 100644 --- a/examples/egocap/frontend/src/setupApi.ts +++ b/examples/egocap/frontend/src/setupApi.ts @@ -47,6 +47,9 @@ export interface CheckItem { status: CheckStatus; /** Why it did not simply pass, or null. */ detail: string | null; + /** What the capture session calls a tracking device whose label is the station's name for it; null or absent + * where the two are one name, for any other check, and from a backend that does not send it. */ + reported_as?: string | null; } /** Where the headset connects, for the station in use. */ diff --git a/examples/egocap/frontend/src/styles.css b/examples/egocap/frontend/src/styles.css index 445a6f72a5..2495cb8cde 100644 --- a/examples/egocap/frontend/src/styles.css +++ b/examples/egocap/frontend/src/styles.css @@ -787,6 +787,13 @@ button.step:hover { overflow-wrap: anywhere; } +/* A device's other name: never in the row's outcome colour, since it states no finding. */ +.check-source { + grid-column: 2; + color: var(--text-secondary); + overflow-wrap: anywhere; +} + .check-row--pass .check-mark { color: var(--positive); } diff --git a/examples/egocap/tests/backend/test_setup_checks.py b/examples/egocap/tests/backend/test_setup_checks.py index 32d8e29828..d78b352d34 100644 --- a/examples/egocap/tests/backend/test_setup_checks.py +++ b/examples/egocap/tests/backend/test_setup_checks.py @@ -157,7 +157,9 @@ def test_a_device_the_station_requires_fails_when_it_is_not_connected_and_the_ot assert first_warning(items) == "Left controller: not connected" -def test_a_device_the_station_requires_is_named_as_the_station_tab_names_it_and_no_other_device_is(tmp_path): +def test_a_device_a_station_can_require_has_the_station_tabs_name_whether_or_not_this_station_requires_it( + tmp_path, +): # The capture session describes its devices in its own words; a glove is a "hand" to it. devices = ( DeviceFact("Pico headset", True, headset=True, kind="headset"), @@ -165,24 +167,45 @@ def test_a_device_the_station_requires_is_named_as_the_station_tab_names_it_and_ DeviceFact("Right hand", False, "unavailable", kind="glove_right"), DeviceFact("Waist tracker", False, "degraded"), ) - said = _items(tmp_path, _facts(devices=devices, mock=True)) - # A station that requires nothing shows every device exactly as the session describes it, as it always did. - assert [(item.label, item.status) for item in said if item.group == "tracking"] == [ - ("Pico headset", PASS), - ("Left hand", WARN), - ("Right hand", WARN), - ("Waist tracker", WARN), + + def rows(required: tuple[str, ...]) -> list[tuple[str, str | None, str]]: + items = _items(tmp_path, _facts(devices=devices, mock=True), required_devices=required) + return [(item.label, item.reported_as, item.status) for item in items if item.group == "tracking"] + + # One name for a device in every row, the Station tab's, with the session's own name beside it. A device no + # station can require has only the session's name, which then stands as its label. + assert rows(()) == [ + ("Headset", "Pico headset", PASS), + ("Left glove", "Left hand", WARN), + ("Right glove", "Right hand", WARN), + ("Waist tracker", None, WARN), ] - items = _items(tmp_path, _facts(devices=devices, mock=True), required_devices=("glove_left",)) - # Only the row of a device the station requires takes the station's word, so the box that was ticked and - # the row that fails name one thing. - assert [(item.label, item.status) for item in items if item.group == "tracking"] == [ - ("Pico headset", PASS), - ("Left glove", FAIL), - ("Right hand", WARN), - ("Waist tracker", WARN), + # Requiring a device changes whether it holds a take, never what it is called. + assert rows(("glove_left",)) == [ + ("Headset", "Pico headset", PASS), + ("Left glove", "Left hand", FAIL), + ("Right glove", "Right hand", WARN), + ("Waist tracker", None, WARN), ] + items = _items(tmp_path, _facts(devices=devices, mock=True), required_devices=("glove_left",)) assert first_failure(items) == "Left glove: unavailable; this station requires it" + assert first_warning(items) == "Right glove: unavailable" + + +def test_the_sessions_name_of_a_device_is_not_repeated_where_it_is_the_stations_and_is_sent_with_the_item( + tmp_path, +): + devices = (HEADSET, DeviceFact("Left Manus glove", True, kind="glove_left")) + items = _items(tmp_path, _facts(devices=devices, mock=True), required_devices=("glove_right",)) + sent = [item.to_json() for item in items if item.group == "tracking"] + assert [(row["label"], row["reported_as"]) for row in sent] == [ + ("Headset", None), + ("Left glove", "Left Manus glove"), + # No device answers this requirement, so the session has no name for it. + ("Right glove", None), + ] + # Every item carries the field; only a tracking device's ever holds a name. + assert all(item.to_json()["reported_as"] is None for item in items if item.group != "tracking") def test_a_required_device_that_is_degraded_meets_its_requirement_only_while_it_still_delivers(tmp_path): @@ -212,10 +235,11 @@ def tracking(device: DeviceFact) -> tuple[list[tuple[str, str, str | None]], str rows, held = tracking(glove(detail, reason)) assert rows[1] == ("Left glove", FAIL, f"{detail}; this station requires it") assert held == f"Left glove: {detail}; this station requires it" - # A station that does not require the glove only warns of it, in every one of those states. + # A station that does not require the glove only warns of it, in every one of those states, under the name + # the row has when it is required. unrequired = _items(tmp_path, _facts(devices=(HEADSET, glove("device error", "DEVICE_ERROR")), mock=True)) assert first_failure(unrequired) is None - assert ("Left hand", WARN, "device error") in [(item.label, item.status, item.detail) for item in unrequired] + assert ("Left glove", WARN, "device error") in [(item.label, item.status, item.detail) for item in unrequired] # Any other state than connected is not there to record with: each holds the take. for state in ("unavailable", "unknown", "initializing", "disconnected", "failed"): gone = (HEADSET, DeviceFact("Left hand", False, state, kind="glove_left")) @@ -598,4 +622,11 @@ def test_the_first_failure_reads_as_one_phrase(): ] assert first_failure(items) == "Gloves" and first_warning(items) is None assert first_warning([CheckItem("d", "tracking", "Glove", WARN, "degraded")]) == "Glove: degraded" - assert items[2].to_json() == {"id": "c", "group": "system", "label": "Cam", "status": "fail", "detail": "x"} + assert items[2].to_json() == { + "id": "c", + "group": "system", + "label": "Cam", + "status": "fail", + "detail": "x", + "reported_as": None, + } diff --git a/examples/egocap/tests/backend/test_setup_service.py b/examples/egocap/tests/backend/test_setup_service.py index ae0f0fda0c..cf7317fb58 100644 --- a/examples/egocap/tests/backend/test_setup_service.py +++ b/examples/egocap/tests/backend/test_setup_service.py @@ -254,6 +254,7 @@ async def test_a_failed_glove_calibration_is_shown_as_failed_and_holds_no_take_t "label": "Glove calibration", "status": "fail", "detail": problem, + "reported_as": None, } # It is shown as failed, in the step too. It is not what holds a take: the take's own gate is, which is # asked as the take is admitted and for the take's operator, not for whoever was in use a moment ago. From 6fbd3fae7a4517d21b932c49f71d7913cb538042 Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 09:56:04 -0800 Subject: [PATCH 10/24] egocap: with no operator in use the glove calibration item says a take brings it in The checklist's Glove calibration item read "no operator name is set ... enter the operator name on the recording page" while the recording page showed an operator. The name is kept by the page and reaches the backend only with a take, so until a take that names an operator is asked for in a run the backend has no operator in use and cannot say whether a page has a name. The sentence now says what the backend knows and what brings the calibration in: no take naming an operator has been asked for in this run yet, and Record loads it for the operator named on the recording page. It is the one sentence for that state, for the checklist with and without the token and for the Glove calibration tool. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- examples/egocap/CALIBRATION_TOOLS.md | 2 +- examples/egocap/backend/README.md | 5 ++++- .../egocap/backend/egocap_web/glove_pairs.py | 5 ++++- .../egocap/tests/backend/test_glove_routes.py | 4 ++-- .../egocap/tests/backend/test_glove_service.py | 17 ++++++++++++++++- 5 files changed, 27 insertions(+), 6 deletions(-) diff --git a/examples/egocap/CALIBRATION_TOOLS.md b/examples/egocap/CALIBRATION_TOOLS.md index 774053a908..8d8d12ab68 100644 --- a/examples/egocap/CALIBRATION_TOOLS.md +++ b/examples/egocap/CALIBRATION_TOOLS.md @@ -1225,7 +1225,7 @@ item for a reader with the token, and by Record where calibration is required. | When | The sentence | | --- | --- | -| No operator name is set. | *no operator name is set, so no glove calibration is loaded; enter the operator name on the recording page* | +| Nobody is the operator in use: no take that names one has been asked for in this run. The backend hears an operator's name only with a take, whatever name the recording page shows. | *no take naming an operator has been asked for in this run yet, so no glove calibration is loaded; it is loaded for the operator named on the recording page when Record is pressed* | | The name is too long to name files, or differs from another operator's only in capital and small letters on a disk that does not tell them apart. | The two sentences under "Whose files, and where they are kept". | | Neither file is listed. | *there is no glove calibration for Alex; open Glove calibration under Settings, Devices to make one* | | One file is listed. | *only the left glove has a calibration file for Alex, Alex_right.mcal is missing; calibrate the gloves again, the two files are made together* | diff --git a/examples/egocap/backend/README.md b/examples/egocap/backend/README.md index 8e7fdbee19..98bf5afce4 100644 --- a/examples/egocap/backend/README.md +++ b/examples/egocap/backend/README.md @@ -285,7 +285,10 @@ The flow is station, devices, record, wrap-up ([`setup_service.py`](egocap_web/s operator has no pair, a file was refused, or the pair waits for a take to end (see [Gloves](#gloves)). The checklist is read without a token, so the item names no operator and no file: `the operator's glove calibration is loaded`, and in place of a sentence that names either `the operator in use has no glove calibration that can - be used; Glove calibration under Settings, Devices says why`. A request that carries `X-Control-Token` gets the + be used; Glove calibration under Settings, Devices says why`. Until a take that names an operator is asked for + in a run there is no operator in use, whatever name a page shows, since the backend hears the name only with a + take; the item then says that no such take has been asked for yet and that Record loads the calibration. + A request that carries `X-Control-Token` gets the detail in full (`for Alex: Alex_left.mcal and Alex_right.mcal`, or the sentence that says why). The item holds no take through the checklist's last result (`setup_checks.HELD_AT_THE_TAKE`): where calibration is required the take itself is refused, by the gate that is asked as the take is admitted, for the take's own operator, a diff --git a/examples/egocap/backend/egocap_web/glove_pairs.py b/examples/egocap/backend/egocap_web/glove_pairs.py index aa0858287d..387c0e3db3 100644 --- a/examples/egocap/backend/egocap_web/glove_pairs.py +++ b/examples/egocap/backend/egocap_web/glove_pairs.py @@ -81,8 +81,11 @@ #: writes a ``-`` only at its start, after ``0``, and to close a character's number. _ATTEMPT_LEFT = re.compile(rf"(cal-[0-9a-f]{{12}})_{LEFT}\.mcal") +#: Nobody is the operator in use. The backend hears an operator's name only with a take, so this says what +#: brings the calibration in, and not that a page has no name: the page may well show one. NO_OPERATOR = ( - "no operator name is set, so no glove calibration is loaded; enter the operator name on the recording page" + "no take naming an operator has been asked for in this run yet, so no glove calibration is loaded; it is " + "loaded for the operator named on the recording page when Record is pressed" ) TOO_LONG = ( 'the operator name "{operator}" is too long to name glove calibration files: a name can have up to ' diff --git a/examples/egocap/tests/backend/test_glove_routes.py b/examples/egocap/tests/backend/test_glove_routes.py index bdb090fa8e..af4a5acba9 100644 --- a/examples/egocap/tests/backend/test_glove_routes.py +++ b/examples/egocap/tests/backend/test_glove_routes.py @@ -359,8 +359,8 @@ def test_the_application_loads_the_pair_of_the_operator_whose_take_is_asked_for_ auth = {"X-Control-Token": context.control_token} _capturing(client) first = _capture_session(client) - # Nobody has asked for a take: no operator is in use, no file is loaded, and the checklist says to - # enter a name, to a page with the token and to one without alike. + # Nobody has asked for a take: no operator is in use, no file is loaded, and the checklist says + # that a take brings the calibration in, to a page with the token and to one without alike. assert _gloves(client)["problem"] == pairs.NO_OPERATOR _poll(lambda: _glove_check(client)["detail"] == pairs.NO_OPERATOR) assert (_glove_check(client)["status"], _glove_check(client, auth)["detail"]) == ( diff --git a/examples/egocap/tests/backend/test_glove_service.py b/examples/egocap/tests/backend/test_glove_service.py index 2e8cdbf997..4fbb2ab475 100644 --- a/examples/egocap/tests/backend/test_glove_service.py +++ b/examples/egocap/tests/backend/test_glove_service.py @@ -373,7 +373,7 @@ async def test_the_operator_the_station_names_has_their_pair_passed_at_the_first assert rig.gloves.uses_gloves and rig.gloves.capture_note() is None -async def test_with_no_operator_capture_starts_without_files_and_says_to_enter_a_name(make_rig): +async def test_with_no_operator_in_use_capture_starts_without_files_and_says_a_take_loads_them(make_rig): rig = await make_rig() await _capturing(rig, None) assert rig.files() == NO_FILES @@ -381,8 +381,23 @@ async def test_with_no_operator_capture_starts_without_files_and_says_to_enter_a assert state["uses_gloves"] and state["loaded"] is None assert (state["operator"], state["in_use"], state["current"], state["expected"]) == (None, None, True, None) assert state["problem"] == pairs.NO_OPERATOR + # The backend hears an operator's name only with a take, so it cannot say that a page has none: it says + # what it knows, and what brings the calibration in. + assert pairs.NO_OPERATOR == ( + "no take naming an operator has been asked for in this run yet, so no glove calibration is loaded; it is " + "loaded for the operator named on the recording page when Record is pressed" + ) + assert "no operator name is set" not in pairs.NO_OPERATOR + # A page that names its operator to look their files up is shown them, and is still not who records. + write_pair(rig.station.directory, "Alex") + assert await rig.gloves.look_up("Alex") == "Alex" + assert rig.gloves.fact() == GloveFact(pairs.NO_OPERATOR) and rig.gloves.state()["in_use"] is None # A take that names nobody is not the glove service's to hold, and makes nobody the operator in use. assert await rig.take("") is None and rig.gloves.state()["in_use"] is None + assert rig.gloves.fact() == GloveFact(pairs.NO_OPERATOR) + # The take that names the operator is what the sentence said it would be. + await rig.recording("Alex") + assert rig.gloves.fact() == GloveFact(None, service.PUBLIC_LOADED) and rig.files() == ALEX async def test_a_pair_with_one_side_missing_is_refused_naming_the_missing_file(make_rig): From c42c7eb78be1e1394c22c69a6e125e53d4e84ee9 Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 09:58:26 -0800 Subject: [PATCH 11/24] egocap: a warning in the Devices step says recording is not blocked The Devices step names a warning and added "takes are not held", which reads as takes that are not kept. It means that the warning does not stop a take from starting. The clause is now "recording is not blocked", one named sentence of the setup service, and the guide that quotes it says the same. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- examples/egocap/LIVEKIT_PREVIEW.md | 2 +- examples/egocap/backend/egocap_web/setup_service.py | 5 ++++- examples/egocap/frontend/src/setupTestDoubles.ts | 2 +- examples/egocap/tests/backend/test_setup_routes.py | 2 +- examples/egocap/tests/backend/test_setup_service.py | 8 ++++---- 5 files changed, 11 insertions(+), 8 deletions(-) diff --git a/examples/egocap/LIVEKIT_PREVIEW.md b/examples/egocap/LIVEKIT_PREVIEW.md index 0e580d1277..7164f1f5c2 100644 --- a/examples/egocap/LIVEKIT_PREVIEW.md +++ b/examples/egocap/LIVEKIT_PREVIEW.md @@ -125,7 +125,7 @@ view therefore tells the backend, every two seconds, what its preview receives o A stream that cannot be recorded at all still fails, as before. A report never fails the item and never holds a take, and the page says so: a warning is listed as "Advisory: does not hold recording.", the Devices step reads -"takes are not held", and each sentence above names the recorder as what checks next. A report is one browser's +"recording is not blocked", and each sentence above names the recorder as what checks next. A report is one browser's observation, and a browser can fail to receive video the recorder would receive (another network path, a codec the browser lacks). What refuses a take is the recorder itself, which joins the room when the take starts and gives up, with its reason, when a stream sends no frame within ten seconds. diff --git a/examples/egocap/backend/egocap_web/setup_service.py b/examples/egocap/backend/egocap_web/setup_service.py index 5bdc084281..e7946bde6b 100644 --- a/examples/egocap/backend/egocap_web/setup_service.py +++ b/examples/egocap/backend/egocap_web/setup_service.py @@ -62,6 +62,9 @@ #: Why a take is held while no current result exists: before the first one, just after the station in use #: changed, or while an evaluation is stuck. CHECKS_PENDING = "the station checks are being evaluated" +#: What follows a warning in the Devices step: the finding is named, and it does not stop a take from starting. +#: Say it of recording: said of takes, "not held" reads as "not kept". +NOT_BLOCKED = "recording is not blocked" def capture_facts( @@ -373,5 +376,5 @@ def _devices_step(items: list[CheckItem]) -> dict[str, Any]: return _step("devices", "Devices", ATTENTION, failure) warning = first_warning(items) if warning is not None: - return _step("devices", "Devices", DONE, f"{warning}; takes are not held") + return _step("devices", "Devices", DONE, f"{warning}; {NOT_BLOCKED}") return _step("devices", "Devices", DONE, "all checks pass") diff --git a/examples/egocap/frontend/src/setupTestDoubles.ts b/examples/egocap/frontend/src/setupTestDoubles.ts index a369d214d8..6e067f9722 100644 --- a/examples/egocap/frontend/src/setupTestDoubles.ts +++ b/examples/egocap/frontend/src/setupTestDoubles.ts @@ -47,7 +47,7 @@ const MISSING_CALIBRATION = "missing head_intrinsics.json, head_extrinsics.json" * holds nothing, with the Devices step done. */ export const SETUP_ADVISED: SetupStatus = { ...SETUP_READY, - steps: SETUP_READY.steps.map((step) => (step.id === "devices" ? { ...step, detail: "Camera calibration: missing: head_camera_intrinsics.json; takes are not held" } : step)), + steps: SETUP_READY.steps.map((step) => (step.id === "devices" ? { ...step, detail: "Camera calibration: missing: head_camera_intrinsics.json; recording is not blocked" } : step)), checks: SETUP_READY.checks.map((check) => (check.id === "calibration" ? { ...check, status: "warn", detail: MISSING_CALIBRATION } : check)), }; diff --git a/examples/egocap/tests/backend/test_setup_routes.py b/examples/egocap/tests/backend/test_setup_routes.py index a99660d4e4..dbf5468138 100644 --- a/examples/egocap/tests/backend/test_setup_routes.py +++ b/examples/egocap/tests/backend/test_setup_routes.py @@ -168,7 +168,7 @@ def test_the_flow_and_the_live_checklist_are_read_openly(tmp_path, monkeypatch): world.headset_connected = False warned = client.get("/api/setup").json() assert warned["blocked_reason"] is None - assert _steps(warned)["devices"] == ("done", "Headset: disconnected; takes are not held") + assert _steps(warned)["devices"] == ("done", "Headset: disconnected; recording is not blocked") assert {item["status"] for item in warned["checks"]} == {"pass", "warn", "skip"} world.tracking_fresh = False held = client.get("/api/setup").json() diff --git a/examples/egocap/tests/backend/test_setup_service.py b/examples/egocap/tests/backend/test_setup_service.py index cf7317fb58..963843b84d 100644 --- a/examples/egocap/tests/backend/test_setup_service.py +++ b/examples/egocap/tests/backend/test_setup_service.py @@ -193,7 +193,7 @@ async def test_missing_calibration_is_advisory_unless_the_deployment_requires_it assert setup.block_reason() is None status = _status(setup) assert status["blocked_reason"] is None - assert _steps(setup)["devices"] == ("done", f"{missing}; takes are not held") + assert _steps(setup)["devices"] == ("done", f"{missing}; recording is not blocked") calibration = next(item for item in status["checks"] if item["id"] == "calibration") assert (calibration["label"], calibration["status"]) == ("Camera calibration", "warn") assert calibration["detail"] == "missing: " + ", ".join(CALIBRATION) @@ -307,7 +307,7 @@ async def test_a_device_that_is_not_connected_does_not_hold_a_take(tmp_path): ) await setup.refresh() assert setup.block_reason() is None - assert _steps(setup)["devices"] == ("done", "Glove: degraded; takes are not held") + assert _steps(setup)["devices"] == ("done", "Glove: degraded; recording is not blocked") async def test_a_device_the_station_requires_holds_a_take_until_it_connects_and_says_why(tmp_path): @@ -344,7 +344,7 @@ async def test_a_device_the_station_requires_holds_a_take_until_it_connects_and_ await stations.update(stations.registry.selected_id, {"required_devices": []}) await setup.refresh() assert setup.block_reason() is None - assert _steps(setup)["devices"] == ("done", "Headset: disconnected; takes are not held") + assert _steps(setup)["devices"] == ("done", "Headset: disconnected; recording is not blocked") async def test_a_required_device_that_still_delivers_with_a_problem_does_not_hold_the_station(tmp_path): @@ -359,7 +359,7 @@ def glove(detail: str, reason: str) -> DeviceFact: world.facts = _healthy(devices=(headset, glove("glove calibration failed", "CALIBRATION_FAILED"))) await setup.refresh() assert setup.block_reason() is None - assert _steps(setup)["devices"] == ("done", "Left glove: glove calibration failed; takes are not held") + assert _steps(setup)["devices"] == ("done", "Left glove: glove calibration failed; recording is not blocked") # Degraded with nothing to send, it holds: Record would save a take without the glove's data. silent = "glove present but has no current usable skeleton data" world.facts = _healthy(devices=(headset, glove(silent, "NO_CURRENT_DATA"))) From b39f14047ad573544b08e0e72ec968cf0e8453fd Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 10:09:43 -0800 Subject: [PATCH 12/24] egocap: the launcher passes the bridge's bitrate maximum and keyframe period on when asked The launcher started the bridge with neither, so the bridge's defaults always stood: a keyframe every 30 frames, which is one a second at 30 fps and two a second at 60. A keyframe costs many times an ordinary frame; at a bitrate that is low for the picture, two a second can show as a pulse in quality. --bridge-bitrate-mbps and --bridge-idr-period pass the bridge its own --bitrate-mbps (the maximum for each track) and --idr-period (frames between keyframes). Neither is passed unless given, so a start without them has the bridge command line it had. A value the bridge would misread is refused on the command line, since the bridge reads its numbers without checking them. CAMERA_SETTINGS.md says what the two settings are, how the keyframe period reads at each frame rate, and where the time shown on the page is spent, leg by leg, with the log line that reports each. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- examples/egocap/CAMERA_SETTINGS.md | 38 +++++++++++- examples/egocap/README.md | 3 +- .../egocap/tests/tools/test_start_system.py | 61 +++++++++++++++++++ examples/egocap/tools/start_system.py | 52 ++++++++++++++++ 4 files changed, 151 insertions(+), 3 deletions(-) diff --git a/examples/egocap/CAMERA_SETTINGS.md b/examples/egocap/CAMERA_SETTINGS.md index d007e73a2e..faf14e866c 100644 --- a/examples/egocap/CAMERA_SETTINGS.md +++ b/examples/egocap/CAMERA_SETTINGS.md @@ -17,7 +17,7 @@ pass it with `--sender-config`. | SIPL platform file | Sensor geometry, sensor rate, trigger mode, link wiring | `sipl.platform_config_json` on the Orin (installed by the BSP or the camera deploy) | | Sender (Orin) | Output frame rate and bitrate, codec, timing records, TCP port | The sender profile, `configs/default-camera-settings.yaml` | | Receiver (PC) | Decoding, the CUDA IPC output and its stream names | Generated by the launcher from the sender profile | -| Bridge (PC) | Publishing into LiveKit; timestamp basis; the chrony addresses; output rate | Command-line flags, built by the launcher | +| Bridge (PC) | Publishing into LiveKit; timestamp basis; the chrony addresses; output rate; its encoder's bitrate maximum and keyframe period | Command-line flags, built by the launcher; `--bridge-bitrate-mbps` and `--bridge-idr-period` pass the last two on | | CaptureServer | The stream descriptors the page reads (room, track, size, nominal fps, timestamp basis) | Generated by the launcher | The sender never reads exposure, gain, white balance, trigger frequency or clock-pin settings from its YAML, and there @@ -83,6 +83,39 @@ These settings fix what the timestamps mean; they do not reduce the actual delay against the link, queues in the kernel and the application, and encoder and decoder throughput. When a stamp is missing, timing is unqualified or the mapping has not settled, the page shows no figure instead of a guess. +**Where the time goes.** The figure on the page runs from the sensor's capture time to the frame being shown, so +it is the sum of four legs, each with its own log line to read it from: + +| Leg | What it holds | Where it is reported | +|---|---|---| +| Sender (Orin) | Acquiring the frame from the camera, the HEVC encode, and waiting for the other cameras where frames are sent together; a stream in the `mailbox` capture mode and one in `fifo` do not wait alike | The sender's KPI lines (`runtime.kpi`), from start of frame to sent | +| Link and receiver (PC) | The TCP link, the decode, and handing the picture to the bridge | The receiver's `decode[avs1]` lines | +| Bridge (PC) | The GPU steps (correction, downscale), the H.264 encode and the hand-over to LiveKit | The bridge's `[stats]` lines every 5 s: capture to ready, encode, bitrate and keyframes | +| LiveKit and the browser | The local room, the browser's buffer and decode, and the display | The page's figure less the legs above | + +The sender's leg and the browser's are usually the long ones; the receiver and the bridge's encode are short. A +difference between two runs smaller than the clock uncertainty the bridge reports is not a difference: the +capture time is carried across two clocks. + +### The bridge's bitrate maximum and keyframe period + +The bridge encodes each track for LiveKit with settings of its own, on the leg from the PC to the page. They are +not the sender's `output.bitrate_mbps` and `output.gop`, which belong to the HEVC leg from the Orin to the PC. +The launcher passes neither unless asked, so the bridge's defaults stand: + +| Launcher flag | Bridge flag | The bridge's default | Meaning | +|---|---|---|---| +| `--bridge-bitrate-mbps MBPS` | `--bitrate-mbps` | 8 | The most the encoder may use for each track. It starts lower and follows the target LiveKit's congestion control reports, never above this. | +| `--bridge-idr-period FRAMES` | `--idr-period` | 30 | Frames between keyframes of each track. | + +The keyframe period is counted in frames, so what it means in time follows the frame rate: the default is a +keyframe a second at 30 fps and two a second at 60 fps. A keyframe costs many times an ordinary frame; at a +bitrate that is low for the picture, two a second can show as a pulse in quality at the keyframe rate. A longer +period is the remedy: give `--bridge-idr-period` more frames than the default. The price is that a +viewer who joins, or who lost a frame, waits longer for the next keyframe unless one is asked for. Raising the +maximum does not by itself raise the rate: the encoder follows LiveKit's target, which the `[stats]` line prints +beside the rate in use. + ## A profile for three cameras A station with a head camera and two wrist cameras on one Orin runs them as three mono streams of one profile. @@ -147,7 +180,8 @@ adds them up and prints the sum at start (`3 streams at 30 fps, 12 Mbit/s in all the sum. Whether the sum fits the link is the station's to make sure of: measure the link with `deploy_sender.py user@orin linktest` and leave headroom. `--bitrate-mbps` sets every stream to the same figure. The bridge's own bitrate is a separate setting on the other leg, from the PC into LiveKit: its `--bitrate-mbps` is a maximum for -each track, 8 Mbit/s unless given, which the launcher does not pass. The bridge's README says the encoder starts +each track, 8 Mbit/s unless given, which the launcher passes only when started with `--bridge-bitrate-mbps` (see +[The bridge's bitrate maximum and keyframe period](#the-bridges-bitrate-maximum-and-keyframe-period)). The bridge's README says the encoder starts at 2 Mbps and follows LiveKit's congestion control up to that maximum, that a 20 Mbps maximum on the head built a standing backlog of about 1.2 s, and to keep the maximum near 8 Mbps; with three tracks the room can therefore carry up to three times that. diff --git a/examples/egocap/README.md b/examples/egocap/README.md index 2a09518898..4a1a2a2fae 100644 --- a/examples/egocap/README.md +++ b/examples/egocap/README.md @@ -410,7 +410,8 @@ scripts. The sender settings come from the checked-in profile `configs/default-camera-settings.yaml` (30 fps, 4 Mbit/s HEVC). Pass another file with `--sender-config`, or override single values with `--fps`, `--bitrate-mbps` and `--sender-port`; the receiver, bridge and CaptureServer descriptor are -built from the same effective values. [`CAMERA_SETTINGS.md`](CAMERA_SETTINGS.md) says which component owns which +built from the same effective values. `--bridge-bitrate-mbps` and `--bridge-idr-period` pass the bridge its own +bitrate maximum and keyframe period for each LiveKit track; without them the bridge's defaults stand. [`CAMERA_SETTINGS.md`](CAMERA_SETTINGS.md) says which component owns which setting and lists every key. **All the station's cameras.** A profile may hold from one to three mono streams, one for each station camera: diff --git a/examples/egocap/tests/tools/test_start_system.py b/examples/egocap/tests/tools/test_start_system.py index c6e51a4b57..dd4b000b1a 100644 --- a/examples/egocap/tests/tools/test_start_system.py +++ b/examples/egocap/tests/tools/test_start_system.py @@ -2433,3 +2433,64 @@ def test_every_taken_port_is_named_with_whose_it_is_and_one_nobody_can_name_says assert [(port.number, port.kind) for port in without] == [(9000, "tcp"), (8082, "tcp"), (5000, "tcp")] taken.clear() ss.refuse_taken_ports(needed) + + +# --- the bridge's own bitrate ceiling and keyframe period, passed through --------------------------------------- + + +def _bridge_words(recorded) -> list[str]: + return next(child.command for child in recorded.children if child.name == "bridge") + + +def test_without_its_flags_the_bridge_is_started_with_no_bitrate_ceiling_or_keyframe_period_of_the_launchers( + recorded_main, +): + assert ss.main([*ORIN_ARGV, *CAMERA_ARGS]) == 0 + bridge = _bridge_words(recorded_main) + # The bridge's own defaults stand: its command line is the one it had before the flags existed. + assert "--bitrate-mbps" not in bridge and "--idr-period" not in bridge + assert bridge[bridge.index("--fps") + 2] == "--timestamp-basis" + assert ss.bridge_encoder_arguments(None, None) == [] + + +def test_the_bridges_bitrate_ceiling_and_keyframe_period_are_passed_under_the_bridges_own_flag_names( + recorded_main, +): + argv = [*ORIN_ARGV, *CAMERA_ARGS, "--bridge-bitrate-mbps", "6", "--bridge-idr-period", "90"] + assert ss.main(argv) == 0 + bridge = _bridge_words(recorded_main) + at = bridge.index("--fps") + # After the rate they belong with, each under the name the bridge reads it by. + assert bridge[at : at + 6] == ["--fps", "30", "--bitrate-mbps", "6", "--idr-period", "90"] + assert bridge[at + 6] == "--timestamp-basis" + # The sender's own bitrate is another setting, on the other leg, and is left as the profile has it. + sender = yaml.safe_load((recorded_main.workdir / "sender.yaml").read_text()) + assert sender["streams"][0]["output"]["bitrate_mbps"] == 4 + + +def test_either_bridge_setting_can_be_given_alone_and_a_fraction_of_a_megabit_is_passed_as_written(recorded_main): + assert ss.main([*ORIN_ARGV, *CAMERA_ARGS, "--bridge-idr-period", "60"]) == 0 + bridge = _bridge_words(recorded_main) + assert "--bitrate-mbps" not in bridge + assert bridge[bridge.index("--idr-period") + 1] == "60" + assert ss.bridge_encoder_arguments("2.5", None) == ["--bitrate-mbps", "2.5"] + + +@pytest.mark.parametrize( + ("flag", "value", "said"), + [ + ("--bridge-bitrate-mbps", "0", "a bitrate above zero"), + ("--bridge-bitrate-mbps", "-4", "a bitrate above zero"), + ("--bridge-bitrate-mbps", "fast", "a bitrate above zero"), + ("--bridge-bitrate-mbps", "nan", "a bitrate above zero"), + ("--bridge-idr-period", "0", "a whole number of frames, at least 1"), + ("--bridge-idr-period", "2.5", "a whole number of frames, at least 1"), + ("--bridge-idr-period", "often", "a whole number of frames, at least 1"), + ], +) +def test_a_bridge_setting_the_bridge_would_misread_is_refused_on_the_command_line(capsys, flag, value, said): + # The bridge reads its numbers without checking them: a word would become zero there. + with pytest.raises(SystemExit) as refused: + ss.parse_args([flag, value]) + assert refused.value.code == 2 + assert said in capsys.readouterr().err diff --git a/examples/egocap/tools/start_system.py b/examples/egocap/tools/start_system.py index 16403b32a5..f4d919ee33 100644 --- a/examples/egocap/tools/start_system.py +++ b/examples/egocap/tools/start_system.py @@ -563,6 +563,42 @@ def bridge_timing_arguments( return [*flags, "--source-full-range"] if settings.full_range else flags +def bridge_bitrate(text: str) -> str: + """A bitrate ceiling for the bridge as the operator wrote it, once it is a number above zero. + + Checked here because the bridge reads its numbers without checking them: a word would become zero there. + """ + try: + value = float(text) + except ValueError: + value = 0.0 + # Not-a-number compares false with everything, and infinity is no ceiling. + if not 0.0 < value < float("inf"): + raise argparse.ArgumentTypeError(f"needs a bitrate above zero, in Mbit/s, got {text!r}") + return text + + +def bridge_idr_period(text: str) -> str: + """A keyframe period for the bridge as the operator wrote it, once it is a whole number of frames.""" + if not text.isascii() or not text.isdigit() or int(text) < 1: + raise argparse.ArgumentTypeError(f"needs a whole number of frames, at least 1, got {text!r}") + return text + + +def bridge_encoder_arguments(bitrate_mbps: str | None, idr_period: str | None) -> list[str]: + """The bridge's own flags for what its encoder may use and how often it sends a keyframe, for each track. + + Given only for what the operator set: left out, the bridge's defaults stand and its command line is the one + it has without these settings. + """ + flags = [] + if bitrate_mbps is not None: + flags += ["--bitrate-mbps", bitrate_mbps] + if idr_period is not None: + flags += ["--idr-period", idr_period] + return flags + + @dataclass(frozen=True) class BridgedStream: """One receiver stream the bridge publishes, and the station camera it is.""" @@ -1622,6 +1658,21 @@ def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: help="override the HEVC bitrate of every stream of the profile; the streams share the link to this PC", ) parser.add_argument("--sender-port", type=int, help="override the profile's TCP video port") + parser.add_argument( + "--bridge-bitrate-mbps", + type=bridge_bitrate, + metavar="MBPS", + help="the most the bridge's encoder may use for each LiveKit track, passed to the bridge as " + "--bitrate-mbps (default: not passed, so the bridge's own maximum stands); the encoder follows LiveKit's " + "target below it. Not the sender's HEVC bitrate, which --bitrate-mbps sets", + ) + parser.add_argument( + "--bridge-idr-period", + type=bridge_idr_period, + metavar="FRAMES", + help="frames between keyframes of each LiveKit track, passed to the bridge as --idr-period (default: not " + "passed, so the bridge's own period stands, which is a second at 30 fps and half a second at 60)", + ) parser.add_argument( "--timesync-tool", type=Path, @@ -1940,6 +1991,7 @@ def main(argv: Sequence[str] | None = None) -> int: ), "--fps", str(sender.fps), + *bridge_encoder_arguments(args.bridge_bitrate_mbps, args.bridge_idr_period), *bridge_timing_arguments( sender, args.mock, From df0a247e629fee67d549514899d1312bfd4a6c3e Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 10:13:09 -0800 Subject: [PATCH 13/24] egocap: an example three-camera profile for an Orin that captures through Argus The launcher's three-camera example was written for the SIPL backend only. An Orin without the SIPL API cannot build that backend, so a station with such an Orin had no example to start from. configs/three-camera-settings.argus.example.yaml is the same three mono HEVC streams for the Argus backend, written from the sender's guide: no sipl section; each camera named by its Argus device index and sensor-mode index, which `argus_sender --list-modes` lists and which is not the number of the port the camera is cabled to; the head stream first, so that it is the sender's priority stream, captured in the default mailbox mode as a priority stream must be; the wrist streams in fifo, where the sender sends the frame closest in time to the head's. Every value that belongs to one station is a placeholder, and the launcher refuses the file while one is left, as it does the SIPL example. CAMERA_SETTINGS.md says which example a station uses and how to tell (the deploy tool's check prints whether the SIPL API is there), what differs between the two, and what the capture modes are. The example was not run on hardware, and the guide says so. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- examples/egocap/CAMERA_SETTINGS.md | 45 +++++++- examples/egocap/README.md | 6 +- .../three-camera-settings.argus.example.yaml | 87 ++++++++++++++ .../tools/test_start_system_three_cameras.py | 108 ++++++++++++++++++ 4 files changed, 241 insertions(+), 5 deletions(-) create mode 100644 examples/egocap/configs/three-camera-settings.argus.example.yaml diff --git a/examples/egocap/CAMERA_SETTINGS.md b/examples/egocap/CAMERA_SETTINGS.md index faf14e866c..6ad4315607 100644 --- a/examples/egocap/CAMERA_SETTINGS.md +++ b/examples/egocap/CAMERA_SETTINGS.md @@ -119,7 +119,10 @@ beside the rate in use. ## A profile for three cameras A station with a head camera and two wrist cameras on one Orin runs them as three mono streams of one profile. -[`configs/three-camera-settings.example.yaml`](configs/three-camera-settings.example.yaml) shows the structure. It +There is an example for each capture backend of the sender; [Which example a station uses](#which-example-a-station-uses) +says how to tell. [`configs/three-camera-settings.example.yaml`](configs/three-camera-settings.example.yaml) shows +the structure for the SIPL backend and +[`configs/three-camera-settings.argus.example.yaml`](configs/three-camera-settings.argus.example.yaml) for Argus. Each is an example, not a station's file: every value that belongs to one station is written `PLACEHOLDER_...` with a comment that says where the station finds it, and the launcher refuses the file while one is left (*... still holds placeholders (...); replace each with this station's value, which the comment beside it says where to @@ -138,11 +141,46 @@ launcher refuses to start without them. is a template for a station whose cameras all arrive through the bridge; with it, and a filled-in profile, the command above starts as written. +### Which example a station uses + +The sender captures through one of two backends, and a profile names the one it is written for +(`capture_backend`). Which a station can use is a property of its Orin: + +| The Orin | Backend | Example | +|---|---|---| +| has the SIPL API installed (`/usr/src/jetson_sipl_api`) | `sipl` | `configs/three-camera-settings.example.yaml` | +| has no SIPL API | `argus` | `configs/three-camera-settings.argus.example.yaml` | + +`deploy_sender.py user@orin check` tells: under *SIPL and multimedia packages* it prints `present: +/usr/src/jetson_sipl_api` or `missing: /usr/src/jetson_sipl_api`. It only reads; nothing on the Orin is changed. +Without the SIPL API the SIPL backend cannot be built there, so a SIPL profile's deploy fails; with it, either +backend can be chosen. + +What differs between the two examples: + +| | SIPL example | Argus example | +|---|---|---| +| What names the cameras | A platform file, a platform name and link masks (`sipl.*`), then each stream's SIPL pipeline index | Each stream's Argus device index and sensor-mode index (`cameras[].device`, `cameras[].mode`), read from `build/argus_sender --list-modes` in a deployed release on the Orin | +| `cameras[].device` is not | the GMSL link number | the number of the port the camera is cabled to | +| Picture size | The sensor's own; the backend does not scale | The sensor mode's own, or a smaller one the sender scales to | +| `nvargus-daemon` | Stopped by the launcher before the sender starts, since it holds the cameras | Left running: Argus capture goes through it | +| Colour range the bridge is told | Full range (`--source-full-range`) | Limited range, the bridge's default | +| Capture mode of each stream | Not used | `capture.mode`, below | + +**Capture modes on Argus.** The sender takes one stream for its priority stream: a stereo HEVC stream at the +highest rate when there is one, otherwise the first stream at the highest rate. In the example that is `head`, +which is listed first and runs at the rate all three share. The other streams' frames are matched to the priority +stream's. A priority stream is captured in the default mode, `mailbox`; the sender refuses one in `fifo`. The two +wrist streams are `fifo`: the sender keeps each one's last two frames and sends the one closest in time to the +head's frame, where a `mailbox` stream is asked for one frame at each tick and has no second one to choose from. +To make another camera the priority stream, list it first. `capture.fifo_length` belongs to a raw stream's own +queue and is not applied to an HEVC stream; left out, it is 3, the least the sender accepts with `fifo`. + **What the three streams share, and what each has of its own.** | Shared by all streams | Each stream's own | |---|---| -| One sender process and one deployment on the Orin, from one uploaded file | Its SIPL pipeline index (`cameras[].device`), which is not the GMSL link number | +| One sender process and one deployment on the Orin, from one uploaded file | Its SIPL pipeline index or Argus device index (`cameras[].device`), which is neither the GMSL link number nor a port's number | | One TCP connection to the PC (`network.port`), so one link carries all of them | Its picture size, which on the SIPL backend is the sensor's own | | One receiver process and one bridge process on the PC | Its HEVC bitrate (`output.bitrate_mbps`) | | One frame rate: the bridge's `--fps` is one value for every stream, so the launcher refuses streams at different rates | Its receiver output and CUDA IPC name, which is the stream's id | @@ -299,7 +337,8 @@ timestamps; it does not configure the Orin or join LiveKit for anyone. config, the mock sender's command, the deploy commands and the stream descriptor it writes were read by those programs' own parsers; the bridge's command line was held only to the rules its guide states, since the bridge needs CUDA to build. `configs/three-camera-settings.example.yaml` holds a placeholder for every station value - and was never deployed. A first run on a station must check: + and was never deployed; `configs/three-camera-settings.argus.example.yaml` was written from the sender's guide + and was never deployed either, and what it says of capture modes is the guide's, not a measurement. A first run on a station must check: - that each stream arrives as the camera its role says: cover one lens at a time and see which tile goes dark, against the `stream '': , ...` lines the launcher prints; - that each corrected picture is corrected with its own camera's calibration: straight edges come out straight diff --git a/examples/egocap/README.md b/examples/egocap/README.md index 4a1a2a2fae..8b33ea7584 100644 --- a/examples/egocap/README.md +++ b/examples/egocap/README.md @@ -431,8 +431,10 @@ The station file is part of the command: the default one requests CaptureServer refuses to start without. `recording/egocap/stations/ego_stations.bridged.example.yaml` is a template for a station whose cameras all arrive through the bridge. -`configs/three-camera-settings.example.yaml` shows such a profile, with a placeholder for every value that belongs -to one station; the launcher refuses it until each is filled in. The streams run at one frame rate, share the one +`configs/three-camera-settings.example.yaml` shows such a profile for an Orin with the SIPL API, and +`configs/three-camera-settings.argus.example.yaml` for one without it, which captures through Argus +([`CAMERA_SETTINGS.md`](CAMERA_SETTINGS.md#which-example-a-station-uses) says how to tell). Each has a placeholder +for every value that belongs to one station; the launcher refuses it until each is filled in. The streams run at one frame rate, share the one link between the Orin and the PC, and `--fps` and `--bitrate-mbps` set every stream alike. See [`CAMERA_SETTINGS.md`](CAMERA_SETTINGS.md#a-profile-for-three-cameras) for what the streams share, what the station file and the station's roles on the page must then name, and the bitrate. diff --git a/examples/egocap/configs/three-camera-settings.argus.example.yaml b/examples/egocap/configs/three-camera-settings.argus.example.yaml new file mode 100644 index 0000000000..b0a9465844 --- /dev/null +++ b/examples/egocap/configs/three-camera-settings.argus.example.yaml @@ -0,0 +1,87 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# An example sender profile for tools/start_system.py on a station with three GMSL cameras on one Orin whose sender +# captures through Argus: the profile for an Orin without the SIPL API, where the SIPL example beside this file +# cannot be built. `deploy_sender.py user@orin check` says which the Orin has (CAMERA_SETTINGS.md, "Which example a +# station uses"). The head camera and the two wrist cameras are each a mono HEVC stream of one sender. It shows the +# structure only. Every value that belongs to one station is written PLACEHOLDER_..., with a comment that says where +# the station finds it, and the launcher refuses the file while one is left. Copy it, fill the copy in and start with +# +# tools/start_system.py ... --sender-config YOUR_COPY --station-config YOUR_STATION_FILE \ +# --stream-role head=ego --stream-role left_wrist=wrist_left --stream-role right_wrist=wrist_right +# +# The station file is one that asks CaptureServer for no camera of its own, such as a copy of +# recording/egocap/stations/ego_stations.bridged.example.yaml, which names the streams by the ids used here. +# +# The launcher gives no stream a role by its name or its place here: --stream-role says which camera each one is. +# CAMERA_SETTINGS.md describes every key and what three streams share. This file was written from the sender's +# guide and has not been run on hardware. + +version: 1 +capture_backend: argus + +network: + bind: 0.0.0.0 + port: 5000 # TCP port the PC receiver connects to; all three streams travel over this one connection + +runtime: + frames: 0 # 0 = run until stopped + kpi: true # periodic rate and timing statistics in the sender log + log_interval_s: 1 + +# The receiver knows a stream by its place in this list and the bridge by its id, which is also the camera's name on +# the page, in the recordings and in the calibration solved for it. Keep the ids when the cabling changes. +streams: + - id: head + type: mono + # The sender's priority stream is the first one at the highest rate: this one, since all three run at one rate. + # The other cameras' frames are matched to its frames. A priority stream is captured in the default mode, + # mailbox, which keeps the newest frame; the sender refuses one in fifo. + capture: + mode: mailbox + cameras: + # The head camera's Argus device index and the index of the sensor mode it runs in. `build/argus_sender + # --list-modes`, run in a deployed release on the Orin, lists both for every camera Argus sees. A device + # index is Argus's own numbering: it is not the number of the port the camera is cabled to. + - {device: PLACEHOLDER_HEAD_ARGUS_DEVICE, mode: PLACEHOLDER_HEAD_SENSOR_MODE} + output: + codec: hevc + # The size this stream is sent at: the sensor mode's own size, or a smaller one, which the sender scales to. + width: PLACEHOLDER_HEAD_WIDTH + height: PLACEHOLDER_HEAD_HEIGHT + # One rate for all three streams, since the bridge runs every stream at one; at most the sensor mode's rate. + fps: PLACEHOLDER_FPS + # Megabits a second for this stream alone. The three share the link between the Orin and the PC. The + # launcher adds the three up and prints the sum; it sets no limit, so the sum must be made to fit what + # `deploy_sender.py user@orin linktest` measures there. + bitrate_mbps: PLACEHOLDER_HEAD_BITRATE_MBPS + + - id: left_wrist + type: mono + # fifo: the sender keeps this camera's last two frames and sends the one closest in time to the head's frame. + capture: + mode: fifo + cameras: + # As for the head camera. + - {device: PLACEHOLDER_LEFT_WRIST_ARGUS_DEVICE, mode: PLACEHOLDER_LEFT_WRIST_SENSOR_MODE} + output: + codec: hevc + width: PLACEHOLDER_LEFT_WRIST_WIDTH # the size this stream is sent at + height: PLACEHOLDER_LEFT_WRIST_HEIGHT + fps: PLACEHOLDER_FPS # the same rate as the head stream + bitrate_mbps: PLACEHOLDER_LEFT_WRIST_BITRATE_MBPS # this stream's share of the link + + - id: right_wrist + type: mono + capture: + mode: fifo # as for the left wrist + cameras: + # As for the head camera. + - {device: PLACEHOLDER_RIGHT_WRIST_ARGUS_DEVICE, mode: PLACEHOLDER_RIGHT_WRIST_SENSOR_MODE} + output: + codec: hevc + width: PLACEHOLDER_RIGHT_WRIST_WIDTH # the size this stream is sent at + height: PLACEHOLDER_RIGHT_WRIST_HEIGHT + fps: PLACEHOLDER_FPS # the same rate as the head stream + bitrate_mbps: PLACEHOLDER_RIGHT_WRIST_BITRATE_MBPS # this stream's share of the link diff --git a/examples/egocap/tests/tools/test_start_system_three_cameras.py b/examples/egocap/tests/tools/test_start_system_three_cameras.py index 718ff1f649..13f719b557 100644 --- a/examples/egocap/tests/tools/test_start_system_three_cameras.py +++ b/examples/egocap/tests/tools/test_start_system_three_cameras.py @@ -1366,6 +1366,114 @@ def test_the_example_profile_uses_only_keys_the_senders_parser_knows(): assert all(f'"{key}"' in parser for key in keys), sorted(key for key in keys if f'"{key}"' not in parser) +# --- the example profile for an Orin that captures through Argus ---------------------------------------------- + +ARGUS_EXAMPLE = ss.EGOCAP_ROOT / "configs" / "three-camera-settings.argus.example.yaml" + + +def test_the_argus_example_is_three_mono_hevc_streams_and_is_refused_as_shipped_for_its_placeholders( + recorded_main, capsys +): + example = yaml.safe_load(ARGUS_EXAMPLE.read_text()) + assert example["capture_backend"] == "argus" and "sipl" not in example + assert [stream["id"] for stream in example["streams"]] == ["head", "left_wrist", "right_wrist"] + assert [(stream["type"], stream["output"]["codec"]) for stream in example["streams"]] == [("mono", "hevc")] * 3 + err = _refused(recorded_main, capsys, _argv(ARGUS_EXAMPLE)) + assert err.startswith(f"error: {ARGUS_EXAMPLE.name} still holds placeholders (") + held = set(ss.placeholders(example)) + # Everything that belongs to a station: each camera's Argus device and sensor mode, sizes, rate, bitrate. + for index in range(3): + assert {f"streams[{index}].cameras[0].device", f"streams[{index}].cameras[0].mode"} <= held + for key in ("width", "height", "fps", "bitrate_mbps"): + assert f"streams[{index}].output.{key}" in held + # Nothing of the SIPL backend is asked of a station that has none. + assert not any(where.startswith("sipl") for where in held) + + +def test_the_argus_example_names_a_camera_by_its_argus_device_and_never_by_a_port(): + text = ARGUS_EXAMPLE.read_text() + example = yaml.safe_load(text) + devices = [stream["cameras"][0]["device"] for stream in example["streams"]] + assert devices == [ + "PLACEHOLDER_HEAD_ARGUS_DEVICE", + "PLACEHOLDER_LEFT_WRIST_ARGUS_DEVICE", + "PLACEHOLDER_RIGHT_WRIST_ARGUS_DEVICE", + ] + # It says where the index is read from and that it is not the port's number. + assert "--list-modes" in text and "not the number of the port" in text + # No station's own value is in it: every number a station would fill in is still a placeholder. + for stream in example["streams"]: + assert all(isinstance(value, str) for value in stream["cameras"][0].values()) + output = stream["output"] + assert all(isinstance(output[key], str) for key in ("width", "height", "fps", "bitrate_mbps")) + + +def test_the_argus_example_captures_the_head_as_the_senders_priority_stream_and_the_wrists_in_fifo(): + example = yaml.safe_load(ARGUS_EXAMPLE.read_text()) + # The sender takes the first stream at the highest rate for its priority stream, and refuses one in fifo. + assert [stream["capture"]["mode"] for stream in example["streams"]] == ["mailbox", "fifo", "fifo"] + # A fifo length is only read for a raw stream's own queue; an HEVC stream takes none. + assert all("fifo_length" not in stream["capture"] for stream in example["streams"]) + guide = (CAMERA_STREAMER / "argus_sender" / "README.md").read_text() + assert "A priority\nstream must use the default mailbox policy regardless of codec" in guide + assert "otherwise it uses the first maximum-rate stream" in guide + + +def _filled_for_argus(value, where: str): + """The Argus example with a station's values in place: a sensor mode beside what ``_filled`` fills in.""" + if isinstance(value, dict): + return {key: _filled_for_argus(inner, f"{where}.{key}") for key, inner in value.items()} + if isinstance(value, list): + return [_filled_for_argus(inner, f"{where}[{index}]") for index, inner in enumerate(value)] + if isinstance(value, str) and ss.PLACEHOLDER_MARK in value and where.endswith("cameras[0].mode"): + return 0 + return _filled(value, where) + + +def test_the_argus_example_with_a_stations_values_in_place_starts_three_cameras_without_anything_of_sipl( + recorded_main, station_calibration, tmp_path: Path +): + example = yaml.safe_load(ARGUS_EXAMPLE.read_text()) + profile = tmp_path / "station.yaml" + filled = _filled_for_argus(example, "") + assert ss.placeholders(filled) == [] + profile.write_text(yaml.safe_dump(filled, sort_keys=False)) + assert ss.main(_argv(profile, "--no-rectify")) == 0 + bridge = _child(recorded_main, "bridge").command + assert bridge.count("--stream") == 3 + assert [camera["role"] for camera in _state(recorded_main)["cameras"].values()] == [ + "ego", + "wrist_left", + "wrist_right", + ] + # An Argus sender: nvargus-daemon is left running, the deploy builds no SIPL backend, and the pictures are + # not signalled as full range. + assert not any("stop-daemon" in deploy or "--with-sipl" in deploy for deploy in recorded_main.deploys) + assert "--source-full-range" not in bridge + # The profile reaches the sender as the station filled it in, capture modes included. + sent = yaml.safe_load((recorded_main.workdir / "sender.yaml").read_text()) + assert [stream["capture"] for stream in sent["streams"]] == [ + {"mode": "mailbox"}, + {"mode": "fifo"}, + {"mode": "fifo"}, + ] + assert sent["capture_backend"] == "argus" + + +def test_the_argus_example_uses_only_keys_the_senders_parser_knows(): + parser = (CAMERA_STREAMER / "argus_sender" / "src" / "Config.cpp").read_text() + example = yaml.safe_load(ARGUS_EXAMPLE.read_text()) + keys = set(example) + for section in ("network", "runtime"): + keys |= set(example.get(section) or {}) + for stream in example["streams"]: + keys |= set(stream) | set(stream["output"]) | set(stream["capture"]) + keys |= {key for camera in stream["cameras"] for key in camera} + assert all(f'"{key}"' in parser for key in keys), sorted(key for key in keys if f'"{key}"' not in parser) + # The values the example does write are ones the parser takes. + assert '"mailbox"' in parser and '"fifo"' in parser and "argus" in parser + + # --- the one-camera start, held to what it was ------------------------------------------------------------------- ONE_CAMERA_RECEIVER = """version: 1 From 3dd75fda853f6b5d7df3579a5d241d80eed3daaa Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 10:14:43 -0800 Subject: [PATCH 14/24] egocap: the guides say the tracking bindings are built for the example's Python The example runs on Python 3.12 and imports the tracking bindings of the checkout it lives in. That checkout builds its bindings for Python 3.11 unless told otherwise, and a compiled module is found only by the Python it was built for, so the first real start failed on a missing module with nothing in the example's guides to say why. The example's README and CaptureServer's now give the configure flag, -DISAAC_TELEOP_PYTHON_VERSION=3.12, the error that bindings of another version produce, and that a build directory configured for another version cannot be switched and is deleted and configured again, as the build itself says. The launcher's guide also says that its output need not be piped to be kept. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- examples/egocap/README.md | 9 +++++++-- examples/egocap/capture_server/README.md | 13 +++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/examples/egocap/README.md b/examples/egocap/README.md index 8b33ea7584..ad24f3fc70 100644 --- a/examples/egocap/README.md +++ b/examples/egocap/README.md @@ -363,7 +363,9 @@ uv run python tools/start_system.py --orin user@orin --deploy-script PATH --live ``` It prints the page URL and the recording control token, and writes what it and its helpers print to -`launcher.log` in its run directory, which its first line names. CaptureServer runs real acquisition, which needs a built +`launcher.log` in its run directory, which its first line names; its output need not be piped into `tee` or a +file to be kept, and where it is piped all the same, the stop still runs to its end when the program at the other +end of the pipe ends first. CaptureServer runs real acquisition, which needs a built IsaacCapture checkout (`ISAAC_ROOT`) and tracking hardware, and it opens only the cameras it is given with `--capture-camera NAME=DEVICE_ID`. The default station file (`--station-config`) is the shipped example, which requests three cameras, so the launcher refuses to start unless each one is given; use a station file whose @@ -479,7 +481,10 @@ recording admission, recovery and shutdown); until then it is the supported way CaptureServer's real mode needs its own Python bindings built in an [IsaacCapture](https://github.com/NVIDIA/IsaacCapture) checkout (`ISAAC_ROOT`, the checkout root) -for tracking, and the `oak` extra plus a camera's device ID for OAK-D cameras. See +for tracking, and the `oak` extra plus a camera's device ID for OAK-D cameras. The bindings have to be built for +this example's Python, 3.12: configure the checkout with `-DISAAC_TELEOP_PYTHON_VERSION=3.12`, since its default +is 3.11 and bindings built for another Python are not found when this example imports them. A build directory +that was already configured for another Python cannot be switched; remove it and configure again. See [`capture_server/README.md`](capture_server/README.md) for exact setup and validated hardware. The backend and frontends are unchanged between mock and real mode — CaptureServer is the only process that differs. diff --git a/examples/egocap/capture_server/README.md b/examples/egocap/capture_server/README.md index 803a564639..1405f02dfb 100644 --- a/examples/egocap/capture_server/README.md +++ b/examples/egocap/capture_server/README.md @@ -47,6 +47,19 @@ in, once its Python bindings are built. The server imports `isaaccapture` only f never uses a bundled copy. Validated with `isaaccapture` 1.7+local (built from IsaacCapture commit `22026461c`), which also provides CloudXR runtime 6.3.0 and needs the project's Python 3.12. +The bindings are compiled for one Python version and are found only by that one. The checkout builds for Python +3.11 unless told otherwise, so build it for this project's: + +```sh +cmake -B build -DISAAC_TELEOP_PYTHON_VERSION=3.12 +cmake --build build --parallel +``` + +Bindings built for another version fail here with `ModuleNotFoundError: No module named +'isaaccapture.deviceio_trackers._deviceio_trackers'`, because the compiled module carries its Python version in +its file name. The version is kept in the build directory: one that was configured for another version refuses the +flag and says so; delete that build directory and configure again. + **CloudXR runtime.** Start the CloudXR service first, using the same build and the project's Python, so an unrelated globally installed SDK is not launched: From 7f160118c54098d152be0fb58a01bc3980b6c306 Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 11:52:06 -0800 Subject: [PATCH 15/24] egocap: a stop request cannot leave a child unregistered, and one that was lost is asked again Two ways were left in which a stop request stopped less than everything. A request raises where the main thread is. Raised between a child's creation and the line that registers it, it left that child running in its own session, unknown to the stop, and the launcher said that every program had stopped. A request is now held while a child is created and registered and raised when that block ends, so a child that exists is one the stop knows of. The helper that waits for the clocks is created under the same hold. What a request raises inside a finalizer is printed by the interpreter and dropped. The request then counted as made, nothing stopped, and every later Ctrl-C, SIGTERM and SIGHUP returned at once. Signals closer together than a second are still one request (a terminal's Ctrl-C and the copy a wrapper passes on); one that comes later, while the stop has not begun, asks again. Once the stop has begun no signal asks for it again: its own handlers take them, as before. The new tests run the launcher's own main() as a real process with real children in their own sessions, and place the signal at the instant each child's creation returns, and inside a finalizer. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- .../tools/test_start_system_real_stop.py | 277 ++++++++++++++++++ examples/egocap/tools/start_system.py | 79 ++++- 2 files changed, 344 insertions(+), 12 deletions(-) create mode 100644 examples/egocap/tests/tools/test_start_system_real_stop.py diff --git a/examples/egocap/tests/tools/test_start_system_real_stop.py b/examples/egocap/tests/tools/test_start_system_real_stop.py new file mode 100644 index 0000000000..9f0f95f67e --- /dev/null +++ b/examples/egocap/tests/tools/test_start_system_real_stop.py @@ -0,0 +1,277 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""The launcher's own ``main()`` and ``leave()`` run as a real process, its children real processes in sessions +of their own: a whole start with the Orin's chain, ended at moments a test places exactly. + +Every program the launcher starts is a stand-in that does nothing but be there: listen where the launcher waits +for it, and leave on the polite signal. What is changed for the run is where things are (a run directory the +test knows, free ports, a frontend that is "built") and the two commands the launcher builds for itself. The stop +is the launcher's own. Each child's process number is written down as the launcher creates it, so a test knows +of a child also where the launcher lost track of it. +""" + +from __future__ import annotations + +import os +import signal +import socket +import subprocess +import sys +import time +from pathlib import Path + +import pytest + +EGOCAP = Path(__file__).resolve().parents[2] + +#: A child of the launcher: there until the polite signal. It listens on its port, where it is given one, and +#: the receiver makes the socket's name the launcher waits for. +CHILD = """ +import os, signal, socket, sys, time +name = sys.argv[1] +signal.signal(signal.SIGINT, lambda *_: os._exit(0)) +port = os.environ.get("PORT_" + name.replace("-", "_")) +listener = socket.create_server(("127.0.0.1", int(port))) if port else None +if name == "receiver": + config = sys.argv[sys.argv.index("--config") + 1] + open(os.path.join(os.path.dirname(config), "camera_receiver.sock"), "w").close() +while True: + time.sleep(0.05) +""" + +#: The sender's deploy tool: ``run`` becomes the sender child; every other command succeeds at once. +DEPLOY = """ +import os, sys +if sys.argv[2] == "run": + os.execv(sys.executable, [sys.executable, os.environ["CHILD"], "sender"]) +print("deploy tool stand-in:", sys.argv[2], flush=True) +""" + +#: The timesync tool: the two helpers the launcher imports, and its commands; ``follow`` becomes the follower. +TIMESYNC = """ +import os, sys + + +def lan_address_toward(host): + return "192.0.2.1" + + +def reference_id_for(host): + return "C000020A" + + +if __name__ == "__main__": + if sys.argv[1] == "follow": + os.execv(sys.executable, [sys.executable, os.environ["CHILD"], "timesync-follower"]) + print("timesync stand-in:", sys.argv[1], flush=True) +""" + +#: Runs the launcher as its ``__main__`` block does. A test may have a signal sent at the instant one child's +#: creation returns (SIGNAL_AT), or inside a finalizer (SIGNAL_IN_FINALIZER), or an error raised where a child +#: would start (RAISE_AT). +DRIVER = """ +import os, signal, subprocess, sys +from pathlib import Path +sys.path.insert(0, sys.argv[1]) +import start_system as ss + +work = Path(os.environ["WORK"]) +ss.tempfile.mkdtemp = lambda **_: str(work / "run") +ss.FRONTEND_INDEX = work / "index.html" +for constant in ("CAPTURE_SERVER_PORT", "LIVEKIT_PORT", "LIVEKIT_RTC_TCP_PORT", "LIVEKIT_RTC_UDP_PORT"): + setattr(ss, constant, int(os.environ[constant])) +starting = [None] +real_start = ss.Stack.start + + +def start(self, name, command, *, grace_s=ss.DEFAULT_GRACE_S, **options): + if os.environ.get("RAISE_AT") == name: + raise RuntimeError(f"injected failure where {name} would start") + if name in ("capture-server", "backend"): + command = [sys.executable, os.environ["CHILD"], name] + starting[0] = name + return real_start(self, name, command, grace_s=min(grace_s, 2.0), **options) + + +ss.Stack.start = start +RealPopen = subprocess.Popen + + +class Popen(RealPopen): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + name = starting[0] + if name is not None and kwargs.get("start_new_session") and kwargs.get("stdout") not in (None, -1): + starting[0] = None + (work / "created" / name).write_text(str(self.pid)) + if os.environ.get("SIGNAL_AT") == name: + os.kill(os.getpid(), signal.SIGINT) + # The handler runs before the next line of Python: the child exists and is not yet registered. + + +subprocess.Popen = Popen +if os.environ.get("SIGNAL_IN_FINALIZER"): + real_del = RealPopen.__del__ + + def __del__(self, *args, **kwargs): + if isinstance(self.args, list) and "deploy" in self.args and os.environ.pop("SIGNAL_IN_FINALIZER", None): + os.kill(os.getpid(), signal.SIGINT) + # Inside a finalizer: what the handler raises here is printed by the interpreter and dropped. + return real_del(self, *args, **kwargs) + + RealPopen.__del__ = __del__ +ss.leave(ss.main(sys.argv[2:])) +""" + +CHILDREN = ["sender", "livekit", "capture-server", "backend", "receiver", "bridge", "timesync-follower"] + + +def _free_ports(kinds: str) -> list[int]: + """A port nobody holds for each letter of ``kinds`` (t for TCP, u for UDP), all held until all are found.""" + held = [] + for kind in kinds: + held.append(socket.socket(socket.AF_INET, socket.SOCK_STREAM if kind == "t" else socket.SOCK_DGRAM)) + held[-1].bind(("127.0.0.1", 0)) + ports = [one.getsockname()[1] for one in held] + for one in held: + one.close() + return ports + + +def _alive(pid: int) -> bool: + """Whether a process is there and is not merely waiting to be collected.""" + state = subprocess.run(["ps", "-o", "stat=", "-p", str(pid)], capture_output=True, text=True).stdout.strip() + return bool(state) and not state.startswith("Z") + + +class Launched: + """One run of the launcher in a directory of its own.""" + + def __init__(self, work: Path) -> None: + self.work = work + self.log = work / "run" / "launcher.log" + self.process: subprocess.Popen | None = None + for name, text in (("child.py", CHILD), ("deploy.py", DEPLOY), ("ts.py", TIMESYNC), ("driver.py", DRIVER)): + (work / name).write_text(text) + for name in ("livekit", "bridge"): + (work / f"{name}.sh").write_text(f"#!/bin/sh\nexec {sys.executable} {work / 'child.py'} {name}\n") + (work / f"{name}.sh").chmod(0o755) + for made in ("run", "created", "calibration"): + (work / made).mkdir() + (work / "index.html").write_text("") + (work / "station.yaml").write_text("stations:\n one:\n video_sources: []\n") + + def start(self, *, closed_output: bool = False, **settings: str) -> None: + """Start the launcher with the Orin's chain. ``settings`` go to the driver in its environment.""" + backend, capture, livekit, rtc_tcp, rtc_udp, chrony = _free_ports("ttttuu") + env = {key: value for key, value in os.environ.items() if not key.startswith("EGOCAP_")} + env |= { + "PYTHONPATH": os.pathsep.join( + str(EGOCAP / sub) for sub in ("recording", "backend", "capture_server", ".") + ), + "WORK": str(self.work), + "CHILD": str(self.work / "child.py"), + "EGOCAP_CALIBRATION_DIR": str(self.work / "calibration"), + # The 3D view is the real backend's; the stand-in has none, so its port is not this run's to need. + "EGOCAP_VISER_ENABLED": "0", + "CAPTURE_SERVER_PORT": str(capture), + "LIVEKIT_PORT": str(livekit), + "LIVEKIT_RTC_TCP_PORT": str(rtc_tcp), + "LIVEKIT_RTC_UDP_PORT": str(rtc_udp), + "PORT_capture_server": str(capture), + "PORT_livekit": str(livekit), + "PORT_backend": str(backend), + **settings, + } + argv = [sys.executable, str(self.work / "driver.py"), str(EGOCAP / "tools")] + argv += ["--orin", "user@192.0.2.10", "--deploy-script", str(self.work / "deploy.py")] + argv += ["--bridge", str(self.work / "bridge.sh"), "--livekit-server", str(self.work / "livekit.sh")] + argv += ["--receiver", f"{sys.executable} {self.work / 'child.py'} receiver"] + argv += ["--timesync-tool", str(self.work / "ts.py"), "--station-config", str(self.work / "station.yaml")] + argv += ["--backend-port", str(backend), "--chrony-cmd-port", str(chrony), "--no-rectify"] + if closed_output: + # Closed before the interpreter starts, which then has no output streams at all. + argv = ["/bin/sh", "-c", 'exec "$@" >&- 2>&-', "sh", *argv] + self.process = subprocess.Popen(argv, env=env, stdin=subprocess.DEVNULL) + else: + out = (self.work / "output.txt").open("w") + self.process = subprocess.Popen(argv, env=env, stdin=subprocess.DEVNULL, stdout=out, stderr=out) + + def said(self) -> str: + """What the launcher's own log holds so far.""" + return self.log.read_text() if self.log.exists() else "" + + def wait_until_up(self) -> None: + """Until the launcher has said the stack is up and has started the last child of the start.""" + deadline = time.monotonic() + 60 + while "Ctrl-C stops everything." not in self.said() or "timesync-follower" not in self.created(): + assert self.process.poll() is None, f"the launcher ended during the start:\n{self.said()}" + assert time.monotonic() < deadline, f"the stack never came up:\n{self.said()}" + time.sleep(0.05) + + def created(self) -> dict[str, int]: + """Every child the launcher created, by name, with its process number.""" + return {made.name: int(made.read_text()) for made in (self.work / "created").iterdir() if made.read_text()} + + def left_alive(self) -> list[str]: + """The children still alive, given a moment for what was killed to be collected.""" + deadline = time.monotonic() + 5 + while True: + alive = sorted(name for name, pid in self.created().items() if _alive(pid)) + if not alive or time.monotonic() >= deadline: + return alive + time.sleep(0.05) + + def end(self) -> None: + """Whatever a test left running is ended, the launcher first.""" + if self.process is not None and self.process.poll() is None: + self.process.kill() + if self.process is not None: + self.process.wait() + for pid in self.created().values(): + try: + os.killpg(pid, signal.SIGKILL) + except (ProcessLookupError, PermissionError): + pass + + +@pytest.fixture +def launched(tmp_path: Path): + run = Launched(tmp_path) + yield run + run.end() + + +@pytest.mark.parametrize("child", CHILDREN) +def test_a_stop_request_at_the_instant_a_child_is_created_stops_that_child_with_the_rest(launched, child): + launched.start(SIGNAL_AT=child) + assert launched.process.wait(timeout=90) == 0, launched.said() + # The child whose creation the request landed in was created, and is gone with every one before it. + assert child in launched.created() + assert launched.left_alive() == [] + said = launched.said() + assert "every program this run started has stopped" in said and "the Orin sender is stopped" in said + + +def test_a_stop_request_lost_in_a_finalizer_is_asked_again_by_the_next_ctrl_c(launched): + launched.start(SIGNAL_IN_FINALIZER="1") + launched.wait_until_up() + # The first request was raised where the interpreter drops what is raised, and stopped nothing. + assert sorted(launched.created()) == sorted(CHILDREN) and launched.process.poll() is None + time.sleep(1.2) + launched.process.send_signal(signal.SIGINT) + assert launched.process.wait(timeout=60) == 0, launched.said() + assert launched.left_alive() == [] + assert "every program this run started has stopped" in launched.said() + + +def test_two_stop_requests_at_one_instant_are_one_request(launched): + launched.start() + launched.wait_until_up() + # A terminal's Ctrl-C and the copy a wrapper passes on. + launched.process.send_signal(signal.SIGINT) + launched.process.send_signal(signal.SIGINT) + assert launched.process.wait(timeout=60) == 0, launched.said() + assert launched.left_alive() == [] diff --git a/examples/egocap/tools/start_system.py b/examples/egocap/tools/start_system.py index f4d919ee33..2a28aa3dc5 100644 --- a/examples/egocap/tools/start_system.py +++ b/examples/egocap/tools/start_system.py @@ -135,6 +135,9 @@ STOP_SIGNALS = tuple(sig for sig in (signal.SIGTERM, getattr(signal, "SIGHUP", None)) if sig is not None) # Seconds a killed child, and whatever is left of its process group, is given to be gone before it is reported. KILL_WAIT_S = 5.0 +# Signals that mean stop and come closer together than this are one request: a terminal's Ctrl-C and the copy a +# wrapper passes on. One that comes later, while nothing has stopped, asks again. +SAME_REQUEST_S = 1.0 # The launcher's own log in the run directory: what it and its helpers print, so its output need not be piped. LAUNCHER_LOG = "launcher.log" # Where CaptureServer listens: its own default port, which the backend's default address names too. @@ -1260,13 +1263,16 @@ def run_supervised(stack: "Stack", command: list[str]) -> int: A required child that dies meanwhile stops the helper and raises, instead of going unnoticed until it returns. """ - process = subprocess.Popen(command, **stack.helper_output) + process = None try: + # A stop request waits until the helper is one the ``finally`` below ends. + with stack.creating(): + process = subprocess.Popen(command, **stack.helper_output) while process.poll() is None: raise_if_a_child_exited(stack) time.sleep(1) finally: - if process.poll() is None: + if process is not None and process.poll() is None: process.kill() process.wait() return process.returncode @@ -1303,6 +1309,9 @@ def __init__(self, workdir: Path) -> None: #: The output arguments of a helper run beside the children (``RunLog.for_helper``); none sends its #: output straight to the terminal. self.helper_output: Mapping[str, int] = {} + #: What a process is created under, so that a stop request cannot land between its creation and the + #: line that makes the stop cover it (``StopRequest.held``); nothing by default. + self.creating: Callable[[], contextlib.AbstractContextManager[None]] = contextlib.nullcontext def start( self, @@ -1324,7 +1333,7 @@ def start( log = self.workdir / f"{name}.log" # A new session makes the child the leader of its own process group, so a signal to the group reaches # anything it spawned and never this script. - with log.open("w") as handle: + with self.creating(), log.open("w") as handle: try: process = subprocess.Popen( list(command), @@ -1337,9 +1346,10 @@ def start( except OSError as error: # A wrong tool path is an operator mistake, so say which tool instead of printing a traceback. raise StartupError(f"cannot start {name} ({command[0]}): {error}") from error - # Registering the child here is what makes stop_all() cover it even if a later step fails. - child = Managed(name, process, log, grace_s, leader_only, optional) - self.children.append(child) + # Registering the child here is what makes stop_all() cover it even if a later step fails. Inside + # the block that holds a stop request back: a child that exists is one the stop knows of. + child = Managed(name, process, log, grace_s, leader_only, optional) + self.children.append(child) print(f"started {name} (pid {process.pid}); log {log}") return child @@ -1539,24 +1549,66 @@ def leave(status: int) -> NoReturn: class StopRequest: """What ``main`` does on Ctrl-C, SIGTERM and SIGHUP: the first of them takes the Ctrl-C path, so a closed - terminal stops the stack like Ctrl-C does, and any that follows raises nothing. + terminal stops the stack like Ctrl-C does, and one that comes with it raises nothing. Two can arrive together: a terminal's Ctrl-C reaches the launcher and a wrapper that runs it, which may pass its own on. The second must not cut the stop off before it has begun; once the stop runs, its own handlers take such a signal as a request to hurry. + + A request is held while a child is being created (``held``): raised between the child's creation and its + registration it would leave a child the stop does not know of. And a request can be lost: what it raises + inside a finalizer is printed and dropped by the interpreter. So a signal that comes later than + ``SAME_REQUEST_S`` after the last request, while the stop has not begun, asks again. """ - def __init__(self) -> None: - """Nothing has asked for a stop yet.""" + def __init__(self, clock: Callable[[], float] = time.monotonic) -> None: + """Nothing has asked for a stop yet. ``clock`` tells how far apart two signals are.""" self.asked = False + self._clock = clock + self._asked_at = 0.0 + # While a child is being created a request waits; whether one came meanwhile. + self._held = False + self._waiting = False + # Once the stop has begun nothing asks for it again. + self._begun = False def __call__(self, signum, frame) -> None: - """Ask for the stop once, by raising ``KeyboardInterrupt`` where the main thread is.""" - if self.asked: + """Ask for the stop, by raising ``KeyboardInterrupt`` where the main thread is, unless the stop has + begun, this is the request just made, or a child is being created.""" + if self._begun: + return + # One that comes with the first is the same request; a later one found the first unanswered. + if self.asked and self._clock() - self._asked_at < SAME_REQUEST_S: return - self.asked = True + if self._held: + # Asked for once the child is registered, so that the stop finds it. + self._waiting = True + return + self._ask() + + def _ask(self) -> None: + """Note the request and when it was made, and raise it.""" + self.asked, self._asked_at = True, self._clock() raise KeyboardInterrupt + @contextlib.contextmanager + def held(self) -> Iterator[None]: + """Keep a stop request from raising inside the block; one that came meanwhile is raised when the block + has ended. For the lines between a child's creation and its registration.""" + self._held = True + try: + yield + finally: + self._held = False + if self._waiting: + self._waiting = False + self._ask() + + def begun(self) -> None: + """The stop that was asked for is being carried out: no later signal asks for it again. The stop's own + handlers take signals from here on, and this one again once they are put back.""" + self._begun = True + def control_token(log: Path) -> str | None: """The recording control token the backend prints at startup, once it has.""" @@ -1751,6 +1803,7 @@ def main(argv: Sequence[str] | None = None) -> int: log.open() print(f"launcher log: {log.path} (everything printed here is written there too)") helper = stack.helper_output = log.for_helper() + stack.creating = stop_request.held # The deploy is checked first so a missing tool fails before anything is running. if args.orin and args.mock: raise StartupError("--mock replaces the Orin sender with a local mock sender; do not pass --orin") @@ -2112,6 +2165,8 @@ def main(argv: Sequence[str] | None = None) -> int: print(f"error: {error}", file=sys.stderr) status = 1 finally: + # First of all: from here the stop's own handlers answer a signal, and none asks for the stop again. + stop_request.begun() stop_sender = [sys.executable, args.deploy_script, args.orin, "stop"] if orin_contacted else None left = shut_down(stack, stop_sender) # A remap table is tens of megabytes and nothing reads it once the bridge has stopped. The logs stay. From be3def978421844e975ea96c436dc9f977683117 Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 11:54:23 -0800 Subject: [PATCH 16/24] egocap: the launcher runs with its output closed, and its log holds an unexpected error's traceback Started with its output closed the interpreter has no output streams, and the launcher's log took the place of a stream that was not there: its first line failed. A missing stream is now what a closed pipe already was, an output that takes nothing: every line is logged, and the launcher runs and stops as with a terminal. An error nobody expected ended the launcher after its log was closed, so the traceback the interpreter prints reached the terminal only. It is now written into the log first, beside the run it ended, and is still printed once. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- .../tools/test_start_system_real_stop.py | 22 +++++++++++ examples/egocap/tools/start_system.py | 37 +++++++++++++++---- 2 files changed, 51 insertions(+), 8 deletions(-) diff --git a/examples/egocap/tests/tools/test_start_system_real_stop.py b/examples/egocap/tests/tools/test_start_system_real_stop.py index 9f0f95f67e..14b61c523a 100644 --- a/examples/egocap/tests/tools/test_start_system_real_stop.py +++ b/examples/egocap/tests/tools/test_start_system_real_stop.py @@ -275,3 +275,25 @@ def test_two_stop_requests_at_one_instant_are_one_request(launched): launched.process.send_signal(signal.SIGINT) assert launched.process.wait(timeout=60) == 0, launched.said() assert launched.left_alive() == [] + + +def test_started_with_its_output_closed_the_launcher_runs_and_stops_as_with_a_terminal(launched): + launched.start(closed_output=True) + launched.wait_until_up() + launched.process.send_signal(signal.SIGINT) + assert launched.process.wait(timeout=60) == 0, launched.said() + assert launched.left_alive() == [] + # With nowhere to print, its own log still holds the run from its first line to its last. + said = launched.said() + assert said.startswith("launcher log: ") and "every program this run started has stopped" in said + + +def test_an_unexpected_error_is_in_the_launchers_log_with_its_traceback_and_everything_is_stopped(launched): + launched.start(RAISE_AT="receiver") + assert launched.process.wait(timeout=90) == 1, launched.said() + assert launched.left_alive() == [] + said = launched.said() + assert "Traceback (most recent call last)" in said + assert "RuntimeError: injected failure where receiver would start" in said + # Shown once on the terminal too, as any error that ends a program is. + assert (launched.work / "output.txt").read_text().count("RuntimeError: injected failure") == 1 diff --git a/examples/egocap/tools/start_system.py b/examples/egocap/tools/start_system.py index 2a28aa3dc5..ce1fb4ea01 100644 --- a/examples/egocap/tools/start_system.py +++ b/examples/egocap/tools/start_system.py @@ -69,6 +69,7 @@ import tempfile import threading import time +import traceback import webbrowser from collections.abc import Callable, Iterator, Mapping, Sequence from dataclasses import dataclass @@ -1113,8 +1114,9 @@ class _Passed: """One of the launcher's output streams while a run log is open: what is written to it goes to the stream it stands for and into the log.""" - def __init__(self, log: "RunLog", stream: TextIO) -> None: - """Stand for ``stream``, passing what is written on through ``log``.""" + def __init__(self, log: "RunLog", stream: TextIO | None) -> None: + """Stand for ``stream``, passing what is written on through ``log``. A launcher started with that + output closed has no stream there: what it prints is then logged and shown nowhere.""" self._log = log self._stream = stream @@ -1188,13 +1190,12 @@ def for_helper(self) -> dict[str, int]: this launcher and never a terminal that went away.""" return {"stdout": self._helper_end, "stderr": self._helper_end} - def record(self, text: str, stream: TextIO) -> None: - """Write ``text`` into the log and on to ``stream``, which is given up on once it refuses a write.""" + def record(self, text: str, stream: TextIO | None) -> None: + """Write ``text`` into the log and on to ``stream``, which is given up on once it refuses a write. + None stands for an output the launcher was started without.""" with self._guard: - if self._file is not None: - self._file.write(text) - self._file.flush() - if id(stream) in self._gone: + self._keep(text) + if stream is None or id(stream) in self._gone: return try: stream.write(text) @@ -1203,6 +1204,18 @@ def record(self, text: str, stream: TextIO) -> None: # The reader of a pipe ended, or the stream was closed: the stop this may be part of goes on. self._gone.add(id(stream)) + def _keep(self, text: str) -> None: + """Write into the file, while it is open; the caller holds the guard.""" + if self._file is not None: + self._file.write(text) + self._file.flush() + + def keep(self, text: str) -> None: + """Write ``text`` into the log only: for what reaches the terminal by another way, such as the + traceback the interpreter prints for an error that ends the program, after this log is closed.""" + with self._guard: + self._keep(text) + def _relay(self, read_end: int) -> None: """Pass on what helpers write until every writer has closed the pipe; the reader thread's work.""" decoder = codecs.getincrementaldecoder("utf-8")(errors="replace") @@ -1538,6 +1551,9 @@ def leave(status: int) -> NoReturn: # Everything is stopped by now: a Ctrl-C has nothing left to do but spoil the exit. signal.signal(signal.SIGINT, signal.SIG_IGN) for stream in (sys.stdout, sys.stderr): + # Started with that output closed: there is no stream to flush. + if stream is None: + continue try: stream.flush() except (OSError, ValueError): @@ -2164,6 +2180,11 @@ def main(argv: Sequence[str] | None = None) -> int: except (StartupError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as error: print(f"error: {error}", file=sys.stderr) status = 1 + except Exception: + # An error nobody expected ends the launcher with its traceback, which the interpreter prints once + # this function has let it go and the log is closed. It is written there now, beside the run it ended. + log.keep(traceback.format_exc()) + raise finally: # First of all: from here the stop's own handlers answer a signal, and none asks for the stop again. stop_request.begun() From f99708b4ab98cb4e747ba11e41d77359fcf405f4 Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 11:58:37 -0800 Subject: [PATCH 17/24] egocap: the launcher's port check covers every port a start binds, on the address it is bound on The check before a start left out two ports the stack binds: the backend's 3D view (EGOCAP_VISER_PORT, 8085) and the command port of the time-sync follower's chrony (--chrony-cmd-port). Both are now checked, each only when it will be bound: the 3D view unless the environment the backend is started in switches it off, the follower's port only with the Orin. Each port is asked on the address its program binds. Asked on every address, a listener on another address of the PC refused a start whose program would have bound loopback without trouble. LiveKit's media ports are still asked on every address, since LiveKit listens for media on the network interfaces' own addresses. With lsof, the program named as the holder is the one with a socket whose local end is the port. A process with a socket merely connected to that port could be named before. --backend-port and --chrony-cmd-port outside 1 to 65535 are refused in a sentence on the command line, where the check ended in a traceback. The guide lists what is checked, when and on which address. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- examples/egocap/README.md | 20 ++- .../egocap/tests/tools/test_start_system.py | 164 +++++++++++++++++- examples/egocap/tools/start_system.py | 116 ++++++++++--- 3 files changed, 269 insertions(+), 31 deletions(-) diff --git a/examples/egocap/README.md b/examples/egocap/README.md index ad24f3fc70..50e35a84e4 100644 --- a/examples/egocap/README.md +++ b/examples/egocap/README.md @@ -399,10 +399,22 @@ child to be gone, asks the Orin's deploy tool to stop the sender and says `the O confirmed. Whatever is not known to have stopped is named with the command that ends it, and the exit status is then 1: a child by its process group, the sender with the deploy tool's `check` and `stop`. -**Before it starts anything** the launcher refuses a start while a port the stack listens on is taken: the -backend's (`--backend-port`, 8010), CaptureServer's (8082) and, with a LiveKit server, LiveKit's (7880 and 7881 over -TCP, 7882 over UDP). The refusal names each port, whose it is and, where the system tells, the program that holds -it, which is usually a program an earlier run left behind. +**Before it starts anything** the launcher refuses a start while a port the stack is about to bind is taken. It +checks each port only when the program that binds it will be started, and on the address that program binds: + +| Port | Whose | Checked when | On | +| --- | --- | --- | --- | +| `--backend-port`, 8010, TCP | the backend | always | loopback | +| 8082, TCP | CaptureServer | always | loopback | +| `EGOCAP_VISER_PORT`, 8085, TCP | the backend's 3D view | unless `EGOCAP_VISER_ENABLED` switches it off | `EGOCAP_VISER_HOST`, loopback unless set | +| 7880, TCP | LiveKit, signalling | with `--livekit-server` | loopback | +| 7881, TCP and 7882, UDP | LiveKit, media | with `--livekit-server` | every address of this PC, since LiveKit listens for media on the network interfaces' own addresses | +| the profile's `network.port`, TCP | the mock sender | with `--mock` and the camera chain | every address | +| `--chrony-cmd-port`, 12301, UDP | the time-sync follower | with `--orin` | loopback | + +The refusal names each port, whose it is and, where the system tells (`ss`, else `lsof`), the program that holds +it, which is usually a program an earlier run left behind. A port taken after the check is reported by the +program that fails to bind it, and the stack is stopped. A port outside 1 to 65535 is refused on the command line. The page needs the frontend built once (`cd frontend && npm install && npm run build`); the launcher refuses to start without `frontend/dist`. For the default receiver, the launcher runs the receiver's `setup.sh` (venv, requirements, diff --git a/examples/egocap/tests/tools/test_start_system.py b/examples/egocap/tests/tools/test_start_system.py index dd4b000b1a..a9a5b7f045 100644 --- a/examples/egocap/tests/tools/test_start_system.py +++ b/examples/egocap/tests/tools/test_start_system.py @@ -13,6 +13,7 @@ import re import shlex import signal +import socket import stat import subprocess import sys @@ -185,7 +186,7 @@ def record_start(self, name, command, *_, **__): monkeypatch.setattr(ss.Stack, "start", record_start) monkeypatch.setattr(ss.Stack, "wait_until", lambda *_, **__: None) monkeypatch.setattr(ss.Stack, "stop_all", lambda *_: []) - monkeypatch.setattr(ss, "port_taken", lambda kind, number: False) + monkeypatch.setattr(ss, "port_taken", lambda kind, number, host="": False) monkeypatch.setattr(ss.subprocess, "run", lambda *_, **__: SimpleNamespace(returncode=0)) argv = ["--orin", "user@192.0.2.5", "--deploy-script", "x", "--bridge", "b", "--livekit-server", "l"] argv += ["--timesync-tool", str(timesync), "--host-lan-ip", "192.0.2.2", *CAMERA_ARGS] @@ -561,7 +562,7 @@ def interrupt(_seconds): # The fake children are not real processes, so there is nothing to signal and nothing is left running. monkeypatch.setattr(ss.Stack, "stop_all", lambda self: []) # Whatever this machine happens to run on the stack's ports does not decide these tests. - monkeypatch.setattr(ss, "port_taken", lambda kind, number: False) + monkeypatch.setattr(ss, "port_taken", lambda kind, number, host="": False) monkeypatch.setattr(ss, "ensure_receiver_environment", lambda: None) # Every deploy, stop and timesync step is recorded and reports success. monkeypatch.setattr( @@ -1041,7 +1042,7 @@ class _Done: monkeypatch.setattr(ss.Stack, "start", fake_start) monkeypatch.setattr(ss.Stack, "wait_until", lambda *_, **__: None) monkeypatch.setattr(ss.Stack, "stop_all", lambda *_: []) - monkeypatch.setattr(ss, "port_taken", lambda kind, number: False) + monkeypatch.setattr(ss, "port_taken", lambda kind, number, host="": False) monkeypatch.setattr(ss.subprocess, "run", lambda cmd, **__: runs.append(list(cmd)) or _Done()) monkeypatch.setattr(ss.time, "sleep", lambda *_: None) argv = ["--orin", "user@192.0.2.5", "--deploy-script", "x", "--bridge", "b", "--livekit-server", "l"] @@ -2395,7 +2396,9 @@ def test_a_port_the_stack_needs_that_is_taken_refuses_the_start_before_anything_ process, port = held_port # The launcher's own look at the port and at who holds it. Only the backend's port is this test's: whatever # else this machine runs on the stack's other ports does not decide it. - monkeypatch.setattr(ss, "port_taken", lambda kind, number: number == port and REAL_PORT_TAKEN(kind, number)) + monkeypatch.setattr( + ss, "port_taken", lambda kind, number, host="": number == port and REAL_PORT_TAKEN(kind, number, host) + ) assert ss.main([*ORIN_ARGV, *CAMERA_ARGS, "--backend-port", str(port)]) == 1 said = capsys.readouterr().err assert said.startswith(f"error: port {port} (the backend's, TCP) is already in use") @@ -2411,7 +2414,7 @@ def test_a_port_the_stack_needs_that_is_taken_refuses_the_start_before_anything_ def test_every_taken_port_is_named_with_whose_it_is_and_one_nobody_can_name_says_how_to_find_out(monkeypatch): taken = {("tcp", 7880), ("udp", 7882)} - monkeypatch.setattr(ss, "port_taken", lambda kind, number: (kind, number) in taken) + monkeypatch.setattr(ss, "port_taken", lambda kind, number, host="": (kind, number) in taken) monkeypatch.setattr(ss, "port_holder", lambda kind, _number: {"tcp": "livekit-server (pid 41)"}.get(kind)) needed = ss.needed_ports(backend_port=8010, livekit=True, mock_sender_port=None) assert [(port.number, port.kind) for port in needed] == [ @@ -2494,3 +2497,154 @@ def test_a_bridge_setting_the_bridge_would_misread_is_refused_on_the_command_lin ss.parse_args([flag, value]) assert refused.value.code == 2 assert said in capsys.readouterr().err + + +# --- every port a start will bind is checked, on the address it is bound on ------------------------------------ + + +def test_the_3d_views_port_and_the_followers_command_port_are_checked_only_where_they_will_be_bound(): + viser, chrony = ("127.0.0.1", 8085), 12301 + needed = ss.needed_ports(8010, livekit=True, mock_sender_port=None, viser=viser, chrony_cmd_port=chrony) + assert [(port.number, port.kind, port.host, port.whose) for port in needed] == [ + (8010, "tcp", "127.0.0.1", "the backend's"), + (8082, "tcp", "127.0.0.1", "CaptureServer's"), + (8085, "tcp", "127.0.0.1", "the backend's 3D view's"), + (7880, "tcp", "127.0.0.1", "LiveKit's"), + # LiveKit listens for media on the addresses of the network interfaces, whatever it is told to bind. + (7881, "tcp", "", "LiveKit's"), + (7882, "udp", "", "LiveKit's"), + (12301, "udp", "127.0.0.1", "the time-sync follower's"), + ] + # A start with the 3D view switched off, or without the Orin, binds neither. + plain = ss.needed_ports(8010, livekit=False, mock_sender_port=None) + assert [(port.number, port.kind) for port in plain] == [(8010, "tcp"), (8082, "tcp")] + + +@pytest.mark.parametrize( + ("environment", "endpoint"), + [ + ({}, ("127.0.0.1", 8085)), + ({"EGOCAP_VISER_PORT": "9001", "EGOCAP_VISER_HOST": "0.0.0.0"}, ("0.0.0.0", 9001)), + ({"EGOCAP_VISER_ENABLED": "off"}, None), + ({"EGOCAP_VISER_ENABLED": " No "}, None), + ({"EGOCAP_VISER_ENABLED": "TRUE"}, ("127.0.0.1", 8085)), + ], +) +def test_the_3d_views_address_is_read_from_the_environment_as_the_backend_reads_it( + monkeypatch, environment, endpoint +): + assert ss.viser_endpoint(environment) == endpoint + # The backend's own reading of the same environment, which is the authority for it. + from egocap_web.config import visualization_from_env + + for name in ("EGOCAP_VISER_ENABLED", "EGOCAP_VISER_HOST", "EGOCAP_VISER_PORT"): + monkeypatch.delenv(name, raising=False) + for name, value in environment.items(): + monkeypatch.setenv(name, value) + backend = visualization_from_env() + assert ((backend.host, backend.port) if backend.enabled else None) == endpoint + + +@pytest.mark.parametrize("environment", [{"EGOCAP_VISER_ENABLED": "maybe"}, {"EGOCAP_VISER_PORT": "eighty"}]) +def test_a_3d_view_setting_the_backend_will_refuse_is_left_for_the_backend_to_refuse(environment): + assert ss.viser_endpoint(environment) is None + + +def test_main_asks_for_the_3d_views_port_and_with_the_orin_the_followers_command_port( + recorded_main, monkeypatch, capsys +): + asked: list[tuple[str, int, str]] = [] + monkeypatch.setattr( + ss, "port_taken", lambda kind, number, host="": asked.append((kind, number, host)) or False + ) + monkeypatch.setenv("EGOCAP_VISER_PORT", "9001") + assert ss.main([*ORIN_ARGV, *CAMERA_ARGS, "--chrony-cmd-port", "12999"]) == 0 + assert ("tcp", 9001, "127.0.0.1") in asked and ("udp", 12999, "127.0.0.1") in asked + asked.clear() + # The PC side alone starts no follower, and a 3D view that is switched off has no port. + monkeypatch.setenv("EGOCAP_VISER_ENABLED", "0") + assert ss.main([*CAMERA_ARGS, "--chrony-cmd-port", "12999"]) == 0 + assert asked == [("tcp", 8010, "127.0.0.1"), ("tcp", 8082, "127.0.0.1")] + + +def test_a_taken_3d_view_port_refuses_the_start_and_names_the_setting_that_moves_it( + recorded_main, monkeypatch, capsys +): + monkeypatch.setattr(ss, "port_taken", lambda kind, number, host="": number == 8085) + monkeypatch.setattr(ss, "port_holder", lambda kind, number: None) + monkeypatch.delenv("EGOCAP_VISER_PORT", raising=False) + monkeypatch.delenv("EGOCAP_VISER_ENABLED", raising=False) + assert ss.main([*ORIN_ARGV, *CAMERA_ARGS]) == 1 + assert capsys.readouterr().err == ( + "error: port 8085 (the backend's 3D view's, TCP) is already in use (`ss -ltnp` or `lsof -nP -iTCP:8085` " + "names the program). An earlier run may still be up: stop that program, or choose another port with " + "EGOCAP_VISER_PORT in the environment, then start again.\n" + ) + assert recorded_main.children == [] and recorded_main.deploys == [] + + +@pytest.mark.parametrize("flag", ["--backend-port", "--chrony-cmd-port"]) +@pytest.mark.parametrize("value", ["70000", "0", "-1", "http"]) +def test_a_port_out_of_range_is_refused_in_a_sentence_on_the_command_line(capsys, flag, value): + with pytest.raises(SystemExit) as refused: + ss.parse_args([flag, value]) + assert refused.value.code == 2 + assert f"argument {flag}: needs a port from 1 to 65535, got '{value}'" in capsys.readouterr().err + + +def test_a_listener_on_another_address_of_this_pc_does_not_take_the_loopback_port(tmp_path: Path): + # What the probe is asked: whether the address a program will bind is free, not whether the number is used + # anywhere. Asked of loopback while this test holds the number on loopback, then of an address nobody holds. + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as holder: + holder.bind(("127.0.0.1", 0)) + holder.listen() + port = holder.getsockname()[1] + assert REAL_PORT_TAKEN("tcp", port, "127.0.0.1") and REAL_PORT_TAKEN("tcp", port, "") + assert not REAL_PORT_TAKEN("tcp", port, "127.0.0.1") + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as holder: + holder.bind(("127.0.0.1", 0)) + port = holder.getsockname()[1] + assert REAL_PORT_TAKEN("udp", port, "127.0.0.1") + # A TCP listener's number is not a UDP port's. + assert not REAL_PORT_TAKEN("tcp", port, "127.0.0.1") + # An address this PC does not have is no port a program could bind, and is not called taken. + assert not REAL_PORT_TAKEN("tcp", port, "192.0.2.77") + + +LSOF_LISTING = """p311 +cpython3.12 +f5 +n127.0.0.1:53124->127.0.0.1:7882 +p902 +clivekit-server +f9 +n*:7882 +f10 +n192.0.2.9:7882 +""" + + +def test_the_holder_lsof_names_is_the_process_bound_to_the_port_not_one_connected_to_it(): + # A lower process number with a socket connected to the port comes first in the listing. + assert ss.lsof_holder(LSOF_LISTING, 7882) == "livekit-server (pid 902)" + assert ss.lsof_holder(LSOF_LISTING, 53124) == "python3.12 (pid 311)" + assert ss.lsof_holder(LSOF_LISTING, 7880) is None and ss.lsof_holder("", 7882) is None + # An IPv6 listener's name ends in the port as well. + assert ss.lsof_holder("p7\ncnode\nf3\nn[::1]:7882\n", 7882) == "node (pid 7)" + + +def test_a_port_held_by_one_process_and_talked_to_by_another_is_named_for_the_holder(tmp_path: Path): + holder, port = _holder(tmp_path, "udp") + talks = "import socket, sys, time\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n" + talks += "s.connect(('127.0.0.1', int(sys.argv[1])))\nopen(sys.argv[2], 'w').close()\ntime.sleep(60)\n" + ready = tmp_path / "talker.ready" + talkers = [subprocess.Popen([sys.executable, "-c", talks, str(port), str(ready)]) for _ in range(3)] + try: + _await_files([ready]) + named = ss.port_holder("udp", port) + # Named where this system has a tool that tells: then it is the holder, whichever number is lower. + assert named is None or f"(pid {holder.pid})" in named + finally: + for process in (holder, *talkers): + process.kill() + process.wait() diff --git a/examples/egocap/tools/start_system.py b/examples/egocap/tools/start_system.py index ce1fb4ea01..07e1267439 100644 --- a/examples/egocap/tools/start_system.py +++ b/examples/egocap/tools/start_system.py @@ -1008,48 +1008,91 @@ class NeededPort: kind: str #: Whose it is, as a refusal says it: "the backend's". whose: str - #: The option that chooses another port, where there is one. + #: What chooses another port, where something does: an option, or a setting in the environment. option: str | None = None + #: The address the program binds; empty for every address of this PC. + host: str = "127.0.0.1" -def needed_ports(backend_port: int, livekit: bool, mock_sender_port: int | None) -> list[NeededPort]: - """The ports of this PC the programs about to be started listen on. +def port_number(text: str) -> int: + """A port given on the command line, once it is one a program can bind.""" + if not (text.isascii() and text.isdigit() and 1 <= int(text) <= 65535): + raise argparse.ArgumentTypeError(f"needs a port from 1 to 65535, got {text!r}") + return int(text) + + +def viser_endpoint(environ: Mapping[str, str]) -> tuple[str, int] | None: + """Where the backend's 3D view will listen, read from the environment the backend is started in as the + backend reads it (``egocap_web.config.visualization_from_env``); None when it is switched off. + + Also None for a setting the backend itself refuses: that refusal is the backend's to make, with its words. + """ + if environ.get("EGOCAP_VISER_ENABLED", "1").strip().lower() not in ("1", "true", "yes"): + return None + try: + port = int(environ.get("EGOCAP_VISER_PORT", "8085")) + except ValueError: + return None + return environ.get("EGOCAP_VISER_HOST", "127.0.0.1"), port + + +def needed_ports( + backend_port: int, + livekit: bool, + mock_sender_port: int | None, + viser: tuple[str, int] | None = None, + chrony_cmd_port: int | None = None, +) -> list[NeededPort]: + """The ports of this PC the programs about to be started listen on, each with the address it is bound on. ``livekit`` is whether a LiveKit server is started; ``mock_sender_port`` is the profile's video port when a - local mock sender listens on it, None when the sender is on the Orin or there is none. + local mock sender listens on it, None when the sender is on the Orin or there is none. ``viser`` is where + the backend's 3D view listens, None when it is switched off; ``chrony_cmd_port`` is the command port of the + time-sync follower, None when none is started (no Orin). """ ports = [ NeededPort(backend_port, "tcp", "the backend's", "--backend-port"), NeededPort(CAPTURE_SERVER_PORT, "tcp", "CaptureServer's"), ] + if viser is not None: + host, port = viser + ports.append( + NeededPort(port, "tcp", "the backend's 3D view's", "EGOCAP_VISER_PORT in the environment", host) + ) if livekit: ports += [ NeededPort(LIVEKIT_PORT, "tcp", "LiveKit's"), - NeededPort(LIVEKIT_RTC_TCP_PORT, "tcp", "LiveKit's"), - NeededPort(LIVEKIT_RTC_UDP_PORT, "udp", "LiveKit's"), + # LiveKit listens for media on the addresses of the network interfaces, whatever it is told to bind. + NeededPort(LIVEKIT_RTC_TCP_PORT, "tcp", "LiveKit's", host=""), + NeededPort(LIVEKIT_RTC_UDP_PORT, "udp", "LiveKit's", host=""), ] if mock_sender_port is not None: - ports.append(NeededPort(mock_sender_port, "tcp", "the mock sender's", "--sender-port")) + # The mock sender is not of this tree; nothing here says which address it binds. + ports.append(NeededPort(mock_sender_port, "tcp", "the mock sender's", "--sender-port", host="")) + if chrony_cmd_port is not None: + ports.append(NeededPort(chrony_cmd_port, "udp", "the time-sync follower's", "--chrony-cmd-port")) return ports -def port_taken(kind: str, number: int) -> bool: - """Whether a program on this PC already holds the port, on any of its addresses. +def port_taken(kind: str, number: int, host: str = "") -> bool: + """Whether a program on this PC already holds the port on ``host``, the address a program of the stack + will bind; an empty ``host`` asks for every address of this PC. - Asked on every address because LiveKit listens for media on the addresses of the network interfaces too, - whatever address it is told to bind. + Asked of the address and not of the number alone: a listener on another address of this PC does not keep + a program from binding loopback. """ # A listener answers a connection whichever address it bound; a bind alone misses one on some systems. - if kind == "tcp" and port_open("127.0.0.1", number): + if kind == "tcp" and port_open("127.0.0.1" if host in ("", "0.0.0.0") else host, number): return True with socket.socket(socket.AF_INET, socket.SOCK_STREAM if kind == "tcp" else socket.SOCK_DGRAM) as probe: if kind == "tcp": # As a server sets it: connections left closing by a run that has just ended hold nothing. probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: - probe.bind(("", number)) + probe.bind((host, number)) except OSError as error: - # Any other refusal (a port this user may not bind) is the program's own to report. + # Any other refusal (a port this user may not bind, an address this PC does not have) is the + # program's own to report. return error.errno == errno.EADDRINUSE return False @@ -1071,18 +1114,35 @@ def _said(command: Sequence[str]) -> str: return "" +def lsof_holder(listing: str, number: int) -> str | None: + """The process bound to a port, as ``name (pid N)``, from ``lsof -F pcn`` output; None when none is. + + ``lsof -i`` also lists a socket that is only connected to the port, under whichever process has it. Such a + socket's name is ``local->remote``: the holder is the process with a socket whose local end is the port. + """ + pid = name = None + for line in listing.splitlines(): + field, value = line[:1], line[1:] + if field == "p": + # A new process: the fields that follow are its own. + pid, name = value, None + elif field == "c": + name = value + elif field == "n" and pid is not None and value.split("->", 1)[0].rsplit(":", 1)[-1] == str(number): + return f"{name or 'a process'} (pid {pid})" + return None + + def port_holder(kind: str, number: int) -> str | None: """The program that holds a port, as ``name (pid N)``, where a tool of this system tells; None where none does. A process of another user is not named to this one.""" letter = "t" if kind == "tcp" else "u" + # ``ss`` lists sockets by their local port, so what it names is the holder. found = re.search(r'users:\(\("([^"]+)",pid=(\d+)', _said(["ss", "-H", f"-l{letter}np", f"sport = :{number}"])) if found is not None: return f"{found[1]} (pid {found[2]})" listening = ["-sTCP:LISTEN"] if kind == "tcp" else [] - found = re.search( - r"^p(\d+)\nc(.+)$", _said(["lsof", "-nP", f"-i{kind.upper()}:{number}", *listening, "-Fpc"]), re.MULTILINE - ) - return f"{found[2]} (pid {found[1]})" if found is not None else None + return lsof_holder(_said(["lsof", "-nP", f"-i{kind.upper()}:{number}", *listening, "-Fpcn"]), number) def refuse_taken_ports(ports: Sequence[NeededPort]) -> None: @@ -1092,7 +1152,7 @@ def refuse_taken_ports(ports: Sequence[NeededPort]) -> None: Asked before anything is deployed or started: a program left by an earlier run would otherwise stop this one half way up, with the Orin's sender already running. """ - taken = [port for port in ports if port_taken(port.kind, port.number)] + taken = [port for port in ports if port_taken(port.kind, port.number, port.host)] if not taken: return said = [] @@ -1747,7 +1807,9 @@ def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: default=Path(os.environ.get("EGOCAP_TIMESYNC_TOOL", TIMESYNC_TOOL)), help="the timesync module's timesync_tool.py", ) - parser.add_argument("--chrony-cmd-port", type=int, default=12301, help="command port of this PC's chronyd") + parser.add_argument( + "--chrony-cmd-port", type=port_number, default=12301, help="command port of this PC's chronyd" + ) parser.add_argument( "--chrony-wait", type=float, @@ -1783,7 +1845,7 @@ def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: help="folder of the operators' glove calibration files (.mcal), given to CaptureServer and to the backend " f"alike (default: {GLOVE_CALIBRATION_SUBDIR}/ under the calibration directory)", ) - parser.add_argument("--backend-port", type=int, default=8010) + parser.add_argument("--backend-port", type=port_number, default=8010) parser.add_argument( "--seconds", type=int, @@ -1915,7 +1977,17 @@ def main(argv: Sequence[str] | None = None) -> int: # Before anything is deployed or started: a program an earlier run left on a port would stop this run # half way up. mock_sender_port = sender.port if chain and args.mock else None - refuse_taken_ports(needed_ports(args.backend_port, bool(args.livekit_server), mock_sender_port)) + # The backend is started in this environment, so its 3D view listens where this environment says; the + # follower's command port is bound only when the Orin's clock is followed. + refuse_taken_ports( + needed_ports( + args.backend_port, + bool(args.livekit_server), + mock_sender_port, + viser_endpoint(os.environ), + args.chrony_cmd_port if args.orin else None, + ) + ) token_file = workdir / "publisher-token.txt" token_file.write_text(publisher_token(LIVEKIT_DEV_KEY, LIVEKIT_DEV_SECRET, room, publisher)) token_file.chmod(0o600) From ea18485c105dd9195dfad079dfda23aa2c115b63 Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 12:00:54 -0800 Subject: [PATCH 18/24] egocap: the launcher's bridge flags take only what the bridge reads as it is written The bridge reads its bitrate maximum and keyframe period without checking them: as far as the text is a number, into 32 bits. The launcher accepted anything Python reads as a positive number, so some values reached the bridge as another number: 1_0 as 1 Mbit/s, digits of another script as 0, a value past 32 bits of bits a second wrapped, a tiny one became no bits at all, and a keyframe period past the bridge's whole number wrapped too. --bridge-bitrate-mbps now takes plain ASCII digits with an optional fraction, from 0.001 to 4294: a thousand bits a second at least, so the bridge's product is not rounded to none, and whole megabits below the 4294.967295 that 32 bits end at. --bridge-idr-period takes plain ASCII digits from 1 to 2147483647, the largest whole number the bridge reads. Everything else is refused in a sentence. A test holds the bounds to the two expressions the bridge reads the flags with. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- examples/egocap/CAMERA_SETTINGS.md | 5 ++ .../egocap/tests/tools/test_start_system.py | 68 ++++++++++++++++--- examples/egocap/tools/start_system.py | 37 ++++++---- 3 files changed, 89 insertions(+), 21 deletions(-) diff --git a/examples/egocap/CAMERA_SETTINGS.md b/examples/egocap/CAMERA_SETTINGS.md index 6ad4315607..3defc0956b 100644 --- a/examples/egocap/CAMERA_SETTINGS.md +++ b/examples/egocap/CAMERA_SETTINGS.md @@ -108,6 +108,11 @@ The launcher passes neither unless asked, so the bridge's defaults stand: | `--bridge-bitrate-mbps MBPS` | `--bitrate-mbps` | 8 | The most the encoder may use for each track. It starts lower and follows the target LiveKit's congestion control reports, never above this. | | `--bridge-idr-period FRAMES` | `--idr-period` | 30 | Frames between keyframes of each track. | +The bridge reads both numbers without checking them, so the launcher takes only what the bridge reads as it is +written: plain digits, for the bitrate with an optional fraction (`8`, `2.5`), from 0.001 to 4294 Mbit/s, since the +bridge keeps bits a second in 32 bits; and for the keyframe period a whole number from 1 to 2147483647. Anything +else (`1_0`, `1e3`, a sign, a space, digits of another script) is refused on the command line. + The keyframe period is counted in frames, so what it means in time follows the frame rate: the default is a keyframe a second at 30 fps and two a second at 60 fps. A keyframe costs many times an ordinary frame; at a bitrate that is low for the picture, two a second can show as a pulse in quality at the keyframe rate. A longer diff --git a/examples/egocap/tests/tools/test_start_system.py b/examples/egocap/tests/tools/test_start_system.py index a9a5b7f045..343adf66cb 100644 --- a/examples/egocap/tests/tools/test_start_system.py +++ b/examples/egocap/tests/tools/test_start_system.py @@ -2479,24 +2479,74 @@ def test_either_bridge_setting_can_be_given_alone_and_a_fraction_of_a_megabit_is assert ss.bridge_encoder_arguments("2.5", None) == ["--bitrate-mbps", "2.5"] +BITRATE_SAID = "needs a bitrate in Mbit/s written in plain digits, from 0.001 to 4294" +PERIOD_SAID = "needs a whole number of frames written in plain digits, from 1 to 2147483647" + + @pytest.mark.parametrize( ("flag", "value", "said"), [ - ("--bridge-bitrate-mbps", "0", "a bitrate above zero"), - ("--bridge-bitrate-mbps", "-4", "a bitrate above zero"), - ("--bridge-bitrate-mbps", "fast", "a bitrate above zero"), - ("--bridge-bitrate-mbps", "nan", "a bitrate above zero"), - ("--bridge-idr-period", "0", "a whole number of frames, at least 1"), - ("--bridge-idr-period", "2.5", "a whole number of frames, at least 1"), - ("--bridge-idr-period", "often", "a whole number of frames, at least 1"), + ("--bridge-bitrate-mbps", "0", BITRATE_SAID), + ("--bridge-bitrate-mbps", "-4", BITRATE_SAID), + ("--bridge-bitrate-mbps", "fast", BITRATE_SAID), + ("--bridge-bitrate-mbps", "nan", BITRATE_SAID), + ("--bridge-bitrate-mbps", "inf", BITRATE_SAID), + # Each of these is a number to Python and something else to the bridge, which reads as far as it can. + ("--bridge-bitrate-mbps", "1_0", BITRATE_SAID), + ("--bridge-bitrate-mbps", "\uff11\uff12", BITRATE_SAID), + ("--bridge-bitrate-mbps", "1e3", BITRATE_SAID), + ("--bridge-bitrate-mbps", "+5", BITRATE_SAID), + ("--bridge-bitrate-mbps", " 5", BITRATE_SAID), + ("--bridge-bitrate-mbps", "5.", BITRATE_SAID), + ("--bridge-bitrate-mbps", ".5", BITRATE_SAID), + # Past what the bridge keeps: bits a second in 32 bits, and at least one of them. + ("--bridge-bitrate-mbps", "4295", BITRATE_SAID), + ("--bridge-bitrate-mbps", "4294.5", BITRATE_SAID), + ("--bridge-bitrate-mbps", "0.0000001", BITRATE_SAID), + ("--bridge-bitrate-mbps", "0.0009", BITRATE_SAID), + ("--bridge-idr-period", "0", PERIOD_SAID), + ("--bridge-idr-period", "2.5", PERIOD_SAID), + ("--bridge-idr-period", "often", PERIOD_SAID), + ("--bridge-idr-period", "1_0", PERIOD_SAID), + ("--bridge-idr-period", "\uff11\uff12\uff10", PERIOD_SAID), + ("--bridge-idr-period", "+5", PERIOD_SAID), + # Past what the bridge reads a whole number into. + ("--bridge-idr-period", "2147483648", PERIOD_SAID), + ("--bridge-idr-period", "4294967296", PERIOD_SAID), ], ) def test_a_bridge_setting_the_bridge_would_misread_is_refused_on_the_command_line(capsys, flag, value, said): # The bridge reads its numbers without checking them: a word would become zero there. with pytest.raises(SystemExit) as refused: - ss.parse_args([flag, value]) + ss.parse_args([f"{flag}={value}"]) assert refused.value.code == 2 - assert said in capsys.readouterr().err + assert f"argument {flag}: {said}, got {value!r}" in capsys.readouterr().err + + +@pytest.mark.parametrize("value", ["0.001", "0.5", "2.5", "8", "008", "4294", "4294.0"]) +def test_a_bitrate_the_bridge_reads_as_it_is_written_is_passed_as_written(value): + assert ss.parse_args(["--bridge-bitrate-mbps", value]).bridge_bitrate_mbps == value + # What the bridge makes of it: bits a second, in 32 bits, as its own expression computes them. + assert 1 <= int(float(value) * 1e6) <= 2**32 - 1 + + +@pytest.mark.parametrize("value", ["1", "30", "007", "2147483647"]) +def test_a_keyframe_period_the_bridge_reads_as_it_is_written_is_passed_as_written(value): + assert ss.parse_args(["--bridge-idr-period", value]).bridge_idr_period == value + + +BRIDGE_SOURCE = ss.REPO_ROOT / "examples" / "camera_livekit_bridge" / "bridge" / "main.cpp" + + +@pytest.mark.skipif(not BRIDGE_SOURCE.is_file(), reason="the bridge's source is not in this tree") +def test_the_bounds_of_the_bridge_settings_are_the_ones_the_bridges_own_reading_has(): + # The two expressions the bridge reads the flags with: bits a second, and a whole number, each kept in 32 + # bits. Should the bridge read them otherwise one day, the bounds here are to be looked at again. + source = BRIDGE_SOURCE.read_text() + assert "defaults.bitrate_bps = static_cast(std::atof(next().c_str()) * 1e6);" in source + assert "defaults.idr_period = static_cast(std::atoi(next().c_str()));" in source + assert (ss.BRIDGE_BITRATE_MBPS_MIN, ss.BRIDGE_BITRATE_MBPS_MAX) == ("0.001", "4294") + assert ss.BRIDGE_IDR_PERIOD_MAX == 2**31 - 1 # --- every port a start will bind is checked, on the address it is bound on ------------------------------------ diff --git a/examples/egocap/tools/start_system.py b/examples/egocap/tools/start_system.py index 07e1267439..58f7cb07e1 100644 --- a/examples/egocap/tools/start_system.py +++ b/examples/egocap/tools/start_system.py @@ -73,6 +73,7 @@ import webbrowser from collections.abc import Callable, Iterator, Mapping, Sequence from dataclasses import dataclass +from decimal import Decimal from pathlib import Path from typing import Any, NoReturn, TextIO @@ -162,6 +163,12 @@ # How many streams one start bridges at most: each fills a station camera role of its own. The sender, the # receiver and the bridge each take more streams than that. MAX_STREAMS = len(ROLE_INTRINSICS) +# What the bridge's own flags take, by how the bridge reads them (bridge/main.cpp). Its bitrate maximum becomes +# bits a second in 32 bits: at least a thousand of them, so that the product is not rounded to none, and whole +# megabits below the 4294.967295 that 32 bits end at. Its keyframe period is read into a signed 32-bit number. +BRIDGE_BITRATE_MBPS_MIN = "0.001" +BRIDGE_BITRATE_MBPS_MAX = "4294" +BRIDGE_IDR_PERIOD_MAX = 2**31 - 1 # The LiveKit track a profile's only stream is published as, whatever role it is given. HEAD_TRACK = "sensing-head" # The track of each stream of a profile that holds several, by the camera role the stream fills. @@ -568,24 +575,30 @@ def bridge_timing_arguments( def bridge_bitrate(text: str) -> str: - """A bitrate ceiling for the bridge as the operator wrote it, once it is a number above zero. + """A bitrate ceiling for the bridge as the operator wrote it, once the bridge reads it as written. - Checked here because the bridge reads its numbers without checking them: a word would become zero there. + The bridge reads the text as far as it is a number, multiplies by a million and keeps bits a second in 32 + bits, checking nothing: ``1_0`` is 1 there, a digit of another script is 0, and too large a value wraps. + So only plain digits with an optional fraction are taken, within what 32 bits of bits a second hold. """ - try: - value = float(text) - except ValueError: - value = 0.0 - # Not-a-number compares false with everything, and infinity is no ceiling. - if not 0.0 < value < float("inf"): - raise argparse.ArgumentTypeError(f"needs a bitrate above zero, in Mbit/s, got {text!r}") + plain = re.fullmatch(r"[0-9]+(?:\.[0-9]+)?", text) is not None + # Compared as decimals: the bounds are exact, and so is what was written. + if not plain or not Decimal(BRIDGE_BITRATE_MBPS_MIN) <= Decimal(text) <= Decimal(BRIDGE_BITRATE_MBPS_MAX): + raise argparse.ArgumentTypeError( + f"needs a bitrate in Mbit/s written in plain digits, from {BRIDGE_BITRATE_MBPS_MIN} to " + f"{BRIDGE_BITRATE_MBPS_MAX}, got {text!r}" + ) return text def bridge_idr_period(text: str) -> str: - """A keyframe period for the bridge as the operator wrote it, once it is a whole number of frames.""" - if not text.isascii() or not text.isdigit() or int(text) < 1: - raise argparse.ArgumentTypeError(f"needs a whole number of frames, at least 1, got {text!r}") + """A keyframe period for the bridge as the operator wrote it, once the bridge reads it as written: plain + digits, and no more than the whole number the bridge reads them into holds.""" + if re.fullmatch(r"[0-9]+", text) is None or not 1 <= int(text) <= BRIDGE_IDR_PERIOD_MAX: + raise argparse.ArgumentTypeError( + f"needs a whole number of frames written in plain digits, from 1 to {BRIDGE_IDR_PERIOD_MAX}, " + f"got {text!r}" + ) return text From 387eca3012ccfbc8b870d584c4afc3629c298180 Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 12:01:47 -0800 Subject: [PATCH 19/24] egocap: the launcher's guide says what its stop does not reach Four limits of the stop, none of them changed: a program that left its child's process group is neither stopped nor reported; a launcher killed outright stops nothing; the Orin's answer to the stop of its sender is waited for 60 s and no longer; and output piped into a program that never reads blocks the launcher, the stop included, which the launcher's own log makes unnecessary. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- examples/egocap/README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/examples/egocap/README.md b/examples/egocap/README.md index 50e35a84e4..42c45c383c 100644 --- a/examples/egocap/README.md +++ b/examples/egocap/README.md @@ -399,6 +399,16 @@ child to be gone, asks the Orin's deploy tool to stop the sender and says `the O confirmed. Whatever is not known to have stopped is named with the command that ends it, and the exit status is then 1: a child by its process group, the sender with the deploy tool's `check` and `stop`. +What the stop does not reach: + +- A program one of the children started and moved out of that child's process group is not the launcher's to + find: it is neither stopped nor reported. +- The launcher killed outright (`kill -9`) stops nothing: its children run in sessions of their own. +- The Orin is given 60 s to answer the request to stop its sender. An answer that never comes is cut off then and + reported as not confirmed; nothing pressed shortens that wait. +- Output piped into a program that stays alive and never reads blocks the launcher once the pipe is full, the + stop included, until that program reads or ends. `launcher.log` holds everything printed, so no pipe is needed. + **Before it starts anything** the launcher refuses a start while a port the stack is about to bind is taken. It checks each port only when the program that binds it will be started, and on the address that program binds: From 59ae880a9e8b0852cdcdf2f75f66ff0eaf17d44b Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 12:04:11 -0800 Subject: [PATCH 20/24] egocap: a recorder writes a last beat as it releases a session A recorder rewrites a session's lock file at once when it takes the session and then on every beat. A holding shorter than a beat therefore left the lock as it was from its first moment to its last, so the session as the recorder left it and a copy taken while it was held showed one lock content for two states. The reader of takes left behind knows a session at rest by that content, and took a restored copy with a waiting take in it for the session it had already read. The release now writes one more beat before it gives the lock up: the same holder's token with the next count, a value the session showed at no moment while it was held. A beat that cannot be written is logged and the lock is released all the same. Every reader of the beat reads it after the release: the scan's judge and its note of a session it closed itself, the hold for a label correction, which writes nothing, and upload's test of an ended batch. A reader that looked at the session while it was held sees that last beat as it sees any beat: its next look says the beat changed, and the look after that finds the session at rest. That is what a reader already met whenever a regular beat fell between its looks; two tests that looked and released within one beat now expect it. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- .../egocap/recording/episode_layout.py | 11 ++++- .../unit/test_take_resolution_layout.py | 41 +++++++++++++++++++ .../test_takes_left_behind.py | 4 ++ 3 files changed, 55 insertions(+), 1 deletion(-) diff --git a/examples/egocap/recording/egocap/recording/episode_layout.py b/examples/egocap/recording/egocap/recording/episode_layout.py index 8ec43f81f0..53f1305b2d 100644 --- a/examples/egocap/recording/egocap/recording/episode_layout.py +++ b/examples/egocap/recording/egocap/recording/episode_layout.py @@ -897,8 +897,17 @@ def _keep_beating(self) -> None: self._failing = False def release(self) -> None: - """Release the lock and stop the beat; safe to call twice.""" + """Release the lock and stop the beat; safe to call twice. + + A last beat is written first, so the lock file a released session keeps holds a value the session + showed at no moment while it was held, however short the holding. A reader that knows a session at + rest by that value can then tell it from a copy taken while it was held. + """ self._released.set() + try: + self.beat() + except Exception: # noqa: BLE001 - nothing a beat can raise may keep the session from being released + logger.exception("the session's last beat could not be written; the lock is released all the same") with self._guard: if not self._handle.closed: fcntl.flock(self._handle, fcntl.LOCK_UN) diff --git a/examples/egocap/tests/recording/unit/test_take_resolution_layout.py b/examples/egocap/tests/recording/unit/test_take_resolution_layout.py index ab7b8e8649..b34be504eb 100644 --- a/examples/egocap/tests/recording/unit/test_take_resolution_layout.py +++ b/examples/egocap/tests/recording/unit/test_take_resolution_layout.py @@ -559,6 +559,47 @@ def test_a_session_that_is_held_changes_its_beat_and_one_that_was_released_does_ lock.release() # twice is harmless +def test_a_release_writes_a_last_beat_so_the_lock_it_leaves_is_one_the_holding_never_showed(tmp_path, monkeypatch): + monkeypatch.setattr(episode_layout, "BEAT_SECONDS", 3600.0) # only the beat written at once + session = _session(tmp_path) + lock = SessionLock(session) + held = episode_layout.session_beat(session)[0] + lock.release() + left = episode_layout.session_beat(session)[0] + # The same holder's token and the next count: a copy taken at any moment of the holding, however short it + # was, differs from the session as the holder left it. + assert held.split() == [left.split()[0], b"1"] and left.split()[1] == b"2" + # Released all the same: another recorder takes the session at once. + SessionLock(session).release() + after_another = episode_layout.session_beat(session)[0] + lock.release() # twice is harmless, and writes nothing more + assert episode_layout.session_beat(session)[0] == after_another + + +def test_a_last_beat_that_cannot_be_written_is_logged_and_the_lock_is_released_all_the_same( + tmp_path, monkeypatch, caplog +): + monkeypatch.setattr(episode_layout, "BEAT_SECONDS", 3600.0) + session = _session(tmp_path) + lock = SessionLock(session) + held = episode_layout.session_beat(session) + + def utime(target, *args, **kwargs): + raise OSError(errno.EIO, "input/output error") + + monkeypatch.setattr(episode_layout.os, "utime", utime) + with caplog.at_level(logging.ERROR, logger="isaaccapture.egocap.episode_layout"): + lock.release() + assert [record.getMessage() for record in caplog.records] == [ + "the session's last beat could not be written; the lock is released all the same" + ] + monkeypatch.undo() + # Nothing keeps the session: its beat thread has ended and another recorder takes it. + assert not _beating(session) + assert episode_layout.session_beat(session)[0].split()[0] == held[0].split()[0] + SessionLock(session).release() + + def test_a_new_holder_never_writes_a_beat_an_earlier_holder_wrote(tmp_path, monkeypatch): monkeypatch.setattr(episode_layout, "BEAT_SECONDS", 3600.0) # only the beat written at once session = _session(tmp_path) diff --git a/examples/egocap/tests/recording_service/test_takes_left_behind.py b/examples/egocap/tests/recording_service/test_takes_left_behind.py index 2771dc45c0..199729ef23 100644 --- a/examples/egocap/tests/recording_service/test_takes_left_behind.py +++ b/examples/egocap/tests/recording_service/test_takes_left_behind.py @@ -288,6 +288,8 @@ async def test_a_look_tells_how_long_until_it_can_judge_a_session_it_has_not_wat holder = episode_layout.SessionLock(session.session_path) assert reader.scan.judge(session.session_path) == (False, 0.0) holder.release() + # The release writes a last beat, which the next look sees like any other; the watch starts from it. + assert reader.scan.judge(session.session_path) == (False, 0.0) reader.now += 0.5 quiet, wait = reader.scan.judge(session.session_path) assert quiet is None and 0 < wait <= WATCH @@ -655,6 +657,8 @@ async def test_a_settled_session_a_recorder_opens_again_and_leaves_a_take_in_is_ interrupted = await _interrupted_take(again) assert reader.look() == [] # open: its recorder's to report await again.close() + # The look after the close sees the recorder's last beat, as it sees any beat; the next one lists the take. + assert reader.look() == [] assert reader.look() == [interrupted.episode_id] From 5456a14f278d296fac9d45bd3a3fab748a9ba21b Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 12:13:17 -0800 Subject: [PATCH 21/24] egocap: a lock file that is empty or a link is no value to know a session by The reader of takes left behind remembers a session at rest by what its last recorder left in its lock file. Two kinds of lock file say nothing and were taken for a value all the same. An empty lock file is what a recorder that wrote no beat left, and it is the same in every such session. Such a session was remembered by the empty value, so another put in its place with a waiting take was taken for the session already read, and its take was never listed. A lock file that is a link was read through, though what stands elsewhere is no word of a recorder of this session; the hold for a label correction already refuses such a lock file. Both now count as a session whose lock file says nothing, like one no recorder ever locked: never remembered, and read again at every look, records and all. The read of the value is the recording library's (session_lock_value), which does not follow a link. The module says what that costs: an output with many such sessions is read slowly for as long as it holds them. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- .../egocap/recording/episode_layout.py | 28 +++++++- .../recording_service/output_scan.py | 27 ++++--- .../unit/test_take_resolution_layout.py | 30 ++++++++ .../test_takes_left_behind.py | 72 ++++++++++++++++++- 4 files changed, 138 insertions(+), 19 deletions(-) diff --git a/examples/egocap/recording/egocap/recording/episode_layout.py b/examples/egocap/recording/egocap/recording/episode_layout.py index 53f1305b2d..b646933f6e 100644 --- a/examples/egocap/recording/egocap/recording/episode_layout.py +++ b/examples/egocap/recording/egocap/recording/episode_layout.py @@ -694,6 +694,10 @@ def remove_owned_episode(session_path: Path, manifest: EpisodeManifest) -> None: BEAT_WATCH_SECONDS = 2.5 +#: How much of a lock file a look reads: more than any beat a recorder writes. +_BEAT_BYTES = 64 + + def session_beat(session_path: Path) -> tuple[bytes, int] | None: """What a session's lock file holds right now and when it was last written; None when it has none. @@ -704,11 +708,33 @@ def session_beat(session_path: Path) -> tuple[bytes, int] | None: """ try: with open(session_path / MANIFEST_DIR / SESSION_LOCK_FILE, "rb") as handle: - return handle.read(64), os.fstat(handle.fileno()).st_mtime_ns + return handle.read(_BEAT_BYTES), os.fstat(handle.fileno()).st_mtime_ns except FileNotFoundError: return None +def session_lock_value(session_path: Path) -> bytes | None: + """What the last recorder to hold a session left in its lock file; None where the file says nothing: it + is missing, it is empty, or it is no file of the session's own. + + The written value alone, without the file's time: only a recorder writes it, and a new holder never writes + an earlier holder's, so it tells a session at rest from another under its name. An empty file is what a + recorder that wrote no beat left, the same in every such session. A link is not followed: what stands + elsewhere is no word of a recorder of this session, as :class:`SessionHold` refuses such a lock file. + """ + try: + descriptor = os.open(session_path / MANIFEST_DIR / SESSION_LOCK_FILE, os.O_RDONLY | os.O_NOFOLLOW) + except FileNotFoundError: + return None + except OSError as refused: + # A link in the lock file's place is refused with this error, and with no other. + if refused.errno == errno.ELOOP: + return None + raise + with os.fdopen(descriptor, "rb") as lock_file: + return lock_file.read(_BEAT_BYTES) or None + + def session_lock_is_free(session_path: Path) -> bool: """Whether no recorder has the session open, asked without waiting and without keeping the lock. diff --git a/examples/egocap/recording/recording_service/output_scan.py b/examples/egocap/recording/recording_service/output_scan.py index bcb3cd785f..8af3e4c7c5 100644 --- a/examples/egocap/recording/recording_service/output_scan.py +++ b/examples/egocap/recording/recording_service/output_scan.py @@ -7,7 +7,8 @@ A caller that shows an operator what earlier sessions left behind reads the whole output, and reads it again from time to time. :class:`OutputScan` keeps what it learned between reads, so a repeated read costs one listing of the output, one small read of each settled session's lock file, and the few sessions that can still change, however -many takes the output holds. +many takes the output holds. A session whose lock file says nothing cannot be remembered and is among those +few at every read, with all its records: an output that holds many of them is read slowly for as long as it does. A session some recorder has open is never listed and never remembered. Two things say so. Its lock, where the lock reaches. And its beat, which reaches wherever the directory can be seen: the recorder rewrites the lock @@ -44,6 +45,7 @@ session_beat, session_has_lock_file, session_lock_is_free, + session_lock_value, ) __all__ = ["LeftBehind", "OutputScan", "SessionOpen", "takes_left_behind"] @@ -96,23 +98,14 @@ class _Watch: since: float -def _last_holder(session_path: Path) -> bytes | None: - """What the last recorder to hold a session left in its lock file; None for a session without one. - - The written value alone, without the file's time: only a recorder writes it, and a new holder never writes - an earlier holder's. - """ - beat = session_beat(session_path) - return None if beat is None else beat[0] - - class OutputScan: """Reads what the sessions of one station left behind under a recording output, remembering between reads. A session is settled, and not opened again, when it was read with nothing left to resolve or when its ``config.yaml`` was read and names a station that is not this reader's. A session that still holds a take is read again every time, and so is one that appeared since the last read, one whose ``config.yaml`` could not - be read yet, and one no recorder ever locked. + be read yet, and one whose lock file says nothing: a session no recorder ever locked, one whose lock file + is empty (a recorder that wrote no beat left it so), and one whose lock file is a link. A settled session is known again by what its last recorder left in its lock file: a token drawn for that one holding of the session and the count of its beats, which only a recorder writes. A directory put in @@ -176,7 +169,8 @@ def read( continue try: # One small read tells a settled session that is as it was from anything else under its name. - if name in self._settled and self._settled[name] == _last_holder(output_root / name): + known = self._settled.get(name) + if known is not None and known == session_lock_value(output_root / name): continue left, settled_as = self._read_session(output_root / name, names) except OSError as exc: @@ -307,10 +301,13 @@ def _read_session(self, session_path: Path, names: frozenset[str]) -> tuple[list self._first_looks += first return [], None # The value judged quiet, taken before the files are read: a recorder that opens the session while they - # are leaves another, and the session is then read again. None for a session no recorder ever locked, - # which holds nothing to know it by. + # are leaves another, and the session is then read again. None for a session that holds nothing to + # know it by: one no recorder ever locked, and one whose lock file is empty or a link, which the + # look at the beat reads through and ``session_lock_value`` does not. beat = self._watches[session_path.name].beat held = None if beat is None else beat[0] + if held != session_lock_value(session_path): + held = None read, station = frozen_station(session_path) if read and station is not None and station not in names: # Another station's session is that station's to resolve, and its name never changes. diff --git a/examples/egocap/tests/recording/unit/test_take_resolution_layout.py b/examples/egocap/tests/recording/unit/test_take_resolution_layout.py index b34be504eb..92e4cfd1be 100644 --- a/examples/egocap/tests/recording/unit/test_take_resolution_layout.py +++ b/examples/egocap/tests/recording/unit/test_take_resolution_layout.py @@ -600,6 +600,36 @@ def utime(target, *args, **kwargs): SessionLock(session).release() +def test_what_a_recorder_left_in_the_lock_file_is_read_without_following_a_link_and_an_empty_file_says_nothing( + tmp_path, monkeypatch +): + monkeypatch.setattr(episode_layout, "BEAT_SECONDS", 3600.0) + session = _session(tmp_path) + lock_file = session / episode_layout.MANIFEST_DIR / episode_layout.SESSION_LOCK_FILE + # Nobody ever opened it: there is no lock file to say anything. + assert episode_layout.session_lock_value(session) is None + SessionLock(session).release() + left = episode_layout.session_lock_value(session) + # The recorder's token and count, as a look at the beat reads them, without the file's time. + assert left == episode_layout.session_beat(session)[0] and left.split()[1] == b"2" + # What a recorder that wrote no beat left: the same in every such session, so no value at all. + lock_file.write_bytes(b"") + assert episode_layout.session_lock_value(session) is None + # A link in the lock file's place is not followed, wherever it leads; a look at the beat reads through it. + elsewhere = tmp_path / "elsewhere.lock" + elsewhere.write_bytes(left) + lock_file.unlink() + lock_file.symlink_to(elsewhere) + assert episode_layout.session_lock_value(session) is None + assert episode_layout.session_beat(session)[0] == left + # Anything else that keeps the file from being read is the caller's to hear of. + lock_file.unlink() + (session / episode_layout.MANIFEST_DIR).rename(tmp_path / "moved-aside") + (session / episode_layout.MANIFEST_DIR).write_text("no directory") + with pytest.raises(NotADirectoryError): + episode_layout.session_lock_value(session) + + def test_a_new_holder_never_writes_a_beat_an_earlier_holder_wrote(tmp_path, monkeypatch): monkeypatch.setattr(episode_layout, "BEAT_SECONDS", 3600.0) # only the beat written at once session = _session(tmp_path) diff --git a/examples/egocap/tests/recording_service/test_takes_left_behind.py b/examples/egocap/tests/recording_service/test_takes_left_behind.py index 199729ef23..c901f411d2 100644 --- a/examples/egocap/tests/recording_service/test_takes_left_behind.py +++ b/examples/egocap/tests/recording_service/test_takes_left_behind.py @@ -671,9 +671,11 @@ async def test_a_session_that_stays_as_it_was_settled_is_not_opened_again_though assert (await record(finished)).disposition is Disposition.KEPT await finished.close() opened, beats = [], [] - real_scan, real_beat = output_scan.scan_session, output_scan.session_beat + real_scan, real_value = output_scan.scan_session, output_scan.session_lock_value monkeypatch.setattr(output_scan, "scan_session", lambda path: opened.append(path.name) or real_scan(path)) - monkeypatch.setattr(output_scan, "session_beat", lambda path: beats.append(path.name) or real_beat(path)) + monkeypatch.setattr( + output_scan, "session_lock_value", lambda path: beats.append(path.name) or real_value(path) + ) reader = _Reader(root, watch=0.0) assert reader.look() == [] and opened == [session.session_id] beats.clear() @@ -697,7 +699,7 @@ async def test_a_settled_session_whose_lock_file_can_no_longer_be_read_is_passed def refuse(session_path): raise PermissionError(errno.EACCES, "Permission denied", str(session_path)) - monkeypatch.setattr(output_scan, "session_beat", refuse) + monkeypatch.setattr(output_scan, "session_lock_value", refuse) with caplog.at_level(logging.WARNING, logger="isaaccapture.egocap.output_scan"): assert reader.look() == [] and reader.look() == [] passed_over = "an entry of the recording output cannot be read and is passed over" @@ -715,6 +717,70 @@ def test_a_session_no_recorder_ever_locked_is_read_every_time(tmp_path, monkeypa assert reader.look() == [] and reader.look() == [] and opened == ["session_by_hand"] * 2 +def _lock_file(session_path: Path) -> Path: + return session_path / episode_layout.MANIFEST_DIR / episode_layout.SESSION_LOCK_FILE + + +def _put_in_place_of(session_path: Path, other: Path, other_id: str | None = None) -> None: + """Replace a session directory by a copy of another, under its name; ``other_id`` is the session the other's + records were written for, where they are to read as this one's own.""" + shutil.rmtree(session_path) + shutil.copytree(other, session_path, symlinks=True) + if other_id is not None: + for record_file in (session_path / episode_layout.MANIFEST_DIR).glob("episode_*.json"): + record_file.write_text(record_file.read_text().replace(other_id, session_path.name)) + + +async def _kept_only(root: Path): + """A session with one kept take and nothing waiting, its recorder closed.""" + service = RecordingService(_config(root)) + session = await service.open_session() + assert (await record(service)).disposition is Disposition.KEPT + assert (await service.close()).released + return session + + +async def test_a_session_whose_lock_file_is_empty_is_read_at_every_look_and_one_put_in_its_place_is_listed( + tmp_path, monkeypatch +): + """A recorder that wrote no beat left its lock file empty: nothing in it tells such sessions apart.""" + root, side = tmp_path / "out", tmp_path / "side" + first = await _kept_only(root) + _lock_file(first.session_path).write_bytes(b"") + opened = [] + real_scan = output_scan.scan_session + monkeypatch.setattr(output_scan, "scan_session", lambda path: opened.append(path.name) or real_scan(path)) + reader = _Reader(root, watch=0.0) + assert reader.look() == [] and reader.look() == [] + # Never remembered: an empty lock is no value to know a session by. + assert opened == [first.session_id] * 2 and reader.scan._settled == {} + restored, _left = await _left_by_a_recorder_that_is_gone(side) + _lock_file(restored.session_path).write_bytes(b"") + _put_in_place_of(first.session_path, restored.session_path, restored.session_id) + # Watched like any session that was never remembered: the other file's time reads as a beat at the first + # look, and the take is listed at the latest by the one after. + assert [reader.look(), reader.look()][-1] == [f"{first.session_id}/episode_1"] + + +async def test_a_lock_file_that_is_a_link_is_not_followed_and_its_session_is_never_remembered( + tmp_path, monkeypatch +): + root = tmp_path / "out" + session = await _kept_only(root) + lock = _lock_file(session.session_path) + elsewhere = tmp_path / "elsewhere.lock" + lock.rename(elsewhere) + lock.symlink_to(elsewhere) + opened = [] + real_scan = output_scan.scan_session + monkeypatch.setattr(output_scan, "scan_session", lambda path: opened.append(path.name) or real_scan(path)) + reader = _Reader(root, watch=0.0) + # A link is nobody's lock file: what it points at is not taken for the word of a recorder of this session. + assert reader.look() == [] and reader.look() == [] + assert opened == [session.session_id] * 2 and reader.scan._settled == {} + assert episode_layout.session_lock_value(session.session_path) is None + + # --- the station: every name it has had, and sessions that carry none ------------------------- From c888115c9f7ec7e241bc0ea2338bae0a9f1d27e2 Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 12:13:59 -0800 Subject: [PATCH 22/24] egocap: tests for three parts of the session reader's rule that none pinned Three parts of how the reader knows a session at rest were right and no test failed without them. Each now has a test in which a real take is hidden when the part is taken out: - the count of beats is compared, not the holder's token alone: a copy of an earlier moment of the same holding, with a take waiting in it, is told from the session as the holder left it; - a session without a lock file is never remembered, also when its configuration reads and nothing waits in it; - the value is the one judged before the session's records are read: a recorder that opens the session, leaves a take and closes right after they were read has the session read again. A fourth test is the case the release's last beat exists for: a copy taken while a recorder wrote a take, restored after the recorder closed within the same beat. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- .../test_takes_left_behind.py | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) diff --git a/examples/egocap/tests/recording_service/test_takes_left_behind.py b/examples/egocap/tests/recording_service/test_takes_left_behind.py index c901f411d2..9bcf592651 100644 --- a/examples/egocap/tests/recording_service/test_takes_left_behind.py +++ b/examples/egocap/tests/recording_service/test_takes_left_behind.py @@ -762,6 +762,96 @@ async def test_a_session_whose_lock_file_is_empty_is_read_at_every_look_and_one_ assert [reader.look(), reader.look()][-1] == [f"{first.session_id}/episode_1"] +async def test_a_copy_taken_while_a_recorder_held_the_session_is_told_from_the_session_as_the_recorder_left_it( + tmp_path, +): + root, backup = tmp_path / "out", tmp_path / "backup" + service = RecordingService(_config(root)) + session = await service.open_session() + episode = await service.start_episode("t", "op") + await submit_all(service, episode.episode_id, take_samples(seconds=0.2)) + # A live copy, taken while the take is written. The recorder then finishes within the same beat. + shutil.copytree(session.session_path, backup) + at_copy = _lock_file(backup).read_bytes() + await service.stop_episode(episode.episode_id) + assert (await service.close()).released + # What the recorder left is a value the copy cannot hold: its release wrote a beat of its own. + assert _lock_file(session.session_path).read_bytes() != at_copy + reader = _Reader(root, watch=0.0) + assert reader.look() == [] and reader.look() == [] + _put_in_place_of(session.session_path, backup) + assert reader.look() == [f"{session.session_id}/episode_0"] + + +async def test_a_copy_of_an_earlier_moment_of_the_same_holding_is_told_by_the_count_of_its_beats(tmp_path): + root, backup = tmp_path / "out", tmp_path / "backup" + service = RecordingService(_config(root)) + session = await service.open_session() + interrupted = await _interrupted_take(service) + shutil.copytree(session.session_path, backup) # a take waits in the copy + assert (await service.discard_pending(interrupted.episode_id)).disposition is Disposition.DISCARDED + assert (await service.close()).released + earlier, left = _lock_file(backup).read_bytes().split(), _lock_file(session.session_path).read_bytes().split() + # One holder, so one token: only the count says that the copy is of an earlier moment. + assert earlier[0] == left[0] and earlier[1] != left[1] + reader = _Reader(root, watch=0.0) + assert reader.look() == [] and reader.look() == [] + _put_in_place_of(session.session_path, backup) + assert reader.look() == [interrupted.episode_id] + + +async def test_a_session_without_a_lock_file_is_never_remembered_though_its_config_reads_and_nothing_waits( + tmp_path, monkeypatch +): + root, side = tmp_path / "out", tmp_path / "side" + quiet = await _kept_only(side / "quiet") + waiting, _left = await _left_by_a_recorder_that_is_gone(side / "waiting") + by_hand = root / "by_hand" + shutil.copytree(quiet.session_path, by_hand) + _lock_file(by_hand).unlink() + opened = [] + real_scan = output_scan.scan_session + monkeypatch.setattr(output_scan, "scan_session", lambda path: opened.append(path.name) or real_scan(path)) + reader = _Reader(root, watch=0.0) + # Everything that lets a session settle is there but a recorder's word of who held it last. + assert reader.look() == [] and reader.look() == [] + assert opened == ["by_hand"] * 2 and reader.scan._settled == {} + _put_in_place_of(by_hand, waiting.session_path) + _lock_file(by_hand).unlink() + # Listed as another session's records found here, which is what they are. + assert reader.look() == ["by_hand/episode_1"] + + +async def test_a_recorder_that_takes_the_session_while_its_records_are_read_has_it_read_again( + tmp_path, monkeypatch +): + root = tmp_path / "out" + session = await _kept_only(root) + real_scan = output_scan.scan_session + acted: list[str] = [] + + def read_then_a_recorder_acts(path): + found = real_scan(path) + if not acted: + # Right after the records were read: a recorder opens the session, leaves a take and closes. + async def a_recorder() -> None: + again = RecordingService(_config(root)) + await again.open_session(session.session_id) + acted.append((await _interrupted_take(again)).episode_id) + assert (await again.close()).released + + worker = threading.Thread(target=lambda: asyncio.run(a_recorder())) + worker.start() + worker.join() + return found + + monkeypatch.setattr(output_scan, "scan_session", read_then_a_recorder_acts) + reader = _Reader(root, watch=0.0) + # The look saw the session as it was before the recorder came, and remembers it by what its lock held then. + assert reader.look() == [] and len(acted) == 1 + assert reader.look() == acted + + async def test_a_lock_file_that_is_a_link_is_not_followed_and_its_session_is_never_remembered( tmp_path, monkeypatch ): From 519474afa9066586db025e3bb20433f1dd4cf547 Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 12:48:28 -0800 Subject: [PATCH 23/24] egocap: the guides say what three cameras were run with, where the tools are, and that the Orin does not resize Three statements in the guides were no longer true, or said something the chain is not meant to do. Three cameras through the launcher have been run on an Orin: once, on one station, through the Argus backend, at one frame rate, published as received, from the launcher to the page. Each guide's "Not yet verified on hardware" says that and what is still not run: three cameras corrected live, the SIPL backend with three cameras, a recording of three cameras, and one camera dropping. What a station checks for itself is listed apart from what nobody has run. The sender, its deploy tool, the mock sender, the bridge and the timesync tool are in this repository; only a LiveKit server is not. The launcher's header, its help and the guides said several of them were not. They now name each tool's place and which the launcher has to be told of. The mock sender binds loopback, so its port is checked there. A stream of the Argus example states its sensor mode's own size. The example and the guide offered a smaller one for the sender to scale to; this chain does no resizing on the Orin, the PC corrects and resizes on its GPU, and correction would then start from a scaled picture. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- examples/egocap/CALIBRATION_TOOLS.md | 16 +++--- examples/egocap/CAMERA_SETTINGS.md | 57 ++++++++++++------- examples/egocap/LIVEKIT_PREVIEW.md | 16 +++--- examples/egocap/README.md | 33 ++++++----- examples/egocap/backend/README.md | 16 +++--- .../three-camera-settings.argus.example.yaml | 8 ++- .../egocap/tests/tools/test_start_system.py | 2 + examples/egocap/tools/start_system.py | 21 ++++--- 8 files changed, 101 insertions(+), 68 deletions(-) diff --git a/examples/egocap/CALIBRATION_TOOLS.md b/examples/egocap/CALIBRATION_TOOLS.md index 8d8d12ab68..1364f4265a 100644 --- a/examples/egocap/CALIBRATION_TOOLS.md +++ b/examples/egocap/CALIBRATION_TOOLS.md @@ -2659,13 +2659,15 @@ start its children with. What that leaves unknown: the camera bridge. The step's rule, the table file and what the bridge tests without a GPU are described in [`../camera_livekit_bridge/GPU_PROCESSING.md`](../camera_livekit_bridge/GPU_PROCESSING.md). The preview and the offline copy follow that rule with OpenCV on the CPU; that the bridge's output equals them has not been seen. -- **Three cameras through the launcher have never been run on an Orin.** No Jetson, GMSL camera or CUDA GPU was - at hand: the three-stream start was run against stand-ins for the programs it starts, and - `configs/three-camera-settings.example.yaml` holds a placeholder for every station value. A first run must check - that each stream arrives as the camera its role says, that each corrected picture is corrected with its own - camera's calibration, the GPU's memory and load with three decode, remap and encode pipelines, the bitrate the - link between the Orin and the PC carries, that time sync settles for all three streams, and what happens when - one camera drops. [`CAMERA_SETTINGS.md`](CAMERA_SETTINGS.md#not-yet-verified-on-hardware) says how to check each. +- **Three cameras through the launcher have been run on an Orin once, in one way.** On one station, through the + Argus backend, at one frame rate, published as received (not corrected), from the launcher to the page. + Everything else of the three-stream start was run against stand-ins for the programs it starts, and both example + profiles hold a placeholder for every station value. Not yet run on hardware: three cameras corrected live, each + with its own camera's calibration; the SIPL backend with three cameras; a recording of three cameras, and with + it that their takes are time-aligned; and what happens when one camera drops. A station still checks for itself + which stream is which camera, what its GPU carries with three decode, remap and encode pipelines, and what its + link between the Orin and the PC carries. [`CAMERA_SETTINGS.md`](CAMERA_SETTINGS.md#not-yet-verified-on-hardware) says how + to check each. - **No real board was captured.** How far towards the rim of a real wide-angle lens the board is still detected, and so whether the reach the guide and the fisheye grade ask for can be had, is not measured; neither is the fisheye solve on a real lens. The live guide judges blur by the board's size in the picture, not by where the diff --git a/examples/egocap/CAMERA_SETTINGS.md b/examples/egocap/CAMERA_SETTINGS.md index 3defc0956b..93ae07bd10 100644 --- a/examples/egocap/CAMERA_SETTINGS.md +++ b/examples/egocap/CAMERA_SETTINGS.md @@ -167,11 +167,16 @@ What differs between the two examples: |---|---|---| | What names the cameras | A platform file, a platform name and link masks (`sipl.*`), then each stream's SIPL pipeline index | Each stream's Argus device index and sensor-mode index (`cameras[].device`, `cameras[].mode`), read from `build/argus_sender --list-modes` in a deployed release on the Orin | | `cameras[].device` is not | the GMSL link number | the number of the port the camera is cabled to | -| Picture size | The sensor's own; the backend does not scale | The sensor mode's own, or a smaller one the sender scales to | +| Picture size | The sensor's own; the backend does not scale | The sensor mode's own. The backend would scale to a smaller one, which this chain is designed to avoid: see below | | `nvargus-daemon` | Stopped by the launcher before the sender starts, since it holds the cameras | Left running: Argus capture goes through it | | Colour range the bridge is told | Full range (`--source-full-range`) | Limited range, the bridge's default | | Capture mode of each stream | Not used | `capture.mode`, below | +**Picture size on Argus.** State each stream's sensor mode's own size in `output.width` and `output.height`. This +chain does no resizing on the Orin: the PC corrects and resizes the picture on its GPU. The Argus backend accepts a +smaller size and then scales the picture on the Orin, which is what the chain is designed to avoid, and correction +on the PC then starts from a scaled picture. + **Capture modes on Argus.** The sender takes one stream for its priority stream: a stereo HEVC stream at the highest rate when there is one, otherwise the first stream at the highest rate. In the example that is `head`, which is listed first and runs at the rate all three share. The other streams' frames are matched to the priority @@ -237,10 +242,10 @@ bridge's guide states what a stream takes in all, and it was not measured. ## Sender profile keys -These keys belong to the sender release the profile targets, which is not part of this tree: it supports the SIPL -backend and the timing extension. An older `argus_sender` in this repository has a different parser and rejects some -of these keys, so check a release's parser before using a key. Defaults are that parser's own and can differ from the -shipped profile. +These keys are read by the sender, `examples/camera_streamer/argus_sender` in this repository; its parser is +`src/Config.cpp` there. A release that was deployed from another checkout may have another parser, which rejects +some of these keys, so check the parser of the release in use before using a key. Defaults are the parser's own and +can differ from the shipped profile. | Key | Default / requirement | Meaning and consumer | |---|---|---| @@ -337,22 +342,30 @@ timestamps; it does not configure the Orin or join LiveKit for anyone. ## Not yet verified on hardware -- **Three cameras through the launcher have never been run on an Orin.** No Jetson, GMSL camera or CUDA GPU was - at hand. The launcher's three-stream start was run against stand-ins for every program it starts; the receiver - config, the mock sender's command, the deploy commands and the stream descriptor it writes were read by those - programs' own parsers; the bridge's command line was held only to the rules its guide states, since the bridge - needs CUDA to build. `configs/three-camera-settings.example.yaml` holds a placeholder for every station value - and was never deployed; `configs/three-camera-settings.argus.example.yaml` was written from the sender's guide - and was never deployed either, and what it says of capture modes is the guide's, not a measurement. A first run on a station must check: +- **Three cameras through the launcher have been run on an Orin once, in one way.** On one station, through the + Argus backend, at one frame rate, published as received (not corrected), from the launcher to the page. That is + all that was run on hardware. The rest of the three-stream start was run against stand-ins for every program it + starts; the receiver config, the mock sender's command, the deploy commands and the stream descriptor it writes + were read by those programs' own parsers; the bridge's command line was held only to the rules its guide states. + Neither example profile was deployed as it is shipped: each holds a placeholder for every station value, and + what the Argus one says of capture modes is the sender's guide's, not a measurement. + + Not yet run on hardware: + - **three cameras corrected live:** that each corrected picture is corrected with its own camera's calibration + (straight edges come out straight in all three, and a take's `rectification.json` names each role's own + intrinsics file), and the GPU's memory and load with a remap step in each of the three pipelines; neither + guide of the receiver or the bridge states a figure; + - **the SIPL backend with three cameras:** the SIPL example profile, the daemon stop before the sender starts, + and full-range pictures through the bridge; + - **a recording of three cameras:** that a take holds all three, and that time sync leaves all three streams + with capture times, so that takes are aligned; + - **what happens when one camera drops:** whether the sender keeps sending the other two, what the receiver and + the bridge report for the missing one, and that a bridge that exits stops the whole stack, as the launcher + means it to. A take is given up when any one of its cameras sends no frame. + + What a station checks for itself, whatever was run elsewhere: - that each stream arrives as the camera its role says: cover one lens at a time and see which tile goes dark, against the `stream '': , ...` lines the launcher prints; - - that each corrected picture is corrected with its own camera's calibration: straight edges come out straight - in all three, and a take's `rectification.json` names each role's own intrinsics file; - - the GPU's memory and load with three decode, remap and encode pipelines running, and that the GPU allows that - many decoder and encoder sessions at once; neither guide of the receiver or the bridge states a figure; - - the bitrate the link between the Orin and the PC carries with three streams, against the sum the profile - asks for (`deploy_sender.py user@orin linktest`), and the receiver's measured rate for each stream; - - that time sync settles and all three streams carry capture times, so takes are aligned; - - what happens when one camera drops: whether the sender keeps sending the other two, what the receiver and the - bridge report for the missing one, and that a bridge that exits stops the whole stack, as the launcher means - it to. A take is given up when any one of its cameras sends no frame. + - that its GPU allows three decoder and three encoder sessions at once, and what they take; + - the bitrate its link between the Orin and the PC carries with three streams, against the sum the profile asks + for (`deploy_sender.py user@orin linktest`), and the receiver's measured rate for each stream. diff --git a/examples/egocap/LIVEKIT_PREVIEW.md b/examples/egocap/LIVEKIT_PREVIEW.md index 7164f1f5c2..7a2dbd6c7a 100644 --- a/examples/egocap/LIVEKIT_PREVIEW.md +++ b/examples/egocap/LIVEKIT_PREVIEW.md @@ -191,13 +191,15 @@ corrected video is what the launcher is for. ## Not yet verified on hardware -- **Three cameras through the launcher have never been run on an Orin.** No Jetson, GMSL camera or CUDA GPU was - at hand: the three-stream start was run against stand-ins for the programs it starts, and - `configs/three-camera-settings.example.yaml` holds a placeholder for every station value. A first run must check - that each stream arrives as the camera its role says, that each corrected picture is corrected with its own - camera's calibration, the GPU's memory and load with three decode, remap and encode pipelines, the bitrate the - link between the Orin and the PC carries, that time sync settles for all three streams, and what happens when - one camera drops. [`CAMERA_SETTINGS.md`](CAMERA_SETTINGS.md#not-yet-verified-on-hardware) says how to check each. +- **Three cameras through the launcher have been run on an Orin once, in one way.** On one station, through the + Argus backend, at one frame rate, published as received (not corrected), from the launcher to the page. + Everything else of the three-stream start was run against stand-ins for the programs it starts, and both example + profiles hold a placeholder for every station value. Not yet run on hardware: three cameras corrected live, each + with its own camera's calibration; the SIPL backend with three cameras; a recording of three cameras, and with + it that their takes are time-aligned; and what happens when one camera drops. A station still checks for itself + which stream is which camera, what its GPU carries with three decode, remap and encode pipelines, and what its + link between the Orin and the PC carries. [`CAMERA_SETTINGS.md`](CAMERA_SETTINGS.md#not-yet-verified-on-hardware) says how + to check each. With three cameras the checklist has an item for each camera the station's roles name, the page reports what its preview receives of each, and a take is given up when any one of the three sends no frame within ten seconds; none of that was seen with three real streams. diff --git a/examples/egocap/README.md b/examples/egocap/README.md index 42c45c383c..5881165011 100644 --- a/examples/egocap/README.md +++ b/examples/egocap/README.md @@ -372,18 +372,21 @@ requests three cameras, so the launcher refuses to start unless each one is give `video_sources` name no CaptureServer cameras when the video comes from the Orin through LiveKit. `--mock` runs without hardware: CaptureServer gives synthetic tracking and cameras, and a local mock sender replaces -the Orin, so nothing real is started and `--orin` is refused. The mock sender is `camera_streamer`'s `mock_sender.py`. -It is not in this tree (it is added by the camera_streamer mock-sender change, PR #1476), so give its path with +the Orin, so nothing real is started and `--orin` is refused. The mock sender is `camera_streamer`'s `mock_sender.py`, +`examples/camera_streamer/mock_sender/mock_sender.py` in this repository; give its path with `--mock-sender` or `EGOCAP_MOCK_SENDER`; it needs `ffmpeg` with `libx265`. With `--bridge`, `--livekit-server` and the mock sender the mock video goes through the same receiver, bridge and page, with the frame-ready time as its timestamp because the mock sender has no clock to measure. A recording made in this mode is synthetic data. Without `--orin` or `--mock` only the PC side starts. `--skip-deploy` reuses the previous release. The sender runs for `--seconds` (default one hour) and the launcher stops the whole stack when it ends, so a take in progress is -cut off; the launcher prints the stop time at startup. The sender release the profile describes, its deploy tool, the -timesync tool, the LiveKit server and the bridge are not in this tree's base, so pass their paths (or set -`EGOCAP_DEPLOY_SCRIPT`, `EGOCAP_TIMESYNC_TOOL`, `EGOCAP_LIVEKIT_SERVER`, `EGOCAP_BRIDGE`); `--orin` needs the timesync -tool and refuses to start without it. `--orin` also needs an IPv4 address, because the bridge finds the sender's chrony +cut off; the launcher prints the stop time at startup. The sender, its deploy tool, the mock sender, the bridge and +the timesync tool are all in this repository; a LiveKit server is not. The launcher is told where two programs are +that it cannot find by itself: the LiveKit server (`--livekit-server` or `EGOCAP_LIVEKIT_SERVER`) and the bridge, +which is built from `examples/camera_livekit_bridge` (`--bridge` or `EGOCAP_BRIDGE`). The deploy tool is +`examples/camera_streamer/argus_sender/deploy/deploy_sender.py`, named with `--deploy-script` (or +`EGOCAP_DEPLOY_SCRIPT`). The timesync tool is `src/core/timesync/tools/timesync_tool.py`, which the launcher uses +unless `--timesync-tool` (or `EGOCAP_TIMESYNC_TOOL`) names another; `--orin` needs it and refuses to start without it. `--orin` also needs an IPv4 address, because the bridge finds the sender's chrony by it. After the bridge starts, the launcher runs time sync through `src/core/timesync/tools/timesync_tool.py` (see that module's README): `ensure-local` (which may install chrony on this PC), an unprivileged chronyd on this PC that measures the Orin's clock, and `configure-remote` on the Orin; each step has a timeout. These steps run before the page address @@ -419,7 +422,7 @@ checks each port only when the program that binds it will be started, and on the | `EGOCAP_VISER_PORT`, 8085, TCP | the backend's 3D view | unless `EGOCAP_VISER_ENABLED` switches it off | `EGOCAP_VISER_HOST`, loopback unless set | | 7880, TCP | LiveKit, signalling | with `--livekit-server` | loopback | | 7881, TCP and 7882, UDP | LiveKit, media | with `--livekit-server` | every address of this PC, since LiveKit listens for media on the network interfaces' own addresses | -| the profile's `network.port`, TCP | the mock sender | with `--mock` and the camera chain | every address | +| the profile's `network.port`, TCP | the mock sender | with `--mock` and the camera chain | loopback | | `--chrony-cmd-port`, 12301, UDP | the time-sync follower | with `--orin` | loopback | The refusal names each port, whose it is and, where the system tells (`ss`, else `lsof`), the program that holds @@ -481,13 +484,15 @@ its [Limits](CALIBRATION_TOOLS.md#limits) for what of this has and has not been Not yet verified on hardware: -- **Three cameras through the launcher have never been run on an Orin.** No Jetson, GMSL camera or CUDA GPU was - at hand: the three-stream start was run against stand-ins for the programs it starts, and - `configs/three-camera-settings.example.yaml` holds a placeholder for every station value. A first run must check - that each stream arrives as the camera its role says, that each corrected picture is corrected with its own - camera's calibration, the GPU's memory and load with three decode, remap and encode pipelines, the bitrate the - link between the Orin and the PC carries, that time sync settles for all three streams, and what happens when - one camera drops. [`CAMERA_SETTINGS.md`](CAMERA_SETTINGS.md#not-yet-verified-on-hardware) says how to check each. +- **Three cameras through the launcher have been run on an Orin once, in one way.** On one station, through the + Argus backend, at one frame rate, published as received (not corrected), from the launcher to the page. + Everything else of the three-stream start was run against stand-ins for the programs it starts, and both example + profiles hold a placeholder for every station value. Not yet run on hardware: three cameras corrected live, each + with its own camera's calibration; the SIPL backend with three cameras; a recording of three cameras, and with + it that their takes are time-aligned; and what happens when one camera drops. A station still checks for itself + which stream is which camera, what its GPU carries with three decode, remap and encode pipelines, and what its + link between the Orin and the PC carries. [`CAMERA_SETTINGS.md`](CAMERA_SETTINGS.md#not-yet-verified-on-hardware) says how + to check each. ### Integration boundary diff --git a/examples/egocap/backend/README.md b/examples/egocap/backend/README.md index 98bf5afce4..0448bd592d 100644 --- a/examples/egocap/backend/README.md +++ b/examples/egocap/backend/README.md @@ -771,13 +771,15 @@ capture server, scripted stand-ins or synthetic data: start of a take, were measured with the recorder driven by the mock CaptureServer on one development computer, and the hardware H.264 encoder was not run. See [`../CALIBRATION_TOOLS.md`](../CALIBRATION_TOOLS.md), "Not yet verified on hardware". -- **Three cameras through the launcher have never been run on an Orin.** No Jetson, GMSL camera or CUDA GPU was - at hand: the three-stream start was run against stand-ins for the programs it starts, and - `configs/three-camera-settings.example.yaml` holds a placeholder for every station value. A first run must check - that each stream arrives as the camera its role says, that each corrected picture is corrected with its own - camera's calibration, the GPU's memory and load with three decode, remap and encode pipelines, the bitrate the - link between the Orin and the PC carries, that time sync settles for all three streams, and what happens when - one camera drops. [`CAMERA_SETTINGS.md`](../CAMERA_SETTINGS.md#not-yet-verified-on-hardware) says how to check each. +- **Three cameras through the launcher have been run on an Orin once, in one way.** On one station, through the + Argus backend, at one frame rate, published as received (not corrected), from the launcher to the page. + Everything else of the three-stream start was run against stand-ins for the programs it starts, and both example + profiles hold a placeholder for every station value. Not yet run on hardware: three cameras corrected live, each + with its own camera's calibration; the SIPL backend with three cameras; a recording of three cameras, and with + it that their takes are time-aligned; and what happens when one camera drops. A station still checks for itself + which stream is which camera, what its GPU carries with three decode, remap and encode pipelines, and what its + link between the Orin and the PC carries. [`CAMERA_SETTINGS.md`](../CAMERA_SETTINGS.md#not-yet-verified-on-hardware) says how + to check each. The backend's side of it (three cameras read from the launcher's report, the seven files a session of three corrected cameras carries, the Rectification tool's and the calibration tools' answers for each role) was run on a report made by the launcher's own planning from three synthetic lenses, never on a report of a real run. diff --git a/examples/egocap/configs/three-camera-settings.argus.example.yaml b/examples/egocap/configs/three-camera-settings.argus.example.yaml index b0a9465844..cfb8ecae34 100644 --- a/examples/egocap/configs/three-camera-settings.argus.example.yaml +++ b/examples/egocap/configs/three-camera-settings.argus.example.yaml @@ -47,7 +47,9 @@ streams: - {device: PLACEHOLDER_HEAD_ARGUS_DEVICE, mode: PLACEHOLDER_HEAD_SENSOR_MODE} output: codec: hevc - # The size this stream is sent at: the sensor mode's own size, or a smaller one, which the sender scales to. + # The sensor mode's own size, which `--list-modes` prints. This chain does no resizing on the Orin: the PC + # corrects and resizes on its GPU. A smaller size here makes the Orin scale the picture, which the chain is + # designed to avoid, and correction on the PC then starts from a scaled picture. width: PLACEHOLDER_HEAD_WIDTH height: PLACEHOLDER_HEAD_HEIGHT # One rate for all three streams, since the bridge runs every stream at one; at most the sensor mode's rate. @@ -67,7 +69,7 @@ streams: - {device: PLACEHOLDER_LEFT_WRIST_ARGUS_DEVICE, mode: PLACEHOLDER_LEFT_WRIST_SENSOR_MODE} output: codec: hevc - width: PLACEHOLDER_LEFT_WRIST_WIDTH # the size this stream is sent at + width: PLACEHOLDER_LEFT_WRIST_WIDTH # this camera's sensor mode's own size, as for the head height: PLACEHOLDER_LEFT_WRIST_HEIGHT fps: PLACEHOLDER_FPS # the same rate as the head stream bitrate_mbps: PLACEHOLDER_LEFT_WRIST_BITRATE_MBPS # this stream's share of the link @@ -81,7 +83,7 @@ streams: - {device: PLACEHOLDER_RIGHT_WRIST_ARGUS_DEVICE, mode: PLACEHOLDER_RIGHT_WRIST_SENSOR_MODE} output: codec: hevc - width: PLACEHOLDER_RIGHT_WRIST_WIDTH # the size this stream is sent at + width: PLACEHOLDER_RIGHT_WRIST_WIDTH # this camera's sensor mode's own size, as for the head height: PLACEHOLDER_RIGHT_WRIST_HEIGHT fps: PLACEHOLDER_FPS # the same rate as the head stream bitrate_mbps: PLACEHOLDER_RIGHT_WRIST_BITRATE_MBPS # this stream's share of the link diff --git a/examples/egocap/tests/tools/test_start_system.py b/examples/egocap/tests/tools/test_start_system.py index 343adf66cb..0ad52b0022 100644 --- a/examples/egocap/tests/tools/test_start_system.py +++ b/examples/egocap/tests/tools/test_start_system.py @@ -2434,6 +2434,8 @@ def test_every_taken_port_is_named_with_whose_it_is_and_one_nobody_can_name_says # A start without the camera chain needs no LiveKit port; a mock sender listens on the profile's port here. without = ss.needed_ports(backend_port=9000, livekit=False, mock_sender_port=5000) assert [(port.number, port.kind) for port in without] == [(9000, "tcp"), (8082, "tcp"), (5000, "tcp")] + # The mock sender binds loopback: its own default, which the launcher's command leaves alone. + assert without[-1].host == "127.0.0.1" taken.clear() ss.refuse_taken_ports(needed) diff --git a/examples/egocap/tools/start_system.py b/examples/egocap/tools/start_system.py index 58f7cb07e1..46494f4bce 100644 --- a/examples/egocap/tools/start_system.py +++ b/examples/egocap/tools/start_system.py @@ -41,11 +41,15 @@ each bridged camera is published as. The plan file and the streams state are the library's to name, read and write (``egocap.calibration.rectification_files``); the backend asks the same module. -The sender release the profile describes, its deploy tool, the timesync tool, the LiveKit server, the bridge and -the mock sender are not part of this tree's base, so the tools' paths are options (or ``EGOCAP_DEPLOY_SCRIPT``, -``EGOCAP_TIMESYNC_TOOL``, ``EGOCAP_LIVEKIT_SERVER``, ``EGOCAP_BRIDGE``, ``EGOCAP_MOCK_SENDER``). The pure -helpers sit above the supervisor so they can be tested without -starting anything. +The sender, its deploy tool, the mock sender, the bridge and the timesync tool are in this repository; a LiveKit +server is not. The launcher is told where the programs are that it cannot find by itself: the LiveKit server +(``--livekit-server`` or ``EGOCAP_LIVEKIT_SERVER``), the bridge built from ``examples/camera_livekit_bridge`` +(``--bridge`` or ``EGOCAP_BRIDGE``), the deploy tool (``--deploy-script`` or ``EGOCAP_DEPLOY_SCRIPT``), which is +``examples/camera_streamer/argus_sender/deploy/deploy_sender.py``, and, with ``--mock``, the mock sender +(``--mock-sender`` or ``EGOCAP_MOCK_SENDER``), which is ``examples/camera_streamer/mock_sender/mock_sender.py``. +The timesync tool, ``src/core/timesync/tools/timesync_tool.py``, is used from where it is unless +``--timesync-tool`` (or ``EGOCAP_TIMESYNC_TOOL``) names another. The pure helpers sit above the supervisor so they +can be tested without starting anything. """ from __future__ import annotations @@ -1080,8 +1084,8 @@ def needed_ports( NeededPort(LIVEKIT_RTC_UDP_PORT, "udp", "LiveKit's", host=""), ] if mock_sender_port is not None: - # The mock sender is not of this tree; nothing here says which address it binds. - ports.append(NeededPort(mock_sender_port, "tcp", "the mock sender's", "--sender-port", host="")) + # The mock sender binds loopback unless it is told another address, and the launcher tells it none. + ports.append(NeededPort(mock_sender_port, "tcp", "the mock sender's", "--sender-port")) if chrony_cmd_port is not None: ports.append(NeededPort(chrony_cmd_port, "udp", "the time-sync follower's", "--chrony-cmd-port")) return ports @@ -1843,7 +1847,8 @@ def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: "--mock-sender", type=Path, default=Path(os.environ["EGOCAP_MOCK_SENDER"]) if os.environ.get("EGOCAP_MOCK_SENDER") else None, - help="camera_streamer's mock_sender.py (not in this tree), used with --mock (needs ffmpeg with libx265)", + help="camera_streamer's mock_sender.py (examples/camera_streamer/mock_sender in this repository), used " + "with --mock (needs ffmpeg with libx265)", ) parser.add_argument( "--capture-camera", From f4849a057ccdbcc8f117685c4963ebbcabc6c659 Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Tue, 1 Dec 2026 14:57:30 -0800 Subject: [PATCH 24/24] egocap: a session just released is noted in a thread, not on the event loop After New batch, and after Recover or Discard of an earlier session's take, the coordinator tells the output reader that the session it just released is at rest. That call takes the reader's lock, which a read of the whole output holds in a worker thread for its walk, and reads the session's lock file. On the event loop it stopped the preview, every viewer's socket and the capture client for as long as that read took. Both calls now run in a thread, as the reader's other calls from the coordinator do. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- .../backend/egocap_web/recording_session.py | 10 ++++---- .../backend/test_takes_left_behind_wire.py | 23 +++++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/examples/egocap/backend/egocap_web/recording_session.py b/examples/egocap/backend/egocap_web/recording_session.py index 62feefe7cf..277a9ab5d9 100644 --- a/examples/egocap/backend/egocap_web/recording_session.py +++ b/examples/egocap/backend/egocap_web/recording_session.py @@ -962,8 +962,9 @@ async def _resolve_in_earlier_session_impl(self, pending: PendingEpisode, discar self._last_issue = "an earlier session did not fully release" elif own_beat: # The session was at rest before this process took it, so it is at rest again now: without - # this its own beat would hide the session's other takes for a watch time. - self._output_scan.note_closed(session_path) + # this its own beat would hide the session's other takes for a watch time. In a thread: the + # note reads the lock file and waits for a read of the whole output that is in flight. + await asyncio.to_thread(self._output_scan.note_closed, session_path) finally: await self.refresh_pending() # What the step did is reported whatever became of the read. @@ -1126,8 +1127,9 @@ async def _new_batch_impl(self) -> None: self._service = None self._status = SessionStatus.CLOSED if session is not None: - # The beat that just stopped was this process's own, so the session needs no second look. - self._output_scan.note_closed(session.session_path) + # The beat that just stopped was this process's own, so the session needs no second look. In a + # thread, as every other call into the reader: it waits for a read of the output in flight. + await asyncio.to_thread(self._output_scan.note_closed, session.session_path) # A take the closed session left pending is now an earlier session's, reachable only by this list. # The read is best effort: the batch rotates whether or not the output could be read. await self.refresh_pending() diff --git a/examples/egocap/tests/backend/test_takes_left_behind_wire.py b/examples/egocap/tests/backend/test_takes_left_behind_wire.py index 588c63c084..7d58b622fe 100644 --- a/examples/egocap/tests/backend/test_takes_left_behind_wire.py +++ b/examples/egocap/tests/backend/test_takes_left_behind_wire.py @@ -290,6 +290,29 @@ async def test_a_take_whose_files_carry_times_in_the_future_is_listed_and_discar # --- every name the station has had --------------------------------------------------------------- +@pytest.mark.parametrize("action", ["discard_pending", "new_batch"]) +async def test_a_session_just_released_is_noted_in_a_thread_never_on_the_event_loop(tmp_path, monkeypatch, action): + """The note waits for a read of the whole output in flight: on the loop it would stop the preview and every + viewer for that long.""" + root = tmp_path / "out" + episode_id = await _a_take_left_interrupted(root) + context = await _restart(root) + if action == "new_batch": + await _take(context) # a session of this batch is open, so New batch has one to close + noted_on: list[int] = [] + note_closed = output_scan.OutputScan.note_closed + + def noting(self, session_path): + noted_on.append(threading.get_ident()) + note_closed(self, session_path) + + monkeypatch.setattr(output_scan.OutputScan, "note_closed", noting) + reply = await _send(context, action, **({"episode_id": episode_id} if action == "discard_pending" else {})) + assert (reply["outcome"], reply["reason"]) == ("ok", None) + assert len(noted_on) == 1 and noted_on[0] != threading.get_ident() + await context.coordinator.close() + + async def test_a_take_left_before_the_station_was_renamed_is_still_listed_and_discarded(tmp_path): root = tmp_path / "out" episode_id = await _a_take_left_interrupted(root) # recorded as "Bench A"