Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0821b1013e | ||
|
|
3cccad3525 | ||
|
|
276c1409e8 | ||
|
|
a0fe3bb55e | ||
|
|
13198bc203 | ||
|
|
42a26753d3 | ||
|
|
0f0674ff36 | ||
|
|
3a796b5013 | ||
|
|
67a3c02e31 | ||
|
|
662919babf | ||
|
|
98bd6ce21c | ||
|
|
608ad6034a | ||
|
|
336a60ce32 | ||
|
|
e1f27958ca | ||
|
|
c969963b83 | ||
|
|
9f2ee5ad68 | ||
|
|
dfc8e6eb5f | ||
|
|
1037d4e125 | ||
|
|
307e2b7308 | ||
|
|
d39fbb9146 | ||
|
|
7fe5d8c0dd | ||
|
|
6df6f97937 | ||
|
|
ca9492be00 | ||
|
|
41b5b68a41 | ||
|
|
9d7c8a0b91 | ||
|
|
5e3323c188 | ||
|
|
25504e0ed4 | ||
|
|
ec870d2d7a | ||
|
|
80797c98b9 | ||
|
|
2fadbbe148 | ||
|
|
5ee07f99a8 | ||
|
|
f0b93b79d3 | ||
|
|
13a530d829 | ||
|
|
f260a6a9e4 | ||
|
|
2e09cf9efe | ||
|
|
9a4b66ff50 | ||
|
|
17269134ce | ||
|
|
d995b815f8 | ||
|
|
f18918f781 | ||
|
|
e0208687b6 | ||
|
|
c699e13104 | ||
|
|
9b12b7d74e | ||
|
|
c7c7c1f772 | ||
|
|
2486a601e3 | ||
|
|
de25633f87 | ||
|
|
53a1836dbb | ||
|
|
73bd0ea28f | ||
|
|
519c623ea9 | ||
|
|
8b1327fe1a | ||
|
|
2351cec310 | ||
|
|
1eb120e6b1 | ||
|
|
8321a99121 | ||
|
|
ea483f7ce3 | ||
|
|
e62ebb8669 | ||
|
|
6fb168a8b8 | ||
|
|
8dbcdecf90 | ||
|
|
b67c973f64 | ||
|
|
99aec84f62 | ||
|
|
e44837cee6 | ||
|
|
95c5d056cf | ||
|
|
e6a931f7ee | ||
|
|
60667dba1f | ||
|
|
0c95d1d731 | ||
|
|
fcb465a45a | ||
|
|
d6930a61f5 | ||
|
|
155deada52 | ||
|
|
597551cf23 | ||
|
|
33fb3bb611 | ||
|
|
6cae2e0afe | ||
|
|
af2ea7c0ee | ||
|
|
060b4957f8 | ||
|
|
57617d4a14 | ||
|
|
83850bb1b7 | ||
|
|
d5a15ebc36 | ||
|
|
b7dfe4759e | ||
|
|
5b6cfcd746 | ||
|
|
e1f7ccee29 | ||
|
|
d8c2ed0c58 | ||
|
|
7851ce90cc | ||
|
|
e1ee5ef395 | ||
|
|
3e7248a04e | ||
|
|
0680297efa | ||
|
|
a11cef49ba | ||
|
|
19032f8963 | ||
|
|
8a02e41b21 | ||
|
|
30e02e9db7 | ||
|
|
06c4ff9556 | ||
|
|
8760ca3083 | ||
|
|
a05e500d30 | ||
|
|
fda6302bd3 | ||
|
|
76e5c4932e | ||
|
|
ae4a1e30ab | ||
|
|
b0415cf150 | ||
|
|
5b08e43a5d | ||
|
|
a533bb973a | ||
|
|
8aaf7db05a | ||
|
|
7fbcd177d3 | ||
|
|
97b7fc837c | ||
|
|
1ebf3692fb | ||
|
|
3ebae6a88f | ||
|
|
554820ffc5 | ||
|
|
bdc84b24d4 | ||
|
|
79eb251d6c | ||
|
|
35196e2955 | ||
|
|
072a294941 | ||
|
|
abb05eb68c | ||
|
|
1fb6e7a38e | ||
|
|
27b731878c | ||
|
|
3b2f065c85 | ||
|
|
c6531148d7 | ||
|
|
7b80592665 | ||
|
|
49b8e050db | ||
|
|
ff36356992 | ||
|
|
4d50739393 | ||
|
|
f60da63702 | ||
|
|
82d2107e1d | ||
|
|
12f2e844d5 | ||
|
|
ee2ce1a8d2 | ||
|
|
7816633353 |
No files matched your search
@@ -26,7 +26,7 @@ A Steam Frame is someone's personal headset, and they may be wearing it while yo
|
||||
|
||||
- Don't kill or restart `gamescope`, `steam`, `vrserver`, `vrcompositor`, the gamescope session, or the Frametop desktop without asking. Each one ends or disrupts whatever is happening in VR.
|
||||
- Don't run host `sudo`, `steamos-readonly disable`, `steamos-devmode` changes, pacman installs, or reboots without explicit approval. Three installers need host `sudo`, and they ask for it: the Bluetooth fixes (`setup/bluetooth/install.sh`), hand tracking (`hands/run.sh install` and `caps`, which set ft-camd's file capabilities with `setcap`), and our own eye tracker's frame grabber (`gaze/tracker/install.sh`).
|
||||
- Write only inside the repo, `/tmp`, and the container unless told otherwise. The installers are the exception: they write the user services, launchers, and the SteamVR driver into the home folder. The Bluetooth fixes and the eye tracker's frame grabber also install root-owned files and system services under `/etc` (`/etc/steamframe`, `/etc/frametop`, `/etc/systemd/system`).
|
||||
- Write only inside the repo, `/tmp`, and the container unless told otherwise. The installers are the exception: they write the user services, launchers, and the SteamVR driver into the home folder. The Bluetooth fixes and the eye tracker's frame grabber also install root-owned files and system services under `/etc` (`/etc/steamframe`, `/etc/frametop`, `/etc/systemd/system`). When an installer starts writing something new outside the repo, add it to `uninstall.sh` too: users uninstall with that script, not with each installer's `uninstall`.
|
||||
- Never copy `.netrc`, SSH keys, or Steam config off the Frame or into this repo.
|
||||
|
||||
## SteamOS updates
|
||||
|
||||
@@ -17,6 +17,8 @@ Join the [Frametop Discord](https://discord.gg/W3X9f7z3Bc) for questions, ideas,
|
||||
|
||||
## 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.
|
||||
@@ -55,10 +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.
|
||||
|
||||
@@ -93,6 +96,18 @@ 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), 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.
|
||||
@@ -122,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
|
||||
@@ -155,23 +171,22 @@ Or by hand: `cd ~/frametop && git pull && ./install.sh`.
|
||||
|
||||
## Uninstall
|
||||
|
||||
In a terminal on the headset, run:
|
||||
|
||||
```
|
||||
./desktops.sh uninstall # the launcher's Desktop entry goes back to the stock desktop
|
||||
./desktops.sh relay uninstall
|
||||
pointer/helper/run.sh uninstall
|
||||
power/run.sh uninstall
|
||||
pointer/driver/install.sh uninstall # then restart SteamVR
|
||||
input-settings/install.sh uninstall
|
||||
display-settings/install.sh uninstall
|
||||
remote/install.sh uninstall
|
||||
setup/bluetooth/install.sh uninstall # if you installed the Bluetooth fixes
|
||||
hands/run.sh uninstall # if you installed hand tracking by hand
|
||||
gaze/run.sh uninstall # if you installed the gaze service
|
||||
gaze/tracker/install.sh uninstall # if you installed our own eye tracker's frame grabber
|
||||
gaze/probe/install.sh uninstall # if you installed the gaze probe
|
||||
curl -fsSL https://deejanuz.github.io/frametop/uninstall.sh | bash
|
||||
```
|
||||
|
||||
Your settings stay: `~/.config/frametop.conf`, `frametop-input.json` (button maps and key combinations), `frametop-layout.json` (the layout and profiles), `frametop-float.json`, and `frametop-remote/` in `~/.config`, and the gaze calibration in `~/.local/state/frametop/gaze`. So does the desktop's own Plasma setup, in `~/.config/frametop`. Delete them too for a clean slate.
|
||||
It works in two steps, so it never takes away the keyboard, mouse, or desktop you're using while it runs:
|
||||
|
||||
1. It stops Frametop from starting. Launch a program → Desktop opens the stock desktop again, and Frametop's services, its SteamVR driver, its menu entries, and the system files of our eye tracker and the Bluetooth fixes are removed (those need your `sudo` password). Everything running now keeps running until you restart the headset, and it offers to restart it for you.
|
||||
2. After the restart, run the same command again. It deletes the code in `~/frametop`, and asks whether to delete your settings, any eye or hand recordings, and the build container (1–2 GB) too.
|
||||
|
||||
To see what it would do without changing anything, add `-s -- --dry-run` after `bash`. If the code isn't in `~/frametop`, add `-s -- --dir <folder>`. From the repo, the same script is `./uninstall.sh`.
|
||||
|
||||
Don't delete `~/frametop` by hand before you uninstall and restart: the desktop and the input relay run from it, and without it Launch a program → Desktop no longer opens anything. If you've already deleted it, the command above still works, since it doesn't need the repo.
|
||||
|
||||
Unless you ask for them to go, your settings stay: `~/.config/frametop.conf`, `frametop-input.json` (button maps and key combinations), `frametop-layout.json` (the layout and profiles), `frametop-float.json`, and `frametop-remote/` in `~/.config`, the gaze calibration in `~/.local/state/frametop`, and the desktop's own Plasma setup in `~/.config/frametop`. A later install picks them up again.
|
||||
|
||||
## How it works
|
||||
|
||||
@@ -181,6 +196,7 @@ A Plasma session runs nested inside ft-screens (`screens/`), a small Wayland com
|
||||
| --- | --- |
|
||||
| `get.sh` | The one-line installer: picks stable or experimental, clones or updates the repo, and runs `install.sh`. |
|
||||
| `install.sh` | The one-step installer. Safe to re-run. |
|
||||
| `uninstall.sh` | The uninstaller: run it, restart the headset, and run it again. It doesn't need the rest of the repo. |
|
||||
| `desktops.sh` | Start, stop, and configure the desktop, and install the input relay. |
|
||||
| `screens/` | ft-screens, the compositor (wlroots and OpenVR). |
|
||||
| `session/` | The desktop session script and its config example. |
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Controller desktop click stability
|
||||
|
||||
Trigger presses reach KDE immediately, but controller motion within 8 logical
|
||||
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
|
||||
@@ -13,11 +13,11 @@ 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 8 on desktop restart):
|
||||
CLI (runtime preferences, reset to 32 on desktop restart):
|
||||
|
||||
```sh
|
||||
input/ft-clickctl status
|
||||
input/ft-clickctl threshold 8
|
||||
input/ft-clickctl threshold 32
|
||||
input/ft-clickctl threshold 0 # disable without a restart
|
||||
```
|
||||
|
||||
@@ -29,6 +29,6 @@ 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. Default threshold is a starting point to test.
|
||||
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.
|
||||
@@ -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.
|
||||
|
||||
@@ -131,7 +133,7 @@ A few overlays need special handling:
|
||||
|
||||
Head follow is experimental and off by default. It works, but it's only lightly tested, and the feel is mostly a matter of its settings; polishing it is left open. With it on (`POINTER_FOLLOW=1`, or a mouse button mapped to Head follow on/off), the cursor rides on a reference direction, where you were facing when your head last settled, and keeps its offset from it. The mouse can put the cursor anywhere up to `POINTER_FOLLOW_REACH` (70 degrees) from the reference, a corner of your view included. While your head stays within `POINTER_LEASH_DEG` of the reference, nothing moves on its own. Once your head has been past the leash for `POINTER_LEASH_DELAY` (0.2 s, so a glance out and back doesn't count), the reference eases to where you're facing (time constant `POINTER_LEASH_RETURN`, 0.2 s), never falling further behind than the leash, and the cursor ends up back where it was in your view. Then it waits for the leash again. Two earlier versions didn't work out. Moving the reference only while your head pulled at the end of the leash left it up to the leash off after you turned back, and getting it centred again meant overshooting with your head. Easing it toward your facing all the time moved the cursor on every small head movement. A leash of 0 makes the reference your facing direction, so the cursor is locked to your view, and mouse movement shifts it within the view. Head roll is ignored, so tilting your head doesn't swing the cursor around. While the left button is held the cursor stays put in the room, so your head can't nudge a click or a drag. When you let go, it carries on from where it is instead of jumping.
|
||||
|
||||
Gaze mode is experimental and off by default (`POINTER_GAZE=1`, the Gaze page of Frametop Input Settings, `gaze/ft-gazectl on`, or a mouse button or key combination mapped to Gaze pointer on/off). It's MAGIC pointing (Zhai, Morimoto and Ihde, 1999): the pointer goes where you look, and the mouse does the last bit. The gaze service (`gaze/ft-gazed`) sends the helper the corrected gaze at 90 Hz (from one eye while the tracker has lost the other), and while the gaze has the pointer, the cursor ray is that gaze from the eye. The pointer is aimed at the gaze each frame, not steered toward it, so nothing can pile up. An earlier try in the gaze probe steered the pointer with relative moves, and lost it when the pointer went idle or a controller had the laser. By default (`POINTER_GAZE_MOUSE_MOVE=held`, the Gaze page's Mouse movement switch) moving the mouse does nothing while the gaze has the pointer: it moves the pointer only while a button is held, as a correction. A bumped or drifting mouse can't pull the pointer off what you're looking at, and every mouse move is a correction, so the lessons aren't polluted by mouse moves to somewhere else (they used to be kept out by an 8 degree limit, which also dropped real corrections when the tracker was further off). With the gaze stale for a second, in a game, or with the headset off, the mouse moves the pointer as usual; with `free`, moving the mouse takes the pointer from the gaze. A left press while the gaze has the pointer isn't sent at once: the pointer stops where the gaze put it, you drag it onto what you meant with the button still down (panels only see it hover), and the release clicks there. Clicking at once clicked wherever the gaze was, often the wrong thing, before you could correct it. The drag is the correction. Snapping the pointer onto buttons and links is deferred: it needs accessibility (AT-SPI) on in the Frametop session, where it's off (no registry runs), plus app restarts, and it makes Chromium and Electron apps use more CPU. A press held still for `POINTER_GAZE_HOLD` (0.5 s) becomes a real press, so drags still work: hold, then move. The right button works the same way, with the right click on the release, and pressing it while the left press is held back starts a drag where the pointer is, like Meta+J then Meta+K. That drag lasts while either button (or key) is held, so a second right press, or a second Meta+K, is free to pan and tilt the panel being dragged; with the keyboard, the head turns it. Outside games the pointer then stays: the mouse going idle doesn't release it. A moving controller still releases it, as without gaze. Gaze mode is a mouse and keyboard feature: Steam reads the Frame controllers itself, outside SteamVR's bindings, so controller clicks at the gaze kept knocking SteamVR out of laser mode (see `docs/gaze-controllers.md`). Keyboard clicks (Meta+J, Meta+K) hold the dot still in your view while the keys are down, so the head, not the mouse, does the last bit; a quick tap clicks where the dot was at the press, since the head moves as you hit the keys. The relay hides Meta from the desktop as soon as such a combination fires, because KWin takes Meta with a mouse button as a window move or resize, which swallowed the clicks. The dot shows all the time by default. With `POINTER_GAZE_DOT=moving` it shows only while the mouse moves it (`POINTER_GAZE_SHOW`), while a press is held, and as a pulse for each click; otherwise it's transparent, so the laser still lands on it. Looking more than `POINTER_GAZE_RETAKE` (5 degrees) away from it, with the mouse still, gives it back, so small eye movements around the pointer don't pull it off what you're doing. A mouse nudge before a click whose correction is within `POINTER_GAZE_NUDGE_MAX` (55 degrees, half of what the headset shows across) is sent to the gaze service as a lesson: you were looking at where you clicked when the mouse took over, so the nudge is the eye tracker's error there. Using it is what calibrates it. A one-dot check in a panel fixed to the headset tops that up when the headset goes on, when our tracker thinks it moved, and when a correction is past that limit (the tracker is far off, so a click there isn't trusted as a lesson), and the full calibration and the headset fit check run in the same panel, so everything a user does to calibrate happens in one place in the headset; the gaze probe, a fullscreen GTK app, is the development tool. The limit was 8 degrees, which dropped every correction while our tracker was 12 off. Its dots sit at known directions from the headset, so the panel needs no screen geometry. The quick check's dot takes the gaze once it has held still, so what the tracker says doesn't have to be close for the capture to work. The full calibration's and the five-dot check's dots wait for a click while you look at the dot (a left click or Meta+J), because a steady gaze isn't always on the dot, and take the gaze held still up to the click; a right click or MetLine truncated
|
||||
Gaze mode is experimental and off by default (`POINTER_GAZE=1`, the Gaze page of Frametop Input Settings, `gaze/ft-gazectl on`, or a mouse button or key combination mapped to Gaze pointer on/off). It's MAGIC pointing (Zhai, Morimoto and Ihde, 1999): the pointer goes where you look, and the mouse does the last bit. The gaze service (`gaze/ft-gazed`) sends the helper the corrected gaze at 90 Hz (from one eye while the tracker has lost the other), and while the gaze has the pointer, the cursor ray is that gaze from the eye. The pointer is aimed at the gaze each frame, not steered toward it, so nothing can pile up. An earlier try in the gaze probe steered the pointer with relative moves, and lost it when the pointer went idle or a controller had the laser. By default (`POINTER_GAZE_MOUSE_MOVE=held`, the Gaze page's Mouse movement switch) moving the mouse does nothing while the gaze has the pointer: it moves the pointer only while a button is held, as a correction. A bumped or drifting mouse can't pull the pointer off what you're looking at, and every mouse move is a correction, so the lessons aren't polluted by mouse moves to somewhere else (they used to be kept out by an 8 degree limit, which also dropped real corrections when the tracker was further off). With the gaze stale for a second, in a game, or with the headset off, the mouse moves the pointer as usual; with `free`, moving the mouse takes the pointer from the gaze. A left press while the gaze has the pointer isn't sent at once: the pointer stops where the gaze put it, you drag it onto what you meant with the button still down (panels only see it hover), and the release clicks there. Clicking at once clicked wherever the gaze was, often the wrong thing, before you could correct it. The drag is the correction. Snapping the pointer onto buttons and links is deferred: the session now starts an AT-SPI registry, but apps still need to expose useful accessibility trees (and may need restarting), and it makes Chromium and Electron apps use more CPU. A press held still for `POINTER_GAZE_HOLD` (0.5 s) becomes a real press, so drags still work: hold, then move. The right button works the same way, with the right click on the release, and pressing it while the left press is held back starts a drag where the pointer is, like Meta+J then Meta+K. That drag lasts while either button (or key) is held, so a second right press, or a second Meta+K, is free to pan and tilt the panel being dragged; with the keyboard, the head turns it. Outside games the pointer then stays: the mouse going idle doesn't release it. A moving controller still releases it, as without gaze. Gaze mode is a mouse and keyboard feature: Steam reads the Frame controllers itself, outside SteamVR's bindings, so controller clicks at the gaze kept knocking SteamVR out of laser mode (see `docs/gaze-controllers.md`). Keyboard clicks (Meta+J, Meta+K) hold the dot still in your view while the keys are down, so the head, not the mouse, does the last bit; a quick tap clicks where the dot was at the press, since the head moves as you hit the keys. The relay hides Meta from the desktop as soon as such a combination fires, because KWin takes Meta with a mouse button as a window move or resize, which swallowed the clicks. The dot shows all the time by default. With `POINTER_GAZE_DOT=moving` it shows only while the mouse moves it (`POINTER_GAZE_SHOW`), while a press is held, and as a pulse for each click; otherwise it's transparent, so the laser still lands on it. Looking more than `POINTER_GAZE_RETAKE` (5 degrees) away from it, with the mouse still, gives it back, so small eye movements around the pointer don't pull it off what you're doing. A mouse nudge before a click whose correction is within `POINTER_GAZE_NUDGE_MAX` (55 degrees, half of what the headset shows across) is sent to the gaze service as a lesson: you were looking at where you clicked when the mouse took over, so the nudge is the eye tracker's error there. Using it is what calibrates it. A one-dot check in a panel fixed to the headset tops that up when the headset goes on, when our tracker thinks it moved, and when a correction is past that limit (the tracker is far off, so a click there isn't trusted as a lesson), and the full calibration and the headset fit check run in the same panel, so everything a user does to calibrate happens in one place in the headset; the gaze probe, a fullscreen GTK app, is the development tool. The limit was 8 degrees, which dropped every correction while our tracker was 12 off. Its dots sit at known directions from the headset, so the panel needs no screen geometry. The quick check's dot takes the gaze once it has held still, so what the tracker says doesn't have to be close for the capture to work. The full calibration's and the five-dot check's dots wait for a click while you look at the dot (a left click or Meta+J), because a steady gaze isn't always on the dot, and take the gaze held still up to the click; a rightLine truncated
|
||||
|
||||
Replacing a loaded driver's files, as re-running the installer used to do, leaves SteamVR honoring the virtual controller's hand role but not its laser claim: the dashboard pointer stays unassigned until SteamVR restarts. The driver installer now leaves an unchanged driver in place.
|
||||
|
||||
@@ -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.
|
||||
@@ -165,10 +169,22 @@ The Frame controllers can be mapped like mouse buttons, but they aren't input de
|
||||
|
||||
## The desktop session
|
||||
|
||||
The session is modeled on SteamOS's `steamos-nested-desktop` and runs beside it. It has its own runtime directory, config (`~/.config/frametop`), and state, so it never disturbs the stock desktop's layout or panels. It runs on a private D-Bus from `dbus-run-session`, which has two consequences. KDE only launches apps in systemd scopes when systemd is on the session bus, so everything started in the desktop lands in its systemd unit, and stopping the unit would kill all of it; `session/keep-apps.sh` moves those programs out first. And tools that need the real user bus, like podman and `distrobox-host-exec`, have to be pointed at it explicitly.
|
||||
The session is modeled on SteamOS's `steamos-nested-desktop` and runs beside it. It has its own runtime directory, config (`~/.config/frametop`), and state, so it never disturbs the stock desktop's layout or panels. It runs on a private D-Bus from `dbus-run-session`, which has two consequences. KDE only launches apps in systemd scopes when systemd is on the session bus, so everything started in the desktop lands in its systemd unit, and stopping the unit would kill all of it; `session/keep-apps.sh` moves those programs out first. And tools that need the real user bus, like podman and `distrobox-host-exec`, have to be pointed at it explicitly. Its own config folder also hides SteamVR's path registry (`~/.config/openvr/openvrpaths.vrpath`) from everything started in it: OpenVR programs there fail with `VRInitError_Init_PathRegistryNotFound`, and `vrpathreg adddriver` writes a new registry under `~/.config/frametop/openvr` that has no SteamVR in it and that SteamVR never reads. So Frametop's scripts run SteamVR's tools with `XDG_CONFIG_HOME=~/.config`.
|
||||
|
||||
The VR launcher starts the session from the Steam client, and the client's environment came along: `LD_LIBRARY_PATH` pointing at Steam's own runtime, whose `libavcodec` has no H.264 decoder, so VLC in the desktop couldn't play most videos, plus the client's overlay and launch settings. The session script drops the client's variables before it starts anything. SteamOS's global Mesa settings (`/usr/share/deckard/mesavars.sh`) stay, and the gamescope session's Vulkan layer (`ENABLE_GAMESCOPE_WSI`) is only kept for the gamescope backend.
|
||||
|
||||
### Nested accessibility
|
||||
|
||||
The session drops an inherited `AT_SPI_BUS_ADDRESS`, so apps cannot accidentally use the host desktop's registry. It autostarts `session/ft-atspi` in Plasma phase 2, after KWin has set the nested display environment. The helper gets the live accessibility address from `org.a11y.Bus` on the private session bus, preserves any existing registry owner, updates the accessibility bus's activation environment, and tries `StartServiceByName` first.
|
||||
|
||||
On SteamOS 0.3.0 with at-spi2-core 2.52.0, the native launcher can choose dbus-broker because its process belongs to a systemd user unit. Registry activation then fails: this desktop's private session bus does not have a systemd activation manager. In that case the helper starts only `at-spi2-registryd` on the already-existing accessibility bus. The registry refuses duplicate ownership. Unlike native activation's `--use-gnome-session`, the fallback does not try to register with GNOME's session manager; that flag did not explain the observed native activation failure.
|
||||
|
||||
The fallback registry does not exit merely when its bus disconnects in the isolated SteamOS test. Its small watcher checks both private buses every 5 seconds, and terminates and reaps only the child it started when either bus disappears or the watcher is stopped. Each check runs `gdbus` twice; once a second, that cost about 1% of a core. `keep-apps.sh` keeps the watcher in the desktop unit when `desktops.sh start` runs the desktop as `frametop-desktop`. Started from the VR launcher, the desktop runs in steam.service, which doesn't stop with it, so there the watcher is the only thing that stops the registry. There is no second accessibility bus, global systemd environment update, process-name kill, or host registry replacement. Missing accessibility files or bus errors are nonfatal; the desktop still starts. Toolkit-specific accessibility opt-ins and pointer snapping are separate work.
|
||||
|
||||
Run the isolated checks on the host with `/usr/bin/python3 session/test/test_accessibility.py`. They use private D-Bus buses, Xvfb and a GTK3 app, never the production display or input. Native activation uses a small `org.a11y.Bus` test provider pointing to a real private dbus-daemon with the installed registry service; the SteamOS fallback uses the installed bus launcher and broker. The tests check real app-tree discovery, existing owners, concurrent starts, session stop/restart, and teardown. They require test-only PyGObject (Gio and GTK3), Xvfb, and at-spi2-core; the runtime helper uses Python's standard library and the existing host `gdbus`. Actual Plasma autostart and VR desktop restart still require an approved hardware test.
|
||||
|
||||
### Other session behavior
|
||||
|
||||
Steam, not systemd, suspends the Frame: after `system_idle_suspend_ac_sec` (an hour by default) without input on AC power, it logs `Switching to power state: k_ESystemPowerState_Sleep` and suspends, even while charging. It's a Steam setting (Settings → Power → When Plugged In and Idle → Sleep after), which the Stay awake while plugged in switch in Frametop Display Settings sets to Never. SteamVR's standby, which turns the displays off when the headset comes off, is separate; see below.
|
||||
|
||||
Flatpak apps need `XDG_DATA_DIRS` to include Flatpak's exports, or Plasma opens Discover instead of launching them, so the session sources `/etc/profile.d/flatpak.sh`.
|
||||
@@ -177,6 +193,14 @@ The private runtime directory also moves the session's document portal to `$XDG_
|
||||
|
||||
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-`.
|
||||
|
||||
## Displays off on a stand
|
||||
@@ -189,6 +213,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 +238,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.
|
||||
@@ -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.
|
||||
|
||||
@@ -18,6 +18,18 @@ 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.
|
||||
|
||||
The nested session also starts an AT-SPI accessibility registry through `session/ft-atspi` in Plasma's autostart. It discovers the bus from this session, ignores an inherited host accessibility address, and leaves an existing registry alone. Accessibility errors do not stop the desktop. This supplies the registry infrastructure for apps that expose AT-SPI trees; it does not enable gaze snapping or force Chromium/Electron accessibility. After an approved desktop restart, an AT-SPI-aware app should be visible on the nested bus. See [design.md](design.md#nested-accessibility) for native activation, fallback lifecycle, and the isolated test command.
|
||||
|
||||
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 +40,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 +64,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 +79,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
|
||||
|
||||
@@ -114,12 +130,13 @@ The pointer settings are in `~/.config/frametop.conf`: `POINTER_SENSITIVITY`, `P
|
||||
|
||||
## 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, 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, 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.
|
||||
- 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, 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), and Meta+Shift+F (float window in VR or put it back); 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.
|
||||
- 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.
|
||||
@@ -129,7 +146,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.
|
||||
|
||||
@@ -199,9 +216,36 @@ 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.
|
||||
@@ -219,7 +263,7 @@ Your hands show over the screens: where a tracked hand is between an eye and a s
|
||||
- `ft-camd` borrows XRService's camera buffers and publishes the four IR tracking cameras to `/run/user/UID/frametop-hands/cam-ring`. It runs on the host as `frametop-camd.service`, with file capabilities that `hands/run.sh install` sets through sudo, and it drops them once set up. A rebuild clears them: `hands/run.sh caps`.
|
||||
- `ft-hands` runs in the `dev` container as `frametop-hands.service`. It finds and triangulates the hands, and publishes `hands` (read by ft-screens' cutouts) and `gestures` (pinches and grips, read by the pointer helper) next to the ring.
|
||||
- The install leaves both off, and they don't start with SteamVR. `ft-handsctl on` starts them while SteamVR runs, and `ft-handsctl off` stops them; they also stop with SteamVR. The install links `ft-handsctl` into `~/.local/bin`. `ft-handsctl status` and `ft-handsctl log` (or `hands/run.sh status` and `log`) show how they're doing, `ft-handsctl cutouts on|off` turns just the cutouts off, and `ft-handsctl gestures` shows pinches and grips live.
|
||||
- Settings in `~/.config/frametop.conf`: `HANDS_SWAP_SIDES` (after some SteamVR restarts the side cameras' names come out swapped, and hands land beside the holes; `hands/tools/check_sides.py --ring` tells), `HANDS_CPUS`, the cameras it tracks with (`HANDS_CAMERAS`, `HANDS_BRIGHT`, `HANDS_BRIGHT_ON`, `HANDS_BRIGHT_OFF`, `HANDS_COLOR_LEFT`, `HANDS_COLOR_CROP`), and the pointer helper's `POINTER_HANDS`, `POINTER_PINCH_GAIN`, `POINTER_PINCH_DEADZONE`, `POINTER_GRIP_GAIN`, `POINTER_GRIP_BELOW`, and `POINTER_PINCH_TYPING`. The example config explains each.
|
||||
- Settings in `~/.config/frametop.conf`: `HANDS_SWAP_SIDES` (`auto`, the default: ft-hands tells from the hands when some SteamVR restart has swapped the side cameras' names, and fixes them; `0` or `1` force them, and `hands/tools/check_sides.py --ring` tells which is right), `HANDS_CPUS`, the cameras it tracks with (`HANDS_CAMERAS`, `HANDS_BRIGHT`, `HANDS_BRIGHT_ON`, `HANDS_BRIGHT_OFF`, `HANDS_COLOR_LEFT`, `HANDS_COLOR_CROP`), and the pointer helper's `POINTER_HANDS`, `POINTER_PINCH_GAIN`, `POINTER_PINCH_DEADZONE`, `POINTER_GRIP_GAIN`, `POINTER_GRIP_BELOW`, and `POINTER_PINCH_TYPING`. The example config explains each.
|
||||
|
||||
Details, options, and the recording and replay tools are in [hands/README.md](../hands/README.md).
|
||||
|
||||
@@ -231,6 +275,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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
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.
|
||||
@@ -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 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`.
|
||||
- **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. Our tracker's first calibration has no gaze to go on, since ft-eyes maps pupils to a gaze only once it has a calibration: it opens once SteamVR's tracker sees an eye and ft-eyes answers, and a click takes the 0.6 s up to it, as long as ft-eyes saw each pupil held still then (before 2026-10-05 it waited for a gaze, so a fresh install could never calibrate ours). 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
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -63,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,
|
||||
@@ -83,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
|
||||
@@ -140,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
|
||||
|
||||
|
||||
@@ -230,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)
|
||||
@@ -242,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
|
||||
@@ -399,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")
|
||||
@@ -411,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")
|
||||
@@ -441,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
|
||||
@@ -700,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()
|
||||
@@ -750,6 +850,7 @@ 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(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)
|
||||
@@ -770,6 +871,7 @@ class Service:
|
||||
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()
|
||||
@@ -790,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":
|
||||
@@ -808,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
|
||||
|
||||
@@ -10,7 +10,9 @@ 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
|
||||
@@ -30,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
|
||||
@@ -43,6 +48,13 @@ click with nothing taken after ACCEPT_WAIT, and a failed calibration names its m
|
||||
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).
|
||||
|
||||
Our tracker's first calibration: before it has one, ft-eyes publishes no gaze (it maps pupils
|
||||
to a gaze only with a calibration), so there's no gaze to hold still. Its calibration runs
|
||||
anyway ("blind"): someone in the headset (SteamVR's tracker sees an eye) and ft-eyes answering
|
||||
are enough to start it, each dot stands in for the gaze, and a click takes the CHECK_WINDOW up
|
||||
to it. ft-eyes then checks that each pupil was seen and held still in that window (calib-point)
|
||||
and says why not. Without this, a fresh install could never calibrate our tracker.
|
||||
|
||||
What a capture teaches:
|
||||
our tracker quick and five: a click ("click T YAW PITCH", like a pointer lesson); full:
|
||||
calib-start, a calib-point for each dot, calib-fit (its calibration)
|
||||
@@ -209,7 +221,9 @@ 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.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
|
||||
@@ -294,17 +308,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 ---
|
||||
|
||||
@@ -324,9 +343,17 @@ class Checks:
|
||||
return time.monotonic() - self.seen_at < within
|
||||
|
||||
def can_run(self):
|
||||
"""Someone's in the headset and the tracker is sending."""
|
||||
"""Someone's in the headset and the tracker is sending. Our tracker sends no gaze before
|
||||
its first calibration: then ft-eyes answering (calibrated() is False only once it has)
|
||||
is enough, since the calibration is what it needs (see "first calibration" at the top)."""
|
||||
if self.blind():
|
||||
return self.eyes_seen()
|
||||
return self.eyes_seen() and time.monotonic() - self.svc.last_sample < 2
|
||||
|
||||
def blind(self):
|
||||
"""Our tracker is in use, running, and not calibrated yet: it has no gaze to send."""
|
||||
return self.svc.kind == "own" and self.calibrated() is False
|
||||
|
||||
def on_gaze_on(self):
|
||||
self.full_armed = True
|
||||
self.need_full("gaze mode came on without a calibration")
|
||||
@@ -341,8 +368,10 @@ class Checks:
|
||||
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
|
||||
why = ("the eye tracker isn't sending" if now - self.svc.last_sample >= 2 and not self.blind()
|
||||
else "no eyes seen (is the headset on?)")
|
||||
elif now < self.full_retry_at:
|
||||
return
|
||||
@@ -394,6 +423,9 @@ class Checks:
|
||||
if not self.can_run():
|
||||
return "error the headset is off or the tracker isn't sending"
|
||||
own = svc.kind == "own"
|
||||
blind = self.blind()
|
||||
if blind and kind != "full":
|
||||
return "error our tracker isn't calibrated yet: use Calibrate"
|
||||
if kind == "full" and own:
|
||||
reply = ask(EYES, "calib-start", 3.0)
|
||||
if not reply.startswith("ok"):
|
||||
@@ -402,8 +434,10 @@ 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": {}, "reasons": {}, "fit_reasons": set(), "note": ""}
|
||||
log(f"{kind} check: {reason}")
|
||||
"skipped": 0, "captured": 0, "points": {}, "reasons": {}, "fit_reasons": set(), "note": "",
|
||||
"blind": blind}
|
||||
log(f"{kind} check: {reason}" + (" (our tracker's first: no gaze yet, so each click takes the look "
|
||||
"up to it)" if blind else ""))
|
||||
if kind == "full":
|
||||
st = ask(SCREENS, "state", 0.5).split()
|
||||
if len(st) >= 3 and st[0] == "ok":
|
||||
@@ -490,6 +524,8 @@ class Checks:
|
||||
|
||||
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()
|
||||
@@ -503,6 +539,12 @@ class Checks:
|
||||
return
|
||||
if c["own"]:
|
||||
src = s["src"].get("own") or {}
|
||||
if c["blind"]:
|
||||
# Our tracker's first calibration: no gaze yet, so the dot stands in for it (the
|
||||
# gaze can't seem to move) and a click takes the look up to it. ft-eyes checks
|
||||
# the pupils held still (see the top).
|
||||
yaw, pitch, _ = c["dots"][c["i"]]
|
||||
src = {"hy": yaw, "hp": pitch}
|
||||
else:
|
||||
src = s["src"].get("mmap1") or {}
|
||||
if "hy" not in src:
|
||||
@@ -742,9 +784,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":
|
||||
@@ -820,9 +881,11 @@ 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 not self.eyes_seen(AWAY_MIN):
|
||||
@@ -831,7 +894,11 @@ class Checks:
|
||||
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
|
||||
if not self.check:
|
||||
# A calibration that closed unfinished opens again. Not one still open: gaze mode
|
||||
# coming on wakes our tracker, so its eyes come back just as the calibration
|
||||
# opens, and re-arming then opened a second one when the first ended.
|
||||
self.full_armed = True
|
||||
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())
|
||||
@@ -844,7 +911,8 @@ class Checks:
|
||||
|
||||
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}
|
||||
|
||||
@@ -47,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>
|
||||
@@ -524,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();
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline test of our own eye tracker's first calibration (gaze/gazecheck.py, "blind"): before
|
||||
it has a calibration, ft-eyes publishes no gaze, and the calibration must still open and take
|
||||
its dots. Until 2026-10-05 it couldn't: a fresh install that chose our tracker never calibrated.
|
||||
|
||||
Runs ft-gazed's Service with its sockets renamed and HOME in a temp folder (state and settings
|
||||
go there), a fake pointer helper (gaze mode on, headset worn), a fake ft-gaze (SteamVR sees both
|
||||
eyes; "own" is {"ok":0}, as with an uncalibrated ft-eyes), a fake ft-eyes control socket, and no
|
||||
panel (a stand-in process). Nothing reaches the live gaze service, the pointer helper, ft-eyes,
|
||||
or SteamVR, so it's safe next to them.
|
||||
|
||||
gaze/test/first-calibration-test.py
|
||||
"""
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
HOME = tempfile.mkdtemp(prefix="ft-gaze-first-cal-test-")
|
||||
os.environ["HOME"] = HOME # before gazecal: its STATE, and frametop.conf, follow HOME
|
||||
|
||||
import importlib.machinery # noqa: E402
|
||||
import importlib.util # noqa: E402
|
||||
import json # noqa: E402
|
||||
import selectors # noqa: E402
|
||||
import shutil # noqa: E402
|
||||
import socket # noqa: E402
|
||||
import subprocess # noqa: E402
|
||||
import sys # noqa: E402
|
||||
import threading # noqa: E402
|
||||
import time # noqa: E402
|
||||
|
||||
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_first_cal_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 = f"\0{tag}_panel"
|
||||
gazed.EYES_SOCKET = gazecheck.EYES = f"\0{tag}_eyes"
|
||||
gazed.read_settings = lambda: ("own", "auto", "auto", 55.0)
|
||||
DOTS = 3
|
||||
real_dots = gazecheck.check_dots
|
||||
gazecheck.check_dots = lambda kind, own: real_dots(kind, own)[:DOTS] # a short calibration
|
||||
logs = []
|
||||
gazed.log = gazecheck.log = lambda msg: logs.append(msg)
|
||||
|
||||
# The fake ft-gaze: 90 samples a second, SteamVR sees both eyes, no gaze from ours.
|
||||
FAKE = os.path.join(HOME, "ft-gaze")
|
||||
with open(FAKE, "w") as f:
|
||||
f.write('''import json, os, select, sys, time
|
||||
while True:
|
||||
if select.select([sys.stdin], [], [], 1 / 90)[0]:
|
||||
if not os.read(0, 4096):
|
||||
break
|
||||
print(json.dumps({"t": time.monotonic(), "src": {"mmap1": {"hy": 1.0, "hp": 2.0, "unc": [0.001, 0.001],
|
||||
"open": [0.8, 0.8]}, "own": {"ok": 0}}}), flush=True)
|
||||
''')
|
||||
SLEEPER = [sys.executable, "-c", "import sys; sys.stdin.read()"] # quits when its stdin closes
|
||||
|
||||
|
||||
def start_helper(self):
|
||||
"""ft-gaze, straight from here instead of the dev container."""
|
||||
self.proc = subprocess.Popen([sys.executable, FAKE], 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""
|
||||
|
||||
|
||||
def start_eyes(self):
|
||||
"""ft-eyes' process: a stand-in. Its control socket is the fake below."""
|
||||
self.eyes_proc = subprocess.Popen(SLEEPER, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
os.set_blocking(self.eyes_proc.stderr.fileno(), False)
|
||||
self.sel.register(self.eyes_proc.stderr, selectors.EVENT_READ, "eyes")
|
||||
|
||||
|
||||
def start_panel(self):
|
||||
self.panel_proc = subprocess.Popen(SLEEPER, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
os.set_blocking(self.panel_proc.stderr.fileno(), False)
|
||||
self.sel.register(self.panel_proc.stderr, selectors.EVENT_READ, "panel")
|
||||
|
||||
|
||||
gazed.Service.start_helper = start_helper
|
||||
gazed.Service.start_eyes = start_eyes
|
||||
gazecheck.Checks.start_panel = start_panel
|
||||
|
||||
# The fake ft-eyes: uncalibrated until calib-fit. "fail" answers the next calib-point with that.
|
||||
eyes_state = {"cal": None, "points": [], "fail": None}
|
||||
eyes = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
|
||||
eyes.bind(gazed.EYES_SOCKET)
|
||||
eyes.settimeout(0.2)
|
||||
|
||||
|
||||
def eyes_answer():
|
||||
while True:
|
||||
try:
|
||||
data, addr = eyes.recvfrom(512)
|
||||
except socket.timeout:
|
||||
continue
|
||||
except OSError:
|
||||
return
|
||||
w = data.decode().split()
|
||||
if w[0] == "status":
|
||||
reply = json.dumps({"calibration": eyes_state["cal"], "calibrating": False, "dots": 0,
|
||||
"eyes": {"right": {"reseat": False}, "left": {"reseat": False}}})
|
||||
elif w[0] == "calib-start":
|
||||
eyes_state["points"] = []
|
||||
reply = "ok"
|
||||
elif w[0] == "calib-point":
|
||||
eyes_state["points"].append(tuple(map(float, w[1:5])))
|
||||
reply, eyes_state["fail"] = eyes_state["fail"] or "ok 50 50 1.00 1.00", None
|
||||
elif w[0] == "calib-fit":
|
||||
eyes_state["cal"] = {"made": "test", "dots": len(eyes_state["points"])}
|
||||
reply = f"ok {len(eyes_state['points'])} dots"
|
||||
else:
|
||||
reply = f"fail unknown command {w[0]}"
|
||||
if addr:
|
||||
eyes.sendto(reply.encode(), addr)
|
||||
|
||||
|
||||
threading.Thread(target=eyes_answer, daemon=True).start()
|
||||
|
||||
helper_state = {"reply": "ok off worn", "heard": []}
|
||||
helper = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
|
||||
helper.bind(gazed.POINTER)
|
||||
helper.settimeout(0.2)
|
||||
|
||||
|
||||
def helper_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)
|
||||
else:
|
||||
helper_state["heard"].append(data.decode())
|
||||
|
||||
|
||||
threading.Thread(target=helper_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(3)
|
||||
|
||||
|
||||
def ask(cmd):
|
||||
ctl.sendto(cmd.encode(), gazed.ME)
|
||||
return ctl.recv(65536).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()
|
||||
|
||||
|
||||
def check_state():
|
||||
return svc.checks.check or {}
|
||||
|
||||
|
||||
def take_dot(i):
|
||||
"""Wait for dot i to settle, then click: is it taken?"""
|
||||
wait(lambda: check_state().get("i") == i and not check_state().get("done_at"), 3)
|
||||
time.sleep(gazecheck.CHECK_SETTLE + gazecheck.CHECK_WINDOW + 0.1)
|
||||
before = check_state().get("captured", 0)
|
||||
ask("calaccept")
|
||||
return wait(lambda: check_state().get("captured", 0) > before, 2)
|
||||
|
||||
|
||||
check("gaze mode off, Gaze page open (wake): ours runs, uncalibrated", ask("wake 60"), "ok")
|
||||
check("the service knows ours has no calibration", wait(lambda: svc.checks.calibrated() is False, 6), True)
|
||||
check("a quick check is refused while ours has no calibration", svc.checks.start("quick", "test"),
|
||||
"error our tracker isn't calibrated yet: use Calibrate")
|
||||
helper_state["reply"] = "ok on worn"
|
||||
check("gaze mode on: the calibration opens by itself", wait(lambda: check_state().get("kind") == "full", 6), True)
|
||||
check("it runs blind (no gaze from ours yet)", check_state().get("blind"), True)
|
||||
check("nothing says it can't open", any("can't open" in m for m in logs), False)
|
||||
# Live 2026-10-05: turning gaze mode on woke our tracker, and the calibration opened before
|
||||
# DON_DELAY of eyes had passed, so "the headset went on" came while it was open. That re-armed
|
||||
# it, and a second calibration opened as soon as the first ended.
|
||||
svc.checks.away, svc.checks.back_since = True, None
|
||||
|
||||
check("dot 1: a click takes it", take_dot(0), True)
|
||||
check("the headset went on while it was open",
|
||||
wait(lambda: not svc.checks.away, gazecheck.DON_DELAY + 2) and bool(svc.checks.check), True)
|
||||
t0, t1, yaw, pitch = eyes_state["points"][0]
|
||||
dot = gazecheck.check_dots("full", True)[0]
|
||||
check("its window is the look up to the click (about CHECK_WINDOW)",
|
||||
abs((t1 - t0) - gazecheck.CHECK_WINDOW) < 0.15, True)
|
||||
check("ft-eyes got that dot's direction", (round(yaw, 3), round(pitch, 3)), (round(dot[0], 3), round(dot[1], 3)))
|
||||
|
||||
eyes_state["fail"] = "fail the left eye was seen in only 3 frames"
|
||||
wait(lambda: check_state().get("i") == 1 and not check_state().get("done_at"), 3)
|
||||
time.sleep(gazecheck.CHECK_SETTLE + gazecheck.CHECK_WINDOW + 0.1)
|
||||
ask("calaccept")
|
||||
check("ft-eyes refusing a dot: its reason reaches the panel's note",
|
||||
wait(lambda: "left eye in only 3 frames" in check_state().get("note", ""), 2), True)
|
||||
check("dot 2, second try: taken", take_dot(1), True)
|
||||
check("dot 3: taken", take_dot(2), True)
|
||||
|
||||
check("all dots: ours fits its calibration (calib-fit)",
|
||||
wait(lambda: eyes_state["cal"] is not None and not svc.checks.check, 4), True)
|
||||
check("the service sees it calibrated", wait(lambda: svc.checks.calibrated() is True, 4), True)
|
||||
check("and gaze mode stays on", "gaze off" in helper_state["heard"], False)
|
||||
check("and no second calibration opens", wait(lambda: svc.checks.check is not None, 3), False)
|
||||
check("one calibration in the log", sum(m.startswith("full check:") for m in logs), 1)
|
||||
|
||||
print("FAILED: " + ", ".join(failures) if failures else "all passed", flush=True)
|
||||
svc.running = False
|
||||
time.sleep(0.7)
|
||||
shutil.rmtree(HOME, ignore_errors=True)
|
||||
os._exit(1 if failures else 0)
|
||||
@@ -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)
|
||||
@@ -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
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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__":
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
# Options (piped, they go after "bash -s --"):
|
||||
# --stable the main branch: tested releases (the default for a new install)
|
||||
# --experimental the experimental branch: the newest features, less tested
|
||||
# --branch NAME another branch, such as a fix to test before it's released
|
||||
# --dir DIR where the repo goes (default ~/frametop)
|
||||
# --clone-only get or update the repo, but don't run install.sh
|
||||
# --yes, --no-bluetooth passed to install.sh (--yes also answers this script's question:
|
||||
@@ -17,7 +18,7 @@ set -euo pipefail
|
||||
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
usage: get.sh [--stable | --experimental] [--dir DIR] [--clone-only] [--yes] [--no-bluetooth]
|
||||
usage: get.sh [--stable | --experimental | --branch NAME] [--dir DIR] [--clone-only] [--yes] [--no-bluetooth]
|
||||
piped: curl -fsSL https://deejanuz.github.io/frametop/get.sh | bash -s -- [options]
|
||||
EOF
|
||||
}
|
||||
@@ -31,6 +32,7 @@ main() {
|
||||
case $1 in
|
||||
--stable) branch=main ;;
|
||||
--experimental) branch=experimental ;;
|
||||
--branch) branch=${2:?--branch needs a branch name}; shift ;;
|
||||
--dir) dir=${2:?--dir needs a folder}; shift ;;
|
||||
--clone-only) clone_only=1 ;;
|
||||
--yes) yes=1; pass+=("$1") ;;
|
||||
@@ -80,6 +82,11 @@ main() {
|
||||
fi
|
||||
fi
|
||||
|
||||
if ! git ls-remote --exit-code --heads "$repo" "$branch" >/dev/null; then
|
||||
echo "Frametop has no branch called $branch (or GitHub can't be reached)." >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
if [ ! -e "$dir" ]; then
|
||||
echo "Cloning Frametop ($branch) into $dir"
|
||||
git clone --branch "$branch" "$repo" "$dir"
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
title: Install the Frametop Hand Recorder
|
||||
---
|
||||
|
||||
# Install the Frametop Hand Recorder
|
||||
|
||||
The Hand Recorder records your hands with the Steam Frame's tracking cameras for Frametop's open hand dataset ([DeeJanuz/frametop-hands](https://huggingface.co/datasets/DeeJanuz/frametop-hands) on Hugging Face). These are the Konsole commands to install it.
|
||||
|
||||
> **Fixed in Frametop 0.2.1 (October 5, 2026):** the recorder now works on headsets without the Arcturus color passthrough module too. If you installed it earlier and the camera check stopped with "Not all of the headset's tracking cameras are running (ft-camd publishes only 2 of 4 mono cameras ...)", run the commands under [Update](#update).
|
||||
|
||||
Join the [Frametop Discord](https://discord.gg/W3X9f7z3Bc) for questions and help with recording.
|
||||
|
||||
For now the recorder runs inside Frametop's desktop, so these steps install Frametop first. A standalone recorder that runs from the SteamVR dashboard without Frametop is planned.
|
||||
|
||||
## Before you start
|
||||
|
||||
- You must be 18 or older, and for now you can't take part if you live in Illinois, Texas or Washington (USA). The [consent text](https://github.com/DeeJanuz/frametop/blob/main/hands/rec/CONSENT.md) explains what's recorded and what you agree to. The recorder shows it again before your first session.
|
||||
- You need a Steam Frame on the stable SteamOS release (not the beta), an internet connection, and a keyboard (Bluetooth, or the on-screen one).
|
||||
- You need a `sudo` password. If you've never set one, run `passwd` in Konsole first.
|
||||
- Recordings are several gigabytes per round, and uploading one needs about the same again free while it runs. `df -h ~` shows your free space.
|
||||
|
||||
## Open Konsole
|
||||
|
||||
1. In the launcher, choose Launch a program → Desktop.
|
||||
2. In the application menu, open System → Konsole.
|
||||
|
||||
## 1. Install Frametop
|
||||
|
||||
```
|
||||
curl -fsSL https://deejanuz.github.io/frametop/get.sh | bash -s -- --stable
|
||||
```
|
||||
|
||||
This clones Frametop into `~/frametop` and runs its installer. The first run downloads 1–2 GB. The installer asks a few questions (gaze mode, the eye tracker, the Bluetooth fixes); the defaults are fine. At the end SteamVR restarts, which closes Konsole. If Frametop is already installed, this updates it.
|
||||
|
||||
## 2. Install the Hand Recorder
|
||||
|
||||
After SteamVR restarts, choose Launch a program → Desktop again, open Konsole, and run:
|
||||
|
||||
```
|
||||
~/frametop/hands/rec/install.sh
|
||||
```
|
||||
|
||||
This builds the camera broker, the hand tracker and the headset panel (the first build takes a few minutes), asks for your `sudo` password once to let the camera broker read the cameras, and adds Frametop Hand Recorder to the application menu.
|
||||
|
||||
## 3. Record
|
||||
|
||||
Open Frametop Hand Recorder from the desktop's application menu. It walks you through the consent text, a short checklist, the recording, a review of what you recorded, and the upload to Hugging Face. Nothing leaves the headset until you press Upload.
|
||||
|
||||
## Update
|
||||
|
||||
```
|
||||
curl -fsSL https://deejanuz.github.io/frametop/get.sh | bash -s -- --stable
|
||||
~/frametop/hands/rec/install.sh
|
||||
```
|
||||
|
||||
Run the second command after SteamVR has restarted, as in the install.
|
||||
|
||||
## Uninstall
|
||||
|
||||
```
|
||||
~/frametop/hands/rec/install.sh uninstall
|
||||
```
|
||||
|
||||
This removes the menu entry. Your recordings stay in `~/.local/share/frametop/hands/contrib`; delete that folder to remove them. To remove Frametop as well, follow [Uninstall](https://github.com/DeeJanuz/frametop#uninstall) in the README.
|
||||
|
||||
## Help
|
||||
|
||||
Ask in the [Frametop Discord](https://discord.gg/W3X9f7z3Bc), the [Frametop issues](https://github.com/DeeJanuz/frametop/issues), or the dataset's [discussion page](https://huggingface.co/datasets/DeeJanuz/frametop-hands/discussions). All three are public.
|
||||
@@ -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
|
||||
@@ -36,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 if the hands disagree it logs a warning and publishes the hands' answer as the truth (`sides.json`), so recordings are labelled right. The example config said `0` until 2026-10-05; `scripts/conf-migrate.sh` (run by `install.sh` and `hands/rec/install.sh`) turns that untouched line into `auto`.
|
||||
- `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`.
|
||||
@@ -86,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
|
||||
|
||||
@@ -102,14 +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.
|
||||
- `--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`: 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.
|
||||
- `--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.
|
||||
@@ -197,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.
|
||||
@@ -207,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`).
|
||||
@@ -0,0 +1,459 @@
|
||||
#!/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", "ISP ")
|
||||
# XRService's numbering of its tracking cameras (the TrackingCameraInit index): ft-hands names
|
||||
# them this way too (track/main.cpp, cameras_from_xrservice_log).
|
||||
NAMES = ("slam_left", "slam_right", "upper_left", "upper_right")
|
||||
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+)")
|
||||
# Without the colour module XRService runs the side cameras through the ISP, as NV12 on other
|
||||
# capture pipes (vfe0 and vfe1), and the upper pair on vfe3 and vfe4.
|
||||
RE_ISP = re.compile(r"ISP (enabled|disabled) for tracking cameras")
|
||||
|
||||
|
||||
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": "", "isp": None, "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_ISP.search(text)
|
||||
if m:
|
||||
ep = self._ep(t)
|
||||
ep["isp"] = m.group(1) == "enabled"
|
||||
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 camera_map(self):
|
||||
"""{calibration name: /dev/videoN's N} from the latest camera start's TrackingCameraInit
|
||||
lines (the whole log's when that start has none yet)."""
|
||||
inits = (self.episode or {}).get("inits") or self.nodes
|
||||
return {NAMES[i]: node for i, node in sorted(inits.items()) if 0 <= i < len(NAMES)}
|
||||
|
||||
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 "",
|
||||
"map": {name: {"node": n, "pipe": pipe_name(n)} for name, n in state.camera_map().items()} if state else {},
|
||||
"ring_missing": []}
|
||||
|
||||
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":
|
||||
have = {c["node"] for c in r["mono"]}
|
||||
want = state.tracking_nodes() if state else SIDE_NODES + UPPER_NODES
|
||||
out["ring_missing"] = [n for n in want if n not in have]
|
||||
status, reason = "degraded", ("ft-camd publishes only %d of %d mono cameras, missing %s" % (
|
||||
len(r["mono"]), TRACKING, " ".join("video%d" % n for n in out["ring_missing"]) or "?"))
|
||||
out.update(status=status, reason=reason, evidence=evidence,
|
||||
summary="ok" if status == "ok" else "%s: %s" % (status, reason))
|
||||
return out
|
||||
|
||||
|
||||
def pipe_name(node):
|
||||
"""The capture pipe behind /dev/videoN (msm_vfe3_video0 and so on), or ""."""
|
||||
try:
|
||||
with open("/sys/class/video4linux/video%d/name" % node) as f:
|
||||
return f.read().strip()
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
|
||||
def is_ring_short(result):
|
||||
"""XRService runs all the tracking cameras, but ft-camd doesn't publish them all."""
|
||||
return bool(result) and result.get("status") == "degraded" and bool(result.get("ring_missing"))
|
||||
|
||||
|
||||
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())
|
||||
@@ -379,9 +379,15 @@ static bool resolve_block(cam_t *c)
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
* Through the ISP (no colour module), the near-black exposures come out all zeros,
|
||||
* the same every time, so their dequeues change no buffer and get no votes. Such
|
||||
* an index is left unmapped (slot -1): on_frame counts its frames as dark without
|
||||
* reading them. Most of a camera's indices silent means it isn't streaming yet.
|
||||
*/
|
||||
static bool resolve_each(cam_t *c)
|
||||
{
|
||||
int depth = c->maxindex + 1;
|
||||
int depth = c->maxindex + 1, silent = 0;
|
||||
bool taken[MAX_SLOTS] = { false };
|
||||
|
||||
for (int i = 0; i < depth; i++) {
|
||||
@@ -396,6 +402,12 @@ static bool resolve_each(cam_t *c)
|
||||
}
|
||||
}
|
||||
|
||||
if (c->nobs[i] >= 3 && v1 <= 0.2 * c->nobs[i]) {
|
||||
c->slot_of[i] = -1;
|
||||
silent++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c->nobs[i] < 3 || best < 0 || taken[best] || v1 < 0.8 * c->nobs[i] || v2 > 0.3 * c->nobs[i])
|
||||
return false;
|
||||
|
||||
@@ -403,9 +415,14 @@ static bool resolve_each(cam_t *c)
|
||||
c->slot_of[i] = best;
|
||||
}
|
||||
|
||||
if (silent * 2 > depth)
|
||||
return false;
|
||||
|
||||
printf("%s: queue depth %d, buffers mapped one by one:", c->slug, depth);
|
||||
for (int i = 0; i < depth; i++)
|
||||
printf(" %d", c->slot_of[i]);
|
||||
c->slot_of[i] < 0 ? printf(" -") : printf(" %d", c->slot_of[i]);
|
||||
if (silent)
|
||||
printf(" (- : %d indices whose frames are all zeros, skipped as dark)", silent);
|
||||
printf("\n");
|
||||
return true;
|
||||
}
|
||||
@@ -677,6 +694,12 @@ static void on_frame(cam_t *c, int64_t index, uint32_t seq, uint64_t ts, uint64_
|
||||
|
||||
int slot = c->slot_of[index];
|
||||
|
||||
if (slot < 0) { /* an index whose frames are all zeros (resolve_each): a dark one */
|
||||
c->dark++;
|
||||
c->rc->dropped++;
|
||||
return;
|
||||
}
|
||||
|
||||
/* color runs at 60 fps: skip frames early enough that the asked rate holds, before any sync */
|
||||
if (c->color && color_fps > 0 && evtime - c->last_pub_ns < (uint64_t)(1e9 / color_fps) - 3000000) {
|
||||
c->paced++;
|
||||
|
||||
@@ -544,22 +544,26 @@ static void probe_cameras(xr_state_t *st)
|
||||
/*
|
||||
* qcom-camss can report bytesperline as the visible width while the VFE
|
||||
* writes a larger aligned pitch. sizeimage is right, so derive the pitch.
|
||||
* For NV12, plane 0 normally holds the chroma rows after the luma (the side
|
||||
* cameras through the ISP: 1056 wide, 1152 bytes a row); if it's too small for
|
||||
* that, it holds the luma alone.
|
||||
*/
|
||||
unsigned xr_camera_stride(const xr_camera_t *c)
|
||||
{
|
||||
if (!c->height || !c->planesize[0])
|
||||
return c->bytesperline ? c->bytesperline : c->width;
|
||||
|
||||
double bpp = 1.0;
|
||||
|
||||
if (c->pixfmt == V4L2_PIX_FMT_NV12 || c->pixfmt == V4L2_PIX_FMT_NV21)
|
||||
bpp = 1.5;
|
||||
|
||||
unsigned s = (unsigned)((double)c->planesize[0] / ((double)c->height * bpp));
|
||||
bool yuv = c->pixfmt == V4L2_PIX_FMT_NV12 || c->pixfmt == V4L2_PIX_FMT_NV21;
|
||||
unsigned s = (unsigned)((double)c->planesize[0] / ((double)c->height * (yuv ? 1.5 : 1.0)));
|
||||
|
||||
if (s >= c->width && s <= c->width * 4)
|
||||
return s;
|
||||
|
||||
s = (unsigned)(c->planesize[0] / c->height);
|
||||
|
||||
if (yuv && s >= c->width && s <= c->width * 4)
|
||||
return s;
|
||||
|
||||
return c->bytesperline ? c->bytesperline : c->width;
|
||||
}
|
||||
|
||||
@@ -591,7 +595,20 @@ void xr_camera_layout(const xr_camera_t *c, xr_layout_t *l)
|
||||
l->pitch = xr_camera_stride(c);
|
||||
l->width = c->width < l->pitch ? c->width : l->pitch;
|
||||
|
||||
if (c->pixfmt == V4L2_PIX_FMT_NV12 || c->pixfmt == V4L2_PIX_FMT_NV21) {
|
||||
/*
|
||||
* Without the colour module, XRService runs the side cameras through the
|
||||
* ISP ("ISP enabled for tracking cameras (main VFE available)" in its log),
|
||||
* and they come out NV12. They're mono sensors, so the luma is the image.
|
||||
*/
|
||||
bool yuv = c->pixfmt == V4L2_PIX_FMT_NV12 || c->pixfmt == V4L2_PIX_FMT_NV21;
|
||||
|
||||
if (yuv && c->role && !strcmp(c->role, "tracking")) {
|
||||
l->fmt = XR_FMT_GREY8;
|
||||
l->rows = c->height;
|
||||
return;
|
||||
}
|
||||
|
||||
if (yuv) {
|
||||
l->fmt = XR_FMT_NV12;
|
||||
l->rows = c->height + c->height / 2;
|
||||
} else {
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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.
|
||||
@@ -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`. With `HANDS_SWAP_SIDES` forced to `0` or `1`, the hands still decide what's published once they disagree (state `"forced, disagrees"`; `read_live` also corrects an ft-hands built before that). 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).
|
||||
@@ -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@`.
|
||||
@@ -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"'
|
||||
@@ -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" "$@"
|
||||
@@ -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;
|
||||
@@ -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())
|
||||
@@ -0,0 +1,39 @@
|
||||
#!/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
|
||||
"$root/scripts/conf-migrate.sh" # HANDS_SWAP_SIDES=0, the old default, becomes auto
|
||||
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
|
||||
@@ -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.
|
||||
|
After Width: | Height: | Size: 87 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
After Width: | Height: | Size: 711 KiB |
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 49 KiB |
|
After Width: | Height: | Size: 48 KiB |
|
After Width: | Height: | Size: 56 KiB |
|
After Width: | Height: | Size: 104 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 42 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 65 KiB |
|
After Width: | Height: | Size: 60 KiB |
|
After Width: | Height: | Size: 78 KiB |
|
After Width: | Height: | Size: 42 KiB |
|
After Width: | Height: | Size: 84 KiB |
|
After Width: | Height: | Size: 39 KiB |
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 67 KiB |
|
After Width: | Height: | Size: 53 KiB |
|
After Width: | Height: | Size: 83 KiB |
|
After Width: | Height: | Size: 60 KiB |
|
After Width: | Height: | Size: 42 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 37 KiB |
@@ -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"
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 59 KiB |
|
After Width: | Height: | Size: 52 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 56 KiB |
|
After Width: | Height: | Size: 52 KiB |
|
After Width: | Height: | Size: 48 KiB |
|
After Width: | Height: | Size: 49 KiB |
|
After Width: | Height: | Size: 68 KiB |
|
After Width: | Height: | Size: 53 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 68 KiB |
@@ -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
|
||||
@@ -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"}
|
||||
]}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
"""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
|
||||
if (s.get("state") == "forced, disagrees" and s.get("swapped") is not None
|
||||
and bool(s["swapped"]) == bool(s.get("names_swapped"))):
|
||||
# An ft-hands built before 2026-10-06 kept a forced HANDS_SWAP_SIDES as the truth even
|
||||
# when the hands disagreed. The hands are right: the truth is the other way round.
|
||||
s = dict(s, swapped=not s["swapped"], decided_by="auto")
|
||||
return s
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -0,0 +1,308 @@
|
||||
#!/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)
|
||||
|
||||
def test_read_live_forced(self):
|
||||
"""HANDS_SWAP_SIDES=0 forced and the hands disagree: the hands are the truth, whether
|
||||
ft-hands published them (built after 2026-10-06) or kept the forced value (before)."""
|
||||
d = tempfile.mkdtemp()
|
||||
try:
|
||||
path = os.path.join(d, "sides.json")
|
||||
|
||||
def live(**kw):
|
||||
s = dict(pid=1, ring_ino=0, mode="0", names_swapped=False,
|
||||
updated_ns=time.clock_gettime_ns(time.CLOCK_MONOTONIC), **kw)
|
||||
with open(path, "w") as f:
|
||||
json.dump(s, f)
|
||||
return sides.read_live(path)
|
||||
|
||||
self.assertEqual(live(state="forced", swapped=False, decided_by="config")["swapped"], False)
|
||||
self.assertEqual(live(state="forced, agrees", swapped=False, decided_by="config")["swapped"], False)
|
||||
old = live(state="forced, disagrees", swapped=False, decided_by="config")
|
||||
self.assertEqual((old["swapped"], old["decided_by"]), (True, "auto"))
|
||||
new = live(state="forced, disagrees", swapped=True, decided_by="auto")
|
||||
self.assertEqual((new["swapped"], new["decided_by"]), (True, "auto"))
|
||||
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_read_sides_forced(self):
|
||||
"""PR #4 on the dataset: HANDS_SWAP_SIDES=0 from the old example config, and the hands
|
||||
disagree. The session takes the hands' answer, not the forced one."""
|
||||
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}}
|
||||
self.live(mode="0", state="forced", swapped=False, decided_by="config", names_swapped=False, evidence=None)
|
||||
s._read_sides(force=True)
|
||||
self.assertIs(s._sides_swapped(), False)
|
||||
self.live(mode="0", state="forced, disagrees", swapped=False, decided_by="config", names_swapped=False)
|
||||
s._read_sides(force=True)
|
||||
self.assertIs(s._sides_swapped(), True)
|
||||
self.assertEqual(s._session_json["sides"]["decided_by"], "auto")
|
||||
self.assertEqual(s._session_json["sides"]["reversed_from"]["decided_by"], "config")
|
||||
|
||||
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()
|
||||
@@ -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()
|
||||
@@ -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())
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
#!/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")]
|
||||
# The colour module unplugged while SteamVR runs (2026-10-05 12:42): XRService reopens the
|
||||
# cameras with the side pair through the ISP on vfe0 and vfe1 (NV12); VCINT stays loaded, so the
|
||||
# upper pair stays on vfe2.
|
||||
UNPLUG = [L("12:42:25", "Received passthrough camera connection event (connected=0)"),
|
||||
L("12:42:25", "[DeckardCaptureSource] Closing tracking camera interfaces camerasToUse: 1111"),
|
||||
L("12:42:26", "FPGA state check: VCINT (register value: 0x00021211)"),
|
||||
L("12:42:26", "Upper cameras FPGA interleaving support: 1 (Driver features available = 1 | VCINT loaded = 1)"),
|
||||
L("12:42:26", "[buildMediaCtlSetupTasks] ISP enabled for tracking cameras (main VFE available)"),
|
||||
L("12:42:26", "[buildMediaCtlSetupTasks] Created 4 tasks (4 tracking, 0 passthrough)")] + \
|
||||
[L("12:42:26", "TrackingCameraInit: index: %d. video device: /dev/video%d. v4l subdevice: x" % (i, n))
|
||||
for i, n in enumerate((0, 3, 6, 7))]
|
||||
# Started without the module (FrameEyeCameraFeed's layout): the upper pair on vfe3 and vfe4.
|
||||
NO_MODULE = [L("10:00:02", "[buildMediaCtlSetupTasks] ISP enabled for tracking cameras (main VFE available)"),
|
||||
L("10:00:02", "[buildMediaCtlSetupTasks] Created 4 tasks (4 tracking, 0 passthrough)")] + \
|
||||
[L("10:00:03", "TrackingCameraInit: index: %d. video device: /dev/video%d. v4l subdevice: x" % (i, n))
|
||||
for i, n in enumerate((0, 3, 9, 13))]
|
||||
|
||||
|
||||
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_camera_map_with_module(self):
|
||||
st = state(START + GOOD_OPEN)
|
||||
self.assertEqual(st.camera_map(), {"slam_left": 9, "slam_right": 13, "upper_left": 6, "upper_right": 7})
|
||||
|
||||
def test_module_unplugged(self):
|
||||
st = state(START + GOOD_OPEN + UNPLUG)
|
||||
self.assertEqual(st.verdict()[0], "ok")
|
||||
self.assertIs(st.episode["isp"], True)
|
||||
self.assertEqual(st.camera_map(), {"slam_left": 0, "slam_right": 3, "upper_left": 6, "upper_right": 7})
|
||||
self.assertEqual(st.tracking_nodes(), (0, 3, 6, 7))
|
||||
|
||||
def test_started_without_module(self):
|
||||
st = state(START + NO_MODULE)
|
||||
self.assertEqual(st.verdict()[0], "ok")
|
||||
self.assertEqual(st.camera_map(), {"slam_left": 0, "slam_right": 3, "upper_left": 9, "upper_right": 13})
|
||||
self.assertEqual(st.upper_nodes(), (9, 13))
|
||||
|
||||
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, nodes=None):
|
||||
"""A ring header as ft-camd writes it (camd/fhring.h), no frames."""
|
||||
cams = [(b"og01a1b", n.encode(), nodes[i] if nodes else 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_ring_missing_the_side_cameras(self):
|
||||
# an ft-camd from before NV12 support, without the colour module: only the upper pair
|
||||
with open(self.log, "w") as f:
|
||||
f.write("\n".join(START + NO_MODULE) + "\n")
|
||||
make_ring(self.ring, ["og0ve10_5-003e_video9", "og0ve10_5-0060_video13"], nodes=[9, 13])
|
||||
r = camcheck.check(log=self.log, proc=False, ring_path=self.ring)
|
||||
self.assertEqual(r["status"], "degraded")
|
||||
self.assertEqual(r["ring_missing"], [0, 3])
|
||||
self.assertIn("missing video0 video3", r["reason"])
|
||||
self.assertTrue(camcheck.is_ring_short(r))
|
||||
self.assertFalse(camcheck.is_vcint_failure(r))
|
||||
self.assertEqual(r["map"]["slam_left"]["node"], 0)
|
||||
|
||||
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()
|
||||
@@ -0,0 +1,232 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Tests for hands/ft-camwatch: its decision logic with made-up inputs (worn or not, VR apps,
|
||||
remote viewers, cooldown, once per failure), following a growing log, and its settings. It
|
||||
never notifies or restarts anything here.
|
||||
|
||||
python3 hands/tests/test_camwatch.py
|
||||
"""
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
HANDS = os.path.dirname(HERE)
|
||||
sys.path.insert(0, HANDS)
|
||||
sys.path.insert(0, HERE)
|
||||
from test_camcheck import CLOSE, FAIL, GOOD_OPEN, RESUME, RESUME_OK, START # noqa: E402
|
||||
|
||||
loader = importlib.machinery.SourceFileLoader("camwatch", os.path.join(HANDS, "ft-camwatch"))
|
||||
spec = importlib.util.spec_from_loader("camwatch", loader)
|
||||
cw = importlib.util.module_from_spec(spec)
|
||||
loader.exec_module(cw)
|
||||
|
||||
ON = dict(cw.DEFAULTS, CAMWATCH_AUTO_RESTART="1", CAMWATCH_IDLE_S="60", CAMWATCH_COOLDOWN_MIN="30")
|
||||
OFF = dict(cw.DEFAULTS)
|
||||
IDLE = {"steamvr": True, "worn": False, "vr_apps": [], "remote": []}
|
||||
WORN = dict(IDLE, worn=True)
|
||||
F1, F2 = "a.log@17:02:47", "b.log@18:10:00"
|
||||
|
||||
|
||||
def kinds(acts):
|
||||
return [k for k, _ in acts]
|
||||
|
||||
|
||||
class Decide(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.mem = cw.new_memory()
|
||||
|
||||
def d(self, now, failure, env=IDLE, conf=ON):
|
||||
return cw.decide(now, failure, env, self.mem, conf)
|
||||
|
||||
def test_nothing_wrong(self):
|
||||
self.assertEqual(self.d(0, "", {}), [])
|
||||
self.assertEqual(self.mem["pending"], "")
|
||||
|
||||
def test_notify_once(self):
|
||||
acts = self.d(0, F1, WORN, OFF)
|
||||
self.assertEqual(kinds(acts), ["log", "notify", "log"])
|
||||
self.assertIn("CAMWATCH_AUTO_RESTART=1", acts[2][1])
|
||||
self.assertEqual(self.d(2, F1, WORN, OFF), []) # same failure, same reason: quiet
|
||||
self.assertEqual(self.d(4, F1, IDLE, OFF), []) # off: never restarts, whatever the state
|
||||
self.assertEqual(self.d(1000, F1, IDLE, OFF), [])
|
||||
|
||||
def test_notify_off(self):
|
||||
acts = self.d(0, F1, WORN, dict(OFF, CAMWATCH_NOTIFY="0"))
|
||||
self.assertNotIn("notify", kinds(acts))
|
||||
|
||||
def test_never_while_worn(self):
|
||||
self.d(0, F1, WORN)
|
||||
for t in range(2, 4000, 2):
|
||||
self.assertNotIn("restart", kinds(self.d(t, F1, WORN)))
|
||||
self.assertIn("worn", self.mem["why"])
|
||||
|
||||
def test_restart_after_idle_then_once(self):
|
||||
self.d(0, F1, WORN)
|
||||
self.assertNotIn("restart", kinds(self.d(10, F1, IDLE))) # just taken off: wait
|
||||
self.assertIn("waiting", self.mem["why"])
|
||||
self.assertNotIn("restart", kinds(self.d(69, F1, IDLE)))
|
||||
acts = self.d(70, F1, IDLE)
|
||||
self.assertEqual(kinds(acts), ["log", "restart"])
|
||||
self.assertEqual(acts[1][1], F1)
|
||||
# the same failure again (the new XRService hasn't logged yet, or failed the same way)
|
||||
acts = self.d(72, F1, IDLE)
|
||||
self.assertNotIn("restart", kinds(acts))
|
||||
self.assertIn("restart the headset", self.mem["why"])
|
||||
for t in range(74, 10000, 500):
|
||||
self.assertNotIn("restart", kinds(self.d(t, F1, IDLE)))
|
||||
|
||||
def test_put_on_resets_the_wait(self):
|
||||
self.d(0, F1, IDLE)
|
||||
self.d(50, F1, WORN) # back on at 50 s
|
||||
self.assertNotIn("restart", kinds(self.d(70, F1, IDLE))) # off again: the 60 s start over
|
||||
self.assertNotIn("restart", kinds(self.d(129, F1, IDLE)))
|
||||
self.assertIn("restart", kinds(self.d(131, F1, IDLE)))
|
||||
|
||||
def test_cooldown(self):
|
||||
self.d(0, F1, IDLE)
|
||||
self.assertIn("restart", kinds(self.d(60, F1, IDLE)))
|
||||
# The restart's new XRService fails too: a new failure, but within the cooldown.
|
||||
self.d(90, "", IDLE)
|
||||
acts = self.d(120, F2, IDLE)
|
||||
self.assertIn("notify", kinds(acts))
|
||||
self.assertNotIn("restart", kinds(acts))
|
||||
self.assertNotIn("restart", kinds(self.d(60 + 30 * 60 - 2, F2, IDLE)))
|
||||
self.assertIn("cooldown", self.mem["why"])
|
||||
self.assertIn("restart", kinds(self.d(60 + 30 * 60, F2, IDLE)))
|
||||
|
||||
def test_vr_app_remote_and_no_steamvr(self):
|
||||
for env, word in ((dict(IDLE, vr_apps=["AppId=450390"]), "VR app"),
|
||||
(dict(IDLE, remote=["0A00000B:D2F0"]), "remote desktop"),
|
||||
(dict(IDLE, steamvr=False), "SteamVR isn't running")):
|
||||
with self.subTest(word=word):
|
||||
self.mem = cw.new_memory()
|
||||
for t in range(0, 600, 2):
|
||||
self.assertNotIn("restart", kinds(self.d(t, F1, env)))
|
||||
self.assertIn(word, self.mem["why"])
|
||||
# once it's gone (and the headset still off), the restart happens
|
||||
self.assertIn("restart", kinds(self.d(600, F1, IDLE)))
|
||||
|
||||
def test_resolved(self):
|
||||
self.d(0, F1, WORN)
|
||||
acts = self.d(10, "", {})
|
||||
self.assertEqual(kinds(acts), ["log"])
|
||||
self.assertIn("no longer current", acts[0][1])
|
||||
self.assertEqual(self.mem["pending"], "")
|
||||
self.assertEqual(self.d(12, "", {}), [])
|
||||
|
||||
def test_memory_round_trip(self):
|
||||
tmp = tempfile.mkdtemp(prefix="camwatch-test-")
|
||||
try:
|
||||
path = os.path.join(tmp, "state", "camwatch.json")
|
||||
self.d(0, F1, IDLE)
|
||||
self.d(60, F1, IDLE)
|
||||
cw.save_memory(self.mem, path)
|
||||
mem = cw.load_memory(path)
|
||||
self.assertEqual(mem["restarted"], {F1: 60})
|
||||
self.assertEqual(mem["notified"], [F1])
|
||||
# the watcher restarted: the same failure neither notifies nor restarts again
|
||||
acts = cw.decide(200, F1, IDLE, mem, ON)
|
||||
self.assertNotIn("notify", kinds(acts))
|
||||
self.assertNotIn("restart", kinds(acts))
|
||||
self.assertEqual(cw.load_memory(os.path.join(tmp, "missing.json"))["restarted"], {})
|
||||
finally:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
|
||||
class Follow(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.mkdtemp(prefix="camwatch-follow-")
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.tmp, ignore_errors=True)
|
||||
|
||||
def test_growing_log(self):
|
||||
path = os.path.join(self.tmp, "x.log")
|
||||
f = cw.Follower(path)
|
||||
text = "\n".join(START + GOOD_OPEN) + "\n"
|
||||
with open(path, "w") as out:
|
||||
out.write(text)
|
||||
self.assertEqual(cw.current_failure(f.poll()), "")
|
||||
self.assertEqual(f.state.verdict()[0], "ok")
|
||||
# half a line, then the rest: read as one line
|
||||
more = "\n".join(CLOSE + RESUME + FAIL) + "\n"
|
||||
cut = more.index("Failed to load VCINT") + 5
|
||||
with open(path, "a") as out:
|
||||
out.write(more[:cut])
|
||||
self.assertEqual(cw.current_failure(f.poll()), "")
|
||||
with open(path, "a") as out:
|
||||
out.write(more[cut:])
|
||||
self.assertTrue(cw.current_failure(f.poll()).endswith("@11:30:01"))
|
||||
self.assertEqual(cw.current_failure(f.state, steamvr_running=False), "")
|
||||
with open(path, "a") as out:
|
||||
out.write("\n".join(CLOSE + RESUME_OK) + "\n")
|
||||
self.assertEqual(cw.current_failure(f.poll()), "")
|
||||
|
||||
def test_new_log_starts_afresh(self):
|
||||
a, b = os.path.join(self.tmp, "a.log"), os.path.join(self.tmp, "b.log")
|
||||
with open(a, "w") as out:
|
||||
out.write("\n".join(START + GOOD_OPEN + CLOSE + RESUME + FAIL) + "\n")
|
||||
f = cw.Follower(a)
|
||||
self.assertTrue(cw.current_failure(f.poll()))
|
||||
with open(b, "w") as out:
|
||||
out.write("\n".join(START + GOOD_OPEN) + "\n")
|
||||
f.fixed = b # as when xrservice.txt points at a new XRService's log
|
||||
self.assertEqual(cw.current_failure(f.poll()), "")
|
||||
self.assertEqual(f.path, b)
|
||||
|
||||
|
||||
class Settings(unittest.TestCase):
|
||||
def test_read_conf(self):
|
||||
tmp = tempfile.mkdtemp(prefix="camwatch-conf-")
|
||||
try:
|
||||
path = os.path.join(tmp, "frametop.conf")
|
||||
with open(path, "w") as f:
|
||||
f.write("# Frametop\nREMOTE=1 # comment\nCAMWATCH_AUTO_RESTART=1\nCAMWATCH_IDLE_S='90'\n"
|
||||
"CAMWATCH_IGNORE_APPIDS=\"1, 2\"\nnot a setting\n")
|
||||
conf = cw.read_conf(path)
|
||||
self.assertEqual(conf["CAMWATCH_AUTO_RESTART"], "1")
|
||||
self.assertEqual(cw.conf_int(conf, "CAMWATCH_IDLE_S"), 90)
|
||||
self.assertEqual(conf["CAMWATCH_IGNORE_APPIDS"], "1, 2")
|
||||
self.assertEqual(cw.conf_int(conf, "CAMWATCH_COOLDOWN_MIN"), 30) # the default
|
||||
self.assertEqual(cw.read_conf(os.path.join(tmp, "none"))["CAMWATCH_AUTO_RESTART"], "0")
|
||||
self.assertEqual(cw.conf_int({"CAMWATCH_IDLE_S": "soon"}, "CAMWATCH_IDLE_S"), 60)
|
||||
finally:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
def test_headset_worn(self):
|
||||
tmp = tempfile.mkdtemp(prefix="camwatch-bl-")
|
||||
orig = cw.process_running
|
||||
try:
|
||||
os.makedirs(os.path.join(tmp, "panel0"))
|
||||
bright = os.path.join(tmp, "panel0", "brightness")
|
||||
for value, compositor, worn in (("95", True, True), ("0", True, False), ("95", False, False)):
|
||||
with open(bright, "w") as f:
|
||||
f.write(value + "\n")
|
||||
cw.process_running = lambda name, c=compositor: c and name == "vrcompositor"
|
||||
self.assertEqual(cw.headset_worn(tmp), worn, (value, compositor))
|
||||
self.assertFalse(cw.headset_worn(os.path.join(tmp, "none")))
|
||||
finally:
|
||||
cw.process_running = orig
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
def test_remote_viewers(self):
|
||||
tmp = tempfile.mkdtemp(prefix="camwatch-tcp-")
|
||||
try:
|
||||
path = os.path.join(tmp, "tcp")
|
||||
with open(path, "w") as f:
|
||||
f.write(" sl local_address rem_address st tx_queue rx_queue\n"
|
||||
" 0: 0100007F:170C 00000000:0000 0A 00000000:00000000\n" # listening
|
||||
" 1: 0B00640A:170C 0C00640A:D2F0 01 00000000:00000000\n" # a viewer
|
||||
" 2: 0B00640A:0016 0C00640A:D2F1 01 00000000:00000000\n") # ssh
|
||||
self.assertEqual(cw.remote_viewers(5900, (path,)), ["0C00640A:D2F0"])
|
||||
self.assertEqual(cw.remote_viewers(5901, (path,)), [])
|
||||
finally:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,11 +1,18 @@
|
||||
"""Check that the side cameras' images carry the right names (slam_left vs slam_right).
|
||||
|
||||
usage: python tools/check_sides.py REC_DIR [--sets N]
|
||||
python tools/check_sides.py --ring [--sets N] (live, from ft-camd's ring)
|
||||
usage: python tools/check_sides.py REC [--sets N] [--pair side|upper] [--calib DIR] [--json]
|
||||
python tools/check_sides.py --ring [--sets N] [--pair side|upper] (live, from ft-camd's ring)
|
||||
|
||||
With --ring it exits 0 when the names are right, 3 when they're swapped (run ft-hands
|
||||
with --swap-sides), and 2 when it can't tell (too little texture in view, or the headset
|
||||
isn't worn).
|
||||
REC is a recording folder (its sets.bin) or a sets file (a take's sets-N.bin). It checks the
|
||||
names as they are in the files: a recording's sides.json or session.json "sides" (the hand
|
||||
recorder's) isn't applied. Exits 0 when the names are right, 3 when they're swapped, and 2 when
|
||||
it can't tell (too little texture in view, or the headset isn't worn). --pair upper checks the
|
||||
upper pair (upper_left vs upper_right) the same way. --calib DIR uses DIR/calibration.json and
|
||||
DIR/device.json (a hand recorder session's, or cut.py's) instead of /persist. --json prints one
|
||||
line: {"pair", "verdict": "named"|"swapped"|"unknown", "named", "swapped", "matches", "sets"}.
|
||||
|
||||
ft-hands decides the side cameras' naming by itself (HANDS_SWAP_SIDES=auto, track/sides.h);
|
||||
this is the independent check, from the scene rather than hands.
|
||||
|
||||
ft-camd tells the two side cameras' buffers apart by the order XRService allocated them,
|
||||
and after some XRService restarts that order puts each camera's images under the other's
|
||||
@@ -15,6 +22,7 @@ with the factory calibration, once as named and once swapped: true matches meet
|
||||
front of both cameras only under the right naming.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
@@ -26,10 +34,34 @@ from tools.show_set import index, read_set # noqa: E402
|
||||
from tools import calib # noqa: E402
|
||||
|
||||
|
||||
PIPES = {'msm_vfe3_video0': 'slam_left', 'msm_vfe4_video0': 'slam_right'} # as ft-hands maps them
|
||||
PIPES = {'msm_vfe3_video0': 'slam_left', 'msm_vfe4_video0': 'slam_right', # with the colour module
|
||||
'msm_vfe2_video0': 'upper_left', 'msm_vfe2_video1': 'upper_right'}
|
||||
|
||||
|
||||
def load_cams():
|
||||
def ring_names():
|
||||
"""{/dev/videoN's N: calibration name} as ft-hands names them: by XRService's log
|
||||
(camcheck.py), else by capture pipe (PIPES)."""
|
||||
import camcheck
|
||||
try:
|
||||
by_log = {node: name for name, node in camcheck.read_log(camcheck.newest_log()).camera_map().items()}
|
||||
except (OSError, ValueError):
|
||||
by_log = {}
|
||||
if by_log:
|
||||
return by_log
|
||||
out = {}
|
||||
for path in os.listdir('/sys/class/video4linux'):
|
||||
if path.startswith('video'):
|
||||
with open('/sys/class/video4linux/%s/name' % path) as f:
|
||||
name = PIPES.get(f.read().strip())
|
||||
if name:
|
||||
out[int(path[5:])] = name
|
||||
return out
|
||||
PAIRS = {'side': ('slam_left', 'slam_right'), 'upper': ('upper_left', 'upper_right')}
|
||||
|
||||
|
||||
def load_cams(calib_dir=None):
|
||||
if calib_dir:
|
||||
return calib.load(os.path.join(calib_dir, 'calibration.json'), os.path.join(calib_dir, 'device.json'))
|
||||
return calib.load()
|
||||
|
||||
|
||||
@@ -68,60 +100,87 @@ def score(cam_a, cam_b, ua, ub):
|
||||
return float(np.mean((d < 0.01) & front))
|
||||
|
||||
|
||||
def recorded_pairs(rec, count):
|
||||
"""(label, slam_left image, slam_right image) from sets spread across a recording."""
|
||||
path = os.path.join(rec, 'sets.bin')
|
||||
def recorded_pairs(rec, count, names=PAIRS['side']):
|
||||
"""(label, left image, right image) from sets spread across a recording (or sets file)."""
|
||||
path = rec if os.path.isfile(rec) else os.path.join(rec, 'sets.bin')
|
||||
offs = index(path)
|
||||
for n in np.linspace(0, len(offs) - 1, count).astype(int):
|
||||
if not offs:
|
||||
return
|
||||
for n in sorted(set(np.linspace(0, len(offs) - 1, count).astype(int))):
|
||||
images = read_set(path, offs[n])
|
||||
if 'slam_left' in images and 'slam_right' in images:
|
||||
yield 'set %5d' % n, images['slam_left'][0], images['slam_right'][0]
|
||||
if names[0] in images and names[1] in images:
|
||||
yield 'set %5d' % n, images[names[0]][0], images[names[1]][0]
|
||||
|
||||
|
||||
def live_pairs(count):
|
||||
"""(label, slam_left image, slam_right image) from ft-camd's ring, half a second apart."""
|
||||
def live_pairs(count, names=PAIRS['side']):
|
||||
"""(label, left image, right image) from ft-camd's ring, half a second apart."""
|
||||
import time
|
||||
from tools.ring import Ring
|
||||
ring = Ring()
|
||||
if not ring.alive():
|
||||
sys.exit('ft-camd isn\'t running (no heartbeat)')
|
||||
cams = {}
|
||||
names_of = ring_names()
|
||||
for c in ring.cams:
|
||||
name = PIPES.get(open('/sys/class/video4linux/video%d/name' % c.node).read().strip())
|
||||
name = names_of.get(c.node)
|
||||
if name and not c.name.endswith('-dark'):
|
||||
cams[name] = c
|
||||
for k in range(count):
|
||||
a, b = ring.read(cams['slam_left']), ring.read(cams['slam_right'])
|
||||
a, b = ring.read(cams[names[0]]), ring.read(cams[names[1]])
|
||||
if a is not None and b is not None:
|
||||
yield 'frame %2d' % k, a.image, b.image
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def verdict(named, swapped, n, total_matches):
|
||||
"""'named', 'swapped' or 'unknown', from the summed per-set scores: the winner must meet
|
||||
clearly more often (by 0.08 a set) and at least 4 times as often. The upper cameras' small
|
||||
images meet within 1 cm less often (0.1-0.4 a set as named, 0 swapped) than the side ones (0.4-0.9)."""
|
||||
hi, lo = max(named, swapped), min(named, swapped)
|
||||
if n == 0 or total_matches < 100 or (hi - lo) / n < 0.08 or lo > 0.25 * hi:
|
||||
return 'unknown'
|
||||
return 'named' if named > swapped else 'swapped'
|
||||
|
||||
|
||||
def check(pairs, left, right, out=print):
|
||||
"""Score (label, left image, right image) pairs: (verdict, named, swapped, matches, sets)."""
|
||||
named = swapped = 0.0
|
||||
n = total_matches = 0
|
||||
for label, img_l, img_r in pairs:
|
||||
ua, ub = matches(img_l, img_r)
|
||||
s_named = score(left, right, ua, ub) # the left-named image seen by the left camera
|
||||
s_swapped = score(right, left, ua, ub) # ... by the right camera
|
||||
named, swapped, n, total_matches = named + s_named, swapped + s_swapped, n + 1, total_matches + len(ua)
|
||||
out('%s: %4d matches, meeting as named %3.0f%%, swapped %3.0f%%' %
|
||||
(label, len(ua), 100 * s_named, 100 * s_swapped))
|
||||
return verdict(named, swapped, n, total_matches), named / max(n, 1), swapped / max(n, 1), total_matches, n
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('rec', nargs='?')
|
||||
ap.add_argument('--ring', action='store_true', help='check the live cameras instead of a recording')
|
||||
ap.add_argument('--sets', type=int, default=8, help='how many sets or live frames to check')
|
||||
ap.add_argument('--pair', choices=sorted(PAIRS), default='side')
|
||||
ap.add_argument('--calib', help='folder with calibration.json and device.json (default: /persist)')
|
||||
ap.add_argument('--json', action='store_true', help='one JSON line instead of the report')
|
||||
a = ap.parse_args()
|
||||
if not a.ring and not a.rec:
|
||||
ap.error('give a recording or --ring')
|
||||
cams = load_cams()
|
||||
left, right = cams['slam_left'], cams['slam_right']
|
||||
named = swapped = 0.0
|
||||
n = total_matches = 0
|
||||
for label, img_l, img_r in (live_pairs(a.sets) if a.ring else recorded_pairs(a.rec, a.sets)):
|
||||
ua, ub = matches(img_l, img_r)
|
||||
s_named = score(left, right, ua, ub) # slam_left's image seen by the left camera
|
||||
s_swapped = score(right, left, ua, ub) # ... by the right camera
|
||||
named, swapped, n, total_matches = named + s_named, swapped + s_swapped, n + 1, total_matches + len(ua)
|
||||
print('%s: %4d matches, meeting as named %3.0f%%, swapped %3.0f%%' %
|
||||
(label, len(ua), 100 * s_named, 100 * s_swapped))
|
||||
if n == 0 or total_matches < 100 or abs(named - swapped) / n < 0.2:
|
||||
print('side cameras: can\'t tell (%d matches)' % total_matches)
|
||||
sys.exit(2)
|
||||
print('side cameras: %s (named %.2f, swapped %.2f)' %
|
||||
('as named' if named > swapped else 'SWAPPED', named / n, swapped / n))
|
||||
sys.exit(0 if named > swapped else 3)
|
||||
cams = load_cams(a.calib)
|
||||
names = PAIRS[a.pair]
|
||||
left, right = cams[names[0]], cams[names[1]]
|
||||
pairs = live_pairs(a.sets, names) if a.ring else recorded_pairs(a.rec, a.sets, names)
|
||||
v, named, swapped, total, n = check(pairs, left, right, out=(lambda s: None) if a.json else print)
|
||||
what = 'side cameras' if a.pair == 'side' else 'upper cameras'
|
||||
if a.json:
|
||||
print(json.dumps({'pair': a.pair, 'verdict': v, 'named': round(named, 3), 'swapped': round(swapped, 3),
|
||||
'matches': total, 'sets': n}))
|
||||
elif v == 'unknown':
|
||||
print('%s: can\'t tell (%d matches)' % (what, total))
|
||||
else:
|
||||
print('%s: %s (named %.2f, swapped %.2f)' % (what, 'as named' if v == 'named' else 'SWAPPED', named, swapped))
|
||||
sys.exit({'named': 0, 'swapped': 3, 'unknown': 2}[v])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// Python prototype: the same scheduling, with the models on a few threads.
|
||||
//
|
||||
// ft-hands [--seconds N] [--threads N] [--int8] [--status S] [--models DIR] [--nice N]
|
||||
// [--no-publish] [--no-gestures] [--record DIR] [--swap-sides] [--cams auto|mono|color|all] ...
|
||||
// [--no-publish] [--no-gestures] [--record DIR] [--sides auto|0|1] [--cams auto|mono|color|all] ...
|
||||
// (--help lists them all)
|
||||
//
|
||||
// --no-gestures: hands for the cutouts only. No pinch or grip detection, so nothing reaches
|
||||
@@ -22,14 +22,25 @@
|
||||
// own clock, so they're placed on the mono cameras' by when they were dequeued, less the
|
||||
// mono cameras' measured delay.
|
||||
//
|
||||
// Which side camera is which (--sides, HANDS_SWAP_SIDES): ft-camd tells slam_left's buffers from
|
||||
// slam_right's by XRService's allocation order, which some XRService starts reverse. auto (the
|
||||
// default) tells from the hands it tracks (track/sides.h): once it's sure, it exchanges the two
|
||||
// cameras if they're backwards (the tracked views move with their images), and checks once
|
||||
// more. 0 and 1 force the naming (1: exchanged; --swap-sides is --sides 1); it still checks,
|
||||
// and if the hands disagree it warns and publishes what the hands say as the truth ("swapped"),
|
||||
// so recordings are labelled right while tracking keeps the forced names. The decision is published in /run/user/UID/frametop-hands/sides.json (see
|
||||
// write_sides below) and, for recordings, in DIR/sides.json. --record-only can't tell (it tracks
|
||||
// nothing): under auto it records the ring's names as they are.
|
||||
//
|
||||
// Settings in ~/.config/frametop.conf (FT_<name> in the environment overrides them, and
|
||||
// options override both): HANDS_SWAP_SIDES (1: as --swap-sides), HANDS_CPUS (as --cpus),
|
||||
// options override both): HANDS_SWAP_SIDES (auto, 0 or 1), HANDS_CPUS (as --cpus),
|
||||
// HANDS_CAMERAS, HANDS_BRIGHT, HANDS_BRIGHT_ON, HANDS_BRIGHT_OFF, HANDS_COLOR_LEFT (which
|
||||
// colour camera is passthrough_left: color_video0 or color_video3), HANDS_COLOR_CROP
|
||||
// (subtract or none: tools/check_color.py tells both).
|
||||
#include "io.h"
|
||||
#include "pinch.h"
|
||||
#include "record.h"
|
||||
#include "sides.h"
|
||||
|
||||
#include <sched.h>
|
||||
#include <sys/resource.h>
|
||||
@@ -45,6 +56,7 @@
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <optional>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
|
||||
@@ -52,7 +64,34 @@ namespace {
|
||||
|
||||
volatile std::sig_atomic_t g_stop = 0, g_record = 0;
|
||||
|
||||
// which calibrated camera each capture pipe carries (XRService's fixed routing)
|
||||
// Which calibrated camera each video device carries. XRService numbers its tracking cameras
|
||||
// (index 0 to 3: slam_left, slam_right, upper_left, upper_right) and logs the device each one
|
||||
// opened ("TrackingCameraInit: index: 0. video device: /dev/video9"). The devices depend on
|
||||
// the colour module: with it, the side cameras are on vfe3 and vfe4 and the upper pair on
|
||||
// vfe2; without it, XRService runs the side cameras through the ISP on vfe0 and vfe1, and the
|
||||
// upper pair on vfe3 and vfe4. So the running XRService's log decides; when it can't be read,
|
||||
// the capture pipes as they are with the module. {} if the log has no cameras.
|
||||
std::map<int, std::string> cameras_from_xrservice_log() {
|
||||
static const char *const names[] = {"slam_left", "slam_right", "upper_left", "upper_right"};
|
||||
const char *home = std::getenv("HOME");
|
||||
std::ifstream in(std::string(home ? home : "") + "/.local/share/Steam/logs/xrservice.txt");
|
||||
const std::string key = "TrackingCameraInit: index: ";
|
||||
std::map<int, int> node_of; // index -> N of /dev/videoN, from the latest camera start
|
||||
std::string line;
|
||||
while (std::getline(in, line)) {
|
||||
if (line.find("XRService logging to") != std::string::npos) node_of.clear();
|
||||
const auto at = line.find(key);
|
||||
int index = -1, node = -1;
|
||||
if (at != std::string::npos &&
|
||||
std::sscanf(line.c_str() + at + key.size(), "%d. video device: /dev/video%d", &index, &node) == 2 &&
|
||||
index >= 0 && index < 4)
|
||||
node_of[index] = node;
|
||||
}
|
||||
std::map<int, std::string> out;
|
||||
for (auto &[index, node] : node_of) out[node] = names[index];
|
||||
return out;
|
||||
}
|
||||
|
||||
const char *camera_for_pipe(int node) {
|
||||
char path[64], name[64] = "";
|
||||
std::snprintf(path, sizeof path, "/sys/class/video4linux/video%d/name", node);
|
||||
@@ -148,12 +187,25 @@ struct Lighting {
|
||||
}
|
||||
};
|
||||
|
||||
// Writes path through a temporary file, so a reader never sees half of it.
|
||||
bool write_file(const std::string &path, const std::string &text) {
|
||||
const std::string tmp = path + ".tmp";
|
||||
FILE *f = std::fopen(tmp.c_str(), "w");
|
||||
if (!f) return false;
|
||||
const bool ok = std::fputs(text.c_str(), f) >= 0;
|
||||
if (std::fclose(f) != 0 || !ok || std::rename(tmp.c_str(), path.c_str()) != 0) return unlink(tmp.c_str()), false;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string json_bool(std::optional<bool> b) { return !b ? "null" : *b ? "true" : "false"; }
|
||||
std::string json_str(const std::string &s) { return s.empty() ? "null" : "\"" + s + "\""; }
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
double seconds = 0, status = 5;
|
||||
int threads = 3, niceness = 5;
|
||||
bool int8 = false, publish = true, track = true, swap_sides = false, gestures_on = true;
|
||||
bool int8 = false, publish = true, track = true, gestures_on = true;
|
||||
std::string models = std::string(argv[0]).substr(0, std::string(argv[0]).rfind('/') + 1) + "../models/ncnn";
|
||||
std::string record, ring_path = "/run/user/" + std::to_string(getuid()) + "/" FH_RING_NAME;
|
||||
// SteamOS starts user processes on CPUs 0-4 and keeps 5-7 (two A720s and the X4) for
|
||||
@@ -163,7 +215,9 @@ int main(int argc, char **argv) {
|
||||
// latency 9.6 against 14.1 ms, and the compositor's late frames and CPU/GPU time didn't change.
|
||||
std::vector<int> cpus = {5, 6, 7};
|
||||
if (const auto c = parse_cpus(setting("HANDS_CPUS").c_str()); !c.empty()) cpus = c;
|
||||
swap_sides = setting("HANDS_SWAP_SIDES") == "1";
|
||||
// Which side camera is which (see the top): auto, 0 or 1, and where that came from
|
||||
std::string sides_mode = setting("HANDS_SWAP_SIDES"), sides_from = "config";
|
||||
if (sides_mode.empty()) sides_mode = "auto", sides_from = "default";
|
||||
// Which cameras (see the top).
|
||||
std::string cams_arg = setting("HANDS_CAMERAS"), bright_arg = setting("HANDS_BRIGHT");
|
||||
std::string color_left = setting("HANDS_COLOR_LEFT"), color_crop = setting("HANDS_COLOR_CROP");
|
||||
@@ -181,7 +235,7 @@ int main(int argc, char **argv) {
|
||||
PinchParams pinch_params;
|
||||
GripParams grip_params;
|
||||
bool gesture_log = false; // what the pinch and grip detectors measure, 10 times a second
|
||||
double record_for = 120;
|
||||
double record_for = 120, record_hz = 0; // record_hz: at most this many sets a second (0: all)
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
const std::string a = argv[i];
|
||||
const bool more = i + 1 < argc;
|
||||
@@ -200,11 +254,13 @@ int main(int argc, char **argv) {
|
||||
else if (a == "--grip-begin" && more) grip_params.begin = std::atof(argv[++i]);
|
||||
else if (a == "--grip-end" && more) grip_params.end = std::atof(argv[++i]);
|
||||
else if (a == "--gesture-log") gesture_log = true;
|
||||
else if (a == "--swap-sides") swap_sides = true;
|
||||
else if (a == "--swap-sides") sides_mode = "1", sides_from = "option";
|
||||
else if (a == "--sides" && more) sides_mode = argv[++i], sides_from = "option";
|
||||
else if (a == "--record-only") track = publish = false;
|
||||
else if (a == "--ring" && more) ring_path = argv[++i];
|
||||
else if (a == "--record" && more) record = argv[++i];
|
||||
else if (a == "--record-for" && more) record_for = std::atof(argv[++i]);
|
||||
else if (a == "--record-hz" && more) record_hz = std::max(0.0, std::atof(argv[++i]));
|
||||
else if (a == "--keep-presence" && more) keep_presence = std::atof(argv[++i]);
|
||||
else if (a == "--cams" && more) cams_arg = argv[++i];
|
||||
else if (a == "--bright" && more) bright_arg = argv[++i];
|
||||
@@ -222,19 +278,22 @@ int main(int argc, char **argv) {
|
||||
else {
|
||||
std::printf("usage: %s [--seconds N] [--threads N] [--int8] [--status S] [--models DIR] [--nice N] [--no-publish]\n"
|
||||
" [--no-gestures] (hands for the cutouts only: no pinches or grips)\n"
|
||||
" [--record DIR] [--record-for S] [--record-only] [--cpus 5,6,7] [--swap-sides]\n"
|
||||
" [--record DIR] [--record-for S] [--record-hz N] [--record-only] [--cpus 5,6,7]\n"
|
||||
" [--sides auto|0|1] (auto: tell from the hands which side camera is which; 1: exchange them,\n"
|
||||
" as --swap-sides; 0: as ft-camd names them)\n"
|
||||
" [--keep-presence P] (0.5) [--ring PATH] (ft-camd's, or ft-ringplay's)\n"
|
||||
" [--cams auto|mono|color|all] (auto) [--bright all|color] (all) [--bright-on L] (40) [--bright-off L] (25)\n"
|
||||
" [--color-left color_video0|color_video3] [--color-crop subtract|none]\n"
|
||||
" [--pinch-begin M] (0.020) [--pinch-end M] (0.035) [--pinch-triangulated] [--pinch-palm-down MAX] (1: off)\n"
|
||||
" [--grip-begin R] (1.2) [--grip-end R] (1.45) [--gesture-log]\n"
|
||||
" [--contrast MODE|PALM/HAND] (clahe[:CLIP], none, stretch; default clahe:2/none)\n"
|
||||
"Recording saves every frame set for S seconds (120) to DIR/sets.bin, for ft-handreplay; SIGUSR1\n"
|
||||
"Recording saves every frame set (at most N a second with --record-hz) for S seconds (120) to DIR/sets.bin,\n"
|
||||
"for ft-handreplay; SIGUSR1\n"
|
||||
"starts one in ~/.local/share/frametop/hands/rec-<time>. --record-only records without tracking, so it\n"
|
||||
"can run beside a tracking ft-hands. With ft-camd --with-dark, recordings also get each\n"
|
||||
"camera's newest dark frame, as <name>_dk; with --with-color, the color cameras' as color_video<N>.\n"
|
||||
"auto picks the cameras by the light (see the top of track/main.cpp).\n"
|
||||
"Settings in ~/.config/frametop.conf: HANDS_SWAP_SIDES=1, HANDS_CPUS=5,6,7, HANDS_CAMERAS, HANDS_BRIGHT,\n"
|
||||
"Settings in ~/.config/frametop.conf: HANDS_SWAP_SIDES=auto|0|1, HANDS_CPUS=5,6,7, HANDS_CAMERAS, HANDS_BRIGHT,\n"
|
||||
"HANDS_BRIGHT_ON, HANDS_BRIGHT_OFF, HANDS_COLOR_LEFT, HANDS_COLOR_CROP (FT_<name> overrides).\n",
|
||||
argv[0]);
|
||||
return a == "--help" ? 0 : 1;
|
||||
@@ -245,6 +304,8 @@ int main(int argc, char **argv) {
|
||||
if ((!automatic && !parse_cams(cams_arg, fixed)) || !parse_cams(bright_arg, bright_cams) || bright_cams == Cams::Mono)
|
||||
return std::fprintf(stderr, "--cams auto|mono|color|all, --bright all|color\n"), 1;
|
||||
if (color_crop != "subtract" && color_crop != "none") return std::fprintf(stderr, "--color-crop subtract|none\n"), 1;
|
||||
if (sides_mode != "auto" && sides_mode != "0" && sides_mode != "1")
|
||||
return std::fprintf(stderr, "--sides (HANDS_SWAP_SIDES) auto, 0 or 1, not %s\n", sides_mode.c_str()), 1;
|
||||
std::setvbuf(stdout, nullptr, _IOLBF, 0); // whole lines to the journal as they come
|
||||
if (nice(niceness) < 0) std::perror("nice"); // the VR stack wins contested CPUs
|
||||
std::signal(SIGINT, [](int) { g_stop = 1; });
|
||||
@@ -260,10 +321,34 @@ int main(int argc, char **argv) {
|
||||
Pinch pinch(pinch_params);
|
||||
Grip grip(grip_params);
|
||||
std::unique_ptr<Recorder> rec;
|
||||
uint64_t rec_start = 0;
|
||||
uint64_t rec_start = 0, rec_next_ns = 0; // rec_next_ns: --record-hz's next set, capture clock
|
||||
// The side cameras (see the top). names_swapped: slam_left's and slam_right's ring cameras
|
||||
// are exchanged from ft-camd's naming. truth: whether ft-camd's naming is backwards, once known.
|
||||
bool names_swapped = sides_mode == "1";
|
||||
std::optional<bool> truth;
|
||||
std::string decided_by, sides_state = "deciding", decision_evidence;
|
||||
double decided_after_s = -1;
|
||||
if (sides_mode != "auto") truth = names_swapped, decided_by = sides_from, sides_state = "forced";
|
||||
std::string rec_dir;
|
||||
std::string cams_json; // which device each calibrated camera is (set below), for the sides files
|
||||
std::vector<std::pair<size_t, bool>> rec_names; // from which recorded set on, names_swapped was what
|
||||
// DIR/sides.json beside a recording's sets.bin: how its side cameras are named. A set's
|
||||
// names are right when its names_swapped equals swapped (null: not known when recorded).
|
||||
auto write_rec_sides = [&] {
|
||||
if (!rec) return;
|
||||
std::string runs;
|
||||
for (auto &[from, sw] : rec_names) runs += (runs.empty() ? "" : ", ") + ("[" + std::to_string(from) + ", " + json_bool(sw) + "]");
|
||||
write_file(rec_dir + "/sides.json",
|
||||
"{\"swapped\": " + json_bool(truth) + ", \"decided_by\": " + json_str(truth ? decided_by : "") +
|
||||
", \"names_swapped\": [" + runs + "]" +
|
||||
(decision_evidence.empty() ? "" : ", \"evidence\": " + decision_evidence) +
|
||||
(cams_json.empty() ? "" : ", \"cameras\": " + cams_json) + "}\n");
|
||||
};
|
||||
auto start_recording = [&](const std::string &dir, std::string &e) {
|
||||
rec = std::make_unique<Recorder>();
|
||||
if (!rec->open(dir, e)) return rec.reset(), false;
|
||||
rec_dir = dir, rec_names = {{0, names_swapped}};
|
||||
write_rec_sides();
|
||||
rec_start = mono_ns();
|
||||
std::printf("recording to %s for %.0f s\n", dir.c_str(), record_for);
|
||||
std::fflush(stdout);
|
||||
@@ -285,26 +370,63 @@ int main(int argc, char **argv) {
|
||||
// (--with-color). Recorded names hold 15 characters, so "upper_right_dark" wouldn't fit.
|
||||
std::map<std::string, int> dark;
|
||||
std::map<std::string, Camera> used;
|
||||
// ft-camd's cameras by XRService's numbering, else by capture pipe (see camera_for_pipe);
|
||||
// ft-ringplay's (no device) by the name it gives
|
||||
const std::map<int, std::string> by_log = cameras_from_xrservice_log();
|
||||
const char *named_by = by_log.empty() ? "capture pipe" : "XRService's log";
|
||||
for (int i = 0; i < ring.cameras(); ++i) {
|
||||
if (ring.camera(i).flags & FH_CAM_COLOR) {
|
||||
const std::string name = "color_video" + std::to_string(ring.camera(i).node);
|
||||
const fh_ring_cam_t &rc = ring.camera(i);
|
||||
if (rc.flags & FH_CAM_COLOR) {
|
||||
const std::string name = "color_video" + std::to_string(rc.node);
|
||||
dark[name] = i, color[name] = i;
|
||||
continue;
|
||||
}
|
||||
// ft-camd's cameras by capture pipe; ft-ringplay's (no device) by the name it gives
|
||||
const char *name = camera_for_pipe(ring.camera(i).node);
|
||||
if (!name && ring.camera(i).node < 0) name = ring.camera(i).name;
|
||||
if (!name || !calib.count(name)) continue;
|
||||
if (ring.camera(i).flags & FH_CAM_DARK) dark[std::string(name) + "_dk"] = i;
|
||||
else index[name] = i, used[name] = calib[name];
|
||||
const auto it = by_log.find(rc.node);
|
||||
const char *name = rc.node < 0 ? rc.name
|
||||
: !by_log.empty() ? (it == by_log.end() ? nullptr : it->second.c_str())
|
||||
: camera_for_pipe(rc.node);
|
||||
if (!name || !calib.count(name)) {
|
||||
if (!(rc.flags & FH_CAM_DARK)) std::fprintf(stderr, "video%d (%s): not one of the calibrated cameras, left out\n", rc.node, rc.name);
|
||||
continue;
|
||||
}
|
||||
if (int(rc.width) != calib[name].width || int(rc.height) != calib[name].height) {
|
||||
std::fprintf(stderr, "video%d (%s) is %ux%u, but %s is calibrated at %dx%d: left out\n", rc.node, rc.name,
|
||||
rc.width, rc.height, name, calib[name].width, calib[name].height);
|
||||
continue;
|
||||
}
|
||||
if (rc.flags & FH_CAM_DARK) {
|
||||
dark[std::string(name) + "_dk"] = i;
|
||||
} else if (index.count(name)) {
|
||||
std::fprintf(stderr, "video%d (%s) would be %s too (video%d is): left out\n", rc.node, rc.name, name,
|
||||
ring.camera(index[name]).node);
|
||||
} else {
|
||||
index[name] = i, used[name] = calib[name];
|
||||
cams_json += std::string(cams_json.empty() ? "" : ", ") + json_str(name) + ": {\"node\": " +
|
||||
std::to_string(rc.node) + ", \"ring\": " + json_str(rc.name) + "}";
|
||||
}
|
||||
}
|
||||
cams_json = "{\"named_by\": " + json_str(named_by) + ", \"cameras\": {" + cams_json + "}}";
|
||||
// ft-camd tells the side cameras' buffers apart by XRService's allocation order, which
|
||||
// some XRService restarts reverse; tools/check_sides.py --ring tells when.
|
||||
if (swap_sides && index.count("slam_left") && index.count("slam_right")) {
|
||||
// some XRService restarts reverse (see the top).
|
||||
const bool have_sides = index.count("slam_left") && index.count("slam_right");
|
||||
std::map<std::string, uint64_t> last; // per camera: the frame last used
|
||||
auto exchange_sides = [&] {
|
||||
std::swap(index["slam_left"], index["slam_right"]);
|
||||
std::swap(last["slam_left"], last["slam_right"]);
|
||||
if (dark.count("slam_left_dk") && dark.count("slam_right_dk")) std::swap(dark["slam_left_dk"], dark["slam_right_dk"]);
|
||||
std::printf("side cameras swapped (--swap-sides)\n");
|
||||
};
|
||||
if (names_swapped && have_sides) {
|
||||
exchange_sides();
|
||||
std::printf("side cameras exchanged (%s)\n", sides_from == "option" ? "--sides 1" : "HANDS_SWAP_SIDES=1");
|
||||
}
|
||||
// the mono cameras the side check may pair (not the colour ones)
|
||||
std::map<std::string, Camera> side_cams;
|
||||
for (auto &[name, i] : index) side_cams[name] = calib[name];
|
||||
SideCheck side_check(side_cams);
|
||||
bool checking = track && have_sides && side_check.usable();
|
||||
int side_round = 0; // auto: 0 deciding, then each check after a decision
|
||||
if (!track && sides_mode == "auto" && have_sides)
|
||||
std::printf("side cameras: as ft-camd names them (--record-only can't tell; the recording's sides.json says so)\n");
|
||||
// The colour pair, calibrated (see the top), unless only the mono cameras are wanted.
|
||||
if (color.size() == 2 && (automatic || fixed != Cams::Mono)) {
|
||||
const std::string left = color.count(color_left) ? color_left : color.begin()->first;
|
||||
@@ -328,7 +450,7 @@ int main(int argc, char **argv) {
|
||||
}
|
||||
const bool switching = automatic && !color.empty();
|
||||
Cams mode = switching || color.empty() ? Cams::Mono : fixed;
|
||||
std::printf("cameras:");
|
||||
std::printf("cameras (by %s):", named_by);
|
||||
for (auto &[name, i] : index) std::printf(" %s=video%d", name.c_str(), ring.camera(i).node);
|
||||
for (auto &[name, i] : color) std::printf(" %s", name.c_str());
|
||||
std::printf(" tracking with %s%s models: %s%s, %d threads on CPUs", cams_name(mode),
|
||||
@@ -345,7 +467,6 @@ int main(int argc, char **argv) {
|
||||
Tracker tracker(used, nets, pool);
|
||||
tracker.set_keep_presence(keep_presence);
|
||||
std::map<std::string, std::vector<uint8_t>> pixels;
|
||||
std::map<std::string, uint64_t> last; // per camera: the frame last used
|
||||
std::map<std::string, uint64_t> lit_seen; // per colour camera: the frame last counted for the light
|
||||
const uint64_t start = mono_ns();
|
||||
uint64_t t_status = start, next_ns = 0, t_want = 0, t_glog = 0;
|
||||
@@ -357,6 +478,74 @@ int main(int argc, char **argv) {
|
||||
// to place the colour frames, whose capture clock is their own (see the top).
|
||||
double mono_delay_ns = -1;
|
||||
const std::string want_file = run_dir() + "/color-fps";
|
||||
// The side cameras' naming, for the hand recorder and other tools (hands/rec/session.py
|
||||
// reads it): written by a tracking, publishing ft-hands at the start, on every change and
|
||||
// every 2 s, and removed when it exits. swapped: ft-camd's naming is backwards (null: not
|
||||
// known yet); names_swapped: whether this ft-hands exchanged them; ring_ino: the ring file's
|
||||
// inode (a new ft-camd makes a new one, and the decision is only good for that run).
|
||||
const std::string sides_file = run_dir() + "/sides.json";
|
||||
const bool write_sides_file = publish && track;
|
||||
struct stat ring_st{};
|
||||
stat(ring_path.c_str(), &ring_st);
|
||||
uint64_t t_sides = 0;
|
||||
auto write_sides = [&] {
|
||||
if (!write_sides_file) return;
|
||||
t_sides = mono_ns();
|
||||
write_file(sides_file,
|
||||
"{\"pid\": " + std::to_string(getpid()) + ", \"ring_ino\": " + std::to_string(ring_st.st_ino) +
|
||||
", \"mode\": \"" + sides_mode + "\", \"state\": \"" + sides_state + "\", \"swapped\": " +
|
||||
json_bool(truth) + ", \"decided_by\": " + json_str(truth ? decided_by : "") +
|
||||
", \"names_swapped\": " + json_bool(names_swapped) +
|
||||
", \"decided_after_s\": " + std::to_string(decided_after_s) +
|
||||
", \"evidence\": " + (decision_evidence.empty() ? "null" : decision_evidence) +
|
||||
", \"checking\": " + (checking ? side_check.json() : "null") +
|
||||
", \"cameras\": " + (cams_json.empty() ? "null" : cams_json) +
|
||||
", \"updated_ns\": " + std::to_string(mono_ns()) + "}\n");
|
||||
};
|
||||
write_sides();
|
||||
// A verdict from the side check (see the top and track/sides.h).
|
||||
auto side_verdict = [&](SideCheck::Verdict v, uint64_t now) {
|
||||
const bool backwards = v == SideCheck::Swapped; // relative to the names as they are now
|
||||
const double after = (now - start) / 1e9;
|
||||
const std::string ev = side_check.json(), text = side_check.summary();
|
||||
if (sides_mode != "auto") { // forced: the names stay; if the hands disagree, they're the truth
|
||||
const std::string what = (sides_from == "option" ? "--sides " : "HANDS_SWAP_SIDES=") + sides_mode;
|
||||
if (backwards)
|
||||
std::printf("side cameras: %s looks WRONG: the hands say the side cameras are the other way round (%s). "
|
||||
"Tracking keeps the forced names; recordings are labelled by the hands. Use auto.\n",
|
||||
what.c_str(), text.c_str());
|
||||
else
|
||||
std::printf("side cameras: %s agrees with the hands (%s)\n", what.c_str(), text.c_str());
|
||||
sides_state = backwards ? "forced, disagrees" : "forced, agrees";
|
||||
if (backwards) truth = !names_swapped, decided_by = "auto", decided_after_s = after;
|
||||
decision_evidence = ev;
|
||||
checking = false;
|
||||
} else if (side_round == 0 || backwards) {
|
||||
if (backwards) {
|
||||
exchange_sides();
|
||||
names_swapped = !names_swapped;
|
||||
tracker.exchange("slam_left", "slam_right");
|
||||
if (rec) rec_names.push_back({rec->added(), names_swapped});
|
||||
}
|
||||
const bool reversed = side_round > 0;
|
||||
truth = names_swapped, decided_by = "auto", decided_after_s = after, decision_evidence = ev;
|
||||
sides_state = reversed ? "decided, reversed" : "decided";
|
||||
std::printf("side cameras: %s after %.1f s (%s)\n",
|
||||
reversed ? "decision REVERSED" : names_swapped ? "SWAPPED, now exchanged" : "as named", after,
|
||||
text.c_str());
|
||||
// check once more with the new names, more strictly; at most two changes
|
||||
side_check.reset();
|
||||
side_check.min_clean = 20, side_check.min_votes = 40;
|
||||
checking = ++side_round < 3;
|
||||
} else {
|
||||
std::printf("side cameras: confirmed after %.1f s (%s)\n", after, text.c_str());
|
||||
sides_state = "confirmed";
|
||||
checking = false;
|
||||
}
|
||||
std::fflush(stdout);
|
||||
write_rec_sides();
|
||||
write_sides();
|
||||
};
|
||||
|
||||
// The colour pair's newest frames if both are newer than last used and taken together
|
||||
// (their own clock): their time, on the mono cameras' capture clock, else 0.
|
||||
@@ -403,8 +592,13 @@ int main(int argc, char **argv) {
|
||||
return n ? sum / n : -1;
|
||||
};
|
||||
|
||||
int exit_code = 0;
|
||||
while (!g_stop && (seconds <= 0 || (mono_ns() - start) / 1e9 < seconds)) {
|
||||
if (!ring.alive()) return std::fprintf(stderr, "ft-camd stopped\n"), 2;
|
||||
if (!ring.alive()) {
|
||||
std::fprintf(stderr, "ft-camd stopped\n");
|
||||
exit_code = 2;
|
||||
break;
|
||||
}
|
||||
const uint64_t now0 = mono_ns();
|
||||
const int64_t raw_off = raw_minus_mono_ns();
|
||||
|
||||
@@ -490,7 +684,16 @@ int main(int argc, char **argv) {
|
||||
if (!start_recording(dir + "/" + name, e)) std::fprintf(stderr, "%s\n", e.c_str());
|
||||
}
|
||||
if (rec) { // about 80 MB/s; dark frames double that, color frames add 70 MB/s
|
||||
if ((mono_ns() - rec_start) / 1e9 < record_for) {
|
||||
const bool due = record_hz <= 0 || tmin >= rec_next_ns; // --record-hz skips the sets between
|
||||
if (due && record_hz > 0) rec_next_ns = tmin + uint64_t(1e9 / record_hz) - 5'000'000;
|
||||
if ((mono_ns() - rec_start) / 1e9 >= record_for) {
|
||||
write_rec_sides();
|
||||
const size_t n = rec->written(), d = rec->dropped();
|
||||
rec.reset(); // writes out what's queued
|
||||
std::printf("recording done: %zu sets, %zu dropped\n", n, d);
|
||||
std::fflush(stdout);
|
||||
if (!track) break;
|
||||
} else if (due) {
|
||||
for (auto &[name, i] : dark) { // the newest dark and color frames, as they are
|
||||
fh_ring_slot_t meta;
|
||||
const uint64_t n = ring.latest(i);
|
||||
@@ -500,12 +703,6 @@ int main(int argc, char **argv) {
|
||||
meta.dqbuf_ns});
|
||||
}
|
||||
rec->add(frames);
|
||||
} else {
|
||||
const size_t n = rec->written(), d = rec->dropped();
|
||||
rec.reset(); // writes out what's queued
|
||||
std::printf("recording done: %zu sets, %zu dropped\n", n, d);
|
||||
std::fflush(stdout);
|
||||
if (!track) break;
|
||||
}
|
||||
}
|
||||
if (!track && rec && status > 0 && (mono_ns() - t_status) / 1e9 >= status) {
|
||||
@@ -548,6 +745,16 @@ int main(int argc, char **argv) {
|
||||
const auto hands = tracker.step(images, int64_t(tmin));
|
||||
const uint64_t capture = uint64_t(int64_t(tmin) - raw_off); // CLOCK_MONOTONIC
|
||||
const std::vector<Seen> views = tracker.views_now();
|
||||
std::vector<Seen> side_views; // the tracker's views, plus the side check's own looks
|
||||
if (checking) {
|
||||
side_views = views;
|
||||
for (Seen &v : side_check.probe(nets, pool, images, views, int64_t(tmin))) side_views.push_back(v);
|
||||
}
|
||||
if (checking && side_check.add(side_views, int64_t(tmin)) > 0) {
|
||||
const SideCheck::Verdict v = side_check.verdict();
|
||||
if (v != SideCheck::Undecided) side_verdict(v, mono_ns());
|
||||
}
|
||||
if (mono_ns() - t_sides > 2'000'000'000ull) write_sides();
|
||||
if (gestures_on) {
|
||||
grip.update(hands, views, int64_t(capture));
|
||||
pinch.update(hands, views, int64_t(capture), grip.gripping());
|
||||
@@ -603,6 +810,9 @@ int main(int argc, char **argv) {
|
||||
s.handoff_miss, s.dups, s.splits, s.created, s.merged, s.forgotten,
|
||||
!rec ? "" : (" recorded " + std::to_string(rec->written()) + " dropped " +
|
||||
std::to_string(rec->dropped())).c_str());
|
||||
if (checking)
|
||||
std::printf(" side cameras: %s, %s\n", side_round ? "checking the decision" : "deciding",
|
||||
side_check.summary().c_str());
|
||||
if (gestures_on) {
|
||||
std::printf(" pinches: left %u right %u (held back, palm down: %d %d) grips: left %u right %u",
|
||||
pinch.side(0).begins, pinch.side(1).begins, pinch.held_back[0], pinch.held_back[1],
|
||||
@@ -628,11 +838,13 @@ int main(int argc, char **argv) {
|
||||
}
|
||||
}
|
||||
if (!color.empty()) unlink(want_file.c_str());
|
||||
if (write_sides_file) unlink(sides_file.c_str());
|
||||
write_rec_sides();
|
||||
if (publish) pub.write({}, mono_ns());
|
||||
if (publish && gestures_on) {
|
||||
pinch.release(int64_t(mono_ns())); // a drag in progress ends, as lost
|
||||
grip.release(int64_t(mono_ns()));
|
||||
gestures.write(pinch, grip, mono_ns());
|
||||
}
|
||||
return 0;
|
||||
return exit_code;
|
||||
}
|
||||
@@ -57,6 +57,7 @@ void Recorder::add(const std::vector<SetFrame> &frames) {
|
||||
return;
|
||||
}
|
||||
queue_.push_back(std::move(rec));
|
||||
++added_;
|
||||
}
|
||||
wake_.notify_one();
|
||||
}
|
||||
|
||||
@@ -42,6 +42,9 @@ public:
|
||||
~Recorder();
|
||||
bool open(const std::string &dir, std::string &err);
|
||||
void add(const std::vector<SetFrame> &frames);
|
||||
// Sets taken (not dropped for a full queue): the next one's place in the file, unless a
|
||||
// write fails.
|
||||
size_t added() const { return added_; }
|
||||
size_t written() const { return written_; }
|
||||
size_t dropped() const { return dropped_; }
|
||||
|
||||
@@ -53,7 +56,7 @@ private:
|
||||
std::condition_variable wake_;
|
||||
std::deque<std::vector<uint8_t>> queue_;
|
||||
bool stop_ = false;
|
||||
size_t written_ = 0, dropped_ = 0;
|
||||
size_t written_ = 0, dropped_ = 0, added_ = 0;
|
||||
};
|
||||
|
||||
// Reads a recording back one set at a time.
|
||||
|
||||