From 2b6dd98cfddb7387c8fa557b119e8d8a4f954e7b Mon Sep 17 00:00:00 2001 From: Shawn Hwang Date: Sat, 28 Nov 2026 19:01:54 -0800 Subject: [PATCH] egocap: the launcher starts, bridges and corrects every station camera The launcher bridged the one stream of its sender profile. It now takes a profile of one to three mono streams and starts one chain for all of them: one sender deployment, one receiver config listing every stream in the profile's order, one camera bridge with a --stream for each, and for each corrected stream a table built at launch from that camera's own calibration and a --gpu-step of its own. Each bridged camera has its own entry in the streams state, so the page, the calibration and rectification tools and the recorder know per camera what was done. Which camera is which - --stream-role STREAM=ROLE is the one authority. A profile's only stream is the head camera as before; among several, each stream needs its role, and nothing is guessed from a stream's name or its place. - Among several streams a lens file that names no camera is refused, and so is one lens file used for two cameras: a picture corrected with another camera's lens would be wrong without anything saying so. - A plan that cannot be built for one camera stops the whole start before anything is deployed, and names the stream. What a profile must hold - Streams at different rates are refused: the bridge takes one rate. - Refused before anything is deployed, where the sender would refuse it afterwards: two streams on one camera device, a stream without exactly one camera, a rate or bitrate that is not a whole number, a port out of range. A value that is no number gets a sentence. - A child that has already exited is reported in place of the line that announces the page. configs/three-camera-settings.example.yaml has the structure of a three-camera profile with a placeholder for every value that belongs to one station; the launcher refuses it while one is left. stations/ego_stations.bridged.example.yaml is a station file for a station whose cameras all arrive through the bridge. A one-stream profile that started before starts the same: every command, file and message is unchanged. Three cameras have not been run on an Orin; CAMERA_SETTINGS.md lists what a first run must check. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Shawn Hwang --- examples/egocap/CALIBRATION_TOOLS.md | 123 +- examples/egocap/CAMERA_SETTINGS.md | 108 +- examples/egocap/LIVEKIT_PREVIEW.md | 16 +- examples/egocap/README.md | 46 +- examples/egocap/backend/README.md | 12 +- .../configs/default-camera-settings.yaml | 5 +- .../three-camera-settings.example.yaml | 83 + .../RectificationDialog.threeCameras.test.tsx | 91 + .../ego_stations.bridged.example.yaml | 65 + .../tests/backend/test_three_camera_run.py | 383 +++++ .../egocap/tests/tools/test_start_system.py | 9 +- .../tools/test_start_system_three_cameras.py | 1510 +++++++++++++++++ examples/egocap/tools/start_system.py | 476 ++++-- 13 files changed, 2785 insertions(+), 142 deletions(-) create mode 100644 examples/egocap/configs/three-camera-settings.example.yaml create mode 100644 examples/egocap/frontend/src/RectificationDialog.threeCameras.test.tsx create mode 100644 examples/egocap/recording/egocap/stations/ego_stations.bridged.example.yaml create mode 100644 examples/egocap/tests/backend/test_three_camera_run.py create mode 100644 examples/egocap/tests/tools/test_start_system_three_cameras.py diff --git a/examples/egocap/CALIBRATION_TOOLS.md b/examples/egocap/CALIBRATION_TOOLS.md index d46bfc37d4..774053a908 100644 --- a/examples/egocap/CALIBRATION_TOOLS.md +++ b/examples/egocap/CALIBRATION_TOOLS.md @@ -2173,27 +2173,40 @@ fisheye model, while a radial-tangential model of a wide lens turns over inside ### What the launcher does at start -`tools/start_system.py` starts the camera bridge for the stream of its sender profile (see the root -[`README.md`](README.md)). With the camera chain running it also: - -1. **Gives each bridged stream a camera role.** The profile's stream is the head camera, `ego`, unless - `--stream-role STREAM=ROLE` says otherwise (`ego`, `wrist_left`, `wrist_right`; repeatable). A malformed value, - an unknown role, a stream that is not bridged, and a stream or a role given twice are startup errors, and so is - a stream id in the sender config that holds `=`, which the bridge could not take in a stream's name. +`tools/start_system.py` starts one camera bridge, with a `--stream` for each stream of its sender profile: from +one to three mono streams, one for each station camera (see the root [`README.md`](README.md) and +[`CAMERA_SETTINGS.md`](CAMERA_SETTINGS.md#a-profile-for-three-cameras)). With the camera chain running it also: + +1. **Gives each bridged stream a camera role.** A profile's only stream is the head camera, `ego`, unless + `--stream-role STREAM=ROLE` says otherwise (`ego`, `wrist_left`, `wrist_right`; repeatable). A profile with + more than one stream needs `--stream-role` for each of them: the launcher takes no role from a stream's name or + from its place in the profile, because a wrist picture corrected with the head camera's lens still looks like a + picture. A malformed value, an unknown role, a stream that is not bridged, a stream or a role given twice, and + a stream left without a role among several are startup errors, and so is a stream id in the sender config that + holds `=`, which the bridge could not take in a stream's name. With several streams it prints what it took + each for, to be held against the cabling: `stream 'left_wrist': wrist_left, 1280x960, track + sensing-wrist-left`. 2. **Reads the plan** `rectification/plan.json` in the calibration directory: `EGOCAP_CALIBRATION_DIR` as the launcher's own environment has it, resolved once. The backend it starts is given that directory by its whole path, so the page saves the plan where the launcher reads it. No file means nothing is corrected. -3. **Plans each stream whose role is switched on**, before any process is started: it loads the role's intrinsics, - refuses them when they were solved for another camera than the stream's, takes the divisor from the file's - `stream` stamp (1 without one), plans the saved choice for the size the bridge receives, writes the table as - `rectify_.icrmap` into its run directory (the `egocap-start-*` temporary directory that also holds the - logs) and reads it back. -4. **Starts the bridge with the table**: `--stream head=sensing-head:1 --gpu-step head:rectify=`. The +3. **Plans each stream whose role is switched on**, before any process is started and each by itself: it loads + that role's intrinsics, refuses them when they were solved for another camera than the stream's, takes the + divisor from the file's `stream` stamp (1 without one), plans the role's saved choice for the size the bridge + receives from that stream, writes the table as `rectify_.icrmap` into its run directory (the + `egocap-start-*` temporary directory that also holds the logs) and reads it back. No camera's calibration, plan + entry or table is used for another camera. +4. **Starts the bridge with the tables**: `--stream head=sensing-head:1 --gpu-step head:rectify=
`. The stream's own divisor, which the bridge applies after its steps, is the plan's oversample: 1 when the table makes the published picture itself, and `--stream head=sensing-head:3` for an oversample of 3, whose table makes a picture three times the size. An uncorrected stream is started with `--stream head=sensing-head:2` and no - step. The stream descriptor CaptureServer offers declares the published size, so that is the size shown and - recorded. + step. With several streams the one bridge is given a `--stream` for each, and a `--gpu-step` for each that is + corrected, in the profile's order: + `--stream head=sensing-head:1 --gpu-step head:rectify=/rectify_ego.icrmap --stream + left_wrist=sensing-wrist-left:2 --stream right_wrist=sensing-wrist-right:1 --gpu-step + right_wrist:rectify=/rectify_wrist_right.icrmap`. A profile's only stream is published as the track + `sensing-head` whatever its role; among several, each stream takes its role's track (`sensing-head`, + `sensing-wrist-left`, `sensing-wrist-right`). The stream descriptor CaptureServer offers declares each + camera's published size, so that is the size shown and recorded. 5. **Writes `streams_state.json`** into the run directory, always, and names it to the backend in `EGOCAP_STREAMS_STATE`. For each bridged camera, under the name CaptureServer offers it by: the stream, the role, the size the bridge receives (`source_size_wh`), the bridge's divisor (for a corrected stream the @@ -2207,22 +2220,29 @@ fisheye model, while a radial-tangential model of a wide lens turns over inside `wrist_calibration_offsets.json` that is not stamped `"pose_source": "openxr"`, or cannot be read, it prints a `WARNING:` line and starts all the same (see "The calibration directory"). -It prints what becomes of each stream: +It prints what becomes of each stream. The first three lines and the last are those of a profile with several +streams: what each stream was taken for, and what the streams ask of the link together. ```text +stream 'head': ego, 2560x1984, track sensing-head +stream 'left_wrist': wrist_left, 1280x960, track sensing-wrist-left +stream 'right_wrist': wrist_right, 1280x960, track sensing-wrist-right stream 'head': rectified as ego, 2560x1984 to 1920x1440, field of view 113.1 by 97.3 degrees; table /rectify_ego.icrmap stream 'head': rectified as ego, 2560x1984 to 640x480 (corrected at 1920x1440, then shrunk by 3), field of view 113.1 by 97.3 degrees; table /rectify_ego.icrmap WARNING: stream 'head': -WARNING: stream 'head': head_camera_intrinsics.json is not stamped for a camera, so it cannot be checked against the camera in this role +WARNING: stream 'head': head_camera_intrinsics.json is not stamped for a camera, so it cannot be checked against the camera in this role (a profile's only stream; among several this is a refusal) WARNING: head_camera_extrinsics.json was made with another tracking source or another tool: calibrate again stream 'head': published as received; no rectification is switched on for it WARNING: the rectification plan switches on wrist_left, which no bridged stream fills; that camera is not rectified rectification is off (--no-rectify): the video is published as received +sender config : 3 streams at 30 fps, 12 Mbit/s in all ('head' 4, 'left_wrist' 4, 'right_wrist' 4), release egocap-start ``` **A plan that cannot be built stops the start**, before anything is running, with exit status 1. There is no fallback to uncorrected video: starting without the correction would publish, and record, video the operator chose -to have corrected. Each refusal is one line that ends with the ways out: +to have corrected. That holds for each camera of several: a plan that cannot be built for one wrist camera stops +the start for all three, so no run has one camera silently left uncorrected beside two that are corrected, and +the line names the stream and its role. Each refusal is one line that ends with the ways out: ```text error: cannot rectify stream 'head' (role ego, calibration head_camera_intrinsics.json): ; change the plan in the Rectification tool or calibrate the camera again, or pass --no-rectify to publish the video as received @@ -2230,8 +2250,52 @@ error: cannot rectify stream 'head' (role ego, calibration head_camera_intrinsic error: the rectification plan cannot be used: ; save it again from the Rectification tool, or pass --no-rectify to publish the video as received error: cannot rectify stream 'head' (role ego): rectify_ego.icrmap could not be written; make sure can be written and has room for the table, or pass --no-rectify to publish the video as received error: the remap table does not read back as planned for stream 'head': it changed on its way to the disk; start again, or pass --no-rectify to publish the video as received +error: cannot rectify stream 'left_wrist' (role wrist_left, calibration left_wrist_camera_intrinsics.json): left_wrist_camera_intrinsics.json is not stamped for a camera, so it cannot be checked against the camera in this role, and with more than one camera bridged it could be another camera's lens; solve this camera's lens again from the page so that the file names its camera, or bridge this camera alone, or pass --no-rectify to publish the video as received +error: cannot rectify streams 'left_wrist' and 'right_wrist' (roles wrist_left and wrist_right): left_wrist_camera_intrinsics.json and right_wrist_camera_intrinsics.json are the same file, and one lens is not two cameras'; calibrate each camera's own lens from the page, or pass --no-rectify to publish the video as received +``` + +The last two are refusals only where more than one stream is bridged. A lens file that names no camera cannot be +held against the stream it is used for, so among several cameras nothing would notice two streams given each +other's roles, or a file placed under the wrong role's name: each would be corrected with another camera's lens. +For a profile's only stream such a file is applied and warned of, as the `WARNING:` line above says. Two bridged +roles whose calibration files are the same file, byte for byte, are refused whatever the file names. + +**A profile or a set of roles the launcher cannot start with** is refused the same way, before the sender is +deployed and before anything is started: + +```text +error: the sender config has 3 streams and 'left_wrist' and 'right_wrist' have no camera role; pass --stream-role STREAM=ROLE for each, with ROLE one of ego, wrist_left, wrist_right +error: --stream-role 'left_wrist=ego': each stream and each role may be given once +error: --stream-role needs STREAM=ROLE with ROLE one of ego, wrist_left, wrist_right, got 'right_wrist=chest' +error: --stream-role 'wrist_right=wrist_right' names a stream that is not bridged (head, left_wrist, right_wrist) +error: has 4 streams, and the launcher bridges at most 3, one for each station camera role (ego, wrist_left, wrist_right); leave only the station's cameras in it +error: must hold a list of streams, from 1 to 3 mono streams +error: : the launcher supports only a mono stream, got type 'stereo' for streams[1] +error: the sender config names two streams 'head'; give each stream an id of its own +error: the sender config's streams run at different rates ('head' 30, 'left_wrist' 30, 'right_wrist' 60 fps) and the camera bridge takes one rate for all of them; set the same output.fps on every stream, or pass --fps +error: the sender config must set streams[1].output.width and height: with more than one stream each states the size of its own picture; or pass --width and --height when every camera sends the same size +error: the sender config's stream id 'wrist=right' holds "=", which the camera bridge cannot take in a stream's name; rename the stream in the sender config +error: still holds placeholders (sipl.platform_config_json, streams[0].cameras[0].device, ...); replace each with this station's value, which the comment beside it says where to find +error: the sender config gives streams 'head' and 'left_wrist' the same camera (cameras[0].device 0); give each stream the device of its own camera +error: the sender config must give streams[1] exactly one camera: cameras is a list of one entry that names its device, since a mono stream has one camera +error: the sender config's streams[1].id must be a name, not a list or a mapping +error: the sender config's streams[1].output.fps must be a whole number of frames a second, got 29.97 +error: the sender config's streams[2].output.bitrate_mbps must be a whole number of megabits a second, got '4M' +error: the sender config's network.port must be a whole number from 1 to 65535, got 70000 ``` +The last six are what the sender itself would refuse, but only once it is deployed and started; they hold for a +one-stream profile too. The launcher repeats no more of the sender's checks than these: a key the sender does not +know, a codec the backend does not take, the `sipl` section, the config version, a wrong size, pipeline index or +link mask are the sender's to refuse, on the Orin. A sender that has exited by the time the PC side is up is +reported (`error: sender exited with ; see `) in place of the line that says the page is up. + +Streams given each other's roles are not something the launcher can see in the profile. What catches them is the +camera each calibration was solved for: a lens file stamped for `right_wrist` is refused for the stream +`left_wrist` (*... was solved for camera 'right_wrist', and 'left_wrist' fills the role now ...*). A lens file that +names no camera, as another tool's does, cannot be held against anything: among several bridged streams it is +refused (above), so on a station with several cameras solve each lens from the page, which stamps it. + A plan file cannot be used when it cannot be read, is not valid JSON, is not a version 1 plan with a `cameras` object, or holds an entry that does not say whether it is enabled with a real true or false. The Rectification tool says so in a note at its top, lists nothing as saved, and offers Save with nothing changed: one press writes @@ -2595,6 +2659,13 @@ 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. - **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 @@ -2789,11 +2860,17 @@ start its children with. What that leaves unknown: both or neither. - **A step cannot be started by voice.** Ready is pressed; the recording shortcuts are suspended while the tool is open, like in every dialog. -- **The launcher corrects the head stream only.** It bridges the one stream of its sender profile. Correcting a - wrist camera on the PC needs the launcher to bridge that camera's stream as well; `--stream-role`, the plan's - `wrist_left` and `wrist_right` entries and the wrist intrinsics files are in place for it. The camera sender is - not part of this tree: where it corrects a wrist picture itself, that has to be switched off first, because a - picture corrected twice is bent again. +- **The launcher gives no camera its role by itself, and the page's roles are set apart from it.** The launcher + bridges every stream of its sender profile, up to one for each camera role, and corrects each with its own + role's calibration and saved choice; which stream is which camera is said with `--stream-role` at every start of + a profile with several streams. The station's own roles (Settings, Station) are a second statement of it, which + the calibration tools, the checklist and the camera grid go by: give each role there the camera the launcher + bridges as it, by the stream's id. Where the two differ the Rectification tool and the calibration tools say so + in a note and nothing is corrected wrongly, but the calibration tools then work on the station's camera. The + camera sender is not asked to correct anything: where a sender profile has it remap a wrist picture itself, that + has to be taken out first, because a picture corrected twice is bent again. +- **One rate for every bridged camera.** The bridge takes one frame rate for all its streams, so the launcher + refuses a profile whose streams run at different rates. - **Calibration takes are the recorder's takes, exempt from the capture checks.** A take either tool records is never judged by the capture checks: a board waved at one camera and hands held still are what those checks reject or set aside. It is never rejected for its camera's rate, flagged or quarantined; its record says why diff --git a/examples/egocap/CAMERA_SETTINGS.md b/examples/egocap/CAMERA_SETTINGS.md index 4bbde3eaf4..d007e73a2e 100644 --- a/examples/egocap/CAMERA_SETTINGS.md +++ b/examples/egocap/CAMERA_SETTINGS.md @@ -31,12 +31,13 @@ camera on the SIPL backend: HEVC at 30 fps and 4 Mbit/s. The file is specific to that rig. A different SIPL platform or camera changes the `sipl` block (platform file, config name, link masks, tuning directory) and possibly the stream id and size. The Argus backend has no `sipl` block: it selects a sensor mode with `cameras[].mode`, can set `capture.mode` and `alignment`, enforces `output.fps` with a rate -limiter and can set output dimensions. Keep one file per rig and pass the right one with `--sender-config`. The launcher itself supports one stream per -file and requires an explicit `output.fps`. +limiter and can set output dimensions. Keep one file per rig and pass the right one with `--sender-config`. The +launcher takes a profile of one to three mono streams, one for each station camera (see +"A profile for three cameras"), and requires an explicit `output.fps`, the same for every stream. `tools/start_system.py` loads this file by default. Command-line overrides (`--fps`, `--bitrate-mbps`, -`--sender-port`) are applied to the loaded mapping, and the result is what is uploaded. The same -values feed the bridge and the CaptureServer descriptor, so they cannot disagree. +`--sender-port`) are applied to the loaded mapping, the first two to every stream of it, and the result is what is +uploaded. The same values feed the bridge and the CaptureServer descriptor, so they cannot disagree. ### How the file reaches the sender @@ -82,6 +83,81 @@ 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. +## 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 +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 +find*). An override on the command line does not stand in for a placeholder. Copy the file, fill the copy in and +keep it outside the repository. + +```bash +uv run python tools/start_system.py --orin user@orin --deploy-script PATH --livekit-server PATH --bridge PATH \ + --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 needed as well: the launcher's default one asks CaptureServer for cameras of its own, and the +launcher refuses to start without them. +[`recording/egocap/stations/ego_stations.bridged.example.yaml`](recording/egocap/stations/ego_stations.bridged.example.yaml) +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. + +**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 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 | +| One LiveKit room and publisher | Its LiveKit track, its camera role, its calibration, its saved correction and its remap table | + +- **The streams' order is the sender's numbering.** The sender's wire format carries no stream ids: the receiver + knows a stream by its place in the profile's list, and the launcher writes the receiver config in that order. +- **The stream's id is the camera's name** in the receiver, the bridge, the page, the recordings and the + calibration solved for it. Changing an id after a lens was solved makes that lens another camera's, and the + launcher then refuses to correct with it. +- **Roles are said at every start**, with `--stream-role STREAM=ROLE` for each stream. The launcher takes no role + from a stream's id or from its place in the list, and refuses a profile of several streams while one has no + role. See [`CALIBRATION_TOOLS.md`](CALIBRATION_TOOLS.md#what-the-launcher-does-at-start) for every refusal. +- **Each stream states its size.** The sensor size the launcher assumes for a one-stream profile is the head + camera's; among several streams none is assumed, so set `output.width` and `output.height` on each (the SIPL + backend accepts them only when they repeat the sensor's size), or pass `--width` and `--height` when all three + cameras send the same size. +- **The station's roles on the page** (Settings, Station) are set to the same cameras by their stream ids; the + calibration tools, the Devices checklist and the camera grid go by them. +- **The station file** names no CaptureServer camera in `video_sources` when all the video comes from the Orin, + and what it says about a camera says it by the stream's id: `alignment.index_source` is the head stream's id + (with another name no take is time-aligned, and only the backend's log says so), and a + `data_check.guardrails.camera_expected_fps` entry is keyed by a stream's id. The template named above is laid + out so. +- **A profile cut down to one stream is the head camera again.** A profile's only stream is taken for `ego` + whatever its id, so the example with only `left_wrist` left in it would be corrected as the head camera. To run + one wrist camera alone, say so: `--stream-role left_wrist=wrist_left`. +- **Lens files name their camera.** Among several bridged streams the launcher refuses a lens file that names no + camera, and two roles whose lens files are one file; solve each camera's lens from the page, which stamps it. + +**Bitrate.** The shipped one-camera profile's 4 Mbit/s is sized for a wireless link between the Orin and the PC. +Three streams share that link, so what it has to carry is the sum of the three `bitrate_mbps` values. The launcher +adds them up and prints the sum at start (`3 streams at 30 fps, 12 Mbit/s in all ('head' 4, 'left_wrist' 4, +'right_wrist' 4)`), and that is all it does with it: there is no limit in the code, and no warning, however large +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 +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. + +**On the PC's GPU** each stream has a decoder in the receiver, a ring of six decoded pictures there +(`ring_depth`), and in the bridge a thread, a GPU pipeline and an encoder of its own. A corrected stream also holds +its remap table on the GPU: the file is 48 bytes plus 8 bytes for each pixel of the picture the table makes, and +the bridge uploads it with a half-size chroma table once, when the stream starts. Neither the receiver's nor the +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 @@ -131,7 +207,8 @@ shipped profile. ## Receiver keys -The receiver reads its own file once at start; the launcher generates it from the sender profile and the stream size. +The receiver reads its own file once at start; the launcher generates it from the sender profile and each stream's +size, with one entry for each stream in the profile's order. | Key | Default / requirement | Meaning | |---|---|---| @@ -180,3 +257,24 @@ timestamps; it does not configure the Orin or join LiveKit for anyone. | `livekit.streams[].width` | Required valid descriptor value | Advertised image width; match processed output. | | `livekit.streams[].height` | Required valid descriptor value | Advertised image height. | | `livekit.streams[].fps` | Required valid descriptor value | Advertised nominal FPS; the launcher sets it to the sender's effective `output.fps`, and it does not command the sender. | + +## 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. 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 + 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. diff --git a/examples/egocap/LIVEKIT_PREVIEW.md b/examples/egocap/LIVEKIT_PREVIEW.md index 1b9e3a7c65..0e580d1277 100644 --- a/examples/egocap/LIVEKIT_PREVIEW.md +++ b/examples/egocap/LIVEKIT_PREVIEW.md @@ -171,7 +171,11 @@ to the backend's log only, since a server's error body can hold anything. A LiveKit stream is recorded as it is published. When the publisher is the camera bridge started by `tools/start_system.py`, the published picture is corrected (rectified) whenever the station's rectification plan is switched on for that camera: the launcher gives the bridge a remap table, declares the corrected size in the -streams file, and tells the backend what it applied through `EGOCAP_STREAMS_STATE`. The backend then adds +streams file, and tells the backend what it applied through `EGOCAP_STREAMS_STATE`. The launcher bridges every +stream of its sender profile, up to the head camera and the two wrist cameras: the streams file it writes then +lists each camera under its own track (`sensing-head`, `sensing-wrist-left`, `sensing-wrist-right`) at the size +that camera is published at, all in one room under one publisher and at one frame rate, and each camera is +corrected, or not, by itself. The backend then adds `rectification.json`, the corrected camera and the lens it was corrected from to every session, and its calibration tools refuse to calibrate a lens from that video. See [`CALIBRATION_TOOLS.md`](CALIBRATION_TOOLS.md#rectification). @@ -187,6 +191,16 @@ 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. + 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. - The page's reports have been exercised against a scripted room and a scripted video element, and the checklist against scripted reports. No LiveKit server, camera sender or emulator was run by this work, so a pass has not been seen for a real stream. diff --git a/examples/egocap/README.md b/examples/egocap/README.md index 4890a44abd..c4650f4d8f 100644 --- a/examples/egocap/README.md +++ b/examples/egocap/README.md @@ -399,21 +399,55 @@ The sender settings come from the checked-in profile `configs/default-camera-set built from the same effective values. [`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: +the head camera and the two wrist cameras. The launcher then deploys and starts one sender for all of them, writes +one receiver config that lists each stream with its own size and CUDA IPC name, and starts one bridge with a +`--stream` for each, every stream under a LiveKit track of its own. Which stream is which camera is said at every +start, with `--stream-role STREAM=ROLE` for each stream; the launcher takes no role from a stream's name or its +place in the profile, and refuses to start while a stream of several has none: + +```bash +uv run python tools/start_system.py --orin user@orin --deploy-script PATH --livekit-server PATH --bridge PATH \ + --sender-config YOUR_COPY_OF_THE_EXAMPLE --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 part of the command: the default one requests CaptureServer cameras, which the launcher +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 +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. + **Rectification.** When the station's rectification plan (`rectification/plan.json` in the calibration directory, -saved by the page's Rectification tool) switches on the camera role of the bridged stream, the launcher plans that -correction from the role's installed lens calibration before anything is started, writes a remap table into its -run directory and starts the bridge with `--gpu-step :rectify=
`. The video is then published, shown +saved by the page's Rectification tool) switches on the camera role of a bridged stream, the launcher plans that +correction from the role's own installed lens calibration before anything is started, writes a remap table into its +run directory and starts the bridge with `--gpu-step :rectify=
`. Each bridged stream is planned by +itself, from its own role's calibration and saved choice, and has a table of its own. The video is then published, shown and recorded corrected, at the plan's output size, and every session recorded in the run says so: its `rectification.json` records the correction, its intrinsics file for that camera describes the corrected picture, and the lens it was corrected from is kept beside it. Where the plan states an oversample, the table makes a picture that many times the size and the bridge's downscale shrinks it to the output. A plan that cannot be built -stops the start with the reason; there is no fallback to uncorrected video. `--no-rectify` publishes the video as received whatever the plan says, which calibrating a -camera's lens needs. `--stream-role STREAM=ROLE` names the camera role a bridged stream fills (the profile's stream -is `ego` by default). The launcher tells the backend what it applied through a file named in +stops the start with the reason, for whichever camera it is; there is no fallback to uncorrected video, and no run in which one camera of several is left uncorrected without a word. `--no-rectify` publishes the video as received whatever the plan says, which calibrating a +camera's lens needs. `--stream-role STREAM=ROLE` names the camera role a bridged stream fills (a profile's only +stream is `ego` by default). The launcher tells the backend what it applied to each camera through a file named in `EGOCAP_STREAMS_STATE`. See [`CALIBRATION_TOOLS.md`](CALIBRATION_TOOLS.md#what-the-launcher-does-at-start) for the steps and the refusals, and its [Limits](CALIBRATION_TOOLS.md#limits) for what of this has and has not been run. +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. + ### Integration boundary The launcher composes the current capture, receiver and browser stack. Its orchestration may be consolidated with diff --git a/examples/egocap/backend/README.md b/examples/egocap/backend/README.md index 919d980cd5..6fb5536d05 100644 --- a/examples/egocap/backend/README.md +++ b/examples/egocap/backend/README.md @@ -687,7 +687,7 @@ only for a session that states none. What still shows the folder: `location` in | `EGOCAP_CAPTURE_SERVER_URL` | `ws://127.0.0.1:8082` | Where to connect for tracking/camera data. | | `LIVEKIT_API_KEY`, `LIVEKIT_API_SECRET` | unset | The LiveKit server's key pair. The backend signs two viewer tokens with it (subscribe and data messages, no media publishing): viewer tokens for `GET /api/livekit-token`, and the recorder's own token. LiveKit recording will not start without both variables; see [`LIVEKIT_PREVIEW.md`](../LIVEKIT_PREVIEW.md). | | `EGOCAP_CALIBRATION_DIR` | `/calibration` | The calibration directory: the station's calibration files, their history and ledger, the calibration tools' work files and the saved rectification plan. See [`../CALIBRATION_TOOLS.md`](../CALIBRATION_TOOLS.md#the-calibration-directory). | -| `EGOCAP_STREAMS_STATE` | unset (no stream facts) | The file in which the launcher (`tools/start_system.py`) says what each bridged camera is published as in this run: the sizes the camera bridge receives and publishes, its divisor, and the rectification it applies, if any. Read once at startup, since the bridge takes its arguments only when it starts. Unset, as when the backend is started by hand, no camera's video is taken for corrected: sessions get no `rectification.json` and no lens solve is refused for a corrected camera. Set and unusable (the log says why), what the run does to each camera is unknown: no take is recorded and no lens is calibrated until the capture stack is started again. See [`../CALIBRATION_TOOLS.md`](../CALIBRATION_TOOLS.md#what-the-launcher-does-at-start). | +| `EGOCAP_STREAMS_STATE` | unset (no stream facts) | The file in which the launcher (`tools/start_system.py`) says what each bridged camera is published as in this run, one entry for each of up to three cameras under the stream's name: the camera role the launcher took it for, the sizes the camera bridge receives and publishes, its divisor, and the rectification it applies, if any. Each corrected camera's role then gets its own corrected-camera and lens file in every session, and one `rectification.json` lists them all. Read once at startup, since the bridge takes its arguments only when it starts. Unset, as when the backend is started by hand, no camera's video is taken for corrected: sessions get no `rectification.json` and no lens solve is refused for a corrected camera. Set and unusable (the log says why), what the run does to each camera is unknown: no take is recorded and no lens is calibrated until the capture stack is started again. See [`../CALIBRATION_TOOLS.md`](../CALIBRATION_TOOLS.md#what-the-launcher-does-at-start). | | `EGOCAP_TASK_FILES_DIR` | the shipped `data/taskfiles/` | Which task-catalog directory the task-file API serves. | | `EGOCAP_RECORDINGS_ENABLED` | off | Turns on the recordings browser's routes, and with them the Rectification tool's take routes and its corrected copy, which are refused in one sentence while it is off. The launcher does not set it: a backend it starts has it only when the launcher's own environment does. | | `EGOCAP_ALLOWED_ORIGINS` | none (same-origin only) | Comma-separated extra origins allowed to open `WS /api/session` — needed when the frontend is hosted separately or behind a reverse proxy. | @@ -766,6 +766,16 @@ 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. + 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. ## Optional LiveKit support diff --git a/examples/egocap/configs/default-camera-settings.yaml b/examples/egocap/configs/default-camera-settings.yaml index e5cbd27cc7..b5f82f756d 100644 --- a/examples/egocap/configs/default-camera-settings.yaml +++ b/examples/egocap/configs/default-camera-settings.yaml @@ -2,8 +2,9 @@ # SPDX-License-Identifier: Apache-2.0 # Default camera settings for tools/start_system.py: what the Orin's camera sender runs with. -# It is the only profile for now and describes one rig, a single SHW5G head camera on the SIPL backend. Pass another -# file with --sender-config for a different rig. CAMERA_SETTINGS.md describes every key. +# It describes one rig, a single SHW5G head camera on the SIPL backend. Pass another file with --sender-config for a +# different rig; three-camera-settings.example.yaml beside this file shows the structure for a head camera and two +# wrist cameras. CAMERA_SETTINGS.md describes every key. # # The launcher uploads this file to the Orin, where the sender reads it once at start; to change a value, stop the # sender and start it again. The same effective values also set the receiver, the bridge and the stream descriptor diff --git a/examples/egocap/configs/three-camera-settings.example.yaml b/examples/egocap/configs/three-camera-settings.example.yaml new file mode 100644 index 0000000000..e9b21c5982 --- /dev/null +++ b/examples/egocap/configs/three-camera-settings.example.yaml @@ -0,0 +1,83 @@ +# 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: the head +# camera and the two wrist cameras, each a mono HEVC stream of one sender on the SIPL backend. 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 has not been run on hardware. + +version: 1 +capture_backend: sipl + +sipl: + # The SIPL platform file on the Orin that describes all three sensors: their sizes, rates and trigger mode. The + # camera vendor's board support package or the station's camera installation puts it there; + # `deploy_sender.py user@orin discover` lists the candidates. + platform_config_json: PLACEHOLDER_PLATFORM_FILE_ON_THE_ORIN + # The name, inside that file, of the platform that holds the station's three cameras. + platform_config_name: PLACEHOLDER_PLATFORM_NAME + # One unsigned mask for each deserializer, in the platform's order, saying which of its GMSL links are powered: a + # list such as [MASK, MASK]. It follows from which deserializer port each camera is cabled to. + link_masks: PLACEHOLDER_LINK_MASKS + # nito_dir: the image-tuning files on the Orin, when they are not where the sender looks by default. + +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 + cameras: + # The SIPL pipeline index of the head camera in the platform above, which is not the GMSL link number. The + # sender prints each stream's pipeline when it starts and names the available ones when an index is wrong. + - {device: PLACEHOLDER_HEAD_PIPELINE_INDEX, mode: 0} + output: + codec: hevc + # This camera's sensor size, from the platform file: the SIPL backend sends that size and does not scale. + width: PLACEHOLDER_HEAD_SENSOR_WIDTH + height: PLACEHOLDER_HEAD_SENSOR_HEIGHT + # One rate for all three streams, since the bridge runs every stream at one; at most the sensors' own 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 + cameras: + - {device: PLACEHOLDER_LEFT_WRIST_PIPELINE_INDEX, mode: 0} # as for the head camera + output: + codec: hevc + width: PLACEHOLDER_LEFT_WRIST_SENSOR_WIDTH # this camera's own sensor size + height: PLACEHOLDER_LEFT_WRIST_SENSOR_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 + cameras: + - {device: PLACEHOLDER_RIGHT_WRIST_PIPELINE_INDEX, mode: 0} # as for the head camera + output: + codec: hevc + width: PLACEHOLDER_RIGHT_WRIST_SENSOR_WIDTH # this camera's own sensor size + height: PLACEHOLDER_RIGHT_WRIST_SENSOR_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/frontend/src/RectificationDialog.threeCameras.test.tsx b/examples/egocap/frontend/src/RectificationDialog.threeCameras.test.tsx new file mode 100644 index 0000000000..a6d1b927e5 --- /dev/null +++ b/examples/egocap/frontend/src/RectificationDialog.threeCameras.test.tsx @@ -0,0 +1,91 @@ +// SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +/** The rectification tool over a run whose launcher bridges all three cameras: a card for each role, each with its own camera, stream and correction. */ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { cleanup, render, screen, within } from "@testing-library/react"; +import { HEAD_APPLIED_FIXTURE, HEAD_PLAN_FIXTURE, RECTIFICATION_FIXTURE, fakeRectificationBackend } from "./calibrationTestDoubles"; +import type { RectificationCamera, RectificationListing } from "./calibrationTypes"; +import { RectificationDialog } from "./RectificationDialog"; +import { fakeTakeBackend } from "./takeTestDoubles"; + +afterEach(cleanup); + +const [HEAD] = RECTIFICATION_FIXTURE.cameras; +/** The left wrist camera, bridged and corrected to a smaller picture than the head's, with a view of its own. */ +const LEFT: RectificationCamera = { + ...HEAD, + role: "wrist_left", + camera: "left_wrist", + intrinsics_file: "left_wrist_camera_intrinsics.json", + model: "pinhole", + plan: { ...HEAD_PLAN_FIXTURE, output_size_wh: [640, 480], balance: 0.2 }, + applied: { ...HEAD_APPLIED_FIXTURE, output_size_wh: [640, 480], balance: 0.2, field_of_view_deg: [71.5, 56.2] }, + stream: { source_size_wh: [1280, 960], divisor: 1, published_size_wh: [640, 480] }, +}; +/** The right wrist camera, bridged and published as it is received: nothing is saved for it. */ +const RIGHT: RectificationCamera = { + ...HEAD, + role: "wrist_right", + camera: "right_wrist", + intrinsics_file: "right_wrist_camera_intrinsics.json", + plan: null, + applied: null, + stream: { source_size_wh: [1280, 960], divisor: 2, published_size_wh: [640, 480] }, + preview_source: "live", +}; +const THREE_BRIDGED: RectificationListing = { ...RECTIFICATION_FIXTURE, cameras: [{ ...HEAD, camera: "head" }, LEFT, RIGHT] }; + +const card = (name: string) => screen.findByRole("region", { name }); +const factsOf = (region: HTMLElement) => within(within(region).getByRole("list", { name: /: what its correction rests on$/ })).getAllByRole("listitem").map((fact) => fact.textContent); +const renderOver = (listing: RectificationListing) => + render(); + +const SAVED_AND_BUILT = "This is what is saved, built from the calibration installed now."; +const NOT_CORRECTED = "Not corrected in this run: its picture is shown and recorded as it is received."; + +describe("a run that bridges the head camera and both wrist cameras", () => { + it("shows a card for each role under the camera the launcher bridges as it", async () => { + renderOver(THREE_BRIDGED); + for (const [name, camera] of [ + ["Ego (head)", "head"], + ["Left wrist", "left_wrist"], + ["Right wrist", "right_wrist"], + ]) { + expect(within(await card(name)).getByRole("heading", { level: 3 }).textContent).toBe(`${name} — ${camera}`); + } + expect(screen.queryByText("No camera is assigned to this role on the station in use.")).toBeNull(); + }); + + it("says of each camera its own stream and its own correction, and which one is published as received", async () => { + renderOver(THREE_BRIDGED); + expect(factsOf(await card("Ego (head)")).slice(1)).toEqual([ + "The camera bridge receives 3840 × 2160 px and publishes 1920 × 1440 px.", + "Corrected in this run to 1920 × 1440 px (balance 0, field-of-view scale 1): 98.4° across, 81.7° down, 0% of the picture without a source pixel.", + SAVED_AND_BUILT, + ]); + expect(factsOf(await card("Left wrist")).slice(1)).toEqual([ + "The camera bridge receives 1280 × 960 px and publishes 640 × 480 px.", + "Corrected in this run to 640 × 480 px (balance 0.2, field-of-view scale 1): 71.5° across, 56.2° down, 0% of the picture without a source pixel.", + SAVED_AND_BUILT, + ]); + expect(factsOf(await card("Right wrist")).slice(1)).toEqual(["The camera bridge receives 1280 × 960 px and publishes 640 × 480 px, the picture divided by 2.", NOT_CORRECTED]); + }); + + it("names each camera's own calibration file as what its correction rests on", async () => { + renderOver(THREE_BRIDGED); + expect(factsOf(await card("Ego (head)"))[0]).toContain("head_camera_intrinsics.json"); + expect(factsOf(await card("Left wrist"))[0]).toContain("left_wrist_camera_intrinsics.json"); + expect(factsOf(await card("Right wrist"))[0]).toContain("right_wrist_camera_intrinsics.json"); + }); + + it("says a change saved for one wrist waits for a restart on that camera's card and not on the others'", async () => { + const waiting: RectificationCamera = { ...LEFT, restart_needed: true, applied: { ...HEAD_APPLIED_FIXTURE, output_size_wh: [960, 720], plan_matches: false } }; + renderOver({ ...THREE_BRIDGED, cameras: [THREE_BRIDGED.cameras[0], waiting, RIGHT], restart_needed: true }); + const said = /^What is saved for this camera is not what this run applies\./; + expect(factsOf(await card("Left wrist")).some((fact) => said.test(fact ?? ""))).toBe(true); + expect(factsOf(await card("Ego (head)")).some((fact) => said.test(fact ?? ""))).toBe(false); + expect(factsOf(await card("Right wrist")).some((fact) => said.test(fact ?? ""))).toBe(false); + }); +}); diff --git a/examples/egocap/recording/egocap/stations/ego_stations.bridged.example.yaml b/examples/egocap/recording/egocap/stations/ego_stations.bridged.example.yaml new file mode 100644 index 0000000000..b3607c93ac --- /dev/null +++ b/examples/egocap/recording/egocap/stations/ego_stations.bridged.example.yaml @@ -0,0 +1,65 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +# Per-station recording configuration for a station whose cameras all arrive through the camera bridge that +# tools/start_system.py starts, as LiveKit streams, and none through CaptureServer. It is ego_stations.example.yaml +# with two differences, and every remark of that file holds here too: only the first station entry is read, and this +# is a template to copy to a path outside the repository or to a gitignored name before filling it in. +# +# - video_sources is empty. CaptureServer is asked for no camera of its own, so the launcher needs no +# --capture-camera and does not refuse the start for cameras it was not given. +# - Whatever names a camera names a bridged stream by its id in the sender profile. The ids here are those of +# configs/three-camera-settings.example.yaml (head, left_wrist, right_wrist); use your profile's. +# +# Pass it with the launcher's --station-config. This file has not been run on hardware. +stations: + station_01: + recording: + data_dir: ~/egocap_data/recordings + record_fps: 60 + stream_fps: 60 + # Final encoder for every camera: ffmpeg_h264 (default), ffmpeg_h264_nvenc or opencv_mp4v. On an NVIDIA + # machine the NVENC writer takes the same crf/preset keys; availability is reported when a take starts. + # video_encoder: ffmpeg_h264_nvenc + # video_encoder_options: {crf: 12, preset: p4} + verbose: false + video_frame_type: RGBCameraFrame + numeric_frame_type: TrackingFrame + meta: + egocap_station_name: Station 01 + task_description: 'Place the object in the tray.' + operator_name: '' + # Off by default: the operator entry field starts empty and the operator types their own name. + auto_fill_operator_name: false + # Each kept episode is time-aligned in the background on index_source's frames. It must be the id of the + # bridged head stream: with a name no recorded camera has, no take is aligned, and only the backend's log says + # so. Alignment needs every recorded camera to carry a sensor capture time, which the launcher's bridge gives + # each stream once time sync has settled. + alignment: + enabled: true + index_source: head + # Estimated device-to-host delay in seconds for each tracking source; it is taken off that source's host + # poll time when recorded, and a source not listed is not time-aligned. Measure it on the station and + # uncomment; no value is assumed. + # tracking_latency_s: {pico_controller: , manus_glove: } + # This station's changes to the capture-QC thresholds, as in ego_stations.example.yaml. A camera is named by its + # stream id, and a name no recorded camera has blocks recording until it is fixed. + # data_check: + # guardrails: + # camera_expected_fps: {head: } + # No camera is requested from CaptureServer: every camera of this station is a stream of the sender profile. + video_sources: [] + numeric_sources: + - type: pico + name: pico_controller + record_fps: 60 + stream_fps: 60 + frame_type: PicoTrackingFrame + latency: 0.05 + - type: manus + name: manus_glove + record_fps: 60 + stream_fps: 60 + frame_type: ManusFrame + latency: 0.05 diff --git a/examples/egocap/tests/backend/test_three_camera_run.py b/examples/egocap/tests/backend/test_three_camera_run.py new file mode 100644 index 0000000000..2f46df3d28 --- /dev/null +++ b/examples/egocap/tests/backend/test_three_camera_run.py @@ -0,0 +1,383 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""A run the launcher started for three cameras, as the backend takes it. The run is made with the launcher's +own planning and its own writer of the streams state, and read with the backend's reader: the files every +session of the run carries, what the recorder is told to copy, and what the Rectification tool and the +calibration tools say of each camera.""" + +from __future__ import annotations + +import hashlib +import json +import logging +import sys +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from egocap.calibration.files import ROLE_INTRINSICS, ROLE_LENS_INTRINSICS, intrinsics_from_record, load_intrinsics +from egocap.calibration.rectification_files import STREAMS_STATE_ENV, write_plan, write_streams_state +from egocap.calibration.rectify import OutputGeometry, plan_rectification +from egocap_web import app as app_module +from egocap_web.auto_align import AutoAligner +from egocap_web.calibration_common import ROLE_PHRASES +from egocap_web.rectification_service import RECTIFIED_NOW, ROLE_DISAGREES_NOTE, standing +from egocap_web.station_config import load_station_config +from egocap_web.streams_state import ( + LENS_CHANGED, + SESSION_RECORD_NAME, + SessionFiles, + streams_state_from_env, + streams_unknown, +) +from tests.backend.test_calibration_service import CAMERA_TAKE, World, refused +from tests.recording.unit.calibration_rectify_helpers import camera_matrix, fisheye_record, good_record + +EGOCAP = Path(__file__).resolve().parents[2] +# tools/ is a plain scripts directory, not a package. +sys.path.insert(0, str(EGOCAP / "tools")) +import start_system as launcher # noqa: E402 + +#: Each bridged camera: the name its stream and its video go by, the size it sends, and its role. +CAMERAS = ( + ("head", (640, 496), "ego"), + ("left_wrist", (640, 480), "wrist_left"), + ("right_wrist", (640, 496), "wrist_right"), +) +NAMES = [name for name, _size, _role in CAMERAS] +ROLE_OF = {name: role for name, _size, role in CAMERAS} +#: The station's roles as an operator sets them to the cameras the launcher bridges. +ASSIGNED = [(role, name) for name, _size, role in CAMERAS] +PLAN = { + "ego": {"enabled": True, "output_size_wh": [480, 360], "balance": 0.0, "fov_scale": 1.0}, + "wrist_left": {"enabled": True, "output_size_wh": [320, 240], "balance": 0.0, "fov_scale": 1.0}, + "wrist_right": {"enabled": True, "output_size_wh": [400, 300], "balance": 0.1, "fov_scale": 1.0}, +} +PLAN = {role: {**entry, "allow_border": role == "wrist_right", "K": None} for role, entry in PLAN.items()} +LOGGER = "isaaccapture.egocap.streams_state" + + +def lenses() -> dict[str, dict]: + """A lens of its own for each role, stamped for the camera that fills it.""" + return { + "ego": fisheye_record(camera="head"), + "wrist_left": good_record(camera="left_wrist"), + "wrist_right": fisheye_record(camera="right_wrist", K=camera_matrix(300.0, 330.0, 250.0).tolist()), + } + + +def launch(tmp_path: Path, plan=PLAN, no_rectify: bool = False) -> SimpleNamespace: + """Start a three-camera run as the launcher does up to the point it starts anything: plan each stream from + its role's lens, write the streams state, and hand the backend the file's name.""" + calibration, run = tmp_path / "calibration", tmp_path / "run" + calibration.mkdir(parents=True, exist_ok=True) + run.mkdir(exist_ok=True) + for role, record in lenses().items(): + (calibration / ROLE_INTRINSICS[role]).write_text(json.dumps(record, indent=2)) + write_plan(calibration, plan) + streams = [ + launcher.BridgedStream(name, launcher.ROLE_TRACKS[role], size, role) for name, size, role in CAMERAS + ] + planned = {} if no_rectify else launcher.plan_rectifications(streams, calibration, run) + path = run / launcher.STREAMS_STATE_FILE + write_streams_state(path, launcher.published_cameras(streams, planned), no_rectify=no_rectify) + state = streams_state_from_env({STREAMS_STATE_ENV: str(path)}) + return SimpleNamespace(state=state, calibration=calibration, run=run) + + +def planned(calibration: Path, name: str): + size = next(size for camera, size, _role in CAMERAS if camera == name) + role = ROLE_OF[name] + return plan_rectification( + load_intrinsics(calibration / ROLE_INTRINSICS[role]), size, OutputGeometry.from_record(PLAN[role]) + ) + + +def test_the_backend_reads_the_launchers_three_camera_report_as_three_corrected_cameras_each_in_its_role( + tmp_path, caplog +): + with caplog.at_level(logging.INFO, logger=LOGGER): + run = launch(tmp_path) + assert not streams_unknown(run.state) and sorted(run.state.cameras) == NAMES + assert "Streams state: 3 camera stream(s), corrected: head, left_wrist, right_wrist" in caplog.text + for name, size, role in CAMERAS: + stream = run.state.camera(name) + assert (stream.stream, stream.role, stream.source_size_wh, stream.divisor) == (name, role, size, 1) + assert stream.published_size_wh == tuple(PLAN[role]["output_size_wh"]) + assert run.state.rectified(name) and run.state.stamp(name) is None + corrected = run.state.corrected_camera(name) + # Each camera's corrected matrix is its own plan's: no camera is described by another's correction. + assert corrected.K.tolist() == planned(run.calibration, name).K.tolist() + assert corrected.image_size_wh == tuple(PLAN[role]["output_size_wh"]) and not corrected.dist.any() + + +def test_every_session_of_the_run_carries_one_record_and_for_each_role_the_corrected_camera_and_its_own_lens( + tmp_path, +): + run = launch(tmp_path) + files = SessionFiles(run.state, lambda: run.calibration) + names = [file.name for file in files.files] + assert names[0] == SESSION_RECORD_NAME and len(names) == 7 and len(set(names)) == 7 + assert sorted(names[1:]) == sorted([*ROLE_INTRINSICS.values(), *ROLE_LENS_INTRINSICS.values()]) + assert files.ensure() is None and files.problem is None + by_name = {file.name: file.source for file in files.files} + assert all(source.parent == run.run and source.is_file() for source in by_name.values()) + record = json.loads(by_name[SESSION_RECORD_NAME].read_text()) + assert record == run.state.session_record() and sorted(record["cameras"]) == NAMES + for name, _size, role in CAMERAS: + # Under the role's usual name, the camera the recorded video is a picture of. + described = json.loads(by_name[ROLE_INTRINSICS[role]].read_text()) + assert "table" not in described and "table" in record["cameras"][name] + corrected = intrinsics_from_record(described, ROLE_INTRINSICS[role]) + assert corrected.image_size_wh == tuple(PLAN[role]["output_size_wh"]) and not corrected.dist.any() + assert corrected.K.tolist() == planned(run.calibration, name).K.tolist() + assert described["calibration"]["file"] == ROLE_INTRINSICS[role] + # Under its lens name, that role's own lens, byte for byte: the one its correction was built from. + lens = (run.calibration / ROLE_INTRINSICS[role]).read_bytes() + assert by_name[ROLE_LENS_INTRINSICS[role]].read_bytes() == lens + assert described["calibration"]["sha256"] == hashlib.sha256(lens).hexdigest() + carried = {by_name[name].read_bytes() for name in ROLE_LENS_INTRINSICS.values()} + assert len(carried) == 3 + + +@pytest.mark.parametrize("role", ["wrist_left", "wrist_right"]) +def test_a_wrist_lens_replaced_during_the_run_holds_the_take_and_names_that_wrists_file(tmp_path, role): + run = launch(tmp_path) + (run.calibration / ROLE_INTRINSICS[role]).write_text(json.dumps(fisheye_record(camera="another"))) + files = SessionFiles(run.state, lambda: run.calibration) + assert files.ensure() == LENS_CHANGED.format(name=ROLE_INTRINSICS[role]) + # Still named, so the recorder requires it and opens no session without it. + assert ROLE_LENS_INTRINSICS[role] in [file.name for file in files.files] + assert not (run.run / f"session_{ROLE_LENS_INTRINSICS[role]}").exists() + + +def test_the_recorder_is_told_to_copy_all_three_roles_files_into_every_session_and_to_require_them( + tmp_path, monkeypatch +): + run = launch(tmp_path) + monkeypatch.setattr(app_module, "calibration_dir", lambda: run.calibration) + assets = app_module._session_calibration_assets(SessionFiles(run.state, lambda: run.calibration)) + names = [asset.name for asset in assets] + # The station's files keep their names and order; the run's record and the three lenses follow them. + assert names[: len(app_module._STATION_CALIBRATION_FILES)] == list(app_module._STATION_CALIBRATION_FILES) + assert names[len(app_module._STATION_CALIBRATION_FILES)] == SESSION_RECORD_NAME + assert sorted(names[len(app_module._STATION_CALIBRATION_FILES) + 1 :]) == sorted(ROLE_LENS_INTRINSICS.values()) + by_name = {asset.name: asset for asset in assets} + for role in ROLE_INTRINSICS: + # Each role's own file is now the run's: the corrected camera, not the station's lens. + corrected = by_name[ROLE_INTRINSICS[role]] + assert corrected.required and corrected.path == run.run / f"session_{ROLE_INTRINSICS[role]}" + assert by_name[ROLE_LENS_INTRINSICS[role]].required and by_name[ROLE_LENS_INTRINSICS[role]].path.is_file() + assert by_name[SESSION_RECORD_NAME].required + others = set(names) - {SESSION_RECORD_NAME, *ROLE_INTRINSICS.values(), *ROLE_LENS_INTRINSICS.values()} + assert others and all(not by_name[name].required for name in others) + + +def test_one_corrected_camera_beside_two_published_as_received_gives_the_sessions_that_cameras_files_only( + tmp_path, monkeypatch +): + only_the_right_wrist = {**PLAN, "ego": {**PLAN["ego"], "enabled": False}, "wrist_left": None} + run = launch(tmp_path, {role: entry for role, entry in only_the_right_wrist.items() if entry is not None}) + assert [run.state.rectified(name) for name in NAMES] == [False, False, True] + # A camera published as received says by how much the bridge shrank it, for a lens solved from its picture. + assert run.state.stamp("head") == {"divisor": 2, "source_size_wh": [640, 496]} + assert run.state.stamp("left_wrist") == {"divisor": 2, "source_size_wh": [640, 480]} + files = SessionFiles(run.state, lambda: run.calibration) + assert [file.name for file in files.files] == [ + SESSION_RECORD_NAME, + ROLE_INTRINSICS["wrist_right"], + ROLE_LENS_INTRINSICS["wrist_right"], + ] + assert files.ensure() is None + assert sorted(run.state.session_record()["cameras"]) == ["right_wrist"] + monkeypatch.setattr(app_module, "calibration_dir", lambda: run.calibration) + by_name = {asset.name: asset for asset in app_module._session_calibration_assets(files)} + # The other two roles' files stay the station's lens calibrations, which describe their recorded video. + for role in ("ego", "wrist_left"): + assert by_name[ROLE_INTRINSICS[role]].path == run.calibration / ROLE_INTRINSICS[role] + assert not by_name[ROLE_INTRINSICS[role]].required and ROLE_LENS_INTRINSICS[role] not in by_name + + +def test_a_run_started_without_rectification_reports_three_cameras_and_gives_its_sessions_no_file(tmp_path): + run = launch(tmp_path, no_rectify=True) + assert run.state.no_rectify and sorted(run.state.cameras) == NAMES + assert not any(run.state.rectified(name) for name in NAMES) + assert SessionFiles(run.state, lambda: run.calibration).files == () + assert run.state.session_record() is None + + +# --- what the Rectification tool says of each camera ----------------------------------------------------------- + + +def test_the_rectification_tool_lists_each_role_with_its_own_camera_stream_and_applied_correction(tmp_path): + run = launch(tmp_path) + listing = standing(run.calibration, ASSIGNED, run.state) + assert [row["role"] for row in listing["cameras"]] == list(ROLE_INTRINSICS) + assert listing["notes"] == [] and listing["streams_reported"] and not listing["restart_needed"] + for row, (name, size, role) in zip(listing["cameras"], CAMERAS, strict=True): + assert (row["camera"], row["intrinsics_file"], row["installed"]) == (name, ROLE_INTRINSICS[role], True) + assert row["problems"] == [] and row["plan_problem"] is None and row["restart_needed"] is False + assert row["stream"] == { + "source_size_wh": list(size), + "divisor": 1, + "published_size_wh": PLAN[role]["output_size_wh"], + } + applied = row["applied"] + assert applied["plan_matches"] and applied["calibration_matches"] + assert applied["output_size_wh"] == PLAN[role]["output_size_wh"] + assert applied["balance"] == PLAN[role]["balance"] + assert [row["model"] for row in listing["cameras"]] == ["fisheye", "pinhole", "fisheye"] + + +def test_the_tool_says_which_camera_is_corrected_and_which_is_published_as_received(tmp_path): + run = launch(tmp_path, {**PLAN, "wrist_left": {**PLAN["wrist_left"], "enabled": False}}) + rows = {row["role"]: row for row in standing(run.calibration, ASSIGNED, run.state)["cameras"]} + assert rows["ego"]["applied"] is not None and rows["wrist_right"]["applied"] is not None + # Bridged and not corrected: its stream is known, and nothing is applied to it. + assert rows["wrist_left"]["applied"] is None + assert rows["wrist_left"]["stream"] == { + "source_size_wh": [640, 480], + "divisor": 2, + "published_size_wh": [320, 240], + } + + +def test_a_choice_saved_for_one_camera_after_the_start_waits_for_a_restart_on_that_camera_alone(tmp_path): + run = launch(tmp_path) + write_plan(run.calibration, {**PLAN, "wrist_left": {**PLAN["wrist_left"], "output_size_wh": [400, 300]}}) + listing = standing(run.calibration, ASSIGNED, run.state) + assert [row["restart_needed"] for row in listing["cameras"]] == [False, True, False] + assert listing["restart_needed"] is True + + +def test_the_tool_shows_the_launchers_camera_for_each_role_and_says_where_the_stations_roles_differ(tmp_path): + run = launch(tmp_path) + # A station whose roles were never given to the bridged cameras. + unassigned = [(role, None) for role in ROLE_INTRINSICS] + listing = standing(run.calibration, unassigned, run.state) + assert [row["camera"] for row in listing["cameras"]] == NAMES + assert listing["notes"] == [ + ROLE_DISAGREES_NOTE.format(bridged=repr(name), phrase=ROLE_PHRASES[role], assigned="no camera") + for name, _size, role in CAMERAS + ] + # A station whose wrists are given to each other's cameras: the launcher's camera is shown, and it is said. + crossed = [("ego", "head"), ("wrist_left", "right_wrist"), ("wrist_right", "left_wrist")] + listing = standing(run.calibration, crossed, run.state) + assert [row["camera"] for row in listing["cameras"]] == NAMES + assert listing["notes"] == [ + ROLE_DISAGREES_NOTE.format( + bridged="'left_wrist'", phrase="left wrist camera", assigned="camera 'right_wrist'" + ), + ROLE_DISAGREES_NOTE.format( + bridged="'right_wrist'", phrase="right wrist camera", assigned="camera 'left_wrist'" + ), + ] + + +# --- what the calibration tools say of each camera ------------------------------------------------------------- + + +@pytest.fixture +async def world(tmp_path): + """A station whose three roles are given to the three cameras a run bridges and corrects.""" + run = launch(tmp_path / "launched") + made = World(tmp_path, streams=run.state) + made.roles.update({role: name for role, name in ASSIGNED}) + made.calibration = run.calibration + made.offered = frozenset(NAMES) + made.over_livekit.update(NAMES) + made.sizes = {name: tuple(PLAN[role]["output_size_wh"]) for name, _size, role in CAMERAS} + yield made + await made.service.aclose() + + +async def test_the_calibration_tools_know_each_of_the_three_cameras_as_corrected_and_refuse_its_lens_take(world): + overview = await world.service.overview(None) + assert [(camera["role"], camera["camera"]) for camera in overview["cameras"]] == ASSIGNED + assert [camera["rectified"] for camera in overview["cameras"]] == [True, True, True] + assert [camera["video_room"] for camera in overview["cameras"]] == [True, True, True] + assert [camera["rectification_waits"] for camera in overview["cameras"]] == [False, False, False] + # A corrected picture has the size its correction gave it: nothing is said of the lens file's size. + assert all(camera["picture_notes"] == {"lens": None, "position": None} for camera in overview["cameras"]) + assert overview["rectification"] == {"restart_needed": False, "streams_reported": True, "notes": []} + for role in ROLE_INTRINSICS: + take = {**CAMERA_TAKE, "role": role, "mode": "intrinsic"} + await refused(world.service.start_recording(take), 409, RECTIFIED_NOW) + + +async def test_a_camera_published_as_received_beside_corrected_ones_is_the_only_one_whose_lens_is_calibrated( + tmp_path, +): + run = launch(tmp_path / "launched", {**PLAN, "wrist_left": {**PLAN["wrist_left"], "enabled": False}}) + world = World(tmp_path, streams=run.state) + world.roles.update({role: name for role, name in ASSIGNED}) + world.calibration = run.calibration + world.offered = frozenset(NAMES) + try: + overview = await world.service.overview(None) + assert [camera["rectified"] for camera in overview["cameras"]] == [True, False, True] + await refused( + world.service.start_recording({**CAMERA_TAKE, "role": "wrist_right", "mode": "intrinsic"}), + 409, + RECTIFIED_NOW, + ) + started = await world.service.start_recording({**CAMERA_TAKE, "role": "wrist_left", "mode": "intrinsic"}) + assert started["phase"] == "recording" + await world.service.cancel_recording() + finally: + await world.service.aclose() + + +async def test_a_station_that_gives_its_roles_to_no_bridged_camera_is_told_so_by_the_calibration_tools(tmp_path): + run = launch(tmp_path / "launched") + world = World(tmp_path, streams=run.state) + world.roles.update({role: None for role in ROLE_INTRINSICS}) + world.calibration = run.calibration + try: + overview = await world.service.overview(None) + # The tools go by the station's roles; what the launcher bridges under each is said beside them. + assert [camera["camera"] for camera in overview["cameras"]] == [None, None, None] + assert overview["rectification"]["notes"] == [ + ROLE_DISAGREES_NOTE.format(bridged=repr(name), phrase=ROLE_PHRASES[role], assigned="no camera") + for name, _size, role in CAMERAS + ] + finally: + await world.service.aclose() + + +# --- time alignment -------------------------------------------------------------------------------------------- + + +def test_takes_of_three_bridged_cameras_are_aligned_when_the_index_source_is_the_head_streams_name( + tmp_path, caplog +): + recorded = frozenset(NAMES) + with caplog.at_level(logging.WARNING, logger="isaaccapture.egocap_web.auto_align"): + aligner = AutoAligner(tmp_path, "head") + aligner.note_video_sources(recorded, recorded) + assert aligner._session_alignable and caplog.text == "" + # The station file's index source must be the head stream's own name: another camera's name, as the + # shipped example station has, switches alignment off for the session and says so in the log. + misnamed = AutoAligner(tmp_path, "head_human_camera") + misnamed.note_video_sources(recorded, recorded) + assert not misnamed._session_alignable + assert "automatic time alignment is off: index source 'head_human_camera'" in caplog.text + # One of the three without a sensor capture time leaves every take of the session unaligned. + aligner.note_video_sources(recorded, frozenset({"head", "left_wrist"})) + assert not aligner._session_alignable + + +# --- the station file ------------------------------------------------------------------------------------------ + + +def test_the_example_station_for_bridged_cameras_loads_with_no_capture_server_camera_and_the_head_as_index(): + resolved = load_station_config( + EGOCAP / "recording" / "egocap" / "stations" / "ego_stations.bridged.example.yaml" + ) + assert resolved.cameras == () and resolved.alignment_index == "head" + assert resolved.data_check is None and resolved.operator_name in (None, "") + # The index source is a camera the launcher's three-camera example bridges, by its stream id. + assert resolved.alignment_index in NAMES diff --git a/examples/egocap/tests/tools/test_start_system.py b/examples/egocap/tests/tools/test_start_system.py index bdf9df9064..769d8406a9 100644 --- a/examples/egocap/tests/tools/test_start_system.py +++ b/examples/egocap/tests/tools/test_start_system.py @@ -714,9 +714,12 @@ def test_a_child_that_dies_during_time_sync_stops_startup(recorded_main, monkeyp def start(self, name, command, *args, **kwargs): managed = real_start(self, name, command, *args, **kwargs) - if name == "bridge": - managed.process.poll = lambda: 3 - managed.process.returncode = 3 + if name == "timesync-follower": + # The bridge dies once time sync is under way. One that had exited before the page is announced is + # said in place of the announcement. + bridge = next(child for child in self.children if child.name == "bridge") + bridge.process.poll = lambda: 3 + bridge.process.returncode = 3 return managed monkeypatch.setattr(ss.Stack, "start", start) diff --git a/examples/egocap/tests/tools/test_start_system_three_cameras.py b/examples/egocap/tests/tools/test_start_system_three_cameras.py new file mode 100644 index 0000000000..245059a2ff --- /dev/null +++ b/examples/egocap/tests/tools/test_start_system_three_cameras.py @@ -0,0 +1,1510 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import re +import sys +import time +from pathlib import Path + +import numpy as np +import pytest +import test_start_system as one_camera +import yaml + +from egocap.calibration.files import ( + HEAD_INTRINSICS, + LEFT_WRIST_INTRINSICS, + RIGHT_WRIST_INTRINSICS, + ROLE_INTRINSICS, + load_intrinsics, +) +from egocap.calibration.rectification_files import read_streams_state +from egocap.calibration.rectify import OutputGeometry, RemapTableError, plan_rectification + +# The one-camera tests' fakes, fixtures and helpers are these runs' too: the same launcher, more streams. +ss = one_camera.ss +rectify_helpers = one_camera.rectify_helpers +recorded_main = one_camera.recorded_main +station_calibration = one_camera.station_calibration +_entry, _save_plan, _child, _state = one_camera._entry, one_camera._save_plan, one_camera._child, one_camera._state + +CAMERA_STREAMER = ss.REPO_ROOT / "examples" / "camera_streamer" +EXAMPLE_PROFILE = ss.EGOCAP_ROOT / "configs" / "three-camera-settings.example.yaml" + +#: Each stream of the three-camera profile: its id, the picture size it sends, and the role the run gives it. +STREAMS = ( + ("head", (640, 496), "ego"), + ("left_wrist", (640, 480), "wrist_left"), + ("right_wrist", (640, 496), "wrist_right"), +) +ROLE_ARGS = [arg for name, _size, role in STREAMS for arg in ("--stream-role", f"{name}={role}")] +TRACKS = {"head": "sensing-head", "left_wrist": "sensing-wrist-left", "right_wrist": "sensing-wrist-right"} +#: A different view saved for each role, so a table made from another role's entry would not pass for its own. +PLAN = { + "ego": _entry(), + "wrist_left": _entry(output_size_wh=[320, 240]), + "wrist_right": _entry(output_size_wh=[400, 300], balance=0.1, allow_border=True), +} +ALL_ROLES_HINT = "pass --stream-role STREAM=ROLE for each, with ROLE one of ego, wrist_left, wrist_right" + + +def _stream(name: str, device: int, size, **output) -> dict: + described = {"codec": "hevc", "fps": 30, "bitrate_mbps": 4, "width": size[0], "height": size[1], **output} + return {"id": name, "type": "mono", "cameras": [{"device": device, "mode": 0}], "output": described} + + +def _profile(tmp_path: Path, mutate=None) -> Path: + config = yaml.safe_load(ss.DEFAULT_SENDER_CONFIG.read_text()) + config["streams"] = [_stream(name, device, size) for device, (name, size, _role) in enumerate(STREAMS)] + if mutate is not None: + mutate(config) + path = tmp_path / "three-cameras.yaml" + path.write_text(yaml.safe_dump(config, sort_keys=False)) + return path + + +def _lenses() -> dict[str, dict]: + """A lens of its own for each role, each stamped for the stream that fills the role: two fisheyes of + different focal lengths and a radial-tangential lens of another picture size.""" + longer = rectify_helpers.camera_matrix(300.0, 330.0, 250.0) + return { + "ego": rectify_helpers.fisheye_record(camera="head"), + "wrist_left": rectify_helpers.good_record(camera="left_wrist"), + "wrist_right": rectify_helpers.fisheye_record(camera="right_wrist", K=longer.tolist()), + } + + +def _calibrate_all(directory: Path, **changes) -> None: + directory.mkdir(parents=True, exist_ok=True) + for role, record in {**_lenses(), **changes}.items(): + if record is not None: + (directory / ROLE_INTRINSICS[role]).write_text(json.dumps(record)) + + +def _argv(profile: Path, *more: str, roles=ROLE_ARGS) -> list[str]: + return [*one_camera.ORIN_ARGV, *one_camera.CAMERA_ARGS, "--sender-config", str(profile), *roles, *more] + + +def _refused(recorded, capsys, argv) -> str: + """Run a start that must be stopped; returns what it said, having deployed and started nothing.""" + assert ss.main(argv) == 1 + assert recorded.children == [] and recorded.deploys == [] + assert list(recorded.workdir.glob("*.icrmap")) == [] + return capsys.readouterr().err + + +def _geometry(role: str) -> OutputGeometry: + return OutputGeometry.from_record(PLAN[role]) + + +def _planned(directory: Path, role: str, size): + return plan_rectification(load_intrinsics(directory / ROLE_INTRINSICS[role]), size, _geometry(role)) + + +# --- the whole chain for three cameras ------------------------------------------------------------------------- + + +def test_three_streams_start_one_sender_one_receiver_and_one_bridge_in_the_order_of_one_stream( + recorded_main, station_calibration, tmp_path: Path +): + _calibrate_all(station_calibration) + _save_plan(station_calibration, PLAN) + assert ss.main(_argv(_profile(tmp_path))) == 0 + workdir = recorded_main.workdir + names = [child.name for child in recorded_main.children] + assert names == ["sender", "livekit", "capture-server", "backend", "receiver", "bridge", "timesync-follower"] + # One deployment and one sender process for all three cameras: the sender takes them from one file. + to_the_orin = [command[3:] for command in recorded_main.deploys if command[1] == "x"] + assert to_the_orin == [ + ["stop"], + ["stop-daemon"], + ["deploy", "--with-sipl", "--name", "egocap-start"], + ["stop"], + ] + assert _child(recorded_main, "sender").command == [ + sys.executable, + "x", + "user@192.0.2.10", + "run", + "--name", + "egocap-start", + "--config", + str(workdir / "sender.yaml"), + "--seconds", + "3600", + ] + assert _child(recorded_main, "receiver").command[-2:] == ["--config", str(workdir / "receiver.yaml")] + + +def test_the_bridge_is_given_a_stream_and_a_rectify_step_for_each_camera_with_its_own_table( + recorded_main, station_calibration, tmp_path: Path +): + _calibrate_all(station_calibration) + _save_plan(station_calibration, PLAN) + assert ss.main(_argv(_profile(tmp_path))) == 0 + workdir = recorded_main.workdir + assert _child(recorded_main, "bridge").command == [ + "b", + "--livekit-url", + "ws://127.0.0.1:7880", + "--livekit-token-file", + str(workdir / "publisher-token.txt"), + "--socket", + str(workdir / "camera_receiver.sock"), + "--stream", + "head=sensing-head:1", + "--gpu-step", + f"head:rectify={workdir / 'rectify_ego.icrmap'}", + "--stream", + "left_wrist=sensing-wrist-left:1", + "--gpu-step", + f"left_wrist:rectify={workdir / 'rectify_wrist_left.icrmap'}", + "--stream", + "right_wrist=sensing-wrist-right:1", + "--gpu-step", + f"right_wrist:rectify={workdir / 'rectify_wrist_right.icrmap'}", + "--fps", + "30", + "--timestamp-basis", + "capture_monotonic_us", + "--chrony-sender", + "192.0.2.10", + "--chrony-sender-refid", + "C000020A", + "--chrony-pc-port", + "12301", + "--source-full-range", + ] + + +def test_each_cameras_table_is_the_plan_of_its_own_calibration_its_own_size_and_its_own_saved_view( + recorded_main, station_calibration, tmp_path: Path +): + _calibrate_all(station_calibration) + _save_plan(station_calibration, PLAN) + assert ss.main(_argv(_profile(tmp_path))) == 0 + plans = {role: _planned(station_calibration, role, size) for _name, size, role in STREAMS} + for _name, size, role in STREAMS: + table = recorded_main.tables[f"rectify_{role}.icrmap"] + assert (table.source_size_wh, table.output_size_wh) == (size, tuple(PLAN[role]["output_size_wh"])) + assert np.array_equal(table.map_x, plans[role].map_x) and np.array_equal(table.map_y, plans[role].map_y) + # No two cameras' tables are the same remap: one camera's lens never corrects another's picture. + assert len({plan.plan_id for plan in plans.values()}) == 3 + assert not np.array_equal(plans["ego"].map_x[:300, :400], plans["wrist_right"].map_x[:300, :400]) + assert list(recorded_main.workdir.glob("*.icrmap")) == [] + + +def test_the_receiver_config_lists_every_stream_in_the_senders_order_with_its_own_size_and_ipc_name( + recorded_main, station_calibration, tmp_path: Path +): + _calibrate_all(station_calibration) + _save_plan(station_calibration, PLAN) + assert ss.main(_argv(_profile(tmp_path))) == 0 + workdir = recorded_main.workdir + assert yaml.safe_load((workdir / "receiver.yaml").read_text()) == { + "version": 1, + "receiver": { + "host": "192.0.2.10", + "port": 5000, + "gpu_id": 0, + "max_record_bytes": 268435456, + "stats_log_interval_s": 2, + }, + "ipc": { + "socket_path": str(workdir / "camera_receiver.sock"), + "owner_name": "egocap_start_system", + "queue_size": 1024, + }, + "streams": [ + { + "index": index, + "name": name, + "type": "mono", + "width": size[0], + "height": size[1], + "output_format": "nv12", + "ring_depth": 6, + "ipc": {"mono": name}, + } + for index, (name, size, _role) in enumerate(STREAMS) + ], + } + + +def test_the_descriptor_declares_each_camera_under_its_own_track_at_the_size_it_is_published_at( + recorded_main, station_calibration, tmp_path: Path +): + _calibrate_all(station_calibration) + _save_plan(station_calibration, PLAN) + assert ss.main(_argv(_profile(tmp_path))) == 0 + assert yaml.safe_load((recorded_main.workdir / "streams.yaml").read_text()) == { + "livekit": { + "url": "ws://127.0.0.1:7880", + "room": "egocap-room", + "publisher": "egocap-bridge", + "timestamp_basis": "capture_monotonic_us", + "streams": [ + {"name": "head", "track": "sensing-head", "width": 480, "height": 360, "fps": 30}, + {"name": "left_wrist", "track": "sensing-wrist-left", "width": 320, "height": 240, "fps": 30}, + {"name": "right_wrist", "track": "sensing-wrist-right", "width": 400, "height": 300, "fps": 30}, + ], + } + } + capture = _child(recorded_main, "capture-server").command + assert capture[capture.index("--livekit-streams") + 1] == str(recorded_main.workdir / "streams.yaml") + + +def test_the_sender_is_uploaded_the_profile_with_all_three_streams_and_overrides_reach_every_stream( + recorded_main, tmp_path: Path +): + profile = _profile(tmp_path) + assert ss.main(_argv(profile, "--fps", "15", "--bitrate-mbps", "3", "--sender-port", "5100")) == 0 + uploaded = yaml.safe_load((recorded_main.workdir / "sender.yaml").read_text()) + expected = yaml.safe_load(profile.read_text()) + expected["network"]["port"] = 5100 + for stream in expected["streams"]: + stream["output"].update(fps=15, bitrate_mbps=3) + assert uploaded == expected + assert [stream["id"] for stream in uploaded["streams"]] == ["head", "left_wrist", "right_wrist"] + bridge = _child(recorded_main, "bridge").command + assert bridge[bridge.index("--fps") + 1] == "15" + declared = yaml.safe_load((recorded_main.workdir / "streams.yaml").read_text())["livekit"]["streams"] + assert [stream["fps"] for stream in declared] == [15, 15, 15] + assert yaml.safe_load((recorded_main.workdir / "receiver.yaml").read_text())["receiver"]["port"] == 5100 + + +def test_the_streams_state_says_of_each_camera_its_role_its_sizes_and_the_calibration_it_was_corrected_with( + recorded_main, station_calibration, tmp_path: Path +): + _calibrate_all(station_calibration) + _save_plan(station_calibration, PLAN) + assert ss.main(_argv(_profile(tmp_path))) == 0 + state = _state(recorded_main) + assert state["version"] == 1 and state["no_rectify"] is False + assert sorted(state["cameras"]) == ["head", "left_wrist", "right_wrist"] + for name, size, role in STREAMS: + camera = dict(state["cameras"][name]) + applied = camera.pop("rectification") + assert camera == { + "stream": name, + "role": role, + "source_size_wh": list(size), + "divisor": 1, + "published_size_wh": PLAN[role]["output_size_wh"], + } + plan = _planned(station_calibration, role, size) + lens = station_calibration / ROLE_INTRINSICS[role] + table = applied.pop("table") + assert applied == plan.metadata( + calibration_file=ROLE_INTRINSICS[role], + calibration_sha256=hashlib.sha256(lens.read_bytes()).hexdigest(), + ) + assert applied["K"] == plan.K.tolist() and applied["image_size_wh"] == PLAN[role]["output_size_wh"] + assert table["file"] == f"rectify_{role}.icrmap" + files = {state["cameras"][name]["rectification"]["calibration"]["file"] for name, _size, _role in STREAMS} + assert files == {HEAD_INTRINSICS, LEFT_WRIST_INTRINSICS, RIGHT_WRIST_INTRINSICS} + # The library's reader, which the backend uses, finds each camera corrected and its own corrected camera. + read = read_streams_state(recorded_main.workdir / ss.STREAMS_STATE_FILE) + assert all(read.rectified(name) for name, _size, _role in STREAMS) + matrices = [read.corrected_camera(name).K.tolist() for name, _size, _role in STREAMS] + assert matrices[0] != matrices[1] != matrices[2] != matrices[0] + assert sorted(read.session_record()["cameras"]) == ["head", "left_wrist", "right_wrist"] + + +def test_what_becomes_of_each_stream_is_printed_with_its_role_its_size_and_its_track( + recorded_main, station_calibration, tmp_path: Path, capsys +): + _calibrate_all(station_calibration) + _save_plan(station_calibration, {"ego": PLAN["ego"], "wrist_right": PLAN["wrist_right"]}) + profile = _profile(tmp_path) + assert ss.main(_argv(profile)) == 0 + out = capsys.readouterr().out + workdir = recorded_main.workdir + assert "stream 'head': ego, 640x496, track sensing-head\n" in out + assert "stream 'left_wrist': wrist_left, 640x480, track sensing-wrist-left\n" in out + assert "stream 'right_wrist': wrist_right, 640x496, track sensing-wrist-right\n" in out + assert "stream 'head': rectified as ego, 640x496 to 480x360, field of view " in out + assert f"degrees; table {workdir / 'rectify_ego.icrmap'}\n" in out + assert "stream 'left_wrist': published as received; no rectification is switched on for it\n" in out + assert "stream 'right_wrist': rectified as wrist_right, 640x496 to 400x300, field of view " in out + assert f"sender config {profile}: 3 streams at 30 fps, 12 Mbit/s in all " in out + assert "('head' 4, 'left_wrist' 4, 'right_wrist' 4), release egocap-start\n" in out + # The roles are said before the plans, so a refused plan is read against them. + assert out.index("stream 'right_wrist': wrist_right, ") < out.index("stream 'head': rectified as ego") + + +def test_a_camera_whose_role_is_not_switched_on_is_published_as_received_beside_two_that_are_corrected( + recorded_main, station_calibration, tmp_path: Path +): + _calibrate_all(station_calibration) + _save_plan(station_calibration, {**PLAN, "wrist_left": _entry(enabled=False)}) + assert ss.main(_argv(_profile(tmp_path))) == 0 + workdir = recorded_main.workdir + bridge = _child(recorded_main, "bridge").command + at = bridge.index("--stream") + assert bridge[at : bridge.index("--fps")] == [ + "--stream", + "head=sensing-head:1", + "--gpu-step", + f"head:rectify={workdir / 'rectify_ego.icrmap'}", + "--stream", + "left_wrist=sensing-wrist-left:2", + "--stream", + "right_wrist=sensing-wrist-right:1", + "--gpu-step", + f"right_wrist:rectify={workdir / 'rectify_wrist_right.icrmap'}", + ] + cameras = _state(recorded_main)["cameras"] + assert cameras["left_wrist"] == { + "stream": "left_wrist", + "role": "wrist_left", + "source_size_wh": [640, 480], + "divisor": 2, + "published_size_wh": [320, 240], + "rectification": None, + } + assert cameras["head"]["rectification"] is not None and cameras["right_wrist"]["rectification"] is not None + assert sorted(recorded_main.tables) == ["rectify_ego.icrmap", "rectify_wrist_right.icrmap"] + declared = yaml.safe_load((workdir / "streams.yaml").read_text())["livekit"]["streams"] + assert [(stream["width"], stream["height"]) for stream in declared] == [(480, 360), (320, 240), (400, 300)] + + +def test_no_rectify_publishes_all_three_cameras_as_received_and_the_state_says_it_was_switched_off( + recorded_main, station_calibration, tmp_path: Path, capsys +): + # A plan that could not be built for any of them: no calibration is installed. It is not looked at. + _save_plan(station_calibration, PLAN) + assert ss.main(_argv(_profile(tmp_path), "--no-rectify")) == 0 + bridge = _child(recorded_main, "bridge").command + assert "--gpu-step" not in bridge + assert [bridge[at + 1] for at, word in enumerate(bridge) if word == "--stream"] == [ + "head=sensing-head:2", + "left_wrist=sensing-wrist-left:2", + "right_wrist=sensing-wrist-right:2", + ] + state = _state(recorded_main) + assert state["no_rectify"] is True + assert [state["cameras"][name]["rectification"] for name, _size, _role in STREAMS] == [None, None, None] + assert [state["cameras"][name]["role"] for name, _size, _role in STREAMS] == [ + "ego", + "wrist_left", + "wrist_right", + ] + assert state["cameras"]["left_wrist"]["published_size_wh"] == [320, 240] + out = capsys.readouterr().out + assert "rectification is off (--no-rectify): the video is published as received" in out + assert "stream 'left_wrist': wrist_left, 640x480, track sensing-wrist-left\n" in out + + +def test_skip_deploy_reuses_the_release_for_all_three_cameras_and_still_uploads_their_profile( + recorded_main, tmp_path: Path +): + assert ss.main(_argv(_profile(tmp_path), "--skip-deploy", "--release", "kept")) == 0 + to_the_orin = [command[3:] for command in recorded_main.deploys if command[1] == "x"] + assert to_the_orin == [["stop"], ["stop-daemon"], ["stop"]] + sender = _child(recorded_main, "sender").command + assert sender[3:7] == ["run", "--name", "kept", "--config"] + assert len(yaml.safe_load(Path(sender[7]).read_text())["streams"]) == 3 + + +def test_the_mock_chain_sends_and_bridges_all_three_streams_in_the_profiles_order( + recorded_main, station_calibration, tmp_path: Path, capsys +): + _calibrate_all(station_calibration) + _save_plan(station_calibration, PLAN) + argv = [*one_camera._mock_chain(tmp_path), "--sender-config", str(_profile(tmp_path)), *ROLE_ARGS] + assert ss.main(argv) == 0 + assert [child.name for child in recorded_main.children] == [ + "mock-sender", + "livekit", + "capture-server", + "backend", + "receiver", + "bridge", + ] + assert _child(recorded_main, "mock-sender").command == [ + sys.executable, + str(tmp_path / "mock_sender.py"), + "--port", + "5000", + "--stream", + "head:640x496@30", + "--stream", + "left_wrist:640x480@30", + "--stream", + "right_wrist:640x496@30", + ] + bridge = _child(recorded_main, "bridge").command + assert bridge.count("--stream") == 3 and bridge.count("--gpu-step") == 3 + assert bridge[bridge.index("--fps") :] == ["--fps", "30", "--timestamp-basis", "monotonic_us"] + out = capsys.readouterr().out + assert ( + "mock sender: 30 fps streams 'head', 'left_wrist', 'right_wrist', timestamps are frame-ready time\n" in out + ) + + +def test_without_the_camera_chain_a_three_stream_profile_bridges_nothing_and_the_state_has_no_cameras( + recorded_main, tmp_path: Path +): + assert ss.main(["--mock", "--sender-config", str(_profile(tmp_path)), *ROLE_ARGS]) == 0 + assert [child.name for child in recorded_main.children] == ["capture-server", "backend"] + assert _state(recorded_main)["cameras"] == {} + + +# --- held against the real programs' own parsers --------------------------------------------------------------- + + +def _load(name: str, path: Path, monkeypatch, beside: bool = False): + if beside: + # The receiver imports its own modules by their bare names. + monkeypatch.syspath_prepend(str(path.parent)) + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + monkeypatch.setitem(sys.modules, name, module) + spec.loader.exec_module(module) + return module + + +RECEIVER = CAMERA_STREAMER / "camera_receiver" / "camera_receiver.py" +MOCK_SENDER = CAMERA_STREAMER / "mock_sender" / "mock_sender.py" + + +@pytest.mark.skipif(not RECEIVER.is_file(), reason="the camera receiver is absent from this tree") +def test_the_real_receivers_parser_reads_the_three_stream_config_as_three_mono_streams_with_unique_ipc_names( + recorded_main, tmp_path: Path, monkeypatch +): + assert ss.main(_argv(_profile(tmp_path), "--no-rectify")) == 0 + receiver = _load("camera_receiver_real", RECEIVER, monkeypatch, beside=True) + written = receiver._load_config(recorded_main.workdir / "receiver.yaml") + parsed = [receiver._parse_stream_config(raw) for raw in written["streams"]] + assert [(stream.index, stream.name, stream.stereo) for stream in parsed] == [ + (0, "head", False), + (1, "left_wrist", False), + (2, "right_wrist", False), + ] + assert [(stream.width, stream.height) for stream in parsed] == [size for _name, size, _role in STREAMS] + assert [stream.ipc_names for stream in parsed] == [("head",), ("left_wrist",), ("right_wrist",)] + assert [stream.output_format for stream in parsed] == ["nv12"] * 3 + + +@pytest.mark.skipif(not MOCK_SENDER.is_file(), reason="the mock sender is absent from this tree") +def test_the_real_mock_senders_parser_takes_the_three_stream_command(recorded_main, tmp_path: Path, monkeypatch): + argv = [*one_camera._mock_chain(tmp_path), "--sender-config", str(_profile(tmp_path)), *ROLE_ARGS] + assert ss.main(argv) == 0 + mock = _load("mock_sender_real", MOCK_SENDER, monkeypatch) + command = _child(recorded_main, "mock-sender").command + specs = [mock.parse_stream_spec(command[at + 1]) for at, word in enumerate(command) if word == "--stream"] + assert [(spec.name, spec.width, spec.height, spec.fps) for spec in specs] == [ + ("head", 640, 496, 30), + ("left_wrist", 640, 480, 30), + ("right_wrist", 640, 496, 30), + ] + + +def test_capture_servers_own_loader_reads_the_three_stream_descriptor( + recorded_main, station_calibration, tmp_path: Path +): + from capture_server.livekit_streams import load_livekit_streams + + _calibrate_all(station_calibration) + _save_plan(station_calibration, PLAN) + assert ss.main(_argv(_profile(tmp_path))) == 0 + offered = load_livekit_streams(recorded_main.workdir / "streams.yaml") + assert [(stream.name, stream.track, stream.width, stream.height, stream.fps) for stream in offered] == [ + ("head", "sensing-head", 480, 360, 30.0), + ("left_wrist", "sensing-wrist-left", 320, 240, 30.0), + ("right_wrist", "sensing-wrist-right", 400, 300, 30.0), + ] + assert {(stream.room, stream.publisher) for stream in offered} == {("egocap-room", "egocap-bridge")} + + +@pytest.mark.skipif(not one_camera.DEPLOY_TOOL.is_file(), reason="the deploy tool is absent from this tree") +def test_every_deploy_command_of_a_three_camera_start_is_accepted_by_the_real_deploy_tool( + recorded_main, tmp_path: Path, monkeypatch +): + tool = _load("deploy_sender_real_three", one_camera.DEPLOY_TOOL, monkeypatch) + dispatched: list[str] = [] + for name in dir(tool): + if name.startswith("cmd_"): + monkeypatch.setattr(tool, name, lambda *a, _name=name, **k: dispatched.append(_name)) + assert ss.main(_argv(_profile(tmp_path), "--no-rectify")) == 0 + issued = [command[2:] for command in recorded_main.deploys if command[1] == "x"] + issued += [child.command[2:] for child in recorded_main.children if child.command[1] == "x"] + for command in issued: + assert tool.main(command) == 0, command + assert dispatched.count("cmd_run") == 1 and dispatched.count("cmd_deploy") == 1 + + +def _bridge_reading(command: list[str]) -> tuple[dict[str, tuple[str, int]], dict[str, str]]: + """The bridge's own rules for its two repeatable flags, written out from its guide: a stream's DIV is cut at + the last ":" and its NAME at the first "="; a step's value is cut at the first "=", and its stream ends at + the last ":" before that.""" + streams, steps = {}, {} + for at, word in enumerate(command): + if word == "--stream": + spec, _, divisor = command[at + 1].rpartition(":") + name, _, track = spec.partition("=") + streams[name] = (track, int(divisor)) + if word == "--gpu-step": + head, _, argument = command[at + 1].partition("=") + stream, _, step = head.rpartition(":") + assert step == "rectify" + steps[stream] = argument + return streams, steps + + +def test_read_by_the_bridges_documented_rules_each_step_belongs_to_a_stream_the_command_names( + recorded_main, station_calibration, tmp_path: Path +): + _calibrate_all(station_calibration) + _save_plan(station_calibration, PLAN) + assert ss.main(_argv(_profile(tmp_path))) == 0 + streams, steps = _bridge_reading(_child(recorded_main, "bridge").command) + assert streams == {name: (TRACKS[name], 1) for name, _size, _role in STREAMS} + workdir = recorded_main.workdir + assert steps == {name: str(workdir / f"rectify_{role}.icrmap") for name, _size, role in STREAMS} + + +# --- which stream is which camera ------------------------------------------------------------------------------ + + +@pytest.mark.parametrize( + ("roles", "without"), + [ + ([], "'head', 'left_wrist' and 'right_wrist' have"), + (["--stream-role", "head=ego"], "'left_wrist' and 'right_wrist' have"), + (["--stream-role", "head=ego", "--stream-role", "right_wrist=wrist_right"], "'left_wrist' has"), + ], +) +def test_a_stream_without_a_role_is_refused_when_the_profile_has_several_and_no_role_is_guessed( + recorded_main, station_calibration, tmp_path: Path, capsys, roles, without +): + # Every calibration and every entry is there: a guess by name or by order would start, and could be wrong. + _calibrate_all(station_calibration) + _save_plan(station_calibration, PLAN) + assert _refused(recorded_main, capsys, _argv(_profile(tmp_path), roles=roles)) == ( + f"error: the sender config has 3 streams and {without} no camera role; {ALL_ROLES_HINT}\n" + ) + + +def test_a_stream_named_for_a_role_is_not_taken_for_it_either(recorded_main, tmp_path: Path, capsys): + def named_for_roles(config): + for stream, role in zip(config["streams"], ROLE_INTRINSICS, strict=True): + stream["id"] = role + + err = _refused(recorded_main, capsys, _argv(_profile(tmp_path, named_for_roles), roles=[])) + assert "'ego', 'wrist_left' and 'wrist_right' have no camera role" in err + + +@pytest.mark.parametrize( + ("roles", "said"), + [ + ( + ["head=ego", "left_wrist=ego", "right_wrist=wrist_right"], + "--stream-role 'left_wrist=ego': each stream and each role may be given once", + ), + ( + ["head=ego", "left_wrist=wrist_left", "left_wrist=wrist_right"], + "--stream-role 'left_wrist=wrist_right': each stream and each role may be given once", + ), + ( + ["head=ego", "left_wrist=wrist_left", "right_wrist=chest"], + "--stream-role needs STREAM=ROLE with ROLE one of ego, wrist_left, wrist_right, got " + "'right_wrist=chest'", + ), + ( + ["head=ego", "left_wrist=wrist_left", "wrist_right=wrist_right"], + "--stream-role 'wrist_right=wrist_right' names a stream that is not bridged " + "(head, left_wrist, right_wrist)", + ), + ], +) +def test_two_streams_on_one_role_a_role_given_twice_an_unknown_role_and_an_unknown_stream_are_refused( + recorded_main, tmp_path: Path, capsys, roles, said +): + given = [arg for pair in roles for arg in ("--stream-role", pair)] + assert _refused(recorded_main, capsys, _argv(_profile(tmp_path), roles=given)) == f"error: {said}\n" + + +def test_the_roles_decide_the_tracks_and_the_tables_whatever_the_order_the_profile_lists_the_streams_in( + recorded_main, station_calibration, tmp_path: Path +): + def wrists_first(config): + config["streams"] = [config["streams"][2], config["streams"][1], config["streams"][0]] + + _calibrate_all(station_calibration) + _save_plan(station_calibration, PLAN) + assert ss.main(_argv(_profile(tmp_path, wrists_first))) == 0 + streams, steps = _bridge_reading(_child(recorded_main, "bridge").command) + assert list(streams) == ["right_wrist", "left_wrist", "head"] + assert streams == {name: (TRACKS[name], 1) for name, _size, _role in STREAMS} + assert steps["head"].endswith("rectify_ego.icrmap") and steps["right_wrist"].endswith( + "rectify_wrist_right.icrmap" + ) + received = yaml.safe_load((recorded_main.workdir / "receiver.yaml").read_text())["streams"] + # The receiver's index is the sender's stream order, which is the profile's. + assert [(stream["index"], stream["name"]) for stream in received] == [ + (0, "right_wrist"), + (1, "left_wrist"), + (2, "head"), + ] + + +def test_two_streams_are_bridged_too_and_a_role_no_stream_fills_is_only_warned_of( + recorded_main, station_calibration, tmp_path: Path, capsys +): + def head_and_left(config): + del config["streams"][2] + + _calibrate_all(station_calibration) + _save_plan(station_calibration, PLAN) + roles = ["--stream-role", "head=ego", "--stream-role", "left_wrist=wrist_left"] + assert ss.main(_argv(_profile(tmp_path, head_and_left), roles=roles)) == 0 + bridge = _child(recorded_main, "bridge").command + assert bridge.count("--stream") == 2 and bridge.count("--gpu-step") == 2 + assert sorted(_state(recorded_main)["cameras"]) == ["head", "left_wrist"] + assert ( + "WARNING: the rectification plan switches on wrist_right, which no bridged stream fills; that camera is " + "not rectified" + ) in capsys.readouterr().out + + +def test_every_role_has_a_track_of_its_own_and_a_profiles_only_stream_keeps_the_head_track(): + assert sorted(ss.ROLE_TRACKS) == sorted(ROLE_INTRINSICS) + assert len(set(ss.ROLE_TRACKS.values())) == len(ROLE_INTRINSICS) + assert ss.MAX_STREAMS == len(ROLE_INTRINSICS) == 3 + assert ss.stream_tracks(["head"], {"head": "ego"}) == {"head": "sensing-head"} + # Whatever role it is given: the one-stream start publishes the track it always did. + assert ss.stream_tracks(["cam"], {"cam": "wrist_left"}) == {"cam": "sensing-head"} + assert ss.stream_tracks(["a", "b"], {"a": "wrist_right", "b": "ego"}) == { + "a": "sensing-wrist-right", + "b": "sensing-head", + } + + +# --- profiles the launcher cannot start -------------------------------------------------------------------------- + + +def _fourth(config): + config["streams"].append(_stream("chest", 3, (640, 496))) + + +def _stereo_wrist(config): + config["streams"][1]["type"] = "stereo" + + +def _same_id(config): + config["streams"][2]["id"] = "head" + + +def _faster_wrist(config): + config["streams"][2]["output"]["fps"] = 60 + + +def _unsized_wrist(config): + del config["streams"][1]["output"]["width"], config["streams"][1]["output"]["height"] + + +def _wrist_the_bridge_cannot_name(config): + config["streams"][2]["id"] = "wrist=right" + + +def test_more_streams_than_the_station_has_camera_roles_are_refused(recorded_main, tmp_path: Path, capsys): + assert _refused(recorded_main, capsys, _argv(_profile(tmp_path, _fourth))) == ( + "error: three-cameras.yaml has 4 streams, and the launcher bridges at most 3, one for each station camera " + "role (ego, wrist_left, wrist_right); leave only the station's cameras in it\n" + ) + + +@pytest.mark.parametrize("streams", [[], None, {"head": {}}, "head"]) +def test_a_profile_that_lists_no_stream_is_refused(recorded_main, tmp_path: Path, capsys, streams): + profile = _profile(tmp_path, lambda config: config.update(streams=streams)) + assert _refused(recorded_main, capsys, _argv(profile)) == ( + "error: three-cameras.yaml must hold a list of streams, from 1 to 3 mono streams\n" + ) + + +def test_a_stream_that_is_not_mono_among_several_is_refused_and_named(recorded_main, tmp_path: Path, capsys): + profile = _profile(tmp_path, _stereo_wrist) + assert _refused(recorded_main, capsys, _argv(profile)) == ( + f"error: {profile}: the launcher supports only a mono stream, got type 'stereo' for streams[1]\n" + ) + + +def test_two_streams_under_one_id_are_refused(recorded_main, tmp_path: Path, capsys): + assert _refused(recorded_main, capsys, _argv(_profile(tmp_path, _same_id))) == ( + "error: the sender config names two streams 'head'; give each stream an id of its own\n" + ) + + +def test_streams_at_different_rates_are_refused_since_the_bridge_takes_one_rate( + recorded_main, tmp_path: Path, capsys +): + assert _refused(recorded_main, capsys, _argv(_profile(tmp_path, _faster_wrist))) == ( + "error: the sender config's streams run at different rates ('head' 30, 'left_wrist' 30, 'right_wrist' 60 " + "fps) and the camera bridge takes one rate for all of them; set the same output.fps on every stream, or " + "pass --fps\n" + ) + + +def test_one_rate_given_on_the_command_line_is_every_streams_rate(recorded_main, tmp_path: Path): + assert ss.main(_argv(_profile(tmp_path, _faster_wrist), "--fps", "30")) == 0 + uploaded = yaml.safe_load((recorded_main.workdir / "sender.yaml").read_text()) + assert [stream["output"]["fps"] for stream in uploaded["streams"]] == [30, 30, 30] + + +def test_a_stream_that_states_no_size_among_several_is_refused_and_no_cameras_size_is_assumed_for_it( + recorded_main, tmp_path: Path, capsys +): + assert _refused(recorded_main, capsys, _argv(_profile(tmp_path, _unsized_wrist))) == ( + "error: the sender config must set streams[1].output.width and height: with more than one stream each " + "states the size of its own picture; or pass --width and --height when every camera sends the same size\n" + ) + # One of the two flags leaves the other dimension to be assumed. + assert "must set streams[1].output.width and height" in _refused( + recorded_main, capsys, _argv(_profile(tmp_path, _unsized_wrist), "--width", "640") + ) + + +def test_a_size_given_on_the_command_line_is_the_size_of_every_stream_that_states_none( + recorded_main, tmp_path: Path +): + def unsized(config): + for stream in config["streams"]: + del stream["output"]["width"], stream["output"]["height"] + + assert ss.main(_argv(_profile(tmp_path, unsized), "--width", "1280", "--height", "992")) == 0 + received = yaml.safe_load((recorded_main.workdir / "receiver.yaml").read_text())["streams"] + assert [(stream["width"], stream["height"]) for stream in received] == [(1280, 992)] * 3 + + +def test_a_stream_name_the_bridge_cannot_take_is_refused_for_any_of_the_streams( + recorded_main, tmp_path: Path, capsys +): + profile = _profile(tmp_path, _wrist_the_bridge_cannot_name) + roles = ["--stream-role", "head=ego", "--stream-role", "left_wrist=wrist_left"] + assert _refused(recorded_main, capsys, _argv(profile, roles=roles)) == ( + "error: the sender config's stream id 'wrist=right' holds \"=\", which the camera bridge cannot take in a " + "stream's name; rename the stream in the sender config\n" + ) + + +@pytest.mark.parametrize( + ("mutate", "said"), + [ + (lambda c: c["streams"][2].pop("id"), "the sender config must set streams[2].id"), + (lambda c: c["streams"][1]["output"].pop("fps"), "the sender config must set streams[1].output.fps"), + ( + lambda c: c["streams"][2]["output"].update(width=-2), + "streams[2].output.width must be a positive integer", + ), + ( + lambda c: c["streams"][1]["output"].pop("height"), + "the sender config must set both streams[1].output.width and height, or neither", + ), + (lambda c: c["streams"].__setitem__(2, 7), "streams[2] must be a mapping"), + (lambda c: c["streams"][1].update(output=[1]), "output must be a mapping"), + ], +) +def test_what_is_wrong_with_a_later_stream_is_said_of_that_stream( + recorded_main, tmp_path: Path, capsys, mutate, said +): + assert said in _refused(recorded_main, capsys, _argv(_profile(tmp_path, mutate))) + + +# --- a correction that cannot be made for one camera ------------------------------------------------------------- + +WAY_OUT = one_camera.WAY_OUT + + +def test_a_wrist_role_switched_on_without_its_calibration_stops_the_start_and_names_that_stream( + recorded_main, station_calibration, tmp_path: Path, capsys +): + _calibrate_all(station_calibration, wrist_right=None) + _save_plan(station_calibration, PLAN) + # The head's and the left wrist's tables were planned by then, and no camera is left to run uncorrected. + assert _refused(recorded_main, capsys, _argv(_profile(tmp_path))) == ( + f"error: cannot rectify stream 'right_wrist' (role wrist_right, calibration {RIGHT_WRIST_INTRINSICS}): " + f"{RIGHT_WRIST_INTRINSICS} could not be read{WAY_OUT}" + ) + + +def test_a_wrist_calibration_of_another_size_than_its_stream_stops_the_start( + recorded_main, station_calibration, tmp_path: Path, capsys +): + # The left wrist sends 640x480 and its role holds a lens solved at 640x496. + _calibrate_all(station_calibration, wrist_left=rectify_helpers.fisheye_record(camera="left_wrist")) + _save_plan(station_calibration, PLAN) + err = _refused(recorded_main, capsys, _argv(_profile(tmp_path))) + assert err.startswith( + f"error: cannot rectify stream 'left_wrist' (role wrist_left, calibration {LEFT_WRIST_INTRINSICS}): " + ) + assert "the calibration was solved at 640x496, which is not the 640x480 picture" in err + + +def test_wrist_calibrations_installed_under_each_others_roles_stop_the_start( + recorded_main, station_calibration, tmp_path: Path, capsys +): + # Same picture size and both sound: only the camera each file was solved for tells them apart. + swapped = { + "wrist_left": rectify_helpers.fisheye_record(camera="right_wrist"), + "wrist_right": rectify_helpers.fisheye_record(camera="left_wrist"), + } + + def same_size(config): + config["streams"][1]["output"].update(width=640, height=496) + + _calibrate_all(station_calibration, **swapped) + _save_plan(station_calibration, PLAN) + assert _refused(recorded_main, capsys, _argv(_profile(tmp_path, same_size))) == ( + f"error: cannot rectify stream 'left_wrist' (role wrist_left, calibration {LEFT_WRIST_INTRINSICS}): " + f"{LEFT_WRIST_INTRINSICS} was solved for camera 'right_wrist', and 'left_wrist' fills the role now; " + "calibrate this camera to replace it, or pass --no-rectify to publish the video as received\n" + ) + + +def test_streams_given_each_others_roles_are_caught_by_the_camera_each_calibration_was_solved_for( + recorded_main, station_calibration, tmp_path: Path, capsys +): + def same_size(config): + config["streams"][1]["output"].update(width=640, height=496) + + _calibrate_all(station_calibration, wrist_left=rectify_helpers.fisheye_record(camera="left_wrist")) + _save_plan(station_calibration, PLAN) + crossed = ["head=ego", "left_wrist=wrist_right", "right_wrist=wrist_left"] + given = [arg for pair in crossed for arg in ("--stream-role", pair)] + err = _refused(recorded_main, capsys, _argv(_profile(tmp_path, same_size), roles=given)) + assert "was solved for camera" in err and "fills the role now" in err + + +def test_a_wrist_calibration_written_in_a_newer_layout_stops_the_start( + recorded_main, station_calibration, tmp_path: Path, capsys +): + newer = rectify_helpers.good_record(camera="left_wrist", schema_version=99) + _calibrate_all(station_calibration, wrist_left=newer) + _save_plan(station_calibration, PLAN) + assert _refused(recorded_main, capsys, _argv(_profile(tmp_path))) == ( + f"error: cannot rectify stream 'left_wrist' (role wrist_left, calibration {LEFT_WRIST_INTRINSICS}): " + f"{LEFT_WRIST_INTRINSICS} is written in layout 99, and this software reads up to layout 1: update the " + f"software, or calibrate again with this one{WAY_OUT}" + ) + + +def test_a_view_the_planner_refuses_for_one_wrist_stops_the_start_with_that_streams_name( + recorded_main, station_calibration, tmp_path: Path, capsys +): + _calibrate_all(station_calibration) + _save_plan(station_calibration, {**PLAN, "wrist_right": _entry(balance=1.0)}) + err = _refused(recorded_main, capsys, _argv(_profile(tmp_path))) + assert err.startswith( + f"error: cannot rectify stream 'right_wrist' (role wrist_right, calibration {RIGHT_WRIST_INTRINSICS}): " + ) + assert err.endswith(WAY_OUT) + + +def test_a_table_that_cannot_be_written_for_the_last_camera_stops_the_start_and_leaves_no_table_behind( + recorded_main, station_calibration, tmp_path: Path, capsys, monkeypatch +): + write = ss.write_remap_table + + def full_at_the_last(path, plan): + if Path(path).name == "rectify_wrist_right.icrmap": + raise RemapTableError(f"{Path(path).name} could not be written") + return write(path, plan) + + monkeypatch.setattr(ss, "write_remap_table", full_at_the_last) + _calibrate_all(station_calibration) + _save_plan(station_calibration, PLAN) + assert _refused(recorded_main, capsys, _argv(_profile(tmp_path))) == ( + "error: cannot rectify stream 'right_wrist' (role wrist_right): rectify_wrist_right.icrmap could not be " + f"written{one_camera._table_way_out(recorded_main)}" + ) + + +def test_a_refused_start_writes_no_streams_state_so_no_backend_reads_one_camera_as_corrected( + recorded_main, station_calibration, tmp_path: Path, capsys +): + _calibrate_all(station_calibration, wrist_left=None) + _save_plan(station_calibration, PLAN) + _refused(recorded_main, capsys, _argv(_profile(tmp_path))) + assert not (recorded_main.workdir / ss.STREAMS_STATE_FILE).exists() + + +def test_each_cameras_planner_warning_is_printed_under_its_own_stream( + recorded_main, station_calibration, tmp_path: Path, capsys +): + seen_less = rectify_helpers.fisheye_record(camera="right_wrist", max_field_angle_deg=20.0) + _calibrate_all(station_calibration, wrist_right=seen_less) + _save_plan(station_calibration, PLAN) + assert ss.main(_argv(_profile(tmp_path))) == 0 + warned = [line for line in capsys.readouterr().out.splitlines() if line.startswith("WARNING: stream ")] + assert any( + line.startswith("WARNING: stream 'right_wrist': the corrected picture looks up to ") for line in warned + ) + assert not any(line.startswith("WARNING: stream 'head'") for line in warned) + assert not any("is not stamped for a camera" in line for line in warned) + + +# --- lens files that cannot be told apart ---------------------------------------------------------------------- + + +def _same_size(config): + for stream in config["streams"]: + stream["output"].update(width=640, height=496) + + +def _unstamped() -> dict[str, dict]: + """A sound fisheye lens for each role, each of another focal length, none naming the camera it was solved + for: as another tool's file, or one placed by hand.""" + focal = {"ego": 282.0, "wrist_left": 260.0, "wrist_right": 300.0} + return { + role: rectify_helpers.fisheye_record(K=rectify_helpers.camera_matrix(length, 328.5, 241.5).tolist()) + for role, length in focal.items() + } + + +SAME_VIEW = {role: _entry() for role in ROLE_INTRINSICS} +UNSTAMPED_AMONG_SEVERAL = ( + " is not stamped for a camera, so it cannot be checked against the camera in this role, and with more than " + "one camera bridged it could be another camera's lens; solve this camera's lens again from the page so that " + "the file names its camera, or bridge this camera alone, or pass --no-rectify to publish the video as " + "received\n" +) + + +def _refused_and_nothing_written(recorded, capsys, argv) -> str: + err = _refused(recorded, capsys, argv) + assert not (recorded.workdir / ss.STREAMS_STATE_FILE).exists() + return err + + +def test_wrists_given_each_others_roles_on_lens_files_that_name_no_camera_are_refused_and_not_corrected_crosswise( + recorded_main, station_calibration, tmp_path: Path, capsys +): + # Same picture size, sound lenses, a plan for each: only a camera's name in the file could tell them apart. + _calibrate_all(station_calibration, **_unstamped()) + _save_plan(station_calibration, SAME_VIEW) + crossed = ["head=ego", "left_wrist=wrist_right", "right_wrist=wrist_left"] + given = [arg for pair in crossed for arg in ("--stream-role", pair)] + err = _refused_and_nothing_written(recorded_main, capsys, _argv(_profile(tmp_path, _same_size), roles=given)) + assert err == ( + f"error: cannot rectify stream 'head' (role ego, calibration {HEAD_INTRINSICS}): {HEAD_INTRINSICS}" + f"{UNSTAMPED_AMONG_SEVERAL}" + ) + + +def test_streams_named_for_the_roles_and_given_each_others_are_refused_on_unstamped_lens_files_too( + recorded_main, station_calibration, tmp_path: Path, capsys +): + def named_for_roles(config): + _same_size(config) + for stream, role in zip(config["streams"], ROLE_INTRINSICS, strict=True): + stream["id"] = role + + _calibrate_all(station_calibration, **{**_unstamped(), "ego": rectify_helpers.fisheye_record(camera="ego")}) + _save_plan(station_calibration, SAME_VIEW) + crossed = ["ego=ego", "wrist_left=wrist_right", "wrist_right=wrist_left"] + given = [arg for pair in crossed for arg in ("--stream-role", pair)] + err = _refused_and_nothing_written( + recorded_main, capsys, _argv(_profile(tmp_path, named_for_roles), roles=given) + ) + # The head's file names its camera and is planned; the first wrist's names none and stops the start. + assert err == ( + f"error: cannot rectify stream 'wrist_left' (role wrist_right, calibration {RIGHT_WRIST_INTRINSICS}): " + f"{RIGHT_WRIST_INTRINSICS}{UNSTAMPED_AMONG_SEVERAL}" + ) + + +@pytest.mark.parametrize("stamp", [None, "left_wrist"]) +def test_one_lens_file_copied_under_two_roles_is_refused_and_both_roles_are_named( + recorded_main, station_calibration, tmp_path: Path, capsys, stamp +): + copied = rectify_helpers.fisheye_record(camera=stamp) + lenses = {**_unstamped(), "ego": rectify_helpers.fisheye_record(camera="head")} + _calibrate_all(station_calibration, **{**lenses, "wrist_left": copied, "wrist_right": copied}) + _save_plan(station_calibration, SAME_VIEW) + err = _refused_and_nothing_written(recorded_main, capsys, _argv(_profile(tmp_path, _same_size))) + assert err == ( + "error: cannot rectify streams 'left_wrist' and 'right_wrist' (roles wrist_left and wrist_right): " + f"{LEFT_WRIST_INTRINSICS} and {RIGHT_WRIST_INTRINSICS} are the same file, and one lens is not two " + "cameras'; calibrate each camera's own lens from the page, or pass --no-rectify to publish the video as " + "received\n" + ) + + +def test_a_lens_file_that_names_no_camera_is_refused_among_several_streams_though_the_roles_are_right( + recorded_main, station_calibration, tmp_path: Path, capsys +): + _calibrate_all(station_calibration, wrist_left=rectify_helpers.good_record()) + _save_plan(station_calibration, PLAN) + assert _refused_and_nothing_written(recorded_main, capsys, _argv(_profile(tmp_path))) == ( + f"error: cannot rectify stream 'left_wrist' (role wrist_left, calibration {LEFT_WRIST_INTRINSICS}): " + f"{LEFT_WRIST_INTRINSICS}{UNSTAMPED_AMONG_SEVERAL}" + ) + + +def test_an_unstamped_lens_file_of_a_role_that_is_not_corrected_stops_nothing( + recorded_main, station_calibration, tmp_path: Path +): + _calibrate_all(station_calibration, wrist_left=rectify_helpers.good_record()) + _save_plan(station_calibration, {**PLAN, "wrist_left": _entry(enabled=False)}) + assert ss.main(_argv(_profile(tmp_path))) == 0 + cameras = _state(recorded_main)["cameras"] + assert cameras["left_wrist"]["rectification"] is None and cameras["right_wrist"]["rectification"] is not None + + +def test_two_bridged_streams_are_several_and_an_unstamped_lens_is_refused_for_them_as_for_three( + recorded_main, station_calibration, tmp_path: Path, capsys +): + def head_and_left(config): + del config["streams"][2] + + _calibrate_all(station_calibration, ego=rectify_helpers.fisheye_record()) + _save_plan(station_calibration, PLAN) + roles = ["--stream-role", "head=ego", "--stream-role", "left_wrist=wrist_left"] + err = _refused_and_nothing_written( + recorded_main, capsys, _argv(_profile(tmp_path, head_and_left), roles=roles) + ) + assert err.startswith("error: cannot rectify stream 'head' (role ego, ") and err.endswith( + UNSTAMPED_AMONG_SEVERAL + ) + + +def test_a_one_stream_start_is_still_only_warned_of_a_lens_file_that_names_no_camera( + recorded_main, station_calibration, capsys +): + one_camera._calibrate(station_calibration) + _save_plan(station_calibration, {"ego": _entry()}) + assert ss.main([*one_camera.ORIN_ARGV, *one_camera.CAMERA_ARGS, *one_camera.FISHEYE_SENSOR]) == 0 + assert one_camera.UNSTAMPED_LENS in capsys.readouterr().out + assert _state(recorded_main)["cameras"]["head"]["rectification"] is not None + + +# --- profiles the sender would refuse once it is deployed -------------------------------------------------------- + + +@pytest.mark.parametrize("second", [0, "0", " 0"]) +def test_two_streams_on_one_camera_device_are_refused_before_the_deploy( + recorded_main, tmp_path: Path, capsys, second +): + def copied_stream(config): + config["streams"][1]["cameras"][0]["device"] = second + + assert _refused(recorded_main, capsys, _argv(_profile(tmp_path, copied_stream))) == ( + "error: the sender config gives streams 'head' and 'left_wrist' the same camera (cameras[0].device 0); " + "give each stream the device of its own camera\n" + ) + + +@pytest.mark.parametrize( + "cameras", + [None, [], [{"device": 1, "mode": 0}, {"device": 5, "mode": 0}], {"device": 1}, [1], [{"mode": 0}]], +) +def test_a_stream_without_exactly_one_camera_is_refused_before_the_deploy( + recorded_main, tmp_path: Path, capsys, cameras +): + def miscabled(config): + config["streams"][1]["cameras"] = cameras + + assert _refused(recorded_main, capsys, _argv(_profile(tmp_path, miscabled))) == ( + "error: the sender config must give streams[1] exactly one camera: cameras is a list of one entry that " + "names its device, since a mono stream has one camera\n" + ) + + +def test_a_one_stream_profile_without_its_camera_is_refused_too(recorded_main, tmp_path: Path, capsys): + profile = one_camera._profile_with(tmp_path, lambda config: config["streams"][0].pop("cameras")) + argv = [*one_camera.ORIN_ARGV, *one_camera.CAMERA_ARGS, "--sender-config", str(profile)] + assert "the sender config must give streams[0] exactly one camera" in _refused(recorded_main, capsys, argv) + + +def test_a_stream_id_that_is_a_list_is_refused(recorded_main, tmp_path: Path, capsys): + profile = _profile(tmp_path, lambda config: config["streams"][1].update(id=["left", "wrist"])) + assert _refused(recorded_main, capsys, _argv(profile)) == ( + "error: the sender config's streams[1].id must be a name, not a list or a mapping\n" + ) + + +@pytest.mark.parametrize( + ("mutate", "said"), + [ + ( + lambda c: c["streams"][1]["output"].update(fps="fast"), + "the sender config's streams[1].output.fps must be a whole number of frames a second, got 'fast'", + ), + ( + lambda c: [stream["output"].update(fps=29.97) for stream in c["streams"]], + "the sender config's streams[0].output.fps must be a whole number of frames a second, got 29.97", + ), + ( + lambda c: c["streams"][2]["output"].update(fps=30.5), + "the sender config's streams[2].output.fps must be a whole number of frames a second, got 30.5", + ), + ( + lambda c: c["streams"][0]["output"].update(fps=-30), + "the sender config's streams[0].output.fps must be a whole number of frames a second, got -30", + ), + ( + lambda c: c["streams"][2]["output"].update(bitrate_mbps="4M"), + "the sender config's streams[2].output.bitrate_mbps must be a whole number of megabits a second, got " + "'4M'", + ), + ( + lambda c: c["streams"][0]["output"].update(bitrate_mbps=2.5), + "the sender config's streams[0].output.bitrate_mbps must be a whole number of megabits a second, got " + "2.5", + ), + ( + lambda c: c["network"].update(port="video"), + "the sender config's network.port must be a whole number from 1 to 65535, got 'video'", + ), + ( + lambda c: c["network"].update(port=70000), + "the sender config's network.port must be a whole number from 1 to 65535, got 70000", + ), + ( + lambda c: c["network"].update(port=True), + "the sender config's network.port must be a whole number from 1 to 65535, got True", + ), + ], +) +def test_a_rate_a_bitrate_or_a_port_that_is_no_whole_number_gets_a_sentence_and_no_traceback( + recorded_main, tmp_path: Path, capsys, mutate, said +): + assert _refused(recorded_main, capsys, _argv(_profile(tmp_path, mutate))) == f"error: {said}\n" + + +def test_whole_numbers_written_as_text_are_taken_as_the_sender_takes_them(recorded_main, tmp_path: Path): + def as_text(config): + config["network"]["port"] = "5001" + for stream in config["streams"]: + stream["output"].update(fps="30", bitrate_mbps="6") + + config = ss.load_sender_config(_profile(tmp_path, as_text)) + assert [(one.port, one.fps, one.bitrate_mbps) for one in ss.sender_streams(config)] == [(5001, 30, 6)] * 3 + + +def test_a_one_stream_profile_with_a_rate_that_is_a_word_gets_the_sentence_too(recorded_main, tmp_path, capsys): + profile = one_camera._profile_with(tmp_path, lambda config: config["streams"][0]["output"].update(fps="x")) + argv = [*one_camera.ORIN_ARGV, *one_camera.CAMERA_ARGS, "--sender-config", str(profile)] + assert _refused(recorded_main, capsys, argv) == ( + "error: the sender config's streams[0].output.fps must be a whole number of frames a second, got 'x'\n" + ) + + +# --- a sender that is gone before the page is announced ---------------------------------------------------------- + + +@pytest.mark.parametrize("several", [True, False]) +def test_a_sender_that_has_already_exited_is_reported_in_place_of_the_announcement_that_the_page_is_up( + recorded_main, tmp_path: Path, monkeypatch, capsys, several +): + started = ss.Stack.start + + def start(self, name, *args, **kwargs): + managed = started(self, name, *args, **kwargs) + if name == "sender": + # As a sender whose profile the Orin refused: gone while the PC side was coming up. + managed.process.poll = lambda: 3 + managed.process.returncode = 3 + return managed + + monkeypatch.setattr(ss.Stack, "start", start) + argv = ( + _argv(_profile(tmp_path), "--no-rectify") if several else [*one_camera.ORIN_ARGV, *one_camera.CAMERA_ARGS] + ) + assert ss.main(argv) == 1 + captured = capsys.readouterr() + assert captured.err == f"error: sender exited with 3; see {recorded_main.workdir / 'sender.log'}\n" + assert "Ego Capture is up" not in captured.out and "setting up time sync" not in captured.out + # Everything was started by then, and the launcher's stop takes it all down again. + assert [child.name for child in recorded_main.children][-1] == "bridge" + + +# --- a station whose cameras all arrive through the bridge ------------------------------------------------------- + +BRIDGED_STATION = ss.EGOCAP_ROOT / "recording" / "egocap" / "stations" / "ego_stations.bridged.example.yaml" + + +def test_the_three_camera_command_of_the_guides_starts_with_the_example_station_for_bridged_cameras( + recorded_main, tmp_path: Path +): + # As the guides write it: no --capture-camera, the station file named. + argv = [*one_camera.ORIN_ARGV, "--sender-config", str(_profile(tmp_path)), *ROLE_ARGS] + assert ss.main([*argv, "--station-config", str(BRIDGED_STATION), "--no-rectify"]) == 0 + capture = _child(recorded_main, "capture-server").command + assert "--camera" not in capture and "--livekit-streams" in capture + assert _child(recorded_main, "backend").env["EGOCAP_STATION_CONFIG"] == str(BRIDGED_STATION) + + +def test_the_example_station_for_bridged_cameras_asks_capture_server_for_none_and_aligns_on_the_head_stream(): + station = next(iter(yaml.safe_load(BRIDGED_STATION.read_text())["stations"].values())) + assert station["video_sources"] == [] + example = yaml.safe_load(EXAMPLE_PROFILE.read_text()) + assert station["alignment"]["index_source"] == example["streams"][0]["id"] == "head" + # No operator, no machine's own path: the template's conventions. + assert station["meta"]["operator_name"] == "" and station["recording"]["data_dir"].startswith("~/") + + +def test_without_a_station_file_the_three_camera_command_is_still_refused_for_the_default_stations_cameras( + recorded_main, tmp_path: Path, capsys +): + argv = [*one_camera.ORIN_ARGV, "--sender-config", str(_profile(tmp_path)), *ROLE_ARGS] + err = _refused(recorded_main, capsys, argv) + assert "requests cameras" in err and "that CaptureServer was not given" in err + + +# --- placeholders, and the example profile --------------------------------------------------------------------- + + +def test_placeholders_are_found_wherever_a_profile_holds_one(tmp_path: Path): + config = { + "sipl": {"platform_config_json": "PLACEHOLDER_PLATFORM_FILE", "link_masks": ["PLACEHOLDER_MASK", 0]}, + "network": {"port": 5000}, + "streams": [{"id": "head", "cameras": [{"device": "PLACEHOLDER_HEAD_PIPELINE"}], "output": {"fps": 30}}], + } + assert ss.placeholders(config) == [ + "sipl.platform_config_json", + "sipl.link_masks[0]", + "streams[0].cameras[0].device", + ] + assert ss.placeholders({"streams": [{"id": "head"}]}) == [] + + +def test_a_profile_that_still_holds_a_placeholder_is_refused_before_anything_starts_and_says_which( + recorded_main, tmp_path: Path, capsys +): + def unfilled(config): + config["sipl"]["platform_config_name"] = "PLACEHOLDER_PLATFORM_NAME" + config["streams"][2]["cameras"][0]["device"] = "PLACEHOLDER_RIGHT_WRIST_PIPELINE" + + assert _refused(recorded_main, capsys, _argv(_profile(tmp_path, unfilled))) == ( + "error: three-cameras.yaml still holds placeholders (sipl.platform_config_name, " + "streams[2].cameras[0].device); replace each with this station's value, which the comment beside it says " + "where to find\n" + ) + + +def test_a_placeholder_is_not_made_good_by_an_override_of_its_value(recorded_main, tmp_path: Path, capsys): + def unfilled(config): + for stream in config["streams"]: + stream["output"]["fps"] = "PLACEHOLDER_FPS" + + err = _refused(recorded_main, capsys, _argv(_profile(tmp_path, unfilled), "--fps", "30")) + assert "still holds placeholders (streams[0].output.fps, streams[1].output.fps, streams[2].output.fps)" in err + + +def test_the_shipped_one_camera_profile_holds_no_placeholder(): + assert ss.placeholders(yaml.safe_load(ss.DEFAULT_SENDER_CONFIG.read_text())) == [] + + +def test_the_example_profile_is_three_mono_streams_and_is_refused_as_shipped_for_its_placeholders( + recorded_main, capsys +): + example = yaml.safe_load(EXAMPLE_PROFILE.read_text()) + assert [stream["type"] for stream in example["streams"]] == ["mono"] * 3 + assert example["capture_backend"] == "sipl" + err = _refused(recorded_main, capsys, _argv(EXAMPLE_PROFILE)) + assert err.startswith(f"error: {EXAMPLE_PROFILE.name} still holds placeholders (") + held = set(ss.placeholders(example)) + # Everything that belongs to a station: where its cameras are, its platform and links, sizes, rate, bitrate. + assert {"sipl.platform_config_json", "sipl.platform_config_name", "sipl.link_masks"} <= held + for index in range(3): + assert f"streams[{index}].cameras[0].device" in held + for key in ("width", "height", "fps", "bitrate_mbps"): + assert f"streams[{index}].output.{key}" in held + + +def _filled(value, where: str): + """A value of the example profile with its placeholders replaced by what a station's file would hold there.""" + if isinstance(value, dict): + return {key: _filled(inner, f"{where}.{key}") for key, inner in value.items()} + if isinstance(value, list): + return [_filled(inner, f"{where}[{index}]") for index, inner in enumerate(value)] + if not (isinstance(value, str) and ss.PLACEHOLDER_MARK in value): + return value + stream = re.search(r"streams\[(\d)\]", where) + if where.endswith(".device"): + return int(stream.group(1)) + if where.endswith((".width", ".height", ".fps", ".bitrate_mbps")): + return {"width": 640, "height": 496, "fps": 30, "bitrate_mbps": 4}[where.rsplit(".", 1)[1]] + return [1] if where.endswith("link_masks") else "filled-in" + + +def test_the_example_profile_with_a_stations_values_in_place_starts_three_cameras_with_the_roles_its_guide_gives( + recorded_main, station_calibration, tmp_path: Path +): + example = yaml.safe_load(EXAMPLE_PROFILE.read_text()) + profile = tmp_path / "station.yaml" + profile.write_text(yaml.safe_dump(_filled(example, ""), sort_keys=False)) + names = [stream["id"] for stream in example["streams"]] + assert names == ["head", "left_wrist", "right_wrist"] + assert ss.main(_argv(profile, "--no-rectify")) == 0 + assert _child(recorded_main, "bridge").command.count("--stream") == 3 + assert [camera["role"] for camera in _state(recorded_main)["cameras"].values()] == [ + "ego", + "wrist_left", + "wrist_right", + ] + + +def test_the_example_profile_uses_only_keys_the_senders_parser_knows(): + # The sender refuses a key it does not know, after the deploy; its parser lists them in Config.cpp. + parser = (CAMERA_STREAMER / "argus_sender" / "src" / "Config.cpp").read_text() + example = yaml.safe_load(EXAMPLE_PROFILE.read_text()) + keys = set(example) + for section in ("sipl", "network", "runtime"): + keys |= set(example.get(section) or {}) + for stream in example["streams"]: + keys |= set(stream) | set(stream["output"]) | {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 one-camera start, held to what it was ------------------------------------------------------------------- + +ONE_CAMERA_RECEIVER = """version: 1 +receiver: + host: 192.0.2.10 + port: 5000 + gpu_id: 0 + max_record_bytes: 268435456 + stats_log_interval_s: 2 +ipc: + socket_path: {socket} + owner_name: egocap_start_system + queue_size: 1024 +streams: +- index: 0 + name: head + type: mono + width: 2560 + height: 1984 + output_format: nv12 + ring_depth: 6 + ipc: + mono: head +""" + +ONE_CAMERA_DESCRIPTOR = """livekit: + url: ws://127.0.0.1:7880 + room: egocap-room + publisher: egocap-bridge + timestamp_basis: capture_monotonic_us + streams: + - name: head + track: sensing-head + width: 1280 + height: 992 + fps: 30 +""" + + +def test_a_one_stream_start_writes_the_files_and_says_the_lines_it_did_before_there_were_three( + recorded_main, capsys +): + assert ss.main([*one_camera.ORIN_ARGV, *one_camera.CAMERA_ARGS]) == 0 + workdir = recorded_main.workdir + assert (workdir / "receiver.yaml").read_text() == ONE_CAMERA_RECEIVER.format( + socket=workdir / "camera_receiver.sock" + ) + assert (workdir / "streams.yaml").read_text() == ONE_CAMERA_DESCRIPTOR + 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 ") + # 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) + + +def test_a_one_stream_start_keeps_the_head_track_and_the_head_role_whatever_the_stream_is_called( + recorded_main, tmp_path: Path +): + profile = one_camera._profile_with_stream_id(tmp_path, "left_wrist") + assert ss.main([*one_camera.ORIN_ARGV, *one_camera.CAMERA_ARGS, "--sender-config", str(profile)]) == 0 + bridge = _child(recorded_main, "bridge").command + assert bridge[bridge.index("--stream") + 1] == "left_wrist=sensing-head:2" + assert _state(recorded_main)["cameras"]["left_wrist"]["role"] == "ego" + + +def test_two_mono_streams_load_now_and_only_their_missing_roles_stop_them(tmp_path: Path): + def head_and_left(config): + del config["streams"][2] + + config = ss.load_sender_config(_profile(tmp_path, head_and_left)) + assert [one.stream_id for one in ss.sender_streams(config)] == ["head", "left_wrist"] + assert [one.index for one in ss.sender_streams(config)] == [0, 1] + with pytest.raises(ss.StartupError, match="'head' and 'left_wrist' have no camera role"): + ss.stream_tracks(["head", "left_wrist"], {}) + + +# --- stopping ---------------------------------------------------------------------------------------------------- + + +def test_the_three_camera_stack_is_stopped_last_started_first_each_child_gone_before_the_next_is_signalled( + tmp_path: Path, monkeypatch +): + events, ready, started = tmp_path / "events", [], [] + real_sleep, real_start = time.sleep, ss.Stack.start + + def start_a_real_child(self, name, command, env=None, cwd=None, grace_s=ss.DEFAULT_GRACE_S, **flags): + # A real process stands in for each program, so the launcher's own stop is what ends it. + ready.append(tmp_path / f"{name}.ready") + stand_in = [sys.executable, "-c", one_camera.POLITE_CHILD, name, str(events), str(ready[-1])] + started.append(name) + return real_start(self, name, stand_in, grace_s=grace_s, **flags) + + def interrupt_once_every_child_is_up(_seconds): + deadline = time.monotonic() + 20 + while not all(path.exists() for path in ready): + assert time.monotonic() < deadline, "a stand-in never became ready" + real_sleep(0.02) + # Once: the stop that follows waits on its children with the same clock. + monkeypatch.setattr(ss.time, "sleep", real_sleep) + raise KeyboardInterrupt + + class Done: + returncode = 0 + + class Timesync: + lan_address_toward = staticmethod(lambda host: "192.0.2.1") + reference_id_for = staticmethod(lambda host: "C000020A") + + workdir = tmp_path / "run" + workdir.mkdir() + frontend = tmp_path / "built.html" + frontend.write_text("") + # As the recorded runs are set up, without their stand-ins for starting and stopping a child. + monkeypatch.setattr(ss.signal, "signal", lambda *_: None) + monkeypatch.setattr(ss.tempfile, "mkdtemp", lambda **_: str(workdir)) + monkeypatch.setattr(ss, "FRONTEND_INDEX", frontend) + monkeypatch.setattr(ss.Stack, "start", start_a_real_child) + monkeypatch.setattr(ss.Stack, "wait_until", lambda *_, **__: None) + monkeypatch.setattr(ss, "ensure_receiver_environment", lambda: None) + monkeypatch.setattr(ss.subprocess, "run", lambda command, **_: Done()) + monkeypatch.setattr(ss, "run_supervised", lambda _stack, command: 0) + monkeypatch.setattr(ss, "load_timesync_tool", lambda _path: Timesync) + monkeypatch.setattr(ss.time, "sleep", interrupt_once_every_child_is_up) + assert ss.main(_argv(_profile(tmp_path), "--no-rectify")) == 0 + assert started == ["sender", "livekit", "capture-server", "backend", "receiver", "bridge", "timesync-follower"] + lines = [line.split() for line in events.read_text().splitlines()] + assert [(name, what) for name, what, _stamp in lines] == [ + (name, what) for name in reversed(started) for what in ("int", "exit") + ] + stamps = [float(stamp) for _name, _what, stamp in lines] + assert stamps == sorted(stamps) + + +def test_the_help_says_how_several_streams_are_given_their_roles(capsys): + with pytest.raises(SystemExit): + ss.parse_args(["--help"]) + text = " ".join(capsys.readouterr().out.split()) + assert "with more than one stream each needs its role" in text + assert "every stream" in text diff --git a/examples/egocap/tools/start_system.py b/examples/egocap/tools/start_system.py index ac23614ffa..b2489339c4 100644 --- a/examples/egocap/tools/start_system.py +++ b/examples/egocap/tools/start_system.py @@ -20,14 +20,19 @@ unless ``--mock`` gives it synthetic tracking and cameras. ``--mock`` also replaces the Orin sender with a local mock sender (no ``--orin``), so nothing real is started; the receiver, bridge and page are the same. +A profile holds one mono stream for each station camera, up to one per camera role. They share one sender on +the Orin, one receiver and one bridge here; each has its own receiver output, LiveKit track and correction. A +profile's only stream is the head camera unless ``--stream-role`` says otherwise; with several streams each is +given its role with ``--stream-role STREAM=ROLE``, and none is guessed. + A bridged stream whose camera role the station's rectification plan switches on is corrected by the bridge: the -launcher plans it for the picture the bridge receives, writes the remap table into its run directory and starts -the bridge with the table. A plan with an oversample has the table make a picture that many times the chosen -size a side, and the bridge shrink it by the same number afterwards, so the published picture is the chosen -size either way. A plan that cannot be built stops the start; ``--no-rectify`` starts with none. The -streams state it writes into the run directory tells the backend what 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. +launcher plans it for the picture the bridge receives, from that role's own calibration, writes the remap table +into its run directory and starts the bridge with the table. A plan with an oversample has the table make a +picture that many times the chosen size a side, and the bridge shrink it by the same number afterwards, so the +published picture is the chosen size either way. A plan that cannot be built for any camera stops the start; +``--no-rectify`` starts with none. The streams state it writes into the run directory tells the backend what +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``, @@ -129,6 +134,15 @@ FRONTEND_INDEX = EGOCAP_ROOT / "frontend" / "dist" / "index.html" # The camera role a single bridged stream fills unless --stream-role says otherwise: the camera on the headset. HEAD_ROLE = "ego" +# 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) +# 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. +ROLE_TRACKS = {HEAD_ROLE: HEAD_TRACK, "wrist_left": "sensing-wrist-left", "wrist_right": "sensing-wrist-right"} +# What a value of a sender profile holds while it stands for one the station has yet to fill in. +PLACEHOLDER_MARK = "PLACEHOLDER" # The streams state's name in the run directory. The backend is given the whole path in the environment and reads # the file once, since the bridge takes its arguments only at start. STREAMS_STATE_FILE = "streams_state.json" @@ -174,25 +188,45 @@ def publisher_token(key: str, secret: str, room: str, identity: str, hours: int return f"{header}.{body}.{signature}" -def streams_yaml( - url: str, room: str, publisher: str, track: str, width: int, height: int, fps: int, basis: str, name: str +def descriptor_yaml( + url: str, room: str, publisher: str, basis: str, fps: int, cameras: Sequence[tuple[str, str, tuple[int, int]]] ) -> str: - """The CaptureServer ``--livekit-streams`` file for one camera published by the bridge.""" - # Dumped from a mapping because the stream name comes from a user-edited profile. + """The CaptureServer ``--livekit-streams`` file for the cameras the bridge publishes into one room. + + ``cameras`` gives each camera's name, its track and the size it is published at; ``fps`` is the one rate + the bridge runs every stream at. + """ + # Dumped from a mapping because the stream names come from a user-edited profile. descriptor = { "livekit": { "url": url, "room": room, "publisher": publisher, "timestamp_basis": basis, - "streams": [{"name": name, "track": track, "width": width, "height": height, "fps": fps}], + "streams": [ + {"name": name, "track": track, "width": size[0], "height": size[1], "fps": fps} + for name, track, size in cameras + ], } } return yaml.safe_dump(descriptor, sort_keys=False) -def receiver_yaml(host: str, port: int, socket_path: str, width: int, height: int, name: str) -> str: - """The camera receiver's config: connect to the sender and expose one mono stream over CUDA IPC.""" +def streams_yaml( + url: str, room: str, publisher: str, track: str, width: int, height: int, fps: int, basis: str, name: str +) -> str: + """The CaptureServer ``--livekit-streams`` file for one camera published by the bridge.""" + return descriptor_yaml(url, room, publisher, basis, fps, [(name, track, (width, height))]) + + +def receiver_config_yaml( + host: str, port: int, socket_path: str, streams: Sequence[tuple[str, tuple[int, int]]] +) -> str: + """The camera receiver's config: connect to the sender and expose each mono stream over CUDA IPC. + + ``streams`` gives each stream's name and picture size in the sender profile's order: the receiver knows a + stream by its place in the sender's list, and names its CUDA IPC output after the stream. + """ config = { "version": 1, "receiver": { @@ -205,23 +239,29 @@ def receiver_yaml(host: str, port: int, socket_path: str, width: int, height: in "ipc": {"socket_path": socket_path, "owner_name": "egocap_start_system", "queue_size": 1024}, "streams": [ { - "index": 0, + "index": index, "name": name, "type": "mono", - "width": width, - "height": height, + "width": size[0], + "height": size[1], "output_format": "nv12", "ring_depth": 6, "ipc": {"mono": name}, } + for index, (name, size) in enumerate(streams) ], } return yaml.safe_dump(config, sort_keys=False) +def receiver_yaml(host: str, port: int, socket_path: str, width: int, height: int, name: str) -> str: + """The camera receiver's config: connect to the sender and expose one mono stream over CUDA IPC.""" + return receiver_config_yaml(host, port, socket_path, [(name, (width, height))]) + + @dataclass(frozen=True) class SenderSettings: - """The effective sender values the rest of the stack must agree with.""" + """The effective sender values the rest of the stack must agree with, for one stream of the profile.""" port: int fps: int @@ -232,6 +272,8 @@ class SenderSettings: # The profile's output size; None leaves the sensor mode's native size, which --width and --height describe. width: int | None = None height: int | None = None + # The stream's place in the profile's list, which is how the sender's wire format and the receiver know it. + index: int = 0 def _section(parent: dict, key: str, path: Path) -> dict: @@ -244,81 +286,179 @@ def _section(parent: dict, key: str, path: Path) -> dict: return value +def placeholders(value: Any, where: str = "") -> list[str]: + """Where a loaded sender profile still holds a placeholder: the keys, in the file's order, whose value + carries ``PLACEHOLDER_MARK``. An example profile marks so every value that belongs to one station.""" + if isinstance(value, dict): + # A key is named the way the guides name it: section.key. + return [ + found + for key, inner in value.items() + for found in placeholders(inner, f"{where}.{key}" if where else str(key)) + ] + if isinstance(value, list): + # An item is named by its place, as the launcher's other messages name a stream. + return [found for index, inner in enumerate(value) for found in placeholders(inner, f"{where}[{index}]")] + # Only text can carry the mark: a number or a switch is a value somebody chose. + return [where] if isinstance(value, str) and PLACEHOLDER_MARK in value else [] + + def load_sender_config( path: Path, fps: int | None = None, bitrate_mbps: int | None = None, sender_port: int | None = None, ) -> dict: - """Read the checked-in sender profile and apply the command-line overrides to the loaded mapping. + """Read a sender profile and apply the command-line overrides to the loaded mapping. The bridge, the receiver and the CaptureServer descriptor are all built from the result, so one value - cannot differ between the sender and its consumers. + cannot differ between the sender and its consumers. A profile holds from one to ``MAX_STREAMS`` mono + streams; an override of the rate or the bitrate is every stream's. """ try: config = yaml.safe_load(path.read_text()) except (OSError, yaml.YAMLError) as error: raise StartupError(f"cannot read the sender config {path}: {error}; pass --sender-config") from error - if not isinstance(config, dict) or not isinstance(config.get("streams"), list) or len(config["streams"]) != 1: - raise StartupError(f"{path}: the launcher supports exactly one stream in the sender config") - stream = config["streams"][0] - if not isinstance(stream, dict): - raise StartupError(f"{path}: streams[0] must be a mapping") - # The receiver stream the launcher writes is mono, so another type would deploy a sender it cannot receive. - if stream.get("type") != "mono": - raise StartupError(f"{path}: the launcher supports only a mono stream, got type {stream.get('type')!r}") + # Asked of the file as it is written: an override on the command line does not make an example a station's. + unfilled = placeholders(config) + if unfilled: + raise StartupError( + f"{path.name} still holds placeholders ({', '.join(unfilled)}); replace each with this station's " + "value, which the comment beside it says where to find" + ) + streams = config.get("streams") if isinstance(config, dict) else None + # The sender refuses a profile without streams too, but only once it is deployed and started. + if not isinstance(streams, list) or not streams: + raise StartupError(f"{path.name} must hold a list of streams, from 1 to {MAX_STREAMS} mono streams") + # Each bridged stream is corrected as one camera role, and a station has no more roles than these. + if len(streams) > MAX_STREAMS: + raise StartupError( + f"{path.name} has {len(streams)} streams, and the launcher bridges at most {MAX_STREAMS}, one for " + f"each station camera role ({', '.join(ROLE_INTRINSICS)}); leave only the station's cameras in it" + ) + for index, stream in enumerate(streams): + if not isinstance(stream, dict): + raise StartupError(f"{path}: streams[{index}] must be a mapping") + # The receiver streams the launcher writes are mono, so another type would deploy a sender it cannot + # receive. Which stream is said only where there is more than one to mean. + if stream.get("type") != "mono": + which = f" for streams[{index}]" if len(streams) > 1 else "" + raise StartupError( + f"{path}: the launcher supports only a mono stream, got type {stream.get('type')!r}{which}" + ) network = _section(config, "network", path) - output = _section(stream, "output", path) - # An override replaces the profile's value; the profile stays the source of everything else. - if fps is not None: - output["fps"] = fps - if bitrate_mbps is not None: - output["bitrate_mbps"] = bitrate_mbps + for stream in streams: + output = _section(stream, "output", path) + # An override replaces the profile's value; the profile stays the source of everything else. + if fps is not None: + output["fps"] = fps + if bitrate_mbps is not None: + output["bitrate_mbps"] = bitrate_mbps if sender_port is not None: network["port"] = sender_port return config -def sender_settings(config: dict) -> SenderSettings: - """The values other components need from a loaded sender config, refusing one that cannot give a latency.""" +def sender_settings(config: dict, index: int = 0) -> SenderSettings: + """The values other components need from one stream of a loaded sender config, the first unless ``index`` + names another, refusing one that cannot give a latency.""" network = config.get("network", {}) - stream = config["streams"][0] + stream = config["streams"][index] output = stream.get("output", {}) # The deploy builds the SIPL backend only for a SIPL profile, and the bridge's range flag follows the backend, # so neither may be guessed from an `auto` or missing value. if config.get("capture_backend") not in ("sipl", "argus"): raise StartupError("the sender config must set capture_backend to sipl or argus") if not stream.get("id"): - raise StartupError("the sender config must set streams[0].id") + raise StartupError(f"the sender config must set streams[{index}].id") + # The id names the stream everywhere after the sender, which itself takes only a single value for it. + if isinstance(stream["id"], (list, dict)): + raise StartupError(f"the sender config's streams[{index}].id must be a name, not a list or a mapping") # The bridge and the descriptor need a number, and a native-rate profile (fps 0) has none until runtime. if not output.get("fps"): raise StartupError( - "the sender config must set streams[0].output.fps; the bridge and descriptor need a rate" + f"the sender config must set streams[{index}].output.fps; the bridge and descriptor need a rate" + ) + # The sender refuses a mono stream without exactly one camera, but only once it is deployed and started. + cameras = stream.get("cameras") + one_camera = isinstance(cameras, list) and len(cameras) == 1 and isinstance(cameras[0], dict) + if not one_camera or "device" not in cameras[0]: + raise StartupError( + f"the sender config must give streams[{index}] exactly one camera: cameras is a list of one entry " + "that names its device, since a mono stream has one camera" ) return SenderSettings( - port=int(network.get("port", 5000)), - fps=int(output["fps"]), - bitrate_mbps=int(output.get("bitrate_mbps", 0)), + port=_whole_number(network.get("port", 5000), "network.port", "from 1 to 65535", 1, 65535), + fps=_whole_number(output["fps"], f"streams[{index}].output.fps", "of frames a second", 1), + bitrate_mbps=_whole_number( + output.get("bitrate_mbps", 0), f"streams[{index}].output.bitrate_mbps", "of megabits a second", 0 + ), stream_id=str(stream["id"]), # SIPL produces full-range pictures; the bridge must say so or the encoded stream signals limited range. full_range=config["capture_backend"] == "sipl", sipl=config["capture_backend"] == "sipl", - width=_output_dimension(output, "width"), - height=_output_dimension(output, "height"), + width=_output_dimension(output, "width", index), + height=_output_dimension(output, "height", index), + index=index, ) -def _output_dimension(output: dict, key: str) -> int | None: +def _whole_number(value: Any, key: str, said: str, least: int, most: int | None = None) -> int: + """A whole number a sender profile states under ``key``, within its bounds; a startup error in a sentence + for anything else. The sender reads these values as unsigned whole numbers and refuses a fraction or a word, + but only once it is deployed and started.""" + # Digits written as text are a number to the sender's reader too; a switch and a fraction are not. + if isinstance(value, str) and value.isascii() and value.isdigit(): + value = int(value) + whole = isinstance(value, int) and not isinstance(value, bool) + if not whole or value < least or (most is not None and value > most): + raise StartupError(f"the sender config's {key} must be a whole number {said}, got {value!r}") + return value + + +def _output_dimension(output: dict, key: str, index: int) -> int | None: + """A stream's output width or height as the profile states it, None when it states none; a startup error + for a value that is no picture dimension.""" value = output.get(key) if value is None: return None if isinstance(value, bool) or not isinstance(value, int) or value <= 0: raise StartupError( - f"the sender config's streams[0].output.{key} must be a positive integer, got {value!r}" + f"the sender config's streams[{index}].output.{key} must be a positive integer, got {value!r}" ) return value +def sender_streams(config: dict) -> list[SenderSettings]: + """Every stream's settings of a loaded sender config, in the profile's order, which is the order the sender + numbers its streams in. A startup error for streams the chain cannot carry side by side.""" + streams = [sender_settings(config, index) for index in range(len(config["streams"]))] + names = [stream.stream_id for stream in streams] + # The receiver's outputs, the bridge's streams and the cameras of the streams state are all named by the id. + for name in names: + if names.count(name) > 1: + raise StartupError(f"the sender config names two streams {name!r}; give each stream an id of its own") + # One camera feeds one stream: the sender refuses a device named twice, after the deploy. A profile copied + # stream by stream keeps the first one's device unless it is changed. + devices: dict[str, str] = {} + for stream, described in zip(streams, config["streams"], strict=True): + device = str(described["cameras"][0]["device"]).strip() + if device in devices: + raise StartupError( + f"the sender config gives streams {devices[device]!r} and {stream.stream_id!r} the same camera " + f"(cameras[0].device {device}); give each stream the device of its own camera" + ) + devices[device] = stream.stream_id + # The bridge's --fps is one value for all its streams: its encoders and its read deadlines follow it. + if len({stream.fps for stream in streams}) > 1: + rates = ", ".join(f"{stream.stream_id!r} {stream.fps}" for stream in streams) + raise StartupError( + f"the sender config's streams run at different rates ({rates} fps) and the camera bridge takes one " + "rate for all of them; set the same output.fps on every stream, or pass --fps" + ) + return streams + + def frame_size(settings: SenderSettings, width: int | None, height: int | None) -> tuple[int, int]: """The picture size the sender delivers: the profile's output size when it sets one, else the sensor's. @@ -329,7 +469,9 @@ def frame_size(settings: SenderSettings, width: int | None, height: int | None) if flag is not None and flag <= 0: raise StartupError(f"{name} must be positive, got {flag}") if (settings.width is None) != (settings.height is None): - raise StartupError("the sender config must set both streams[0].output.width and height, or neither") + raise StartupError( + f"the sender config must set both streams[{settings.index}].output.width and height, or neither" + ) if settings.width is not None: for name, flag, value in (("--width", width, settings.width), ("--height", height, settings.height)): if flag is not None and flag != value: @@ -342,16 +484,41 @@ def frame_size(settings: SenderSettings, width: int | None, height: int | None) return size +def stream_sizes( + streams: Sequence[SenderSettings], width: int | None, height: int | None +) -> list[tuple[int, int]]: + """The picture size each stream of the profile delivers, by ``frame_size``, in the profile's order. + + The sensor size the launcher assumes for a profile's only stream is one camera's. Among several streams + none is assumed: each states its size, or --width and --height together give the size of all that do not. + """ + for settings in streams: + # One flag alone would leave the other dimension to the head camera's default. + unsized = settings.width is None and settings.height is None + if len(streams) > 1 and unsized and (width is None or height is None): + raise StartupError( + f"the sender config must set streams[{settings.index}].output.width and height: with more than " + "one stream each states the size of its own picture; or pass --width and --height when every " + "camera sends the same size" + ) + return [frame_size(settings, width, height) for settings in streams] + + +def mock_sender_streams_command( + python: str, script: Path, streams: Sequence[SenderSettings], sizes: Sequence[tuple[int, int]] +) -> list[str]: + """The local mock sender that stands in for the Orin: an HEVC stream shaped like each real one, in the + profile's order, which is the order the receiver config lists them in.""" + command = [python, str(script), "--port", str(streams[0].port)] + # One --stream for each, in order: the mock numbers its streams as it is given them, as the sender does. + for settings, (width, height) in zip(streams, sizes, strict=True): + command += ["--stream", f"{settings.stream_id}:{width}x{height}@{settings.fps}"] + return command + + def mock_sender_command(python: str, script: Path, settings: SenderSettings, width: int, height: int) -> list[str]: """The local mock sender that stands in for the Orin: one HEVC stream shaped like the real one.""" - return [ - python, - str(script), - "--port", - str(settings.port), - "--stream", - f"{settings.stream_id}:{width}x{height}@{settings.fps}", - ] + return mock_sender_streams_command(python, script, [settings], [(width, height)]) def bridge_timing_arguments( @@ -423,7 +590,8 @@ def bridge_stream_name(name: str) -> str: def stream_roles(pairs: Sequence[str], streams: Sequence[str]) -> dict[str, str]: """The station camera role of each bridged stream, from the ``--stream-role STREAM=ROLE`` values. - With none given a single stream is the head camera. A stream left out has no role and is not rectified. + With none given a single stream is the head camera. A stream left out has no role here; ``stream_tracks`` + refuses one among several, so that no stream is corrected as a camera nobody said it is. """ # The default profile's one camera sits on the headset; any other arrangement is said outright. if not pairs: @@ -446,6 +614,59 @@ def stream_roles(pairs: Sequence[str], streams: Sequence[str]) -> dict[str, str] return roles +def _listed(names: Sequence[str]) -> str: + """Stream names as a sentence lists them: 'a', 'a' and 'b', 'a', 'b' and 'c'.""" + quoted = [repr(name) for name in names] + return quoted[0] if len(quoted) == 1 else f"{', '.join(quoted[:-1])} and {quoted[-1]}" + + +def stream_tracks(streams: Sequence[str], roles: Mapping[str, str]) -> dict[str, str]: + """The LiveKit track each stream of the profile is published as, by stream name. + + A profile's only stream keeps the head track whatever its role. Among several streams each takes its + role's track, and a stream without a role is a startup error: a role taken from a stream's name or its place + in the profile could be the wrong one, and a wrist picture corrected with the head's lens still looks like one. + """ + # The track a one-stream start has always published, which its streams file and its recordings name. + if len(streams) == 1: + return {streams[0]: HEAD_TRACK} + without = [stream for stream in streams if stream not in roles] + if without: + raise StartupError( + f"the sender config has {len(streams)} streams and {_listed(without)} " + f"{'has' if len(without) == 1 else 'have'} no camera role; pass --stream-role STREAM=ROLE for each, " + f"with ROLE one of {', '.join(ROLE_INTRINSICS)}" + ) + return {stream: ROLE_TRACKS[roles[stream]] for stream in streams} + + +def report_streams(streams: Sequence[BridgedStream]) -> None: + """Print each stream's camera role, picture size and track for a profile that holds several, to be held + against the cabling: streams given each other's roles are corrected with each other's lenses.""" + # A profile's only stream has nothing to be mistaken for. + if len(streams) < 2: + return + for stream in streams: + width, height = stream.source_size_wh + print(f"stream {stream.name!r}: {stream.role}, {width}x{height}, track {stream.track}") + + +def report_sender(path: Path, streams: Sequence[SenderSettings], release: str) -> None: + """Print the rate and the bitrate the sender runs with, and for several streams what they add up to: they + share the one link between the Orin and this PC.""" + first = streams[0] + # A profile's only stream is the whole of what the link carries. + if len(streams) == 1: + print(f"sender config {path}: {first.fps} fps, {first.bitrate_mbps} Mbit/s, release {release}") + return + each = ", ".join(f"{stream.stream_id!r} {stream.bitrate_mbps}" for stream in streams) + total = sum(stream.bitrate_mbps for stream in streams) + print( + f"sender config {path}: {len(streams)} streams at {first.fps} fps, {total} Mbit/s in all ({each}), " + f"release {release}" + ) + + def enabled_rectifications(directory: Path) -> dict[str, Mapping[str, Any]]: """The entries of the station's rectification plan that are switched on, by camera role. @@ -463,12 +684,13 @@ def enabled_rectifications(directory: Path) -> dict[str, Mapping[str, Any]]: def plan_stream_rectification( - stream: BridgedStream, entry: Mapping[str, Any], directory: Path, run_dir: Path + stream: BridgedStream, entry: Mapping[str, Any], directory: Path, run_dir: Path, several: bool = False ) -> StreamRectification: """Plan one stream's rectification from its role's installed intrinsics and write its table into ``run_dir``. Every refusal, of the calibration, of the geometry or of the table file, is a startup error carrying the - library's reason: nothing falls back to uncorrected video. + library's reason: nothing falls back to uncorrected video. ``several`` says more than one stream is bridged: + a lens file that names no camera is then refused, where for a profile's only stream it is warned of. """ calibration = ROLE_INTRINSICS[stream.role] table = run_dir / f"rectify_{stream.role}{REMAP_TABLE_SUFFIX}" @@ -482,6 +704,15 @@ def plan_stream_rectification( elsewhere = other_camera_problem(intrinsics.record, stream.name, calibration) if elsewhere is not None: raise StartupError(f"{what}: {elsewhere}, or {_NO_RECTIFY_HINT}") + # Among several cameras a file that names none cannot be told from another camera's: streams given + # each other's roles would each be corrected with the other's lens, and nothing else would notice. + unnamed = camera_stamp_note(intrinsics.record, calibration) + if several and unnamed is not None: + raise StartupError( + f"{what}: {unnamed}, and with more than one camera bridged it could be another camera's lens; " + "solve this camera's lens again from the page so that the file names its camera, or bridge this " + f"camera alone, or {_NO_RECTIFY_HINT}" + ) # A lens solved on a stream the bridge had shrunk says by how much in its stream stamp. The planner takes # that number, or an exact match of the sizes, and guesses no other relation between them. plan = plan_rectification( @@ -515,13 +746,36 @@ def plan_stream_rectification( f"its way to the disk; start again, or {_NO_RECTIFY_HINT}" ) record = {**plan.metadata(calibration_file=calibration, calibration_sha256=digest), "table": facts} - # A lens file from another tool carries no camera name, so the check above had nothing to compare. The - # correction is applied, and the operator is told it rests on the file being this camera's. - unnamed = camera_stamp_note(intrinsics.record, calibration) + # A lens file from another tool carries no camera name, so the check above had nothing to compare. For a + # profile's only stream the correction is applied, and the operator is told it rests on the file being + # this camera's. warnings = plan.warnings if unnamed is None else (*plan.warnings, unnamed) return StreamRectification(table, plan.size_wh, plan.geometry.oversample, record, warnings) +def refuse_one_lens_for_two_cameras(streams: Sequence[BridgedStream], directory: Path) -> None: + """Refuse to correct two bridged streams from calibration files that are one file by their content: a lens + file copied under a second role's name describes one of the two cameras and bends the other's picture. + + Asked before any stream is planned, of the files' bytes alone. A file that cannot be read is left to the + planning of its own stream, which says so in its own sentence. + """ + seen: dict[str, BridgedStream] = {} + for stream in streams: + try: + digest = hashlib.sha256((directory / ROLE_INTRINSICS[stream.role]).read_bytes()).hexdigest() + except OSError: + continue + other = seen.setdefault(digest, stream) + if other is not stream: + raise StartupError( + f"cannot rectify streams {other.name!r} and {stream.name!r} (roles {other.role} and " + f"{stream.role}): {ROLE_INTRINSICS[other.role]} and {ROLE_INTRINSICS[stream.role]} are the same " + "file, and one lens is not two cameras'; calibrate each camera's own lens from the page, or " + f"{_NO_RECTIFY_HINT}" + ) + + def plan_rectifications( streams: Sequence[BridgedStream], directory: Path, run_dir: Path ) -> dict[str, StreamRectification]: @@ -531,6 +785,7 @@ def plan_rectifications( is a startup error. """ enabled = enabled_rectifications(directory) + refuse_one_lens_for_two_cameras([stream for stream in streams if stream.role in enabled], directory) planned: dict[str, StreamRectification] = {} for stream in streams: entry = enabled.get(stream.role) @@ -538,7 +793,9 @@ def plan_rectifications( if entry is None: print(f"stream {stream.name!r}: published as received; no rectification is switched on for it") continue - rectification = planned[stream.name] = plan_stream_rectification(stream, entry, directory, run_dir) + rectification = planned[stream.name] = plan_stream_rectification( + stream, entry, directory, run_dir, several=len(streams) > 1 + ) source, output = stream.source_size_wh, rectification.output_size_wh across, down = rectification.record["field_of_view_deg"] made = rectification.record["table_size_wh"] @@ -953,20 +1210,25 @@ def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: parser.add_argument("--release", default="egocap-start", help="release name for the Orin deploy") parser.add_argument("--skip-deploy", action="store_true", help="reuse the release named by --release") parser.add_argument( - "--sender-config", type=Path, default=DEFAULT_SENDER_CONFIG, help="sender profile uploaded to the Orin" + "--sender-config", + type=Path, + default=DEFAULT_SENDER_CONFIG, + help=f"sender profile uploaded to the Orin: from one to {MAX_STREAMS} mono streams, one for each camera", ) parser.add_argument("--station-config", type=Path, default=DEFAULT_STATION_CONFIG) parser.add_argument( "--width", type=int, - help="sensor width when the profile sets no output size (default 2560); the receiver expects it and the " - "descriptor declares it divided by the bridge shrink, or the rectified width", + help="sensor width when the profile sets no output size (default 2560 for a profile's only stream; among " + "several, of every stream that sets none); the receiver expects it and the descriptor declares it divided " + "by the bridge shrink, or the rectified width", ) parser.add_argument( "--height", type=int, - help="sensor height when the profile sets no output size (default 1984); the receiver expects it and the " - "descriptor declares it divided by the bridge shrink, or the rectified height", + help="sensor height when the profile sets no output size (default 1984 for a profile's only stream; " + "among several, of every stream that sets none); the receiver expects it and the descriptor declares it " + "divided by the bridge shrink, or the rectified height", ) parser.add_argument( "--stream-role", @@ -974,8 +1236,8 @@ def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: default=[], metavar="STREAM=ROLE", help=f"the station camera role a bridged stream fills ({', '.join(ROLE_INTRINSICS)}), which decides the " - "calibration and the rectification choice applied to it; repeatable (default: the sender profile's stream " - f"is {HEAD_ROLE})", + "calibration and the rectification choice applied to it; repeatable (default: a profile's only stream is " + f"{HEAD_ROLE}; with more than one stream each needs its role, and none is guessed)", ) parser.add_argument( "--no-rectify", @@ -983,8 +1245,12 @@ def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: help="publish the video as received even where the station's rectification plan corrects it, as " "calibrating a camera's lens needs", ) - parser.add_argument("--fps", type=int, help="override the profile's output.fps") - parser.add_argument("--bitrate-mbps", type=int, help="override the profile's HEVC bitrate") + parser.add_argument("--fps", type=int, help="override output.fps of every stream of the profile") + parser.add_argument( + "--bitrate-mbps", + type=int, + 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( "--timesync-tool", @@ -1043,7 +1309,7 @@ def main(argv: Sequence[str] | None = None) -> int: """Bring the stack up in dependency order, print how to use it, then wait until interrupted.""" args = parse_args(argv) orin_host = args.orin.rsplit("@", 1)[-1] if args.orin else None - room, publisher, track = "egocap-room", "egocap-bridge", "sensing-head" + room, publisher = "egocap-room", "egocap-bridge" livekit_url = "ws://127.0.0.1:7880" workdir = Path(tempfile.mkdtemp(prefix="egocap-start-")) ipc_socket = str(workdir / "camera_receiver.sock") @@ -1075,21 +1341,29 @@ def main(argv: Sequence[str] | None = None) -> int: basis = MOCK_TIMESTAMP_BASIS if args.mock else TIMESTAMP_BASIS # One loaded profile is the source for the sender, the receiver, the bridge and the descriptor. sender_config = load_sender_config(args.sender_config, args.fps, args.bitrate_mbps, args.sender_port) - sender = sender_settings(sender_config) - width, height = frame_size(sender, args.width, args.height) + senders = sender_streams(sender_config) + # What the streams share: the sender's port and backend, and the one rate the bridge runs them all at. + sender = senders[0] + sizes = stream_sizes(senders, args.width, args.height) # The bridge identifies the Orin's chrony by the reference id of its IPv4 address. if args.orin: try: ipaddress.IPv4Address(orin_host) except ValueError as error: raise StartupError(f"--orin needs an IPv4 address for the Orin, got {orin_host!r}") from error - # The profile's stream is the one the chain bridges; without the chain nothing is bridged or rectified. - # A name the bridge cannot take is refused here, not by the bridge once everything else is up. + # The profile's streams are the ones the chain bridges; without the chain nothing is bridged or + # rectified. A name the bridge cannot take is refused here, not by the bridge once everything else is up. + names = [one.stream_id for one in senders] if chain: - bridge_stream_name(sender.stream_id) - roles = stream_roles(args.stream_role, [sender.stream_id]) - stream = BridgedStream(sender.stream_id, track, (width, height), roles.get(sender.stream_id)) - bridged = [stream] if chain else [] + for name in names: + bridge_stream_name(name) + roles = stream_roles(args.stream_role, names) + tracks = stream_tracks(names, roles) + streams = [ + BridgedStream(name, tracks[name], size, roles.get(name)) + for name, size in zip(names, sizes, strict=True) + ] + bridged = streams if chain else [] # Resolved once, here. The backend is started in another directory, where a relative path would name # another place: the page would then save a plan this launcher never reads. station_calibration = calibration_dir().resolve() @@ -1100,38 +1374,35 @@ def main(argv: Sequence[str] | None = None) -> int: glove_calibration = glove_dir.resolve() # Planned before anything is started, so a plan that cannot be built stops a stack that is not yet up. rectifications: dict[str, StreamRectification] = {} + report_streams(bridged) if bridged and args.no_rectify: print("rectification is off (--no-rectify): the video is published as received") elif bridged: rectifications = plan_rectifications(bridged, station_calibration, workdir) - published = published_size(stream, rectifications.get(stream.name)) write_streams_state( workdir / STREAMS_STATE_FILE, published_cameras(bridged, rectifications), no_rectify=args.no_rectify ) (workdir / "sender.yaml").write_text(yaml.safe_dump(sender_config, sort_keys=False)) + # Each camera is declared at the size the bridge publishes it at, which is the size recorded. + declared = [(one.name, one.track, published_size(one, rectifications.get(one.name))) for one in streams] (workdir / "streams.yaml").write_text( - streams_yaml( - livekit_url, - room, - publisher, - track, - published[0], - published[1], - sender.fps, - basis, - sender.stream_id, - ) + descriptor_yaml(livekit_url, room, publisher, basis, sender.fps, declared) ) (workdir / "receiver.yaml").write_text( - receiver_yaml(orin_host or "127.0.0.1", sender.port, ipc_socket, width, height, sender.stream_id) + receiver_config_yaml( + orin_host or "127.0.0.1", + sender.port, + ipc_socket, + [(one.name, one.source_size_wh) for one in streams], + ) ) if args.mock: - print(f"mock sender: {sender.fps} fps stream {sender.stream_id!r}, timestamps are frame-ready time") + # The mock sends every stream of the profile, at the one rate they share. + said = "stream" if len(names) == 1 else "streams" + listed = ", ".join(repr(name) for name in names) + print(f"mock sender: {sender.fps} fps {said} {listed}, timestamps are frame-ready time") else: - print( - f"sender config {args.sender_config}: {sender.fps} fps, {sender.bitrate_mbps} Mbit/s, " - f"release {args.release}" - ) + report_sender(args.sender_config, senders, args.release) if args.orin: stop_at = time.strftime("%H:%M:%S", time.localtime(time.time() + args.seconds)) print(f"the Orin sender stops after {args.seconds} s (about {stop_at}), which stops this stack") @@ -1193,13 +1464,13 @@ def main(argv: Sequence[str] | None = None) -> int: mock_sender = None if chain and args.mock: mock_sender = stack.start( - "mock-sender", mock_sender_command(python, args.mock_sender, sender, width, height) + "mock-sender", mock_sender_streams_command(python, args.mock_sender, senders, sizes) ) # 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) - # 3. CaptureServer announces the stream and serves tracking. + # 3. CaptureServer announces the streams and serves tracking. capture = stack.start( "capture-server", [ @@ -1249,7 +1520,7 @@ def main(argv: Sequence[str] | None = None) -> int: stack.wait_until( backend, lambda: port_open("127.0.0.1", args.backend_port), f"listening on {args.backend_port}", 60 ) - # 5. The receiver decodes the sender's stream; the bridge republishes it into the LiveKit room. + # 5. The receiver decodes the sender's streams; the bridge republishes each into the LiveKit room. if chain: if mock_sender is not None: # Building the mock's test streams with ffmpeg can take a while on the first run. @@ -1286,6 +1557,9 @@ def main(argv: Sequence[str] | None = None) -> int: ), ], ) + # The sender and the bridge are not waited on, so one that has exited by now is said here, in place of + # an announcement that the page is up. + raise_if_a_child_exited(stack) url = f"http://127.0.0.1:{args.backend_port}/" token = control_token(backend.log) print(f"\nEgo Capture is up at {url}\nrecording control token: {token}\nlogs: {workdir}")