Compare commits

...
107 Commits
Author SHA1 Message Date
DeeJanuzandClaude Opus 5.5 06f2dd63c1 FrameDrop: proof of concept for installing Frametop from FrameDrop (#25)
FrameDrop sideloads a Linux zip as a Steam Devkit Game. Frametop can't be
copied over as an app, so the zip holds a small installer: playing it runs
get.sh --yes in a transient user service (Steam reaps the title's process
tree on quit) and shows progress in a GTK window.

- probe/probe.sh records what a Devkit Game can reach. On SteamOS 0.3.0 it
  runs on the host with git, podman, systemd and GTK, even with the SLR4
  compat tool set; inside SLR4, flatpak-spawn --host reaches the host.
- devkit.sh registers a folder the way FrameDrop does (Valve's devkit-utils),
  for testing without a PC.
- build.sh makes a reproducible Frametop.zip and the FrameDrop manifest.

Nothing is published. Open: whether FrameDrop keeps the exec bit, and its
start command and runtime choice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 21:19:30 -06:00
DeeJanuzandClaude Opus 5.5 ec870d2d7a Merge branch laser-release (release a held button that can't come up on a screen: the game kept losing its controllers) into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 09:37:46 -06:00
DeeJanuzandClaude Opus 5.5 80797c98b9 Screens: release a held button that can't come up on a screen
Pausing, or hiding the screen a button went down on, took the laser off
it mid-click; the pause gesture's second thumbstick click does that.
SteamVR's laser mouse then forgot the button ("Mouse down count is 1 but
states are all false"), no release came, and the catcher kept showing
whenever the pressing laser was off the panels, even while paused. Being
interactive, it kept the VR game's controllers from it until the
desktop restarted (2026-10-04, Beat Saber).

ft-screens now releases a held button when it's paused, when the screen
it went down on is hidden, or, during VR games, when the pressing hand
controller has held nothing for a second. GetControllerState answers
overlay apps only while a game runs; outside games a hold is never cut.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 09:31:27 -06:00
DeeJanuzandClaude Opus 5.5 2fadbbe148 Merge branch orphan-panel (bring back a taskbar saved on a screen the desktop doesn't have, #18) into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 08:42:12 -06:00
DeeJanuzandClaude Opus 5.5 5ee07f99a8 Merge branch menu-entry-programs (Hide/Show Screens no longer launches Reset Screen Layout) into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 08:39:44 -06:00
John MurrayandClaude Opus 5.5 f0b93b79d3 Menu entries: own programs for Reset Screen Layout and Hide/Show Screens
Reset Screen Layout and Hide/Show Screens both ran ft-layout. Steam lists
entries by program, so Hide/Show launched Reset. Each gets a wrapper.

From PR #17 (only this part of 9618be8; its host_command change is for the
Nix packages).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 08:39:40 -06:00
DeeJanuzandClaude Opus 5.5 13a530d829 Merge branch mute-key (PR #24: the mute key toggles the default output's mute) into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 08:36:44 -06:00
DeeJanuzandClaude Opus 5.5 f260a6a9e4 Merge branch lazy-susan (PR #22: Meta+Alt+Tab spins the panels around you) into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 08:36:44 -06:00
DeeJanuzandClaude Opus 5.5 2e09cf9efe Merge PR #24 (SuperTuxii: the mute key toggles the default output's mute) into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 08:36:33 -06:00
DeeJanuzandClaude Opus 5.5 9a4b66ff50 keys-test: the spin bindings (Meta+Alt+Tab, Meta+Alt+Shift+Tab), not while paused
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 08:36:33 -06:00
DeeJanuzandClaude Opus 5.5 17269134ce Merge PR #22 (ehippy: lazy susan, Meta+Alt+Tab spins the panels around you) into experimental
Conflicts with experimental's pause_toggle, steam_menu and command: actions and its
AnnounceOverlay: both kept. The spin bindings join the Meta tap in the defaults, spinning
doesn't need pointer mode, and like other actions it does nothing while Frametop is paused.
AnnounceOverlay now sends through the PR's SendPointer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 08:36:33 -06:00
DeeJanuzandClaude Opus 5.5 d995b815f8 Session: bring back a taskbar saved on a screen the desktop doesn't have
Plasma 6.2.5 keeps a panel on a screen number and never moves one whose
number is past the screen count, so a taskbar saved on a spare output
(#18, lastScreen=8 with three screens) or on a screen a smaller layout
dropped stayed hidden. Before Plasma starts, session/fix-panels.py moves
such a panel and its tray's containment to screen 0 (the primary),
keeping its widgets, unless screen 0 already has a panel on that edge.
doctor.sh checks the panels' screens, and report.sh lists them with the
live outputs and panels.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 08:32:04 -06:00
SuperTuxii f18918f781 input-relay: Add mute key as volume key
Add KEY_MUTE as volume key. It will be mapped to KEY_MACRO28 and
use wpctl to toggle the mute of the default audio sink. The toggle of
the mute state will be done once when the key is pressed instead of
continuously toggling it when it is held down.
This allows the mute button on keyboards to work properly.

Signed-off-by: SuperTuxii <123881249+SuperTuxii@users.noreply.github.com>
2026-10-04 16:06:37 +02:00
DeeJanuzandClaude Opus 5.5 e0208687b6 Merge branch tip-in-games (controller laser tip found during VR games) into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 21:33:49 -06:00
DeeJanuzandClaude Opus 5.5 c699e13104 Screens: find the controllers' laser tip during VR games too
GetComponentStateForDevicePath with no input source handle fails for
every render model component while a VR game runs (checked 2026-10-03
with a game up: all 21 components of frame_controller_right). TipOffset
then fell back to the controller's pose, which aims 40 degrees above the
Frame controller's laser. In games, pointing at a screen's middle missed
it and pointing below it hit, so the new aim-to-laser only worked from
the bottom; the controls' reveal and pin/roll aim were off the same way.
GetComponentState still answers then, with the same tip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 21:33:49 -06:00
DeeJanuzandClaude Opus 5.5 9b12b7d74e Merge branch aim-lasers (in games, pointing a controller at a Frametop panel turns its laser on) into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 21:27:49 -06:00
DeeJanuzandClaude Opus 5.5 c7c7c1f772 Screens: in games, pointing a controller at a panel turns its laser on
SteamVR's own floating windows take the laser while a controller points
at them in a game and give it back when it points away. Frametop's
panels didn't: with the controllers left to the game (outside_games, the
default, or dashboard), they couldn't be clicked without the dashboard.

ft-screens now sets MakeOverlaysInteractiveIfVisible on a screen or
floating window while a hand controller's laser pose meets it, its
controls, or its popups (UpdateAim; curved screens hit on their
cylinder), and clears it 0.3 s after the aim leaves a wider margin. A
drag or a held button keeps it on. The keyboard, one overlay, uses
ComputeOverlayIntersection and now follows the mode when a game starts
or ends while it's open. This replaces the reset button's own aim zone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 21:27:49 -06:00
DeeJanuzandClaude Opus 5.5 2486a601e3 Merge branch click-threshold (controller click zone 32 px by default) into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 21:17:49 -06:00
DeeJanuzandClaude Opus 5.5 de25633f87 Click stability: 32 logical pixels by default, not 8
8 is about 0.2 degrees on a 3.4 m wide 3440-pixel screen 2 m away, so a
trigger press turned into a drag unless the hand was very still. 32
(about 0.9 degrees) felt much better in the headset (2026-10-03).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 21:17:49 -06:00
DeeJanuzandClaude Opus 5.5 53a1836dbb Merge branch reset-button (a reset button next to each screen's grab bar, clickable in VR games) into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 21:15:51 -06:00
DeeJanuzandClaude Opus 5.5 73bd0ea28f Screens: a reset button next to the grab bar, clickable in VR games
Each desktop screen gets a reset button left of its bar (a reticle). It
puts every screen back in its layout around where you are now, like
Meta+Shift+R (ft-layout apply).

In a VR game the screens leave the controllers to the game (the
outside_games and dashboard modes), so a controller couldn't click any
of their controls. Aiming a hand controller at the reset button now sets
MakeOverlaysInteractiveIfVisible on that button's overlay alone, so the
trigger clicks it; the flag clears half a second after the aim leaves a
zone twice as wide, and the game gets the controllers back. The aim
comes from the laser poses ft-screens already reads to show the controls.

The ft-layout spawn is now RunLayout(cmd), shared with the arrange.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 21:15:48 -06:00
DeeJanuzandClaude Opus 5.5 519c623ea9 Merge branch perf (dynamic per-screen frame rates, idle pointer, remote on demand, lighter gaze) into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 17:10:34 -06:00
DeeJanuzandClaude Opus 5.5 8b1327fe1a Merge branch hand-recorder (the hand dataset recorder) into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 14:35:37 -06:00
DeeJanuzandClaude Opus 5.5 2351cec310 hand recorder: final consent text (2026-10-03), residency check, installer
Consent 2026-10-03, after a non-lawyer review: who runs this and how to reach
them, the dataset is public (Hugging Face, possibly abroad), the Hugging Face
username shows next to the contributor id, purposes (no identification), safety,
the maintainer grant passes to whoever maintains Frametop next, withdrawal
before and after merge, rights such as the GDPR's, and what a new version means.
Residents of Illinois, Texas and Washington can't take part for now (biometric
privacy laws): a third checkbox, profile consent.region_ok, checked by
validate.py from this consent version on. The DRAFT banners are gone, so uploads
no longer need FT_HANDREC_ALLOW_UPLOAD.

hands/rec/install.sh installs the recorder on a Frame with Frametop: container
packages, hand tracking and panel builds, ft-camd's capabilities, menu entry.

test_qml_backend also checks each call's argument count against the slots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 14:35:18 -06:00
DeeJanuzandClaude Opus 5.5 1eb120e6b1 hand recorder export: no controller poses without controllers, nothing in deleted ranges
When the checklist says no controllers, exported poses.jsonl has left and right
null and feedback lines carry no controller state: controllers left switched on
still get tracked (one wandered 2 m in a real session) and would read as the
hands' ground truth. Poses and live-tracker feedback inside deleted ranges are
left out too, as the images there are.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 14:24:39 -06:00
DeeJanuzandClaude Opus 5.5 8321a99121 hand recorder: take.json keeps camera clock samples
sets.bin's capture_ns is CLOCK_MONOTONIC_RAW; poses.jsonl and prompts.jsonl are
CLOCK_MONOTONIC. On 2026-10-03 the two were 0.80 s apart during a session and
1.11 s apart five hours later, so images can't be paired with poses by
capture_ns. take.json now samples RAW minus MONOTONIC as each recording part
starts and stops (as ft-hands' raw_minus_mono_ns), so readers can put each
exposure on the poses' clock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 13:32:32 -06:00
DeeJanuzandClaude Opus 5.5 ea483f7ce3 hand recorder: log in from the Upload page, three-step page, no terminal
The Upload page is now three numbered steps: choose the export, log in to
Hugging Face, upload. Log in runs hub.py login, huggingface_hub's browser
login (OAuth device code, as hf auth login does): the link opens in the
browser and the page shows the code to enter, with Copy code and Cancel.
hub.py saves the token; the window never sees one, and nobody pastes one.

The terminal upload and the login command are gone from the page, and
UPLOAD.md is now a short 'About uploading' under the steps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 13:01:08 -06:00
DeeJanuzandClaude Opus 5.5 e62ebb8669 hand recorder: login command works from Frametop's Konsole
Frametop's Konsole sets XDG_RUNTIME_DIR=/run/user/UID/frametop, where podman finds
no container state, so 'distrobox enter dev -- hf auth login' failed with a crun
error. The command the Upload page shows now sets the real runtime folder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 12:48:17 -06:00
Patrick McDavidandClaude Opus 5.5 6fb168a8b8 Lazy susan: Meta+Alt+Tab spins the panels around you
- ft-screens "spin next|prev|<degrees>": every unpinned screen and
  floating window turns together about a vertical axis through your
  head (0.3 s, eased), so the next panel on the right or left comes to
  straight ahead; the arrangement stays as it is. Taps during a spin
  add to it, from where the panels are headed; grabbing a panel or
  placing it (ft-layout, ft-floatd) takes it out of the spin
- when a spin settles, the panel in front gets the pointer (recenter),
  typing (as after a click), and KWin's active window: its floating
  window, or the top window on a screen (ft-floatd "front N", the KWin
  script's activate-output). KWin's outputs follow the screens'
  new places (ft-layout scale), as after a move
- the input relay: spin_next and spin_prev actions, Meta+Alt+Tab and
  Meta+Alt+Shift+Tab by default; Frametop Input Settings lists them.
  Not Meta+Tab: that's Cmd+Tab on a Mac reached through a remote
  desktop like RustDesk, and the relay would take the Mac's app
  switcher. Meta+Alt+Tab (Cmd+Option+Tab) is unused on macOS,
  Windows, and KDE

Used on the Frame (SteamOS 0.3.0 build 20260922) with one screen and
three or four floating windows, through RustDesk to a Mac.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 10:17:22 -06:00
DeeJanuzandClaude Opus 5.5 8dbcdecf90 Hands: fix Export doing nothing, and show it's busy at once
af2ea7c put _stay_awake between exportSession and its @Slot, so the
window's Export button called a method QML couldn't see. A new test checks
every backend call in main.qml against Backend's slots and properties.
Export and Upload now say Exporting…/Uploading… with a spinner the moment
they're pressed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:29:04 -06:00
DeeJanuz b67c973f64 Merge branch perf-gaze into perf 2026-10-03 09:28:44 -06:00
DeeJanuzandClaude Opus 5.5 99aec84f62 Pointer: ft-screens announces new panels to the helper
The helper now reads SteamVR's list of panels every 20 s instead of every second, so a panel
made in between (a floating window's menu, frametop.float.N.sub.K, or the Frametop keyboard
the first time it opens) couldn't be clicked with the mouse until the next read. ft-screens
now sends "overlay <key>" to @ft_pointer_helper right after it makes one, and the helper adds
it to its list at once (only frametop.* keys). An older helper ignores it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:28:10 -06:00
DeeJanuzandClaude Opus 5.5 e44837cee6 Gaze: the hidden panel waits for a command instead of waking every 50 ms
The calibration panel runs for as long as the gaze service does, hidden nearly all the time,
and it woke 20 to 30 times a second to look at its socket and SteamVR's events: about 0.9% of
a core, the main cost left with gaze idle.

It now waits in poll() on its command socket: up to a second while hidden, and up to 10 ms
while shown, as before (it still drains SteamVR's events each pass, so a quit is acknowledged
within a second while hidden). A command wakes it at once, so "show" draws sooner than
before. With --watch-stdin, its stdin closing wakes it as well, so stopping it doesn't wait.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:28:02 -06:00
DeeJanuzandClaude Opus 5.5 95c5d056cf Gaze: ft-gaze's loop runs every 4 ms instead of 2
ft-gaze's loop slept 2 ms, so 500 times a second it read the head pose
(GetDeviceToAbsoluteTrackingPose), checked the eye tracker's counter, and drained SteamVR's
events, for samples that come 90 times a second.

It now sleeps 4 ms. A new sample is printed within 4 ms of appearing, 2 on average (was 1),
and the pose history still has a pose within 2 ms of any sample's time, which keeps the
head-pose error under 0.2 degrees for a head turning 100 degrees a second. Sleeping until
the next sample is due would have thinned the pose history to 11 ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:26:54 -06:00
DeeJanuz e6a931f7ee Merge branch perf-pointer into perf 2026-10-03 09:26:18 -06:00
DeeJanuzandClaude Opus 5.5 60667dba1f Pointer: don't put a vanished panel back in the visibility map
The panel-edge test read visible[edgeKey], and when the last panel the cursor touched was
gone from the overlay list, that added it back as hidden. The map then had more entries than
there are handles, which made the 50 ms visibility poll run every frame, and since the last
commit it also counted as a visibility change each time, so unchanged frames were never
reused. The edge test now looks the key up without adding it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:25:16 -06:00
DeeJanuzandClaude Opus 5.5 0c95d1d731 Gaze: ft-gaze prints and reads only the sources in use
ft-gaze computed and printed all six sources for every sample: about 1.3 KB of JSON a line
with our tracker (practice2), 120 KB a second through podman's stdio relay for ft-gazed to
json.loads 90 times a second. It also read SteamVR's gaze action for every sample outside
games (UpdateActionState and GetEyeTrackingDataRelativeToNow, two calls into vrserver, 180 a
second), though with our tracker ft-gazed only uses own and mmap1.

- ft-gaze takes --sources LIST (action, mmap1, mmap2, left, right, own, and eye for the EYE
  object; all by default, so the probe and ft-eyes-session are unchanged), and with
  --watch-stdin a line "sources LIST" on stdin switches them. A source left out isn't read
  and prints as {"ok":0} ("eye" as null), so every line keeps the same keys. An older
  ft-gaze ignores both, and prints everything as before.
- ft-gazed asks for what it reads: own,mmap1 with our tracker; left,right,mmap1 with
  SteamVR's eyes; the source plus mmap1 and mmap2 on the older one-source path. While a
  check or the calibration runs or waits to open, all of them, since checks record every
  source (the calibration fits the action's correction too) and the fit check reads "eye".
  It switches as soon as that changes, well inside the check's 0.45 s settle.
- So the action is read only during checks, or with --source action.

On recorded samples, a line with own and mmap1 is about 700 bytes instead of 1,300
(practice2), and one with left, right and mmap1 about 550 instead of 940 (test1).
gaze/test/idle-test.py now checks that ft-gaze starts with every source for a check and is
then switched to those in use, without the action or own; all its checks pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:23:53 -06:00
DeeJanuzandClaude Opus 5.5 fcb465a45a Input relay: send mouse motion at most every 4 ms
The relay sent the helper one "move" per SYN_REPORT, so a 1000 Hz mouse sent 1000 datagrams
a second to a helper whose loop runs every 8 ms, and each one went through a dozen sscanf
and strncmp tests in the helper before reaching the move handler. In a 200 ms test at
1000 Hz, 149 reports now make 45 moves with the same total.

flush() on a report now sends only once 4 ms have passed since the last move; tick() sends
the rest when due, and the select timeout shrinks to match. Buttons and the gaze
keys still flush first, unconditionally, so a click lands where the pointer was. In the
helper, "move" is now tested first in the command dispatch, and its handling is one lambda.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:23:47 -06:00
DeeJanuz d6930a61f5 Merge branch perf-session into perf 2026-10-03 09:22:07 -06:00
DeeJanuz 155deada52 Merge branch perf-screens into perf 2026-10-03 09:22:07 -06:00
DeeJanuzandClaude Opus 5.5 597551cf23 Pause gesture: look the controllers up every 30 s, not every 3 s
The gesture reader fetched vrserver's /input/getstate.json over HTTP every 3 seconds, the
whole time the relay runs, to notice a controller's root path changing when the 3D mouse
takes or gives back its hand role.

It now looks them up when it connects, when a message comes from a device path it doesn't
know (at most every 3 s; the device is read from the message with two string searches, not
a JSON parse of all 160 a second), 1.5 s after the relay's 3D mouse connects or lets go (the
relay tells it through GamePause.controllers_changed), and otherwise every 30 s. The keys
test's pause stub gets the new method.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:21:09 -06:00
DeeJanuzandClaude Opus 5.5 33fb3bb611 update-check: KWin's blur and contrast effect ids, retest hints
The session now turns KWin's blur and contrast effects off by id (blurEnabled and
contrastEnabled in the desktop's kwinrc), and a KWin that renamed them would quietly
leave them on. The check looks for their built-in factories (KWin::blur_factory,
KWin::contrast_factory) in kwin_wayland, which it already reads for --output-count,
and warns if one is gone. The kwin and plasma-workspace retest hints gain the blur and
the hidden autostart entries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:21:09 -06:00
DeeJanuzandClaude Opus 5.5 6cae2e0afe Remote Access: check the status every 5 s instead of every 2 s
While its window was open, Frametop Remote Access ran remote-ctl.sh status every 2 s,
and each run spawns bash, curl (the tailnet name from tailscaled) and python3 to parse
it. It now checks every 5 s, plus when the window comes to the front and once more 2 s
after turning remote access on or off or changing the password, so a change still
shows within a couple of seconds. A check doesn't start while one is still running.
Doing the check in-process would duplicate remote-ctl.sh's idea of "running", which
the session and the pause code share.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:20:32 -06:00
DeeJanuzandClaude Opus 5.5 af2ea7c0ee Hands: upload from the headset, then plug in and leave it
Export and upload are done in the headset now: the export page only notes
that VR may stutter a little. Upload opens the pull request first (a
draft) and shows its link, telling the person to plug in the headset and
leave it until it says Uploaded; the files then go to refs/pr/N, and the
pull request is marked open at the end. A retry of the same export goes on
in the same pull request. While an export or upload runs, a host unit holds
a logind sleep inhibitor so the Frame stays awake with the headset off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:20:00 -06:00
DeeJanuzandClaude Opus 5.5 060b4957f8 Eye tracker: ft-eyegrab checks only the slot each camera writes next
While copying, ft-eyegrab woke every 300 us (about 1,500 to 3,000 times a second) and
fingerprinted all eight slots each time: 8 x 256 strided reads from DMA-BUF memory.

- Each look now checks only the slot each camera writes next. The order is known (camera 0
  3,0,1,2; camera 1 7,5,4,6,5,7,6,4), and the next slot follows from the last two; the table
  starts from those orders and learns from every frame, so a SteamVR update that changes
  them costs a few seconds of full scans, not frames.
- A camera with nothing in its expected slot 1.5 frames after its last one, or with no
  order yet, gets all four slots checked, as before. A frame that turns up in an unexpected
  slot means full scans for that camera for 2 s.
- A slot's fingerprint is taken again when it stops being one of the two in use, so a later
  check sees only a new frame. A frame is still passed on when its camera starts the frame
  after next.
- Between frames it sleeps until 2.5 ms before the next is due, then looks every 1 ms, with
  0.5 ms of timer slack (PR_SET_TIMERSLACK, --share only). With no frames from either
  camera for 0.5 s (headset off) it looks every 4 ms.
- --rec keeps its 0.3 ms polls (and the expected-slot checks), for its timestamps.

Tested offline by building poll_frames against simulated cameras that write each frame in
four bursts, the last after the next frame starts (6 s, both cameras): 1,076 frames passed
on, none torn or skipped, with the known orders and with camera 1 in a different order.
Wakeups 1,486/s -> 207/s, the poller's CPU 3.6% -> 0.8% of a core (in plain memory; the real
DMA-BUF reads cost more), and a frame's start is seen 1.35 ms after it begins on average
instead of 0.76. With a camera stalling 15 ms every 2 s, the old poller passed on 22 torn
frames and the new one 8 or fewer.

Built (glibc 2.38 symbols at most, the host has 2.39), not installed: it runs as root from
/etc/frametop, so it takes effect only after gaze/tracker/install.sh (sudo).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:20:00 -06:00
DeeJanuzandClaude Opus 5.5 57617d4a14 ft-powerd: ask SteamVR every 100 ms, not on every input event
The loop polled the input devices with a 100 ms timeout and then, on every wake, did
SteamVR's part: PollNextEvent, the headset's activity level and every device's pose, all
IPC calls to vrserver. Input wakes it at once so the displays come on with the first
key or motion, but a moving mouse sends hundreds of events a second, so moving the mouse
meant hundreds of rounds of IPC a second instead of 10.

Every wake still drains the input devices and the control socket and counts input as
use straight away; SteamVR's part, and the backlight read that goes with it, now run
only when 100 ms have passed since the last time, and poll sleeps until then. Built in
the dev container (power/build.sh, no warnings); not run, since the live ft-powerd holds
@ft_powerd.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:19:49 -06:00
DeeJanuzandClaude Opus 5.5 83850bb1b7 Pointer driver: parse outside the lock, report only changes
Handle() held the state lock through a chain of up to a dozen sscanf calls per command, and
RunFrame, which vrserver calls every frame, takes the same lock, so a burst of commands
(about 116 poses a second, plus moves and buttons) could hold up vrserver's frame. Commands
are now parsed into locals first, and the lock is held only to store the result.

RunFrame also called UpdateBooleanComponent six times and UpdateScalarComponent twice every
frame, and TrackedDevicePoseUpdated every frame even while disconnected. Components now go to
SteamVR only when they change (all of them on the first frame). The pose still goes out every
frame while the device is connected, as a tracked device's should; the disconnected pose goes
out once. The helper now sends a pose only when it changes, so the comment says the driver
keeps the last one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:19:38 -06:00
DeeJanuzandClaude Opus 5.5 d5a15ebc36 Input relay: never block on the pointer helper's socket
The relay sent to @ft_pointer_helper on a blocking socket. When the helper stalled, a
layout placement or grabprobe holds it for seconds while ft-gazed keeps filling its socket at
90 Hz, the relay's one loop blocked with it: keyboards, the volume keys (which must never
reach gamescope), and pausing all stopped until the helper read again.

The socket is non-blocking now. A command the helper doesn't take (EAGAIN) waits in a queue,
and everything after it queues behind it so the order holds; tick() sends what it can on each
loop, and the select timeout drops to 20 ms while anything waits. Mouse moves add up into one
queued move. A scroll notch is dropped rather than queued, since scrolling seconds late is no
use; its release still goes. Presses, releases, show, hide, and the rest are kept, so no
button stays down. The queue holds at most 512 commands. While paused, the configured
pointer's queue still drains, so the releases and "hide" from standing down arrive. A
"vrbind" that hits a full socket is sent again on the next loop instead of being lost.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:18:43 -06:00
DeeJanuzandClaude Opus 5.5 b7dfe4759e Session: don't autostart Discover's notifier or IBus in the desktop
The nested Plasma session runs the system's XDG autostart entries. Discover's update
notifier (/etc/xdg/autostart/org.kde.discover.notifier.desktop) started
plasma-discover --mode update inside it, 520-620 MB resident and about 9% of a core,
with flatpak-system-helper and AppStream downloads behind it. IBus started a nested
ibus-daemon with kimpanel and ibus-extension-gtk3, which no app in the desktop can use:
KWin's input method is ft-textinput (zwp_input_method_v1, focus reports only; the VR
keyboard types through ft-screens' seat), and the session already drops QT_IM_MODULE,
GTK_IM_MODULE and XMODIFIERS. Nothing in Frametop talks to IBus.

Before Plasma starts, the session script copies both entries into
$XDG_CONFIG_HOME/autostart with Hidden=true, which plasma-session honours for that
desktop only. It does this once ([Defaults] autostart=1 in frametoprc) and skips a name
the user already has a file for, so deleting the copy brings the program back. The
geoclue demo agent stays (it answers apps' location requests outside GNOME and idles at
0%), and orca's entry is OnlyShowIn GNOME-family desktops, so it never ran. Tested
against a temporary XDG_CONFIG_HOME, including an existing user ibus.desktop left alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:18:31 -06:00
DeeJanuzandClaude Opus 5.5 5b6cfcd746 Session: blur, background contrast and animations off by default
The nested kwinrc had no [Plugins] group, so KWin ran its default blur and background
contrast effects, and kdeglobals had no AnimationDurationFactor, so animations ran at
full length. KWin renders through zink on Turnip, on the GPU vrcompositor needs, and
blur re-renders what's behind every translucent panel and menu; each animation frame is
another frame for KWin and ft-screens.

Before KWin starts, the session script now writes [Plugins] blurEnabled=false and
contrastEnabled=false to $XDG_CONFIG_HOME/kwinrc and [KDE] AnimationDurationFactor=0 to
its kdeglobals, each only if the desktop's own file has no value for it. It does this
once and records that in $XDG_CONFIG_HOME/frametoprc ([Defaults] effects=1), because
System Settings deletes a key put back to its default: without the marker, turning blur
back on wouldn't survive a restart. The ids blur and contrast are the built-in effects
of KWin 6.2.5 on SteamOS (both enabled by default in its plugin metadata). Tested
against a temporary XDG_CONFIG_HOME: fresh config, an existing blurEnabled=true kept,
and a deleted key not rewritten.

README and docs/reference.md say how to turn them back on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:17:44 -06:00
DeeJanuzandClaude Opus 5.5 e1f7ccee29 Pointer: skip unchanged work while the pointer is awake
Every frame (about 116 a second) the helper tested the cursor ray against every visible
overlay twice with ComputeOverlayIntersection, set the dot's alpha, width, transform and
visibility (five calls into SteamVR), and sent the driver a pose datagram, even with the
mouse and the head still.

Now a frame reuses the last collision result when the mouse, the anchor (1 mm) and the
eye (5 mm) haven't moved and no overlay showed, hid, or changed handle. The passes still run
at least every 100 ms, since overlays move on their own (a floating window's controls follow
it), and always while dragging. The dots' setters go to SteamVR only when their value changes:
the placement when the dot moved 0.2 mm or the eye 5 mm, which turns or resizes it by well
under 1%, and the width on a 0.5% change. The plain pose goes to the driver only when the
laser's origin moved 0.2 mm or its direction 0.04 deg (0.1 mm where it lands, 15 cm on), and
at least every 100 ms; the driver keeps the last pose and reports it every frame. A tilt's
pose, a placement, or waking sends the next one regardless.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:16:57 -06:00
DeeJanuzandClaude Opus 5.5 d8c2ed0c58 Screens: frame rates by attention, ticks in step with the display
ft-screens gave KWin a frame callback for every committed screen on each tick, and the tick
was an 11 ms timer set again after each run, so it slid through the display's frame and came
about 85 times a second at 90 Hz: the desktop repeated a frame several times a second (judder
in scrolling and video), and KWin drew every screen in one burst at a random point of
vrcompositor's frame. Hidden screens got the same 90 Hz unless Frametop was paused for a game.

- Ticks run on a timerfd at absolute times, once per display frame, 1 ms after the vsync
  (IVRSystem::GetTimeSinceLastVsync and the HMD's display frequency, read once a second), so
  KWin gets its callbacks early in the frame. Measured with --no-vr: 91 wakeups a second
  instead of about 85. On the Frame the vsync times SteamVR reports lie on a 90 Hz grid.
- Each screen's callbacks come at a rate for how much of it you see (vr.cpp,
  UpdateAttention): every frame while focused (within 12 degrees of where your head points,
  a laser or the mouse on it in the last 1.5 s, carried, or typed on), 15 a second for the
  rest of what you see (within 60 degrees), and 1 a second when hidden, behind you, or
  paused. Levels rise at once and fall after 1.5 s (focused) or 0.5 s (in view). KWin draws
  a screen only after its callback and its apps wait for theirs, so this throttles the apps
  too. A screen where nothing changes costs nothing at any rate, as before.
- A video in view keeps every frame: 8 commits in a row that each redraw 6% or more of the
  screen, at 10 a second or more, count as one (from the surface's buffer damage).
- "rates F V H" / --rates set the three rates (default 0 15 1, 0 = every frame), "rates?"
  shows them and each screen's level, "watch S" gives everything full rate for S seconds for
  a remote viewer (vnc-bridge.sh renews it), and "phase MS" moves the ticks for tuning.
- ft-screens' main thread runs at nice -5 after the session starts: SteamOS allows down to
  -8 once the soft RLIMIT_NICE is raised, and KWin waits on these ticks. It had spent nearly
  3 times as long waiting to run as running.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:16:46 -06:00
DeeJanuzandClaude Opus 5.5 7851ce90cc Eye tracker: ft-eyes sleeps until the next frame is due
ft-eyes looked for new frames about 1,000 times a second: each pass of its loop asked the
control socket with a non-blocking recvfrom (a BlockingIOError nearly every time), read
both cameras' counters, and slept 1 ms. The frames come every 11.1 ms per camera, and only
as counters in ft-eyegrab's shared memory, so there's no fd to wait on.

Now each pass ends in select() on the control socket, with a timeout until 2 ms before the
next frame of either camera is due (from when its last one was seen), then every 1 ms until
it comes. A command wakes it at once. A camera with no frame for 0.1 s (headset off,
grabber idle) isn't waited for, and with both stopped it looks every 20 ms. Waiting for the
frame grabber's file uses the same select, 0.2 s at a time, instead of sleeping through
commands.

A new frame is still seen within about 1 ms of when it lands. On a synthetic share at 90 Hz
per camera, on a heavily loaded headset (load average 23, so ft-eyes rarely sat idle), its
waits went from 178 to 81 a second; unloaded, the old loop's 1 ms sleeps add up to about
1,000.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:15:27 -06:00
DeeJanuzandClaude Opus 5.5 e1ee5ef395 Remote desktop: read the layout only after it changes
While FreeRDP ran, vnc-bridge.sh called ft-layout remote-view every 5 s, which scans
all of /proc for plasmashell and runs kscreen-doctor -j: about 4.4% of a core for a
layout that rarely changes.

It now stats the two files the answer depends on, the nested KWin's
~/.config/frametop/kwinoutputconfig.json (positions, scales, primary) and
~/.config/frametop-layout.json (screen sizes), once a second while FreeRDP runs. After
either changes it reads the layout every 2 s for 10 s, since KWin's outputs follow the
file a few seconds later; otherwise once a minute, in case a change touched neither.
With no VNC viewer connected nothing runs (previous commit).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:14:43 -06:00
DeeJanuzandClaude Opus 5.5 3e7248a04e Remote desktop: connect FreeRDP only while a VNC viewer is connected
vnc-bridge.sh kept FreeRDP connected to krdpserver from the moment remote desktop
started, so krdp captured and H.264-encoded every KWin redraw in software (openh264)
with nobody watching: krdpserver 55-78% of a core, xfreerdp 16-27%, Xvnc 6-11%, with 0
clients on :5900. krdp 6.7 creates its screencast session per RDP connection and drops
it when the connection closes, so krdpserver itself idles without one and stays up.

The bridge now counts established connections to Xvnc's port with ss, starts FreeRDP
when a viewer appears (the desktop shows about 3 s later; the VNC screen is black until
then) and stops it 45 s after the last one leaves (VNC_IDLE_SEC). Xvnc has no client
hook, so its log output, which it writes for every connection, wakes the bridge early;
otherwise it looks every 5 s while idle (0.1% of a core measured, against 0.9% for ss
once a second) and every second while FreeRDP runs. The layout check runs only while
FreeRDP runs.

While a viewer is connected the bridge sends "watch 15" to ft-screens (@ft_screens) at
once and every 5 s, so screens at a reduced frame rate (out of view, headset on a
stand) stream at full rate; it lapses by itself if the bridge dies, and an ft-screens
without the command just answers an error. The window search after starting FreeRDP
now ends when FreeRDP exits instead of polling for 30 s.

krdp on 127.0.0.1 with a fresh password, VNC on the tailnet address with VncAuth, and
remote-ctl.sh start/stop (pause and resume) are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:14:25 -06:00
DeeJanuzandClaude Opus 5.5 0680297efa Pointer: sleep on the command socket while the pointer is off
The main loop slept a fixed 8 ms, about 116 wakeups a second, whether the pointer was awake
or not, and every second it looked up every overlay's handle and read a string property from
all 64 device slots to find its own device.

With the pointer off and hand gestures off, the loop now waits in poll() on its command
socket for up to 250 ms, or 20 ms while mapped Frame controller buttons are being read
(SteamVR input has no event to wait for). A mouse command ends the wait at once. The
headset's activity level, the game check, and the "vrgame" and "gazeawake" repeats keep
going at that pace. The 50 ms visibility poll and the 1 s handle lookups run only while the
pointer is awake, and waking forces both. The device index is looked for only while it's
unknown, and again after SteamVR activates or deactivates a device. The HMD pose history is
kept only with hand gestures on, its one user.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:12:33 -06:00
DeeJanuzandClaude Opus 5.5 a11cef49ba Gaze: ft-eyes and ft-gaze below SteamVR's priority
ft-eyes and ft-gaze run in the dev container through distrobox, so they live in podman's
libpod scope: frametop-gaze.service's limits never reach them, and they ran at nice 0
next to vrcompositor and vrserver, also at nice 0.

- ft-eyes sets itself to nice 10 and SCHED_BATCH at start, before its threads. Batch
  turns off wakeup preemption, so a frame ft-eyes wakes up for can wait out a running
  compositor's turn; a few ms late costs the gaze little.
- ft-gaze sets nice 5 before its threads start, but stays SCHED_OTHER: each sample goes
  on to the pointer, and batch would add the same wait to every one of them.
- Both only ever lower their priority (a higher nice already set wins), and a failure
  is logged and ignored. Checked in the dev container: nice 0 -> 10, policy 0 -> 3
  (SCHED_BATCH) without any capability.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:11:15 -06:00
DeeJanuzandClaude Opus 5.5 19032f8963 Pointer: read the overlay list every 20 s, not every second
The helper ran `vrcmd --overlays` once a second while the pointer was awake, and in gaze
mode the pointer never sleeps. Each run is a shell plus vrcmd, a new SteamVR client, about
26 to 30 ms of CPU, so about 3% of a core all the time.

The list is now read every 20 seconds, and at once (at most once a second) when it may have
changed: the pointer waking, the dashboard opening or closing or creating an overlay, the
scene app changing, an "overlays" request, and a left click that hit nothing, which may be
on a panel that came up since. The thread waits on a condition variable instead of waking
every 100 ms, so it sleeps while paused. The main loop looks the keys up again as soon as a
new list is in, rather than at its next 1 s tick. Overlays already on the list still show
and hide within 50 ms, from the IsOverlayVisible poll.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:10:30 -06:00
DeeJanuzandClaude Opus 5.5 8a02e41b21 Eye tracker: one thread for OpenCV and numpy
Nothing called cv2.setNumThreads, so OpenCV kept a pool of one worker per core for
pupil windows of 140 to 240 px. Live, its idle workers spun and yielded about 14,000
times a second each, about a quarter of a core, next to SteamVR's compositor. numpy's
OpenBLAS also started 8 threads that never had work.

eyes_pupil.py now sets OpenCV to one thread, and ft-eyes sets OPENBLAS_NUM_THREADS and
OMP_NUM_THREADS to 1 before numpy loads (a value already in the environment wins).

Replaying fit1 into a scratch share (ft-eyes-replay, 14 s measured, capped at one core
with the replay): threads 13 -> 1, involuntary context switches 3,812/s -> 430/s,
system time 6.9% -> 1.6% of a core. Under that cap the frames it kept up with went from
21-36 to 57-69 a second per eye.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 09:08:16 -06:00
DeeJanuzandClaude Opus 5.5 30e02e9db7 Hands: push steps say to follow the hollow circle, not the blue dot
The dot is the current tracker's distance guess, often wrong; the ring is
where the hands should be.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 08:59:39 -06:00
DeeJanuzandClaude Opus 5.5 06c4ff9556 Merge branch game-pause (Game optimization page) into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 08:47:44 -06:00
DeeJanuzandClaude Opus 5.5 8760ca3083 Input Settings: the Games page is Game optimization
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 08:47:44 -06:00
DeeJanuzandClaude Opus 5.5 a05e500d30 Hands: the recorder's host commands run from the home folder
host-spawn starts a host command in the caller's folder. Started from /tmp,
the app's folder in the container is /run/host/tmp, which the host doesn't
have, so starting ft-camd (and every other host command) exited 127.
host_command now runs from home (env -C), and the launcher cds there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 08:45:40 -06:00
DeeJanuzandClaude Opus 5.5 fda6302bd3 Hands: the recorder measures the light itself
The checklist page measures the light when it opens, starting ft-camd if
nothing runs it (and stopping it on quit), instead of saying the cameras
aren't running. The round's lighting defaults to what the cameras measure:
daylight or indoor, from the mono cameras' ambient infrared. Lamps give off
little infrared, so dim and normal rooms read alike; picking dim, room or
daylight still overrides it. session.json gets source, measured and
ambient_ir.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 08:37:54 -06:00
DeeJanuzandClaude Opus 5.5 76e5c4932e Merge branch game-pause (update-check: still controllers) into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 08:37:18 -06:00
DeeJanuzandClaude Opus 5.5 ae4a1e30ab update-check: a still controller isn't a broken web socket
vrserver sends a controller's state only when something on it changes, and one lying still
or asleep may not even send its first one. The check subscribed to one controller and failed
after 3 s of silence. It now subscribes to all, and silence after a good handshake is a skip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 08:37:15 -06:00
DeeJanuzandClaude Opus 5.5 b0415cf150 Merge branch game-pause (pause Frametop for VR games, gaze idle) into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 08:34:50 -06:00
DeeJanuzandClaude Opus 5.5 5b08e43a5d Gaze: idle while the gaze isn't used
The gaze service ran ft-gaze and our own eye tracker all the time: with gaze mode off, ft-eyes
still took about 60% of a core, and ft-eyegrab, ft-gaze and ft-gazed 3 to 4% each. Now ft-gaze
and our tracker run only while gaze mode is on and someone wears the headset, while a check or
the calibration is open or asked for, or under a "wake" lease, which the Gaze page of Frametop
Input Settings renews while it's open. 30 s after the last use they stop, and the frame grabber
idles with our tracker.

- The pointer helper answers "gaze ? headset" with worn|away (SteamVR's activity level for the
  headset); an older helper answers it as before, and the service then goes by gaze mode alone.
- A quick check, calibration, or fit check asked for while idle wakes the tracker and opens once
  it sends; the automatic calibration waits quietly while it starts.
- Status has "awake" and "idle" (why), and the Gaze page shows it.
- gaze/test/idle-test.py runs the service with a fake helper and ft-gaze, offline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 08:32:49 -06:00
DeeJanuzandClaude Opus 5.5 a533bb973a Hands: ft-hands works out which side camera is which
ft-camd tells the side cameras apart by XRService's buffer allocation order,
which some XRService starts reverse; both of 2026-10-02's starts did, so the
cutouts missed the hands. HANDS_SWAP_SIDES=auto (the default) has ft-hands
vote from hands seen in both side cameras: the landmark rays meet in front
of both cameras only under the right naming. While undecided it probes the
exchanged naming with the landmark model. It decides in about 2 s of hands
(right on all 7 recordings replayed), swaps the views in place, and publishes
sides.json. 0 and 1 still force it, with a warning when the hands disagree.

Recordings carry each part's naming and the session's decision; review,
export, validate and ft-handreplay put the names right, and takes.py sides
records a decision by hand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 22:24:13 -06:00
DeeJanuzandClaude Opus 5.5 8aaf7db05a Pause Frametop for VR games
Frametop kept using the headset during games: with gaze mode off, our eye tracker still took
about 60% of a core, remote desktop about 2 cores while on, and KWin kept drawing hidden
screens because ft-screens sent their frame callbacks at 90 Hz. Pausing gives that back, and
resuming brings back only what pausing stopped. It's also a way to keep the gaze service and
our eye tracker off during games, which PR #13 asked for.

Paused (input/game_pause.py, run by the input relay):
- frametop-gaze stops (ft-eyegrab then idles by itself), and hand tracking and remote desktop
  stop if they run
- the desktop hides and slows down: ft-screens "pause on" hides every panel and sends KWin a
  frame callback once a second; or, with pause_desktop "close", the desktop closes and starts
  again on resume
- the relay lets go of the 3D mouse, typing goes to Steam, and mapped buttons and key
  combinations do only pause_toggle, steam_menu and commands

Toggled by both thumbsticks clicked together twice (configurable), read passively from
vrserver's web socket (input/vrws.py) so it works in games and takes nothing from them; by the
new pause_toggle action; by input/ft-pause; and, with pause_auto (default on), by a VR game
starting and ending, which the pointer helper now reports ("vrgame 1|0"). Frametop Input
Settings has a Games page for it. update-check.py checks the web socket, and doesn't count a
paused gaze service as failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 21:58:09 -06:00
DeeJanuzandClaude Opus 5.5 7fbcd177d3 Input relay test: let the fake devices past the udev permission check
Since the relay leaves a node it can't read yet for the next scan (12f2e84, PR #12), it
checks os.access first, and the test's fake /dev/input paths don't exist, so the relay never
opened them and every key check failed. The fake os now says they're readable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 21:58:09 -06:00
DeeJanuzandClaude Opus 5.5 97b7fc837c Hands: shorter recording sessions with pose sweeps
The second real session took 16 minutes, half of it 36 still poses. Labels
come from the auto-labeller, so what matters is variety, not clean holds.
A sweep step shows a strip of pose pictures and lights one every 4 s while
the hands move slowly near and far; each cue is a prompt event with
"cue": true. The core session is now 15 steps, about 5 minutes recorded.

The pose groups, the one-hand sweeps' groups and the cue order are shuffled
per session, seeded from its id and saved in session.json. A quick round
(--quick, or the checklist's choice) is about 2 minutes for extra lighting.
Touch the dot has 6 dots, the push sections two heights.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 21:30:50 -06:00
Patrick McDavidandClaude Opus 5.5 1ebf3692fb ft-floatd: a launch for a missing app no longer kills the control socket (#16)
Gio.DesktopAppInfo.new() returns NULL for a desktop file that doesn't
exist, and PyGObject raises TypeError ("constructor returned NULL")
rather than returning None, so launch()'s `if info is None` never ran.
The exception escaped the control socket's GLib callback, GLib dropped
the watch, and ft-floatd stopped answering everything: the float key,
dock, Launch as Standalone, and profiles, until the desktop restarted.

Found on the Frame (2026-10-02): a profile saved with RustDesk's
Flatpak open records its window's app id, com.carriez.flutter_hbb,
which has no desktop file (the Flatpak's is com.rustdesk.RustDesk).
`ft-layout use` on that profile asked ft-floatd to launch it, and
ft-floatd went silent. With this, that launch replies "error no app
com.carriez.flutter_hbb" and the profile's other apps open.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 21:12:49 -06:00
DeeJanuzandClaude Opus 5.5 3ebae6a88f Hands: check the tracking cameras before recording, and watch for losing them
After the headset wakes, XRService sometimes fails to load the colour module's
VCINT FPGA image; then only the two side cameras run, without the IR light,
and the tracker finds no hands. hands/camcheck.py reads XRService's log, the
video nodes it holds and ft-camd's ring, and says ok, degraded or unknown.

The recorder won't start while degraded (--ignore-cameras overrides it), offers
a confirmed SteamVR restart, and stops the first hand-size step when the
tracker sees no hand at all. ft-camwatch (unit file only, not enabled) follows
the log, notifies, and with CAMWATCH_AUTO_RESTART=1 restarts SteamVR when the
headset isn't worn and nothing else uses VR.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 20:12:16 -06:00
DeeJanuzandClaude Opus 5.5 554820ffc5 ft-floatd: profiles keep and relaunch Flatpak apps whose window names another app id
An X11 window in a Flatpak can give KWin an app id with no desktop file:
RustDesk's says com.carriez.flutter_hbb (its GTK application id), and the
Flatpak's desktop file is com.rustdesk.RustDesk. A profile recorded that
id, so it couldn't relaunch the app (PR #16 keeps that from killing
ft-floatd's socket). And the window's pid is the sandbox's own, so a
launched window matched neither by process nor by app id, and didn't
float.

desktop_name() finds the desktop file whose StartupWMClass names the
window's class (or app id) when the app id has none. Capture records
that name, a profile claims open windows by it, and a launch's window
matches by it.

Profiles saved before this keep the old id; save them again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 19:40:45 -06:00
Patrick McDavidandClaude Opus 5.5 bdc84b24d4 ft-floatd: a launch for a missing app no longer kills the control socket
Gio.DesktopAppInfo.new() returns NULL for a desktop file that doesn't
exist, and PyGObject raises TypeError ("constructor returned NULL")
rather than returning None, so launch()'s `if info is None` never ran.
The exception escaped the control socket's GLib callback, GLib dropped
the watch, and ft-floatd stopped answering everything: the float key,
dock, Launch as Standalone, and profiles, until the desktop restarted.

Found on the Frame (2026-10-02): a profile saved with RustDesk's
Flatpak open records its window's app id, com.carriez.flutter_hbb,
which has no desktop file (the Flatpak's is com.rustdesk.RustDesk).
`ft-layout use` on that profile asked ft-floatd to launch it, and
ft-floatd went silent. With this, that launch replies "error no app
com.carriez.flutter_hbb" and the profile's other apps open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 19:39:33 -06:00
DeeJanuzandClaude Opus 5.5 79eb251d6c Hands: the headset button as Next, clearer push steps
The headset's right-side click button (KEY_SELECT on gpio-keys, read without
a grab) now works the session: Next while a step waits, pause during a hold,
resume while paused. With no mouse connected the hints lead with it.

The push sections say plainly to push straight out from the headset and pull
back, with a side-view picture of the head, the headset and the arrow, and
the bar's ends read "At your chest" and "Arm out". The bar labels are sent
as one field, so labels with spaces no longer split.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 17:19:16 -06:00
DeeJanuzandClaude Opus 5.5 35196e2955 Hands: step mode and pose pictures for the hand recorder
The first real session moved on every 5 s with text only, too fast to follow.
Each step now waits for Next (Space or the window's button), counts down 3-2-1
while recording, then holds. P pauses, R redoes a step, S skips a section;
"Advance by itself" (--auto) keeps the old timed flow. Nothing records while
a step waits: each step is its own recording part.

The panel and the window show a picture of each pose (hands/rec/poses,
generated by make_poses.py from a parametric hand, MIT) and a diagram of where
to hold the hands and how far out. prompts.jsonl gains ready, wait and redo
events; session.json gains mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 16:34:45 -06:00
DeeJanuzandClaude Opus 5.5 072a294941 README: Frametop doesn't work on the SteamOS beta yet
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 16:12:52 -06:00
DeeJanuz abb05eb68c README: Frametop doesn't work on the SteamOS beta yet
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 072a294941)
2026-10-02 16:12:52 -06:00
DeeJanuzandClaude Opus 5.5 1fb6e7a38e Hands: upload from the hand recorder's window, export checks, a rehearsal
hands/rec/validate.py (standard library; Linux and Windows, Python 3.12+)
checks an export before upload and when it's received: SHA256SUMS, an
allow-list of files, the manifest's schema and keys, the consent version,
a uuid4 contributor, no identifying fields in calibration.json or
device.json, every sets.bin.zst decompressed to its end as a stream with
each FHSET01 header checked against the manifest, jsonl lines, the total
size. It decompresses with compression.zstd, zstandard or the zstd
program. validate.py DIR [--json].

hands/rec/hub.py uploads an export with huggingface_hub, as a pull
request to contributions/<contributor>/<session>: validate first, refuse
a repeat of the same export, check the login (whoami) and access
(auth_check), upload_folder(create_pr=True) with the manifest summary as
the description, then record the PR under "uploads" in session.json.
Errors are explained (terms not accepted, not found, 401/403, network).
--dry-run makes no network calls. FT_HANDREC_DATASET overrides
HF_DATASET (DeeJanuz/frametop-hands); while the texts are drafts a real
upload needs FT_HANDREC_ALLOW_UPLOAD=1.

The Upload page shows the login with "Check again" and how to run
hf auth login in a terminal (the token never enters the window), then
Upload with a phase, progress and Cancel (hub.py as a child process), the
PR link, and a warning for an export uploaded before. The manual
command stays as the fallback. ft-handrec --hub-dry-run.

session.py also saves device.json: cv.cad_from_cal and head from
/persist/device_config.json, the labeller's shape, nothing identifying;
export copies it. Session ids with a -N suffix are accepted everywhere.

hands/rec/rehearse.sh runs it all without the headset: ft-ringplay plays
30 s of a capture into a ring, session.py records a short test script
with ft-handpanel --no-vr and a tracker, then export, validate and a
dry-run upload (--repo ID uploads for real). It runs in one frame-job
scope, deletes its data and stops its processes, also on Ctrl+C.

hands/rec/tests/test_validate.py covers good and broken exports and hub.py
without the network. The dev container gains python3-huggingface-hub.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 13:53:53 -06:00
DeeJanuzandClaude Opus 5.5 27b731878c Hands: the hand recorder's window, review and export
hands/rec/ft_handrec.py + main.qml (Kirigami, dev container; host launcher
hands/rec/ft-handrec): consent (CONSENT.md, asked again when its version
changes; profile.json with a random contributor id), the before-you-start
checklist with the lighting and free-space checks, the session controls
(Space pauses, Esc stops), review with a frame-set viewer that deletes
ranges, takes and sessions, export with progress and cancel (warns while
the headset is worn), and the upload page (UPLOAD.md, the
huggingface-cli command; HF_DATASET is a placeholder). --dry-run runs
sessions without processes, for testing.

hands/rec/takes.py (standard library): indexes sets.bin and sets-N.bin
without reading pixels, reads one set's cameras, keeps deleted ranges in
take.json, and exports: deleted sets left out, zstd -10 -T2 at nice 19,
manifest.json and SHA256SUMS, nothing left behind on cancel.

CONSENT.md and UPLOAD.md are drafts pending a legal review; the window
says contributions aren't open yet. The dev container gains zstd.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 10:50:22 -06:00
DeeJanuzandClaude Opus 5.5 3b2f065c85 Hands: the hand recorder's session runner and guided script
hands/rec/session.py runs a recording session from script.json: it starts
ft-camd and a tracking ft-hands as transient units only if they aren't
running, records each section as one take (ft-hands --record-only at
10 sets/s, a new sets-N.bin after each pause), drives ft-handpanel, and
writes session.json, calibration.json (identifying fields removed),
prompts.jsonl and take.json. Feedback comes from the live hands file and,
in the controller sections, from the panel's device poll. It also runs
from the command line (--dry-run, --speed, --ring, --no-start).

hands/rec/script.json: 11 sections, about 9 minutes without the object
and controller sections.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 10:48:59 -06:00
DeeJanuzandClaude Opus 5.5 c6531148d7 Hands: the recorder's worn check goes by the panel's backlight, as frame-job does
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 10:36:17 -06:00
DeeJanuzandClaude Opus 5.5 7b80592665 Hands: ft-handpanel, the hand recorder's headset panel
A head-locked SteamVR overlay for the hand recorder (hands/rec/DESIGN.md):
1.2 m ahead, 12 degrees up, 36 degrees wide, drawn with stb_truetype
into three shared DMA-BUFs as ft-gazepanel does. It shows the title,
step, wrapped instruction, note, countdown, hand chips, near/far bar
and a "Paused" cover, driven over @ft_handpanel.

It also places the touch target, a 2 cm dot in its own overlay fixed
in the room where the head was at the first command for that point,
and logs head and controller poses to poses.jsonl at 250 Hz from a
thread of its own. Both threads take one lock around OpenVR calls.

--no-vr prints each picture's state to stdout (and --dump writes the
pictures), for testing without a headset. hands/rec/build.sh builds it
in the dev container.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 10:35:43 -06:00
DeeJanuzandClaude Opus 5.5 49b8e050db Hands: --record-hz, and the hand recorder's design (hands/rec/DESIGN.md)
ft-hands --record-hz N records at most N frame sets a second, for the hand recorder (10).
DESIGN.md lays out the recorder: the headset panel, the session runner and its script,
the files, review and export, consent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 10:26:13 -06:00
DeeJanuzandClaude Opus 5.5 ff36356992 Merge branch gaze-games (PR #13, narrowed) into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 09:18:26 -06:00
4d50739393 Gaze: leave SteamVR's gaze action alone during VR games
From curiousjtuber's PR #13: with the gaze service running, SteamVR
restarted its eye tracker every 10 to 13 s of Beat Saber, as if the
headset came off, and each restart took input focus from the game.
The PR stopped every read in a game. Only the action path reaches
SteamVR (UpdateActionState on the gaze set at overlay-global priority,
then GetEyeTrackingDataRelativeToNow); the mmap and our tracker are
read-only files. So only the action is skipped while a scene app runs,
and gaze keeps moving the pointer over the dashboard in a game. The
action source is only used with --source action.

Co-Authored-By: CuriousJ <curious.j.tuber@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 09:15:57 -06:00
DeeJanuzandClaude Opus 5.5 f60da63702 Merge PR #12 and #14 (relay udev retry, catcher crash) into experimental
From curiousjtuber's PRs: the relay leaves a new input node for the next
scan until udev gives it to the input group, rather than marking it seen
after a failed open; and ft-screens' catcher takes a screen's overlays
from one copy of All() instead of begin() and end() of two temporaries,
which crashed libc++ builds on the first click.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 09:15:04 -06:00
CuriousJ 82d2107e1d Screens: take a screen's overlays from one copy in the catcher
While a button pressed on a screen is held, UpdateCatcher checks every tick
whether the laser is still on one of the screen's overlays. It built that list
from s.All().begin() and s.All().end(), but All() returns a std::array by
value: iterators into two different temporaries, which is undefined behaviour.
A clang build of ft-screens got a garbage length, threw std::length_error, and
aborted on the first click, taking KWin and the desktop with it.
2026-10-02 09:11:46 -06:00
CuriousJ 12f2e844d5 Input relay: retry a new device until udev gives it to the input group
A new /dev/input node is root:root 0600 until udev applies GROUP=input. The
scan probed each new node once and marked it seen even when the open failed, so
a node caught in that gap was never opened. Behind a KVM, a switch brings back a
hub of devices at once: on the Frame, four nodes failed with EACCES in one switch,
the keyboard was never grabbed, and its keys went to gamescope instead of the
desktop screens. A node that isn't readable yet now waits for the next scan.
2026-10-02 09:11:46 -06:00
DeeJanuzandClaude Opus 5.5 ee2ce1a8d2 Merge PR #11 (controller click stability) into experimental
From jlneal's PR: a trigger press on a desktop screen stays put until the
laser moves more than 8 logical pixels, so controller jitter doesn't turn
a click into a drag. On top of it, only a hand controller's press starts
the filter: the 3D mouse's laser reaches the screens the same way, and the
PR as sent turned the mouse's short drags into clicks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 23:20:06 -06:00
DeeJanuzandClaude Opus 5.5 540d8c425c Click stability: only a hand controller's press starts it
The 3D mouse drives SteamVR's laser through the ft_pointer virtual
controller, so its events reach the screens the same way a controller's
do. The filter held every press, which turned the mouse's short drags
(selecting a character or two, nudging a slider) into clicks. Mark
button events from hand controllers and start the filter only on those.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 23:19:58 -06:00
Codex ba6ccdfbd1 Clear reported drag state on controller release 2026-10-01 23:18:41 -06:00
Codex 77f28f0922 Prevent small desktop overlay pointer movements from starting a drag 2026-10-01 23:18:41 -06:00
DeeJanuzandClaude Opus 5.5 85532a54f3 Wait for a new container to finish setting up before entering it
container-up.sh starts the dev container in a scope of its own, so
distrobox enter finds it running and skips its wait for distrobox-init.
On a fresh install, init was still setting up passwordless sudo when
dev-container.sh ran sudo dnf install, and sudo asked for a password
with no terminal to read it from. container-up.sh now waits for
container_setup_done itself, and the container's sudo calls use -n,
so a password prompt fails at once with a clear message.

Fixes #9

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 21:58:17 -06:00
DeeJanuzandClaude Opus 5.5 7816633353 README: link the Frametop Discord
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 21:18:09 -06:00
DeeJanuzandClaude Opus 5.5 3864741f53 README: link the Frametop Discord
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 21:13:19 -06:00
DeeJanuzandClaude Opus 5.5 12ad93d24c Gaze: install our eye tracker, prefer it, and say why a calibration dot wasn't taken
A user on a fresh install got "Calibration failed: only 0 of 21 dots" with
no reason. The installer never installed our tracker, so gaze used
SteamVR's, and the only way SteamVR's tracker rejects a dot is losing an
eye for most of the look. The panel just showed a red ring.

- install.sh: step 9/10 installs our tracker (gaze/tracker/install.sh)
  after gaze mode, yes by default; it needs sudo, so --yes runs it only
  when sudo won't prompt. If it fails, gaze keeps SteamVR's tracker.
  Configs that still say GAZE_TRACKER=steam (the old template) are asked
  whether to switch.
- GAZE_TRACKER=auto, the new default: ours when it's installed (the
  frame grabber, its unit, and ft-eyes' Python), else SteamVR's.
  ft-gazed rechecks every second, so installing it switches over. Input
  Settings lists Own tracker first as recommended, and says how to
  install it when it's missing (checking the host's /etc through
  /run/host from the dev container).
- The calibration panel has a note line, orange over the instructions:
  why a dot wasn't taken (an eye lost, a blink, the eyes disagreeing for
  SteamVR's tracker, from steady_samples' new drop counts; ft-eyes' reply
  for ours), what a click is still waiting for after 1.5 s, and a failed
  calibration's most common reason, which the Gaze page shows too.
  steady_samples keeps the same samples as before (checked on 2037
  windows of recordings); a lost eye is named before a blink, since its
  openness reads 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 20:48:52 -06:00
DeeJanuzandClaude Opus 5.5 a7f9a8dd80 Gaze: say why gaze mode can't work yet, and open the calibration whenever it's missing
Turning gaze mode on without a calibration opened Calibrate only on the
off-to-on change, and only if it could open right then. With the headset
off, the eye tracker silent, or the panel not built, or with gaze mode
already on when the gaze service started, nothing opened and nothing said
why: the pointer just stayed a mouse.

- The gaze service now checks every second: gaze mode on, no calibration
  for the tracker in use, eyes seen -> the full calibration opens. One
  that closes unfinished opens again only after the headset comes off and
  on, gaze mode off and on, or Calibrate, so it doesn't loop. A start that
  fails retries every 10 s.
- Its status says why gaze mode can't work yet (checks.problem): not
  calibrated and opening, open, closed unfinished, or can't open and why.
- Input Settings shows that under the Gaze pointer switch, along with the
  gaze service not installed or not running and our tracker missing its
  frame grabber.
- ft-gazectl on notes a missing calibration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 17:50:52 -06:00
DeeJanuzandClaude Opus 5.5 ac142f6e4a ft-cutouts status: only the current run's tracker lines
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 17:26:59 -06:00
DeeJanuzandClaude Opus 5.5 b417534425 Hands: ft-cutouts, the hand cutouts without pinches and grips
hands/ft-cutouts on|off|status starts ft-camd and ft-hands as transient
user units with ft-hands' new --no-gestures: hands are published for
ft-screens' cutouts, but no pinch or grip is detected, so nothing clicks
or drags and a closing hand doesn't raise the tracking rate. It needs a
build and ft-camd's capabilities, not hands/run.sh install. Its units
conflict with ft-handsctl's, so each stops the other, and they stop with
SteamVR.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 17:22:52 -06:00
DeeJanuz c377133859 Merge experimental into shortcuts
# Conflicts:
#	input/input-relay.py
2026-10-01 17:08:15 -06:00
DeeJanuzandClaude Opus 5.5 675ef3f0d5 Relay: share a key combination's Meta release with frame-voice
A Meta+key combination (Meta+J for gaze_left, say) hides Meta's release
from the desktop, and the relay skipped share_key for it too. frame-voice
saw Meta go down on @frametop_keys and never come up, so it held all
dictated text back, waiting for that release. Keys of grabbed keyboards
are now shared as pressed, before key_binding() decides what the desktop
gets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 17:07:38 -06:00
DeeJanuzandClaude Opus 5.5 fadc0f467c Shortcuts: Steam menu, commands, and modifier taps
Key combinations (and mouse and controller buttons) get two new actions:
- steam_menu: Open Steam menu / close dashboard (steam/ft-steam menu).
- command:CMD: run CMD with sh -c, as the relay's service, with layout/,
  float/ and steam/ on its PATH. Input Settings offers it for key
  combinations as Run a command...
Both work without pointer mode.

A modifier on its own is now a key combination too: a tap, pressed and
released with no other key, mouse button, or scroll in between. A bound
tap sends the desktop F24 before the release, so Plasma's launcher stays
shut. The defaults gain a Meta tap for the Steam menu; this replaces
META_DASHBOARD, which only worked in pointer mode.

input/test/keys-test.py runs the relay against fake devices with every
outgoing socket renamed, so it's safe next to the live relay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 17:06:30 -06:00
DeeJanuzandClaude Opus 5.5 2487351556 ft-steam: open Steam's menu through Steam's own UI
steam/ft-steam menu opens the SteamVR dashboard on Steam's menu, or closes
the dashboard if it's up, without pointer mode: it asks Steam's UI over its
debugging port to show its dashboard overlay (ShowVROverlay, what Steam
calls itself) and focus the Steam frame's left menu (MenuStore.OpenMainMenu).
ft-steam check says whether those calls still exist, and update-check.py
runs it, since a Steam client update can rename them.

The CDP client moves from display-settings/steam_settings.py to
steam/steamui.py, so both use it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 17:06:30 -06:00
DeeJanuzandClaude Opus 5.5 4479fbfcc1 Input relay: typing with the pointer helper down no longer ends the relay
Typing on a pass-through keyboard tells the helper "typing". With the
helper not running (SteamVR off), that send raised ConnectionRefusedError
and the relay exited, dropping every grab until systemd restarted it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 17:01:31 -06:00
149 changed files with 21222 additions and 843 deletions

No files matched your search

+26 -7
View File
@@ -13,8 +13,12 @@ Two settings apps come with it: Frametop Display Settings for the screens, profi
Frametop is an independent project, not made by or affiliated with Valve.
Join the [Frametop Discord](https://discord.gg/W3X9f7z3Bc) for questions, ideas, and help with your setup.
## Install on the headset
> **Frametop doesn't work on the SteamOS beta right now.** On the beta (SteamOS 0.4.3), gaze mode can't read the eye tracker, and the desktop has started without its taskbar ([#15](https://github.com/DeeJanuz/frametop/issues/15)). Use the stable SteamOS release until this note is gone.
You need a Steam Frame with an internet connection, a keyboard (Bluetooth, or the on-screen one), and about 3 GB of free space.
1. In the launcher, choose Launch a program → Desktop.
@@ -27,7 +31,7 @@ You need a Steam Frame with an internet connection, a keyboard (Bluetooth, or th
It asks which version you want: stable (the `main` branch, tested releases) or experimental (the `experimental` branch, the newest features, less tested). Then it clones the repo into `~/frametop` and runs `install.sh`. To choose without the question, add `-s -- --stable` or `-s -- --experimental` after `bash`. By hand, the same is `git clone https://github.com/DeeJanuz/frametop.git ~/frametop`, then `cd ~/frametop` and `./install.sh` (add `--branch experimental` to the clone for experimental).
The installer sets up distrobox in your home folder (the system files aren't touched), a Fedora build container, and everything else. The first run downloads 1–2 GB. It asks you three things along the way: whether to install gaze mode (experimental, yes by default) and the Bluetooth fixes, then whether to restart SteamVR. The Bluetooth fixes need your `sudo` password; if you've never set one, run `passwd` first, or skip them for now. SteamVR has to restart once at the end, which closes everything open in VR, including the terminal. Rebooting the headset works too.
The installer sets up distrobox in your home folder (the system files aren't touched), a Fedora build container, and everything else. The first run downloads 1–2 GB. It asks you four things along the way: whether to install gaze mode (experimental, yes by default), our own eye tracker for it (yes by default), and the Bluetooth fixes, then whether to restart SteamVR. The eye tracker and the Bluetooth fixes need your `sudo` password; if you've never set one, run `passwd` first, or skip them for now. SteamVR has to restart once at the end, which closes everything open in VR, including the terminal. Rebooting the headset works too.
After the restart, Launch a program → Desktop opens the multi-screen desktop, with its screens arranged around where you're facing. Frametop Display Settings and Frametop Input Settings are in the desktop's application menu, under Settings.
@@ -53,9 +57,11 @@ If you work in the desktop for long stretches, or leave the headset on a stand,
| While carrying a screen, sweep its laser across your other controller's ring, then let go | Pins it to that wrist, at its size and distance, as you hold it when you let go; it shows while you see its front. Grab its bar to adjust it (it stays pinned); sweep across the ring again to take it off |
| Set a screen to On your head (Frametop Display Settings, Visibility & pins) | Pins it to your head where it is, like a HUD. Grab its bar to move it; it stays on your head |
| Meta+Shift+R in the desktop | Puts the screens back in their layout (also in the menu as Reset Screen Layout, and mappable to a mouse button) |
| Meta+Alt+Tab, or Meta+Alt+Shift+Tab | Spins every screen and floating window around you together, like a lazy susan, so the next one on your right (or left) glides to straight ahead, with the pointer and typing going to it. Their arrangement stays the same: the room turns instead of you. Tap again to keep going; Meta+Shift+R puts the screens back. Pinned screens stay where they are |
| Meta+Shift+H in the desktop | Hides or shows all screens (also in the menu as Hide/Show Screens, and mappable). The Visibility & pins tab of Frametop Display Settings can instead show them only with the dashboard open, or while you look at your wrist |
| Tap Meta, on any keyboard | Opens the Steam menu in the SteamVR dashboard, or closes the dashboard, wherever you are. The desktop's launcher is still on the taskbar and Alt+F1. Change it in Frametop Input Settings (Keyboard page), where any key combination or modifier tap can do a Frametop or Steam action, open a profile, or run a command of your own |
| Switch a screen to Hidden (Frametop Display Settings, Visibility & pins → Screens shown) | Hides just that screen until you switch it back, whatever the other visibility settings say; new windows that would open on it float instead |
| Play a VR game | The screens hide and your controllers stay in the game. Open the SteamVR dashboard, or press Meta+Shift+H, to see and use them. To keep them visible over games, change During VR games on the Visibility & pins tab; the controllers still stay in the game, and you use the screens with the mouse or the dashboard |
| Play a VR game | Frametop pauses so the game gets the headset to itself (see [Pause for VR games](#pause-for-vr-games)): the screens hide and your controllers stay in the game. Click both thumbsticks together twice to bring Frametop back. With the automatic pause off, the screens still hide, and the SteamVR dashboard or Meta+Shift+H shows them; to keep them visible over games, change During VR games on the Visibility & pins tab |
Restarting the desktop (Restart desktop in Frametop Display Settings) closes its windows, but background work you started in it, such as servers, tmux sessions, or builds, keeps running.
@@ -90,9 +96,21 @@ A profile is a named setup: where the screens are, with their sizes and pins, wh
| Pick a profile under Arrangement and press Open profile | Switches to it: the screens move, open windows of its apps go to their places, and the apps that aren't open start. Nothing closes |
| Pick a profile under Start in profile, or run its entry (Frametop: NAME) from SteamVR's Launch a program list | The desktop starts in that profile, or switches to it if it's running. A profile can also go on a key combination, mouse button, or controller button in Frametop Input Settings |
### Pause for VR games
Frametop pauses while a VR game runs, so the game gets the headset's CPU and GPU, and comes back a few seconds after the game ends. Paused, the screens hide and the desktop nearly stops drawing, but its windows stay open. Gaze mode's eye tracking stops, and so do remote desktop and hand tracking if they run. The mouse works as a plain mouse in SteamVR.
| Do this | To get this |
| --- | --- |
| Click both thumbsticks together, twice | Pauses Frametop, or brings it back, in a game or not. You hear a short sound. The game sees the clicks too |
| Start a VR game | Frametop pauses, and comes back 5 seconds after the game ends. Bring it back during the game, and it stays on until that game ends |
| Map Pause/resume Frametop to a mouse button, key combination, or controller button | The same, from that button (Frametop Input Settings) |
The Game optimization page of Frametop Input Settings turns the automatic pause off, changes the gesture, closes the desktop instead of hiding it (more for the game, but its windows close), and turns the sound off. From a terminal: `input/ft-pause on`, `off`, or `status`.
### Gaze mode (experimental)
In gaze mode the pointer goes where you look, and the mouse or the keyboard does the last bit. The installer offers it (or run `gaze/run.sh install` later). Turn it on and calibrate it on the Gaze page of Frametop Input Settings.
In gaze mode the pointer goes where you look, and the mouse or the keyboard does the last bit. The installer offers it (or run `gaze/run.sh install` later), and then our own eye tracker for it, which is more accurate than SteamVR's (or run `gaze/tracker/install.sh` later; it needs `sudo`). Gaze mode uses ours once it's installed, and SteamVR's until then. Turn it on and calibrate it on the Gaze page of Frametop Input Settings.
| Do this | To get this |
| --- | --- |
@@ -119,15 +137,16 @@ This is an early release, tested on one Steam Frame (SteamOS 0.3.0 build 2026092
- A SteamOS or SteamVR update can break parts of it until Frametop catches up. After an update, run `cd ~/frametop && scripts/doctor.sh` in a terminal. It checks what Frametop needs from SteamOS, and says what changed since the versions you last marked as working and what to try. Once everything works, `scripts/doctor.sh --mark-good` records the versions. If something stops working, please report it.
- The first install downloads 1–2 GB for the build container and compiles everything on the headset, which takes several minutes.
- During a VR game you can't show the screens with a controller button, because the game owns the buttons. Open the SteamVR dashboard, press Meta+Shift+H, or use a mapped mouse button instead.
- Flatscreen games aren't detected as games. If your controllers end up working the screens instead of the game, set Controllers on the screens to "Only with the SteamVR dashboard open" (Frametop Display Settings, Visibility & pins tab).
- During a VR game, mapped controller buttons belong to the game, so they can't bring the screens up. The pause gesture still works: Frametop reads it without taking the thumbsticks from the game. With the automatic pause off, open the SteamVR dashboard, press Meta+Shift+H, or use a mapped mouse button instead.
- Flatscreen games aren't detected as games, so they don't pause Frametop by themselves: click both thumbsticks twice to pause it. If your controllers end up working the screens instead of the game, set Controllers on the screens to "Only with the SteamVR dashboard open" (Frametop Display Settings, Visibility & pins tab).
- Typing follows your last click. A controller click on a panel other than the screens (the dashboard, a Steam app) doesn't move typing there; click it with the mouse, or click a screen to bring typing back.
- The screens don't draw a mouse cursor of their own. The 3D mouse's dot or SteamVR's laser shows where you're pointing.
- Profiles reopen apps, not what the apps had open. Tabs, files, and folders are left to each app's own restore.
- Dragging something from one panel to another (a screen and a floating window) works, but the dragged item's icon doesn't show while the pointer is between panels.
- Gaze mode is only as good as its calibration, and that depends on how the headset sits on your face. If the pointer lands off after you adjust the headset, run Quick check or Calibrate on the Gaze page of Frametop Input Settings.
- On SteamVR's Settings page, the 3D mouse shows a laser beam and a larger hit dot, like a controller. SteamVR doesn't tell other programs where that page is (unlike Steam's pages, such as Library), so the mouse used to miss most of it: clicks went through to a desktop screen behind, and the dot disappeared. As a workaround, on that page only, the laser starts near your eye and SteamVR finds the page itself. See docs/design.md.
- Remote desktop over VNC (Frametop Remote Access in the app menu, or `./desktops.sh remote on`) needs Tailscale on the Frame. It shows the primary screen only. The app turns it on and off, shows the address, and shows, copies, or changes the VNC password. The password is made at random on the Frame and kept in `~/.config/frametop-remote` (only you can read it); VNC limits it to 8 characters, and the tailnet encrypts the connection. Turning it on in a desktop that started with it off takes a desktop restart.
- Remote desktop over VNC (Frametop Remote Access in the app menu, or `./desktops.sh remote on`) needs Tailscale on the Frame. It shows the primary screen only. The app turns it on and off, shows the address, and shows, copies, or changes the VNC password. The password is made at random on the Frame and kept in `~/.config/frametop-remote` (only you can read it); VNC limits it to 8 characters, and the tailnet encrypts the connection. Turning it on in a desktop that started with it off takes a desktop restart. It costs almost nothing until a viewer connects; the picture then takes a few seconds to appear.
- The desktop has no blur behind panels and menus, and no window animations, so it leaves the headset's GPU to SteamVR. Turn them back on in the Frametop desktop's System Settings (Desktop Effects, and Animation speed under General Behavior); Frametop won't turn them off again.
- Turning the displays off on a stand only turns their backlight off. SteamVR has no way for other programs to put the headset in standby, so tracking and rendering keep running, and the headset draws nearly its full power.
## Reporting problems
@@ -138,7 +157,7 @@ In a terminal on the headset, run:
cd ~/frametop && scripts/report.sh
```
This writes `frametop-report-<date>.txt` with version numbers, service states, settings, and recent logs. Bluetooth addresses and the headset's serial number are masked. Then [open an issue](https://github.com/DeeJanuz/frametop/issues), describe what you did, what you expected, and what happened, and attach the file.
This writes `frametop-report-<date>.txt` with version numbers, service states, settings, and recent logs. Bluetooth addresses and the headset's serial number are masked. Then [open an issue](https://github.com/DeeJanuz/frametop/issues), describe what you did, what you expected, and what happened, and attach the file. Quick questions can go to [Discord](https://discord.gg/W3X9f7z3Bc) instead.
## Update
+1 -1
View File
@@ -3,7 +3,7 @@ Type=Application
Name=Reset Screen Layout
GenericName=Put the VR desktop's screens back in their layout
Comment=Float the screens and arrange them in the layout from Frametop Display Settings
Exec=@REPO@/layout/ft-layout apply
Exec=@REPO@/layout/ft-layout-reset
Icon=view-restore
Categories=Settings;
Keywords=display;screen;layout;arrange;reset;steamvr;frametop;
+1 -1
View File
@@ -3,7 +3,7 @@ Type=Application
Name=Hide/Show Screens
GenericName=Hide or show the VR desktop's screens
Comment=Hide the screens (and SteamVR's laser) for a VR game; press again to bring them back
Exec=@REPO@/layout/ft-layout toggle
Exec=@REPO@/layout/ft-hide-show
Icon=view-visible
Categories=Settings;
Keywords=display;screen;hide;show;steamvr;frametop;
+1 -1
View File
@@ -802,7 +802,7 @@ Kirigami.ApplicationWindow {
Repeater {
model: [
{ value: "hide", text: "Hide them unless the SteamVR dashboard is open", help: "The game has the view to itself; open the dashboard (or press Meta+Shift+H) to see the screens." },
{ value: "visible", text: "Keep them visible over the game", help: "They float over the game as they are outside it." }
{ value: "visible", text: "Keep them visible over the game", help: "They float over the game as they are outside it. Turn off Pause while a VR game runs in Frametop Input Settings (Game optimization), or Frametop pauses and hides them anyway." }
]
delegate: ColumnLayout {
required property var modelData
+11 -102
View File
@@ -4,117 +4,26 @@ Steam, not systemd, puts the Frame to sleep: after "When Plugged In and Idle ->
(an hour by default) without input, even while it charges. That's a Steam client setting,
`system_idle_suspend_ac_sec` (0 = never), with no file or command line to change it. Steam
on the Frame runs with -cef-enable-debugging, so its UI's JavaScript context
(SharedJSContext) is reachable over the Chrome DevTools Protocol on 127.0.0.1:8080. There
`settingsStore.clientSettings` has the current values, and `SteamClient.Settings.SetSetting`
takes a change as a serialized CMsgClientSettings protobuf, which is what Steam's own
Settings -> Power page sends. Standard library only (a minimal WebSocket client).
(SharedJSContext) is reachable over the Chrome DevTools Protocol on 127.0.0.1:8080
(steam/steamui.py). There `settingsStore.clientSettings` has the current values, and
`SteamClient.Settings.SetSetting` takes a change as a serialized CMsgClientSettings protobuf,
which is what Steam's own Settings -> Power page sends.
"""
import base64
import json
import os
import socket
import struct
import urllib.request
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "steam"))
from steamui import SteamUnreachable, evaluate # noqa: E402,F401 (callers catch SteamUnreachable here)
CDP_PORT = 8080
# CMsgClientSettings field numbers (Steam's UI bundle maps the names to these).
FIELDS = {"system_idle_suspend_ac_sec": 24004, "system_idle_suspend_battery_sec": 24003}
class SteamUnreachable(Exception):
pass
class _WebSocket:
def __init__(self, url, timeout=5):
host_port, path = url[len("ws://"):].split("/", 1)
host, port = host_port.rsplit(":", 1)
self.sock = socket.create_connection((host, int(port)), timeout=timeout)
key = base64.b64encode(os.urandom(16)).decode()
self.sock.sendall((f"GET /{path} HTTP/1.1\r\nHost: {host_port}\r\nUpgrade: websocket\r\n"
f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n").encode())
head = b""
while b"\r\n\r\n" not in head:
chunk = self.sock.recv(4096)
if not chunk:
raise SteamUnreachable("Steam closed the connection")
head += chunk
if b" 101 " not in head.split(b"\r\n", 1)[0]:
raise SteamUnreachable(head.split(b"\r\n", 1)[0].decode(errors="replace"))
self.buf = head.split(b"\r\n\r\n", 1)[1]
def send(self, text):
data, mask = text.encode(), os.urandom(4)
n = len(data)
if n < 126:
head = struct.pack(">BB", 0x81, 0x80 | n)
elif n < 65536:
head = struct.pack(">BBH", 0x81, 0x80 | 126, n)
else:
head = struct.pack(">BBQ", 0x81, 0x80 | 127, n)
self.sock.sendall(head + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(data)))
def _take(self, n):
while len(self.buf) < n:
chunk = self.sock.recv(65536)
if not chunk:
raise SteamUnreachable("Steam closed the connection")
self.buf += chunk
out, self.buf = self.buf[:n], self.buf[n:]
return out
def recv(self):
message = b""
while True:
b0, b1 = self._take(2)
n = b1 & 0x7F
if n == 126:
n = struct.unpack(">H", self._take(2))[0]
elif n == 127:
n = struct.unpack(">Q", self._take(8))[0]
message += self._take(n)
if b0 & 0x80:
return message.decode(errors="replace")
def close(self):
self.sock.close()
def _evaluate(expression):
"""Runs JavaScript in Steam's SharedJSContext and returns its (awaited) value."""
try:
with urllib.request.urlopen(f"http://127.0.0.1:{CDP_PORT}/json", timeout=3) as r:
targets = json.load(r)
except OSError as e:
raise SteamUnreachable(f"Steam isn't reachable on port {CDP_PORT} ({e})") from e
url = next((t["webSocketDebuggerUrl"] for t in targets if t.get("title") == "SharedJSContext"), None)
if not url:
raise SteamUnreachable("Steam's UI isn't running")
try:
ws = _WebSocket(url)
try:
ws.send(json.dumps({"id": 1, "method": "Runtime.evaluate",
"params": {"expression": expression, "awaitPromise": True, "returnByValue": True}}))
while True:
reply = json.loads(ws.recv())
if reply.get("id") == 1:
break
finally:
ws.close()
except OSError as e:
raise SteamUnreachable(str(e)) from e
result = reply.get("result", {})
if "exceptionDetails" in result:
details = result["exceptionDetails"]
raise SteamUnreachable(details.get("exception", {}).get("description") or details.get("text", "error"))
return result.get("result", {}).get("value")
def sleep_settings():
"""{"ac": seconds, "battery": seconds}: when Steam puts the Frame to sleep without input,
plugged in and on battery (0 = never)."""
value = _evaluate("(() => { const c = settingsStore.clientSettings; "
"return {ac: c.system_idle_suspend_ac_sec, battery: c.system_idle_suspend_battery_sec}; })()")
value = evaluate("(() => { const c = settingsStore.clientSettings; "
"return {ac: c.system_idle_suspend_ac_sec, battery: c.system_idle_suspend_battery_sec}; })()")
if not isinstance(value, dict) or not all(isinstance(value.get(k), int) for k in ("ac", "battery")):
raise SteamUnreachable("Steam's settings don't have the sleep timeouts")
return value
@@ -125,7 +34,7 @@ def set_sleep_setting(name, seconds):
field, seconds = FIELDS[name], int(seconds)
if seconds < 0:
raise ValueError("seconds must be 0 (never) or more")
ok = _evaluate(f"""(async () => {{
ok = evaluate(f"""(async () => {{
const bytes = [];
const varint = n => {{ while (n > 127) {{ bytes.push((n & 127) | 128); n = Math.floor(n / 128); }} bytes.push(n); }};
varint({field} * 8); varint({seconds});
+34
View File
@@ -0,0 +1,34 @@
# Controller desktop click stability
Trigger presses reach KDE immediately, but controller motion within 32 logical
pixels of the press stays at that position until release. Releasing without a motion outside this
zone delivers the click at the original position, even if the hand moved during
release. Moving outside the zone begins a normal drag immediately; returning to
the zone does not turn it back into a click. There is no hold-duration timer.
This filters overlay pointer content events on desktop monitors only, and only
presses from hand controllers start it. The 3D mouse (whose laser comes from the
`ft_pointer` virtual controller), SteamVR UI, separate screen grab bars and
floating-app title-bar carrying are unaffected. Multi-button gestures keep their
existing behavior. A motion onto another desktop monitor starts a drag;
cross-monitor motion is not stabilized.
CLI (runtime preferences, reset to 32 on desktop restart):
```sh
input/ft-clickctl status
input/ft-clickctl threshold 32
input/ft-clickctl threshold 0 # disable without a restart
```
Thresholds are 0–64 logical pixels, normalized to each panel's KDE scale.
Status reports held state, suppressed motions, stabilized clicks and drags.
Changing the threshold while a controller button is held is refused.
This is a separate contribution from desktop mouse/controller ownership. Its
hardware validation must check small controls, intentional text selection,
long presses, cross-monitor dragging and simultaneous mouse use. The existing
renderer laser remains tracked; this change stabilizes desktop input rather
than smoothing the visual laser. The default was 8 at first. That's about 0.2° on a 3.4 m wide 3440-pixel screen 2 m away, and clicking took a very still hand, so it's 32 (about 0.9°) since 2026-10-03.
Run `scripts/test-controller-click.sh` for the isolated gesture-state tests.
+26 -6
View File
@@ -38,7 +38,7 @@ The curved layout chains screens edge to edge, like monitors on a desk: the midd
A resize handle has to be able to shrink a screen from any direction, so the dragged corner follows the laser along the screen's diagonal rather than taking the larger of its horizontal and vertical reach. Pushing and pulling a carried screen moves it along the line from your head, because the 3D mouse's virtual controller sits just in front of the bar, below the screen's centre, so the line from the device points mostly upward.
Wherever ft-screens needs to know where a laser points (showing the controls, the resize tab, the roll knob), it uses the laser's own pose, the render model's `tip` component, rather than the controller's pose. On the Frame's controllers the tip points 40° below the pose's forward axis, so rays from the pose missed what the laser was actually on. The 3D mouse's virtual controller has no tip, and its laser runs along its pose.
Wherever ft-screens needs to know where a laser points (showing the controls, the resize tab, the roll knob), it uses the laser's own pose, the render model's `tip` component, rather than the controller's pose. On the Frame's controllers the tip points 40° below the pose's forward axis, so rays from the pose missed what the laser was actually on. The 3D mouse's virtual controller has no tip, and its laser runs along its pose. ft-screens reads the tip with `GetComponentState`: `GetComponentStateForDevicePath` without an input source handle fails for every component while a VR game runs, so in games the rays came from the pose, 40° too high.
`ComputeOverlayIntersection` ignores `SetOverlayIntersectionMask`, and a control can't be allowed to cover part of its screen, so the resize tab sits entirely outside the corner.
@@ -62,6 +62,8 @@ A profile's screen part is the custom arrangement under a name: each screen's po
`IVRApplications::GetCurrentSceneProcessId()` is 0 when no game is running (the Frame's home environment isn't a scene app) and the game's process ID while one is. ft-screens checks it twice a second, turns the flag off while a game runs, and by default hides the screens unless the dashboard is open. Flatscreen games run inside Steam's gamescope overlay and aren't scene apps, which is why "only with the dashboard open" is offered as a controller setting.
In a game, Frametop's panels work like SteamVR's own floating windows: point a controller at one and its laser comes on, point away and the game has the controllers again. ft-screens turns the flag on for a panel while a hand controller's laser pose meets it, its controls, or a floating window's popups. It finds that from the poses it already reads to show the controls, so SteamVR's laser doesn't have to be on first. Leaving takes a margin two control-sizes wide and 0.3 s, a drag or a held button keeps the flag on, and the keyboard, a single overlay, uses SteamVR's `ComputeOverlayIntersection`. The 3D mouse doesn't need any of this: it has its own laser mode.
## Floating windows
[floating-windows.md](floating-windows.md) describes the feature and its parts. Drag and drop and the clipboard only work between windows of one compositor, so a floating window stays a KWin window and gets a KWin output of its own: one of the spare outputs KWin opens after the screens, shown by ft-screens as a panel cropped to the window. What follows is how KWin 6.2.5 behaves underneath that, from its source (`src/backends/wayland/`) and from trying it on the Frametop desktop.
@@ -116,9 +118,9 @@ The driver starts disconnected, because holding the right-hand role while SteamV
### The cursor
Mouse motion turns into yaw and pitch around an anchor, the head position at the last recenter. A ray from the anchor is tested against every visible overlay with `ComputeOverlayIntersection`. On a hit, the cursor sits on that surface; otherwise it floats at `POINTER_DISTANCE`. Since the anchor isn't your current eye position, a second test runs along your line of sight to the cursor point, and anything nearer wins, so the cursor always lands on what you see under it. Overlays in `POINTER_IGNORE` are left out of both tests. A display-only panel, like a performance overlay locked to your view, has no input method, so SteamVR's laser passes through it, but `ComputeOverlayIntersection` still hits it, and the cursor stuck to it. The laser starts just before the cursor point, so an ignored panel nearer to you doesn't catch it either.
Mouse motion turns into yaw and pitch around an anchor, the head position at the last recenter. A ray from the anchor is tested against every visible overlay with `ComputeOverlayIntersection`. On a hit, the cursor sits on that surface; otherwise it floats at `POINTER_DISTANCE`. Since the anchor isn't your current eye position, a second test runs along your line of sight to the cursor point, and anything nearer wins, so the cursor always lands on what you see under it. Overlays in `POINTER_IGNORE` are left out of both tests. A display-only panel, like a performance overlay locked to your view, has no input method, so SteamVR's laser passes through it, but `ComputeOverlayIntersection` still hits it, and the cursor stuck to it. The laser starts just before the cursor point, so an ignored panel nearer to you doesn't catch it either. Both tests ask SteamVR about every visible overlay, so a frame where nothing moved (the mouse, the anchor, the eye by more than 5 mm, which overlays show) reuses the last result, for up to 100 ms, since overlays can also move on their own. The dots' overlay settings go to SteamVR only when they change, and the pose goes to the driver, which keeps the last one, only when the laser would land 0.1 mm or more elsewhere, and at least every 100 ms.
OpenVR has no call to list other programs' overlays, so the helper runs `vrcmd --overlays` in the background. It includes hidden overlays, because a floating window's controls only appear while something hovers the window, and the cursor has to find them immediately.
OpenVR has no call to list other programs' overlays, so the helper runs `vrcmd --overlays` in the background. It includes hidden overlays, because a floating window's controls only appear while something hovers the window, and the cursor has to find them immediately. Each run is a shell and a new SteamVR client, about 30 ms of CPU, and it ran every second while the pointer was awake, which in gaze mode is all the time. Now it runs every 20 seconds, and at once when the pointer wakes, when the dashboard opens or closes, when a game starts or ends, and when a left click hits nothing (a panel that came up since). An overlay already on the list showing or hiding needs no new list: the helper checks the visibility of the ones it knows every 50 ms.
The laser starts partway along your line of sight to the cursor rather than at your eye. SteamVR sizes its hit dot by distance from the laser's origin, and a laser from the eye still shows a beam in each eye. Starting it close to the target makes the beam and the dot tiny, while `POINTER_ORIGIN_MARGIN` keeps the origin in front of the small window controls, which float a few centimetres in front of their panels. The helper's own white dot is the visible cursor. In empty space it's an interactive overlay that the laser lands on, so SteamVR never draws a laser into nothing.
@@ -141,7 +143,7 @@ Replacing a loaded driver's files, as re-running the installer used to do, leave
The dashboard follows whichever device summoned it or last pressed its trigger. Frametop adds "last used wins": moving a real controller releases the pointer, and the next mouse movement takes the laser back. Moving means faster than 0.35 m/s or 2 rad/s (both times `POINTER_CONTROLLER_PICKUP`, 1 by default) for 100 ms in a row, while the controller is tracked normally. A single sample over the limit used to be enough, and controllers resting on a desk took the laser back on a knock or a tracking jump while the mouse was in use. Small movements don't count; waking needs `POINTER_WAKE_COUNTS` of mouse motion within a second, so desk jitter doesn't steal the laser. While the pointer is awake, a tiny transparent overlay with `MakeOverlaysInteractiveIfVisible` keeps SteamVR's laser mouse on, since otherwise the first click would only switch the laser on.
When the headset comes off, SteamVR reports its activity level as idle at once and turns the displays off 5 seconds later (`power.turnOffScreensTimeout`), unless something keeps it awake. An awake pointer did, and so did the helper's `vrcmd` runs: each is a new SteamVR client, and a new client every second kept SteamVR out of standby. The helper now releases the pointer as soon as the headset is idle, ignores the mouse until you're wearing it again, and pauses the overlay list whenever the pointer is off.
When the headset comes off, SteamVR reports its activity level as idle at once and turns the displays off 5 seconds later (`power.turnOffScreensTimeout`), unless something keeps it awake. An awake pointer did, and so did the helper's `vrcmd` runs: each is a new SteamVR client, and a new client every second kept SteamVR out of standby. The helper now releases the pointer as soon as the headset is idle, ignores the mouse until you're wearing it again, and pauses the overlay list whenever the pointer is off. With the pointer off it also stops running its loop every 8 ms, about 116 wakeups a second for nothing: it waits up to 250 ms for a command on its socket (20 ms while it reads mapped controller buttons, which SteamVR input only offers by polling), and leaves the overlay lookups until the pointer wakes.
### Moving floating windows
@@ -153,6 +155,8 @@ SteamVR opens every input device only when it starts. When a Bluetooth mouse sle
Keyboards aren't grabbed by default, because a grabbed keyboard's keys went into a virtual keyboard nothing typed from; the relay forwards them to ft-screens instead.
The relay never waits on the pointer helper. Its socket to the helper used to block, so when the helper stalled (a layout placement or `grabprobe` holds it for seconds, and the gaze service fills its socket 90 times a second meanwhile), the whole relay stopped with it: keyboards, the volume keys, and pausing. Now what the helper doesn't take waits in order and goes out on the next loops. Mouse moves add up into one while they wait, and a scroll notch is dropped, since scrolling seconds late is no use; presses and releases are kept, so no button stays down. Mouse motion goes to the helper at most every 4 ms, rather than once per report, which from a 1000 Hz mouse was 1000 datagrams a second to a helper that runs every 8 ms; a button sends the motion before it first, so the click lands where the pointer was.
An ungrabbed keyboard reaches both sides at once. In VR, gamescope reads every input device itself (the SteamOS build's `InputStealer`, libinput with udev hotplug, so new devices too) and types into its focused app, and ft-screens types the same keys into the desktop. So Space in the desktop also paused Spotify on the dashboard. Typing now follows the last click. ft-screens sees clicks on its own screens, from the mouse or a controller. A click anywhere else is only visible for the mouse: overlay apps get SteamVR's `OverlayFocusChanged` (which panel the laser is on) but no controller button events, so the pointer helper reports the panel under the dot on each left press. ft-screens tells the relay where typing goes every second, from an unbound socket so the relay's replies can't loop back into its control socket, and the relay grabs pass-through keyboards while it's the desktop. A grab waits until the keyboard has no key down, so no key stays held on either side, and the relay lets go if ft-screens stops reporting. A program that reads every keyboard for a hotkey (a dictation tool, say) loses a grabbed keyboard. Repeating the keys on another input device doesn't work: gamescope reads that device too, whether it's the relay's virtual keyboard or one created later, and every Space, typed or dictated, paused Spotify again. So with `SHARE_KEYS=1` the relay sends a grabbed keyboard's keys to `@frametop_keys` as datagrams (`key <code> <value> <device name>`). It's off by default, because the relay can't tell who is listening: abstract sockets have no permissions, and any local process that binds the name first gets every key typed into the desktop, passwords included. A listener should accept only its own user (`SO_PASSCRED`) and skip any keyboard of its own that the relay grabs too.
Volume keys must never reach gamescope. With the openvr backend, gamescope sends volume up and down to Steam by moving keyboard focus to Steam for the key and then back to the previously focused surface. When nothing had focus, the one it moves back to is null, and wlroots aborts on a null focus surface (`wlr_seat_keyboard_notify_enter: Assertion 'surface' failed`), which ends the whole VR session. Keyboard focus is often empty while you work in VR, so one press of the headset's volume button could take everything down. gamescope reads the headset's buttons and every keyboard itself (`InputStealer`), as do SteamVR's processes, so the relay has to stop volume keys at the device. Grabbing `gpio-keys` would also take the headset's click button, so the relay remaps the volume entries in each device's keymap (`EVIOCSKEYCODE`) and handles the stand-in codes itself. That fix covers every device at once, including keyboards that aren't grabbed.
@@ -175,7 +179,15 @@ Flatpak apps need `XDG_DATA_DIRS` to include Flatpak's exports, or Plasma opens
The private runtime directory also moves the session's document portal to `$XDG_RUNTIME_DIR/frametop/doc`, and that broke saving and uploading in Flatpak apps. The file picker (xdg-desktop-portal 1.18.4 on SteamOS) gives a sandboxed app the host path of the file it picked, `/run/user/1000/frametop/doc/ID/NAME`. Inside the sandbox the portal is at `/run/flatpak/doc`, and `/run/user/1000` is a private per-app folder (`.flatpak/APP/xdg-run` in the runtime directory). So Brave created the missing folder there, "finished" the download into it, and the file vanished when the session cleaned up. The session script now links that path to `/run/flatpak/doc` in each installed app's folder before Plasma starts. Upstream xdg-desktop-portal fixed this after 1.22.1 (commit `69ba5e1`) by handing Flatpak apps `/run/flatpak/doc` paths, after which the links go unused.
A podman container's monitor process (conmon) stays in the cgroup of whatever started the container, and `distrobox enter` starts it on demand. When a Frametop service happened to start the `dev` container, stopping that service stopped the container and everything in it, including the desktop's compositor. `scripts/container-up.sh` starts the container in a systemd scope of its own before anything enters it.
A podman container's monitor process (conmon) stays in the cgroup of whatever started the container, and `distrobox enter` starts it on demand. When a Frametop service happened to start the `dev` container, stopping that service stopped the container and everything in it, including the desktop's compositor. `scripts/container-up.sh` starts the container in a systemd scope of its own before anything enters it. It then waits for distrobox-init to log `container_setup_done`, as `distrobox enter` does only for containers it starts itself. A new container's first start takes a minute or more (it installs distrobox's dependencies and sets up passwordless sudo), and an install that entered right away met a sudo password prompt with no terminal to answer it ([#9](https://github.com/DeeJanuz/frametop/issues/9)).
KWin renders with OpenGL through zink on Turnip, Vulkan on the same GPU vrcompositor needs to hit its frame time, and on the Frame that costs CPU too. The nested session started with KWin's defaults: blur and background contrast on (no `[Plugins]` group in its kwinrc) and animations at full length. Blur re-renders what's behind every translucent panel and menu each time it changes, and every animated frame is one more frame for KWin and ft-screens to draw and send. They're off by default in the Frametop desktop. The session script writes them before KWin starts, only where the desktop's own config has no value, once: System Settings deletes a setting put back to KDE's default rather than writing it, so without the marker in `frametoprc` a user who turned blur back on would lose it at the next start. The effect ids (`blur`, `contrast`) are the ones built into KWin 6.2.5 on SteamOS; KWin reads `<id>Enabled` from `[Plugins]`.
The nested session also runs the system's XDG autostart entries, being a KDE session. Discover's update notifier started `plasma-discover --mode update` in it (520 to 620 MB resident and about 9% of a core, plus `flatpak-system-helper` and AppStream downloads), and IBus started a daemon, the kimpanel panel and its GTK extension that nothing can use: KWin hands text input to the one input method it starts (`ft-textinput`), and the session drops `QT_IM_MODULE`, `GTK_IM_MODULE` and `XMODIFIERS`. The session hides both for this desktop only, with `Hidden=true` copies in its own autostart folder. The geoclue demo agent stays: it's what answers apps' location requests to Geoclue outside GNOME, and it costs nothing while idle. Orca's entry only starts in GNOME-family desktops.
Plasma 6.2.5 keeps each panel on a screen number (`lastScreen` in `plasma-org.kde.plasma.desktop-appletsrc`), and the numbers rank the enabled outputs by priority, so 0 is the primary screen. A panel whose number is past the screen count gets no view, and Plasma never moves it: the remap it runs at every start only moves a panel whose number has no desktop, and this desktop keeps a desktop for every output it has seen, spares included. So the taskbar was lost when the number of screens went down, and once it was found saved on a spare output, number 8 of a desktop with three screens ([#18](https://github.com/DeeJanuz/frametop/issues/18)). Before Plasma starts, the session runs `session/fix-panels.py`, which moves any panel numbered past the screen count, with its system tray's containment, to screen 0, keeping its widgets and settings. A panel stays put when screen 0 already has one on that edge, and comes back by itself if the screens do. The file is backed up to `<file>.ft-bak` first. Plasma's scripting can't do this while it runs (`panel.screen` is read-only in 6.2.5), so a lost taskbar comes back at the desktop's next start. `scripts/doctor.sh` and `scripts/report.sh` list the panels and their screens.
Remote desktop is a chain (krdp, then FreeRDP inside Xvnc) because nothing on SteamOS serves KWin over VNC directly. Kept connected all the time, it cost about a core with nobody watching: krdpserver 55 to 78% (it encodes H.264 in software with openh264: VA-API finds no driver for the Frame's GPU in the container), FreeRDP 16 to 27%, Xvnc 6 to 11%, and the bridge's layout check every 5 seconds another 4%. krdp creates its screencast session per RDP connection and drops it when the connection closes (`SessionController::onNewConnection` in krdp 6.7), so an idle krdpserver costs nothing and can stay up; only the RDP connection has to go. The bridge connects FreeRDP when a VNC client appears and disconnects 45 seconds after the last one leaves. Xvnc has no hook for its clients, so the bridge counts established connections to its port with `ss`, woken early by Xvnc's log output; looking with `ss` once a second cost about 0.9% of a core in bash, against about 0.1% this way. `Xvnc -inetd` from a systemd socket would start a server per connection and lose sharing between viewers. The layout check (`ft-layout remote-view`, which scans `/proc` for plasmashell and runs `kscreen-doctor -j`) now runs only while FreeRDP runs, and then only after `kwinoutputconfig.json` or `frametop-layout.json` changes, with one check a minute in case a change touched neither.
Program names stay within 15 characters, because Linux truncates process names there and the scripts find programs with `pgrep -x` and `pkill -x`. That's why the prefix is `ft-`.
@@ -189,6 +201,15 @@ Movement is judged within 10-second windows. On the mount, the head pose jittere
Staying awake while charging uses Steam's own setting rather than a logind sleep inhibitor. Steam suspends with `dbus-send ... login1.Manager.Suspend boolean:true`, and a block inhibitor does stop that (`CanSuspend` answers "challenge" while one is held), but it stops the power button too. `system_idle_suspend_ac_sec` is field 24004 of Steam's CMsgClientSettings. In Steam's SharedJSContext, reachable over CDP on port 8080 because Steam runs with `-cef-enable-debugging`, `SteamClient.Settings.SetSetting` takes a change as a base64 protobuf, the way Steam's Power page sends it (0 is never), and `settingsStore.clientSettings` has the current values.
## Pausing for VR games
Hiding the screens during a game kept them out of view, but Frametop kept using the headset. Measured on 2026-10-02 with gaze mode off and no game running, in shares of one core: our eye tracker (ft-eyes) about 60%, ft-eyegrab, ft-gaze and ft-gazed about 3 to 4% each; remote desktop (krdpserver, FreeRDP, Xvnc) about 2 cores while it ran; KWin about 13%, ft-screens about 4%. The gaze service ran at full rate whether gaze mode was on or not; now it idles while the gaze isn't used (gaze/README.md), and pausing stops it outright. Reading SteamVR's eye tracking 90 times a second also made it restart every 10 to 13 seconds during Beat Saber, and each restart took input focus from the game, which paused it (PR #13; since then ft-gaze skips SteamVR's gaze action during games, but our own tracker kept running). So pausing stops what costs the most and leaves windows where they are.
- A hidden screen still cost as much as a visible one. ft-screens sent every committed screen its frame callback at 90 Hz whether its overlay showed or not (since then, a hidden screen always gets one a second; see the frame rates in reference.md), so KWin kept drawing, and its apps with it. Paused, ft-screens sends the callbacks once a second. A Wayland client draws again only after its last frame's callback, so KWin's output stalls, KWin's own clients stop getting theirs, and the whole desktop idles, without anything losing its connection. A second's pace, rather than none, keeps any client that waits on a callback from waiting forever. Stopping KWin or the apps with SIGSTOP would free the same, but a Wayland peer that stops reading overflows the other side's 4 KB socket buffer, which ends the connection: that's how the live desktop died once when its KWin stalled (`Data too big for buffer`). They also sit in different cgroups (KWin under steam.service when the VR launcher starts it, ft-screens in the dev container's), so no single freeze stops them together.
- The relay does the pausing because it's the one part that always runs, and the pointer helper keeps running because stopping it leaves its virtual controller connected with its last pose (the driver has no staleness timeout), maybe holding a hand role, with the 3D mouse dead. Releasing it does the job. The helper already checks for a scene app twice a second, so it's what tells the relay a game started.
- The gesture has to work during a game, but SteamVR input reaches only the app with input focus, and an overlay with global input (`steamvr/globalActionSetPriority`) takes the buttons it binds from the game. vrserver's web socket on 127.0.0.1:27062, which its controller binding page uses for the live view, reports every controller component whatever has focus, and reading it takes nothing. The game sees the clicks too, so the default is a gesture games hardly use: both thumbsticks, together, twice. "Together" means within 0.3 seconds of each other, so a stick held down to sprint while the other clicks doesn't count. The stream is about 160 messages a second, nearly all capacitive sensing, so the reader parses only the few that mention a gesture's button. A controller's root path changes while the 3D mouse holds its hand role (`/devices/cv/<serial>` instead of `/user/hand/right`), so the reader looks the controllers up again (an HTTP request to vrserver): when the relay's 3D mouse connects or lets go, when a message comes from a device it doesn't know, and every 30 seconds. It used to be every 3 seconds.
- Resuming starts remote desktop through `systemd-run --scope`: started straight from the relay, it would join the relay's cgroup and end with the next relay restart.
## SteamOS updates
On the Frame, SteamVR is part of the OS image (`/opt/steamvr`, the `deckard-steamvr-rel` package), next to KWin, gamescope, and the kernel, so every SteamOS update can bring a new SteamVR too. Frametop survives updates: it lives in the home folder and the `dev` container, the Bluetooth fixes are in `/etc`, which SteamOS keeps across updates, and nothing goes into `/usr`. What an update can break is what Frametop uses from the image. The public OpenVR API is versioned and stays put. The rest is less certain: `IVRIPCResourceManagerClient`, which is newer than the header SteamVR ships; the text `vrcmd --overlays` prints; the eye tracker's shared memory layout; XRService's camera buffers; KWin's nested backend; and behavior Frametop works around, such as the SteamVR Settings page that `ComputeOverlayIntersection` can't find or the scale KWin's nested backend doesn't undo.
@@ -205,6 +226,5 @@ On the Frame, SteamVR is part of the OS image (`/opt/steamvr`, the `deckard-stea
- A controller button that shows the screens during a game. Games own the controllers, so this needs SteamVR input actions for ft-screens.
- Drawing KWin's cursor on the screens.
- Plasma can lose its panels when the number of screens goes down, because they're saved against a screen that no longer exists. Removing `plasma-org.kde.plasma.desktop-appletsrc` and `plasmashellrc` from `~/.config/frametop` brings the default panels back.
- Frame pacing and GPU cost with several busy screens haven't been measured.
- Real standby on a stand, with rendering and tracking paused, not just the backlight off. SteamVR has no call for it, and its activity level follows the proximity sensor.
+2 -2
View File
@@ -46,8 +46,8 @@ So a "Work" profile can put three screens around you with a browser, two termina
## How it works
- **Capture** (`ft-layout save NAME`, and Save as profile… in Display Settings). ft-layout captures the screens as before, then asks ft-floatd for the windows (`windows` on @frametop_float). ft-floatd has the KWin script report every window as it is now (`report-all`), then answers with every normal window: its desktop file name, the screen it's on, its rectangle there, and whether it's maximized. For floating windows it gives their panel's place, their size in pixels, and their scale. Windows with no desktop file name are kept by their process's command line (`/proc/<pid>/cmdline`) and window class. Windows of Plasma itself, the Frametop settings apps, and dialogs aren't recorded. If ft-floatd doesn't answer, the profile keeps the apps it had.
- **Apply** (`ft-layout use NAME`, Open profile in Display Settings). ft-layout makes the profile's hidden screens the screens' own setting, arranges the screens (which hides and shows them: ft-screens' `conceal` and `reveal`), then has ft-floatd open the apps (`profile NAME`; ft-floatd reads the windows from the layout file). If the screens can't be arranged, for example with the headset off and no head pose, the apps still open: the screens stay where they are, the profile's hidden screens still hide, and floating windows go relative to the screens wherever they are. ft-floatd goes through the entries app by app. It claims windows of that app already open (oldest first, each claimed once), and moves each to its entry's place: onto its screen at its rect (or maximized), or floating at its pose. For the entries left over, it launches the app once (`ft-float launch`, the same path as Launch as Standalone) and waits up to 30 seconds for its first window. Each window that shows up goes to the next entry's place. Once the first window has been up for 3 seconds (time for an app that restores its own windows to show them), ft-floatd launches the app again for each entry still waiting, and waits up to 30 seconds more. New windows are matched to the launch by process (or a child of it), or by desktop file name: single-instance and D-Bus-activated apps open their windows from a process that was already running.
- **Capture** (`ft-layout save NAME`, and Save as profile… in Display Settings). ft-layout captures the screens as before, then asks ft-floatd for the windows (`windows` on @frametop_float). ft-floatd has the KWin script report every window as it is now (`report-all`), then answers with every normal window: its desktop file name, the screen it's on, its rectangle there, and whether it's maximized. For floating windows it gives their panel's place, their size in pixels, and their scale. A window whose app id has no desktop file (a Flatpak app's X11 window can give its own: RustDesk's says `com.carriez.flutter_hbb`, its desktop file is `com.rustdesk.RustDesk`) is kept by the desktop file whose `StartupWMClass` names its window class. Windows with no desktop file name are kept by their process's command line (`/proc/<pid>/cmdline`) and window class. Windows of Plasma itself, the Frametop settings apps, and dialogs aren't recorded. If ft-floatd doesn't answer, the profile keeps the apps it had.
- **Apply** (`ft-layout use NAME`, Open profile in Display Settings). ft-layout makes the profile's hidden screens the screens' own setting, arranges the screens (which hides and shows them: ft-screens' `conceal` and `reveal`), then has ft-floatd open the apps (`profile NAME`; ft-floatd reads the windows from the layout file). If the screens can't be arranged, for example with the headset off and no head pose, the apps still open: the screens stay where they are, the profile's hidden screens still hide, and floating windows go relative to the screens wherever they are. ft-floatd goes through the entries app by app. It claims windows of that app already open (oldest first, each claimed once), and moves each to its entry's place: onto its screen at its rect (or maximized), or floating at its pose. For the entries left over, it launches the app once (`ft-float launch`, the same path as Launch as Standalone) and waits up to 30 seconds for its first window. Each window that shows up goes to the next entry's place. Once the first window has been up for 3 seconds (time for an app that restores its own windows to show them), ft-floatd launches the app again for each entry still waiting, and waits up to 30 seconds more. New windows are matched to the launch by process (or a child of it), or by desktop file name (found the same way as at capture): single-instance and D-Bus-activated apps open their windows from a process that was already running.
- **Default at start.** The session script runs `ft-layout start --wait 90`. That opens the profile in `FT_PROFILE` or `default_profile` (screens, then the apps once ft-floatd is up), or runs `apply --wait` if there's none. Start in profile on the Layout & profiles page sets `default_profile` (`ft-layout default NAME|none`). Plasma's session restore is turned off in the session (`ksmserverrc`: `loginMode=emptySession`).
- **Launcher entries.** Each profile gets `~/.local/share/applications/frametop-profile-<name>.desktop` ("Frametop: Work"), written when it's saved and removed when it's deleted. They show in SteamVR's Launch a program list, the Application Launcher, and KRunner. Running one (`ft-layout open NAME`) switches to that profile if the desktop runs. Otherwise it starts the desktop with `FT_PROFILE` set (`systemd-run`, as `desktops.sh start` does), which overrides `default_profile` for that start. That needs SteamVR to be running.
- **The action.** `profile:NAME` in the input relay (it runs `ft-layout use NAME`) for key combinations, mouse buttons, and controller buttons, with or without pointer mode. Input Settings lists one "Open profile NAME" action per profile.
+59 -13
View File
@@ -18,6 +18,16 @@ desktops.sh start | stop | restart | status | log [lines]
When the VR launcher starts the desktop, it inherits the Steam client's environment. The session script drops the client's runtime from it (`LD_LIBRARY_PATH`, the `STEAM_*` settings, and the Steam overlay's Vulkan layer), so apps in the desktop use the system's libraries, including its video codecs, just as they would after a normal login.
KWin's blur and background contrast effects and its animations are off in this desktop, because KWin draws on the headset's GPU, which SteamVR needs. The session script turns them off once, the first time it starts (it leaves a setting you already have alone, and marks it done in `~/.config/frametop/frametoprc`), so turning them back on sticks. In the Frametop desktop, System Settings → Window Management → Desktop Effects has Blur and Background Contrast, and General Behavior has Animation speed. Or from a terminal, then restart the desktop:
```
kwriteconfig6 --file ~/.config/frametop/kwinrc --group Plugins --key blurEnabled true
kwriteconfig6 --file ~/.config/frametop/kwinrc --group Plugins --key contrastEnabled true
kwriteconfig6 --file ~/.config/frametop/kdeglobals --group KDE --key AnimationDurationFactor 1
```
Two of the system's autostart programs don't start in this desktop: Discover's update notifier (`org.kde.discover.notifier`), which starts Discover to check for updates, and IBus (`ibus`), which can't reach the desktop's apps because KWin's input method is `input/ft-textinput`. The session script puts copies with `Hidden=true` in `~/.config/frametop/autostart` once (marked in `frametoprc`), and skips a name you already have a file for. Delete a copy to start that program again.
Settings are in two files, and Frametop Display Settings edits both. The screens (resolution, width in metres, scale, curve, which one has the taskbar) and their layout are in `~/.config/frametop-layout.json`. The backend, remote desktop, and pointer settings are in `~/.config/frametop.conf`; `session/frametop.conf.example` lists every key.
Restarting the desktop closes its windows. Before the unit stops, `session/keep-apps.sh` moves every program started in the desktop into a systemd scope of its own, so background work such as servers, tmux, and builds keeps running. An app that shuts down its own helper processes when its window closes will still lose them; run that kind of work outside the desktop, for example as a systemd user service.
@@ -28,12 +38,13 @@ Restarting the desktop closes its windows. Before the unit stops, `session/keep-
Each KWin window is one screen. ft-screens sets its size with an `xdg_toplevel` configure and KWin resizes the output to match, live. Frames arrive as DMA-BUFs and go to SteamVR through OpenVR's `IVRIPCResourceManagerClient::ImportDmabuf`, with no copy and no size limit.
Every screen is an overlay named `frametop.screen.N` with four controls:
Every screen is an overlay named `frametop.screen.N` with five controls:
- `.bar` moves the screen. Drag it with any laser or with the 3D mouse, whose right-drag tilts. Scrolling while you drag pushes the screen away or pulls it closer, along the line from your head.
- `.curve` bends the screen into a cylinder around you, using your current distance as the radius, or makes it flat again.
- `.roll` rolls the screen when you drag it sideways, like a knob. It snaps level within 2.5°, and scrolling on it turns 5° per notch.
- `.resize`, the tab on the bottom right corner, sets the width. Screens go down to 15 cm wide.
- `.reset`, left of the bar, puts every screen back in its layout around where you are now, like Meta+Shift+R (`ft-layout apply`).
The controls are sized from both the screen's width and its distance from you, follow the surface of a curved screen, and stay invisible until a laser or the 3D mouse's cursor lands on one or comes within about 1.5 times a button's size of it. While invisible they're still there, fully transparent, so SteamVR's laser can find them. They're translucent until a laser is on them, like SteamVR's own window controls.
@@ -51,7 +62,7 @@ The Visibility & pins tab of Frametop Display Settings decides when the screens
In the last three modes the hotkey shows the screens anyway. A screen can also be hidden on its own (Screens shown on the same tab, or `ft-layout hide N`): it stays hidden whatever the mode or the hotkey says, until it's shown again there. Windows on it stay put, and a new window that would open on it floats instead (ft-floatd). Profiles use this to show only some screens. Two more settings on the same tab cover VR games, which ft-screens detects as SteamVR scene apps:
- During VR games, the Always mode hides the screens unless the dashboard is open (the default), or leaves them up.
- Controllers on the screens. Visible screens can keep SteamVR's laser mouse on, so controllers work them with the dashboard closed, but that also takes the controllers away from a game. By default this is off while a VR game runs, and the 3D mouse or the dashboard works the screens. The other choices are always on, or only with the dashboard open, which also suits flatscreen games since they aren't scene apps.
- Controllers on the screens. Visible screens can keep SteamVR's laser mouse on, so controllers work them with the dashboard closed, but that also takes the controllers away from a game. By default this is off while a VR game runs, and the 3D mouse or the dashboard works the screens. Pointing a controller at a screen, a floating window, or the keyboard still turns its laser on, like SteamVR's own floating windows, and pointing away gives the game the controllers back. The other choices are always on, or only with the dashboard open, which also suits flatscreen games since they aren't scene apps.
Input from the lasers reaches KWin through ft-screens' own seat. Keys come from the input relay, from pass-through keyboards and any key a pointer device passes through. Typing follows your last click: after a click on a screen it goes to the desktop, even with the SteamVR dashboard open, and after a mouse click on any other panel (the dashboard, Steam, an app like Spotify) it goes there instead. While it goes to the desktop, the relay grabs pass-through keyboards so gamescope, which reads every keyboard itself, doesn't type them into the Steam app too. A program that watches every keyboard for a hotkey loses a grabbed one; with `SHARE_KEYS=1` in `~/.config/frametop.conf`, their keys also go to `@frametop_keys` for it. That's off by default, since any local process that binds the name first would get everything typed into the desktop. Hidden screens don't take typing.
@@ -66,12 +77,15 @@ place N x y z yaw pitch roll width N metres curve N radius|on|off
pin N|all left|right|head [matrix] unpin N|all size N w h
get N screens head state key code value scale N s vrkeyboard show|hide|toggle|close
visibility always|dashboard|gesture|toggle wrist degrees gesture left|right degrees
hide | show | toggle controllers always|outside_games|dashboard ingames hide|visible
hide | show | toggle controllers always|outside_games|dashboard ingames hide|visible pause on|off|state
conceal N|all reveal N|all concealed cutouts on|off|state cutouts predict on|off cutouts lead ms
float N mpp x y w h title unfloat N pose N matrix sub N k x y w h | sub N k off minimized N 0|1 carry N
rates focused in_view hidden rates? watch seconds phase ms
```
`conceal` and `reveal` hide and show one screen on its own (`ft-layout hide` and `show` send them), and `concealed` lists those screens. `cutouts` turns the hand cutouts on and off (`ft-handsctl cutouts`). The last line is ft-floatd's, for floating windows: N is a floating window's panel, numbered on from the screens, one per spare output. `float` gives the window's rectangle in its output, metres per pixel, and the title bar's height, and shows the panel; `unfloat` hides it. `pose` places it (a 3x4 matrix, standing universe), `sub` shows popup or dialog k over it, `minimized` hides it while its window is minimized, and `carry` moves it with the laser that pressed the window's own title bar.
Each screen draws at a frame rate for how much of it you see. KWin draws a screen only after ft-screens gives it a frame callback, and its apps wait for theirs, so the rate of callbacks is the screen's frame rate, for KWin and the apps on it alike. A screen is focused while you look at it (within 12 degrees of where your head points), while a laser or the mouse is on it or was in the last 1.5 seconds, while it's carried, and while you type on it; it gets every display frame. The rest of what you can see (within 60 degrees) gets 15 frames a second, and a hidden screen, one behind you, and everything while paused get one a second. A level goes up at once and comes down after a moment (1.5 s from focused, 0.5 s from in view). A video, or anything moving over a large part of a screen (6% or more of it, redrawn on 8 commits in a row, 10 or more a second), keeps every frame while in view. A floating window is a screen of its own here. Nothing that stands still costs anything at any rate: KWin sends a frame only when something on the screen changed. `rates F V H` sets the three rates in Hz (0: every display frame; default `0 15 1`, also `ft-screens --rates 0,15,1`), and `rates?` shows them, the display's rate, and for each screen its level, its milliseconds between frames, and whether it counts as a video. `watch S` gives every screen full rate for S seconds: remote desktop renews it while a VNC client is connected, since a viewer sees what KWin draws. The ticks (SteamVR events and the callbacks) come once per display frame, 1 ms after the vsync (`phase ms` changes that, for tuning), in step with the display rather than on a timer that drifted through the frame.
`conceal` and `reveal` hide and show one screen on its own (`ft-layout hide` and `show` send them), and `concealed` lists those screens. `pause on` (from the input relay, when Frametop pauses for a VR game) hides every screen and floating window whatever else says, and slows the desktop down; `pause off` undoes it. `cutouts` turns the hand cutouts on and off (`ft-handsctl cutouts`). The last line is ft-floatd's, for floating windows: N is a floating window's panel, numbered on from the screens, one per spare output. `float` gives the window's rectangle in its output, metres per pixel, and the title bar's height, and shows the panel; `unfloat` hides it. `pose` places it (a 3x4 matrix, standing universe), `sub` shows popup or dialog k over it, `minimized` hides it while its window is minimized, and `carry` moves it with the laser that pressed the window's own title bar.
## Input relay
@@ -85,6 +99,8 @@ The relay also owns the volume keys, on every device that has them, the headset'
desktops.sh relay install # enable it (starts with the next reboot or SteamVR start)
desktops.sh relay status | log | uninstall
input/input-relay.py --no-grab # try it without taking devices from SteamVR
input/test/keys-test.py # key combinations and modifier taps, against fake devices (safe next to the live relay)
steam/ft-steam menu # what Open Steam menu does; ft-steam check: Steam's UI still has the calls
```
The first time, the relay has to start before SteamVR, so reboot or restart SteamVR after installing it. After that it's safe to restart on its own: systemd keeps the virtual devices open in its file descriptor store (`FileDescriptorStorePreserve=yes`), so SteamVR keeps the same devices.
@@ -99,7 +115,7 @@ A mouse drives SteamVR the way a controller's laser does, but shows up as a smal
Whichever device you used last wins. Picking up a controller hands the laser back at once, and moving the mouse takes it again. When the headset comes off, the pointer lets go, so the displays can sleep, and it stays off until you're wearing the headset again.
To move a floating panel, left-drag its grab bar. The scroll wheel pushes and pulls it while you drag. Hold the right button while dragging and move the mouse to tilt the panel around the grab point; the right press isn't sent as a click. The tilt stays for the rest of the drag, and releasing the left button drops the panel as it is. A mapped Toggle dashboard button (or a Meta tap, with `META_DASHBOARD=1`) wakes the pointer if needed and holds the virtual system button for 0.12 s, because SteamVR ignores a press and release in the same instant.
To move a floating panel, left-drag its grab bar. The scroll wheel pushes and pulls it while you drag. Hold the right button while dragging and move the mouse to tilt the panel around the grab point; the right press isn't sent as a click. The tilt stays for the rest of the drag, and releasing the left button drops the panel as it is. A mapped Toggle dashboard button wakes the pointer if needed and holds the virtual system button for 0.12 s, because SteamVR ignores a press and release in the same instant. Open Steam menu / close dashboard (`steam_menu`) needs no pointer: `steam/ft-steam menu` asks Steam's UI, over its debugging port (`steam/steamui.py`), to show its dashboard overlay and focus the Steam frame's menu, or to hide the dashboard if it's up.
```
pointer/driver/build.sh && pointer/driver/install.sh install # then restart SteamVR
@@ -108,16 +124,17 @@ pointer/helper/run.sh status | log | restart
pointer/driver/install.sh probe # devices, hand roles, who owns the dashboard pointer
```
The pointer settings are in `~/.config/frametop.conf`: `POINTER_SENSITIVITY`, `POINTER_IDLE`, `POINTER_WAKE_COUNTS`, `POINTER_CONTROLLER_PICKUP`, `POINTER_DISTANCE`, `POINTER_CURSOR_DEG`, `POINTER_ORIGIN_FRACTION`, `POINTER_ORIGIN_MARGIN`, `POINTER_SCENE_RADIUS`, `POINTER_EDGE_REACH`, `POINTER_LASER_WIDTH`, `POINTER_IGNORE`, the head follow settings `POINTER_FOLLOW`, `POINTER_LEASH_DEG`, `POINTER_LEASH_DELAY`, `POINTER_LEASH_RETURN`, and `POINTER_FOLLOW_REACH`, and the gaze mode settings `POINTER_GAZE`, `POINTER_GAZE_RETAKE`, `POINTER_GAZE_NUDGE_MAX`, `POINTER_GAZE_HOLD`, `POINTER_GAZE_DOT`, `POINTER_GAZE_SHOW`, `POINTER_GAZE_MOUSE`, `POINTER_GAZE_MOUSE_MOVE`, and the keyboard clicks' `POINTER_HEAD_DEADZONE` and `POINTER_KEY_TAP`, and the gaze service's `GAZE_TRACKER` (SteamVR's eye tracker or our own) and `GAZE_EYE` (the eye bias). The example config explains each. Frametop Input Settings changes them live; after editing the file by hand, restart the relay or the helper (the gaze service reads its two again when the file changes).
The pointer settings are in `~/.config/frametop.conf`: `POINTER_SENSITIVITY`, `POINTER_IDLE`, `POINTER_WAKE_COUNTS`, `POINTER_CONTROLLER_PICKUP`, `POINTER_DISTANCE`, `POINTER_CURSOR_DEG`, `POINTER_ORIGIN_FRACTION`, `POINTER_ORIGIN_MARGIN`, `POINTER_SCENE_RADIUS`, `POINTER_EDGE_REACH`, `POINTER_LASER_WIDTH`, `POINTER_IGNORE`, the head follow settings `POINTER_FOLLOW`, `POINTER_LEASH_DEG`, `POINTER_LEASH_DELAY`, `POINTER_LEASH_RETURN`, and `POINTER_FOLLOW_REACH`, and the gaze mode settings `POINTER_GAZE`, `POINTER_GAZE_RETAKE`, `POINTER_GAZE_NUDGE_MAX`, `POINTER_GAZE_HOLD`, `POINTER_GAZE_DOT`, `POINTER_GAZE_SHOW`, `POINTER_GAZE_MOUSE`, `POINTER_GAZE_MOUSE_MOVE`, and the keyboard clicks' `POINTER_HEAD_DEADZONE` and `POINTER_KEY_TAP`, and the gaze service's `GAZE_TRACKER` (`auto`, the default: our own eye tracker when it's installed, else SteamVR's; or `own` or `steam`) and `GAZE_EYE` (the eye bias). The example config explains each. Frametop Input Settings changes them live; after editing the file by hand, restart the relay or the helper (the gaze service reads its two again when the file changes).
## Frametop Input Settings
A Kirigami app with a Python backend, in the Plasma menu under Settings. It runs in the `dev` container and talks to the relay over its control socket, `@frametop_relay`. It has eight pages:
A Kirigami app with a Python backend, in the Plasma menu under Settings. It runs in the `dev` container and talks to the relay over its control socket, `@frametop_relay`. It has nine pages:
- Devices lists every USB and Bluetooth mouse and keyboard, with a light that flashes when the device is used. Each device gets a role: 3D pointer (grabbed, drives the pointer; the default for anything with a mouse), Pass through (grabbed only while typing goes to the desktop; the default for keyboards, where a Meta tap toggles the dashboard if `META_DASHBOARD=1` is in `~/.config/frametop.conf`), or Ignore. A device is identified by its Bluetooth address, or its USB ids and name, so all of its input nodes share one role. Forget drops everything saved for a device.
- Buttons maps a pointer device's buttons. Choose Capture a button, press the button or key, then pick an action: a click, back, scroll, toggle dashboard, recenter, pointer on or off, head follow on or off, gaze pointer on or off, gaze precision, gaze drag, gaze quick check, faster or slower, reset the screen layout, hide or show the screens, open or close the keyboard, float a window in VR or put it back, put all floating windows back, Open profile NAME (one per profile, [profiles.md](profiles.md)), pass the key through, or nothing. Devices with saved mappings are listed even while they're asleep.
- Devices lists every USB and Bluetooth mouse and keyboard, with a light that flashes when the device is used. Each device gets a role: 3D pointer (grabbed, drives the pointer; the default for anything with a mouse), Pass through (grabbed only while typing goes to the desktop; the default for keyboards, whose key combinations work everywhere), or Ignore. A device is identified by its Bluetooth address, or its USB ids and name, so all of its input nodes share one role. Forget drops everything saved for a device.
- Buttons maps a pointer device's buttons. Choose Capture a button, press the button or key, then pick an action: a click, back, scroll, toggle dashboard, recenter, pointer on or off, head follow on or off, gaze pointer on or off, gaze precision, gaze drag, gaze quick check, faster or slower, reset the screen layout, hide or show the screens, open or close the keyboard, float a window in VR or put it back, put all floating windows back, pause or resume Frametop ([Pausing for VR games](#pausing-for-vr-games)), Open profile NAME (one per profile, [profiles.md](profiles.md)), pass the key through, or nothing. Devices with saved mappings are listed even while they're asleep.
- Controllers maps the Frame controllers' buttons (every button but the system button) to the same actions, except passing a key through and the gaze actions: gaze mode is a mouse and keyboard feature ([gaze-controllers.md](gaze-controllers.md)). Capture a button and press it on a controller, or pick it from the list. The controllers aren't input devices on the host; only SteamVR sees them. So the pointer helper reads them with SteamVR input (`pointer/helper/vrbuttons.h`, `pointer/helper/actions/`) and sends presses to the relay (`vrbtn right/a 1`), which does the mapped action. The helper only takes the buttons that are mapped (the relay tells it with `vrbind`), at an overlay-global priority, and only while no game (scene application) runs, so games keep every button; with In games on (`controller_in_games`), a mapped button is taken from games too. That needs SteamVR's "Enable global input from overlays (Experimental)" setting (`steamvr/globalActionSetPriority`), which the page's Global input switch turns on and off. Mappings are saved as `controller_buttons` in `~/.config/frametop-input.json`.
- Keyboard sets when Frametop's keyboard opens: whenever a text field is selected; only while no pass-through keyboard is connected (the default; keyboards other programs make through uinput, like frame-voice's, don't count); only with a mouse or controller button mapped to Open/close keyboard; or never, which turns the button off too. Keep it open (on by default, `vr_keyboard_persist`) leaves it open after the text field loses focus. The mode is saved as `vr_keyboard` in `~/.config/frametop-input.json`, and the page lists the keyboards that count as connected. Its Key combinations section maps modifiers plus a key, on any keyboard, to any action but passing a key through or nothing. The gaze clicks (Gaze left click and Gaze right click) only go on key combinations. The defaults are Meta+J (gaze left click), Meta+K (gaze right click), and Meta+Shift+F (float window in VR or put it back); remove them or add others there. The combination's last key isn't typed, and the modifiers still reach the app. They're saved as `key_bindings` in the same file.
- Game optimization has the pause for VR games: its state with Pause now or Resume, whether VR games pause Frametop by themselves, the controller gesture (one or two buttons, pressed once or twice; one button always takes two presses), what happens to the desktop, and the sound. They're saved as `pause_auto`, `pause_gesture`, `pause_desktop`, and `pause_sound` in `~/.config/frametop-input.json`. See [Pausing for VR games](#pausing-for-vr-games).
- Keyboard sets when Frametop's keyboard opens: whenever a text field is selected; only while no pass-through keyboard is connected (the default; keyboards other programs make through uinput, like frame-voice's, don't count); only with a mouse or controller button mapped to Open/close keyboard; or never, which turns the button off too. Keep it open (on by default, `vr_keyboard_persist`) leaves it open after the text field loses focus. The mode is saved as `vr_keyboard` in `~/.config/frametop-input.json`, and the page lists the keyboards that count as connected. Its Key combinations section maps modifiers plus a key, or one modifier tapped on its own, on any keyboard, to any action but passing a key through or nothing, or to Run a command…: a command line the input relay runs with `sh -c` when you press the keys (`command:CMD`). The command runs as the relay's user service, outside the desktop's session, with `layout/`, `float/` and `steam/` on its `PATH` (so `ft-layout use Work` or `ft-float launch org.kde.dolphin` work as they are), and its output goes to the relay's journal. The gaze clicks (Gaze left click and Gaze right click) only go on key combinations. The defaults are a Meta tap (open the Steam menu, or close the dashboard), Meta+J (gaze left click), Meta+K (gaze right click), Meta+Shift+F (float window in VR or put it back), and Meta+Alt+Tab and Meta+Alt+Shift+Tab (spin the panels: every screen and floating window turns about your head, so the next one on the right or left comes to the front; ft-screens' `spin next|prev|<degrees>`); remove them or add others there. A tap is a press and release with no other key, mouse button, or scroll in between; a bound one sends the desktop F24 before the release, so Plasma's launcher doesn't open on it. The combination's last key isn't typed, and the modifiers still reach the app; while typing goes to Steam rather than the desktop, keyboards aren't grabbed, so Steam or the game sees the keys too. They're saved as `key_bindings` in the same file; a file with its own list, even an empty one, gets no defaults.
- Pointer has a Head follow switch and sliders for the pointer settings, which apply immediately, and a Recenter button.
- Ignored panels lists the SteamVR overlays that are showing, grouped by app (the first two parts of the overlay key, such as `sasaken.frame-perf-overlay`), from the pointer helper (`overlays`). Tick a panel, or Ignore the whole app, and the pointer passes through it to what's behind. It's for panels you only look at, like a performance overlay that follows your view. The list is saved as `POINTER_IGNORE` in `~/.config/frametop.conf`: comma-separated overlay keys, where a shell pattern like `vendor.app*` covers a whole app, including panels it opens later. The helper reloads at once. Frametop's own screens aren't listed, and entries for apps that aren't open are listed below, to remove.
- Gaze has the gaze pointer switch (on now and from now on; a mapped button toggles it until the helper restarts), what the mouse's left button and movement do, the gaze dot, the eye tracker and eye bias, the gaze mode sliders, the gaze service's state (headset, samples per second, how often the tracker is losing each eye, the calibration, the nudges learned), and Quick check, Calibrate, and Check headset fit (each in a panel in the headset), Reload calibration, and Forget nudges. The gaze probe, a development tool, is in the page's overflow menu.
@@ -127,7 +144,7 @@ Device rules are saved in `~/.config/frametop-input.json`. `input-settings/insta
## Frametop Display Settings and ft-layout
When the desktop starts, its screens arrange themselves around where you're facing. You can move them by hand at any time and put them back with Meta+Shift+R, the Reset Screen Layout menu entry, Arrange now in the app, or a mouse button mapped to Reset desktop screen layout.
When the desktop starts, its screens arrange themselves around where you're facing. You can move them by hand at any time and put them back with Meta+Shift+R, the reset button left of any screen's bar, the Reset Screen Layout menu entry, Arrange now in the app, or a mouse button mapped to Reset desktop screen layout.
The desktop's own screen arrangement follows where the screens are around you, whatever their numbers: a screen you see to the left of another is to its left in Plasma too, so the pointer and dragged windows cross straight to it. Screens one above the other stack, and screens pinned to a wrist or your head come last. It's updated at startup, after arranging or saving the layout, and half a second after you let go of a screen you moved. With the headset off there's no head pose to go by, and the arrangement stays as it was.
@@ -197,14 +214,41 @@ power/run.sh off | on # the displays off now, or back on
power/run.sh log
```
## Pausing for VR games
Paused, Frametop leaves the headset's CPU and GPU to a VR game. The input relay does it (`input/game_pause.py`), since it's the one part that always runs:
- The gaze service stops (`frametop-gaze`: ft-gazed, ft-gaze, our own eye tracker, the gaze panel), so nothing reads SteamVR's eye tracking. Our frame grabber, the root service `ft-eyegrab`, goes idle by itself 3 seconds after our eye tracker stops asking it for frames.
- Hand tracking stops if it runs (`frametop-camd`, `frametop-hands`).
- The desktop, as the Game optimization page of Frametop Input Settings says (`pause_desktop`): hidden (the default) or closed. Hidden, ft-screens hides every screen and floating window whatever the visibility mode, the hotkey, or the dashboard says, and gives KWin a frame callback once a second instead of every display frame. KWin draws a screen only after its frame callback, and its apps wait for theirs, so the desktop hardly draws, but its windows stay open. Remote desktop stops if it runs (`session/remote-ctl.sh`). Closed, `desktops.sh stop` closes the desktop and its windows, and resuming starts it again (about 12 seconds), in its start profile if it has one.
- The relay lets go of the 3D mouse and feeds pointer devices to its virtual mouse and keyboard, as with `POINTER=0`. Typing goes to Steam. Mapped buttons and key combinations do nothing but pausing, the Steam menu, and commands; a key combination that does nothing is typed as usual.
Resuming starts again only what pausing stopped, and plays a second sound. The pointer helper and ft-powerd keep running: they cost little, the helper is what says a game started, and stopping it would leave its virtual controller connected with its last pose.
Ways to pause and resume:
- The controller gesture, by default both thumbsticks clicked together twice: both go down within 0.3 seconds of each other, and the second time within 0.7 seconds of the first. The relay reads it from vrserver's web socket (`input/vrws.py`), which works whatever has input focus and takes nothing from the game, so the game sees the clicks too. The Game optimization page changes it: one or two of the buttons the Controllers page lists, pressed once or twice (one button always takes two), or none.
- The Pause/resume Frametop action, on a mouse button, a key combination, or a controller button (outside games, like every mapped controller button).
- VR games, with Pause while a VR game runs on (`pause_auto`, the default). The pointer helper tells the relay when a scene app starts and ends (`vrgame 1|0`, repeated every 5 seconds). A game starting pauses Frametop. A pause that starts while a game runs ends 5 seconds after the game does, unless another game starts first. Resumed during a game, Frametop stays on until that game ends. A pause that starts outside a game lasts until you resume. Flatscreen games aren't scene apps, so they don't pause it.
- From a terminal or a script:
```
input/ft-pause on | off | toggle # pause or resume
input/ft-pause status # the state as JSON (the relay's "pause ?")
input/vrws.py 10 # the controllers' buttons from vrserver's web socket, for 10 s
input/test/pause-test.py # the gesture and the automatic pause, offline
```
The state outlives a relay restart, in `/run/user/UID/frametop-pause.json`. A SteamVR restart while paused starts the gaze service with it, and the relay stops it again when the pointer helper comes back.
## Gaze pointer (experimental)
In gaze mode the 3D mouse's pointer goes where you look, and the mouse or the keyboard does the last bit. It needs the gaze service, which `install.sh` offers (yes by default) and `gaze/run.sh install` installs on its own: it builds it and runs `gaze/ft-gazed` as `frametop-gaze.service`, which starts with SteamVR. Turn gaze mode on with the Gaze page of Frametop Input Settings, `gaze/ft-gazectl on`, `POINTER_GAZE=1`, or a button or key combination mapped to Gaze pointer on/off.
In gaze mode the 3D mouse's pointer goes where you look, and the mouse or the keyboard does the last bit. It needs the gaze service, which `install.sh` offers (yes by default) and `gaze/run.sh install` installs on its own: it builds it and runs `gaze/ft-gazed` as `frametop-gaze.service`, which starts with SteamVR. The service idles while the gaze isn't used: its eye tracker reader and our own eye tracker run only while gaze mode is on and someone wears the headset, while a check or the calibration runs, or while the Gaze page of Frametop Input Settings is open, and stop 30 seconds after ([gaze/README.md](../gaze/README.md)). Turn gaze mode on with the Gaze page of Frametop Input Settings, `gaze/ft-gazectl on`, `POINTER_GAZE=1`, or a button or key combination mapped to Gaze pointer on/off.
- Meta+J left-clicks and Meta+K right-clicks where you look. A quick tap clicks where the dot was at the press. Hold instead, and the dot stays put in your view: turn your head until it's on what you meant, and let go to click there. Held still for `POINTER_GAZE_HOLD` (0.5 s), the press becomes a real one, and your head drags. Meta+K with Meta+J held presses where the dot is now, to drag from there, and a second Meta+K during that drag (a double Meta+K) pans and tilts what you're dragging while it's held.
- The mouse's buttons work the same way, with the mouse steering instead of your head (`POINTER_GAZE_MOUSE=precision`, the default): the right button with the left held starts a drag, and a double right click pans and tilts what you're dragging. With `POINTER_GAZE_MOUSE_MOVE=held`, the default, the mouse only corrects: while the gaze has the pointer, moving it does nothing unless a button is held. `free` lets the mouse take the pointer any time. With the gaze stale for a second, in a game, or with the headset off, the mouse works as usual.
- A correction before a click teaches the gaze service the tracker's error there. A correction bigger than `POINTER_GAZE_NUDGE_MAX` (55 degrees) isn't learned; it opens a quick check instead.
- Calibration and checks run in a panel fixed to the headset (`gaze/panel/ft-gazepanel`, which the gaze service runs), from the Gaze page: Quick check is one dot, and also opens when you put the headset on. Calibrate is three rounds of dots, dark to bright; look at each dot and left click or press Meta+J to take it. Check headset fit shows, live, how well the tracker sees each eye. A right click or Meta+K closes the panel. Gaze mode coming on without a calibration opens Calibrate by itself.
- Calibration and checks run in a panel fixed to the headset (`gaze/panel/ft-gazepanel`, which the gaze service runs), from the Gaze page: Quick check is one dot, and also opens when you put the headset on. Calibrate is three rounds of dots, dark to bright; look at each dot and left click or press Meta+J to take it. Check headset fit shows, live, how well the tracker sees each eye. A right click or Meta+K closes the panel. Gaze mode on without a calibration opens Calibrate by itself, as soon as your eyes are seen. If gaze mode is on but can't follow your eyes yet (no calibration, the calibration can't open, the gaze service not running), the Gaze page says why under the Gaze pointer switch, and `gaze/ft-gazectl on` notes it.
[gaze/README.md](../gaze/README.md) has the details, our own eye tracker, and the gaze probe, a development tool.
@@ -229,6 +273,8 @@ It listens on port 5900 on the Frame's Tailscale address only, not the LAN, so i
No VNC server can capture KWin on SteamOS directly: `krfb` needs `xdg-desktop-portal-kde`, which SteamOS doesn't ship, and `wayvnc` only works with wlroots compositors. So `session/remote-desktop.sh` captures the desktop with KDE's `krdpserver --plasma` on `127.0.0.1:3390`, and `session/vnc-bridge.sh` runs TigerVNC's `Xvnc` on display `:20` with a FreeRDP client inside it and serves that. Both run in the `dev` container, and the extra hop adds a little latency. krdp streams every screen; the VNC screen is the primary's size, and the FreeRDP window is shifted so the primary fills it (`ft-layout remote-view` gives the offset). krdp's own `--monitor` would stream just one screen, but it maps the pointer as if that screen sat at 0,0, so clicks would miss. When the layout changes, the VNC screen resizes and FreeRDP reconnects within a few seconds.
FreeRDP runs only while a VNC viewer is connected, because while it's connected krdp captures and encodes every redraw. With no viewer, krdp has no RDP connection and so captures nothing, and Xvnc shows a black screen. When a viewer connects, the bridge starts FreeRDP, and the desktop appears about 3 seconds later; FreeRDP stops 45 seconds after the last viewer leaves (`VNC_IDLE_SEC` in the bridge's environment). The bridge looks for viewers with `ss` whenever Xvnc logs something, as it does for every connection, and every 5 seconds otherwise. While a viewer is connected, the bridge asks ft-screens to draw every screen at full rate (`watch 15` on `@ft_screens`, renewed every 5 seconds), so screens you aren't looking at in the headset, or a headset on a stand, don't stream at a low rate. It reads the primary screen's place again (`ft-layout remote-view`) only while FreeRDP runs, after `~/.config/frametop/kwinoutputconfig.json` or `~/.config/frametop-layout.json` changes, and once a minute.
With remote access on, the nested KWin runs with `KWIN_WAYLAND_NO_PERMISSION_CHECKS=1` and `KWIN_SCREENSHOT_NO_PERMISSION_CHECKS=1`, so any app in the Frametop desktop could capture its screens or inject input. The second one lets scripts take screenshots through KWin's `org.kde.KWin.ScreenShot2` D-Bus interface. This applies only to that desktop, not the stock one. Port 3389 is SteamOS's own `xrdp`, which starts a separate X11 session rather than showing the VR desktop.
## Limits
+11
View File
@@ -378,6 +378,17 @@ function run(c) {
case "activate":
if (w) workspace.activeWindow = w;
break;
case "activate-output": { // the top window on that output (a spin brought it to the front)
const order = workspace.stackingOrder;
for (let i = order.length - 1; i >= 0; --i) {
const o = order[i];
if (o.deleted || o.minimized || o.hidden || !o.managed || !o.output) continue;
if (o.output.name !== c.output || !o.normalWindow || o.popupWindow) continue;
workspace.activeWindow = o;
break;
}
break;
}
case "minimize":
if (w) w.minimized = c.on;
break;
+38 -6
View File
@@ -18,6 +18,8 @@ command-line side). Replies go to the sender:
("float pointer" is the float key: the window under the pointer, else the active one,
floated or docked; the input relay sends it for float_toggle, and "dock all" for dock_all)
dock N | close N | resize N W H | scale N STEPS (ft-screens, N = its screen)
front N (ft-screens: a spin brought panel N to the front: make its window, or the top one
on a screen, KWin's active window)
Spare outputs are WL-<screens> .. WL-<screens + slots - 1>. A floating window's output is its
frame plus a margin on each side (FLOAT_MARGIN pixels), so menus have room; the panel shows
@@ -229,6 +231,24 @@ def cmdline(pid):
return []
def desktop_name(app, cls):
"""The desktop file name for a window's app id and class. A Flatpak app's window can give an
id with no desktop file: RustDesk's (an X11 window) says com.carriez.flutter_hbb, and its
desktop file is com.rustdesk.RustDesk. That file's StartupWMClass names the window's class
then. The app id itself when nothing matches."""
try:
if not app or Gio.DesktopAppInfo.new(app + ".desktop"):
return app
except TypeError: # PyGObject raises for the NULL a missing desktop file returns
pass
names = {n.lower() for n in (app, cls) if n}
for info in Gio.AppInfo.get_all():
wm = info.get_startup_wm_class() if isinstance(info, Gio.DesktopAppInfo) else None
if wm and wm.lower() in names:
return info.get_id().removesuffix(".desktop")
return app
class Launch:
"""An app we started: its first window floats, or (for a profile) its windows go to the
profile's entries for it, in order."""
@@ -745,7 +765,10 @@ class Daemon:
Returns (reply, pid or None)."""
if app:
app = app.removesuffix(".desktop")
info = Gio.DesktopAppInfo.new(app + ".desktop")
try:
info = Gio.DesktopAppInfo.new(app + ".desktop")
except TypeError: # PyGObject raises for the NULL a missing desktop file returns
info = None
if info is None:
return f"error no app {app}", None
pids = []
@@ -776,8 +799,10 @@ class Daemon:
return None
chain = pid_chain(int(ev.get("pid") or 0))
app = ev.get("app", "")
# (An X11 window in a Flatpak gives its pid in the sandbox: only its app id can match.)
apps = {app, desktop_name(app, ev.get("cls", ""))} if app and any(la.app for la in self.launches) else {app}
for la in self.launches:
if any(p in chain for p in la.pids) or (la.app and app and la.app == app):
if any(p in chain for p in la.pids) or (la.app and app and la.app in apps):
if not la.entries or len(la.entries) <= 1:
self.launches.remove(la)
return la
@@ -841,7 +866,7 @@ class Daemon:
for wid, ev in self.windows.items():
if not recordable(ev):
continue
entry = {"app": ev["app"]} if ev.get("app") else {"cmd": cmdline(ev.get("pid")), "class": ev.get("cls", "")}
entry = {"app": desktop_name(ev["app"], ev.get("cls", ""))} if ev.get("app") else {"cmd": cmdline(ev.get("pid")), "class": ev.get("cls", "")}
if not entry.get("app") and not entry.get("cmd"):
continue
f = self.floats.get(wid)
@@ -868,7 +893,7 @@ class Daemon:
return out
def window_key(self, ev):
return ev.get("app") or json.dumps(cmdline(ev.get("pid")))
return desktop_name(ev.get("app", ""), ev.get("cls", "")) or json.dumps(cmdline(ev.get("pid")))
def open_profile(self, name):
"""Open a profile's apps (additive: nothing closes)."""
@@ -884,9 +909,9 @@ class Daemon:
if key != "[]":
groups.setdefault(key, []).append(e)
claimed = set()
keys = {wid: self.window_key(ev) for wid, ev in self.windows.items() if recordable(ev)}
for key, entries in groups.items():
have = [ev for wid, ev in self.windows.items()
if wid not in claimed and recordable(ev) and self.window_key(ev) == key]
have = [ev for wid, ev in self.windows.items() if wid not in claimed and keys.get(wid) == key]
for e, ev in zip(entries, have):
claimed.add(ev["id"])
self.place_entry(ev, e)
@@ -1040,6 +1065,13 @@ class Daemon:
for f in list(self.floats.values()):
self.dock(f)
return "ok"
if cmd == "front" and len(rest) == 1 and rest[0].isdigit():
f = self.by_panel(int(rest[0]))
if f:
self.command(cmd="activate", id=f.id)
else: # a screen: its output is WL-<N - 1>
self.command(cmd="activate-output", output=f"WL-{int(rest[0]) - 1}")
return "ok"
if cmd in ("dock", "close", "resize", "scale") and rest and rest[0].isdigit():
f = self.by_panel(int(rest[0]))
if not f:
+59
View File
@@ -0,0 +1,59 @@
# Install with FrameDrop (proof of concept)
[FrameDrop](https://framedropvr.com) is a Windows app that sideloads onto a Steam Frame: it copies a build to the headset and adds it to the Steam library. Issue #25 asks for an "Install with FrameDrop" button. Frametop isn't an app FrameDrop can copy over as is: it builds in a container, installs user services and a SteamVR driver, and asks questions in a terminal. So FrameDrop installs a small installer instead. Playing "Frametop" from the library runs the one-line installer (`get.sh --yes`) and shows its progress.
Nothing here is published yet: no release asset, no manifest on Pages, no button.
## How FrameDrop installs a Linux zip
It uses Valve's SteamOS Devkit path: pair once with the headset's devkit service, then rsync the unpacked zip into `~/devkit-game/<name>` over SSH, and register it with Steam as a Devkit Game with a start command. `devkit.sh` here makes the same calls with Valve's devkit-utils, so all of this can be tested on the Frame without a PC.
## What the probe found (SteamOS 0.3.0, build 20260922.6101926)
`probe/probe.sh`, started as a Devkit Game, recorded:
- Devkit titles run on the host, not in a container, as user `steamos`, from a process tree that Steam's reaper owns. This held even with the compat tool set to `SteamLinuxRuntime_4-arm64`: Steam recorded the mapping and still ran it on the host.
- On the host, everything the installer needs works: git, curl to GitHub, podman (sees the `dev` container), `systemctl --user`, `systemd-run --user`, and GTK 4 with libadwaita.
- A GTK window opens in gamescope (an X11 window on `:1`, drawn through gamescope's Vulkan WSI).
- Steam puts its overlay in `LD_PRELOAD` and Steam runtime paths in `LD_LIBRARY_PATH` and `PATH`. Every host tool prints a preload error unless they're cleared.
- Inside the Steam Linux Runtime 4 container (started by hand with its `run` script), there's no git, podman, systemctl, or GTK, but `flatpak-spawn --host` runs commands on the host.
- Steam refuses Devkit Game names with a `-` ("missing/invalid arguments").
- Steam doesn't make the start command executable: without the exec bit, the title exits in a second and nothing runs.
## The installer
`installer/frametop-install.sh` is the start command.
1. In the container, it starts itself again on the host with `flatpak-spawn --host`.
2. It clears Steam's preload and library paths.
3. It runs `curl get.sh | bash -s -- --yes` in a transient user service, `frametop-framedrop-install`, unless one is already running. The service is used because Steam ends the title's whole process tree when it's quit, and starts it with an OOM score of 900.
4. `installer/progress.py` (GTK 4 and libadwaita) follows the service's log, shows `install.sh`'s steps as a progress bar, and reports the result. Closing it leaves the install running. Playing the title again reattaches.
`--yes` keeps the version that's installed, or installs stable. It skips the parts that need sudo (our eye tracker and the Bluetooth fixes) and the SteamVR restart. The window says to restart SteamVR.
`--dry-run` clones into `~/.cache/frametop-framedrop/dry-run` and stops there (`get.sh --clone-only`).
## Try it on the Frame
```
framedrop/devkit.sh add FrametopTest framedrop/installer "./frametop-install.sh --dry-run"
framedrop/devkit.sh run FrametopTest # or Play it from the Steam library
framedrop/devkit.sh remove FrametopTest
framedrop/devkit.sh add FrametopProbe framedrop/probe "./probe.sh native" # the probe
```
The probe writes `~/.cache/frametop-framedrop/probe-native.log`, and the installer writes `~/.cache/frametop-framedrop/install.log`.
## Build the download
```
framedrop/build.sh [ZIP_URL]
```
This writes `framedrop/build/Frametop.zip` (reproducible) and `frametop.framedrop.json`, FrameDrop's manifest with the zip's sha256. By default, `ZIP_URL` points at a `framedrop-installer` release asset. The button's link would be `https://framedropvr.com/install?manifest=https://deejanuz.github.io/frametop/frametop.framedrop.json`, with the manifest committed to main for Pages.
## Open questions, for a test with FrameDrop on a Windows PC
- Does FrameDrop keep or set the exec bit on `frametop-install.sh`? A zip unpacked on Windows loses it, and without it nothing runs.
- What start command does FrameDrop pick for this zip, and which runtime?
- Does the manifest's `name` become the Devkit Game name? It has to stay free of `-`.
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env bash
# Build the FrameDrop download: framedrop/build/Frametop.zip (the installer in a "Frametop"
# folder) and framedrop/build/frametop.framedrop.json, the manifest an "Install with
# FrameDrop" button points at. The zip is reproducible: same files, same sha256.
#
# Usage: framedrop/build.sh [ZIP_URL]
# ZIP_URL where the zip will be downloaded from (default: the framedrop-installer release)
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
url=${1:-https://github.com/DeeJanuz/frametop/releases/download/framedrop-installer/Frametop.zip}
out=$here/build
mkdir -p "$out"
python3 - "$here/installer" "$out/Frametop.zip" <<'EOF'
import os, sys, zipfile
src, dest = sys.argv[1:]
with zipfile.ZipFile(dest, "w", zipfile.ZIP_DEFLATED) as z:
for name in ("frametop-install.sh", "progress.py"):
info = zipfile.ZipInfo(f"Frametop/{name}", date_time=(2026, 1, 1, 0, 0, 0))
info.create_system = 3 # unix, so the permissions below count
info.external_attr = (0o100755 if os.access(os.path.join(src, name), os.X_OK) else 0o100644) << 16
info.compress_type = zipfile.ZIP_DEFLATED
with open(os.path.join(src, name), "rb") as f:
z.writestr(info, f.read())
EOF
sha=$(sha256sum "$out/Frametop.zip" | cut -d' ' -f1)
python3 - "$url" "$sha" >"$out/frametop.framedrop.json" <<'EOF'
import json, sys
url, sha = sys.argv[1:]
print(json.dumps({
"schema": "framedrop.install/v1",
"name": "Frametop",
"files": [{"url": url, "sha256": sha}],
}, indent=2))
EOF
echo "built $out/Frametop.zip ($sha)"
echo " $out/frametop.framedrop.json"
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env bash
# Do on the Frame what FrameDrop does from a PC: copy a folder into ~/devkit-game/NAME and
# register it with Steam as a "Devkit Game" (Valve's devkit-utils, the same calls FrameDrop and
# the SteamOS Devkit Client make over SSH). For testing the FrameDrop installer and the probe
# without a PC. Steam must be running, and Developer Mode on.
#
# Usage: devkit.sh add NAME DIR COMMAND [--compat TOOL]
# devkit.sh run NAME # start it, as the library's Play button does
# devkit.sh remove NAME # delete the folder and the Steam entry
# devkit.sh list
#
# NAME can't contain "-": Steam answers "missing/invalid arguments". COMMAND is relative to
# the folder, like FrameDrop's start command ("./probe.sh native"). --compat sets the runtime
# (SteamLinuxRuntime_4-arm64, say); on SteamOS 0.3.0 Steam recorded it but still ran the
# title on the host. There's no environment option: this Steam ignores the devkit env file.
#
# devkit-utils is Valve's (LGPL, gitlab.steamos.cloud/devkit/steamos-devkit). FrameDrop and
# the devkit client copy it to ~/devkit-utils; if that isn't there, it's fetched at a pinned
# commit into ~/.cache/frametop-framedrop.
set -euo pipefail
devkit_rev=a00ceb7d91ea44a0c3e714a91a06417d6e5cdb33
cache=$HOME/.cache/frametop-framedrop
usage() { sed -n '7,10p' "$0" | sed 's/^# \{0,1\}//' >&2; exit 2; }
utils() {
if [ -e "$HOME/devkit-utils/steam-client-create-shortcut" ]; then
echo "$HOME/devkit-utils"; return
fi
if [ ! -e "$cache/devkit-utils/steam-client-create-shortcut" ]; then
echo "fetching devkit-utils ($devkit_rev)" >&2
local tmp
tmp=$(mktemp -d)
git -C "$tmp" init -q
git -C "$tmp" fetch -q --depth 1 https://gitlab.steamos.cloud/devkit/steamos-devkit.git "$devkit_rev"
git -C "$tmp" checkout -q FETCH_HEAD
mkdir -p "$cache"
rm -rf "$cache/devkit-utils"
cp -r "$tmp/client/devkit-utils" "$cache/devkit-utils"
rm -rf "$tmp"
fi
echo "$cache/devkit-utils"
}
[ $# -ge 1 ] || usage
cmd=$1; shift
case $cmd in
add)
[ $# -ge 3 ] || usage
name=$1 src=$2 start=$3; shift 3
case $name in *-*) echo "NAME can't contain '-' (Steam refuses it)" >&2; exit 2 ;; esac
compat=
while [ $# -gt 0 ]; do
case $1 in
--compat) compat=${2:?}; shift ;;
*) usage ;;
esac
shift
done
u=$(utils)
dir=$(python3 "$u/steamos-prepare-upload" --gameid "$name" | python3 -c 'import json,sys; print(json.load(sys.stdin)["directory"])')
# FrameDrop rsyncs the unpacked zip; --delete as a clean upload would.
rsync -a --delete "$src/" "$dir/"
parms=$(python3 - "$name" "$dir" "$start" "$compat" <<'EOF'
import json, sys
name, directory, start, compat = sys.argv[1:]
print(json.dumps({
"gameid": name, "directory": directory,
"argv": [start], "env": {},
"settings": {"steam_play": "0", "compat_tool": compat},
"force_appid": "", "lepton_args": "",
}))
EOF
)
res=$(python3 "$u/steam-client-create-shortcut" --parms "$parms" | tail -1)
echo "Steam: $res"
case $res in *'"error"'*) exit 1 ;; esac
echo "registered $name ($dir)"
;;
run)
[ $# -eq 1 ] || usage
python3 "$(utils)/steam-devkit-rpc" run-game "gameid=$1" | tail -1
echo
;;
remove)
[ $# -eq 1 ] || usage
python3 "$(utils)/steamos-delete" --delete-title "$1"
rm -f "$HOME/devkit-game/$1"-*.json
;;
list)
python3 "$(utils)/steam-devkit-rpc" list-shortcuts
;;
*) usage ;;
esac
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env bash
# Frametop's FrameDrop installer: the start command of the "Frametop" title that FrameDrop
# puts in the Steam library. Playing it installs Frametop (or updates it) with the one-line
# installer, get.sh --yes, and shows its progress in a window.
#
# Steam ends a title's whole process tree when it's quit, and starts it with a high OOM score,
# so the install runs in a user service of its own (frametop-framedrop-install) and the window
# only follows its log. Quitting or closing the window leaves the install running; playing the
# title again reattaches to it.
#
# Usage: frametop-install.sh [--dry-run]
# --dry-run clone into ~/.cache/frametop-framedrop/dry-run instead of ~/frametop, and
# don't run install.sh (get.sh --clone-only), for testing this flow
set -u
here=$(cd "$(dirname "$0")" && pwd)
self=$here/$(basename "$0")
# A Linux title can be started in the Steam Linux Runtime container, which has no git, podman,
# systemctl, or GTK. Start this again on the host. (SteamOS 0.3.0 runs devkit titles on the
# host anyway; this is for when FrameDrop or Steam picks the runtime.)
if [ -e /run/pressure-vessel ]; then
exec flatpak-spawn --host --watch-bus --env=DISPLAY="${DISPLAY-}" \
--env=XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR-}" --env=SteamAppId="${SteamAppId-}" \
--env=ENABLE_GAMESCOPE_WSI="${ENABLE_GAMESCOPE_WSI-}" /usr/bin/bash "$self" "$@"
fi
# Steam adds its overlay and runtime libraries to every child; host tools don't want them.
unset LD_PRELOAD LD_LIBRARY_PATH
export PATH=/usr/local/bin:/usr/bin:/bin
dry_run=0
[ "${1-}" = --dry-run ] && dry_run=1
unit=frametop-framedrop-install
state=$HOME/.cache/frametop-framedrop
log=$state/install.log
mkdir -p "$state"
get_args="--yes"
[ "$dry_run" = 1 ] && get_args="--yes --clone-only --dir $state/dry-run"
# Start the install unless one is running already. RemainAfterExit keeps its result for the
# window; the next start clears it.
if [ "$(systemctl --user show -P ActiveState "$unit" 2>/dev/null)" != activating ]; then
systemctl --user stop "$unit" 2>/dev/null
systemctl --user reset-failed "$unit" 2>/dev/null
: >"$log"
systemd-run --user --unit="$unit" --description="Frametop install (FrameDrop)" \
--property=Type=oneshot --property=RemainAfterExit=yes \
--property=StandardOutput="truncate:$log" --property=StandardError=inherit \
--setenv=HOME="$HOME" --setenv=PATH="$PATH" --setenv=TERM=dumb \
--working-directory="$HOME" --quiet --no-block \
/usr/bin/bash -c 'set -o pipefail; curl -fsSL https://deejanuz.github.io/frametop/get.sh | bash -s -- '"$get_args" ||
{ echo "couldn't start the install service" >&2; exit 1; }
fi
exec /usr/bin/python3 "$here/progress.py" "$unit" "$log"
+125
View File
@@ -0,0 +1,125 @@
#!/usr/bin/env python3
"""Progress window for the FrameDrop installer: follows the install service's log and state.
Usage: progress.py UNIT LOG
Closing the window doesn't stop the install; it keeps running in the user service UNIT.
"""
import re
import subprocess
import sys
import gi
gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
from gi.repository import Adw, GLib, Gtk, Pango # noqa: E402
UNIT, LOG = sys.argv[1], sys.argv[2]
ANSI = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")
# install.sh marks each step with "== N/10 what it is"
STEP = re.compile(r"^== (\d+)/(\d+) (.*)$")
DONE_TEXT = ("Frametop is installed. Restart SteamVR once, or reboot the headset, so it loads "
"Frametop's driver. Then open Launch a program, then Desktop.")
def unit_state():
out = subprocess.run(
["systemctl", "--user", "show", "-P", "ActiveState", UNIT],
capture_output=True, text=True).stdout.strip()
return out or "inactive"
class Window(Adw.ApplicationWindow):
def __init__(self, app):
super().__init__(application=app, title="Frametop")
self.set_default_size(900, 600)
self.offset = 0
self.partial = ""
self.status = Gtk.Label(label="Installing Frametop", xalign=0, wrap=True)
self.status.add_css_class("title-2")
self.detail = Gtk.Label(label="Starting...", xalign=0, wrap=True)
self.bar = Gtk.ProgressBar()
self.bar.pulse()
self.text = Gtk.TextView(editable=False, cursor_visible=False, monospace=True,
wrap_mode=Pango.WrapMode.WORD_CHAR)
self.text.set_left_margin(8)
self.text.set_right_margin(8)
scroll = Gtk.ScrolledWindow(vexpand=True, child=self.text)
self.scroll = scroll
self.note = note = Gtk.Label(
label="You can close this window: the install keeps going. Play Frametop again to "
"come back to it.", xalign=0, wrap=True)
note.add_css_class("dim-label")
close = Gtk.Button(label="Close", halign=Gtk.Align.END)
close.connect("clicked", lambda *_: self.close())
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12,
margin_top=18, margin_bottom=18, margin_start=18, margin_end=18)
for w in (self.status, self.detail, self.bar, scroll, note, close):
box.append(w)
view = Adw.ToolbarView(content=box)
view.add_top_bar(Adw.HeaderBar())
self.set_content(view)
self.finished = False
GLib.timeout_add(500, self.tick)
self.tick()
def add_lines(self, lines):
buf = self.text.get_buffer()
for line in lines:
m = STEP.match(line)
if m:
n, total, what = int(m[1]), int(m[2]), m[3]
self.bar.set_fraction((n - 1) / total)
self.detail.set_label(f"Step {n} of {total}: {what}")
buf.insert(buf.get_end_iter(), line + "\n")
# Keep the view at the newest line.
end = buf.create_mark(None, buf.get_end_iter(), False)
self.text.scroll_mark_onscreen(end)
buf.delete_mark(end)
def tick(self):
try:
with open(LOG, "rb") as f:
f.seek(self.offset)
data = f.read()
self.offset += len(data)
except FileNotFoundError:
data = b""
if data:
text = self.partial + ANSI.sub("", data.decode("utf-8", "replace")).replace("\r", "\n")
*lines, self.partial = text.split("\n")
self.add_lines(lines)
state = unit_state()
if state == "activating":
if self.bar.get_fraction() == 0:
self.bar.pulse()
return True
if self.partial:
self.add_lines([self.partial])
self.partial = ""
self.note.set_visible(False)
if state == "active":
self.status.set_label("Done")
self.detail.set_label(DONE_TEXT)
self.bar.set_fraction(1)
else:
self.status.set_label("The install stopped")
self.detail.set_label("The log above says why. Play Frametop again to try again.")
return False
def main():
app = Adw.Application(application_id="io.github.deejanuz.FrametopInstall")
app.connect("activate", lambda a: Window(a).present())
app.run([])
if __name__ == "__main__":
main()
+114
View File
@@ -0,0 +1,114 @@
#!/usr/bin/env bash
# FrameDrop proof of concept, step 1: run as a Steam "Devkit Game" (what FrameDrop installs a
# Linux zip as) and record what an installer started from Steam could use: host or Steam Linux
# Runtime container, podman, the user's systemd, git, the network, GTK, and a window on screen.
# Register and start it: framedrop/devkit.sh add FrametopProbe framedrop/probe "./probe.sh native"
# framedrop/devkit.sh run FrametopProbe
# Usage: probe.sh LABEL
# Writes ~/.cache/frametop-framedrop/probe-LABEL.log, replacing the previous one.
label=${1:-unlabeled}
out=$HOME/.cache/frametop-framedrop
mkdir -p "$out"
log=$out/probe-$label.log
exec >"$log" 2>&1
here=$(cd "$(dirname "$0")" && pwd)
section() { printf '\n== %s\n' "$1"; }
have() { command -v "$1" >/dev/null 2>&1; }
check() { # check NAME CMD...: one line, ok or failed with the exit status
local name=$1; shift
if out_=$(timeout 20 "$@" 2>&1); then echo "ok $name: $(echo "$out_" | head -1)"
else echo "FAILED $name (exit $?): $(echo "$out_" | head -2 | tr '\n' ' ')"; fi
}
section "when, who, where"
date -Is
echo "label=$label uid=$(id -u) user=$(id -un) pwd=$PWD here=$here"
echo "args: $*"
grep -E '^(ID|VARIANT_ID|VERSION_ID|BUILD_ID|PRETTY_NAME)=' /etc/os-release
section "container?"
for p in /run/pressure-vessel /.flatpak-info /run/host/os-release; do
[ -e "$p" ] && echo "present: $p" || echo "absent: $p"
done
echo "container=${container-} PRESSURE_VESSEL_RUNTIME=${PRESSURE_VESSEL_RUNTIME-}"
[ -e /run/host/os-release ] && grep -E '^(ID|VARIANT_ID)=' /run/host/os-release
section "environment"
env | grep -E '^(PATH|HOME|XDG_[A-Z_]+|DISPLAY|WAYLAND_DISPLAY|DBUS_SESSION_BUS_ADDRESS|SteamAppId|SteamGameId|STEAM_COMPAT_[A-Z_]+|LD_LIBRARY_PATH|LD_PRELOAD|SDL_[A-Z_]+|GDK_BACKEND|ENABLE_[A-Z_]+|PRESSURE_VESSEL_[A-Z_]+)=' | sort
echo "process tree:"
pid=$$
for _ in 1 2 3 4 5 6 7 8; do
[ "$pid" -le 1 ] 2>/dev/null && break
printf ' %s %s\n' "$pid" "$(tr '\0' ' ' </proc/"$pid"/cmdline 2>/dev/null | cut -c1-200)"
pid=$(awk '/^PPid:/{print $2}' /proc/"$pid"/status 2>/dev/null)
done
# Steam adds its overlay (LD_PRELOAD) and runtime libraries to every child. An installer has
# to drop them before running host tools, as the checks below do.
unset LD_PRELOAD
LD_LIBRARY_PATH=$(printf %s "${LD_LIBRARY_PATH-}" | tr ':' '\n' | grep -v -e '/Steam/' -e '^$' -e 'x86_64' -e 'i386' | paste -sd:)
[ -n "$LD_LIBRARY_PATH" ] && export LD_LIBRARY_PATH || unset LD_LIBRARY_PATH
PATH=$(printf %s "$PATH" | tr ':' '\n' | grep -v '/Steam/' | paste -sd:)
echo "cleaned: PATH=$PATH LD_LIBRARY_PATH=${LD_LIBRARY_PATH-}"
section "tools"
for t in bash git curl python3 podman distrobox systemctl systemd-run busctl gdbus flatpak-spawn \
steam-runtime-launch-client konsole zenity kdialog; do
printf '%-28s %s\n' "$t" "$(command -v "$t" || echo -)"
done
section "what an installer needs"
check "home writable" sh -c 'f=$HOME/.cache/frametop-framedrop/.w && : >"$f" && rm "$f" && echo yes'
check "~/frametop visible" sh -c 'ls -d "$HOME/frametop" && git -C "$HOME/frametop" log -1 --format=%h'
have git && check "git ls-remote github" git ls-remote --heads https://github.com/DeeJanuz/frametop.git experimental
have curl && check "curl get.sh" sh -c 'curl -fsSL https://deejanuz.github.io/frametop/get.sh | head -1'
have podman && check "podman ps" podman ps --format '{{.Names}}'
have distrobox && check "distrobox list" distrobox list
have systemctl && check "systemctl --user" systemctl --user is-system-running
have systemctl && check "user units visible" systemctl --user is-enabled frametop-input-relay.service
have python3 && check "python3 gi Gtk 4" python3 -c 'import gi; gi.require_version("Gtk","4.0"); gi.require_version("Adw","1"); from gi.repository import Gtk, Adw; print(Gtk.get_major_version(), Gtk.get_minor_version())'
section "escape to the host (needed if this is a container)"
# A transient user unit runs in the host's user manager, outside any container.
if have systemd-run; then
rm -f "$out/escape-$label"
check "systemd-run --user" systemd-run --user --wait --collect --quiet -- \
sh -c "grep -E '^(ID|VARIANT_ID)=' /etc/os-release > '$out/escape-$label'; command -v podman git >> '$out/escape-$label'"
[ -s "$out/escape-$label" ] && sed 's/^/ host says: /' "$out/escape-$label"
fi
if have busctl; then
check "busctl --user (systemd1)" busctl --user get-property org.freedesktop.systemd1 /org/freedesktop/systemd1 org.freedesktop.systemd1.Manager Version
fi
section "window"
# A plain GTK 4 window for 20 s. Watch for it on the Frame; "window: mapped" means GTK showed it.
if have python3; then
timeout 40 python3 - <<'EOF'
import sys
try:
import gi
gi.require_version("Gtk", "4.0")
from gi.repository import Gtk, GLib
except Exception as e:
print("window: no GTK 4:", e); sys.exit(0)
app = Gtk.Application(application_id="io.github.deejanuz.FrametopProbe")
def on_activate(app):
w = Gtk.ApplicationWindow(application=app, title="Frametop installer probe")
w.set_default_size(640, 240)
w.set_child(Gtk.Label(label="Frametop installer probe\n\nIf you can read this, a FrameDrop install can show progress.\nThis window closes in 20 seconds."))
w.connect("map", lambda *_: print("window: mapped", flush=True))
w.present()
GLib.timeout_add_seconds(20, app.quit)
app.connect("activate", on_activate)
print("window: display", Gtk.Widget.get_display(Gtk.Label()) if hasattr(Gtk.Widget, "get_display") else "?", flush=True)
app.run([])
print("window: closed")
EOF
echo "window exit: $?"
else
echo "window: no python3"
fi
section "done"
date -Is
+6 -5
View File
@@ -2,12 +2,12 @@
The Steam Frame's eye tracking as pointer input: a gaze mode for the 3D mouse (the pointer goes where you look, and the mouse does the last bit), and the tools to calibrate and measure it.
- `ft-gaze` (C++, OpenVR, runs in the dev container) reads the eye tracker and prints one JSON line per sample (90 Hz). For each source, it gives the gaze direction relative to the head and the Frametop screen pixel it lands on.
- `ft-gaze` (C++, OpenVR, runs in the dev container) reads the eye tracker and prints one JSON line per sample (90 Hz). For each source, it gives the gaze direction relative to the head and the Frametop screen pixel it lands on. The gaze service asks it for only the sources it uses (`--sources`, and `sources LIST` on its stdin): our tracker and mmap set 1 with Own tracker, about 700 bytes a line instead of 1.3 KB, and every source while a check or the calibration runs. So SteamVR's gaze action, the only source that calls into vrserver (twice a sample), is read only then. The probe gets them all.
- `gazecal.py` has what the probe and the gaze service share: the correction models, filters, and the reader for SteamVR's eye tracking log.
- `tracker/` is our own eye tracker, an alternative to SteamVR's: `ft-eyes` finds the pupils and glints in the eye-camera frames that `ft-eyegrab` (a small root service) copies out of SteamVR's tracker. See "Our own eye tracker" below.
- `probe/ft-gazeprobe` (GTK 4, host Python) is a fullscreen playground, for developing the gaze tracking: day to day, the calibration and the checks run in the headset panel (Quick check, Calibrate, and Check headset fit on the Gaze page). It runs ft-gaze, draws where you're looking, measures accuracy, and tries out hold-to-adjust clicking with a calibration that learns from your adjustments.
Day to day, install the gaze service, then turn gaze mode on and calibrate on the Gaze page of Frametop Input Settings (Calibrate). The installer offers the gaze service (`gaze/run.sh install`); the probe and our own tracker are installed by hand.
Day to day, install the gaze service, then turn gaze mode on and calibrate on the Gaze page of Frametop Input Settings (Calibrate). The installer offers the gaze service (`gaze/run.sh install`) and then our own tracker (`gaze/tracker/install.sh`), which gaze mode uses once it's installed; the probe is installed by hand.
```
gaze/run.sh install # the gaze service: builds ft-gaze and the panel, starts with SteamVR
@@ -23,7 +23,7 @@ gaze/probe/ft-gazeprobe --screen 1
Gaze as an input method for the whole desktop, without replacing anything of SteamVR's:
- `ft-gazed` (host Python, a user service: `gaze/run.sh install`) runs ft-gaze and corrects its gaze. Two settings on the Gaze page of Frametop Input Settings (`GAZE_TRACKER` and `GAZE_EYE` in `~/.config/frametop.conf`, read again when the file changes) pick whose eye tracking it uses and how it weights the eyes:
- **Eye tracker:** SteamVR's (the default), or our own (Own tracker: see "Our own eye tracker" below). The gaze service runs ours while this is on. It keeps its own calibration: with Own tracker chosen, Calibrate on the Gaze page calibrates it. The gaze pointer's settings (hand back, nudges, hold to drag, the dot) are the pointer helper's, so they're the same with either.
- **Eye tracker:** our own (Own tracker: see "Our own eye tracker" below) or SteamVR's. The default, `GAZE_TRACKER=auto`, is ours when it's installed (its frame grabber, and ft-eyes' Python in the gaze service's checkout), else SteamVR's, and it switches when ours is installed or removed; picking one on the Gaze page sets it for good. The gaze service runs ours while it's the one in use. It keeps its own calibration: with Own tracker chosen, Calibrate on the Gaze page calibrates it. The gaze pointer's settings (hand back, nudges, hold to drag, the dot) are the pointer helper's, so they're the same with either.
- **Eye bias:** Auto, Left, or Right. The gaze combines both eyes, each calibrated on its own, because their errors partly cancel: on 306 clicks with our tracker, the eyes' sideways errors were correlated -0.37, and both together were 0.65 degrees off (median) against 0.96 for the left eye alone and 1.11 for the right. So Left or Right leans instead of choosing: that eye counts twice as much as the other (0.03 degrees worse there toward the better eye, 0.13 toward the worse). Auto weights each eye by the inverse square of how far off it was at your last 20 nudges, once each eye has 5, and evenly before that. Each eye's miss is measured before that nudge teaches anything, so each is a fresh test. The calibration's own fit isn't used for this: on SteamVR's test of 2026-09-29, the calibration dots said the left eye was the better one, and new spots said the right. Either eye carries the gaze alone while the other is closed or lost.
With SteamVR, each eye is its own reading (set 2), corrected by its calibration from the probe (the Left eye and Right eye sources) plus what the pointer has taught that eye since. On that test, the two eyes each calibrated and averaged were 1.70 degrees off (median; mean 1.62) against 1.72 (mean 1.84) for SteamVR's combined gaze with its calibration. A calibration from before the probe had the eyes as sources, or `--source`, uses the older path. That path runs on SteamVR's combined gaze (mmap set 1), corrected as a whole. When the tracker loses one eye (its variance for that eye jumps from about 0.001 to 0.02), the gaze comes from the other eye instead: that eye's own reading (set 2) plus what it usually reads against the combined gaze, learned while both eyes are seen, in 10 degree cells of where it looks. Set 1 keeps going on one eye too, but it holds the lost eye's yaw where it was, so the gaze moves half as far sideways as your eyes do. On a recording, one eye alone came out a median 0.8 degrees from both eyes' gaze over a steady look, a little more jittery.
@@ -33,8 +33,9 @@ Gaze as an input method for the whole desktop, without replacing anything of Ste
- **The mouse only corrects** (the default; the Gaze page's Mouse movement switch, `POINTER_GAZE_MOUSE_MOVE=held`): while the gaze has the pointer, moving the mouse does nothing. The buttons work like Meta+J and Meta+K: press and hold one and the pointer stops where you look; move the mouse onto what you meant and let go to click there (a left or a right click). Held still for half a second, a press is a real one (to drag). Once you've moved, the left button alone only clicks: press the right one while still holding the left to start a drag there; it lasts while either button is held. Press the right one again (a double right click, the left still held) to pan and tilt what you're dragging, as a right press does during any drag. A bumped or drifting mouse can't pull the pointer away, and every mouse move is a correction, so the tracker only learns from real ones. With the gaze stale for a second (the tracker stopped, eyes lost), in a game, or with the headset off, the mouse moves the pointer as usual. `free` (the switch off) lets the mouse take the pointer any time.
- **Keyboard clicks** (Meta+J left, Meta+K right; other key combinations on the Keyboard page of Input Settings): tap to click where you look. A quick tap (let go within 0.25 s, `POINTER_KEY_TAP`) clicks where the dot was when you pressed, whatever your head did, and tells the gaze service it was right there. Hold instead, and the dot stays put in your view: turn your head until it sits on what you meant, and let go to click there (the correction is a lesson, as with the mouse, under the same limit: past `POINTER_GAZE_NUDGE_MAX` it opens the quick check instead). Hold still for half a second to press for real, then turn your head to drag. With Meta+J held, Meta+K presses where the dot is now, so you can correct first and then drag; the drag lasts while either key is held. Meta+K during a Meta+J drag (again, after starting it with Meta+K: a double Meta+K) pans and tilts what you're dragging while it's held: turn your head to turn it.
- **Learning from nudges:** if the mouse took the pointer from the gaze and moved it (0.2 degrees or more, and the correction within `POINTER_GAZE_NUDGE_MAX`: 55 degrees by default, half of the 109 the headset shows across, and 1 to 110; the same limit for mouse, keyboard, and pinch clicks) before you clicked, or you dragged a held press that far, you were nudging it onto what you looked at. The helper sends that as a lesson, from the raw gaze when the mouse took over to where you clicked, and ft-gazed learns it. So using it is what calibrates it. The raw gaze is one ft-gazed sent, so it also finds when that look was, and what each eye read then. With SteamVR, each eye learns its own error. With our tracker, the look goes to it as a click, like the probe's, and it relearns how the headset sits on your face. After the headset was off, your first nudge and click there resets that (the quick check's dot does the same). A correction past `POINTER_GAZE_NUDGE_MAX` isn't learned: the helper asks ft-gazed for the quick check instead ("recheck", after its 2-minute cooldown). Tested on our tracker's 409 clicks since its Sep 29 calibration: a one-dot check set from any one of them put the next 2 minutes' clicks within 15 degrees (99% within 4.2) and the next 10 minutes' within 25 (the far ones after the headset moved), so the check gets back well under it. The limit used to be 8 degrees, and live on 2026-10-01 our tracker was 12 off after the headset went on, so every correction was dropped. One lesson moves the whole correction by only a third of what it measured (more near where it was taken), since in the first live test one 6 degree lesson moved everything and put the next target 7 degrees off. `ft-gazectl status` shows the lessons, and `ft-gazectl forget` drops them.
- **Checks and calibration in the headset** (`gaze/gazecheck.py`, shown by `gaze/panel/ft-gazepanel`, a panel fixed to the headset that ft-gazed runs): a one-dot quick check opens when you put the headset on (SteamVR's tracker sees your eyes for 3 s after none for 3 s; its "HMD on" log line can't say, since it repeats every minute or so and can stay on for hours with nobody in the headset), when our tracker asks for a click (its "reseat", when the headset may sit differently), at most once every 2 minutes, and from Quick check on the Gaze page. Look at the dot: it takes your gaze once it has held still for 0.6 s (the steadiness counts, not where the tracker puts it, so it works however far off it is), or at once with a left click or Meta+J; a right click or Meta+K closes it, and ignoring it changes nothing. It also runs when a click's correction was past `POINTER_GAZE_NUDGE_MAX`. The dot is still and the ring fills in quarters, so the panel is drawn again only a few times per dot. If the first 3 lessons after it are still over 2 degrees off, five dots follow. The full calibration (Calibrate on the Gaze page, or by itself when gaze mode comes on without one) is the probe's: three rounds, dark, medium and bright, of the middle and a ring around it, in a panel 64 degrees wide, with Frametop's screens hidden. Its dots (and the five-dot check's) wait for a click: look at the dot and left click or press Meta+J, and the gaze held still up to then is taken. Capturing whenever the gaze held still sometimes took a look that wasn't on the dot. The panel draws into three shared buffers SteamVR imported once, as Frametop's keyboard does: uploading each picture anew (SetOverlayRaw) flickered, and in one live test left the headset showing an old picture. Quitting it while there's still no calibration turns gaze mode off; turning it on again reopens it. For our tracker a check is a click and the calibration is its own (calib-point per dot); for SteamVR's, a check is a lesson for each eye and the calibration replaces calibration.json, and the lessons start over. Checks go to `checks.jsonl`.
- **Checks and calibration in the headset** (`gaze/gazecheck.py`, shown by `gaze/panel/ft-gazepanel`, a panel fixed to the headset that ft-gazed runs): a one-dot quick check opens when you put the headset on (SteamVR's tracker sees your eyes for 3 s after none for 3 s; its "HMD on" log line can't say, since it repeats every minute or so and can stay on for hours with nobody in the headset), when our tracker asks for a click (its "reseat", when the headset may sit differently), at most once every 2 minutes, and from Quick check on the Gaze page. Look at the dot: it takes your gaze once it has held still for 0.6 s (the steadiness counts, not where the tracker puts it, so it works however far off it is), or at once with a left click or Meta+J; a right click or Meta+K closes it, and ignoring it changes nothing. It also runs when a click's correction was past `POINTER_GAZE_NUDGE_MAX`. The dot is still and the ring fills in quarters, so the panel is drawn again only a few times per dot. If the first 3 lessons after it are still over 2 degrees off, five dots follow. The full calibration (Calibrate on the Gaze page, or by itself whenever gaze mode is on without one and your eyes are seen) is the probe's: three rounds, dark, medium and bright, of the middle and a ring around it, in a panel 64 degrees wide, with Frametop's screens hidden. Its dots (and the five-dot check's) wait for a click: look at the dot and left click or press Meta+J, and the gaze held still up to then is taken. A dot that isn't taken says why, on an orange line over the instructions: with SteamVR's tracker, what dropped most of that look's samples (an eye lost, a blink, the two eyes disagreeing); with ours, its reply (an eye seen in too few frames, or moving). A dot gets two tries, then it's skipped. A calibration left with under two thirds of its dots fails and names the most common reason, as the Gaze page does after it. A click that has taken nothing after 1.5 s says what it waits for: the gaze to hold still, or an eye tracker that isn't sending. Capturing whenever the gaze held still sometimes took a look that wasn't on the dot. The panel draws into three shared buffers SteamVR imported once, as Frametop's keyboard does: uploading each picture anew (SetOverlayRaw) flickered, and in one live test left the headset showing an old picture. Quitting it while there's still no calibration turns gaze mode off; turning it on again reopens it. One that closes otherwise unfinished (ignored for 2 minutes, too few dots) opens again after the headset comes off and on. Why gaze mode, on, can't work yet goes in the service's status as `checks.problem`, which the Gaze page shows under the Gaze pointer switch. For our tracker a check is a click and the calibration is its own (calib-point per dot); for SteamVR's, a check is a lesson for each eye and the calibration replaces calibration.json, and the lessons start over. Checks go to `checks.jsonl`.
- Nothing writes to SteamVR, its eye tracker, or its files: ft-gaze maps the eye tracker's shared memory read-only. With no fresh gaze (a blink, the service stopped, the headset off), the pointer stays where it is, and the mouse works as always.
- **Idle while the gaze isn't used:** ft-gaze and our own tracker run only while gaze mode is on and someone wears the headset (the pointer helper says both: SteamVR drops the headset's activity level as soon as it comes off), while a check or the calibration is open or asked for, or while the Gaze page of Frametop Input Settings is open (it renews a `wake` lease). 30 seconds after the last use they stop, and our frame grabber goes idle with our tracker. With our tracker, that saves over half a core: on 2026-10-02, with gaze mode off, ft-eyes took about 60% of a core, and ft-eyegrab, ft-gaze and ft-gazed 3 to 4% each. A check asked for while it idles starts the tracker and opens once it sends. When the gaze is used again, it takes a few seconds to come back, and our tracker's first click re-seats it, as after the headset was off: so the quick check opens when gaze mode comes on after the service idled, as it does when you put the headset on. `ft-gazectl status` says `"awake"`, and `"idle"` says why it isn't. A stand that covers the proximity sensor makes the headset seem worn, so with gaze mode on it doesn't idle there.
Lessons are logged to `pointer-lessons.jsonl`: the raw gaze, the true direction, the correction at the time, and how far off it was.
@@ -62,7 +63,7 @@ Ground rules, for anyone changing it:
- **Clean room.** Nothing of Valve's goes in: we don't decompile, disassemble, or patch the `eyetracking` binary or its network weights, and we don't copy their code or weights. Its public output (eye-server.mmap, read-only) is fair game as a baseline and as labels, and so are published papers and openly licensed pupil detectors (check each one's license: PuRe, PuReST, ElSe, and ExCuSe are non-commercial only).
- **Root only reads.** ft-eyegrab never writes to, stops, or signals the `eyetracking` process, vrserver, or vrcompositor, never opens `/dev/adsp`, `/dev/cdsp`, or `/dev/spidev0.1`, and never writes to `/dev/shm/eye-server.mmap` (it also carries calibration clicks into SteamVR's tracker), `/opt`, or `/persist`.
- **Eye images are biometric data.** Recordings live outside the repo, in `~/.local/share/frametop/eyes/captures` (0700), and `.gitignore` catches stray frame dumps. They go nowhere but the machine that runs your offline jobs.
- **Mind the headset's budget.** Finding a pupil takes about 0.4 ms a frame while ft-eyes follows it, and 1.4-2.1 ms when it searches the whole frame. Replays, scoring, and training go to a PC.
- **Mind the headset's budget.** Finding a pupil takes about 0.4 ms a frame while ft-eyes follows it, and 1.4-2.1 ms when it searches the whole frame. ft-eyes keeps OpenCV and numpy to one thread: their pools of one per core spun idle workers at about a quarter of a core, for frames this small. It also runs at nice 10 with SCHED_BATCH, and ft-gaze at nice 5 (not batch, since each sample goes on to the pointer): both run in the dev container's podman scope, out of reach of the gaze service's unit, on the cores vrcompositor and vrserver use at nice 0. Replays, scoring, and training go to a PC.
## Headset fit
+119 -33
View File
@@ -4,7 +4,14 @@
// Every eye tracker sample (90 Hz) becomes one JSON line on stdout with each gaze source
// hit-tested against the Frametop screens:
//
// Options: -v (log action errors), --watch-stdin (quit when stdin closes).
// Options: -v (log action errors), --watch-stdin (quit when stdin closes; until then, a line
// "sources LIST" on stdin switches the sources as --sources does), --sources LIST (comma-
// separated: action, mmap1, mmap2, left, right, own, and eye for EYE; or all, the default).
// Sources left out are read not at all and print as {"ok":0} ("eye" as null), so every line
// keeps the same keys. The gaze service asks for the ones it uses (own and mmap1 with our
// tracker), and all of them while a check or the calibration runs. Only the action costs
// SteamVR anything (two calls into vrserver per sample), and a line with every source is
// about 1.5 KB, 130 KB a second through podman's relay.
//
// {"t":<sample time, CLOCK_MONOTONIC_RAW s>,"age":<ms old when read>,"n":<sample counter>,
// "head":{"yaw":..,"pitch":..,"hit":HIT}, head forward ray (for head nudging)
@@ -58,6 +65,7 @@
#include <algorithm>
#include <atomic>
#include <cerrno>
#include <chrono>
#include <climits>
#include <cmath>
@@ -72,6 +80,7 @@
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
@@ -389,6 +398,30 @@ std::string SrcJson(const std::vector<Screen> &screens, const vr::HmdMatrix34_t
return buf + extra + "\"hit\":" + HitJson(screens, head, yaw, pitch) + "}";
}
// Sources (--sources, "sources LIST" on stdin): a bit each.
enum : unsigned { kAction = 1, kMmap1 = 2, kMmap2 = 4, kLeft = 8, kRight = 16, kOwn = 32, kEye = 64, kAll = 127 };
bool ParseSources(const std::string &list, unsigned &mask) {
static const struct {
const char *name;
unsigned bit;
} names[] = {{"action", kAction}, {"mmap1", kMmap1}, {"mmap2", kMmap2}, {"left", kLeft},
{"right", kRight}, {"own", kOwn}, {"eye", kEye}, {"all", kAll}};
unsigned m = 0;
size_t at = 0;
while (at <= list.size()) {
const size_t comma = std::min(list.find(',', at), list.size());
const std::string name = list.substr(at, comma - at);
bool known = false;
for (const auto &n : names)
if (name == n.name) m |= n.bit, known = true;
if (!known) return false;
at = comma + 1;
}
mask = m;
return true;
}
// Head poses of the last half second, so a sample can use the pose at its own time.
class PoseHistory {
public:
@@ -426,17 +459,42 @@ std::string ExeDir() {
int main(int argc, char **argv) {
bool verbose = false, watchStdin = false;
std::atomic<unsigned> sources{kAll};
for (int i = 1; i < argc; ++i) {
if (std::strcmp(argv[i], "-v") == 0) verbose = true;
if (std::strcmp(argv[i], "--watch-stdin") == 0) watchStdin = true;
if (std::strcmp(argv[i], "--sources") == 0 && i + 1 < argc) {
unsigned m;
if (ParseSources(argv[++i], m))
sources = m;
else
std::fprintf(stderr, "ft-gaze: --sources %s: unknown source (all used)\n", argv[i]);
}
}
// Nice 5, before any thread starts (they inherit it): we run in the dev container's podman
// scope, beside vrcompositor and vrserver at nice 0, and the gaze service's unit doesn't
// reach us. Not SCHED_BATCH, as ft-eyes is: that would let each wakeup wait out another
// task's turn, and each sample goes on to the pointer.
errno = 0;
const int nice0 = getpriority(PRIO_PROCESS, 0);
if (errno == 0 && nice0 < 5 && setpriority(PRIO_PROCESS, 0, 5) != 0)
std::fprintf(stderr, "ft-gaze: nice: %s\n", std::strerror(errno));
// --watch-stdin: quit when stdin closes. The probe runs us through distrobox, which
// passes neither its signals nor a closed stdout on to us, but does pass stdin's end.
// Lines on stdin until then: "sources LIST".
std::atomic<bool> stdinClosed{false};
if (watchStdin)
std::thread([&stdinClosed] {
std::thread([&stdinClosed, &sources] {
char c[256];
while (read(0, c, sizeof c) > 0) {
std::string line;
ssize_t n;
while ((n = read(0, c, sizeof c)) > 0) {
line.append(c, size_t(n));
for (size_t nl; (nl = line.find('\n')) != std::string::npos; line.erase(0, nl + 1)) {
unsigned m;
if (line.compare(0, 8, "sources ") == 0 && ParseSources(line.substr(8, nl - 8), m)) sources = m;
}
if (line.size() > 4096) line.clear(); // no newline in sight: not ours
}
stdinClosed = true;
}).detach();
@@ -479,9 +537,24 @@ int main(int argc, char **argv) {
double lastEmit = 0;
int actionErrors = 0;
vr::EVRInputError lastActionError = vr::VRInputError_None;
// During a VR game, SteamVR's gaze action is left alone. With ft-gaze reading the eyes, SteamVR
// restarted its eye tracker every 10 s or so in a game, as if the headset came off, and each
// restart took input focus from the game: Beat Saber paused (PR #13). Of what ft-gaze reads,
// only the action reaches SteamVR (the mmap and our tracker are files), so gaze still works
// over the dashboard. Games are told apart the way ft-screens does it, by the scene app.
bool inGame = false;
double nextGameCheck = 0;
while (true) {
const double now = NowRaw();
if (now >= nextGameCheck) {
nextGameCheck = now + 0.5;
const bool game = vr::VRApplications()->GetCurrentSceneProcessId() != 0;
if (game != inGame)
std::fprintf(stderr, "ft-gaze: %s\n",
game ? "a VR game is running: SteamVR's gaze action left alone" : "the VR game ended");
inGame = game;
}
vr::TrackedDevicePose_t hp;
sys->GetDeviceToAbsoluteTrackingPose(vr::TrackingUniverseStanding, 0, &hp, 1);
if (hp.bPoseIsValid) history.Add(now, hp.mDeviceToAbsoluteTracking);
@@ -494,6 +567,7 @@ int main(int argc, char **argv) {
if (fresh && hp.bPoseIsValid) {
lastEmit = now;
const unsigned want = sources;
const auto list = screens.Get();
const vr::HmdMatrix34_t &headNow = hp.mDeviceToAbsoluteTracking;
vr::HmdMatrix34_t headThen = headNow;
@@ -502,24 +576,26 @@ int main(int argc, char **argv) {
// SteamVR's action: a room-space origin and fixation point, turned into the head
// frame so every source reports the same kind of angles.
std::string action = "{\"ok\":0}";
vr::VRActiveActionSet_t active{};
active.ulActionSet = set;
active.nPriority = vr::k_nActionSetOverlayGlobalPriorityMin;
input->UpdateActionState(&active, sizeof active, 1);
vr::VREyeTrackingData_t e{};
const vr::EVRInputError ae =
input->GetEyeTrackingDataRelativeToNow(gaze, vr::TrackingUniverseStanding, 0, &e, sizeof e);
if (ae == vr::VRInputError_None && e.bActive && e.bValid) {
const Vec3 o{e.vGazeOrigin.v[0], e.vGazeOrigin.v[1], e.vGazeOrigin.v[2]};
const Vec3 t{e.vGazeTarget.v[0], e.vGazeTarget.v[1], e.vGazeTarget.v[2]};
const Vec3 dHead = RotateInverse(headNow, Normalize(t - o));
char extra[96];
std::snprintf(extra, sizeof extra, "\"tracked\":%d,\"dist\":%.3f,", int(e.bTracked), Length(t - o));
action = SrcJson(list, headNow, dHead, extra);
} else if (ae != lastActionError || (verbose && ++actionErrors % 90 == 1)) {
std::fprintf(stderr, "ft-gaze: action: error %d active %d valid %d\n", int(ae), int(e.bActive),
int(e.bValid));
lastActionError = ae;
if (!inGame && (want & kAction)) {
vr::VRActiveActionSet_t active{};
active.ulActionSet = set;
active.nPriority = vr::k_nActionSetOverlayGlobalPriorityMin;
input->UpdateActionState(&active, sizeof active, 1);
vr::VREyeTrackingData_t e{};
const vr::EVRInputError ae =
input->GetEyeTrackingDataRelativeToNow(gaze, vr::TrackingUniverseStanding, 0, &e, sizeof e);
if (ae == vr::VRInputError_None && e.bActive && e.bValid) {
const Vec3 o{e.vGazeOrigin.v[0], e.vGazeOrigin.v[1], e.vGazeOrigin.v[2]};
const Vec3 t{e.vGazeTarget.v[0], e.vGazeTarget.v[1], e.vGazeTarget.v[2]};
const Vec3 dHead = RotateInverse(headNow, Normalize(t - o));
char extra[96];
std::snprintf(extra, sizeof extra, "\"tracked\":%d,\"dist\":%.3f,", int(e.bTracked), Length(t - o));
action = SrcJson(list, headNow, dHead, extra);
} else if (ae != lastActionError || (verbose && ++actionErrors % 90 == 1)) {
std::fprintf(stderr, "ft-gaze: action: error %d active %d valid %d\n", int(ae), int(e.bActive),
int(e.bValid));
lastActionError = ae;
}
}
std::string m1 = "{\"ok\":0}", m2 = m1, left = m1, right = m1, eye = "null";
@@ -543,26 +619,33 @@ int main(int argc, char **argv) {
return std::string(b);
};
char extra[256];
std::snprintf(extra, sizeof extra, "\"dist\":%.3f,\"open\":[%.3f,%.3f],\"lr\":%.3f,", Length(s.fix1),
s.open[0], s.open[1], lr(s.left1, s.right1));
m1 = SrcJson(list, headThen, s.left1 + s.right1, extra + eyes(s.left1, s.right1) + unc(s.var1));
std::snprintf(extra, sizeof extra, "\"lr\":%.3f,", lr(s.left2, s.right2));
m2 = SrcJson(list, headThen, s.left2 + s.right2, extra + eyes(s.left2, s.right2) + unc(s.var2));
left = SrcJson(list, headThen, s.left2);
right = SrcJson(list, headThen, s.right2);
if (want & kMmap1) {
std::snprintf(extra, sizeof extra, "\"dist\":%.3f,\"open\":[%.3f,%.3f],\"lr\":%.3f,", Length(s.fix1),
s.open[0], s.open[1], lr(s.left1, s.right1));
m1 = SrcJson(list, headThen, s.left1 + s.right1, extra + eyes(s.left1, s.right1) + unc(s.var1));
}
if (want & kMmap2) {
std::snprintf(extra, sizeof extra, "\"lr\":%.3f,", lr(s.left2, s.right2));
m2 = SrcJson(list, headThen, s.left2 + s.right2, extra + eyes(s.left2, s.right2) + unc(s.var2));
}
if (want & kLeft) left = SrcJson(list, headThen, s.left2);
if (want & kRight) right = SrcJson(list, headThen, s.right2);
// "new" compares with the last sample, so the last measurement is kept either way.
const float *m = s.meas;
const bool newL = m[0] != lastMeas[0] || m[1] != lastMeas[1];
const bool newR = m[2] != lastMeas[2] || m[3] != lastMeas[3];
std::memcpy(lastMeas, m, sizeof lastMeas);
std::snprintf(extra, sizeof extra, "{\"q\":[%.3g,%.3g],\"m\":[[%.4f,%.4f],[%.4f,%.4f]],\"new\":[%d,%d]}",
(m[4] + m[5]) / 2, (m[6] + m[7]) / 2, m[0], m[1], m[2], m[3], int(newL), int(newR));
eye = extra;
if (want & kEye) {
std::snprintf(extra, sizeof extra, "{\"q\":[%.3g,%.3g],\"m\":[[%.4f,%.4f],[%.4f,%.4f]],\"new\":[%d,%d]}",
(m[4] + m[5]) / 2, (m[6] + m[7]) / 2, m[0], m[1], m[2], m[3], int(newL), int(newR));
eye = extra;
}
}
// Our tracker: its own sample time picks the head pose, like the mmap's.
std::string own = "{\"ok\":0}";
OwnSample o;
if (ownFile.Read(o) && now - o.t < 0.1) {
if ((want & kOwn) && ownFile.Read(o) && now - o.t < 0.1) {
vr::HmdMatrix34_t headOwn = headNow;
history.At(o.t, headOwn);
auto pair = [](bool ok, float a, float b) {
@@ -607,7 +690,10 @@ int main(int argc, char **argv) {
break;
}
if (stdinClosed) break;
std::this_thread::sleep_for(std::chrono::milliseconds(2));
// 250 passes a second: a new sample is printed within 4 ms (2 on average) of appearing,
// and the pose history has a pose within 2 ms of any sample's time (a 0.2 degree head
// turn at 100 degrees a second). Every 2 ms read the pose and the events twice as often.
std::this_thread::sleep_for(std::chrono::milliseconds(4));
}
screens.Stop();
vr::VR_Shutdown();
+10 -1
View File
@@ -36,8 +36,17 @@ def main():
if r is None:
sys.exit("the pointer helper isn't running")
print(f"gaze mode {r.removeprefix('ok ')}" if r else "no answer (an older pointer helper without gaze mode?)")
if ask("ft_gazed", "status", 0.3) is None:
st = ask("ft_gazed", "status", 0.3)
if st is None:
print("note: the gaze service (ft-gazed) isn't running, so the pointer has no gaze to follow")
elif r == "ok on":
try:
calibrated = (json.loads(st).get("checks") or {}).get("calibrated")
except ValueError:
calibrated = None
if calibrated is False:
print("note: no calibration for this eye tracker yet; it opens in the headset "
"(if it can't, ft-gazectl status says why: checks.problem)")
elif cmd in ("status", "forget", "reload"):
r = ask("ft_gazed", cmd)
if r is None:
+140 -18
View File
@@ -3,8 +3,12 @@
Two settings in ~/.config/frametop.conf (the Gaze page of Frametop Input Settings), read
again when the file changes:
GAZE_TRACKER=steam|own SteamVR's eye tracker (default), or our own (gaze/tracker/ft-eyes,
ft-gaze's source "own"; this service runs it, see below)
GAZE_TRACKER=auto|own|steam
our own eye tracker (gaze/tracker/ft-eyes, ft-gaze's source "own";
this service runs it, see below) or SteamVR's. auto (the default)
is ours when it's installed (gaze/tracker/install.sh: the frame
grabber, and ft-eyes' Python in this checkout), else SteamVR's; it
switches when ours is installed or removed.
GAZE_EYE=auto|left|right the eye bias (gazecal.EyeWeights): auto weights each eye by how far
off it was at your recent nudges; left or right counts that eye twice
as much as the other. Either eye alone carries the gaze when the
@@ -59,9 +63,24 @@ and the error moves): lessons from before count less then, so the first few afte
relearn the offset.
Our own tracker (gaze/tracker/ft-eyes) runs here too, in the dev container, while
GAZE_TRACKER=own or the gaze probe asks for it ("eyes SECONDS", a lease the probe renews). It
reads the eye-camera frames the root service frametop-eyegrab copies (gaze/tracker/install.sh),
which copies them only while ft-eyes runs.
GAZE_TRACKER=own and the gaze is in use (below), or the gaze probe asks for it ("eyes SECONDS",
a lease the probe renews). It reads the eye-camera frames the root service frametop-eyegrab
copies (gaze/tracker/install.sh), which copies them only while ft-eyes runs.
Idle: ft-gaze and our own tracker run only while the gaze is in use: gaze mode on with someone
wearing the headset (the pointer helper says both: "gaze ? headset" -> "ok on|off worn|away"), a
check or calibration open or asked for, or a "wake" lease (the Gaze page of Frametop Input
Settings renews one while it's open). IDLE_AFTER after the last use they stop, and the frame
grabber goes idle with our tracker; with our tracker, that was over half a core with gaze mode
off. A check asked for while idle waits for the tracker to start (at most WAKE_SETTLE). Our
tracker's next click after it starts again re-seats it, as after the headset was off, so turning
gaze mode on after a while opens the quick check.
ft-gaze prints only the sources this uses ("sources LIST" on its stdin, see wanted_sources):
own and mmap1 with our tracker, left, right and mmap1 with SteamVR's eyes, and every source
while a check or the calibration runs or is asked for, since those record them all. So
SteamVR's gaze action, the one source that calls into vrserver, is read only then (or with
--source action).
Checks and calibration (gaze/gazecheck.py): a one-dot quick check when the headset goes on or
our tracker asks for a click, and the full calibration when gaze mode comes on without one,
@@ -79,6 +98,8 @@ Control socket: abstract unix datagram "@ft_gazed":
reload read calibration.json and the settings again
eyes <seconds> keep our own tracker running that much longer (at most 120),
whatever GAZE_TRACKER says: the probe's lease. Reply: "ok"
wake <seconds> keep the gaze running (not idle) that much longer (at most 120),
whatever gaze mode says: Input Settings' Gaze page. Reply: "ok"
quickcal the one-dot check now (the calibration if there's none)
calibrate the full calibration in the panel
fitcheck the headset fit check in the panel
@@ -119,6 +140,7 @@ EYES_PROG = REPO / "gaze" / "tracker" / "ft-eyes" # our own tracker
EYES_PYTHON = REPO / "gaze" / "tracker" / "build" / "venv" / "bin" / "python" # numpy, OpenCV (build.sh)
EYES_SOCKET = "\0ft_eyes" # its control socket
EYES_CAMS = Path("/dev/shm/frametop-eyes-cams") # the frames it reads (frametop-eyegrab.service)
EYEGRAB = (Path("/etc/frametop/ft-eyegrab"), Path("/etc/systemd/system/frametop-eyegrab.service")) # tracker/install.sh
CONF = Path.home() / ".config" / "frametop.conf"
CALIBRATION = STATE / "calibration.json"
LESSONS = STATE / "pointer-lessons.json"
@@ -126,6 +148,7 @@ LESSON_LOG = STATE / "pointer-lessons.jsonl"
SOURCES = ("action", "mmap1", "mmap2", "left", "right") # the ones with a calibration here
SIDES = ("left", "right") # ft-gaze's order, and the sources for each eye alone
TRACKERS = ("steam", "own")
TRACKER_SETTINGS = ("auto",) + TRACKERS
BIASES = ("auto", "left", "right")
NUDGE_MAX = 55.0 # degrees: POINTER_GAZE_NUDGE_MAX's default, the largest lesson taken
HISTORY = 12.0 # seconds of the gaze sent, to find a lesson's look (the helper sends it up to 10 s later)
@@ -134,6 +157,9 @@ RETRY = 3.0 # seconds before starting ft-gaze again
EYES_RETRY = 10.0 # seconds before starting ft-eyes again after it stopped on its own
EYES_LEASE_MAX = 120.0
SETTLE = 0.3 # seconds after an eye is found again before the fallback learns from it
IDLE_AFTER = 30.0 # seconds after the gaze was last in use before ft-gaze and our tracker stop
WAKE_SETTLE = 15.0 # seconds after waking that the tracker may take to start sending
WAKE_MAX = 120.0
KEYBOARD_PITCH = -20.0 # degrees: gaze under this, on no screen, is a look at the keyboard
@@ -153,8 +179,14 @@ def log(msg):
print(f"ft-gazed: {msg}", file=sys.stderr, flush=True)
def own_installed():
"""Is our own tracker installed: its frame grabber, and ft-eyes' Python here?"""
return all(p.exists() for p in EYEGRAB) and EYES_PYTHON.exists()
def read_settings():
"""(tracker, eye bias, nudge max) from frametop.conf, defaults for anything missing or unknown."""
"""(tracker, GAZE_TRACKER, eye bias, nudge max) from frametop.conf, defaults for anything
missing or unknown. The tracker is "steam" or "own": auto picks ours when it's installed."""
conf = {}
try:
for line in CONF.read_text().splitlines():
@@ -164,13 +196,15 @@ def read_settings():
conf[k.strip()] = v.strip().lower()
except OSError:
pass
tracker = conf.get("GAZE_TRACKER", "steam")
setting = conf.get("GAZE_TRACKER", "auto")
setting = setting if setting in TRACKER_SETTINGS else "auto"
tracker = setting if setting != "auto" else "own" if own_installed() else "steam"
bias = conf.get("GAZE_EYE", "auto")
try:
nudge = min(max(float(conf.get("POINTER_GAZE_NUDGE_MAX", NUDGE_MAX)), 1.0), 110.0) # the helper's range
except ValueError:
nudge = NUDGE_MAX
return tracker if tracker in TRACKERS else "steam", bias if bias in BIASES else "auto", nudge
return tracker, setting, bias if bias in BIASES else "auto", nudge
def mtime(path):
@@ -185,7 +219,7 @@ class Service:
self.override, self.verbose, self.to = source, verbose, to
self.source = source or "mmap1" # the older path's source
STATE.mkdir(parents=True, exist_ok=True)
self.tracker, self.bias, self.nudge_max = read_settings()
self.tracker, self.tracker_setting, self.bias, self.nudge_max = read_settings()
self.conf_mtime = mtime(CONF)
self.models = {name: Correction() for name in SOURCES}
self.mode = DEFAULT_MODEL
@@ -216,6 +250,10 @@ class Service:
self.eyes_proc = None # ft-eyes, while it runs
self.eyes_until = 0.0 # the probe's lease (monotonic time)
self.eyes_restart_at = 0.0
self.awake = False # ft-gaze (and our tracker) run: the gaze is in use (see the top)
self.idle_at = 0.0 # idle from then, unless it's in use again first
self.woke_at = 0.0
self.wake_until = 0.0 # a "wake" lease
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM | socket.SOCK_CLOEXEC | socket.SOCK_NONBLOCK)
self.sock.bind(ME)
@@ -228,6 +266,7 @@ class Service:
self.sel.register(self.eyes_sock, selectors.EVENT_READ, "own")
self.checks = Checks(self, self.sel)
self.proc = None
self.proc_sources = None # what ft-gaze was last told to print
self.buf = b""
self.restart_at = 0.0
self.running = True
@@ -246,9 +285,12 @@ class Service:
def load_settings(self):
self.conf_mtime = mtime(CONF)
tracker, bias, self.nudge_max = read_settings()
tracker, self.tracker_setting, bias, self.nudge_max = read_settings()
if (tracker, bias) != (self.tracker, self.bias):
log(f"tracker {tracker}, eye bias {bias}" + (f" (--source {self.override} wins)" if self.override else ""))
auto = ""
if self.tracker_setting == "auto":
auto = " (auto: ours is installed)" if tracker == "own" else " (auto: ours isn't installed)"
log(f"tracker {tracker}{auto}, eye bias {bias}" + (f" (--source {self.override} wins)" if self.override else ""))
self.tracker, self.bias = tracker, bias
for w in self.weights.values():
w.bias = bias
@@ -382,8 +424,73 @@ class Service:
log(f"lesson log: {e}")
return rec
# --- Idle (see the top) ---
def use_reason(self):
"""Why the gaze is in use now, or None."""
c = self.checks
if c.gaze_on and c.headset is not False:
return "gaze mode is on"
if c.active or c.pending:
return "a check"
if time.monotonic() < self.wake_until:
return "asked to stay awake"
return None
def idle_reason(self):
c = self.checks
if c.gaze_on is None:
return "the pointer helper isn't answering (SteamVR not running?)"
if c.gaze_on and c.headset is False:
return "nobody is wearing the headset"
return "gaze mode is off"
def waking(self):
"""Idle, or awake too briefly for the tracker to be sending yet."""
return not self.awake or time.monotonic() - self.woke_at < WAKE_SETTLE
def update_awake(self):
now = time.monotonic()
why = self.use_reason()
if why:
self.idle_at = now + IDLE_AFTER
if why and not self.awake:
self.awake, self.woke_at, self.restart_at = True, now, 0.0
log(f"awake: {why}")
elif not why and self.awake and now >= self.idle_at:
self.awake = False
log(f"idle: {self.idle_reason()}; ft-gaze and our tracker stop until the gaze is used again")
self.stop_helper()
if self.eyes_proc and not self.eyes_wanted():
self.stop_eyes()
# --- ft-gaze ---
def wanted_sources(self):
"""The sources ft-gaze should print (its --sources): what on_sample and the checks read.
mmap1 always (blinks, lost eyes, and the headset going on, from its openness and
variances); everything while a check runs or waits, since they record every source."""
c = self.checks
if c.active or c.pending:
return "all"
kind = self.kind
if kind == "own":
return "own,mmap1"
if kind == "eyes":
return "left,right,mmap1"
return ",".join(dict.fromkeys((self.source, "mmap1", "mmap2"))) # mmap2: each eye, for the fallback
def sync_sources(self):
want = self.wanted_sources()
if not self.proc or want == self.proc_sources:
return
try:
self.proc.stdin.write(f"sources {want}\n".encode())
self.proc.stdin.flush()
except (OSError, ValueError):
return # it's stopping: read_stdout notices
self.proc_sources = want
def start_helper(self):
if not HELPER.exists():
log(f"ft-gaze isn't built: run {REPO}/gaze/build.sh")
@@ -394,9 +501,11 @@ class Service:
subprocess.run([str(REPO / "scripts" / "container-up.sh")], env=env, check=False)
distrobox = Path.home() / ".local" / "bin" / "distrobox"
# ft-gaze quits when its stdin closes: the one thing distrobox passes on.
self.proc = subprocess.Popen([str(distrobox), "enter", "dev", "--", str(HELPER), "--watch-stdin"], env=env,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
start_new_session=True)
sources = self.wanted_sources()
self.proc = subprocess.Popen([str(distrobox), "enter", "dev", "--", str(HELPER), "--watch-stdin",
"--sources", sources], env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, start_new_session=True)
self.proc_sources = sources
os.set_blocking(self.proc.stdout.fileno(), False)
os.set_blocking(self.proc.stderr.fileno(), False)
self.sel.register(self.proc.stdout, selectors.EVENT_READ, "stdout")
@@ -424,7 +533,7 @@ class Service:
self.proc = None
def eyes_wanted(self):
return (self.tracker == "own" and not self.override) or time.monotonic() < self.eyes_until
return (self.tracker == "own" and not self.override and self.awake) or time.monotonic() < self.eyes_until
def start_eyes(self):
"""Our own tracker, in the dev container, with build/venv's numpy and OpenCV. Like
@@ -683,6 +792,14 @@ class Service:
reply = "ok"
except ValueError:
reply = "error bad seconds"
elif words[:1] == ["wake"] and len(words) == 2:
try:
secs = min(max(float(words[1]), 0.0), WAKE_MAX)
self.wake_until = max(self.wake_until, time.monotonic() + secs)
self.update_awake()
reply = "ok"
except ValueError:
reply = "error bad seconds"
elif words[:1] == ["reload"]:
self.load_settings()
self.load_calibration()
@@ -733,7 +850,9 @@ class Service:
st.update(calibration_samples=cal.get("dots", 0), calibration_made=cal.get("made"),
lessons=max(len(m) for m in w.misses), own_running=bool(own),
own_reseat=any(e.get("reseat") for e in own.get("eyes", {}).values()))
st.update(eyes_process=self.eyes_proc is not None, eyegrab=EYES_CAMS.exists())
st.update(awake=self.awake, idle=None if self.awake else self.idle_reason())
st.update(eyes_process=self.eyes_proc is not None, eyegrab=EYES_CAMS.exists(),
tracker_setting=self.tracker_setting, own_installed=own_installed())
st.update({"ft_gaze": self.proc is not None, "sample_age_s": round(time.monotonic() - self.last_sample, 2)
if self.last_sample else None, "headset_on": self.steam.wearing(),
"headset_on_since": self.steam.worn(), "last": [round(v, 2) for v in self.last] if self.last else None,
@@ -749,8 +868,10 @@ class Service:
if mtime(CALIBRATION) != self.cal_mtime:
self.load_calibration()
self.refit()
if mtime(CONF) != self.conf_mtime:
if mtime(CONF) != self.conf_mtime or (self.tracker_setting == "auto"
and own_installed() != (self.tracker == "own")):
self.load_settings()
self.update_awake()
want = self.eyes_wanted()
if want and not self.eyes_proc and time.monotonic() >= self.eyes_restart_at:
self.start_eyes()
@@ -771,7 +892,7 @@ class Service:
next_verbose = time.monotonic() + 5
while self.running:
now = time.monotonic()
if not self.proc and now >= self.restart_at:
if self.awake and not self.proc and now >= self.restart_at:
self.start_helper()
for key, _ in self.sel.select(timeout=0.05 if self.checks.active else 0.5):
if key.data == "control":
@@ -789,6 +910,7 @@ class Service:
elif key.data == "stderr" and self.proc:
self.read_stderr()
self.checks.tick()
self.sync_sources()
if now >= next_periodic:
self.periodic()
next_periodic = now + 1.0
+23 -10
View File
@@ -640,31 +640,44 @@ def cross_validate(points, mode):
return errs
def steady_samples(samples, vergence_jump=1.5):
def steady_samples(samples, vergence_jump=1.5, why=None):
"""The samples of one look at one spot where the tracker had both eyes: none in a blink
(openness under half its median over the samples), none where it had lost an eye (its
variance over EYE_LOST), and none where the angle between the eyes' directions (`lr`, the
vergence) is more than `vergence_jump` degrees from its median over the samples. The
vergence itself depends on distance (about 2.8 degrees for a screen 1.3 m away, a
fraction of one far off), so only a jump away from what it was during this look means
the tracker lost an eye. Without the mmap there's nothing to judge by: all are kept."""
the tracker lost an eye. Without the mmap there's nothing to judge by: all are kept.
`why`, a dict, gets how many were dropped for each reason: "lost_left", "lost_right",
"lost_both", "blink" and "vergence" (each sample once, for the first that applies)."""
if why is None:
why = {}
# Openness: a blink is a sharp drop from what it was during this look. Not a fixed
# level: looking down, the upper lids come down with the eyes, and in bright light you
# squint, so the reading can stay under 0.5 for the whole look while the tracker follows
# the eyes fine (a calibration dot at the bottom of the bright round failed that way).
opens = [min(o) for o in ((smp["src"].get("mmap1") or {}).get("open") for smp in samples) if o]
floor = max(0.12, 0.5 * statistics.median(opens)) if len(opens) >= 5 else 0.12
opened = []
seen = []
for smp in samples:
o = (smp["src"].get("mmap1") or {}).get("open")
if not o or min(o) >= floor:
opened.append(smp)
m1 = smp["src"].get("mmap1") or {}
o = m1.get("open")
lost = [u > EYE_LOST for u in m1.get("unc") or [0, 0]]
# A lost eye's openness reads 0 too, so a lost eye is named before a blink.
key = ("lost_both" if all(lost) else "lost_left" if lost[0] else "lost_right") if any(lost) else \
"blink" if o and min(o) < floor else None
if key:
why[key] = why.get(key, 0) + 1
else:
seen.append(smp)
def vergence(smp):
return (smp["src"].get("mmap1") or {}).get("lr", (smp["src"].get("mmap2") or {}).get("lr"))
opened = [smp for smp in opened if max((smp["src"].get("mmap1") or {}).get("unc") or [0]) <= EYE_LOST]
have = [v for v in map(vergence, opened) if v is not None]
have = [v for v in map(vergence, seen) if v is not None]
if len(have) < 5:
return opened
return seen
med = statistics.median(have)
return [smp for smp in opened if vergence(smp) is None or abs(vergence(smp) - med) <= vergence_jump]
kept = [smp for smp in seen if vergence(smp) is None or abs(vergence(smp) - med) <= vergence_jump]
if len(kept) < len(seen):
why["vergence"] = why.get("vergence", 0) + len(seen) - len(kept)
return kept
+191 -34
View File
@@ -10,16 +10,21 @@ directions: look at each one.
once every QUICK_COOLDOWN, and on "quickcal" (Frametop Input Settings, or a mouse
button or key combination mapped to Gaze quick check), and when a click's correction
was past POINTER_GAZE_NUDGE_MAX (55 degrees; the helper's "recheck"): the tracker is
far off. Ignored, it closes after QUICK_TIMEOUT and changes nothing.
far off. Ignored, it closes after QUICK_TIMEOUT and changes nothing. The headset going
on is seen only while the gaze service is awake (gaze mode on, someone wearing it: see
ft-gazed), so it also opens when gaze mode comes on after the service idled.
five the middle and four around it, when the first FIVE_COUNT lessons after a quick check
were all over FIVE_LIMIT degrees off: the quick check didn't fix it.
full the calibration, as the gaze probe's: three rounds, dark, medium and bright (pupil
size, and the tracker's error with it, changes with brightness), each the middle and
a ring of six (SteamVR's tracker) or eight (ours, whose fit goes wrong past its dots)
RING degrees out, half that in the middle round, turned 20 degrees a round. It opens
when gaze mode comes on without a calibration for the tracker in use, and on
"calibrate". Frametop's screens hide while it runs. Quitting it while there's still
no calibration turns gaze mode off (POINTER_GAZE=0); turning it on again reopens it.
whenever gaze mode is on without a calibration for the tracker in use and someone's
in the headset, and on "calibrate". One that closes unfinished (ignored, too few
dots) opens again only once the headset comes off and on, or gaze mode off and on.
Frametop's screens hide while it runs. Quitting it while there's still no
calibration turns gaze mode off (POINTER_GAZE=0); turning it on again reopens it.
Why gaze mode can't work yet goes in the status ("problem"), for Input Settings.
fit the headset fit check (on "fitcheck", Check headset fit on the Gaze page): live, a
card per eye (tracked or lost, the tracker's signal, how much of the last 10 s it was
@@ -27,6 +32,9 @@ directions: look at each one.
adjust the headset. A left click or Meta+J runs its guided check (dots, then looks
down, up, left and right); a right click or Meta+K closes it, as does FIT_TIMEOUT.
A check asked for while the gaze service idles (quickcal, calibrate, fitcheck) wakes it and
waits until the tracker sends, at most ft-gazed's WAKE_SETTLE; then it opens, or logs why not.
The quick check's dot captures itself: from CHECK_SETTLE after it shows (the eyes getting
there), once the gaze has held within CHECK_SPREAD for CHECK_WINDOW (the probe's max spread and
capture time). It's the gaze holding still that counts, not where the tracker puts it, so it
@@ -34,7 +42,10 @@ works however far off the tracker is; a left click or Meta+J (the pointer helper
"calaccept") takes it now. The full calibration's and five's dots wait for that click: you
click when you're looking at the dot (the user asked for that: a steady gaze isn't always on
the dot), and the gaze held still up to then is taken (ACCEPT_SPREAD). They wait as long as
it takes, up to CLICK_IDLE. A right click or Meta+K ("calquit") closes the panel. The pointer hides meanwhile ("calpanel 1",
it takes, up to CLICK_IDLE. A dot not taken says why in the panel's note line (reject_reason:
gazecal.steady_samples' drop counts for SteamVR's tracker, ft-eyes' reply for ours), as does a
click with nothing taken after ACCEPT_WAIT, and a failed calibration names its most common
reason there and in the status. A right click or Meta+K ("calquit") closes the panel. The pointer hides meanwhile ("calpanel 1",
renewed every second; the helper shows it again by itself when that stops).
What a capture teaches:
@@ -90,6 +101,7 @@ ROUND_BG = (0.03, 0.33, 0.8)
ROUND_NAMES = ("dark", "medium", "bright")
RING_SCALE = (1.0, 0.5, 1.0)
PANEL_RETRY = 10.0
FULL_RETRY = 10.0 # seconds before an automatic calibration that failed to start tries again
FIT_TIMEOUT = 300.0 # seconds the fit check stays up
FIT_EVERY = 0.5 # seconds between its cards' updates (each is a new picture for the panel)
FIT_HINT_WIDTH = 95 # characters a hint line holds in the panel
@@ -117,6 +129,42 @@ def check_dots(kind, own):
return out
# Why SteamVR's samples for a look were dropped (gazecal.steady_samples' counts) -> (short, long):
# short for the small panel, long for the calibration's. FIT_HINT goes after the ones the
# headset's fit causes, in the calibration's panel.
STEAM_REASONS = {"lost_left": ("left eye lost", "SteamVR lost your left eye"),
"lost_right": ("right eye lost", "SteamVR lost your right eye"),
"lost_both": ("both eyes lost", "SteamVR lost both eyes"),
"blink": ("blinked", "you blinked"),
"vergence": ("eyes disagreed", "SteamVR's two eyes disagreed")}
FIT_HINT = "check the headset fit"
ACCEPT_WAIT = 1.5 # seconds after a click with no capture before the panel says what it waits for
def reject_reason(reply, why):
"""Why a dot wasn't taken -> (short, long, fit): our tracker's reply (`reply`), or SteamVR's
drop counts (`why`, when `reply` is None). `fit`: the headset's fit is the likely cause."""
if reply is None:
if not why:
return "no reading", "SteamVR sent no reading for that look", False
key = max(why, key=why.get)
return *STEAM_REASONS[key], key.startswith("lost")
words = reply.removeprefix("fail ").split()
# ft-eyes: "fail the left eye was seen in only 3 frames", "fail the left eye moved (4.2 px)"
if len(words) >= 3 and words[0] == "the" and words[2] == "eye":
eye = words[1]
if "seen" in words:
return f"{eye} eye not seen", f"our tracker saw your {eye} eye in only {words[-2]} frames", True
if "moved" in words:
return f"{eye} eye moved", f"your {eye} eye moved while you looked", False
if not reply:
return "no answer", "our tracker didn't answer", False
if reply.startswith("our tracker isn't running"):
return "tracker not running", "our tracker isn't running", False
text = reply.removeprefix("fail ")
return text[:24], f"our tracker said: {text}", False
def spread(points):
"""The median point and the spread around it (1.4826 x the median distance: a standard
deviation that one stray sample can't move far)."""
@@ -166,8 +214,13 @@ class Checks:
sel.register(self.out, selectors.EVENT_READ, "checks")
self.check = None
self.gaze_on = None
self.headset = None # someone wears it (the helper's "worn"), False "away", None unknown
self.gaze_heard = 0.0
self.want_full_until = 0.0 # gaze mode came on before the tracker said whether it's calibrated
self.pending = None # (command words, when): asked for while the gaze service idled
self.full_armed = True # gaze mode on without a calibration opens the full one (need_full)
self.full_blocked = None # why it can't open now
self.full_retry_at = 0.0
self.full_failed = None # why the last calibration failed (too few dots), for problem()
self.last_quick = 0.0
self.sample_at = 0.0 # the tracker last sent anything
self.seen_at = 0.0 # eyes last seen (SteamVR's tracker's variance for them, "unc")
@@ -248,17 +301,22 @@ class Checks:
pass
def on_readable(self):
"""Replies on our socket: the helper's "ok on|off" to "gaze ?"; the panel's are dropped."""
"""Replies on our socket: the helper's "ok on|off [worn|away]" to "gaze ? headset" (an
older helper leaves the headset out); the panel's are dropped."""
while True:
try:
data = self.out.recv(4096).decode("utf-8", "replace")
words = self.out.recv(4096).decode("utf-8", "replace").split()
except (BlockingIOError, OSError):
return
if data in ("ok on", "ok off"):
on = data == "ok on"
was, self.gaze_on, self.gaze_heard = self.gaze_on, on, time.monotonic()
if on and was is False:
if words[:1] == ["ok"] and len(words) in (2, 3) and words[1] in ("on", "off"):
on = words[1] == "on"
headset = None if len(words) == 2 else words[2] == "worn"
was = (self.gaze_on, self.headset)
self.gaze_on, self.headset, self.gaze_heard = on, headset, time.monotonic()
if on and was[0] is False:
self.on_gaze_on()
if was != (on, headset):
self.svc.update_awake()
# --- State ---
@@ -282,11 +340,51 @@ class Checks:
return self.eyes_seen() and time.monotonic() - self.svc.last_sample < 2
def on_gaze_on(self):
self.full_armed = True
self.need_full("gaze mode came on without a calibration")
def need_full(self, reason):
"""Gaze mode is on without a calibration: open the full one, once per arming (see the top),
or note why it can't open."""
cal = self.calibrated()
if cal is False:
self.start("full", "gaze mode came on without a calibration")
elif cal is None:
self.want_full_until = time.monotonic() + 20
if cal:
self.full_armed = True # missing one later (the other tracker picked) is news again
if not self.gaze_on or self.check or not self.full_armed or cal is not False:
self.full_blocked = None
return
now = time.monotonic()
if not self.can_run() and self.svc.waking():
return # the tracker is still starting (the service idled)
if not self.can_run():
why = ("the eye tracker isn't sending" if now - self.svc.last_sample >= 2
else "no eyes seen (is the headset on?)")
elif now < self.full_retry_at:
return
else:
reply = self.start("full", reason)
why = None if reply == "ok" else reply.removeprefix("error ")
if why:
self.full_retry_at = now + FULL_RETRY
if why and why != self.full_blocked:
log(f"the calibration can't open: {why}")
self.full_blocked = why
if not why:
self.full_armed = False
def problem(self):
"""Why gaze mode, on, can't follow your eyes yet, or None. Our tracker not having said
yet is None: Input Settings has its own line for our tracker."""
if not self.gaze_on or self.calibrated() is not False:
return None
if self.check and self.check["kind"] == "full":
return "Not calibrated yet: the calibration is open in the headset"
if self.full_blocked:
return f"Not calibrated, and the calibration can't open: {self.full_blocked}"
if not self.full_armed:
if self.full_failed:
return f"Not calibrated: the calibration failed (most dots: {self.full_failed}). Use Calibrate"
return "Not calibrated: the calibration closed unfinished. Use Calibrate"
return "Not calibrated: the calibration opens in the headset"
def auto_quick(self, reason):
now = time.monotonic()
@@ -318,7 +416,7 @@ class Checks:
now = time.monotonic()
self.check = {"kind": kind, "reason": reason, "own": own, "dots": check_dots(kind, own), "i": 0,
"started": now, "shown": now, "run": [], "accept": False, "done_at": None, "tries": 0,
"skipped": 0, "captured": 0, "points": {}}
"skipped": 0, "captured": 0, "points": {}, "reasons": {}, "fit_reasons": set(), "note": ""}
log(f"{kind} check: {reason}")
if kind == "full":
st = ask(SCREENS, "state", 0.5).split()
@@ -402,10 +500,12 @@ class Checks:
self.to_panel(f"dot {yaw:.3f} {pitch:.3f} look")
self.last_progress = None
c["shown"] = time.monotonic()
c["run"], c["accept"], c["done_at"] = [], False, None
c["run"], c["accept"], c["done_at"], c["accept_at"] = [], False, None, None
def on_sample(self, s):
self.sample_at = time.monotonic()
if self.pending:
self.run_pending()
unc = (s["src"].get("mmap1") or {}).get("unc")
if unc and min(unc) <= EYE_LOST:
self.seen_at = time.monotonic()
@@ -428,6 +528,7 @@ class Checks:
if "hy" not in src:
return
now = time.monotonic()
c["gaze_at"] = now
if now < c["shown"] + CHECK_SETTLE:
return
g = (src["hy"], src["hp"])
@@ -488,7 +589,9 @@ class Checks:
if ok:
svc.weights["own"].add(miss)
else:
steady = steady_samples(samples)
why = {}
steady = steady_samples(samples, why=why)
rec["dropped"] = why
reads = {}
for name in ("action", "mmap1", "mmap2", "left", "right"):
pts = [(smp["src"][name]["hy"], smp["src"][name]["hp"]) for smp in steady
@@ -522,23 +625,41 @@ class Checks:
if svc.kind == "eyes":
svc.weights["steam"].add(miss)
svc.dirty = True
if not ok:
short, long, fit = reject_reason(rec.get("reply", "") if c["own"] else None, rec.get("dropped"))
rec["reason"] = long
c["reasons"][long] = c["reasons"].get(long, 0) + 1
if fit:
c["fit_reasons"].add(long)
rec["accepted"] = ok
self.log_check(rec)
if not ok:
c["tries"] += 1
log(f"{c['kind']} check dot {c['i'] + 1}: not taken ({rec.get('reply', '')})")
if c["tries"] >= 2 or c["kind"] != "full":
log(f"{c['kind']} check dot {c['i'] + 1}: not taken: {rec['reason']} ({rec.get('reply', '')})")
full = c["kind"] == "full"
if c["tries"] >= 2 or not full:
self.note(f"Dot skipped: {long}" + (f" ({FIT_HINT})" if fit else "") if full else f"Skipped: {short}")
self.skip()
else:
self.note(f"Not taken: {long}. Look at the dot and click again")
self.to_panel(f"dot {yaw:.3f} {pitch:.3f} fail")
c["run"], c["accept"] = [], False
c["run"], c["accept"], c["accept_at"] = [], False, None
c["shown"] = time.monotonic() # settle again, then retry
return
c["captured"] += 1
c["tries"] = 0
self.note("")
self.to_panel(f"dot {yaw:.3f} {pitch:.3f} done")
c["done_at"] = time.monotonic() + DONE_PAUSE
def note(self, text):
"""The panel's warning line, over the instructions (empty: none). It stays until the
next dot is taken, so a skipped dot's reason is still there at the one after it."""
c = self.check
if c.get("note") != text:
c["note"] = text
self.to_panel(f"note {text}".rstrip())
def skip(self):
c = self.check
yaw, pitch, _ = c["dots"][c["i"]]
@@ -567,12 +688,20 @@ class Checks:
return
n = len(c["dots"])
if c["captured"] < n * 2 / 3:
log(f"calibration failed: only {c['captured']} of {n} dots; the old one stays")
reasons = c["reasons"]
main = max(reasons, key=reasons.get) if reasons else None
self.full_failed = main
log(f"calibration failed: only {c['captured']} of {n} dots; the old one stays"
+ (f". Not taken: {', '.join(f'{r} ({k})' for r, k in reasons.items())}" if reasons else ""))
self.to_panel(f"text Calibration failed: only {c['captured']} of {n} dots. Try again from Input Settings")
if main:
fit = main in c["fit_reasons"]
self.note(f"Most dots: {main}" + (". Check headset fit on the Gaze page" if fit else ""))
self.to_panel("dot 0 0 off")
c["done_at"] = time.monotonic() + 3.0
c["done_at"] = time.monotonic() + (8.0 if main else 3.0) # time to read why
c["closing"] = True
return
self.full_failed = None
if c["own"]:
reply = ask(EYES, "calib-fit", 10.0)
log(f"calibration ({c['captured']} of {n} dots): our tracker says {reply or 'nothing'}")
@@ -629,9 +758,28 @@ class Checks:
# --- From the service ---
def command(self, words):
def run_pending(self):
"""A check asked for while the service idled: once the tracker sends (and our tracker has
said whether it's calibrated), or WAKE_SETTLE after waking, when its error is the real one."""
svc = self.svc
words, _ = self.pending
ready = (time.monotonic() - svc.last_sample < 2 if words[0] == "fitcheck" else self.can_run()) \
and (svc.kind != "own" or self.calibrated() is not None)
if not ready and svc.waking():
return
self.pending = None
reply = self.command(words, queue=False)
if reply != "ok":
log(f"{words[0]}, asked for while idle: {reply.removeprefix('error ')}")
def command(self, words, queue=True):
"""quickcal, calibrate, calaccept, calquit -> a reply."""
cmd = words[0]
if cmd in ("quickcal", "calibrate", "fitcheck") and queue and self.svc.waking() and not self.check:
# The tracker isn't running (or only just started): wake it, and do this once it sends.
self.pending = (words, time.monotonic())
self.svc.update_awake()
return "ok waking the eye tracker first"
if cmd == "quickcal":
return self.start("full" if self.calibrated() is False else "quick", "asked for")
if cmd == "calibrate":
@@ -642,6 +790,8 @@ class Checks:
if self.check and self.check["kind"] == "fit":
self.check["fit"].toggle_guide(time.monotonic())
elif self.check:
if not self.check["accept"]:
self.check["accept_at"] = time.monotonic()
self.check["accept"] = True
return "ok"
if cmd == "calquit":
@@ -688,6 +838,13 @@ class Checks:
return
if c["done_at"]:
return
if c["accept"] and c["accept_at"] and now - c["accept_at"] > ACCEPT_WAIT:
# Clicked, but no capture yet (see on_sample): say what it's waiting for.
full = c["kind"] == "full"
if now - c.get("gaze_at", 0.0) > 0.5:
self.note("Waiting: the eye tracker isn't sending a gaze" if full else "Waiting: no gaze")
else:
self.note("Waiting for your gaze to hold still on the dot" if full else "Hold your look still")
if c["kind"] == "quick" and now - c["started"] > QUICK_TIMEOUT:
self.close("ignored")
elif c["kind"] != "quick" and now - c["shown"] > CLICK_IDLE:
@@ -698,23 +855,20 @@ class Checks:
now = time.monotonic()
if not self.panel_proc and now >= self.panel_restart_at:
self.start_panel()
self.to_helper("gaze ?")
self.to_helper("gaze ? headset")
if now - self.gaze_heard > 5:
self.gaze_on = None # the helper isn't answering
self.gaze_on = self.headset = None # the helper isn't answering
if self.pending:
self.run_pending()
if self.check:
self.to_helper("calpanel 1")
if self.want_full_until:
cal = self.calibrated()
if cal is not None or now > self.want_full_until:
self.want_full_until = 0.0
if cal is False and self.gaze_on:
self.start("full", "gaze mode came on without a calibration")
if not self.eyes_seen(AWAY_MIN):
self.away, self.back_since = True, None
elif self.back_since is not None and not self.eyes_seen():
self.back_since = None # gone again before DON_DELAY
elif self.back_since is not None and now - self.back_since >= DON_DELAY:
self.away, self.back_since = False, None
self.full_armed = True # a calibration that closed unfinished opens again
self.auto_quick("the headset went on")
if svc.kind == "own" and now - svc.own_at < 5:
reseat = any(e.get("reseat") for e in (svc.own.get("eyes") or {}).values())
@@ -723,10 +877,13 @@ class Checks:
elif not self.reseat_seen and self.can_run():
self.reseat_seen = True
self.auto_quick("our tracker asked for a click")
self.need_full("gaze mode is on without a calibration")
def status(self):
c = self.check
st = {"check": None, "gaze_mode": self.gaze_on, "calibrated": self.calibrated(), "eyes": self.eyes_seen(),
st = {"check": None, "gaze_mode": self.gaze_on, "headset_worn": self.headset, "pending": self.pending[0][0]
if self.pending else None, "calibrated": self.calibrated(), "eyes": self.eyes_seen(),
"problem": self.problem(),
"panel": self.panel_proc is not None,
"last_quick_s": round(time.monotonic() - self.last_quick) if self.last_quick else None}
if c:
+15 -3
View File
@@ -22,6 +22,8 @@
// look, capture (a ring filling to progress), done,
// fail, off
// title <text> / text <text> a line at the top / at the bottom (empty to clear)
// note <text> a warning line just above the bottom one, in orange (red on
// the bright round): why a dot wasn't taken (empty to clear)
// eye <0|1> <r> <g> <b> <signal 0..1|-1> <seen 0..1|-1> <word>
// fit: an eye's card (0 left): its state in that colour, the
// tracker's signal, the share of the last 10 s it was seen
@@ -45,6 +47,7 @@
#include <drm_fourcc.h>
#include <fcntl.h>
#include <gbm.h>
#include <poll.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
@@ -143,7 +146,7 @@ struct Panel {
double wDeg = kQuickDeg; // across
std::vector<uint8_t> px;
double bg = 0.05;
std::string title, text;
std::string title, text, note;
bool dotOn = false;
double dotYaw = 0, dotPitch = 0, progress = 0;
std::string state = "off";
@@ -268,6 +271,9 @@ void Draw(Panel &p) {
const int titleSize = int(pxPerDeg * (p.full ? 1.5 : 1.1)), textSize = int(pxPerDeg * (p.full ? 1.2 : 0.9));
Text(p, p.title, titleSize, p.w / 2, int(titleSize * 1.2), faint);
Text(p, p.text, textSize, p.w / 2, p.h - int(textSize * 1.3), faint);
// Under the full calibration's lowest dots (RING degrees down) and over the text.
if (light) Text(p, p.note, textSize, p.w / 2, p.h - int(textSize * 2.8), 0.7, 0.12, 0.05);
else Text(p, p.note, textSize, p.w / 2, p.h - int(textSize * 2.8), 1.0, 0.62, 0.3);
if (p.fit) DrawFit(p, pxPerDeg, textSize, faint);
if (!p.dotOn || p.state == "off") return;
double x, y;
@@ -468,7 +474,7 @@ int main(int argc, char **argv) {
p.w = p.full ? kFullW : p.fit ? kFitW : kQuickPx;
p.h = p.full ? kFullH : p.fit ? kFitH : kQuickPx;
p.wDeg = p.full ? kFullDeg : p.fit ? kFitDeg : kQuickDeg;
p.title.clear(), p.text.clear(), p.dotOn = false, p.state = "off";
p.title.clear(), p.text.clear(), p.note.clear(), p.dotOn = false, p.state = "off";
p.eyes[0] = p.eyes[1] = EyeCard{}, p.hints.clear();
place();
visible = dirty = true; // shown with its first picture
@@ -496,6 +502,8 @@ int main(int argc, char **argv) {
p.title = buf[5] == ' ' ? buf + 6 : "", dirty = true;
} else if (!std::strncmp(buf, "text", 4)) {
p.text = buf[4] == ' ' ? buf + 5 : "", dirty = true;
} else if (!std::strncmp(buf, "note", 4)) {
p.note = buf[4] == ' ' ? buf + 5 : "", dirty = true;
} else if (std::sscanf(buf, "%15s", word) == 1 && !std::strcmp(word, "ping")) {
reply = visible ? "ok shown" : "ok hidden";
} else {
@@ -517,7 +525,11 @@ int main(int argc, char **argv) {
if (!shown) ov->ShowOverlay(h), shown = true;
dirty = false;
}
std::this_thread::sleep_for(std::chrono::milliseconds(visible ? 10 : 50));
// Until a command comes, or 10 ms while shown (SteamVR's events). Hidden, it waits up to a
// second: it woke 20 to 30 times a second for nothing, the main cost left with gaze idle.
// A closed stdin (--watch-stdin) wakes it too, so quitting doesn't wait.
pollfd fds[2] = {{sock, POLLIN, 0}, {0, POLLIN, 0}};
poll(fds, watchStdin ? 2 : 1, visible ? 10 : 1000);
}
ov->DestroyOverlay(h);
buffers.Drop();
+178
View File
@@ -0,0 +1,178 @@
#!/usr/bin/env python3
"""Offline test of the gaze service idling (gaze/ft-gazed, gaze/gazecheck.py): ft-gaze runs only
while the gaze is in use, and a check asked for while it idles waits for the tracker.
Runs ft-gazed's Service with its sockets renamed, a fake pointer helper (answers "gaze ?
headset" as the test says), and a fake ft-gaze (prints samples, quits when its stdin closes).
SteamVR's tracker is the one in use, so our own isn't started; the panel isn't either. Nothing
reaches the live gaze service, the pointer helper, or SteamVR, so it's safe next to them.
gaze/test/idle-test.py
"""
import importlib.machinery
import importlib.util
import os
import socket
import subprocess
import sys
import tempfile
import threading
import time
HERE = os.path.dirname(os.path.abspath(__file__))
GAZE = os.path.join(HERE, "..")
sys.path.insert(0, GAZE)
loader = importlib.machinery.SourceFileLoader("ftgazed", os.path.join(GAZE, "ft-gazed"))
gazed = importlib.util.module_from_spec(importlib.util.spec_from_loader("ftgazed", loader))
loader.exec_module(gazed)
import gazecheck # noqa: E402 (the module ft-gazed imported)
tag = f"ft_gaze_idle_test_{os.getpid()}"
gazed.ME = f"\0{tag}_gazed"
gazed.POINTER = gazecheck.POINTER = f"\0{tag}_helper"
gazecheck.SCREENS = f"\0{tag}_screens"
gazecheck.PANEL_PROG = gazed.REPO / "nonexistent-panel" # "isn't built": no panel
gazed.IDLE_AFTER, gazed.WAKE_SETTLE = 1.0, 3.0
gazed.read_settings = lambda: ("steam", "steam", "auto", 55.0)
logs = []
gazed.log = gazecheck.log = lambda msg: logs.append(msg)
# The fake ft-gaze: 90 samples a second, both eyes seen, until its stdin closes. It logs the
# sources it was asked for: "argv LIST" (--sources), then "line LIST" for each "sources LIST".
tmp = tempfile.mkdtemp(prefix="ft-gaze-idle-test-")
FAKE = os.path.join(tmp, "ft-gaze")
SOURCES_LOG = os.path.join(tmp, "sources.log")
with open(FAKE, "w") as f:
f.write('''import json, os, select, sys, time
log = open(sys.argv[1], "a", buffering=1)
log.write("argv " + (sys.argv[sys.argv.index("--sources") + 1] if "--sources" in sys.argv else "-") + "\\n")
buf = b""
while True:
if select.select([sys.stdin], [], [], 1 / 90)[0]:
data = os.read(0, 4096)
if not data:
break
buf += data
while b"\\n" in buf:
line, buf = buf.split(b"\\n", 1)
if line.startswith(b"sources "):
log.write("line " + line[8:].decode() + "\\n")
eye = {"hy": 1.0, "hp": 2.0}
print(json.dumps({"t": time.monotonic(), "src": {"mmap1": {"hy": 1.0, "hp": 2.0, "unc": [0.001, 0.001],
"open": [0.8, 0.8]}, "left": eye, "right": eye}}), flush=True)
''')
started = []
def start_helper(self):
"""ft-gaze, straight from here instead of the dev container."""
import selectors
self.proc = subprocess.Popen([sys.executable, FAKE, SOURCES_LOG, "--sources", self.wanted_sources()],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self.proc_sources = self.wanted_sources()
os.set_blocking(self.proc.stdout.fileno(), False)
os.set_blocking(self.proc.stderr.fileno(), False)
self.sel.register(self.proc.stdout, selectors.EVENT_READ, "stdout")
self.sel.register(self.proc.stderr, selectors.EVENT_READ, "stderr")
self.buf = b""
started.append(time.monotonic())
gazed.Service.start_helper = start_helper
# The fake pointer helper.
helper_state = {"reply": "ok off worn"}
helper = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
helper.bind(gazed.POINTER)
helper.settimeout(0.2)
def answer():
while True:
try:
data, addr = helper.recvfrom(512)
except socket.timeout:
continue
except OSError:
return
if data.startswith(b"gaze ?") and addr:
helper.sendto(helper_state["reply"].encode(), addr)
threading.Thread(target=answer, daemon=True).start()
svc = gazed.Service(None, False, gazed.POINTER)
threading.Thread(target=svc.run, daemon=True).start()
ctl = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
ctl.bind("")
ctl.settimeout(2)
def ask(cmd):
ctl.sendto(cmd.encode(), gazed.ME)
return ctl.recv(4096).decode()
failures = []
def check(label, got, want):
ok = got == want
print(("ok " if ok else "FAIL ") + label + ("" if ok else f": got {got!r}, want {want!r}"), flush=True)
if not ok:
failures.append(label)
def wait(cond, seconds):
end = time.monotonic() + seconds
while time.monotonic() < end:
if cond():
return True
time.sleep(0.05)
return cond()
time.sleep(2.5)
check("gaze mode off: idle, no ft-gaze", (svc.awake, svc.proc is None), (False, True))
check("status says why", ask("status").count('"idle": "gaze mode is off"'), 1)
helper_state["reply"] = "ok on worn"
check("gaze mode on, headset worn: awake within 2 s", wait(lambda: svc.awake and svc.proc is not None, 2.5), True)
check("samples come in", wait(lambda: svc.counts["samples"] > 20, 2), True)
helper_state["reply"] = "ok on away"
check("headset off: still awake for IDLE_AFTER", wait(lambda: not svc.awake, 0.5), False)
check("then idle, ft-gaze stopped", wait(lambda: not svc.awake and svc.proc is None, 3.5), True)
check("why: nobody wears it", ask("status").count('"idle": "nobody is wearing the headset"'), 1)
helper_state["reply"] = "ok on"
check("an older helper (no headset word): awake with gaze mode on", wait(lambda: svc.awake, 2.5), True)
helper_state["reply"] = "ok off worn"
check("gaze mode off again: idle", wait(lambda: not svc.awake and svc.proc is None, 4.5), True)
check("wake lease", ask("wake 2"), "ok")
check("wake: awake at once", (svc.awake, wait(lambda: svc.proc is not None, 1)), (True, True))
check("lease over (2 s + IDLE_AFTER): idle", wait(lambda: not svc.awake, 4.5), True)
time.sleep(0.5)
logs.clear()
open(SOURCES_LOG, "w").close()
count = len(started)
check("quick check while idle: queued, waking", ask("quickcal"), "ok waking the eye tracker first")
check("it woke", wait(lambda: svc.awake and len(started) > count, 1.5), True)
check("once the tracker sends, it ran (and says why it couldn't open)",
wait(lambda: any("quickcal, asked for while idle: the panel isn't running" in m for m in logs), 3), True)
check("nothing left pending", svc.checks.pending, None)
sources = open(SOURCES_LOG).read().split("\n")
check("ft-gaze started with every source for the check", sources[0], "argv all")
in_use = svc.wanted_sources()
check("then only those in use (SteamVR's tracker: not the action, not own)",
(f"line {in_use}" in sources, in_use != "all", "action" in in_use, "own" in in_use), (True, True, False, False))
check("idle again after", wait(lambda: not svc.awake, 3), True)
print("FAILED: " + ", ".join(failures) if failures else "all passed", flush=True)
svc.running = False
time.sleep(0.7)
os.remove(FAKE)
os.remove(SOURCES_LOG)
os.rmdir(tmp)
os._exit(1 if failures else 0)
+6 -1
View File
@@ -9,7 +9,12 @@ the search runs again with a smaller closing.
import cv2
import numpy as np
DARK = 30 # pupil pixels are below this (the face around it is 40-180)
# One thread: OpenCV's pool of one per core costs more than it saves on a frame this small
# (a 140-240 px window while it follows the pupil). Its idle workers spun and yielded about
# 14,000 times a second each, a quarter of a core, beside SteamVR's compositor.
cv2.setNumThreads(1)
DARK = 30 # pupil pixels are below this (the face around it is 40-180)
MIN_AREA = 150 # pupil area range in pixels
MAX_AREA = 20000
MIN_FILL = 0.75 # blob area / fitted-ellipse area
+7
View File
@@ -63,6 +63,13 @@ reading only.
frame when its camera starts the frame after next (no slot is rewritten sooner than three
frames), ignores late writes to the frame just finished, and saves from a separate
thread. fit1 may hold a few percent of torn frames.
- `--share` (2026-10-03) checks only the slot each camera writes next, from the two before
(the orders above, learned again if they change; all four slots for 2 s after a frame turns
up elsewhere), sleeps until 2.5 ms before the next frame is due, then looks every 1 ms with
0.5 ms of timer slack. Against the 0.3 ms poll of all eight slots, on simulated cameras:
207 wakeups a second instead of 1,486, 0.8% of a core instead of 3.6% (more on the real
DMA-BUF memory), no torn or skipped frames, and a frame's start seen 1.35 ms late on
average instead of 0.76. `--rec` still polls all slots every 0.3 ms, for its times.
- Eye tracking stops when the headset is off ("HMD off, stopping eye tracking"), so
recordings are empty then.
- **Which camera is which eye** (capture fit1, 2026-09-29, closing one eye at a time):
+73 -16
View File
@@ -46,6 +46,7 @@
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <time.h>
@@ -288,20 +289,53 @@ static int eye_buffer(void) {
// Calls done(frame, slot, time) for every complete eye-camera frame until `seconds` pass
// (forever if negative), a stop signal comes, the tracker process goes away, or keep()
// (checked about every 0.25 s, when given) says to stop.
// (checked about every 0.25 s, when given) says to stop. Looks every `poll_us`.
//
// A frame lands over several milliseconds, in bursts, and its last bursts can come after
// the camera has started its next frame. A slot isn't rewritten until at least three frames
// later (camera 0 cycles 3,0,1,2; camera 1 7,5,4,6,5,7,6,4), so a frame is passed on when
// its camera starts the frame after next. Changes to the slot just finished are late bursts,
// not a new frame. A frame's time is when its slot first changed.
//
// Each look checks only the slot each camera writes next: the one that followed the last two
// before (after[][], seeded with the orders above and learned as frames come). Every check
// reads 256 words spread over a frame in DMA-BUF memory, so all eight slots each time was
// most of the cost. A camera with nothing in its expected slot for 1.5 frames, or with no
// order known yet, has all its slots checked until a frame comes. When that finds a frame
// somewhere else (the order changed, or a frame was missed), all its slots are checked for
// SCAN_AFTER_MISS, as before, while after[][] learns the new order. A slot's fingerprint is
// taken again when it stops being one of the two in use, so a check later sees only a new frame.
// Between frames it sleeps until FRAME_EARLY before the next one is due (the cameras run at
// 90 fps, within a ms of each other), then looks every `poll_us`.
#define FRAME_DUE (1.5 / 90) // s: a camera that hasn't started a frame by then gets all its slots checked
#define SCAN_AFTER_MISS 2.0 // s of checking all slots after a frame came in an unexpected one
#define CAMS_IDLE 0.5 // s without a frame from either camera: look 4 times less often
#define FRAME_EARLY 0.0025 // s before a frame is due to start looking for it
// When to start looking for the next frame: FRAME_EARLY before the first camera's is due. A
// camera already late (it lost its order, or stopped) means now.
static double next_due(const double last[2], double t) {
double due = 1e300;
for (int cam = 0; cam < 2; cam++) {
double d = last[cam] + 1.0 / 90 - FRAME_EARLY;
if (t - last[cam] > CAMS_IDLE) continue; // stopped: the other one sets the pace
if (d < due) due = d;
}
return due < 1e300 ? due : t;
}
static void poll_frames(int b, double seconds, int pid, void (*done)(const uint8_t *, int, double),
int (*keep)(void)) {
int (*keep)(void), unsigned poll_us) {
static const int order[2][8] = {{3, 0, 1, 2, 3, 0, 1, 2}, {7, 5, 4, 6, 5, 7, 6, 4}};
int after[EYE_SLOTS][EYE_SLOTS];
memset(after, -1, sizeof after);
for (int c = 0; c < 2; c++)
for (int i = 0; i < 8; i++) after[order[c][i]][order[c][(i + 1) % 8]] = order[c][(i + 2) % 8];
uint64_t sig[EYE_SLOTS];
double first[EYE_SLOTS];
int cur[2] = {-1, -1}, prev[2] = {-1, -1};
for (int k = 0; k < EYE_SLOTS; k++) sig[k] = frame_sig(bufs[b].p + slot_start(k)), first[k] = 0;
double start = now(), checked = start, kept = start;
double start = now(), checked = start, kept = start, last[2] = {start, start}, scan_until[2] = {0, 0};
char proc[64];
snprintf(proc, sizeof proc, "/proc/%d", pid);
while ((seconds < 0 || now() - start < seconds) && !stop_rec) {
@@ -315,18 +349,36 @@ static void poll_frames(int b, double seconds, int pid, void (*done)(const uint8
if (!keep()) return;
kept = t;
}
for (int k = 0; k < EYE_SLOTS; k++) {
uint64_t s = frame_sig(bufs[b].p + slot_start(k));
if (s == sig[k]) continue;
sig[k] = s;
int cam = k >= 4;
if (k == cur[cam] || k == prev[cam]) continue; // landing, or a late burst
if (prev[cam] >= 0) done(bufs[b].p + slot_start(prev[cam]), prev[cam], first[prev[cam]]);
prev[cam] = cur[cam];
cur[cam] = k;
first[k] = t;
for (int cam = 0; cam < 2; cam++) {
int next = prev[cam] >= 0 ? after[prev[cam]][cur[cam]] : -1;
int all = next < 0 || t - last[cam] > FRAME_DUE || t < scan_until[cam];
int from = all ? cam * 4 : next, to = all ? cam * 4 + 4 : next + 1;
for (int k = from; k < to; k++) {
uint64_t s = frame_sig(bufs[b].p + slot_start(k));
if (s == sig[k]) continue;
sig[k] = s;
if (k == cur[cam] || k == prev[cam]) continue; // landing, or a late burst
if (next >= 0 && k != next) scan_until[cam] = t + SCAN_AFTER_MISS;
if (prev[cam] >= 0) {
done(bufs[b].p + slot_start(prev[cam]), prev[cam], first[prev[cam]]);
after[prev[cam]][cur[cam]] = k;
// Out of use from now on: later changes are a new frame.
sig[prev[cam]] = frame_sig(bufs[b].p + slot_start(prev[cam]));
}
prev[cam] = cur[cam];
cur[cam] = k;
first[k] = t;
last[cam] = t;
next = prev[cam] >= 0 ? after[prev[cam]][cur[cam]] : -1;
}
}
usleep(300);
double wait = poll_us * 1e-6;
if (t - last[0] > CAMS_IDLE && t - last[1] > CAMS_IDLE) {
wait *= 4;
} else if (next_due(last, t) - t > wait) {
wait = next_due(last, t) - t;
}
usleep((useconds_t)(wait * 1e6));
}
}
@@ -356,7 +408,7 @@ static int rec(double seconds, const char *dir, int pid) {
pthread_t writer;
pthread_create(&writer, NULL, ring_writer, NULL);
double start = now();
poll_frames(b, seconds, pid, rec_frame, NULL);
poll_frames(b, seconds, pid, rec_frame, NULL, 300); // 0.3 ms: recordings' times
pthread_mutex_lock(&ring.mu);
ring.done = 1;
pthread_cond_signal(&ring.cv);
@@ -383,6 +435,10 @@ static int rec(double seconds, const char *dir, int pid) {
#define SHARE_SLOTS 8
#define SHARE_MAGIC 0x31434546u // "FEC1"
#define WANT_FRESH 3.0 // seconds a touch of the --want file lasts
// How often --share looks for frames, with a timer slack that lets the kernel group the
// wakeups: a frame reaches ft-eyes 1 to 1.5 ms after its camera starts the next, not 0.3.
#define SHARE_POLL_US 1000
#define SHARE_SLACK_NS 500000
typedef struct {
uint32_t magic, version, width, height, slots, entry_size;
@@ -462,6 +518,7 @@ static int share_loop(const char *path) {
.slots = SHARE_SLOTS, .entry_size = (uint32_t)esize};
signal(SIGINT, on_stop);
signal(SIGTERM, on_stop);
if (prctl(PR_SET_TIMERSLACK, SHARE_SLACK_NS, 0, 0, 0) != 0) perror("PR_SET_TIMERSLACK");
fprintf(stderr, "ft-eyegrab: sharing frames in %s%s%s\n", path, want_path ? " while wanted by " : "",
want_path ? want_path : "");
int pid = -1, idle = -1, missing = 0;
@@ -486,7 +543,7 @@ static int share_loop(const char *path) {
if (idle != 0 || missing) fprintf(stderr, "ft-eyegrab: copying frames from eyetracking %d\n", pid);
idle = 0, missing = 0;
h->tracker_pid = pid;
poll_frames(eye_buffer(), -1, pid, share_frame, wanted);
poll_frames(eye_buffer(), -1, pid, share_frame, wanted, SHARE_POLL_US);
struct stat st;
char proc[64];
snprintf(proc, sizeof proc, "/proc/%d", pid);
+42 -4
View File
@@ -50,6 +50,7 @@ import json
import math
import mmap
import os
import select
import socket
import struct
import sys
@@ -58,7 +59,12 @@ import time
from collections import deque
from pathlib import Path
import numpy as np
# One thread for numpy's BLAS and OpenMP, set before numpy loads: it would start one per core
# (8 here) for small arrays that never need them. eyes_pupil keeps OpenCV to one as well.
for _var in ("OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS"):
os.environ.setdefault(_var, "1")
import numpy as np # noqa: E402
sys.path.insert(0, str(Path(__file__).resolve().parent))
import eyes_model # noqa: E402
@@ -82,6 +88,15 @@ GAP = 3.0 # s without frames: the headset was off, and may sit diffe
CLICK_BEFORE = 0.3 # a click's frames: the 300 ms before it (like the probe's fixation)
CALIB_MIN = 15 # frames an eye needs in a calibration dot's window
CALIB_SPREAD = 4.0 # px: more than this and the eye moved during the dot
# Waiting for frames. They come only as a counter in shared memory, so there's nothing to block
# on: sleep until a camera's next frame is due, then look every POLL. ft-eyegrab passes each one
# on within a ms or two of when its camera starts the one after, so they arrive 11.1 ms apart,
# give or take that.
PERIOD = 1 / 90 # s between a camera's frames
EARLY = 0.002 # start looking this long before a frame is due
POLL = 0.001 # then this often until it comes
STALLED = 0.1 # s without a frame: that camera stopped (headset off), and isn't waited for
IDLE_POLL = 0.02 # how often to look while both are stopped
class Cams:
@@ -352,7 +367,7 @@ def wait_for_cams(sock, tracker, want):
return Cams()
except (OSError, ValueError, RuntimeError):
serve(sock, tracker)
time.sleep(0.2)
select.select([sock], [], [], 0.2)
def serve(sock, tracker):
@@ -372,7 +387,24 @@ def serve(sock, tracker):
pass
def below_steamvr():
"""Nice 10 and SCHED_BATCH, for this thread and those it starts. ft-eyes runs in the dev
container's podman scope, where the gaze service's unit doesn't reach it, so it ran at
nice 0 on the cores vrcompositor and vrserver use. Batch also lets a waking ft-eyes wait
for the running task's turn instead of taking the core: a frame a few ms late costs the
gaze little, a late compositor frame costs a dropped frame in the headset."""
try:
os.setpriority(os.PRIO_PROCESS, 0, max(os.getpriority(os.PRIO_PROCESS, 0), 10))
except OSError as e:
print(f"ft-eyes: nice: {e}", file=sys.stderr, flush=True)
try:
os.sched_setscheduler(0, os.SCHED_BATCH, os.sched_param(0))
except (OSError, AttributeError) as e:
print(f"ft-eyes: SCHED_BATCH: {e}", file=sys.stderr, flush=True)
def main():
below_steamvr()
verbose = "-v" in sys.argv
if "--watch-stdin" in sys.argv:
# Run by ft-gazed through distrobox, which doesn't pass a stop on: quit when our
@@ -398,6 +430,7 @@ def main():
print("ft-eyes: frames found, tracking", file=sys.stderr, flush=True)
seen = [cams.count(0), cams.count(1)]
report = time.monotonic()
arrived = [0.0, 0.0] # when each camera's newest frame was seen (monotonic)
while True:
serve(sock, tracker)
want()
@@ -407,6 +440,7 @@ def main():
if n == seen[c]:
continue
seen[c] = n
arrived[c] = time.monotonic()
got = cams.frame(c, n - 1) # only the newest: never fall behind
if got:
eyes[c].feed(*got)
@@ -425,8 +459,6 @@ def main():
shifts += [float(v) for v in e.shift.value]
pupils += [e.gaze[3], e.gaze[4]] if fresh else [math.nan, math.nan]
out.write(latest, (yaw, pitch), flags, per, shifts, pupils)
else:
time.sleep(0.001)
now = time.monotonic()
if now - report >= 5:
if verbose:
@@ -444,6 +476,12 @@ def main():
print("ft-eyes: frames went away; waiting", file=sys.stderr, flush=True)
cams = wait_for_cams(sock, tracker, want)
seen = [cams.count(0), cams.count(1)]
# Until the next frame is due (a command on the socket wakes us sooner).
wait = IDLE_POLL
for c in (0, 1):
if now - arrived[c] < STALLED:
wait = min(wait, max(arrived[c] + PERIOD - EARLY - now, POLL))
select.select([sock], [], [], wait)
if __name__ == "__main__":
+3 -2
View File
@@ -2,8 +2,9 @@
# Install (or remove) the frame grabber our own eye tracker needs: ft-eyegrab, as the system
# service frametop-eyegrab.service. It copies the eye-camera frames, read-only, out of
# SteamVR's eyetracking process into /dev/shm/frametop-eyes-cams for ft-eyes, and only while
# ft-eyes wants them. The gaze service (gaze/ft-gazed) runs ft-eyes itself, when Eye tracker
# is Own tracker or the gaze probe uses it.
# ft-eyes wants them. The gaze service (gaze/ft-gazed) runs ft-eyes itself, when ours is the
# tracker in use (GAZE_TRACKER=auto, the default, picks it once this is installed) or the gaze
# probe uses it. install.sh offers this after gaze mode.
# Needs host sudo, for the binary (/etc/frametop/ft-eyegrab, root's) and the unit: it asks for
# the password in the terminal, on the Frame or from a PC, or runs SUDO_ASKPASS when that's set
# (frame_sudo in scripts/_env.sh, which also takes it from the repo's .env).
+11 -3
View File
@@ -1,6 +1,7 @@
# Hand tracking, built into build/ (hands/build.sh runs this in the dev container):
# make ft-camd (camd/: runs on the host, so linked statically) and ft-hands (track/)
# make tools ft-handreplay and ft-ringplay, for recordings
# make check builds and runs the C++ unit tests (tests/sides_test.cpp)
# The first build fetches ncnn (NCNN_TAG) and builds it into build/ncnn, which takes a few
# minutes. NCNN=DIR uses an ncnn install already built instead.
NCNN_TAG = 20260526
@@ -11,7 +12,7 @@ CXXFLAGS += -std=c++17 -fopenmp -I$(NCNN)/include/ncnn
LDLIBS = $(NCNN)/lib/libncnn.a -ljsoncpp -fopenmp -lpthread
CAMD = camd/camd.c camd/tp.c camd/xrcams.c
TRACK = track/calib.cpp track/nets.cpp track/tracker.cpp track/io.cpp track/record.cpp track/pinch.cpp
TRACK = track/calib.cpp track/nets.cpp track/tracker.cpp track/io.cpp track/record.cpp track/pinch.cpp track/sides.cpp
HDR = $(wildcard track/*.h) camd/fhring.h include/fh_hands.h include/fh_gestures.h
all: build/ft-camd build/ft-hands
@@ -29,6 +30,13 @@ build/ft-handreplay: track/replay.cpp $(TRACK) $(HDR) $(NCNN)/lib/libncnn.a
@mkdir -p build
$(CXX) $(CXXFLAGS) -o $@ track/replay.cpp $(TRACK) $(LDLIBS)
build/sides-test: tests/sides_test.cpp $(TRACK) $(HDR) $(NCNN)/lib/libncnn.a
@mkdir -p build
$(CXX) $(CXXFLAGS) -o $@ tests/sides_test.cpp $(TRACK) $(LDLIBS)
check: build/sides-test
build/sides-test
build/ft-ringplay: track/ringplay.cpp track/record.h camd/fhring.h
@mkdir -p build
$(CXX) $(CXXFLAGS) -o $@ track/ringplay.cpp
@@ -44,6 +52,6 @@ build/ncnn/install/lib/libncnn.a:
cmake --build build/ncnn/build --target install > build/ncnn/build.log
clean:
rm -f build/ft-camd build/ft-hands build/ft-handreplay build/ft-ringplay
rm -f build/ft-camd build/ft-hands build/ft-handreplay build/ft-ringplay build/sides-test
.PHONY: all tools clean
.PHONY: all tools check clean
+62 -6
View File
@@ -14,6 +14,8 @@ Two programs, each a user service that stops when SteamVR does:
They don't start with SteamVR. `hands/run.sh install` builds them, gives ft-camd its capabilities, installs both services disabled, and links `hands/ft-handsctl` into `~/.local/bin`. Then `ft-handsctl on` starts hand tracking and `ft-handsctl off` stops it. `install.sh` doesn't install it.
For the cutouts alone, `hands/ft-cutouts on` starts the same two programs with ft-hands' `--no-gestures`: your hands show through the screens, and no pinch or grip is detected, so nothing clicks or drags. It runs this checkout's build as transient user units, so it needs `hands/build.sh` and ft-camd's capabilities (`hands/run.sh caps`) but not `hands/run.sh install`. It and `ft-handsctl on` stop each other's services, and it stops with SteamVR too.
```
ft-handsctl on | off # on the Frame: start or stop hand tracking (SteamVR must be running)
ft-handsctl status # the services, and ft-hands' last status lines
@@ -21,6 +23,8 @@ ft-handsctl log [lines]
ft-handsctl cutouts on|off|state # ft-screens' hand cutouts, without stopping tracking
ft-handsctl gestures # pinches and grips, live (tools/watch_gestures.py --distance)
hands/ft-cutouts on | off | status # the cutouts only: no pinches or grips
hands/run.sh install # build, give ft-camd its capabilities (sudo, once per build), install disabled
hands/run.sh start|stop # start or stop the services
hands/run.sh restart # after changing a setting
@@ -32,7 +36,7 @@ hands/run.sh uninstall
Settings in `~/.config/frametop.conf` (`FT_<name>` in the environment overrides them), read when ft-camd and ft-hands start:
- `HANDS_SWAP_SIDES=1`: the two side cameras' names are swapped (see ft-camd below). Check with `tools/check_sides.py --ring`.
- `HANDS_SWAP_SIDES=auto` (the default): ft-hands tells from the hands which side camera is which, and corrects ft-camd's names when they're backwards (see "Which camera is which" below). `1` forces them exchanged and `0` forces ft-camd's names; ft-hands still checks and logs a warning if the hands disagree.
- `HANDS_CPUS=5,6,7`: the CPUs the model threads run on (below).
- `HANDS_CAMERAS` (`auto`), `HANDS_BRIGHT` (`all`), `HANDS_BRIGHT_ON` (40), `HANDS_BRIGHT_OFF` (25): which cameras ft-hands tracks with, as `--cams`, `--bright`, `--bright-on` and `--bright-off` (see ft-hands). `HANDS_CAMERAS=mono` also keeps ft-camd off the colour cameras.
- `HANDS_COLOR_LEFT` (`color_video0`), `HANDS_COLOR_CROP` (`subtract`): how the colour module's calibration maps onto its images, as `--color-left` and `--color-crop`.
@@ -82,7 +86,14 @@ Options:
It exits when XRService exits, or when a camera's buffers keep going stale, which means XRService has reallocated them. The service starts it again, and it attaches to the new buffers.
**Which camera is which:** video9 is `slam_left`, video13 is `slam_right`, video6 is `upper_left` and video7 is `upper_right`. This was checked by rendering the same view from each camera with the factory calibration. But ft-camd tells the side cameras' buffers apart only by XRService's allocation order, and after some XRService restarts it gets them backwards. Then every hand is seen by one camera only, at the wrong depth, and the hand holes land beside the hands. With the headset on, looking at a room with some texture, `tools/check_sides.py --ring` says whether the names are right (exit 0), swapped (exit 3), or it can't tell (exit 2). When they're swapped, set `HANDS_SWAP_SIDES=1`. The colour cameras are video3 (`arcimx616 0-0010`) and video0 (`0-001a`); which of them is `passthrough_left` in the module's calibration is for `tools/check_color.py` to settle, on a recording with texture in view.
**Which camera is which:** video9 is `slam_left`, video13 is `slam_right`, video6 is `upper_left` and video7 is `upper_right`. This was checked by rendering the same view from each camera with the factory calibration. But ft-camd tells the side cameras' buffers apart only by XRService's allocation order, and after some XRService restarts it gets them backwards. Then every hand is seen by one camera only, at the wrong depth, and the hand holes land beside the hands. ft-hands now catches this by itself (`track/sides.h`, `HANDS_SWAP_SIDES=auto`):
- Whenever a hand's landmarks are found in two cameras at once (one of them a side camera), it intersects the rays through the 21 landmarks twice: once with the calibrations as named, once with the two side cameras exchanged. The same hand seen the right way meets within a few mm, in front of both cameras and as far away as its size says. The wrong way misses by centimetres or meets behind a camera.
- With the names wrong, the tracker never gets such pairs on its own: it hands the hand over to where the wrong calibration puts it and finds nothing there. So 5 times a second while undecided, the check places a tracked hand in 3D under the other naming and runs the landmark model where that puts it in the other side camera.
- It decides after 10 votes one way and none the other, or 20 with at most a fifth the other way, over at least 1 s. That takes about 1-2 s of hands in view. If the names are backwards, it exchanges them; the tracked views move with their images. Then it checks once more, more strictly.
- The log says what it found (`side cameras: SWAPPED, now exchanged after 3.2 s (votes ...)`). So does `/run/user/UID/frametop-hands/sides.json`, which the hand recorder reads. Recordings get a `DIR/sides.json` (hands/rec/sides.py has the rules).
- `--record-only` can't tell (it tracks nothing): it records ft-camd's names unless `--sides 0|1` says otherwise.
`tools/check_sides.py --ring` is the independent check from the scene (ORB matches meeting under each naming): exit 0 as named, 3 swapped, 2 can't tell. `--pair upper` checks the upper pair the same way: in every recording so far (3 XRService starts, both side namings) the upper pair was named right. The colour cameras are video3 (`arcimx616 0-0010`) and video0 (`0-001a`); which of them is `passthrough_left` in the module's calibration is for `tools/check_color.py` to settle, on a recording with texture in view.
## ft-hands
@@ -98,13 +109,14 @@ Options:
- `--threads N`: model threads, pinned to the `--cpus` list. Default 3.
- `--cpus LIST`: CPUs for the model threads and the main loop. Default `5,6,7` (`HANDS_CPUS`). SteamOS starts user processes on CPUs 0-4, and XRService's head tracking runs on 2-3. With the headset on, a step took 8.4 ms on 5-7 against 13.2 ms on 2-4, and SteamVR's frame timing didn't change (2026-09-29, three rounds of the same replayed frames).
- `--contrast MODE` or `PALM/HAND`: how crops are equalized before the models see them: `clahe[:CLIP]`, `none`, or `stretch` (1st-99th percentile). Default `clahe:2/none`. In the dim recording, CLAHE let the palm search find about 10% more hands, but it made the landmarks jitter more (published median 6.9 mm, against 6.0 mm with plain landmark crops).
- `--swap-sides`: swap the two side cameras (`HANDS_SWAP_SIDES`, see ft-camd).
- `--sides auto|0|1`: which side camera is which (`HANDS_SWAP_SIDES`, see "Which camera is which"); `--swap-sides` is `--sides 1`.
- `--seconds N`: stop after N seconds.
- `--status S`: how often to print status, in seconds.
- `--models DIR`: where the models are.
- `--nice N`: niceness. Default 5, so the VR stack wins contested CPUs.
- `--no-publish`: don't write the hands and gestures files.
- `--record DIR`, `--record-for S`: save every frame set for S seconds (default 120) to `DIR/sets.bin`. That's about 80 MB/s. Sending the tracker SIGUSR1 (`pkill -USR1 -x ft-hands`) starts a recording in `~/.local/share/frametop/hands/rec-<time>` without a restart. Recordings are images of your hands and room: they stay on the headset unless you move them.
- `--no-gestures`: hands for the cutouts only. No pinch or grip detection, so nothing reaches the pointer and a closing hand doesn't raise the rate to 30 Hz. The gestures file is removed at start. `ft-cutouts` runs it this way.
- `--record DIR`, `--record-for S`, `--record-hz N`: save every frame set for S seconds (default 120) to `DIR/sets.bin`, or at most N sets a second with `--record-hz` (the hand recorder uses 10). Every set is about 80 MB/s. Sending the tracker SIGUSR1 (`pkill -USR1 -x ft-hands`) starts a recording in `~/.local/share/frametop/hands/rec-<time>` without a restart. Recordings are images of your hands and room: they stay on the headset unless you move them.
- `--record-only`: record without tracking or publishing, so it can run beside the live tracker. Give it `--record DIR`, since SIGUSR1 would reach both trackers. With `ft-camd --with-dark`, recordings also hold each camera's newest dark frame as `<name>_dk`, which doubles the rate. With `--with-color`, each colour camera's newest frame is saved with every set, as `color_video<N>`, which adds about 70 MB/s. Run the recorder at normal I/O priority: idle I/O priority stalled a 165 MB/s recording.
- `--keep-presence P`: the landmark presence a tracked view needs to stay tracked. New views always need 0.5. Default 0.5. Lowering it to 0.2 barely helped in the bright recording, because lost hands drop to near-zero presence.
- `--ring PATH`: read frames from another ring, such as `ft-ringplay`'s.
@@ -192,7 +204,7 @@ hands/build/ft-handreplay ~/.local/share/frametop/hands/rec-20260929-120000 --co
Python, with NumPy and OpenCV. `setup/dev-container.sh` doesn't install them, because Fedora's `python3-opencv` pulls in over a gigabyte; in the dev container, run `sudo dnf install python3-numpy python3-opencv` once. Off the Frame, `FRAME_JOB_DEVICE_ROOT` can point at a folder with copies of the headset's calibration files.
- `tools/check_sides.py --ring` (or a recording): are the side cameras named right?
- `tools/check_sides.py --ring` (or a recording, a sets file, `--pair upper`, `--calib DIR`, `--json`): are the side cameras named right, from the scene? ft-handreplay's `--sides file|0|1|auto` replays with DIR/sides.json's names (the default), as recorded, exchanged, or as auto decides, and reports what the side check found and when.
- `tools/check_color.py REC`: how the colour module's calibration maps onto its images.
- `tools/show_set.py REC`: a recording's frame sets as images.
- `tools/watch_gestures.py [--distance]`: pinches and grips, live.
@@ -202,15 +214,59 @@ Python, with NumPy and OpenCV. `setup/dev-container.sh` doesn't install them, be
To try the hand cutouts without restarting the desktop, `screens/build/ft-handtest [--distance m] [--width m] [--seconds s]` (built by `screens/build.sh`, run in the dev container, with hand tracking on) shows a test panel of its own, a light grid 1 m wide and 0.8 m ahead by default, and cuts your hands out of it the way ft-screens cuts them out of the screens.
## Camera check
Hand tracking needs all four mono cameras and the headset's IR light. With the Arcturus colour module attached, SteamVR's XRService loads an FPGA image ("VCINT") onto the module every time it opens the cameras: when SteamVR starts and after every wake. When that load fails, XRService runs only the two side cameras, the frames come out darker and noisier, and ft-hands finds no hands at all. It happened on 2026-10-02 at 17:02, after the headset slept; the hand recorder then said "I can't see your hands" for a whole session.
`hands/camcheck.py` (system Python, standard library) tells whether the four cameras run: `ok`, `degraded: upper cameras and IR light off (VCINT FPGA failed to load)` (or another `degraded:` reason), or `unknown` (SteamVR not running, the cameras closed while the headset sleeps). It prints the log lines and other evidence it used; `--json` is for programs; the exit status is 0, 1 or 2. It reads:
- the running XRService's log (`~/.local/share/Steam/logs/xrservice.txt`): the last camera start (from the FPGA check to the next "Closing tracking camera interfaces"), its VCINT result, `Upper cameras FPGA interleaving support: N`, `Created N tasks (T tracking, P passthrough)` and the `TrackingCameraInit` lines. A wake that works prints no "Created N tasks", so an older one doesn't count;
- which `/dev/video*` XRService has open (`/proc/PID/fd`; video9 and video13 are the side pair, video6 and video7 the upper pair). Only on the host: the dev container can't read another process's open files, so there it's skipped;
- ft-camd's ring header, when it runs: how many mono cameras it publishes.
The hand recorder runs it before a session (DESIGN.md, "Camera check"). `hands/tests/test_camcheck.py` runs it on the 2026-10-02 log cut at several points, and on made-up logs.
### The watcher (off by default)
`hands/ft-camwatch` follows the XRService log (a stat every 2 s, reading only what's new). On a VCINT failure it posts a notification in the Frametop desktop, on the desktop's own D-Bus, found through its plasmashell as `decoration/apply.sh` does. With `CAMWATCH_AUTO_RESTART=1` in `~/.config/frametop.conf` it also restarts SteamVR, but only:
- while the headset isn't worn (frame-job's check: `vrcompositor` runs and a `/sys/class/backlight/*/brightness` is over 0), and after it has been off for `CAMWATCH_IDLE_S` (60);
- with no app Steam launched (`SteamLaunch AppId=N` in a process's arguments; `CAMWATCH_IGNORE_APPIDS` lists ids that don't count) and nobody on the remote desktop (an established connection to the VNC port, `VNC_PORT`, 5900);
- once per failure, and not again within `CAMWATCH_COOLDOWN_MIN` (30) of the last automatic restart. It remembers both in `~/.local/state/frametop/camwatch.json`, so its own restart doesn't reset them.
It logs every decision to the journal. `ft-camwatch --once` prints the state and what it would do, and does nothing; `--dry-run` keeps watching without acting. `hands/frametop-camwatch.service` is the unit (a template, `@REPO@` as in the others; nothing installs or enables it yet). It isn't `PartOf=steamvr.service`, so it outlives the restart it asks for. `CAMWATCH_NOTIFY=0` turns the notification off. `hands/tests/test_camwatch.py` tests its decisions with made-up inputs.
### What a SteamVR restart does to Frametop
Read from the code on the experimental branch, not tried live:
- ft-screens quits when SteamVR does: on `VREvent_Quit` it ends its Wayland display (`screens/vr.cpp`, `ft_vr_poll`; `screens/compositor.c`, `handle_vr_event`). It never connects to SteamVR again: `ft_vr_init` runs once, at its start.
- KWin runs nested in ft-screens, so the Frametop desktop ends with it, every window in it too (the hand recorder's as well). Its unit, `frametop-desktop`, is a transient `systemd-run` unit with `Restart=no`, so the desktop doesn't come back by itself: start it again (Desktop in the library, or `desktops.sh start`).
- When the unit stops, systemd ends what's left in it. `session/keep-apps.sh` moves programs started in the desktop out of the unit first, but only `desktops.sh stop` runs it; here they stop too. Programs in the dev container (ft-screens, the hand recorder) are in the container's cgroup and end when their Wayland connection goes.
- The units that are `PartOf=steamvr.service` restart with it: `frametop-camd`, `frametop-hands`, the pointer helper, gaze and power, and the hand recorder's own transient ft-camd and ft-hands units.
### Verified, and what's a guess
Verified, from the XRService logs of 2026-10-01 and 2026-10-02 and the running system:
- The failure's log lines and its effect: "Failed to load VCINT FPGA image when passthrough cameras are connected", interleaving support 0, "Created 4 tasks (2 tracking, 2 passthrough)", and only video9 and video13 opened. At 19:38-19:59 XRService held only those two of the four (plus video0 and video3), and ft-camd published two mono cameras.
- A wake's load can work and can fail. Both wakes in the logs started from an FPGA that answered nothing ("ERROR/UNKNOWN"): the one at 2026-10-01 16:39 loaded VCINT, the one at 2026-10-02 17:02 failed ("FPGA config_done signal did not assert").
- After a reboot the FPGA reads PASSTHRU and SteamVR's start loads VCINT (2026-10-01 21:53, 2026-10-02 13:39).
- A SteamVR restart within a boot found VCINT still loaded and loaded nothing (2026-10-01 15:27): XRService checks the FPGA when it starts and loads only when it must.
Guesses, not tested:
- **Whether a SteamVR restart fixes it.** After a failed load the FPGA doesn't answer, so a new XRService would run the same load a wake runs, which has worked once and failed once. It's never been tried after a failure. If it doesn't help, only a reboot is known to work (the FPGA comes up as PASSTHRU, and the load at SteamVR's start has worked both times).
- That the IR light is off because of the FPGA: the frames are darker and the illuminator ring isn't seen, and the FPGA loader lists a `room_led_en` pin, but nothing shows the light's state directly.
- That a sleep and wake (taking the headset off long enough) would retry the load too: it should, since every wake loads VCINT, but no failure has been followed by a wake yet.
- How the Frametop desktop behaves on a SteamVR restart (above): read from the code only.
- That Steam-launched apps carry `SteamLaunch AppId=N`: from Steam on other Linux systems; no VR game has run on the Frame to confirm it.
## Build
`hands/build.sh` builds in the dev container on the Frame, into `hands/build/`, with `hands/Makefile`. The first build fetches ncnn at a pinned tag (`NCNN_TAG` in the Makefile) and builds it into `hands/build/ncnn`, which takes a few minutes; `NCNN=DIR` points at an ncnn install already built instead. ft-camd is linked statically, because it runs on the host, which has an older glibc than the container.
## Known issues
- **The side cameras can come out swapped.** ft-camd tells the side cameras' buffers apart only by XRService's allocation order, and some XRService restarts reverse it. For now it's caught by hand: `tools/check_sides.py --ring`, then `HANDS_SWAP_SIDES=1`. It needs a fix in ft-camd, or at least an automatic check when it starts.
- **The side cameras can come out swapped.** ft-camd tells the side cameras' buffers apart only by XRService's allocation order, and some XRService restarts reverse it. ft-hands corrects it from the hands (`HANDS_SWAP_SIDES=auto`, the default). Until it has seen about 1-2 s of hands in both namings' reach, the cutouts may sit beside the hands. ft-camd itself still can't tell.
- **The colour cameras can't be used while the headset is worn.** The colour module then writes only a half-size image into the top-left quarter of its buffers, and ft-camd drops those frames. So the service runs the mono cameras only, and tracking in bright light, where the mono cameras see dark hands, doesn't get the colour pair's help.
- **The colour calibration mapping isn't settled.** Which colour camera is `passthrough_left` (`HANDS_COLOR_LEFT`) and how the module's crop applies (`HANDS_COLOR_CROP`) still need `tools/check_color.py` on a recording with a lit, textured view.
- **Depth when one camera loses the hand.** A hand seen in one camera drifts 10% per update toward the one-camera depth guess (`kMonoDepthGain`, 0.1, in `track/tracker.cpp`). In the 2026-09-30 replays that was worse than keeping the last distance (see "3D" above). A smaller gain, such as 0.02, is the next thing to try.
- **Pinches aren't reliable enough for everyday use yet.** That's why hand tracking stays off until `ft-handsctl on`, and `POINTER_HANDS` is 0 by default.
- **SteamVR can leave the upper cameras and the IR light off after a wake**, and then no hands are found. See "Camera check" above: `camcheck.py` tells, the hand recorder won't start a session, and the fix is a SteamVR restart or a reboot.
- **Floating windows don't get hand cutouts.** Their panels show crops of the client buffer, which the cutouts' side-by-side buffer doesn't match (`screens/vr.cpp`, `UpdateCutouts`).
+422
View File
@@ -0,0 +1,422 @@
#!/usr/bin/env python3
"""camcheck: are the headset's four mono tracking cameras running, so that ft-camd and
ft-hands see them all?
The Frame has four mono IR tracking cameras: the side pair slam_left and slam_right
(/dev/video9 and /dev/video13) and the upper pair (/dev/video6 and /dev/video7). With the
Arcturus colour module attached, SteamVR's XRService loads an FPGA image ("VCINT") onto the
module whenever it opens the cameras (at start and after every wake). When that load fails
(seen 2026-10-02 17:02, after a sleep), XRService runs only the two side cameras, the IR
illuminator seems to stay off, and ft-hands finds no hands at all.
What it looks at, cheapest first, all read-only:
1. The newest XRService log (~/.local/share/Steam/logs/xrservice.txt, a symlink to the
running instance's log): the last camera start, its VCINT result, "Upper cameras FPGA
interleaving support: N", "Created N tasks (T tracking, P passthrough)" and the
TrackingCameraInit lines. A wake doesn't always print "Created N tasks", so the parser
tracks each camera start ("episode") from the FPGA check to the next close.
2. Which /dev/video* XRService has open (/proc/PID/fd). Only on the host: the dev container
can't read another process's fd table (checked 2026-10-02), and then this is skipped.
3. A running ft-camd's ring header (/run/user/UID/frametop-hands/cam-ring): how many mono
cameras it publishes.
Status: "ok", "degraded: <why>" or "unknown" (SteamVR not running, the cameras closed while
the headset sleeps, no log). Exit status 0, 1, 2 for those.
python3 hands/camcheck.py # the status and its evidence
python3 hands/camcheck.py --json # for programs
python3 hands/camcheck.py --log FILE --no-proc --no-ring # a saved log only (tests)
System Python, standard library only; session.py and ft-camwatch import it.
"""
import argparse
import glob
import json
import os
import re
import struct
import sys
import time
LOG_DIR = os.path.expanduser("~/.local/share/Steam/logs")
LOG_LINK = os.path.join(LOG_DIR, "xrservice.txt")
SIDE_NODES = (9, 13) # slam_left, slam_right (TrackingCameraInit index 0 and 1)
UPPER_NODES = (6, 7) # the upper pair (index 2 and 3)
TRACKING = 4
VCINT_REASON = "upper cameras and IR light off (VCINT FPGA failed to load)"
DEGRADED_VCINT = "degraded: " + VCINT_REASON
# What the window and the recorder say when the check fails this way.
USER_TEXT = ("The headset's upper cameras and IR light are off. SteamVR couldn't start the colour camera "
"module (it happens sometimes after the headset sleeps). Restart SteamVR, or restart the headset "
"if that doesn't fix it.")
ANSI = re.compile(r"\x1b\[[0-9;]*m")
STAMP = re.compile(r"^\w{3} \w{3} \d{2} \d{4} (\d{2}:\d{2}:\d{2})\.\d+ (\w+): ?(.*)$")
# Lines worth reading; anything else is skipped before the regexes (the log grows by MBs a day).
KEYS = ("FPGA", "VCINT", "Created", "TrackingCameraInit", "Closing tracking camera", "Streaming",
"systemd suspend", "systemd resume", "XRService logging to", "Exiting XRService")
RE_PASSTHRU = re.compile(r"Passthrough connected but FPGA is (\S+) - loading VCINT")
RE_INTERLEAVE = re.compile(r"Upper cameras FPGA interleaving support: (\d)")
RE_TASKS = re.compile(r"Created (\d+) tasks \((\d+) tracking, (\d+) passthrough\)")
RE_INIT = re.compile(r"TrackingCameraInit: index: (\d+)\. video device: /dev/video(\d+)")
RE_STREAM = re.compile(r"Streaming resumed \(FPGA: (\S+), VC interleaving: (\w+)\)")
RE_STATE = re.compile(r"FPGA state check: (\S+)")
class LogState:
"""Reads an XRService log line by line (feed), so the watcher can follow it as it grows.
An episode is one opening of the cameras: from the first FPGA, task or camera-init line
after the log starts or after "Closing tracking camera interfaces", to the next close."""
def __init__(self, path=""):
self.path = path
self.instance = "" # the "XRService logging to" line's time
self.exited = False
self.closed = False # the cameras were closed and haven't opened again
self.closed_at = ""
self.episode = None
self.nodes = {} # TrackingCameraInit index -> /dev/videoN, from the whole log
self.failures = [] # [(time, line)]: every VCINT failure in this log
self.lines = 0
def _new_episode(self, t):
self.closed = False
self.episode = {"start": t, "fpga_before": "", "vcint": "", "interleave": None, "tasks": None,
"inits": {}, "stream": "", "failure": "", "evidence": []}
if self.closed_at:
self.episode["evidence"].append(self.closed_at)
def _ep(self, t):
if self.episode is None or self.closed:
self._new_episode(t)
return self.episode
def feed(self, raw):
self.lines += 1
if not any(k in raw for k in KEYS):
return
line = ANSI.sub("", raw).rstrip("\n")
m = STAMP.match(line)
if not m:
return # the FPGA loader's own output, without a time
t, _level, text = m.groups()
short = ("%s %s" % (t, text))[:220]
if "XRService logging to" in text:
lines = self.lines
self.__init__(self.path)
self.instance, self.lines = t, lines
return
if "Exiting XRService" in text:
self.exited = True
return
if "Closing tracking camera interfaces" in text:
self.closed, self.closed_at = True, short
return
if "systemd suspend notification" in text or "systemd resume notification" in text:
if "resume" in text:
self.closed_at = (self.closed_at + " / " if self.closed_at else "") + short
return
m = RE_PASSTHRU.search(text)
if m:
ep = self._ep(t)
ep["fpga_before"] = m.group(1)
ep["evidence"].append(short)
return
if "FPGA image VCINT loaded and verified successfully" in text:
ep = self._ep(t)
ep["vcint"] = "ok"
ep["evidence"].append(short)
return
if "Failed to load VCINT FPGA image" in text:
ep = self._ep(t)
ep["vcint"] = "failed"
ep["failure"] = t
ep["evidence"].append(short)
self.failures.append((t, short))
return
if "FPGA load failed" in text:
self._ep(t)["evidence"].append(short)
return
m = RE_INTERLEAVE.search(text)
if m:
ep = self._ep(t)
ep["interleave"] = int(m.group(1))
ep["evidence"].append(short)
return
m = RE_TASKS.search(text)
if m:
ep = self._ep(t)
ep["tasks"] = tuple(int(v) for v in m.groups())
ep["evidence"].append(short)
return
m = RE_INIT.search(text)
if m:
ep = self._ep(t)
idx, node = int(m.group(1)), int(m.group(2))
ep["inits"][idx] = node
self.nodes[idx] = node
ep["evidence"].append(short)
return
m = RE_STREAM.search(text)
if m:
ep = self._ep(t)
ep["stream"] = "%s, interleaving %s" % m.groups()
ep["evidence"].append(short)
return
m = RE_STATE.search(text)
if m:
ep = self._ep(t)
if not ep["fpga_before"] and not ep["vcint"]:
ep["fpga_before"] = m.group(1)
if m.group(1) == "VCINT":
ep["vcint"] = "loaded" # already there: no load needed (a SteamVR restart in the same boot)
ep["evidence"].append(short)
def feed_text(self, text):
for line in text.splitlines():
self.feed(line)
return self
def upper_nodes(self):
got = tuple(self.nodes[i] for i in (2, 3) if i in self.nodes)
return got if len(got) == 2 else UPPER_NODES
def tracking_nodes(self):
got = tuple(self.nodes[i] for i in range(TRACKING) if i in self.nodes)
return got if len(got) == TRACKING else SIDE_NODES + UPPER_NODES
def verdict(self):
"""(status, reason, evidence): status "ok", "degraded" or "unknown"."""
if self.lines == 0:
return "unknown", "the XRService log is empty", []
if self.exited:
return "unknown", "XRService has exited (SteamVR isn't running)", []
if self.episode is None:
return "unknown", "the cameras haven't started yet in this log", []
ep = self.episode
ev = ep["evidence"][-14:]
if self.closed:
return "unknown", "the cameras are closed (the headset is asleep, or SteamVR is stopping)", \
ev + [self.closed_at]
tracking = len(ep["inits"]) if ep["inits"] else (ep["tasks"][1] if ep["tasks"] else None)
if ep["vcint"] == "failed":
return "degraded", VCINT_REASON, ev
if tracking is not None and tracking < TRACKING:
why = "only %d of %d tracking cameras running" % (tracking, TRACKING)
if ep["interleave"] == 0:
why += " (upper cameras' FPGA interleaving off)"
return "degraded", why, ev
if tracking == TRACKING:
return "ok", "%d tracking cameras running" % TRACKING, ev
return "unknown", "the cameras are starting", ev
def snapshot(self):
status, reason, ev = self.verdict()
ep = self.episode or {}
return {"status": status, "reason": reason, "evidence": ev, "log": self.path, "instance": self.instance,
"episode": {k: (list(v) if isinstance(v, tuple) else v) for k, v in ep.items() if k != "evidence"},
"failure": "%s@%s" % (self.path, ep["failure"]) if ep.get("vcint") == "failed" else ""}
# ------------------------------------------------------------------------------------------
# Processes
def proc_argv(pid):
try:
with open("/proc/%s/cmdline" % pid, "rb") as f:
return [a.decode(errors="replace") for a in f.read().split(b"\0") if a]
except OSError:
return []
def xrservice_pid():
"""XRService's pid (its main thread renames itself XRServiceLoopTh), or None."""
for pid in os.listdir("/proc"):
if not pid.isdigit():
continue
try:
with open("/proc/%s/comm" % pid) as f:
if not f.read().startswith("XRService"):
continue
except OSError:
continue
argv = proc_argv(pid)
if argv and os.path.basename(argv[0]) == "XRService":
return int(pid)
return None
def xrservice_fds(pid):
"""{"videos": [N, ...], "log": path or ""} from /proc/PID/fd, or None if it can't be read
(the dev container can't)."""
try:
fds = os.listdir("/proc/%d/fd" % pid)
except OSError:
return None
videos, log = set(), ""
for fd in fds:
try:
target = os.readlink("/proc/%d/fd/%s" % (pid, fd))
except OSError:
continue
m = re.match(r"/dev/video(\d+)$", target)
if m:
videos.add(int(m.group(1)))
elif re.search(r"/XRService-[^/]*\.log$", target):
log = target
if not videos and not log:
return None # nothing readable: as good as no access
return {"videos": sorted(videos), "log": log}
def newest_log():
"""The running XRService's log: the xrservice.txt symlink, else the newest by time."""
if os.path.exists(LOG_LINK):
return os.path.realpath(LOG_LINK)
found = glob.glob(os.path.join(LOG_DIR, "XRService-*", "XRService-*.log"))
found += glob.glob(os.path.join(LOG_DIR, "XRService-*.log"))
found = [p for p in found if os.path.isfile(p)]
return max(found, key=os.path.getmtime) if found else ""
def read_log(path):
st = LogState(path)
with open(path, "r", errors="replace") as f:
for line in f:
st.feed(line)
return st
# ------------------------------------------------------------------------------------------
# ft-camd's ring (camd/fhring.h; the header only, as session.py's Ring reads it)
RING_HDR = struct.Struct("<8sIIIIQqQ16x")
RING_CAM = struct.Struct("<32s32siIIIIIQQQQQIf24x")
FH_CAM_DARK, FH_CAM_COLOR = 1, 2
def default_ring():
return "/run/user/%d/frametop-hands/cam-ring" % os.getuid()
def read_ring(path):
"""{"alive", "writer_pid", "mono": [{"name", "sensor", "node"}]} or None (no ring)."""
try:
with open(path, "rb") as f:
data = f.read(RING_HDR.size + 8 * RING_CAM.size)
except OSError:
return None
if len(data) < RING_HDR.size:
return None
magic, version, _, ncams, _, _, writer, _ = RING_HDR.unpack_from(data, 0)
if magic != b"FHRING01" or version != 1:
return None
hb = struct.unpack_from("<Q", data, 40)[0]
alive = hb != 0 and (time.clock_gettime_ns(time.CLOCK_MONOTONIC) - hb) / 1e9 < 2.0
mono = []
for i in range(min(ncams, 8)):
off = RING_HDR.size + i * RING_CAM.size
if off + RING_CAM.size > len(data):
break
f = RING_CAM.unpack_from(data, off)
sensor = f[0].split(b"\0", 1)[0].decode(errors="replace")
name = f[1].split(b"\0", 1)[0].decode(errors="replace")
if f[13] & (FH_CAM_DARK | FH_CAM_COLOR) or name.endswith("_dk") or name.startswith("color"):
continue
mono.append({"name": name, "sensor": sensor, "node": f[2]})
return {"alive": alive, "writer_pid": writer, "mono": mono}
# ------------------------------------------------------------------------------------------
# The check
def check(log=None, proc=True, ring=True, ring_path=None):
"""The cameras' state: {"status": "ok"|"degraded"|"unknown", "summary": "ok" or
"degraded: ..." or "unknown: ...", "reason", "evidence": [lines], "log", "xrservice", "ring"}."""
evidence = []
pid = xrservice_pid() if proc else None
fds = xrservice_fds(pid) if pid else None
path = log or (fds or {}).get("log") or newest_log()
state = None
if path:
try:
state = read_log(path)
except OSError as e:
evidence.append("log %s: %s" % (path, e))
if state:
status, reason, ev = state.verdict()
evidence += ["log %s:" % path] + [" " + e for e in ev]
else:
status, reason = "unknown", "no XRService log in %s" % LOG_DIR
out = {"log": path, "xrservice": None, "ring": None,
"episode": state.snapshot()["episode"] if state else {},
"failure": state.snapshot()["failure"] if state else ""}
if proc:
if pid is None:
# The log can't tell a killed XRService from a running one; no process settles it.
evidence.append("XRService isn't running")
status, reason = "unknown", "SteamVR isn't running (no XRService)"
elif fds is None:
evidence.append("XRService pid %d: its open files can't be read here (in the dev container?)" % pid)
out["xrservice"] = {"pid": pid, "videos": None}
else:
videos = fds["videos"]
want = state.tracking_nodes() if state else SIDE_NODES + UPPER_NODES
upper = state.upper_nodes() if state else UPPER_NODES
have = [n for n in want if n in videos]
evidence.append("XRService pid %d has open: %s (tracking cameras: %s; upper: %s)" % (
pid, " ".join("video%d" % n for n in videos) or "no cameras",
" ".join("video%d" % n for n in want), " ".join("video%d" % n for n in upper)))
out["xrservice"] = {"pid": pid, "videos": videos, "tracking_open": len(have)}
closed = state is not None and state.closed
if not closed and len(have) == TRACKING and status == "unknown":
status, reason = "ok", "XRService has all %d tracking cameras open" % TRACKING
elif not closed and videos and not all(n in videos for n in upper) and status != "degraded":
status, reason = "degraded", ("XRService has %d of %d tracking cameras open (the upper pair "
"is missing)" % (len(have), TRACKING))
if ring:
r = read_ring(ring_path or default_ring())
out["ring"] = r
if r is None:
evidence.append("ft-camd: no camera ring (not running)")
else:
names = " ".join(c["name"] for c in r["mono"]) or "none"
evidence.append("ft-camd (pid %d, %s): %d mono cameras: %s" % (
r["writer_pid"], "running" if r["alive"] else "stale ring", len(r["mono"]), names))
if r["alive"] and len(r["mono"]) < TRACKING and status == "ok":
status, reason = "degraded", ("ft-camd publishes only %d of %d mono cameras (it started while "
"they were missing: restart it)" % (len(r["mono"]), TRACKING))
out.update(status=status, reason=reason, evidence=evidence,
summary="ok" if status == "ok" else "%s: %s" % (status, reason))
return out
def is_vcint_failure(result):
return bool(result) and result.get("status") == "degraded" and result.get("reason") == VCINT_REASON
def main(argv=None):
ap = argparse.ArgumentParser(description="Are the headset's four mono tracking cameras running?")
ap.add_argument("--json", action="store_true", help="print the result as JSON")
ap.add_argument("--log", help="read this XRService log (default: the running instance's)")
ap.add_argument("--no-proc", action="store_true", help="don't look at XRService's process")
ap.add_argument("--no-ring", action="store_true", help="don't look at ft-camd's ring")
ap.add_argument("--ring", help="ft-camd's ring (default /run/user/UID/frametop-hands/cam-ring)")
a = ap.parse_args(argv)
r = check(log=a.log, proc=not a.no_proc, ring=not a.no_ring, ring_path=a.ring)
if a.json:
print(json.dumps(r, indent=1))
else:
print(r["summary"])
for line in r["evidence"]:
print(" " + line)
return {"ok": 0, "degraded": 1}.get(r["status"], 2)
if __name__ == "__main__":
sys.exit(main())
+21
View File
@@ -0,0 +1,21 @@
# Template: the installer replaces @REPO@ with the repo path on the Frame. Not installed or
# enabled by anything yet (hands/README.md, "Camera check").
[Unit]
Description=Frametop camera watch: tells you when SteamVR leaves the headset's upper cameras off
Documentation=file://@REPO@/hands/README.md
# Not PartOf=steamvr.service: it has to outlive the SteamVR restart it may ask for.
[Service]
# On the host, system Python, standard library only. It stats the XRService log every 2 s and
# reads only what's new. Notifications go to the Frametop desktop's own D-Bus (found through its
# plasmashell). With CAMWATCH_AUTO_RESTART=1 in ~/.config/frametop.conf it may restart SteamVR
# while the headset isn't worn: that also closes the Frametop desktop.
ExecStart=/usr/bin/python3 @REPO@/hands/ft-camwatch
Restart=on-failure
RestartSec=30
Nice=10
CPUQuota=5%
MemoryMax=64M
[Install]
WantedBy=default.target
+378
View File
@@ -0,0 +1,378 @@
#!/usr/bin/env python3
"""ft-camwatch: watches SteamVR's XRService log for the camera failure that turns off the
headset's upper cameras and IR light (a VCINT FPGA load that fails, usually after a wake;
hands/camcheck.py), tells the Frametop desktop, and can restart SteamVR by itself.
Off by default: hands/frametop-camwatch.service is a template the installer doesn't enable.
Settings in ~/.config/frametop.conf:
CAMWATCH_AUTO_RESTART=1 restart SteamVR on a failure (default 0: only a notification). Only
while the headset isn't worn (frame-job's check: vrcompositor runs and
a backlight is on), after it has been off for CAMWATCH_IDLE_S, with no
Steam-launched app running and nobody on the remote desktop (VNC).
At most once per failure, and not again within CAMWATCH_COOLDOWN_MIN.
CAMWATCH_IDLE_S=60 how long the headset must be off first
CAMWATCH_COOLDOWN_MIN=30 the least time between two automatic restarts
CAMWATCH_IGNORE_APPIDS= Steam app ids that don't count as a running VR app (comma-separated)
CAMWATCH_NOTIFY=1 post a notification in the Frametop desktop (0: log only)
A SteamVR restart also closes the Frametop desktop and every window in it (ft-screens quits
with SteamVR, and the desktop's unit doesn't restart: see hands/README.md, "Camera check").
It follows the log with a stat every 2 s (no inotify, nothing else while all is well), and
logs every decision to stdout (the journal). --dry-run never notifies or restarts; --once
prints the state and what it would do now, and exits.
"""
import argparse
import json
import os
import subprocess
import sys
import time
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import camcheck # noqa: E402
CONF = os.path.expanduser("~/.config/frametop.conf")
STATE = os.path.expanduser("~/.local/state/frametop/camwatch.json")
BACKLIGHTS = "/sys/class/backlight"
POLL_S = 2.0
MAX_READ = 16 << 20 # a poll reads at most this much of a log that grew
NOTIFY_TITLE = "Hand tracking: cameras off"
NOTIFY_TEXT = ("The headset's upper cameras and IR light are off: SteamVR couldn't start the colour camera "
"module (it happens sometimes after the headset sleeps). Restart SteamVR, or the headset if "
"that doesn't fix it. Restarting SteamVR closes this desktop and its windows.")
DEFAULTS = {"CAMWATCH_AUTO_RESTART": "0", "CAMWATCH_IDLE_S": "60", "CAMWATCH_COOLDOWN_MIN": "30",
"CAMWATCH_IGNORE_APPIDS": "", "CAMWATCH_NOTIFY": "1", "VNC_PORT": "5900"}
def log(text):
print("%s %s" % (time.strftime("%H:%M:%S"), text), flush=True)
def read_conf(path=CONF):
"""KEY=VALUE lines of a shell-style file (comments and quotes stripped), over DEFAULTS."""
conf = dict(DEFAULTS)
try:
with open(path) as f:
for line in f:
line = line.split("#", 1)[0].strip()
if "=" not in line:
continue
k, v = line.split("=", 1)
k, v = k.strip(), v.strip().strip("'\"")
if k.replace("_", "").isalnum():
conf[k] = v
except OSError:
pass
return conf
def conf_int(conf, key):
try:
return int(float(conf.get(key, DEFAULTS.get(key, "0"))))
except ValueError:
return int(DEFAULTS.get(key, "0") or 0)
# ------------------------------------------------------------------------------------------
# What's going on around (all read-only, from /proc and /sys)
def process_running(name):
for pid in os.listdir("/proc"):
if pid.isdigit():
try:
with open("/proc/%s/comm" % pid) as f:
if f.read().strip() == name:
return True
except OSError:
pass
return False
def headset_worn(backlights=BACKLIGHTS):
"""frame-job's check: vrcompositor runs and any panel's backlight is on (SteamVR turns the
panels off 5 s after the headset comes off)."""
lit = False
try:
for name in os.listdir(backlights):
try:
with open(os.path.join(backlights, name, "brightness")) as f:
lit = lit or int(f.read().strip()) > 0
except (OSError, ValueError):
pass
except OSError:
return False
return lit and process_running("vrcompositor")
def vr_apps(ignore=()):
"""Apps Steam launched ("SteamLaunch AppId=N" in a process's arguments, as Steam's reaper
runs them): ["AppId=N ..."]. Steam's own processes, SteamVR's and Frametop's services aren't
launched this way. A guess: no VR game has been run on the Frame to confirm the form."""
out = set()
for pid in os.listdir("/proc"):
if not pid.isdigit():
continue
argv = camcheck.proc_argv(pid)
if "SteamLaunch" not in argv:
continue
ids = [a.split("=", 1)[1] for a in argv if a.startswith("AppId=")]
if ids and ids[0] not in ignore:
out.add("AppId=" + ids[0])
return sorted(out)
def remote_viewers(port=5900, tables=("/proc/net/tcp", "/proc/net/tcp6")):
"""Established connections to the remote desktop's VNC port, from /proc/net/tcp(6)."""
out = []
for path in tables:
try:
with open(path) as f:
next(f)
for line in f:
p = line.split()
if len(p) > 3 and p[3] == "01" and int(p[1].rsplit(":", 1)[1], 16) == port:
out.append(p[2])
except (OSError, StopIteration, ValueError):
pass
return out
def frametop_bus():
"""The Frametop desktop's D-Bus (from its plasmashell, as decoration/apply.sh finds it), or None."""
for pid in os.listdir("/proc"):
if not pid.isdigit():
continue
try:
with open("/proc/%s/comm" % pid) as f:
if f.read().strip() != "plasmashell":
continue
with open("/proc/%s/environ" % pid, "rb") as f:
env = dict(kv.split(b"=", 1) for kv in f.read().split(b"\0") if b"=" in kv)
except OSError:
continue
if env.get(b"XDG_RUNTIME_DIR", b"").endswith(b"/frametop") and b"DBUS_SESSION_BUS_ADDRESS" in env:
return env[b"DBUS_SESSION_BUS_ADDRESS"].decode()
return None
def notify(title, text):
bus = frametop_bus()
if not bus:
log("no Frametop desktop running: no notification")
return False
r = subprocess.run(["notify-send", "-a", "Frametop", "-u", "critical", "-i", "dialog-warning", title, text],
env=dict(os.environ, DBUS_SESSION_BUS_ADDRESS=bus), capture_output=True, text=True,
timeout=10)
if r.returncode:
log("notify-send failed (%d): %s" % (r.returncode, r.stderr.strip()))
return r.returncode == 0
def restart_steamvr():
# --no-block: the job runs in systemd; the Frametop desktop closing doesn't cut it short.
r = subprocess.run(["systemctl", "--user", "restart", "--no-block", "steamvr.service"],
capture_output=True, text=True, timeout=30)
log("systemctl --user restart steamvr.service: exit %d %s" % (r.returncode, (r.stderr or "").strip()))
return r.returncode == 0
def environment(conf):
ignore = tuple(a.strip() for a in conf.get("CAMWATCH_IGNORE_APPIDS", "").replace(",", " ").split() if a.strip())
return {"steamvr": camcheck.xrservice_pid() is not None, "worn": headset_worn(),
"vr_apps": vr_apps(ignore), "remote": remote_viewers(conf_int(conf, "VNC_PORT"))}
# ------------------------------------------------------------------------------------------
# The decision (pure: tests feed it made-up states)
def new_memory():
return {"pending": "", "notified": [], "restarted": {}, "last_restart": 0.0, "idle_since": None, "why": ""}
def decide(now, failure, env, mem, conf):
"""What to do now. failure: the current VCINT failure's id ("" if none: the cameras run,
or they're closed); env: {"steamvr", "worn", "vr_apps", "remote"} (only looked at while a
failure is current); mem: new_memory(), updated in place; now: wall-clock seconds.
Returns [("log", text) | ("notify", failure) | ("restart", failure)]."""
acts = []
if not failure:
if mem["pending"]:
acts.append(("log", "failure %s is no longer current" % mem["pending"]))
mem.update(pending="", idle_since=None, why="")
return acts
if mem["pending"] != failure:
mem.update(pending=failure, why="")
acts.append(("log", "VCINT failure: %s (upper cameras and IR light off)" % failure))
if failure not in mem["notified"]:
mem["notified"] = (mem["notified"] + [failure])[-20:]
if conf.get("CAMWATCH_NOTIFY", "1") != "0":
acts.append(("notify", failure))
if env.get("worn"):
mem["idle_since"] = None
elif mem["idle_since"] is None:
mem["idle_since"] = now
idle_s = conf_int(conf, "CAMWATCH_IDLE_S")
cooldown = conf_int(conf, "CAMWATCH_COOLDOWN_MIN") * 60
if conf.get("CAMWATCH_AUTO_RESTART", "0") != "1":
why = "no automatic restart (CAMWATCH_AUTO_RESTART=1 in ~/.config/frametop.conf turns it on)"
elif failure in mem["restarted"]:
why = "SteamVR was restarted once for this failure already: restart the headset"
elif mem["last_restart"] and now - mem["last_restart"] < cooldown:
why = "no restart: the last automatic one was %d min ago (cooldown %d min)" % (
(now - mem["last_restart"]) // 60, cooldown // 60)
elif not env.get("steamvr"):
why = "no restart: SteamVR isn't running"
elif env.get("worn"):
why = "no restart while the headset is worn"
elif env.get("vr_apps"):
why = "no restart: a VR app is running (%s)" % ", ".join(env["vr_apps"])
elif env.get("remote"):
why = "no restart: someone is on the remote desktop (%s)" % ", ".join(env["remote"])
elif now - mem["idle_since"] < idle_s:
why = "waiting for the headset to stay off for %d s" % idle_s
else:
mem["restarted"][failure] = now
mem["last_restart"] = now
why = "restarting SteamVR (the headset is off, nothing else in VR)"
acts.append(("log", why))
acts.append(("restart", failure))
mem["why"] = why
return acts
if why != mem["why"]:
mem["why"] = why
acts.append(("log", why))
return acts
def load_memory(path=STATE):
mem = new_memory()
try:
with open(path) as f:
saved = json.load(f)
mem["notified"] = list(saved.get("notified", []))[-20:]
mem["restarted"] = dict(saved.get("restarted", {}))
mem["last_restart"] = float(saved.get("last_restart", 0.0))
except (OSError, ValueError, TypeError, AttributeError):
pass
return mem
def save_memory(mem, path=STATE):
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = path + ".tmp"
with open(tmp, "w") as f:
json.dump({"notified": mem["notified"], "restarted": mem["restarted"],
"last_restart": mem["last_restart"]}, f)
os.replace(tmp, path)
# ------------------------------------------------------------------------------------------
# Following the log
class Follower:
"""The running XRService's log, read as it grows. A new log (SteamVR restarted) starts afresh."""
def __init__(self, path=None):
self.fixed = path
self.path, self.ino, self.offset, self.rest = "", None, 0, ""
self.state = None
def poll(self):
path = self.fixed or camcheck.newest_log()
if not path:
return None
try:
st = os.stat(path)
except OSError:
return self.state
if path != self.path or st.st_ino != self.ino or st.st_size < self.offset:
self.path, self.ino, self.offset, self.rest = path, st.st_ino, 0, ""
self.state = camcheck.LogState(path)
log("following %s" % path)
if st.st_size > self.offset:
with open(path, "rb") as f:
f.seek(self.offset)
data = f.read(MAX_READ)
self.offset += len(data)
text = self.rest + data.decode(errors="replace")
lines = text.split("\n")
self.rest = lines.pop()
for line in lines:
self.state.feed(line)
return self.state
def current_failure(state, steamvr_running=True):
"""The failure id if the log's current camera start is a VCINT failure, else ""."""
if state is None or not steamvr_running:
return ""
snap = state.snapshot()
return snap["failure"] if snap["status"] == "degraded" and snap["reason"] == camcheck.VCINT_REASON else ""
def act(acts, dry):
changed = False
for kind, arg in acts:
if kind == "log":
log(arg)
elif kind == "notify":
changed = True
if dry:
log("(dry run) would notify: %s" % NOTIFY_TITLE)
else:
notify(NOTIFY_TITLE, NOTIFY_TEXT)
elif kind == "restart":
changed = True
if dry:
log("(dry run) would restart SteamVR")
else:
restart_steamvr()
return changed
def main(argv=None):
ap = argparse.ArgumentParser(description="Watch for the camera failure that turns off the upper cameras.")
ap.add_argument("--dry-run", action="store_true", help="log what it would do; never notify or restart")
ap.add_argument("--once", action="store_true", help="look once, print the decision (a dry run), and exit")
ap.add_argument("--log", help="follow this file instead of the running XRService's log (tests)")
ap.add_argument("--state", default=STATE, help="where it remembers past failures (default %(default)s)")
a = ap.parse_args(argv)
dry = a.dry_run or a.once
mem = load_memory(a.state)
follower = Follower(a.log)
conf = read_conf()
conf_mtime = 0.0
log("watching; automatic restart %s" % ("on" if conf.get("CAMWATCH_AUTO_RESTART") == "1" else "off"))
while True:
try:
m = os.stat(CONF).st_mtime
except OSError:
m = 0.0
if m != conf_mtime:
conf, conf_mtime = read_conf(), m
state = follower.poll()
failure = current_failure(state)
env = {}
if failure or mem["pending"]:
env = environment(conf)
if not env["steamvr"] and not a.log:
failure = "" # the log's last word, but XRService is gone
acts = decide(time.time(), failure, env, mem, conf)
if a.once:
snap = state.snapshot() if state else {"status": "unknown", "reason": "no log"}
print("log: %s\nstate: %s %s\nenvironment: %s" % (follower.path, snap["status"], snap["reason"],
json.dumps(env)))
act(acts, True)
return 0
if act(acts, dry) and not dry:
save_memory(mem, a.state)
time.sleep(POLL_S)
if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
sys.exit(0)
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env bash
# ft-cutouts: the hand cutouts without pinches and grips. Your hands show through Frametop's
# screens, but ft-hands runs with --no-gestures, so nothing clicks or drags. ft-handsctl on is
# the full version; each stops the other. Like it, this doesn't start with SteamVR, and it
# stops when SteamVR does. On the Frame.
#
# ft-cutouts on | off | status
#
# Runs this checkout's hands/build as transient user units, so it doesn't need hands/run.sh
# install: only a build (hands/build.sh) and ft-camd's capabilities (hands/run.sh caps).
set -euo pipefail
here=$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)
camd=frametop-cutouts-camd.service hands=frametop-cutouts-hands.service
die() { echo "$*" >&2; exit 1; }
run_unit() { # unit, the ft-handsctl unit it replaces, description, then the command
local unit=$1 conflicts=$2 what=$3
shift 3
systemctl --user -q is-active "$unit" && return
systemd-run --user --quiet --collect --unit="$unit" --description="Frametop hand cutouts: $what" \
-p PartOf=steamvr.service -p After=steamvr.service -p Conflicts="$conflicts" \
-p Restart=always -p RestartSec=5 -p TimeoutStopSec=5 "$@"
}
case ${1:-status} in
on)
systemctl --user -q is-active steamvr.service || die "SteamVR isn't running"
[ -x "$here/build/ft-camd" ] && [ -x "$here/build/ft-hands" ] || die "not built: hands/build.sh"
grep -qa -- --no-gestures "$here/build/ft-hands" || die "ft-hands predates --no-gestures: hands/build.sh"
getcap "$here/build/ft-camd" | grep -q cap_sys_ptrace ||
die "ft-camd needs its capabilities: hands/run.sh caps (asks for sudo)"
if systemctl --user -q is-active frametop-camd.service frametop-hands.service; then
echo "stopping ft-handsctl's hand tracking (it has pinches and grips)"
fi
run_unit $camd frametop-camd.service "the camera broker" "$here/build/ft-camd" --status 60
if ! systemctl --user -q is-active $hands; then
"$here/../scripts/container-up.sh" # so stopping the unit can't take the container down
pkill -x ft-hands || true
fi
run_unit $hands frametop-hands.service "hand tracking, no gestures" "$HOME/.local/bin/distrobox" enter dev -- \
"$here/build/ft-hands" --status 60 --no-gestures
"$here/ft-handsctl" cutouts on >/dev/null || true
sleep 4
"$0" status ;;
off)
systemctl --user stop $hands $camd 2>/dev/null || true
systemctl --user -q is-active frametop-hands.service || pkill -x ft-hands || true
echo "hand cutouts off" ;;
status)
for u in $camd $hands; do echo "$u: $(systemctl --user is-active $u || true)"; done
echo "ft-screens cutouts: $("$here/ft-handsctl" cutouts state 2>&1)"
inv=$(systemctl --user show -p InvocationID --value $hands) # this run's lines only
[ -n "$inv" ] && journalctl --user _SYSTEMD_INVOCATION_ID="$inv" --no-pager -o cat |
grep -E '^ *[0-9.]+s |sets with a hand|cameras:' | tail -2 | cut -c1-160 || true ;;
*) sed -n '2,10p' "$0" | sed 's/^# \{0,1\}//'; exit 2 ;;
esac
+97
View File
@@ -0,0 +1,97 @@
# Recording your hands for the Frametop hand dataset
Version: 2026-10-03
Frametop's hand tracking needs a small model that finds hands in the headset's camera images. To train it, we're collecting recordings of many people's hands into a public dataset. This page explains what the hand recorder records, where it goes, and what you agree to if you take part. Please read all of it.
## Who runs this
Frametop is an independent open-source project, maintained by DeeJanuz (<https://github.com/DeeJanuz>). It isn't affiliated with or endorsed by Valve or Hugging Face. Steam and Steam Frame are trademarks of Valve Corporation. This text was written without a lawyer, in good faith; if something in it seems wrong or unclear, please say so before you take part.
You can reach the maintainer through the Frametop repository's issues (<https://github.com/DeeJanuz/frametop/issues>) or the dataset's discussion page on Hugging Face. Both are public.
## Who can take part
- You must be **18 or older**.
- For now, you can't take part if you live in **Illinois, Texas or Washington** (USA). Those states have laws about biometric data (such as hand geometry) that need more than this project can provide yet.
- Take part only if you're comfortable with images of your hands and the room in front of you being public.
## What is recorded
While a session runs, the hand recorder saves:
- **Camera images.** Infrared images from the headset's 4 tracking cameras, about 10 sets a second. They show your hands, your arms, your clothing and whatever is in front of you: your room, your desk and the things on it. They're grey, low-detail images, but people and things can be recognised in them. The size and shape of your hands can be measured from them: that's part of what they're for.
- **Motion.** The position and rotation of the headset, many times a second, and of the controllers when you use them in the recording.
- **Prompts.** What you were asked to do and when, and what the live hand tracker saw at the time.
- **Calibration.** Where the cameras sit on the headset and how their lenses bend the image. Serial numbers and other fields that identify your headset are removed first, and the export lists what was removed.
- **Your answers.** Which objects you had, the lighting, whether you wore sleeves, rings or a watch, your handedness if you gave it, and any notes you typed in the checklist or in Review. Notes are uploaded with the recordings and read by the maintainer: don't put anything in them that identifies you.
- **Times.** When each session was recorded, with your time zone.
- **A contributor id.** A random number made on your headset the first time you agree to this page. It isn't made from your name, your Steam account or your headset. It keeps your sessions together and lets you withdraw them.
The recorder doesn't record sound, your name, your email address or your Steam account. The tracking cameras look outward, so your eyes and face aren't recorded, unless a mirror or something shiny shows them: avoid those.
**Your Hugging Face account.** You upload with your own Hugging Face account, and your pull request shows its username next to your contributor id, publicly. So anyone can see which Hugging Face account contributed which recordings. Use an account you're happy to have linked to them.
## What it's used for
- Training and testing hand-tracking models: finding hands, their keypoints, their shape and how far away they are. Mainly for Frametop's hand cutouts, and by anyone else for non-commercial work under the dataset's license.
- It isn't used to recognise or identify people, and the dataset's terms forbid anyone from trying.
## Nothing leaves your headset unless you send it
- Recordings stay on your headset, in `~/.local/share/frametop/hands/contrib`. Nothing is uploaded automatically.
- Before you share anything, you can watch every recording in the Review page. You can delete any stretch of a recording, a whole take or a whole session. Export leaves out what you deleted.
- You upload the export yourself, from the Upload page. That opens a pull request on the dataset. The maintainer checks it before it becomes part of the dataset, and may decline it. Until it's merged, you can close the pull request yourself.
## Where it goes
- **The dataset is public.** It's hosted on Hugging Face (<https://huggingface.co/datasets/DeeJanuz/frametop-hands>), whose servers may be outside your country, for example in the USA. Anyone who accepts the dataset's terms can download it.
- People who download it agree not to try to identify anyone or anything in it, and to delete recordings that are later withdrawn. We can't enforce that against everyone: assume copies may exist.
- Recordings stay in the dataset until they're withdrawn or the dataset is taken down.
## Keep other people and private things out of view
While recording, please:
- face away from other people, mirrors, screens showing private things, papers, letters, photos and anything else you wouldn't want public;
- make sure nobody else's face or hands are in view, and record only where the people you share the space with are fine with it;
- don't record children.
If something private got into a recording, delete that stretch in Review before you export. If you notice it after uploading, withdraw the session (below).
## Safety
The sessions ask you to move your hands and arms around you, out to full reach. Sit where you normally use the headset, clear an arm's reach around you, and stop whenever anything is uncomfortable. You take part at your own risk.
## The license
- **The dataset is published under Creative Commons Attribution-NonCommercial 4.0 (CC BY-NC 4.0).** Anyone may use it for non-commercial purposes, with attribution. Your contribution is credited by its contributor id, not your name.
- **You also give the maintainer of Frametop a non-exclusive, worldwide, royalty-free license to use your contribution for any purpose, including commercially.** That includes copying it, changing it, and training, publishing and selling models made from it, in Frametop and elsewhere. The maintainer today is DeeJanuz. If someone else, or an organization, takes over maintaining Frametop, this license passes to them. It's non-exclusive: you keep any rights you have in your recordings and can do what you like with your own copies. It ends for a recording when you withdraw it, except for models already trained with it.
- You confirm that you have the right to give these licenses: the recordings are yours, and nothing in them belongs to someone who hasn't agreed.
- There is no payment. The dataset and the hand recorder come with no warranty, and as far as the law allows, the maintainer isn't liable for any loss or damage from taking part.
## Withdrawing
You can withdraw a contribution at any time, without giving a reason:
- **Before it's merged:** close your pull request on Hugging Face. The maintainer deletes its files.
- **After it's merged:** post on the dataset's discussion page, or in the Frametop repository's issues, with your contributor id (shown in the hand recorder) and which sessions, or "all". Post from the Hugging Face account that uploaded them if you can, so the maintainer can tell it's you; otherwise, say how to check. These requests are public, so don't add anything else that identifies you.
Then, usually within 30 days:
- your recordings are deleted from the dataset and purged from its repository's history, so they can't be downloaded from there again;
- they're left out of anything trained after that.
What can't be undone: copies others downloaded before the withdrawal, and models already trained with them.
## Your rights
Depending on where you live (for example in the EU or the UK, under the GDPR), the law may give you more rights over this data: to get a copy of it, to have it corrected or deleted, to object to its use, and to complain to your data protection authority. The data is used because you agreed to it, and you can withdraw that agreement at any time, as above. Withdrawing doesn't make earlier use unlawful. To use any of these rights, contact the maintainer as above.
## Changes to this text
If this text changes, the hand recorder shows the new version and asks you again before your next session. Each upload records the version you agreed to, and recordings you already uploaded stay under that version, unless you agree to a newer one or withdraw them.
## Agreeing
By ticking the three boxes and "Agree and continue", you confirm that you're 18 or older, that you don't live in Illinois, Texas or Washington, and that you agree to the above. You can still decide not to upload anything.
+366
View File
@@ -0,0 +1,366 @@
# Hand recorder: design (Phase 1 of the hands plan)
The hand recorder guides a person through recording their hands with the headset's cameras. It saves the recordings as files, lets them review and delete anything, then exports a package to contribute to the open hand dataset. Recordings never leave the headset unless the person uploads them.
The plan this belongs to is `~/Desktop/Projects/frame-hands/notes/hands-plan.md` (on the maintainer's Frame). In short, the dataset trains a small hand model for Frametop's hand cutouts.
## Parts
| Part | What it does |
|---|---|
| `hands/rec/panel/ft-handpanel.cpp` (C++, dev container) | The headset panel: a SteamVR overlay fixed to the head that shows the prompts. It also places the "touch the dot" target in the room and logs head and controller poses. Driven over `@ft_handpanel`. |
| `hands/rec/session.py` (Python, no Qt) | The session runner. It reads `script.json`, starts and stops the recordings, and drives the panel. It reads the live hands file for feedback and writes each take's files. It also runs from the command line (`--dry-run`) for testing. |
| `hands/rec/script.json` | The guided script: sections, prompts, timings. |
| `hands/rec/poses/` | The pose pictures, `poses.json` and its PNGs (below). |
| `hands/rec/takes.py` (Python, no Qt) | Reads sessions and takes from disk: frame sets for review, deleted ranges, export (compress, strip, manifest, checksums). |
| `hands/rec/ft_handrec.py` + `main.qml` (PySide6 + Kirigami, dev container) | The desktop window: consent, the before-you-start checklist, the session controls, review, export and upload instructions. |
| `hands/rec/ft-handrec` | The host launcher, like `input-settings/ft-input-settings`. |
| `hands/rec/build.sh` | Builds `ft-handpanel` into `hands/rec/build/`, like `gaze/build.sh`. |
| `hands/rec/CONSENT.md`, `hands/rec/UPLOAD.md` | The texts the window shows. |
| `hands/rec/install.sh` | Installs the recorder on a Frame with Frametop: the dev container's packages, hands/build.sh, the panel, ft-camd's capabilities, and the menu entry (`uninstall` removes the entry). |
| ft-hands `--record-hz N` (done) | Records at most N frame sets a second. The recorder uses 10. |
| `hands/camcheck.py` (shared, standard library) | Are all four mono cameras running? The recorder runs it before a session and when a step sees no hands (below; `hands/README.md`, "Camera check"). |
Every part runs in the dev container, as ft-hands and Input Settings do. The host Python isn't used: it lacks PySide6 and zstd. `setup/dev-container.sh` gains `zstd`.
## Processes during a session
- **ft-camd** publishes the camera ring. If it isn't running, the session starts it as the transient user unit `frametop-handrec-camd.service`, the way `hands/ft-cutouts` starts `frametop-cutouts-camd.service` (needs `hands/build/ft-camd` with capabilities: `hands/run.sh caps`). An ft-camd already running from ft-cutouts or ft-handsctl is used as it is.
- **A tracking ft-hands** gives feedback through the hands file: which hands are seen, the palm's distance, the index tip. If none is running, the session starts `ft-hands --no-gestures --status 0` (unit `frametop-handrec-hands.service`). An ft-hands already running is used as it is.
- **A recording ft-hands** runs once per recording part: `ft-hands --record-only --record DIR --record-for SECONDS --record-hz 10 --status 0 --sides auto|0|1` (below, "Side cameras"). It runs as a plain child process of the session, ended with SIGTERM when the part ends. SIGTERM ends ft-hands' loop, and `Recorder` writes out its queue when it's destroyed. In step mode (below) a part is one step's countdown and hold, so a take has one part per step (about 40 in the hand poses); in auto mode a take is one part, plus one more after each pause. `--record-for` is only a safety net.
- Why a process per part rather than one kept alive and paused: measured in the dev container with `ft-ringplay`'s ring (2026-10-02), `ft-hands --record-only` writes its first set 16-27 ms after it starts and ends 4-6 ms after SIGTERM, so a new part costs nothing the 3 s countdown doesn't cover. Every reader already takes parts in order (`takes.py`, `validate.py` through the export's single stream, the labeller's `fhl_io.py`, numbering `sets-10.bin` after `sets-9.bin`), ft-hands needs no new control, and nothing is written while a step waits. Before the hold starts the session checks that the part has written a set (`Recorder.has_data`, up to 3 s more), so the hold is recorded from its first frame.
- **Side cameras.** ft-camd can name the two side cameras the wrong way round (hands/README.md, "Which camera is which"). The tracking ft-hands decides from the hands within about 2 s of them being in view (`HANDS_SWAP_SIDES=auto`, hands/track/sides.h) and publishes that in `/run/user/UID/frametop-hands/sides.json`. The session reads it (`sides.py`, `read_live`) and stores it in session.json `"sides"`. Each later part is recorded named right (`--sides 1` or `0`). Parts recorded before the decision use ft-camd's names (`--sides auto`; a record-only ft-hands can't tell), and readers rename them (`sides.py`). Each part's `names_swapped` goes into take.json `"parts"`. Without a tracking ft-hands nothing decides: `"swapped": null`, the names stay as recorded, and the maintainer's check (`hub_review check`, check_sides on a few sets per take) tells. `takes.py sides SESSION --set swapped|named` records a decision by hand.
- **ft-handpanel** runs as a child process with `--watch-stdin`. It shows the panel and logs poses during each take.
- **The headset button's reader** is a thread of the session (`ButtonReader`, below), not a process.
Test hooks:
- `--ring PATH` goes to both ft-hands (`ft-ringplay` publishes a recording there, so the whole flow runs without the headset).
- `--no-start` uses only what's already running.
- `--dry-run` runs no processes and only prints the panel commands, with timing sped up by `--speed X`.
- `--next-after S` presses Next by itself after S seconds of waiting (real time), so a step-mode session runs unattended. Lines on stdin steer it too: `n` or an empty line is Next, `p` pause or resume, `r` redo, `s` skip the section, `q` stop.
- `--no-headset-button` leaves the headset's button alone (`ft-handrec --no-headset-button` too). `--button-device PATH` reads it from PATH instead, an event device or a FIFO of `input_event` structs, also in a dry run: a simulated button for tests.
- `--auto` runs the timed flow; `--poses DIR` takes the pose pictures from DIR; `--plan` prints the sections, their steps and length.
- `--ignore-cameras` (`ft-handrec --ignore-cameras` too) starts even when the camera check fails. A dry run and `--ring` skip the check by themselves.
## Files
```
~/.local/share/frametop/hands/contrib/
profile.json consent and contributor id (below)
sessions/<YYYYMMDD-HHMMSS>/ (a second session started in the same second gets -2, and so on)
session.json the session: checklist answers, lighting, versions, mode, takes
calibration.json /persist/xrservice.json with identifying fields removed (below)
device.json the rig's pose in the CAD frame from /persist/device_config.json (below)
takes/<NN>-<section>/
sets.bin ft-hands' recording (FHSET01, hands/track/record.h), 10 sets/s: the first part
sets-2.bin, sets-3.bin, ... the next parts (step mode: one per step; any mode: after a pause)
prompts.jsonl what the person was asked to do, when (below)
poses.jsonl head and controller poses from ft-handpanel (below)
take.json {"section", "title", "started_ns", "ended_ns", "status": "complete"|"stopped"|"skipped",
"deleted": [[from_ns, to_ns], ...], "notes": "",
"parts": {"sets.bin": {"names_swapped": false}, "sets-2.bin": {...}},
"clock": [[mono_ns, raw_minus_mono_ns], ...]}
exports/<session>/ what export writes (below)
```
All `_ns` times are CLOCK_MONOTONIC nanoseconds, the clock of `dqbuf_ns` in sets.bin and of `capture_ns` in the hands file. sets.bin's `capture_ns` is the camera clock (CLOCK_MONOTONIC_RAW). The two drift apart with NTP's corrections: on 2026-10-03 RAW ran 0.80 s ahead, gaining about 10 ppm. take.json `"clock"` samples the difference (RAW minus MONOTONIC, as ft-hands' `raw_minus_mono_ns()`) when each part starts and stops, so a set's exposure time on the poses' clock is `capture_ns - raw_minus_mono_ns`, interpolated between samples. `dqbuf_ns` is on the right clock already, but a few ms after the exposure. Takes recorded before 2026-10-03 have no `"clock"`.
### profile.json
```json
{"schema": 1, "contributor": "<random uuid4>", "consent": {"version": "2026-10-02", "accepted": "<ISO time>", "adult": true},
"optional": {"handedness": "right|left|both|", "notes": ""}}
```
No name, email, or account. The contributor id is random, so several sessions from one person can be held out together in evaluation. Withdrawal also goes by that id.
### session.json
```json
{"schema": 1, "tool": "ft-handrec <git describe>", "started": "<ISO>", "contributor": "<uuid>",
"lighting": {"chosen": "dim|room|daylight|indoor", "source": "measured|picked", "measured": "indoor|daylight|",
"ambient_ir": 0.0, "ring": {"<cam>": {"mean": 0.0, "dark_mean": 0.0}}},
"checklist": {"objects": ["pencil", "phone", "cup", "keyboard", "mouse", "gamepad", "small"], "own_objects": ["..."],
"controllers": "straps|none", "sleeves": "short|long|", "rings": false, "watch": false, "notes": ""},
"device": {"steamos": "<VERSION_ID from /etc/os-release>", "steamvr": "<version if known>", "cameras": [{"name", "width", "height"}]},
"mode": "step|auto", "quick": false, "shuffle": {"seed": 123, "sweeps": {"pose-sweeps": [{"id", "hands", "cues"}]}},
"takes": ["01-hand-size", "..."],
"camera": {"status": "ok|unknown|degraded", "reason": "..."}, "stop_reason": "...",
"sides": {"swapped": true|false|null, "decided_by": "auto|config|option|manual", "state": "decided|confirmed|...",
"evidence": {"as_named": 0, "swapped": 10, "seconds": 1.8, "miss_mm": [-1, 4.2], "probes": 30, "found": 10},
"decided_at": "<ISO>", "decided_ns": 0}}
```
`sides`: whether ft-camd's side camera names were backwards during the session (`swapped`), as the live tracker decided it (above, "Side cameras"); `null` while nobody knows. A part's names are right when its take.json `names_swapped` equals `swapped`. Parts without a `parts` entry were recorded with ft-camd's names. Sessions from before this have no `sides`.
`camera` is the camera check's verdict at the start (no paths or log lines: those go to `session.log`). `stop_reason` is there when a session was stopped at the no-hands screen, with the check's result.
A session started before step mode existed has no `mode`: it ran as `auto`. `quick` and `shuffle` (below, "Sweeps" and "Quick round") are missing from sessions before the sweeps.
### calibration.json
This is a copy of `/persist/xrservice.json` (`/run/host/persist/` in the container). Keep the cameras' intrinsics and extrinsics, and drop anything that identifies the unit: keys containing `serial`, `sn`, `uuid`, `mac` or `id`, or values that look like serial numbers. List what was removed in `session.json` (`"calibration_removed": [...]`), so a reviewer can check it.
### device.json
The head frame needs the rig's pose in the CAD frame, from `/persist/device_config.json`. Only two of its keys are kept, `cv.cad_from_cal` (Cam0 in the CAD frame) and `head` (the head in CAD), in the shape the labeller in frame-hands `train/label` reads, as its `cut.py` writes it:
```json
{"cv": {"cad_from_cal": {"method": "FrontAndUpperCamPositions", "plus_x": [x, y, z], "plus_z": [x, y, z], "position": [x, y, z]}},
"head": {"plus_x": [x, y, z], "plus_z": [x, y, z], "position": [x, y, z]}}
```
The rest of that file identifies the unit (serial number, display EDID) and is never copied. The two kept keys go through `strip_calibration` as well, and anything it removes is listed in `calibration_removed` as `device.json:<path>`. Sessions recorded before device.json existed have none: they still validate, with a warning, and the labeller falls back to another unit's pose.
### prompts.jsonl
One JSON object per line:
```json
{"t": 123, "event": "take", "section": "static-poses", "take": "03-static-poses"}
{"t": 123, "event": "prompt", "id": "static-poses/fist/left/near", "text": "...", "hands": "left|right|both|none",
"pose": "fist", "distance": "near|mid|far|", "position": "centre|left|right|up|down|", "object": "", "controller": false}
{"t": 123, "event": "target", "id": "touch/3", "head": [x, y, z], "room": [x, y, z], "state": "show|hold|done|timeout"}
{"t": 123, "event": "bar", "target": 0.0}
{"t": 123, "event": "feedback", "left": true, "right": false, "palm_m": [0.0, 0.0]}
{"t": 123, "event": "pause"}
{"t": 123, "event": "resume"}
{"t": 123, "event": "ready", "id": "static-poses/fist/left/near", "seconds": 3}
{"t": 123, "event": "wait"}
{"t": 123, "event": "redo", "id": "static-poses/fist/left/near", "from": 123, "to": 123}
{"t": 123, "event": "nohands", "id": "hand-size/flat/both", "reads": 120, "published": 118}
{"t": 123, "event": "end", "status": "complete|stopped|skipped"}
```
`feedback` is written about twice a second while recording. It's the live tracker's view, kept for later checks; it's not a label.
A prompt holds from its `prompt` until the next `prompt`, `ready`, `wait` or `end`. A step in step mode reads:
```
ready Next pressed: recording part N starts, the 3-2-1 countdown runs (recorded, no label)
prompt the hold: its labels start here
(bar, target, feedback, pause/resume during the hold)
wait the hold is over: no labels from here; part N stops
```
The touch-the-dot targets after the first follow straight on: no `ready` or `wait` between them. `redo` marks a try done again (R): `from` is that step's `ready` (or its `prompt` if it had none), `to` its end. Its prompt is skipped; the sets stay. In auto mode there's no `ready` or `wait`, and the intro is a recorded prompt `<section>/intro`. `nohands` marks the first hand-size step stopped because no hand was seen (below, "Camera check"); a `redo` over the same range follows it, so the try gets no labels. A sweep step (below, "Sweeps") has a `prompt` per cue, each with its `pose`, `"cue": true` and `"step"`, the step's id; its `ready`, `wait` and `redo` carry the step's id. Readers that knew only `prompt` and `end` keep working, but they'd give the countdown to the step before: `hub_review.py` (frame-hands `train/hub`) shows it as "(countdown)", redone prompts as "(redone)" and cues as "[pose] text"; `FORMAT.md` in the dataset repo has the rules.
### poses.jsonl
ft-handpanel writes one line per sample, 250 a second, from `GetDeviceToAbsoluteTrackingPose(TrackingUniverseStanding, 0)`:
```json
{"t": 123, "hmd": {"m": [12 floats, row-major 3x4], "r": 200, "ok": true},
"left": {"m": [...], "r": 200, "ok": true}, "right": null}
```
`r` is `ETrackingResult` (200 = Running_OK, 201 = Running_OutOfRange, and so on). `left` and `right` are the devices holding those controller roles, or null. No device serials are logged.
## The panel (`ft-handpanel`)
- **Placement.** A SteamVR overlay fixed to the head, like `gaze/panel/ft-gazepanel.cpp`: key `frametop.handpanel`, sort order 250. It sits 1.2 m ahead, centred 12 degrees above straight ahead, so the hands stay clear below it. It's 36 degrees wide, 4:3, 1024x768 pixels, dim and see-through. It's drawn on the CPU with stb_truetype (and stb_image for the pose pictures, PNG only, the same pinned stb commit) into three shared DMA-BUFs SteamVR imports once, as ft-gazepanel does, and is drawn again only when something changes.
- **Layout.** The title and step on top (a red "Rec" by the step while recording), a rule. With a pose picture or a diagram, a 14-degree column on the left holds the picture (or the flipped copy and the picture side by side) and the where-to diagram under it; the text takes the right. The text column holds the instruction, the orange note, the big countdown ("3", "2", "1", then "Hold" or "Go") and the cyan action line ("Ready? Press Space or click Next"), centred together. At the bottom: the near/far bar, the hand chips, the time-left bar and the key hints.
- **Socket.** Abstract unix datagram `@ft_handpanel` (`--socket NAME`). A sender with an address gets `ok ...` or `error ...`.
- **Options:** `--watch-stdin` (quit when stdin closes), `--socket NAME`, `--distance M`, `--no-vr`. `--no-vr` makes no SteamVR connection and prints each picture's text to stdout: for testing without a headset.
Commands (UTF-8; `|` starts a new line in text):
| Command | Effect |
|---|---|
| `show` / `hide` | The panel. A "show" makes it visible with its first picture. |
| `title <text>` | Big line at the top. |
| `step <text>` | Small line at the top right, e.g. `Section 3 of 11`. |
| `text <text>` | The instruction, large, wrapped to the panel's width, centred. |
| `note <text>` | An orange line under the instruction: a warning ("I can't see your left hand"). Empty clears it. |
| `countdown <0..1>` / `countdown off` | A thin bar along the bottom: the share of this prompt's time left. |
| `hands <left> <right>` | Two chips, "Left hand" and "Right hand", each `seen` (green), `lost` (orange) or `off` (hidden). |
| `bar <target 0..1> <current 0..1 or -1> [near label] [far label]` / `bar off` | The near/far bar for the push out and back: a horizontal track with a target marker and the hand's current position. |
| `paused on` / `paused off` | A "Paused" overlay over the picture. |
| `image <path> [mirror\|both]` / `image off` | The pose picture, a PNG (below), in the left column. `mirror` flips it (a left hand); `both` draws a flipped copy on its left. A file that can't be read: `error ...` and no picture. |
| `where <position\|-> <distance\|->` / `where off` | The where-to diagram under the picture: a 3x3 front view with the asked cell lit (`centre`, `left`, `right`, `up`, `down`, and the push sections' `chest`, `desk`, `eye`), and a side view of the head and three marks for `near` ("Close"), `mid` ("Halfway out") and `far` ("Arm out"). `-` leaves that half out. |
| `action <text>` | The cyan line under the instruction (empty clears it). |
| `big <text>` | Large cyan text under the instruction: the countdown (empty clears it). |
| `keys <text>` | The faint key hints along the bottom. |
| `rec on` / `rec off` | The red "Rec" by the step line. |
| `strip <cue> <path>\|<mode>\|<label>;...` / `strip off` | A sweep's row of pose pictures (path `-`: none; mode `-` or `mirror`), each with its label under it; the one at index `cue` (from 0, -1 for none) framed in cyan and bright, the others dim. It sits along the bottom of the space left, the where-to diagram at its right end if there is one, and the text above it; it takes the left column's place. Each picture is loaded once. A file that can't be read: `error can't read ...`, and that item shows an empty frame. |
| `target <x> <y> <z> [show\|hold <0..1>\|done]` / `target off` | The touch target: a small sphere-like dot about 2 cm across, in its own overlay (`frametop.handpanel.target`). The point is in the head frame (metres, +x right, +y up, -z forward). The first `target` with a new point places it in the room with the current HMD pose, and it stays there. Later commands with the same point change only the state. `hold` draws a filling ring, `done` turns it green. Reply: `ok <room x> <room y> <room z>`. |
| `poses start <path>` / `poses stop` | Log poses to the path (appending, `poses.jsonl` format above) from a thread at 250 Hz, until stopped. |
| `devices` | Reply: `ok hmd <r> left <r or -> right <r or ->`, the current `ETrackingResult` values (`-` for no device in that role). |
| `head` | Reply: `ok <12 floats>`, the current HMD pose (standing universe). |
| `ping` | `ok shown` or `ok hidden`. |
It quits on SteamVR's quit event, as ft-gazepanel does. `--no-vr --dump DIR` writes each picture to `DIR/panel.pam`, to check the layout without a headset.
## The pose pictures (`poses/`)
`poses/poses.json` maps the script's `pose` ids to pictures: `{"<pose>": {"file": "<name>.png", "two_hands": false, "caption": "..."}}`. Each PNG is RGBA, square (512x512), drawn as the wearer sees it: a right hand, unless `two_hands` (then it shows both). How a prompt shows it (`session.pose_view`):
| Prompt's `hands` | Picture |
|---|---|
| `right` (and `any`, `none`, empty) | as drawn |
| `left` | flipped left to right (`image ... mirror`) |
| `both`, not `two_hands` | a flipped copy on the left, the picture on the right (`image ... both`) |
| anything, `two_hands` | as drawn |
A pose with no entry, or whose file is missing, shows no picture: the text alone. The session reads `poses.json` when it starts. The window shows the same picture (QML `Image.mirror`), its caption, and the same diagram.
## The script (`script.json`)
```json
{"version": 1,
"cue_names": {"thumbs-up": "Thumbs up", "...": "..."},
"sections": [
{"id": "hand-size", "title": "Hand size", "requires": [], "intro": "text shown before the first prompt: 4 s, or until Next", "go": "Hold",
"quick": true, "prompts": [{"text": "...", "cues": ["flat", "flat-back", "spread"], "cue_s": 5, "hands": "both", "distance": "mid"}]},
{"id": "pose-sweeps", "title": "Hand poses", "kind": "sweep", "quick": true, "cue_s": 4, "step_s": 20,
"groups": [["open", "fist", "point", "pinch"], ["ok", "thumbs-up", "spread", "claw"], ["count-1", "...", "count-5"]],
"sweeps": [{"hands": "both", "group": "next", "text": "..."}, {"hands": "left", "group": "any", "quick": false, "text": "..."}]},
{"id": "objects", "title": "Things you hold", "requires": ["objects"], "for_each": "object",
"prompts": [{"text": "Pick up the {object} and use it the way you normally would.", "seconds": 15, "hands": "both", "object": "{object}"}]},
{"id": "touch", "title": "Touch the dot", "kind": "targets", "hold_s": 1.0, "timeout_s": 8,
"targets": [[0.0, -0.15, -0.40], ...], "text": "Touch the dot with your index fingertip and hold still."},
{"id": "controller-push", "title": "Depth with controllers", "requires": ["controllers"], "kind": "bar",
"intro": "...", "heights": ["chest", "desk", "eye", "left", "right"], "reps": 5, "period_s": 6, "near_m": 0.2, "far_m": 0.6}
]}
```
- `requires`: `objects` (at least one object ticked), `controllers` (straps ticked). A section whose requirements aren't met is skipped and logged.
- `go`: the word the countdown ends on, "Go" unless set ("Hold" for the still poses).
- `quick`: the section is in a quick round; a step with `"quick": false` isn't (below).
- `kind`:
- `prompts` (the default): each prompt shows for its `seconds` with a countdown. A prompt with `cues` (and `cue_s`) is a sweep step with those cues in that order, `seconds` = cues x cue_s (hand size; the mouse and switch step).
- `sweep`: steps built from `sweeps` (below).
- `targets`: each target shows until the live index tip is within 3 cm of it for `hold_s`, or `timeout_s` passes.
- `bar`: the target marker sweeps near to far and back, `reps` times per height, at `period_s` per sweep. The current marker follows the live palm distance.
- Each section is one take. Prompts within it are marked in `prompts.jsonl`.
- `cue_names`: the short labels under the strip's pictures (otherwise the pose id).
### Sweeps
The second in-headset session (sessions/20261002-202734) took about 16 min and was "super long and kind of annoying": the 36 held poses alone took 7.9 min, 3.2 of it reading, and the person skipped the wrist turns and gave up on the bare push after 3 steps. The labels come from the auto-labeller (teacher model and triangulation, frame-hands `train/label`), not from the prompts, so what the recordings need is variety (shapes, distances, angles), not clean holds. So the poses are swept:
- A sweep step shows a strip of 2-5 pose pictures and asks for slow, continuous movement (near and far, all around) while the hands change shape with the lit picture. The light moves on every `cue_s` (4 s), cycling, over `step_s` (20 s): 5 cues for a group of 4 or 5. Each cue is a `prompt` event with that `pose`, `"cue": true` and `"step"` (the step's id); `distance` and `position` are "" (varied). So the timeline tags each pose roughly, and the countdown, `wait` and `redo` work per step as before. The time-left bar covers the whole step.
- `groups`: lists of poses. A step takes `"group": "next"` (the groups in turn) or `"any"` (one drawn at random, a different one for each "any" while there are groups left), or names its own `cues`. `"shuffle": false` (gestures) keeps the script's order; `"cycle": false` runs the cues once; `"fixed": true` keeps one step's order.
- The pose sweeps: 3 two-hand sweeps, one per group ([open, fist, point, pinch], [ok, thumbs-up, spread, claw], [count-1 ... count-5]); then a left-hand and a right-hand sweep (the other hand in the lap) on groups drawn from those three, which also turn the wrist as they go, so the wrist angles come for free (the old wrist-turns section is gone).
- **The shuffle, per session.** The groups' order, the "any" draws and the cues' order in each step are shuffled with a seed from the session's id (`session_seed`: the first 8 hex digits of its SHA-256), separately per section (`random.Random("<seed>/<section>")`). The sections' order isn't shuffled (the controller sections need their before and after). session.json records `"shuffle": {"seed", "sweeps": {section: [{"id", "hands", "cues"}]}}`, and `build_plan(script, checklist, seed=...)` gives the same again. `--seed N` overrides it; `--plan` without one shows the script's order.
- The strip has one picture per pose, a single hand: both hands make the same shape, and five pairs wouldn't fit. A left hand's pictures are flipped.
- Gestures are sweeps too, in order and once: tap then drag; grab, cross, overlap; near the face then a screen's distance. Hand size is one step of three held shapes (flat, backs, spread; 5 s each), still the no-hands check's first step.
### Quick round
For more lighting rounds: "Quick round (about 3 min)" on the checklist page, `session.py --quick`. It has the sections marked `quick` (hand size, the pose sweeps without the one-hand ones, touch the dot, no hands), about 2 min recorded in 6 steps. session.json gets `"quick": true`. The checklist page suggests it (and picks it) once a full session has gone to the end (`Backend.hasFullSession`: a session.json with status `done`, not quick, not a dry run).
### Step mode (the default) and auto mode
The first in-headset session (2026-10-02) went too fast: each prompt advanced after 4-8 s, before there was time to read it and find the hand shape. So by default every step waits:
1. **Ready.** The panel shows the step: section title, "step N of M", the instruction, the pose picture, the where-to diagram, and the Next hint ("Ready? Press the button on the right side of the headset", or with a mouse also Space and Next: see Controls). The hand chips show which hands are seen, with no warnings yet. It waits as long as it takes, and nothing records.
2. **Countdown.** Next starts a new recording part and a "ready" event, and the panel counts 3, 2, 1 (big), recorded so the hold is captured from its first frame. In the push sections the bar sits at near meanwhile.
3. **Hold.** The `prompt` event, the section's word ("Hold" or "Go") and the time-left bar for the prompt's seconds (or the bar's sweeps, or the targets). Then a `wait` event and the part stops.
Steps that wait: each prompt, each bar height, and the first touch-the-dot target (the others follow straight on, as each waits for the touch anyway). Before a section, one screen shows the section's intro (with its `before` text, such as putting on the controllers) and waits for Next too; the welcome screen as well. The take starts with the section's first countdown, so a section skipped at its intro leaves no take. A pause in a hold works as before (the part stops; resume starts the next one).
Auto mode ("Advance by itself" on the checklist page, `session.py --auto`) is the old timed flow: the welcome, the between and before screens, the intro (recorded) and each prompt for its seconds, one recording per take. R still works there: it restarts the step running.
Steps are 20 s sweeps, 16-18 s gestures, 10-12 s desk and object steps, the touch targets (6) and the push heights (2, 3 reps of 6 s). The core session (no objects, no controllers) records about 5 min in 15 steps; with 5 s of reading a step that's about 6 min. Everything ticked (four objects, controllers): about 7.3 min recorded in 24 steps. A quick round: about 2 min in 6 steps. The window and `session.py --plan` give these (`plan_summary`); in step mode they leave the reading time out and say so.
The sections, in this order (see the plan):
1. hand size (one step: flat, backs, spread)
2. pose sweeps (above: 3 with both hands, one with each hand)
3. gestures (3 sweeps: pinch taps and drags; grabs, crossing and overlapping; near the face, then pointing at screen distance)
4. desk work (typing or pretend typing; the mouse, with switching to the keyboard when both are there)
5. objects (one prompt per ticked object, own objects included)
6. touch the dot (6 dots spread near and far, left and right, low)
7. controller depth, straps (push out and back at chest and eye level, 3 reps each; then the wrists and fingers with the controllers on). "Out and back" is straight away from the headset and back toward it: the first in-headset session took the left-right bar for sideways. The texts say so, the bar's ends read "At your chest" and "Arm out" (`near_label`, `far_label`, sent as `bar ... At your chest|Arm out`), and the picture is a side view.
8. bridge (one controller on, the bare fingertip on its thumbstick while that hand moves from close to arm's length and back, then swap; then a controller on the desk, touched from the front and above, then from the sides: 4 steps, the controller changes during the ready screens)
9. bare repeat of section 7's pushes, controllers off
10. no hands (10 s)
Before section 7: "Put on both controllers and tighten the straps". Before section 9: "Take the controllers off and put them out of view".
### Feedback while recording
- **Hands seen:** from the hands file. A hand counts as seen if its flags match the side and the file is fresh (publish within 0.3 s). Prompts with `hands` set show the `hands` chips. If an asked-for hand is lost for more than 1.5 s, the note says "I can't see your left hand: bring it into view".
- **Controller tracking:** in sections 8 and 9, `devices` is polled once a second. A result other than 200 for more than 1 s says "The left controller lost tracking: turn your palm slightly toward you". Each such stretch goes into `prompts.jsonl` as `feedback` with `"controller": {...}`.
- **Lighting, measured:** the checklist page measures the light when it opens, starting ft-camd (`frametop-handrec-camd.service`) if nothing runs it; the window stops it again on quit if it started it. The mean of every mono camera's `mean` and `dark_mean` from the ring (`hands/tools/ring.py` layout; struct only, no numpy) is compared with the person's earlier sessions. If it matches an earlier round's within 15%, the window says so before starting.
- **Lighting label:** "Measured by the cameras" is the default. `ambient_ir`, the mono cameras' mean `dark_mean` (the room's infrared), labels the round `daylight` from 6.0 and `indoor` below (`session.classify_lighting`). Lamps and LEDs give off hardly any infrared, so a dim room and a lit one read about the same (1.8 by one lamp, 2.2 in a lamp-lit room) and the cameras can't tell them apart; the person can pick dim, room or daylight instead (`source: "picked"`). The 6.0 threshold is a guess until a daylight round is measured.
### Camera check
On 2026-10-02 a whole session showed "I can't see your hands": after the headset slept, SteamVR had failed to load the colour module's FPGA image, which left the upper cameras and the IR light off (`hands/README.md`, "Camera check"). Two checks keep that from wasting a session:
- **Before the session.** The window runs `hands/camcheck.py` when the checklist page opens ("Tracking cameras:", with the evidence under Details and Check again), and again when Start is pressed; `session.py` runs it first thing, before it makes the session's folder or starts anything (`Session._preflight`). If it finds the cameras degraded, the session doesn't start. The window says: "The headset's upper cameras and IR light are off. SteamVR couldn't start the colour camera module (it happens sometimes after the headset sleeps). Restart SteamVR, or restart the headset if that doesn't fix it." (another `degraded:` reason gets a sentence naming it), and Start stays off. `unknown` (SteamVR not running, the cameras asleep) doesn't stop it: the session's own start fails clearly then. From the command line, `session.py` prints the check and exits with status 3.
- **Restart SteamVR.** The message has a Restart SteamVR button. After a confirmation it runs `systemctl --user restart --no-block steamvr.service` on the host (through `distrobox-host-exec`), then checks the cameras every 3 s, for up to 2 minutes, until a new XRService has opened its cameras. The confirmation says what really happens: every VR app closes, and so does the Frametop desktop with all its windows, this one included, and it doesn't come back by itself (`hands/README.md`, "What a SteamVR restart does to Frametop"). So the check after the restart mostly happens when the recorder is opened again; it re-runs when the checklist page opens. `--no-block` lets the restart finish after the window is gone.
- **No hands in the first step.** The first step of the hand-size section has both hands up, about 40 cm away. During its hold, the session counts the hands file's reads (about 20 a second). If the tracker published in at least half of at least 10 reads and never saw a hand, the step stops: a `wait` and the recording stops as usual, then a `nohands` event and a `redo` over the try. The session runs the camera check and shows "I can't see your hands" with its result (the camera text above when it's the VCINT failure, else "The camera check found nothing wrong"). The state is `nohands`, waiting: Next (the headset button, Space, Try again) or R starts the same step's countdown at once; Stop (Esc) ends the session with `stop_reason` set; S skips the section. One missed step costs a retry, not the session, and every hold of that step is logged ("hands check ...: a hand in N of M reads"). Without a tracker publishing the session can't tell, logs that, and goes on. Only that one step is checked: later steps have their notes ("I can't see your left hand") as before. Auto mode does the same; its recording pauses meanwhile.
### Controls
- The window has Start, a big Next (while a step waits; its hint is the panel's), Pause/Resume, Redo step, Skip section and Stop. While it has focus: Space is Next, P pauses or resumes, R redoes, S skips the section, Esc stops. The panel's bottom line and the window list them. The window also shows the step's picture, diagram, countdown and "Hold".
- **The headset's button.** The Frame has a click button on its right side, for use without controllers: `KEY_SELECT` (353) on the evdev device `gpio-keys`. While a step waits (the welcome, a section's intro, a step's ready screen) a press is Next; during a countdown or hold (and auto mode's timed screens) it pauses; while paused it resumes. The session finds the device in `/proc/bus/input/devices` by name and its KEY bitmap (`event3` on the maintainer's Frame) and reads `input_event` structs with plain `struct` (no python-evdev), from a thread. Only key-downs count (value 1: releases and autorepeat, value 2, don't), and presses closer than 0.3 s count once.
- It's read, never grabbed (`EVIOCGRAB`). Frametop's input relay (`input/input-relay.py`), ft-powerd, SteamVR and gamescope read the same device, and the relay remaps its volume keys (the experimental branch's `docs/hazards.md`). A grab would take the volume keys from the relay.
- `steamos` is in the `input` group, so it needs no sudo. The dev container sees the host's `/dev/input` and `/proc/bus/input/devices`, and the group carries over (checked 2026-10-02), so it works from the window there and from `session.py` on the host. If the device is missing or can't be opened, the session logs it, keeps trying every 5 s, and the hints don't mention the button.
- **Not known yet (needs the headset):** what SteamVR and gamescope do with the same press. They read it too, so it may also click whatever is under the head or gaze pointer in VR, or open something. Check on the first session; if it does, the fix is on their side or a different button, not a grab.
- **The Next hint follows what's there.** No mouse connected: "Ready? Press the button on the right side of the headset" (the window's Next can't be clicked, and Space needs the window focused). A mouse: "Ready? Press Space, click Next, or press the headset button". No button: "Ready? Press Space or click Next". The panel's bottom line leads with "Headset button: next, pause". A mouse is a device in `/proc/bus/input/devices` with EV_REL, REL_X and REL_Y that isn't made in software: uinput devices (Frametop's virtual mouse, frame-voice's keyboard) sit under `/devices/virtual/input` or on the virtual bus (6), and are left out; Bluetooth mice come through uhid, under `/devices/virtual/misc/uhid`, and count. It's looked at again at each step, so a mouse plugged in mid-session counts from the next step.
- **R (redo).** During a step's countdown or hold: that step starts again from its ready screen. At a step's ready screen: the step before it (in this section) goes again. Either way a `redo` event marks the range of the try being redone, so its labels are skipped; the sets stay, to delete in review if wanted.
- A pause stops the take's recording and starts it again on resume as the next part of the same take (`sets-2.bin`, and so on). takes.py reads all parts in order. A pause while a step waits only shows "Paused"; a Next pressed while paused doesn't count.
## Review and export (`takes.py`, the window)
- **Review.** Each session lists its takes: title, duration, status, a thumbnail (the first set's `slam_left`). A viewer shows one frame set (all cameras side by side, 8-bit grey) at a time with a slider. It can mark a range and delete it. Deleted ranges go into `take.json`, and export leaves them out; the files keep everything until export. A whole take or session can be deleted (files removed, after a confirmation).
- **Export.** It writes `exports/<session>/`:
- `manifest.json`: profile fields except `optional.notes` unless kept, session.json (without its `uploads` records), takes, schema, tool version, the consent version.
- `calibration.json` and `device.json`, when the session has them.
- Per take: `prompts.jsonl`, `poses.jsonl`, `take.json`, and `sets.bin.zst` (sets in deleted ranges removed, then zstd -10 with 2 threads).
- The side cameras are named right in every exported set when the session's `sides.swapped` is known: parts that need it get slam_left and slam_right (and their `_dk`) exchanged in the set headers as they're compressed. The exported take.json says `"parts": {"sets.bin": {"names_swapped": <swapped>}}`, and the manifest's take entry `"sides": {"names_swapped", "renamed_sets"}`. Unknown, the names stay as recorded.
- `poses.jsonl` and `prompts.jsonl` without what's in the deleted ranges: no poses and no live-tracker `feedback` there (the prompt timeline stays). With the checklist's controllers at `none`, the controllers' poses are null and `feedback` has no `controller` (`takes.export_jsonl`): controllers left switched on still get tracked, and their poses would pass for the hands' ground truth.
- `SHA256SUMS`.
Compression runs at nice 19. While it runs with the headset worn, the window notes that VR may stutter a little (exports are done in the headset). Worn is judged the way `frame-job` does: `vrcompositor` runs and a `/sys/class/backlight/*/brightness` reads over 0 (SteamVR turns the panel off 5 s after the headset comes off). CPU work while in VR causes stutter. The proximity sensor is no use here: it read 9-43 with the headset sitting unworn.
- **Upload.** The Upload page uploads an export from the window, logging in included: no terminal. Below its steps it shows `UPLOAD.md` ("About uploading"), with the export's path, size and contributor id filled in.
- **`hands/rec/validate.py`** (standard library) checks an export. The window runs it before an upload, and the maintainer runs it on each submission (`validate.py DIR [--json]`, exit status 1 on errors). It checks:
- `SHA256SUMS`: every file listed and matching.
- An allow-list: `manifest.json`, `calibration.json`, `device.json` and `SHA256SUMS` at the top, and `prompts.jsonl`, `poses.jsonl`, `take.json` and `sets.bin.zst` in `takes/<NN>-<section>/`. Anything else is an error, and so is a symlink.
- The manifest's schema, keys and types, and that it matches the files.
- The consent version is present and the contributor confirmed being an adult. The contributor id is a uuid4.
- `calibration.json` has nothing that `session.py`'s `strip_calibration` would still remove.
- `device.json` holds only `cv.cad_from_cal` and `head`, each `plus_x`, `plus_z` and `position` as 3 numbers (plus `cad_from_cal`'s `method`). Without it: a warning.
- Each `sets.bin.zst` decompresses to its end, so a truncated one fails, and every set's FHSET01 header is sane: camera names, sizes, record length. Set counts and raw bytes match the manifest. Pixels aren't decoded.
- Every jsonl line parses.
- `session.sides` is `{"swapped": true|false|null}`, and every take's `sides.names_swapped` equals it (else an error: export again). Without `sides`, or `null`: a warning (the maintainer's check tells).
- The total size: a warning over 15 GB, an error over 40 GB.
Warnings cover notes kept in the export, a home folder path in the manifest, and missing `poses.jsonl` files.
It runs on Linux and on Windows (the maintainer's PC) with Python 3.12 or later. It decompresses with Python 3.14's `compression.zstd`, else the `zstandard` package, else the `zstd` program, and handles several zstd frames in a row.
- **`hands/rec/hub.py`** does the upload. It runs as a child process of the window (Cancel ends it), or from the command line (`hub.py [--base DIR] whoami | login | upload SESSION [--dry-run] [--again] [--json]`). It uses `huggingface_hub` (`python3-huggingface-hub` in the dev container) with the login saved in huggingface_hub's token file.
- **`login`** is huggingface_hub's browser login (OAuth device code), the same as `hf auth login`'s default since huggingface_hub 1.x. It asks Hugging Face for a link (`https://hf.co/oauth/device`) and a short code, prints them (`{"phase": "code", "url", "code", "expires_in"}`), and waits while the person enters the code in their browser and approves. Then it saves the token, which can refresh itself. Nobody types or pastes a token, and the window never sees one. It uses huggingface_hub's own helpers (`request_device_code`, `poll_device_token`, `_save_oauth_token`), as there's no public call that hands back the code. On 2026-10-03 the code lasted 5 minutes and wasn't filled into the link. The consent screen lists the person's organizations: none are needed, as a pull request on a public dataset comes from the person's own account.
An upload goes through these steps: An upload goes through these steps:
1. Validate, and stop on errors.
2. Stop if the same export was uploaded before (same `SHA256SUMS`), unless asked again.
3. Stop while the texts are drafts, unless `FT_HANDREC_ALLOW_UPLOAD=1`.
4. `whoami`: a read-only token is refused.
5. `auth_check` on the dataset: a gated dataset whose terms aren't accepted gives "accept the dataset's terms first", with the link.
6. Open the pull request first: `create_pull_request(HF_DATASET, title, description=...)`, an empty draft. Its link goes to the window right away (`{"phase": "opened", "pr_url"}`), which tells the person to plug the headset in and leave it. Record `{"repo", "pr_url", "pr_num", "started", "export_sha", "status": "started"}` in `uploads` in `session.json`. A retry of the same export goes on in that pull request while it's draft or open.
7. `upload_folder(repo_id=HF_DATASET, repo_type="dataset", folder_path=EXPORT, path_in_repo="contributions/<contributor>/<session>", revision="refs/pr/N", commit_message=..., commit_description=...)`. The description summarizes the manifest: takes, minutes, sets, lighting, objects, controllers, the consent and tool versions, the size, and validate's warnings. Then mark the pull request open if it's still a draft (the maintainer's `list` shows open ones, so drafts are uploads still in progress).
8. Mark the record `"status": "done"` with `uploaded`. `export_sha` is the SHA256 of `SHA256SUMS`. The file keeps its modification time, so the export doesn't count as out of date. Only finished records count as "uploaded before" (records without a status are from before 2026-10-03 and finished).
Errors get a plain explanation: not logged in, a login Hugging Face rejects (401), a login that can't open a pull request (403), terms not accepted, dataset not found, network errors. `--dry-run` does everything except the network calls and the record, and lists what it would upload.
- **The page** has three numbered steps:
1. Choose the export, with its size.
2. Log in to Hugging Face. The page shows whether someone is logged in (`whoami`). Log in runs `hub.py login`, opens the link in the browser, and shows the code large, with Copy code and Cancel. "Use another account" logs in again. A classic read-only token counts as not logged in.
3. Upload, with a note to accept the dataset's terms the first time.
Upload has Cancel, the phase with a progress bar (a share while the export is checked, a sweep while it's sent, as `huggingface_hub` reports no progress), the pull request's link once it's open, with "plug in the headset and leave it plugged in until this says Uploaded", and Uploaded at the end. If this export was uploaded before, the page says so, and uploading it again asks first. A stale export can't be uploaded.
- **Staying awake:** while an export or an upload runs, the window holds a host unit, `frametop-handrec-awake.service`, running `systemd-inhibit --what=sleep:idle --mode=block ... sleep infinity`, and stops it when the last of them ends (or on quit). It's meant to keep Steam from putting the Frame to sleep with the headset off; whether Steam's sleep honours a logind block inhibitor is still to be checked on the device. Exports and uploads are done in the headset: the export page only notes that VR may stutter a little while it compresses.
- **While the texts are drafts**, Upload stays off unless `FT_HANDREC_ALLOW_UPLOAD=1`, so the maintainer can rehearse against a private test repo. `FT_HANDREC_DATASET` overrides `HF_DATASET`. `ft-handrec --hub-dry-run` makes Upload a dry run: no network, so it isn't held back by the drafts.
- **Rehearsal: `hands/rec/rehearse.sh [--repo ID]`** runs it all without the headset, in the dev container, in one `frame-job --local` scope when frame-job is installed. `ft-ringplay` plays 30 s of a recording into a ring in `/run/user/UID`. A tracking ft-hands that's already running is used, or one is started on that ring. `ft-handpanel --no-vr` stands in for the panel. `session.py --no-start --next-after 0.3` records a three-section test script (a prompt, a two-cue sweep, no hands) in step mode, three parts of 6 s (countdown and hold), about 360 MB once exported. Then `takes.py` exports, `validate.py` checks, and `hub.py` uploads: a dry run by default, or for real to `--repo ID` with `FT_HANDREC_ALLOW_UPLOAD=1`. It prints a summary, deletes its temporary folders (camera images of a room) and stops everything it started, Ctrl+C included. The `--no-vr` panel logs no poses, so `poses.jsonl` is missing there (a warning).
## Licensing and consent (texts in `CONSENT.md`)
- The dataset is CC BY-NC 4.0.
- Contributors also grant the maintainer (DeeJanuz) a broad, non-exclusive license to their contribution.
- Contributors confirm they're 18 or older.
- The text explains what's recorded and that nothing uploads automatically, how review works, how to withdraw (by contributor id), and that a withdrawal is purged from the repo's history.
- The texts need a legal review before the dataset launches. Until then they carry a "draft" banner, and the Upload page says contributions aren't open yet.
- The dataset repo: `HF_DATASET` in `hub.py`, `DeeJanuz/frametop-hands` (private until launch).
+9
View File
@@ -0,0 +1,9 @@
### About uploading
- **What's sent:** the export in `@EXPORT_PATH@` (@EXPORT_SIZE@), into `contributions/@CONTRIBUTOR@/@SESSION@` in [@DATASET@](https://huggingface.co/datasets/@DATASET@). Upload first checks that every file is complete and matches its checksum, and that nothing identifying is left in.
- **Your account:** the pull request comes from your Hugging Face account, and anyone can see its username next to your contributor id, `@CONTRIBUTOR@`. The dataset itself credits the contributor id, not your name. The login stays saved on this headset, so you only log in once.
- **The dataset's terms:** the first time, open the dataset's page and accept its terms. Until you have, Upload stops with "accept the dataset's terms first".
- **Once your pull request's link shows, plug in the headset and leave it plugged in until this page says Uploaded.** A round is several gigabytes, so this can take a while. You can take the headset off: the Hand Recorder keeps it awake until the upload is done. Keep the Hand Recorder open, since closing it stops the upload.
- **If it stops partway** (Cancel, or the network drops), press Upload again. It carries on in the same pull request, and files already sent aren't sent twice.
- **The maintainer's review:** they check that the files are complete, and that nobody else and nothing private is in view, before merging. You can follow it and answer questions on the pull request's page. Once it's merged, you can delete the session and its export here to free the space.
- **Withdrawing:** see "Withdrawing" in the consent text. You'll need your contributor id, `@CONTRIBUTOR@`.
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env bash
# Build the hand recorder's headset panel ft-handpanel in the dev container on the Frame
# (hands/rec/build/; it also runs there). Like gaze/build.sh: the pinned public OpenVR header
# (the DMA-BUF import is newer than the header shipped with SteamVR's samples), stb_truetype
# for the text and stb_image (PNG only) for the pose pictures, at the same stb commit.
set -euo pipefail
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
"$root/scripts/sync.sh" >/dev/null
exec "$root/scripts/frame.sh" -C hands/rec 'set -e; mkdir -p build/include
openvr=v2.15.6
[ -f build/include/openvr-$openvr ] || { curl -fsSL "https://raw.githubusercontent.com/ValveSoftware/openvr/$openvr/headers/openvr.h" -o build/include/openvr.h && touch build/include/openvr-$openvr; }
stb=2c980bb59875b0d32144a71867fbdebb2f77cd20
[ -f build/include/stb-$stb ] || { curl -fsSL "https://raw.githubusercontent.com/nothings/stb/$stb/stb_truetype.h" -o build/include/stb_truetype.h && touch build/include/stb-$stb; }
[ -f build/include/stb_image-$stb ] || { curl -fsSL "https://raw.githubusercontent.com/nothings/stb/$stb/stb_image.h" -o build/include/stb_image.h && touch build/include/stb_image-$stb; }
g++ -std=c++17 -O2 -Wall -Wno-unused-parameter -Wno-missing-field-initializers -Ibuild/include $(pkg-config --cflags gbm libdrm) \
-o build/ft-handpanel panel/ft-handpanel.cpp -L/opt/steamvr/bin/linuxarm64 -lopenvr_api -Wl,-rpath,/opt/steamvr/bin/linuxarm64 \
$(pkg-config --libs gbm libdrm) -lpthread
echo "built build/ft-handpanel"'
+21
View File
@@ -0,0 +1,21 @@
#!/bin/bash
# Launch the Frametop Hand Recorder from a Plasma session on the Frame host.
# The app runs in the dev container (PySide6, Kirigami and zstd come from Fedora there).
# podman needs the real XDG_RUNTIME_DIR and the real user bus (to reach systemd for
# the container's cgroup; the Frametop session runs on a private bus from
# dbus-run-session). The session's Wayland socket and bus go to the app itself.
# Options go to ft_handrec.py: --base DIR, --page NAME, and --dry-run for testing.
here=$(cd "$(dirname "$(readlink -f "$0")")" && pwd)
wl=${WAYLAND_DISPLAY:-wayland-0}
case $wl in /*) ;; *) wl="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/$wl" ;; esac
session_bus=${DBUS_SESSION_BUS_ADDRESS:-}
export XDG_RUNTIME_DIR=/run/user/$(id -u)
export DBUS_SESSION_BUS_ADDRESS=unix:path=$XDG_RUNTIME_DIR/bus
# From the home folder: the app's host commands (distrobox-host-exec) run in its folder on the
# host, and a folder only the container has, such as /run/host/tmp, makes them all fail.
cd "$HOME" || exit 1
"$here/../../scripts/container-up.sh"
exec "$HOME/.local/bin/distrobox" enter dev -- env WAYLAND_DISPLAY="$wl" DISPLAY="${DISPLAY:-}" \
XAUTHORITY="${XAUTHORITY:-}" DBUS_SESSION_BUS_ADDRESS="$session_bus" \
QT_QPA_PLATFORM="wayland;xcb" \
python3 "$here/ft_handrec.py" "$@"
+9
View File
@@ -0,0 +1,9 @@
[Desktop Entry]
Type=Application
Name=Frametop Hand Recorder
GenericName=Record your hands for the hand dataset
Comment=Record, review and export hand recordings for Frametop's open hand dataset
Exec=@REPO@/hands/rec/ft-handrec
Icon=camera-video
Categories=Utility;
Keywords=hands;hand tracking;dataset;record;frametop;
+1214
View File
File diff suppressed because it is too large. Load diff
+468
View File
@@ -0,0 +1,468 @@
#!/usr/bin/env python3
"""Upload a hand recorder export to the hand dataset on Hugging Face (DESIGN.md "Upload").
The window runs this as a child process (so Cancel can end it, and huggingface_hub stays out
of the window's process); it also runs from the command line. It uses huggingface_hub (in the
dev container: python3-huggingface-hub, from setup/dev-container.sh) with the login that
`hub.py login` (the window's Log in) or `hf auth login` saved. Nobody types a token anywhere.
`login` is huggingface_hub's browser login (OAuth device code, as `hf auth login` does): it gets a
link and a short code, the person enters the code in their browser and approves, and the token goes
straight from Hugging Face into huggingface_hub's token file. This process saves it; it never
prints it, and the window never sees it.
An upload:
1. checks the export with validate.py, and stops on errors;
2. stops if this export (same SHA256SUMS) was uploaded before, unless --again;
3. stops while CONSENT.md or UPLOAD.md is a draft, unless FT_HANDREC_ALLOW_UPLOAD=1;
4. checks the login (whoami: a read-only token can't open a pull request) and access to the
dataset (auth_check: a gated dataset's terms must be accepted first);
5. opens the pull request first (a draft, empty), so its link can be shown while the files go,
and records it under "uploads" in session.json with "status": "started";
6. upload_folder(..., revision="refs/pr/N") to contributions/<contributor>/<session>; a retry of
the same export goes on in the same pull request while it's still open;
7. marks the record {"repo", "pr_url", "pr_num", "uploaded", "export_sha", "status": "done"}.
--dry-run does all of it except the network calls (4 to 6) and recording (5, 7), and says what
it would upload.
The dataset is HF_DATASET; FT_HANDREC_DATASET overrides it (a test repo, for rehearsals).
usage: hub.py [--base DIR] whoami [--json]
hub.py [--base DIR] login [--json]
hub.py [--base DIR] upload SESSION [--dry-run] [--again] [--json]
With --json, each line of output is one JSON object: {"phase", "text", "fraction"} as it goes,
with {"phase": "opened", "pr_url"} once the pull request exists, then {"done": {...}} or
{"error": {"kind", "text", "link", "errors"}}. login says {"phase": "code", "url", "code",
"expires_in"} once it has the link, then {"done": {"name", "role"}}. Exit status 0: done.
"""
import argparse
import datetime
import hashlib
import json
import os
import re
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import takes # noqa: E402 (next to this file)
# The dataset contributions go to (DESIGN.md "Licensing and consent").
HF_DATASET = "DeeJanuz/frametop-hands"
DATASET_ENV = "FT_HANDREC_DATASET"
ALLOW_ENV = "FT_HANDREC_ALLOW_UPLOAD"
CONSENT_PATH = os.path.join(HERE, "CONSENT.md")
UPLOAD_PATH = os.path.join(HERE, "UPLOAD.md")
REPO_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*/[A-Za-z0-9][A-Za-z0-9._-]*$")
TOKENS_URL = "https://huggingface.co/settings/tokens"
# Quiet huggingface_hub: no progress bars on stderr, no telemetry or update hints.
HF_ENV = {"HF_HUB_DISABLE_PROGRESS_BARS": "1", "HF_HUB_DISABLE_TELEMETRY": "1", "HF_HUB_DISABLE_UPDATE_CHECK": "1"}
class HubError(Exception):
"""What went wrong, for people: kind (below), text, a link to open, validation errors.
Kinds: missing (no huggingface_hub), login, read-token, terms, not-found, permission,
network, hub, invalid, duplicate, closed, no-export."""
def __init__(self, kind, text, link="", errors=None, extra=None):
super().__init__(text)
self.kind, self.text, self.link = kind, text, link
self.errors = errors or []
self.extra = extra or {}
def as_dict(self):
return dict(self.extra, kind=self.kind, text=self.text, link=self.link, errors=self.errors)
def dataset_id():
"""HF_DATASET, or FT_HANDREC_DATASET when set."""
repo = os.environ.get(DATASET_ENV, "").strip() or HF_DATASET
if not REPO_RE.match(repo):
raise HubError("not-found", f"{DATASET_ENV}={repo!r} isn't a dataset id like owner/name")
return repo
def dataset_url(repo=None):
return "https://huggingface.co/datasets/" + (repo or dataset_id())
def is_draft(path):
try:
with open(path, encoding="utf-8") as f:
return "DRAFT" in f.readline()
except OSError:
return False
def texts_draft():
return is_draft(CONSENT_PATH) or is_draft(UPLOAD_PATH)
def upload_allowed():
"""Real uploads: once the texts aren't drafts, or for the maintainer's rehearsal against a
test repo (FT_HANDREC_ALLOW_UPLOAD=1)."""
return not texts_draft() or os.environ.get(ALLOW_ENV) == "1"
def now_iso():
return datetime.datetime.now().astimezone().isoformat(timespec="seconds")
# ---------------------------------------------------------------- records in session.json
def export_sha(export_dir):
"""The export's identity: the SHA256 of its SHA256SUMS ("" if there's none)."""
try:
with open(os.path.join(export_dir, "SHA256SUMS"), "rb") as f:
return hashlib.sha256(f.read()).hexdigest()
except OSError:
return ""
def uploads(store, session):
meta = takes.read_json(os.path.join(store.session_dir(session), "session.json"))
return [u for u in meta.get("uploads") or [] if isinstance(u, dict)]
def previous_upload(store, session, sha):
"""The latest finished upload of this same export, or None. (Records from before
2026-10-03 have no status: they were written only when an upload finished.)"""
same = [u for u in uploads(store, session) if sha and u.get("export_sha") == sha
and u.get("status", "done") == "done"]
return same[-1] if same else None
def unfinished_upload(store, session, sha, repo):
"""The latest upload of this same export to repo that opened its pull request and didn't
finish, or None."""
same = [u for u in uploads(store, session) if sha and u.get("export_sha") == sha and u.get("repo") == repo
and u.get("status") == "started" and u.get("pr_num")]
return same[-1] if same else None
def record_upload(store, session, record):
"""Add record to session.json's "uploads". The file keeps its time: an upload doesn't
change the recordings, so the export mustn't count as out of date because of it
(takes.Store.sessions compares times)."""
path = os.path.join(store.session_dir(session), "session.json")
try:
st = os.stat(path)
except OSError:
st = None
meta = takes.read_json(path)
records = meta.setdefault("uploads", [])
same = [i for i, u in enumerate(records) if isinstance(u, dict) and record.get("pr_num")
and u.get("pr_num") == record["pr_num"] and u.get("repo") == record.get("repo")]
if same:
records[same[-1]] = record # the same pull request: started, then done
else:
records.append(record)
takes.write_json(path, meta)
if st:
os.utime(path, ns=(st.st_atime_ns, st.st_mtime_ns))
# ---------------------------------------------------------------- the pull request's text
def describe(summary, report, sha, nbytes):
"""(commit message, commit description) from validate's summary of the manifest."""
s = summary
objects = ", ".join(s.get("objects") or []) or "none"
if s.get("own_objects"):
objects += f" (+{s['own_objects']} of their own)"
message = f"Hands: session {s.get('session')} from {s.get('contributor')}"
lines = ["Contribution to the Frametop hand dataset, uploaded from the hand recorder.", "",
f"- Session: {s.get('session')}",
f"- Contributor: {s.get('contributor')}",
f"- Takes: {s.get('takes')} ({s.get('minutes')} minutes, {s.get('sets')} frame sets)",
f"- Lighting: {s.get('lighting') or 'not given'}",
f"- Objects: {objects}",
f"- Controllers: {s.get('controllers') or 'not given'}",
f"- Consent version: {s.get('consent_version')}",
f"- Tool: {s.get('tool')}",
f"- Size: {takes.human_bytes(nbytes)}",
f"- SHA256 of SHA256SUMS: {sha}", "",
"Checked with hands/rec/validate.py: no errors" + (f", {len(report.warnings)} warnings:"
if report.warnings else ".")]
lines += [f"- {w}" for w in report.warnings]
return message, "\n".join(lines) + "\n"
# ---------------------------------------------------------------- talking to the Hub
def _hf():
os.environ.update({k: v for k, v in HF_ENV.items() if k not in os.environ})
try:
import huggingface_hub
except ImportError:
raise HubError("missing", "huggingface_hub isn't installed in the dev container: run setup/dev-container.sh "
"(or: pip install --user huggingface_hub)") from None
return huggingface_hub
def explain(e, repo):
"""A huggingface_hub (or network) exception as a HubError."""
if isinstance(e, HubError):
return e
try:
from huggingface_hub import errors as hf
except ImportError:
hf = None
url = dataset_url(repo)
if hf is not None:
if isinstance(e, hf.LocalTokenNotFoundError):
return HubError("login", "You're not logged in to Hugging Face. Press Log in.")
if isinstance(e, hf.GatedRepoError):
return HubError("terms", f"Accept the dataset's terms first: open {url}, read them and accept them, "
"then try again.", url)
if isinstance(e, hf.RepositoryNotFoundError):
return HubError("not-found", f"The dataset {repo} wasn't found, or it's private and your account has "
"no access to it.", url)
if isinstance(e, hf.HfHubHTTPError):
status = getattr(getattr(e, "response", None), "status_code", None)
first = str(e).strip().splitlines()[0] if str(e).strip() else type(e).__name__
if status == 401:
return HubError("login", "Hugging Face didn't accept your login (it may have expired or been "
"revoked). Log in again.")
if status == 403:
return HubError("permission", "Your login isn't allowed to open a pull request. Log in again, "
"and allow everything the Hugging Face page asks for.")
return HubError("hub", f"Hugging Face refused the upload ({status or 'no status'}): {first}")
try:
import httpx
net = (httpx.TransportError, OSError)
except ImportError:
net = (OSError,)
if isinstance(e, net):
return HubError("network", f"Couldn't reach huggingface.co ({type(e).__name__}: {e}). Check the network "
"and try again: files already sent usually aren't sent twice.")
return HubError("hub", f"{type(e).__name__}: {e}")
def whoami():
"""{"name", "role"} for the saved login; HubError if there's none or it doesn't work.
role: "write", "read", "fineGrained" or ""."""
hf = _hf()
try:
info = hf.HfApi().whoami()
except Exception as e:
raise explain(e, dataset_id()) from None
token = ((info.get("auth") or {}).get("accessToken") or {})
return {"name": info.get("name", ""), "role": token.get("role", "")}
def login(progress=None):
"""The browser login: progress("code", text, url=, code=, expires_in=) once the link is ready,
then wait (up to the code's expiry: 5 minutes on 2026-10-03) for the person to approve it, and save
the token. Returns whoami(). Uses huggingface_hub's own device code helpers (1.x)."""
tell = progress or (lambda phase, text, **extra: None)
_hf()
try:
from huggingface_hub._login import _save_oauth_token
from huggingface_hub.errors import DeviceCodeError
from huggingface_hub.utils._oauth_device import poll_device_token, request_device_code
except ImportError:
raise HubError("missing", "This huggingface_hub has no browser login: update the dev container "
"(setup/dev-container.sh).") from None
try:
info = request_device_code()
tell("code", "Approve the login in your browser", url=info["verification_uri_complete"],
code=info["user_code"], expires_in=info["expires_in"])
_save_oauth_token(poll_device_token(info))
except DeviceCodeError as e:
raise HubError("login", f"The login didn't go through: {e}. Press Log in to try again.") from None
except Exception as e:
raise explain(e, dataset_id()) from None
return whoami()
def upload(store, session, dry_run=False, again=False, progress=None, log=None):
"""Upload exports/<session> (the steps in this file's docstring). progress(phase, text,
fraction or None); log(text) for the dry run's account. Returns the result; raises HubError."""
tell = progress or (lambda phase, text, fraction=None, **extra: None)
say = log or (lambda text: None)
import validate
repo = dataset_id()
try:
export = store.export_dir(session)
except ValueError as e:
raise HubError("no-export", str(e)) from None
if not os.path.isfile(os.path.join(export, "manifest.json")):
raise HubError("no-export", f"No export of session {session}: export it first")
tell("check", "Checking the export", 0.0)
report = validate.validate(export, progress=lambda f, text: tell("check", text, f))
if not report.ok:
raise HubError("invalid", f"The export has {len(report.errors)} problems, so it can't be uploaded. Export "
"the session again; if that doesn't help, report it.", errors=report.errors)
summary = report.summary
contributor = summary.get("contributor", "")
sha = export_sha(export)
before = previous_upload(store, session, sha)
if before and not again:
raise HubError("duplicate", f"This export was uploaded already, on {before.get('uploaded', '?')}: "
f"{before.get('pr_url', '')}", before.get("pr_url", ""), extra={"previous": before})
if not dry_run and not upload_allowed():
raise HubError("closed", "Contributions aren't open yet: the texts are drafts waiting for a legal review. "
f"(For a rehearsal against a test repo: {ALLOW_ENV}=1.)")
path_in_repo = f"contributions/{contributor}/{session}"
message, description = describe(summary, report, sha, report.bytes)
files = []
for root, _, names in os.walk(export):
files += [os.path.relpath(os.path.join(root, n), export) for n in names]
plan = {"repo": repo, "repo_type": "dataset", "folder_path": export, "path_in_repo": path_in_repo,
"create_pr": True, "commit_message": message, "commit_description": description,
"files": len(files), "bytes": report.bytes, "warnings": report.warnings}
if dry_run:
say(f"dry run: would check the login (whoami) and access to {repo} (auth_check)")
say(f"dry run: would upload_folder {len(files)} files, {takes.human_bytes(report.bytes)}, "
f"from {export} to datasets/{repo}/{path_in_repo}, as a pull request")
for rel in sorted(files):
say(f" {rel} {takes.human_bytes(os.path.getsize(os.path.join(export, rel)))}")
say(f"dry run: commit message: {message}")
say("dry run: commit description:\n" + description.rstrip())
record = {"repo": repo, "pr_url": "", "uploaded": now_iso(), "export_sha": sha, "status": "done"}
say(f"dry run: would record in session.json's uploads: {json.dumps(record)}")
tell("done", "Dry run: nothing was uploaded", 1.0)
return dict(plan, dry_run=True, pr_url="", record=record)
hf = _hf()
api = hf.HfApi()
tell("login", "Checking your Hugging Face login", None)
try:
who = api.whoami()
except Exception as e:
raise explain(e, repo) from None
role = ((who.get("auth") or {}).get("accessToken") or {}).get("role", "")
if role == "read":
raise HubError("read-token", "Your saved login is a read-only token, so it can't open a pull request. "
"Log in again.")
tell("access", f"Checking access to {repo}", None)
try:
api.auth_check(repo, repo_type="dataset")
except Exception as e:
raise explain(e, repo) from None
# The pull request first, so its link shows while the files go (and the person can plug the
# headset in and leave it). A retry of this export goes on in its pull request if it's open.
tell("open", "Opening your pull request", None)
pr = None
before = unfinished_upload(store, session, sha, repo)
if before:
try:
d = api.get_discussion_details(repo, int(before["pr_num"]), repo_type="dataset")
if d.is_pull_request and d.status in ("draft", "open"):
pr = d
except Exception:
pr = None
if pr is None:
try:
pr = api.create_pull_request(repo, message, description=description, repo_type="dataset")
except Exception as e:
raise explain(e, repo) from None
pr_url = getattr(pr, "url", "") or f"{dataset_url(repo)}/discussions/{pr.num}"
record = {"repo": repo, "pr_url": pr_url, "pr_num": pr.num, "started": now_iso(), "export_sha": sha,
"status": "started"}
record_upload(store, session, record)
tell("opened", f"Pull request #{pr.num} is open. Uploading {len(files)} files ({takes.human_bytes(report.bytes)})",
None, pr_url=pr_url)
try:
api.upload_folder(repo_id=repo, repo_type="dataset", folder_path=export, path_in_repo=path_in_repo,
revision=f"refs/pr/{pr.num}", commit_message=message, commit_description=description)
except Exception as e:
raise explain(e, repo) from None
try: # a pull request opened through the API stays a draft until it's marked open
if api.get_discussion_details(repo, pr.num, repo_type="dataset").status == "draft":
api.change_discussion_status(repo, pr.num, "open", repo_type="dataset")
except Exception:
pass # the maintainer can open it
record = dict(record, uploaded=now_iso(), status="done")
record_upload(store, session, record)
tell("done", "Uploaded", 1.0)
return dict(plan, dry_run=False, pr_url=pr_url, pr_num=pr.num, user=who.get("name", ""), record=record)
# ---------------------------------------------------------------- the command line
def main():
ap = argparse.ArgumentParser(description="Upload a hand recorder export to the hand dataset on Hugging Face.")
ap.add_argument("--base", default=takes.DEFAULT_BASE)
sub = ap.add_subparsers(dest="cmd", required=True)
w = sub.add_parser("whoami", help="show the saved Hugging Face login")
w.add_argument("--json", action="store_true")
li = sub.add_parser("login", help="log in to Hugging Face in the browser")
li.add_argument("--json", action="store_true")
u = sub.add_parser("upload", help="upload exports/SESSION as a pull request")
u.add_argument("session")
u.add_argument("--dry-run", action="store_true", help="no network: say what would be uploaded")
u.add_argument("--again", action="store_true", help="upload even if this export was uploaded before")
u.add_argument("--json", action="store_true", help="JSON lines, for the window")
a = ap.parse_args()
def emit(obj):
print(json.dumps(obj), flush=True)
try:
if a.cmd == "whoami":
who = whoami()
if a.json:
emit({"done": who})
else:
print(f"logged in as {who['name']} (token role: {who['role'] or 'unknown'})")
return 0
if a.cmd == "login":
def code(phase, text, **extra):
if a.json:
emit(dict(extra, phase=phase, text=text))
else:
print(f"Open {extra['url']} and approve the code {extra['code']}. Waiting...", flush=True)
who = login(code)
if a.json:
emit({"done": who})
else:
print(f"logged in as {who['name']}")
return 0
if a.json:
def progress(phase, text, fraction=None, **extra):
emit(dict(extra, phase=phase, text=text, fraction=fraction))
def log(text):
emit({"log": text})
else:
last = {}
def progress(phase, text, fraction=None, **extra):
if extra.get("pr_url"):
print(f"pull request: {extra['pr_url']}", flush=True)
line = text if fraction is None else f"{fraction * 100:5.1f}% {text}"
if (phase, text) != last.get("key") or fraction in (0.0, 1.0):
print(line, file=sys.stderr, flush=True)
last["key"] = (phase, text)
def log(text):
print(text, flush=True)
if hasattr(os, "setpriority"):
try:
os.setpriority(os.PRIO_PROCESS, 0, 19) # validation reads and hashes everything: stay out of VR's way
except OSError:
pass
result = upload(takes.Store(a.base), a.session, dry_run=a.dry_run, again=a.again, progress=progress, log=log)
if a.json:
emit({"done": result})
elif result["dry_run"]:
print(f"dry run done: {result['files']} files would go to datasets/{result['repo']}/{result['path_in_repo']}")
else:
print(f"uploaded: {result['pr_url']}")
return 0
except HubError as e:
if a.json:
emit({"error": e.as_dict()})
else:
print(f"error ({e.kind}): {e.text}", file=sys.stderr)
for line in e.errors:
print(f" {line}", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
# Install the hand recorder on a Frame that has Frametop (get.sh --experimental): bring the dev
# container's packages up to date, build hand tracking's camera broker and tracker (hands/build.sh:
# the first build fetches and builds ncnn, a few minutes) and the headset panel (hands/rec/build.sh),
# give ft-camd its capabilities (hands/run.sh caps: asks for the password, once per build), and add
# "Frametop Hand Recorder" to the app menu (for Frametop's desktop: it isn't tested from SteamVR's
# "Launch a program", which runs apps outside it; the standalone recorder is for that).
# It doesn't turn on Frametop's live hand tracking (that's hands/run.sh install, still deferred).
# Usage: hands/rec/install.sh install or update
# hands/rec/install.sh uninstall remove the menu entry (recordings stay where they are)
set -euo pipefail
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
. "$root/scripts/_env.sh"
entry='~/.local/share/applications/frametop-handrec.desktop'
case ${1:-install} in
install)
echo "== 1/4 dev container packages"
"$root/setup/dev-container.sh"
echo "== 2/4 hand tracking: ft-camd and ft-hands"
"$root/hands/build.sh"
echo "== 3/4 the headset panel: ft-handpanel"
"$root/hands/rec/build.sh"
echo "== 4/4 ft-camd's capabilities (asks for your password) and the menu entry"
"$root/hands/run.sh" caps
fill_template "$root/hands/rec/ft-handrec.desktop" |
on_frame "mkdir -p ~/.local/share/applications && cat > $entry"
echo
echo "Installed. On Frametop's desktop, open \"Frametop Hand Recorder\" from the app menu."
echo "Recordings go to ~/.local/share/frametop/hands/contrib."
;;
uninstall)
on_frame "rm -f $entry"
echo "Removed the menu entry. Your recordings are still in ~/.local/share/frametop/hands/contrib:"
echo "delete that folder to remove them."
;;
*) echo "usage: $0 [install|uninstall]" >&2; exit 2 ;;
esac
+1846
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+52
View File
@@ -0,0 +1,52 @@
# Pose images for the hand recorder
Small pictures of each hand pose in `script.json`, shown on the headset panel next to the prompt text.
- `<id>.png`: one image per pose, 512x512 RGBA with a transparent background. Made for a dark panel and still readable at about 250 px.
- `poses.json`: maps each pose id to `{"file", "two_hands", "caption"}`.
- `contact-sheet.png`: every image in a grid with its id, for review. The panel doesn't use it.
- `make_poses.py`: the generator that makes all of the above.
## How the images are drawn
Every image shows a right hand as the wearer sees it from their own eyes. "Palm toward you" shows the palm, with its creases. "Back toward you" shows the back of the hand, with the nails and knuckles. Fingers point up unless the pose says otherwise.
- **Left-hand prompts:** the panel mirrors the image horizontally.
- **"Both" prompts:** the panel shows two copies, one of them mirrored.
- **`two_hands: true`:** the image already shows the whole scene: both hands, or one hand with an object, as in `hold`. Show it once, without mirroring or copying. This applies to `cross`, `overlap`, `near-face`, `typing`, `lift`, `switch`, `hold`, `push`, `push-controller`, `touch-stick` and `touch-stick-desk`.
- **`touch-stick`:** shows the left hand holding the controller while the right index touches its thumbstick. For prompts where the right hand holds the controller (`controllers: ["right"]`), mirror it.
`push` and `push-controller` are side views: the wearer's head with a headset on, one arm out in front with the palm out, a ghost of the hand further out, and a straight double arrow from the headset outward, labelled "near" and "arm out". The labels use Pillow's built-in font.
Other motion poses show the start pose, a faint blue "ghost" of the end pose, and orange arrows. Objects (keyboard, mouse, bottle, bar, controller, screen, head and headset) are plain grey shapes.
Besides the pose ids in `script.json`, these extra ids exist for prompts that need a different picture:
| id | for |
| --- | --- |
| `push` | the bar sections: push straight out from the headset and back, palms out |
| `push-controller` | the same with controllers on |
| `touch-stick-desk` | touching the thumbstick of a controller lying on the desk |
| `no-hands` | the no-hands section: hands down, out of view |
| `open-close` | already used by the bar sections |
`count-5` is the same picture as `spread`.
## Regenerating
You need Python 3 with numpy and Pillow. The script uses about one core-minute per image at the default quality, so don't run it on the headset. Run it on a build machine:
```sh
python3 -m venv venv && venv/bin/pip install numpy pillow
venv/bin/python make_poses.py --jobs 6 # all images, poses.json, contact sheet
venv/bin/python make_poses.py --only fist,ok # just some (poses.json is left alone)
venv/bin/python make_poses.py --ss 1 --jobs 6 # rough and about 8x faster, for trying things
```
`--out DIR` writes somewhere other than this folder.
Each pose is a short entry in the `POSES` table in `make_poses.py`: a caption, the `two_hands` flag, and a function that returns the scene. A scene is the camera, layers of hands and objects (a layer can be a faint ghost), and arrows. Hands are built from joint angles: flexion at each finger's three joints, sideways spread, and four thumb angles. A thumb can also be given a target point, such as "touch the index fingertip", and a small solver finds the angles. The presets near `FLAT`, `FIST` and `OK` are a good place to start a new pose.
## License
MIT, like the rest of the repository. The script draws everything itself. A hand made of a palm slab and tapered capsules is ray-marched as a signed distance field, then shaded and outlined. No photos, downloaded images, scanned or research hand models, or AI image generators are involved, so the images carry no other terms.
Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 711 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

File diff suppressed because it is too large. Load diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

+182
View File
@@ -0,0 +1,182 @@
{
"flat": {
"file": "flat.png",
"two_hands": false,
"caption": "Palm toward you, fingers together"
},
"flat-back": {
"file": "flat-back.png",
"two_hands": false,
"caption": "Back of the hand toward you"
},
"spread": {
"file": "spread.png",
"two_hands": false,
"caption": "Fingers spread wide"
},
"open": {
"file": "open.png",
"two_hands": false,
"caption": "Open and relaxed"
},
"fist": {
"file": "fist.png",
"two_hands": false,
"caption": "A fist"
},
"point": {
"file": "point.png",
"two_hands": false,
"caption": "Point with your index finger"
},
"pinch": {
"file": "pinch.png",
"two_hands": false,
"caption": "Thumb and index tips touching"
},
"ok": {
"file": "ok.png",
"two_hands": false,
"caption": "OK sign: a ring, three fingers up"
},
"thumbs-up": {
"file": "thumbs-up.png",
"two_hands": false,
"caption": "Thumbs up"
},
"claw": {
"file": "claw.png",
"two_hands": false,
"caption": "Fingers curled like a claw"
},
"count-1": {
"file": "count-1.png",
"two_hands": false,
"caption": "One: index finger"
},
"count-2": {
"file": "count-2.png",
"two_hands": false,
"caption": "Two: index and middle"
},
"count-3": {
"file": "count-3.png",
"two_hands": false,
"caption": "Three: index, middle, ring"
},
"count-4": {
"file": "count-4.png",
"two_hands": false,
"caption": "Four: thumb folded in"
},
"count-5": {
"file": "count-5.png",
"two_hands": false,
"caption": "Five: all fingers spread"
},
"turn-in-out": {
"file": "turn-in-out.png",
"two_hands": false,
"caption": "Turn your wrist: palm in, palm out"
},
"turn-up-down": {
"file": "turn-up-down.png",
"two_hands": false,
"caption": "Palm down, turn it up, then back"
},
"bend": {
"file": "bend.png",
"two_hands": false,
"caption": "Bend your wrist up, down, side to side"
},
"pinch-tap": {
"file": "pinch-tap.png",
"two_hands": false,
"caption": "Tap thumb and index together"
},
"pinch-drag": {
"file": "pinch-drag.png",
"two_hands": false,
"caption": "Pinch, move to the side, let go"
},
"grab": {
"file": "grab.png",
"two_hands": false,
"caption": "Close your hand around a bar, open it"
},
"open-close": {
"file": "open-close.png",
"two_hands": false,
"caption": "Open and close your hand"
},
"cross": {
"file": "cross.png",
"two_hands": true,
"caption": "Cross your hands, then uncross"
},
"overlap": {
"file": "overlap.png",
"two_hands": true,
"caption": "One hand over the other, slide around"
},
"near-face": {
"file": "near-face.png",
"two_hands": true,
"caption": "Hands near your face, not touching"
},
"screen-point": {
"file": "screen-point.png",
"two_hands": false,
"caption": "Point at a screen at arm's length"
},
"typing": {
"file": "typing.png",
"two_hands": true,
"caption": "Type on the keyboard"
},
"lift": {
"file": "lift.png",
"two_hands": true,
"caption": "Lift your hands off the keyboard, put them back"
},
"mouse": {
"file": "mouse.png",
"two_hands": false,
"caption": "Hand on the mouse, move and click"
},
"switch": {
"file": "switch.png",
"two_hands": true,
"caption": "Switch between keyboard and mouse"
},
"hold": {
"file": "hold.png",
"two_hands": true,
"caption": "Pick it up, use it, put it down"
},
"push": {
"file": "push.png",
"two_hands": true,
"caption": "Push straight out, away from the headset, and back"
},
"push-controller": {
"file": "push-controller.png",
"two_hands": true,
"caption": "Controllers on: push straight out from the headset, and back"
},
"touch-stick": {
"file": "touch-stick.png",
"two_hands": true,
"caption": "Touch the thumbstick with your other index"
},
"touch-stick-desk": {
"file": "touch-stick-desk.png",
"two_hands": true,
"caption": "Touch the thumbstick of the controller on the desk"
},
"no-hands": {
"file": "no-hands.png",
"two_hands": false,
"caption": "Hands down, out of view"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

+211
View File
@@ -0,0 +1,211 @@
#!/usr/bin/env bash
# The hand recorder end to end, without the headset (DESIGN.md "Upload"): a short stretch of
# an ft-hands recording plays into a camera ring (ft-ringplay), a session records it with a
# short test script (session.py, the panel as ft-handpanel --no-vr, a tracking ft-hands),
# takes.py exports it, validate.py checks the export, and hub.py uploads it: a dry run by
# default, or for real to a (test) dataset with --repo.
#
# hands/rec/rehearse.sh [--repo ID] [--capture DIR] [--from S] [--prompt-seconds N] [--keep]
#
# --repo ID upload for real to this dataset, as a pull request. While the texts are
# drafts that also needs FT_HANDREC_ALLOW_UPLOAD=1 in the environment.
# --capture DIR the recording to play (default the frame-hands capture
# rec-20260930-103803-lit); --from S: start this far into it (60)
# --prompt-seconds N each test step's length (3): a prompt, a two-cue sweep, no hands. The
# session runs in step mode, Next pressed by itself (--next-after): each
# step is a recording part of its own, with its 3 s countdown, so about
# 18 s are recorded in all, a few hundred MB before compression
# --keep keep the temporary folders (camera images of a room: delete them after)
#
# It runs in the dev container (where ft-hands, ft-handpanel, zstd and huggingface_hub are),
# and in one frame-job scope when frame-job is installed, so it stays capped while the headset
# is worn. Everything goes in temporary folders that are deleted at the end, and every process
# it started is stopped, also on Ctrl+C. A tracking ft-hands that's already running is used as
# it is; otherwise one is started for the rehearsal (it publishes the usual hands file).
set -euo pipefail
here=$(cd "$(dirname "$(readlink -f "$0")")" && pwd)
root=$(cd "$here/../.." && pwd)
uid=$(id -u)
if [ ! -e /run/.containerenv ]; then
"$root/scripts/container-up.sh"
# Ctrl+C and kill don't reach through distrobox: the rehearsal inside writes its PID to this
# file, and a signal here is passed on to it, so it still cleans up.
pidfile=$(mktemp "/run/user/$uid/ft-handrec-rehearse-pid.XXXXXX")
# The real user bus, so frame-job's systemd-run reaches the host's user manager.
"$HOME/.local/bin/distrobox" enter dev -- env DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$uid/bus" \
XDG_RUNTIME_DIR="/run/user/$uid" FT_REHEARSE_PIDFILE="$pidfile" bash "$here/rehearse.sh" "$@" </dev/null &
child=$! stopping=0 status=0
pass_on() { [ -s "$pidfile" ] && kill -TERM "$(cat "$pidfile")" 2>/dev/null; return 0; }
trap 'stopping=1; pass_on' INT TERM HUP
while kill -0 "$child" 2>/dev/null; do
wait "$child" && status=0 || status=$? # (set -e would end this on a signal)
[ "$stopping" = 0 ] || pass_on
done
rm -f "$pidfile"
exit "$status"
fi
if [ -z "${FT_REHEARSE_SCOPE:-}" ] && command -v frame-job >/dev/null; then
export FT_REHEARSE_SCOPE=1
cd /tmp # no .frame-job up from here: it runs locally, capped
exec frame-job --local -- bash "$here/rehearse.sh" "$@"
fi
[ -z "${FT_REHEARSE_PIDFILE:-}" ] || echo $$ >"$FT_REHEARSE_PIDFILE"
repo="" capture="$HOME/Desktop/Projects/frame-hands/captures/rec-20260930-103803-lit" from=60 prompt_s=3 keep=0
while [ $# -gt 0 ]; do
case $1 in
--repo) repo=$2; shift 2 ;;
--capture) capture=$2; shift 2 ;;
--from) from=$2; shift 2 ;;
--prompt-seconds) prompt_s=$2; shift 2 ;;
--keep) keep=1; shift ;;
-h|--help) sed -n '2,/^set -euo/p' "$0" | sed '$d; s/^# \{0,1\}//'; exit 0 ;;
*) echo "rehearse: unknown option $1" >&2; exit 2 ;;
esac
done
ringplay=$root/hands/build/ft-ringplay
hands=$root/hands/build/ft-hands
panel=$here/build/ft-handpanel
for b in "$ringplay" "$hands"; do
[ -x "$b" ] || { echo "rehearse: $b isn't built: hands/build.sh --tools" >&2; exit 1; }
done
[ -x "$panel" ] || { echo "rehearse: $panel isn't built: hands/rec/build.sh" >&2; exit 1; }
[ -f "$capture/sets.bin" ] || { echo "rehearse: no recording in $capture" >&2; exit 1; }
if pgrep -x ft-handpanel >/dev/null; then
echo "rehearse: an ft-handpanel is running (a real session?): try again when it's done" >&2
exit 1
fi
if [ -n "$repo" ]; then
if python3 -c "import sys; sys.path.insert(0, '$here'); import hub; sys.exit(0 if hub.upload_allowed() else 1)"; then :; else
echo "rehearse: the texts are drafts: a real upload needs FT_HANDREC_ALLOW_UPLOAD=1 as well as --repo" >&2
exit 1
fi
python3 -c "import huggingface_hub" 2>/dev/null || {
echo "rehearse: huggingface_hub isn't installed: setup/dev-container.sh" >&2; exit 1; }
fi
# The data: the ring in the runtime folder (memory), the rest in /tmp. Both go at the end.
work=$(mktemp -d "${TMPDIR:-/tmp}/ft-handrec-rehearse.XXXXXX")
ringdir=$(mktemp -d "/run/user/$uid/ft-handrec-rehearse.XXXXXX")
base=$work/base ring=$ringdir/cam-ring logs=$work/logs
mkdir -p "$base" "$logs"
pids=()
cleanup() {
local code=$?
# Finish even if more signals come: frame-job stops its scope with SIGTERM to every process
# in it when it's interrupted.
trap '' INT TERM HUP
trap - EXIT
for p in "${pids[@]}"; do kill "$p" 2>/dev/null || true; done
for p in "${pids[@]}"; do wait "$p" 2>/dev/null || true; done
if [ "$keep" = 1 ]; then
echo "kept: $work and $ringdir (camera images of a room: delete them when done)"
else
rm -rf "$work" "$ringdir"
fi
exit "$code"
}
trap cleanup EXIT
trap 'exit 130' INT TERM
t0=$(date +%s)
step() { echo; echo "== $*"; }
# Long steps run in the background and are waited for: a signal then ends the wait at once,
# and cleanup stops them (bash runs traps only after a foreground command ends).
run() { "$@" & local p=$!; pids+=("$p"); wait "$p"; }
indent() { sed 's/^/ /'; }
step "1. Playing ${capture##*/} from ${from} s into $ring"
"$ringplay" "$capture" --ring "$ring" --from "$from" --to "$((from + 30))" --loop >"$logs/ringplay.log" 2>&1 &
pids+=($!)
for _ in $(seq 100); do
python3 -c "import sys; sys.path.insert(0, '$here'); import session
r = session.Ring('$ring'); sys.exit(0 if r.alive() else 1)" 2>/dev/null && break
sleep 0.2
done
python3 -c "import sys; sys.path.insert(0, '$here'); import session
r = session.Ring('$ring'); print(' cameras:', ', '.join('%s %dx%d' % (c['name'], c['width'], c['height']) for c in r.cams))
sys.exit(0 if r.alive() else 1)" || { echo "rehearse: ft-ringplay doesn't publish: $(tail -3 "$logs/ringplay.log")" >&2; exit 1; }
step "2. Session (test script, panel --no-vr)"
tracker=existing
if ! python3 -c "import sys; sys.path.insert(0, '$here'); import session; sys.exit(0 if session.tracker_running() else 1)"; then
"$hands" --ring "$ring" --no-gestures --status 0 >"$logs/tracker.log" 2>&1 &
pids+=($!)
tracker=started
fi
echo " tracker: $tracker"
"$panel" --no-vr >"$logs/panel.log" 2>&1 &
pids+=($!)
python3 - "$here" "$base" "$prompt_s" "$work/script.json" <<'EOF'
import json, os, re, sys, uuid
here, base, secs, out = sys.argv[1], sys.argv[2], float(sys.argv[3]), sys.argv[4]
consent = re.search(r"^Version:\s*(\S+)", open(os.path.join(here, "CONSENT.md")).read(), re.M).group(1)
json.dump({"schema": 1, "contributor": str(uuid.uuid4()),
"consent": {"version": consent, "accepted": "2026-10-02T00:00:00+00:00", "adult": True},
"optional": {"handedness": "", "notes": ""}}, open(os.path.join(base, "profile.json"), "w"))
json.dump({"version": 1, "intro_s": 1, "between_s": 1,
"welcome": {"title": "Rehearsal", "seconds": 1, "text": "A rehearsal of the hand recorder."},
"done": {"title": "Done", "seconds": 1, "text": "Rehearsal done."},
"stopped": {"title": "Stopped", "seconds": 1, "text": "Rehearsal stopped."},
"sections": [
{"id": "hand-size", "title": "Hand size", "intro": "Rehearsal: hands.",
"prompts": [{"text": "Both hands flat, palms toward you.", "seconds": secs, "hands": "both",
"pose": "flat", "distance": "mid"}]},
{"id": "pose-sweeps", "title": "Hand poses", "kind": "sweep", "intro": "", "cue_s": secs / 2,
"groups": [["open", "fist"]], "sweeps": [{"hands": "both", "group": "next", "text": "Keep moving."}]},
{"id": "no-hands", "title": "No hands", "intro": "",
"prompts": [{"text": "Hands out of view.", "seconds": secs, "hands": "none"}]}]},
open(out, "w"))
EOF
for _ in $(seq 50); do
python3 -c "import sys; sys.path.insert(0, '$here'); import session
sys.exit(0 if session.Panel().cmd('ping', reply=True) else 1)" 2>/dev/null && break
sleep 0.2
done
run python3 "$here/session.py" --ring "$ring" --no-start --base "$base" --script "$work/script.json" --lighting room \
--next-after 0.3 \
</dev/null > >(indent)
sid=$(ls "$base/sessions" | tail -1)
[ -n "$sid" ] || { echo "rehearse: the session left nothing" >&2; exit 1; }
python3 "$here/takes.py" --base "$base" takes "$sid" | sed 's/^/ /'
echo " panel pictures: $(grep -c '^--- picture' "$logs/panel.log" || true)"
step "3. Export"
run python3 "$here/takes.py" --base "$base" export "$sid" >"$logs/export.log"
tr '\r' '\n' <"$logs/export.log" | tail -1 | indent
export_dir=$base/exports/$sid
step "4. Validate"
valid=1
run python3 "$here/validate.py" "$export_dir" --json >"$work/validate.json" || valid=0
python3 -c "import json, sys; v = json.load(open(sys.argv[1]))
for k in ('errors', 'warnings'):
for line in v[k]: print(' %s: %s' % (k[:-1], line))
print(' OK' if v['ok'] else ' %d errors' % len(v['errors']))" "$work/validate.json"
[ "$valid" = 1 ] || { echo "rehearse: the export didn't validate" >&2; exit 1; }
if [ -n "$repo" ]; then
step "5. Upload to $repo (for real)"
run env FT_HANDREC_DATASET="$repo" python3 "$here/hub.py" --base "$base" upload "$sid" >"$logs/hub.log"
indent <"$logs/hub.log"
else
step "5. Upload (dry run: --repo ID uploads for real)"
run python3 "$here/hub.py" --base "$base" upload "$sid" --dry-run >"$logs/hub.log"
indent <"$logs/hub.log"
fi
step "Summary"
python3 - "$work/validate.json" "$logs/hub.log" "$tracker" "$(( $(date +%s) - t0 ))" <<'EOF'
import json, sys
v = json.load(open(sys.argv[1]))
s = v["summary"]
hub = open(sys.argv[2]).read().strip().splitlines()
print(f" session {s['session']}: {s['takes']} takes, {s['sets']} sets, {s['minutes']} min recorded")
print(f" export: {v['bytes'] / 1e6:.1f} MB, {len(v['errors'])} errors, {len(v['warnings'])} warnings")
for w in v["warnings"]:
print(f" warning: {w}")
print(f" hub: {hub[-1] if hub else '-'}")
print(f" tracker: {sys.argv[3]}; took {sys.argv[4]} s")
EOF
+118
View File
@@ -0,0 +1,118 @@
{
"version": 1,
"intro_s": 4,
"between_s": 3,
"welcome": {"title": "Hand recorder", "seconds": 7,
"text": "Follow the steps on this panel. Each one shows what to do with your hands, and where. A bar shows the time left.|The button on the right side of the headset goes on when a step waits for you, and pauses while recording."},
"done": {"title": "All done", "seconds": 6,
"text": "Thank you! You can take off the headset.|Review your recordings in the Hand recorder window."},
"stopped": {"title": "Stopped", "seconds": 4,
"text": "What was recorded so far is saved. Review it in the Hand recorder window."},
"cue_names": {"flat": "Flat", "flat-back": "Backs", "spread": "Spread", "open": "Open", "fist": "Fist",
"point": "Point", "pinch": "Pinch", "ok": "OK", "thumbs-up": "Thumbs up", "claw": "Claw", "count-1": "1",
"count-2": "2", "count-3": "3", "count-4": "4", "count-5": "5", "pinch-tap": "Tap", "pinch-drag": "Drag",
"grab": "Grab", "cross": "Cross", "overlap": "Overlap", "near-face": "Face", "screen-point": "Screen",
"mouse": "Mouse", "switch": "Switch"},
"objects": {"pencil": "pencil or pen", "phone": "phone", "cup": "cup", "keyboard": "keyboard",
"mouse": "mouse", "gamepad": "gamepad", "small": "small thing"},
"sections": [
{"id": "hand-size", "title": "Hand size", "requires": [], "go": "Hold", "quick": true,
"intro": "First, your hand size. Hold each shape still while its picture is lit.",
"defaults": {"hands": "both", "distance": "mid", "position": "centre"},
"prompts": [
{"text": "Both hands about 40 cm away, still. Make each lit shape: flat with palms toward you, then the backs toward you, then fingers spread wide.",
"cues": ["flat", "flat-back", "spread"], "cue_s": 5}
]},
{"id": "pose-sweeps", "title": "Hand poses", "kind": "sweep", "requires": [], "quick": true,
"intro": "Now keep your hands moving slowly while they change shape. A picture lights up every few seconds: make that shape wherever your hands are. Close, far, high, low: all of it helps.",
"cue_s": 4, "step_s": 20,
"groups": [["open", "fist", "point", "pinch"], ["ok", "thumbs-up", "spread", "claw"],
["count-1", "count-2", "count-3", "count-4", "count-5"]],
"sweeps": [
{"hands": "both", "group": "next", "text": "Both hands: move them slowly and keep going, from close to you out to arm's length and all around in front of you. Change shape with the lit picture."},
{"hands": "both", "group": "next", "text": "Both hands again: slowly near and far, high and low, left and right. Change shape with the lit picture."},
{"hands": "both", "group": "next", "text": "Both hands, still moving slowly all around in front of you. Change shape with the lit picture."},
{"hands": "left", "group": "any", "quick": false, "text": "Left hand only, the right one in your lap. Move it slowly near and far and all around, change shape with the lit picture, and turn your wrist as you go: palm toward you, then away."},
{"hands": "right", "group": "any", "quick": false, "text": "Right hand only, the left one in your lap. Move it slowly near and far and all around, change shape with the lit picture, and turn your wrist as you go: palm toward you, then away."}
]},
{"id": "gestures", "title": "Gestures", "kind": "sweep", "requires": [], "shuffle": false, "cycle": false,
"intro": "Now some movements, at a calm, normal pace. Follow the lit picture.",
"defaults": {"hands": "both"},
"sweeps": [
{"id": "pinch", "cues": ["pinch-tap", "pinch-drag"], "cue_s": 8,
"text": "Both hands: tap thumb and index finger together a few times. Then pinch, drag slowly to the side and let go, again and again."},
{"id": "grab-cross", "cues": ["grab", "cross", "overlap"], "cue_s": 6,
"text": "Grab as if holding a bar and open again. Then cross your hands and uncross them. Then hold one over the other and slide them around."},
{"id": "face-screen", "cues": ["near-face", "screen-point"], "cue_s": 8,
"text": "Move your hands close around your face, without touching the headset. Then reach out to where a screen would be and point at things on it."}
]},
{"id": "desk-work", "title": "Desk work", "requires": [],
"intro": "Now your desk. Look down at your hands while you work.",
"defaults": {"hands": "both", "position": "down"},
"prompts": [
{"when": "objects:keyboard", "text": "Type on your keyboard the way you normally do. Any text is fine.", "seconds": 10, "pose": "typing", "object": "keyboard"},
{"when": "!objects:keyboard", "text": "Rest your hands on the desk and pretend to type.", "seconds": 10, "pose": "typing"},
{"when": ["objects:mouse", "objects:keyboard"], "text": "Use your mouse: move it and click. When the picture changes, switch between the mouse and the keyboard a few times.", "cues": ["mouse", "switch"], "cue_s": 6, "object": "mouse"},
{"when": ["objects:mouse", "!objects:keyboard"], "text": "Use your mouse: move it around and click a few times.", "seconds": 10, "hands": "right", "pose": "mouse", "object": "mouse"},
{"when": "!objects:mouse", "text": "Put one hand flat on the desk and slide it around, as if using a mouse.", "seconds": 10, "hands": "right", "pose": "mouse"}
]},
{"id": "objects", "title": "Things you hold", "requires": ["objects"], "for_each": "object",
"skip_objects": ["keyboard", "mouse"],
"intro": "Now the things you set out. Use each one the way you normally would.",
"defaults": {"hands": "both"},
"prompts": [
{"text": "Pick up the {object}, use it for a moment, then put it down.", "seconds": 12, "pose": "hold", "object": "{object}"}
]},
{"id": "touch", "title": "Touch the dot", "kind": "targets", "requires": [], "quick": true,
"intro": "A small dot will appear. Touch it with your index fingertip and hold still until it turns green.",
"defaults": {"hands": "any", "pose": "point"},
"hold_s": 1.0, "timeout_s": 8,
"text": "Touch the dot with your index fingertip and hold still.",
"targets": [[0.00, -0.20, -0.25], [-0.20, -0.10, -0.40], [0.20, -0.10, -0.40], [-0.15, -0.25, -0.35],
[0.25, -0.05, -0.50], [0.05, -0.10, -0.55]]},
{"id": "controller-push", "title": "Depth with controllers", "kind": "bar", "requires": ["controllers"],
"before": {"text": "Put on both controllers and tighten the straps. Take your time.", "seconds": 25},
"intro": "Push both hands straight out in front of you, away from the headset, then pull them back toward it. Only nearer and farther, not sideways. Follow the hollow circle on the bar: right is arm out, left is at your chest. The blue dot is the current hand tracking's guess at how far your hands are. It's only an approximation and often wrong, so ignore it.",
"defaults": {"hands": "both", "pose": "open", "picture": "push-controller", "controller": true, "controllers": ["left", "right"]},
"near_m": 0.2, "far_m": 0.6, "near_label": "At your chest", "far_label": "Arm out", "period_s": 6, "lead_s": 3, "reps": 3,
"heights": [
{"id": "chest", "text": "Chest height, palms out like a stop sign. Push straight out, away from the headset, then pull back to your chest. Follow the hollow circle, not the blue dot."},
{"id": "eye", "text": "Now at eye level, palms out. Push straight out, away from the headset, then pull back toward it. Follow the hollow circle, not the blue dot."}
],
"prompts": [
{"text": "Controllers on: slowly turn your wrists, and open and close your hands, a few times.", "seconds": 10, "pose": "open-close", "distance": "mid"}
]},
{"id": "bridge", "title": "Controller and fingertip", "requires": ["controllers"],
"intro": "Now one controller on and one hand bare. The thumbstick is the point to touch.",
"defaults": {"controller": true},
"prompts": [
{"text": "Left controller on, the right one off on the desk. Touch the left thumbstick with your right index fingertip, and keep touching it while you move your left hand slowly from close to you out to arm's length and back.", "seconds": 12, "hands": "both", "pose": "touch-stick", "controllers": ["left"]},
{"text": "Swap: right controller on, the left one off. Touch the right thumbstick with your left index fingertip, and keep touching it while you move your right hand slowly from close to you out to arm's length and back.", "seconds": 12, "hands": "both", "pose": "touch-stick", "picture_mirror": true, "controllers": ["right"]},
{"text": "Put the right controller on the desk in front of you. Touch its thumbstick with your index fingertip from the front, then from above.", "seconds": 8, "hands": "any", "pose": "touch-stick", "picture": "touch-stick-desk", "position": "down"},
{"text": "Now touch it reaching from the left, then from the right.", "seconds": 8, "hands": "any", "pose": "touch-stick", "picture": "touch-stick-desk", "position": "down"}
]},
{"id": "bare-push", "title": "Depth, bare hands", "kind": "bar", "requires": [],
"before": {"when": "controllers", "text": "Take the controllers off and put them out of view.", "seconds": 15},
"intro": "Push both hands straight out in front of you, away from the headset, then pull them back toward it. Only nearer and farther, not sideways. Follow the hollow circle on the bar: right is arm out, left is at your chest. The blue dot is the current hand tracking's guess at how far your hands are. It's only an approximation and often wrong, so ignore it.",
"defaults": {"hands": "both", "pose": "open", "picture": "push"},
"near_m": 0.2, "far_m": 0.6, "near_label": "At your chest", "far_label": "Arm out", "period_s": 6, "lead_s": 3, "reps": 3,
"heights": [
{"id": "chest", "text": "Chest height, palms out like a stop sign. Push straight out, away from the headset, then pull back to your chest. Follow the hollow circle, not the blue dot."},
{"id": "eye", "text": "Now at eye level, palms out. Push straight out, away from the headset, then pull back toward it. Follow the hollow circle, not the blue dot."}
]},
{"id": "no-hands", "title": "No hands", "requires": [], "quick": true,
"intro": "Last one: put your hands down, out of view.",
"prompts": [
{"text": "Keep your hands out of view and look slowly around the room.", "seconds": 10, "hands": "none", "picture": "no-hands"}
]}
]
}
+2587
View File
File diff suppressed because it is too large. Load diff
+128
View File
@@ -0,0 +1,128 @@
"""Which side camera is which, in recordings: the rules every reader shares.
ft-camd tells slam_left's buffers from slam_right's by the order XRService allocated them, and
some XRService starts reverse it: then each side camera's images carry the other's name. A
tracking ft-hands tells from the hands (hands/track/sides.h, HANDS_SWAP_SIDES=auto) and publishes
what it found in /run/user/UID/frametop-hands/sides.json (read_live). Two things are recorded:
swapped whether ft-camd's naming was backwards during the recording (the truth);
None while nobody knows. A hand recorder session has it in session.json
"sides": {"swapped", "decided_by", "evidence", ...}; an ft-hands --record
recording in DIR/sides.json.
names_swapped per recording file: whether the side cameras' names in it were exchanged from
ft-camd's (ft-hands --sides 1). A session's take.json "parts": {"sets.bin":
{"names_swapped": false}, "sets-2.bin": {...}}; DIR/sides.json "names_swapped":
[[first set, bool], ...] (it can change inside a recording when ft-hands decides).
A file's names are right when names_swapped == swapped. Readers rename slam_left <-> slam_right
(and their _dk dark frames) where they differ (needs_rename). Exports always carry the right
names, with names_swapped = swapped written next to them, so applying the rule again is harmless.
Standard library only (the window, validate.py on Windows, the maintainer's tools).
"""
import json
import os
import struct
import time
HDR = struct.Struct("<8sII") # fh_set_hdr_t (hands/track/record.h)
CAM = struct.Struct("<16sIIQQ") # fh_set_cam_t: name, width, height, capture_ns, dqbuf_ns
SIDES = {"slam_left": "slam_right", "slam_right": "slam_left",
"slam_left_dk": "slam_right_dk", "slam_right_dk": "slam_left_dk"}
LIVE_FRESH_S = 6.0 # ft-hands rewrites its sides.json at least every 2 s
def other_name(name):
"""slam_left <-> slam_right (and their dark frames); other names as they are."""
return SIDES.get(name, name)
def needs_rename(swapped, names_swapped):
"""True when a file's side cameras carry each other's names. Unknown truth: leave them."""
if swapped is None:
return False
return bool(names_swapped) != bool(swapped)
def rename_record(record):
"""One FHSET01 record (bytes) with slam_left and slam_right's names exchanged (and their
dark frames'). Only the 16-byte name fields change; pixels and lengths stay."""
out = bytearray(record)
ncams = HDR.unpack_from(out, 0)[1]
for k in range(ncams):
off = HDR.size + k * CAM.size
raw = bytes(out[off:off + 16])
name = raw.split(b"\0", 1)[0].decode(errors="replace")
new = other_name(name)
if new != name:
out[off:off + 16] = new.encode().ljust(16, b"\0")
return bytes(out)
# ------------------------------------------------------------------ sessions and recordings
def session_sides(session_json):
"""A session.json's "sides" (a dict), or {"swapped": None} when it has none."""
s = (session_json or {}).get("sides")
return s if isinstance(s, dict) else {"swapped": None}
def part_names_swapped(take_json, part):
"""Whether a take's part file (e.g. "sets-2.bin") was recorded with exchanged names."""
parts = (take_json or {}).get("parts")
entry = parts.get(part) if isinstance(parts, dict) else None
return bool(entry.get("names_swapped")) if isinstance(entry, dict) else False
def part_rename(session_json, take_json, part):
"""Should a session take's part file have its side cameras renamed when read?"""
return needs_rename(session_sides(session_json).get("swapped"), part_names_swapped(take_json, part))
def recording_runs(rec_dir):
"""An ft-hands --record recording (DIR/sets.bin + DIR/sides.json): [(first set, rename)],
or [(0, False)] when it has no sides.json (recorded before there was one)."""
try:
with open(os.path.join(rec_dir, "sides.json")) as f:
s = json.load(f)
except (OSError, ValueError):
return [(0, False)]
runs = s.get("names_swapped") or [[0, False]]
return [(int(first), needs_rename(s.get("swapped"), sw)) for first, sw in runs]
def rename_at(runs, i):
"""recording_runs()'s answer for set i."""
out = False
for first, rename in runs:
if i >= first:
out = rename
return out
# ------------------------------------------------------------------ the live decision
def run_dir():
return "/run/user/%d/frametop-hands" % os.getuid()
def read_live(path=None, ring_path=None, now_ns=None):
"""The tracking ft-hands' sides.json, or None if there's none or it's stale (ft-hands
rewrites it every 2 s and removes it when it exits). With ring_path, also None when it
was written for another ft-camd run than the ring there now."""
path = path or os.path.join(run_dir(), "sides.json")
try:
with open(path) as f:
s = json.load(f)
except (OSError, ValueError):
return None
now = time.clock_gettime_ns(time.CLOCK_MONOTONIC) if now_ns is None else now_ns
if not isinstance(s, dict) or (now - int(s.get("updated_ns", 0))) / 1e9 > LIVE_FRESH_S:
return None
if ring_path:
try:
if os.stat(ring_path).st_ino != s.get("ring_ino"):
return None
except OSError:
return None
return s
+647
View File
@@ -0,0 +1,647 @@
#!/usr/bin/env python3
"""The hand recorder's sessions and takes on disk: listing, review, deleting, export.
Standard library only (no Qt, no NumPy), so the window and the command line share it.
The layout is hands/rec/DESIGN.md's "Files":
BASE/profile.json
BASE/sessions/<YYYYMMDD-HHMMSS>/session.json, calibration.json
BASE/sessions/<id>/takes/<NN>-<section>/sets.bin (sets-2.bin, ... after pauses),
prompts.jsonl, poses.jsonl, take.json
BASE/exports/<session>/
A take's recording is one or more FHSET01 files (hands/track/record.h): per set a header
(magic, ncams, bytes), one fh_set_cam_t per camera, then each camera's 8-bit pixels.
Deleted ranges live in take.json ("deleted": [[from_ns, to_ns], ...], CLOCK_MONOTONIC, the
clock of dqbuf_ns); the files keep every set until export leaves them out.
Side cameras (sides.py): a part recorded before the live tracker decided which side camera is
which may carry slam_left's and slam_right's names the wrong way round. TakeIndex renames them as
it reads (session.json "sides" against take.json "parts"), so review and export see the right
names, and export writes them so: an export's files are always named right, its take.json says
"parts": {"sets.bin": {"names_swapped": <the session's swapped>}}, and its manifest has each
take's "sides". `takes.py sides SESSION` shows the decision; --set swapped|named records one by
hand (e.g. from tools/check_sides.py on a session no live tracker decided).
usage: takes.py [--base DIR] list | takes SESSION | export SESSION | sides SESSION [--set swapped|named]
"""
import argparse
import datetime
import hashlib
import json
import os
import re
import shutil
import struct
import subprocess
import sys
import threading
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import sides # noqa: E402 (hands/rec/sides.py, next to this file)
DEFAULT_BASE = os.path.expanduser("~/.local/share/frametop/hands/contrib")
REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
MAGIC = b"FHSET01"
HDR = struct.Struct("<8sII") # fh_set_hdr_t: magic, ncams, bytes (the whole record)
CAM = struct.Struct("<16sIIQQ") # fh_set_cam_t: name, width, height, capture_ns, dqbuf_ns
MAX_CAMS = 16 # SetReader's limit
PART_RE = re.compile(r"^sets(?:-(\d+))?\.bin$")
SESSION_RE = re.compile(r"^\d{8}-\d{6}(?:-\d+)?$") # session.py adds -2, -3 to a second one in a second
EXPORT_SCHEMA = 1
# zstd as DESIGN.md has it: level 10, two threads, at the lowest CPU priority (CPU work while
# someone is in VR makes the headset stutter).
ZSTD_ARGS = ["-10", "-T2", "-q", "-c"]
ZSTD_PATHS = ("/usr/bin/zstd", "/usr/local/bin/zstd", "/run/host/usr/bin/zstd")
CHUNK = 1 << 20
class Cancelled(Exception):
pass
def read_json(path, default=None):
try:
with open(path) as f:
return json.load(f)
except (OSError, ValueError):
return {} if default is None else default
def write_json(path, obj):
"""Write through a temporary file, so a crash never leaves half a file."""
tmp = path + ".tmp"
with open(tmp, "w") as f:
json.dump(obj, f, indent=2)
f.write("\n")
os.replace(tmp, path)
def find_zstd():
"""The zstd binary, or None. The dev container gets it from setup/dev-container.sh."""
found = shutil.which("zstd")
if found:
return found
return next((p for p in ZSTD_PATHS if os.access(p, os.X_OK)), None)
def tool_version():
"""ft-handrec plus the checkout's git describe, for session.json and the manifest."""
try:
out = subprocess.run(["git", "-C", REPO, "describe", "--always", "--dirty", "--tags"],
capture_output=True, text=True, timeout=5)
described = out.stdout.strip()
except (OSError, subprocess.TimeoutExpired):
described = ""
return "ft-handrec " + (described or "unknown")
def free_bytes(path):
"""Free space on the file system that holds path (or its nearest existing parent)."""
while path and not os.path.exists(path):
path = os.path.dirname(path)
try:
return shutil.disk_usage(path or "/").free
except OSError:
return 0
def tree_stat(path):
"""(bytes, newest mtime) of the files under path."""
total, newest = 0, 0.0
for root, _, files in os.walk(path):
for name in files:
try:
st = os.lstat(os.path.join(root, name))
except OSError:
continue
total += st.st_size
newest = max(newest, st.st_mtime)
return total, newest
def tree_bytes(path):
return tree_stat(path)[0]
def in_ranges(t, ranges):
return any(a <= t <= b for a, b in ranges)
def export_jsonl(src, dst, ranges, keep_controllers):
"""Copy a take's poses.jsonl or prompts.jsonl for export:
- poses in the deleted ranges are left out, and the live tracker's feedback there (the
prompt timeline stays: it says what was asked, and shows nothing);
- without controllers (the checklist's "none"), the controllers' poses are null and feedback
carries no controller state: controllers lying about still get logged, and those poses
would read as hands' ground truth.
Lines that don't parse are copied as they are (validate.py reports them)."""
poses = os.path.basename(src) == "poses.jsonl"
with open(src, encoding="utf-8") as f, open(dst, "w", encoding="utf-8", newline="\n") as out:
for line in f:
try:
obj = json.loads(line)
except ValueError:
out.write(line)
continue
if not isinstance(obj, dict):
out.write(line)
continue
t = obj.get("t")
gone = isinstance(t, int) and in_ranges(t, ranges)
if poses:
if gone:
continue
if not keep_controllers:
obj["left"] = obj["right"] = None
elif obj.get("event") == "feedback":
if gone:
continue
if not keep_controllers:
obj.pop("controller", None)
out.write(json.dumps(obj, separators=(", ", ": ")) + "\n")
def merge_ranges(ranges):
"""Sorted, with overlapping or touching ranges joined."""
out = []
for a, b in sorted((min(a, b), max(a, b)) for a, b in ranges):
if out and a <= out[-1][1] + 1:
out[-1][1] = max(out[-1][1], b)
else:
out.append([a, b])
return out
# ---------------------------------------------------------------- one take's recording
class TakeIndex:
"""Where each set of a take's recording is, without reading pixels. Sets are numbered
across the parts (sets.bin, sets-2.bin, ...) in order."""
def __init__(self, take_dir):
self.dir = take_dir
self.parts = self._parts(take_dir)
self.sets = [] # (part, offset, bytes, time_ns): time_ns is the cameras' earliest dqbuf_ns
self.part_starts = [] # index of each part's first set
self.cams = [] # the first set's [{name, width, height}], side cameras named right
# per part: are its side cameras named the wrong way round (sides.py)? read_set and
# read_raw rename them.
session = read_json(os.path.join(os.path.dirname(os.path.dirname(take_dir)), "session.json"))
take = read_json(os.path.join(take_dir, "take.json"))
self.swapped = sides.session_sides(session).get("swapped")
self.names_swapped = [sides.part_names_swapped(take, os.path.basename(p)) for p in self.parts]
self.rename = [sides.needs_rename(self.swapped, n) for n in self.names_swapped]
for p, path in enumerate(self.parts):
self.part_starts.append(len(self.sets))
self._index(p, path)
@staticmethod
def _parts(take_dir):
found = []
try:
names = os.listdir(take_dir)
except OSError:
return []
for name in names:
m = PART_RE.match(name)
if m:
found.append((int(m.group(1) or 1), os.path.join(take_dir, name)))
return [path for _, path in sorted(found)]
def _index(self, p, path):
try:
size = os.path.getsize(path)
f = open(path, "rb")
except OSError:
return
with f:
off = 0
while off + HDR.size <= size:
f.seek(off)
head = f.read(HDR.size)
if len(head) < HDR.size:
break
magic, ncams, nbytes = HDR.unpack(head)
# A truncated last set (the recorder was killed mid-write) ends the part.
if magic[:7] != MAGIC or not 0 < ncams <= MAX_CAMS or nbytes < HDR.size or off + nbytes > size:
break
cams = f.read(CAM.size * ncams)
if len(cams) < CAM.size * ncams:
break
fields = [CAM.unpack_from(cams, i * CAM.size) for i in range(ncams)]
if not self.cams:
self.cams = [{"name": self._name(p, n), "width": w, "height": h} for n, w, h, _, _ in fields]
self.sets.append((p, off, nbytes, min(c[4] for c in fields)))
off += nbytes
def _name(self, p, raw):
name = raw.split(b"\0", 1)[0].decode(errors="replace")
return sides.other_name(name) if self.rename[p] else name
def renamed_sets(self, keep=None):
"""How many of the sets (all, or the indices in keep) read renamed."""
return sum(1 for i in (range(len(self.sets)) if keep is None else keep) if self.rename[self.sets[i][0]])
def __len__(self):
return len(self.sets)
def time_ns(self, i):
return self.sets[i][3]
def duration_s(self):
"""Recorded time: each part's first to last set, so pauses don't count."""
total = 0
ends = self.part_starts[1:] + [len(self.sets)]
for start, end in zip(self.part_starts, ends):
if end > start:
total += self.sets[end - 1][3] - self.sets[start][3]
return total / 1e9
def bytes(self):
return sum(s[2] for s in self.sets)
def read_set(self, i, only=None):
"""Set i's cameras: [{name, width, height, capture_ns, dqbuf_ns, pixels}], pixels as raw
8-bit grey bytes (width x height, packed). only: a camera name, to read just that one."""
p, off, nbytes, _ = self.sets[i]
with open(self.parts[p], "rb") as f:
f.seek(off)
ncams = HDR.unpack(f.read(HDR.size))[1]
heads = f.read(CAM.size * ncams)
out = []
px_off = off + HDR.size + CAM.size * ncams
for k in range(ncams):
name, w, h, capture_ns, dqbuf_ns = CAM.unpack_from(heads, k * CAM.size)
name = self._name(p, name)
if only is None or name == only:
f.seek(px_off)
out.append({"name": name, "width": w, "height": h, "capture_ns": capture_ns,
"dqbuf_ns": dqbuf_ns, "pixels": f.read(w * h)})
px_off += w * h
return out
def read_raw(self, i):
"""Set i's whole record, as it is in the file but with the side cameras named right."""
p, off, nbytes, _ = self.sets[i]
with open(self.parts[p], "rb") as f:
f.seek(off)
record = f.read(nbytes)
return sides.rename_record(record) if self.rename[p] else record
_index_cache = {}
_index_lock = threading.Lock()
def take_index(take_dir):
"""A TakeIndex, cached until one of the take's recording files, its take.json or its
session.json (the side cameras' decision) changes size or time."""
key_parts = []
meta = [os.path.join(take_dir, "take.json"), os.path.join(os.path.dirname(os.path.dirname(take_dir)), "session.json")]
for path in TakeIndex._parts(take_dir) + meta:
try:
st = os.stat(path)
key_parts.append((path, st.st_size, st.st_mtime_ns))
except OSError:
pass
key = tuple(key_parts)
with _index_lock:
cached = _index_cache.get(take_dir)
if cached and cached[0] == key:
return cached[1]
index = TakeIndex(take_dir)
with _index_lock:
_index_cache[take_dir] = (key, index)
return index
# ---------------------------------------------------------------- the store
class Store:
def __init__(self, base=DEFAULT_BASE):
self.base = os.path.abspath(os.path.expanduser(base))
self.sessions_dir = os.path.join(self.base, "sessions")
self.exports_dir = os.path.join(self.base, "exports")
self.profile_path = os.path.join(self.base, "profile.json")
# --- paths, checked: ids come from the window, so nothing may climb out of the base
def session_dir(self, session):
if not SESSION_RE.match(session or ""):
raise ValueError(f"not a session id: {session!r}")
return os.path.join(self.sessions_dir, session)
def take_dir(self, session, take):
if not take or "/" in take or take.startswith("."):
raise ValueError(f"not a take id: {take!r}")
return os.path.join(self.session_dir(session), "takes", take)
def export_dir(self, session):
self.session_dir(session) # checks the id
return os.path.join(self.exports_dir, session)
def profile(self):
return read_json(self.profile_path)
# --- listing
def sessions(self):
"""Newest first: [{id, started, takes, bytes, lighting, status, dry_run, contributor, exported,
export_stale (changed since), export_bytes}]."""
out = []
try:
names = os.listdir(self.sessions_dir)
except OSError:
return out
for sid in names:
path = os.path.join(self.sessions_dir, sid)
if not SESSION_RE.match(sid) or not os.path.isdir(path):
continue
meta = read_json(os.path.join(path, "session.json"))
size, changed = tree_stat(path)
manifest = os.path.join(self.export_dir(sid), "manifest.json")
exported = os.path.getmtime(manifest) if os.path.isfile(manifest) else 0.0
out.append({"id": sid, "started": meta.get("started", ""), "takes": len(self.take_ids(sid)),
"bytes": size, "contributor": meta.get("contributor", ""),
"lighting": (meta.get("lighting") or {}).get("chosen", ""),
"status": meta.get("status", ""), "dry_run": bool(meta.get("dry_run")),
"exported": bool(exported), "export_stale": bool(exported) and changed > exported,
"export_bytes": tree_bytes(self.export_dir(sid)) if exported else 0})
return sorted(out, key=lambda s: s["id"], reverse=True)
def take_ids(self, session):
try:
names = os.listdir(os.path.join(self.session_dir(session), "takes"))
except OSError:
return []
return sorted(n for n in names if not n.startswith(".")
and os.path.isdir(os.path.join(self.session_dir(session), "takes", n)))
def takes(self, session):
"""[{id, section, title, status, sets, deleted_sets, ranges, duration_s, bytes, cams}]."""
out = []
for tid in self.take_ids(session):
path = self.take_dir(session, tid)
meta = read_json(os.path.join(path, "take.json"))
index = take_index(path)
ranges = merge_ranges(meta.get("deleted") or [])
out.append({"id": tid, "section": meta.get("section", tid.split("-", 1)[-1]),
"title": meta.get("title") or tid, "status": meta.get("status", "recording"),
"sets": len(index), "parts": len(index.parts),
"deleted_sets": sum(1 for s in index.sets if in_ranges(s[3], ranges)),
"ranges": ranges, "duration_s": index.duration_s(), "bytes": index.bytes(),
"cams": [c["name"] for c in index.cams]})
return out
def take_meta(self, session, take):
return read_json(os.path.join(self.take_dir(session, take), "take.json"))
# --- deleted ranges
def ranges(self, session, take):
return merge_ranges(self.take_meta(session, take).get("deleted") or [])
def _set_ranges(self, session, take, ranges):
path = os.path.join(self.take_dir(session, take), "take.json")
meta = read_json(path)
meta["deleted"] = merge_ranges(ranges)
write_json(path, meta)
return meta["deleted"]
def delete_range(self, session, take, from_ns, to_ns):
"""Leave sets from from_ns to to_ns (dqbuf_ns, inclusive) out of the export."""
return self._set_ranges(session, take, self.ranges(session, take) + [[int(from_ns), int(to_ns)]])
def restore_range(self, session, take, i):
"""Take deleted range i (in ranges()' order) back."""
ranges = self.ranges(session, take)
if 0 <= i < len(ranges):
del ranges[i]
return self._set_ranges(session, take, ranges)
# --- deleting files
def delete_take(self, session, take):
path = self.take_dir(session, take)
if os.path.isdir(path):
shutil.rmtree(path)
meta_path = os.path.join(self.session_dir(session), "session.json")
meta = read_json(meta_path)
if take in (meta.get("takes") or []):
meta["takes"] = [t for t in meta["takes"] if t != take]
meta.setdefault("deleted_takes", []).append(take)
write_json(meta_path, meta)
def delete_session(self, session):
"""The session and its export, if any."""
for path in (self.session_dir(session), self.export_dir(session)):
if os.path.isdir(path):
shutil.rmtree(path)
def delete_export(self, session):
path = self.export_dir(session)
if os.path.isdir(path):
shutil.rmtree(path)
# --- export
def sides(self, session, swapped=None):
"""session.json's side camera decision (sides.py) plus each take's parts; with swapped
(True/False), record that by hand first ("decided_by": "manual"). No set is rewritten:
reading and export rename."""
path = os.path.join(self.session_dir(session), "session.json")
meta = read_json(path)
if not meta:
raise RuntimeError(f"no session {session}")
if swapped is not None:
old = sides.session_sides(meta)
new = {"swapped": bool(swapped), "decided_by": "manual",
"decided_at": datetime.datetime.now().astimezone().isoformat(timespec="seconds")}
if old.get("swapped") is not None:
new["replaced"] = old
meta["sides"] = new
write_json(path, meta)
out = {"sides": sides.session_sides(meta), "takes": {}}
for tid in self.take_ids(session):
index = take_index(self.take_dir(session, tid))
out["takes"][tid] = {os.path.basename(p): {"names_swapped": n, "renamed_when_read": r}
for p, n, r in zip(index.parts, index.names_swapped, index.rename)}
return out
def export(self, session, progress=None, cancel=None, keep_notes=False, low_priority=True):
"""Write exports/<session>/ (DESIGN.md "Export"): manifest.json, calibration.json, per
take prompts.jsonl, poses.jsonl, take.json and sets.bin.zst (sets in deleted ranges
left out), then SHA256SUMS. progress(fraction 0..1, text) is called as it goes;
cancel() (or cancel.is_set()) returning true stops it, raising Cancelled. Nothing is
left behind on failure or cancel. Returns the export's path.
low_priority: run this thread at nice 19 as well as zstd (Linux nice is per thread)."""
zstd = find_zstd()
if not zstd:
raise RuntimeError("zstd isn't installed (in the dev container: sudo dnf install zstd)")
cancelled = getattr(cancel, "is_set", cancel) or (lambda: False)
report = progress or (lambda fraction, text: None)
src = self.session_dir(session)
if not os.path.isdir(src):
raise RuntimeError(f"no session {session}")
if low_priority:
try:
os.setpriority(os.PRIO_PROCESS, threading.get_native_id(), 19)
except OSError:
pass
final = self.export_dir(session)
work = final + ".partial"
if os.path.isdir(work):
shutil.rmtree(work)
os.makedirs(work)
try:
self._export(session, src, work, zstd, report, cancelled, keep_notes)
if os.path.isdir(final):
shutil.rmtree(final)
os.replace(work, final)
except BaseException:
shutil.rmtree(work, ignore_errors=True)
raise
report(1.0, "Done")
return final
def _export(self, session, src, work, zstd, report, cancelled, keep_notes):
profile = self.profile()
meta = read_json(os.path.join(src, "session.json"))
meta.pop("uploads", None) # earlier uploads' records (hub.py) aren't part of the contribution
takes = self.takes(session)
total = sum(t["bytes"] for t in takes) or 1
done = 0
take_entries = []
keep_controllers = (meta.get("checklist") or {}).get("controllers") == "straps"
for t in takes:
if cancelled():
raise Cancelled()
tdir = self.take_dir(session, t["id"])
out = os.path.join(work, "takes", t["id"])
os.makedirs(out)
ranges = t["ranges"]
for name in ("prompts.jsonl", "poses.jsonl"):
if os.path.isfile(os.path.join(tdir, name)):
export_jsonl(os.path.join(tdir, name), os.path.join(out, name), ranges, keep_controllers)
index = take_index(tdir)
keep = [i for i in range(len(index)) if not in_ranges(index.time_ns(i), ranges)]
# one file, named right where the decision is known (sides.py): its names_swapped is
# then the session's swapped; unknown, it's the parts' own (None if they differ)
if index.swapped is not None:
names_swapped = bool(index.swapped)
else:
names_swapped = index.names_swapped[0] if len(set(index.names_swapped)) == 1 else None
take_meta = read_json(os.path.join(tdir, "take.json"))
if take_meta:
take_meta["parts"] = {"sets.bin": {"names_swapped": names_swapped}}
write_json(os.path.join(out, "take.json"), take_meta)
entry = {"id": t["id"], "section": t["section"], "title": t["title"], "status": t["status"],
"sets": len(keep), "sets_deleted": len(index) - len(keep), "cameras": index.cams,
"duration_s": round(t["duration_s"], 2), "file": None,
"sides": {"names_swapped": names_swapped, "renamed_sets": index.renamed_sets(keep)}}
done += index.bytes() - sum(index.sets[i][2] for i in keep) # deleted sets count as done
if keep:
entry["file"] = "takes/%s/sets.bin.zst" % t["id"]
def step(nbytes, title=t["title"]):
nonlocal done
done += nbytes
report(min(done / total, 0.99), f"Compressing {title}")
entry["raw_bytes"] = self._compress(index, keep, zstd, os.path.join(out, "sets.bin.zst"),
step, cancelled)
take_entries.append(entry)
if cancelled():
raise Cancelled()
for name in ("calibration.json", "device.json"):
if os.path.isfile(os.path.join(src, name)):
shutil.copyfile(os.path.join(src, name), os.path.join(work, name))
shown_profile = json.loads(json.dumps(profile))
if not keep_notes and isinstance(shown_profile.get("optional"), dict):
shown_profile["optional"].pop("notes", None)
manifest = {"schema": EXPORT_SCHEMA, "tool": tool_version(),
"exported": datetime.datetime.now().astimezone().isoformat(timespec="seconds"),
"session_id": session, "contributor": profile.get("contributor", meta.get("contributor", "")),
"consent_version": (profile.get("consent") or {}).get("version", ""),
"profile": shown_profile, "session": meta, "takes": take_entries}
write_json(os.path.join(work, "manifest.json"), manifest)
report(0.995, "Writing checksums")
sums = []
for root, _, files in os.walk(work):
for name in files:
path = os.path.join(root, name)
sums.append((os.path.relpath(path, work), sha256_file(path, cancelled)))
with open(os.path.join(work, "SHA256SUMS"), "w") as f:
for rel, digest in sorted(sums):
f.write(f"{digest} {rel}\n")
@staticmethod
def _compress(index, keep, zstd, dest, step, cancelled):
"""Stream the kept sets through zstd into dest. Returns the uncompressed size."""
raw = 0
with open(dest, "wb") as out:
proc = subprocess.Popen(["nice", "-n", "19", zstd] + ZSTD_ARGS, stdin=subprocess.PIPE, stdout=out,
stderr=subprocess.PIPE)
try:
for i in keep:
if cancelled():
raise Cancelled()
record = index.read_raw(i)
proc.stdin.write(record)
raw += len(record)
step(len(record))
proc.stdin.close()
err = proc.stderr.read().decode(errors="replace").strip()
if proc.wait() != 0:
raise RuntimeError(f"zstd failed: {err or proc.returncode}")
except BaseException:
proc.kill()
proc.wait()
raise
finally:
proc.stderr.close()
return raw
def sha256_file(path, cancelled=lambda: False):
h = hashlib.sha256()
with open(path, "rb") as f:
while chunk := f.read(CHUNK):
if cancelled():
raise Cancelled()
h.update(chunk)
return h.hexdigest()
def human_bytes(n):
for unit in ("B", "KB", "MB", "GB"):
if n < 1000 or unit == "GB":
return f"{n:.0f} {unit}" if unit == "B" else f"{n:.1f} {unit}"
n /= 1000
return f"{n:.1f} TB"
def main():
ap = argparse.ArgumentParser(description="List, check and export hand recorder sessions.")
ap.add_argument("--base", default=DEFAULT_BASE)
sub = ap.add_subparsers(dest="cmd", required=True)
sub.add_parser("list")
sub.add_parser("takes").add_argument("session")
sub.add_parser("export").add_argument("session")
sp = sub.add_parser("sides", help="show (or record) which way round the side cameras were")
sp.add_argument("session")
sp.add_argument("--set", choices=("swapped", "named"),
help="record the decision by hand (e.g. from tools/check_sides.py on a take)")
a = ap.parse_args()
store = Store(a.base)
if a.cmd == "list":
for s in store.sessions():
print(f"{s['id']} {s['takes']} takes {human_bytes(s['bytes'])} {s['lighting'] or '-'}"
+ (" exported" if s["exported"] else ""))
elif a.cmd == "takes":
for t in store.takes(a.session):
print(f"{t['id']} {t['status']} {t['sets']} sets ({t['deleted_sets']} deleted) "
f"{t['duration_s']:.1f} s {human_bytes(t['bytes'])}")
elif a.cmd == "sides":
print(json.dumps(store.sides(a.session, None if a.set is None else a.set == "swapped"), indent=1))
else:
path = store.export(a.session, progress=lambda f, text: print(f"\r{f * 100:5.1f}% {text:40.40}", end="",
flush=True))
print(f"\n{path} {human_bytes(tree_bytes(path))}")
if __name__ == "__main__":
main()
+228
View File
@@ -0,0 +1,228 @@
#!/usr/bin/env python3
"""Tests for the session's camera check: the preflight that keeps a session from starting
with the upper cameras off, and the early no-hands stop in the hand-size section's first step
(dry runs with a made-up hands file; no processes, no real cameras).
python3 hands/rec/tests/test_nohands.py
"""
import json
import os
import sys
import threading
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(HERE))
sys.path.insert(0, HERE)
import session # noqa: E402
import camcheck # noqa: E402 (session.py put hands/ on the path)
from test_session import SessionBase # noqa: E402
SCRIPT = {
"version": 1, "intro_s": 1, "between_s": 1,
"welcome": {"title": "Test", "seconds": 1, "text": "A test."},
"done": {"title": "Done", "seconds": 0, "text": "Done."},
"stopped": {"title": "Stopped", "seconds": 0, "text": "Stopped."},
"sections": [
{"id": "hand-size", "title": "Hand size", "intro": "Hand size.", "go": "Hold",
"defaults": {"hands": "both"},
"prompts": [{"text": "Both hands flat.", "seconds": 6, "pose": "flat"},
{"text": "Backs.", "seconds": 2, "pose": "flat-back"}]}]}
HAND = {"palm": [0.0, 0.0, -0.4], "palm_m": 0.4, "tip": [0.0, 0.05, -0.45]}
DEGRADED = {"status": "degraded", "reason": camcheck.VCINT_REASON, "summary": camcheck.DEGRADED_VCINT,
"evidence": ["17:02:47 Failed to load VCINT FPGA image when passthrough cameras are connected"]}
OK = {"status": "ok", "reason": "4 tracking cameras running", "summary": "ok", "evidence": []}
class FakeHands:
"""Stands in for the hands file: what read() gives can change mid-session."""
def __init__(self, value):
self.value = value
self.lock = threading.Lock()
def set(self, value):
with self.lock:
self.value = value
def read(self):
with self.lock:
return None if self.value is None else dict(self.value)
class NoHandsTest(SessionBase):
def setUp(self):
super().setUp()
with open(self.script, "w") as f:
json.dump(SCRIPT, f)
def events(self, s):
with open(os.path.join(s.session_dir, "takes", "01-hand-size", "prompts.jsonl")) as f:
# feedback lines (twice a second, as the tracker publishes) aren't what's tested here
return [e for e in map(json.loads, f) if e["event"] != "feedback"]
def run_to_first_hold(self, hands, camera=DEGRADED, **kw):
s = self.session(hands_reader=hands, speed=3, **kw)
s.camera_check_fn = lambda: camera
s.start()
self.waiting(s, "starting")
s.next_step()
self.waiting(s, "intro")
s.next_step()
self.waiting(s, "ready", "Both hands flat.")
s.next_step()
return s
def session_json(self, s):
with open(os.path.join(s.session_dir, "session.json")) as f:
return json.load(f)
def log(self, s):
with open(os.path.join(s.session_dir, "session.log")) as f:
return f.read()
def test_no_hands_then_redo(self):
hands = FakeHands({"left": None, "right": None}) # the tracker publishes, sees nothing
s = self.run_to_first_hold(hands)
st = self.wait_for(s, lambda st: st["state"] == "nohands" and st["waiting"], "the no-hands stop")
self.assertTrue(st["nohands"])
self.assertTrue(st["can_redo"])
self.assertEqual(st["camera"]["status"], "degraded")
self.assertIn(camcheck.USER_TEXT, st["prompt"])
self.assertIn("panel: title " + session.NO_HANDS_TITLE, self.panel)
hands.set({"left": HAND, "right": HAND})
s.next_step() # try again: straight to the countdown, no second ready wait
self.wait_for(s, lambda st: st["state"] == "countdown", "the countdown again")
self.waiting(s, "ready", "Backs.")
s.next_step()
s.join(20)
self.assertEqual(s.state, "done")
ev = self.events(s)
names = [e["event"] for e in ev]
self.assertEqual(names, ["take", "ready", "prompt", "wait", "nohands", "redo",
"ready", "prompt", "wait", "ready", "prompt", "wait", "end"])
nohands, redo = ev[4], ev[5]
self.assertGreaterEqual(nohands["reads"], session.HANDS_CHECK_MIN_READS)
self.assertEqual(redo["from"], ev[1]["t"]) # the failed try gets no labels
self.assertTrue(ev[2]["t"] < redo["to"])
# the retry wasn't stopped: a hand was seen
self.assertRegex(self.log(s), r"hands check hand-size/flat/both: a hand in [1-9][0-9]* of")
self.assertNotIn("stop_reason", self.session_json(s))
def test_no_hands_then_stop(self):
s = self.run_to_first_hold(FakeHands({"left": None, "right": None}))
self.wait_for(s, lambda st: st["state"] == "nohands" and st["waiting"], "the no-hands stop")
s.stop(wait=10)
self.assertEqual(s.state, "stopped")
sj = self.session_json(s)
self.assertIn("no hands were seen", sj["stop_reason"])
self.assertIn(camcheck.DEGRADED_VCINT, sj["stop_reason"])
self.assertIn(camcheck.USER_TEXT, s._status["prompt"])
self.assertIn("camera check: " + camcheck.DEGRADED_VCINT, self.log(s))
def test_redo_key_and_skip(self):
hands = FakeHands({"left": None, "right": None})
s = self.run_to_first_hold(hands, camera=OK)
st = self.wait_for(s, lambda st: st["state"] == "nohands" and st["waiting"], "the no-hands stop")
self.assertIn("The camera check found nothing wrong", st["prompt"])
s.redo() # R is the same as Next there
self.wait_for(s, lambda st: st["state"] == "countdown", "the countdown again")
self.wait_for(s, lambda st: st["state"] == "nohands" and st["waiting"], "no hands again")
s.skip() # S skips the section; the no-hands note doesn't stick
s.join(20)
self.assertEqual(s.state, "done")
self.assertNotIn("stop_reason", self.session_json(s))
self.assertEqual([e["event"] for e in self.events(s)].count("nohands"), 2)
def test_hand_seen_sometimes(self):
hands = FakeHands({"left": None, "right": None})
s = self.run_to_first_hold(hands)
self.wait_for(s, lambda st: st["state"] == "running", "the hold")
hands.set({"left": HAND, "right": None}) # one hand, for part of the hold: fine
self.waiting(s, "ready", "Backs.")
s.next_step()
s.join(20)
self.assertEqual(s.state, "done")
self.assertNotIn("nohands", [e["event"] for e in self.events(s)])
def test_no_tracker_cant_tell(self):
s = self.run_to_first_hold(FakeHands(None)) # nothing published: can't tell, go on
self.waiting(s, "ready", "Backs.")
s.next_step()
s.join(20)
self.assertEqual(s.state, "done")
self.assertNotIn("nohands", [e["event"] for e in self.events(s)])
self.assertIn("can't tell", self.log(s))
def test_only_the_first_step(self):
hands = FakeHands({"left": HAND, "right": HAND})
s = self.run_to_first_hold(hands)
self.wait_for(s, lambda st: st["state"] == "running", "the hold")
self.waiting(s, "ready", "Backs.")
hands.set({"left": None, "right": None}) # gone in step 2: notes, but no stop
s.next_step()
s.join(20)
self.assertEqual(s.state, "done")
self.assertNotIn("nohands", [e["event"] for e in self.events(s)])
def test_auto_mode(self):
hands = FakeHands({"left": None, "right": None})
s = self.session(hands_reader=hands, speed=3, auto=True)
s.camera_check_fn = lambda: DEGRADED
s.start()
self.wait_for(s, lambda st: st["state"] == "nohands" and st["waiting"], "the no-hands stop")
hands.set({"left": HAND, "right": HAND})
s.next_step()
s.join(20)
self.assertEqual(s.state, "done")
names = [e["event"] for e in self.events(s)]
self.assertEqual(names, ["take", "prompt", "prompt", "pause", "nohands", "redo", "resume", "prompt",
"prompt", "end"])
class PreflightTest(SessionBase):
def test_degraded_stops_before_anything(self):
s = self.session()
s.dry_run = False # as a real session; the check is the only step run
s.camera_check_fn = lambda: DEGRADED
self.assertTrue(s._preflight())
self.assertEqual(s.state, "error")
self.assertEqual(s._status["error"], camcheck.USER_TEXT)
self.assertEqual(s.session_dir, "") # no session folder made
self.assertFalse(os.path.exists(os.path.join(self.tmp, "base", "sessions")))
def test_other_degraded_text(self):
r = dict(DEGRADED, reason="only 3 of 4 tracking cameras running")
self.assertIn("only 3 of 4", session.camera_text(r))
self.assertEqual(session.camera_text(OK), "")
self.assertEqual(session.camera_text({"status": "unknown"}), "")
self.assertEqual(session.camera_text(None), "")
def test_ok_unknown_ignored(self):
for result in (OK, {"status": "unknown", "summary": "unknown: x", "evidence": []}):
s = self.session()
s.dry_run = False
s.camera_check_fn = lambda: result
self.assertFalse(s._preflight())
s = self.session(check_cameras=False)
s.dry_run = False
s.camera_check_fn = lambda: DEGRADED
self.assertFalse(s._preflight()) # --ignore-cameras
s = self.session(ring="/tmp/some-ring")
s.dry_run = False
s.camera_check_fn = lambda: DEGRADED
self.assertFalse(s._preflight()) # ft-ringplay's frames: no headset cameras involved
def test_camera_check_never_raises(self):
orig = camcheck.check
try:
camcheck.check = lambda: 1 / 0
r = session.camera_check()
finally:
camcheck.check = orig
self.assertEqual(r["status"], "unknown")
if __name__ == "__main__":
unittest.main()
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env python3
"""main.qml against ft_handrec.Backend: every backend.name(...) the window calls is a slot, and
every backend.name it reads is a property or a slot. A method that lost its @Slot shows up in
QML only as "is not a function" when its button is pressed (2026-10-03: Export did nothing).
Needs PySide6 (the dev container); skipped without it.
python3 hands/rec/tests/test_qml_backend.py
"""
import os
import re
import sys
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
REC = os.path.dirname(HERE)
sys.path.insert(0, REC)
class QmlBackendTest(unittest.TestCase):
def setUp(self):
try:
import ft_handrec
except ImportError as e:
self.skipTest(f"no PySide6: {e}")
meta = self.meta = ft_handrec.Backend.staticMetaObject
self.slots = {bytes(meta.method(i).name()).decode() for i in range(meta.methodCount())}
self.props = {meta.property(i).name() for i in range(meta.propertyCount())}
with open(os.path.join(REC, "main.qml")) as f:
self.qml = f.read()
def test_calls_are_slots(self):
called = set(re.findall(r"\bbackend\.(\w+)\s*\(", self.qml))
self.assertTrue(called)
self.assertEqual(sorted(called - self.slots), [], "called from main.qml but not a slot")
def test_call_arity(self):
"""Each backend.name(a, b) call passes as many arguments as some slot of that name takes
(a decorator left at the old count fails only when the button is pressed)."""
arity = {}
meta = self.meta
for i in range(meta.methodCount()):
mm = meta.method(i)
arity.setdefault(bytes(mm.name()).decode(), set()).add(mm.parameterCount())
bad = []
for m in re.finditer(r"\bbackend\.(\w+)\s*\(", self.qml):
depth, args, k, seen = 1, 0, m.end(), False
while depth and k < len(self.qml):
c = self.qml[k]
if c in "([{":
depth += 1
elif c in ")]}":
depth -= 1
elif c == "," and depth == 1:
args += 1
elif not c.isspace() and depth >= 1:
seen = True
k += 1
n = args + 1 if seen else 0
if m.group(1) in arity and n not in arity[m.group(1)]:
bad.append("%s: %d arguments, slots take %s" % (m.group(1), n, sorted(arity[m.group(1)])))
self.assertEqual(bad, [])
def test_reads_exist(self):
read = set(re.findall(r"\bbackend\.(\w+)\b(?!\s*\()", self.qml))
self.assertTrue(read)
self.assertEqual(sorted(read - self.props - self.slots), [], "read in main.qml but not on Backend")
if __name__ == "__main__":
unittest.main()
+634
View File
@@ -0,0 +1,634 @@
#!/usr/bin/env python3
"""Tests for session.py's step mode (dry runs, no processes): the ready, countdown and hold
timeline in prompts.jsonl, R (redo), the timed flow (--auto), the pose pictures' display rule,
the length estimates, and a take recorded in many parts through review, export and validate.
python3 hands/rec/tests/test_session.py
"""
import json
import os
import shutil
import sys
import tempfile
import struct
import time
import unittest
from unittest import mock
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(HERE))
import session # noqa: E402
import takes # noqa: E402
import validate # noqa: E402
from test_validate import fhset, make_session, SESSION # noqa: E402
SCRIPT = {
"version": 1, "intro_s": 1, "between_s": 1,
"welcome": {"title": "Test", "seconds": 1, "text": "A test."},
"done": {"title": "Done", "seconds": 0, "text": "Done."},
"stopped": {"title": "Stopped", "seconds": 0, "text": "Stopped."},
"sections": [
{"id": "poses", "title": "Poses", "intro": "Some poses.", "go": "Hold",
"prompts": [{"text": "Fist.", "seconds": 4, "hands": "left", "pose": "fist", "distance": "near",
"position": "left"},
{"text": "Open.", "seconds": 4, "hands": "both", "pose": "open"}]}]}
class SessionBase(unittest.TestCase):
"""Dry-run sessions of SCRIPT, steered from the test."""
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="handrec-session-test-")
self.script = os.path.join(self.tmp, "script.json")
with open(self.script, "w") as f:
json.dump(SCRIPT, f)
self.panel = []
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def session(self, **kw):
kw.setdefault("speed", 10)
s = session.Session(os.path.join(self.tmp, "base"), {}, {}, "room", self.script, dry_run=True,
poses_dir=os.path.join(self.tmp, "no-poses"), **kw)
s.print = self.panel.append
return s
def wait_for(self, s, pred, what, timeout=10):
end = time.monotonic() + timeout
while time.monotonic() < end:
st = dict(s._status)
if pred(st):
return st
time.sleep(0.005)
self.fail("timed out waiting for %s: %s" % (what, s._status))
def waiting(self, s, state, prompt=None):
return self.wait_for(s, lambda st: st["state"] == state and st["waiting"]
and (prompt is None or st["prompt"] == prompt), "%s %s" % (state, prompt or ""))
def events(self, s):
with open(os.path.join(s.session_dir, "takes", "01-poses", "prompts.jsonl")) as f:
return [json.loads(line) for line in f]
class SessionTest(SessionBase):
def test_step_flow(self):
s = self.session(next_after=0.0)
s.start()
s.join(20)
self.assertEqual(s.state, "done")
ev = self.events(s)
self.assertEqual([e["event"] for e in ev],
["take", "ready", "prompt", "wait", "ready", "prompt", "wait", "end"])
self.assertEqual(ev[1]["id"], ev[2]["id"])
self.assertEqual(ev[1]["seconds"], session.COUNTDOWN_S)
self.assertTrue(ev[1]["t"] < ev[2]["t"] < ev[3]["t"] < ev[4]["t"])
# the countdown is recorded (3 s at 10x speed), and the hold after it
self.assertGreater(ev[2]["t"] - ev[1]["t"], 0.25e9)
with open(os.path.join(s.session_dir, "session.json")) as f:
self.assertEqual(json.load(f)["mode"], "step")
# a clock sample as each part starts (2 steps: 2 parts), for capture_ns (RAW) -> MONOTONIC
with open(os.path.join(s.session_dir, "takes", "01-poses", "take.json")) as f:
clock = json.load(f)["clock"]
self.assertEqual(len(clock), 2)
self.assertTrue(all(len(c) == 2 and all(isinstance(v, int) for v in c) for c in clock))
self.assertLess(clock[0][0], clock[1][0])
# the panel: Ready?, then the countdown, then the section's word for the hold, the diagram
self.assertIn("panel: action " + session.READY_TEXT, self.panel)
self.assertLess(self.panel.index("panel: big 3"), self.panel.index("panel: big 1"))
self.assertIn("panel: big Hold", self.panel)
self.assertIn("panel: where left near", self.panel)
self.assertIn("panel: rec on", self.panel)
def test_redo(self):
s = self.session()
s.start()
self.waiting(s, "starting")
s.next_step()
self.waiting(s, "intro")
s.redo() # nothing to do again yet: dropped
s.next_step()
st = self.waiting(s, "ready", "Fist.")
self.assertFalse(st["can_redo"])
s.next_step()
self.wait_for(s, lambda st: st["state"] == "running", "the hold")
s.redo() # during the hold: it starts again
self.waiting(s, "ready", "Fist.")
s.next_step()
st = self.waiting(s, "ready", "Open.")
self.assertTrue(st["can_redo"])
s.redo() # at the next step's ready screen: the one before goes again
self.waiting(s, "ready", "Fist.")
s.next_step()
self.waiting(s, "ready", "Open.")
s.next_step()
s.join(20)
self.assertEqual(s.state, "done")
ev = self.events(s)
names = [e["event"] for e in ev]
self.assertEqual(names, ["take", "ready", "prompt", "redo", "wait", "ready", "prompt", "wait", "redo",
"ready", "prompt", "wait", "ready", "prompt", "wait", "end"])
first, second = ev[3], ev[8]
self.assertEqual(first["id"], "poses/fist/left/near/left")
self.assertEqual(first["from"], ev[1]["t"]) # from its countdown
self.assertTrue(ev[2]["t"] < first["to"] <= ev[4]["t"])
self.assertEqual((second["from"], second["id"]), (ev[5]["t"], first["id"]))
self.assertTrue(ev[6]["t"] < second["to"] <= ev[7]["t"])
# what labels keep: prompts outside every redo range
kept = [e["id"] for e in ev if e["event"] == "prompt"
and not any(r["from"] <= e["t"] <= r["to"] for r in ev if r["event"] == "redo")]
self.assertEqual(kept, ["poses/fist/left/near/left", "poses/open/both"])
def test_pause_while_waiting(self):
s = self.session()
s.start()
self.waiting(s, "starting")
s.next_step()
self.waiting(s, "intro")
s.next_step()
self.waiting(s, "ready", "Fist.")
s.pause()
self.wait_for(s, lambda st: st["state"] == "paused", "paused")
s.next_step() # ignored while paused
s.resume()
st = self.waiting(s, "ready", "Fist.")
s.stop(wait=10)
self.assertEqual(s.state, "stopped")
# nothing recorded: no take
self.assertEqual(os.listdir(os.path.join(s.session_dir, "takes")), [])
def test_auto(self):
s = self.session(auto=True, speed=20)
s.start()
s.join(20)
self.assertEqual(s.state, "done")
ev = self.events(s)
self.assertEqual([e["event"] for e in ev], ["take", "prompt", "prompt", "prompt", "end"])
self.assertEqual(ev[1]["id"], "poses/intro")
def test_auto_redo_after_pause(self):
s = self.session(auto=True)
s.start()
self.wait_for(s, lambda st: st["state"] == "running" and st["prompt"] == "Fist.", "the first prompt")
s.pause()
self.wait_for(s, lambda st: st["state"] == "paused", "paused")
s.redo() # ends the pause; the prompt starts again, recording again
s.join(20)
self.assertEqual(s.state, "done")
names = [e["event"] for e in self.events(s)]
self.assertEqual(names, ["take", "prompt", "prompt", "pause", "redo", "resume", "prompt", "prompt", "end"])
def test_pose_view(self):
d = os.path.join(self.tmp, "poses")
os.makedirs(d)
for name in ("fist.png", "cross.png"):
open(os.path.join(d, name), "wb").close()
with open(os.path.join(d, "poses.json"), "w") as f:
json.dump({"fist": {"file": "fist.png", "two_hands": False, "caption": "A fist"},
"cross": {"file": "../cross.png", "two_hands": True, "caption": ""},
"ok": {"file": "ok.png", "two_hands": False}}, f)
poses = session.load_poses(d)
fist = os.path.join(d, "fist.png")
self.assertEqual(session.pose_view(poses, {"pose": "fist", "hands": "right"}), (fist, "", "A fist"))
self.assertEqual(session.pose_view(poses, {"pose": "fist", "hands": "left"})[1], "mirror")
self.assertEqual(session.pose_view(poses, {"pose": "fist", "hands": "both"})[1], "both")
self.assertEqual(session.pose_view(poses, {"pose": "fist", "hands": "any"})[1], "")
# two hands drawn already; the file stays in the folder
self.assertEqual(session.pose_view(poses, {"pose": "cross", "hands": "both"})[:2],
(os.path.join(d, "cross.png"), ""))
self.assertEqual(session.pose_view(poses, {"pose": "ok", "hands": "both"}), ("", "", "")) # no file
self.assertEqual(session.pose_view(poses, {"pose": "claw", "hands": "both"}), ("", "", ""))
self.assertEqual(session.load_poses(os.path.join(self.tmp, "none")), {})
def test_plan(self):
plan, _ = session.build_plan(SCRIPT, {})
self.assertEqual(session.plan_steps(plan), 2)
self.assertEqual(session.plan_seconds(SCRIPT, plan, auto=False), 2 * session.COUNTDOWN_S + 8)
self.assertEqual(session.plan_seconds(SCRIPT, plan, auto=True), 1 + 1 + 8)
self.assertIn("2 steps", session.plan_summary(SCRIPT, plan))
SWEEP_SCRIPT = {
"version": 1, "intro_s": 1, "between_s": 1,
"welcome": {"title": "Test", "seconds": 1, "text": "A test."},
"done": {"title": "Done", "seconds": 0, "text": "Done."},
"stopped": {"title": "Stopped", "seconds": 0, "text": "Stopped."},
"cue_names": {"thumbs-up": "Thumbs up"},
"sections": [
{"id": "sweeps", "title": "Poses", "kind": "sweep", "intro": "Keep moving.", "quick": True,
"cue_s": 2, "step_s": 6,
"groups": [["open", "fist"], ["ok", "thumbs-up", "claw"]],
"sweeps": [{"hands": "both", "group": "next", "text": "Both hands."},
{"hands": "left", "group": "any", "quick": False, "text": "Left hand."}]}]}
class SweepTest(SessionBase):
def setUp(self):
super().setUp()
with open(self.script, "w") as f:
json.dump(SWEEP_SCRIPT, f)
def events(self, s):
with open(os.path.join(s.session_dir, "takes", "01-sweeps", "prompts.jsonl")) as f:
return [json.loads(line) for line in f]
def test_sweep_flow(self):
s = self.session(next_after=0.0, speed=10, seed=1)
s.start()
s.join(20)
self.assertEqual(s.state, "done")
ev = self.events(s)
names = [e["event"] for e in ev]
self.assertEqual(names, ["take", "ready", "prompt", "prompt", "prompt", "wait",
"ready", "prompt", "prompt", "prompt", "wait", "end"])
plan = {p["id"]: p["cues"] for p in s.plan[0]["prompts"]}
for step, first in (("sweeps/both-1", 2), ("sweeps/left-1", 7)):
cues = [e for e in ev[first:first + 3]]
self.assertEqual([e["pose"] for e in cues], plan[step]) # one prompt per cue, in order
self.assertTrue(all(e["cue"] and e["step"] == step for e in cues))
self.assertTrue(all(e["distance"] == e["position"] == "" for e in cues))
self.assertEqual(ev[first - 1], dict(ev[first - 1], event="ready", id=step))
gaps = [(b["t"] - a["t"]) / 1e9 for a, b in zip(cues, cues[1:])]
self.assertTrue(all(0.15 < g < 0.4 for g in gaps), gaps) # cue_s 2 at 10x speed
# a cue repeated within a step (6 s of 2 s cues from a group of 2) gets its own id
both = [e["id"] for e in ev[2:5]]
self.assertEqual(len(set(both)), 3)
# the strip: every picture of the step, the cue lit
strips = [c for c in self.panel if c.startswith("panel: strip ")]
self.assertIn("panel: strip off", strips)
self.assertTrue(any(c.startswith("panel: strip 1 ") for c in strips))
with open(os.path.join(s.session_dir, "session.json")) as f:
meta = json.load(f)
self.assertEqual(meta["shuffle"]["seed"], 1)
self.assertEqual({x["id"]: x["cues"] for x in meta["shuffle"]["sweeps"]["sweeps"]}, plan)
self.assertFalse(meta["quick"])
def test_seed_from_session_id(self):
s = self.session(next_after=0.0, speed=20)
s.start()
s.join(20)
with open(os.path.join(s.session_dir, "session.json")) as f:
meta = json.load(f)
sid = os.path.basename(s.session_dir)
self.assertEqual(meta["shuffle"]["seed"], session.session_seed(sid))
again, _ = session.build_plan(SWEEP_SCRIPT, {}, seed=meta["shuffle"]["seed"]) # reproducible
self.assertEqual(session.plan_record(again), meta["shuffle"]["sweeps"])
def test_quick_session(self):
s = self.session(next_after=0.0, speed=20, quick=True)
s.start()
s.join(20)
self.assertEqual(s.state, "done")
self.assertEqual([e["event"] for e in self.events(s)].count("ready"), 1) # the left sweep left out
with open(os.path.join(s.session_dir, "session.json")) as f:
self.assertTrue(json.load(f)["quick"])
def test_auto(self):
s = self.session(auto=True, speed=20)
s.start()
s.join(20)
self.assertEqual(s.state, "done")
names = [e["event"] for e in self.events(s)]
self.assertEqual(names, ["take", "prompt"] + ["prompt"] * 6 + ["end"]) # intro, 3 cues a step
class ShuffleTest(unittest.TestCase):
def setUp(self):
self.script = session.load_script(session.SCRIPT_PATH)
def cues(self, seed, quick=False, checklist=None):
plan, _ = session.build_plan(self.script, checklist or {}, seed=seed, quick=quick)
return session.plan_record(plan)
def test_deterministic(self):
self.assertEqual(self.cues(42), self.cues(42))
self.assertNotEqual(self.cues(42)["pose-sweeps"], self.cues(43)["pose-sweeps"])
self.assertEqual(session.session_seed("20261002-202734"), session.session_seed("20261002-202734"))
self.assertNotEqual(session.session_seed("20261002-202734"), session.session_seed("20261002-202735"))
def test_groups(self):
groups = [sorted(g) for g in self.script["sections"][1]["groups"]]
for seed in range(20):
steps = self.cues(seed)["pose-sweeps"]
self.assertEqual([x["hands"] for x in steps], ["both", "both", "both", "left", "right"])
used = [sorted(set(x["cues"])) for x in steps]
self.assertEqual(sorted(used[:3]), sorted(groups)) # each group once with both hands
self.assertTrue(all(u in groups for u in used[3:]))
self.assertNotEqual(used[3], used[4]) # the one-hand sweeps differ
self.assertTrue(all(len(x["cues"]) == 5 for x in steps)) # 20 s of 4 s cues
# unshuffled: the script's order
steps = self.cues(None)["pose-sweeps"]
self.assertEqual(steps[0]["cues"], ["open", "fist", "point", "pinch", "open"])
# gestures and hand size keep their order
for seed in (1, 2, 3):
self.assertEqual([x["cues"] for x in self.cues(seed)["gestures"]],
[["pinch-tap", "pinch-drag"], ["grab", "cross", "overlap"], ["near-face", "screen-point"]])
self.assertEqual(self.cues(seed)["hand-size"][0]["cues"], ["flat", "flat-back", "spread"])
def test_plans(self):
full, skipped = session.build_plan(self.script, {}, seed=5)
self.assertEqual([s["id"] for s in full],
["hand-size", "pose-sweeps", "gestures", "desk-work", "touch", "bare-push", "no-hands"])
self.assertEqual(session.plan_steps(full), 15)
self.assertLess(session.plan_seconds(self.script, full, auto=False), 6 * 60)
everything, _ = session.build_plan(self.script, {"objects": ["pencil", "keyboard", "mouse"],
"controllers": "straps"}, seed=5)
self.assertEqual(len(everything), 10)
quick, skipped = session.build_plan(self.script, {"objects": ["pencil"], "controllers": "straps"},
seed=5, quick=True)
self.assertEqual([s["id"] for s in quick], ["hand-size", "pose-sweeps", "touch", "no-hands"])
self.assertEqual([p["hands"] for p in quick[1]["prompts"]], ["both"] * 3)
self.assertEqual(len(quick[2]["targets"]), 6)
self.assertLess(session.plan_seconds(self.script, quick, auto=False), 150)
self.assertIn({"section": "objects", "reason": "not in a quick round"}, skipped)
# desk work: the mouse-and-keyboard step only with both ticked
desk = [s for s in everything if s["id"] == "desk-work"][0]["prompts"]
self.assertEqual([p.get("cues") for p in desk], [None, ["mouse", "switch"]])
class StripPanelTest(unittest.TestCase):
"""The panel's strip command on ft-handpanel --no-vr (skipped if it isn't built)."""
def test_strip(self):
import subprocess
binary = session.PANEL_BIN
if not os.access(binary, os.X_OK):
self.skipTest("ft-handpanel isn't built")
name = "hrtest-strip-%d" % os.getpid()
proc = subprocess.Popen([binary, "--no-vr", "--socket", name], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True)
try:
panel = session.Panel(name=name)
for _ in range(50):
if panel.cmd("ping", reply=True, timeout=0.1):
break
if proc.poll() is not None:
self.skipTest("ft-handpanel doesn't run here: " + proc.stderr.read().strip()[-200:])
time.sleep(0.1)
else:
self.fail("ft-handpanel --no-vr doesn't answer")
poses = session.POSES_DIR
ok = panel.cmd("strip 1 %s/fist.png|mirror|Fist;-|-|No picture;%s/ok.png|-|OK" % (poses, poses), reply=True)
bad = panel.cmd("strip 1", reply=True)
missing = panel.cmd("strip 0 /nonexistent.png|-|Gone", reply=True)
panel.cmd("show", reply=True)
panel.cmd("strip off", reply=True)
panel.close()
finally:
proc.terminate()
out = proc.communicate(timeout=5)[0]
self.assertEqual(ok, "ok")
self.assertTrue(bad.startswith("error usage: strip"))
self.assertTrue(missing.startswith("error can't read"))
self.assertIn("strip: cue 0: Gone(/nonexistent.png)", out)
self.assertIn("strip: off", out)
# /proc/bus/input/devices as the Frame has it (2026-10-02), trimmed, plus a USB mouse.
DEVICES = """I: Bus=0019 Vendor=0001 Product=0001 Version=0100
N: Name="gpio-keys"
P: Phys=gpio-keys/input0
S: Sysfs=/devices/platform/gpio-keys/input/input3
U: Uniq=
H: Handlers=kbd kbd event3 qcom_pon_combo_timer_listener
B: PROP=0
B: EV=3
B: KEY=100000000000 0 0 0 0 200000000 0 0 0 0 0
I: Bus=0006 Vendor=4d44 Product=0001 Version=0001
N: Name="frametop virtual mouse"
P: Phys=
S: Sysfs=/devices/virtual/input/input4
U: Uniq=
H: Handlers=event4 qcom_pon_combo_timer_listener
B: PROP=0
B: EV=7
B: KEY=ffffff 0 0 0 0
B: REL=ffff
I: Bus=0003 Vendor=0001 Product=0001 Version=0001
N: Name="frame-voice keyboard"
P: Phys=py-evdev-uinput
S: Sysfs=/devices/virtual/input/input7
U: Uniq=
H: Handlers=kbd sysrq kbd event7 qcom_pon_combo_timer_listener
B: PROP=0
B: EV=200003
B: KEY=1ffffffffffffff ffffffffffffffff ffffffffffffffff fffffffffffffffe
I: Bus=0005 Vendor=214e Product=0035 Version=0001
N: Name="Z3 Keyboard"
P: Phys=90:82:c3:5f:4a:a7
S: Sysfs=/devices/virtual/misc/uhid/0005:214E:0035.0005/input/input27
U: Uniq=da:ef:2f:d2:be:e2
H: Handlers=kbd sysrq kbd event9 qcom_pon_combo_timer_listener
B: PROP=0
B: EV=10001f
B: KEY=300000000000 33eff 0 0 483ffff17aff32d bfd4444600000000 1 130ff38b17c007 ffff7bfad9415fff feb2ffdfffefffff fffffffffffffffe
B: REL=1040
B: MSC=10
"""
BT_MOUSE = """
I: Bus=0005 Vendor=214e Product=0035 Version=0001
N: Name="Z3 Mouse"
P: Phys=90:82:c3:5f:4a:a7
S: Sysfs=/devices/virtual/misc/uhid/0005:214E:0035.0005/input/input26
U: Uniq=da:ef:2f:d2:be:e2
H: Handlers=event8 qcom_pon_combo_timer_listener
B: PROP=0
B: EV=17
B: KEY=ffff0000 0 0 0 0
B: REL=1943
B: MSC=10
"""
USB_MOUSE = """
I: Bus=0003 Vendor=046d Product=c077 Version=0111
N: Name="Logitech USB Optical Mouse"
P: Phys=usb-xhci-hcd.1.auto-1/input0
S: Sysfs=/devices/platform/soc@0/a600000.usb/xhci-hcd.1.auto/usb1/1-1/1-1:1.0/0003:046D:C077.0001/input/input40
U: Uniq=
H: Handlers=mouse0 event13
B: PROP=0
B: EV=17
B: KEY=70000 0 0 0 0
B: REL=903
B: MSC=10
"""
def event(etype, code, value):
return session.INPUT_EVENT.pack(1, 2, etype, code, value)
PRESS = event(session.EV_KEY, session.KEY_SELECT, 1) + event(0, 0, 0)
RELEASE = event(session.EV_KEY, session.KEY_SELECT, 0) + event(0, 0, 0)
class InputTest(unittest.TestCase):
def test_devices(self):
devs = session.parse_input_devices(DEVICES)
self.assertEqual([d["name"] for d in devs], ["gpio-keys", "frametop virtual mouse", "frame-voice keyboard",
"Z3 Keyboard"])
self.assertEqual(session.find_button(devs), "/dev/input/event3")
self.assertFalse(any(session.real_mouse(d) for d in devs)) # the virtual mouse, keyboards with wheels
for extra, name in ((BT_MOUSE, "Z3 Mouse"), (USB_MOUSE, "Logitech USB Optical Mouse")):
mice = [d["name"] for d in session.parse_input_devices(DEVICES + extra) if session.real_mouse(d)]
self.assertEqual(mice, [name])
# another gpio-keys without KEY_SELECT isn't the button
self.assertIsNone(session.find_button(session.parse_input_devices(DEVICES.replace("200000000", "0"))))
def test_presses(self):
data = (PRESS + event(session.EV_KEY, session.KEY_SELECT, 2) * 3 # autorepeat: not presses
+ RELEASE + event(session.EV_KEY, 115, 1) + PRESS) # another key
self.assertEqual(session.button_presses(data), (2, b""))
n, rest = session.button_presses(PRESS + PRESS[:10])
self.assertEqual((n, rest), (1, PRESS[:10])) # half an event waits for the rest
self.assertEqual(session.button_presses(rest + PRESS[10:])[0], 1)
def test_reader_fifo(self):
tmp = tempfile.mkdtemp(prefix="handrec-button-test-")
try:
fifo = os.path.join(tmp, "button")
os.mkfifo(fifo)
presses = []
reader = session.ButtonReader(fifo, lambda: presses.append(time.monotonic()), debounce_s=0.3).start()
with open(fifo, "wb", buffering=0) as w:
w.write(PRESS + RELEASE)
w.write(PRESS[:7]) # a press split across writes, a bounce
time.sleep(0.05)
w.write(PRESS[7:] + RELEASE)
time.sleep(0.4)
w.write(PRESS + RELEASE)
time.sleep(0.2)
with open(fifo, "wb", buffering=0) as w: # the writer comes back: read again
time.sleep(0.4)
w.write(PRESS)
time.sleep(0.3)
reader.stop()
self.assertEqual(len(presses), 3)
self.assertTrue(reader.ok)
finally:
shutil.rmtree(tmp, ignore_errors=True)
def test_missing_device(self):
logs = []
reader = session.ButtonReader("/nonexistent/event99", lambda: None, log=logs.append).start()
time.sleep(0.1)
reader.stop()
self.assertFalse(reader.ok)
self.assertIn("can't open", logs[0])
class ButtonSessionTest(SessionBase):
"""A dry run steered with a simulated headset button (a FIFO), with no mouse, then one."""
def test_button(self):
fifo = os.path.join(self.tmp, "button")
os.mkfifo(fifo)
procfile = os.path.join(self.tmp, "devices")
with open(procfile, "w") as f:
f.write(DEVICES)
writer = os.open(fifo, os.O_RDWR) # kept open, so the reader never sees the end
press = lambda: os.write(writer, PRESS + RELEASE)
try:
with mock.patch.object(session, "BUTTON_DEBOUNCE_S", 0.0):
s = self.session(speed=4, button_device=fifo)
s.input_devices = procfile
s.start()
st = self.waiting(s, "starting")
self.assertEqual((st["button"], st["mouse"], st["ready_text"]), (True, False, session.READY_BUTTON))
self.assertIn("panel: action " + session.READY_BUTTON, self.panel)
self.assertIn("panel: keys " + session.KEYS_STEP_BUTTON, self.panel)
press()
self.waiting(s, "intro")
press()
self.waiting(s, "ready", "Fist.")
press() # Next
self.wait_for(s, lambda st: st["state"] == "running", "the hold")
press() # pause
self.wait_for(s, lambda st: st["state"] == "paused", "paused")
with open(procfile, "a") as f: # a mouse arrives
f.write(BT_MOUSE)
press() # resume
st = self.waiting(s, "ready", "Open.")
self.assertEqual((st["mouse"], st["ready_text"]), (True, session.READY_BUTTON_MOUSE))
press()
s.join(20)
self.assertEqual(s.state, "done")
names = [e["event"] for e in self.events(s)]
self.assertEqual(names, ["take", "ready", "prompt", "pause", "resume", "wait", "ready", "prompt", "wait",
"end"])
finally:
os.close(writer)
def test_no_button(self):
s = self.session(next_after=0.0, button=False, button_device="/nonexistent")
s.start()
s.join(20)
self.assertEqual(s.state, "done")
self.assertIn("panel: action " + session.READY_TEXT, self.panel)
self.assertIn("panel: keys " + session.KEYS_STEP, self.panel)
class LightingTest(unittest.TestCase):
"""The measured lighting label: the mono cameras' ambient infrared."""
def ring(self, slam, upper):
return {"slam_left": {"mean": 70.0, "dark_mean": slam}, "slam_right": {"mean": 80.0, "dark_mean": slam},
"upper_left": {"mean": 50.0, "dark_mean": upper}, "upper_right": {"mean": 20.0, "dark_mean": upper}}
def test_indoor_and_daylight(self):
self.assertEqual(session.classify_lighting(self.ring(3.0, 0.5)), "indoor") # one lamp, 2026-10-02
self.assertEqual(session.classify_lighting(self.ring(3.7, 0.7)), "indoor") # a lamp-lit room
self.assertEqual(session.classify_lighting(self.ring(20.0, 8.0)), "daylight")
self.assertEqual(session.classify_lighting(self.ring(0.0, 0.0)), "") # no dark frames yet
self.assertEqual(session.classify_lighting(None), "")
self.assertEqual(session.ambient_ir(self.ring(3.0, 0.5)), 1.75)
def test_record(self):
rec = session.lighting_record("auto", self.ring(3.0, 0.5))
self.assertEqual((rec["chosen"], rec["source"], rec["measured"]), ("indoor", "measured", "indoor"))
rec = session.lighting_record("dim", self.ring(3.0, 0.5))
self.assertEqual((rec["chosen"], rec["source"], rec["measured"]), ("dim", "picked", "indoor"))
rec = session.lighting_record("auto", None)
self.assertEqual((rec["chosen"], rec["source"], rec["ring"]), ("", "measured", {}))
class ManyPartsTest(unittest.TestCase):
"""A take recorded in 40 parts (step mode stops the recording between steps): review reads
them in order, export makes one stream, validate passes."""
def setUp(self):
if not takes.find_zstd():
self.skipTest("no zstd")
self.tmp = tempfile.mkdtemp(prefix="handrec-parts-test-")
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def test_parts(self):
make_session(self.tmp)
tdir = os.path.join(self.tmp, "sessions", SESSION, "takes", "01-hand-size")
t0 = 5 * 10 ** 12
for part in range(1, 41):
name = "sets.bin" if part == 1 else "sets-%d.bin" % part
with open(os.path.join(tdir, name), "wb") as f:
for i in range(3): # 3 sets a part, 10 s apart between parts
f.write(fhset(t0 + part * 10 ** 10 + i * 10 ** 8, part))
store = takes.Store(self.tmp)
index = takes.take_index(tdir)
self.assertEqual(len(index.parts), 40)
self.assertEqual(len(index), 120)
times = [index.time_ns(i) for i in range(len(index))]
self.assertEqual(times, sorted(times)) # sets-10.bin after sets-9.bin
self.assertAlmostEqual(index.duration_s(), 40 * 0.2) # the gaps between parts don't count
path = store.export(SESSION, low_priority=False)
r = validate.validate(path)
self.assertEqual(r.errors, [])
self.assertEqual(r.summary["sets"], 120 + 30)
if __name__ == "__main__":
unittest.main()
+269
View File
@@ -0,0 +1,269 @@
#!/usr/bin/env python3
"""Tests for the side cameras' naming in recordings (sides.py) and its readers: takes.py's
review and export, validate.py, and session.py's live decision and recording parts.
python3 hands/rec/tests/test_sides.py
"""
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time
import unittest
from unittest import mock
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(HERE))
import session # noqa: E402
import sides # noqa: E402
import takes # noqa: E402
import validate # noqa: E402
from test_validate import fhset, make_session, SESSION # noqa: E402
def names(record):
ncams = sides.HDR.unpack_from(record, 0)[1]
return [sides.CAM.unpack_from(record, sides.HDR.size + k * sides.CAM.size)[0].split(b"\0")[0].decode()
for k in range(ncams)]
class RulesTest(unittest.TestCase):
def test_rename_record(self):
rec = fhset(10 ** 9, 3)
out = sides.rename_record(rec)
self.assertEqual(names(rec), ["slam_left", "slam_right"])
self.assertEqual(names(out), ["slam_right", "slam_left"])
self.assertEqual(len(out), len(rec))
head = sides.HDR.size + 2 * sides.CAM.size
self.assertEqual(out[head:], rec[head:]) # pixels untouched
self.assertEqual(sides.rename_record(out), rec)
def test_other_name(self):
self.assertEqual(sides.other_name("slam_left_dk"), "slam_right_dk")
self.assertEqual(sides.other_name("upper_left"), "upper_left")
def test_needs_rename(self):
self.assertTrue(sides.needs_rename(True, False))
self.assertFalse(sides.needs_rename(True, True))
self.assertTrue(sides.needs_rename(False, True))
self.assertFalse(sides.needs_rename(None, True)) # unknown: leave the names
def test_part_rename(self):
sess = {"sides": {"swapped": True}}
take = {"parts": {"sets.bin": {"names_swapped": False}, "sets-2.bin": {"names_swapped": True}}}
self.assertTrue(sides.part_rename(sess, take, "sets.bin"))
self.assertFalse(sides.part_rename(sess, take, "sets-2.bin"))
self.assertTrue(sides.part_rename(sess, {}, "sets-3.bin")) # no record: as ft-camd named them
self.assertFalse(sides.part_rename({}, take, "sets.bin")) # no decision
def test_recording_runs(self):
d = tempfile.mkdtemp()
try:
self.assertEqual(sides.recording_runs(d), [(0, False)])
with open(os.path.join(d, "sides.json"), "w") as f:
json.dump({"swapped": True, "decided_by": "auto", "names_swapped": [[0, False], [37, True]]}, f)
runs = sides.recording_runs(d)
self.assertEqual(runs, [(0, True), (37, False)])
self.assertTrue(sides.rename_at(runs, 36))
self.assertFalse(sides.rename_at(runs, 37))
finally:
shutil.rmtree(d)
def test_read_live(self):
d = tempfile.mkdtemp()
try:
path, ring = os.path.join(d, "sides.json"), os.path.join(d, "cam-ring")
open(ring, "w").close()
now = time.clock_gettime_ns(time.CLOCK_MONOTONIC)
live = {"pid": 1, "ring_ino": os.stat(ring).st_ino, "swapped": True, "decided_by": "auto",
"state": "decided", "updated_ns": now}
with open(path, "w") as f:
json.dump(live, f)
self.assertEqual(sides.read_live(path, ring)["swapped"], True)
self.assertIsNone(sides.read_live(path, ring, now_ns=now + 10 * 10 ** 9)) # stale
os.remove(ring)
open(ring, "w").close() # a new ft-camd: a new ring file
if os.stat(ring).st_ino != live["ring_ino"]:
self.assertIsNone(sides.read_live(path, ring))
self.assertIsNone(sides.read_live(os.path.join(d, "none.json")))
finally:
shutil.rmtree(d)
class TakesTest(unittest.TestCase):
"""A swapped session: one take's parts recorded before the decision (ft-camd's names) and
after it (named right)."""
def setUp(self):
if not takes.find_zstd():
self.skipTest("no zstd")
self.tmp = tempfile.mkdtemp(prefix="handrec-sides-test-")
make_session(self.tmp)
self.sdir = os.path.join(self.tmp, "sessions", SESSION)
meta = takes.read_json(os.path.join(self.sdir, "session.json"))
meta["sides"] = {"swapped": True, "decided_by": "auto", "state": "confirmed"}
takes.write_json(os.path.join(self.sdir, "session.json"), meta)
self.tdir = os.path.join(self.sdir, "takes", "01-hand-size")
with open(os.path.join(self.tdir, "sets-2.bin"), "wb") as f: # after the decision: --sides 1
for i in range(5):
f.write(sides.rename_record(fhset(9 * 10 ** 12 + i * 10 ** 8, i)))
tj = takes.read_json(os.path.join(self.tdir, "take.json"))
tj["parts"] = {"sets.bin": {"names_swapped": False}, "sets-2.bin": {"names_swapped": True}}
takes.write_json(os.path.join(self.tdir, "take.json"), tj)
self.store = takes.Store(self.tmp)
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def test_review_reads_right_names(self):
index = takes.take_index(self.tdir)
self.assertEqual(index.rename, [True, False])
self.assertEqual([c["name"] for c in index.cams], ["slam_right", "slam_left"])
self.assertEqual([c["name"] for c in index.read_set(0)], ["slam_right", "slam_left"])
self.assertEqual([c["name"] for c in index.read_set(len(index) - 1)], ["slam_right", "slam_left"])
# the same pixels under the other name
raw = takes.TakeIndex(self.tdir).read_set(0, only="slam_right")[0]["pixels"]
self.assertEqual(raw, fhset(10 ** 12, 0)[sides.HDR.size + 2 * sides.CAM.size:][:32 * 24])
self.assertEqual(index.renamed_sets(), 30)
# the other take has no parts record: recorded as ft-camd named them, renamed too
other = takes.take_index(os.path.join(self.sdir, "takes", "02-no-hands"))
self.assertEqual(other.rename, [True])
def test_export_writes_right_names(self):
path = self.store.export(SESSION, low_priority=False)
r = validate.validate(path)
self.assertEqual(r.errors, [])
self.assertEqual(r.warnings, [])
m = takes.read_json(os.path.join(path, "manifest.json"))
t = m["takes"][0]
self.assertEqual(t["sides"], {"names_swapped": True, "renamed_sets": 30})
self.assertEqual(m["session"]["sides"]["swapped"], True)
self.assertEqual(takes.read_json(os.path.join(path, "takes", t["id"], "take.json"))["parts"],
{"sets.bin": {"names_swapped": True}})
# every exported set: right names (the rule applied again changes nothing)
data = subprocess.run([takes.find_zstd(), "-dc", os.path.join(path, t["file"])],
capture_output=True, check=True).stdout
off, seen = 0, 0
while off < len(data):
nbytes = sides.HDR.unpack_from(data, off)[2]
self.assertEqual(names(data[off:off + nbytes]), ["slam_right", "slam_left"])
off, seen = off + nbytes, seen + 1
self.assertEqual(seen, 35)
def test_validate_catches_wrong_names(self):
path = self.store.export(SESSION, low_priority=False)
mpath = os.path.join(path, "manifest.json")
m = takes.read_json(mpath)
m["takes"][0]["sides"]["names_swapped"] = False
takes.write_json(mpath, m)
report = validate.Report(path)
validate.check_manifest(m, report, path)
self.assertTrue(any("aren't named right" in e for e in report.errors), report.errors)
def test_undecided_warns(self):
meta = takes.read_json(os.path.join(self.sdir, "session.json"))
meta["sides"] = {"swapped": None}
takes.write_json(os.path.join(self.sdir, "session.json"), meta)
path = self.store.export(SESSION, low_priority=False)
r = validate.validate(path)
self.assertEqual(r.errors, [])
self.assertTrue(any("wasn't decided" in w for w in r.warnings), r.warnings)
m = takes.read_json(os.path.join(path, "manifest.json"))
self.assertIsNone(m["takes"][0]["sides"]["names_swapped"]) # the parts differ
self.assertEqual(m["takes"][0]["sides"]["renamed_sets"], 0)
def test_sides_command(self):
out = self.store.sides(SESSION)
self.assertTrue(out["sides"]["swapped"])
self.assertEqual(out["takes"]["01-hand-size"]["sets-2.bin"], {"names_swapped": True, "renamed_when_read": False})
out = self.store.sides(SESSION, False)
self.assertEqual(out["sides"]["decided_by"], "manual")
self.assertTrue(out["sides"]["replaced"]["swapped"])
self.assertTrue(out["takes"]["01-hand-size"]["sets-2.bin"]["renamed_when_read"])
self.assertEqual(takes.take_index(self.tdir).rename, [False, True]) # the cache saw session.json change
class SessionSidesTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="handrec-sides-session-")
self.script = os.path.join(self.tmp, "script.json")
with open(self.script, "w") as f:
json.dump({"version": 1, "sections": [{"id": "a", "title": "A", "prompts": [{"text": "x", "seconds": 1}]}]},
f)
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def live(self, **kw):
d = dict(pid=1, ring_ino=0, mode="auto", state="decided", swapped=True, decided_by="auto",
evidence={"as_named": 0, "swapped": 10}, updated_ns=time.clock_gettime_ns(time.CLOCK_MONOTONIC))
d.update(kw)
with open(os.path.join(self.tmp, "sides.json"), "w") as f:
json.dump(d, f)
def test_read_sides(self):
s = session.Session(os.path.join(self.tmp, "base"), {}, {}, "room", self.script, dry_run=True,
hands_dir=self.tmp)
s.session_dir = self.tmp
s._session_json = {"sides": {"swapped": None}}
s._read_sides(force=True)
self.assertIsNone(s._sides_swapped()) # no file
self.live(swapped=None, state="deciding", decided_by=None)
s._read_sides(force=True)
self.assertIsNone(s._sides_swapped())
self.live()
s._read_sides(force=True)
self.assertTrue(s._sides_swapped())
self.assertEqual(s._session_json["sides"]["evidence"]["swapped"], 10)
self.live(state="confirmed")
s._read_sides(force=True)
self.assertEqual(s._session_json["sides"]["state"], "confirmed")
self.live(swapped=False, state="decided, reversed")
s._read_sides(force=True)
self.assertFalse(s._sides_swapped())
self.assertTrue(s._session_json["sides"]["reversed_from"]["swapped"])
self.assertFalse(takes.read_json(os.path.join(self.tmp, "session.json"))["sides"]["swapped"])
def test_recorder_parts(self):
calls = []
class FakeProc:
returncode = 0
def __init__(self, argv, **kw):
calls.append(argv)
def poll(self):
return 0
take = os.path.join(self.tmp, "take")
os.makedirs(take)
with mock.patch.object(session.subprocess, "Popen", FakeProc):
r1 = session.Recorder(take, 1, 10, None, None)
r2 = session.Recorder(take, 2, 10, None, None, swap=True)
r3 = session.Recorder(take, 3, 10, None, None, swap=False)
argv = [c[c.index("--sides") + 1] for c in calls]
self.assertEqual(argv, ["auto", "1", "0"])
# ft-hands' DIR/sides.json goes into names_swapped and away
os.makedirs(r2.dir, exist_ok=True)
with open(os.path.join(r2.dir, "sets.bin"), "wb") as f:
f.write(fhset(10 ** 9, 0))
with open(os.path.join(r2.dir, "sides.json"), "w") as f:
json.dump({"swapped": None, "names_swapped": [[0, True]]}, f)
r2.stop()
self.assertTrue(r2.names_swapped)
self.assertEqual(r2.file, "sets-2.bin")
self.assertTrue(os.path.isfile(os.path.join(take, "sets-2.bin")))
self.assertFalse(os.path.exists(r2.dir))
with open(os.path.join(take, "sides.json"), "w") as f:
json.dump({"swapped": None, "names_swapped": [[0, False]]}, f)
r1.stop()
self.assertFalse(r1.names_swapped)
self.assertFalse(os.path.exists(os.path.join(take, "sides.json")))
self.assertFalse(r3.names_swapped)
if __name__ == "__main__":
unittest.main()
+556
View File
@@ -0,0 +1,556 @@
#!/usr/bin/env python3
"""Tests for validate.py and hub.py (no network): a good export, and broken ones.
python3 hands/rec/tests/test_validate.py (in the dev container, or anywhere with zstd)
"""
import hashlib
import json
import os
import shutil
import struct
import sys
import tempfile
import unittest
import uuid
from unittest import mock
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(HERE))
import hub # noqa: E402
import session # noqa: E402
import takes # noqa: E402
import validate # noqa: E402
SESSION = "20261002-101500"
DEVICE = {"cv": {"cad_from_cal": {"method": "FrontAndUpperCamPositions", "plus_x": [0.63, -0.77, 0.02],
"plus_z": [-0.45, -0.35, 0.82], "position": [-0.05, -0.02, 0.04]}},
"head": {"plus_x": [-1, 0, 0], "plus_z": [0, 0, -1], "position": [0, 0, 0]}}
CAMS = [("slam_left", 32, 24), ("slam_right", 32, 24)]
def fhset(t_ns, seed):
"""One FHSET01 record: header, camera headers, pixels."""
pixels = b"".join(bytes((seed + i) % 256 for i in range(w * h)) for _, w, h in CAMS)
size = validate.HDR.size + validate.CAM.size * len(CAMS) + len(pixels)
out = validate.HDR.pack(b"FHSET01\0", len(CAMS), size)
for name, w, h in CAMS:
out += validate.CAM.pack(name.encode(), w, h, t_ns - 1000, t_ns)
return out + pixels
def write_sums(export):
sums = []
for root, _, files in os.walk(export):
for name in files:
rel = os.path.relpath(os.path.join(root, name), export)
if rel != "SHA256SUMS":
with open(os.path.join(root, name), "rb") as f:
sums.append((rel, hashlib.sha256(f.read()).hexdigest()))
with open(os.path.join(export, "SHA256SUMS"), "w") as f:
for rel, digest in sorted(sums):
f.write(f"{digest} {rel}\n")
def make_session(base, contributor=None, sid=None, device=True):
"""A small recorded session in base, as session.py leaves it."""
contributor = contributor or str(uuid.uuid4())
os.makedirs(base, exist_ok=True)
takes.write_json(os.path.join(base, "profile.json"), {
"schema": 1, "contributor": contributor,
"consent": {"version": "2026-10-02", "accepted": "2026-10-02T10:00:00+00:00", "adult": True},
"optional": {"handedness": "right", "notes": ""}})
sdir = os.path.join(base, "sessions", sid or SESSION)
os.makedirs(os.path.join(sdir, "takes"))
takes.write_json(os.path.join(sdir, "session.json"), {
"schema": 1, "tool": "ft-handrec test", "started": "2026-10-02T10:15:00+0000", "contributor": contributor,
"lighting": {"chosen": "room", "ring": {}},
"checklist": {"objects": ["pencil"], "own_objects": ["stapler"], "controllers": "none", "sleeves": "",
"rings": False, "watch": False, "notes": ""},
"device": {"steamos": "3.8", "steamvr": "r25358740+28b72a4f-1", "cameras": [{"name": n, "width": w, "height": h}
for n, w, h in CAMS]},
"calibration_removed": ["serial"], "takes": ["01-hand-size", "02-no-hands"], "status": "done",
"sides": {"swapped": False, "decided_by": "auto", "state": "confirmed"}})
takes.write_json(os.path.join(sdir, "calibration.json"),
{"cameras": [{"name": "slam_left", "intrinsics": [1.0, 2.0, 3.0]}]})
if device:
takes.write_json(os.path.join(sdir, "device.json"), DEVICE)
for k, tid in enumerate(("01-hand-size", "02-no-hands")):
tdir = os.path.join(sdir, "takes", tid)
os.makedirs(tdir)
t0 = 10 ** 12 * (k + 1)
with open(os.path.join(tdir, "sets.bin"), "wb") as f:
for i in range(30):
f.write(fhset(t0 + i * 100_000_000, i))
with open(os.path.join(tdir, "prompts.jsonl"), "w") as f:
f.write(json.dumps({"t": t0, "event": "take", "section": tid[3:], "take": tid}) + "\n")
f.write(json.dumps({"t": t0 + 5, "event": "end", "status": "complete"}) + "\n")
with open(os.path.join(tdir, "poses.jsonl"), "w") as f:
for i in range(10):
f.write(json.dumps({"t": t0 + i, "hmd": {"m": [0.0] * 12, "r": 200, "ok": True},
"left": None, "right": None}) + "\n")
takes.write_json(os.path.join(tdir, "take.json"), {"section": tid[3:], "title": tid, "started_ns": t0,
"ended_ns": t0 + 3 * 10 ** 9, "status": "complete",
"deleted": [], "notes": ""})
return contributor
class ValidateTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
if not takes.find_zstd():
raise unittest.SkipTest("no zstd")
cls.tmp = tempfile.mkdtemp(prefix="handrec-validate-test-")
cls.base = os.path.join(cls.tmp, "base")
cls.contributor = make_session(cls.base)
cls.store = takes.Store(cls.base)
# One deleted range, so the export leaves sets out.
index = takes.take_index(cls.store.take_dir(SESSION, "01-hand-size"))
cls.store.delete_range(SESSION, "01-hand-size", index.time_ns(3), index.time_ns(5))
cls.export = cls.store.export(SESSION, low_priority=False)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tmp, ignore_errors=True)
def copy(self):
d = tempfile.mkdtemp(dir=self.tmp)
dest = os.path.join(d, SESSION)
shutil.copytree(self.export, dest)
return dest
def assertError(self, report, text):
self.assertTrue(any(text in e for e in report.errors), f"no error with {text!r}: {report.errors}")
def test_good(self):
r = validate.validate(self.export)
self.assertEqual(r.errors, [])
self.assertEqual(r.warnings, [])
self.assertTrue(os.path.isfile(os.path.join(self.export, "device.json")))
self.assertEqual(r.summary["takes"], 2)
self.assertEqual(r.summary["sets"], 57)
self.assertEqual(r.summary["consent_version"], "2026-10-02")
self.assertEqual(r.summary["contributor"], self.contributor)
def test_extra_file(self):
d = self.copy()
with open(os.path.join(d, "notes.txt"), "w") as f:
f.write("hello\n")
os.makedirs(os.path.join(d, "takes", "01-hand-size", "extra"))
r = validate.validate(d)
self.assertError(r, "notes.txt: not an allowed file")
self.assertError(r, "not in SHA256SUMS: notes.txt")
self.assertError(r, "extra/: not an allowed folder")
def test_symlink(self):
d = self.copy()
os.symlink("/etc/hostname", os.path.join(d, "takes", "01-hand-size", "take.json.link"))
self.assertError(validate.validate(d), "a symlink")
def test_bad_checksum(self):
d = self.copy()
path = os.path.join(d, "takes", "02-no-hands", "poses.jsonl")
with open(path, "r+b") as f:
f.seek(5)
f.write(b"9") # "t": 2... becomes "t": 9...: still valid JSON
r = validate.validate(d)
self.assertError(r, "checksum mismatch: takes/02-no-hands/poses.jsonl")
self.assertEqual(len(r.errors), 1, r.errors)
def test_calibration_serial(self):
d = self.copy()
takes.write_json(os.path.join(d, "calibration.json"),
{"cameras": [{"name": "slam_left", "serial": "X", "label": "unit 4H2K19A7731"}]})
write_sums(d)
r = validate.validate(d)
self.assertError(r, "calibration.json: identifying fields left in")
self.assertIn("cameras[0].serial", r.errors[0])
self.assertIn("cameras[0].label", r.errors[0])
self.assertEqual(len(r.errors), 1, r.errors)
def test_truncated_zst(self):
d = self.copy()
path = os.path.join(d, "takes", "01-hand-size", "sets.bin.zst")
os.truncate(path, os.path.getsize(path) // 2)
write_sums(d)
r = validate.validate(d)
self.assertTrue(any("sets.bin.zst" in e and ("cut short" in e or "set " in e or "decompress" in e)
for e in r.errors), r.errors)
def test_truncated_zst_command(self):
"""The same with the zstd program (Python before 3.14)."""
d = self.copy()
path = os.path.join(d, "takes", "01-hand-size", "sets.bin.zst")
os.truncate(path, os.path.getsize(path) // 2)
with mock.patch.object(validate, "_zstd", None):
r = validate.validate(d)
self.assertTrue(any("sets.bin.zst" in e and "checksum" not in e for e in r.errors), r.errors)
self.assertEqual(validate.validate(self.export).errors, [])
def test_garbage_records(self):
d = self.copy()
rec = bytearray(fhset(10 ** 9, 0))
rec[validate.HDR.size:validate.HDR.size + 16] = b"slam left!\0\0\0\0\0\0"
zst = os.path.join(d, "takes", "02-no-hands", "sets.bin.zst")
with open(zst + ".raw", "wb") as f:
f.write(bytes(rec))
os.system(f"zstd -q -f {zst}.raw -o {zst} && rm {zst}.raw")
write_sums(d)
self.assertError(validate.validate(d), "a camera name that isn't one")
def test_manifest(self):
d = self.copy()
path = os.path.join(d, "manifest.json")
with open(path) as f:
m = json.load(f)
m["contributor"] = m["profile"]["contributor"] = str(uuid.uuid1())
m["consent_version"] = ""
m["profile"]["consent"]["version"] = ""
m["takes"][0]["sets"] += 1
m["session"]["dry_run"] = True
m["session"]["device"]["serial_number"] = "x"
del m["exported"]
takes.write_json(path, m)
with open(os.path.join(d, "takes", "02-no-hands", "prompts.jsonl"), "a") as f:
f.write("{not json\n")
write_sums(d)
r = validate.validate(d)
self.assertError(r, "isn't a random uuid4")
self.assertError(r, "the consent version is empty")
self.assertError(r, "27 sets, the manifest says 28")
self.assertError(r, "dry-run session")
self.assertError(r, "identifying fields: session.device.serial_number")
self.assertError(r, "exported is missing")
self.assertError(r, "prompts.jsonl line 3: not valid JSON")
def test_region(self):
"""From consent 2026-10-03, the residency confirmation must be there."""
d = self.copy()
path = os.path.join(d, "manifest.json")
with open(path) as f:
m = json.load(f)
m["consent_version"] = m["profile"]["consent"]["version"] = "2026-10-03"
takes.write_json(path, m)
write_sums(d)
self.assertError(validate.validate(d), "Illinois, Texas or Washington")
m["profile"]["consent"]["region_ok"] = True
takes.write_json(path, m)
write_sums(d)
self.assertEqual(validate.validate(d).errors, [])
def test_device(self):
d = self.copy()
bad = json.loads(json.dumps(DEVICE))
bad["device_serial_number"] = "X"
bad["head"]["position"] = [0, 0]
takes.write_json(os.path.join(d, "device.json"), bad)
write_sums(d)
r = validate.validate(d)
self.assertError(r, "expected cv and head only")
self.assertError(r, "head.position isn't 3 numbers")
self.assertError(r, "device.json: identifying fields: device_serial_number")
def test_no_device(self):
"""Sessions from before device.json still pass, with a warning."""
d = self.copy()
os.remove(os.path.join(d, "device.json"))
write_sums(d)
r = validate.validate(d)
self.assertEqual(r.errors, [])
self.assertTrue(any("no device.json" in w for w in r.warnings), r.warnings)
def test_zstandard(self):
"""The zstandard package's path (the maintainer's Windows PC), good and truncated."""
if validate._zstandard is None:
self.skipTest("no zstandard")
with mock.patch.object(validate, "_zstd", None):
self.assertEqual(validate.validate(self.export).errors, [])
d = self.copy()
path = os.path.join(d, "takes", "01-hand-size", "sets.bin.zst")
os.truncate(path, os.path.getsize(path) // 2)
write_sums(d)
self.assertError(validate.validate(d), "sets.bin.zst: the zstd stream is cut short")
def test_frames(self):
"""Several zstd frames one after another (zstd -T2 can write them) read as one stream."""
if validate._zstd is None and validate._zstandard is None:
self.skipTest("no compression.zstd or zstandard")
d = self.copy()
zst = os.path.join(d, "takes", "02-no-hands", "sets.bin.zst")
with open(zst, "rb") as f:
one = f.read()
with open(zst, "ab") as f:
f.write(one)
with open(os.path.join(d, "manifest.json")) as f:
m = json.load(f)
m["takes"][1]["sets"] *= 2
m["takes"][1]["raw_bytes"] *= 2
takes.write_json(os.path.join(d, "manifest.json"), m)
write_sums(d)
r = validate.validate(d)
self.assertEqual([e for e in r.errors if "go back" not in e], [])
def test_cli(self):
self.assertEqual(os.system(f"{sys.executable} {validate.__file__} {self.export} --json >/dev/null"), 0)
d = self.copy()
os.remove(os.path.join(d, "manifest.json"))
self.assertNotEqual(os.system(f"{sys.executable} {validate.__file__} {d} >/dev/null"), 0)
class ExportJsonlTest(unittest.TestCase):
"""takes.export_jsonl: deleted ranges and the controllers when the checklist says none."""
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="handrec-jsonl-test-")
ctrl = {"m": [0.0] * 12, "r": 200, "ok": True}
with open(os.path.join(self.tmp, "poses.jsonl"), "w") as f:
for t in range(10):
f.write(json.dumps({"t": t, "hmd": ctrl, "left": ctrl, "right": ctrl}) + "\n")
with open(os.path.join(self.tmp, "prompts.jsonl"), "w") as f:
for e in ({"t": 1, "event": "prompt", "id": "a"}, {"t": 4, "event": "feedback", "left": True},
{"t": 7, "event": "feedback", "left": True, "controller": {"left": "ok"}}):
f.write(json.dumps(e) + "\n")
os.makedirs(os.path.join(self.tmp, "out"))
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def run_export(self, name, keep):
out = os.path.join(self.tmp, "out", name)
takes.export_jsonl(os.path.join(self.tmp, name), out, [[3, 5]], keep)
with open(out) as f:
return [json.loads(line) for line in f]
def test_no_controllers(self):
poses = self.run_export("poses.jsonl", False)
self.assertEqual([p["t"] for p in poses], [0, 1, 2, 6, 7, 8, 9]) # 3-5 deleted
self.assertTrue(all(p["left"] is None and p["right"] is None and p["hmd"] for p in poses))
prompts = self.run_export("prompts.jsonl", False)
self.assertEqual([e["t"] for e in prompts], [1, 7]) # the feedback at 4 was in a deleted range
self.assertNotIn("controller", prompts[1])
def test_with_controllers(self):
poses = self.run_export("poses.jsonl", True)
self.assertTrue(all(p["left"] and p["right"] for p in poses))
self.assertIn("controller", self.run_export("prompts.jsonl", True)[1])
class SessionFilesTest(unittest.TestCase):
"""session.py's device.json, and session ids with a suffix."""
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="handrec-session-test-")
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def test_write_device(self):
full = dict(json.loads(json.dumps(DEVICE)), device_serial_number="ABC12345678", display_edid="00ff",
model_number="Frame")
src = os.path.join(self.tmp, "device_config.json")
takes.write_json(src, full)
s = session.Session.__new__(session.Session)
s.session_dir, s._log = self.tmp, lambda text: None
with mock.patch.object(session, "host_path", lambda p: src if p.endswith("device_config.json") else None):
self.assertEqual(s._write_device(), [])
with open(os.path.join(self.tmp, "device.json")) as f:
self.assertEqual(json.load(f), DEVICE)
with mock.patch.object(session, "host_path", lambda p: None):
self.assertEqual(s._write_device(), [])
def test_suffix_id(self):
if not takes.find_zstd():
self.skipTest("no zstd")
sid = SESSION + "-2"
make_session(self.tmp, sid=sid)
store = takes.Store(self.tmp)
self.assertEqual([x["id"] for x in store.sessions()], [sid])
path = store.export(sid, low_priority=False)
self.assertEqual(validate.validate(path).errors, [])
class LoginTest(unittest.TestCase):
"""hub.login: the link and code go out first, the token is saved by huggingface_hub and never
passed on, and a refused login is a "login" error. huggingface_hub's helpers are faked."""
def setUp(self):
try:
import huggingface_hub._login
import huggingface_hub.utils._oauth_device
except ImportError as e:
self.skipTest(f"no huggingface_hub browser login: {e}")
self.login_mod = huggingface_hub._login
self.device = huggingface_hub.utils._oauth_device
def test_code_then_saved(self):
told, saved = [], []
info = {"verification_uri_complete": "https://hf.co/oauth/device", "user_code": "ABCD-1234", "expires_in": 300}
with mock.patch.object(self.device, "request_device_code", return_value=info), \
mock.patch.object(self.device, "poll_device_token", return_value={"access_token": "secret"}), \
mock.patch.object(self.login_mod, "_save_oauth_token", side_effect=saved.append), \
mock.patch.object(hub, "whoami", return_value={"name": "someone", "role": ""}):
who = hub.login(lambda phase, text, **extra: told.append(dict(extra, phase=phase)))
self.assertEqual(told, [{"phase": "code", "url": info["verification_uri_complete"], "code": "ABCD-1234",
"expires_in": 300}])
self.assertEqual(saved, [{"access_token": "secret"}])
self.assertEqual(who["name"], "someone")
self.assertNotIn("secret", json.dumps(told) + json.dumps(who))
def test_refused(self):
from huggingface_hub.errors import DeviceCodeError
info = {"verification_uri_complete": "u", "user_code": "c", "expires_in": 300}
with mock.patch.object(self.device, "request_device_code", return_value=info), \
mock.patch.object(self.device, "poll_device_token", side_effect=DeviceCodeError("access_denied")):
with self.assertRaises(hub.HubError) as cm:
hub.login()
self.assertEqual(cm.exception.kind, "login")
class HubTest(unittest.TestCase):
"""hub.py without the network: the dry run, the draft gate, upload records."""
def setUp(self):
if not takes.find_zstd():
self.skipTest("no zstd")
self.tmp = tempfile.mkdtemp(prefix="handrec-hub-test-")
self.contributor = make_session(self.tmp)
self.store = takes.Store(self.tmp)
self.store.export(SESSION, low_priority=False)
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def test_dry_run(self):
logged = []
with mock.patch.dict(os.environ, {hub.DATASET_ENV: "someone/test-hands"}):
result = hub.upload(self.store, SESSION, dry_run=True, log=logged.append)
self.assertTrue(result["dry_run"])
self.assertEqual(result["repo"], "someone/test-hands")
self.assertEqual(result["path_in_repo"], f"contributions/{self.contributor}/{SESSION}")
self.assertIn("- Takes: 2", result["commit_description"])
self.assertIn("- Consent version: 2026-10-02", result["commit_description"])
self.assertIn("- Objects: pencil (+1 of their own)", result["commit_description"])
self.assertTrue(any("manifest.json" in line for line in logged))
self.assertEqual(hub.uploads(self.store, SESSION), []) # a dry run records nothing
def test_dataset_env(self):
self.assertEqual(hub.dataset_id(), hub.HF_DATASET)
with mock.patch.dict(os.environ, {hub.DATASET_ENV: "not a repo"}):
self.assertRaises(hub.HubError, hub.dataset_id)
def test_draft_gate(self):
with mock.patch.object(hub, "texts_draft", return_value=True), \
mock.patch.dict(os.environ, {hub.ALLOW_ENV: ""}):
with self.assertRaises(hub.HubError) as cm:
hub.upload(self.store, SESSION)
self.assertEqual(cm.exception.kind, "closed")
self.assertFalse(hub.upload_allowed())
with mock.patch.object(hub, "texts_draft", return_value=True), \
mock.patch.dict(os.environ, {hub.ALLOW_ENV: "1"}):
self.assertTrue(hub.upload_allowed())
def test_invalid_blocks(self):
with open(os.path.join(self.store.export_dir(SESSION), "extra.bin"), "w") as f:
f.write("x")
with self.assertRaises(hub.HubError) as cm:
hub.upload(self.store, SESSION, dry_run=True)
self.assertEqual(cm.exception.kind, "invalid")
self.assertTrue(cm.exception.errors)
def test_record_and_duplicate(self):
export = self.store.export_dir(SESSION)
sha = hub.export_sha(export)
self.assertEqual(len(sha), 64)
hub.record_upload(self.store, SESSION, {"repo": "a/b", "pr_url": "https://huggingface.co/datasets/a/b/discussions/1",
"uploaded": hub.now_iso(), "export_sha": sha})
# The upload record doesn't make the export look out of date...
self.assertFalse(self.store.sessions()[0]["export_stale"])
# ...and the next upload of the same export stops, unless asked again.
with self.assertRaises(hub.HubError) as cm:
hub.upload(self.store, SESSION, dry_run=True)
self.assertEqual(cm.exception.kind, "duplicate")
self.assertTrue(hub.upload(self.store, SESSION, dry_run=True, again=True)["dry_run"])
# A new export leaves the records out of its manifest.
self.store.export(SESSION, low_priority=False)
with open(os.path.join(export, "manifest.json")) as f:
self.assertNotIn("uploads", json.load(f)["session"])
def test_pull_request_first(self):
"""The pull request opens before the files go; a retry goes on in it."""
calls = []
class Pr:
def __init__(self, num, status="draft"):
self.num, self.status, self.is_pull_request = num, status, True
self.url = f"https://huggingface.co/datasets/a/b/discussions/{num}"
class Api:
fail = True
status = "draft"
def whoami(self):
return {"name": "someone", "auth": {"accessToken": {"role": "write"}}}
def auth_check(self, repo, repo_type=None):
pass
def create_pull_request(self, repo, title, description=None, repo_type=None):
calls.append("create")
return Pr(7)
def get_discussion_details(self, repo, num, repo_type=None):
return Pr(num, Api.status)
def upload_folder(self, **kw):
calls.append(("upload", kw["revision"], kw.get("create_pr")))
if Api.fail:
raise ConnectionResetError("reset")
def change_discussion_status(self, repo, num, status, repo_type=None):
calls.append(("status", num, status))
fake = mock.Mock(HfApi=Api)
seen = []
env = {hub.DATASET_ENV: "a/b", hub.ALLOW_ENV: "1"}
with mock.patch.dict(os.environ, env), mock.patch.object(hub, "_hf", return_value=fake):
with self.assertRaises(hub.HubError):
hub.upload(self.store, SESSION, progress=lambda phase, text, fraction=None, **extra: seen.append(
(phase, extra.get("pr_url"))))
self.assertIn(("opened", "https://huggingface.co/datasets/a/b/discussions/7"), seen)
[rec] = hub.uploads(self.store, SESSION)
self.assertEqual((rec["status"], rec["pr_num"]), ("started", 7))
self.assertIsNone(hub.previous_upload(self.store, SESSION, rec["export_sha"])) # not a duplicate
Api.fail = False
result = hub.upload(self.store, SESSION)
self.assertEqual(calls, ["create", ("upload", "refs/pr/7", None), ("upload", "refs/pr/7", None),
("status", 7, "open")]) # the retry reused #7
self.assertEqual(result["pr_url"], "https://huggingface.co/datasets/a/b/discussions/7")
[rec] = hub.uploads(self.store, SESSION)
self.assertEqual(rec["status"], "done")
with mock.patch.dict(os.environ, env), self.assertRaises(hub.HubError) as cm:
hub.upload(self.store, SESSION, dry_run=True)
self.assertEqual(cm.exception.kind, "duplicate")
def test_explain(self):
try:
import httpx
from huggingface_hub import errors as hf
except ImportError:
self.skipTest("no huggingface_hub")
def response(code):
return httpx.Response(code, request=httpx.Request("POST", "https://huggingface.co/api/x"))
cases = [(hf.GatedRepoError("gated", response=response(403)), "terms"),
(hf.RepositoryNotFoundError("nope", response=response(404)), "not-found"),
(hf.HfHubHTTPError("no", response=response(403)), "permission"),
(hf.HfHubHTTPError("bad token", response=response(401)), "login"),
(hf.LocalTokenNotFoundError("none"), "login"),
(httpx.ConnectError("down"), "network"),
(ConnectionResetError("reset"), "network")]
for exc, kind in cases:
e = hub.explain(exc, "a/b")
self.assertEqual(e.kind, kind, exc)
self.assertIn("https://huggingface.co/datasets/a/b", hub.explain(cases[0][0], "a/b").link)
if __name__ == "__main__":
unittest.main()
+768
View File
@@ -0,0 +1,768 @@
#!/usr/bin/env python3
"""Check a hand recorder export before it's uploaded, or when it's received (DESIGN.md "Upload").
The window runs it before an upload and refuses on errors; the maintainer runs it on each
submission. Standard library only. Given an export folder (takes.py's exports/<session>/), it
checks:
- SHA256SUMS: every file listed and matching, nothing missing from it;
- an allow-list of files: anything else (or a symlink) is an error;
- manifest.json: the schema, required keys and types, and that it agrees with the files;
- the consent version is there, the contributor id is a random uuid4, the contributor is an adult;
- calibration.json has nothing session.py's strip_calibration would still remove;
- device.json (the rig's pose in the CAD frame) holds only cv.cad_from_cal and head, as
plus_x, plus_z and position; sessions recorded before it existed get a warning;
- each sets.bin.zst decompresses to the end (so a truncated one fails) and parses as FHSET01:
every set's header is checked (camera names, sizes, record length) and counted against the
manifest; the pixels themselves aren't looked at;
- every .jsonl line parses, and take.json does;
- the side cameras (sides.py): the session's "sides" decision, and each take's files named
right by it (a warning when it wasn't decided: the maintainer's check tells then);
- the total size.
It runs on Linux and Windows, with Python 3.12 or later. It reports errors (don't upload or accept this) and warnings (look at it).
usage: validate.py DIR [--json] exit status 0: no errors, 1: errors, 2: not an export
"""
import argparse
import hashlib
import json
import math
import os
import re
import shutil
import struct
import subprocess
import sys
import uuid
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from session import _key_identifies, strip_calibration # noqa: E402 (standard library only, next to this file)
# Decompression, the first that's there: Python 3.14's compression.zstd, the zstandard package
# (pip install zstandard: the maintainer's Windows PC), the zstd program.
try:
from compression import zstd as _zstd
except ImportError:
_zstd = None
try:
import zstandard as _zstandard
except ImportError:
_zstandard = None
EXPORT_SCHEMA = 1
TOP_FILES = {"manifest.json", "calibration.json", "device.json", "SHA256SUMS"}
REGION_CONSENT = "2026-10-03" # the consent version that added the residency confirmation
TAKE_FILES = {"prompts.jsonl", "poses.jsonl", "take.json", "sets.bin.zst"}
TAKE_RE = re.compile(r"^\d{2}-[a-z0-9][a-z0-9-]*$")
SESSION_RE = re.compile(r"^\d{8}-\d{6}(?:-\d+)?$")
SUM_RE = re.compile(r"^([0-9a-f]{64}) (\S.*)$")
CAM_NAME_RE = re.compile(r"^[a-z][a-z0-9_]{0,15}$")
TAKE_STATUSES = ("complete", "stopped", "skipped")
HDR = struct.Struct("<8sII") # fh_set_hdr_t: magic, ncams, bytes (hands/track/record.h)
CAM = struct.Struct("<16sIIQQ") # fh_set_cam_t: name, width, height, capture_ns, dqbuf_ns
MAX_CAMS = 16
MIN_SIDE, MAX_SIDE = 16, 4096
# One round is about 10 GB before compression (ft_handrec.ROUND_BYTES), a few GB after it.
WARN_BYTES = 15 * 1000 ** 3
MAX_BYTES = 40 * 1000 ** 3
CHUNK = 1 << 20
OUT_CHUNK = 8 << 20
# zstandard's decompressobj has no output limit: it gets the input this much at a time, so even a
# stream made to inflate hugely gives out a few hundred MB at most per call.
ZSTANDARD_PIECE = 8 << 10
MAX_LISTED = 10 # removed calibration paths and the like: list this many, then "and N more"
class Cancelled(Exception):
pass
class Report:
def __init__(self, path):
self.path = path
self.errors = []
self.warnings = []
self.summary = {}
self.bytes = 0
def error(self, text):
self.errors.append(text)
def warn(self, text):
self.warnings.append(text)
@property
def ok(self):
return not self.errors
def as_dict(self):
return {"path": self.path, "ok": self.ok, "errors": self.errors, "warnings": self.warnings,
"summary": self.summary, "bytes": self.bytes}
def listed(items):
items = list(items)
more = len(items) - MAX_LISTED
return ", ".join(items[:MAX_LISTED]) + (f" and {more} more" if more > 0 else "")
def is_uuid4(s):
try:
u = uuid.UUID(s)
except (TypeError, ValueError, AttributeError):
return False
return u.version == 4 and str(u) == s
def sha256_file(path, step=None, cancelled=lambda: False):
h = hashlib.sha256()
with open(path, "rb") as f:
while chunk := f.read(CHUNK):
if cancelled():
raise Cancelled()
h.update(chunk)
if step:
step(len(chunk))
return h.hexdigest()
# ---------------------------------------------------------------- the files
def walk_files(root, report):
"""The export's files as relative paths, and allow-list errors on the way."""
files = []
for dirpath, dirnames, filenames in os.walk(root):
rel_dir = os.path.relpath(dirpath, root).replace(os.sep, "/")
rel_dir = "" if rel_dir == "." else rel_dir
depth = 0 if not rel_dir else rel_dir.count("/") + 1
for d in list(dirnames):
rel = f"{rel_dir}/{d}" if rel_dir else d
ok = (depth == 0 and d == "takes") or (depth == 1 and rel_dir == "takes" and TAKE_RE.match(d))
if os.path.islink(os.path.join(dirpath, d)):
report.error(f"{rel}: a symlink, not allowed in an export")
dirnames.remove(d)
elif not ok:
report.error(f"{rel}/: not an allowed folder")
dirnames.remove(d)
for name in filenames:
rel = f"{rel_dir}/{name}" if rel_dir else name
full = os.path.join(dirpath, name)
if os.path.islink(full) or not os.path.isfile(full):
report.error(f"{rel}: a symlink or special file, not allowed in an export")
continue
if not ((depth == 0 and name in TOP_FILES) or (depth == 2 and name in TAKE_FILES)):
report.error(f"{rel}: not an allowed file")
files.append(rel)
return sorted(files)
def check_sums(root, files, report, step, cancelled):
path = os.path.join(root, "SHA256SUMS")
if not os.path.isfile(path):
report.error("SHA256SUMS is missing")
return
sums = {}
with open(path, encoding="utf-8", errors="replace") as f:
for n, line in enumerate(f, 1):
line = line.rstrip("\n")
m = SUM_RE.match(line)
if not m:
report.error(f"SHA256SUMS line {n}: not \"<sha256> <path>\"")
continue
digest, rel = m.groups()
if rel.startswith("/") or ".." in rel.split("/") or rel == "SHA256SUMS":
report.error(f"SHA256SUMS line {n}: a path that doesn't belong: {rel}")
continue
if rel in sums:
report.error(f"SHA256SUMS lists {rel} twice")
sums[rel] = digest
present = set(files) - {"SHA256SUMS"}
missing = sorted(set(sums) - present)
if missing:
report.error(f"in SHA256SUMS but missing: {listed(missing)}")
unlisted = sorted(present - set(sums))
if unlisted:
report.error(f"not in SHA256SUMS: {listed(unlisted)}")
bad = []
for rel in sorted(set(sums) & present):
if sha256_file(os.path.join(root, rel), step, cancelled) != sums[rel]:
bad.append(rel)
if bad:
report.error(f"checksum mismatch: {listed(bad)}")
def read_json_file(path, rel, report):
try:
with open(path, encoding="utf-8") as f:
return json.load(f)
except OSError as e:
report.error(f"{rel}: can't read it: {e.strerror or e}")
except ValueError as e:
report.error(f"{rel}: not valid JSON: {e}")
return None
def check_jsonl(path, rel, report, cancelled):
"""Every line a JSON object with a time "t"."""
try:
with open(path, encoding="utf-8") as f:
for n, line in enumerate(f, 1):
if n % 50000 == 0 and cancelled():
raise Cancelled()
if not line.strip():
continue
try:
obj = json.loads(line)
except ValueError as e:
report.error(f"{rel} line {n}: not valid JSON: {e}")
return
if not isinstance(obj, dict) or not isinstance(obj.get("t"), int):
report.error(f"{rel} line {n}: not an object with a time \"t\"")
return
except UnicodeDecodeError:
report.error(f"{rel}: not UTF-8 text")
except OSError as e:
report.error(f"{rel}: can't read it: {e.strerror or e}")
# ---------------------------------------------------------------- FHSET01 inside the zstd stream
class SetParser:
"""Feed it the decompressed stream in pieces: it checks each set's header and skips the
pixels. problem holds the first thing wrong (parsing stops there)."""
def __init__(self):
self.buf = bytearray()
self.skip = 0 # pixel bytes of the current set still to pass over
self.sets = 0
self.raw = 0
self.cams = {} # name -> (width, height), every camera seen
self.first = None # the first set's cameras, [{name, width, height}]
self.last_t = 0
self.backwards = 0 # sets whose earliest dqbuf_ns went back in time
self.problem = ""
def feed(self, data):
if self.problem:
return
self.raw += len(data)
view = memoryview(data)
while len(view) and not self.problem:
if self.skip:
n = min(self.skip, len(view))
self.skip -= n
view = view[n:]
continue
self.buf += view
view = view[len(view):]
self._parse()
def _parse(self):
while not self.problem and not self.skip:
if len(self.buf) < HDR.size:
return
magic, ncams, nbytes = HDR.unpack_from(self.buf, 0)
where = f"set {self.sets + 1}"
if magic != b"FHSET01\0":
self.problem = f"{where}: not an FHSET01 record"
return
if not 0 < ncams <= MAX_CAMS:
self.problem = f"{where}: {ncams} cameras"
return
head = HDR.size + CAM.size * ncams
if len(self.buf) < head:
return
pixels, cams, times = 0, [], []
for k in range(ncams):
raw_name, w, h, _, dqbuf_ns = CAM.unpack_from(self.buf, HDR.size + k * CAM.size)
name_bytes, _, pad = raw_name.partition(b"\0")
name = name_bytes.decode("ascii", errors="replace")
if pad.strip(b"\0") or not CAM_NAME_RE.match(name):
self.problem = f"{where}: a camera name that isn't one: {raw_name!r}"
return
if not (MIN_SIDE <= w <= MAX_SIDE and MIN_SIDE <= h <= MAX_SIDE):
self.problem = f"{where}: camera {name} is {w}x{h}"
return
if self.cams.setdefault(name, (w, h)) != (w, h):
self.problem = f"{where}: camera {name} changed size to {w}x{h}"
return
pixels += w * h
cams.append({"name": name, "width": w, "height": h})
times.append(dqbuf_ns)
if nbytes != head + pixels:
self.problem = f"{where}: {nbytes} bytes, but its cameras need {head + pixels}"
return
if self.first is None:
self.first = cams
t = min(times)
if t < self.last_t:
self.backwards += 1
self.last_t = t
self.sets += 1
rest = len(self.buf) - head
if rest >= pixels:
del self.buf[:head + pixels]
else:
self.skip = pixels - rest
self.buf.clear()
def finish(self):
"""After the stream's end: a set cut short is a problem."""
if not self.problem and (self.skip or self.buf):
self.problem = f"the stream ends inside set {self.sets + 1}"
def find_zstd():
found = shutil.which("zstd")
if found:
return found
return next((p for p in ("/usr/bin/zstd", "/run/host/usr/bin/zstd") if os.access(p, os.X_OK)), None)
class Frames:
"""A zstd stream, decompressed piece by piece with compression.zstd or zstandard, frame after
frame (zstd -T2 may write several). feed(data) yields the output; complete is false while a
frame is unfinished, which at the end of the input means the stream was cut short."""
def __init__(self):
self.dec = self._new()
self.fed = False # the current decompressor has had input
@staticmethod
def _new():
return _zstd.ZstdDecompressor() if _zstd is not None else _zstandard.ZstdDecompressor().decompressobj()
@property
def complete(self):
return self.dec.eof or not self.fed
def feed(self, data):
while data:
if self.dec.eof: # another frame follows the one that ended
self.dec, self.fed = self._new(), False
if _zstd is not None:
out = self.dec.decompress(data, max_length=OUT_CHUNK)
data = b""
self.fed = True
yield out
# More output may wait without more input.
while not self.dec.eof and not self.dec.needs_input:
yield self.dec.decompress(b"", max_length=OUT_CHUNK)
else:
piece, data = data[:ZSTANDARD_PIECE], data[ZSTANDARD_PIECE:]
self.fed = True
out = self.dec.decompress(piece)
if out:
yield out
if self.dec.eof:
data = self.dec.unused_data + data
def check_sets(path, rel, entry, report, step, cancelled):
"""Decompress rel as a stream and parse it. entry: its take in the manifest, or None."""
parser = SetParser()
try:
if _zstd is not None or _zstandard is not None:
frames = Frames()
with open(path, "rb") as f:
while not parser.problem and (data := f.read(CHUNK)):
if cancelled():
raise Cancelled()
step(len(data))
for out in frames.feed(data):
parser.feed(out)
if parser.problem:
break
if not parser.problem and not frames.complete:
report.error(f"{rel}: the zstd stream is cut short")
return
else:
zstd = find_zstd()
if not zstd:
report.warn(f"{rel}: not checked: no zstd (Python 3.14's compression.zstd, the zstandard "
"package or the zstd program)")
return
argv = [zstd, "-dcq", path]
if os.name == "posix" and shutil.which("nice"):
argv = ["nice", "-n", "19"] + argv
proc = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
try:
while not parser.problem and (data := proc.stdout.read(CHUNK)):
if cancelled():
raise Cancelled()
parser.feed(data)
except BaseException:
proc.kill()
proc.wait()
proc.stdout.close()
raise
if parser.problem:
proc.kill()
code = proc.wait()
proc.stdout.close()
step(os.path.getsize(path))
if not parser.problem and code != 0:
report.error(f"{rel}: doesn't decompress (zstd exit {code})")
return
except Cancelled:
raise
except Exception as e: # OSError, compression.zstd.ZstdError
report.error(f"{rel}: doesn't decompress: {e}")
return
parser.finish()
if parser.problem:
report.error(f"{rel}: not a valid FHSET01 recording: {parser.problem}")
return
if parser.sets == 0:
report.error(f"{rel}: holds no frame sets")
if parser.backwards:
report.warn(f"{rel}: {parser.backwards} sets go back in time")
if entry is not None:
if entry.get("sets") != parser.sets:
report.error(f"{rel}: {parser.sets} sets, the manifest says {entry.get('sets')}")
if "raw_bytes" in entry and entry.get("raw_bytes") != parser.raw:
report.error(f"{rel}: {parser.raw} bytes uncompressed, the manifest says {entry.get('raw_bytes')}")
if isinstance(entry.get("cameras"), list) and parser.first is not None and entry["cameras"] != parser.first:
report.error(f"{rel}: its cameras don't match the manifest's")
return parser
# ---------------------------------------------------------------- the manifest
def need(obj, key, types, where, report, required=True):
"""obj[key] if it's of the given type(s); an error otherwise."""
if not isinstance(obj, dict) or key not in obj:
if required:
report.error(f"manifest: {where}{key} is missing")
return None
v = obj[key]
allowed = types if isinstance(types, tuple) else (types,)
if not isinstance(v, allowed) or (isinstance(v, bool) and bool not in allowed):
report.error(f"manifest: {where}{key} has the wrong type ({type(v).__name__})")
return None
return v
def check_pose(pose, where, report, extra=()):
"""A pose as device_config.json has it: plus_x, plus_z, position, each 3 finite numbers."""
if not isinstance(pose, dict):
report.error(f"device.json: {where} isn't an object")
return
for key in ("plus_x", "plus_z", "position"):
v = pose.get(key)
if not (isinstance(v, list) and len(v) == 3 and all(isinstance(x, (int, float)) and not isinstance(x, bool)
and math.isfinite(x) for x in v)):
report.error(f"device.json: {where}.{key} isn't 3 numbers")
unknown = set(pose) - {"plus_x", "plus_z", "position"} - set(extra)
if unknown:
report.error(f"device.json: {where} has unexpected keys: {listed(sorted(unknown))}")
def check_device(dev, report):
"""device.json: only cv.cad_from_cal and head (session.py's _write_device)."""
if not isinstance(dev, dict):
report.error("device.json: not a JSON object")
return
if set(dev) != {"cv", "head"}:
report.error(f"device.json: keys {listed(sorted(dev))}, expected cv and head only")
cv = dev.get("cv")
if not isinstance(cv, dict) or set(cv) != {"cad_from_cal"}:
report.error("device.json: cv should hold cad_from_cal only")
else:
check_pose(cv["cad_from_cal"], "cv.cad_from_cal", report, extra=("method",))
if not isinstance(cv["cad_from_cal"].get("method", ""), str):
report.error("device.json: cv.cad_from_cal.method isn't text")
if "head" in dev:
check_pose(dev["head"], "head", report)
_, removed = strip_calibration(dev)
if removed:
report.error(f"device.json: identifying fields: {listed(removed)}")
def identifying_keys(o, path):
"""Paths of keys under o that name a serial, uuid, mac or id (session.py's rule)."""
out = []
if isinstance(o, dict):
for k, v in o.items():
p = f"{path}.{k}"
out += [p] if _key_identifies(k) else identifying_keys(v, p)
elif isinstance(o, list):
for i, v in enumerate(o):
out += identifying_keys(v, f"{path}[{i}]")
return out
def check_manifest(m, report, root):
"""The manifest's keys and types. Returns {take id: entry} for the file checks."""
if not isinstance(m, dict):
report.error("manifest: not a JSON object")
return {}
if m.get("schema") != EXPORT_SCHEMA:
report.error(f"manifest: schema {m.get('schema')!r}, expected {EXPORT_SCHEMA}")
tool = need(m, "tool", str, "", report)
if tool is not None and not tool.startswith("ft-handrec"):
report.warn(f"manifest: tool is {tool!r}")
need(m, "exported", str, "", report)
sid = need(m, "session_id", str, "", report)
if sid is not None and not SESSION_RE.match(sid):
report.error(f"manifest: session_id {sid!r} isn't a session id")
if sid and SESSION_RE.match(os.path.basename(root)) and os.path.basename(root) != sid:
report.warn(f"the folder is named {os.path.basename(root)}, the manifest's session is {sid}")
contributor = need(m, "contributor", str, "", report)
if contributor is not None and not is_uuid4(contributor):
report.error(f"manifest: the contributor id {contributor!r} isn't a random uuid4")
parent = os.path.basename(os.path.dirname(root))
if contributor and is_uuid4(parent) and parent != contributor:
report.error(f"the export sits under contributor {parent}, but its manifest says {contributor}")
consent = need(m, "consent_version", str, "", report)
if consent is not None and not consent.strip():
report.error("manifest: the consent version is empty")
profile = need(m, "profile", dict, "", report)
if profile is not None:
if profile.get("contributor") != contributor:
report.error("manifest: profile.contributor differs from contributor")
pc = need(profile, "consent", dict, "profile.", report)
if pc is not None:
if pc.get("version") != consent:
report.error("manifest: profile.consent.version differs from consent_version")
if pc.get("adult") is not True:
report.error("manifest: the contributor didn't confirm being 18 or older")
# from consent 2026-10-03: not living in Illinois, Texas or Washington (CONSENT.md)
if str(pc.get("version") or "") >= REGION_CONSENT and pc.get("region_ok") is not True:
report.error("manifest: the contributor didn't confirm not living in Illinois, Texas or Washington")
need(pc, "accepted", str, "profile.consent.", report)
optional = profile.get("optional")
if isinstance(optional, dict) and str(optional.get("notes") or "").strip():
report.warn("the profile's notes are included: check they hold nothing private")
extra = set(profile) - {"schema", "contributor", "consent", "optional"}
if extra:
report.error(f"manifest: the profile has unexpected keys: {listed(sorted(extra))}")
session = need(m, "session", dict, "", report)
if session is not None:
if session.get("contributor") not in (contributor, ""):
report.error("manifest: session.contributor differs from contributor")
for key, t in (("started", str), ("lighting", dict), ("checklist", dict), ("device", dict),
("takes", list)):
need(session, key, t, "session.", report)
if session.get("dry_run"):
report.error("this is a dry-run session: it has no real recordings")
if "uploads" in session:
report.warn("manifest: session.uploads is included (earlier uploads' links)")
if not isinstance(session.get("calibration_removed", []), list):
report.error("manifest: session.calibration_removed isn't a list")
checklist = session.get("checklist")
if isinstance(checklist, dict) and str(checklist.get("notes") or "").strip():
report.warn("the checklist's notes are included: check they hold nothing private")
# Keys only: version strings like SteamVR's "r25358740+28b72a4f-1" look like serials.
keys = identifying_keys(session.get("device"), "session.device")
if keys:
report.error(f"manifest: identifying fields: {listed(keys)}")
if "/home/" in json.dumps(m):
report.warn("manifest: it mentions a home folder path (a username may show)")
entries = {}
takes = need(m, "takes", list, "", report)
for i, t in enumerate(takes or []):
where = f"takes[{i}]."
if not isinstance(t, dict):
report.error(f"manifest: takes[{i}] isn't an object")
continue
tid = need(t, "id", str, where, report)
if tid is None:
continue
if not TAKE_RE.match(tid):
report.error(f"manifest: take id {tid!r} isn't one")
continue
if tid in entries:
report.error(f"manifest: take {tid} is listed twice")
entries[tid] = t
for key, typ in (("section", str), ("title", str), ("status", str), ("sets", int),
("sets_deleted", int), ("cameras", list), ("duration_s", (int, float))):
need(t, key, typ, where, report)
if t.get("status") not in TAKE_STATUSES:
report.warn(f"manifest: take {tid} has status {t.get('status')!r}")
f = t.get("file")
if f is None:
if t.get("sets"):
report.error(f"manifest: take {tid} has {t.get('sets')} sets but no file")
elif f != f"takes/{tid}/sets.bin.zst":
report.error(f"manifest: take {tid}'s file is {f!r}")
elif not isinstance(t.get("raw_bytes"), int):
report.error(f"manifest: take {tid} has a file but no raw_bytes")
check_sides(m, entries, report)
return entries
def check_sides(m, entries, report):
"""Which side camera is which (sides.py): session.sides.swapped is true, false or null, and
every take's files carry names_swapped equal to it (export renames them so)."""
session = m.get("session") if isinstance(m.get("session"), dict) else {}
s = session.get("sides")
if s is None:
report.warn("manifest: no session.sides (recorded before the side cameras were checked): "
"the maintainer's check tells which way round they are")
return
if not isinstance(s, dict) or s.get("swapped") not in (True, False, None):
report.error("manifest: session.sides isn't {\"swapped\": true|false|null, ...}")
return
swapped = s["swapped"]
if swapped is None:
report.warn("the side cameras' naming wasn't decided while recording (no live tracker): "
"the maintainer's check tells which way round they are")
for tid, t in entries.items():
ts = t.get("sides")
if ts is None:
continue
if not isinstance(ts, dict) or ts.get("names_swapped") not in (True, False, None):
report.error(f"manifest: take {tid}'s sides isn't {{\"names_swapped\": true|false|null, ...}}")
elif swapped is not None and ts["names_swapped"] != swapped:
report.error(f"take {tid}: its side cameras aren't named right (names_swapped "
f"{ts['names_swapped']}, the session's swapped {swapped}): export it again")
def summarize(m):
"""What a pull request's description says about the export: takes, minutes, lighting,
objects, controllers, the consent and tool versions."""
if not isinstance(m, dict):
return {}
session = m.get("session") if isinstance(m.get("session"), dict) else {}
checklist = session.get("checklist") if isinstance(session.get("checklist"), dict) else {}
lighting = session.get("lighting") if isinstance(session.get("lighting"), dict) else {}
takes = [t for t in m.get("takes") or [] if isinstance(t, dict)]
seconds = sum(t.get("duration_s") or 0 for t in takes if isinstance(t.get("duration_s"), (int, float)))
return {"session": m.get("session_id", ""), "contributor": m.get("contributor", ""),
"takes": sum(1 for t in takes if t.get("file")), "takes_listed": len(takes),
"sets": sum(t.get("sets") or 0 for t in takes if isinstance(t.get("sets"), int)),
"minutes": round(seconds / 60, 1), "lighting": lighting.get("chosen", ""),
"objects": list(checklist.get("objects") or []), "own_objects": len(checklist.get("own_objects") or []),
"controllers": checklist.get("controllers", ""), "consent_version": m.get("consent_version", ""),
"tool": m.get("tool", "")}
# ---------------------------------------------------------------- all of it
def validate(root, progress=None, cancel=None):
"""Check the export at root. progress(fraction 0..1, text) is called as it goes; cancel()
(or cancel.is_set()) returning true raises Cancelled. Returns a Report."""
root = os.path.abspath(root)
report = Report(root)
cancelled = getattr(cancel, "is_set", cancel) or (lambda: False)
tell = progress or (lambda fraction, text: None)
if not os.path.isdir(root):
report.error(f"{root}: no such folder")
return report
files = walk_files(root, report)
sizes = {rel: os.path.getsize(os.path.join(root, rel)) for rel in files}
report.bytes = sum(sizes.values())
# Work: each file's checksum, plus reading each sets.bin.zst again to decompress it.
total = max(1, report.bytes + sum(n for rel, n in sizes.items() if rel.endswith(".zst")))
done = 0
def step(n, text):
nonlocal done
done += n
tell(min(done / total, 0.999), text)
tell(0.0, "Checking checksums")
check_sums(root, files, report, lambda n: step(n, "Checking checksums"), cancelled)
manifest = None
if "manifest.json" in files:
manifest = read_json_file(os.path.join(root, "manifest.json"), "manifest.json", report)
else:
report.error("manifest.json is missing")
entries = check_manifest(manifest, report, root) if manifest is not None else {}
report.summary = summarize(manifest)
if "calibration.json" in files:
cal = read_json_file(os.path.join(root, "calibration.json"), "calibration.json", report)
if cal is not None:
if not isinstance(cal, dict):
report.error("calibration.json: not a JSON object")
else:
_, removed = strip_calibration(cal)
if removed:
report.error(f"calibration.json: identifying fields left in: {listed(removed)}")
else:
report.warn("no calibration.json: the recordings can't be used in 3D without it")
if "device.json" in files:
dev = read_json_file(os.path.join(root, "device.json"), "device.json", report)
if dev is not None:
check_device(dev, report)
else:
report.warn("no device.json (a session from before it was recorded): the labeller falls back to "
"another unit's head frame")
take_dirs = sorted({rel.split("/")[1] for rel in files if rel.startswith("takes/") and rel.count("/") == 2})
for tid in take_dirs:
if tid not in entries:
report.error(f"takes/{tid}/ isn't in the manifest")
for tid, entry in entries.items():
if tid not in take_dirs:
report.error(f"take {tid} is in the manifest but has no folder")
for tid in take_dirs:
if cancelled():
raise Cancelled()
base = f"takes/{tid}/"
title = (entries.get(tid) or {}).get("title") or tid
for name in ("prompts.jsonl", "poses.jsonl"):
rel = base + name
if rel in sizes:
check_jsonl(os.path.join(root, rel), rel, report, cancelled)
else:
report.warn(f"{rel} is missing")
if base + "take.json" in sizes:
tj = read_json_file(os.path.join(root, base + "take.json"), base + "take.json", report)
if tj is not None and not isinstance(tj, dict):
report.error(f"{base}take.json: not a JSON object")
else:
report.warn(f"{base}take.json is missing")
rel = base + "sets.bin.zst"
entry = entries.get(tid)
if rel in sizes:
check_sets(os.path.join(root, rel), rel, entry, report,
lambda n, title=title: step(n, f"Checking {title}"), cancelled)
elif entry is not None and entry.get("file"):
report.error(f"{rel} is missing")
if report.bytes > MAX_BYTES:
report.error(f"the export is {report.bytes / 1000 ** 3:.1f} GB, over the {MAX_BYTES / 1000 ** 3:.0f} GB limit")
elif report.bytes > WARN_BYTES:
report.warn(f"the export is large: {report.bytes / 1000 ** 3:.1f} GB")
tell(1.0, "Checked")
return report
def main():
ap = argparse.ArgumentParser(description="Check a hand recorder export (an exports/<session>/ folder).")
ap.add_argument("dir")
ap.add_argument("--json", action="store_true", help="print the result as JSON")
a = ap.parse_args()
if not os.path.isdir(a.dir):
print(f"{a.dir}: no such folder", file=sys.stderr)
return 2
if hasattr(os, "setpriority"): # not on Windows
try:
os.setpriority(os.PRIO_PROCESS, 0, 19) # checksums and decompression: stay out of VR's way
except OSError:
pass
report = validate(a.dir)
if a.json:
print(json.dumps(report.as_dict(), indent=2))
else:
for e in report.errors:
print(f"error: {e}")
for w in report.warnings:
print(f"warning: {w}")
s = report.summary
if s:
print(f"{s.get('session')}: {s.get('takes')} takes, {s.get('sets')} sets, {s.get('minutes')} min, "
f"{report.bytes / 1000 ** 2:.1f} MB, consent {s.get('consent_version') or '-'}")
print("OK" if report.ok else f"{len(report.errors)} errors")
return 0 if report.ok else 1
if __name__ == "__main__":
sys.exit(main())
+146
View File
@@ -0,0 +1,146 @@
// Unit tests for the side cameras' naming check (track/sides.h), on made-up cameras and a
// made-up hand: no models, no recordings. make check (in the dev container) builds and runs it.
#include "../track/sides.h"
#include <cstdio>
#include <cstdlib>
namespace {
int failures = 0;
#define CHECK(c) \
do { \
if (!(c)) std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c), ++failures; \
} while (0)
V3 cross(V3 a, V3 b) { return {a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]}; }
// An equidistant fisheye (k = 0) at origin, looking along look, image "down" toward head -y.
Camera camera(const char *name, V3 origin, V3 look, int w, int h, double f) {
Camera c;
c.name = name, c.width = w, c.height = h, c.fx = c.fy = f, c.cx = w / 2.0, c.cy = h / 2.0;
const V3 z = unit(look), down{0, -1, 0};
const V3 y = unit(down - z * dot(down, z)), x = cross(y, z);
for (int i = 0; i < 3; ++i) c.R[i][0] = x[i], c.R[i][1] = y[i], c.R[i][2] = z[i];
c.origin = origin;
return c;
}
// MediaPipe-like world landmarks (m, hand-centred, flat: z = 0): x across the palm, y along the fingers
const double kHand[21][2] = {{0, 0}, {0.03, 0.03}, {0.05, 0.05}, {0.065, 0.07}, {0.075, 0.09},
{0.025, 0.09}, {0.025, 0.13}, {0.025, 0.155}, {0.025, 0.175}, {0.005, 0.095},
{0.005, 0.14}, {0.005, 0.165}, {0.005, 0.185}, {-0.015, 0.09}, {-0.015, 0.13},
{-0.015, 0.155}, {-0.015, 0.17}, {-0.033, 0.08}, {-0.033, 0.11}, {-0.033, 0.13},
{-0.033, 0.145}};
// The hand with its wrist at p, the palm facing toward `facing`, as cam sees it.
Landmarks view(const Camera &cam, V3 p, V3 facing) {
const V3 n = unit(facing - p), up0{0, 1, 0};
const V3 along = unit(up0 - n * dot(up0, n)), across = cross(along, n);
Landmarks lm;
for (int k = 0; k < 21; ++k) {
const V3 q = p + across * kHand[k][0] + along * kHand[k][1];
lm.pts[k] = cam.project(q, nullptr);
lm.world[k][0] = kHand[k][0], lm.world[k][1] = kHand[k][1], lm.world[k][2] = 0;
}
lm.presence = 0.9;
return lm;
}
Seen seen(const std::string &cam, const Landmarks &lm) { return Seen{cam, 0, Roi{}, lm, {}}; }
} // namespace
int main() {
std::map<std::string, Camera> cams;
cams["slam_left"] = camera("slam_left", {-0.045, 0, -0.03}, {-0.5, -0.6, -0.6}, 1056, 1024, 300);
cams["slam_right"] = camera("slam_right", {0.045, 0, -0.03}, {0.5, -0.6, -0.6}, 1056, 1024, 300);
cams["upper_left"] = camera("upper_left", {-0.03, 0.02, -0.04}, {-0.2, 0.1, -1}, 640, 480, 180);
cams["upper_right"] = camera("upper_right", {0.03, 0.02, -0.04}, {0.2, 0.1, -1}, 640, 480, 180);
const Camera &L = cams["slam_left"], &R = cams["slam_right"], &UL = cams["upper_left"], &UR = cams["upper_right"];
const V3 hand{0.0, -0.22, -0.35}, eyes{0, 0, -0.03};
const Landmarks inL = view(L, hand, eyes), inR = view(R, hand, eyes), inUL = view(UL, hand, eyes),
inUR = view(UR, hand, eyes);
SideCheck sc(cams);
CHECK(sc.usable());
// 1. the side pair, named right: meets as named, not swapped
SideCheck::Miss m = sc.test("slam_left", inL, "slam_right", inR);
std::printf("side pair as named: miss %.4f m as named, %.4f swapped\n", m.m[0], m.m[1]);
CHECK(m.m[0] >= 0 && m.m[0] < 0.001);
CHECK(SideCheck::vote(m) == 0);
// 2. the same images under each other's names (what a backwards ft-camd gives)
m = sc.test("slam_left", inR, "slam_right", inL);
std::printf("side pair swapped: miss %.4f m as named, %.4f swapped\n", m.m[0], m.m[1]);
CHECK(m.m[1] >= 0 && m.m[1] < 0.001);
CHECK(SideCheck::vote(m) == 1);
// 3. a side camera with an upper one
m = sc.test("slam_left", inL, "upper_left", inUL);
CHECK(SideCheck::vote(m) == 0);
m = sc.test("slam_right", inL, "upper_left", inUL); // slam_left's image under slam_right's name
CHECK(SideCheck::vote(m) == 1);
m = sc.test("upper_right", inUR, "slam_left", inR); // ... and the other way round, other order
CHECK(SideCheck::vote(m) == 1);
// 4. the upper pair alone says nothing
CHECK(sc.add({seen("upper_left", inUL), seen("upper_right", inUR)}, 1) == 0);
// 5. two different hands, one in each side camera, don't vote
const V3 other{0.25, -0.3, -0.3};
m = sc.test("slam_left", inL, "slam_right", view(R, other, eyes));
std::printf("two hands: miss %.4f m as named, %.4f swapped\n", m.m[0], m.m[1]);
CHECK(SideCheck::vote(m) == -1);
// 6. a vote needs one way clearly better: both meeting about as well is no vote
CHECK(SideCheck::vote({{0.004, 0.006}}) == -1);
CHECK(SideCheck::vote({{0.004, 0.02}}) == 0);
CHECK(SideCheck::vote({{-1, 0.003}}) == 1);
CHECK(SideCheck::vote({{0.02, -1}}) == -1); // too far apart to be one hand
CHECK(SideCheck::vote({{-1, -1}}) == -1);
// 7. the decision: min_clean votes and none against, or min_votes and at most max_other
// against, over min_span_s
const std::vector<Seen> named = {seen("slam_left", inL), seen("slam_right", inR)};
const std::vector<Seen> swapped = {seen("slam_left", inR), seen("slam_right", inL)};
const int64_t s = 1'000'000'000;
sc.reset();
for (int i = 0; i < 9; ++i) CHECK(sc.add(named, i * s / 5) == 1);
CHECK(sc.verdict() == SideCheck::Undecided); // 9 votes
sc.add(named, 9 * s / 5);
CHECK(sc.verdict() == SideCheck::AsNamed); // 10 clean votes over 1.8 s
std::printf("%s\n", sc.summary().c_str());
// fast: 30 clean votes in 0.97 s aren't enough; the vote at 1.0 s is
sc.reset();
for (int i = 0; i < 30; ++i) sc.add(swapped, i * s / 30);
CHECK(sc.votes[1] == 30 && sc.verdict() == SideCheck::Undecided);
sc.add(swapped, s);
CHECK(sc.verdict() == SideCheck::Swapped);
CHECK(sc.median_miss_mm(1) >= 0 && sc.median_miss_mm(1) < 1);
// one vote against: it waits for min_votes
sc.reset();
sc.add(swapped, 0);
for (int i = 1; i < 20; ++i) sc.add(named, i * s / 10);
CHECK(sc.verdict() == SideCheck::Undecided); // 19 to 1
sc.add(named, 2 * s);
CHECK(sc.verdict() == SideCheck::AsNamed); // 20 to 1
// mixed evidence waits until the other way is at most a fifth of the votes
sc.reset();
for (int i = 0; i < 20; ++i) sc.add(named, i * s / 10);
for (int i = 0; i < 6; ++i) sc.add(swapped, (20 + i) * s / 10);
CHECK(sc.verdict() == SideCheck::Undecided); // 6 of 26
for (int i = 0; i < 4; ++i) sc.add(named, (26 + i) * s / 10);
CHECK(sc.verdict() == SideCheck::AsNamed); // 6 of 30
// the stricter check after a decision
sc.reset();
sc.min_clean = 20, sc.min_votes = 40;
for (int i = 0; i < 19; ++i) sc.add(named, i * s / 10);
CHECK(sc.verdict() == SideCheck::Undecided);
sc.add(named, 2 * s);
CHECK(sc.verdict() == SideCheck::AsNamed);
CHECK(sc.json().find("\"as_named\": 20") != std::string::npos);
// without both side cameras it can't check
std::map<std::string, Camera> one{{"slam_left", L}, {"upper_left", UL}};
SideCheck none(one);
CHECK(!none.usable());
CHECK(none.add(named, 0) == 0);
std::printf(failures ? "%d FAILED\n" : "sides_test: all passed\n", failures);
return failures ? 1 : 0;
}
+274
View File
@@ -0,0 +1,274 @@
#!/usr/bin/env python3
"""Tests for hands/camcheck.py: the real XRService log of 2026-10-02 (a good start at 13:39,
the VCINT failure after the 17:02 wake) cut at several points, synthetic logs for the other
cases, and a made-up ft-camd ring. Nothing here touches SteamVR or the cameras.
python3 hands/tests/test_camcheck.py
"""
import io
import json
import os
import shutil
import struct
import sys
import tempfile
import time
import unittest
from contextlib import redirect_stdout
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(HERE))
import camcheck # noqa: E402
REAL_LOG = os.path.expanduser("~/.local/share/Steam/logs/XRService-2026.10.02/XRService-13-39-32.log")
def L(t, text, level="INFO"):
"""A log line as XRService writes it (with its colour codes on INFO lines)."""
if level == "INFO":
return "Fri Oct 02 2026 %s.000000 INFO: \x1b[0;36m%s\x1b[0m" % (t, text)
return "Fri Oct 02 2026 %s.000000 %s: %s" % (t, level, text)
START = [L("10:00:00", "XRService logging to /tmp/x.log. Use --showLogToConsole to see it here as well")]
GOOD_OPEN = [
L("10:00:01", "FPGA state check: PASSTHRU (register value: 0x00011212)"),
L("10:00:01", "Passthrough connected but FPGA is PASSTHRU - loading VCINT"),
L("10:00:01", "Loading FPGA image: VCINT"),
L("10:00:02", "FPGA image VCINT loaded and verified successfully"),
L("10:00:02", "Upper cameras FPGA interleaving support: 1 (Driver features available = 1 | VCINT loaded = 1)"),
L("10:00:02", "[buildMediaCtlSetupTasks] Created 6 tasks (4 tracking, 2 passthrough)"),
] + [L("10:00:03", "TrackingCameraInit: index: %d. video device: /dev/video%d. v4l subdevice: /dev/v4l-subdev3%d"
% (i, n, i)) for i, n in enumerate((9, 13, 6, 7))]
CLOSE = [L("11:00:00", "[SystemdInhibitor] Received systemd suspend notification"),
L("11:00:00", "[DeckardCaptureSource] Closing tracking camera interfaces camerasToUse: 1111"),
L("11:00:01", "[DeckardCaptureSource] Streaming paused")]
RESUME = [L("11:30:00", "[SystemdInhibitor] Received systemd resume notification"),
L("11:30:00", "Failed to read FPGA register 0x12 (exit code 256)", "ERROR"),
L("11:30:00", "Passthrough connected but FPGA is ERROR/UNKNOWN - loading VCINT"),
L("11:30:00", "Loading FPGA image: VCINT")]
FAIL = [L("11:30:01", "FPGA load failed (exit code 256): Loading VC Interleaving FPGA image", "ERROR"),
"Loading FPGA image from bitstream file /usr/lib/deckard-fpga/images/csi_agg_deckard_ev1_1_vcint.binx",
" FAILED: FPGA config_done signal did not assert",
L("11:30:01", "Failed to load VCINT FPGA image when passthrough cameras are connected", "ERROR"),
L("11:30:01", "Upper cameras FPGA interleaving support: 0 (Driver features available = 1 | VCINT loaded = 0)"),
L("11:30:01", "[buildMediaCtlSetupTasks] Created 4 tasks (2 tracking, 2 passthrough)"),
L("11:30:01", "TrackingCameraInit: index: 0. video device: /dev/video9. v4l subdevice: /dev/v4l-subdev31"),
L("11:30:01", "TrackingCameraInit: index: 1. video device: /dev/video13. v4l subdevice: /dev/v4l-subdev30"),
L("11:30:02", "[DeckardCaptureSource] Streaming resumed (FPGA: PASSTHRU, VC interleaving: disabled)")]
# A wake that works prints no "Created N tasks" (2026-10-01 16:39), so an older one must not count.
RESUME_OK = [L("12:30:00", "[SystemdInhibitor] Received systemd resume notification"),
L("12:30:00", "Passthrough connected but FPGA is ERROR/UNKNOWN - loading VCINT"),
L("12:30:01", "FPGA image VCINT loaded and verified successfully"),
L("12:30:01", "FPGA state check: VCINT (register value: 0x00021211)"),
L("12:30:01", "Upper cameras FPGA interleaving support: 1 (Driver features available = 1 | VCINT loaded = 1)")] + \
[L("12:30:01", "TrackingCameraInit: index: %d. video device: /dev/video%d. v4l subdevice: x" % (i, n))
for i, n in enumerate((9, 13, 6, 7))] + \
[L("12:30:02", "[DeckardCaptureSource] Streaming resumed (FPGA: VCINT, VC interleaving: enabled)")]
EXIT = [L("13:00:00", "XRService - main thread exiting"), L("13:00:00", "Exiting XRService")]
def state(lines):
return camcheck.LogState("test").feed_text("\n".join(lines))
class SyntheticLogs(unittest.TestCase):
def test_good_start(self):
st = state(START + GOOD_OPEN)
self.assertEqual(st.verdict()[:2], ("ok", "4 tracking cameras running"))
self.assertEqual(st.episode["vcint"], "ok")
self.assertEqual(st.upper_nodes(), (6, 7))
def test_good_start_tasks_only(self):
# "Created 6 tasks (4 tracking ...)" and no camera init yet: 4 tracking cameras planned
self.assertEqual(state(START + GOOD_OPEN[:6]).verdict()[0], "ok")
def test_starting(self):
self.assertEqual(state(START + GOOD_OPEN[:3]).verdict()[:2], ("unknown", "the cameras are starting"))
def test_vcint_already_loaded(self):
# A SteamVR restart in the same boot (2026-10-01 15:27): the FPGA still has VCINT.
lines = START + [L("10:00:01", "FPGA state check: VCINT (register value: 0x00021211)"),
L("10:00:01", "Upper cameras FPGA interleaving support: 1 (Driver features available = 1 | VCINT loaded = 1)"),
L("10:00:01", "[buildMediaCtlSetupTasks] Created 6 tasks (4 tracking, 2 passthrough)")]
st = state(lines)
self.assertEqual(st.verdict()[0], "ok")
self.assertEqual(st.episode["vcint"], "loaded")
def test_asleep(self):
status, reason, ev = state(START + GOOD_OPEN + CLOSE).verdict()
self.assertEqual(status, "unknown")
self.assertIn("closed", reason)
self.assertTrue(any("Closing tracking camera interfaces" in e for e in ev))
def test_vcint_failure(self):
st = state(START + GOOD_OPEN + CLOSE + RESUME + FAIL)
status, reason, ev = st.verdict()
self.assertEqual((status, reason), ("degraded", camcheck.VCINT_REASON))
self.assertTrue(any("Created 4 tasks (2 tracking, 2 passthrough)" in e for e in ev))
self.assertTrue(any("Closing tracking camera interfaces" in e for e in ev))
self.assertFalse(any("\x1b" in e for e in ev))
self.assertEqual(st.snapshot()["failure"], "test@11:30:01")
self.assertEqual(len(st.failures), 1)
def test_failure_seen_before_the_cameras_start(self):
# the failure line alone (camera init not logged yet): degraded already
st = state(START + GOOD_OPEN + CLOSE + RESUME + FAIL[:4])
self.assertEqual(st.verdict()[0], "degraded")
def test_wake_after_failure_works(self):
st = state(START + GOOD_OPEN + CLOSE + RESUME + FAIL + CLOSE + RESUME_OK)
self.assertEqual(st.verdict()[0], "ok")
self.assertEqual(st.snapshot()["failure"], "")
self.assertEqual(len(st.failures), 1) # still remembered for the log's history
def test_fewer_cameras_without_vcint(self):
lines = START + [L("10:00:01", "[buildMediaCtlSetupTasks] Created 4 tasks (2 tracking, 2 passthrough)")]
status, reason, _ = state(lines).verdict()
self.assertEqual(status, "degraded")
self.assertEqual(reason, "only 2 of 4 tracking cameras running")
def test_exited_and_empty(self):
self.assertEqual(state(START + GOOD_OPEN + EXIT).verdict()[0], "unknown")
self.assertEqual(state([]).verdict()[0], "unknown")
self.assertEqual(state(START).verdict()[:2], ("unknown", "the cameras haven't started yet in this log"))
def test_new_instance_resets(self):
st = state(START + GOOD_OPEN + CLOSE + RESUME + FAIL + START + GOOD_OPEN)
self.assertEqual(st.verdict()[0], "ok")
self.assertEqual(st.failures, [])
def test_incremental_equals_whole(self):
text = "\n".join(START + GOOD_OPEN + CLOSE + RESUME + FAIL)
st = camcheck.LogState("test")
for line in text.split("\n"):
st.feed(line + "\n")
self.assertEqual(st.snapshot(), state(START + GOOD_OPEN + CLOSE + RESUME + FAIL).snapshot())
@unittest.skipUnless(os.path.exists(REAL_LOG), "the 2026-10-02 XRService log isn't on this machine")
class RealLog(unittest.TestCase):
"""The log with both the good 13:39 start and the 17:02 failure, cut in copies in /tmp."""
@classmethod
def setUpClass(cls):
with open(REAL_LOG, errors="replace") as f:
cls.lines = f.read().split("\n")
cls.tmp = tempfile.mkdtemp(prefix="camcheck-test-")
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tmp, ignore_errors=True)
def cut_after(self, needle, nth=1):
"""The log up to and including the nth line containing needle, as a file in /tmp."""
seen = 0
for i, line in enumerate(self.lines):
if needle in line:
seen += 1
if seen == nth:
path = os.path.join(self.tmp, "cut-%d.log" % i)
with open(path, "w") as f:
f.write("\n".join(self.lines[:i + 1]) + "\n")
return path
self.fail("no line %d with %r" % (nth, needle))
def check(self, path):
return camcheck.check(log=path, proc=False, ring=False)
def test_cut_points(self):
cases = [
("Loading FPGA image: VCINT", 1, "unknown", "the cameras are starting"),
("FPGA image VCINT loaded and verified successfully", 1, "unknown", "the cameras are starting"),
("Created 6 tasks (4 tracking, 2 passthrough)", 1, "ok", None),
("TrackingCameraInit: index: 3.", 1, "ok", None),
("Upper cameras are not in sync", 1, "ok", None), # 15:45: a resync, not a failure
("Closing tracking camera interfaces", 1, "unknown", None), # 16:41: asleep
("Passthrough connected but FPGA is ERROR/UNKNOWN", 1, "unknown", "the cameras are starting"),
("Failed to load VCINT FPGA image", 1, "degraded", camcheck.VCINT_REASON),
("Created 4 tasks (2 tracking, 2 passthrough)", 1, "degraded", camcheck.VCINT_REASON),
("Streaming resumed (FPGA: PASSTHRU", 1, "degraded", camcheck.VCINT_REASON),
]
for needle, nth, status, reason in cases:
with self.subTest(cut=needle):
r = self.check(self.cut_after(needle, nth))
self.assertEqual(r["status"], status, r["summary"])
if reason:
self.assertEqual(r["reason"], reason)
r = self.check(self.cut_after("Closing tracking camera interfaces"))
self.assertIn("closed", r["reason"])
def test_whole_log(self):
r = self.check(REAL_LOG)
self.assertEqual(r["summary"], camcheck.DEGRADED_VCINT)
ev = "\n".join(r["evidence"])
for want in ("17:02:47 Failed to load VCINT FPGA image", "interleaving support: 0",
"Created 4 tasks (2 tracking, 2 passthrough)", "/dev/video9", "/dev/video13",
"Closing tracking camera interfaces"):
self.assertIn(want, ev)
self.assertNotIn("/dev/video6", ev) # the 13:39 start isn't this episode's evidence
self.assertTrue(r["failure"].endswith("@17:02:47"))
self.assertTrue(camcheck.is_vcint_failure(r))
def test_cli(self):
out = io.StringIO()
with redirect_stdout(out):
code = camcheck.main(["--log", REAL_LOG, "--no-proc", "--no-ring", "--json"])
self.assertEqual(code, 1)
self.assertEqual(json.loads(out.getvalue())["status"], "degraded")
out = io.StringIO()
with redirect_stdout(out):
code = camcheck.main(["--log", self.cut_after("TrackingCameraInit: index: 3."), "--no-proc", "--no-ring"])
self.assertEqual(code, 0)
self.assertEqual(out.getvalue().split("\n")[0], "ok")
def make_ring(path, mono_names, alive=True):
"""A ring header as ft-camd writes it (camd/fhring.h), no frames."""
cams = [(b"og01a1b", n.encode(), 9 + i) for i, n in enumerate(mono_names)]
hb = time.clock_gettime_ns(time.CLOCK_MONOTONIC) if alive else 1
data = bytearray(camcheck.RING_HDR.pack(b"FHRING01", 1, 0, len(cams), 0, 0, 4242, 0))
struct.pack_into("<Q", data, 40, hb)
for sensor, name, node in cams:
data += camcheck.RING_CAM.pack(sensor, name, node, 0, 1056, 1024, 1056, 16, 0, 0, 0, 0, 0, 0, 0.0)
with open(path, "wb") as f:
f.write(bytes(data))
class Ring(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="camcheck-ring-")
self.ring = os.path.join(self.tmp, "cam-ring")
self.log = os.path.join(self.tmp, "x.log")
with open(self.log, "w") as f:
f.write("\n".join(START + GOOD_OPEN) + "\n")
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def test_two_cameras_in_ring(self):
make_ring(self.ring, ["slam_video9", "slam_video13"])
r = camcheck.check(log=self.log, proc=False, ring_path=self.ring)
self.assertEqual(r["status"], "degraded")
self.assertIn("ft-camd publishes only 2 of 4", r["reason"])
def test_four_cameras_in_ring(self):
make_ring(self.ring, ["a_video9", "b_video13", "c_video6", "d_video7", "a_video9_dk"])
r = camcheck.check(log=self.log, proc=False, ring_path=self.ring)
self.assertEqual(r["status"], "ok")
self.assertEqual(len(r["ring"]["mono"]), 4) # the dark twin doesn't count
def test_stale_ring_ignored(self):
make_ring(self.ring, ["slam_video9"], alive=False)
r = camcheck.check(log=self.log, proc=False, ring_path=self.ring)
self.assertEqual(r["status"], "ok")
self.assertIn("stale ring", "\n".join(r["evidence"]))
def test_no_ring(self):
r = camcheck.check(log=self.log, proc=False, ring_path=os.path.join(self.tmp, "none"))
self.assertEqual(r["status"], "ok")
self.assertIsNone(r["ring"])
if __name__ == "__main__":
unittest.main()
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff. Show more