Compare commits

..
Author SHA1 Message Date
DeeJanuzandClaude Opus 5.5 962e99de2d Merge branch 'hand-bounties' into experimental
Hand Recorder bounty rounds and testing sessions, under the testing
consent (TESTING.md) and encrypted to the gated test dataset; the eye
recorder work comes along.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:05:27 -06:00
DeeJanuzandClaude Opus 5.5 304dea488f hands/rec: TESTING.md approved, test uploads open
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:02:30 -06:00
DeeJanuzandClaude Opus 5.5 2ab76aa547 hands/rec: test_debug finds test_validate under python -I too
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:58:58 -06:00
DeeJanuzandClaude Opus 5.5 14c7e88b7b Remote displays: a Linux host's private displays are virtual
Vibepollo on Linux lists its own virtual displays as "Vibepollo Private
Display (DP-n)", without the SDD EDID that marks them on Windows, so Add
displays offered them as monitors, and the host refuses those as Frametop
displays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:58:49 -06:00
DeeJanuzandClaude Opus 5.5 9969a20d30 hands/rec: testing-session key help, per-kind "text changed", 16 GB rounds
The Session page's help names Mark and Finish in a testing session.
Welcome's "this text changed" shows only to someone who agreed to an
older version of that consent, not to anyone with a contributor id. A
bounty round records 13-15 GB at 30 sets/s, so the free-space check
wants 16 GB and the checklist says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:56:54 -06:00
DeeJanuzandClaude Opus 5.5 8835767181 hands/rec: testing sessions and an encrypted test phase
Testing session (debug.json, session.py --debug): with Frametop's hand
tracking installed, the board's first row records up to 3 minutes of
normal use at 30 sets/s plus the live tracker's hands and gestures
files (livelog.py, live.bin), the HANDS_/POINTER_ settings and model
hashes. The headset button marks a failure; holding it finishes.

Test phase (takes.TEST_PHASE): bounty rounds and testing sessions are
recorded under a short testing-only consent (TESTING.md, draft) and go
to the gated DeeJanuz/frametop-hands-test, encrypted on the headset to
the maintainer keys (test-recipients.txt, age). validate.py checks the
encryption, the consent kind and the live files. The window switches
consent text, upload gate and dataset per round and per session.

Also: the export's manifest profile keeps only the consent record of
its kind (bounty counts made validate reject it), and age.shape moves
from gaze/rec/validate.py to recorder/age.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:49:12 -06:00
DeeJanuzandClaude Opus 5.5 be1a78eb1a Hand recorder: 2 s minimum when the acts switch hands
A scene step whose acts switch between the hands (L/R buttons, or acts
naming each hand) gives each act at least CHOICE_MIN_S (2 s) lit, so
there's time to see which hand and use it. The buttons generator
stretches its lit time; a written act that's shorter fails the plan.
The tap rounds' both-hands steps go to 16 s (6 taps).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:07:34 -06:00
DeeJanuzandClaude Opus 5.5 8dcd6dc491 Hand recorder: pointing taps and "Switch to" ticks
The tap rounds now ask for the hand raised and pointing at the lit
button, palm away, as with Frametop's hand ray, instead of tapping from
the lap while looking: each hand with the arm straight then bent, two
windows, high and low, a far window, both hands, presses, near misses.

A step with two poses says when to change ("switch"): the time-left
bar gets a tick with "Switch to <pose>" over it (the panel's new split
command), lit once reached, optionally a new instruction, and a
"switch" event in prompts.jsonl. All four hand-size steps use it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 15:57:59 -06:00
DeeJanuzandClaude Opus 5.5 6fa9997394 Hand recorder: bounties first, end to end in the window
The window opens on the Bounties page. Picking a bounty (or the full
session or quick round) goes through consent when needed, then the
checklist with the camera and privacy checks, then the round. When the
round is done, "Export and upload" exports it and opens the Upload page
for that export (new exportDone signal on RecorderBackend).

The checklist's Round section shows the pick with "Pick another…";
objects, controllers and guidance are hidden for a bounty.
test_qml_backend checks that main.qml's backend handlers are signals.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 15:32:14 -06:00
DeeJanuzandClaude Opus 5.5 e915f6343b Merge branch 'experimental' into hand-bounties
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 15:13:43 -06:00
DeeJanuzandClaude Opus 5.5 532cd494af Hands: bounty rounds on virtual windows (taps, middle taps, pinches, card grabs)
The hand recorder gets the eye recorder's bounty board (recorder/bounties.py):
short rounds of what the tracker needs most. Instead of held poses, a bounty
puts windows in front of the person and asks for real interactions on them:
tap the lit button, pinch the corner and drag it to a ghost, grab the edge
like a playing card and throw it. The windows don't move; each try's target
and time are logged as weak labels.

- ft-handpanel: "layout top" (a band along the top) and up to 4 windows in
  their own overlays (win place/lit/ghost/off/clear): plain, grid or list
  looks, lit bar/edges/corners/buttons ("+" for several), coloured by
  gesture, dashed ghosts, poses in the room in the replies.
- session.py: "kind": "scene" sections with acts and generators (buttons,
  moves), steady lights, act/scene/steady events in prompts.jsonl, a script's
  record_hz (the bounties: 30), --bounty and --board, the done mark.
- Four bounties (bounties.json, bounties/*.json): index-taps, middle-taps,
  pinches, card-grabs; about 2.5-2.9 min recorded each.
- Window: the bounties under "Round:" on the checklist page, Get the newest
  board, the bounty in Review; the old planText/startSession signatures stay
  for the standalone recorder's window.
- hub.py board; the bounty and sets a second in the upload's description.
- tests/test_bounties.py; DESIGN.md "Scenes" and "Bounties".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 15:11:25 -06:00
DeeJanuzandClaude Opus 5.5 01796eb299 Releases: ship the Hand Recorder
The image builds ft-handpanel (hands/rec/build.sh, against scripts/openvr.sh
like gaze), and a release's installer offers the recorder: ft-camd's
capabilities and the menu entry, nothing to build. The FrameDrop window has a
Hand Recorder box, and --no-hand-recorder leaves it out. An entry from the
release before is renewed without asking, since it points into that
release's folder.

The recorder runs ft-hands through scripts/in-box instead of the "dev"
container, so a release uses its own container, and its repair hints say to
reinstall the release rather than run a build script.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 14:32:07 -06:00
DeeJanuzandClaude Opus 5.5 3e6dba8276 Report: an area per flag, and --watch records each area live
scripts/report.sh takes --system, --desktop, --gaze (--eyes), --hands and --voice; with
none it reports on all of them, as before. Every report keeps the versions and the
settings. New in it: CPU, memory, heat and the busiest processes (--system), and Frametop
Voice (--voice): its services, state, settings (counts, not phrases or commands), speech
models, and the microphone: proxmicmute's gain, PipeWire's capture chain with its errors,
who holds the capture device, and its level over one second (no sound is kept).

--watch SECONDS now runs scripts/report-watch.py for the chosen areas, one thread each:
ft-screens' debug line (desktop), the gaze service's status (gaze), ft-hands' published
frames read under their sequence lock each second (rate, age, each hand's share and
confidence, closest thumb-index and thumb-middle tips) and the side cameras' decision
(hands), Frametop Voice's events with what was said replaced by word counts and the mic's
level each second with its gain when it goes silent (voice), and load, clocks, heat,
memory and the busiest processes every 5 s (system). Then each area's logs from that time.
README's Reporting problems says how.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 14:16:16 -06:00
DeeJanuzandClaude Opus 5.5 098ba9e71e Hands: pinches let go less easily by default
Fresh installs ended taps and pinches at 3.5 cm, the values the headset's tester
found "release way too easily" on 2026-10-11 (ends came at 4-6 cm, grips took
pinches 130 ms in). The headset has run with HANDS_PINCH_END=0.045,
HANDS_PINCH_DRAG_OPEN=0.065, HANDS_PINCH_DRAG_OPEN_S=0.2 and
HANDS_GRIP_TAKEOVER_S=0.1 since; they are now the defaults. pinch_test keeps the
old values for its rule tests and checks the new defaults on their own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 13:17:00 -06:00
DeeJanuzandClaude Opus 5.5 eb31589aed Report: hand tracking's state (models, cameras, sides, ft-hands counts)
scripts/report.sh had no hand tracking at all, so a "tracking is bad" report couldn't
tell a stock model from the pinned one, a failed camera start from bad light, or a
starved tracker. Its new section: HANDS_MODE and the three services, the fine-tuned
models' version and models.sh check, any HANDS_MODELS override, hands/camcheck.py,
sides.json, CPU 5-7 clocks and the hottest thermal zone, ft-hands' starts and last
status, and ft-camd's start lines. --watch adds ft-hands' log (pinches) too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 13:17:00 -06:00
DeeJanuzandClaude Opus 5.5 6e06a96103 Gaze: the fit watch, the put-on check and the slip note (GAZE_FIT_WATCH)
Off by default until it's been tried in the headset. The fit check keeps
a good fit as yours (fit-baseline.json), as the eye recorder's fitment
does. With GAZE_FIT_WATCH=1:

- The quick check that opens when the headset goes on first holds its
  dot while the fit coach reads the fit against the saved one. Moved
  past 5 degrees, the panel widens and says which way to move it, live,
  until it's back; a click or 30 s takes the dot as it sits.
- With our tracker in use and gaze mode on, ft-eyes' glint slip (status
  now has jump_px) past 5 degrees for 2 s shows a small strip low in
  view ("show note" in ft-gazepanel), for 8 s or until the slip is gone,
  at most once every 2 minutes.

gaze/test/fit-watch-test.py tests both offline. The eye recorder's
redo test waited on a state the step before left, and missed the redo
about 1 run in 8.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 12:18:14 -06:00
DeeJanuzandClaude Opus 5.5 b7f0e68d81 Eye recorder design: the license and when the standalone repo comes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 11:42:11 -06:00
DeeJanuzandClaude Opus 5.5 0b53cc5ddc Eye recorder: the window, and its shared half in recorder/window.py
The hand window's non-hand backend (consent, disk, session controls,
export, Hugging Face login and upload) moves to recorder/window.py as
RecorderBackend; ft_handrec.Backend subclasses it. Subclass properties
notify only through their own signals (relays): PySide6 6.11 gives a
property notifying on a base class's signal no notify at all, and QML
crashed at load.

gaze/rec/ft_eyerec.py + main.qml: the eye window, copied from the hand
window's pages, plus the bounty board, the checklist with the opt-in
health answers, the eye camera check (90 fps, with the SteamVR restart
fix), the fit card during the fitment, and a viewer that shows both
eyes side by side. ft-eyerec launches it in the dev container,
install.sh adds it to the menu.

CONSENT.md and UPLOAD.md are drafts, so uploads to the real dataset
stay closed (hub.py's gate) until their review. The session status
carries the fit card and the IPD setting; hub.py fetches the board.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 11:14:56 -06:00
DeeJanuzandClaude Opus 5.5 0bad928f51 Eye recorder design: the shared recorder/ modules and the upload gate
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 10:36:32 -06:00
DeeJanuzandClaude Opus 5.5 44ae86a28b Eye recorder: hub.py uploads to the eye dataset; shared Hub code in recorder/hub.py
The real dataset (DeeJanuz/frametop-eyes) takes nothing until CONSENT.md and UPLOAD.md exist and
aren't drafts; FT_EYEREC_ALLOW_UPLOAD=1 opens rehearsals only to another dataset. The hand
recorder's hub.py keeps its names and tests on top of the shared module.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 10:35:39 -06:00
DeeJanuzandClaude Opus 5.5 ea030ca721 Eye recorder: validate.py for encrypted exports; shared checks in recorder/checks.py
Without a key it checks the checksums, an allow-list (no unencrypted chunk or health.json), every
.age file's header and size against the manifest's recipients and recipients.txt, the manifest
(consent, uuid4 contributor, no dry run or replay), and each index.tsv against its chunks. With
--identity it also decrypts each chunk and checks its frames.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 10:29:56 -06:00
DeeJanuzandClaude Opus 5.5 462864c49e Eye recorder: the round store and its encrypted export; shared file helpers in recorder/files.py
gaze/rec/takes.py lists rounds and takes, keeps deleted ranges (MONOTONIC, turned to RAW with the
take's clock samples), and exports each chunk and health.json encrypted to recipients.txt, with
deleted frames cut out of their chunks, the RAW-timed logs cut to match, and SHA256SUMS. unpack
checks and decrypts an export with one of the dataset's keys. The hand recorder's takes.py now
imports the helpers both use.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 10:25:39 -06:00
DeeJanuzandClaude Opus 5.5 129c796b05 Eye recorder: cryptography in the dev container and the locked tracker group, for age
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 10:18:37 -06:00
DeeJanuzandClaude Opus 5.5 923ea10ac9 Recorder: age v1 encryption for exports, and the eye dataset's recipients
recorder/age.py writes and reads age v1 files to X25519 recipients on
Python's cryptography library (SteamOS's Python has it; the age command
isn't on the Frame). Checked against age 1.1.1 both ways: real age
decrypted its files with both dataset keys, and it decrypts real age's;
tests/data/age-vector.age, made by age for a test-only key, keeps that
check in the tests.

gaze/rec/recipients.txt: the two public keys exports encrypt to. Key 1
stays on the maintainer's training machine, key 2 offline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 10:16:04 -06:00
DeeJanuzandClaude Opus 5.5 fdd1b3adb5 Eye recorder: the session runner, the bounty board and the ten launch rounds
gaze/rec/session.py runs one round for one bounty: the fitment (the fit
coach on a centre dot until the fit is good; Next before that warns, a
second press goes on and fit.json says it was skipped), an IPD sweep on a
first round or when the IPD changed, the nine dots, then the bounty's
steps from rounds/<script>.json. Step mode with a recorded 3-2-1, takes by
step group (eye frames, the panel's targets/poses/ipd logs, ft-eyes'
finds as own.jsonl, ft-gaze's steamvr.jsonl, prompts.jsonl, take.json),
redo/skip/pause/stop and the headset button as in the hand recorder, and
a shift check after each centre dot against the round's own fit.
load_round checks every dot and path against the rec panel's reach.

recorder/bounties.py: the board, shared with the hand recorder. A fetched
board can only describe, reorder, reprioritise or retire bounties: each
names a round script shipped with the recorder.

ft-eyes gains "finds start PATH / finds stop" (a row per frame looked at),
the panel an "ipd" command. Tested in dry runs and on a replay of
practice1 (5 takes, both cameras 90 fps, nothing dropped).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 10:11:22 -06:00
DeeJanuzandClaude Opus 5.5 c1df76d17c Gaze panel: the eye recorder's rec mode, moving dots and the ground-truth log
"show rec" is the full calibration's size and background with the hand
panel's lines (title, step with a Rec dot, wrapped text, big, action,
note, keys, countdown, paused). Its dot is a second overlay, drawn once
per state and only moved, so "path" (circle, line, figure eight) moves
it at the headset's frame rate without new pictures, and "world" keeps a
dot fixed in the room, facing the head. "distance" moves the panel and
its dot for the Depth bounty.

"log start DIR" writes targets.jsonl (a row per frame the dot moves and
per change: the estimated photon time and the time it was set, on
CLOCK_MONOTONIC_RAW like the eye frames, the vsync count, direction,
distance, state, background), poses.jsonl (the headset at 250 Hz on its
own thread) and ipd.jsonl (at the start, on SteamVR's event, and looked
at 30 times a second). --overlay lets the recorder run its own copy;
--no-vr with --dump runs it without SteamVR for the new test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 09:48:06 -06:00
DeeJanuzandClaude Opus 5.5 1b256289b9 Hands: new hand models reach installs without a release
The pin moves out of models.sh into hands/models.pin. When hand tracking starts,
frametop-hands.service runs `hands/models.sh auto`: it reads models.pin from
GitHub (main for stable releases, experimental for experimental ones and clones
on that branch), and if it pins other models, fetches them into
models/.student-new, checks every sha256 and swaps the folder in whole with
one rename. At most every 15 minutes and within a minute; offline, a 404 or
anything not matching keeps the models it has.

A pin from GitHub is checked line by line before use: a 40-hex commit, a
plain folder name, file names from a fixed list, 64-hex sums, and a format
number, so a model that needs a newer ft-hands can be held back from older
installs. The Hugging Face repo stays fixed in the script.
HANDS_MODELS_UPDATE=0 turns it off; `hands/models.sh update` checks now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 09:46:01 -06:00
DeeJanuzandClaude Opus 5.5 0331d8bd50 Fit check: the fit coach's hint first, from ft-eyes' finds
ft-eyes keeps the fit coach's last second of pupil and glint finds and
answers "fit" with their summary (in frame time, so replays work and a
stopped camera empties it). The Gaze page's headset fit check runs
ft-eyes for itself on a lease, whichever tracker is in use, asks twice
a second, and judges only while SteamVR's gaze stays within 8 degrees
of straight ahead; away from that it shows the last centred reading.
Between OK and adjust without an earlier OK, the coach names the
biggest term so there's always something to do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 09:39:35 -06:00
DeeJanuzandClaude Opus 5.5 fc5ec50ba1 Eye recorder: fit coach (gaze/fitcoach.py) and a provisional reference
From ft-eyes' pupil and glint positions over the last second: where each
eye sits against a reference (a per-camera Jacobian fitted from
calibration dots, so offsets come out as gaze degrees for both camera
orientations), split into up/down, left/right, IPD and tilt, plus eye
relief from the glint spacing against this face's baseline. Hints with
hysteresis, a lost-eye state, and IPD advice only once we know the eye
cameras move with the lenses (headset test pending).

gaze/fit-reference.json is fitted from two of the maintainer's three
calibrations, so it is marked provisional. The reflections hint needs 5+
glints in half the finds: 3+ are common without glasses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 09:32:25 -06:00
DeeJanuzandClaude Opus 5.5 ab83894578 Eye recorder: frame writer (gaze/rec/eyerec.py) and the shared-frame reader
eyerec.Writer copies both eye cameras out of ft-eyegrab's share on one thread and writes zstd-1
chunks (a second per camera) on another, with index.tsv written after each chunk is on disk.
Pause ends the chunks; it follows a replaced share, drops whole chunks if the writer falls
behind, and stops before the disk fills. zstd: compression.zstd, zstandard, or the zstd command
(the host's Python 3.12). gaze/tracker/eyes_share.py is the share reader, now also
ft-eyes-record's.

Replay of a real capture (12 s, 2,160 frames): none dropped, 90 fps per camera, 56 % of raw,
the writer busy 17 % of one core.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 09:24:41 -06:00
DeeJanuzandClaude Opus 5.5 c3f0fb3bd8 Recorders: shared recorder/ module (button, units, clocks) out of hands/rec/session.py
The headset button reader and gestures, the systemd unit helpers, the clock samples and the
version readers move to recorder/ for the eye recorder (gaze/rec/DESIGN.md, "Shared with the
hand recorder"). session.py imports them under the names it always had, so the window, the
standalone recorder's spike and tests keep working. start_unit takes the app name for the unit
description (default: the hand recorder's). The standalone recorder's package.sh needs to ship
recorder/ when its submodule moves past this.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 09:20:23 -06:00
DeeJanuzandClaude Opus 5.5 5d06261370 Eye recorder design: decisions (encrypted gated dataset, bounty board, health opt-in, keys)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 09:13:33 -06:00
DeeJanuzandClaude Opus 5.5 aef8b0bc90 Eye recorder: design draft (gaze/rec/DESIGN.md)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 09:02:41 -06:00
DeeJanuzandClaude Opus 5.5 9eac1e29a9 Hands: ship the fine-tuned hand models (v13b-p1) instead of stock MediaPipe
hands/models.sh fetches MediaPipe's palm detector and hand landmark model,
retrained on the Frame's infrared cameras with the Frametop Hands dataset,
from a pinned commit of the Hugging Face repo DeeJanuz/frametop-hands-models,
and checks every file's sha256. hands/build.sh runs it, so source installs
and the release image both get them; the release smoke test checks them.
The weights are CC BY-NC 4.0, not MIT, so they stay out of this repository
(gitignored, dockerignored); their LICENSE and model card come with them.

ft-hands and ft-handreplay now default to hands/models/student when it's
there (HANDS_MODELS and --models still override; --int8 keeps the stock
models, which are the only ones with 8-bit files).

Replays through ft-hands, hands tracked, stock -> v13b-p1: bright room
442 -> 960, dim 912 -> 1224, lit 782 -> 1433. On held-out contributors
the landmark error drops from 5.2 to 3.8 px (median).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 08:30:04 -06:00
DeeJanuz 4d4825bf9a Install: hand tracking is an install option, in releases too
install.sh offers hand tracking (step 9/12, yes by default; --no-hands skips it,
and --yes installs it only when sudo runs without a prompt). Installed, it runs
with the Frametop desktop (HANDS_MODE=frametop), unless the settings already say
always. get.sh, pack/install-release.sh and the FrameDrop window pass --no-hands,
and the window has a hand tracking box that needs the password like the eye
tracker's.

The release image builds ft-camd and ft-hands (with ncnn at the tag
hands/Makefile pins), and hands/run.sh install doesn't build in a release, so
it only sets ft-camd's file capabilities and installs the units. The release
workflow's smoke test checks both binaries. Docs drop "deferred" and describe
the gestures and the Hands page.
2026-10-13 22:22:37 -06:00
DeeJanuzandClaude Opus 5.5 e6dd58c406 spotwatch test: skip ft-spotwatch when "gi" isn't PyGObject
The release image's test stage imports a "gi" without require_version,
which failed the v0.3.0-exp.8 build instead of skipping.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 22:00:27 -06:00
DeeJanuzandClaude Opus 5.5 83ab2f0b5e Host setup: Frametop's Vibepollo build frametop-2.0.0-2
The monitor's closest listed mode, and HDR off before the resolution
switch. frametop-2.0.0-1 joins the older builds the setup replaces.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 21:44:22 -06:00
DeeJanuzandClaude Opus 5.5 6f63702089 host/macos: setting up the per-display Sunshine instances by hand
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 21:31:56 -06:00
DeeJanuzandClaude Opus 5.5 36d11c523e docs: monitors that come and go on the hosts; SteamVR panel grabs off
host/macos: an instance follows its monitor by maker, model and serial,
waits while it's unplugged, and a new monitor needs the setup again.
host/windows: new monitors show up in Add displays; how long a virtual
monitor lives. remote-displays.md: the Mac runs one instance per display
now. hands/README: SteamVR's panels take taps, not grabs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 21:27:48 -06:00
DeeJanuzandClaude Opus 5.5 4b9f5bf8dd update-check: find XRService by its command line
XRService renames its main thread to "XRServiceLoopTh", so pgrep -x
XRService never matched and the check reported it missing while it ran.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 21:25:11 -06:00
DeeJanuzandClaude Opus 5.5 afab3cbecc pointer: the 3D mouse is a treadmill again, now that it can move windows
Reverts 797e5c7. With pointer/dashpatch, the treadmill moves SteamVR's
windows by their grab bars, so the default goes back to the role that
leaves both hands to the controllers. docs/design.md explains the cause and
the patch; reference.md lists the patch; update-check.py checks that the
dashboard still has the function the patch wraps and that its debugger is
reachable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 21:25:11 -06:00
DeeJanuzandClaude Opus 5.5 6d0c542bb8 pointer: a dashboard patch lets the treadmill move SteamVR's windows
SteamVR's dashboard starts a floating window's move only for a press from
the head or a hand: UndockedOverlay.startFloatingWindowMove reads the
pressing device from the mouse event's CapsLock/NumLock bits and logs "mouse
event carried no input path" for anything else. So the 3D mouse as a
treadmill clicked and resized SteamVR's windows but couldn't move them, the
regression since 2026-10-09.

pointer/dashpatch wraps the grab bar's handler in the dashboard page: a
press with no device runs it as the right hand, with that pose answered by
/user/treadmill, and the move then follows /user/treadmill.
frametop-dashpatch.service puts it in over the dashboard's debugger, again
whenever SteamVR restarts. The installer turns the debugger on at
127.0.0.1:8089 (not 8087, which SteamOS forwards to the network on 8088);
the uninstaller turns it off if Frametop turned it on.

Headset test 2026-10-13: window moves with the treadmill role work.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 21:23:04 -06:00
DeeJanuzandClaude Opus 5.5 b0af03e83c hands: SteamVR's panels take taps but no card grabs
Pinching a SteamVR panel like a card never moved it reliably (the dashboard
follows only a hand device's grab, and our hand's ray isn't one), so its
edges and corners now take nothing. A pinch on a window's grab bar with the
hand ray still moves it. Frametop's own panels keep card grabs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 21:22:46 -06:00
DeeJanuzandClaude Opus 5.5 ada9d6e9c9 hands: a gamescope app window counts as a floating SteamVR panel
Spotifast's window (gamescope.gamescope-0.window.N) never shows the
dashboard's floating footer, so every border pinch on it was refused. Its
grab bar and resize handle are there all the same (probing 2026-10-13: the
bar 6-9 cm under the bottom edge, the handle 1-5 cm past the bottom right
corner), so it skips the footer check and its resize aims 3 cm out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 20:36:50 -06:00
DeeJanuzandClaude Opus 5.5 797e5c7b12 pointer: the 3D mouse is the right hand again, not a treadmill
As a treadmill (the default since 564bb4b), the 3D mouse's laser clicks and
resizes SteamVR's windows but can't move them by their grab bars: the
compositor's window grab follows only /user/hand/left or /user/hand/right,
and logs nothing. With the right hand's role the same laser moves them
(headset test 2026-10-13, SteamVR 2.18.2). The driver's default role is 2
again and POINTER_ROLE defaults to right; treadmill stays a setting.
update-check warns when the device is at /user/treadmill.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 20:33:32 -06:00
DeeJanuzandClaude Opus 5.5 8f79a90044 Merge branch 'steamvr-panels-hands' (9d6f598) into experimental
Hands on SteamVR's own panels through the pointer helper's laser. Its WIP
commit 3a8741a (cornerprobe, LockMousePosition on the trigger) stays on the
branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 20:31:21 -06:00
DeeJanuzandClaude Opus 5.5 9d6f5984a8 hands: near input on SteamVR's own panels through the pointer helper's laser
The dashboard, the Steam menu, Steam's keyboard and other apps' overlays now
take a poke or a pinch on the content as a click, and a pinch on the border,
like a card or at a corner moves or resizes a floating one. The edge and
corner glows show there too.

OpenVR gives no transform or size for dashboard panels, so ft-screens casts a
7x7 cone of rays from the eyes past each index tip and fits each panel to the
hits' texture coordinates (steampanels.cpp). Near input treats the fitted
panels as foreign: no fist grabs, two-hand stretch, throws, flicks, pushes,
rewinds or two-finger scroll.

ft-screens can't click those panels, so it drives the helper's laser with
"touch" lines (hover, press, move, up, grab, end). A move or resize first
hovers inside the edge and presses the grab bar or resize margin only once a
floating panel's window controls show under it; otherwise the log says why.
The helper keeps its overlay list while hands are allowed and sends it to
ft-screens ("steamvr ...").

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 19:47:25 -06:00
DeeJanuzandClaude Opus 5.5 7dfdfd24e1 pack: release notes point to the remote displays host kits
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 18:05:26 -06:00
DeeJanuzandClaude Opus 5.5 35d30474bc docs: setting up a computer for remote displays (Windows, macOS, Linux)
A Remote displays section in the README with the three host kits; host/windows/README.md
and host/linux/README.md beside the Mac's; reference.md names frametop-2.0.0-2 for the
resolution switch; remote-displays.md is the design notes now. No machine names in hands/README.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 18:05:04 -06:00
DeeJanuzandClaude Opus 5.5 f447ecc7ec hands: gap_report says how late a hand came back; replay_gaps takes REPLAY=
gap_report: per side, for gaps where the full search lost the hand for a while
(back in view) and the rest, the time from the oracle's first sample finding it
again to the tracker having it. replay_gaps.sh: REPLAY=BINARY replays with
another ft-handreplay build, for a baseline.

On 2026-10-13 they showed student v13b losing hands v11c keeps (bright desk
recording: 12.8% of findable hands missed against 3.3%, mostly palms the
landmark model rejected).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 17:44:20 -06:00
DeeJanuzandClaude Opus 5.5 9029a2d7a5 hands: drawn hands blend between frames, hold still when lost, refuse jumps
User, 2026-10-13: "implement interpolation for the rendered hands so that they
feel smoother", and "if the hand is lost it's preferable the rendered hand
display freeze instead of make impossible movements, spaz out, or vanish until a
few seconds have passed".

screens/handhold.h, per side in ft-handview:
- each tracking frame blends in joint by joint from the drawn pose over about
  the frame interval (15-70 ms), drawn every 15 ms meanwhile;
- a lost hand stays frozen where it was drawn for HANDS_VIEW_HOLD s (3);
- a frame 15 cm / 6 m/s off the last one taken, or with the palm turned over,
  waits for two agreeing frames (or 0.25 s) while the drawn hand holds still;
  a first-seen or returning hand waits for two agreeing frames too.
HANDS_VIEW_SMOOTH=0 gives the old behaviour. Tests in handview_test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 17:30:41 -06:00
DeeJanuzandClaude Opus 5.5 09ba8afcf0 hands: the lazy susan by hand is a little harder again
User, 2026-10-13: "make the lazy susan just slightly more difficult to trigger".
One hand: edge 0.88, lead 0.16, 20 cm, quick at 0.75 m/s somewhere along it;
3 frames off shape ridden out. The flags replayed: all 47 practice strokes still
count (each peaked at 0.8 m/s or more), other use 3 false strokes, down from 4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 17:15:36 -06:00
DeeJanuzandClaude Opus 5.5 57d3510ad7 screens: a hand ray carrying a panel keeps it facing you
The ray places it; the wrist's turn no longer tilts or turns it. Controllers
and the mouse still carry it rigidly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 17:00:39 -06:00
DeeJanuzandClaude Opus 5.5 45e6759ef2 screens: a wider resize corner, its glow as wide
The handle (the laser's hit area, all outside the corner) is 1.8 buttons
wide, and the laser's corner glow reaches as far off the edges.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 16:56:12 -06:00
DeeJanuzandClaude Opus 5.5 341fa2435f screens: the resize handle draws nothing; a soft glow shows the corner
The laser's aim at a corner gets the same white L a hand's pinch gets
(a third guide overlay, frametop.guide.laser), brightest while resizing.
The handle stays just outside the corner as the laser's hit area.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 16:49:14 -06:00
DeeJanuzandClaude Opus 5.5 0b08bfabaa hands: the lazy susan by hand is easier to trigger
The live misses were palm-led strokes with the palm's lead under 0.25, tilted
0.81-0.88 toward flat, or drifting 21-22 cm up. Lead 0.3 (one hand 0.12),
edge 0.85 (one hand 0.9), drift 0.3, 4 frames off shape ridden out. The
flags: 51 strokes (49), 4 in other use (2). A refused stroke's log now says
which place rule refused it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 16:46:23 -06:00
DeeJanuzandClaude Opus 5.5 d1b495a7f0 hands: grab that's start-up line names the aim
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 16:38:24 -06:00
DeeJanuzandClaude Opus 5.5 e4bc1fbc6e hands: grab that and its glow aim where the open palm faces
The line from the eyes through the palm lit panels off to the side of a palm
that wasn't facing them. The line is now the palm's own, along its normal,
with the margins seen from the palm. HANDS_GRAB_THAT_AIM=eyes brings the old
line back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 16:36:01 -06:00
DeeJanuzandClaude Opus 5.5 9f3dc1ca12 float: spares in a grid below the screens, inside Xwayland's coordinates
X11 windows get the layout's coordinates times its largest scale, which wrap
past 32767. The 4th spare at x 27000 and scale 1.25 put Brave at x -31506:
KWin focused it on a click, but the click never reached it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 16:31:11 -06:00
DeeJanuzandClaude Opus 5.5 0abcda6e80 float: 16 floating windows by default, up from 8
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 16:27:33 -06:00
DeeJanuzandClaude Opus 5.5 30313ea7db ft-floatd: launched apps float when their window gives only a class (Brave)
Brave's Flatpak opens an X11 window with no app id, class Brave-browser, and a pid inside
its sandbox, so neither the process nor the desktop file name matched and it opened docked
(2026-10-13). desktop_name now finds a window's desktop file by its app id, else by its class:
StartupWMClass, the desktop file's name or its last dotted part, or the program it runs
(Flatpak's --command=). As a last resort, a window no desktop file claims floats as the
launch's when exactly one launch is waiting. The same name keys floating places, spotlist
and profiles (a profile now relaunches such an app by its desktop file, not a sandbox pid's
command line). Answers are cached for a minute.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 16:22:58 -06:00
DeeJanuzandClaude Opus 5.5 b0300387f4 spotwatch: Frametop's own apps count as running
ft-floatd's spotlist used the profile filter, which leaves out every ft-* window, so Enter
on an open Input Settings, Display Settings or Remote Displays launched another copy
(2026-10-13). spotlist now has its own filter (listable) that keeps them; profiles still
leave them out. ft-spotwatch logs each click and menu with the row, to tell a right click
from a left one in the headset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 16:18:11 -06:00
DeeJanuzandClaude Opus 5.5 7cea0b440a ft-layout: remote stream sizes rounded down to even numbers
A width typed as 1921 in Remote Displays was saved and asked for as is. The host's encoder
(NVENC, 4:2:0) sent no video for it, the host ended the stream about 11 s in, and the
display reconnected forever (2026-10-13). remote set, remote add --size and each stream's
start round to even, so a saved odd size from before works too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 16:01:59 -06:00
DeeJanuzandClaude Opus 5.5 54341c5aa4 ft-screens: spin to N uses the front slot while the lazy susan brings panels
spotwatch's "spin to N" still turned the whole ring after the merge, the panel in the
front slot with it, while next and prev bring one panel to the slot. With
SCREEN_SPIN_BRING on (the default) it now brings panel N there too; the ring turn stays
for SCREEN_SPIN_BRING=0 and for degrees. Docs: reference.md's spin, spotwatch.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 15:45:49 -06:00
DeeJanuzandClaude Opus 5.5 63fb9e0127 Release hygiene: drop the unused demo recorder, keep spotwatch's render tool out of the test glob
- hands/rec/demo: ft-handdemo, sheets.py and gifs.py recorded the demo clips in the
  headset, dropped on 2026-10-12 for generated skeleton clips. camgifs.py keeps its
  gifsicle lookup; the README covers what's left.
- hands/.gitignore: rec/demos-recorded/, the recorded clips show the recorder's room.
- spotwatch/test/render.py -> spotwatch/tools/render.py: it needs an output path, and
  just test-python ran every spotwatch/test/*.py with no arguments.
- voice/README.md: the advanced example's hook is the repo's hooks/on-command, not a
  path in one person's home.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 15:43:44 -06:00
DeeJanuzandClaude Opus 5.5 49411bb828 Merge branch 'mac-host' into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 15:34:18 -06:00
DeeJanuzandClaude Opus 5.5 09126151d8 Merge branch 'hands-feed' into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 15:34:08 -06:00
DeeJanuzandClaude Opus 5.5 870ad7687c Merge branch 'hands-fistguard' into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 15:32:45 -06:00
DeeJanuzandClaude Opus 5.5 3fe498ffc3 Merge branch 'hands-r6' into experimental: hand tracking as the main input
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 15:32:45 -06:00
DeeJanuzandClaude Opus 5.5 4c20053101 Hands: far two-fist resize, hand-tap reset asks first, easier lone-hand lazy susan
- Far stretch: both palms held out at the same far panel, then two fists
  within 0.6 s, scales it round its centre (a floating window by pixels)
  until a hand opens. Aims at the panel both hands' lines meet, or the
  line through the palms' midpoint. Grab that holds its fire meanwhile, and
  both hands are claimed from the pointer helper so a fist passing through
  a pinch doesn't click or drag under a raised hand ray. Near misses log why.
- Reset button: a hand's tap shows "Reset the layout? Tap" under it for
  5 s; a tap on it (or the button again) resets. A laser click resets at once.
- Lazy susan: with the other hand still or unseen, a looser shape, 18 cm
  and 0.5 m/s count; any stroke rides out 2 frames off its shape; misses
  log open/tilt/lead against their limits.
- Pointer helper: the two-hand gaze drag no longer logs "with the right
  button" (it is the left alone).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 15:25:01 -06:00
DeeJanuzandClaude Opus 5.5 1faa0241e2 Hands: easier pinch throws; sent away, a panel keeps its distance and size; reset on a tap; glow under hand rays only
Throws: a carry's let-go takes the fastest outward stretch in the last
150 ms before the fingers opened (a hand slows as it lets go), at 0.45 m/s
within 70 deg (was 0.55 within 60, the last 100 ms only). Every let-go
moving 0.3 m/s or more is logged.

Sent away (thrown, flicked, pushed), a panel goes along that line out as
far and as big as it was before a hand or "grab that" took it, not back
to its old spot (layouts are for that). Put down past 1.2 m, that's its
distance from then on; never taken, it flies to 3 m as before. The front
slot's screen leaves the slot the same way.

The bar's buttons sit a button's width apart, and the reset button
resets the layout on a tap (HANDS_RESET_HOLD_MS=0; 500 before).

Grab that's glow: ft_pointer's laser sits on the panel with the cursor
all the time (the 3D mouse, the gaze), so "no glow under a laser" kept
the glow off that panel. The pointer helper now tells ft-screens which
hand rays are up ("ray L R", on change and every second); our laser
counts as one only then. Controllers' lasers count as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:50:10 -06:00
DeeJanuzandClaude Opus 5.5 c0947a438e Grab that: the glow shows on every panel again, in its own shape
The "no glow under a laser" rule counted any overlay event as a laser, and
SteamVR sends panels events from the headset and from no device at all, so
the glow stayed off nearly everywhere and only the last one drawn (the
32:9 remote) was ever seen. Only a controller's events (the pointer
helper's 3D mouse and hand ray are ft_pointer controllers) count now. The
log says when a laser holds the glow back, and the glow's size per panel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:27:12 -06:00
DeeJanuzandClaude Opus 5.5 60ca2fba69 Lazy susan: ultrawides come up to 150 deg wide so their text reads
A 5120x1440 remote in the front slot was held to 100 deg wide (51 px/deg,
hard to read). Panels 3:1 or wider may now go to SCREEN_SPIN_MAX_WIDE_DEG
(150) instead, and their curve may wrap that far round you.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:27:12 -06:00
DeeJanuzandClaude Opus 5.5 81dbd32812 ft-camd: exit when a camera's node changes format
Plugging the colour module in with passthrough working moves the side
cameras from the ISP nodes (video0/3) to video9/13 and puts the colour
cameras on video0/3. Those nodes keep streaming, so silent_camera never
fired and ft-hands was fed 2464x2464 NV12 frames as side cameras.

Check each node's format once a second on a handle opened at setup;
any change exits with status 4 so systemd restarts on the new layout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 10:51:59 -06:00
DeeJanuzandClaude Opus 5.5 fdf382f0f5 ft-camd: a camera that wakes late after the headset goes back on isn't a moved camera
Headset off/on 2026-10-13: one camera started 0.1 s, then over 3 s, after
the others, and ft-camd exited as if XRService had moved the cameras (about
5 s without hands each time). For 10 s after the cameras start again a
silent camera is allowed; one moved while the headset was off is caught
after that.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 10:42:46 -06:00
DeeJanuzandClaude Opus 5.5 53cdefd74b Hand recorder: recorded-hands guidance, clips made from a session's side cameras
The v2 script's demo clips come in two kinds now, picked on the start page
("Guidance") and kept in settings.json: recorded clips of real hands
(demos-recorded/) or the drawn skeleton ones (demos/). Recorded is the
default when there are any; a part with no clip of the chosen kind shows the
other kind. session.json records the choice. The panel's demo command takes
"nokey" so a recorded clip shows without the skeleton's colour key; the
window does the same.

demo/camgifs.py makes the recorded clips from a recorder session: each
part's right-hand (or both-hands) step, the two side fisheyes redrawn as a
plain view from between the eyes using the session's calibration.json,
denoised so the GIFs compress (10-15 MB a clip without it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 10:15:43 -06:00
DeeJanuzandClaude Opus 5.5 672d186faf ft-camd: read every side-camera frame through the ISP, tell dark from bright by its pixels
Without the colour module the side cameras come through the ISP and their
near-black exposures are all zeros. ft-camd learned once which V4L2 indices
carry them and never read those indices again. Measured 2026-10-13 with the
headset worn, that split moves every few seconds: bright frames landing on a
skipped index were dropped, and find_fresh published them at the next dequeue
under its timestamp, 8 ms late. The side cameras matched the upper ones in
only ~55-60% of sets and live tracking fell from ~28 to 10-18 sets/s with 2-3x
the stereo error.

A camera bound by VIDIOC_QUERYBUF now maps every index to its own buffer and
judges each frame by its pixels, like the upper cameras; a repeated all-zero
frame counts as dark, never as a reason to grab another buffer. Live: 30.0
matched sets/s, offsets 0.3 ms, tracker 27.2 sets/s, 1.5 mm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 08:19:36 -06:00
DeeJanuzandClaude Opus 5.5 6d74ea2ab3 hands/rec: pause Frametop's drawn hands and hand pointer during a session
The hand overlay covered what the person watches, and the pointer turned the steps' pinches into
clicks and opened Steam's menu. A session stops the running ones after the camera check and starts
them again when it ends; a list in the run dir lets the window or the next session start them if
the recorder was killed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 21:50:04 -06:00
DeeJanuzandClaude Opus 5.5 4ef4f5d5ba hands: recover from moved cameras, stop a session that records nothing
- ft-camd exits when a mono camera goes silent for 3 s while the others
  run (XRService moved it), so its service starts it on the new devices
- a step whose recording exits, lacks the side pair or writes no set for
  3 s waits for the camera check (with repair, up to 120 s) and goes
  again; it fails the session if they don't come back or after 3 losses
- the session's preflight repairs an ft-camd left on moved cameras

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 17:19:57 -06:00
DeeJanuzandClaude Opus 5.5 2b79093086 hands/rec: catch an ft-camd left on moved cameras, refuse recordings without the side pair
At 08:10 the colour module disconnected and XRService moved the side
cameras from video9/13 to video0/3. ft-camd, started the day before, kept
publishing the old devices; ft-hands named cameras by the new log and left
both side cameras out, so a full v2 session recorded only the upper pair.
The camera check counted 4 cameras and said ok.

- camcheck: ft-camd's devices must be the ones XRService runs now
- camera_check(repair): also restarts the live frametop-camd (then
  frametop-hands, which names cameras when it starts)
- a part whose first set has no slam_left/slam_right stops the session

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 17:08:14 -06:00
DeeJanuzandClaude Opus 5.5 d70c99dd7e Hand recorder: v2 script with demo clips on the panel and in the window
script-v2.json has a step per part of demo/parts.json, each playing that
part's GIF from hands/rec/demos: one-hand parts run left (the clip
flipped), right, then both. About 12 min recorded; the quick round is
hand size, index taps, palm up and no hands. ft-handrec --script and
session.py --script pick it; script.json stays v1 for now.

ft-handpanel: "demo <path> [mirror] | restart | off" plays a GIF in a
16-degree left column with a key under it (light: palm, dark: back of
hand), the text beside it left-aligned. Frames are decoded one at a time
with stb_image's GIF decoder, so a clip holds three frames in memory, and
each frame redraws and copies only the clip's rectangle. The session
restarts the clip when a hold begins; prompt events carry "demo" and
session.json the script's name. The window plays the same clip
(AnimatedImage) with the same key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 16:29:58 -06:00
DeeJanuzandClaude Opus 5.5 119b248063 Hand demo: instructions on a headset panel during takes, Steam's menu closed
The demo recorder keeps the part and its motions on ft-handpanel, fixed to
the head and raised above the recorded headset view (new --up and --width
options); gifs.py crops off the strip where it dips in. SteamVR opens
Steam's menu on the same side button, so the app closes it after each press
and as a take starts. 2a and 3a say to look down at the low hand, and the
spoken-number check takes "to a" for 2a.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 15:03:38 -06:00
DeeJanuzandClaude Opus 5.5 fabee2b1fe Hand demo README: 15 s trims for 2b, 7a and 11a
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 14:45:17 -06:00
DeeJanuz fccccbffc6 docs: the Mac kit's release, macos-host-1 2026-10-12 09:42:08 -06:00
DeeJanuz 188f107cfc host/macos: Frametop Streams, a menu bar icon that turns the displays on and off
Frametop Streams lists the Mac's displays (its Sunshine instances) and turns
each one, or all of them, on or off. ft-sunshine off|on|status does the same
in Terminal. Off disables the instance's LaunchAgent, so it stays off through
logins until on. The setup compiles the app from Frametop Streams.applescript
(AppleScriptObjC, no compiler) and starts it at login; --undo removes it.

README.md is the Mac setup guide, also the notes of the kit's release.
2026-10-12 09:38:24 -06:00
DeeJanuzandClaude Opus 5.5 db033b238d Hand demo parts: 7a, 7b and 11a fit about 15 s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 08:43:33 -06:00
DeeJanuzandClaude Opus 5.5 d6d27716e3 Hand recorder: demo clip recorder for the v2 script's GIFs
hands/rec/demo: ft-handdemo (GTK 4) walks parts.json, one take per part from
the headset's right-side button, recording the headset view (Room View) with
vr-record while panels hide, hand tracking parks and gaze is off. sheets.py
makes contact sheets and checks the spoken part number; gifs.py turns the
hand-picked trims into one GIF per part.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 08:40:36 -06:00
DeeJanuzandClaude Opus 5.5 80bce4cf66 Gaze + hands: the two-hand drag works like Meta+J/K; held pinches no longer drop on a clock race; easier lazy susan
User 2026-10-11, the second gaze test:
- "hand tracking stopped" ends were an unsigned age: ft-hands publishing just after the
  loop's tnow made it negative, wrapped to 584 years, and ended held pinches, nudges,
  drags and scrolls. Signed now.
- The two-hand drag mirrors the keys: hold one pinch (aim, nudge), pinch with the other:
  the left button goes down where the dot is (as Meta+K with Meta+J held); the drag
  lasts while either pinch holds, and the hand still pinching drags. A second pinch
  during a drag joins it.
- The fast-hand filter refused dozens of still pinches (frame-to-frame palm speed is
  noisy): smoothed, 1.0 m/s.
- A three-finger scroll goes on when ft-hands swaps which finger it calls pinched.
- Lazy susan: counted strokes came at 25-30 cm in 230-470 ms, at both limits: 22 cm,
  quick somewhere along it (0.7 m/s peak) within 0.9 s; looser hand shape. The flags
  replayed: 2 strokes in 45 flags of other use.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 18:13:38 -06:00
DeeJanuzandClaude Opus 5.5 0ce6843338 Front slot: a brought screen stays until you move it
User 2026-10-11: "the lazy susan can be considered to be in use and remain active until I
move it out of its spot manually through either the eye tracking or grabbing it with
hand-tracking". Looking away no longer sends it home (SCREEN_FRONT_AWAY=1 brings that
back, with the keep-by-use); a gaze-pinch drag, a hand grab, a push or grab that
releases it, and the next stroke sends it home.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 17:17:56 -06:00
DeeJanuzandClaude Opus 5.5 b67c1931c6 ft-hands: settings for how easily a pinch lets go
HANDS_PINCH_END, HANDS_PINCH_DRAG_OPEN, HANDS_PINCH_DRAG_OPEN_S, HANDS_GRIP_TAKEOVER_S
(user 2026-10-11, gaze + hands: pinches released at 4-6 cm, and grips took pinches
130 ms in, while the fingers were still together).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 17:11:24 -06:00
DeeJanuzandClaude Opus 5.5 0b72710474 Gaze + hands: two-hand drag (hold, tap the other), pinches held through tracking pauses, no clicks from fists or strokes, the pointer hides while typing; the slot keeps only on real use
The user's 2026-10-11 test of gaze + hands:
- Two-hand drag as they meant it: hold one hand's pinch (nudge it into place), tap
  with the other: index presses the left button where the pointer is, middle the
  right; the first hand drags (POINTER_GAZE_TWO_HAND). The tap-first right-drag is
  off by default (it could catch a tap followed by a nudge).
- 9 held pinches ended as "hand tracking stopped (1.5 s)" while ft-hands still held
  them: 4 s with nothing pressed, 2.5 s with a press, and the line now says the file's
  seq and ages to find the cause.
- A gaze pinch held back ends without a click when the hand closes into a fist
  (ft-hands' grip may not take it past 0.1 s now); a pinch begun while the palm
  moves faster than 0.6 m/s (a stroke) doesn't click (POINTER_PINCH_MAX_SPEED).
- Three-finger scroll: 3.5 cm and 0.4 s to join.
- Gaze mode hides the dot and collapses its laser for 1.5 s after each key
  (POINTER_TYPING_HIDE): it sat big and bright on the text being typed.
- The front slot's keep counts clicks, scrolls, drags and keys, not the gaze pointer
  passing over it (every brought screen was kept 3 s in).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 17:11:24 -06:00
DeeJanuzandClaude Opus 5.5 02f1575c52 Gaze + hands first: right-drag by two taps, three-finger scroll, fist guard on every pinch; the slot lets go to manual controls; palm-only susan; dot-only hand laser
User 2026-10-11, gaze + hands becoming the main input:
- Right-drag: an index tap on one hand, then an index pinch on the other within 1 s,
  holds the right button at the gaze lock; that hand drags until it ends
  (POINTER_GAZE_RIGHT_DRAG). It replaces the chord (POINTER_GAZE_CHORD=0).
- Three-finger scroll: the thumb on both the index and middle tips (3 cm) scrolls where
  you looked as the hand moves, like the ray's middle-pinch stick (POINTER_GAZE_SCROLL).
- The fist guard (a hand closing into a fist: no click) now covers gaze and chord
  pinches too, from each hand's own frame (not the ray's).
- A hand's laser shows only its dot: the beam starts just short of it, as the eye's
  does, held still through a carry (POINTER_RAY_BEAM=0; SteamVR's beam width is one
  global setting it reads only at start).
- The front slot gives a screen up to manual controls: grab that, a push, flick or
  throw, or a carry by hand or laser releases it (it moves like any other and stays
  where you put it); the next stroke puts it home and brings the next.
- The lazy susan counts only palm-led strokes (the return stroke does nothing; the
  other hand palms the other way; HANDS_SWEEP_BACK=1 for both).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 16:38:29 -06:00
DeeJanuzandClaude Opus 5.5 90114ed043 The front slot: one place in front of you for the lazy susan and grab that
The user's proposals (2026-10-11): the lazy susan and grab that were two systems that
fought over a screen (grab that took one the susan brought: 2.3 m wide at 1.5 m).
Now one front slot, one screen at a time (the one there goes home first):
- reading distance (the lazy susan, 1 m) and arm's reach (grab that), both readable
  (ReadableSize, the same view at either); grab that at the one there pulls it closer;
- a push, flick or throw steps it back: arm's reach -> reading -> home;
- one home per screen: every dismissal returns it there; moved by hand or laser it
  lives where you put it; resized in the slot it keeps that view next time;
- turned away from it goes home, unless used 3 s (kept; SCREEN_FRONT_KEEP_MS);
- a strip of the screens' names, left to right as they live, for 2.5 s after each
  stroke, the one in the slot lit and the next each way marked (keyboard.cpp's font,
  now DrawLabel for other panels too);
- SCREEN_UI_SCALE for a remote display's own UI scale (a Mac's Retina: 2);
- the reset button needs a 0.5 s hold, laser or finger (a stray poke reset the layout;
  HANDS_RESET_HOLD_MS).
grab that's remembered widths, send-away widths and view fit go (the slot sizes it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 16:15:58 -06:00
DeeJanuzandClaude Opus 5.5 12b8159d4e Lazy susan: readable at 1 m, cycles every screen; the laser only for pinching, none in a fist
Lazy susan (the third live test): a brought screen comes 1 m ahead, as big as its
resolution needs for text to read: its logical pixels (KWin's scale undone, now passed
to vr.cpp) at 26 px/deg, at most 100x55 deg keeping its shape, at least 40 deg wide,
curved round you past 60 deg (grabthat::ReadableSize; SCREEN_SPIN_DISTANCE, _PPD,
_MAX_DEG, _MAX_TALL_DEG). Its curve comes back on the way home. The strokes cycled
104, 1, 104 with three screens up: a screen still flying home read as straight ahead;
each one is now taken where it lives (home, or where it's going).

Accidental clicks: most were pinches with no laser up pressing where the pointer was
last left ("no ray up: a press where the pointer is", a dozen in two minutes). With
gaze off they now only wake the pointer (POINTER_PINCH_NO_RAY=1: the old air mouse).
The hand's laser shows only with the thumb and index within 6 cm (gone past 10;
POINTER_RAY_READY), and a fist drops it: fh_ray's "ready" and "open" tests, the fist
read as the index and the other three both curled under 1.1 (FistCurl; measured on 47k
flagged hands: the other three alone read as a fist in a fifth of the pinches). A ray
pinch made while the hand closes into a fist doesn't click. Input Settings switches for
all three (POINTER_ ones reload the helper).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 16:06:15 -06:00
DeeJanuzandClaude Opus 5.5 a546469db6 Lazy susan brings the next screen to you; easier sweeps; grab that fits wide screens to the view
The lazy susan (the sweep, Meta+Alt+Tab) no longer turns the room: the next screen
round, by where each one lives, comes in front of you at a distance it spans at most
60 deg of the view at, and takes the typing. The next stroke sends it home and brings
the one after; pushed, flicked or thrown it goes home; turned away from for 0.6 s it
goes home; moved by hand or laser it stays. SCREEN_SPIN_BRING=0 turns the room again
(Input Settings switch too).

Sweeps were hard to make (counted strokes came at 30-35 cm, just over the 30 asked):
25 cm in 0.5 s, the hand open 1.4, tilted up to ~45 deg off its edge, and hovering near
a screen counts (the brought one sits right there). The flags replayed: one stroke in
49 flags of other use.

Grab that brought a remote display back at the 1.62 m it was resized to, 0.45 m ahead:
it filled the view and every poke went through it (both flags of the second live test).
A wide one now comes as far out as it spans at most 75 deg (HANDS_GRAB_THAT_VIEW_DEG).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 15:01:57 -06:00
DeeJanuzandClaude Opus 5.5 978929ef8c ft-layout: a desktop start with the headset off still sends KWin's scales
Starting the desktop with the headset off failed to arrange the screens (no head
pose) and returned before telling ft-screens KWin's scales. With the native screen
at 125%, every laser and tap there landed at 1.25x its distance from the top-left
corner, hundreds of pixels off mid-screen. Arranging that fails at start is logged
and the scales are sent anyway.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 13:33:33 -06:00
DeeJanuzandClaude Opus 5.5 6164766efa Input Settings: switch every hand interaction on or off, live
User, 2026-10-11: "make every interaction able to be enabled or disabled".
The Hands page gets a "Hand interactions" section: 24 switches in four
groups (tapping, moving screens, gestures, feedback), each writing its
frametop.conf key and telling ft-screens at once ("handsetting KEY 0|1",
SetHandSetting; number-valued ones go back to their defaults when switched
on). They follow the direct touch switch above.

The command is checked before the helper's "hands L R allowed" word: that
pattern matched "handsetting X 0" too and scrambled the hands word.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 12:02:28 -06:00
DeeJanuzandClaude Opus 5.5 cb109db6ac ft-screens: name the hand spin in the event switch (no -Wswitch warning)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 11:30:23 -06:00
DeeJanuzandClaude Opus 5.5 802779cae7 Hands: the lazy susan by hand: sweep an open hand on its edge sideways
User, 2026-10-11: "paw with a mostly horizontal hand back and forth like
pushing branches out of the way, left or right, and lazy susan through
windows and displays"; decided: one panel per stroke; the palm or the back
of the hand leading, never a flat hand; every stroke counts, but a large one.

An open hand on its edge (fingers open, the palm's normal within 0.55 of
level and along the motion), away from every panel, 18 cm or more in front
of the eyes, from 50 cm under them to 15 over, sweeping 30 cm sideways
within 0.6 s, drifting at most 15 cm: Event::Spin -> the spin's next (swept
left: the panel on the right comes) or prev. Not while typing, pressing,
holding, pinching or arming grab that. HANDS_SWEEP.

Tests: 40 cm in 0.4 s either way spins once; flat, slow (1.5 s), short
(15 cm) don't; back and forth spins each stroke. Flag replays: no strokes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 11:29:01 -06:00
DeeJanuzandClaude Opus 5.5 114c22e90b Hands: taps aim along the fingertip's path; pushed through at a frozen aim, a tap
From the 2026-10-11 11:00 live test:
- The finger's line overshot on the native screens: the screen sits low,
  the hand comes up steeply, and the line from a tip a few cm out met the
  screen 2-4 cm ahead of the drawn fingertip (the flags' clips show the dot
  there). The aim is now the tip's path: where it's heading as it comes in,
  carried on to the surface, at most 1.2 times its distance off the tip's
  own point; still or slow, the tip's own point (HANDS_TAP_AIM=path|finger|
  straight).
- Slow deliberate pushes on the remote displays were refused (too slow,
  reaching through): once the aim has frozen on the way in, a pointing
  finger pushed 1 cm through the panel (on its way in: within 5 cm, 10
  frames) taps at the aim, whatever its speed or angle (HANDS_LOCK_PUSH).
- A hand at a corner's zone shows the corner's glow before the tap dot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 11:17:42 -06:00
DeeJanuzandClaude Opus 5.5 1202029d43 Hands: taps land where the finger points; the bar row clears grown buttons; no pull glow under a laser
From the 2026-10-11 10:49 live test:
- Taps were offset from where the user aimed, most at the edges: the tip's
  own point (straight in from it) sits short of where the finger points when
  it comes in at 30-50 degrees, by the tip's distance times that angle's
  tangent (about 1.3 cm with the aim locked 1.5 cm out). The aim, the dot,
  the cursor and the press now use the line from the index's middle joint
  through its tip, met with the panel (at most 4 cm off; HANDS_FINGER_RAY).
- With a hand near, the grown buttons overlapped the screen: the bar's row
  sits below the screen by the taller of the bar and a button.
- The "grab that" glow doesn't show on a panel a laser is on (the gesture
  still works there).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 10:59:36 -06:00
DeeJanuzandClaude Opus 5.5 624dc73099 Hands: let go of a panel without nudging it
User, 2026-10-11: after arranging a window it's almost impossible to keep it
exactly where it was: the hand moves a little as the fingers (or the whole
hand) let go. Only the let-go is treated differently, so carrying has no
added smoothing or latency:
- The panel stops following once the fingers open 8 mm past their tightest
  this hold (a fist: its curl 0.3), or three times the reading's own wobble,
  on two frames running, and goes back to where it was 70 ms before the
  opening first showed; closed again, it follows on from there (the carry
  or the two hands' stretch starts afresh). HANDS_RELEASE_FREEZE.
- A slow let-go the freeze didn't catch: back to where it was 120 ms before
  (Event::Settle; HANDS_RELEASE_REWIND_MS). Throws are left alone.
- The same hand doesn't take the panel it let go of again within 250 ms.
Test: a let-go with the hand sagging 2 cm leaves the panel 1.3 mm from where
it was held (14.7 without). Flag replays: 2 pinch freezes, 2 fist ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 10:48:18 -06:00
DeeJanuzandClaude Opus 5.5 f93b0e6c40 Hands: a fingertip dot, the tap's aim locked on the way in, presses by motion, bigger buttons for fingers
Tapping, after the 2026-10-11 10:10 live test:
- A soft white dot on the panel where a tap would land (Guide::Touch,
  HANDS_TOUCH_DOT): smaller and brighter as the fingertip comes in, lit with
  a ring while pressed; it shows with the cutouts off.
- The aim locks 1.5 cm out (HANDS_TAP_LOCK): the press lands where the tip
  was as it came within lockOut, not where its jitter or slide put it on
  crossing; the cursor holds there too.
- A press by motion (HANDS_MOTION_PRESS): a tip that came in at 0.25 m/s or
  more, 3 cm or more, and stopped or turned back within 1.5 cm of the surface
  presses there (the depth reads short of the touch).
- A hand at a panel makes its round buttons at least 2.4 cm across
  (HANDS_BUTTON_SIZE), and they take a fingertip or pinch 2.5 cm round
  (HANDS_BUTTON_REACH, was 1.5).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 10:31:17 -06:00
DeeJanuzandClaude Opus 5.5 6d5dfeef6c Hands: a tap clicks where it went down; two-finger scroll survives a swipe in the air
From the 2026-10-11 10:10 live test: pokes went down at one spot and up
10-30 cm of pixels away (the tip slides down the panel as the finger curls
back off it), so apps saw a drag. A press doesn't drag in its first 250 ms
(HANDS_TAP_MS). Two-finger scrolls started three times and ended at once:
a swipe in the air drifts off the surface; it now ends only 5 cm off, the
fingers 10 cm apart, or not two fingers for 6 frames.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 10:22:00 -06:00
DeeJanuzandClaude Opus 5.5 95d2c696ab Hands: two-fist resize by shape, two-finger scroll, no stuck presses, ray hidden near panels, quieter glows
From the 2026-10-11 09:43 live test:
- Two fists anywhere near one panel (palms 30 cm in front to 15 behind, 30 cm
  round it) resize it by their shape alone (HANDS_FIST_PAIR): ft-hands' grip
  only begins on a hand seen open just before, at the panel.
- Two fingers (index and middle straight, together, level; ring and little
  curled) touching the content: a swipe scrolls (a notch per 1.2 cm, the
  content following), a lift unmoved clicks, held still they act as a poke
  (HANDS_TWO_FINGER_SCROLL).
- Stuck presses: a press isn't held through a tracking loss (only grabs are);
  a poke lets go as the index curls; a pinch-click as the tips are seen 4.5 cm
  apart; either held still 1.5 s (HANDS_PRESS_STILL_MS).
- The hand ray hides within 22 cm in front of a panel and for 0.8 s after
  (HANDS_RAY_HIDE_REACH); the pointer helper ignores a ray-less pinch there
  without the gaze (it woke the laser).
- The push/flick hint glow is off (HANDS_PUSH_GLOW): it covered near panels
  the palm faced while clicking.
- Grab that gives panels that look small up to 10 deg more aim margin
  (HANDS_GRAB_THAT_SMALL).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 10:09:23 -06:00
DeeJanuzandClaude Opus 5.5 1521420964 Hands: fists resize only, easier throws, natural grab that, curve that fits, no laser while touching
From the 2026-10-11 09:25 live test:
- A fist only resizes (HANDS_FIST_RESIZE_ONLY, default on): one fist holds the
  panel still as an anchor; two hands with a fist among them scale it about
  its centre, no move or turn. Pinches still carry and turn.
- Throws need 0.55 m/s (was 1.0): the user's releases were 0.62-0.96 m/s.
- Grab that brings a panel back at the width it had when it was last sent
  away from arm's reach (g_nearWidth), not grab that's maxWidth.
- A natural reach arms grab that: palmArm 0.2 (was 0.45), aimFacing 80 deg
  (was 55), aim margin 10 deg (was 6). Flag replays: 11 fires (was 8).
- Curve: a curved screen's radius follows its distance from the head after
  every move, and it bends at most SCREEN_CURVE_MAX_DEG (100) round: one
  curved up close and thrown 3 m out at full width had wrapped into a
  cylinder.
- The pointer helper releases its laser while a hand touches a panel
  (ft-screens' near claim): the laser from the head to the fingertip's
  cursor got in the way and held the button, refusing pokes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 09:42:30 -06:00
DeeJanuzandClaude Opus 5.5 c5e0c4f529 hands: fist guard on the pinch (HANDS_PINCH_FIST_CURL, 1.2)
No pinch begins while the index and middle are both curled (tip-to-wrist
under fist_curl times knuckle-to-wrist, Grip's curl measure), and a close
held back so has to open past end_m before one can begin. A pinch already
down carries on. A fist puts the thumb tip on the curled index, and live
ft-hands read 96% of fist frames in the flags as pinched.

1.2 rather than the flag analysis' 1.3: the model's world landmarks read
pinching fingers more curled. Replays (student v11c) against the tap
labels: clear non-fist pinches lost 2 of 204 at 1.2 (4 at 1.3), labelled
fists read as pinches 8 -> 5.

ft-handreplay: --pinch-fist-curl, the guard's count in the summary, the
finger curls in the timeline. The flag manifest's settings gain
pinch_dip and pinch_fist_curl.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 08:56:40 -06:00
DeeJanuzandClaude Opus 5.5 516f2c056d Grab that: take the panel the palm's line passes just under
Fifth live test (2026-10-10 22:55): grab that brought the desktop in, it was
carried and thrown 3 m out, then five gestures at it or the remote displays
logged "no panel there". The open palm is held out below the line of sight,
so the line from the eyes through it runs 12-15 deg under where the head
points (the user's flag 150115). Since the fourth live test the line had to
meet a panel exactly, and a thrown 1.35 m tall desktop 3 m out is only
12.7 deg each way, so the line passed just under it. One of the flag's two
fires misses such a panel that way.

Pick now takes the panel the line meets (unchanged, nearest wins), else the
one whose outline it passes nearest within HANDS_GRAB_THAT_MARGIN_DEG
(6 deg seen from the eyes; 0 = the old rule). The gesture itself is
unchanged, so it stays as hard to trigger, and held, pinned, pressed and
near panels are still never taken. "no panel there" now logs where the line
went relative to the head and the nearest panel it may take, with its angle.

Test: TestGrabThatAfterThrow runs the user's sequence with synthetic hands:
grab that brings the desktop in, a bar carry is thrown out and up at
1.3 m/s, then grab that at it again (missed by 0.8 deg with the old rule,
taken now), a remote display after that, precision cases, and the flag's
two fires (2 of 2 now, 1 with the old rule).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 23:24:02 -06:00
DeeJanuzandClaude Opus 5.5 1c10e9a717 Docs and settings: two anchors, fist reach, buttons for hands, the soft glows, grab that's targets
The example config gets HANDS_FIST_REACH, HANDS_JOIN_REACH, HANDS_BUTTON_REACH,
HANDS_PINCH_BUTTONS, HANDS_EDGE_GLOW, HANDS_GRAB_THAT_FROM, HANDS_GRAB_THAT_MARGIN and
HANDS_GRAB_THAT_FACING; hands/README.md and docs/reference.md describe them, the white
halo, the corner, edge and button glows, and that near panels go away by push, flick or
throw now, not by grab that. `handinput state` counts joins, pinches that waited to be
fists, and buttons pinched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 22:52:57 -06:00
DeeJanuzandClaude Opus 5.5 b905a63345 ft-screens: a soft white halo, glows at corners, edges and buttons, grab that's targets
The fourth live test: "The glow is too powerful. It should be a white glow and far more
subtle. It should only be around the outside of the window." And for resizing, "almost
like a cutout of the soft glow ... just around the edges and corners".

- The target glow (grab that, and dimmer a push or flick) is a white halo outside the
  panel's edges, about 1.3 degrees wide, at most half opaque, clear over the content,
  in the panel's plane after it (frametop.guide.target).
- Each hand's guide (handinput's Guide) as the same halo: an L round the corner a pinch
  would resize from, a segment along the edge it would move by, a ring round a button;
  brighter closer, lit while held (frametop.guide.hand.left/right). Shown with the
  cutouts off. With HANDS_EDGE_GLOW (default) the resize handle no longer follows hands.
- softglow.h: the textures as pure code, tested.
- Grab that takes only panels shown, unpinned, not held by a laser or a hand, not pressed,
  and (grabthat's nearest) farther than 0.8 m; a fist or pinch waits on it only while it
  aims at one of those; a send-away quiets it for 1 s; its claim likewise.
- Settings: HANDS_JOIN_REACH, HANDS_FIST_REACH, HANDS_BUTTON_REACH, HANDS_PINCH_BUTTONS,
  HANDS_EDGE_GLOW, HANDS_GRAB_THAT_FROM, HANDS_GRAB_THAT_MARGIN, HANDS_GRAB_THAT_FACING.
  The log names a pressed control.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 22:50:08 -06:00
DeeJanuzandClaude Opus 5.5 5fb194a01f Hand input after the fourth live test: two anchors, fists, buttons, a stricter grab that
Two fists (flags 215945 and 215955, the live log): the right hand's fist began as a
pinch with the thumb on the index while the other fingers were still closing, waited
0.6 s on "grab that" (armed by the open hand held out to the near panel), then clicked
the content and held the click 9 s, so the left fist's hold never got a second anchor.

- A second hand at a panel the other holds (15 cm in front, 12 behind, 10 round) joins
  it with a pinch or fist anywhere on it: the stretch (move, scale, turn). No click,
  poke, push or flick on a held panel (HANDS_JOIN_REACH).
- A pinch on the content by a closing hand waits up to 150 ms to become a fist; a wait
  on grab that ends as a join, a fist or a pinch, as the hand is then.
- Fists reach 11 cm in front and 10 behind; a curled hand is claimed that far
  (HANDS_FIST_REACH).
- Controls: the nearest wins (the bar took the curve button's pokes), round buttons get
  a 1.5 cm hit area, a pinch presses them (HANDS_BUTTON_REACH, HANDS_PINCH_BUTTONS); the
  log names the control.
- Guides: per hand, what its soft glow shows (corner, edge, button; lit while held).
- A carried panel turns at most 6 deg a tick about the hand's point.
- Grab that: the line through the palm has to meet the panel (no margin, no head cone),
  panels within 0.8 m aren't taken, the arming hold faces the aim within 55 deg and is
  still under 0.5 m/s, and a send-away quiets it for 1 s.

Tests: buttons, guides, the fist settle and reach, joins, two-fist flag replays (before:
a click and no two-hand hold; now: 9.4 s of stretch with the panel 4 cm nearer or 8
cm farther), grab that at near and far panels.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 22:42:24 -06:00
DeeJanuzandClaude Opus 5.5 639a761d88 ft-pointer: log the hands feed going quiet, and say so when a ray goes off for it
A side "off" for no hand tracking logged as "off: its controller is in
use" (State() != Hand covered both), which hid the 2026-10-10 flicker
behind controller handoff. Now each change of the feed's liveness logs one
line ("hand tracking: nothing new for 1.5 s: sides off" / "publishing"),
and a ray dropped for it says "off: no hand tracking".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 22:04:49 -06:00
DeeJanuzandClaude Opus 5.5 d1ceb3d744 ft-pointer: a hands frame newer than the loop's clock is fresh, not 584 years old
The loop reads its clock at the top and ft-hands' files later in the pass.
A frame written in between has publish_ns after tnow, and the unsigned
"now - publish_ns" in HandsInRoom::Live wrapped round: the feed read as
stale for that one pass, both sides went "off", and the "hands" word to
ft-screens flickered to "off off" and back. 2026-10-10 20:30-20:37: 24
flickers in 7 minutes, each with ft-hands publishing at full rate (pinches
logged at the same moments), each ending ft-screens' holds and the ray.

feedage.h: AgeNs/Fresh, age 0 for a frame from after "now". Live and the
gestures check that ends holds ("hand tracking stopped") use them.
pointer/tests/feedage-test.cpp replays the loop against 30, 15 and 1 Hz
publishing: the old check calls 28-2408 passes stale, the new one none.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 22:03:15 -06:00
DeeJanuzandClaude Opus 5.5 249f622b1b Palm menu: "at a panel" within 12 cm in front and 8 cm round; flag replays compare the old menu
HandAtPanel's defaults (17.5 and 10 cm) kept the ring away from a palm at chest height under a
panel at arm's reach; 12 and 8 still take a palm up just under a panel's bottom edge (the card
pinch from below). `handinput-test --grabthat` also replays each flag through the palm menu as it
was before the third live test: 9 toggles on the 23 flags (none meant), 0 now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 21:41:26 -06:00
DeeJanuzandClaude Opus 5.5 cad02f978c Docs and settings: push, two-hand turns, tracking gates, the target's glow, send-away widths
hands/README.md (near input, the palm menu), docs/reference.md and session/frametop.conf.example:
HANDS_PUSH, HANDS_PUSH_SPEED, HANDS_STRETCH_TURN, HANDS_TRACK_GATE, HANDS_TARGET_GLOW,
HANDS_SEND_AWAY_WIDTH; fists ft-hands calls pinches, the pinch slack, holds through the helper's
word, the near-the-eyes carry, the stricter palm menu, with the replays' numbers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 21:38:30 -06:00
DeeJanuzandClaude Opus 5.5 65105eeb59 ft-screens: a held panel's turn follows the hand at most at 4 Hz
fh_smooth.h's Params get maxCutoff (0, the default: no limit, as before for the ray and the
pointer helper). With the tracking gate on, a carried panel's turn (the wrist turn, a card's room
turn) is smoothed at most at 4 Hz however fast the hand's frame turns, so a flip the gate takes
after three agreeing frames is followed over about 40 ms instead of in one tick. On the third live
test's flags, carried panels' turn per 90 Hz tick: second difference rms 1.87 -> 1.60 deg, 99th
percentile 6.2 -> 5.2, the centre's 11.5 -> 9.7 mm (hands-throw: 33.3 deg and 159 mm).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 21:36:53 -06:00
DeeJanuzandClaude Opus 5.5 8ae8b8400e ft-screens: the gesture target's glow, send-away widths, holds through the helper's word
- A glow on the panel a gesture under way would take: "grab that" (blue, fading in as the open
  hand held out to it arms, by its own Pick) or a push or flick (warm, dimmer: an open palm close
  in front of it, handinput's throwAims). One overlay, frametop.guide.target, sized and curved to
  the panel, 4 mm in front of it: an edge glow and a faint tint, drawn with cutouts off.
  HANDS_TARGET_GLOW.
- Sent away (thrown, flicked, pushed, or grab that's send-back) a panel keeps its width; one that
  grab that shrank to come to arm's reach and that's still that wide gets its width back
  (HANDS_SEND_AWAY_WIDTH=restore, the default; keep: never). In the third live test the 2.5 m
  desktop came at 0.6 m and was thrown 3 m out at 0.6.
- A hand holding a panel or KWin's button holds on while the pointer helper's word says its
  side is "off" (not a controller's) for up to holdLostMs: the word flickered off 24 times in the
  session's 7 minutes and dropped three holds.
- The palm menu gets "grab that" as busy and whether the hand is at a panel (near input's near,
  or HandAtPanel within 17.5 cm and 10 cm round a panel).
- Settings: HANDS_PUSH, HANDS_PUSH_SPEED, HANDS_STRETCH_TURN, HANDS_TRACK_GATE, HANDS_TARGET_GLOW,
  HANDS_SEND_AWAY_WIDTH; `handinput state` and `palmmenu state` count the new things.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 21:32:18 -06:00
DeeJanuzandClaude Opus 5.5 d0029054ee Hand input after the third live test: steady carries, fists, push, a stricter palm menu
From the 2026-10-10 19:28 session (ten flags, ft-screens' and the helper's logs):

- Tracking gates (Params::gate, HANDS_TRACK_GATE): a held hand's frame that no hand makes
  (faster than 4 m/s, or more than 0.5*100 m/s^2*dt^2 + 2 cm off where its velocity had it) is
  dropped unless three in a row agree; its frame turning faster than 540 deg/s likewise. One
  camera's frames and frames near the edge of view (50-80 deg off the head's forward) are smoothed
  harder and don't turn the panel; past 80 deg the hand counts as unseen (the panel holds). On the
  side-grab flag (203635) the left hand read alternately at two places 10-20 cm apart with its frame
  flipping 100-180 deg.
- CarryPose faces the head from a point between the hand and the panel's centre when the panel is
  held near the eyes by a far point (kCarryShare): facing from the centre had no steady answer
  there and spun 0.6 m panels held by an edge at arm's reach. A centre near the eyes stops turning.
- A pinch by a closed hand (index <= 1.15, the others <= 1.05) is a fist grab, not a pinch click:
  ft-hands called the user's two fists pinches (flag 203215) and the content was clicked.
- Two hands turn a panel on every axis with the line between them and roll it with their wrists
  (StretchTurn, Params::stretchTurn, HANDS_STRETCH_TURN); fists find a panel by its edge too.
- A pinch the touch zone claimed takes the border 3 cm past the band's depth (Params::pinchSlack).
- The push (Params::push, HANDS_PUSH): an open hand, palm to the panel, pushed straight into it
  at 0.5 m/s (5 cm in) or 15 cm in slowly, throws it 3 m out like a flick. A flat or pushing open
  hand doesn't poke. throwAims() says which panel a push or flick would throw.
- The palm menu: facing 45 deg (60 to leave), the palm still, not at a panel (Input::atPanel,
  HandAtPanel) nor for a second after it or after a hold; a pinch with the middle finger in it
  does nothing on the ring.
- "Grab that": Aim() for the target's glow.

Tests: gates (alternating misreads, real moves, a real jump, the edge of view, flipping frames,
one camera), fist pinches and two-fist stretch and turn, StretchTurn, push vs poke, rest, wave and
the back of the hand, pinch slack, the stricter palm menu; replays: --carries (steadiness of
carried panels on the flags, gates on and off), --grabthat with pushes and the palm menu.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 21:28:40 -06:00
DeeJanuzandClaude Opus 5.5 39198fc1b5 ft-screens: a second hand's corner grab doesn't move the handle mid-stretch
A second hand taking a panel the first already holds (a stretch) by a
corner moved the resize handle there; it stays where it is now. And the
controls' comment is back over UpdateControls, UpdateCorner's over it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 19:25:16 -06:00
DeeJanuzandClaude Opus 5.5 f956dd3e52 ft-screens: the resize handle's corner for hands, and late window resizes
- A hand pinching the resize handle after it moved to another corner
  (a laser or the gaze took it there) resized from the bottom right:
  handinput read the tab as that corner always. It takes the corner
  from where the handle is now.
- A floating window's last resize can be answered after the release:
  its opposite corner stays kept for half a second after a resize ends,
  not reset to the top left at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 19:24:19 -06:00
DeeJanuzandClaude Opus 5.5 a54d89ee86 Docs and settings: corner resize, card fingers, holds, flicks and throws
session/frametop.conf.example: HANDS_POKE_TRAVEL=0.017, the card
pinch's fingers, and the new HANDS_HOLD_LOST_MS, HANDS_FLICK,
HANDS_FLICK_SPEED, HANDS_FLICK_OPENING, HANDS_THROW, HANDS_THROW_SPEED,
HANDS_THROW_DISTANCE and POINTER_GAZE_CONTROL_HOLD. scripts/conf-migrate.sh
moves the example's exact HANDS_POKE_TRAVEL=0.025 line (hands-touch,
never released) to 0.017. hands/README.md's near input section,
docs/reference.md's .resize, settings and handinput state, and the
gesture tables at the top of handinput.h and vr.cpp say what each
gesture does now and what wins. The README notes that the hand glows
are drawn into the cutout buffer, so they don't show with the cutouts
off (the default since the drawn hands).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 19:22:39 -06:00
DeeJanuzandClaude Opus 5.5 6c9f86145b handinput tests: remote displays through every hand path
Remote displays (frametop.remote.N, index 101 and up) go through the
same paths as screens: InputPanel lists every visible panel, events and
carries name the panel, StartHandDrag, FinishDrag (no KWin rearrange for
them, as for a laser), "grab that" (targets, the width cap, sending
back), throws, the resize handle and ft-layout's capture all take them.
The test pokes, corner-resizes and flicks a panel numbered 102. The only
gap found was the helper learning a new remote display's controls up to
20 s late; the chrome is announced as it's made now (the corner commit).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 19:22:39 -06:00
DeeJanuzandClaude Opus 5.5 b1b773551c ft-screens: flick a panel away, or throw it from a carry
User, 2026-10-10. Both send the panel 3 m from the eyes
(HANDS_THROW_DISTANCE), facing them, over 400 ms easing out; "grab that"
brings it back from there.

- Flick (HANDS_FLICK): a hand at a panel (its palm within 12 cm in
  front of it or 4 cm behind, over it, and nearly still there: under
  0.6 m/s) flicks out: away from the eyes (within 40 deg) at 1.2 m/s or
  more (HANDS_FLICK_SPEED, a fit over 100 ms), 12 cm or more from there
  within 200 ms, the fingers open (mean extension 1.5 or more) and
  opening on the way by 0.15 (HANDS_FLICK_OPENING; 0 lets an open hand
  pushed out flick too). The panel goes out along the line from the
  eyes through its centre. Not a poke (a pointing hand's fingers read
  about 1.3; an open hand coming through a panel faster than 0.8 m/s
  doesn't poke it), not a wave (the direction), not "grab that" (its
  pull back is toward the eyes). Without the opening rule the
  recordings' probe moves, with a panel 0.3-0.45 m ahead, flicked 6
  times in 11 minutes; with it once. None in the 13 "grab that" flags.
- Card throw (HANDS_THROW): a carry by one hand (a card, a fist, a pinch
  on the border, bar or title; not a resize or two hands) let go moving
  at 1.0 m/s or more (HANDS_THROW_SPEED; a fit over the 100 ms before
  the fingers opened), within 60 deg of away from the eyes: the panel
  goes on along that line to 3 m from the eyes. A slower release leaves
  it where it is. The velocity's track starts afresh when the hand comes
  back from a gap, and a flick doesn't reach back over one.
- vr.cpp animates a throw like a "grab that" move (ease-out), and
  forgets that the panel came by "grab that": the throw is its place
  now, so the gesture brings it back and sends it back there.
- "grab that" finds a panel along the palm's line within 3 deg seen
  from the eyes (or 10 cm), so a 0.6 m panel 3 m out isn't missed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 19:18:21 -06:00
DeeJanuzandClaude Opus 5.5 06cdb2ed8b Resize from any corner, for hands, the gaze and lasers
User, 2026-10-10: Vision Pro-style resize from all four corners. Only the
bottom right worked by laser (the .resize handle), and a resize kept the
screen centred.

- One resize handle per panel still (SteamVR's 128 overlays are tight:
  a third remote display once didn't fit), but it moves to the corner
  being aimed at (vr.cpp UpdateCorner): a laser's ray (a controller's,
  or the pointer helper's device, which the gaze and the hand ray
  drive) landing within a fifth of the screen's height (5-20 cm) of a
  corner, or a hand's pinch at one (handinput's corners()). Its texture
  turns for that corner, it brightens the closer the aim (from the
  controls' idle 0.55 to 1), and it's lit blue while resizing. With no
  aim it lingers 0.4 s, then goes back to the bottom right.
- Any corner resizes and the opposite one stays put: screens and
  remote displays keep their aspect (the corner follows the diagonal,
  ResizeFromCorner, on the cylinder for curved ones: SurfacePose),
  floating windows take the pixels from that corner (ft-floatd's new
  size is placed keeping the opposite corner, keepX/keepY; every corner
  of a window resizes now, the title bar's ends included).
- Near hands: a pinch at any corner resizes the same way (the carry
  now gives the pose as well as the width).
- Gaze pinches (gazehand.h): with the pointer on a screen's resize
  handle or grab bar, the pinch is a press after 0.12 s still
  (POINTER_GAZE_CONTROL_HOLD), not 0.5: nothing to click there, and the
  hand drags the resize. The chrome overlays are announced to the
  helper as they're made, so its ray and the gaze find a new remote
  display's handle at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 19:05:07 -06:00
DeeJanuzandClaude Opus 5.5 c91f4a21f5 ft-screens: a card takes the index and middle, or bunched fingertips
User, 2026-10-10: the card hold (the panel rigidly with the hand) should
start only when the edge is held with at least the index and middle
fingers together against the thumb, or all four fingertips bunched at
it. A plain thumb-index pinch at an edge stays the border's move (or a
corner's resize).

The fingers come from the keypoints (ft-hands' pinchD[1] is the fit's
only): thumb to middle tip within 4.5 cm and index to middle tip within
3.5 cm, or every fingertip within 5 cm of the thumb tip. The straddle
rule (thumb and index tips either side of the plane at the border) is
as before. The middle finger often closes after the index: a border
move begun straddling the edge becomes a card, from where it is, if the
fingers join within 300 ms. The green glow shows only for the card's
fingers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 18:57:21 -06:00
DeeJanuzandClaude Opus 5.5 63c9aafff2 ft-screens: a hand holds through tracking loss
Losing the hand for 250 ms (or ft-hands ending its pinch as lost) dropped
whatever it held. Now a pinch, card or fist grab, and a poke's or a
pinch's press in KWin, last until a clear release: the hand seen with
its gesture up and its fingers open (thumb to index tip over 3.5 cm; a
fist's fingers over 1.35 extended) on 2 hands frames in a row, or the
gesture up for 6 frames whatever the fingers say. A pinch that
flickers up for a frame or two in fast motion, or that ft-hands ended
as lost while the hand comes back still pinched, holds on. Unseen for
1.75 s (HANDS_HOLD_LOST_MS), it ends where it is.

While unseen (or on a frame whose point jumped more than 12 cm, up to
2 in a row: a glitch), the carried point coasts on the hand's last
velocity (a fit over 110 ms), slowing to a stop over 150 ms. When the
hand is back, the smoothing restarts there moving at the gap's average
velocity (fh_smooth Point::Seed, new) and the panel blends from the
coast to it (smoothstep over 100 ms, longer for more than 0.6 m/s on
average). The raw track starts afresh, so a throw's release velocity
never sees the gap.

Synthetic carries at 0.6 m/s losing the hand for 3, 6 and 10 frames:
held, the panel's largest step 12-17 mm a tick (6.7 moving; 13-24 with
3 mm of noise), back under the hand after. Two glitch frames 30 cm off:
11 mm. Release now comes 2 frames (67 ms) after the fingers open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 18:55:27 -06:00
DeeJanuzandClaude Opus 5.5 2711c8850c ft-screens: pokes that the second live test refused
The second live test (2026-10-10 18:20) refused 39 of 50 pokes. Fixes:

- "another fingertip nearer the panel than the index" (14): the replays
  show the tracker reading a pointing hand's middle finger nearly as
  straight as the index (1.65-1.75 against 1.7-1.8) with its tip -7 to
  +4 mm from the index tip's depth at 20-30 deg. The other tips may now
  be up to 6 mm deeper than the index (it had to be 5 mm nearer). Made-up
  pokes along the finger in the replays press 19 of 23 (probe-moves, 3
  before), 31 of 55 (lit, 18), 4 of 6 (2026-09-29, 1); a flat hand with
  the middle tip 1.2 cm deeper still doesn't press.
- "off the content" (25): most were the index crossing the plane below
  the panel as the hand reached for the bar (each was followed by a bar
  grab). Those aren't poke attempts any more (counted as offContent and
  logged once as "not a poke"); a tap within 1.5 cm past the content's
  edge presses at the edge (the desktop's panel is on the bottom edge).
- "past the surface for 1 frame" (5; 1.7 and 2.0 cm in on the content):
  a one-frame press needs 1.7 cm of travel (2.5 before); under 2.5 cm
  the tip must come in on each of the last 3 frames. A finger held 1.5
  cm out with 6 mm of noise presses 4 a minute (2 with the old rule, 0
  with 3 mm of noise), at 2.5 cm none.
- Refusal logs say where the tip crossed and, for "not nearest", which
  tip, how deep, and the fingers' extensions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 18:45:41 -06:00
DeeJanuzandClaude Opus 5.5 a4f21a305e ft-screens: a pinch anywhere in the touch zone's depth by the border grabs
The border band reached 4 cm in front of a panel, the touch zone 7.5: a
pinch 5-7.5 cm out by an edge was claimed (the helper left it) but took
nothing. The band's depth is now the zone's (at least 4 cm).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 18:13:47 -06:00
DeeJanuzandClaude Opus 5.5 9972d53fbc Docs and settings: the 3-inch touch zone, pokes, pinch, card and fist grabs
session/frametop.conf.example: HANDS_NEAR_REACH=0.075, the new
HANDS_POKE_TRAVEL, HANDS_GRAB_BAND, HANDS_PINCH_CLICK, HANDS_CARD_PINCH and
HANDS_FIST_GRAB. scripts/conf-migrate.sh moves the example's exact 0.30
line (hands-reach, never released) to 0.075. hands/README.md's near input
section, docs/reference.md's settings and handinput state, and the
gesture table at the top of handinput.h and vr.cpp say what each gesture
does near a panel and what wins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 18:12:07 -06:00
DeeJanuzandClaude Opus 5.5 99da5e8942 Hands: the touch zone's margin hides the ray but leaves pinches to the helper
The near report to the pointer helper ("near <ns> <L> <R>") was one flag
for two things: the hand's ray hides, and its pinches and grips are
ft-screens'. With the 0.075 m zone, its 2.5 cm leave margin and 200 ms
linger (there so the ray doesn't flicker at the edge) would still have
swallowed pinches made just outside the zone, the live test's complaint.

Now ft-screens says 1 when the hand is within the zone itself (or
pressing, grabbing, or waiting on "grab that"): its gestures are ours; 2
in the margin: the ray stays hidden, the gestures are the helper's (ray or
gaze); 0 otherwise. The helper takes 1 as the claim and 1 or 2 as near for
the ray; an older helper takes 2 as 1, as before. ft-screens' own pinch
and fist begins need the zone itself too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 18:09:00 -06:00
DeeJanuzandClaude Opus 5.5 03fc7eac40 ft-screens: "grab that" at a display near you sends it back or centres it
In the live test of 2026-10-10 "grab that" fired three times, each
bringing another remote display to arm's reach (they stacked up in one
spot), and never sent one back: a panel had to be within 15 cm of where
it came to go back.

Now (grabthat::Decide): at a panel that came by the gesture and is within
arm's reach (0.45 + 0.35 m of the eyes), wherever it was moved about
there, it goes back where it was; at a panel within arm's reach that
didn't come by it, it centres it at arm's reach (and the gesture again
sends it back); a panel farther away comes as before. One at a time: a
panel that came before and is still where it came goes back as another
one comes.

The touch zone and the fist grab don't take the gesture's hand any more
(the previous commit: a fist or pinch on a hand the gesture has waits on
it). The user's flag replayed through hand input and the detector, with a
panel 0.35-0.45 m ahead where the gesture brings one, still fires twice,
with no press or grab.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 18:06:10 -06:00
DeeJanuzandClaude Opus 5.5 b3a26004a8 ft-screens: hand touch within 3 inches, reliable pokes, pinch and fist grabs
From the live test of 2026-10-10 (handinput.h has the rules and numbers):

- The touch zone (HANDS_NEAR_REACH) is 0.075 m (was 0.30: "1 foot is way
  too far, it should be closer to 3 inches"). A hand stays near until
  2.5 cm farther out, then 200 ms; a hand resting low by the body is near
  only within 4 cm. Beyond the zone a pinch is the ray's or the gaze's.
  ft-hands is asked for 30 Hz while a hand is within 0.30 m of a panel, so
  a tap from outside the zone isn't seen at a still hand's 15 Hz.
- Pokes: a decisive tap (2.5 cm in on average over the last 300 ms, on its
  way in on the frame before too, 0.10 m/s or faster) presses on its first
  frame past the surface; others still need two. The finger's angle is
  taken knuckle to tip (the 2 cm last bone turned 15-20 degrees with a few
  mm of noise), the index counts as straight from 1.5 (was 1.6), a new
  press needs the tip back 1 cm out (a noisy pull-back pressed twice), and
  a finger past the surface more than 5 frames or 4 cm deep is reaching
  through. On noisy synthetic taps (3-6 mm of hand noise) 50-56 of 60
  shallow taps (0.5 cm past) press, against 34-36 with the old rules; a
  still finger 1.5-2.5 cm out presses no more often than before.
- Logs: each press and release (panel, place, depth, speed, frames), each
  poke attempt that crossed the surface without a press with the rules
  that held it back, each grab and its end, printed by ft-screens as
  "hands: ...". handinput state counts them.
- Pinch grabs test where the thumb and index meet (the gestures file's
  point is the knuckles, 5-8 cm behind them, which the 3 cm deep zones
  rarely had): a band 6 cm outside to 2.5 cm inside the border, 4 cm deep
  either side (HANDS_GRAB_BAND); corners (6 cm) resize, the rest moves.
  The glow shows it before the pinch: amber at a corner, blue on the
  border, green for a card pinch.
- A near pinch on the content clicks where the fingertip's cursor was (or
  where the fingers meet), held while the pinch is (HANDS_PINCH_CLICK).
- Card pinch (HANDS_CARD_PINCH): the thumb and index either side of the
  panel's plane at its border, the hand along it; the panel goes rigidly
  with the hand, position and full turn, past 1 cm and 3 degrees.
- Fist grab (HANDS_FIST_GRAB): a grip begun with the palm or knuckles at a
  panel carries it and turns it with the wrist; two fists stretch it. A
  fist or pinch on a hand "grab that" has waits until it fires or lets the
  hand go (at most 0.6 s): on the user's flag, with a panel where the
  gesture brings one, a pinch-click on the closing hand stole the second
  fire before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 18:05:15 -06:00
DeeJanuzandClaude Opus 5.5 0249491033 ft-screens: a hand at a panel owns the pointer
In the live test of 2026-10-10 the cursor followed the fingertip but taps
on remote displays didn't click. ft-screens' log shows the pokes did reach
the streams (remote 104 got 10 button downs and ups, 100-200 ms each), so
the press itself wasn't the only problem: SteamVR's laser moves (the
pointer helper's head or gaze pointer, a controller's laser) on the same
panel still went to KWin or to the remote host between the hand's press
and release, so the host saw a drag from the fingertip to the other
pointer and back, not a click, and while the finger hovered the host's
pointer jumped between the two.

Now, while a hand holds the button, SteamVR's mouse moves go nowhere, and
on a panel whose pointer a fingertip moved within the last 250 ms
(kHandPointerMs), neither do its moves nor its focus leaving.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 18:04:33 -06:00
DeeJanuz 1f0383ce4c Merge branch 'eye-rate' into experimental: SteamVR's eye cameras at 90 fps for gaze mode 2026-10-10 17:58:26 -06:00
DeeJanuzandClaude Opus 5.5 a0e46e4954 gaze: keep SteamVR's eye cameras at 90 fps (gaze/eye-rate.py)
The Frame's SteamVR driver runs the eye cameras at 15 to 90 fps and, with its
defaults, picks 15. Our tracker then sees 8 or 9 frames in a calibration
dot's 0.6 s, where it needs 15, so it can never calibrate (2026-10-10 report:
"the right eye was seen in only 8 frames" on all 27 dots). With
steamvr.gazeDepEyeToHeadEnable on, SteamVR asks for 90 at every start; the
reporter calibrated once it was on.

gaze/run.sh install turns it on (vrcmd with SteamVR running, else the
settings file), and marks it as Frametop's; gaze/run.sh uninstall and
uninstall.sh turn it off only then. update-check.py (doctor) and
gaze-report.py report the cameras' rate from eyetracking.txt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 17:58:26 -06:00
DeeJanuzandClaude Opus 5.5 8d3de8e13f Merge branch 'hands-gazechord' into hands-next: the gaze chord, hand input switches
Conflicts:
- ft-pointer.cpp, the gaze pinch comment: typing's "the rules for all
  gestures hold (..., typing, ...)" kept, gazechord's chord and
  POINTER_GAZE_PINCH paragraphs added after it, and a line that a hand
  typing holds back makes no chord.
- ft-pointer.cpp, the hands settings: gazechord's gazePinchOn, nearOn,
  handsTrack kept; typingHold dropped for typing's typing::Params.
- ft-pointer.cpp, mayPoint: both conditions (handsOn, and not a side
  typing holds back).
- ft-pointer.cpp, beginGazePinch: gazechord's busy line (a chord isn't
  busy), without the old sinceKey/typingHold lines. The chord's pinch
  goes through typing.h's Why in the gesture loop before startGesture,
  like any pinch, so a hand typing holds back can't make one.
- docs/reference.md settings line: typing's and reach's keys, plus
  POINTER_GAZE_PINCH.
- hands/README.md near input: typing's hold-back sentence and
  gazechord's HANDS_NEAR=on.
- session/frametop.conf.example: reach's HANDS_GRAB_ROTATE* and
  HANDS_GRAB_THAT* lines, then gazechord's HANDS_NEAR line.

Reconciled: gazehand's Situation loses sinceKey and typingHold, and
Refused its "ignored (typing)": the helper had stopped setting them on
hands-typing (typing.h holds hands back first), so that guard could
never fire. gazehand-test's key checks now drive typing.h: keys hold a
hand back (2 s now, was 1), POINTER_PINCH_TYPING=0 is no guard, and a
chord's pinch by a hand on the keys is held back while one lifted off
them goes ahead. The chord's own pinch counts as a gesture held for
typing's "busy" (free if out of the keyboard zone when keys come), as
the left's hold does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 16:08:29 -06:00
DeeJanuzandClaude Opus 5.5 fae63a8820 Merge branch 'hands-reach' into hands-next: 30 cm touch, wrist turn, grab that
Conflict: docs/reference.md's hands settings line (typing's POINTER_TYPING_*
keys next to reach's HANDS_NEAR_REACH, HANDS_GRAB_ROTATE* and
HANDS_GRAB_THAT*): both kept.

Typing and grab that: a hand typing holds back (the helper's "typing" word)
doesn't arm or fire "grab that" either, so it never claims a fist as near;
vr.cpp's UpdateGrabThat leaves it out, as Poke and Grab already do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:53:25 -06:00
DeeJanuzandClaude Opus 5.5 64d2f018ac Merge branch 'hands-typing' into hands-next: typing holds hands back
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:52:20 -06:00
DeeJanuz f025e56d0f Merge branch 'mac-host' into hands-full: Mac host permission checks 2026-10-10 15:49:48 -06:00
DeeJanuz 0571d4a67d Merge branch 'mac-host' into experimental: Mac host permission checks 2026-10-10 15:49:41 -06:00
DeeJanuzandClaude Opus 5.5 6c921b113c ft-screens: "grab that" brings a panel to arm's reach (HANDS_GRAB_THAT)
Hold an open hand out to a screen, remote display or floating window,
palm to it, then pull the arm back making a fist: the panel comes over
250 ms to 45 cm ahead of the eyes, at the fist's height, facing you
(user, 2026-10-10). Screens wider than HANDS_GRAB_THAT_WIDTH (0.6 m)
come at that width. The same gesture at a panel that came, still where
it came to, sends it back; the reset button sends floating windows back
(the layout reset places screens and remote displays itself).

screens/grabthat.{h,cpp}: the detector (pure logic): open fingers, palm
ahead and the wrist 28 cm out for 0.2 s arm it; the fingers closing with
the palm still to the panel, then on one frame a fist, the wrist 8 cm
back within 0.5 s and the palm turned over fire it. The panel is the one
the eye-through-palm line meets, else the one the head points at. From
the closing (thumb clear of the index: not a pinch) to 0.4 s after the
fire the hand counts as near, so the helper doesn't take the fist as a
gaze grip. Hands frames carry the head pose at capture now
(Hands::captureHead).

Tests replay the user's flag (fires twice, right hand, at -11.35 and
-5.89 s; expected -11.4 and -5.9), and the other 12 flags and 15 minutes
of recordings fire nothing (1 of 143 pinches, 3 of 12 grips begin on a
claimed hand); synthetic waves, pushes, fists without the pull, slow
pulls, a hand turned over first, held-out pinches, a drop to the lap and
typing don't fire. handinput-test --grabthat FLAG_DIR... scans flags.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:49:38 -06:00
DeeJanuz 9290ae6c0e host/macos: check Sunshine's permissions, ask again for Accessibility
Without Accessibility, Sunshine on macOS still moves the pointer (it
warps it) but clicks, scrolling and typing are dropped. Sunshine asks
only once, so a lost grant, or one given to a Homebrew Sunshine, never
gets asked for again.

The setup now reports Screen Recording and Accessibility from what
Sunshine noted at its last start, at the end of a run and with --check.
If Accessibility is still missing after the first instance restarts, it
offers to clear Sunshine's TCC records and restart it so macOS asks
again. Documented in remote-displays.md and reference.md.
2026-10-10 15:49:37 -06:00
DeeJanuzandClaude Opus 5.5 141fb3b152 docs: the gaze chord, POINTER_GAZE_PINCH and HANDS_NEAR=on
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:49:33 -06:00
DeeJanuzandClaude Opus 5.5 8135bd351d Input Settings: hand input switches on the Hands page
Three switches, each on its own: pinch to click where you look (gaze
on), a raised hand's ray (gaze off), and direct touch on Frametop's
screens (gaze on or off). They write through handsmode.method_writes,
reload the helper and relay, and tell ft-screens direct touch live.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:49:12 -06:00
DeeJanuzandClaude Opus 5.5 213207309d handsmode: the three hand input switches, read and written apart
methods_of reads gaze clicks, the hand ray and direct touch from
frametop.conf as they work today; method_writes toggles one and pins
the others' keys so they don't move with POINTER_HANDS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:47:34 -06:00
DeeJanuzandClaude Opus 5.5 24d2d12397 pointer: the gaze chord in the helper, and hand methods as their own switches
The helper sends the chord's right button (btn b) apart from the left's
press, so both reach the panel; the chord ends with its pinch, its hand
lost, the pointer going, a controller on its side, or the calibration
panel. POINTER_GAZE_PINCH (1) turns clicks at the gaze off on their own.
HANDS_NEAR=on runs the handoff for ft-screens' direct touch without
POINTER_HANDS (HANDS_NEAR=1 keeps its meaning), and the relay feeds it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:46:31 -06:00
DeeJanuzandClaude Opus 5.5 be8f786efd gazehand: the two-hand chord, left and right held together
An index pinch by the other hand while a gaze pinch is held presses the
right button until that pinch ends; a first pinch still held back becomes
a real left press at once, where the pointer is. ChordButton times the
right press (30 ms after a left the chord made, a tap clicks, a lost hand
releases). Tests for the chord sequences.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:42:02 -06:00
DeeJanuzandClaude Opus 5.5 b6fff6d491 docs: hands-typing, what the branch does and the replays
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:34:50 -06:00
DeeJanuzandClaude Opus 5.5 78ec0f14f3 pointer: typing.h times can be negative (replays relative to a flag)
The posture's and a raise's start used -1 for none, so a replay of a flag
(times before it negative) never saw the posture. Found replaying the
2026-10-10 flags through it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:33:20 -06:00
DeeJanuzandClaude Opus 5.5 e511c705f9 ft-screens: turn a carried panel with the wrist (HANDS_GRAB_ROTATE)
While one hand carries a panel, the hand's turn since the grab turns it
too, 1:1 about yaw, pitch and roll (user, 2026-10-10: line displays up).
The turn comes from the wrist and the index and little knuckles, which
hold still while the fingers pinch, smoothed with fh_smooth's Direction
filter, relative to facing the head across the floor from the hand, and
is applied on top of the panel facing the head: carrying a panel round
you still only keeps it facing you. Nothing turns until the hand has
turned HANDS_GRAB_ROTATE_DEADZONE (5 deg), then it turns from there
without a jump; within 2.5 deg of level it snaps level. Let go, it keeps
the turn, and the next grab starts from it. Corner and tab grabs only
resize; a stretch is unchanged and the hand left holding starts afresh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:32:53 -06:00
DeeJanuzandClaude Opus 5.5 f4f526dc08 screens: no pokes or near grabs by a hand typing holds back
ft-screens takes the pointer helper's "typing <L> <R>" (lapses after 3 s):
such a hand presses nothing, grabs nothing, and the cursor doesn't follow its
fingertip; a press or grab already held carries on. handinput's state counts
them as held back (typing).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:31:25 -06:00
DeeJanuzandClaude Opus 5.5 56fb3b3d82 pointer: typing holds hands back: no pinches, grips or ray, and ft-screens hears it
The helper feeds typing.h the relay's keys and each hands frame. A hand it
holds back makes no pinch, middle pinch or grip (ray, gaze or plain), and has
no ray: one that drove the pointer drops it (to the mouse or the gaze, not
the controllers) and can't claim it again until lifted off the keys. A hand
pointing or holding a gesture out of the keyboard zone isn't held back by
the other hand's keys. ft-screens gets "typing <L> <R>" on a change and every
second. The old 1 s guards (beginHold, gazehand's) give way to it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:30:06 -06:00
DeeJanuzandClaude Opus 5.5 a67abc62ff pointer: typing.h, which hands typing holds back (keys, on the keyboard, the posture)
A key holds every hand back for POINTER_PINCH_TYPING (now 2 s); a hand in the
keyboard zone while typing stays held back until it rises POINTER_TYPING_RAISE
above where it typed (or turns its palm); both hands in the keyboard posture
count as typing within POINTER_TYPING_RECENT of a key. Tests with made-up keys
and hands placed as in the 2026-10-10 flags and the desk take.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:26:46 -06:00
DeeJanuzandClaude Opus 5.5 388e8584d4 ft-screens: a hand within 30 cm of a panel touches it (HANDS_NEAR_REACH)
The near claim reaches 0.30 m (was 0.15): within it the pointer helper
hides that hand's ray and leaves its pinches alone, and the index pokes
(user, 2026-10-10: "near = poke within a foot"). A hand near a panel
stays near until 5 cm farther out, then 250 ms on, so the ray doesn't
flicker at the zone's edge. A hand resting low by the body (the poke's
resting rule) is near only within 0.15 m, so a low panel within reach
doesn't take gaze pinches from the lap. The poke's rules are unchanged:
on the PR #3 desk and touch replays the presses are the same as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:25:39 -06:00
DeeJanuzandClaude Opus 5.5 8a0c6c707e docs: what typing did to hand input on 2026-10-10 (logs, flags, desk take)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 15:23:48 -06:00
DeeJanuz 2032a5478d Merge branch 'spotwatch' into experimental: Meta+Space search for apps and remote displays 2026-10-10 12:08:59 -06:00
DeeJanuzandClaude Opus 5.5 2c472879ed Spotwatch: Meta+Space search for apps and remote displays
A Spotlight-like search pill (docs/spotwatch.md). Meta+Space (the input
relay's new spotwatch action, bindable to mouse and controller buttons
too) opens a faux-glass pill straight ahead of the head. Typing finds
apps and remote displays ({host} - {display}). Enter brings a running
app's most recent window to the front with the lazy susan, launches an
app that isn't running as a floating window, or connects and spins to a
remote display. Shift+Enter or a right click opens the item's menu: the
app's desktop actions, Open new window, Open docked on this screen, and
its windows; a display's Go to and Disconnect.

- spotwatch/ft-spotwatch (Python, in the Plasma session's autostart):
  the index, ranking (spotsearch.py), keys via libxkbcommon, usage.
- spotwatch/ft-spotpanel.cpp (SteamVR overlay, built by
  screens/build.sh): the pill, drawn on the CPU; --render for a look
  without a headset.
- ft-screens: "spin to N", "front N", and "spotwatch on|off", which
  routes every key to the search while it's open (a lease, renewed
  every second) and dismisses it on a click elsewhere or a pause.
- ft-floatd: "spotlist", "activate ID", and launch action=/screen=;
  the KWin script tracks when each window was last active.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 12:08:59 -06:00
DeeJanuz 384e1a84c7 Merge branch 'experimental' into hands-full: display ports from the layout 2026-10-10 11:26:29 -06:00
DeeJanuz b338d04acb ft-stream: a display's port from the layout when given HOST alone
A Mac runs a Sunshine instance per display, and each display's client is
paired with its own. An ft-layout from before ports (release 0.2.2's Reset
Screen Layout, Display Settings and profile launchers) restarted the
Mac's streams at the bare address, the instance on 47989: the other
displays froze, unpaired, and their pointer went to the main display.
ft-stream now looks its port up by its client id, as it reads the route.
Checked: pair with the bare address finds 48089 and the paired client.
2026-10-10 11:26:08 -06:00
DeeJanuz 948017953d Merge branch 'mac-host' into experimental: display ports from the layout 2026-10-10 11:26:08 -06:00
DeeJanuz 1d795874e7 Merge branch 'experimental' into hands-full: docs 2026-10-10 11:15:35 -06:00
DeeJanuz 887afb0090 docs: how Remote Displays tells plain Sunshine from Vibepollo 2026-10-10 11:15:35 -06:00
DeeJanuz 94da65bc93 Merge branch 'mac-host' into experimental: docs 2026-10-10 11:15:35 -06:00
DeeJanuz 8bc187503b Merge branch 'experimental' into hands-full: Sunshine sign-in 2026-10-10 11:15:26 -06:00
DeeJanuz 5366a8774e Remote Displays: recognise Sunshine by its bare 400 to /api/token
Upstream Sunshine answers a POST to a path it doesn't have with
400 {"error": "Bad Request"} before any login check, not 404, so signing
in to a Mac said "It didn't make a token (400 ...)". Checked with a wrong
password against the Mac: it now reaches the login check.
2026-10-10 11:15:26 -06:00
DeeJanuz 5459723bda Merge branch 'mac-host' into experimental: Sunshine sign-in 2026-10-10 11:15:26 -06:00
DeeJanuz 939df2f1cd Merge branch 'experimental' into hands-full: apostrophes in host names 2026-10-10 11:13:05 -06:00
DeeJanuz 5ca7c488b5 Remote Displays: a host's name may have an apostrophe
A Mac's computer name is often "Name's MacBook", and Add computer refused
it. The name only goes to ft-layout as an argument and into the layout and
panel labels, never through a shell.
2026-10-10 11:13:05 -06:00
DeeJanuz 87c5267f27 Merge branch 'mac-host' into experimental: apostrophes in host names 2026-10-10 11:13:05 -06:00
DeeJanuz ca1e5c38ab Merge branch 'experimental' into hands-full: a Mac's real monitors through Sunshine, Frametop Voice
# Conflicts:
#	input-settings/ft_input_settings.py
#	input-settings/main.qml
#	input/game_pause.py
#	session/frametop.conf.example
2026-10-10 11:01:32 -06:00
DeeJanuz 6ccd0be3b7 Merge branch 'mac-host' into experimental: a Mac's real monitors through Sunshine 2026-10-10 10:52:09 -06:00
DeeJanuz 35906887bb Remote displays: a Mac's real monitors, one Sunshine instance per display
host/macos/frametop-host-setup.sh makes a Mac a host: the pinned Sunshine
pre-release (v2026.1010.141104, the first with the mouse fix for displays
other than the main one), and one instance per real display on ports
47989 + 100*N, each started at login by a LaunchAgent. An instance follows
its monitor (vendor, model, serial), looks its display id up at every start,
and waits while the monitor is unplugged. One certificate and one Web UI
login for all of them. No virtual displays on the Mac.

On the Frame: a display can have a port, and ft-stream takes HOST:PORT.
Plain Sunshine has no tokens, so Remote Displays checks the Web UI login at
sign-in, keeps it in memory until the picked displays are paired, and
passes it on stdin (ft-layout remote add --port --login, ft-stream pair
--login), where ft-stream approves its own pairing request by id. The
Mac's instances show up as one computer.

Tested against the M3 Max with throwaway instances: pairing, remote add,
three streams at once, sound, and the pointer on a non-main display. Not
yet tested in the headset or the live desktop.
2026-10-10 10:52:05 -06:00
DeeJanuzandClaude Opus 5.5 d7472b78ff Merge branch 'display-mode' into experimental: remote monitors follow the stream's resolution
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 10:10:30 -06:00
DeeJanuzandClaude Opus 5.5 0ed59fde40 Remote displays: a monitor switches to its stream's resolution
Frametop's Vibepollo build now switches a streamed monitor to the stream's
resolution while it streams, and back afterwards, instead of scaling the
monitor's own resolution into the stream. Nothing changes on the Frame:
ft-stream already asks for the size set in Remote Displays. The note under a
monitor's stream settings, reference.md and remote-displays.md say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 10:10:30 -06:00
DeeJanuzandClaude Opus 5.5 f71d2f7887 Merge branch 'voice' into experimental: Frametop Voice
frame-voice moves into Frametop as voice/ (its history kept), installed
by install.sh (step 8/11, yes by default, --no-voice). The input relay
takes its push-to-talk keys (a Right Ctrl tap alone, by default) and
types its text where typing goes; SHARE_KEYS is gone. Input Settings
gets a Voice page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 09:30:03 -06:00
DeeJanuzandClaude Opus 5.5 bce02ac568 Voice: don't log stopping whisper-server at startup, when it isn't running
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 09:27:14 -06:00
DeeJanuzandClaude Opus 5.5 018677bcb1 Input Settings: a Voice page, dictation actions, right-hand taps
- Voice page: Frametop Voice on or off (enable/disable --now on the
  host), its keys (shown, set on the Keyboard page), controller buttons
  (capture or pick; read by ft-voiced, so games keep them) and hold or
  toggle, typing as you talk, sounds, the wake word and its phrases,
  and the voice commands in the file. ft-voiced's "status" every 2 s.
- Dictation: start or stop / while held, for key combinations and
  mouse buttons; not on the Controllers page, which would take the
  button from games.
- A captured tap of a right-hand modifier binds that key alone ("97",
  shown as Right Ctrl tap), as the relay now reads it. The defaults
  include the Right Ctrl tap once Frametop Voice is installed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 09:18:14 -06:00
DeeJanuzandClaude Opus 5.5 b3275e7843 Voice: frame-voice becomes Frametop Voice, installed with Frametop
voice/ft-voiced (was frame_voice.py) runs in Frametop's container as
frametop-voice.service. It keeps the mic, the wake word and live text,
and hands the keyboard side to the input relay:
- push-to-talk keys are key combinations (dictate, dictate_hold); the
  relay sends "toggle|start|stop" to @frametop_voice, taken only from
  this user
- text goes to the relay as "type TEXT" (ASCII, in pieces of 2000
  bytes), so it lands where typing goes; the relay holds it back while
  a modifier is held
- controller buttons are read from vrserver's web socket with
  input/vrws.py, in a thread, so the websockets package goes
No own uinput keyboard, fd store, evdev, or controller service any more.
whisper-server runs only while the wake word is on, started and stopped
by ft-voiced. Voice commands and hooks run on the host through
distrobox-host-exec (env passed through env(1)); their FRAME_VOICE_*
variables keep frame-voice's names.

Settings: ~/.config/frametop-voice.json (voice_settings.py, standard
library), wake word off by default, "advanced" for the old config.toml
tunables. voice/run.sh install carries frame-voice's settings over once
(its keys become key combinations) and turns the standalone units off.

Install: install.sh step 8/11 asks (yes by default; --no-voice through
get.sh, install-release.sh and a FrameDrop checkbox). voice/build.sh
builds whisper-server (whisper.cpp d09f61a, Vulkan, static) and
build/venv; voice/models.sh fetches the 322 MB of models into
~/.local/share/frametop/voice by fixed URL and sha256. The image gets
glslc, spirv-headers-devel and pipewire-utils, uv.lock a voice group (sherpa-onnx with its
core pinned: uv dropped it), CI smoke whisper-server and the venv.
uninstall.sh asks about the models; update-check and report.sh know the
service (report.sh leaves out the lines with what was said).

Tests: voice/test (settings, carrying over, typing through a stand-in
relay, push-to-talk, controller buttons from a stand-in web socket) in
just test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 09:18:14 -06:00
DeeJanuzandClaude Opus 5.5 85f920ff58 Relay: type dictation, take its push-to-talk keys, drop SHARE_KEYS
For Frametop Voice (voice/, next commits), the input relay does the
keyboard side of dictation:

- "type TEXT" on its control socket types TEXT where typing goes: to
  ft-screens for the desktop, else on the virtual keyboard SteamVR
  passes to Steam and games. US layout, one key every 4 ms, and a
  character waits while a modifier is held. Only from the relay's own
  user: the socket now reads each sender's credentials (SO_PASSCRED).
- New actions dictate (a press starts or stops) and dictate_hold
  (records while held) send "toggle|start|stop <source>" to
  @frametop_voice. They work without pointer mode and while paused.
- A modifier tap bound by its right-hand code ("97") is that key's
  alone and comes before the folded one, so dictation's default, a
  Right Ctrl tap, doesn't fire on Left Ctrl (crouch in many games).
  It's in the defaults once frametop-voice.service is installed.

SHARE_KEYS and @frametop_keys go: they existed only so frame-voice
could see keyboards the relay grabs, and sent every key typed into the
desktop to a socket any local process could bind. conf-migrate.sh drops
the example's line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 08:53:46 -06:00
DeeJanuzandClaude Opus 5.5 bd44735f3b Bring frame-voice into Frametop as voice/, with its history
Imported from DeeJanuz/frame-voice (branch frametop-keys, 1d88af4).
The next commits make it a Frametop module.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

git-subtree-dir: voice
git-subtree-mainline: b29adb50cc
git-subtree-split: 1d88af4c6e
2026-10-10 08:40:52 -06:00
DeeJanuz b29adb50cc Merge branch 'notify-forward' into experimental 2026-10-10 08:33:12 -06:00
DeeJanuzandClaude Opus 5.5 700f534a27 ft-notifyfwd: settings state from its last state line; keep "on" out of the way
- Display Settings read the log's last line, so an error logged after
  "forwarding" (a failed Notify) showed "In the desktop" while forwarding.
  It takes the last state line now.
- "on" also forwards to SteamOS's steam_notif_daemon, where notifications are
  lost while Plasma's popups are off. The settings app shows it only while
  frametop.conf has it, with that warning.
- update-check reads libnotificationmanager.so.1 (its soname) first; the
  unversioned .so is a dev symlink.
- justfile: why session/test/test_notifyfwd.py isn't in test-python.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 08:33:12 -06:00
DeeJanuzandClaude Opus 5.5 995d407328 Merge utrack/notify-forward: forward the desktop's notifications to the Steam session (#48)
From https://github.com/utrack/frametop/tree/notify-forward. docs/reference.md:
kept both the notifications paragraph and experimental's three-autostart one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 08:32:06 -06:00
DeeJanuzandClaude Opus 5.5 1d88af4c6e Push-to-talk key counts only on its own, not with another modifier held
A modifier already held when the key went down (Shift, then Right Ctrl)
still started or stopped dictation; only keys pressed during the hold
counted as a shortcut. Now any other modifier held on any keyboard at
the press makes it a shortcut too, in tap and hold mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 08:26:08 -06:00
DeeJanuzandClaude Opus 5.5 2a51094d8e rayeval: guided captures' poses, pinch release and grab measures
A guided capture (probes/tap_session.py) has its head poses in poses.jsonl
("hmd": {"m": [...]}) and the raw-to-mono clock pairs in prompts.jsonl:
--prompts maps them, so the tap capture's drags and holds can be replayed.
From a dump it now also reads each pinch's distance and ends, and reports
a ray pinch's release kick, the raw ray's per-frame jumps, the pinch point
a near grab carries (measured and pinned to the palm) with its jitter,
drift and release kick, and where the hand's own direction sits against
the shoulder's ray. --set takes the new fh_ray settings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 20:15:51 -06:00
DeeJanuzandClaude Opus 5.5 93adab7302 Hand ray: the torso faces the head and the hands (StereoKit's body model)
Ideas from StereoKit (MIT, 07b9f0d), credited where a formula comes from it:
- The torso faces the head's forward counted twice plus the direction to
  each wrist seen (POINTER_RAY_TORSO_WRISTS, on), so looking aside while
  pointing swings the shoulders, and the ray, less. probe-moves replay: the
  shoulder's share of a still hand's ray motion 20 -> 18%, p90 2.0-3.7 ->
  1.7-3.6 deg/s; the tap capture: nothing worse.
- The ray can turn toward the hand's own direction, from the palm's axes
  (wrist, middle, ring and little knuckles) tilted -30/8 deg
  (POINTER_RAY_HAND_WEIGHT, 0). Off: every weight measured worse (at 0.3:
  judder 0.07-0.14 -> 0.11-0.33 deg rms per 90 Hz tick, raw jumps over
  3 deg 159 -> 330). The gate still tests the shoulder's ray.
- The knuckle point can be pinned to the palm's axes during a pinch, easing
  back on the steady shoulder's schedule (POINTER_RAY_ANCHOR, 0). Off: our
  pinch point is the knuckles already, and pinned it shook as much or more
  and kicked no less on release, fitted or not.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 20:15:51 -06:00
DeeJanuzandClaude Opus 5.5 723ad4a6b9 ft-camd: put back a camera's buffers the plane pairing lost
After a SteamVR restart XRService put a 16 MB udmabuf between one of
video9's buffers' two planes. The pairing skipped that buffer, the camera
had 15 of its 16, and ft-camd kept saying "still learning". A run bound
by VIDIOC_QUERYBUF knows every buffer of its camera: the missing ones go
back in, in fd order, and out of any fragment run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 19:50:54 -06:00
DeeJanuzandClaude Opus 5.5 ac5111c552 Merge branch 'experimental' into hands-full
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 19:44:05 -06:00
DeeJanuzandClaude Opus 5.5 26507e62b3 Merge branch 'hands-flag' into hands-full
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 17:29:22 -06:00
DeeJanuzandClaude Opus 5.5 cfe227f0d1 Merge branch 'hands-taps' into hands-full
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 17:25:47 -06:00
DeeJanuzandClaude Opus 5.5 f7c580506d Hands: optional dip rule for pinches (HANDS_PINCH_DIP=1)
Quick taps with the hand raised often read 25-30 mm at contact and spring
back without reaching the 2 cm begin, so they never click. With
HANDS_PINCH_DIP=1 (ft-hands --pinch-dip, ft-handreplay --pinch-dip) a pinch
also begins on a sharp dip: within 150 ms the distance falls by 40% of its
recent highest to under 3.2 cm, with the palm moving under 0.3 m/s and the
thumb at least 4 cm from the middle fingertip. It ends 6 mm over its lowest,
or becomes an ordinary pinch once the tips get within 2 cm. Off by default;
the middle pinch doesn't use it.

Guided tap capture replay (student v4): quick taps on a 2 Hz click 10 -> 25
of 30, clear teacher taps 0.62 -> 0.74 at precision 0.93 -> 0.91. Near
misses (fingers ~1 cm apart) now click: 5 -> 16 pinches in that segment.
Unit tests in tests/pinch_test.cpp.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 17:20:57 -06:00
DeeJanuzandClaude Opus 5.5 7160180906 Merge branch 'org-home' into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 16:17:40 -06:00
DeeJanuzandClaude Opus 5.5 72d9b79d7b Frametop moves to the organization's repo: issues too
The plan changed from two repos to one: DeeJanuz/frametop transfers to the Frametop
organization, so issues and pull requests go to Frametop/frametop as well (report.sh,
keys-report.py, README, the hand recorder page). The consent text keeps its old link, which
GitHub redirects, so its wording doesn't change. pack/README.md says how the move keeps the old
links and the old one-liner working.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 16:17:40 -06:00
DeeJanuzandClaude Opus 5.5 2ae1a36b33 Hands: flag tracking failures (ft-handsctl flag, a rolling buffer in ft-hands)
ft-hands keeps the last 12 s of hand crops (each view's landmark crop, 1.6x, at most
224 px), its hands, gestures and landmarks in RAM (track/flagbuf.h, HANDS_FLAG_BUFFER=1).
`ft-handsctl flag [note]` asks for them through run_dir/flag; ft-hands writes them and the
next 2 s to HANDS_FLAG_DIR/flag-<time> from a low-priority thread, for frame-hands'
offline tools. ft-handsctl also saves a /dev/video99 frame and ft-handview's head poses,
and the drawn hands pulse cyan when a flag is taken (ft-handview's new flash and poses
commands). ft-handreplay --flag-at/--flag-every makes the same flags from recordings.
Measured on a replayed ring: +58 MB peak RSS, 0.1 ms a crop on an A720 (about 1% of a
core). Unit tests: tests/flagbuf_test.cpp (make check), tests/test_handsflag.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 16:11:53 -06:00
DeeJanuzandClaude Opus 5.5 b5e410b0b9 Merge branch 'org-home' into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 16:11:45 -06:00
DeeJanuzandClaude Opus 5.5 d9f213b872 Frametop's home is the organization's repo; a stable release in get.sh
New clones, the one-liners (frametop.github.io/frametop), the SteamOS table that releases
check, and FrameDrop's download URLs now point at Frametop/frametop, where CI builds the
releases. Issues and pull requests stay on DeeJanuz/frametop, the upstream it mirrors.
get.sh's menu offers a stable release next to the experimental one (3 and 4). SteamOS 0.4.5
(20261007.6125817) is marked tested with Frametop 0.2.2. pack/README.md says how the two repos
and a release fit together.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 16:11:43 -06:00
DeeJanuzandClaude Opus 5.5 9df7df5f91 Run programs from wake word commands that start with a set phrase
A "commands" list in settings.json maps phrases to an argv. After the
wake word, a command whose words start with a phrase runs that program
(longest phrase wins) instead of the command hook, with the rest of the
words as one extra argument. No shell is involved. The command event
gains "matched" and "ran". Entries are validated and reload live.

The settings app now writes only the keys it manages and keeps every
other key in the file, so hand-edited commands survive its saves.

Adds a small unittest suite for the matcher and the settings round trip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 15:54:01 -06:00
DeeJanuzandClaude Opus 5.5 811e15ed9d Merge branch 'calpanel-clicks' into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 15:30:46 -06:00
DeeJanuzandClaude Opus 5.5 7f55e9328a Gaze calibration: don't wait for ft-eyes' answers
With our tracker, the full calibration asked ft-eyes about each dot (calib-point, up to 3 s)
and for the fit (calib-fit, up to 10 s) with a blocking ask(), which held up the whole gaze
service. Meanwhile the gaze stopped, the helper's 3 s panel lease ran out (the pointer came
back, and a click went to the desktop behind the panel), and an answer slower than EYES_GONE
closed the calibration as if the headset came off.

Checks.ask_eyes sends the command on a socket of its own in ft-gazed's selector, and the answer
(or its deadline, in tick) finishes the dot or the fit. The dot shows its ring full meanwhile;
further clicks do nothing, and a right click doesn't close the panel during the fit.
first-calibration-test.py covers a slow and a silent ft-eyes; the old code fails it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 15:30:43 -06:00
DeeJanuzandClaude Opus 5.5 9def5f1762 Gaze calibration panel: a gaze precision or gaze drag press takes the dot
While the panel was up, the helper took only "btn trigger 1" and "gazekey left 1" as
"take this dot". A left button mapped to gaze precision or gaze drag sends "precision|gazedrag
<source> 1" instead, which the panel dropped, so the click did nothing. The panel's answers
move to pointer/helper/calpanel.h, with an offline test (pointer/test/calpanel-test.sh).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 15:30:43 -06:00
DeeJanuzandClaude Opus 5.5 2af6207862 ft-handreplay: --tips for pinch analysis, --rate and --want-hz
--tips FILE logs, per processed set and hand, the thumb, index and middle tips
(measured, smoothed, fitted), the pinch detector's distance measures (world
landmarks, triangulated, fitted), the palm normal and each view's 2D tips, plus
the pinch and middle-pinch events, for scoring taps against auto-labels
(frame-hands train/taps/tapeval.py). --rate HZ processes at a fixed rate
instead of the live rule; --want-hz HZ plays a reader asking for one. The
replay's live rule now also counts the middle pinch, as ft-hands does.
tools/replay_tips.sh runs several replays with --tips.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 14:51:52 -06:00
DeeJanuzandClaude Opus 5.5 920d16ee5e Hands: the drawn hands instead of the passthrough holes in the panels (HANDS_CUTOUTS=1 brings them back)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 14:00:31 -06:00
DeeJanuzandClaude Opus 5.5 b45a99030a Merge branch 'hands-robot' into hands-full
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 13:52:13 -06:00
DeeJanuzandClaude Opus 5.5 f16ad59a92 ft-handview: a robot hand built from the skeleton (HANDS_VIEW_MODEL=robot)
A stylized robot hand made in code, no asset: rigid pieces, each fixed to
one bone, so nothing bends or stretches out of shape. A light shell per
finger bone (a tapered box with rounded edges and ends), dark balls at the
knuckles and the thumb's base, dark hinges at the other joints, a palm of a
dark core between a palm plate and a back plate with panel lines, and a
short closed cuff past the wrist. Cyan accents glow: fingertip pads, a line
across the knuckles, a dot in the palm, a ring round the cuff. solid is
ceramic white over dark grey metal; ghost is pale and see-through.

screens/handrobot.cpp builds one mesh (2373 vertices, 4360 triangles) once,
a right hand on DemoPose's open hand, in 16 segments' frames. The frames are
handskin's rule (new handskin::TrackedFrames); a left hand's are a right
one's mirrored, so the same mesh draws it mirrored. Each vertex is fixed to
its bone's start or end: shells keep their rounded ends, the straight middle
takes up the tracked length, fingertips end at the tracked tips. The vertex
shader applies one segment's matrix per vertex; no cap pass (it's closed).

Cost (--snapshot, frame-job 4 cores, same run): robot 0.21-0.24 ms CPU and
0.55-0.57 ms GPU wait per draw, against asset 0.28/0.66, babylon 0.26/0.66,
mrtk3 0.25/0.66.

Tests: segments start at their joints along their bones, no vertex past its
bone's length, fingertips at the tracked tips, left = right mirrored vertex
for vertex, rigid segments across poses, only the middle stretches with a
longer bone, accents on the right sides.

No free robot hand asset fit; screens/assets/hands/README.md says what was
looked at.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 13:51:50 -06:00
DeeJanuzandClaude Opus 5.5 68c783fd20 Merge branch 'hands-look2' into hands-full
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 13:27:02 -06:00
DeeJanuzandClaude Opus 5.5 366f5efa4c ft-handview: a cleaner look, a capped wrist, and four more hand models
The look: no more drawn outline. The old rim pass lit a hard line wherever the
hand met the background or a part of it further back, so a finger over the palm
got scratchy white lines. Now the body pass keeps only the surface nearest the
eye (depth) and writes how squarely it faces the eye, the fade, a light from
above and how near a fingertip; the second pass turns that into a soft fresnel
rim, a slight fingertip glow and an antialiased outline. ghost glows white
toward its edges; solid is lit from above with a soft cool rim.

The wrist: the model is cut open where the fade ends, so a hand pointing away
showed its inside (a hollow tube, a fist's fingertips through the palm). A
stencil pass counts front faces up and back faces down along each view (on its
own, with the depth test off: early depth would drop hidden ones); where a view
went in through the cut, a disc where the fade begins covers it.

The models: HANDS_VIEW_MODEL=asset (generic-hand, still the default) | babylon
(Babylon.js, CC BY 4.0) | mrtk3 (BSD-3-Clause, right only, mirrored) | godot
(Godot XR Tools, CC0) | mrtk2 (MIT) | capsules. Each is in
screens/assets/hands/<name>/ with its licence and a README giving the source
commit, hashes and conversion (the MRTK ones were FBX: assimp, then the new
screens/tools/hand-glb-clean.py). hand-asset.py maps each skeleton onto WebXR's
25 joints by name and writes them all into handasset.h; handskin takes the
model's index.

Cost (--snapshot, asset): CPU 0.34 ms per draw (was 0.32-0.33), GPU wait
0.61-0.62 ms per draw (was 0.57). --snapshot now prints the GPU wait.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 13:26:31 -06:00
DeeJanuzandClaude Opus 5.5 e4c51ccf6b Pointer: the drawn hands' overlays aren't panels, so the hand ray and pinches pass through them
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 13:03:14 -06:00
DeeJanuzandClaude Opus 5.5 8a0176075e Merge branch 'hands-look' into hands-full
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 12:46:14 -06:00
DeeJanuzandClaude Opus 5.5 db2e633502 Merge branch 'hands-gaze' into hands-full
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 12:44:51 -06:00
DeeJanuzandClaude Opus 5.5 c2a8328f35 Merge branch 'hands-smooth' into hands-full
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 12:44:32 -06:00
DeeJanuzandClaude Opus 5.5 3a7a532cb9 ft-handview: your hands as a 3D hand model, with Room View on too
The rendered hands are now the WebXR Input Profiles' generic hand (MIT),
posed by the tracked skeleton and skinned on the GPU: per joint a frame
from the bone and the palm, scaled to the hand and each bone's length.
Two looks, HANDS_VIEW_STYLE=ghost|solid; HANDS_VIEW_MODEL=capsules keeps
the tube hand. With HANDS_VIEW_ROOMVIEW=1 (the default) the hands also
float over the cutout with Room View on. --snapshot draws demo poses
into a PNG without SteamVR, and the cost (0.4 ms a draw, the tubes 0.6).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 12:44:29 -06:00
DeeJanuzandClaude Opus 5.5 ac94fb2828 Hands: a held pinch survives a loosened finger or the hand closing around it
A pinch held 0.3 s or longer (a drag) ends only once the tips are 5 cm apart, or 0.12 s
after they first went past 3.5 cm without closing back under 3 cm. Drags in the 2026-10-09
headset test ended with the tips 3.5-4.0 cm apart. A grip takes a pinch only within 0.3 s
of its begin (closing the hand into a fist); after that no grip begins on that hand, so
curling the other fingers around a held pinch doesn't drop it (3 of 28 pinches in the same
test). Taps end as before.

On the lit recording's replayed distances, pinches held 0.3 s or more ended 33-134 ms later
than before, 200 at most. tests/pinch_test.cpp (make check).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 12:43:10 -06:00
DeeJanuzandClaude Opus 5.5 eafb73483b Near grabs: a carried panel moves smoothly and holds still in a still hand
A near grab carried the pinch point moved ahead along the hand's velocity, which is mostly
noise times the lead, so the panel shook. It now carries the pinch point as the cameras saw
it, smoothed (fh_smooth.h, read every frame ft-screens draws), and moves nothing until the
point is 1 cm from where the pinch began, then carries on from there without a jump. The
head the panel turns to face is smoothed too. On the probe-moves replay the carried point's
second difference per 90 Hz tick went from 13-17 mm rms to 2.3-2.6 mm; it now trails the
capture by 85 ms while moving.

Settings: HANDS_GRAB_SMOOTH_MINCUTOFF, HANDS_GRAB_SMOOTH_BETA, HANDS_GRAB_DEADZONE.
handinput_test --replay reports the grab input's smoothness.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 12:43:05 -06:00
DeeJanuzandClaude Opus 5.5 0d6b0c93b5 Hand ray: drags move smoothly and hold steady, and a quick tap stays a click
The ray's One Euro filters (new hands/include/fh_smooth.h) run in continuous time and the
helper reads the ray every loop, so the pose sent to ft_pointer moves at about 100 Hz
instead of jumping at the tracker's 15-30 Hz (the dashboard's dragger made those jumps
jerky). The direction is filtered on the sphere. On the probe-moves replay the pose's
second difference per 90 Hz tick went from 0.90-0.96 deg rms to 0.24-0.26 at the same lag.

While a ray pinch is held the ray pivots on the shoulder as it was at the press, so looking
around doesn't move what's dragged; the reach for push and pull is filtered. A pinch's
first 0.3 s takes 6 deg of turn before it drags. One failed read of the gestures file no
longer ends a drag, and the log says why a drag ended or the ray went off.

Settings: POINTER_RAY_SMOOTH_MINCUTOFF, POINTER_RAY_SMOOTH_BETA, POINTER_RAY_SMOOTH_HOLD,
POINTER_RAY_STEADY, POINTER_RAY_TAP, POINTER_RAY_TAP_DEADZONE. rayeval reads publish dumps
and reports the smoothness at the display's rate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 12:42:59 -06:00
DeeJanuzandClaude Opus 5.5 bd7b15613f Input Settings: the gaze pinch's nudge dead zone and speed on the Gaze page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 12:39:05 -06:00
DeeJanuzandClaude Opus 5.5 d348e0a260 Gaze + hands: look and pinch to click, pinch and move to nudge the pointer
With gaze mode and POINTER_HANDS on, the gaze is the pointer and the hand ray
stays off (POINTER_GAZE_HAND_RAY=1 brings it back). A pinch clicks where you
looked 75 ms before ft-hands saw it; held and moved past 4 deg of hand
movement (POINTER_GAZE_PINCH_DEADZONE) it nudges the pointer at 0.3x
(POINTER_GAZE_PINCH_GAIN), and the correction is a gaze lesson. Held still for
POINTER_GAZE_HOLD it's a press the hand drags. A middle pinch right-clicks at
the gaze. One log line per pinch. Rules in pointer/helper/gazehand.h, tested
in pointer/tests/gazehand-test.cpp.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 12:39:05 -06:00
DeeJanuzandClaude Opus 5.5 3c4964bc56 Hand cutouts: a round hole per hand by default (HANDS_MATTE=circle)
Until the tracking is good enough for a hand-shaped hole, each hand cuts a
disk facing the eye, wide enough for the whole hand plus the margin, drawn
as the stadium around the ellipse each eye sees on the screen with a soft
edge. mesh and capsules stay selectable (HANDS_MATTE, cutouts matte).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 12:17:04 -06:00
DeeJanuzandClaude Opus 5.5 45c716da7c Hands: the tracker's service runs in the tree's own container, a release's too
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:30:16 -06:00
DeeJanuzandClaude Opus 5.5 1a575e922a Hands: the install puts in the hand view's unit too
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:29:39 -06:00
DeeJanuzandClaude Opus 5.5 7ccf34c042 Merge branch 'hands-view' into hands-full
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:25:25 -06:00
DeeJanuzandClaude Opus 5.5 3d1eee828a ft-handview: your hands drawn over games, the dashboard and the void with Room View off
Quest-style: a see-through light hand from the tracked skeleton with a bright
rim, fading out behind the wrist, over everything. Each hand is a placed,
side-by-side overlay facing the head, so it stays put as the head turns and
redraws only as the hand moves. Hidden while a hand holds a controller (the
pointer helper's word, now also on @ft_handview). frametop-handview.service
runs it; nothing installs it yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:24:28 -06:00
DeeJanuzandClaude Opus 5.5 2bb7c43af9 Hand cutouts: only with Room View on (a cutout over the void or a game shows nothing)
screens/roomview.h tells whether Room View is on: forced by HANDS_ROOMVIEW, else
off when the passthrough shared state says disabled, else the last
RoomViewShown/Hidden event in a game, else off in a game and the construct's
setting outside one. `cutouts state` says which; `cutouts roomview auto|on|off`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:24:28 -06:00
DeeJanuzandClaude Opus 5.5 2c57eef75c Merge branch 'hands-settings' into hands-full
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:13:28 -06:00
DeeJanuzandClaude Opus 5.5 64bead79c9 Merge branch 'hands-palm-menu' into hands-full
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:13:16 -06:00
DeeJanuzandClaude Opus 5.5 2fcd29c0f5 Merge branch 'hands-ray-fix' into hands-full
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:13:16 -06:00
DeeJanuzandClaude Opus 5.5 07ce0d9d59 Hand ray: the laser stays with one hand, and a pinch clicks where it pointed
Live test 2026-10-09: taps took several tries and the laser jumped between
hands. The owner's ray dropping for a moment (closing the fingers turns the
hand) handed the laser to the other raised hand at once, for good; a pinch
by the other hand pressed where the old owner's ray pointed; a pinch whose
ray had just dropped became a press at a stale spot, or only woke the
pointer.

- The owner keeps the laser through POINTER_RAY_GRACE (0.5 s) of its ray
  being down; the other hand takes it by pinching, by raising its ray while
  the owner's is down, or after the grace (pointer/helper/rayowner.h).
- A pinch on a ray that dropped within the grace, or is on its way up,
  brings it back (fh_ray.h ShowForPinch) and is a ray pinch.
- Aim lock: the press goes along the ray from just before the fingers
  began to close, after a pose along it has gone out; a tap that ends
  before its press clicks there too.
- Each ray follows one tracked hand through a brief flip of ft-hands'
  left/right call.
- Log: owner changes with the reason, the owner's ray down and back, and
  one line per pinch saying what it clicked or why not.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:12:46 -06:00
DeeJanuzandClaude Opus 5.5 85d34c73a4 Input Settings: a Hands page for when hand tracking runs and the cutout margin
Hand tracking: With Frametop / Always / Off, applied at once through
hands/handsmode.py on the host, with a status line that says what runs
and why it can't (not installed, no capabilities, cameras). Hand cutout
margin: 0-3 degrees in 0.25 steps, written to HANDS_MATTE_MARGIN and sent
live to ft-screens (the still margin only).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:12:40 -06:00
DeeJanuzandClaude Opus 5.5 98475f2b7d Hands: HANDS_MODE runs hand tracking with Frametop, with SteamVR, or not at all
hands/handsmode.py starts and stops ft-camd, ft-hands and the hand view
(frametop-handview.service, when installed) by HANDS_MODE: frametop =
while the desktop runs (session hooks), always = wanted by
steamvr.service (and kept running through game pauses), off = the
default, only ft-handsctl on as before. ft-handsctl mode sets it;
missing ft-camd capabilities start nothing and say what to run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:12:40 -06:00
DeeJanuzandClaude Opus 5.5 2c9924484d Hands: palm up shows a ring, a pinch on it opens the Steam menu
Turn a bare hand palm up toward your face and look at it: after 0.3 s a
small ring shows above the palm and follows it, like the Vision Pro's
home indicator. A thumb-index pinch tap by that hand runs
`ft-steam menu` (opens the Steam menu, or closes the dashboard); the
ring is blue while the pinch is held. ft-screens owns it
(screens/palmmenu.cpp) and reports that hand near while the ring shows,
so the pointer helper doesn't also gaze-click the pinch. The helper is
unchanged. HANDS_PALM_MENU=0 turns it off; `palmmenu on|off|state`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 11:07:39 -06:00
DeeJanuzandClaude Opus 5.5 4c348e6b2b Merge experimental into hands-full (SteamOS 0.4.5 fixes)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 10:38:59 -06:00
DeeJanuz b521564a68 Merge branch 'report-input' into experimental 2026-10-09 10:03:41 -06:00
DeeJanuzandClaude Opus 5.5 1fdd6f0e78 report.sh: Frametop's keyboard, the Steam menu, and --watch to record a problem
For reports like "windows won't drag while the Steam menu is open" and
"Frametop's keyboard doesn't open", the report now has:

- A section on the keyboard and the Steam menu: the Keyboard setting,
  the relay's devices (a pass-through keyboard keeps ours closed by
  default), ft-textinput and KWin's input method, the desktop's
  QT_IM_MODULE and GTK_IM_MODULE, ft-screens' state and new debug line,
  the SteamVR overlays shown, and the matching log lines.
- --watch [SECONDS]: after the report, it records ft-screens' debug line
  whenever it changes, and the logs, while the user makes it happen.
- A release's version and container (it reported "container dev:
  missing"), the gaze, desktop, eye grabber and Bluetooth units, and the
  newest SteamVR start rather than the log's first.

ft-screens: a "debug" command (Steam menu, Steam in front, our keyboard
shown or aside, mode, lasers, held press and which laser, drags in
progress, where typing goes), and log lines when a drag starts, ends, or
can't start, when Steam comes in front or goes, and when a requested
keyboard doesn't open. The relay logs why a focused text field did or
didn't open the keyboard, once per decision (keys-test covers it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 10:03:41 -06:00
DeeJanuz 6b7af52e1c Merge branch 'steamos-045-tested' into experimental 2026-10-09 09:31:41 -06:00
DeeJanuzandClaude Opus 5.5 a53ced4f88 SteamOS 0.4.5 is tested (Frametop 0.3.0-exp.4, SteamVR 2.18.2)
Headset tests on 2026-10-09: Bluetooth reconnects, doctor ok, gaze with
our own tracker and SteamOS 0.4's eye-tracker layout, and the desktop
without Steam's autostart and with its own cursor theme. Release
installs stop asking before they install on build 20261007.6125817.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 09:31:41 -06:00
DeeJanuz 28f91af0d2 Merge branch 'doctor-release-box' into experimental 2026-10-09 09:27:58 -06:00
DeeJanuzandClaude Opus 5.5 e69fe11b2a doctor: in a release, check the release's own container
A release runs in the container its .frametop-release names (BOX, as
scripts/in-box reads it), but doctor.sh looked for the dev build box,
so every release install reported "FAIL container dev" (seen on
0.3.0-exp.4).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 09:27:58 -06:00
DeeJanuz 65acbd9638 Merge branch 'host-build-release' into experimental 2026-10-09 09:26:43 -06:00
DeeJanuzandClaude Opus 5.5 ef1c802e2d Host setup: Frametop's Vibepollo build from its release
The fork's CI published frametop-2.0.0-1 (Vibepollo 2.0.0 with Frametop's
changes, now including the HDR-off guard for SDR display streams). $BuildUrl
points at its sunshine.exe, so a PC needs only host/windows; the first CI
build (a84b6cfc) is upgraded like the hand-built one. Tested on the test PC:
over the first CI build, the setup downloaded the release, matched its
SHA-256, swapped it in and restarted Vibepollo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 09:26:32 -06:00
DeeJanuz 26de1430b0 Merge branch 'release-notes-channel' into experimental 2026-10-09 09:04:59 -06:00
DeeJanuzandClaude Opus 5.5 e21a2beae0 Release CI: an experimental release's install line says --experimental
get.sh --release asks for a channel and offers stable first, and the
Frametop organization has no stable release yet, so the notes' line
fetched releases/latest and got a 404 unless you picked 2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 09:04:59 -06:00
DeeJanuz 8d6aa459fc Merge branch 'release-notes-url' into experimental 2026-10-09 09:04:07 -06:00
DeeJanuzandClaude Opus 5.5 b93c25eb7e Release notes: get.sh --release from the Frametop organization's Pages
deejanuz.github.io serves DeeJanuz/frametop's main, whose get.sh has no
--release yet ("unknown option: --release"). frametop.github.io serves
Frametop/frametop's experimental, where the releases are built.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 09:04:07 -06:00
DeeJanuz b61aebcf16 Merge branch 'own-one-eye' into experimental 2026-10-09 08:42:41 -06:00
DeeJanuzandClaude Opus 5.5 dba0ef5707 Gaze: with our tracker and one eye tracked, take that eye's blink for both
With Track Dominant Eye Only on, SteamVR judges only that eye's
openness. Our own tracker still finds both pupils, but ft-gazed took the
blinks from SteamVR per eye, so whatever SteamVR reports for the ignored
eye could drop our good reading of it. A blink closes both eyes, so the
tracked eye's now marks both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 08:42:41 -06:00
DeeJanuz 70c3ad9b1c Merge branch 'steamos-keep' into experimental 2026-10-09 08:36:34 -06:00
DeeJanuzandClaude Opus 5.5 185cb766b1 SteamOS updates: keep the Bluetooth fixes and the eye grabber through them
A SteamOS update deletes every /etc file its keep list
(/usr/lib/rauc/atomic-update-keep.conf) doesn't name. The list keeps
units but not what they run, so after the 0.4.5 update
steamframe-bt-fixups.service and frametop-eyegrab.service failed with
203/EXEC: Bluetooth LE devices stopped reconnecting, and gaze mode fell
back to SteamVR's tracker, which had no calibration.

- Both installers add a drop-in to /etc/atomic-update.conf.d naming
  their file; uninstall removes it.
- update-check.py (doctor.sh) fails when a unit's program is gone and
  warns when it isn't kept.
- ft-gazed's log and Input Settings' Bluetooth page say what to reinstall.
- setup/README no longer says /etc survives updates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 08:36:34 -06:00
DeeJanuzandClaude Opus 5.5 305dd9bcef Merge branch 'steamos-0.4' into experimental
SteamOS 0.4 (0.4.5) fixes: gaze goes by one eye with Track Dominant Eye
Only; eye-server layouts named by release; update-check covers the new
parts; the desktop no longer autostarts Steam and keeps its own cursor
theme; README note updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 23:33:44 -06:00
DeeJanuzandClaude Opus 5.5 90698db6c7 Docs: SteamOS 0.4 is out; one-eye tracking
The README's note said Frametop didn't work on the 0.4 beta. Gaze reads
0.4's eye tracker layout now, and the missing taskbar in #15 wasn't the
beta's doing (0.4.5 has the same KWin and Plasma as 0.3.0), so the note
now says what the update changes and to run doctor.sh after it. The gaze
README covers Track Dominant Eye Only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 23:33:03 -06:00
DeeJanuzandClaude Opus 5.5 48a2dcf759 Session: no Steam autostart in the desktop, keep its own cursor theme
The desktop is a KDE session, so it ran /etc/xdg/autostart/steam.desktop.
Steam is already running (the desktop starts from it), so `steam -silent`
only reached that client as a command line it ran (ExecCommandLine in its
console log). SteamOS 0.4 adds -vrdisable -deckard to that entry, for
Desktop Mode, where Plasma starts Steam itself. The session now hides it
with the other two. The marker goes to 2, so desktops that hid the first
two get Steam's copy once, and an entry someone brought back stays.

The Steam client's XCURSOR_THEME=steam reaches the desktop through its
environment, and KWin and the apps prefer it to the desktop's setting.
There was no such theme, so they fell back to Breeze; SteamOS 0.4's
holo-cursors adds one. The session sets the desktop's own theme (Breeze
unless changed in its System Settings) and leaves the size as it was.
ft-screens doesn't draw KWin's cursor, so this shows over remote access
and with the gamescope backend.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 23:33:03 -06:00
DeeJanuzandClaude Opus 5.5 06228725cc SteamOS 0.4: name the eye-server layouts by release, check its new parts
SteamOS 0.4 (0.4.5) is the stable release now, with the eye-server.mmap
layout that the 0.4.3 beta brought (its eye tracker and cv driver differ
from the beta's only in thread priorities and the presence sensor). ft-gaze
and update-check call the layouts "SteamOS 0.3" and "SteamOS 0.4 (+5)"
instead of stable and beta.

update-check also reports when Track Dominant Eye Only is on, warns when
/usr/share/steamos/steamos-cursor.png (the gamescope backend's cursor) is
gone, since SteamOS 0.4's own session moved to /usr/share/holo, and gives
retest hints for steamdeck-kde-presets (its Steam autostart entry changed)
and the new holo-cursors package.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 23:33:03 -06:00
DeeJanuzandClaude Opus 5.5 d82364ed00 Gaze: go by one eye when SteamVR tracks only the dominant one
SteamOS 0.4 adds Track Dominant Eye Only (SteamVR settings, General,
advanced: steamvr.eyeTrackingDominantEyeOnly with steamvr.dominantEye).
SteamVR's tracker then ignores the other eye. The calibration kept only
samples where it had both eyes, so if that eye reads as lost, no dot
would ever be taken.

gazecal.tracked_eye reads the setting (TrackedEye re-reads it when the
settings file changes). With it on, steady_samples judges the tracked
eye alone (no vergence check), the calibration needs only that eye's
reading and drops the other's and set 2's average, ft-gazed ignores the
other eye (its mmap2 source takes the eye's own reading, and "eyes"
mode needs only that eye calibrated), and the fit check marks the other
eye "not tracked". Nothing changes with the setting off.

Untested in the headset: what SteamVR's mmap reports for the ignored
eye is unknown; gaze/test/one-eye-test.py covers the logic offline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 23:33:03 -06:00
DeeJanuzandClaude Opus 5.5 5d214d4c3b Hand input: a poke comes at the panel's face; typing under a low panel doesn't poke it
User decision (2026-10-08, "approach from front"): a poke counts only when the fingertip moves
into the panel (4 cm/s or more over the last 100 ms when it crosses the surface) with the
finger's last bone within 50 degrees of the panel's normal (HANDS_POKE_ANGLE), and not from a
hand resting low by the body: palm over 0.30 m under the eyes and within 0.32 m of the head
across the floor, until it's 5 cm higher or further out (HANDS_POKE_REST_BELOW, _NEAR; the
hand recorder's desk take had typing palms at 0.34-0.40 m under, 0.23-0.28 m out). The slow
1 cm-deep press is gone. The index counts as the poking finger when it's nearest the surface
or when the hand points (index straighter than the others by 0.2): pointing at a panel from
below, the loosely curled fingertips sit 1-3 cm nearer it (the touch take).

ft-handreplay --publish-dump writes FHDUMP02 (each set's dequeue time too), and the replay
tests read a take's poses.jsonl and prompts.jsonl next to the dump: head poses, panels around
the head, the touch take's dots, made-up pokes from still pointing hands, low panels.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 22:57:35 -06:00
DeeJanuzandClaude Opus 5.5 2852ad9f99 screens: read a gestures file of any version from 2 on
fh_gestures version 3 (the middle pinch) is longer; ft-screens mapped exactly its own struct's
size, so an older ft-hands' file wasn't read at all, and the dumps written by one weren't either.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 22:57:35 -06:00
DeeJanuzandClaude Opus 5.5 be0314867e Merge branch 'hands-pointer' into hands-full
Joins with hands-screens: ft-hands keeps 30 Hz for a middle pinch as well
as for a want-hz reader; GesturePublisher keeps both use() (replay dumps)
and write()'s middle-pinch slots; both test groups run in test-c.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 22:09:44 -06:00
DeeJanuzandClaude Opus 5.5 bcc2da2b4a screens: gestures from a stale hands file count as up
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 22:04:46 -06:00
DeeJanuzandClaude Opus 5.5 08656417e1 Hands docs: the hand-shaped matte, near input, their settings and offline results
A carried panel a laser takes over (or one let go of elsewhere) no longer follows the hand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 22:03:17 -06:00
DeeJanuzandClaude Opus 5.5 4f5087201d Docs: the hand ray, handoff and parking in the reference
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 22:01:14 -06:00
DeeJanuzandClaude Opus 5.5 cb417e4fb5 screens: hulls drawn as their grown polygons, cut shaders discard outside, a forearm stub; matte bench
The hull shader ran over each piece's box; a forearm across the panel covered a fraction of
it. Now the polygon grown by the margin and the feather is drawn, and fragments outside a
piece are discarded (no blend). The forearm is a stub toward the elbow (18 cm at the average
hand size, as the capsules' 16 cm): the elbow is a guess and a longer piece costs a bigger
redraw. tests/matte_bench.cpp (scripts/bench-matte.sh) times the composite offline on the GPU,
mesh against capsules, frame by frame in turn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 22:01:04 -06:00
DeeJanuzandClaude Opus 5.5 400fe0ca5f Pointer: ray gestures only with the ray still up; presses wait for a fresh wake
A gesture that waited for ft-screens' near report is a ray gesture only if
its ray is still up when it starts; a ray pinch's press waits until a
pointer the ray just woke is bound (350 ms). keys-test's pause stub knows
the relay's new calls.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 21:59:29 -06:00
DeeJanuzandClaude Opus 5.5 d16f774d50 Hands: park hand tracking during VR games instead of stopping it
With hand interaction on (POINTER_HANDS=1), the hands have to be there
when the dashboard opens during a game (design section 5.5):
- ft-hands: while /run/user/UID/frametop-hands/park exists it processes
  no frames (models stay loaded), publishes no hands, ends gestures as
  lost, and writes 0 to hands-want every second.
- ft-camd: stops copying the mono frames while hands-want is fresh and 0
  (a dead ft-hands' stale file doesn't starve other ring readers).
- The input relay (game_pause.py) leaves the hand services running when
  it pauses for a game and parks them instead; it unparks while the
  dashboard is open (the helper's new "vrdash 1|0") and on resume.
- hands/README.md: gestures v3, parking, and the hand ray.
- pause-test.py: parking, and "paused" kept off the live helper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 21:58:01 -06:00
DeeJanuzandClaude Opus 5.5 0e036482e0 Hands: middle pinch (thumb to middle finger), fh_gestures v3
ft-hands publishes a middle pinch per side in the gestures file's new
pinch2 slots (version 3; older readers copy the size they know). The
pointer helper's hand ray makes it a right click or scrolling.

- Pinch takes the fingertip (8 or 12), the other one it must be clearly
  nearer than (1 cm for the middle pinch), and the two pinches exclude
  each other on a hand. A middle pinch also wants the index extended and
  the hand tracked 5 frames: closing the hand into a grab brought the
  middle tip to the thumb (PR #8 gestures take: 6 false middle pinches
  before, 1 after; the 2026-09-30 lit recording: none, and the same 48
  pinches).
- ft-handreplay runs it too (timeline: pinch2); watch_gestures.py reads v3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 21:58:01 -06:00
DeeJanuzandClaude Opus 5.5 bf6266ce81 screens: hand-shaped matte from fh_hands v2, glows, near hand input (poke, grab, resize, stretch)
- handcut: reads fh_hands version 2 (the skeleton's joints, radii, elbow, pinch point; version 1
  still works) and the gestures file; the matte is hand-shaped: a tapered capsule per finger
  bone, the palm and the thumb's web as convex slabs, the forearm toward the elbow, drawn with
  a soft-edged convex polygon shader; its margin is an angle from the eyes plus motion
  (HANDS_MATTE_MARGIN, _MOTION, _MOTION_MAX), the capsules stay selectable (HANDS_MATTE), and a
  per-distance correction hook is off by default (HANDS_MATTE_SHIFT). The CPU part is in
  handcut.cpp (no GPU or SteamVR calls), the renderer in handrender.cpp.
- handinput: the near claim, poke to click (index straight and nearest, two frames at the
  surface, an approach speed or 1 cm deep, release 1.5 cm out or 1 cm back, the click held
  still until a 1.5 cm slide, re-press guard, through-the-panel release), pokes on the curve,
  reset, dock and close buttons, pinch on the bar, edges, corners, tab or title bar to move
  (facing the head) or resize, two hands to stretch and turn, two hands to one, lost hands.
- vr.cpp: hands read once per tick, "hands <L> <R> <allowed>" from the pointer helper, "near
  <capture_ns> <L> <R>" to it per hands frame, want-hz while near, glows on the cutout buffer,
  hand holders for KWin's button and carried panels, the handinput and cutouts commands.
- tests/handinput_test.cpp: unit tests, and replays of ft-handreplay --publish-dump
  (scripts/test-handinput.sh, justfile test-c).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 21:53:06 -06:00
DeeJanuzandClaude Opus 5.5 5d96d211ec Pointer: the hand ray drives ft_pointer; ray pinch, push and pull
With POINTER_HANDS=1 and POINTER_HAND_RAY=1 (design sections 2, 5):
- Per side, each hands frame goes through fh_ray's gate; the first ray up
  drives the pointer (a pinch by the other hand's ray takes it). It wakes
  the pointer and claims the laser unless a controller pressed within 2 s.
  The mouse takes the pointer back; the ray returns after 1 s of no mouse.
- The pose is the ray's origin and direction (a visible beam); our dot only
  where it meets a panel, no catcher in free space. A controller taking
  the laser hides our dot until a ray pinch claims it back.
- A ray pinch is the left button, 30 ms after a claim it had to make;
  the direction holds until POINTER_RAY_DEADZONE (2.5 deg), then drags.
  A middle pinch (fh_gestures v3) is a right click, or scrolling when
  held and moved. Gaze pinches and grips are unchanged with the ray down.
- Push and pull while carrying (POINTER_RAY_PUSH): the origin moves along
  the ray, distance d0 (h/h0)^3.
- ft-screens' "near <capture_ns> <L> <R>": a gesture waits for the report
  on its frame (60 ms at most) and is left to ft-screens if near.
- The ray lets go of a pointer it woke POINTER_RAY_RELEASE after it went;
  at once when its side's controller is in use or in a game.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 21:47:53 -06:00
DeeJanuzandClaude Opus 5.5 2ed603b304 Hands: the hand ray model (fh_ray.h), with tests and an offline evaluation
hands/include/fh_ray.h, shared by the pointer helper and ft-screens (design
sections 2.4-2.5): a body model (torso yaw = head yaw low-passed, at most
30 deg behind; shoulders from it), the ray from the shoulder through the
knuckles (20 ms prediction), the pointing gate (show tests for 120 ms,
hide after 250 ms of a failed keep test; near and "off" hide at once;
held through a ray pinch), and One Euro filters on yaw, pitch and origin.

- pointer/tests/handray-test.cpp: body, gate timing and tests, filter
  (just test-c).
- ft-handreplay --ray FILE: per set and hand, what the helper reads.
- pointer/tools/rayeval: the ray over a replay, with the head poses from the
  ft-handtest probe's log of the same session (clock matched by the
  published capture times): how often it shows, why not, jitter, the ray's
  shift into a pinch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 21:47:28 -06:00
DeeJanuzandClaude Opus 5.5 564bb4bdc5 Pointer: treadmill role by default, and per-hand last used wins
- The driver's default role is the treadmill (4), hinted from Activate;
  the helper's POINTER_ROLE defaults to treadmill. Needs the driver
  reinstalled and a SteamVR restart to take effect.
- The "no hand role" release skips a device whose hint is the treadmill.
- Hand gestures: none begins on a side whose controller is in use, or by a
  hand at a controller (by position); a held one ends, as lost, when its
  side turns controller.
- The moving-controller release no longer applies while a bare hand's ray
  drives the pointer (that ray goes only when its own side turns controller).
- update-check.py: the virtual controller's path, and the touch components.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 21:32:14 -06:00
DeeJanuzandClaude Opus 5.5 742bd32c32 Pointer: handoff arbiter for hand interaction (log only)
Per side, a controller used recently wins, else the bare hand
(pointer/helper/handoff.h, design section 1): touch and presses from the
input relay, motion, charging and tracking from SteamVR, and the tracked
hands from ft-hands' hands file (handsin.h, which also takes the gestures
reader and the head pose history out of ft-pointer.cpp).

- The relay's web socket reader (game_pause.py TouchTracker) sends
  "ctl <side> touch 0|1", "ctl <side> press", "ctl <side> gone" and
  "ctl ws 0|1" with POINTER_HANDS=1, and the pause state as "paused 1|0".
- The helper logs transitions and sends ft-screens "hands <L> <R> <allowed>"
  (hand|controller|off, 0|1) on a change and every second. Nothing acts
  on it yet.
- fh_gestures v3 adds the middle pinch slots (written as zero for now).
- Tests: pointer/tests/handoff-test.cpp (just test-c), input/test/touch-test.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 21:30:56 -06:00
DeeJanuzandClaude Opus 5.5 2f0285e22a hands: ft-handreplay --publish-dump; ft-hands keeps the full rate while want-hz asks
--publish-dump writes what ft-hands would have published after each processed set (the hands
and gestures files' bytes), for ft-screens' offline hand input tests. want-hz: a reader
(ft-screens with a hand near a panel) asks for up to 30 Hz by keeping the file fresh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 21:27:43 -06:00
DeeJanuzandClaude Opus 5.5 44c99f2980 Pointer: treadmill role in the driver, and probes for hand interaction
The driver takes "role treadmill" and hints its role from Activate, so a
treadmill gets /user/treadmill (from gaze-first 87a6393); the compositor
binding has the /user/treadmill entries. The default role stays the right
hand until the helper side is ready. docs/design.md says why (Treadmill role).

Probes for frame-hands/notes/hand-interaction.md section 7:
- pointer/probe/lasertest (from gaze-first): who has the laser, claim time
- pointer/probe/ctlnoise: controller pose noise, activity level, charging
- vrprobe prints each device's activity level and charging
- input/vrws.py --touch prints touch and value components

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 21:24:43 -06:00
DeeJanuzandClaude Opus 5.5 82d09cf98f Merge branch 'hand-skeleton' into hands-full
Conflicts were side by side (options, tracker setters, replay flags). Two
joins: Hand::right() keeps the pairing's side and the skeleton's fields,
and the skeleton now fits after the left/right pairing, so it fits the
side ft-hands publishes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 21:18:29 -06:00
DeeJanuz 9f567b4bb2 Merge branch 'hands-reacquire' into hands-full
# Conflicts:
#	hands/track/main.cpp
2026-10-08 21:12:51 -06:00
DeeJanuzandClaude Opus 5.5 eca95477cd Hands: HANDS_MODELS setting picks ft-hands' model folder
Fine-tuned models (the hand dataset's student models) can't ship in the
repo yet, so a headset that has them sets HANDS_MODELS in
~/.config/frametop.conf instead of passing --models to every launcher
(service, ft-cutouts, recorder, probes). --models still overrides it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 19:44:28 -06:00
DeeJanuzandClaude Opus 5.5 a57bd822de Hands: re-acquire lost hands fast, pair left/right, hold longer
Live (2026-10-08 probe) a hand that dropped out of tracking stayed gone for
2-4 s while plainly in view. Cause: the palm search is the only way back once
a hand is forgotten (0.3 s), and it tries 2 of 42 tiles per round, so even the
likeliest tile comes round every 10-11 rounds: ~2 s at 5 rounds/s, 4-5 s live
(a round costs ~52 ms beside SteamVR). A quarter of the probe's per-side
"missing" time was a labelling error instead: both hands published, both
called the same side.

Tracker (on in ft-hands by default; off in ft-handreplay unless asked):
- --reacquire S (1.5): from the first step a hand (3+ frames) is missing
  until S after it's forgotten, the palm search aims up to 2 tiles at its
  predicted position in the cameras that see it best, every processed set;
  the rotation keeps at least one tile. Held hands' hand-over crops follow
  their velocity.
- --pair-sides (1): two hands seen together are one left and one right, by
  fading log-odds of the model's calls (wrist order breaks close calls).
- --hold S (0.6): an established hand (30+ frames) is held 0.6 s, not 0.3.

Replay tooling: tracker trace events in --timeline, --cost-hand/--cost-palm
(live costs 14/52), per-side gap counts, label-free oracle miss rate,
--drop-every (blind a hand 0.35 s, time the re-find), tools/gap_report.py
(gap causes), tools/replay_gaps.sh. Results: frame-hands notes/reacquire.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 17:47:57 -06:00
Nikita Koptelov (@ Steam Frame ssh key) dd777576d8 ft-notifyfwd: add settings knobs 2026-10-08 23:34:32 +02:00
Nikita Koptelov (@ Steam Frame ssh key) 3a63780bbd ft-notifyfwd: forward notifications to an external notify daemon 2026-10-08 23:26:30 +02:00
DeeJanuzandClaude Opus 5.5 d3ec6877ae hands: skeleton keeps a tracked hand's side while the model's call hovers; README
A hand whose running left/right call wandered across 0.5 got mirrored
mid-track: the palm normal turned over (the PR #3 gestures take's 90th
percentile change per update, fingers moving, 94 -> 32 degrees). Now it
keeps its side while the call is within 0.25 of 0.5.

hands/README.md: the Skeleton section, with what replays measured, the
new settings and ft-handreplay options.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 13:17:13 -06:00
DeeJanuzandClaude Opus 5.5 6accce9769 hands: skeleton chains also start from last frame's pose
Each chain runs Gauss-Newton from the measured bone directions and from
last frame's angles, and keeps the better fit, so it hops less between
two poses that fit about as well: tip jitter tails 2-6% lower in the lit
and dim recordings, for 25 -> 42 us median per hand on a big core.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 13:09:54 -06:00
DeeJanuzandClaude Opus 5.5 f9408a6612 hands: skeleton side hysteresis, glitch-aware filter, finger twist
- Fingers get a small twist at the knuckle (±25°): without it the fitted
  index tip sat a median 8 mm across the finger from the measured one in
  the PR #3 gestures take, and 11 mm from the labels against 7.7 mm.
- The other side wins only after 3 frames in a row of fitting far
  better, and then sticks while the hand is tracked (110 flips in the dim
  recording before, 6 after): each switch reset the filter.
- A chain fitting its landmarks worse than 15 mm moves the filter (and
  its speed) less: those frames are mostly a hidden landmark misplaced.
- Calibration skips phalanges far off the average hand's proportions and
  drifts at most 0.02 mm a sample after settling.
- ft-handreplay: the fit timed alone on a little and a big core, the
  palm normal's steadiness, rest meaning the fingers still too, and
  --skeleton-dump.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 12:55:27 -06:00
DeeJanuzandClaude Opus 5.5 e9cb33389d hands: per-user skeleton fit, fh_hands version 2
ft-hands fits a skeleton to each hand's 21 landmarks after the 3D step
(track/skeleton.{h,cpp}):

- Bone lengths and palm shape are learned per side from clean stereo
  frames (medians, then a slow running median), with the model's average
  hand times Hand::scale, or the other side, as the prior.
- Each frame: the palm as a rigid body, then each finger and the thumb as
  a chain with joint limits (Gauss-Newton), the chain bases allowed a few
  mm off the rigid palm. Landmarks are weighted by their triangulation
  residual and down-weighted along the line of sight.
- The pose (palm centre, palm rotation, joint angles) is filtered, not the
  points; each finger's cutoff follows its own speed.
- An elbow from the arm model in frame-hands' notes/forearm.md.

The hands file goes to version 2: version 1's struct is unchanged and an
fh_hand_fit_t per hand follows it (joints as position + quaternion,
bone lengths, angles, elbow, pinch point, fit quality, head-frame
velocities). Version 1's points and capsules come from the skeleton
(HANDS_SKELETON=0 or --skeleton 0 for the old ones). The hand
recorder's reader accepts version 2.

ft-handreplay reports the fit (track/skeval.h): time, residual,
calibration, bone-length spread, jitter, tip lag, elbow, and with
--labels the distance to frame-hands' auto-labels. SetReader reads a
hand-recorder take's later parts (sets-2.bin, ...).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 12:33:11 -06:00
DeeJanuz 52b10478ad Merge branch 'stream-in-box' into experimental 2026-10-08 10:45:56 -06:00
DeeJanuzandClaude Opus 5.5 275529da8f Gaze probe: run ft-gaze through scripts/in-box, not the "dev" container
On a release install there is no "dev" container. in-box picks the release's own container,
and starts it first, as container-up.sh did here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 10:45:56 -06:00
DeeJanuz b727b8b8fe Merge branch 'stream-in-box' into experimental 2026-10-08 10:44:20 -06:00
DeeJanuzandClaude Opus 5.5 46bf562c5f Remote displays: ft-layout runs ft-stream in the release's container, not "dev"
On a release install with no "dev" container, distrobox asked whether to create it, and
adding a display hung until it timed out. run_stream now goes through scripts/in-box, as
gazecheck.py does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 10:44:20 -06:00
DeeJanuz 0ffbf7a718 Merge branch 'get-release-menu' into experimental 2026-10-08 09:53:38 -06:00
DeeJanuzandClaude Opus 5.5 2e293beb3a get.sh: the menu offers the experimental release; releases come from the Frametop org
A third choice installs the newest experimental release, built, so an install in the headset
needs only the short command typed on the virtual keyboard, not --release options. Releases
are looked up in Frametop/frametop, where CI builds them (Depot's runners need an
organization); FRAMETOP_REPO still overrides it, and the branches still clone from
DeeJanuz/frametop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 09:53:38 -06:00
DeeJanuz 4daa8fea5b Merge branch 'five-dot-panel' into experimental
# Conflicts:
#	gaze/README.md
#	gaze/gazecheck.py
2026-10-08 09:40:14 -06:00
DeeJanuz 78fac8ca0a Merge branch 'fix/0x1f6-pr42' into experimental 2026-10-08 09:40:02 -06:00
DeeJanuz 09cec0c980 Merge branch 'standalone-recorder' into experimental 2026-10-08 09:40:02 -06:00
DeeJanuz 325d3d91a4 Merge branch 'hand-probe' into experimental 2026-10-08 09:40:02 -06:00
DeeJanuz 48a3c0af87 Merge branch 'hands-misread' into experimental 2026-10-08 09:40:02 -06:00
DeeJanuz d7cc82ab09 Merge branch 'lighting-doc-fix' into experimental 2026-10-08 09:40:02 -06:00
DeeJanuzandClaude Opus 5.5 a4a1d8819c Gaze: the five-dot check gets its own wider, see-through panel
The quick check's 16 degree square left four of the five dots (12 degrees left and right,
9 up and down) off the panel, unseen. The five-dot check now shows in a 40 degree 4:3 panel,
see-through like quick, with the full calibration's longer notes. gazecheck.py's PANEL_DEG
mirrors the panel sizes and logs any dot that wouldn't fit. ft-gazectl and ft-gazed take
quickcal, calibrate, fitcheck, and fivecheck to open a check from a shell.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 09:40:00 -06:00
DeeJanuzandClaude Opus 5.5 e2b4eb2a81 Hand recorder: the standalone repo moved to the Frametop org
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 09:24:39 -06:00
DeeJanuzandClaude Opus 5.5 95938a1f27 Merge branch remote-displays (profiles keep remote displays; quick reset opens the profile) into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 09:22:26 -06:00
DeeJanuzandClaude Opus 5.5 9c0facd0c5 Quick reset opens the profile in use, as Open profile does
ft-layout reset reopens the profile in use (the custom arrangement with an
active profile) with use NAME, so its screens, hidden screens, remote
displays and apps all go back as the profile has them. Without one it runs
apply, as before. Meta+Shift+R and the Reset Screen Layout entry
(ft-layout-reset), the input relay's layout_reset action (a mapped mouse or
controller button), and the reset button on a screen's bar now run it.
Display Settings' Arrange now still only arranges.

Before, every quick reset ran apply, which put the desktop screens back but
left the profile's hidden screens, remote displays and apps alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 09:22:14 -06:00
DeeJanuzandClaude Opus 5.5 eaaab1ccaf Profiles keep remote displays like apps, and connect them when opened
Saving a profile records the remote displays connected then, with their
places and hidden state, the way it records the apps open then. Opening the
profile (use, open, desktop start), or arranging while it's the profile in
use, connects each of them whose host answers on Vibepollo's Web UI port (at
its address or its dongle's, as its route allows) and puts it back where it
was saved. A host that doesn't answer within 1.5 s is skipped, and its
displays stay disconnected. Like apps, displays the profile doesn't have are
left as they are: a profile connects, but never disconnects.

Before, a profile kept the places of every display that had one, connected
or not, and opening it never reconnected a display.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 09:22:09 -06:00
DeeJanuzandClaude Opus 5.5 84a354536e install-release.sh: don't take "current" for an old release; pack/trial.sh switches the live install
Found in the runtime trial (2026-10-07): the clean-up after an install loops over
releases/*/, which includes the "current" link to the release just installed, so it removed
that release's container and image, and the services it had just started kept failing until
the release was installed again. Links are skipped now.

pack/trial.sh switches this Frame to a release and back: on saves what the release's
install.sh replaces (the frametop-* units with their drop-ins and .wants links, the launcher
and menu entries, the driver's folder and SteamVR's registry, frametop.conf, the desktop's
shortcuts), moves the drop-ins aside, installs from the unpacked zip with
--no-eye-tracker --no-bluetooth, and restarts SteamVR; desktop restarts the VR desktop from
the release; status shows which container each program runs in; off puts everything back,
restarts SteamVR, and stops the release's container.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 23:31:37 -06:00
DeeJanuzandClaude Opus 5.5 14cbfc310e FrameDrop window: a keypad for the password, clicked with the controller's laser
Tested in VR with frame-testbench: laser clicks reach the install window (the password field
takes focus, a checkbox toggles), but SteamVR's keyboard doesn't come up for the field, and
opened with steam://open/keyboard its keys never reach the window (the field stayed empty,
read through accessibility). So the window brings its own keypad under each password field:
letters, digits, Shift, symbols, space, and delete, shown when Steam started the window and
toggled with a Keypad button. Checked on a virtual display with pointer clicks and
accessibility. Also: "Frametop 0.3.0-exp.0, built,:" reads "Frametop 0.3.0-exp.0:".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 23:15:05 -06:00
DeeJanuzandClaude Opus 5.5 40c7606ace Merge branch remote-displays (the host setup installs the CI build of Vibepollo) into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 22:18:52 -06:00
DeeJanuzandClaude Opus 5.5 00a377a0fb Host setup: Frametop's Vibepollo build from its CI, with WebRTC
The pinned sunshine.exe is now the frametop/2.0.0 build from Frametop/frametop-vibepollo's
CI (a84b6cfc), configured like stock 2.0.0, WebRTC included; the hand-made build it
replaces had WebRTC off. A PC with that older build gets the new one like a stock install
does, and the original exe stays the one kept for -Undo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 22:18:52 -06:00
DeeJanuzandClaude Opus 5.5 95ccaa30de Merge branch remote-displays (the fork's new address) into experimental
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 21:25:15 -06:00
DeeJanuzandClaude Opus 5.5 b655cd7446 Remote displays: the Vibepollo fork moved to the Frametop org
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 21:25:15 -06:00
DeeJanuzandClaude Opus 5.5 f0df502a23 Hands: misread guards for fine-tuned landmark models
ft-hands --misread-guard 1 (HANDS_MISREAD_GUARD=1) and ft-handreplay --misread-guard. Fine-tuned
landmark models stay sure of a hand when two hands touch, and can read the held hand as the
other side: the two cameras' views then miss by 3-4 cm, the tracker splits one off as a new
hand, the hand-over puts the old hand back onto it, the duplicate check drops the new one, and
round it goes (a contributed session, holding a card with both hands: 51 duplicates and 40
splits in 59 s with the fine-tuned models, 5 and 9 with the stock ones). With the guard, a
reading whose side is more than 0.7 off its established hand's is dropped, and a split-off view
that sits where its hand already is in that camera is dropped instead of starting a new hand:
21 duplicates and 10 splits, both hands tracked as often. Off by default: the stock model's side
calls are noisier, and the first guard costs it tracking on some recordings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 17:38:34 -06:00
DeeJanuzandClaude Opus 5.5 d4558c7187 Hand recorder docs: hand contrast isn't a daylight test
PR #6, recorded at night in a pale room, had hands nearly as faint against the room (1.22x) as
PR #5's sunlit round (1.15x). Review decides daylight from the pictures (sunlit windows, the
time of day); the contrast is supporting evidence only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 15:17:51 -06:00
DeeJanuzandClaude Opus 5.5 aef18d3601 Hand recorder: press the headset button twice to redo, hold it to stop
The headset button now has three gestures (ButtonGestures), so a session
can run with the window out of reach, as the standalone Hand Recorder's
window is in SteamVR's dashboard:
- a press: Next, pause or resume, as before. It counts once 0.45 s pass
  without a second press.
- two presses: redo, as R.
- a hold of 1.5 s: stop, as Esc, while the button is still down.

Gaps between events come from the kernel's timestamps, so two presses
read in one go still count as two. The panel's key line, the pause
note and the no-hands question say how.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 13:43:22 -06:00
DeeJanuzandClaude Opus 5.5 983a4654b3 Hand recorder: delete the window before the backend on quit
Python tore the backend down first, so every binding ran once more against null on the way out
and the log filled with "Cannot read property ... of null".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 10:33:49 -06:00
DeeJanuzandClaude Opus 5.5 85b8717bb8 Hand recorder: a dry run doesn't start the camera broker to measure the light
checkLighting started ft-camd when no ring was live, dry run or not (found porting the window
for the standalone Hand Recorder). Also drops the backend's unused standalone property.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 10:31:56 -06:00
DeeJanuzandClaude Opus 5.5 dfd1bbca0f Hand recorder: hooks for the standalone Hand Recorder
frametop-hand-recorder (a separate repo, with this one as a submodule) ships hands/ with its own
dashboard window and binaries built for the SteamOS host. A standalone.json at the top of its tree
marks it (takes.standalone()):
- session.py starts ft-hands directly instead of through distrobox, for recording and tracking
- session.json's and the manifest's tool name its build ("ft-handrec <describe> (<name> <version>)")
- the repair hints say to run its install command again (fix_hint)

ft_handrec.py takes --qml and --style for that window, and has toolVersion and standalone for it.
The Makefile passes LDFLAGS to the ft-hands links (its release links them statically), and
test_qml_backend.py checks another window with FT_HANDREC_QML.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 09:42:00 -06:00
DeeJanuzandClaude Opus 5.5 0318bb72ab ft-handtest --probe: point at the analysis script's place
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 09:19:58 -06:00
DeeJanuzandClaude Opus 5.5 3519a7a0e1 ft-handtest --probe: dots where the cutouts would land, for measuring them against Room View
A see-through test panel with dots on the wrist, middle knuckle and fingertips of each
tracked hand, one colour per timing: where the cameras saw the hand, moved ahead to now,
and moved ahead to now + the cutouts' lead. Recorded together with the headset view, they
show how far the cutouts land from the hand Room View shows, still and moving, and which
lead fits. Each tick goes to a JSON-lines log. Renderer::Marks draws the dots; Hands::Points
gives the landmarks. ft-screens' cutouts are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 09:04:52 -06:00
DeeJanuzandClaude Opus 5.5 8117a4fb7e Merge branch hand-perf (hand cutouts without waiting for the GPU) into hand-probe
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 09:00:31 -06:00
DeeJanuzandClaude Opus 5.5 891d84ae2b Hands: name the side cameras as XRService does, and bind their buffers exactly
The side cameras came out swapped on most SteamVR starts, and right on some.
Two guesses combined:

- ft-hands and camcheck.py named each video device by its TrackingCameraInit
  index (0 = slam_left). The index is only the order XRService opens the
  cameras in: on every start logged since 2026-10-04, index 0 was slam_right.
  XRService names each sensor subdev itself ("Found camera 'slam_left': ...
  v4l_subdev=/dev/v4l-subdev30"), and each TrackingCameraInit line says which
  subdev it opened. Name the devices by that; the index order stays the
  fallback for a log without those lines. The capture-pipe fallback had vfe3
  and vfe4 backwards too.

- ft-camd bound each run of XRService's buffers to a device by the sensor
  subdev opened just before it in XRService's fd table. That order changes
  when XRService restarts its cameras (17:09 today: the run after
  og01a1b 4-0060's subdev was video9's). VIDIOC_QUERYBUF on the device names
  the descriptor XRService queued at each index, from any handle, so bind runs
  by that, and split a run holding two cameras' buffers (the upper pair and the
  colour pair came as 32-buffer runs). The order stays the fallback.

Checked on the live XRService: all four tracking cameras "bound by
VIDIOC_QUERYBUF" with 16 buffers each, and ft-hands now reads
slam_left=video13 slam_right=video9. ft-hands' hands-based side check stays
as the safety net.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 17:46:22 -06:00
DeeJanuzandClaude Opus 5.5 64c4eec59f Screens: hand cutouts without waiting for the GPU
The cutout composite drew each screen's whole client buffer into a side-by-side buffer on
every tick a hand was in front of it, then waited for the GPU with glFinish (1-6 ms, the
likely cause of the VR frame drops on 2026-10-01). Now:

- A drawn buffer gets a fence and is shown from a later tick once the fence has passed, so
  ft-screens never waits for the GPU (except for a panel's first buffer after a pause, so a
  stale one never shows). The prediction lead goes from 25 to 36 ms for that tick.
- Nothing is drawn when the client frame and the cutouts haven't changed, and SteamVR
  isn't handed the same buffer again.
- When only the cutouts moved, a buffer that holds the same client frame is drawn again
  only around the old and new cutouts (scissored).
- "cutouts state" reports draws, partial draws, unchanged ticks, busy ticks, waits and CPU
  time per second since the last state; ft-handtest prints the same counts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 10:14:54 -06:00
DeeJanuzandClaude Opus 5.5 a658b80aee README: the Frametop key relay is optional and needs SHARE_KEYS=1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 16:52:49 -06:00
DeeJanuzandClaude Opus 5.5 5cc7da193c Start, stop and autostart from the settings app; work in Frametop
The settings app gets a Service group: Running starts or stops all three
units, Start at system startup enables or disables them. Disabling keeps
the repo links and never lets systemd see the unit missing (disable and
link with --no-reload, then daemon-reload): a plain disable drops
frame-voice's fd store, and with it the typing keyboard SteamVR opened,
even while the service runs.

Frametop's desktop sets its own XDG_RUNTIME_DIR, session bus and
XDG_CONFIG_HOME. Launched there, the app couldn't reach systemd or the
control socket, and saved settings to a copy the daemon never read. The
app and frame-voice-ctl now use /run/user/<uid>, and settings live in
~/.config/frame-voice/settings.json (FRAME_VOICE_SETTINGS overrides it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 16:43:38 -06:00
DeeJanuzandClaude Opus 5.5 95574d60d5 Join live dictation windows so pauses don't break sentences
Each window of live text was decoded on its own, so every pause read as a
finished sentence ("increase the. Width"), and the seam logic lost or
doubled words. Now:

- Each window is decoded after the last 1.5 s of the previous one
  (context_seconds), so a sentence that goes on is heard as one.
- Decodes are lined up with the typed words by content, not word count.
  This replaces the 1-3 word duplicate skip, which deleted a phrase said
  twice across a pause ("reset the leash pose. The leash pose ...").
- Punctuation after a pause waits for the next decode; a period is dropped
  when the next decode runs on and the word can't end a sentence.
- One word that flips between decodes no longer stalls live typing.
- A window cut without a pause commits only agreed words and carries the
  rest, since Moonshine garbles cut-off audio ("on a dot on a dot").
- Onset padding is 0.5 s plus any unflagged sound in the last second, and
  no decode passes Moonshine's ~9 s limit.

On TTS clips with pauses mid-sentence and between sentences, replayed in
real time, no mid-sentence seam got a stray period (previously 4 of 6),
and the last word of a phrase is typed 0.3-1.8 s after it is spoken.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 16:43:38 -06:00
DeeJanuzandClaude Opus 5.5 712bc10af5 Read keys of keyboards Frametop grabs, from its input relay
Frametop's input relay now grabs pass-through keyboards while typing goes
to its VR desktop, so gamescope doesn't type them into the Steam app too.
A grabbed keyboard can't be read here, so the Right Ctrl hotkey stopped
working in the desktop. The relay sends those keys to @frametop_keys as
"key <code> <value> <device name>" datagrams; frame-voice listens there and
feeds them to the same hotkey and modifier handling. The socket is
abstract, so only datagrams from our own user are accepted (SO_PASSCRED).
Keys from our own typing keyboard, which the relay grabs too, are skipped:
seen as user input, they turned the stop tap into a Ctrl shortcut.

When live typing waits for a held modifier, the log now says which key on
which device, to track down one that looks stuck.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 10:12:39 -06:00
DeeJanuzandClaude Opus 5.5 ef10d84e2f Rename to frame-voice; make wake words configurable
Everything named scarlet is now frame-voice: scripts, services
(frame-voice, frame-voice-whisper, frame-voice-vr-input), the
frame-voice-ctl and frame-voice-config commands, paths under
~/.config, ~/.local/state and the runtime dir, and the virtual keyboard.
Bindings and options move to ~/.config/frame-voice/settings.json.

Wake words are a list in settings.json, managed in the settings app
(add, remove, listening on/off). The daemon rebuilds the keyword spotter
when the list changes; any English words work. The default is
"Hey Computer".

The whisper service sets LD_LIBRARY_PATH, since the binary's RUNPATH is
the directory it was built in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 20:16:49 -06:00
DeeJanuzandClaude Opus 5.5 128d5a2035 Name the project frame-voice
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 20:06:06 -06:00
DeeJanuzandClaude Opus 5.5 7a99a2003e Local voice dictation and "Hey Scarlet" wake word for the Steam Frame
Dictation runs fully on the headset: Moonshine (sherpa-onnx, CPU) types words
live as two decodes agree, whisper.cpp (Vulkan) handles wake-word commands,
and a uinput keyboard types into whatever has focus, including SteamVR and
gamescope apps. Push-to-talk works from any keyboard or mouse button and from
Steam Frame controller buttons read through vrserver, set in a GTK 4 settings
app. Runs as systemd user services.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 19:50:32 -06:00
327 changed files with 74417 additions and 3389 deletions

No files matched your search

+3
View File
@@ -16,3 +16,6 @@
**/.env.*
frametop-report-*.txt
.frame-job.d/
# the fine-tuned hand models: the image fetches its own pinned copy (hands/models.sh)
hands/models/student/
hands/models/.student-*
+19 -5
View File
@@ -53,13 +53,19 @@ jobs:
run: |
podman run --rm --entrypoint sh "$FT_IMAGE" -c '
set -e
for p in ft-screens ft-pointer ft-powerd ft-gaze ft-gazepanel ft-stream ft-eyegrab; do
for p in ft-screens ft-spotpanel ft-pointer ft-powerd ft-gaze ft-gazepanel ft-stream ft-eyegrab whisper-server; do
test -x /opt/frametop/bin/$p
done
test -f /src/frametop/pointer/driver/build/driver_ft_pointer.so
test -x /src/frametop/hands/build/ft-camd
test -x /src/frametop/hands/build/ft-hands
test -x /src/frametop/hands/rec/build/ft-handpanel
/src/frametop/hands/models.sh check
test -x /src/frametop/pack/build/distrobox/install
/src/frametop/gaze/tracker/build/venv/bin/python -c "import numpy, cv2"
python3 -c "import PySide6"'
/src/frametop/voice/build/venv/bin/python -c "import numpy, sentencepiece, sherpa_onnx"
python3 -c "import PySide6, huggingface_hub"
command -v zstd >/dev/null'
# The FrameDrop manifest names the zip's URL in this repo's release (a fork's, in a fork).
- name: Frametop.zip
@@ -83,9 +89,17 @@ jobs:
env:
GH_TOKEN: ${{ github.token }}
run: |
pre=()
[[ $VERSION == *-* ]] && pre=(--prerelease)
pre=() notes=pack/release-notes.md
if [[ $VERSION == *-* ]]; then
pre=(--prerelease)
# get.sh --release asks for a channel and offers stable first: an experimental
# release's install line names its channel.
notes=$RUNNER_TEMP/release-notes.md
sed 's/bash -s -- --release`/bash -s -- --release --experimental`/' pack/release-notes.md >"$notes"
grep -q -- '--release --experimental`' "$notes" ||
echo "::warning::pack/release-notes.md has no get.sh --release line to mark experimental"
fi
gh release create "$GITHUB_REF_NAME" --draft --verify-tag "${pre[@]}" \
--title "Frametop $VERSION" --notes-file pack/release-notes.md --generate-notes \
--title "Frametop $VERSION" --notes-file "$notes" --generate-notes \
framedrop/build/Frametop.zip framedrop/build/frametop.framedrop.json \
framedrop/build/frametop-release.json framedrop/build/SHA256SUMS
+73 -12
View File
@@ -4,8 +4,10 @@ Frametop is a desktop for the Steam Frame that runs on the headset itself, with
- **Screens that are real monitors.** Each KDE Plasma screen has its own resolution and shape: an ultrawide in front, portrait screens beside it. Move, resize, curve, and roll them, or pin one to your wrist or your head. They come back to your layout when the desktop starts.
- **Windows that float on their own.** Take any app window off the screens into a panel of its own with Meta+Shift+F, its title bar button, or Launch as Standalone. It stays part of the desktop, so drag and drop and the clipboard still work between floating windows and the screens.
- **Your other computers' monitors.** Stream a Windows PC's or a Mac's monitors, or a virtual monitor at any size, as screens of their own, with the same controls. See [Remote displays](#remote-displays).
- **Profiles.** Save where your screens are, which ones show, and which apps are open where. Switch to a profile from Display Settings, a key, or its launcher entry, or start the desktop in one.
- **One mouse for all of SteamVR.** A Bluetooth mouse drives a small dot anchored in the room. It works the screens, the dashboard, Steam, and overlays, and hands the laser back when you pick up a controller.
- **Your hands (experimental).** Hand tracking from the headset's own cameras: poke a screen to click, pinch and grab screens to move, resize, and throw them, and see your hands over the screens.
- **Look and click (experimental).** In gaze mode the pointer goes where you look. Meta+J and Meta+K, or the mouse buttons, click and fine-tune, and each correction teaches the tracker. Calibration runs in the headset.
- **Made for long sessions.** The displays turn off when the headset isn't used, even on a stand that makes it seem worn. It stays awake on the charger, and you can reach the desktop remotely over VNC.
@@ -13,11 +15,13 @@ Two settings apps come with it: Frametop Display Settings for the screens, profi
Frametop is an independent project, not made by or affiliated with Valve.
Frametop lives at [Frametop/frametop](https://github.com/Frametop/frametop): code, releases, issues, and pull requests. It moved there from DeeJanuz/frametop on 2026-10-09; the old links and clones still work.
Join the [Frametop Discord](https://discord.gg/W3X9f7z3Bc) for questions, ideas, and help with your setup.
## Install on the headset
> **Frametop doesn't work on the SteamOS beta right now.** On the beta (SteamOS 0.4.3), gaze mode can't read the eye tracker, and the desktop has started without its taskbar ([#15](https://github.com/DeeJanuz/frametop/issues/15)). Use the stable SteamOS release until this note is gone.
> **SteamOS 0.4:** SteamOS 0.4 moved the eye tracker's data that gaze mode reads. This version of Frametop reads both SteamOS 0.3's and 0.4's, and it's tested on 0.4.5. Run `scripts/doctor.sh` after the update: it says whether the eye tracker's layout is one Frametop knows. It also says whether the update deleted the Bluetooth fixes or our eye tracker's frame grabber, which happens when they were installed by Frametop 0.3.0-exp.3 or older. Reinstall what it names (`setup/bluetooth/install.sh install`, `gaze/tracker/install.sh`). From then on they're kept through updates.
You need a Steam Frame with an internet connection, a keyboard (Bluetooth, or the on-screen one), and about 3 GB of free space.
@@ -26,12 +30,14 @@ You need a Steam Frame with an internet connection, a keyboard (Bluetooth, or th
3. Run:
```
curl -fsSL https://deejanuz.github.io/frametop/get.sh | bash
curl -fsSL https://frametop.github.io/frametop/get.sh | bash
```
It asks which version you want: stable (the `main` branch, tested releases) or experimental (the `experimental` branch, the newest features, less tested). Then it clones the repo into `~/frametop` and runs `install.sh`. To choose without the question, add `-s -- --stable` or `-s -- --experimental` after `bash`. By hand, the same is `git clone https://github.com/DeeJanuz/frametop.git ~/frametop`, then `cd ~/frametop` and `./install.sh` (add `--branch experimental` to the clone for experimental).
It asks which version you want: stable (the `main` branch, tested releases) or experimental (the `experimental` branch, the newest features, less tested). Then it clones the repo into `~/frametop` and runs `install.sh`. To choose without the question, add `-s -- --stable` or `-s -- --experimental` after `bash`. By hand, the same is `git clone https://github.com/Frametop/frametop.git ~/frametop`, then `cd ~/frametop` and `./install.sh` (add `--branch experimental` to the clone for experimental).
The installer sets up distrobox in your home folder (the system files aren't touched), a Fedora build container, and everything else. The first run downloads 1–2 GB. It asks you four things along the way: whether to install gaze mode (experimental, yes by default), our own eye tracker for it (yes by default), and the Bluetooth fixes, then whether to restart SteamVR. The eye tracker and the Bluetooth fixes need your `sudo` password; if you've never set one, run `passwd` first, or skip them for now. SteamVR has to restart once at the end, which closes everything open in VR, including the terminal. Rebooting the headset works too.
The third and fourth choices, stable release and experimental release, download Frametop already built (`Frametop.zip`, about 1.1 GB, from the [releases](https://github.com/Frametop/frametop/releases)) and install it without compiling anything. `-s -- --release` picks the stable release without the question, and `-s -- --release --experimental` the experimental one.
The installer sets up distrobox in your home folder (the system files aren't touched), a Fedora build container, and everything else. The first run downloads 1–2 GB. It asks you six things along the way: whether to install voice dictation (yes by default; it downloads about 320 MB of speech models), hand tracking (experimental, yes by default), gaze mode (experimental, yes by default), our own eye tracker for it (yes by default), and the Bluetooth fixes, then whether to restart SteamVR. Hand tracking, the eye tracker, and the Bluetooth fixes need your `sudo` password; if you've never set one, run `passwd` first, or skip them for now. SteamVR has to restart once at the end, which closes everything open in VR, including the terminal. Rebooting the headset works too.
After the restart, Launch a program → Desktop opens the multi-screen desktop, with its screens arranged around where you're facing. Frametop Display Settings and Frametop Input Settings are in the desktop's application menu, under Settings. SteamOS's own single-screen desktop is still there, as Native Desktop in the same list.
@@ -49,7 +55,7 @@ If you work in the desktop for long stretches, or leave the headset on a stand,
| Do this | To get this |
| --- | --- |
| Point near the bottom of a screen | Its controls fade in: the bar, the curve and roll buttons, and the resize tab on the corner |
| Point near the bottom of a screen | Its controls fade in: the bar, the curve and roll buttons, and, near a corner, a soft glow round it: press there and drag to resize |
| Drag the bar under a screen | Moves the screen; scroll while dragging to push it away or pull it closer. With the mouse, hold right while dragging to tilt it |
| Drag the tab on a screen's bottom right corner | Resizes the screen |
| Click the curve button (next to the bar) | Curves the screen around you, or flattens it |
@@ -58,6 +64,7 @@ If you work in the desktop for long stretches, or leave the headset on a stand,
| 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+Space, on any keyboard | Opens spotwatch, a search pill in front of you: type an app's or a remote display's name and press Enter. A running app's window spins to the front, an app that isn't running opens floating, and a remote display connects and spins to the front. Shift+Enter (or a right click) has more: a private window, a new window, docked on this screen, or one of its windows. Esc closes it. See [docs/spotwatch.md](docs/spotwatch.md) |
| 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 |
@@ -96,6 +103,22 @@ 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 |
### Remote displays
Remote displays bring another computer's monitors into Frametop. Each one is a panel with a screen's controls: move it, resize it, curve it, pin it, and save it in a profile. The mouse, the keyboard and the lasers work on it, and its sound plays on the Frame. The computer streams with Sunshine's protocol, and the Frame decodes the streams in hardware.
Each computer needs a host kit once:
| Computer | What it streams | Set up with |
| --- | --- | --- |
| Windows PC | Its monitors, and virtual monitors at any size | Vibepollo with Frametop's build: [host/windows/README.md](host/windows/README.md) |
| Mac with Apple silicon | Its monitors | Sunshine, one instance per monitor, and Frametop Streams in the menu bar to turn them on and off: [host/macos/README.md](host/macos/README.md) |
| Linux PC (Arch, CachyOS) | Its monitors, and virtual monitors | Vibepollo with Frametop's build, not tested yet: [host/linux/README.md](host/linux/README.md) |
Then, on the Frame, open Frametop Remote Displays (in the app menu, or Remote displays in Display Settings), choose Add computer, sign in with the computer's Web UI login, and pick its displays. Each display has a Connected switch, a Shown switch, and its stream's resolution, frame rate and bitrate. Meta+Space finds a remote display by name and brings it to the front. A PC with a Steam Link dongle can stream over it, which skips your router.
A monitor you stream switches to the stream's resolution while it streams (Windows), so pick a size the monitor has, or one with the same shape. A computer that's asleep can't be reached. [docs/reference.md](docs/reference.md#frametop-remote-displays) has the details.
### 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.
@@ -122,6 +145,21 @@ In gaze mode the pointer goes where you look, and the mouse or the keyboard does
By default the mouse only corrects: while the gaze has the pointer, moving the mouse does nothing until you hold a button. Each correction before a click teaches the tracker where it was off. A correction past the learning limit (55 degrees by default, about half of what you can see) starts a quick check instead. Calibrate, on the Gaze page, runs a full calibration in a panel in front of you: look at each dot and click. Check headset fit shows how well the eye tracker sees your eyes. [gaze/README.md](gaze/README.md) has the details.
### Hand tracking (experimental)
Hand tracking uses the headset's own cameras, with no controllers. The installer offers it (or run `hands/run.sh install` later; it needs `sudo` once, to let its camera broker read the cameras). Installed, it runs while the Frametop desktop does, and parks while Frametop is paused for a VR game. It uses a lot of the headset's CPU.
| Do this | To get this |
| --- | --- |
| Poke a screen with your index finger | A click there |
| Pinch a screen's bar, edge, or corner, and move | Moves or resizes the screen |
| Hold a screen like a card, or in a fist | Carries it; turn your wrist to turn it. Flick it away, or let go fast to throw it |
| Hold both hands on a screen and pull them apart | Stretches it |
| Hold an open hand out to a far screen, then make a fist and pull it back ("grab that") | Brings it to arm's reach |
| Turn a hand palm up toward your face, look at it, and pinch the ring that shows | Opens the Steam menu |
The Hands page of Frametop Input Settings sets when it runs (with Frametop, always with SteamVR, or off) and switches each hand interaction on or off, live. `ft-handsctl status` shows how it's doing. [hands/README.md](hands/README.md) has the details.
### Leave the headset on a stand and reach it remotely
To keep the Frame on and connected while you're not wearing it, for SSH, remote desktop, or anything else running on it, open the Power tab in Frametop Display Settings:
@@ -133,7 +171,7 @@ With the displays off, the headset keeps tracking and rendering, so it uses abou
## Known limitations
This is an early release, tested on one Steam Frame (SteamOS 0.3.0 build 20260922, SteamVR 2.17.10).
This is an early release, tested on one Steam Frame (SteamOS 0.4.5 build 20261007, SteamVR 2.18.2; before that SteamOS 0.3.0 build 20260922, SteamVR 2.17.10).
- 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.
@@ -157,14 +195,28 @@ In a terminal on the headset, run:
cd ~/frametop && scripts/report.sh
```
This writes `frametop-report-<date>.txt` with version numbers, service states, settings, and recent logs. Bluetooth addresses and the headset's serial number are masked. It takes up to half a minute, because it also checks gaze mode: it starts the gaze service for a moment to see whether the eye tracker sends. If gaze or its calibration doesn't work, run it while you wear the headset. `scripts/gaze-report.py` prints only the gaze part, with what looks wrong first. Then [open an issue](https://github.com/DeeJanuz/frametop/issues), describe what you did, what you expected, and what happened, and attach the file. Quick questions can go to [Discord](https://discord.gg/W3X9f7z3Bc) instead.
From a release, start in `~/.local/share/frametop/releases/current` instead of `~/frametop`.
This writes `frametop-report-<date>.txt` with version numbers, settings, service states, CPU, memory and heat, and the state and recent logs of every part: the desktop (Frametop's keyboard, the Steam menu, the screens), gaze, hand tracking (its models, cameras, and how often it sees each hand), and voice (its models and the microphone). It takes up to half a minute, because it starts the gaze service for a moment to see whether the eye tracker sends. Bluetooth addresses and the headset's serial number are masked, and what you said to Frametop Voice is left out.
To report on one part only, name it: `--system`, `--desktop`, `--gaze`, `--hands` or `--voice` (several are fine, for example `scripts/report.sh --hands --voice`).
If the problem is something you can make happen, like a window that won't drag, a pinch that doesn't register, or dictation that types nothing, add `--watch`. After the report it records for 60 seconds (`--watch 120` for longer) while you make it happen in the headset, and keeps the logs from that time:
- desktop: when the Steam menu opens and closes, which laser drags what, where typing goes, and when Frametop's keyboard opens or why it doesn't
- gaze: which eye tracker the gaze service uses, and whether its samples come in
- hands: each second, how many frames hand tracking made, how often it saw each hand, and how close the fingertips came
- voice: what Frametop Voice did (the number of words, not the words) and the microphone's level each second (no sound is kept)
- system: every 5 seconds, the CPU's load, clocks and heat, and the busiest programs
If gaze or its calibration doesn't work, run the report while you wear the headset. `scripts/gaze-report.py` prints only the gaze part, with what looks wrong first. Then [open an issue](https://github.com/Frametop/frametop/issues), describe what you did, what you expected, and what happened, and attach the file. Quick questions can go to [Discord](https://discord.gg/W3X9f7z3Bc) instead.
## Update
Run the same command again. It updates `~/frametop` to the latest of the version you have (or switches, if you pick the other one) and installs it:
```
curl -fsSL https://deejanuz.github.io/frametop/get.sh | bash
curl -fsSL https://frametop.github.io/frametop/get.sh | bash
```
Or by hand: `cd ~/frametop && git pull && ./install.sh`.
@@ -174,7 +226,7 @@ Or by hand: `cd ~/frametop && git pull && ./install.sh`.
In a terminal on the headset, run:
```
curl -fsSL https://deejanuz.github.io/frametop/uninstall.sh | bash
curl -fsSL https://frametop.github.io/frametop/uninstall.sh | bash
```
It works in two steps, so it never takes away the keyboard, mouse, or desktop you're using while it runs:
@@ -194,7 +246,7 @@ A Plasma session runs nested inside ft-screens (`screens/`), a small Wayland com
| Folder | What it is |
| --- | --- |
| `get.sh` | The one-line installer: picks stable or experimental, clones or updates the repo, and runs `install.sh`. |
| `get.sh` | The one-line installer: picks stable or experimental, clones or updates the repo, and runs `install.sh`; or installs a built release (`--release`). |
| `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. |
@@ -206,10 +258,14 @@ A Plasma session runs nested inside ft-screens (`screens/`), a small Wayland com
| `input/` | The input relay (Bluetooth mice and keyboards, button maps). |
| `pointer/` | The 3D mouse: SteamVR driver, helper service, and a probe tool. |
| `power/` | ft-powerd: turns the displays off while the headset isn't used. |
| `voice/` | Frametop Voice: dictation and wake words, recognised on the headset; the input relay types the text. See [voice/README.md](voice/README.md). |
| `gaze/` | Gaze mode (experimental): the gaze service, its calibration panel, our own eye tracker, and the gaze probe. See [gaze/README.md](gaze/README.md). |
| `hands/` | Hand tracking (experimental, deferred: the installer doesn't offer it). See [hands/README.md](hands/README.md). |
| `hands/` | Hand tracking (experimental): the camera broker and the tracker. See [hands/README.md](hands/README.md). |
| `display-settings/`, `input-settings/` | The two settings apps (Kirigami, Python). |
| `remote/` | Frametop Remote Access, the app that turns remote desktop over VNC on and off. |
| `remote-displays/` | Frametop Remote Displays, the app that adds other computers' monitors as screens. |
| `stream/` | ft-stream, one per remote display: receives and decodes its stream for ft-screens. |
| `host/` | The host kits for remote displays: Windows, macOS and Linux. |
| `setup/` | The build container and the Bluetooth fixes. See [setup/README.md](setup/README.md). |
| `scripts/` | Helpers the installers use. They run commands locally on the Frame, or over SSH from a PC. |
@@ -254,4 +310,9 @@ Programs built in the `dev` container link against its glibc, which is newer tha
## License
MIT. See [LICENSE](LICENSE).
MIT. See [LICENSE](LICENSE). The rendered hands' 3D models in `screens/assets/hands` (see its [README](screens/assets/hands/README.md); each folder has its licence) are from:
- the W3C Immersive Web Working Group's WebXR Input Profiles, `generic-hand` (MIT, Copyright (c) 2019 Amazon), the default;
- Babylon.js's hand meshes by Patrick Ryan, https://github.com/BabylonJS/Assets (CC BY 4.0, https://creativecommons.org/licenses/by/4.0/), unchanged;
- the Mixed Reality Toolkit: MRTK3's OpenXR hand (BSD-3-Clause, Copyright (c) 2025, Mixed Reality Toolkit Contributors) and MRTK2's rigged hand (MIT, Copyright (c) Microsoft Corporation), converted to glTF;
- Godot XR Tools' hands by DigitalN8m4r3 (Miodrag Sejic), CC0 1.0.
+49 -4
View File
@@ -10,8 +10,9 @@ the dev container:
1920x1080 worth of pixels, rotation for portrait.)
- Visibility (ft-screens): when the screens show (always, only with the SteamVR
dashboard open, while you look at a controller, or only when toggled), the wrist
angle within which a pinned screen shows, and pinning each screen to a wrist or
your head.
angle within which a pinned screen shows, pinning each screen to a wrist or your
head, and whether the desktop's notifications go to the Steam session
(NOTIFY_FORWARD, session/ft-notifyfwd; its state from its log).
- Layout: a preset (curved or flat, rows, distance, gap, height) or a named layout
saved from where the screens are, with a preview; arrange now; save the current
arrangement under a name; rename and delete; arrange automatically when the
@@ -62,6 +63,8 @@ FT_POWERD = "\0ft_powerd"
# nothing was saved.
STEAM_SLEEP_AC_DEFAULT = 3600
SCALES = [0.75, 1.0, 1.25, 4 / 3, 1.5, 1.75, 2.0]
NOTIFY_FORWARD = ("auto", "on", "off") # session/ft-notifyfwd; frametop.conf's NOTIFY_FORWARD
NOTIFYFWD_LOG = "/tmp/frametop-notifyfwd.log" # its last line is its state (/tmp is the host's)
ROTATIONS = [("normal", "Landscape"), ("left", "Portrait"), ("right", "Portrait (flipped)")]
@@ -121,6 +124,7 @@ class Backend(QObject):
self._steam_busy = False
self._steamDone.connect(self._steam_done, Qt.QueuedConnection)
self._pins = [] # each running screen's pin: none | left | right | head
self._notify_state = ""
self.poll = QTimer(interval=3000, timeout=self._check_running)
self.poll.start()
self._check_running()
@@ -133,8 +137,10 @@ class Backend(QObject):
return cast(conf.get(key, default))
except ValueError:
return default
notify = conf.get("NOTIFY_FORWARD", "auto")
return {"screens": num("SCREENS", 2, int), "width": num("WIDTH", 1920, int),
"height": num("HEIGHT", 1080, int), "physWidth": num("PHYS_WIDTH", 1.6)}
"height": num("HEIGHT", 1080, int), "physWidth": num("PHYS_WIDTH", 1.6),
"notifyForward": notify if notify in NOTIFY_FORWARD else "off"}
def _check_running(self):
# The session's own Wayland socket (host processes' environments aren't readable
@@ -142,12 +148,15 @@ class Backend(QObject):
running = os.path.exists(f"/run/user/{os.getuid()}/frametop/wayland-0")
count = self._screens_running() if running and ft_layout.backend() == "screens" else 0
pins = self._read_pins(count)
if running != self._running or count != self._running_count or pins != self._pins:
notify_state = self._read_notify_state() if running else ""
if (running != self._running or count != self._running_count or pins != self._pins
or notify_state != self._notify_state):
if running != self._running or count != self._running_count:
self._started = self._conf() if running else {}
self._running = running
self._running_count = count
self._pins = pins
self._notify_state = notify_state
self.changed.emit()
self._check_powerd()
@@ -159,6 +168,22 @@ class Backend(QObject):
pins.append(f[16] if len(f) > 16 else "none")
return pins
@staticmethod
def _read_notify_state():
"""ft-notifyfwd's: forwarding | waiting (no usable server on the user bus) | "" (not running)."""
try:
with open(NOTIFYFWD_LOG) as f:
lines = f.read().splitlines()
except OSError:
return ""
# the last state line: errors it logs in between (a failed Notify) don't change it
for line in reversed(lines):
if line == "ft-notifyfwd: forwarding":
return "forwarding"
if line.startswith("ft-notifyfwd: not forwarding"):
return "waiting"
return ""
def _ask_screens(self, text):
"""Request/reply to ft-screens; None if it isn't running."""
try:
@@ -383,6 +408,26 @@ class Backend(QObject):
def toggleScreens(self):
self._ask_screens("toggle")
# --- the desktop's notifications in the Steam session (session/ft-notifyfwd) ---
@Property(str, notify=changed)
def notifyForward(self):
return self._conf()["notifyForward"]
@Property(str, notify=changed)
def notifyForwardState(self):
return self._notify_state
@Property(bool, notify=changed)
def notifyRestartNeeded(self):
"""The session writes ft-notifyfwd's autostart entry when it starts."""
return self._running and bool(self._started) and self._started["notifyForward"] != self._conf()["notifyForward"]
@Slot(str)
def setNotifyForward(self, mode):
if mode in NOTIFY_FORWARD:
write_conf_value("NOTIFY_FORWARD", mode)
self.changed.emit()
# --- ft-screens: visibility and pinning ---
@Property("QVariantMap", notify=changed)
def visibility(self):
+54
View File
@@ -958,6 +958,60 @@ Kirigami.ApplicationWindow {
+ "your head where you let go. Choosing a pin above keeps the screen where it is now, so place "
+ "it first. Save as profile… (Layout) keeps pins."
}
Kirigami.FormLayout {
Layout.fillWidth: true
Kirigami.Separator { Kirigami.FormData.isSection: true; Kirigami.FormData.label: "Notifications" }
Repeater {
model: [
{ value: "auto", text: "Show them in the Steam session", help: "The desktop's notifications go to the Steam session's notification server, such as one that shows them in VR, with their buttons. Plasma's own popups stay off meanwhile; its history keeps them. Not to SteamOS's own server, which can't show them on the Frame." },
{ value: "on", text: "Always send them to the Steam session", help: "Whatever serves notifications there, SteamOS's own server too, which can't show them on the Frame: they're lost then." },
{ value: "off", text: "Keep them in the desktop", help: "Plasma shows them on the desktop's screens." }
]
delegate: ColumnLayout {
required property var modelData
spacing: 0
// "on" can lose them (SteamOS's server): set in frametop.conf, shown only then
visible: modelData.value !== "on" || backend.notifyForward === "on"
Controls.RadioButton {
text: modelData.text
checked: backend.notifyForward === modelData.value
onToggled: if (checked) backend.setNotifyForward(modelData.value)
}
Controls.Label {
text: modelData.help
opacity: 0.7
font: Kirigami.Theme.smallFont
leftPadding: Kirigami.Units.gridUnit * 1.6
wrapMode: Text.Wrap
Layout.maximumWidth: Kirigami.Units.gridUnit * 26
}
}
}
Controls.Label {
Kirigami.FormData.label: "Now:"
visible: backend.desktopRunning
text: backend.notifyForwardState === "forwarding" ? "In the Steam session"
: backend.notifyForwardState === "waiting" ? "In the desktop: the Steam session has no notification server that can show them"
: "In the desktop"
wrapMode: Text.Wrap
Layout.maximumWidth: Kirigami.Units.gridUnit * 26
}
RowLayout {
visible: backend.notifyRestartNeeded
Controls.Label {
text: "Applies when the desktop starts again."
wrapMode: Text.Wrap
}
Controls.Button {
text: "Restart desktop"
icon.name: "system-reboot"
onClicked: restartDialog.open()
}
}
}
}
}
}
+22 -6
View File
@@ -74,7 +74,7 @@ In a game, Frametop's panels work like SteamVR's own floating windows: point a c
- Disabling a nested output keeps its host window. `Output::applyChanges` only flips `enabled`, KWin stops rendering it (no more commits), and Plasma drops its desktop view. So ft-screens keeps the same toplevel, and its screen numbers stay put. Enabling the output again resumes on the same toplevel.
- Each output's host window is titled `KDE Wayland Compositor WL-<n>`, with `- Output disabled` appended while it's disabled (`WaylandOutput::updateWindowTitle`, on every `enabledChanged`). ft-screens reads the title to tell screens (`WL-0` to `WL-<SCREENS-1>`) from spares, and to see a spare turn on and off.
- A spare resized while it's disabled comes up at the new size on its first frame, so floating a window needn't blink. Outputs with gaps between them are accepted, so ft-floatd places spares apart from the screens and from each other, within Xwayland's 32767-pixel limit.
- A spare resized while it's disabled comes up at the new size on its first frame, so floating a window needn't blink. Outputs with gaps between them are accepted, so ft-floatd places spares apart from the screens and from each other: a grid below them, 4000 logical pixels a cell. Xwayland's coordinates are the layout's times its largest output scale, and they wrap past 32767, so an X11 window on a spare past that took no clicks (Brave on the 4th spare at x 27000 and scale 1.25 sat at x -31506; KWin still focused it). The grid ends at 20000 for 16 spares, within the limit up to scale 1.6.
- KWin keeps a Wayland popup inside its parent's output (`XdgPopupWindow::updateRelativePlacement` uses the output's placement area), and X11 apps place their menus within the monitor. That's why a floating window's output has a margin around the window: menus and dropdowns open past the window's edges, into the margin.
- KWin makes a nested output the size it's configured to times its scale, rounded (at 1.5 it lays out 1067 × 667 on a 1600 × 1000 buffer), and gives the buffer a whole buffer scale (1.2 becomes 2). A buffer whose size isn't a multiple of that is a protocol error that disconnects KWin, so ft-floatd sizes spares in multiples of it. After a scale change, ft-floatd asks for the output's size again in the new scale's terms, or the next configure would make it the old size times the scale.
- **Virtual outputs don't work.** `createVirtualOutput` makes an output window but never adds it to the backend's `m_outputs`, so `findOutput()` returns null when the pointer enters it, and the next line dereferences it (`Q_ASSERT` is compiled out). A click on such a panel would crash KWin. This rules out virtual outputs (`stream_virtual_output`) for floating windows without a patched KWin.
@@ -117,7 +117,13 @@ Driver poses are in SteamVR's raw tracking space, and client programs work in th
Frametop's SteamVR clients (ft-pointer, ft-screens, ft-gaze) connect as a background app first and switch to an overlay app only once that works. `VR_Init` as an overlay app starts vrserver itself when none is running, and one started that way from the dev container never finds the headset. At a boot where the gamescope session timed out, systemd dropped `steamvr.service`'s start job, the pointer service (ordered only `After=` it) started anyway, and its vrserver made every SteamVR launch fail with `HmdNotFound`. SteamOS's health check then kept resetting the Steam client and tried to fall back to the previous OS slot. The units also say `Requisite=steamvr.service`, so they don't start at all when SteamVR's start fails.
The driver starts disconnected, because holding the right-hand role while SteamVR starts leaves the Steam UI stuck on its loading icon. It connects when the mouse is used and claims the right hand. SteamVR keeps a hand role reserved for a disconnected device that still asks for it, so the driver switches its role hint between right hand (connected) and opt-out (not connected).
The driver starts disconnected, because holding the right-hand role while SteamVR starts leaves the Steam UI stuck on its loading icon. It connects when the mouse is used. With a hand role (`POINTER_ROLE=right`, the default before the treadmill role) it claims that hand: SteamVR keeps a hand role reserved for a disconnected device that still asks for it, so the driver switches its role hint between the hand (connected) and opt-out (not connected). The treadmill role (below), now the default, needs no switching.
#### Treadmill role
With a hand role, a Frame controller held in that hand takes the role back (its touch sensors count as use), and the virtual controller is left with no role and no clicks. So mixing a controller in one hand with the 3D mouse or a bare hand's ray in the other fails whenever that controller is merely held. The treadmill role (4) is no hand: the real controllers keep both hand roles, and the virtual controller never fights them. It held the dashboard laser in the gaze-first tests (2026-09-30, branch `gaze-first`), with two conditions. SteamVR gives a device the `/user/treadmill` path only when the device is added, so the driver must hint the role from `Activate`, not on connect: the `role` in its `default.vrsettings` (or `driver_ft_pointer/role` in SteamVR's settings), and switching it needs a SteamVR restart. And the compositor binding needs `/user/treadmill` entries next to the hand ones (`ft_pointer_vrcompositor.json`). A treadmill reports no controller role (`GetControllerRoleForTrackedDeviceIndex` is invalid), so the helper's "no hand role" release skips it. The laser claim (`/input/a`, bound to `switchlaserhand`) works the same; SteamVR took the laser back to our device 11-15 ms after a controller took it.
A treadmill can't move SteamVR's own floating windows by their grab bars, though: SteamVR's dashboard (a web page in vrwebhelper) starts a window's move in `UndockedOverlay.startFloatingWindowMove`, which reads the pressing device from the mouse event's CapsLock and NumLock bits (head, left hand, right hand) and, for anything else, logs "mouse event carried no input path" and does nothing. Clicks and resizes don't ask, so only moves broke, from 2026-10-09, when treadmill became the default (found 2026-10-13, SteamVR 2.18.2; with role 2 the same laser moved them). `pointer/dashpatch` puts that back. `treadmill-move.js` wraps the grab bar's handler: a press with no device runs it as the right hand, with that one pose query answered by `/user/treadmill`, and the move then follows `/user/treadmill`. `ft-dashpatch.py run` (`frametop-dashpatch.service`, started with SteamVR) puts it into the dashboard over the Chrome DevTools Protocol, again whenever the page is new, and checks every 30 s that it's still in. The dashboard's debugger is off unless `VRWebHelper/DebuggerEnabled` is on; the installer turns it on (`ft-dashpatch.py on`, from SteamVR's next start) on port 8089, bound to 127.0.0.1. Not the usual 8087: SteamOS's `steamvr-web-debug-portforward.service` forwards 0.0.0.0:8088 to 127.0.0.1:8087, which would open the dashboard to the network. Like Steam's own debugger on 8080, any local program can use it. The uninstaller turns it off again if Frametop turned it on. The patch finds the handler by its name and React by its module, so a SteamVR update that renames them leaves windows unmovable for the treadmill again, without breaking anything else; `ft-dashpatch.py status` shows whether it's in and how many moves it made.
### The cursor
@@ -160,7 +166,7 @@ Keyboards aren't grabbed by default, because a grabbed keyboard's keys went into
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.
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. Until 2026-10-10, `SHARE_KEYS=1` sent a grabbed keyboard's keys to `@frametop_keys` as datagrams for frame-voice. It was 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 got every key typed into the desktop, passwords included. Now frame-voice is part of Frametop (Frametop Voice), and the relay does its keyboard side itself: its push-to-talk key is a key combination, and its text comes to the relay as `type TEXT`, taken only from the relay's own user (`SO_PASSCRED`), and goes where typing goes, like a keyboard's keys: to ft-screens for the desktop, or the virtual keyboard for Steam, never both. Its own uinput keyboard went with it, so SteamVR no longer has to have opened a second keyboard for dictation to reach games.
A mouse button that pointer mode passes through as a key (a side button for Back) is a pointer button to ft-screens, not a key, so it goes to the screen the pointer is on rather than where typing goes. As a key, its release was lost whenever typing moved while it was held (the dashboard closing, a click on another panel, a pause), and wlroots counts presses per button: from then on that button, the lasers' left click included, did nothing in the desktop, and KWin kept it held. So ft-screens tracks the relay's buttons itself, lets a release through whenever it took the press, and releases them when the pointer leaves the screens, its screen hides, or Frametop pauses.
@@ -168,7 +174,7 @@ Volume keys must never reach gamescope. With the openvr backend, gamescope sends
Frametop's keyboard opens by itself for a text field on the desktop. The apps run inside the nested KWin, so only KWin knows when a text field has focus, and the way it tells anyone is its input method protocol (`zwp_input_method_v1`): KWin starts one input method program and activates it whenever the focused app turns on text input. `input/ft-textinput` is that program, speaking the Wayland wire protocol directly so it needs nothing but Python on the host. It only reports focus. The gamescope session puts `QT_IM_MODULE=xim` and `GTK_IM_MODULE=xim` in the systemd user environment; with those, Qt and GTK apps use X input methods and never turn on Wayland text input, so the session script drops them.
The keyboard itself is ft-screens' own panel (`screens/keyboard.cpp`). We tried SteamVR's first (`ShowKeyboardForOverlay`), and on the Frame it doesn't fit a desktop. It's Steam's own panel (`valve.steam.gamepadui.keyboard`), which SteamVR mounts in the dashboard's scene, so with the dashboard closed it opened but wasn't drawn. Placing it in the room ourselves (`SetKeyboardTransformAbsolute`) made it show, but SteamVR moves it to whichever overlay the laser goes to and mounts it again, and while it's open the controllers switch to SteamVR's own laser. Our panel is an overlay like the screens' controls: any laser or the 3D mouse clicks it, nothing moves it, and its keys go out as key presses on ft-screens' seat rather than as text handed back to the input method. So nothing typed leaves ft-screens (a socket to the input method could be claimed by any local process, like `@frametop_keys`), apps without text input (X11, Electron) take the keys too, and they mean what the desktop's keyboard layout says. It's drawn on the CPU and uploaded with `SetOverlayRaw` when a key's look changes; the labels come from stb_truetype, so the container needs no text rendering stack.
The keyboard itself is ft-screens' own panel (`screens/keyboard.cpp`). We tried SteamVR's first (`ShowKeyboardForOverlay`), and on the Frame it doesn't fit a desktop. It's Steam's own panel (`valve.steam.gamepadui.keyboard`), which SteamVR mounts in the dashboard's scene, so with the dashboard closed it opened but wasn't drawn. Placing it in the room ourselves (`SetKeyboardTransformAbsolute`) made it show, but SteamVR moves it to whichever overlay the laser goes to and mounts it again, and while it's open the controllers switch to SteamVR's own laser. Our panel is an overlay like the screens' controls: any laser or the 3D mouse clicks it, nothing moves it, and its keys go out as key presses on ft-screens' seat rather than as text handed back to the input method. So nothing typed leaves ft-screens (a socket to the input method could be claimed by any local process, as the old `@frametop_keys` could), apps without text input (X11, Electron) take the keys too, and they mean what the desktop's keyboard layout says. It's drawn on the CPU and uploaded with `SetOverlayRaw` when a key's look changes; the labels come from stb_truetype, so the container needs no text rendering stack.
The Frame controllers can be mapped like mouse buttons, but they aren't input devices on the host: they reach SteamVR over the headset's own radio, and no evdev or hidraw node exists for them. So only a SteamVR client can read them. Overlay apps normally get controller input only while they have input focus, which a background helper never has. SteamVR's experimental global action set priority (`steamvr/globalActionSetPriority`, "Enable global input from overlays") lets an overlay's action set receive input anyway, and takes the inputs it binds from the scene app. Binding every button would take them all from games, so the helper's action manifest puts each button in an action set of its own, and it activates only the sets of mapped buttons. The mapping itself stays in the relay, which does the action, so mice and controllers share one list of actions.
@@ -188,6 +194,16 @@ The fallback registry does not exit merely when its bus disconnects in the isola
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.
### Notifications outside the desktop
The private bus keeps the desktop's notifications in it: apps notify Plasma, and Plasma's popups appear on the desktop's screens, whose panels may be hidden, or behind a VR game. Putting the desktop on the user bus instead would collide with the Steam session: Steam owns `org.freedesktop.ScreenSaver` there, the Steam session's portals and accessibility bus are there, Plasma would start its parts as units of the user's systemd and push its environment (`DISPLAY`, `WAYLAND_DISPLAY`, its runtime directory) into the bus's and systemd's activation environment, which programs started later in the Steam session would inherit.
`session/ft-notifyfwd` forwards instead. Taking `org.freedesktop.Notifications` from Plasma isn't reliable: plasmashell, the bus's "D-Bus master", registers it with `ReplaceExistingService` and `DontAllowReplacement` (plasma-workspace's `libnotificationmanager/server_p.cpp`), so another owner only keeps it by starting first, and loses it to a Plasma restart in between. Plasma 6.2.5 has a watcher API for this: `org.kde.NotificationManager.RegisterWatcher` on Plasma's notification object, after which Plasma calls `org.kde.NotificationWatcher.Notify` (its own id first, then the spec's arguments with the body as sent and the app's hints, image data included) and `CloseNotification` on the watcher's `/NotificationWatcher`, and `InvokeAction(id, key)`, which makes Plasma emit `ActionInvoked` to the app. The app only accepts that signal from its notification server's owner, which is why a click has to go back through Plasma. The helper copies each notification to the user bus's server keeping the hints' D-Bus types, maps the two servers' ids (a replacement reuses Plasma's), and maps that server's `ActionInvoked` to `InvokeAction`. Its `NotificationClosed` with reason 2 (dismissed) closes the notification in Plasma, so the app sees it closed (as revoked, reason 3); an expired one stays in Plasma's history. While it forwards, it holds an `Inhibit` on Plasma, which turns its popups off as Do not disturb does, and ends with the helper's connection; watchers get every notification regardless. It follows both servers' owners: it registers and inhibits again when Plasma restarts, and in `auto` mode checks `GetServerInformation` whenever the user bus's server changes. SteamOS's `steam_notif_daemon` reports itself as `simple_notif_daemon`; it passes notifications to `~/.steam/root/ubuntu12_32/steam` with a `steam://open_xdg_notification` URL, an x86 program that can't run on the Frame, and the Frame's Steam client ignores that URL anyway, so forwarding there would lose them. The helper is event-driven (GLib's main loop, PyGObject), so it costs nothing between notifications, and exits when the desktop's bus closes.
Notifications sent through the notification portal (`org.freedesktop.portal.Notification.AddNotification`, as Flatpak apps do) reach the watchers too: xdg-desktop-portal-kde passes them to Plasma's `Notify`. Plasma sends no activation token with `InvokeAction`, so KWin's focus stealing prevention may keep a window that an action raises from coming to the front. KDE's inline reply needs the `inline-reply` capability from the other server; without it, it's an action like any other.
Run the isolated checks on the host with `/usr/bin/python3 session/test/test_notifyfwd.py`. Two private buses stand in for the desktop's and the user bus, with a fake Plasma (the watcher API, Inhibit) on one and a fake notification server on the other. They check forwarding with the hints' types, actions coming back, dismissed and expired notifications, replacements and closes mapping ids, `auto` skipping `simple_notif_daemon` until another server replaces it and giving Plasma its popups back when none is left, registering again after a Plasma restart, exiting with the desktop's bus, and doing nothing outside the Frametop desktop.
### 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.
@@ -200,7 +216,7 @@ A podman container's monitor process (conmon) stays in the cgroup of whatever st
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.
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`. Steam's entry (`steam -silent`, from steamdeck-kde-presets) reached the running Steam client as a command line it ran (`ExecCommandLine` in its console log), since the desktop starts from Steam; SteamOS 0.4 added `-vrdisable -deckard` to it, for Desktop Mode, where Plasma starts Steam itself. The session hides all three 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. Before each repair the file is backed up to `<file>.ft-bak.last`. `<file>.ft-bak` keeps it as it was before the first repair and is never overwritten. The repair writes over a moved panel's old screen number, so the backups are the only record of it, and `.ft-bak.last` also keeps everything changed since the first repair. 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.
@@ -231,7 +247,7 @@ Hiding the screens during a game kept them out of view, but Frametop kept using
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.
`scripts/update-check.py`, which `scripts/doctor.sh` runs, checks what it can directly: that SteamVR still serves every OpenVR interface version the installed programs were built against (read from the binaries), that `vrcmd`'s format still parses, that the eye tracker's shared memory still has a layout ft-gaze knows (stable's, or the 0.4.x beta's, with every field from the timestamp on 5 bytes later), by the same test ft-gaze uses to pick one, and the host files, services, sockets, and driver registration. Behavior can't be checked without someone in the headset, so it records the versions of the packages that matter once things work (`--mark-good`), and after an update names what changed and what to try by hand.
`scripts/update-check.py`, which `scripts/doctor.sh` runs, checks what it can directly: that SteamVR still serves every OpenVR interface version the installed programs were built against (read from the binaries), that `vrcmd`'s format still parses, that the eye tracker's shared memory still has a layout ft-gaze knows (SteamOS 0.3's, or 0.4's, with every field from the timestamp on 5 bytes later), by the same test ft-gaze uses to pick one, and the host files, services, sockets, and driver registration. Behavior can't be checked without someone in the headset, so it records the versions of the packages that matter once things work (`--mark-good`), and after an update names what changed and what to try by hand.
## Approaches we dropped
+2 -2
View File
@@ -28,7 +28,7 @@ The numbers are cited in the code, so they stay as they are. Struck-out text was
| # | Question | Decision |
|---|---|---|
| 1 | How many windows can float at once | 8 spare outputs by default, configurable with `FLOAT_SLOTS` (at most 16); a change needs a desktop restart. A Display Settings control isn't built |
| 1 | How many windows can float at once | 16 spare outputs by default (also the most), configurable with `FLOAT_SLOTS`; a change needs a desktop restart. A Display Settings control isn't built |
| 2 | Menus and dropdowns | Each floating output has a margin around the window. The panel shows only the window, and each open popup gets a small overlay of its own, cut from the same buffer |
| 3 | Tearing off | Not built. Drag the title bar past a screen's edge and let go in the air, with a small dead zone past the edge |
| 4 | Docking by dragging | Not built. Push the window flush against a screen (within about 10 cm), with the landing spot highlighted, and let go |
@@ -73,7 +73,7 @@ Alternatives considered:
### Where the extra outputs come from: spare outputs
KWin's nested backend opens its outputs at start (`--output-count`). The session starts KWin with the screen count plus `FLOAT_SLOTS` outputs (default 8, at most 16). ft-floatd turns off the spares nothing floats on with `kscreen-doctor` once it starts. Floating a window enables a spare, and docking the window disables it again. `FLOAT_SLOTS` limits how many windows can float at once, and changing it means restarting the desktop. How KWin's nested backend treats disabled outputs, and why its virtual outputs can't be used instead, is in [design.md](design.md#floating-windows).
KWin's nested backend opens its outputs at start (`--output-count`). The session starts KWin with the screen count plus `FLOAT_SLOTS` outputs (default and most 16). ft-floatd turns off the spares nothing floats on with `kscreen-doctor` once it starts. Floating a window enables a spare, and docking the window disables it again. `FLOAT_SLOTS` limits how many windows can float at once, and changing it means restarting the desktop. How KWin's nested backend treats disabled outputs, and why its virtual outputs can't be used instead, is in [design.md](design.md#floating-windows).
ft-screens creates a `screen` for each toplevel in the order they appear, and indexes its settings by that order. Spares come after the screens, so they get indices `SCREENS` and up. Their panels are hidden while their output is disabled.
+87
View File
@@ -0,0 +1,87 @@
# Hands while typing on a real keyboard
Branch `hands-typing` (2026-10-10). The problem, from the user's headset session that day (hand
tracking with student-v10a): typing on the real keyboard made hands click (pinches, middle pinches,
grips, pokes), and the hand ray took the pointer from the mouse or the gaze during or right after
typing.
## What the logs showed (2026-10-10)
Sources: `journalctl --user -u frametop-pointer` (the helper), `-u frametop-hands`, `-u
frametop-input-relay`, and the four flags the user said "flag that" for
(`frame-hands/captures/flags/flag-20261010-145753`, `-145841`, `-145857`, `-150115`: 16 s of hands
in the head frame plus head poses). Keys aren't logged anywhere, so how long after a key a gesture
came is known only as "within 1 s" (the old guard's "ignored (no ray up; typing)") or not.
- The old guard (`POINTER_PINCH_TYPING`, 1 s) caught 23 pinches today (09:12-09:42 and
14:59-15:02), always "no ray up" ones. It never looked at ray pinches, middle pinches, grips,
ft-screens' pokes and grabs, or the ray showing.
- 14:57:10-14:57:30, typing into a text field on the TK-KB006 keyboard (connected 14:56:27, field
focused 14:56:34): 11 pinches became "no ray up: a press where the pointer is, on nothing" and 2
more were "ignored (a press is already held)". All began at 1.7-2.0 cm (deliberate pinches read
0.4-1.0 cm), so typing thumbs. None was within 1 s of a key: typing pauses are longer than that.
- 14:57:37 the right hand's ray came up ("hand ray: none -> right (raised)") with the hand on the
keyboard, and at 14:57:38 a typing pinch became a ray press on `frametop.remote.103.bar`, held
1.89 s. Flag 145753 shows that moment: both palms 0.29-0.33 m under the eyes, 0.26-0.34 m ahead,
palms down (0.90-1.00 of the normal pointing down), 0.17-0.22 m apart. The knuckles sat 0.29-0.31 m
under the eyes, right at the ray's "raised" limit (0.30 m to show).
- 15:00:37 and 15:02:24: two more presses at the pointer between "ignored (typing)" pinches.
- 15:01:15 (flag 150115): both hands typing at 0.40-0.42 m under the eyes, 0.18-0.21 m ahead, palms
down 0.84-0.97, 0.15-0.16 m apart; the right hand rose, gripped, dragged a panel, then came back
to 0.28 m under the eyes, palm down 0.84, and a ray pinch clicked `frametop.screen.1`.
- Flags 145841 and 145857 are deliberate ray use: the pointing hand 0.15-0.30 m under the eyes and
0.33-0.46 m ahead, palm anywhere from sideways to down; the other hand resting low (0.41-0.52 m
under the eyes, -0.1 to 0.2 m ahead), 0.35-0.6 m away.
- "pinch right: left to ft-screens (the hand is near its panel)" bursts (14:58:26-14:58:42,
09:14:51-09:15:02) are hands near a low panel; with typing nearby those are ft-screens' to judge.
The hand recorder's desk take (PR #3, `frame-hands/dumps/pr3-04-desk-work`, head poses known):
| phase | palms under the eyes | ahead | palm down | apart | height difference |
| --- | --- | --- | --- | --- | --- |
| typing | 0.36-0.39 m | 0.22-0.29 m | 0.85-0.99 | 0.17 m (p90 0.40) | 0.00-0.01 m |
| mouse (one hand on the keys) | 0.38-0.41 m | 0.21-0.29 m | 0.82-0.99 | 0.41 m | 0.00-0.02 m |
| switching | 0.37-0.40 m | 0.21-0.29 m | 0.82-1.00 | 0.17-0.41 m | 0.00-0.02 m |
Deliberate gestures in the same recording (`pr3-03-gestures`): the hand 0.0-0.10 m under the eyes,
0.26-0.37 m ahead. The touch take (`pr3-06-touch`, low dots) had the touching hand 0.24-0.30 m
under the eyes, palm down 0.7-0.9, but 0.10-0.17 m higher than the other hand.
So typing hands sit anywhere from 0.29 to 0.42 m under the eyes depending on the desk and chair,
which is also where deliberate gaze pinches with the elbow resting sit (0.35-0.45 m): no fixed
height tells them apart. What does: both hands down together (level within a few cm, 0.15-0.25 m
apart, palms down), and a hand that types rising well above where it typed when it's meant.
## What the branch does
`pointer/helper/typing.h` (tests: `pointer/tests/typing-test.cpp`) decides, per side, whether typing
holds a hand back; the pointer helper feeds it the relay's keys and each hands frame, and ft-screens
hears the result (`typing <L> <R>` on @ft_screens).
- Keys: for `POINTER_PINCH_TYPING` (2 s, was 1) after a key, every hand is held back, except one
that has left the keyboard or is busy out of the keyboard zone (its ray up, a gesture held:
pointing with one hand and pressing Enter with the other).
- On the keyboard: a hand in the keyboard zone (palm at least `POINTER_TYPING_BELOW`, 0.2 m, under
the eyes, 0.05-0.45 m ahead, palm down) while typing is parked, and stays held back through any
pause until it rises `POINTER_TYPING_RAISE` (0.08 m) above where it typed, or turns its palm up,
for 0.1 s. Freed, it works at once, keys or not. A hand on the mouse beside the keyboard is parked
too once a key comes (its pinches are mouse clicks). Unseen 3 s, it's forgotten.
- The posture: both hands in the zone, level within 8 cm and at most 32 cm apart, for
`POINTER_TYPING_POSTURE` (0.3 s), is typing before any key, within `POINTER_TYPING_RECENT` (600 s)
of a key. Without that limit, both hands resting on a desk would hold gaze pinches back.
- Held back: no pinch, middle pinch or grip (ray, gaze or plain) in the helper; no ray (an owner
drops the pointer to the mouse or the gaze, "hand ray: right -> none (typing)"); no poke, near grab
or fingertip cursor in ft-screens. A gesture already held carries on.
Replaying the four flags and the PR #3 takes through typing.h (`/tmp` driver, not in the repo; the
flags have no keys, so a key a minute before the window was assumed):
| recording | result |
| --- | --- |
| flag 145753 (typing, the ray click at 14:57:38) | both hands parked by the posture 0.3 s into the window, held back 98% of it; the 14:57:38 pinch came 0.27 s into the window, before the replay's posture (live, the hands had been on the keys since 14:57:10) |
| flag 150115 (typing, then the right hand up for a grip, a drag and a click) | posture at once; the right hand freed by its raise (0.18 m), its grip and two pinches allowed; the left held back 98% |
| flags 145841, 145857 (deliberate ray use, the other hand low) | nothing held back, all 11 pinches allowed |
| desk take, keys during the typing prompt | typing, mouse and switching: both hands held back 100% |
| desk take, no keys | the posture alone: typing 84-100%, mouse phase: the mouse hand free (0.41 m from the other hand) |
| gestures take (pinches, grabs, pointing) | nothing held back |
| touch take (low dots) | the posture took both hands while they waited low; the touching hand freed by its first raise, then held back 9% |
+1 -1
View File
@@ -25,6 +25,6 @@ ft-screens drops keys while no screen has focus or the SteamVR dashboard is open
## Typing and grabbed keyboards
- **Programs that watch every keyboard lose grabbed ones.** While typing goes to the desktop, the relay grabs pass-through keyboards, so a hotkey tool reading them directly stops seeing their keys. `SHARE_KEYS=1` in `~/.config/frametop.conf` sends their keys to the abstract socket `@frametop_keys` instead. It's off by default: abstract sockets have no permissions, and any local process that binds the name first receives every key typed into the desktop, passwords included.
- **Programs that watch every keyboard lose grabbed ones.** While typing goes to the desktop, the relay grabs pass-through keyboards, so a hotkey tool reading them directly stops seeing their keys. Bind the tool's key as a Frametop key combination that runs a command (`command:CMD`) instead: the relay sees every keyboard. Frametop Voice's push-to-talk key works this way. (Until 2026-10-10, `SHARE_KEYS=1` sent every key typed into the desktop to the abstract socket `@frametop_keys`, which any local process could bind first.)
- **Typing starts out going to Steam.** After the desktop starts, keys go to Steam until you click a screen.
- **Controller clicks don't move typing.** Overlay apps don't see controller clicks on other panels, so after one typing stays where it was. A mouse click, or a click on a screen, moves it.
+3 -1
View File
@@ -6,7 +6,8 @@ A profile is a named layout that also opens apps. It holds:
- where each screen goes, with its size in metres, curve, roll, and pin (what a named layout held before profiles);
- which screens show and which are hidden;
- the apps, one entry per window: on a screen at a place and size, or floating at a pose, size, and scale.
- the apps, one entry per window: on a screen at a place and size, or floating at a pose, size, and scale;
- the remote displays connected when it was saved, each with its place and whether it's hidden ([remote-displays.md](remote-displays.md)). Opening the profile connects them, if their computer answers, and puts them back. Like its apps, it leaves other displays connected.
So a "Work" profile can put three screens around you with a browser, two terminals, and an editor on them, and a "Couch" profile can hide every screen and float one video player in front of you.
@@ -50,5 +51,6 @@ So a "Work" profile can put three screens around you with a browser, two termina
- **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 quick reset.** Meta+Shift+R, the reset button on a screen's bar, the Reset Screen Layout menu entry, and a button mapped to Reset desktop screen layout run `ft-layout reset`: with a profile in use (`active`, and the custom arrangement), that's `use` on it again, so everything goes back as the profile has it. Without one, it's `apply`.
- **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.
- **Display Settings.** On the Layout & profiles page, the arrangement list has the profiles, which can be renamed and deleted. Open profile and Save as profile… are the page's actions. A profile's apps are listed with where each goes and a button to leave one out, plus which screens it hides. Start in profile picks the one the desktop starts with. The Visibility tab's Screens shown switches hide screens one at a time.
+65 -22
View File
@@ -30,7 +30,9 @@ kwriteconfig6 --file ~/.config/frametop/kwinrc --group Plugins --key contrastEna
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.
The desktop's notifications can show outside it, in the Steam session. Plasma there runs on the desktop's own D-Bus, so its popups only appear on the desktop's screens. `session/ft-notifyfwd` (Plasma's autostart; log: `/tmp/frametop-notifyfwd.log`) hands each one to the notification server on the user bus, the one the Steam session's apps use, for example a VR notification server that draws them as panels. Its buttons work: a click there reaches the app as if made in Plasma, and dismissing it there closes it in Plasma. While it forwards, Plasma's own popups are off (do not disturb, held by "frametop"), and Plasma's notification history still has every one. `NOTIFY_FORWARD` in `~/.config/frametop.conf` (or Notifications on the Visibility & pins tab of Frametop Display Settings) sets it: `auto` (the default) forwards only when the user bus's server isn't SteamOS's own `steam_notif_daemon`, which hands notifications to a Steam client that can't show them on the Frame, so with stock SteamOS nothing changes; `on` forwards to any server, SteamOS's too, where they're lost (it's in the file only; the settings app shows it while it's set); `off` keeps them in the desktop. Restart the desktop after a change. Notifications Flatpak apps send through the notification portal go along too. KDE's inline reply shows as a plain Reply button there; see [design.md](design.md#notifications-outside-the-desktop).
Three 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, IBus (`ibus`), which can't reach the desktop's apps because KWin's input method is `input/ft-textinput`, and Steam (`steam`), which is already running. The session script puts copies with `Hidden=true` in `~/.config/frametop/autostart` once (marked in `frametoprc`; Steam's was added later and is hidden once on desktops that already had the other two), 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.
@@ -47,8 +49,8 @@ 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`).
- `.resize`, the handle on a corner, sets the size from there, the opposite corner staying put (a screen keeps its aspect; a floating window gets that many pixels). It sits on the bottom right, and goes to whichever corner a laser, the gaze or a hand's pinch comes near, brightening as it comes; lit blue while resizing. Screens go down to 15 cm wide.
- `.reset`, left of the bar, is the quick reset, like Meta+Shift+R (`ft-layout reset`): with a profile in use it opens that profile again, as Open profile does, and otherwise it puts every screen back in its layout around where you are now.
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.
@@ -68,7 +70,7 @@ In the last three modes the hotkey shows the screens anyway. A screen can also b
- 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. 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, a keyboard's media keys (its Consumer Control node), and any key a pointer device passes through. A mouse button passed through as a key in pointer mode (a side button for Back) goes to the screen the pointer is on instead, wherever typing goes, and only while the pointer is on a screen that shows and Frametop isn't paused. Its release always goes through, and ft-screens releases it itself when the pointer leaves the screens, its screen hides, or Frametop pauses (`scripts/test-relay-buttons.sh` checks this offline). 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.
Input from the lasers reaches KWin through ft-screens' own seat. Keys come from the input relay: from pass-through keyboards, a keyboard's media keys (its Consumer Control node), and any key a pointer device passes through. A mouse button passed through as a key in pointer mode (a side button for Back) goes to the screen the pointer is on instead, wherever typing goes, and only while the pointer is on a screen that shows and Frametop isn't paused. Its release always goes through, and ft-screens releases it itself when the pointer leaves the screens, its screen hides, or Frametop pauses (`scripts/test-relay-buttons.sh` checks this offline). 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; bind its key as a key combination with a command instead (Frametop Input Settings, Keyboard). Frametop Voice types its text through the relay the same way, so it lands where typing goes. Hidden screens don't take typing.
Frametop's keyboard opens by itself when a text field on the desktop gets focus, and stays open until its Close key, a layout reset, or a mapped button closes it (or, with Keep it open off in Frametop Input Settings, until the text field loses focus). While the Steam menu (the dashboard) or Steam's own keyboard is up, it steps aside, and it comes back where it was when they're gone; one asked for meanwhile appears then. In the "only with the dashboard" visibility mode, the dashboard doesn't count. It doesn't open without a head pose (the headset in standby). It's a panel of keys (a US laptop layout, with Esc where Caps Lock would be, arrows, and a Close key) that ft-screens shows 0.7 m in front of you and below your eyes, facing you. It stays where it opened, and its grab bar (the pill along the top) moves it like a screen's. Type on it with a controller's laser or the 3D mouse. Shift, Ctrl and Alt latch for the next key, and a held key repeats. KWin starts `input/ft-textinput` as the desktop's input method, and KWin activates it whenever the focused app turns on text input for a field. It tells the relay (`textfield 1` or `0`), the relay decides by the Keyboard setting in Frametop Input Settings, and ft-screens opens the keyboard for the screen that has keyboard focus (`vrkeyboard show`, `hide`, or `toggle` from a mapped button). Its keys reach the focused screen as key presses, so it works in every app, but only apps that use Wayland text input (Qt, GTK, Firefox) open it by themselves; Chromium, Electron and X11 apps need the button. The session drops the `QT_IM_MODULE=xim` and `GTK_IM_MODULE=xim` that the gamescope session sets, or Qt and GTK apps wouldn't use Wayland text input either.
@@ -83,13 +85,18 @@ get N screens head state key code value scale N s vrkeyboard s
visibility always|dashboard|gesture|toggle wrist degrees gesture left|right degrees
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
cutouts matte circle|mesh|capsules cutouts margin deg [ms [deg]] cutouts shift off|spec cutouts roomview auto|on|off
hands L R allowed handinput on|off|force|state palmmenu on|off|state grabthat on|off|state
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
spin next|prev|DEGREES|to N front N spotwatch on|off
```
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.
`spin` is the lazy susan. By default it brings panels to a front slot at reading distance and leaves the rest where they are: `next` and `prev` bring the next one round on the right or left (the one in the slot goes home), and `to N` brings panel N. With `SCREEN_SPIN_BRING=0` in `~/.config/frametop.conf` it turns every panel in the room about your head instead: `next` and `prev` bring the next one on the right or left to straight ahead, and `to N` turns the short way to panel N. Either way, a number of degrees turns the room that far. Typing goes to the panel that ends up in front. `front N` gives panel N the typing where it is, as a spin to it would. `spotwatch on`, renewed every second, gives spotwatch's search the typing, and `spotwatch off` gives it back ([Spotwatch](#spotwatch)).
`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`), and sets their matte, its margin and the per-distance correction (hands/README.md, "Hand cutouts and near input"); they cut only with Room View on, detected or forced (`cutouts roomview`, hands/README.md "Rendered hands"). `hands` is the pointer helper's word on hand input (each side `hand`, `controller` or `off`, and whether it's allowed now); `handinput` turns near input on (following that word), off, or on without it, and `handinput state` reports what each hand is doing, its counts (presses, one-frame presses, pinch clicks, grabs by card and fist, poke attempts and those refused, crossings off the content, presses at the edge, flicks and throws, holds through tracking loss, second hands joining a held panel, pinches that waited to become fists, buttons pinched) and what held presses back; each press, release, refused poke and grab also goes to ft-screens' log as a `hands:` line. `palmmenu` turns the palm menu (a bare hand palm up, pinch: the Steam menu) on and off, and `palmmenu state` reports it. `grabthat` turns "grab that" (an open hand held out to a panel farther than arm's reach, then a fist pulled back: it comes to arm's reach) on and off, and `grabthat state` reports each hand's state, its counts and the panels that came. 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
@@ -115,9 +122,10 @@ A mouse drives SteamVR the way a controller's laser does, but shows up as a smal
- The input relay, in pointer mode (`POINTER=1`), sends mouse motion, clicks, and scrolling to the helper. A deliberate movement or a click wakes the pointer, and 30 seconds without mouse input releases it.
- The helper, `pointer/helper/ft-pointer`, runs in the `dev` container as `frametop-pointer.service` and starts with SteamVR. It keeps the cursor, tests it against every visible overlay, draws the dot, and sends the driver an exact pose.
- The driver, `pointer/driver/` (`ft_pointer`), is loaded by SteamVR. It's an invisible virtual right-hand controller whose laser follows the cursor.
- The driver, `pointer/driver/` (`ft_pointer`), is loaded by SteamVR. It's an invisible virtual controller whose laser follows the cursor. It takes the treadmill role, no hand, so the real controllers keep theirs and one can be used beside it (`POINTER_ROLE` and the driver's `role` setting; see docs/design.md, "Treadmill role").
- The dashboard patch, `pointer/dashpatch/` (`frametop-dashpatch.service`, starts with SteamVR), lets that treadmill move SteamVR's own windows by their grab bars, which SteamVR allows only for the head or a hand. It goes into SteamVR's dashboard page through the dashboard's debugger, which the installer turns on at 127.0.0.1:8089 (`VRWebHelper/DebuggerEnabled`; the uninstaller turns it off). `pointer/dashpatch/run.sh status` shows whether it's in.
Whichever device you used last wins. Picking up a controller hands the laser back at once, and moving the mouse takes it again. When the headset comes off, the pointer lets go, so the displays can sleep, and it stays off until you're wearing the headset again.
Whichever device you used last wins. Picking up a controller hands the laser back at once, and moving the mouse takes it again. With hand interaction (`POINTER_HANDS=1`), this goes per hand: a controller used recently wins its hand, and the other hand can stay bare. When the headset comes off, the pointer lets go, so the displays can sleep, and it stays off until you're wearing the headset again.
To move a floating panel, left-drag its grab bar. The scroll wheel pushes and pulls it while you drag. Hold the right button while dragging and move the mouse to tilt the panel around the grab point; the right press isn't sent as a click. The tilt stays for the rest of the drag, and releasing the left button drops the panel as it is. A mapped Toggle dashboard button wakes the pointer if needed and holds the virtual system button for 0.12 s, because SteamVR ignores a press and release in the same instant. Open Steam menu / close dashboard (`steam_menu`) needs no pointer: `steam/ft-steam menu` asks Steam's UI, over its debugging port (`steam/steamui.py`), to show its dashboard overlay and focus the Steam frame's menu, or to hide the dashboard if it's up.
@@ -125,20 +133,22 @@ To move a floating panel, left-drag its grab bar. The scroll wheel pushes and pu
pointer/driver/build.sh && pointer/driver/install.sh install # then restart SteamVR
pointer/helper/build.sh && pointer/helper/run.sh install
pointer/helper/run.sh status | log | restart
pointer/driver/install.sh probe # devices, hand roles, who owns the dashboard pointer
pointer/driver/install.sh probe # devices, hand roles, activity, charging, who owns the dashboard pointer
pointer/probe/build.sh # probes: vrprobe, lasertest (who has the laser), ctlnoise (controller noise)
```
The pointer settings are in `~/.config/frametop.conf`: `POINTER_SENSITIVITY`, `POINTER_IDLE`, `POINTER_WAKE_COUNTS`, `POINTER_CONTROLLER_PICKUP`, `POINTER_DISTANCE`, `POINTER_CURSOR_DEG`, `POINTER_ORIGIN_FRACTION`, `POINTER_ORIGIN_MARGIN`, `POINTER_SCENE_RADIUS`, `POINTER_EDGE_REACH`, `POINTER_LASER_WIDTH`, `POINTER_IGNORE`, the head follow settings `POINTER_FOLLOW`, `POINTER_LEASH_DEG`, `POINTER_LEASH_DELAY`, `POINTER_LEASH_RETURN`, and `POINTER_FOLLOW_REACH`, and the gaze mode settings `POINTER_GAZE`, `POINTER_GAZE_RETAKE`, `POINTER_GAZE_NUDGE_MAX`, `POINTER_GAZE_HOLD`, `POINTER_GAZE_DOT`, `POINTER_GAZE_SHOW`, `POINTER_GAZE_MOUSE`, `POINTER_GAZE_MOUSE_MOVE`, and the keyboard clicks' `POINTER_HEAD_DEADZONE` and `POINTER_KEY_TAP`, and the gaze service's `GAZE_TRACKER` (`auto`, the default: our own eye tracker when it's installed, else SteamVR's; or `own` or `steam`) and `GAZE_EYE` (the eye bias). The example config explains each. Frametop Input Settings changes them live; after editing the file by hand, restart the relay or the helper (the gaze service reads its two again when the file changes).
The pointer settings are in `~/.config/frametop.conf`: `POINTER_SENSITIVITY`, `POINTER_IDLE`, `POINTER_WAKE_COUNTS`, `POINTER_CONTROLLER_PICKUP`, `POINTER_DISTANCE`, `POINTER_CURSOR_DEG`, `POINTER_ORIGIN_FRACTION`, `POINTER_ORIGIN_MARGIN`, `POINTER_SCENE_RADIUS`, `POINTER_EDGE_REACH`, `POINTER_LASER_WIDTH`, `POINTER_IGNORE`, the head follow settings `POINTER_FOLLOW`, `POINTER_LEASH_DEG`, `POINTER_LEASH_DELAY`, `POINTER_LEASH_RETURN`, and `POINTER_FOLLOW_REACH`, and the gaze mode settings `POINTER_GAZE`, `POINTER_GAZE_RETAKE`, `POINTER_GAZE_NUDGE_MAX`, `POINTER_GAZE_HOLD`, `POINTER_GAZE_CONTROL_HOLD`, `POINTER_GAZE_DOT`, `POINTER_GAZE_SHOW`, `POINTER_GAZE_MOUSE`, `POINTER_GAZE_MOUSE_MOVE`, and the keyboard clicks' `POINTER_HEAD_DEADZONE` and `POINTER_KEY_TAP`, and the gaze service's `GAZE_TRACKER` (`auto`, the default: our own eye tracker when it's installed, else SteamVR's; or `own` or `steam`), `GAZE_EYE` (the eye bias), and `GAZE_FIT_WATCH` (the put-on check and the slip note, off by default: [gaze/README.md](../gaze/README.md), "Headset fit"). The example config explains each. Frametop Input Settings changes them live; after editing the file by hand, restart the relay or the helper (the gaze service reads its three again when the file changes).
## Frametop Input Settings
A Kirigami app with a Python backend, in the Plasma menu under Settings. It runs in the `dev` container and talks to the relay over its control socket, `@frametop_relay`. It has nine 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 ten 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, 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`.
- 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.
- 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 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. With Frametop Voice installed, a Right Ctrl tap starts and stops dictation too. A tap is a press with no other modifier held, then a 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. Tapping a left modifier binds either side's; tapping a right one (Right Ctrl) binds that key alone. 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.
- Voice has Frametop Voice's settings (see Voice dictation): on or off, the dictation keys (set on the Keyboard page), the controller buttons and their mode, typing as you talk, sounds, and the wake word and its phrases. They're saved in `~/.config/frametop-voice.json`, and the service applies them within 2 seconds.
- 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.
@@ -148,7 +158,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 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.
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, or a button mapped to Reset desktop screen layout. With a profile in use, these open it again, the same as Open profile: its screens, hidden screens, remote displays and apps. Arrange now in the app arranges the screens (and the profile's remote displays) without reopening its apps or hiding its hidden screens again.
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.
@@ -156,7 +166,7 @@ Frametop Display Settings has four tabs (three with the gamescope backend, which
- Screens: add and remove screens, and set each one's resolution (presets from 1080p to 4K, ultrawide, super ultrawide, portrait, or custom), its width in VR (0.5 to 6 m), its scale, whether it's curved, and whether it has the taskbar. Resolution, width, and curve apply at once. Adding or removing a screen takes a desktop restart, which the app offers.
- Layout (the Layout & profiles page): the Arrangement list starts with two presets: Curved around you, with the screens hinged edge to edge like monitors on a desk and each turned to face you, and Flat wall. Both take rows, distance, gap, and height, and Arrange now applies them. Save as profile… saves where the screens are now (positions, sizes, curves, and pins), which ones are hidden, and the open apps and where their windows are, under a name. Profiles are listed in Arrangement after the presets: pick one and Open profile switches to it, and the buttons next to the list rename or delete it. Below it, Apps lists the profile's windows and where they go, and Leave out drops one. A profile saved with fewer screens than you have now leaves the others where they were saved last, or where the preset would put them. Start in profile picks the profile the desktop starts in; with None, a switch turns auto-arrange at startup on or off. A preview shows the layout from above and from the front. See [profiles.md](profiles.md).
- Visibility & pins: the visibility, game, and controller settings described above, the wrist angle, where each screen is pinned (in the room, a wrist, or your head), and buttons to pin all screens or unpin them.
- Visibility & pins: the visibility, game, and controller settings described above, the wrist angle, where each screen is pinned (in the room, a wrist, or your head), and buttons to pin all screens or unpin them. Its Notifications section sets `NOTIFY_FORWARD` (whether the desktop's notifications show in the Steam session, see [The desktop](#the-desktop)), shows where they go now, and offers a desktop restart after a change.
- Power: when the displays turn off while the headset isn't used, their state now, Turn displays off now (to try it), and Stay awake while plugged in. See [Displays off and sleep](#displays-off-and-sleep).
`layout/ft-layout` does the arranging. It's a Python script that uses only the standard library and runs on the host:
@@ -181,7 +191,7 @@ The layout is stored relative to your head when it's applied. `/run/user/<uid>/f
## Frametop Remote Displays
Other computers' monitors as Frametop screens (ft-screens only), streamed from Vibepollo with Moonlight's protocol. Frametop Remote Displays (`remote-displays/`, also opened by the Remote displays button on Display Settings' Screens page) finds Vibepollo computers on the network, signs in to one with its Web UI login (it keeps a narrow API token, not the password, and pins the host's certificate), shows whether it answers, and adds its displays: its monitors, or a virtual one at any size. A computer with a Steam Link dongle on the Frame's hotspot streams over it (Connection: auto, network or dongle only); the others use the network. Each display has a Connected switch (and the host one for all of its displays), Shown, its stream's resolution, frame rate and bitrate, and its width in VR. A disconnected display keeps its settings, and within the same desktop run, its place. In VR each one is a panel with a screen's controls, and profiles keep where they are. See [remote-displays.md](remote-displays.md).
Other computers' monitors as Frametop screens (ft-screens only), streamed from Vibepollo or Sunshine with Moonlight's protocol. Frametop Remote Displays (`remote-displays/`, also opened by the Remote displays button on Display Settings' Screens page) finds Vibepollo and Sunshine computers on the network, signs in to one with its Web UI login (it keeps a narrow API token, not the password, and pins the host's certificate), shows whether it answers, and adds its displays: its monitors, or a virtual one at any size. A computer with a Steam Link dongle on the Frame's hotspot streams over it (Connection: auto, network or dongle only); the others use the network. Each display has a Connected switch (and the host one for all of its displays), Shown, its stream's resolution, frame rate and bitrate, and its width in VR. On Windows, a monitor switches to its stream's resolution while it streams (or its closest mode with the same shape), and back when the stream ends. That takes Frametop's build `frametop-2.0.0-2` or newer; `frametop-2.0.0-1` scaled the monitor's own resolution into the stream. A disconnected display keeps its settings, and within the same desktop run, its place. In VR each one is a panel with a screen's controls, and profiles keep where they are. See [remote-displays.md](remote-displays.md).
```
layout/ft-layout remote list # the remote displays and their streams' state
@@ -189,13 +199,15 @@ layout/ft-layout remote connect|disconnect ID...
remote-displays/install.sh # its menu entry
```
On the PC, `host/windows/Setup Frametop host.cmd` sets it up for Frametop: Vibepollo 2.0.0 (installed if missing), Frametop's build of its `sunshine.exe`, the settings Frametop needs, the Web UI login you sign in with from the Frame, and a firewall check (`-Check` to see what it would change, `-Undo` to put things back).
On the PC, `host/windows/Setup Frametop host.cmd` sets it up for Frametop: Vibepollo 2.0.0 (installed if missing), Frametop's build of its `sunshine.exe`, the settings Frametop needs, the Web UI login you sign in with from the Frame, and a firewall check (`-Check` to see what it would change, `-Undo` to put things back). [host/windows/README.md](../host/windows/README.md) has the steps, and the [`windows-host-1`](https://github.com/Frametop/frametop/releases/tag/windows-host-1) release has the kit as a zip. A Linux PC (Arch or CachyOS) installs Frametop's Vibepollo package with Vibepollo's installer, as [host/linux/README.md](../host/linux/README.md) says; it hasn't been tested yet.
On a Mac, `host/macos/frametop-host-setup.sh` (or `Setup Frametop host.command`) installs Sunshine and runs one instance per real display, each on its own port (47989 + 100·N), started at login. You allow Sunshine Screen Recording and Accessibility once in System Settings. Without Accessibility the Frame's pointer moves on the Mac but clicks, scrolling and typing don't arrive; the setup checks both, and offers to ask again if Accessibility is missing. Remote Displays finds the Mac as one computer; signing in with the Web UI login pairs the displays you pick, and the password isn't kept, so adding more later signs in again. Macs have no virtual displays (`--check`, `--undo` as on the PC). Frametop Streams in the menu bar turns each display on or off with a click, or all of them, and `ft-sunshine off|on|status` does the same in Terminal. Off lasts through logins until on. [host/macos/README.md](../host/macos/README.md) has the steps for setting up a Mac, and the [`macos-host-1`](https://github.com/Frametop/frametop/releases/tag/macos-host-1) release has the kit as a zip.
## Floating windows
A desktop window can float in VR as a panel of its own, away from the screens. Meta+Shift+F floats the window under the pointer (or the active one, over the wallpaper), or puts it back on its screen if it floats. So do Float in VR in every window's menu (Alt+F3; Back to Desktop on a floating one), the button left of Close in its title bar, and a mouse button, controller button, or key combination mapped to Float window in VR in Frametop Input Settings; Put all floating windows back is mappable too. Launch as Standalone, in an app's right-click menu in the Application Launcher or the taskbar, starts the app with its first window floating, where that app last floated or in front of you. [floating-windows.md](floating-windows.md) explains how it works.
`float/ft-floatd` does this. It runs inside the desktop's Plasma session (log: `/tmp/frametop-floatd.log`), loads the KWin script `float/frametop-float.js`, and moves each floating window to a spare KWin output of its own, which ft-screens shows as a panel cropped to the window. The settings are in `~/.config/frametop.conf`: `FLOAT_SLOTS` is how many windows can float at once (8, at most 16; 0 turns floating off; restart the desktop after a change), and `FLOAT_MARGIN` the pixels around each window on its output, so menus have room past its edges (300). Each app's last floating place, size, and scale are kept in `~/.config/frametop-float.json` by desktop file name, relative to the primary screen, so they move with the screens. `FT_FLOAT_DEBUG=1` in ft-floatd's environment logs every event from the KWin script.
`float/ft-floatd` does this. It runs inside the desktop's Plasma session (log: `/tmp/frametop-floatd.log`), loads the KWin script `float/frametop-float.js`, and moves each floating window to a spare KWin output of its own, which ft-screens shows as a panel cropped to the window. The settings are in `~/.config/frametop.conf`: `FLOAT_SLOTS` is how many windows can float at once (16, the most; 0 turns floating off; restart the desktop after a change), and `FLOAT_MARGIN` the pixels around each window on its output, so menus have room past its edges (300). Each app's last floating place, size, and scale are kept in `~/.config/frametop-float.json` by desktop file name, relative to the primary screen, so they move with the screens. `FT_FLOAT_DEBUG=1` in ft-floatd's environment logs every event from the KWin script.
With floating on, the session gives the desktop's windows Frametop's own decoration (`decoration/`): Breeze's look plus the float button. Apps that draw their own title bar, like Chromium and Electron apps, don't have the button. `decoration/apply.sh` puts a changed copy into the running desktop, and `decoration/apply.sh --off` goes back to Breeze until the next desktop start.
@@ -207,6 +219,20 @@ float/ft-float launch org.kde.dolphin # start an app (its desktop file name) flo
float/ft-float run COMMAND [ARG...] # the same for a command
float/ft-float close ID # close a window
float/ft-float list # the spare outputs and what floats on them
float/ft-float launch firefox action=new-private-window # one of the app's own actions, floating
float/ft-float launch org.kde.dolphin screen=2 # its first window docked on screen 2
float/ft-float activate ID # make a window the active one, unminimized
```
## Spotwatch
Meta+Space opens spotwatch, a search pill straight ahead of where your head points, for apps and remote displays (`{host} - {display}`). Tab, Shift+Tab, and the arrow keys move through what it finds, and Enter or a click opens it. A running app's most recent window spins to the front with the lazy susan. An app that isn't running starts floating. A remote display connects if needed and spins to the front. Shift+Enter or a right click opens an item's menu: an app's own actions (a private window), Open new window, Open docked on this screen, and its windows; a remote display's Go to and Disconnect. Esc, Meta+Space again, or a click elsewhere closes it. It's the `spotwatch` action in Frametop Input Settings, bindable to mouse and controller buttons too, and opened that way it brings Frametop's keyboard. [spotwatch.md](spotwatch.md) has the decisions and how it works.
`spotwatch/ft-spotwatch` runs inside the desktop's Plasma session (log: `/tmp/frametop-spotwatch.log`) and runs the pill, `ft-spotpanel` (built by `screens/build.sh`), in the container. While the search is open, ft-screens sends it every key. Use counts are in `~/.config/frametop-spotwatch.json` and icons in `~/.cache/frametop/spotwatch`.
```
spotwatch/test/spotwatch-test.py # the ranking and the search against a fake ft-screens and ft-floatd (offline)
spotwatch/tools/render.py OUT.png # the panel's picture, without a headset
```
## Displays off and sleep
@@ -237,7 +263,7 @@ Paused, Frametop leaves the headset's CPU and GPU to a VR game. The input relay
- 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, releasing any click still held on it (a mouse button, a mapped controller button, or a key combination), 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.
- The relay lets go of the 3D mouse, releasing any click still held on it (a mouse button, a mapped controller button, or a key combination), 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, dictation, 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.
@@ -258,6 +284,23 @@ input/test/pause-buttons-test.py # a click held into a pause comes up, 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.
## Voice dictation
Frametop Voice (`voice/`, [voice/README.md](../voice/README.md)) types what you say where you type, recognised on the headset; nothing leaves it. `voice/ft-voiced` runs in Frametop's container as `frametop-voice.service` (installed by `voice/run.sh install`, which `install.sh` offers, yes by default), starting at login. It records with `pw-record` and transcribes live with Moonshine on the CPU; `frametop-voice-whisper.service` (whisper.cpp on the GPU) runs only while the wake word is on, for its commands. Its models, about 320 MB, are downloaded on install into `~/.local/share/frametop/voice/models` (`voice/models.sh`: fixed URLs, checked by sha256).
The input relay does the keyboard side. Dictation's keys are key combinations with the actions `dictate` (a press starts or stops) and `dictate_hold` (records while held); with Frametop Voice installed, the default key combinations add a Right Ctrl tap (`"97": "dictate"`, Right Ctrl alone: a right-hand modifier's own code is that key's tap only). Like every tap, it doesn't count with another modifier held, or with a key, click or scroll in between. The relay sends `toggle|start|stop <source>` to `@frametop_voice`, and dictation works while Frametop is paused. ft-voiced sends its text back as `type TEXT` on `@frametop_relay`; the relay types it, one key every 4 ms on a US layout, to ft-screens while typing goes to the desktop, otherwise on its virtual keyboard for Steam and games, and holds a character back while a modifier is held. Both sockets take these only from their own user. Frame controller buttons (left d-pad down, held, by default) are read by ft-voiced itself from vrserver's web socket (`input/vrws.py`), so games still get them.
Frametop Input Settings' Voice page turns it on and off and sets the controller buttons and their mode (hold or press to toggle), typing as you talk, sounds, and the wake word (off by default) and its phrases, in `~/.config/frametop-voice.json`; the keys are on its Keyboard page. Wake word commands that run a program, and advanced settings, are edited in that file by hand (voice/README.md).
```
voice/build.sh && voice/run.sh install
voice/run.sh status # the services, and ft-voiced's state as JSON
voice/ft-voice toggle # start or stop dictation; also start, stop, cancel, type TEXT, wake on|off, events
voice/run.sh log
voice/models.sh check # every model's sha256
voice/test/test_daemon.py # typing through a stand-in relay, push-to-talk, offline
```
## 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. 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.
@@ -269,16 +312,16 @@ In gaze mode the 3D mouse's pointer goes where you look, and the mouse or the ke
[gaze/README.md](../gaze/README.md) has the details, our own eye tracker, and the gaze probe, a development tool.
## Hand tracking (experimental, deferred)
## Hand tracking (experimental)
Deferred: it costs a lot of the headset's CPU and needs more work, so `install.sh` doesn't offer it. It still builds and runs, installed by hand, for working on it.
It costs a lot of the headset's CPU. `install.sh` offers it (yes by default, `--no-hands` skips it, and it needs `sudo` for ft-camd's file capabilities), and a release brings `ft-camd` and `ft-hands` built in its image. Installed, it runs while the Frametop desktop does (`HANDS_MODE=frametop`).
Your hands show over the screens: where a tracked hand is between an eye and a screen, ft-screens lets that eye see the room through the screen. The same tracker detects pinches and grips, and with `POINTER_HANDS=1` in `~/.config/frametop.conf` they work the pointer. In gaze mode a pinch clicks where you look when it opens; hold it and move the hand to correct the pointer first. Without gaze mode a pinch is a press like the mouse's button, so a held pinch drags. A grip (closing the hand) presses and drags. To install it: `hands/run.sh install`.
Your hands show over the screens: where a tracked hand is between an eye and a screen, ft-screens lets that eye see the room through the screen (a round hole per hand, `HANDS_MATTE=circle`; `mesh` and `capsules` are the older shapes). ft-handview (`frametop-handview.service`) draws your hands as a 3D hand model posed by the tracking: over games and the void with Room View off, and over the hole with it on (`HANDS_VIEW_ROOMVIEW=1`, the default). `HANDS_VIEW_MODEL` picks the model: `asset` (the default), `babylon`, `mrtk3`, `godot`, `mrtk2`, `robot` (a robot hand built in code from the tracked skeleton: light shells, dark joints, cyan accents), or `capsules` for the older tubes; `HANDS_VIEW_STYLE=ghost|solid` the look. The models, in `screens/assets/hands` with their licences: the WebXR Input Profiles' generic hand (`asset`; MIT, Copyright (c) 2019 Amazon), Babylon.js's hand meshes by Patrick Ryan (`babylon`; CC BY 4.0, https://github.com/BabylonJS/Assets), MRTK3's OpenXR hand (`mrtk3`; BSD-3-Clause, Copyright (c) 2025, Mixed Reality Toolkit Contributors), Godot XR Tools' hands by DigitalN8m4r3 (`godot`; CC0 1.0) and MRTK2's rigged hand (`mrtk2`; MIT, Copyright (c) Microsoft Corporation). The same tracker detects pinches and grips, and with `POINTER_HANDS=1` in `~/.config/frametop.conf` they work the pointer. In gaze mode your eyes aim and your hands click, Vision Pro style: a pinch clicks where you were looking as it began, and the hand ray stays off (`POINTER_GAZE_HAND_RAY=1` brings it back beside the gaze). Pinch, hold and move the hand a few centimetres to nudge the pointer slowly onto the target, then let go to click there; the correction teaches the gaze tracker, as the mouse's do. Pinch and hold still for half a second to press and drag with the hand. A middle pinch right-clicks the same way. Hold a pinch with one hand and pinch with the other to hold both buttons, left and right, each until its pinch opens. Without gaze mode a pinch is a press like the mouse's button, so a held pinch drags. A grip (closing the hand) presses and drags. To install it: `hands/run.sh install`. With `POINTER_HANDS=1` and gaze mode off, a bare hand raised and pointing also shows a ray that drives the pointer like a controller's laser (a pinch clicks, a middle pinch right-clicks or scrolls, reaching out and in pushes and pulls a carried panel), a controller used recently takes over its own hand only, and during a paused VR game hand tracking is parked rather than stopped, waking when the dashboard opens. Details: [hands/README.md](../hands/README.md), "Pinches and grips in the pointer". When tracking goes wrong, `ft-handsctl flag [note]` (or a voice command through frame-voice, "flag that") saves the last 12 seconds of hand crops and what the tracker made of them for the offline tools: ft-hands keeps them in RAM (`HANDS_FLAG_BUFFER=1`, about 50 MB), the drawn hands pulse cyan when a flag is taken (`HANDS_FLAG_FLASH`, `HANDS_FLAG_TONE`), and flags go to `HANDS_FLAG_DIR`. See [hands/README.md](../hands/README.md), "Flags".
- `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`. The Hand Recorder's installer (`hands/rec/install.sh`) sets them the same way. `hands/run.sh uncaps` takes them back while neither the services nor the Hand Recorder is installed. `hands/run.sh uninstall` and `hands/rec/install.sh uninstall` run it after removing their own part, and `uninstall.sh` always takes them back.
- `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` (`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.
- `HANDS_MODE` says when they run: `off` (the default until install.sh installs hand tracking, which sets `frametop`) only after `ft-handsctl on`, until `ft-handsctl off` or SteamVR stops; `frametop` while the Frametop desktop runs; `always` whenever SteamVR runs, in games too. Frametop Input Settings' Hands page sets it and applies it at once (`hands/handsmode.py`), next to the hand cutouts' margin (`HANDS_MATTE_MARGIN`, live). 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` (`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`, typing's `POINTER_PINCH_TYPING`, `POINTER_TYPING_RAISE`, `POINTER_TYPING_BELOW`, `POINTER_TYPING_POSTURE`, `POINTER_TYPING_RECENT`, the gaze pinch's `POINTER_GAZE_PINCH`, `POINTER_GAZE_HAND_RAY`, `POINTER_GAZE_PINCH_DEADZONE`, and `POINTER_GAZE_PINCH_GAIN`, the hand ray's `POINTER_HAND_RAY`, `POINTER_RAY_DEADZONE`, `POINTER_RAY_PUSH`, `POINTER_RAY_SCROLL`, `POINTER_RAY_RELEASE`, `POINTER_RAY_GRACE`, its smoothing and taps (`POINTER_RAY_SMOOTH_MINCUTOFF`, `POINTER_RAY_SMOOTH_BETA`, `POINTER_RAY_SMOOTH_HOLD`, `POINTER_RAY_STEADY`, `POINTER_RAY_TAP`, `POINTER_RAY_TAP_DEADZONE`), its body and hand models (`POINTER_RAY_TORSO_WRISTS`, `POINTER_RAY_HAND_WEIGHT`, `POINTER_RAY_HAND_PITCH`, `POINTER_RAY_HAND_YAW`, `POINTER_RAY_ANCHOR`), and ft-screens' near reach (`HANDS_NEAR_REACH`, 0.075 m), pokes (`HANDS_POKE_ANGLE`, `HANDS_POKE_TRAVEL`, `HANDS_POKE_REST_BELOW`, `HANDS_POKE_REST_NEAR`) and near grabs (the border band `HANDS_GRAB_BAND`, a pinch on the content clicking `HANDS_PINCH_CLICK`, the card pinch `HANDS_CARD_PINCH`, the fist grab `HANDS_FIST_GRAB` and its reach `HANDS_FIST_REACH`, a second hand joining a held panel `HANDS_JOIN_REACH`, two hands turning a panel on every axis `HANDS_STRETCH_TURN`, the round buttons' hit area for hands `HANDS_BUTTON_REACH` and pinches pressing them `HANDS_PINCH_BUTTONS`, `HANDS_GRAB_SMOOTH_MINCUTOFF`, `HANDS_GRAB_SMOOTH_BETA`, `HANDS_GRAB_DEADZONE`, the wrist turning a carried panel: `HANDS_GRAB_ROTATE`, `HANDS_GRAB_ROTATE_DEADZONE`, holding through tracking loss `HANDS_HOLD_LOST_MS`, ignoring tracking no hand makes `HANDS_TRACK_GATE`), throws (the flick `HANDS_FLICK`, `HANDS_FLICK_SPEED`, `HANDS_FLICK_OPENING`, a carry let go fast `HANDS_THROW`, `HANDS_THROW_SPEED`, the push `HANDS_PUSH`, `HANDS_PUSH_SPEED`, where they go, `HANDS_THROW_DISTANCE`, and at what width, `HANDS_SEND_AWAY_WIDTH`), its "grab that" gesture (`HANDS_GRAB_THAT`, `HANDS_GRAB_THAT_DISTANCE`, `HANDS_GRAB_THAT_WIDTH`, which panels: `HANDS_GRAB_THAT_FROM`, `HANDS_GRAB_THAT_MARGIN`, `HANDS_GRAB_THAT_MARGIN_DEG`, `HANDS_GRAB_THAT_FACING`), the soft white halo round a gesture's target panel (`HANDS_TARGET_GLOW`), and the soft glow round the corner, edge or button a hand is at (`HANDS_EDGE_GLOW`). The example config explains each.
Details, options, and the recording and replay tools are in [hands/README.md](../hands/README.md).
+42 -22
View File
@@ -1,6 +1,6 @@
# Remote displays (exploration)
# Remote displays: design notes
Status: exploration. Spike S1 is done; nothing in Frametop has changed yet. Branch `remote-displays`, written 2026-10-06.
These are the notes from building remote displays, from the first exploration (2026-10-06) on: what the Frame's hardware gives us, the spikes, and the decisions. To set a computer up, see [Remote displays in the README](../README.md#remote-displays) and the host kits: [Windows](../host/windows/README.md), [macOS](../host/macos/README.md), [Linux](../host/linux/README.md). How the pieces work now is in [reference.md](reference.md#frametop-remote-displays).
The idea: show desktops streamed from other machines as Frametop panels that behave like the native screens. They get placement, curve, pinning, layouts, lasers, gaze, and attention-based frame rates. The target is up to 5 remote displays from 2 hosts, with no more headset overhead than 5 native screens.
@@ -33,7 +33,7 @@ Five 1440p displays fit at full rate with room left. Five 4K displays only fit a
### The planned setup
Two hosts that share the same two desk monitors: a Mac (14-inch MacBook Pro) with those two plus its built-in display, and the test PC (Windows, RTX 5090) with the two. Windows and Linux hosts run Vibepollo, which streams real displays and creates virtual ones on demand. The Mac runs Sunshine and is limited to one display for now (see "Host side"). At 60 fps:
Two hosts that share the same two desk monitors: a Mac (14-inch MacBook Pro) with those two plus its built-in display, and the test PC (Windows, RTX 5090) with the two. Windows and Linux hosts run Vibepollo, which streams real displays and creates virtual ones on demand. The Mac runs Sunshine, which began with one display; it now runs one instance per display (see "Host side"). At 60 fps:
| Display | Share of the decoder |
|---|---|
@@ -175,7 +175,7 @@ The requirement: each host streams its real displays, and virtual displays it cr
|---|---|---|
| Windows | Vibepollo | 1 main session (real or virtual) + up to 4 virtual Remote Monitors |
| Linux (Arch, CachyOS; beta) | Vibepollo | The same, with at most 4 virtual displays at once |
| macOS | Sunshine | 1, the Mac's main display, for now |
| macOS | Sunshine | Every real display, one Sunshine instance each (`host/macos`); no virtual displays |
### Windows and Linux: Vibepollo
@@ -210,19 +210,15 @@ The config folder is admin-only, so the change is a script for the user to run (
**Risk.** Vibepollo is new, moves fast, and has one maintainer, and its README says about 99% of its code is AI-generated. Frametop depends only on its Moonlight-protocol behaviour and the Remote Monitor app ids, so on Windows Apollo (virtual displays through the SudoVDA driver) or plain Sunshine (real displays) stay as fallbacks.
### macOS: Sunshine, one display for now
### macOS: Sunshine, one instance per display
Vibepollo has no macOS build. Sunshine (v2026.914, labelled experimental on macOS) is the only Moonlight-protocol host for the Mac, so the Mac streams one display: its main display, from one Sunshine instance. The reasons:
Vibepollo has no macOS build. Sunshine (labelled experimental on macOS) is the only Moonlight-protocol host for the Mac. One Sunshine streams one display, so the Mac runs one instance per real display, each with its own config file, ports (`port` 47989 + 100·N) and `output_name` (the display's CGDirectDisplayID). `host/macos/frametop-host-setup.sh` sets them up (see "The Mac" below). Sunshine can't create virtual displays on macOS, and no PR is open for it.
- Since v2026.906, absolute mouse input only reaches the main display (Sunshine #5733). Any other display would show but couldn't be clicked.
- Nobody reports running several Sunshine instances on one Mac yet.
- Sunshine can't create virtual displays on macOS.
- Absolute mouse input reached only the main display from v2026.906 (Sunshine #5733). libvirtualhid #145 and Sunshine #5739 fixed it on 2026-10-09, first in the pre-release v2026.1010.141104, which the host setup pins until a release has it.
- Capture is at backing pixel size, so the built-in display streams at 3024x1964. Closing the lid removes the built-in display, so a stream of it ends. Sunshine now keeps a display awake while it captures it (#5509 was the stall when one slept).
- Sound comes from a Core Audio tap (macOS 14+), so nothing like BlackHole is needed. Every instance carries it; ft-stream's per-address lock plays one.
The main display is the one with the menu bar (System Settings → Displays). Capture is at backing pixel size, so the built-in display streams at 3024x1964. Closing the lid removes the built-in display, so a stream of it ends. Capture stalls if the display sleeps mid-stream (#5509).
One display can still reach the encoder's limit. Sunshine forces VideoToolbox's low-latency mode, which roughly halves throughput (#5814); an M4 Pro managed 0.36-0.46 Gpix/s in that mode. The super ultrawide at 60 fps is 0.44 Gpix/s, so full-motion video on it may need a lower fps or a smaller stream. The other two displays need 0.30 and 0.36 Gpix/s.
**What would lift the limit.** The mouse fix is libvirtualhid PR #145 ("target configured mouse viewport", open), which Sunshine's draft PR #5739 pulls in. Once it ships, spike S4 tries one Sunshine instance per display (own config file, `port` about 100 apart, `output_name`) and BetterDisplay virtual displays switched on by `global_prep_cmd`. Open PR #5817 (ScreenCaptureKit + OBS's VideoToolbox encoder) may raise the encoder limit. Helping #145 along upstream is the one Mac contribution worth making.
Full-motion video can still reach the encoder's limit. Sunshine forces VideoToolbox's low-latency mode, which roughly halves throughput (#5814); an M4 Pro managed 0.36-0.46 Gpix/s in that mode. The super ultrawide at 60 fps is 0.44 Gpix/s; the test Mac is an M3 Max, with two encode engines. Open PR #5817 (ScreenCaptureKit + OBS's VideoToolbox encoder) may raise the limit. Its capture (AVFoundation) also sends 30-55 fps of a still desktop, not `minimum_fps_target`'s 1 fps, at a low bitrate (1-6 Mbit/s).
### What stock hosts cost us
@@ -232,8 +228,8 @@ One display can still reach the encoder's limit. Sunshine forces VideoToolbox's
| One stream per display | Five ft-stream processes, connections, and client pairings on the Frame | Measure the CPU (S3) |
| One real display per Vibepollo install | A second real display needs a second host instance | Use virtual displays; S3 tries a second instance on Windows |
| Cursor drawn into the video | Lags the laser by a round trip; each mouse move over a still page becomes a video frame | Accept |
| Mac: one display | Sunshine's mouse reaches only the main display, and there are no virtual displays | Upstream fix in progress, then S4 |
| Mac encoder | Full-motion video on the super ultrawide at 60 fps is at the limit | Lower fps or size for that stream |
| Mac: an instance per display | Each display pairs on its own, with the Web UI login (no tokens); no virtual displays | Remote Displays pairs all the picked displays from one sign-in |
| Mac encoder | Full-motion video on the super ultrawide at 60 fps is at the limit; a still desktop still streams 30-55 fps | Lower fps or size for that stream; ScreenCaptureKit (#5817) upstream |
What Frametop maintains: ft-stream (pairing, decoder, keyframe sampling, input mapping, Remote Monitor launch and resume; the protocol itself is moonlight-common-c's), the remote screen type in ft-screens, the layout and settings changes, and host setup notes or scripts.
@@ -341,7 +337,7 @@ So far, Vibepollo 2.0.0's Remote Monitors aren't reliable on the test PC: a stal
- the release rolls back, so the virtual display stays attached and "Disconnect Monitor" does nothing;
- for a normal game (the Mac's session), the per-client identity stays held, and every later composition fails on it.
Removing the virtual display alone, as a Vibepollo restart does, left the layout intact. The fork [DeeJanuz/frametop-vibepollo](https://github.com/DeeJanuz/frametop-vibepollo) (GPL-3.0, like Vibepollo), on branch `fix/windows-remote-monitor-release`, changes two things on Windows:
Removing the virtual display alone, as a Vibepollo restart does, left the layout intact. The fork [Frametop/frametop-vibepollo](https://github.com/Frametop/frametop-vibepollo) (GPL-3.0, like Vibepollo), on branch `fix/windows-remote-monitor-release`, changes two things on Windows:
- The coordinator removes the departing display first and recomposes only if another owned display remains (`retire_before_recompose`, set by the Windows runtime). A normal game's identity is released even when its display is already gone. Linux keeps the old order, which exists so KWin never has zero outputs.
- Composed layout applies run with display recovery off, so a refused layout can't reset the host's arrangement.
@@ -401,7 +397,7 @@ The user decided remote displays are Frametop displays, with the same controls a
- `frametop-layout.json` has a `hosts` list. Each host has its displays: id, paired client, what it streams, label, stream size, fps, bitrate, and a screen's place, width, curve, pin and hidden flag. Each display keeps its screen number (101 and up), so the numbers don't shift when one is removed.
- ft-layout starts the remote displays' streams on every apply and at desktop start, even without a head pose, and places them when there is one. Displays without a place go in a row above the screens.
- `capture` and `save` record their places.
- A profile keeps their places and hidden state by id (`profiles[NAME]["remote"]`), and `use` puts them back.
- A profile keeps the displays connected when it's saved, like the apps open then: their places and hidden state by id (`profiles[NAME]["remote"]`). Opening it (`use`, `open`, desktop start), or arranging (`apply`, Reset Screen Layout) while it's the profile in use, connects each of them whose host answers on Vibepollo's Web UI port, at its address or its dongle's as its route allows, and puts it back where it was saved. A host that doesn't answer is skipped, and its displays stay disconnected. Displays the profile doesn't have stay as they are: a profile connects, but never disconnects (user decision, 2026-10-08).
- `hide`/`show N` take their numbers.
- `ft-layout remote list|monitors|add|set|connect|disconnect|remove`: `add` pairs the display's client with the host's token, and `remove` unpairs it (the host stays). `disconnect` sets the display's `off` flag and stops its stream; apply, profiles and desktop start skip it until `connect`.
- ft-screens starts a host's streams one after another. Three started at once made Vibepollo refuse some ("Another stream operation is still running"), and the captures that started while the Remote Monitor appeared got no picture.
@@ -439,17 +435,42 @@ The user decided remote displays are Frametop displays, with the same controls a
**The PC side: Frametop host setup (2026-10-07, ~17:40):**
- `host/windows/Setup Frametop host.cmd` (it runs `frametop-host-setup.ps1` and asks for admin) does what the test PC got by hand, nothing else of its settings:
1. Vibepollo 2.0.0 with its own installer when it isn't there (downloaded from Nonary/Vibepollo's release, SHA-256 checked first; you click through it).
2. Frametop's build of `sunshine.exe` over the original (kept as `sunshine.exe.2.0.0-original`), SHA-256 checked: from `-FrametopBuild PATH|URL`, the script's `$BuildUrl`, or `sunshine-frametop.exe` next to it. Only over Vibepollo 2.0.0's own exe; another version stops it with a message. Without the build, virtual displays still work, but not the PC's own monitors.
2. Frametop's build of `sunshine.exe` over the original (kept as `sunshine.exe.2.0.0-original`), SHA-256 checked: from `-FrametopBuild PATH|URL`, the script's `$BuildUrl` (the fork's release), or `sunshine-frametop.exe` next to it. Only over Vibepollo 2.0.0's own exe; another version stops it with a message. Without the build, virtual displays still work, but not the PC's own monitors.
3. `remote_monitor_mute_audio = disabled`, `remote_monitor_disconnect_on_client_disconnect = enabled`, `remote_monitor_disconnect_on_stream_end = disabled`. The rest of `sunshine.conf` stays as it is.
4. The Web UI login: keep the one there is, or set one (`sunshine.exe --creds`, the password typed into a hidden prompt and passed to it quoted).
5. Checks: an inbound firewall rule for `sunshine.exe` on every network type (added if missing; Windows puts a Steam Link dongle's network in Public), whether a Steam Link dongle (an adapter "For Valve") is connected, and that the Web UI answers. It ends with what to pick and sign in as on the Frame.
`-Check` only says what it would change, `-SkipLogin` leaves the login, `-Undo` puts back the original exe and the oldest backup of the settings. Backups and a log go to `%ProgramData%\Frametop`.
- Tested on the test PC (admin over SSH, `FRAMETOP_NO_PAUSE=1`): `-Check`; a run with nothing to change (no restart); `-Undo` (the original exe back) and a run with `-FrametopBuild D:\vp-build\src\build\sunshine.exe` (backed up, swapped, Vibepollo restarted, the streams came back on their own). Not tested: a PC without Vibepollo (the download and its installer), setting the login (needs the user at the PC), adding the firewall rule.
- Still to decide: where other PCs get Frametop's build. `$BuildUrl` is empty; publishing it needs the fork's source published with it (GPL-3.0).
- Where other PCs get Frametop's build: the fork's GitHub releases, with the source as the release's tag (GPL-3.0). See below (2026-10-09).
- The Frame side: `install.sh` now builds ft-stream (`stream/build.sh`, step 7) with Remote Displays' menu entry, and `uninstall.sh` offers to delete `~/.local/share/frametop-stream` (the clients' keys, the hosts' tokens and pins) with the other settings.
- Linux hosts (Vibepollo's Arch package): a host setup like this one, later.
- After Vibepollo restarted, a stream checked the dongle in 300 ms, too soon, and went over the network; ft-stream now gives it a second.
**Frametop's build released (2026-10-09):**
- Release [`frametop-2.0.0-2`](https://github.com/Frametop/frametop-vibepollo/releases/tag/frametop-2.0.0-2) of Frametop/frametop-vibepollo (2026-10-14; `frametop-2.0.0-1` was the first) has `sunshine.exe` and the Arch package (`pacman -U`), each with its `.sha256`. The fork's CI (`frametop-build.yml`, Depot's runners) builds them from the tag and publishes them; a `frametop-*` tag is what makes a release. The tag is the source.
- The host setup's `$BuildUrl` points at that `sunshine.exe`, so a PC needs only `host/windows`. It replaces the original, the hand-built `2f032252`, and the first CI build (`a84b6cfc`).
- New in it: a Frametop display stream that asks for SDR turns the display's HDR off while it captures it, and back on when the stream ends (with `dd_hdr_option` automatic, Vibepollo's default). The test PC's HDR monitor looked washed out in SDR: Vibepollo's conversion clips at 80 nits while Windows draws SDR content at its SDR white level (240 nits there), and scaling for that left the colours heavily oversaturated. Displays it turned off are listed in `config\frametop_display_hdr.json` until they're back on, so the next start turns them back on after a crash or a forced stop. On the test PC's dev build: HDR off 0.4 s after the stream started, 8-bit capture, back on at the end, off again on a reconnect.
- Tested on the test PC: with the first CI build installed and only `host/windows` in a folder, `-Check` downloaded the release and matched its SHA-256, and the run backed up, swapped and restarted Vibepollo; the Web UI answered.
**The monitor follows the stream's resolution (frametop-vibepollo, 2026-10-10):**
- Before, a Frametop display stream captured the monitor at its own resolution and Vibepollo fit that picture into the stream's size, so a stream smaller than the monitor, or of another shape, never showed its desktop pixel for pixel.
- Now the stream switches the monitor to the stream's width and height, at the monitor's own refresh rate, before capture starts, and puts it back when the stream ends, the way `dd_resolution_option` automatic (Vibepollo's default) matches a main session's display to the client. With it set to manual or disabled, nothing changes. A monitor without that mode gets its closest mode with the same shape, and the stream scales that; one with no mode of that shape keeps its own and is scaled as before.
- The change is temporary: Windows' saved display settings stay as they were, so a reboot undoes it too. Windows may move the other monitors to keep them touching one that changed size, so every monitor's place is noted before the first change and put back after the last, in one change that either fully applies or doesn't.
- Two streams of the same monitor share the first one's mode. HDR (above) goes off after the mode changes and back on before it's put back.
- Monitors it changed are listed in `config\frametop_display_mode.json` (each one's own mode and the one it set, and the places) until they're back, so the next start puts them back after a crash or a forced stop. One someone has changed since keeps theirs.
- In Frametop nothing changes: ft-stream already asks for the size set in Remote Displays, and changing it starts the stream over, which switches the monitor again. The note under a monitor's stream settings says what happens.
**The Mac: one Sunshine instance per display (2026-10-10, branch `mac-host`):**
- `host/macos/frametop-host-setup.sh` (or `Setup Frametop host.command`): installs the pinned Sunshine pre-release (SHA-256 checked, notarized by LizardByte), lists the displays (`displays.js`, JavaScript for Automation, no compiler), and writes an instance per display in `~/Library/Application Support/Frametop/sunshine/instance-N`, the main display's first, each started at login by the LaunchAgent `frametop.sunshine.N`. Its settings: `port`, `sunshine_name` "COMPUTER: DISPLAY (WxH)", its own state and apps files, `minimum_fps_target = 1`, and the menu bar icon on the first only. The rest of each `sunshine.conf` (Web UI changes) is kept on a rerun. `--check`, `--undo` (removes the LaunchAgents; settings, pairings and Sunshine stay), `--set-login`, `--skip-login`.
- Turning them off and on (2026-10-12): Frametop Streams, a menu bar icon, lists the displays with a check by each one that's on. A click turns one on or off, Turn All On and Turn All Off do every one, and the icon dims while they're all off. It's `Frametop Streams.applescript`, a stay-open AppleScriptObjC app (`NSStatusItem`, so no compiler) that the setup compiles into `~/Applications`, marks `LSUIElement` (no Dock icon), signs again ad hoc after that change, and starts at login with the LaunchAgent `frametop.streams`. Quit from its menu, it stays quit until the next login. It runs `ft-sunshine off|on|status [--tsv] [N...]`, in the background for a change, with the output in `~/Library/Logs/Frametop/streams.log`. `ft-sunshine` is installed next to `ft-sunshine-instance` and linked into `~/.local/bin` when there is one. Off disables each instance's LaunchAgent (`launchctl disable`) and stops it, so it stays off through logins. On enables it and starts it, or starts one quit from Sunshine's own menu bar icon, which launchd leaves stopped after a clean exit. Rerunning the setup turns them all on. The Frame's streams of the Mac keep trying while it's off and reconnect after on. Tested with throwaway LaunchAgents serving fake instances, through the menu (UI scripting) and `ft-sunshine`: on, on again (the running one kept its pid), off, on after off, one display, a stopped one, unknown numbers, a display that isn't connected, and the app started by its LaunchAgent and quit from its menu. On the M3 Max: the setup from the kit zip, unpacked with a download's quarantine (the installed scripts keep it, and run anyway: launchd and the app run them through bash and sh), which turned the three on; then Turn All Off, Turn All On and Turn All Off again from the menu, each done within 3 s.
- The kit as a release (2026-10-12): [`macos-host-1`](https://github.com/Frametop/frametop/releases/tag/macos-host-1) of Frametop/frametop has `frametop-macos-host-1.zip`, `host/macos` of 188f107 in a `frametop-macos-host` folder (`zip -qr -X`), and its `.sha256`. Its notes are `host/macos/README.md` without the title, plus the files. It isn't marked Latest and has no `Frametop.zip`, so get.sh skips it: stable takes `releases/latest`, experimental the newest release with a `Frametop.zip`. Its tag doesn't start with `v`, so `release.yml` doesn't build it. A new kit is a new release, `macos-host-N`, with the zip renamed to match.
- An instance is tied to its monitor by vendor, model and serial, not to a display id: `ft-sunshine-instance` looks the id up at every start and passes `output_name=ID`. While the monitor is unplugged it doesn't start Sunshine, which would fall back to the main display, and launchd tries again.
- One certificate for all the instances, so Remote Displays pins one key per Mac; one Web UI login file for all, kept from an earlier Sunshine install if there was one. An earlier Homebrew Sunshine's LaunchAgent (the same ports) is turned off, and back on with `--undo`.
- Screen Recording and Accessibility are granted by hand, once for all the instances: macOS lists them as Sunshine (the LaunchAgent runs a bash script that execs it; `AssociatedBundleIdentifiers` makes Login Items say Sunshine too). Sunshine started from a terminal gets that terminal's grants instead.
- Without Accessibility (Post Event access) the pointer still moves, since libvirtualhid also warps it (`CGWarpMouseCursorPosition`, no permission needed), but clicks, scrolling and keys go only through `CGEventPost`, which macOS drops without a word: every Frame input method moved the pointer and clicked nothing, while the Mac's own trackpad worked. Sunshine notes at each start whether it had each permission (`defaults read dev.lizardbyte.app.Sunshine inputPostEventPermissionState`, 2 = granted, 1 = asked and not granted) and asks only once, so a grant macOS lost track of, or one given to an older Homebrew Sunshine (a separate app to macOS), stays broken with nothing asking again. The setup reports both permissions at the end and with `--check`. After the first instance's restart, if Accessibility is still missing, it offers to clear Sunshine's records (`tccutil reset Accessibility` and `PostEvent` for its bundle id, and that note) and restart the instance so macOS asks again, which fixed the test Mac (2026-10-10).
- Frametop side: a display has a `port` when its instance isn't on 47989, and ft-stream takes `HOST:PORT`, so ft-screens passes it through as it is. The token, pin and audio lock stay per address. Given HOST alone, ft-stream takes its display's port from the layout, by its client: an ft-layout from before ports (an older release's Reset Screen Layout and profile launchers) restarted the Mac's streams at HOST, the instance on 47989, where they froze unpaired and their pointer went to the main display. `host_answers` checks the displays' ports. Remote Displays tries `/api/token` at sign-in; a bare 400 "Bad Request" (upstream Sunshine's answer to a path it doesn't have, before any login check) or a 404 means plain Sunshine, and the login is checked on `/api/clients/list`. It's kept in memory only, passed on stdin to `ft-layout remote add --port P --login` and on to `ft-stream pair --login` for each display picked, then forgotten. Upstream Sunshine (v2026.1010) lists a waiting pairing request with an id (`GET /api/pin`); ft-stream approves its own (libgamestream's device name "roth", from its own address) with `POST /api/pin {pairing_id, pin, name}`. The login is checked first: a wrong password's request, left waiting, blocked the next try. There are no permissions to grant. Add computer merges the instances' mDNS entries ("Mac (2)") into one computer, and Add displays lists the instances from their serverinfo on ports 47989 + 100·N.
- Tested on the M3 Max (macOS 26.6.2: built-in 3024x1964, MPG491CX OLED 5120x1440, LC34G55T 3440x1440): the setup with `--check`, a first run and a rerun; the three instances answer from the Frame. With throwaway test instances (their own login, removed after): pairing with a wrong password then the right one; `ft-layout remote add --port --login` into a scratch layout; streams through a stand-in for ft-screens, the three at once (no losses; 35, 52 and 36 fps of still desktops, 3-9% of a Frame core each, about 6% CPU for Sunshine on the Mac for the OLED); the host's sound; a pointer move to two corners of the LC34G55T, not the main display, landing within a pixel of where it should. Not tested: the Remote Displays app itself, the live desktop, drags across the Mac's displays (separate processes; the release goes through the stream the press went down on), full-motion video's encode rate, replugging a monitor.
**Tested in the live desktop (frame-testbench, the 3D mouse through `@ft_pointer_helper`, 2026-10-07):**
- An Explorer window carried by its title bar from the Remote Monitor to the OLED stayed there, and carried back, stayed there too. The log showed one change of screen each way.
- Disconnect, connect: the panel came back where it was, at its width. Connect in a new run with the headset off: placed from screen 1's anchor.
@@ -475,7 +496,6 @@ The user decided remote displays are Frametop displays, with the same controls a
## Open questions
- Which of the test PC's two desk monitors is the real one (the main session)?
- The Mac's chip (Max chips have two video encode engines) and BetterDisplay Pro matter only once the Mac goes past one display.
- Mac virtual displays: BetterDisplay switched on by `global_prep_cmd`, or a small helper on the private `CGVirtualDisplay` API. Not needed for v1.
- Audio: none, the focused display's host, or a fixed one?
- Does a remote display belong to a profile, so switching profiles connects and disconnects streams?
- Remote displays outside the desktop: should they also show over games, where the decoder is shared with Steam Link VR?
+76
View File
@@ -0,0 +1,76 @@
# Spotwatch
Spotwatch is Frametop's search for apps and remote displays, like Spotlight on a Mac. Press Meta+Space and a glass search pill opens straight ahead of where your head points. Type part of an app's name, or a remote display's `{host} - {display}`, and pick from what it finds:
- **An app that's already running:** its most recent window comes to you. The lazy susan spins the panel it's on, a screen or its own floating window, to straight ahead, and typing goes to it.
- **An app that isn't running:** it starts as a floating window, where that app last floated or in front of you.
- **A remote display:** spotwatch connects it if needed, then spins it to the front.
Use Tab, Shift+Tab, or the arrow keys to move through the results, and Enter or a click to open one. Shift+Enter or a right click opens the item's menu:
- **For an app:** its own launch options, such as a browser's New Private Window, plus Open new window (even when one is open), Open docked on this screen, and each of its open windows.
- **For a remote display:** Go to (connecting it first if needed) and Disconnect.
Esc goes back from a menu and closes the search. Meta+Space again, or a click anywhere else, closes it too.
Spotwatch works while the Frametop desktop is running and Frametop isn't paused for a VR game. It's the `spotwatch` action in Frametop Input Settings, so a mouse button, a controller button, or another key combination can open it too. When it opens from a mouse or controller, Frametop's keyboard opens with it.
## Not built
- Searching open windows by title, Frametop's own actions ("Reset layout"), and profiles (decision 4).
- Moving the caret within the query. Typing and Backspace work at the end only.
- A setting for its distance and size (`--distance` and `--width` on ft-spotpanel; 1 m and 0.56 m).
## Decisions
These were settled with the user on 2026-10-10. The numbers may be cited in the code, so they stay as they are.
| # | Question | Decision |
|---|---|---|
| 1 | The look | A rounded glass pill with a results card under it. The glass is faux, because SteamVR's overlays have alpha but no backdrop blur: a translucent dark tint, a soft sheen from the top, a bright rim fading down the edges, and a shadow outside. Real blur would mean reading the panels back every frame on the Frame's GPU |
| 2 | Where it opens | Fixed in the room, centred where the head points (not the eye gaze), at 1 m, upright, tilted no more than 60° up or down. The card hangs below the pill, so the pill stays put as results change |
| 3 | An app with several windows | One row per app. Enter goes to its most recently active window, and Shift+Enter or a right click lists the others with the menu items |
| 4 | What it searches | Apps and remote displays only. Hidden remote displays are left out, and disconnected ones show with Connect |
| 5 | Disconnected remote displays | Enter connects the display (`ft-layout remote connect`), waits for its panel, then spins to it |
| 6 | When it works | Only while Frametop is running and active: the session starts it, and the input relay doesn't run the action while Frametop is paused. A pause while it's open closes it |
| 7 | Without a keyboard | `spotwatch` is an action like the others, so it can be bound to a mouse button or a controller button. Opened that way, Frametop's keyboard opens too and closes with it |
| 8 | The menu | The app's desktop actions, Open new window (the app's own new-window action when it has one, else a plain launch), Open docked on this screen (the screen nearest straight ahead), and its windows |
| 9 | An app that isn't running | It floats, where ft-floatd puts any launched app (where it last floated, or in front of you) |
| 10 | A window on a pinned panel | Pinned panels don't spin. Typing goes to it where it is (`front N`), and a short note says where it is ("on your left wrist") |
| 11 | Shortcut | Meta+Space by default. Plasma's KRunner has Alt+Space, and nothing in Frametop used Meta+Space |
| 12 | Branch | `spotwatch`, off `experimental`, merged into `experimental` |
## How it works
Spotwatch has three parts, and needs changes in ft-screens, ft-floatd and the input relay:
- **`spotwatch/ft-spotwatch`** (`ft_spotwatch.py`) runs inside the desktop's Plasma session, started from its autostart like ft-floatd, so it's up exactly while the desktop is. It keeps the app index (Gio's, so it sees what the desktop's menus see), the remote displays from the layout, the usage counts, and the search state. It decides what each key and click does. Its log is `/tmp/frametop-spotwatch.log`.
- **`spotwatch/ft-spotpanel.cpp`** is the pill: a SteamVR overlay drawn on the CPU, like ft-gazepanel, built by `screens/build.sh` and run by ft-spotwatch in the container. It holds no state beyond the picture. ft-spotwatch sends it the whole state each time, and it sends back hovers, clicks, right clicks, scrolls, and clicks beside the card. Its clear area catches those clicks.
- **`spotwatch/spotsearch.py`** ranks the results with plain Python, so its test runs anywhere. Name matches come first, from the strongest kind of match to the weakest: the name's start, a word's start, initials, anywhere in the name, then letters in order. Generic names, keywords, and program names count for less and never match fuzzily. Every word of the query must match. Use counts and use in the last day raise an item, and so does an app that's running.
The search has to take the typing from wherever it went, Steam included. While it's open, ft-screens sends every key to `@ft_spotwatch` instead of KWin or a remote display's stream, from keyboards and Frametop's keyboard alike, and tells the input relay that typing goes to the desktop, so the relay grabs the keyboards. ft-spotwatch holds this with `spotwatch on`, renewed every second. ft-screens lets it lapse after 3 seconds, so a crashed ft-spotwatch can't keep the keys. A click on any other panel, or a pause, ends it, and ft-screens says `dismiss` so the pill closes.
ft-spotwatch turns key codes into text on the desktop's keyboard layout (Plasma's `kxkbrc`) through libxkbcommon, and falls back to a US layout without it. The input relay sends no key repeats, so ft-spotwatch repeats a held Backspace or arrow key itself.
Bringing a window to the front takes three commands:
1. ft-floatd's `activate ID` makes the window KWin's active window, unminimized.
2. ft-screens' `spin to N` brings panel N to the front slot at reading distance (or, with `SCREEN_SPIN_BRING=0`, turns the ring of panels the short way so it ends straight ahead). Screens are 1 to S, floating windows come after them, and remote displays start at 101.
3. When the spin settles, ft-screens gives that panel the typing, as any spin does. When the panel can't spin (pinned, or a floating window that's minimized), `front N` gives it the typing where it is.
ft-floatd's `spotlist` lists every app window with its desktop file name, title, panel, and when it was last active. The KWin script keeps that timestamp.
Launching uses ft-floatd's `launch APP.desktop`, which now takes `action=ACTION` (one of the desktop file's actions) and `screen=N` (open docked on screen N; the KWin script's `to-output`). Without ft-floatd (`FLOAT_SLOTS=0`), spotwatch launches through Gio itself, and nothing counts as running.
Apps' icons come from the desktop's icon theme (`kdeglobals`, then breeze and hicolor). GdkPixbuf rasterizes them to 64x64 RGBA files in `~/.cache/frametop/spotwatch` for the panel, one at a time in idle moments after the desktop starts. Use counts are kept in `~/.config/frametop-spotwatch.json`.
```
spotwatch/test/spotwatch-test.py # the ranking, then ft-spotwatch against a fake ft-screens and ft-floatd (offline)
spotwatch/tools/render.py OUT.png # what the panel draws, without a headset (ft-spotpanel --render)
```
## Risks
- **Stray key releases.** A key pressed before the search opened is released to wherever it went, so nothing stays held. A key pressed in the search and released after it closes (the Enter that opened something) reaches the window that now has the typing as a release without a press. Apps ignore those.
- **Laser input.** While the pill shows, it makes SteamVR's lasers active (`MakeOverlaysInteractiveIfVisible`), as Frametop's keyboard does. The search is short-lived, but during that time a game loses its controllers.
- **Matching windows to apps.** Matching uses KWin's desktop file name, then the window class. An app whose windows report neither, such as some X11 apps under Flatpak, doesn't show as running, and Enter starts it again.
+11 -1
View File
@@ -17,6 +17,7 @@ const settled = {}; // id -> {output, frame, fullScreen, maximized}: where a
const held = {}; // id -> {w, h, until, asked}: a size asked for, for a second (see hold)
const moved = {}; // id -> true, or "back" once put back: it moved while KWin changed the outputs
let layout = "", layoutOutputs = {}, layoutSince = 0; // the outputs at the last screensChanged
const activeAt = {}; // id -> when it was last KWin's active window (ms), for spotwatch's most recent
function send(ev) {
callDBus(SERVICE, PATH, IFACE, "Event", JSON.stringify(ev));
@@ -52,7 +53,7 @@ function info(w) {
frame: rect(w.frameGeometry), client: rect(w.clientGeometry), popup: w.popupWindow,
transient: w.transient, parent: w.transientFor ? String(w.transientFor.internalId) : "",
normal: w.normalWindow, dialog: w.dialog, fullScreen: w.fullScreen, minimized: w.minimized,
onAllDesktops: w.onAllDesktops, maximized: isMaximized(w)
onAllDesktops: w.onAllDesktops, maximized: isMaximized(w), activeAt: activeAt[String(w.internalId)] || 0
};
}
@@ -268,8 +269,10 @@ workspace.windowRemoved.connect(w => {
delete settled[id];
delete held[id];
delete moved[id];
delete activeAt[id];
});
workspace.windowActivated.connect(w => {
if (w) activeAt[String(w.internalId)] = Date.now();
if (w && isSpare(w.output)) send({ev: "activated", id: String(w.internalId)});
});
takeLayout();
@@ -376,8 +379,15 @@ function run(c) {
if (w) w.closeWindow();
break;
case "activate":
if (w && w.minimized) w.minimized = false;
if (w) workspace.activeWindow = w;
break;
case "to-output": { // a launched window that opens docked, onto that screen (spotwatch)
const o = outputByName(c.output);
if (w && o && (!w.output || w.output.name !== o.name)) workspace.sendClientToScreen(w, o);
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) {
+3
View File
@@ -8,7 +8,10 @@
ft-float dock all put every floating window back
ft-float launch APP start an app (its desktop file name, e.g. org.kde.dolphin) and
float its first window where that app last floated
ft-float launch APP action=ACTION ...one of its desktop file's actions (a private window)
ft-float launch APP screen=N ...its first window docked on screen N instead
ft-float run COMMAND [ARG...] the same for a command
ft-float activate ID make a window KWin's active one, unminimized
ft-float close ID close a window
ft-float list the spare outputs and what floats on them
FT_FLOAT_SOCKET names ft-floatd's socket (default frametop_float).
+152 -46
View File
@@ -12,8 +12,12 @@ which window floats on which spare output and panel, and connects three parts:
Commands and ft-screens' events arrive as datagrams on @frametop_float (ft-float is the
command-line side). Replies go to the sender:
float [ID|active|pointer] dock [ID|active|all] close ID list quit (ft-float)
launch APP.desktop run ["argv", ...] (start an app and float its first window)
launch APP.desktop [action=ACTION] [screen=N] run ["argv", ...]
(start an app, or one of its desktop file's actions, and float its first window;
with screen=N its first window opens docked on screen N instead)
windows (-> JSON: the open apps' windows and where they are, for a profile; ft-layout save)
spotlist (-> JSON: every app window, its title, panel, and when it was last active; spotwatch)
activate ID (make that window KWin's active one, unminimized; spotwatch)
profile NAME (open a profile's apps: move the matching windows, launch the missing ones)
("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)
@@ -24,15 +28,15 @@ command-line side). Replies go to the sender:
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
only the window. Spares are placed apart from the screens and from each other in KWin's
layout, all within Xwayland's 32767-pixel limit.
layout, within Xwayland's 32767-pixel limit at scales up to 1.6.
Usage: ft-floatd [--screens N] [--slots N] [--margin PX] [--control NAME] [--socket NAME]
Defaults: FT_SCREEN_COUNT (from the session) or the layout's count, FLOAT_SLOTS and
FLOAT_MARGIN from ~/.config/frametop.conf (8 and 300), @ft_screens, @frametop_float.
Launching floating: "launch" starts a desktop file's app (Gio), "run" a command. The next
normal window from that process (or a child), or with that desktop file name, within
LAUNCH_SECONDS floats: where that app last floated, or in front of you. Single-instance and
normal window from that process (or a child), or of that desktop file (desktop_name: by its app
id, else its class, so Flatpak and X11 apps match too), within LAUNCH_SECONDS floats: where that app last floated, or in front of you. Single-instance and
D-Bus-activated apps open their window from a process that was already running, hence the
name. Each app's last floating place (its pose relative to the primary screen, so it moves
with the screens' layout), size in pixels, and scale are kept in PLACES_PATH, by desktop
@@ -73,7 +77,11 @@ SERVICE = IFACE = "org.frametop.Float"
PATH = "/Float"
SCRIPT = "frametop-float"
POLL_SECONDS = 20 # NextCommand answers empty after this (KWin's D-Bus timeout is 25 s)
SPARE_X, SPARE_CELL = 12000, 5000 # spares in KWin's layout: a grid from here, 4 across
# Spares in KWin's layout: a grid 4 across, below the screens. X11 windows get Xwayland
# coordinates of the layout's times its largest scale, which wrap past 32767: a window there
# takes no clicks. 16 spares end at 20000, fine up to scale 1.6 (12000 across had the 4th
# column past it at 1.25).
SPARE_Y, SPARE_CELL = 4000, 4000
PULL_OUT = 0.3 # a floated window starts this far in front of its screen (metres), clear of it
DEFAULT_MPP = 1.6 / 1920 # metres per pixel when ft-screens can't say (no SteamVR)
PLACES_PATH = os.path.expanduser("~/.config/frametop-float.json") # each app's last floating place
@@ -223,6 +231,14 @@ def recordable(ev):
return app not in SKIP_APPS and not any(n.startswith(("ft-", "frametop", "ksplash")) for n in (app, cls))
def listable(ev):
"""An app's top-level window, the kind spotwatch finds: Frametop's own settings apps too,
which profiles leave out (an open Input Settings launched a second copy, 2026-10-13)."""
if not ev.get("normal") or ev.get("popup") or ev.get("transient"):
return False
return ev.get("app", "") not in SKIP_APPS and not any(n.startswith("ksplash") for n in (ev.get("app", ""), ev.get("cls", "")))
def cmdline(pid):
try:
with open(f"/proc/{int(pid)}/cmdline", "rb") as f:
@@ -231,22 +247,56 @@ def cmdline(pid):
return []
_names = {} # (app, cls) -> (desktop file name, when): desktop_name's answers for a minute
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."""
now = time.monotonic()
hit = _names.get((app, cls))
if hit and now - hit[1] < 60:
return hit[0]
if len(_names) > 512:
_names.clear()
name = _desktop_name(app, cls)
_names[(app, cls)] = (name, now)
return name
def _desktop_name(app, cls):
"""The desktop file name (without .desktop) for a window's app id and class, or "" when no
desktop file is its. Most windows give their desktop file name as the app id. The others:
- 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.
- An X11 window can give no app id at all, only its class: Brave's Flatpak says
"Brave-browser" (2026-10-13), and its desktop file is com.brave.Browser.
Then, by the class (or the id), in this order: a desktop file's StartupWMClass; a desktop
file whose name, or its last dotted part, is that name; the program a desktop file runs
(Flatpak's --command=, else the Exec's own), by its name."""
try:
if not app or Gio.DesktopAppInfo.new(app + ".desktop"):
if app and 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 not names:
return ""
infos = [i for i in Gio.AppInfo.get_all() if isinstance(i, Gio.DesktopAppInfo) and i.get_id()]
for info in infos:
wm = info.get_startup_wm_class()
if wm and wm.lower() in names:
return info.get_id().removesuffix(".desktop")
return app
for info in infos:
did = info.get_id().removesuffix(".desktop").lower()
if did in names or did.rsplit(".", 1)[-1] in names:
return info.get_id().removesuffix(".desktop")
for info in infos:
line = info.get_commandline() or ""
m = re.search(r"--command=(\S+)", line)
prog = os.path.basename(m.group(1) if m else (info.get_executable() or ""))
if prog and prog.lower() not in ("flatpak", "env", "sh", "bash", "python3", "snap") and \
any(n == prog.lower() or n.startswith(prog.lower() + "-") for n in names):
return info.get_id().removesuffix(".desktop")
return ""
class Launch:
@@ -259,6 +309,7 @@ class Launch:
self.pids = [pid] if pid else [] # the processes we started (none when D-Bus started it)
self.entries = entries # a profile's entries still waiting for a window, or None
self.relaunched = False
self.dock = None # its first window opens docked on this output (launch screen=N)
self.until = time.monotonic() + LAUNCH_SECONDS
@@ -287,7 +338,7 @@ class Slot:
self.k = k
self.output = f"WL-{screens + k}"
self.index = screens + k + 1 # ft-screens' number (1-based)
self.pos = (SPARE_X + (k % 4) * SPARE_CELL, (k // 4) * SPARE_CELL)
self.pos = ((k % 4) * SPARE_CELL, SPARE_Y + (k // 4) * SPARE_CELL)
self.size = None # its output's size in pixels, as last set
self.want = None # the size in pixels asked for (size is at least that)
self.kscale = 1.0 # its output's scale in KWin, as last set
@@ -308,7 +359,7 @@ class Daemon:
self.sub_numbers = {} # popup/dialog id -> (window id, number)
self.next_sub = 1
self.launches = [] # Launch: apps we started, waiting for their window
self.captures = {} # token -> sender: "windows" requests waiting for the script's report
self.captures = {} # token -> (sender, what): "windows" and "spotlist" requests waiting for the script's report
self.next_token = 1
self.sock = None # our socket (set by main), for deferred replies
self.places = load_places() # app -> {"rel": pose by the primary screen, "pixels", "scale"}
@@ -394,6 +445,11 @@ class Daemon:
return
if kind == "added" and self.launches and not f:
launch = self.launched(ev)
if launch and launch.dock:
log(f"{wid[:9]} ({ev.get('cls')}) opens docked on {launch.dock}")
self.command(cmd="to-output", id=wid, output=launch.dock)
self.seen(ev)
return
if launch and launch.entries is None:
self.float_launched(ev, launch)
return
@@ -469,7 +525,7 @@ class Daemon:
return
# Floating when ft-floatd (re)started: take it over where it is.
f = Float(wid, slot, None)
f.app = ev.get("app", "")
f.app = desktop_name(ev.get("app", ""), ev.get("cls", "")) or ev.get("app", "")
slot.window = f
self.floats[wid] = f
f.scale = slot.kscale = output_scales().get(slot.output, 1.0)
@@ -557,7 +613,7 @@ class Daemon:
"to float another.")
return None
f = Float(wid, slot, {"output": ev["output"], "frame": ev["frame"], "onAllDesktops": ev.get("onAllDesktops")})
f.app = ev.get("app", "")
f.app = desktop_name(ev.get("app", ""), ev.get("cls", "")) or ev.get("app", "")
slot.window = f
self.floats[wid] = f
scales = output_scales()
@@ -760,9 +816,11 @@ class Daemon:
c[1] -= 0.1 * d # a little below eye level, like a screen
return c, ft_layout.turn_yaw((1.0, 0.0, 0.0), heading), (0.0, 1.0, 0.0), ft_layout.turn_yaw((0.0, 0.0, 1.0), heading)
def launch(self, app=None, argv=None):
"""Start an app (a desktop file name) or a command; its first window will float.
Returns (reply, pid or None)."""
def launch(self, app=None, argv=None, action=None, dock=None):
"""Start an app (a desktop file name) or a command; its first window will float, or
with dock (an output name) open docked there. action: one of the desktop file's
actions instead (no pid: its window is known by the app's name). Returns (reply, pid or
None)."""
if app:
app = app.removesuffix(".desktop")
try:
@@ -771,14 +829,22 @@ class Daemon:
info = None
if info is None:
return f"error no app {app}", None
if action and action not in info.list_actions():
return f"error {app} has no action {action}", None
pids = []
try:
info.launch_uris_as_manager([], Gio.AppLaunchContext(), GLib.SpawnFlags.SEARCH_PATH,
None, None, lambda _info, pid, *_: pids.append(pid), None)
if action:
info.launch_action(action, Gio.AppLaunchContext())
else:
info.launch_uris_as_manager([], Gio.AppLaunchContext(), GLib.SpawnFlags.SEARCH_PATH,
None, None, lambda _info, pid, *_: pids.append(pid), None)
except GLib.Error as e:
return f"error {app}: {e.message}", None
self.launches.append(Launch(app, pids[0] if pids else None))
log(f"launched {app} (pid {pids[0] if pids else 'by D-Bus'})")
la = Launch(app, pids[0] if pids else None)
la.dock = dock
self.launches.append(la)
log(f"launched {app}{' (' + action + ')' if action else ''}"
f"{' docked on ' + dock if dock else ''} (pid {pids[0] if pids else 'by D-Bus'})")
return "ok", (pids[0] if pids else None)
else:
try:
@@ -798,16 +864,26 @@ class Daemon:
if not ev.get("normal") or ev.get("popup") or ev.get("transient"):
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}
# A window in a sandbox (Flatpak, Snap) gives its pid in there, and a single-instance app
# opens it from a process that was already running: then only its desktop file can match.
name = desktop_name(ev.get("app", ""), ev.get("cls", "")) if any(la.app for la in self.launches) else ""
for la in self.launches:
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
if any(p in chain for p in la.pids) or (la.app and name == la.app):
return self.took(la)
# Last: a window no desktop file claims, while exactly one app launch waits and none of
# its processes made it (an app whose window names itself after nothing we can find).
waiting = [la for la in self.launches if la.app]
if not name and len(waiting) == 1 and not any(p in chain for la in self.launches for p in la.pids):
log(f"{ev.get('id', '')[:9]} ({ev.get('cls', '') or '?'}): no desktop file claims it; "
f"taken as {waiting[0].app}'s, the one launch waiting")
return self.took(waiting[0])
return None
def took(self, la):
if not la.entries or len(la.entries) <= 1:
self.launches.remove(la)
return la
def concealed(self):
"""The screens (1-based) hidden on their own (ft-layout hide N)."""
reply = self.screens.ask("concealed", quiet=True)
@@ -825,7 +901,7 @@ class Daemon:
def float_launched(self, ev, launch):
"""Float a launched app's window (or one that opened on a hidden screen) where that app
last floated (its size too), or in front of you, at the primary screen's density."""
app = ev.get("app") or (launch.app if launch else "")
app = (launch.app if launch and launch.app else "") or desktop_name(ev.get("app", ""), ev.get("cls", "")) or ev.get("app", "")
known = self.places.get(app) if app else None
ref = self.reference()
place = to_world(ref, known["rel"]) if known and ref and len(known.get("rel", [])) == 12 else self.in_front()
@@ -838,25 +914,42 @@ class Daemon:
# ------------------------------------------------------------ profiles (docs/profiles.md)
def capture(self, sender):
""""windows": have the script report every window as it is now, and answer when the
report is in (or after 3 seconds with what we know)."""
def capture(self, sender, what="windows"):
""""windows" and "spotlist": have the script report every window as it is now, and
answer when the report is in (or after 3 seconds with what we know)."""
if not sender:
return "error windows needs a reply address"
return f"error {what} needs a reply address"
token = self.next_token
self.next_token += 1
self.captures[token] = sender
self.captures[token] = (sender, what)
self.command(cmd="report-all", token=token)
GLib.timeout_add(3000, lambda: self.captured(token) and False)
return None # answered by captured
def captured(self, token):
sender = self.captures.pop(token, None)
sender, what = self.captures.pop(token, (None, None))
if sender and self.sock:
entries = self.spot_entries() if what == "spotlist" else self.window_entries()
try:
self.sock.sendto(("ok " + json.dumps(self.window_entries())).encode(), sender)
self.sock.sendto(("ok " + json.dumps(entries)).encode(), sender)
except OSError as e:
log(f"windows: {e}")
log(f"{what}: {e}")
def spot_entries(self):
"""Every app window for spotwatch's search: its desktop file name, title, the panel
it's on (a screen or a floating window's; None elsewhere), and when it was last active."""
out = []
for wid, ev in self.windows.items():
if not listable(ev):
continue
f = self.floats.get(wid)
m = re.match(r"WL-(\d+)$", ev.get("output", ""))
panel = f.slot.index if f else (int(m.group(1)) + 1 if m and int(m.group(1)) < self.screens_n else None)
out.append({"id": wid, "app": desktop_name(ev.get("app", ""), ev.get("cls", "")),
"class": ev.get("cls", ""), "pid": ev.get("pid") or 0, "title": ev.get("caption", ""),
"panel": panel, "floating": bool(f), "minimized": bool(ev.get("minimized")),
"activeAt": ev.get("activeAt") or 0})
return out
def window_entries(self):
"""Every app window and where it is, as a profile keeps it."""
@@ -866,7 +959,8 @@ class Daemon:
for wid, ev in self.windows.items():
if not recordable(ev):
continue
entry = {"app": desktop_name(ev["app"], ev.get("cls", ""))} if ev.get("app") else {"cmd": cmdline(ev.get("pid")), "class": ev.get("cls", "")}
app = desktop_name(ev.get("app", ""), ev.get("cls", ""))
entry = {"app": app} if 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)
@@ -1036,8 +1130,15 @@ class Daemon:
if not words:
return "error empty"
cmd, rest = words[0], words[1:]
if cmd == "launch" and len(rest) == 1:
return self.launch(app=rest[0])[0]
if cmd == "launch" and rest:
opts = dict(w.split("=", 1) for w in rest[1:] if "=" in w)
if len(opts) != len(rest) - 1 or set(opts) - {"action", "screen"}:
return "error launch APP.desktop [action=ACTION] [screen=N]"
screen = opts.get("screen")
if screen is not None and not (screen.isdigit() and 1 <= int(screen) <= self.screens_n):
return f"error no screen {screen}"
return self.launch(app=rest[0], action=opts.get("action"),
dock=f"WL-{int(screen) - 1}" if screen else None)[0]
if cmd == "run" and rest:
try:
argv = json.loads(text.split(None, 1)[1])
@@ -1046,8 +1147,13 @@ class Daemon:
if not isinstance(argv, list) or not argv or not all(isinstance(a, str) for a in argv):
return "error run takes a JSON list"
return self.launch(argv=argv)[0]
if cmd == "windows":
return self.capture(sender)
if cmd in ("windows", "spotlist"):
return self.capture(sender, cmd)
if cmd == "activate" and len(rest) == 1:
if rest[0] not in self.windows:
return f"error no window {rest[0]}"
self.command(cmd="activate", id=rest[0])
return "ok"
if cmd == "profile" and rest:
return self.open_profile(text.split(None, 1)[1])
if cmd == "list":
@@ -1160,7 +1266,7 @@ def main():
conf = ft_layout.read_conf()
p = argparse.ArgumentParser(description="Floating windows for the Frametop desktop")
p.add_argument("--screens", type=int, default=int(os.environ.get("FT_SCREEN_COUNT") or 0))
p.add_argument("--slots", type=int, default=int(conf.get("FLOAT_SLOTS") or 8))
p.add_argument("--slots", type=int, default=int(conf.get("FLOAT_SLOTS") or 16))
p.add_argument("--margin", type=int, default=int(conf.get("FLOAT_MARGIN") or 300))
p.add_argument("--control", default="ft_screens")
p.add_argument("--socket", default="frametop_float")
+5 -5
View File
@@ -1,6 +1,6 @@
# Install with FrameDrop (proof of concept)
[FrameDrop](https://framedropvr.com) is a Windows app that sideloads onto a Steam Frame: it copies a build to the headset and adds it to the Steam library. Issue #25 asks for an "Install with FrameDrop" button. Frametop isn't an app FrameDrop can copy over as is: it installs user services, a SteamVR driver, and a container, and two optional parts need sudo. So FrameDrop installs a small installer instead. Playing "Frametop" from the library opens a window that asks what to install, and your password for the parts that need it, then installs and shows its progress. A release's Frametop.zip (about 1.1 GB, built by CI on a tag, see [pack/README.md](../pack/README.md), Releases) carries Frametop built, as an image, and installs it with `install-release.sh`: nothing compiles on the headset and nothing else downloads. The same zip works unpacked on the headset. A test zip (a few KB) clones Frametop with `get.sh` instead.
[FrameDrop](https://framedropvr.com) is a Windows app that sideloads onto a Steam Frame: it copies a build to the headset and adds it to the Steam library. Issue #25 asks for an "Install with FrameDrop" button. Frametop isn't an app FrameDrop can copy over as is: it installs user services, a SteamVR driver, and a container, and four optional parts need sudo. So FrameDrop installs a small installer instead. Playing "Frametop" from the library opens a window that asks what to install, and your password for the parts that need it, then installs and shows its progress. A release's Frametop.zip (about 1.1 GB, built by CI on a tag, see [pack/README.md](../pack/README.md), Releases) carries Frametop built, as an image, and installs it with `install-release.sh`: nothing compiles on the headset and nothing else downloads. The same zip works unpacked on the headset. A test zip (a few KB) clones Frametop with `get.sh` instead.
Nothing here is published yet: no release, no button.
@@ -26,7 +26,7 @@ It uses Valve's SteamOS Devkit path: pair once with the headset's devkit service
1. In the container, it starts itself again on the host with `flatpak-spawn --host`.
2. It clears Steam's preload and library paths, and opens `installer/progress.py` (GTK 4 and libadwaita).
3. The window asks which optional parts to install: our own eye tracker (on by default) and the Bluetooth fixes. Both need sudo, so it asks for your SteamOS password and checks it with `sudo -v`. If your user has no password (SteamOS starts without one), it says how to set one and leaves both out.
3. The window asks which optional parts to install: voice dictation (on by default), hand tracking (on by default), the Hand Recorder (on by default; a release's zip only, since a clone builds it with `hands/rec/install.sh`), our own eye tracker (on by default), and the Bluetooth fixes. All but voice dictation need sudo, so it asks for your SteamOS password and checks it with `sudo -v`. If your user has no password (SteamOS starts without one), it says how to set one and leaves those out.
4. It runs the zip's `install-release.sh --yes` (a test zip: `get.sh --yes`) in a transient user service, `frametop-framedrop-install`. The service is used because Steam ends the title's whole process tree when it's quit, and starts it with an OOM score of 900. Opened from a VR desktop (the zip unpacked by hand), it still uses the user's real bus and runtime folder for the service.
5. It follows the service's log, shows the steps as a progress bar, and reports the result. Closing it leaves the install running. Playing the title again reattaches.
@@ -34,7 +34,7 @@ It uses Valve's SteamOS Devkit path: pair once with the headset's devkit service
### The password
FrameDrop has no way to pass a password along, and the zip is the same file for everyone, so the password is typed on the headset, in the window. It stays in the window's memory until the install ends:
FrameDrop has no way to pass a password along, and the zip is the same file for everyone, so the password is typed on the headset, in the window. In VR that means the window's own keypad (shown when Steam starts the window; its Keypad button shows or hides it), whose keys you click with the controller's laser. SteamVR's keyboard doesn't come up for the field by itself, and when it's opened (`steam://open/keyboard`) its keys don't reach the window (tested with frame-testbench, 2026-10-07: the field stayed empty, while laser clicks on the window's checkboxes worked). A Bluetooth keyboard types as usual. The password stays in the window's memory until the install ends:
- The service gets `SUDO_ASKPASS=installer/askpass`. When install.sh's sudo asks, askpass connects to a socket the window keeps in `/run/user/UID/frametop-install` (mode 0700), and the window answers only a process in the install's own service (checked by its peer credentials and cgroup). If it doesn't have the password yet (the window was opened again), it asks you for it, or you skip that part.
- The password is never written to a file, a log, the service's environment, or a command line. The window wipes its copy when the install ends or the window closes. Strings Python and GTK made from it along the way can't be wiped; they go with the process.
@@ -62,11 +62,11 @@ framedrop/build.sh --image REF --version V [--commit SHA] [--channel C] [ZIP_URL
framedrop/build.sh [ZIP_URL] # a test zip
```
This writes `framedrop/build/Frametop.zip` (reproducible), `frametop.framedrop.json` (FrameDrop's manifest with the zip's sha256), and `SHA256SUMS`. A release's zip has the image REF (`podman save`) with its `frametop-release.json` (`pack/release-info.py`) and `install-release.sh`; CI builds it on a tag (`.github/workflows/release.yml`). A test zip has `get.sh` instead. By default, `ZIP_URL` is the release's asset (`releases/download/vV/Frametop.zip`; for a test zip, a `framedrop-installer` release's). Each release carries its manifest, so the button's link can point at the newest stable one: `https://framedropvr.com/install?manifest=https://github.com/DeeJanuz/frametop/releases/latest/download/frametop.framedrop.json` (the exact URL format is FrameDrop's to confirm).
This writes `framedrop/build/Frametop.zip` (reproducible), `frametop.framedrop.json` (FrameDrop's manifest with the zip's sha256), and `SHA256SUMS`. A release's zip has the image REF (`podman save`) with its `frametop-release.json` (`pack/release-info.py`) and `install-release.sh`; CI builds it on a tag (`.github/workflows/release.yml`). A test zip has `get.sh` instead. By default, `ZIP_URL` is the release's asset (`releases/download/vV/Frametop.zip`; for a test zip, a `framedrop-installer` release's). Each release carries its manifest, so the button's link can point at the newest stable one: `https://framedropvr.com/install?manifest=https://github.com/Frametop/frametop/releases/latest/download/frametop.framedrop.json` (the exact URL format is FrameDrop's to confirm).
## Open questions, for a test with FrameDrop on a Windows PC
- Does FrameDrop keep or set the exec bit on `frametop-install.sh`? A zip unpacked on Windows loses it, and without it nothing runs.
- What start command does FrameDrop pick for this zip, and which runtime?
- Does the manifest's `name` become the Devkit Game name? It has to stay free of `-`.
- Can you type the password in the window in VR: does the SteamVR keyboard come up for its password field?
- Typing the password with the window's keypad, launched with Play from the library (frame-testbench reached the window only when started with devkit.sh run, where the systemui overlay hides its lower half).
+2 -2
View File
@@ -40,14 +40,14 @@ files=("$here/installer/frametop-install.sh" "$here/installer/progress.py" "$her
if [ -n "$image" ]; then
[ -n "$version" ] || { echo "--image needs --version" >&2; exit 2; }
commit=${commit:-$(git -C "$repo" rev-parse HEAD)}
url=${1:-https://github.com/DeeJanuz/frametop/releases/download/v$version/Frametop.zip}
url=${1:-https://github.com/Frametop/frametop/releases/download/v$version/Frametop.zip}
echo "saving $image"
podman save -q --format oci-archive -o "$out/frametop-image.tar" "$image"
python3 "$repo/pack/release-info.py" --image-file "$out/frametop-image.tar" --version "$version" \
--commit "$commit" ${channel:+--channel "$channel"} >"$out/frametop-release.json"
files+=("$repo/pack/install-release.sh" "$out/frametop-release.json" "$out/frametop-image.tar")
else
url=${1:-https://github.com/DeeJanuz/frametop/releases/download/framedrop-installer/Frametop.zip}
url=${1:-https://github.com/Frametop/frametop/releases/download/framedrop-installer/Frametop.zip}
files+=("$repo/get.sh")
fi
+116 -21
View File
@@ -13,7 +13,7 @@ The install runs in a user service of its own (UNIT): Steam ends the title's who
tree when it's quit, and starts it with a high OOM score. Closing the window doesn't stop the
install; playing the title again reattaches to it.
Our eye tracker and the Bluetooth fixes need sudo. The window asks for your password on the
Hand tracking, the Hand Recorder, our eye tracker and the Bluetooth fixes need sudo. The window asks for your password on the
headset, checks it with sudo, and keeps it in this process's memory until the install ends.
sudo in the install gets it through askpass (SUDO_ASKPASS), from a socket in a folder only you
can open, and the window answers only programs in the install's service. It's never written to
@@ -46,7 +46,7 @@ RELEASE = (HERE / "install-release.sh").exists() and (HERE / "frametop-image.tar
SOCK_DIR = Path(f"/run/user/{os.getuid()}/frametop-install")
SOCK = SOCK_DIR / "askpass"
ANSI = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")
# get.sh and install.sh mark each step with "== N/10 what it is"
# get.sh and install.sh mark each step with "== N/M what it is"
STEP = re.compile(r"^== (\d+)/(\d+) (.*)$")
DONE_TEXT = ("Frametop is installed. Restart SteamVR once, or reboot the headset, so it loads "
"Frametop's driver. Then open Launch a program, then Desktop.")
@@ -101,7 +101,7 @@ def in_unit(pid):
return False
def install_command(eye_tracker, bluetooth):
def install_command(eye_tracker, bluetooth, voice=True, hands=True, hand_recorder=True):
if RELEASE:
args = [str(HERE / "install-release.sh"), "--yes"]
if DRY_RUN:
@@ -110,6 +110,12 @@ def install_command(eye_tracker, bluetooth):
args = [str(HERE / "get.sh"), "--yes"]
if DRY_RUN:
args += ["--clone-only", "--dir", str(STATE / "dry-run")]
if not voice:
args.append("--no-voice")
if not hands:
args.append("--no-hands")
if RELEASE and not hand_recorder: # a clone (get.sh) doesn't offer it: hands/rec/install.sh builds it
args.append("--no-hand-recorder")
if not eye_tracker:
args.append("--no-eye-tracker")
if bluetooth:
@@ -199,10 +205,82 @@ class Askpass:
SOCK.unlink(missing_ok=True)
class Keypad(Gtk.Box):
"""Keys to click with the controller's laser, for a password field: in VR, SteamVR's own
keyboard comes up for a Steam title's window but its keys don't reach it (tested
2026-10-07), while clicks on the window's buttons do. A physical keyboard types as usual."""
LETTERS = ("1234567890", "qwertyuiop", "asdfghjkl", "zxcvbnm")
SYMBOLS = ("!@#$%^&*()", "-_=+[]{}\\|", ";:'\",.<>/?", "`~")
def __init__(self, entry):
super().__init__(orientation=Gtk.Orientation.VERTICAL, spacing=4)
self.entry = entry
self.shift = self.symbols = False
self.rows = []
for _ in range(4):
row = Gtk.Box(spacing=4, halign=Gtk.Align.CENTER, homogeneous=True)
self.rows.append(row)
self.append(row)
bottom = Gtk.Box(spacing=4, halign=Gtk.Align.CENTER)
for label, action in (("Shift", self.toggle_shift), ("!#1", self.toggle_symbols),
("Space", lambda *_: self.type(" ")), ("Delete", self.backspace)):
b = Gtk.Button(label=label)
b.set_size_request(110 if label != "Space" else 260, 48)
b.connect("clicked", action)
bottom.append(b)
if label == "!#1":
self.symbols_key = b
self.append(bottom)
self.fill()
def fill(self):
for row, keys in zip(self.rows, self.SYMBOLS if self.symbols else self.LETTERS):
while (child := row.get_first_child()) is not None:
row.remove(child)
for k in keys:
k = k.upper() if self.shift and not self.symbols else k
b = Gtk.Button(label=k)
b.set_size_request(56, 48)
b.connect("clicked", lambda _b, k=k: self.type(k))
row.append(b)
def type(self, text):
self.entry.set_text(self.entry.get_text() + text)
self.entry.set_position(-1)
def backspace(self, *_):
self.entry.set_text(self.entry.get_text()[:-1])
self.entry.set_position(-1)
def toggle_shift(self, *_):
self.shift = not self.shift
self.fill()
def toggle_symbols(self, *_):
self.symbols = not self.symbols
self.symbols_key.set_label("abc" if self.symbols else "!#1")
self.fill()
def keypad_row(entry, *extra):
"""The password field, a button that shows or hides the keypad, and the keypad: shown by
itself when Steam started this (FrameDrop's title, so most likely in VR)."""
keypad = Keypad(entry)
keypad.set_visible("SteamAppId" in os.environ)
toggle = Gtk.Button(label="Keypad")
toggle.connect("clicked", lambda *_: keypad.set_visible(not keypad.get_visible()))
row = Gtk.Box(spacing=8)
entry.set_hexpand(True)
for w in (entry, toggle, *extra):
row.append(w)
return row, keypad
class Window(Adw.ApplicationWindow):
def __init__(self, app):
super().__init__(application=app, title="Frametop")
self.set_default_size(900, 640)
self.set_default_size(900, 860 if "SteamAppId" in os.environ else 640)
self.offset = 0
self.partial = ""
self.askpass = None
@@ -228,10 +306,18 @@ class Window(Adw.ApplicationWindow):
# --- what to install, and the password
def show_choices(self):
what = f"Frametop {release_version()}, built," if RELEASE else "Frametop from GitHub"
what = f"Frametop {release_version()}" if RELEASE else "Frametop from GitHub"
self.detail.set_label(f"This installs {what}: the multi-screen desktop, the 3D mouse, gaze "
"mode, and Frametop's settings apps. Two optional parts need your "
"SteamOS password (sudo):")
"mode, and Frametop's settings apps. Optional: voice dictation, and "
"parts that need your SteamOS password (sudo):")
self.voice = Gtk.CheckButton(label="Voice dictation: a Right Ctrl tap or holding the left d-pad down, and "
"what you say is typed (downloads about 320 MB)", active=True)
self.hands = Gtk.CheckButton(label="Hand tracking (experimental): poke, pinch and grab the screens with "
"your hands. It uses a lot of the headset's CPU", active=True)
# A release brings it built; a clone builds it with hands/rec/install.sh, so isn't offered it
self.recorder = Gtk.CheckButton(label="Hand Recorder: record your hands for Frametop's open hand "
"dataset, which trains hand tracking (nothing is uploaded "
"until you press Upload)", active=True, visible=RELEASE)
self.eye = Gtk.CheckButton(label="Our own eye tracker for gaze mode (more accurate than SteamVR's)",
active=True)
self.bt = Gtk.CheckButton(label="Bluetooth fixes (LE mice and keyboards, like the Swiftpoint Z3, "
@@ -246,26 +332,29 @@ class Window(Adw.ApplicationWindow):
self.go.add_css_class("suggested-action")
self.go.connect("clicked", self.install)
self.pw.connect("activate", self.install)
self.choices = [self.eye, self.bt, self.pw, pw_note, self.error, self.go]
pw_row, keypad = keypad_row(self.pw)
self.choices = [self.voice, self.hands, self.recorder, self.eye, self.bt, pw_row, keypad, pw_note,
self.error, self.go]
if not password_set():
for c in (self.eye, self.bt):
for c in (self.hands, self.recorder, self.eye, self.bt):
c.set_active(False)
c.set_sensitive(False)
self.pw.set_visible(False)
pw_note.set_label("Your user has no password, so sudo can't run and these two can't be "
pw_row.set_visible(False)
keypad.set_visible(False)
pw_note.set_label("Your user has no password, so sudo can't run and these can't be "
"installed from here. To set one, run passwd in Konsole; then play "
"Frametop again, or install them later from a terminal "
"(gaze/tracker/install.sh, setup/bluetooth/install.sh).")
for c in (self.eye, self.bt):
c.connect("toggled", lambda *_: self.pw.set_sensitive(self.eye.get_active() or self.bt.get_active()))
"(hands/run.sh install, hands/rec/install.sh, gaze/tracker/install.sh, "
"setup/bluetooth/install.sh).")
for c in (self.hands, self.recorder, self.eye, self.bt):
c.connect("toggled", lambda *_: pw_row.set_sensitive(self.needs_password()))
for w in self.choices:
self.box.append(w)
def install(self, *_):
if self.checking:
return
needs = self.eye.get_active() or self.bt.get_active()
if not needs:
if not self.needs_password():
return self.begin(None)
text = self.pw.get_text()
if not text:
@@ -292,12 +381,17 @@ class Window(Adw.ApplicationWindow):
threading.Thread(target=check, daemon=True).start()
def needs_password(self):
return (self.hands.get_active() or (RELEASE and self.recorder.get_active()) or self.eye.get_active()
or self.bt.get_active())
def say(self, text):
self.error.set_label(text)
self.error.set_visible(True)
def begin(self, pw):
args = install_command(self.eye.get_active(), self.bt.get_active())
args = install_command(self.eye.get_active(), self.bt.get_active(), self.voice.get_active(),
self.hands.get_active(), self.recorder.get_active())
if pw is not None:
try:
self.askpass = Askpass(self.ask_again)
@@ -328,16 +422,17 @@ class Window(Adw.ApplicationWindow):
scroll = Gtk.ScrolledWindow(vexpand=True, child=self.text)
# The install wants the password and the window doesn't have it (played again).
self.ask_bar = Gtk.Box(spacing=8, visible=False)
self.ask_pw = Gtk.PasswordEntry(show_peek_icon=True, hexpand=True,
self.ask_pw = Gtk.PasswordEntry(show_peek_icon=True,
placeholder_text="The next step needs your SteamOS password")
ok = Gtk.Button(label="OK")
skip = Gtk.Button(label="Skip that part")
ok.connect("clicked", self.answer_ask)
self.ask_pw.connect("activate", self.answer_ask)
skip.connect("clicked", self.skip_ask)
for w in (self.ask_pw, ok, skip):
self.ask_bar.append(w)
ask_row, ask_keypad = keypad_row(self.ask_pw, ok, skip)
self.ask_bar = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8, visible=False)
self.ask_bar.append(ask_row)
self.ask_bar.append(ask_keypad)
self.ask_error = Gtk.Label(xalign=0, wrap=True, visible=False)
self.ask_error.add_css_class("error")
+2 -2
View File
@@ -61,8 +61,8 @@ done
section "what an installer needs"
check "home writable" sh -c 'f=$HOME/.cache/frametop-framedrop/.w && : >"$f" && rm "$f" && echo yes'
check "~/frametop visible" sh -c 'ls -d "$HOME/frametop" && git -C "$HOME/frametop" log -1 --format=%h'
have git && check "git ls-remote github" git ls-remote --heads https://github.com/DeeJanuz/frametop.git experimental
have curl && check "curl get.sh" sh -c 'curl -fsSL https://deejanuz.github.io/frametop/get.sh | head -1'
have git && check "git ls-remote github" git ls-remote --heads https://github.com/Frametop/frametop.git experimental
have curl && check "curl get.sh" sh -c 'curl -fsSL https://frametop.github.io/frametop/get.sh | head -1'
have podman && check "podman ps" podman ps --format '{{.Names}}'
have distrobox && check "distrobox list" distrobox list
have systemctl && check "systemctl --user" systemctl --user is-system-running
+11 -2
View File
@@ -9,8 +9,11 @@ The Steam Frame's eye tracking as pointer input: a gaze mode for the 3D mouse (t
Day to day, install the gaze service, then turn gaze mode on and calibrate on the Gaze page of Frametop Input Settings (Calibrate). The installer offers the gaze service (`gaze/run.sh install`) and then our own tracker (`gaze/tracker/install.sh`), which gaze mode uses once it's installed; the probe is installed by hand.
The gaze service's install also turns on SteamVR's `steamvr.gazeDepEyeToHeadEnable` (`gaze/eye-rate.py on`), which counts from SteamVR's next start. The Frame's SteamVR driver runs the eye cameras at 15 to 90 fps (`eyeTrackingRateMin` and `eyeTrackingRateMax` in its `frame_hmd_additional.vrsettings`) and picks the rate as SteamVR starts: with its defaults, 15 (`eyetracking.txt`: "Set framerate 15"). That's enough for SteamVR's own tracker, but our tracker then sees 8 or 9 frames in a calibration dot's 0.6 s, where it needs 15, so it can never calibrate (a 2026-10-10 report: "the right eye was seen in only 8 frames" on every dot, while SteamVR's fit screen showed both eyes tracked). With that setting on, SteamVR asks for 90 at every start (vrserver.txt: "cv: Request eye tracking framerate: 90"). Valve's driver leaves it off and SteamVR's settings have no switch for it; what else it changes isn't documented, and the headset Frametop is developed on runs with it on. Uninstalling turns it off again only if Frametop turned it on. `scripts/doctor.sh` and `scripts/gaze-report.py` report the cameras' rate.
```
gaze/run.sh install # the gaze service: builds ft-gaze and the panel, starts with SteamVR
gaze/eye-rate.py status # SteamVR's eye cameras: the setting that keeps them at 90 fps, and their rate now
gaze/ft-gazectl on # the pointer follows your gaze (off: the mouse alone)
gaze/tracker/install.sh # our own eye tracker's frame grabber (asks for sudo)
gaze/build.sh # build ft-gaze and the panel by hand
@@ -26,6 +29,7 @@ Gaze as an input method for the whole desktop, without replacing anything of Ste
- `ft-gazed` (host Python, a user service: `gaze/run.sh install`) runs ft-gaze and corrects its gaze. Two settings on the Gaze page of Frametop Input Settings (`GAZE_TRACKER` and `GAZE_EYE` in `~/.config/frametop.conf`, read again when the file changes) pick whose eye tracking it uses and how it weights the eyes:
- **Eye tracker:** our own (Own tracker: see "Our own eye tracker" below) or SteamVR's. The default, `GAZE_TRACKER=auto`, is ours when it's installed (its frame grabber, and ft-eyes' Python in the gaze service's checkout), else SteamVR's, and it switches when ours is installed or removed; picking one on the Gaze page sets it for good. The gaze service runs ours while it's the one in use. It keeps its own calibration: with Own tracker chosen, Calibrate on the Gaze page calibrates it. The gaze pointer's settings (hand back, nudges, hold to drag, the dot) are the pointer helper's, so they're the same with either.
- **Eye bias:** Auto, Left, or Right. The gaze combines both eyes, each calibrated on its own, because their errors partly cancel: on 306 clicks with our tracker, the eyes' sideways errors were correlated -0.37, and both together were 0.65 degrees off (median) against 0.96 for the left eye alone and 1.11 for the right. So Left or Right leans instead of choosing: that eye counts twice as much as the other (0.03 degrees worse there toward the better eye, 0.13 toward the worse). Auto weights each eye by the inverse square of how far off it was at your last 20 nudges, once each eye has 5, and evenly before that. Each eye's miss is measured before that nudge teaches anything, so each is a fresh test. The calibration's own fit isn't used for this: on SteamVR's test of 2026-09-29, the calibration dots said the left eye was the better one, and new spots said the right. Either eye carries the gaze alone while the other is closed or lost.
- **One eye:** SteamOS 0.4's Track Dominant Eye Only (SteamVR's settings, General, with Show advanced settings on; `steamvr.eyeTrackingDominantEyeOnly` with `steamvr.dominantEye`) makes SteamVR's tracker ignore the other eye. With SteamVR's tracker, Frametop then goes by that eye alone: the calibration and the checks wait only for it, the gaze is that eye's own reading once it's calibrated (SteamVR's combined gaze before, which follows that eye then), and the fit check shows the other eye as not tracked. The service reads the setting again when SteamVR's settings file changes. Not yet tried in the headset: what SteamVR's shared memory says about the ignored eye wasn't measured.
With SteamVR, each eye is its own reading (set 2), corrected by its calibration from the probe (the Left eye and Right eye sources) plus what the pointer has taught that eye since. On that test, the two eyes each calibrated and averaged were 1.70 degrees off (median; mean 1.62) against 1.72 (mean 1.84) for SteamVR's combined gaze with its calibration. A calibration from before the probe had the eyes as sources, or `--source`, uses the older path. That path runs on SteamVR's combined gaze (mmap set 1), corrected as a whole. When the tracker loses one eye (its variance for that eye jumps from about 0.001 to 0.02), the gaze comes from the other eye instead: that eye's own reading (set 2) plus what it usually reads against the combined gaze, learned while both eyes are seen, in 10 degree cells of where it looks. Set 1 keeps going on one eye too, but it holds the lost eye's yaw where it was, so the gaze moves half as far sideways as your eyes do. On a recording, one eye alone came out a median 0.8 degrees from both eyes' gaze over a steady look, a little more jittery.
@@ -34,7 +38,7 @@ 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. 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`.
- **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 middle, and 12 degrees left and right and 9 up and down, in a see-through panel 40 degrees wide (the quick check's 16 degree square left four of them off the panel, unseen). 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 button mapped to gaze precision or gaze drag counts as the left click there (before 2026-10-09 the panel ignored it). 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). The dot's ring shows full while ft-eyes checks it; the service doesn't wait for that answer (before 2026-10-09 it did, up to 3 s a dot, so the pointer could come back over the panel, and a slow answer closed the calibration as if the headset came off). 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.
@@ -55,7 +59,7 @@ The tracker stops when the headset is off your head. SteamVR also calibrates gaz
`gaze/tracker/` is an eye tracker of our own, because SteamVR's is about 1.5 degrees off after the best correction the gaze service can learn, and what's left is mostly look-to-look noise that no correction on top of its output can remove. Ours processes the eye cameras itself: 0.59 degrees (median) in its best live session against 0.83 for SteamVR's with the probe's correction, and after the headset was taken off and put back without recalibrating, 0.58 once your first clicks had taught it where the headset sat (`tracker/findings.md` has the measurements).
- `ft-eyegrab` (C, root, the system service `frametop-eyegrab.service`) copies the eye-camera frames (512x400, 90 fps per eye) out of the DMA-BUFs SteamVR's `eyetracking` process holds into `/dev/shm/frametop-eyes-cams`, owned by you. It maps them read-only, and it only copies while someone touches `/dev/shm/frametop-eyes-want` (ft-eyes and the recorder do, every second). Otherwise it holds none of the tracker's buffers. Its unit keeps only the capabilities that needs (`CAP_SYS_PTRACE`, `CAP_DAC_READ_SEARCH`, `CAP_CHOWN`). `gaze/tracker/install.sh` builds it and installs it to `/etc/frametop` with sudo, which it asks for (`uninstall`, `status`, and `log` too).
- `ft-eyegrab` (C, root, the system service `frametop-eyegrab.service`) copies the eye-camera frames (512x400, 90 fps per eye, or 15 without `gaze/eye-rate.py on`) out of the DMA-BUFs SteamVR's `eyetracking` process holds into `/dev/shm/frametop-eyes-cams`, owned by you. It maps them read-only, and it only copies while someone touches `/dev/shm/frametop-eyes-want` (ft-eyes and the recorder do, every second). Otherwise it holds none of the tracker's buffers. Its unit keeps only the capabilities that needs (`CAP_SYS_PTRACE`, `CAP_DAC_READ_SEARCH`, `CAP_CHOWN`). `gaze/tracker/install.sh` builds it and installs it to `/etc/frametop` with sudo, which it asks for (`uninstall`, `status`, and `log` too). It also adds it to SteamOS's update keep list (`/etc/atomic-update.conf.d/frametop-eyegrab.conf`): an update deletes `/etc` files that list doesn't name, and without the grabber gaze mode falls back to SteamVR's tracker and its calibration. `scripts/doctor.sh` reports a grabber an update deleted.
- `ft-eyes` (Python with numpy and OpenCV, in the dev container: `gaze/tracker/build.sh` puts the pinned `requirements.txt` in `gaze/tracker/build/venv`) finds each eye's pupil (dark threshold, closing, ellipse fit) and glint pair (`eyes_pupil.py`), and maps them to a gaze with a quadratic fit per eye (`eyes_model.py`). It follows the headset moving on your face with a per-eye shift, which your clicks teach, and uses the glints only to notice a sudden jump. It publishes the gaze in `/dev/shm/frametop-eyes-gaze` (ft-gaze's source `own`) and takes calibration dots and clicks on `@ft_eyes`. The gaze service runs it while Eye tracker is Own tracker, or while the probe uses it. State (the calibration, each eye's shift, the clicks) is in `~/.local/state/frametop/gaze/eyes/`.
- `lab/` has the tools for improving it on recordings. `ft-eyes-record NAME` (or `ft-eyes-session`, with SteamVR's gaze alongside) records the cameras. `ft-eyes-score` fits and scores on recordings against the probe's practice clicks. `ft-eyes-e2e` runs the whole live path on two recordings (calibrate on one, click through the other). `ft-eyes-replay` plays a recording into a scratch share. Heavy ones are meant for a PC: if you have `frame-job` (a personal tool, not in this repo), `gaze/tracker/.frame-job` sends them there. `lab/py` runs them with that Python (in the dev container on the Frame; on a PC, the same venv from `requirements.txt`, which frame-job's setup makes).
@@ -70,6 +74,11 @@ Ground rules, for anyone changing it:
Check headset fit on the Gaze page opens it in the headset panel: a card per eye (tracked or lost, the tracker's signal, how much of the last 10 s it was seen) and the hints, live while you adjust the headset. A left click or Meta+J runs the guided check (dots, then looks down, up, left and right), and a right click or Meta+K closes it. The probe's Headset fit mode (`ft-gazeprobe --mode fit`, for development) has the same check with maps: it shows, for each eye, whether the tracker has it, how open it is, and the tracker's confidence in it, and a map of where you looked coloured by how often it lost that eye there. Hints under the maps say which eye gets lost where, and what to try. Enter runs a guided check: dots around the screen, then looking down at the keyboard, up, left and right. R starts over. Adjust the headset while you watch it.
**The fit watch** (`GAZE_FIT_WATCH=1` in `~/.config/frametop.conf`; off by default until it's been tried in the headset). The fit check keeps a good fit as yours: when its coach (`gaze/fitcoach.py`, from ft-eyes' pupils and glints, with the shipped reference) last read it as good while you looked straight ahead, closing the check saves that reading to `~/.local/state/frametop/gaze/fit-baseline.json`, with the IPD setting. The eye recorder's fitment step saves it too. Then, with the fit watch on:
- **Put-on check:** when the headset goes on, the quick check first holds its dot for up to 4 s while the coach reads the fit against your saved one. If it sits the same, the dot is taken as usual. If it moved (5 degrees of gaze or more), the panel widens and says which way to move the headset, and a changed IPD over that, live, until it's back ("Good: it's back where it was"); then the dot is taken. A click takes the dot as the headset sits, and after 30 s it's taken anyway. It needs our tracker installed (ft-eyes runs for it with either tracker in use), and without a saved fit it's the plain quick check.
- **Slip note:** with our tracker in use and gaze mode on, ft-eyes' glint slip (its `jump_px`, how far each pupil moved in its image since the last click) is turned into degrees through the reference. Past 5 degrees for 2 s, a small strip low in your view says "Your headset slipped" and which way to move it, for 8 s or until the slip is gone, at most once every 2 minutes. It isn't a check: the pointer stays, and a click or the quick check still teaches the tracker the new seating.
`gaze/test/fit-watch-test.py` tests both offline.
Losing an eye is usually about where you look, not the tracker. On this Frame the left eye was lost 57 to 64 % of the time looking 30 to 50 degrees down (at the keyboard) and the right eye never; at screen height both were seen over 98 % of the time. Looking down, the lids come down over the eyes. That's harmless, since the gaze service ignores looks down past the screens: they show on the maps, but not in the counts or as a problem.
## Probe
+141
View File
@@ -0,0 +1,141 @@
#!/usr/bin/env python3
"""Keep SteamVR's eye cameras at 90 fps, for gaze mode.
The Frame's SteamVR driver runs the eye cameras at 15 to 90 fps (steamvr.eyeTrackingRateMin
and eyeTrackingRateMax, in drivers/frame_hmd/resources/frame_hmd_additional.vrsettings),
and asks for the rate once, as SteamVR starts (vrserver.txt: "cv: Request eye tracking
framerate"). With its defaults it asks for 15 (eyetracking.txt: "Set framerate 15"). SteamVR's
own tracker copes, but our tracker gets 8 or 9 frames in a calibration dot's 0.6 s, where it
needs 15, so it can never calibrate, and the gaze pointer would move 15 times a second.
With steamvr.gazeDepEyeToHeadEnable on, SteamVR asks for 90 (seen 2026-10-10: a headset with
it on asks for 90 at every start; a user's with it off, at 15, calibrated once it was on).
SteamVR's settings have no switch for it.
gaze/eye-rate.py on # turn it on (gaze/run.sh install); it counts from SteamVR's next start
gaze/eye-rate.py off # turn it off again, if this turned it on (gaze/run.sh uninstall)
gaze/eye-rate.py status # the setting, and the rate the eye cameras run at now
With SteamVR running it goes through vrcmd, since SteamVR keeps its settings in memory and
writes over the file; without it, it edits SteamVR's settings file.
"""
import json
import os
import re
import subprocess
import sys
from pathlib import Path
HOME = Path.home()
SECTION, KEY = "steamvr", "gazeDepEyeToHeadEnable"
STEAMVR_BIN = "/opt/steamvr/bin/linuxarm64"
# The first that exists is SteamVR's (as gaze/gazecal.py reads them).
STEAMVR_SETTINGS = (HOME / ".config/openvr/config/steamvr.vrsettings",
HOME / ".steam/steam/config/steamvr.vrsettings")
# There when this turned the setting on (it was off), so `off` leaves a setting someone chose alone.
MARK = HOME / ".local/state/frametop/gaze/steamvr-eye-rate"
EYE_LOG = HOME / ".local/share/Steam/logs/eyetracking.txt"
# A terminal in the desktop has the desktop's own config folder, where SteamVR's path registry
# isn't (see scripts/update-check.py): vrcmd needs the real one.
ENV = dict(os.environ, XDG_CONFIG_HOME=str(HOME / ".config"), LD_LIBRARY_PATH=STEAMVR_BIN)
def steamvr_up():
return subprocess.run(["pgrep", "-x", "vrserver"], capture_output=True).returncode == 0
def vrcmd(*args):
p = subprocess.run([f"{STEAMVR_BIN}/vrcmd", *args], capture_output=True, text=True, timeout=15, env=ENV)
return p.stdout
def settings_file():
return next((p for p in STEAMVR_SETTINGS if p.exists()), STEAMVR_SETTINGS[0])
def get():
"""The setting: True, False, or None when SteamVR isn't running and its file doesn't say
(then the driver's default, off)."""
if steamvr_up():
# vrcmd prints "steamvr.gazeDepEyeToHeadEnable=true"
m = re.search(rf"^{SECTION}\.{KEY}=(\w+)", vrcmd("--settings-bool", f"{SECTION}.{KEY}"), re.M)
return None if not m else m.group(1) in ("true", "1")
try:
value = json.loads(settings_file().read_text()).get(SECTION, {}).get(KEY)
except (OSError, ValueError, AttributeError):
return None
return value if isinstance(value, bool) else None
def put(on):
if steamvr_up():
# 1 or 0: vrcmd reads "true" as 0.
vrcmd("--set-settings-bool", f"{SECTION}.{KEY}", "1" if on else "0")
return get() is on
path = settings_file()
try:
d = json.loads(path.read_text())
except FileNotFoundError:
d = {}
except (OSError, ValueError) as e:
print(f"can't read {path}: {e}", file=sys.stderr)
return False
d.setdefault(SECTION, {})[KEY] = on
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".frametop-tmp")
tmp.write_text(json.dumps(d, indent=3) + "\n")
tmp.replace(path)
return True
def camera_rate():
"""The rate the eye cameras run at since the eye tracker last started: the last "Set
framerate" after its last start, or 90 when it set none (it starts at 90). None without
the log or a start in it."""
try:
lines = EYE_LOG.read_text(errors="replace").splitlines()
except OSError:
return None
starts = [i for i, line in enumerate(lines) if " startup with PID" in line]
if not starts:
return None
rates = re.findall(r"CStereoAdspCams: Set framerate ([\d.]+)", "\n".join(lines[starts[-1]:]))
return float(rates[-1]) if rates else 90.0
def main():
what = sys.argv[1] if len(sys.argv) == 2 else ""
if what == "on":
if get():
print(f"SteamVR's eye cameras: {SECTION}.{KEY} is on already, so they run at 90 fps")
return 0
if not put(True):
print(f"couldn't turn on {SECTION}.{KEY}: the eye cameras may stay at 15 fps, and our eye "
"tracker can't calibrate at that. Try again with: gaze/eye-rate.py on", file=sys.stderr)
return 1
MARK.parent.mkdir(parents=True, exist_ok=True)
MARK.write_text(f"{SECTION}.{KEY} was off; Frametop turned it on\n")
print(f"SteamVR's eye cameras: turned on {SECTION}.{KEY}, so they run at 90 fps, not 15, "
"once SteamVR restarts")
return 0
if what == "off":
if not MARK.exists():
print(f"SteamVR's eye cameras: left as they are (Frametop didn't turn on {SECTION}.{KEY})")
return 0
if not put(False):
print(f"couldn't turn off {SECTION}.{KEY}. Try again with: gaze/eye-rate.py off", file=sys.stderr)
return 1
MARK.unlink()
print(f"SteamVR's eye cameras: turned {SECTION}.{KEY} off again (back to 15 fps once SteamVR restarts)")
return 0
if what == "status":
value = get()
rate = camera_rate()
print(f"{SECTION}.{KEY}: {'on' if value else 'off'}" + (" (set by Frametop)" if MARK.exists() else ""))
print("eye cameras: " + (f"{rate:g} fps since the eye tracker started" if rate else "unknown (no eyetracking.txt)"))
return 0
print("usage: gaze/eye-rate.py on|off|status", file=sys.stderr)
return 2
if __name__ == "__main__":
sys.exit(main())
+46
View File
@@ -0,0 +1,46 @@
{
"schema": 1,
"made": "2026-10-14",
"source": "the maintainer's headset: 2 of 3 own-tracker calibrations (2026-10-08, 2026-10-09), the third fitted worse than 4 px",
"faces": 1,
"ipd": 0.0651,
"cameras_follow_lenses": null,
"eyes": {
"0": {
"centre": [
341.04,
221.4
],
"jacobian": [
[
1.2749,
-0.4221
],
[
-0.4783,
-1.3388
]
],
"fits": 2,
"fit_err": 2.339
},
"1": {
"centre": [
334.74,
173.53
],
"jacobian": [
[
-1.3415,
-0.5307
],
[
-0.4822,
1.4794
]
],
"fits": 2,
"fit_err": 2.146
}
}
}
+17 -4
View File
@@ -51,7 +51,10 @@ GUIDE = [
class FitCheck:
def __init__(self):
def __init__(self, ignore=None):
# The eye SteamVR's tracker ignores (0 left, 1 right) with Track Dominant Eye Only on
# (gazecal.tracked_eye), or None: its losses say nothing about the fit.
self.ignore = ignore
self.reset()
def reset(self):
@@ -99,7 +102,8 @@ class FitCheck:
if q and (eye.get("new") or [1, 1])[k]:
self.q[k].append(q[k])
closed = [opens[k] < CLOSED for k in (0, 1)]
if all(closed) or all(self.lost):
judged = [k for k in (0, 1) if k != self.ignore]
if all(closed[k] for k in judged) or all(self.lost[k] for k in judged):
return # a blink: says nothing about the fit
key = (math.floor(hy / CELL), math.floor(hp / CELL))
for k in (0, 1):
@@ -143,6 +147,8 @@ class FitCheck:
# --- Summaries ---
def status(self, k):
if k == self.ignore:
return "not tracked", (0.6, 0.6, 0.6)
if not self.samples:
return "no data", (0.6, 0.6, 0.6)
if self.lost[k]:
@@ -174,8 +180,13 @@ class FitCheck:
return ["Look around slowly (the screen's corners, then down at your keyboard, up, left and right) "
"or press Enter for a guided check."]
out = []
if self.ignore is not None:
out.append(f"SteamVR tracks only your {EYES[1 - self.ignore].lower()} (Track Dominant Eye Only in "
f"SteamVR's settings), so your {EYES[self.ignore].lower()} doesn't count here.")
bad = {}
for k in (0, 1):
if k == self.ignore:
continue
for key, words, _ in REGIONS:
share = self.region_share(k, key)
if share is not None and share >= 0.15:
@@ -197,7 +208,7 @@ class FitCheck:
"face, not one eye's fit.")
continue
k = next(iter(eyes))
other = self.region_share(1 - k, key)
other = self.region_share(1 - k, key) if 1 - k != self.ignore else None
vs = f", the {EYES[1 - k].lower()} {other:.0%}" if other is not None else ""
line = f"{EYES[k]}: lost {eyes[k]:.0%} of the time looking {words}{vs}."
if key == "down":
@@ -211,10 +222,12 @@ class FitCheck:
"eyes.")
out.append(line)
s0, s1 = self.signal(0), self.signal(1)
if s0 is not None and s1 is not None and abs(s0 - s1) > 0.25:
if self.ignore is None and s0 is not None and s1 is not None and abs(s0 - s1) > 0.25:
k = 0 if s0 < s1 else 1
out.append(f"The tracker is less sure of your {EYES[k].lower()} even when it has it "
f"(signal {min(s0, s1):.0%} against {max(s0, s1):.0%}).")
if self.ignore is not None and len(out) == 1:
out.append(f"Your {EYES[1 - self.ignore].lower()} is tracked everywhere you've looked so far.")
if not out:
out.append("Both eyes are tracked everywhere you've looked so far.")
return out
+521
View File
@@ -0,0 +1,521 @@
#!/usr/bin/env python3
"""fitcoach: how the headset sits on this face, from where our tracker sees each eye, and what
to do about it (gaze/rec/DESIGN.md, "Fit coach"). The eye recorder runs it before each round;
the gaze service's fit check, put-on check and slip notice use it too (gaze/gazecheck.py).
It takes per-frame pupil finds (gaze/tracker/eyes_pupil.find_pupil: centre, axes, glints) for
each camera (0 the right eye, 1 the left), keeps the last second, and compares the medians
with a reference: where a well-fitted eye sits in that camera's image while looking straight
ahead, and how the pupil moves per degree of gaze (the reference's Jacobian, fitted on
calibration dots). Offsets go through that Jacobian into degrees as if the eye had turned, so
the cameras' orientations don't matter (camera 1's image is turned 180 degrees from camera 0's:
looking left moves its pupil the other way) and both eyes' readings can be added up:
both eyes appear to look up the eyes sit high in the headset: it's too low -> push it up
both appear to look left the headset sits off to the right -> slide it left
the eyes appear to look apart the eyes are wider apart than the lenses -> IPD wider
one appears to look higher the headset is tilted -> level it
The IPD reading only becomes a hint once we know the eye cameras move with the lenses
(HEADSET-TESTS, 2026-10-14): if they're fixed to the housing, the offset also depends on the IPD
setting, and that needs a reference per setting. Until then it's reported, not advised.
A baseline is the same reading saved from one person's good fit. Compared with a baseline the
glint pair's spacing says whether the eye is nearer the camera than then (the eye relief: on
the maintainer's headset it moved 18 % between two seatings, and 4 % within one), and the put-on
check says how far the headset moved since. The reference starts as the maintainer's
(gaze/fit-reference.json); its hints are marked provisional until it's built from more faces.
Measured on the maintainer's headset (2026-10-14, three calibrations of 27 dots): straight-ahead
pupils moved 15-20 px between seatings, at about 1.3 px per degree; so OK within OK_DEG and
adjust past ADJUST_DEG, both provisional.
Usage (on the Frame, in the dev container, with frametop-eyegrab running):
python3 gaze/fitcoach.py live [--baseline] print the reading twice a second; --baseline saves
the last one as your baseline on Ctrl-C
python3 gaze/fitcoach.py reference [DOTS...] fit a reference from calibration-dots.jsonl files
"""
import json
import math
import os
import statistics
import sys
import threading
import time
from collections import deque
HERE = os.path.dirname(os.path.abspath(__file__))
REFERENCE = os.path.join(HERE, "fit-reference.json")
BASELINE = os.path.expanduser("~/.local/state/frametop/gaze/fit-baseline.json")
DOTS = os.path.expanduser("~/.local/state/frametop/gaze/eyes/calibration-dots.jsonl")
EYES = ("right", "left") # camera 0, camera 1
WINDOW = 1.0 # s of finds per reading
MIN_FINDS = 10 # finds in the window before an eye is judged
MIN_FOUND = 0.5 # share of frames with a pupil: under this, the eye is lost
OK_DEG = 5.0 # every term within this: the fit is good (provisional)
ADJUST_DEG = 8.0 # a term past this: say what to do (between the two: keep the last state)
TILT_DEG = 4.0 # half the eyes' vertical difference
RELIEF_TOL = 0.08 # glint spacing this much off the baseline: nearer or further
MANY_GLINTS = 5 # a find with this many glints has stray reflections. Without glasses
# (three maintainer captures, 2026-10-14) 3+ glints came in up to 37 % of
# finds and 5+ in up to 12 %: a guess until the Glasses bounty's data
EXTRA_GLINTS = 0.5 # share of finds with MANY_GLINTS: reflections (glasses, a smudge)
MOVED_DEG = 5.0 # put-on check: this far from the baseline, the headset moved; the slip
# notice: ft-eyes' glint jump this far
# ------------------------------------------------------------------------------------------
# Readings
def glint_spacing(p):
"""The LED glint pair's spacing in pixels, or None (eyes_pupil.glint_pair's rule)."""
pair = _glint_pair(p)
if not pair:
return None
(x0, y0), (x1, y1) = pair
return math.hypot(x1 - x0, y1 - y0)
def _glint_pair(p):
"""eyes_pupil.glint_pair without numpy: the vertical-ish pair nearest the pupil centre."""
g, best = p.get("glints") or [], None
for i in range(len(g)):
for j in range(i + 1, len(g)):
dx, dy = g[j][0] - g[i][0], g[j][1] - g[i][1]
d = math.hypot(dx, dy)
if not 5 <= d <= 45 or abs(dy) < 2 * abs(dx):
continue
cost = math.hypot((g[i][0] + g[j][0]) / 2 - p["x"], (g[i][1] + g[j][1]) / 2 - p["y"])
if best is None or cost < best[0]:
best = (cost, (g[i], g[j]) if dy > 0 else (g[j], g[i]))
return best[1] if best else None
class Observations:
"""The last WINDOW seconds of pupil finds per camera. add() from any thread."""
def __init__(self, window=WINDOW):
self.window = window
self._rows = {0: deque(), 1: deque()} # (t, x, y, a, spacing or None, extra glints) or (t, None)
self._lock = threading.Lock()
def add(self, cam, t, p):
if p is None:
row = (t, None)
else:
row = (t, float(p["x"]), float(p["y"]), float(p["a"]), glint_spacing(p), len(p.get("glints") or []) >= MANY_GLINTS)
with self._lock:
rows = self._rows[cam]
rows.append(row)
while rows and rows[0][0] < t - self.window:
rows.popleft()
def summary(self, now=None):
"""{camera: {"n", "found", "x", "y", "a", "spacing", "extra"}}: medians of the finds,
found the share of frames with a pupil, extra the share with MANY_GLINTS or more. A camera with
no frames in the window: {"n": 0}."""
out = {}
with self._lock:
for cam, rows in self._rows.items():
rs = [r for r in rows if now is None or r[0] >= now - self.window]
finds = [r for r in rs if r[1] is not None]
if not rs:
out[cam] = {"n": 0}
continue
sp = [r[4] for r in finds if r[4] is not None]
out[cam] = {"n": len(rs), "finds": len(finds), "found": len(finds) / len(rs),
"x": statistics.median(r[1] for r in finds) if finds else None,
"y": statistics.median(r[2] for r in finds) if finds else None,
"a": statistics.median(r[3] for r in finds) if finds else None,
"spacing": statistics.median(sp) if len(sp) >= 3 else None,
"extra": sum(r[5] for r in finds) / len(finds) if finds else 0.0}
return out
# ------------------------------------------------------------------------------------------
# The reference and the baseline
def _solve3(a, b):
"""x for a 3x3 system a x = b (Gaussian elimination with pivoting), or None if singular."""
m = [row[:] + [v] for row, v in zip(a, b)]
for i in range(3):
k = max(range(i, 3), key=lambda r: abs(m[r][i]))
if abs(m[k][i]) < 1e-12:
return None
m[i], m[k] = m[k], m[i]
for r in range(3):
if r != i:
f = m[r][i] / m[i][i]
m[r] = [x - f * y for x, y in zip(m[r], m[i])]
return [m[i][3] / m[i][i] for i in range(3)]
def fit_linear(truths, values):
"""value = c0 + c1 yaw + c2 pitch by least squares: [c0, c1, c2], or None."""
rows = [(1.0, float(t[0]), float(t[1])) for t in truths]
ata = [[sum(r[i] * r[j] for r in rows) for j in range(3)] for i in range(3)]
atb = [sum(r[i] * v for r, v in zip(rows, values)) for i in range(3)]
return _solve3(ata, atb)
class Reference:
"""Per camera: the straight-ahead pupil centre (px) and the Jacobian [[dx/dyaw, dx/dpitch],
[dy/dyaw, dy/dpitch]] (px per degree); optionally the glint spacing, the IPD it was made
at (m), whether the eye cameras move with the lenses, where it came from and from how many faces."""
def __init__(self, eyes, ipd=None, source="", faces=1, cameras_follow_lenses=None, made=""):
self.eyes, self.ipd, self.source, self.faces = eyes, ipd, source, faces
self.cameras_follow_lenses, self.made = cameras_follow_lenses, made
@property
def provisional(self):
return self.faces < 3
@classmethod
def from_dots(cls, rows, source="", ipd=None, max_err=4.0):
"""From calibration-dots.jsonl rows ({"made", "truth": [yaw, pitch], "eye": {"0": {"pupil": [x, y]}}}).
Each calibration ("made") is fitted on its own; those that fit worse than max_err px
(median) are left out, and the rest averaged."""
fits = {0: [], 1: []}
for made in sorted({r.get("made", "") for r in rows}):
for cam in (0, 1):
rs = [r for r in rows if r.get("made", "") == made and (r.get("eye") or {}).get(str(cam))]
if len(rs) < 6:
continue
truths = [r["truth"] for r in rs]
px = [r["eye"][str(cam)]["pupil"] for r in rs]
cx, cy = fit_linear(truths, [p[0] for p in px]), fit_linear(truths, [p[1] for p in px])
if cx is None or cy is None:
continue
err = statistics.median(math.hypot(cx[0] + cx[1] * t[0] + cx[2] * t[1] - p[0],
cy[0] + cy[1] * t[0] + cy[2] * t[1] - p[1]) for t, p in zip(truths, px))
if err <= max_err:
fits[cam].append((cx, cy, err))
eyes = {}
for cam, fs in fits.items():
if not fs:
continue
avg = lambda k, i: sum(f[k][i] for f in fs) / len(fs) # noqa: E731
eyes[cam] = {"centre": [avg(0, 0), avg(1, 0)], "jacobian": [[avg(0, 1), avg(0, 2)], [avg(1, 1), avg(1, 2)]],
"fits": len(fs), "fit_err": statistics.median(f[2] for f in fs)}
return cls(eyes, ipd=ipd, source=source, made=time.strftime("%Y-%m-%d"))
def degrees(self, cam, dx, dy):
"""A pupil offset in px as the gaze change it would be: (yaw, pitch) degrees."""
(a, b), (c, d) = self.eyes[cam]["jacobian"]
det = a * d - b * c
if abs(det) < 1e-9:
return 0.0, 0.0
return (d * dx - b * dy) / det, (-c * dx + a * dy) / det
def to_json(self):
eyes = {str(k): {"centre": [round(v, 2) for v in e["centre"]],
"jacobian": [[round(v, 4) for v in row] for row in e["jacobian"]],
**{k2: (round(v2, 3) if isinstance(v2, float) else v2) for k2, v2 in e.items()
if k2 not in ("centre", "jacobian")}}
for k, e in sorted(self.eyes.items())}
return {"schema": 1, "made": self.made, "source": self.source, "faces": self.faces, "ipd": self.ipd,
"cameras_follow_lenses": self.cameras_follow_lenses,
"eyes": eyes}
@classmethod
def from_json(cls, d):
return cls({int(k): v for k, v in d.get("eyes", {}).items()}, ipd=d.get("ipd"), source=d.get("source", ""),
faces=d.get("faces", 1), cameras_follow_lenses=d.get("cameras_follow_lenses"), made=d.get("made", ""))
@classmethod
def load(cls, path=REFERENCE):
try:
with open(path) as f:
return cls.from_json(json.load(f))
except (OSError, ValueError):
return None
def save(self, path=REFERENCE):
_write_json(path, self.to_json())
def make_baseline(summary, ipd=None):
"""A baseline from a good reading: per camera the centre and glint spacing, and the IPD."""
eyes = {str(c): {"centre": [s["x"], s["y"]], "spacing": s.get("spacing"), "a": s.get("a")}
for c, s in summary.items() if s.get("x") is not None}
return {"schema": 1, "made": time.strftime("%Y-%m-%d %H:%M:%S"), "ipd": ipd, "eyes": eyes}
def load_baseline(path=BASELINE):
try:
with open(path) as f:
return json.load(f)
except (OSError, ValueError):
return None
def save_baseline(baseline, path=None):
"""Keep a good fit as the person's (the gaze service's fit check, the eye recorder's fitment)."""
_write_json(path or BASELINE, baseline)
def _write_json(path, obj):
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = path + ".tmp"
with open(tmp, "w") as f:
json.dump(obj, f, indent=1)
f.write("\n")
os.replace(tmp, path)
# ------------------------------------------------------------------------------------------
# The assessment
HINTS = {
"up": "Push the headset up a little (the top strap).",
"down": "Let the headset down a little.",
"left": "Slide the headset a little to your left.",
"right": "Slide the headset a little to your right.",
"ipd-wider": "Turn the IPD wheel a little wider.",
"ipd-narrower": "Turn the IPD wheel a little narrower.",
"tilt-left-up": "Level the headset: lift its left side a little.",
"tilt-right-up": "Level the headset: lift its right side a little.",
"nearer": "The headset sits closer to your eyes than your saved fit: loosen the back strap a little.",
"further": "The headset sits further from your eyes than your saved fit: tighten the back strap a little.",
"reflections": "Stray reflections in the {eye} eye's camera: tilt your glasses a little, or wipe the lens.",
"lost": "The {eye} eye is hard to see: lashes touching the lens, or the headset too low on that side?",
"ipd-changed": "The IPD setting changed since your saved fit ({was:.1f} mm, now {now:.1f} mm).",
}
def assess(summary, ref, ipd=None, baseline=None, previous=None):
"""The reading: {"state": "ok" | "adjust" | "lost" | "waiting", "eyes": {camera: {...}},
"terms": {"up", "left", "ipd", "tilt"} in degrees, "hints": [{"key", "text", "amount"}],
"provisional", "against": "baseline" | "reference"}.
Against a baseline (the person's own good fit) when there is one, else the reference.
previous (an earlier assess() result) keeps the state between OK_DEG and ADJUST_DEG."""
eyes, hints, offsets = {}, [], {}
centres = {}
if baseline:
centres = {int(k): v["centre"] for k, v in baseline.get("eyes", {}).items()}
for cam, s in summary.items():
e = {"name": EYES[cam], "found": round(s.get("found", 0.0), 3), "seen": bool(s.get("n"))}
if not s.get("n") or s.get("finds", 0) < MIN_FINDS:
e["state"] = "waiting" if not s.get("n") else "lost"
elif s["found"] < MIN_FOUND:
e["state"] = "lost"
else:
e["state"] = "found"
centre = centres.get(cam) or (ref.eyes.get(cam) or {}).get("centre") if ref else centres.get(cam)
if centre and ref and cam in ref.eyes:
dx, dy = s["x"] - centre[0], s["y"] - centre[1]
offsets[cam] = ref.degrees(cam, dx, dy)
e["offset_px"] = [round(dx, 1), round(dy, 1)]
e["offset_deg"] = [round(v, 2) for v in offsets[cam]]
if s.get("extra", 0.0) > EXTRA_GLINTS:
hints.append({"key": "reflections", "text": HINTS["reflections"].format(eye=EYES[cam]), "amount": s["extra"]})
if baseline:
b = baseline.get("eyes", {}).get(str(cam)) or {}
if b.get("spacing") and s.get("spacing"):
rel = s["spacing"] / b["spacing"] - 1.0
e["relief"] = round(rel, 3)
eyes[cam] = e
lost = [c for c, e in eyes.items() if e["state"] == "lost"]
for c in lost:
hints.append({"key": "lost", "text": HINTS["lost"].format(eye=EYES[c]), "amount": 1.0 - eyes[c]["found"]})
terms = {}
if offsets:
yaws = {c: v[0] for c, v in offsets.items()}
pitches = {c: v[1] for c, v in offsets.items()}
terms["up"] = sum(pitches.values()) / len(pitches) # + : the eyes sit high: the headset is low
terms["left"] = sum(yaws.values()) / len(yaws) # + : the eyes sit left: the headset is right
if len(offsets) == 2:
terms["ipd"] = (yaws[1] - yaws[0]) / 2 # + : the eyes are wider apart than the lenses
terms["tilt"] = (pitches[1] - pitches[0]) / 2 # + : the left eye sits higher: its side is low
t = terms
if abs(t.get("up", 0)) > ADJUST_DEG:
hints.append(_hint("up" if t["up"] > 0 else "down", t["up"]))
if abs(t.get("left", 0)) > ADJUST_DEG:
hints.append(_hint("left" if t["left"] > 0 else "right", t["left"]))
ipd_advice = ref is not None and ref.cameras_follow_lenses is True
if ipd_advice and abs(t.get("ipd", 0)) > ADJUST_DEG:
hints.append(_hint("ipd-wider" if t["ipd"] > 0 else "ipd-narrower", t["ipd"]))
if abs(t.get("tilt", 0)) > TILT_DEG:
hints.append(_hint("tilt-left-up" if t["tilt"] > 0 else "tilt-right-up", t["tilt"]))
reliefs = [e["relief"] for e in eyes.values() if "relief" in e]
if reliefs:
rel = sum(reliefs) / len(reliefs)
terms["relief"] = rel
if abs(rel) > RELIEF_TOL:
hints.append({"key": "nearer" if rel > 0 else "further", "text": HINTS["nearer" if rel > 0 else "further"],
"amount": rel})
if baseline and ipd and baseline.get("ipd") and abs(ipd - baseline["ipd"]) >= 0.001:
hints.insert(0, {"key": "ipd-changed", "amount": ipd - baseline["ipd"],
"text": HINTS["ipd-changed"].format(was=baseline["ipd"] * 1000, now=ipd * 1000)})
# The state, with hysteresis on the position terms.
big = max([abs(t.get(k, 0.0)) for k in ("up", "left")] + ([abs(t.get("ipd", 0.0))] if ipd_advice else []), default=0.0)
if any(e["state"] == "waiting" for e in eyes.values()) or not eyes:
state = "waiting"
elif lost:
state = "lost"
elif not offsets:
state = "waiting"
elif big > ADJUST_DEG or abs(t.get("tilt", 0)) > TILT_DEG or abs(t.get("relief", 0)) > RELIEF_TOL:
state = "adjust"
elif big <= OK_DEG:
state = "ok"
else:
state = (previous or {}).get("state") if (previous or {}).get("state") in ("ok", "adjust") else "adjust"
if state == "adjust" and not hints:
# Between OK_DEG and ADJUST_DEG, and not OK before: name the biggest term.
names = {"up": ("up", "down"), "left": ("left", "right")}
if ipd_advice:
names["ipd"] = ("ipd-wider", "ipd-narrower")
term = max((k for k in names if k in t), key=lambda k: abs(t[k]), default=None)
if term:
hints.append(_hint(names[term][0] if t[term] > 0 else names[term][1], t[term]))
hints.sort(key=lambda h: (h["key"] not in ("ipd-changed", "lost"), -abs(h["amount"])))
return {"state": state, "eyes": eyes, "terms": {k: round(v, 3) for k, v in terms.items()}, "hints": hints,
"provisional": bool(ref is None or ref.provisional), "against": "baseline" if centres else "reference",
"ipd": ipd, "ipd_advice": ipd_advice}
def _hint(key, amount):
return {"key": key, "text": HINTS[key], "amount": amount}
def moved(reading):
"""Put-on check: the headset sits more than MOVED_DEG from the baseline (or changed IPD)."""
t = reading.get("terms", {})
return reading.get("against") == "baseline" and (
max(abs(t.get("up", 0.0)), abs(t.get("left", 0.0))) > MOVED_DEG or
any(h["key"] == "ipd-changed" for h in reading.get("hints", [])))
def position_hint(terms, limit=MOVED_DEG):
"""The biggest position term (up, left) past limit as a hint ("up", "down", "left" or
"right"), or None."""
names = {"up": ("up", "down"), "left": ("left", "right")}
term = max((k for k in names if abs(terms.get(k, 0.0)) > limit), key=lambda k: abs(terms[k]), default=None)
if term is None:
return None
return _hint(names[term][0] if terms[term] > 0 else names[term][1], terms[term])
def slip_terms(jumps, ref):
"""ft-eyes' glint jumps ({camera: (dx, dy)}, pixels: how far each pupil moved in its image
since the last click, the headset having slipped) as the coach's position terms, {"up",
"left"} in degrees, through the reference's Jacobian as assess() does; {} without any."""
offsets = [ref.degrees(cam, dx, dy) for cam, (dx, dy) in jumps.items() if ref and cam in ref.eyes]
if not offsets:
return {}
return {"up": sum(o[1] for o in offsets) / len(offsets), "left": sum(o[0] for o in offsets) / len(offsets)}
# ------------------------------------------------------------------------------------------
# Live finds from the shared frames (numpy and OpenCV: the dev container, or a venv with them)
class LiveFinder:
"""Runs the pupil finder on each camera's newest frame, at most rate times a second, and adds
the finds to obs. About 0.4 ms a frame while it follows the pupil, 2 ms when it searches."""
def __init__(self, obs, rate=30.0, share_path=None, want_path=None, log=None):
sys.path.insert(0, os.path.join(HERE, "tracker"))
import eyes_pupil # noqa: E402 (numpy, OpenCV)
import eyes_share # noqa: E402
import numpy as np # noqa: E402
self._pupil, self._share_mod, self._np = eyes_pupil, eyes_share, np
self.obs, self.period = obs, 1.0 / rate
self.share_path, self.want_path = share_path, want_path
self.log = log or (lambda line: None)
self.error = None
self._stop = threading.Event()
self._thread = threading.Thread(target=self._run, name="fitcoach-finder", daemon=True)
def start(self):
self._thread.start()
return self
def stop(self):
self._stop.set()
self._thread.join(2)
def _run(self):
share = self._share_mod.open_share(10, self.share_path, self.want_path)
if share is None:
self.error = "no eye camera frames: is frametop-eyegrab.service running?"
self.log("fit coach: " + self.error)
return
last, near, touched = {0: -1, 1: -1}, {0: None, 1: None}, 0.0
np = self._np
while not self._stop.is_set():
t0 = time.monotonic()
for cam in (0, 1):
n = share.count(cam)
if n == last[cam] or n == 0:
continue
last[cam] = n
f = share.frame(cam, n - 1)
if f is None:
continue
img = np.frombuffer(f[2], np.uint8).reshape(self._share_mod.H, self._share_mod.W)
p = self._pupil.find_pupil(img, near[cam])
near[cam] = p
self.obs.add(cam, f[0], p)
if t0 - touched >= 1.0:
touched = t0
self._share_mod.touch_want(self.want_path)
if share.replaced():
share.close()
share = self._share_mod.open_share(10, self.share_path, self.want_path)
if share is None:
self.error = "the eye camera frames stopped"
return
self._stop.wait(max(0.0, self.period - (time.monotonic() - t0)))
share.close()
# ------------------------------------------------------------------------------------------
def _print_reading(r):
eyes = "; ".join("%s %s found %.0f%%%s" % (e["name"], e["state"], 100 * e["found"],
" off %+.1f,%+.1f deg" % tuple(e["offset_deg"]) if "offset_deg" in e else "")
for _c, e in sorted(r["eyes"].items()))
terms = " ".join("%s %+.1f" % kv for kv in sorted(r["terms"].items()))
print("%-7s %s | %s%s" % (r["state"], eyes, terms, " (provisional)" if r["provisional"] else ""))
for h in r["hints"]:
print(" -> " + h["text"])
def main(argv):
if not argv or argv[0] in ("-h", "--help"):
sys.exit(__doc__)
if argv[0] == "reference":
paths = argv[1:] or [DOTS]
rows = []
for p in paths:
with open(p) as f:
rows += [json.loads(line) for line in f if line.strip()]
ref = Reference.from_dots(rows, source="calibration dots: " + ", ".join(os.path.basename(p) for p in paths))
print(json.dumps(ref.to_json(), indent=1))
return
if argv[0] == "live":
ref = Reference.load()
baseline = load_baseline()
obs = Observations()
finder = LiveFinder(obs, log=print).start()
last = None
try:
while finder.error is None:
time.sleep(0.5)
last = assess(obs.summary(), ref, baseline=baseline, previous=last)
_print_reading(last)
except KeyboardInterrupt:
pass
finder.stop()
if "--baseline" in argv and last and last["state"] in ("ok", "adjust"):
_write_json(BASELINE, make_baseline(obs.summary()))
print("saved the baseline: " + BASELINE)
return
sys.exit(__doc__)
if __name__ == "__main__":
main(sys.argv[1:])
+9 -8
View File
@@ -98,10 +98,11 @@ double NowRaw() {
}
// --- eye-server.mmap (packed, unaligned: read with memcpy) ---
// The SteamOS 0.4.x beta (SteamVR 2.18.2) moved every field from the timestamp on by 5
// bytes (measured 2026-10-04 with the ftdiag scan: timestamp 0x157 -> 0x15c, the vectors
// moved with it; the counter at 0x38 kept its place). Which layout is live is detected at
// runtime (EyeFile::Detect), so one binary serves both generations.
// SteamOS 0.4 (SteamVR 2.18.2; first on the 0.4.3 beta, the same on 0.4.5, the release)
// moved every field from the timestamp on by 5 bytes (measured 2026-10-04 with the ftdiag
// scan: timestamp 0x157 -> 0x15c, the vectors moved with it; the counter at 0x38 kept its
// place). Which layout is live is detected at runtime (EyeFile::Detect), so one binary
// serves both generations.
constexpr size_t kCounter = 0x38; // u32, one per sample
constexpr size_t kTime = 0x157; // f64, CLOCK_MONOTONIC_RAW seconds
constexpr size_t kLeft1 = 0x15f, kRight1 = 0x16b; // set 1: unit vectors, head space
@@ -115,11 +116,11 @@ constexpr size_t kVar1 = 0x177, kVar2 = 0x1b3;
// x, y, right x, y). An eye's pair stops changing while the tracker can't see it.
constexpr size_t kMeas = 0x1d3;
constexpr size_t kNeed = 0x1f3 + 5; // enough for either layout
constexpr size_t kShifts[] = {0, 5}; // the layouts EyeFile::Detect knows: stable, 0.4.x beta
constexpr size_t kShifts[] = {0, 5}; // the layouts EyeFile::Detect knows: SteamOS 0.3, 0.4
struct EyeFile {
// Everything from the timestamp on is read at base + shift: 0 on stable, 5 on the
// 0.4.x beta (see the constants above). known once Detect has seen that layout's
// Everything from the timestamp on is read at base + shift: 0 on SteamOS 0.3, 5 on 0.4
// (see the constants above). known once Detect has seen that layout's
// timestamp tick; before that, reading would yield garbage that still passes
// ReadSample's check.
size_t shift = 0;
@@ -673,7 +674,7 @@ int main(int argc, char **argv) {
if (haveMmap && !eyes.known && (eyes.Detecting() || (writing && now >= nextLayoutCheck))) {
const EyeFile::Detection d = eyes.Detect(now);
if (d == EyeFile::kFound) {
std::fprintf(stderr, "ft-gaze: eye-server.mmap layout: %s\n", eyes.shift ? "beta (+5)" : "stable");
std::fprintf(stderr, "ft-gaze: eye-server.mmap layout: %s\n", eyes.shift ? "SteamOS 0.4 (+5)" : "SteamOS 0.3");
} else if (d == EyeFile::kNone) {
nextLayoutCheck = now + 1.0;
if (!missSince) missSince = now;
+8
View File
@@ -6,6 +6,9 @@
ft-gazectl status the gaze service (ft-gazed): samples, lessons, the correction
ft-gazectl forget drop what the pointer's lessons taught (the calibration stays)
ft-gazectl reload the service reads calibration.json again
ft-gazectl quickcal|calibrate|fitcheck|fivecheck
open that check in the headset panel: the one-dot check, the
full calibration, the headset fit check, the five-dot check
"""
import json
@@ -55,6 +58,11 @@ def main():
print(json.dumps(json.loads(r), indent=1))
except ValueError:
print(r)
elif cmd in ("quickcal", "calibrate", "fitcheck", "fivecheck"):
r = ask("ft_gazed", cmd)
if r is None:
sys.exit("the gaze service (ft-gazed) isn't running")
print(r)
else:
sys.exit(__doc__)
+55 -9
View File
@@ -103,8 +103,11 @@ Control socket: abstract unix datagram "@ft_gazed":
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
fivecheck the five-dot check now (it otherwise follows a quick check
that didn't fix the tracker)
calaccept | calquit from the pointer helper while the panel is up: take this dot
now (a left click, Meta+J) | close it (a right click, Meta+K)
now (a left click, Meta+J, or a gaze precision or gaze drag
press) | close it (a right click, Meta+K)
Options: --source action|mmap1|mmap2 (the older one-source path with that source, whatever
the settings say; set 2 was a little quieter in the probe, but loses the pointer whenever
@@ -129,7 +132,7 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from gazecal import (DEFAULT_MODEL, EYE_FOUND, EYE_LOST, MODELS, STATE, Correction, EyeFallback, # noqa: E402
EyeWeights, Fixation, LiveCorrection, SteamEyeLog)
EyeWeights, Fixation, LiveCorrection, SteamEyeLog, TrackedEye)
from gazecheck import Checks # noqa: E402
REPO = Path(__file__).resolve().parents[1]
@@ -237,6 +240,9 @@ class Service:
self.opens = (deque(maxlen=90), deque(maxlen=90)) # left, right
self.vergence = deque(maxlen=90)
self.fallback = EyeFallback()
# SteamVR's tracker following one eye only (gazecal.tracked_eye): 0 left, 1 right, or None.
self.tracked = TrackedEye()
self.one_eye = self.tracked()
self.lost = [False, False]
self.bad_at = [0.0, 0.0] # sample time an eye was last lost or closed
self.counts = {"samples": 0, "sent": 0, "blinks": 0, "one_eye": 0, "one_eye_used": 0, "lost_left": 0,
@@ -281,7 +287,9 @@ class Service:
return "source"
if self.tracker == "own":
return "own"
return "eyes" if all(self.models[e].samples for e in SIDES) else "source"
# With one eye tracked, that eye's own calibration is enough.
sides = SIDES if self.one_eye is None else (SIDES[self.one_eye],)
return "eyes" if all(self.models[e].samples for e in sides) else "source"
# --- Settings, calibration and lessons ---
@@ -292,6 +300,9 @@ class Service:
auto = ""
if self.tracker_setting == "auto":
auto = " (auto: ours is installed)" if tracker == "own" else " (auto: ours isn't installed)"
if tracker == "steam" and EYEGRAB[1].exists() and not EYEGRAB[0].exists():
auto = (f" (auto: ours lost {EYEGRAB[0]}, which SteamOS updates delete unless it's kept;"
" reinstall it with gaze/tracker/install.sh)")
log(f"tracker {tracker}{auto}, eye bias {bias}" + (f" (--source {self.override} wins)" if self.override else ""))
self.tracker, self.bias = tracker, bias
for w in self.weights.values():
@@ -534,6 +545,9 @@ class Service:
self.proc = None
self.mmap_unknown = False
def own_installed(self):
return own_installed() # (for the checks: the fit coach needs ft-eyes)
def eyes_wanted(self):
return (self.tracker == "own" and not self.override and self.awake) or time.monotonic() < self.eyes_until
@@ -638,11 +652,17 @@ class Service:
for k in (0, 1):
self.lost[k] = unc[k] > (EYE_FOUND if self.lost[k] else EYE_LOST)
if not down:
self.counts["lost_left"] += self.lost[0]
self.counts["lost_right"] += self.lost[1]
self.counts["lost_left"] += self.lost[0] and self.one_eye != 1
self.counts["lost_right"] += self.lost[1] and self.one_eye != 0
return low
def on_sample(self, s):
one = self.tracked()
if one != self.one_eye:
log("SteamVR now tracks both eyes" if one is None else
f"SteamVR tracks the {SIDES[one]} eye only (Track Dominant Eye Only): going by that eye")
self.one_eye = one
self.fix.reset()
self.checks.on_sample(s)
kind = self.kind
if kind != self.last_kind:
@@ -669,7 +689,8 @@ class Service:
eyes = [(p["hy"], p["hp"]) if "hy" in p else None for p in per]
if not any(eyes):
return
hp, hit = next(e[1] for e in eyes if e), m1.get("hit")
one = self.one_eye
hp, hit = (eyes[one] if one is not None and eyes[one] else next(e for e in eyes if e))[1], m1.get("hit")
self.counts["samples"] += 1
self.last_sample = time.monotonic()
down = hp < KEYBOARD_PITCH and not hit
@@ -677,8 +698,14 @@ class Service:
if down:
self.counts["looking_down"] += 1
return
if own and self.one_eye is not None:
# SteamVR judges only that eye's openness, and a blink closes both: ours still
# sees the other, so it stays in.
low[1 - self.one_eye] = low[self.one_eye]
# Our tracker finds the pupils itself; SteamVR's openness still marks the blinks.
bad = [eyes[k] is None or low[k] or (not own and self.lost[k]) for k in (0, 1)]
if not own and self.one_eye is not None:
bad[1 - self.one_eye] = True # SteamVR ignores that eye
if all(bad):
self.counts["blinks"] += 1
return
@@ -713,11 +740,27 @@ class Service:
self.bad_at[k] = s["t"] # the fallback doesn't learn from these either
return
bad = [low[k] or self.lost[k] for k in (0, 1)]
hy, hp = src["hy"], src["hp"]
eyes = (s["src"].get("mmap2") or {}).get("eyes")
one = self.one_eye
if one is not None:
# SteamVR's combined gaze already follows that eye alone; set 2's averages the
# ignored one in, so mmap2 takes the eye's own reading. No fallback to learn.
if bad[one]:
self.counts["blinks"] += 1
return
if self.source == "mmap2":
if not eyes:
self.counts["dropped"] += 1
return
hy, hp = eyes[one]
fy, fp = self.fix(hy, hp, s["t"], 1.0)
cy, cp = self.correction(self.source, fy, fp)
self.send(s["t"], fy + cy, fp + cp, fy, fp, None)
return
if all(bad):
self.counts["blinks"] += 1
return
hy, hp = src["hy"], src["hp"]
eyes = (s["src"].get("mmap2") or {}).get("eyes")
for k in (0, 1):
if bad[k]:
self.bad_at[k] = s["t"]
@@ -788,7 +831,8 @@ class Service:
elif words[:1] == ["forget"]:
self.forget_lessons()
reply = "ok"
elif words[:1] and words[0] in ("quickcal", "calibrate", "fitcheck", "calaccept", "calquit", "recheck"):
elif words[:1] and words[0] in ("quickcal", "calibrate", "fitcheck", "fivecheck", "calaccept", "calquit",
"recheck"):
reply = self.checks.command(words)
elif words[:1] == ["eyes"] and len(words) == 2:
try:
@@ -904,6 +948,8 @@ class Service:
self.on_control()
elif key.data == "checks":
self.checks.on_readable()
elif key.data == "eyes_reply":
self.checks.on_eyes_reply(key.fileobj)
elif key.data == "panel" and self.checks.panel_proc:
self.checks.read_panel()
elif key.data == "own":
+70 -3
View File
@@ -7,6 +7,7 @@ the tracker has lost the other), EyeWeights (how much each eye counts), and Stea
reports them.
"""
import json
import math
import os
import statistics
@@ -397,6 +398,63 @@ class LiveCorrection:
EYE_LOST = 0.004
EYE_FOUND = 0.0025
# SteamOS 0.4's "Track Dominant Eye Only" (SteamVR's settings, General, advanced): SteamVR's
# tracker ignores the other eye, for someone whose eyes don't look at the same spot. Its
# settings: steamvr.eyeTrackingDominantEyeOnly, and steamvr.dominantEye (0 left, 1 right,
# SteamVR's default). Frametop then goes by that eye alone: a calibration that waits for both
# eyes would never take a dot, and the other eye's reading isn't where the person looks.
STEAMVR_SETTINGS = (Path.home() / ".config" / "openvr" / "config" / "steamvr.vrsettings",
Path.home() / ".steam" / "steam" / "config" / "steamvr.vrsettings")
def tracked_eye(paths=STEAMVR_SETTINGS):
"""The one eye SteamVR's tracker follows (0 left, 1 right), or None for both. The first
of the settings files that exists counts (SteamVR keeps only settings changed from its
defaults, so a missing key is the default)."""
for path in paths:
try:
text = Path(path).read_text()
except OSError:
continue
try:
steamvr = json.loads(text).get("steamvr")
except (ValueError, AttributeError):
return None
if not isinstance(steamvr, dict) or steamvr.get("eyeTrackingDominantEyeOnly") is not True:
return None
return 0 if steamvr.get("dominantEye", 1) == 0 else 1
return None
class TrackedEye:
"""tracked_eye(), read again when SteamVR's settings file changes (looked at no more than
every CHECK seconds), since the setting can change while a service runs."""
CHECK = 2.0
def __init__(self, paths=STEAMVR_SETTINGS):
self.paths = paths
self.eye = None
self.stamp = None
self.checked = None
def __call__(self, now=None):
now = time.monotonic() if now is None else now
if self.checked is not None and now - self.checked < self.CHECK:
return self.eye
self.checked = now
stamp = []
for path in self.paths:
try:
st = os.stat(path)
stamp.append((st.st_mtime_ns, st.st_size))
except OSError:
stamp.append(None)
if stamp != self.stamp:
self.stamp = stamp
self.eye = tracked_eye(self.paths)
return self.eye
class EyeFallback:
"""The gaze from one eye, while the tracker has lost the other.
@@ -640,7 +698,7 @@ def cross_validate(points, mode):
return errs
def steady_samples(samples, vergence_jump=1.5, why=None):
def steady_samples(samples, vergence_jump=1.5, why=None, eye=None):
"""The samples of one look at one spot where the tracker had both eyes: none in a blink
(openness under half its median over the samples), none where it had lost an eye (its
variance over EYE_LOST), and none where the angle between the eyes' directions (`lr`, the
@@ -648,28 +706,37 @@ def steady_samples(samples, vergence_jump=1.5, why=None):
vergence itself depends on distance (about 2.8 degrees for a screen 1.3 m away, a
fraction of one far off), so only a jump away from what it was during this look means
the tracker lost an eye. Without the mmap there's nothing to judge by: all are kept.
`eye` (0 left, 1 right; see tracked_eye) judges that eye alone: the other one's loss,
openness and the vergence don't count.
`why`, a dict, gets how many were dropped for each reason: "lost_left", "lost_right",
"lost_both", "blink" and "vergence" (each sample once, for the first that applies)."""
if why is None:
why = {}
def openness(o):
return o[eye] if eye is not None else min(o)
# Openness: a blink is a sharp drop from what it was during this look. Not a fixed
# level: looking down, the upper lids come down with the eyes, and in bright light you
# squint, so the reading can stay under 0.5 for the whole look while the tracker follows
# the eyes fine (a calibration dot at the bottom of the bright round failed that way).
opens = [min(o) for o in ((smp["src"].get("mmap1") or {}).get("open") for smp in samples) if o]
opens = [openness(o) for o in ((smp["src"].get("mmap1") or {}).get("open") for smp in samples) if o]
floor = max(0.12, 0.5 * statistics.median(opens)) if len(opens) >= 5 else 0.12
seen = []
for smp in samples:
m1 = smp["src"].get("mmap1") or {}
o = m1.get("open")
lost = [u > EYE_LOST for u in m1.get("unc") or [0, 0]]
if eye is not None:
lost[1 - eye] = False
# A lost eye's openness reads 0 too, so a lost eye is named before a blink.
key = ("lost_both" if all(lost) else "lost_left" if lost[0] else "lost_right") if any(lost) else \
"blink" if o and min(o) < floor else None
"blink" if o and openness(o) < floor else None
if key:
why[key] = why.get(key, 0) + 1
else:
seen.append(smp)
if eye is not None:
return seen
def vergence(smp):
return (smp["src"].get("mmap1") or {}).get("lr", (smp["src"].get("mmap2") or {}).get("lr"))
+445 -31
View File
@@ -14,7 +14,8 @@ directions: look at each one.
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.
were all over FIVE_LIMIT degrees off: the quick check didn't fix it. Its panel is
wider than quick's, to hold them (PANEL_DEG).
full the calibration, as the gaze probe's: three rounds, dark, medium and bright (pupil
size, and the tracker's error with it, changes with brightness), each the middle and
a ring of six (SteamVR's tracker) or eight (ours, whose fit goes wrong past its dots)
@@ -31,6 +32,28 @@ directions: look at each one.
seen) and hints, from the gaze probe's Headset fit (gaze/fitcheck.py), while you
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.
With our tracker installed, its first hint line is the fit coach's (gaze/fitcoach.py):
where the headset sits, from where ft-eyes sees each pupil and glint (ft-eyes "fit",
run for the check whichever tracker is in use). It's judged only while you look
straight ahead (COACH_CENTRE), since the pupils move with the gaze. A good reading
(the coach's "ok") is kept as your saved fit when the check closes (fitcoach.BASELINE,
with SteamVR's IPD setting from the panel): the put-on check compares with it.
The fit watch (GAZE_FIT_WATCH=1 in frametop.conf, off by default until it's been tried; read
again when the file changes) adds two things, with our tracker installed, its reference
(gaze/fit-reference.json) and a saved fit:
put-on the quick check that opens when the headset goes on first reads the fit coach while
you look at its dot, against your saved fit, and holds the dot meanwhile (at most
PUTON_READ). If the headset sits more than fitcoach.MOVED_DEG from it, or the IPD
setting changed, the panel widens (five's size) and says which way to move it, live,
until it's back; then the dot is taken as usual. A left click or Meta+J takes it as
it sits, and after PUTON_TIMEOUT it's taken anyway. So the click teaches our tracker
the headset where you meant it to be, not where it landed.
slip while gaze mode is on with our tracker, ft-eyes' glint jump (the headset slipped
since the last click; "jump_px" in its status) past fitcoach.MOVED_DEG for SLIP_HOLD
shows a small note low in view for NOTE_SECONDS (the panel's "note" strip: "Your
headset slipped" and which way to push it), at most once every NOTE_COOLDOWN, and
never over a check. It goes sooner once the slip is gone.
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.
@@ -45,8 +68,10 @@ the dot), and the gaze held still up to then is taken (ACCEPT_SPREAD). They wait
it takes, up to CLICK_IDLE. A dot not taken says why in the panel's note line (reject_reason:
gazecal.steady_samples' drop counts for SteamVR's tracker, ft-eyes' reply for ours), as does a
click with nothing taken after ACCEPT_WAIT, and a failed calibration names its most common
reason there and in the status. A right click or Meta+K ("calquit") closes the panel. The pointer hides meanwhile ("calpanel 1",
renewed every second; the helper shows it again by itself when that stops).
reason there and in the status. A right click or Meta+K ("calquit") closes the panel. A press
mapped to gaze precision or gaze drag counts as the left click (pointer/helper/calpanel.h). 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
@@ -55,6 +80,12 @@ are enough to start it, each dot stands in for the gaze, and a click takes the C
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.
The service doesn't wait for ft-eyes' answers to calib-point and calib-fit (ask_eyes): the dot
shows its ring full, and further clicks do nothing until the answer comes, or its deadline
passes; while it fits, a right click doesn't close the panel either. Until 2026-10-09 it waited, up to 3 s a dot and 10 s for the fit, so the gaze stopped,
the helper's panel lease ran out (the pointer came back, and a click went to the desktop
behind the panel), and an answer over EYES_GONE closed the calibration as the headset coming off.
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)
@@ -74,8 +105,10 @@ import statistics
import subprocess
import sys
import time
from collections import deque
from pathlib import Path
import fitcoach
from fitcheck import MIN_REGION, FitCheck, wrap
from gazecal import DEFAULT_MODEL, EYE_LOST, STATE, steady_samples
@@ -112,6 +145,15 @@ FULL_RETRY = 10.0 # seconds before an automatic calibration that failed to
FIT_TIMEOUT = 300.0 # seconds the fit check stays up
FIT_EVERY = 0.5 # seconds between its cards' updates (each is a new picture for the panel)
FIT_HINT_WIDTH = 95 # characters a hint line holds in the panel
COACH_CENTRE = 8.0 # degrees: the fit coach judges only while the gaze stays this near straight ahead
COACH_LEASE = 5.0 # seconds of ft-eyes asked for at a time, while the fit check is up
PUTON_REASON = "the headset went on"
PUTON_READ = 4.0 # seconds the put-on check holds the dot for a straight-ahead reading
PUTON_TIMEOUT = 30.0 # seconds it says what to move before the dot is taken as it sits
PUTON_GONE = 5.0 # seconds without eyes that close it meanwhile (adjusting loses them)
SLIP_HOLD = 2.0 # seconds a slip lasts before its note
NOTE_SECONDS = 8.0
NOTE_COOLDOWN = 120.0
def log(msg):
@@ -172,6 +214,26 @@ def reject_reason(reply, why):
return text[:24], f"our tracker said: {text}", False
# The panel's sizes for each check (ft-gazepanel.cpp's kQuickDeg, kFiveDeg, kFullDeg): width in
# degrees, and height / width. Every dot of a check must fit its panel (off_panel).
PANEL_DEG = {"quick": (16.0, 1.0), "five": (40.0, 0.75), "full": (64.0, 0.75)}
def off_panel(kind, own):
"""The dots of a check that wouldn't show whole on its panel: the panel's projection
(ft-gazepanel's ToPixel), with a degree to spare for the dot's ring."""
wdeg, aspect = PANEL_DEG[kind]
half = math.tan(math.radians(wdeg / 2))
m = math.tan(math.radians(1.0)) / (2 * half)
out = []
for yaw, pitch, _ in check_dots(kind, own):
x = 0.5 - math.tan(math.radians(yaw)) / (2 * half)
y = 0.5 - math.tan(math.radians(pitch)) / math.cos(math.radians(yaw)) / (2 * half) / aspect
if not (m <= x <= 1 - m and m / aspect <= y <= 1 - m / aspect):
out.append((yaw, pitch))
return out
def spread(points):
"""The median point and the spread around it (1.4826 x the median distance: a standard
deviation that one stray sample can't move far)."""
@@ -239,6 +301,12 @@ class Checks:
self.panel_restart_at = 0.0
self.screens_shown = None
self.last_progress = 0.0
self.asking = None # (socket, deadline, done): a command to ft-eyes waiting for its reply
self.watch = (None, False) # (frametop.conf's mtime, GAZE_FIT_WATCH on)
self.slip_ref = None # the fit coach's reference, for the slip note (loaded once)
self.slip_since = None # a slip past MOVED_DEG since then
self.note_until = None # the slip note shows until then
self.note_next = 0.0 # and not again before
@property
def active(self):
@@ -324,6 +392,48 @@ class Checks:
if was != (on, headset):
self.svc.update_awake()
def ask_eyes(self, command, timeout, done):
"""A command to ft-eyes whose reply comes later: done(reply) runs from on_eyes_reply, or with
"" after `timeout` (tick), as ask() gives without one. ask() held the whole service up to 3 s
a dot (calib-point) and 10 s at the end (calib-fit): the gaze stopped, and the helper's 3 s
calpanel lease ran out, so the pointer came back and a click went to the desktop behind the
panel. Each command has its own socket, so a late reply can't be taken for the next one."""
self.drop_ask()
s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM | socket.SOCK_CLOEXEC | socket.SOCK_NONBLOCK)
try:
s.bind("")
s.sendto(command.encode(), EYES)
except OSError:
s.close()
done("")
return
self.sel.register(s, selectors.EVENT_READ, "eyes_reply")
self.asking = (s, time.monotonic() + timeout, done)
def on_eyes_reply(self, sock):
if not self.asking or self.asking[0] is not sock:
return # dropped already (closed, or timed out in this loop)
try:
reply = sock.recv(4096).decode("utf-8", "replace")
except BlockingIOError:
return
except OSError:
reply = ""
done = self.asking[2]
self.drop_ask()
done(reply)
def drop_ask(self):
if not self.asking:
return
s = self.asking[0]
self.asking = None
try:
self.sel.unregister(s)
except (KeyError, ValueError):
pass
s.close()
# --- State ---
def calibrated(self):
@@ -418,6 +528,34 @@ class Checks:
return
self.start("quick", reason)
def fit_watch(self):
"""GAZE_FIT_WATCH=1 in frametop.conf: the put-on check and the slip note (see the top)."""
try:
m = CONF.stat().st_mtime_ns
except OSError:
m = None
if m != self.watch[0]:
on = False
try:
for line in CONF.read_text().splitlines():
k, _, v = line.split("#", 1)[0].partition("=")
if k.strip() == "GAZE_FIT_WATCH":
on = v.strip() == "1"
except OSError:
pass
if on != self.watch[1]:
log(f"fit watch {'on' if on else 'off'}")
self.watch = (m, on)
return self.watch[1]
def panel_ipd(self):
"""SteamVR's IPD setting (metres) from the panel, or None."""
words = ask(PANEL, "ipd", 0.3).split()
try:
return float(words[1]) if words[:1] == ["ok"] and float(words[1]) > 0 else None
except (IndexError, ValueError):
return None
# --- Running a check ---
def start(self, kind, reason):
@@ -446,13 +584,19 @@ class Checks:
"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 ""))
self.note_until = None # the check's panel replaces the slip note
if kind == "quick" and reason == PUTON_REASON:
self.start_puton(now)
if kind == "full":
st = ask(SCREENS, "state", 0.5).split()
if len(st) >= 3 and st[0] == "ok":
self.screens_shown = (st[2] == "0") if st[1] == "always" else (st[2] == "1")
ask(SCREENS, "hide", 0.5)
self.to_helper("calpanel 1")
self.to_panel(f"show {'full' if kind == 'full' else 'quick'}")
off = off_panel(kind, own)
if off:
log(f"{kind} check: {len(off)} dots off its panel: {off}")
self.to_panel(f"show {kind}")
self.show_dot()
if kind == "quick":
self.last_quick = now
@@ -463,19 +607,219 @@ class Checks:
if time.monotonic() - self.sample_at > 2:
return "error the headset is off or the eye tracker isn't sending"
now = time.monotonic()
ignore = None if self.svc.one_eye is None else 1 - self.svc.one_eye # the eye SteamVR ignores
self.check = {"kind": "fit", "reason": reason, "own": False, "dots": [], "i": 0, "started": now, "shown": now,
"run": [], "accept": False, "done_at": None, "tries": 0, "skipped": 0, "captured": 0,
"points": {}, "fit": FitCheck(), "drawn": {}, "drawn_at": 0.0, "step": None}
"points": {}, "fit": FitCheck(ignore=ignore), "drawn": {}, "drawn_at": 0.0, "step": None,
"coach": self.new_coach()}
log(f"fit check: {reason}")
self.note_until = None
if self.check["coach"]:
self.check["coach"]["ipd"] = self.panel_ipd()
self.to_helper("calpanel 1")
self.to_panel("show fit")
self.to_panel("title Headset fit: adjust the headset while you watch")
self.to_panel("text Left click or Meta+J: guided check · Right click or Meta+K: done")
return "ok"
def new_coach(self):
"""The fit coach's part of the fit check, or None without our tracker (or its reference)."""
if not self.svc.own_installed():
return None
ref = fitcoach.Reference.load()
if ref is None:
log(f"fit coach: no reference ({fitcoach.REFERENCE})")
return None
return {"ref": ref, "baseline": fitcoach.load_baseline(), "reading": None, "summary": None,
"looks": deque(), "centred": False, "logged": None, "ipd": None, "good": None}
def coach_feed(self, s, now):
k = self.check["coach"]
m1 = s["src"].get("mmap1") or {}
if k is None or "hy" not in m1:
return
k["looks"].append((now, m1["hy"], m1["hp"]))
while k["looks"] and k["looks"][0][0] < now - fitcoach.WINDOW:
k["looks"].popleft()
def coach_tick(self, now):
"""Keeps ft-eyes running and asks it for the last second of finds; judged when centred."""
k = self.check["coach"]
if k is None:
return
svc = self.svc
svc.eyes_until = max(svc.eyes_until, now + COACH_LEASE)
looks = k["looks"]
k["centred"] = (len(looks) >= 10 and looks[-1][0] - looks[0][0] > 0.8 * fitcoach.WINDOW
and all(math.hypot(y, p) <= COACH_CENTRE for _, y, p in looks))
if self.asking:
if now >= self.asking[1]:
self.drop_ask()
return
if not svc.eyes_proc:
k["summary"] = None
return
centred = k["centred"]
def got(reply):
try:
summary = {int(cam): v for cam, v in json.loads(reply).items()}
except (ValueError, AttributeError):
k["summary"] = None
return
k["summary"] = summary
if centred and self.check and self.check.get("coach") is k:
k["reading"] = fitcoach.assess(summary, k["ref"], ipd=k["ipd"], baseline=k["baseline"],
previous=k["reading"])
if k["reading"]["state"] == "ok":
k["good"] = summary # (the fit check keeps the last as your saved fit)
self.ask_eyes("fit", 0.4, got)
def coach_lines(self):
"""The fit coach's hints for the panel (first), or [] without it."""
c = self.check
k = c.get("coach")
if k is None:
return []
if k["summary"] is None:
return ["Headset position: starting our eye tracker..."]
if not k["centred"]:
if k["reading"] is None:
return ["Headset position: look straight ahead for a moment."]
return [f"Headset position (when you last looked straight ahead): {self.coach_words(k['reading'])}"]
return [f"Headset position: {self.coach_words(k['reading'])}"] if k["reading"] else []
@staticmethod
def coach_words(r):
if r["state"] == "waiting":
return "waiting for both eyes."
hints = " ".join(h["text"] for h in r["hints"][:2])
if r["state"] == "ok":
words = "good." + (f" {hints}" if hints else "")
else:
words = hints or "a little off."
if r["provisional"] and r["against"] == "reference":
words += " (A first guess: measured on one face so far.)"
return words
# --- The put-on check (the fit watch: see the top) ---
def start_puton(self, now):
c = self.check
if not self.fit_watch():
return
k = self.new_coach()
if k is None or not k["baseline"]:
if k is not None:
log("put-on check: no saved fit yet (Check headset fit saves a good one)")
return
k["ipd"] = self.panel_ipd()
c["coach"] = k
c["puton"] = {"state": "reading", "until": now + PUTON_READ, "since": now, "lines": None}
log("put-on check: reading the fit against your saved one")
def puton_holds(self, c):
"""The put-on check holds the quick check's dot (reading, or the headset moved)."""
return (c.get("puton") or {}).get("state") in ("reading", "moved")
def puton_tick(self, now):
c = self.check
pu, k = c["puton"], c["coach"]
if not self.puton_holds(c):
return # (no more asks: the quick check skips samples while one waits)
self.coach_tick(now)
if c["accept"]:
self.puton_done("the dot taken as the headset sits (a click)")
return
r = k["reading"] if k["centred"] and k["summary"] is not None else None
if r is not None and r["state"] == "waiting":
r = None
if pu["state"] == "reading":
if r is None:
if now > pu["until"]:
self.puton_done("no straight-ahead reading in time; the dot is taken as usual")
return
if not fitcoach.moved(r):
self.puton_done("the headset sits as your saved fit")
return
pu["state"], pu["since"] = "moved", now
log("put-on check: the headset moved since your saved fit: terms "
+ ", ".join(f"{n} {v:+.1f}" for n, v in r["terms"].items()))
self.to_panel("show five") # wider: the hints don't fit quick's square
self.to_panel("title The headset sits differently from your saved fit")
self.show_dot()
self.puton_lines(r)
return
if r is not None and not fitcoach.moved(r):
self.note("Good: it's back where it was")
self.puton_done("the headset is back as your saved fit")
return
if r is not None:
self.puton_lines(r)
if now - pu["since"] > PUTON_TIMEOUT:
self.puton_done(f"not back after {PUTON_TIMEOUT:.0f} s: the dot is taken as the headset sits")
def puton_lines(self, r):
"""What to move, in the panel: the position hint at the bottom, a changed IPD over it."""
pu = self.check["puton"]
ipd = next((h["text"] for h in r["hints"] if h["key"] == "ipd-changed"), "")
pos = fitcoach.position_hint(r["terms"])
lines = (pos["text"] if pos else "Move the headset back where it sat, then look at the dot", ipd)
if lines != pu["lines"]:
pu["lines"] = lines
self.to_panel(f"text {lines[0]}")
self.note(lines[1])
def puton_done(self, why):
c = self.check
now = time.monotonic()
c["puton"]["state"], c["puton"]["why"] = "done", why
log(f"put-on check: {why}")
c["run"], c["started"], c["shown"] = [], now, now # the quick check's own time starts now
if c["puton"]["lines"]:
self.to_panel("text Look at the dot")
# --- The slip note (the fit watch: see the top) ---
def slip_watch(self, now):
svc = self.svc
own = svc.own if now - svc.own_at < 3 else {}
on = (svc.kind == "own" and svc.eyes_proc is not None and own and self.gaze_on
and self.headset is not False and not self.check and self.fit_watch())
hint = None
if on:
if self.slip_ref is None:
self.slip_ref = fitcoach.Reference.load() or False
jumps = {}
for cam, name in enumerate(fitcoach.EYES):
j = (own.get("eyes") or {}).get(name, {}).get("jump_px")
if j and any(j):
jumps[cam] = j
hint = fitcoach.position_hint(fitcoach.slip_terms(jumps, self.slip_ref or None))
if hint is None:
self.slip_since = None
if self.note_until is not None and not self.check:
self.to_panel("hide")
self.note_until = None
return
if self.note_until is not None:
if now >= self.note_until:
self.to_panel("hide")
self.note_until = None
return
if self.slip_since is None:
self.slip_since = now
if now - self.slip_since >= SLIP_HOLD and now >= self.note_next:
self.to_panel("show note")
self.to_panel("title Your headset slipped")
self.to_panel(f"text {hint['text']}")
self.note_until, self.note_next = now + NOTE_SECONDS, now + NOTE_COOLDOWN
log(f"slip note: {hint['text']} ({hint['amount']:+.1f} deg)")
def fit_tick(self, now):
c = self.check
fit = c["fit"]
self.coach_tick(now)
# The guided check: its dots at head-relative directions in the panel (the probe's
# screen fractions, spread over the middle of the panel), and its looks as the title.
step = fit.guide_step(now)
@@ -508,6 +852,7 @@ class Checks:
hints = ["Look around slowly: up, down, left and right. Or left click (Meta+J) for a guided check."]
else:
hints = fit.hints()
hints = self.coach_lines() + hints
lines = [line for h in hints for line in wrap(h, FIT_HINT_WIDTH)][:8]
cmd = "hints " + "|".join(lines)
if drawn.get("hints") != cmd:
@@ -535,16 +880,20 @@ class Checks:
if self.pending:
self.run_pending()
unc = (s["src"].get("mmap1") or {}).get("unc")
if unc and min(unc) <= EYE_LOST:
one = self.svc.one_eye
if unc and (min(unc) if one is None else unc[one]) <= EYE_LOST:
self.seen_at = time.monotonic()
if self.away and self.back_since is None:
self.back_since = self.seen_at
c = self.check
if c and c["kind"] == "fit":
c["fit"].feed(s, self.sample_at)
self.coach_feed(s, self.sample_at)
return
if not c or c["done_at"]:
return
if c and self.puton_holds(c):
self.coach_feed(s, self.sample_at)
if not c or c["done_at"] or self.asking:
return # (asking: ft-eyes has this dot's look, or the fit)
if c["own"]:
src = s["src"].get("own") or {}
if c["blind"]:
@@ -563,7 +912,7 @@ class Checks:
return
now = time.monotonic()
c["gaze_at"] = now
if now < c["shown"] + CHECK_SETTLE:
if now < c["shown"] + CHECK_SETTLE or self.puton_holds(c):
return
g = (src["hy"], src["hp"])
run = c["run"]
@@ -612,9 +961,12 @@ class Checks:
rec.update(eyes=eyes, miss=miss)
t0, t1 = samples[0]["t"], samples[-1]["t"]
if c["kind"] == "full":
reply = ask(EYES, f"calib-point {t0:.6f} {t1:.6f} {yaw:.4f} {pitch:.4f}", 3.0)
rec["reply"] = reply
ok = reply.startswith("ok")
# ft-eyes checks the pupils held still: its answer takes the dot or not (point_done).
# The ring shows it full meanwhile, so the click is seen to have landed.
self.to_panel(f"dot {yaw:.3f} {pitch:.3f} capture 1.00")
self.ask_eyes(f"calib-point {t0:.6f} {t1:.6f} {yaw:.4f} {pitch:.4f}", 3.0,
lambda reply: self.point_done(rec, miss, reply))
return
else:
try:
svc.eyes_sock.sendto(f"click {t1:.6f} {yaw:.4f} {pitch:.4f}".encode(), EYES)
@@ -624,7 +976,8 @@ class Checks:
svc.weights["own"].add(miss)
else:
why = {}
steady = steady_samples(samples, why=why)
one = svc.one_eye
steady = steady_samples(samples, why=why, eye=one)
rec["dropped"] = why
reads = {}
for name in ("action", "mmap1", "mmap2", "left", "right"):
@@ -632,11 +985,20 @@ class Checks:
if "hy" in (smp["src"].get(name) or {})]
if len(pts) >= 15:
reads[name] = (statistics.median(p[0] for p in pts), statistics.median(p[1] for p in pts))
if one is not None:
# SteamVR tracks one eye (gazecal.tracked_eye): the other's reading isn't where
# you look, and set 2's average has it in, so mmap2 is that eye's own (as ft-gazed
# sends it then).
reads.pop(("left", "right")[1 - one], None)
reads.pop("mmap2", None)
if ("left", "right")[one] in reads:
reads["mmap2"] = reads[("left", "right")[one]]
rec["reads"] = reads
main = ("left", "right") if svc.kind == "eyes" else (svc.source,)
main = (("left", "right") if one is None else (("left", "right")[one],)) if svc.kind == "eyes" else (svc.source,)
if not all(n in reads for n in main):
ok = False
rec["reply"] = f"only {len(steady)} of {len(samples)} samples had both eyes"
rec["reply"] = f"only {len(steady)} of {len(samples)} samples had " + (
"both eyes" if one is None else f"your {('left', 'right')[one]} eye")
elif c["kind"] == "full":
for name, (hy, hp) in reads.items():
c["points"].setdefault(name, []).append((hy, hp, yaw - hy, pitch - hp))
@@ -656,9 +1018,23 @@ class Checks:
svc.lives[name].add({"time": time.time(), "hy": hy, "hp": hp, "dy": yaw - hy, "dp": pitch - hp,
"wy": 1.0, "wp": 1.0, "how": "check"}, svc.models[name], svc.mode)
rec["miss"] = miss
if svc.kind == "eyes":
if svc.kind == "eyes" and len(miss) == 2: # (one eye tracked: nothing to weigh)
svc.weights["steam"].add(miss)
svc.dirty = True
self.captured(rec, ok)
def point_done(self, rec, miss, reply):
"""ft-eyes' answer to a full calibration dot's calib-point ("" without one)."""
rec["reply"] = reply
ok = reply.startswith("ok")
if ok:
self.svc.weights["own"].add(miss)
self.captured(rec, ok)
def captured(self, rec, ok):
"""A capture is over: the dot is taken, tried again, or skipped."""
c = self.check
yaw, pitch, _ = c["dots"][c["i"]]
if not ok:
short, long, fit = reject_reason(rec.get("reply", "") if c["own"] else None, rec.get("dropped"))
rec["reason"] = long
@@ -670,9 +1046,9 @@ class Checks:
if not ok:
c["tries"] += 1
log(f"{c['kind']} check dot {c['i'] + 1}: not taken: {rec['reason']} ({rec.get('reply', '')})")
full = c["kind"] == "full"
full, big = c["kind"] == "full", c["kind"] != "quick" # quick's panel holds only short notes
if c["tries"] >= 2 or not full:
self.note(f"Dot skipped: {long}" + (f" ({FIT_HINT})" if fit else "") if full else f"Skipped: {short}")
self.note(f"Dot skipped: {long}" + (f" ({FIT_HINT})" if fit else "") if big else f"Skipped: {short}")
self.skip()
else:
self.note(f"Not taken: {long}. Look at the dot and click again")
@@ -737,8 +1113,15 @@ class Checks:
return
self.full_failed = None
if c["own"]:
reply = ask(EYES, "calib-fit", 10.0)
log(f"calibration ({c['captured']} of {n} dots): our tracker says {reply or 'nothing'}")
def fitted(reply):
log(f"calibration ({c['captured']} of {n} dots): our tracker says {reply or 'nothing'}")
self.close()
self.to_panel("text Saving the calibration")
c["done_at"] = None # (tick would advance past the last dot again)
c["fitting"] = True
self.ask_eyes("calib-fit", 10.0, fitted)
return
else:
mode = svc.mode if svc.mode != "none" else DEFAULT_MODEL
for name, pts in c["points"].items():
@@ -761,6 +1144,18 @@ class Checks:
return
if why:
log(f"{self.check['kind']} check closed: {why}")
k = self.check.get("coach")
if k and k["reading"]:
r = k["reading"]
log(f"fit coach, last reading: {r['state']} against the {r['against']}, terms "
+ ", ".join(f"{n} {v:+.1f}" for n, v in r["terms"].items()))
if k and k["good"] and self.check["kind"] == "fit":
try:
fitcoach.save_baseline(fitcoach.make_baseline(k["good"], k["ipd"]))
log(f"fit coach: a good fit, saved as yours ({fitcoach.BASELINE})")
except OSError as e:
log(f"fit coach: can't save the fit: {e}")
self.drop_ask()
self.to_panel("hide")
self.to_helper("calpanel 0")
if self.check["kind"] == "full" and self.screens_shown:
@@ -770,8 +1165,8 @@ class Checks:
def quit(self):
c = self.check
if not c:
return
if not c or c.get("fitting"):
return # (fitting: ft-eyes has every dot; the panel closes once it answers)
self.close("quit")
if c["kind"] == "full" and self.calibrated() is False:
# No calibration still: gaze mode can't work, so it goes off until it's turned on again.
@@ -807,9 +1202,9 @@ class Checks:
log(f"{words[0]}, asked for while idle: {reply.removeprefix('error ')}")
def command(self, words, queue=True):
"""quickcal, calibrate, calaccept, calquit -> a reply."""
"""quickcal, calibrate, fitcheck, fivecheck, calaccept, calquit -> a reply."""
cmd = words[0]
if cmd in ("quickcal", "calibrate", "fitcheck") and queue and self.svc.waking() and not self.check:
if cmd in ("quickcal", "calibrate", "fitcheck", "fivecheck") 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()
@@ -820,10 +1215,13 @@ class Checks:
return self.start("full", "asked for")
if cmd == "fitcheck":
return self.start("fit", "asked for")
if cmd == "fivecheck":
return self.start("five", "asked for")
if cmd == "calaccept":
if self.check and self.check["kind"] == "fit":
self.check["fit"].toggle_guide(time.monotonic())
elif self.check:
elif self.check and (not self.asking or self.puton_holds(self.check)):
# (asking: this dot's click landed already; the put-on check's asks are the coach's)
if not self.check["accept"]:
self.check["accept_at"] = time.monotonic()
self.check["accept"] = True
@@ -861,25 +1259,37 @@ class Checks:
else:
self.fit_tick(now)
return
if c.get("puton"):
self.puton_tick(now)
c = self.check
if not c:
return
if self.asking:
# ft-eyes has a dot's look or the fit: wait for its answer, at most to the deadline.
if now >= self.asking[1]:
done = self.asking[2]
self.drop_ask()
done("")
return
if c["done_at"] and now >= c["done_at"]:
if c.get("closing"):
self.close()
else:
self.advance()
return
if not self.eyes_seen(EYES_GONE):
if not self.eyes_seen(PUTON_GONE if self.puton_holds(c) else EYES_GONE):
self.close("the headset came off")
return
if c["done_at"]:
return
if c["accept"] and c["accept_at"] and now - c["accept_at"] > ACCEPT_WAIT:
# Clicked, but no capture yet (see on_sample): say what it's waiting for.
full = c["kind"] == "full"
big = c["kind"] != "quick"
if now - c.get("gaze_at", 0.0) > 0.5:
self.note("Waiting: the eye tracker isn't sending a gaze" if full else "Waiting: no gaze")
self.note("Waiting: the eye tracker isn't sending a gaze" if big else "Waiting: no gaze")
else:
self.note("Waiting for your gaze to hold still on the dot" if full else "Hold your look still")
if c["kind"] == "quick" and now - c["started"] > QUICK_TIMEOUT:
self.note("Waiting for your gaze to hold still on the dot" if big else "Hold your look still")
if c["kind"] == "quick" and now - c["started"] > QUICK_TIMEOUT and not self.puton_holds(c):
self.close("ignored")
elif c["kind"] != "quick" and now - c["shown"] > CLICK_IDLE:
self.close(f"no click on dot {c['i'] + 1} for {CLICK_IDLE:.0f} s")
@@ -916,6 +1326,7 @@ class Checks:
self.reseat_seen = True
self.auto_quick("our tracker asked for a click")
self.need_full("gaze mode is on without a calibration")
self.slip_watch(now)
def status(self):
c = self.check
@@ -923,10 +1334,13 @@ class Checks:
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}
"last_quick_s": round(time.monotonic() - self.last_quick) if self.last_quick else None,
"fit_watch": self.watch[1], "slip_note": self.note_until is not None}
if c:
st["check"] = {"kind": c["kind"], "dot": c["i"] + 1, "dots": len(c["dots"]), "captured": c["captured"],
"skipped": c["skipped"], "reason": c["reason"]}
if c.get("puton"):
st["check"]["puton"] = c["puton"]["state"]
return st
def stop(self):
+708 -68
View File
@@ -7,14 +7,19 @@
//
// The panel sits POINTER-like at --distance (1.5 m, about where Frametop's screens are, so
// the eyes converge as they do in use). "quick" is a small square, QUICK_DEG across, for the
// one-dot check; "full" is FULL_DEG across (4:3), with a solid background whose brightness the
// service sets per round (pupil size changes with it, and the tracker's error with it); "fit"
// is FIT_DEG across (4:3), see-through like quick, for the headset fit check: a card per eye
// (tracked or lost, the tracker's signal, how much of the last 10 s it was seen) and hints.
// one-dot check; "five" is FIVE_DEG across (4:3), see-through like quick, for the five-dot
// check, whose dots are 12 degrees left and right and 9 up and down; "full" is FULL_DEG
// across (4:3), with a solid background whose brightness the service sets per round (pupil
// size changes with it, and the tracker's error with it); "fit" is FIT_DEG across (4:3),
// see-through like quick, for the headset fit check: a card per eye (tracked or lost, the
// tracker's signal, how much of the last 10 s it was seen) and hints. Every dot a check shows
// must fit its panel: gazecheck.py's PANEL_DEG mirrors these sizes and checks it. "note" is a
// strip NOTE_DEG across (4:1), see-through, NOTE_PITCH degrees below straight ahead, for the gaze
// service's slip notice: its title and text lines only, no dot.
//
// Control socket: abstract unix datagram "@ft_gazepanel" (--socket NAME); a sender with an
// address gets "ok" or "error ...":
// show quick|full|fit the panel, empty, in front of you
// show quick|five|full|fit|note the panel, empty, in front of you (note: below it)
// hide
// bg <0..1> the background's brightness (full)
// dot <yaw> <pitch> <state> [<progress 0..1>]
@@ -30,6 +35,48 @@
// hints <line>|<line>|... fit: lines under the cards (empty to clear)
// ping
//
// The eye recorder's mode (gaze/rec/DESIGN.md, "Panel"): "show rec" is FULL_DEG across with
// the full calibration's solid background (bg), and the hand panel's lines (hands/rec/panel):
// title <text> the big line at the top
// step <text> a small line at the top right, "Round 2 of 5"; rec on|off puts a
// red "Rec" dot by it
// text <text> the instruction, under the title, wrapped ("|" starts a line)
// big <text> / action <text> large in the middle (the countdown) / a cyan line under it
// note <text> / keys <text> the orange warning line / a faint line along the bottom
// countdown <0..1>|off a thin bar along the bottom: the share of the step's time left
// paused on|off "Paused" over the picture
// Its dot is a second overlay (OVERLAY.dot), drawn once per state and only moved, so a moving
// dot is smooth at the headset's frame rate and costs no pictures:
// dot <yaw> <pitch> <state> [<progress>] as above, at the panel's distance
// path circle <yaw> <pitch> <radius> <seconds>
// path line <yaw0> <pitch0> <yaw1> <pitch1> <seconds>
// path eight <yaw> <pitch> <yaw radius> <pitch radius> <seconds>
// the dot moves by itself: round the circle once per seconds
// (from the top, going left), along the line and back (seconds
// each way, at a steady speed), or a figure eight (seconds a
// loop; up and down twice per side to side), until the next dot,
// path, world or "dot 0 0 off". Reply: "ok"
// world <x> <y> <z> [<state> [<progress>]]
// a dot fixed in the room: the point is in the head frame now
// (metres, +x right, +y up, -z forward), placed in the room with
// the headset's pose, facing the head as it moves; the same point
// again changes only the state. Reply "ok <room x> <y> <z>"
// (standing universe)
// distance <metres> the panel and its dot that far away (0.25 to 10), the same size
// in degrees (the Depth bounty)
// ipd "ok <metres>": SteamVR's IPD setting now (--no-vr: 0.0630)
// log start <dir> / log stop append to <dir>/targets.jsonl, poses.jsonl and ipd.jsonl (below)
// until stopped; "log stop" replies "ok <targets> <poses> <ipd>"
// targets.jsonl, the ground truth: what the dot did, when. A row for each frame the dot moves in
// (path, world) and for each change (dot, state, background, distance): {"t": when the frame
// reaches the eyes (estimated: the next vsync after the change, plus SteamVR's vsync to photons),
// "set": when the panel set it, both CLOCK_MONOTONIC_RAW seconds, the eye frames' clock;
// "frame": SteamVR's vsync count; "dot": "fixed|path|world|off", "yaw", "pitch" (head-relative
// degrees, for world from the head's predicted pose), "dist" (metres), "state", "progress",
// "bg"}. poses.jsonl: the headset's pose 250 times a second, {"t", "hmd": {"m": 3x4 row-major,
// standing universe, "r": ETrackingResult, "ok"}}. ipd.jsonl: SteamVR's IPD setting at the start
// and when it changes, {"t", "ipd": metres}, looked at 30 times a second as well as on its event.
//
// Each picture goes into the next of three shared buffers (linear DMA-BUFs SteamVR imported
// once, the size of the biggest panel; the texture bounds show the part in use), and the panel
// switches to it, as screens/keyboard.cpp does. SetOverlayRaw, which uploads a new texture each
@@ -38,7 +85,10 @@
// It's only the fallback. A "show" makes the panel visible once its first picture is in.
//
// Options: --watch-stdin (quit when stdin closes: the service runs it), --socket NAME,
// --distance METRES. Runs in the dev container (gaze/build.sh builds it into gaze/build).
// --overlay KEY (frametop.gazepanel; the eye recorder runs a copy of its own next to the gaze
// service's), --distance METRES, --no-vr (no SteamVR: for tests, at a made-up 90 Hz vsync; with
// --dump DIR each picture goes there as a PAM file). Runs in the dev container (gaze/build.sh
// builds it into gaze/build).
#include <openvr.h>
#define STB_TRUETYPE_IMPLEMENTATION
@@ -48,6 +98,7 @@
#include <fcntl.h>
#include <gbm.h>
#include <poll.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
@@ -61,6 +112,7 @@
#include <cstdlib>
#include <cstring>
#include <map>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
@@ -71,8 +123,23 @@ using Clock = std::chrono::steady_clock;
constexpr double kQuickDeg = 16; // QUICK_DEG: the one-dot check's square
constexpr double kFullDeg = 64; // FULL_DEG: the full calibration's width (4:3)
constexpr double kFitDeg = 40; // FIT_DEG: the headset fit check's width (4:3)
constexpr int kQuickPx = 320, kFullW = 1024, kFullH = 768, kFitW = 800, kFitH = 600;
constexpr double kFiveDeg = 40; // FIVE_DEG: the five-dot check's width (4:3), past its dots
constexpr double kNoteDeg = 30; // NOTE_DEG: the slip notice's strip (4:1)
constexpr double kNotePitch = -16; // NOTE_PITCH: the strip's centre, degrees below straight ahead
constexpr int kQuickPx = 320, kFullW = 1024, kFullH = 768, kFitW = 800, kFitH = 600, kFiveW = 800, kFiveH = 600;
constexpr int kNoteW = 600, kNoteH = 150;
constexpr double kDotDeg = 1.8; // the rec mode's dot overlay: the ring's 1.5 degrees, and a margin
constexpr int kDotPx = 96;
constexpr int64_t kPosePeriodNs = 4'000'000; // 250 Hz, as the hand panel
constexpr int64_t kIpdPeriodNs = 33'000'000;
std::atomic<bool> g_stop{false};
std::mutex g_vr; // around OpenVR calls once the pose log's thread makes them too
int64_t RawNs() {
timespec ts;
clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
return int64_t(ts.tv_sec) * 1'000'000'000 + ts.tv_nsec;
}
// ---------------------------------------------------------------- text (as screens/keyboard.cpp)
@@ -131,6 +198,41 @@ std::vector<uint32_t> Codepoints(const std::string &s) {
return out;
}
int TextWidth(const std::string &s, int size) {
if (!g_fontOk) return 0;
int width = 0;
for (uint32_t cp : Codepoints(s)) width += GetGlyph(cp, size).advance;
return width;
}
// s as lines no wider than width (the hand panel's): "|" starts a new line, and lines break
// between words.
std::vector<std::string> Wrap(const std::string &s, int size, int width) {
std::vector<std::string> out;
if (s.empty()) return out;
for (size_t at = 0; at <= s.size();) {
const size_t bar = std::min(s.find('|', at), s.size());
const std::string para = s.substr(at, bar - at);
std::string line;
for (size_t w = 0; w < para.size();) {
const size_t space = std::min(para.find(' ', w), para.size());
const std::string word = para.substr(w, space - w);
w = space + 1;
if (word.empty()) continue;
const std::string longer = line.empty() ? word : line + " " + word;
if (line.empty() || TextWidth(longer, size) <= width) {
line = longer;
} else {
out.push_back(line);
line = word;
}
}
out.push_back(line);
at = bar + 1;
}
return out;
}
// ---------------------------------------------------------------- the picture
struct EyeCard {
@@ -139,7 +241,10 @@ struct EyeCard {
};
struct Panel {
bool full = false, fit = false;
bool full = false, fit = false, rec = false, strip = false; // strip: "show note"
std::string step, big, action, keys; // rec
bool recOn = false, paused = false;
double countdown = -1;
EyeCard eyes[2];
std::vector<std::string> hints;
int w = kQuickPx, h = kQuickPx;
@@ -249,9 +354,58 @@ void ToPixel(const Panel &p, double yaw, double pitch, double &x, double &y) {
y = (0.5 - Y / (2 * half) * p.w / p.h) * p.h;
}
void DrawDot(Panel &p, double x, double y, double pxPerDeg, const std::string &state, double progress, double ink);
// The eye recorder's panel (see the top). Its dot is the other overlay's.
void DrawRec(Panel &p, double pxPerDeg) {
const bool light = p.bg > 0.5;
const double faint = light ? 0.2 : 0.75, ink = light ? 0.05 : 0.95;
const int titleSize = int(pxPerDeg * 1.5), textSize = int(pxPerDeg * 1.2), small = int(pxPerDeg * 0.9);
const int bigSize = int(pxPerDeg * 4.0), margin = int(p.w * 0.05);
const int titleY = int(titleSize * 1.2);
Text(p, p.title, titleSize, p.w / 2, titleY, ink);
if (!p.step.empty()) {
const int sw = TextWidth(p.step, small);
Text(p, p.step, small, p.w - margin - sw, titleY, faint, true);
if (p.recOn) {
const int rx = p.w - margin - sw - small;
Disc(p, rx, titleY, small * 0.35, 0, 0.9, 0.15, 0.1, 1);
Text(p, "Rec", small, rx - small - TextWidth("Rec", small), titleY, 1.0, 0.35, 0.3, true);
}
} else if (p.recOn) {
Disc(p, p.w - margin - small * 0.35, titleY, small * 0.35, 0, 0.9, 0.15, 0.1, 1);
}
int y = titleY + int(titleSize * 1.4);
for (const std::string &line : Wrap(p.text, textSize, int(p.w * 0.8))) {
Text(p, line, textSize, p.w / 2, y, faint);
y += int(textSize * 1.35);
}
Text(p, p.big, bigSize, p.w / 2, p.h / 2, ink);
if (light) Text(p, p.action, textSize, p.w / 2, int(p.h * 0.68), 0.0, 0.35, 0.45);
else Text(p, p.action, textSize, p.w / 2, int(p.h * 0.68), 0.35, 0.85, 1.0);
if (light) Text(p, p.note, textSize, p.w / 2, p.h - int(textSize * 2.8), 0.7, 0.12, 0.05);
else Text(p, p.note, textSize, p.w / 2, p.h - int(textSize * 2.8), 1.0, 0.62, 0.3);
Text(p, p.keys, small, p.w / 2, p.h - int(small * 1.6), faint);
if (p.countdown >= 0) {
const int bh = std::max(3, int(pxPerDeg * 0.2));
Rect(p, 0, p.h - bh, p.w, p.h, ink, ink, ink, 0.12);
Rect(p, 0, p.h - bh, int(p.w * std::clamp(p.countdown, 0.0, 1.0)), p.h, 0.35, 0.85, 1.0, 0.9);
}
if (p.paused) {
Rect(p, 0, 0, p.w, p.h, 0, 0, 0, 0.55);
Text(p, "Paused", bigSize, p.w / 2, p.h / 2, 1.0);
}
}
void Draw(Panel &p) {
p.px.assign(size_t(p.w) * p.h * 4, 0);
const double pxPerDeg = p.w / p.wDeg;
if (p.rec) {
for (size_t i = 0; i < p.px.size(); i += 4)
p.px[i] = p.px[i + 1] = p.px[i + 2] = uint8_t(std::lround(p.bg * 255)), p.px[i + 3] = 255;
DrawRec(p, pxPerDeg);
return;
}
if (p.full) {
for (size_t i = 0; i < p.px.size(); i += 4)
p.px[i] = p.px[i + 1] = p.px[i + 2] = uint8_t(std::lround(p.bg * 255)), p.px[i + 3] = 255;
@@ -268,6 +422,12 @@ void Draw(Panel &p) {
}
const bool light = p.full && p.bg > 0.5; // a dark dot on the bright round
const double ink = light ? 0.0 : 1.0, faint = light ? 0.2 : 0.75;
if (p.strip) {
// The slip notice: the title and the hint, together in the middle of the strip.
Text(p, p.title, int(pxPerDeg * 1.4), p.w / 2, int(p.h * 0.36), ink);
Text(p, p.text, int(pxPerDeg * 1.05), p.w / 2, int(p.h * 0.68), faint);
return;
}
const int titleSize = int(pxPerDeg * (p.full ? 1.5 : 1.1)), textSize = int(pxPerDeg * (p.full ? 1.2 : 0.9));
Text(p, p.title, titleSize, p.w / 2, int(titleSize * 1.2), faint);
Text(p, p.text, textSize, p.w / 2, p.h - int(textSize * 1.3), faint);
@@ -278,21 +438,26 @@ void Draw(Panel &p) {
if (!p.dotOn || p.state == "off") return;
double x, y;
ToPixel(p, p.dotYaw, p.dotPitch, x, y);
DrawDot(p, x, y, pxPerDeg, p.state, p.progress, ink);
}
// The dot at (x, y): its look for each state.
void DrawDot(Panel &p, double x, double y, double pxPerDeg, const std::string &state, double progress, double ink) {
const double core = 0.22 * pxPerDeg;
if (p.state == "look") {
if (state == "look") {
// Still, so the panel looks solid and is drawn again only when something changes.
const double rr = 0.75 * pxPerDeg;
Disc(p, x, y, rr, rr - 0.12 * pxPerDeg, ink, ink, ink, 0.6);
Disc(p, x, y, core, 0, ink, ink, ink, 1);
} else if (p.state == "capture") {
} else if (state == "capture") {
const double rr = 0.75 * pxPerDeg;
Disc(p, x, y, rr, rr - 0.12 * pxPerDeg, ink, ink, ink, 0.25);
Disc(p, x, y, rr, rr - 0.12 * pxPerDeg, 0.3, 0.85, 1.0, 1, std::clamp(p.progress, 0.0, 1.0));
Disc(p, x, y, rr, rr - 0.12 * pxPerDeg, 0.3, 0.85, 1.0, 1, std::clamp(progress, 0.0, 1.0));
Disc(p, x, y, core, 0, ink, ink, ink, 1);
} else if (p.state == "done") {
} else if (state == "done") {
Disc(p, x, y, 0.75 * pxPerDeg, 0, 0.25, 0.85, 0.4, 0.9);
Disc(p, x, y, core, 0, 1, 1, 1, 1);
} else if (p.state == "fail") {
} else if (state == "fail") {
Disc(p, x, y, 0.75 * pxPerDeg, 0.6 * pxPerDeg, 0.95, 0.35, 0.3, 0.9);
Disc(p, x, y, core, 0, ink, ink, ink, 1);
}
@@ -308,6 +473,7 @@ struct Buffer {
};
struct Buffers {
int w = kMaxW, h = kMaxH; // the biggest picture they take
int drm = -1;
gbm_device *gbm = nullptr;
Buffer b[3];
@@ -315,14 +481,15 @@ struct Buffers {
bool ok = false;
bool Make() {
std::lock_guard<std::mutex> lk(g_vr);
drm = open("/dev/dri/renderD128", O_RDWR | O_CLOEXEC);
if (drm >= 0) gbm = gbm_create_device(drm);
for (Buffer &x : b) {
// ABGR8888 is R, G, B, A in memory, like Panel::px.
if (gbm) x.bo = gbm_bo_create(gbm, kMaxW, kMaxH, GBM_FORMAT_ABGR8888, GBM_BO_USE_RENDERING | GBM_BO_USE_LINEAR);
if (gbm) x.bo = gbm_bo_create(gbm, w, h, GBM_FORMAT_ABGR8888, GBM_BO_USE_RENDERING | GBM_BO_USE_LINEAR);
if (!x.bo || (x.fd = gbm_bo_get_fd(x.bo)) < 0) break;
vr::DmabufAttributes_t a{};
a.unWidth = kMaxW, a.unHeight = kMaxH;
a.unWidth = w, a.unHeight = h;
a.unDepth = a.unMipLevels = a.unArrayLayers = a.unSampleCount = 1;
a.unFormat = DRM_FORMAT_ABGR8888;
a.ulModifier = DRM_FORMAT_MOD_LINEAR;
@@ -336,12 +503,17 @@ struct Buffers {
ok = b[2].handle != 0;
if (!ok) {
std::fprintf(stderr, "ft-gazepanel: no shared buffers; falling back to SetOverlayRaw (it flickers)\n");
Drop();
DropLocked();
}
return ok;
}
void Drop() {
std::lock_guard<std::mutex> lk(g_vr);
DropLocked();
}
void DropLocked() {
for (Buffer &x : b) {
if (x.handle) vr::VRIPCResourceManager()->UnrefResource(x.handle);
if (x.fd >= 0) close(x.fd);
@@ -358,6 +530,7 @@ struct Buffers {
void Present(vr::IVROverlay *ov, vr::VROverlayHandle_t h, const Panel &p) {
vr::EVROverlayError e;
if (!ok) {
std::lock_guard<std::mutex> lk(g_vr);
e = ov->SetOverlayRaw(h, const_cast<uint8_t *>(p.px.data()), uint32_t(p.w), uint32_t(p.h), 4);
} else {
Buffer &x = b[next];
@@ -379,7 +552,8 @@ struct Buffers {
}
}
gbm_bo_unmap(x.bo, mapping);
const vr::VRTextureBounds_t bounds{0, 0, float(p.w) / kMaxW, float(p.h) / kMaxH};
std::lock_guard<std::mutex> lk(g_vr);
const vr::VRTextureBounds_t bounds{0, 0, float(p.w) / w, float(p.h) / this->h};
ov->SetOverlayTextureBounds(h, &bounds);
vr::Texture_t tex = {&x.handle, vr::TextureType_SharedTextureHandle, vr::ColorSpace_Gamma};
e = ov->SetOverlayTexture(h, &tex);
@@ -389,18 +563,213 @@ struct Buffers {
}
};
// ---------------------------------------------------------------- the rec mode's logs (see the top)
void PutFloat(FILE *f, double v) { std::fprintf(f, "%.6g", std::isfinite(v) ? v : 0.0); }
double Sec(int64_t ns) { return double(ns) / 1e9; }
// A JSON-lines file the main thread writes.
struct Lines {
FILE *f = nullptr;
long rows = 0;
bool Open(const std::string &path) {
Close();
if (!(f = std::fopen(path.c_str(), "ae"))) return false;
std::setvbuf(f, nullptr, _IOFBF, 1 << 16);
rows = 0;
return true;
}
long Close() {
if (!f) return rows;
if (std::fflush(f) != 0 || std::ferror(f)) std::fprintf(stderr, "ft-gazepanel: writing a log failed\n");
std::fclose(f);
f = nullptr;
return rows;
}
};
// The headset's pose 250 times a second (as the hand panel's, head only), on a thread of its
// own, so a picture or a command never delays a sample.
struct PoseLog {
FILE *f = nullptr;
std::thread th;
std::atomic<bool> run{false};
std::atomic<long> samples{0};
bool Start(const std::string &path, bool vr) {
Stop();
if (!(f = std::fopen(path.c_str(), "ae"))) return false;
std::setvbuf(f, nullptr, _IOFBF, 1 << 16);
samples = 0;
if (vr) run = true, th = std::thread([this] { Run(); });
return true;
}
long Stop() {
if (!f) return 0;
run = false;
if (th.joinable()) th.join();
if (std::fflush(f) != 0 || std::ferror(f)) std::fprintf(stderr, "ft-gazepanel: writing the pose log failed\n");
std::fclose(f);
f = nullptr;
return samples;
}
void Run() {
auto *sys = vr::VRSystem();
vr::TrackedDevicePose_t pose{};
int64_t next = RawNs(), lastFlush = next;
while (run) {
int64_t before, after;
{
std::lock_guard<std::mutex> lk(g_vr);
before = RawNs();
sys->GetDeviceToAbsoluteTrackingPose(vr::TrackingUniverseStanding, 0, &pose, 1);
after = RawNs();
}
const int64_t t = before + (after - before) / 2;
std::fprintf(f, "{\"t\": %.6f, \"hmd\": ", Sec(t));
if (!pose.bDeviceIsConnected) {
std::fputs("null}\n", f);
} else {
std::fputs("{\"m\": [", f);
for (int k = 0; k < 12; ++k) {
if (k) std::fputs(", ", f);
PutFloat(f, pose.mDeviceToAbsoluteTracking.m[k / 4][k % 4]);
}
std::fprintf(f, "], \"r\": %d, \"ok\": %s}}\n", int(pose.eTrackingResult), pose.bPoseIsValid ? "true" : "false");
}
++samples;
if (t - lastFlush >= 1'000'000'000) std::fflush(f), lastFlush = t;
next += kPosePeriodNs;
const int64_t now = RawNs();
if (next < now - kPosePeriodNs) next = now;
const timespec ts{time_t(next / 1'000'000'000), long(next % 1'000'000'000)};
clock_nanosleep(CLOCK_MONOTONIC_RAW, TIMER_ABSTIME, &ts, nullptr);
}
}
};
// ---------------------------------------------------------------- the rec mode's dot
// A head-relative direction (yaw +left, pitch +up; see ToPixel) as a unit vector in the head
// frame (+x right, +y up, -z forward), and back.
void Direction(double yaw, double pitch, double v[3]) {
const double yr = yaw * M_PI / 180, pr = pitch * M_PI / 180;
v[0] = -std::sin(yr) * std::cos(pr), v[1] = std::sin(pr), v[2] = -std::cos(yr) * std::cos(pr);
}
void Angles(const double v[3], double &yaw, double &pitch) {
yaw = std::atan2(-v[0], -v[2]) * 180 / M_PI;
pitch = std::atan2(v[1], std::hypot(v[0], v[2])) * 180 / M_PI;
}
// An overlay's transform at `at`, its face (+z) turned toward `eye`, upright (the hand panel's).
vr::HmdMatrix34_t Facing(const double at[3], const double eye[3]) {
auto norm = [](double v[3]) {
const double n = std::sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
if (n < 1e-9) return false;
v[0] /= n, v[1] /= n, v[2] /= n;
return true;
};
double z[3] = {eye[0] - at[0], eye[1] - at[1], eye[2] - at[2]};
if (!norm(z)) z[0] = z[1] = 0, z[2] = 1;
double x[3] = {z[2], 0, -z[0]};
if (!norm(x)) x[0] = 1, x[1] = x[2] = 0;
const double y[3] = {z[1] * x[2] - z[2] * x[1], z[2] * x[0] - z[0] * x[2], z[0] * x[1] - z[1] * x[0]};
vr::HmdMatrix34_t m{};
for (int r = 0; r < 3; ++r)
m.m[r][0] = float(x[r]), m.m[r][1] = float(y[r]), m.m[r][2] = float(z[r]), m.m[r][3] = float(at[r]);
return m;
}
// m's point p in the room -> the device frame (m is device to room, rotation orthonormal).
void ToDevice(const vr::HmdMatrix34_t &m, const double p[3], double out[3]) {
const double d[3] = {p[0] - m.m[0][3], p[1] - m.m[1][3], p[2] - m.m[2][3]};
for (int c = 0; c < 3; ++c) out[c] = m.m[0][c] * d[0] + m.m[1][c] * d[1] + m.m[2][c] * d[2];
}
void ToRoom(const vr::HmdMatrix34_t &m, const double p[3], double out[3]) {
for (int r = 0; r < 3; ++r) out[r] = m.m[r][0] * p[0] + m.m[r][1] * p[1] + m.m[r][2] * p[2] + m.m[r][3];
}
struct Dot {
std::string mode = "off"; // off, fixed, path, world
double yaw = 0, pitch = 0;
std::string state = "look";
double progress = 0;
// path
std::string kind;
double a[4] = {0, 0, 0, 0}, seconds = 1;
int64_t start = -1; // the path's first frame's photon time (ns), set on that frame
// world
double room[3] = {0, 0, 0}, head[3] = {0, 0, 0}; // where it is, and the head-frame point it came from
// drawn: what the overlay's picture shows, and whether it's visible
std::string drawnState;
double drawnProgress = -1, drawnBg = -1;
bool shown = false;
bool changed = true; // log a row on the next frame
};
// Where a path's dot is t seconds after it started.
void PathAt(const Dot &d, double t, double &yaw, double &pitch) {
const double ph = t / std::max(d.seconds, 0.05);
if (d.kind == "circle") {
yaw = d.a[0] + d.a[2] * std::sin(2 * M_PI * ph), pitch = d.a[1] + d.a[2] * std::cos(2 * M_PI * ph);
} else if (d.kind == "line") {
double f = std::fmod(ph, 2.0);
if (f > 1) f = 2 - f;
yaw = d.a[0] + (d.a[2] - d.a[0]) * f, pitch = d.a[1] + (d.a[3] - d.a[1]) * f;
} else { // eight
yaw = d.a[0] + d.a[2] * std::sin(2 * M_PI * ph), pitch = d.a[1] + d.a[3] * std::sin(4 * M_PI * ph);
}
}
// --no-vr: a picture as a PAM file (RGBA, straight alpha), as the hand panel's.
void Dump(const Panel &p, const std::string &path) {
if (FILE *f = std::fopen(path.c_str(), "wb")) {
std::fprintf(f, "P7\nWIDTH %d\nHEIGHT %d\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n", p.w, p.h);
std::fwrite(p.px.data(), 1, p.px.size(), f);
std::fclose(f);
}
}
// The headset's pose `ahead` seconds from now; --no-vr's is at the room's origin, looking down -z.
vr::TrackedDevicePose_t HeadPose(bool noVr, float ahead) {
vr::TrackedDevicePose_t pose{};
if (noVr) {
pose.bPoseIsValid = pose.bDeviceIsConnected = true;
pose.mDeviceToAbsoluteTracking.m[0][0] = pose.mDeviceToAbsoluteTracking.m[1][1] = pose.mDeviceToAbsoluteTracking.m[2][2] = 1;
} else {
std::lock_guard<std::mutex> lk(g_vr);
vr::VRSystem()->GetDeviceToAbsoluteTrackingPose(vr::TrackingUniverseStanding, ahead, &pose, 1);
}
return pose;
}
bool Is(const char *buf, const char *word, const char **rest = nullptr) {
const size_t n = std::strlen(word);
if (std::strncmp(buf, word, n) || (buf[n] && buf[n] != ' ')) return false;
if (rest) *rest = buf[n] ? buf + n + 1 : buf + n;
return true;
}
} // namespace
int main(int argc, char **argv) {
bool watchStdin = false;
std::string sockName = "ft_gazepanel";
bool watchStdin = false, noVr = false;
std::string sockName = "ft_gazepanel", overlayKey = "frametop.gazepanel", dumpDir;
double distance = 1.5;
for (int i = 1; i < argc; ++i) {
if (!std::strcmp(argv[i], "--watch-stdin")) watchStdin = true;
else if (!std::strcmp(argv[i], "--no-vr")) noVr = true;
else if (!std::strcmp(argv[i], "--socket") && i + 1 < argc) sockName = argv[++i];
else if (!std::strcmp(argv[i], "--overlay") && i + 1 < argc) overlayKey = argv[++i];
else if (!std::strcmp(argv[i], "--dump") && i + 1 < argc) dumpDir = argv[++i];
else if (!std::strcmp(argv[i], "--distance") && i + 1 < argc) distance = std::clamp(std::atof(argv[++i]), 0.5, 5.0);
else {
std::fprintf(stderr, "usage: %s [--watch-stdin] [--socket NAME] [--distance METRES]\n", argv[0]);
std::fprintf(stderr, "usage: %s [--watch-stdin] [--socket NAME] [--overlay KEY] [--distance METRES] "
"[--no-vr [--dump DIR]]\n", argv[0]);
return 2;
}
}
@@ -423,39 +792,176 @@ int main(int argc, char **argv) {
return 1;
}
// As Frametop's other SteamVR clients: background first, so we never start vrserver.
vr::EVRInitError err = vr::VRInitError_None;
vr::VR_Init(&err, vr::VRApplication_Background);
if (err == vr::VRInitError_None) {
vr::VR_Shutdown();
vr::VR_Init(&err, vr::VRApplication_Overlay);
vr::IVROverlay *ov = nullptr;
vr::VROverlayHandle_t h = vr::k_ulOverlayHandleInvalid, dotH = vr::k_ulOverlayHandleInvalid;
double period = 1 / 90.0, toPhotons = 0;
if (!noVr) {
// As Frametop's other SteamVR clients: background first, so we never start vrserver.
vr::EVRInitError err = vr::VRInitError_None;
vr::VR_Init(&err, vr::VRApplication_Background);
if (err == vr::VRInitError_None) {
vr::VR_Shutdown();
vr::VR_Init(&err, vr::VRApplication_Overlay);
}
if (err != vr::VRInitError_None) {
std::fprintf(stderr, "ft-gazepanel: SteamVR: %s\n", vr::VR_GetVRInitErrorAsEnglishDescription(err));
return 1;
}
ov = vr::VROverlay();
if (ov->CreateOverlay(overlayKey.c_str(), "Frametop gaze calibration", &h) != vr::VROverlayError_None ||
ov->CreateOverlay((overlayKey + ".dot").c_str(), "Frametop gaze dot", &dotH) != vr::VROverlayError_None) {
std::fprintf(stderr, "ft-gazepanel: can't create the overlay (another copy running?)\n");
return 1;
}
ov->SetOverlaySortOrder(h, 250); // in front of Frametop's screens and the pointer's dot
ov->SetOverlaySortOrder(dotH, 251);
auto *sys = vr::VRSystem();
vr::ETrackedPropertyError pe;
const float hz = sys->GetFloatTrackedDeviceProperty(vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_DisplayFrequency_Float, &pe);
if (pe == vr::TrackedProp_Success && hz > 30) period = 1.0 / hz;
const float ph = sys->GetFloatTrackedDeviceProperty(vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_SecondsFromVsyncToPhotons_Float, &pe);
if (pe == vr::TrackedProp_Success && ph >= 0 && ph < 0.1) toPhotons = ph;
}
if (err != vr::VRInitError_None) {
std::fprintf(stderr, "ft-gazepanel: SteamVR: %s\n", vr::VR_GetVRInitErrorAsEnglishDescription(err));
return 1;
}
vr::IVROverlay *ov = vr::VROverlay();
vr::VROverlayHandle_t h = vr::k_ulOverlayHandleInvalid;
if (ov->CreateOverlay("frametop.gazepanel", "Frametop gaze calibration", &h) != vr::VROverlayError_None) {
std::fprintf(stderr, "ft-gazepanel: can't create the overlay (another copy running?)\n");
return 1;
}
ov->SetOverlaySortOrder(h, 250); // in front of Frametop's screens and the pointer's dot
LoadFont();
Buffers buffers;
if (buffers.Make()) ov->SetOverlayFlag(h, vr::VROverlayFlags_IsPremultiplied, true);
Buffers buffers, dotBuffers;
dotBuffers.w = dotBuffers.h = kDotPx;
if (!noVr && buffers.Make()) ov->SetOverlayFlag(h, vr::VROverlayFlags_IsPremultiplied, true);
if (!noVr && dotBuffers.Make()) ov->SetOverlayFlag(dotH, vr::VROverlayFlags_IsPremultiplied, true);
if (!dumpDir.empty()) mkdir(dumpDir.c_str(), 0755);
Panel p;
Panel dotPic; // the rec mode's dot overlay's picture
dotPic.w = dotPic.h = kDotPx, dotPic.wDeg = kDotDeg;
Dot dot;
Lines targets, ipdLog;
PoseLog poses;
float ipdNow = -1;
int64_t ipdAt = 0;
int pictures = 0;
bool visible = false, dirty = false, shown = false; // shown: SteamVR shows it (after its first picture)
auto place = [&] {
if (noVr) return;
const double half = std::tan(p.wDeg * M_PI / 360);
vr::HmdMatrix34_t m{};
m.m[0][0] = m.m[1][1] = m.m[2][2] = 1;
m.m[2][3] = float(-distance);
// Turned down about x by the strip's pitch (none for the others), facing the eyes.
const double tilt = p.strip ? kNotePitch * M_PI / 180 : 0, c = std::cos(tilt), sn = std::sin(tilt);
m.m[0][0] = 1;
m.m[1][1] = float(c), m.m[1][2] = float(-sn), m.m[2][1] = float(sn), m.m[2][2] = float(c);
m.m[1][3] = float(distance * sn), m.m[2][3] = float(-distance * c);
std::lock_guard<std::mutex> lk(g_vr);
ov->SetOverlayTransformTrackedDeviceRelative(h, vr::k_unTrackedDeviceIndex_Hmd, &m);
ov->SetOverlayWidthInMeters(h, float(2 * distance * half));
};
std::fprintf(stderr, "ft-gazepanel running: @%s, %.2f m\n", sockName.c_str(), distance);
auto hideDot = [&] {
if (dot.shown && !noVr) {
std::lock_guard<std::mutex> lk(g_vr);
ov->HideOverlay(dotH);
}
dot.shown = false;
};
// The next frame's vsync count and when it reaches the eyes (RAW ns).
auto nextFrame = [&](int64_t now, uint64_t &frame) {
double since = 0;
frame = 0;
if (!noVr) {
float s = 0;
std::lock_guard<std::mutex> lk(g_vr);
if (vr::VRSystem()->GetTimeSinceLastVsync(&s, &frame)) since = s;
} else {
const int64_t per = int64_t(period * 1e9);
since = double(now % per) / 1e9, frame = uint64_t(now / per);
}
frame += 1;
return now + int64_t((period - std::min(since, period) + toPhotons) * 1e9);
};
auto ipdLook = [&](int64_t now, const char *why) {
if (noVr || !ipdLog.f) return;
vr::ETrackedPropertyError pe;
float v;
{
std::lock_guard<std::mutex> lk(g_vr);
v = vr::VRSystem()->GetFloatTrackedDeviceProperty(vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_UserIpdMeters_Float, &pe);
}
ipdAt = now;
if (pe != vr::TrackedProp_Success || v == ipdNow) return;
ipdNow = v;
std::fprintf(ipdLog.f, "{\"t\": %.6f, \"ipd\": %.5f, \"from\": \"%s\"}\n", Sec(now), v, why);
++ipdLog.rows;
};
// The rec mode's dot, once a frame: where it is at the next frame's photons, the overlay
// moved there, and a targets row when it moved or changed.
auto dotTick = [&](int64_t now) {
if (!p.rec || !visible || dot.mode == "off") {
if (dot.changed && targets.f && p.rec) {
uint64_t frame;
const int64_t t = nextFrame(now, frame);
std::fprintf(targets.f, "{\"t\": %.6f, \"set\": %.6f, \"frame\": %llu, \"dot\": \"off\", \"dist\": %.3f, \"bg\": %.3f}\n",
Sec(t), Sec(now), (unsigned long long)frame, distance, p.bg);
++targets.rows;
}
dot.changed = false;
hideDot();
return;
}
uint64_t frame;
const int64_t t = nextFrame(now, frame);
double yaw = dot.yaw, pitch = dot.pitch, dist = distance;
bool moved = false;
vr::HmdMatrix34_t m{};
bool absolute = false;
if (dot.mode == "path") {
if (dot.start < 0) dot.start = t;
PathAt(dot, Sec(t - dot.start), yaw, pitch);
moved = true;
}
if (dot.mode == "world") {
// The head where it will be at the photons, and the dot's direction from it.
const vr::TrackedDevicePose_t pose = HeadPose(noVr, float(Sec(t - now)));
if (pose.bPoseIsValid) {
double v[3];
ToDevice(pose.mDeviceToAbsoluteTracking, dot.room, v);
dist = std::sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
if (dist > 1e-6) {
for (double &c : v) c /= dist;
Angles(v, yaw, pitch);
}
const double eye[3] = {pose.mDeviceToAbsoluteTracking.m[0][3], pose.mDeviceToAbsoluteTracking.m[1][3],
pose.mDeviceToAbsoluteTracking.m[2][3]};
m = Facing(dot.room, eye);
absolute = true;
}
moved = true;
} else {
double v[3];
Direction(yaw, pitch, v);
const double at[3] = {v[0] * dist, v[1] * dist, v[2] * dist}, eye[3] = {0, 0, 0};
m = Facing(at, eye);
}
const bool redraw = dot.state != dot.drawnState || dot.progress != dot.drawnProgress || p.bg != dot.drawnBg;
if (redraw) {
dotPic.px.assign(size_t(dotPic.w) * dotPic.h * 4, 0);
DrawDot(dotPic, dotPic.w / 2.0, dotPic.h / 2.0, dotPic.w / dotPic.wDeg, dot.state, dot.progress, p.bg > 0.5 ? 0.0 : 1.0);
dot.drawnState = dot.state, dot.drawnProgress = dot.progress, dot.drawnBg = p.bg;
if (!noVr) dotBuffers.Present(ov, dotH, dotPic);
}
if (!noVr && (moved || dot.changed || redraw)) {
std::lock_guard<std::mutex> lk(g_vr);
if (absolute) ov->SetOverlayTransformAbsolute(dotH, vr::TrackingUniverseStanding, &m);
else ov->SetOverlayTransformTrackedDeviceRelative(dotH, vr::k_unTrackedDeviceIndex_Hmd, &m);
ov->SetOverlayWidthInMeters(dotH, float(2 * dist * std::tan(kDotDeg * M_PI / 360)));
if (!dot.shown) ov->ShowOverlay(dotH);
}
dot.shown = true;
if (targets.f && (moved || dot.changed || redraw)) {
std::fprintf(targets.f, "{\"t\": %.6f, \"set\": %.6f, \"frame\": %llu, \"dot\": \"%s\", \"yaw\": %.4f, \"pitch\": %.4f, "
"\"dist\": %.3f, \"state\": \"%s\", \"progress\": %.3f, \"bg\": %.3f}\n",
Sec(t), Sec(now), (unsigned long long)frame, dot.mode.c_str(), yaw, pitch, dist, dot.state.c_str(),
dot.progress, p.bg);
++targets.rows;
}
dot.changed = false;
};
std::fprintf(stderr, "ft-gazepanel running: @%s, %.2f m%s\n", sockName.c_str(), distance, noVr ? ", no SteamVR" : "");
while (!g_stop) {
char buf[512];
@@ -463,29 +969,118 @@ int main(int argc, char **argv) {
socklen_t fromLen = sizeof from;
ssize_t n;
while ((n = recvfrom(sock, buf, sizeof buf - 1, 0, reinterpret_cast<sockaddr *>(&from), &fromLen)) > 0) {
while (n > 0 && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) --n; // from echo or socat
buf[n] = 0;
std::string reply = "ok";
char word[16] = "", state[16] = "";
double a = 0, b = 0, c = 0, d = 0, e = 0;
int rest = 0;
const char *arg = nullptr;
if (!std::strncmp(buf, "show ", 5)) {
p.rec = !std::strcmp(buf + 5, "rec");
p.full = !std::strcmp(buf + 5, "full");
p.fit = !std::strcmp(buf + 5, "fit");
p.w = p.full ? kFullW : p.fit ? kFitW : kQuickPx;
p.h = p.full ? kFullH : p.fit ? kFitH : kQuickPx;
p.wDeg = p.full ? kFullDeg : p.fit ? kFitDeg : kQuickDeg;
p.strip = !std::strcmp(buf + 5, "note");
const bool five = !std::strcmp(buf + 5, "five"), big = p.full || p.rec;
p.w = big ? kFullW : p.fit ? kFitW : five ? kFiveW : p.strip ? kNoteW : kQuickPx;
p.h = big ? kFullH : p.fit ? kFitH : five ? kFiveH : p.strip ? kNoteH : kQuickPx;
p.wDeg = big ? kFullDeg : p.fit ? kFitDeg : five ? kFiveDeg : p.strip ? kNoteDeg : kQuickDeg;
p.title.clear(), p.text.clear(), p.note.clear(), p.dotOn = false, p.state = "off";
p.eyes[0] = p.eyes[1] = EyeCard{}, p.hints.clear();
p.step.clear(), p.big.clear(), p.action.clear(), p.keys.clear();
p.recOn = p.paused = false, p.countdown = -1;
dot.mode = "off", dot.changed = true;
place();
visible = dirty = true; // shown with its first picture
} else if (!std::strcmp(buf, "hide")) {
ov->HideOverlay(h);
if (!noVr) {
std::lock_guard<std::mutex> lk(g_vr);
ov->HideOverlay(h);
}
hideDot();
visible = shown = false;
dot.mode = "off", dot.changed = true;
} else if (std::sscanf(buf, "bg %lf", &a) == 1) {
p.bg = std::clamp(a, 0.0, 1.0), dirty = true;
p.bg = std::clamp(a, 0.0, 1.0), dirty = true, dot.changed = true;
} else if (std::sscanf(buf, "dot %lf %lf %15s %lf", &a, &b, state, &c) >= 3) {
p.dotYaw = a, p.dotPitch = b, p.state = state, p.progress = c;
p.dotOn = std::strcmp(state, "off") != 0, dirty = true;
p.dotOn = std::strcmp(state, "off") != 0;
if (p.rec) {
dot.mode = p.dotOn ? "fixed" : "off", dot.yaw = a, dot.pitch = b, dot.state = state, dot.progress = c;
dot.changed = true;
} else {
dirty = true;
}
} else if (Is(buf, "path", &arg)) {
char kind[16] = "";
double v[5] = {0, 0, 0, 0, 0};
const int got = std::sscanf(arg, "%15s %lf %lf %lf %lf %lf", kind, &v[0], &v[1], &v[2], &v[3], &v[4]);
const int want = !std::strcmp(kind, "circle") ? 5 : (!std::strcmp(kind, "line") || !std::strcmp(kind, "eight")) ? 6 : 0;
if (!p.rec) {
reply = "error path is for show rec";
} else if (!want || got != want || v[want - 2] <= 0) {
reply = "error path circle|line|eight <numbers> <seconds>";
} else {
dot.mode = "path", dot.kind = kind, dot.seconds = v[want - 2], dot.start = -1;
for (int k = 0; k < 4; ++k) dot.a[k] = k < want - 2 ? v[k] : 0;
dot.state = "look", dot.progress = 0, dot.changed = true;
}
} else if (Is(buf, "world", &arg)) {
double v[3];
char st[16] = "look";
double prog = 0;
if (!std::strcmp(arg, "off")) {
if (dot.mode == "world") dot.mode = "off", dot.changed = true;
} else if (!p.rec) {
reply = "error world is for show rec";
} else if (std::sscanf(arg, "%lf %lf %lf %15s %lf", &v[0], &v[1], &v[2], st, &prog) < 3) {
reply = "error world <x> <y> <z> [<state> [<progress>]]";
} else {
const vr::TrackedDevicePose_t pose = HeadPose(noVr, 0);
if (!pose.bPoseIsValid) {
reply = "error no headset pose";
} else {
if (dot.mode != "world" || v[0] != dot.head[0] || v[1] != dot.head[1] || v[2] != dot.head[2])
ToRoom(pose.mDeviceToAbsoluteTracking, v, dot.room);
std::copy(v, v + 3, dot.head);
dot.mode = "world", dot.state = st, dot.progress = prog, dot.changed = true;
char r[96];
std::snprintf(r, sizeof r, "ok %.4f %.4f %.4f", dot.room[0], dot.room[1], dot.room[2]);
reply = r;
}
}
} else if (std::sscanf(buf, "distance %lf", &a) == 1) {
distance = std::clamp(a, 0.25, 10.0), dot.changed = true;
place();
} else if (Is(buf, "ipd")) {
float v = 0.063f;
vr::ETrackedPropertyError pe = vr::TrackedProp_Success;
if (!noVr) {
std::lock_guard<std::mutex> lk(g_vr);
v = vr::VRSystem()->GetFloatTrackedDeviceProperty(vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_UserIpdMeters_Float, &pe);
}
char r[48];
std::snprintf(r, sizeof r, "ok %.5f", v);
reply = pe == vr::TrackedProp_Success ? r : "error no IPD from SteamVR";
} else if (Is(buf, "log", &arg)) {
if (!std::strncmp(arg, "start ", 6)) {
const std::string dir = arg + 6;
if (!targets.Open(dir + "/targets.jsonl") || !ipdLog.Open(dir + "/ipd.jsonl") ||
!poses.Start(dir + "/poses.jsonl", !noVr)) {
targets.Close(), ipdLog.Close(), poses.Stop();
reply = "error can't write in " + dir;
} else {
ipdNow = -1, dot.changed = true;
ipdLook(RawNs(), "start");
}
} else if (!std::strcmp(arg, "stop")) {
char r[96];
const long tr = targets.Close(), ir = ipdLog.Close(), pr = poses.Stop();
std::snprintf(r, sizeof r, "ok %ld %ld %ld", tr, pr, ir);
reply = r;
} else {
reply = "error log start <dir> | log stop";
}
} else if (int k; std::sscanf(buf, "eye %d %lf %lf %lf %lf %lf %n", &k, &a, &b, &c, &d, &e, &rest) >= 6 &&
rest > 0 && (k == 0 || k == 1)) {
p.eyes[k] = EyeCard{buf + rest, a, b, c, d, e}, dirty = true;
@@ -498,12 +1093,26 @@ int main(int argc, char **argv) {
at = bar + 1;
}
dirty = true;
} else if (!std::strncmp(buf, "title", 5)) {
p.title = buf[5] == ' ' ? buf + 6 : "", dirty = true;
} else if (!std::strncmp(buf, "text", 4)) {
p.text = buf[4] == ' ' ? buf + 5 : "", dirty = true;
} else if (!std::strncmp(buf, "note", 4)) {
p.note = buf[4] == ' ' ? buf + 5 : "", dirty = true;
} else if (Is(buf, "title", &arg)) {
p.title = arg, dirty = true;
} else if (Is(buf, "text", &arg)) {
p.text = arg, dirty = true;
} else if (Is(buf, "note", &arg)) {
p.note = arg, dirty = true;
} else if (Is(buf, "step", &arg)) {
p.step = arg, dirty = true;
} else if (Is(buf, "big", &arg)) {
p.big = arg, dirty = true;
} else if (Is(buf, "action", &arg)) {
p.action = arg, dirty = true;
} else if (Is(buf, "keys", &arg)) {
p.keys = arg, dirty = true;
} else if (Is(buf, "rec", &arg) && (!std::strcmp(arg, "on") || !std::strcmp(arg, "off"))) {
p.recOn = !std::strcmp(arg, "on"), dirty = true;
} else if (Is(buf, "paused", &arg) && (!std::strcmp(arg, "on") || !std::strcmp(arg, "off"))) {
p.paused = !std::strcmp(arg, "on"), dirty = true;
} else if (Is(buf, "countdown", &arg)) {
p.countdown = !std::strcmp(arg, "off") ? -1 : std::clamp(std::atof(arg), 0.0, 1.0), dirty = true;
} else if (std::sscanf(buf, "%15s", word) == 1 && !std::strcmp(word, "ping")) {
reply = visible ? "ok shown" : "ok hidden";
} else {
@@ -513,26 +1122,57 @@ int main(int argc, char **argv) {
sendto(sock, reply.data(), reply.size(), 0, reinterpret_cast<sockaddr *>(&from), fromLen);
fromLen = sizeof from;
}
vr::VREvent_t ev;
while (vr::VRSystem()->PollNextEvent(&ev, sizeof ev))
if (ev.eventType == vr::VREvent_Quit) {
vr::VRSystem()->AcknowledgeQuit_Exiting();
g_stop = true;
if (!noVr) {
vr::VREvent_t ev;
std::unique_lock<std::mutex> lk(g_vr);
while (vr::VRSystem()->PollNextEvent(&ev, sizeof ev)) {
if (ev.eventType == vr::VREvent_Quit) {
vr::VRSystem()->AcknowledgeQuit_Exiting();
g_stop = true;
} else if (ev.eventType == vr::VREvent_IpdChanged && ipdLog.f) {
ipdNow = ev.data.ipd.ipdMeters;
std::fprintf(ipdLog.f, "{\"t\": %.6f, \"ipd\": %.5f, \"from\": \"event\"}\n", Sec(RawNs()), ipdNow);
++ipdLog.rows;
}
}
}
if (visible && dirty) {
Draw(p);
buffers.Present(ov, h, p);
if (!shown) ov->ShowOverlay(h), shown = true;
++pictures;
if (!dumpDir.empty()) Dump(p, dumpDir + "/" + std::to_string(pictures) + ".pam");
if (!noVr) {
buffers.Present(ov, h, p);
std::lock_guard<std::mutex> lk(g_vr);
if (!shown) ov->ShowOverlay(h);
}
shown = true;
dirty = false;
}
// 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.
const int64_t now = RawNs();
dotTick(now);
if (ipdLog.f && now - ipdAt >= kIpdPeriodNs) ipdLook(now, "look");
// Until a command comes, or the next frame while the rec mode's dot moves, 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.
double wait = visible ? 0.010 : 1.0;
if (visible && p.rec && (dot.mode == "path" || dot.mode == "world")) {
uint64_t frame;
// Just after the next vsync: the compositor has taken this frame's transform.
wait = std::max(0.001, Sec(nextFrame(now, frame) - now) - toPhotons + 0.001);
}
if (ipdLog.f) wait = std::min(wait, Sec(kIpdPeriodNs));
pollfd fds[2] = {{sock, POLLIN, 0}, {0, POLLIN, 0}};
poll(fds, watchStdin ? 2 : 1, visible ? 10 : 1000);
const timespec ts{time_t(wait), long((wait - std::floor(wait)) * 1e9)};
ppoll(fds, watchStdin ? 2 : 1, &ts, nullptr);
}
ov->DestroyOverlay(h);
buffers.Drop();
vr::VR_Shutdown();
targets.Close(), ipdLog.Close(), poses.Stop();
if (!noVr) {
std::lock_guard<std::mutex> lk(g_vr);
ov->DestroyOverlay(dotH);
ov->DestroyOverlay(h);
}
buffers.Drop(), dotBuffers.Drop();
if (!noVr) vr::VR_Shutdown();
return 0;
}
+3 -4
View File
@@ -161,11 +161,10 @@ class GazeReader:
env = dict(os.environ)
# The Frametop desktop has its own runtime dir; podman needs the real one.
env["XDG_RUNTIME_DIR"] = f"/run/user/{os.getuid()}"
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, which is the one thing distrobox passes on
# when we go away (even if we're killed).
self.proc = subprocess.Popen([str(distrobox), "enter", "dev", "--", str(HELPER), "--watch-stdin"], env=env,
# when we go away (even if we're killed). in-box starts the container first, and picks
# the release's own on a release install.
self.proc = subprocess.Popen([str(REPO / "scripts" / "in-box"), str(HELPER), "--watch-stdin"], env=env,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
start_new_session=True)
out = Gio.UnixInputStream.new(self.proc.stdout.fileno(), False)
+96
View File
@@ -0,0 +1,96 @@
# Recording your eyes for the Frametop eye dataset (DRAFT, not reviewed yet)
Version: 2026-10-14-draft
Frametop's eye tracking needs a better model than it has: one that keeps working when you look far to the side, blink, squint, wear glasses or makeup, or when the headset moves on your face. To train it, we're collecting recordings of many people's eyes into a dataset that only the maintainers can read. This page explains what the eye recorder records, where it goes, who can see it, 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/Frametop/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, which includes images of the iris, that need more than this project can provide yet.
- Take part only if you're comfortable with the maintainers seeing close-up images of your eyes.
## Your eyes are biometric data
The headset's eye cameras film each eye from a few centimetres away. The iris in those images can identify a person, the way a fingerprint can. That's why this dataset works differently from Frametop's hand dataset:
- **The eye images are never public.** Your headset encrypts them before they're uploaded, so that only the maintainers' keys can read them. Hugging Face, other contributors and people who download the dataset get only the encrypted files.
- **What's trained from them can be public.** Models trained on the dataset can be published and shared. They don't contain your images, though no one can rule out that a model remembers something about the eyes it was trained on.
## What is recorded
While a round runs, the eye recorder saves:
- **Eye images.** Infrared images from the headset's 2 eye cameras, about 90 a second each. They show your eyes, eyelids, eyelashes and the skin around them, and your glasses or contact lenses if you wear them. Encrypted in the export.
- **Where you looked.** Where each dot was when you looked at it, what Frametop's eye tracker and SteamVR's found in each image (pupil and glint positions, gaze directions), and how the fit check rated the headset's position. These stay readable in the export, so a pull request can be checked before anyone decrypts it.
- **Motion and settings.** The headset's position and rotation, many times a second, and its IPD setting (the distance between the lenses).
- **Prompts.** What you were asked to do and when.
- **Your answers.** Glasses, contacts or inserts, eye makeup, the face pad and strap, and your measured IPD if you gave it. Readable in the export.
- **Health answers, only if you tick their box.** Eye surgery and conditions such as a turned eye, a droopy eyelid or nystagmus. They're health data, so they're kept in a separate file and encrypted like the images. You can leave them out, and still take part.
- **Times.** When each round 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 rounds together and lets you withdraw them.
The recorder doesn't record sound, the headset's outward cameras, your name, your email address or your Steam account.
**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. The images in it are encrypted, but anyone can see that this account contributed eye recordings, and read the readable parts listed above. Use an account you're happy to have linked to them.
## What it's used for
- Training and testing eye-tracking models: finding the pupil, the glints and the eyelids, and working out where you're looking, including when the headset sits badly. Mainly for Frametop, and possibly elsewhere (below, "The license").
- Checking and improving the recorder's fit coach, which helps people put the headset on well.
- It isn't used to recognise or identify people, and the maintainers won't try.
## Nothing leaves your headset unless you send it
- Recordings stay on your headset, in `~/.local/share/frametop/eyes/contrib`. Nothing is uploaded automatically.
- Before you share anything, you can look through every recording in the Review page. You can delete any stretch of a take, a whole take or a whole round. 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, and who can read it
- The dataset is hosted on Hugging Face (<https://huggingface.co/datasets/DeeJanuz/frametop-eyes>), whose servers may be outside your country, for example in the USA. It's gated: people must accept its terms to download it, and what they get has the eye images and health answers encrypted.
- Only the maintainers hold the keys that decrypt them. Today that's DeeJanuz, with one key on their own computer and a backup copy stored offline. The keys are never uploaded. If a key ever leaked, uploads made to it could be read: the maintainers would say so on the dataset's page and stop using it.
- Decrypted images are kept only on the maintainers' own computers, for training and checking models, and aren't shared with anyone else or uploaded to other services.
- Recordings stay in the dataset until they're withdrawn or the dataset is taken down.
## Safety
The rounds ask you to look at dots, including far to the sides, to blink and squint, and sometimes to turn your head or move the headset on your face. Sit where you normally use the headset and stop whenever anything is uncomfortable, or if your eyes get tired or sore. If you have a condition that bright or moving lights affect, such as photosensitive epilepsy, don't take part. You take part at your own risk.
## The license
- **You 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. It doesn't include publishing your eye images or health answers, or giving them to anyone outside the maintainers. The maintainer today is DeeJanuz. If someone else, or an organization, takes over maintaining Frametop, this license passes to them, with the same limits. 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 this license: the recordings are of your own eyes.
- There is no payment. The dataset and the eye 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 eye recorder) and which rounds, 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, and the maintainers delete their decrypted copies;
- they're left out of anything trained after that.
What can't be undone: 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. Eye images that can identify you and health answers are special kinds of data there, and they're used only because you explicitly agreed to it, here and with the health answers' own tick. 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 eye recorder shows the new version and asks you again before your next round. 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, including the use of images of your eyes as described. You can still decide not to upload anything.
+176
View File
@@ -0,0 +1,176 @@
# Eye recorder: design (2026-10-14)
The eye recorder guides a person through recording their eyes with the headset's two eye cameras, at known gaze targets and through the cases where eye tracking breaks. It also fits the headset: it shows whether each eye sits where the cameras see it best, helps set the IPD, and catches the headset shifting on the face, with instructions to put it back. Recordings stay on the headset until the person uploads them. Only the maintainers can read what's uploaded (below, "Privacy").
It's the hand recorder's sibling (`hands/rec/DESIGN.md`): the same session runner pattern, headset button, review, export and Hugging Face upload, with eye cameras instead of hand cameras. Like the hand recorder it ships in Frametop and, later, as a standalone app for people without Frametop (Frametop/frametop-eye-recorder, Frametop as a submodule).
The data is for training a better eye tracker than `gaze/tracker/` (ft-eyes, a classic pupil and glint finder) and SteamVR's, one that holds up at the edges of view, through blinks and squints, with glasses and makeup, and when the headset moves.
## Decisions (2026-10-14)
| | Decided |
|---|---|
| Who reads the recordings | Maintainers only. The eye cameras see the iris, which identifies a person. Trained models can be public; the images never are. |
| How | Encrypted frames in a gated dataset, `DeeJanuz/frametop-eyes` (below, "Privacy"). |
| Keys | Two maintainer keys, both recipients of every upload: key 1 on the maintainer's training machine (the 7i), key 2 kept offline in the maintainer's password manager. |
| Packaging | Backend here in `gaze/rec/`, then a standalone repo with Frametop as a submodule, as the hand recorder does. |
| Sessions | Short rounds picked from a bounty board (below, "Bounty board"), not one long session. Each round starts with a fit check and 9 dots. |
| Bounty list | `bounties.json` in the dataset repo, fetched by the app (a copy ships for offline use). The board shows your own done marks and a maintainer-set priority tag per bounty, not community counts. |
| Fit and slip source | Our tracker, ft-eyes: pupil and glint positions in the camera image. It needs ft-eyegrab, the root service `gaze/tracker/install.sh` installs. |
| Where the fit coach runs | A fitment step in the recorder before each round, for better recordings, and the put-on and slip check in Frametop's gaze service. |
| Shared code | The hand recorder's non-hand parts move into a shared module first, and the bounty board is built there too, so the hand recorder can use it next. |
| License | As hands: contributors give the maintainer a license for any use, including commercial models; the eye images and health answers are never published or shared outside the maintainers (user, 2026-10-14). |
| Standalone repo | Created after the window and a full round pass in the headset; step 9 comes first (user, 2026-10-14). |
| Checklist | Glasses/inserts/contacts, eye makeup, measured IPD, and eye surgery or conditions. That last one is health data: a separate opt-in, and its answers are encrypted like the images. |
## Privacy
A private Hugging Face repo can't take contributions: people outside the org can't see it, so they can't open a pull request, and org membership would let every member read every contribution. So the dataset is gated like `DeeJanuz/frametop-hands`, and the export encrypts what identifies a person before upload:
- Every frame chunk is encrypted with [age](https://age-encryption.org) (pyrage, which has aarch64 wheels: `pyrage-1.4.0-cp310-abi3-manylinux_2_17_aarch64`) to the recipients in `recipients.txt`: the maintainers' public keys: key 1 on the 7i, key 2 offline. The private keys never go in a repo.
- The health answers go in `health.json.age`, encrypted the same way.
- Labels, timings, fit readings, the IPD and the rest of session.json stay readable, so `validate.py` and a review can check a pull request before anyone decrypts it.
- Contributors open pull requests from their own accounts, so `hub.py` and the review tools carry over from hands.
The risk: if a private key leaks, every upload made to it can be read. A new key is one more recipient for new uploads; old uploads stay readable to the old key until they're re-encrypted. Withdrawal means deleting the files and squashing history, as with hands.
## What's measured already
- **The eye cameras** (`gaze/tracker/ft-eyegrab.c`): 512x400 8-bit IR, about 90 fps each when SteamVR runs them at 90 (`gaze/eye-rate.py`; at its default 15 fps a recording is worth little, so the recorder checks the rate first). Camera 0 is the right eye (steep angle), camera 1 the left (head-on). ft-eyegrab copies the frames read-only into `/dev/shm/frametop-eyes-cams` while someone touches `/dev/shm/frametop-eyes-want`.
- **Size.** Raw, both cameras are 36.9 MB/s, 2.2 GB a minute. zstd level 1 on 200 MB of the `fit1` capture (2026-10-14): 56 % of the size at about 250 MB/s on one core, so compressing while recording costs about 15 % of a core. Level 3: 53 %, 2.3x slower. Level 9: 49 %, 9.5x slower. The recorder uses level 1 while recording: about 1.2 GB per recorded minute, so a session of about 10 recorded minutes (below) is about 12 GB, close to a hand session.
- **IPD.** SteamVR reports it (2026-10-14, a probe against the live vrserver): `Prop_UserIpdMeters_Float` 0.0651, `Prop_IpdUIRangeMinMeters` 0.057, `Max` 0.071, `Prop_MinimumIpdStepMeters` 0.0015, and the eye-to-head transforms are ±IPD/2. `driver_cv.so` reads the range from the headset's EEPROM. So the recorder can read the IPD setting live and record it with every take. Not yet known: whether the eye cameras move with the lenses when the IPD changes. That decides how the IPD guidance works (below), and it's the first headset test.
- **ft-eyes** already finds each pupil (centre, ellipse) and glint pair per frame, keeps a per-eye slip estimate from the glints (`eyes_model.SlipTracker`), and resets its shift when frames stop for 3 s (the headset was off). `gaze/fitcheck.py` already keeps per-eye tracked and lost by gaze direction, with hints.
## Parts
| Part | What it does |
|---|---|
| `gaze/rec/session.py` (Python, no Qt) | The session runner, like `hands/rec/session.py`: reads a round's script, drives the panel, starts and stops the frame writer per step, reads the live fit for feedback, writes each take. `--dry-run`, `--next-after`, stdin steering and `--button-device` as in hands. |
| `gaze/rec/rounds/<id>.json` | Each kind of round's steps, targets and timings (below, "Bounty board"). |
| `gaze/rec/eyerec.py` | The frame writer: reads the shared frames (as `lab/ft-eyes-record` does) and writes zstd-1 chunks, one per second per camera, with an index (below, "Files"). A thread of the session, not a process: ft-eyes-record shows the copy needs no numpy. |
| `gaze/fitcoach.py` (shared) | The fit coach: from ft-eyes' pupil and glint positions, how the headset sits on this face, and what to do about it (below, "Fit coach"). The recorder, the Gaze page's fit check and the put-on check all use it. |
| ft-gazepanel `rec` mode | The headset panel. The gaze panel already draws dots at exact head-relative directions, which the ground truth needs, so it gains a `rec` mode with the hand panel's text, step, countdown and paused lines rather than a second panel (below, "Panel"). |
| `gaze/rec/takes.py`, `validate.py`, `hub.py` | Review, export, checks and upload, from `hands/rec/`'s. The shared parts move into a common module rather than being copied (below, "Shared with the hand recorder"). |
| `gaze/rec/ft_eyerec.py` + `main.qml` | The desktop window: consent, the bounty board, the checklist and eye camera check, the round with its fit card, review, export, upload. Launched by `ft-eyerec` (the dev container), installed to the app menu by `install.sh`. The standalone app gets a Qt Quick Controls window, as the hand recorder's does. |
| `gaze/rec/CONSENT.md`, `UPLOAD.md` | The texts. Eye images need a stronger consent than hands (biometric data, who can read it, how to withdraw). They need a review like `frame-hands/notes/legal-review-2026-10-03.md` before uploads open. |
## Fit coach
It reads, per eye, from ft-eyes: the pupil centre, its ellipse, the glint pair (both glints and their spacing), and how often the eye was found over the last second. It compares them with a reference: where a well-fitted eye sits in that camera's image. At first the reference comes from the maintainer's headset; once contributions come in, it comes from their rounds with good nine-dot fits (every round's fitment step records exactly that), per headset model. The coach says which reference it used, and until it's built from more than one face its hints are marked provisional.
What it can tell, and the instruction it gives:
| Reading | Means | Instruction |
|---|---|---|
| Both pupils high or low in their images | The headset sits low or high on the face | "Push the headset up" / "Let it down a little", with the top strap |
| Both pupils left or right | The headset sits off to one side | "Slide the headset right" |
| Pupils apart or together, compared with the reference at this IPD | IPD set too narrow or wide | "Turn the IPD wheel wider", until both are centred |
| One pupil higher than the other | The headset is tilted | "Level the headset" |
| Glint pair spacing larger or smaller than the reference | The eye is nearer or further than usual (eye relief: face pad, straps, glasses) | "Tighten the back strap" / "The headset is pressing close: loosen it" |
| A glint missing, or extra bright spots | Glasses reflections, or the lens fogged or smudged | "Tilt your glasses" / "Wipe the lenses" |
| An eye found in under half the frames, looking straight ahead | Lashes on the lens, a droopy lid, or the eye outside the camera's view | The per-eye card says which |
The IPD row depends on the first headset test. If the cameras move with the lenses, a pupil's sideways offset in its image directly says how far that eye is from its lens axis, and the coach turns the IPD wheel's direction into "wider" or "narrower" until both offsets are about zero, at any IPD. If the cameras are fixed, the offset depends on the IPD setting too, and the coach needs the reference at each IPD step: the fitment step's IPD sweep (below, "Bounty board") builds that.
**Put-on and shift check.** After a good fit, the coach keeps that fit as the person's baseline (`~/.local/state/frametop/gaze/fit-baseline.json`: per eye, the pupil looking straight ahead and the glint pair, with the IPD setting). Then:
- When the headset goes back on (frames resume after ft-eyes' 3 s gap), it shows the fit card for a few seconds while the person looks ahead. If the pupils sit more than a threshold (start with 1.5 mm equivalent, tuned from data) from the baseline, it says which way to move the headset, live, until it's back. If the IPD setting changed, it says so first.
- While in use, ft-eyes' glint slip estimate already tracks small movement. A shift past the threshold that stays for 2 s gets a quiet notice ("Your headset slipped down: push it up, or look at the dot to recalibrate"), not a modal.
In the recorder the fit coach runs as each round's fitment step, and the shift warning runs during the round. In Frametop the put-on and slip check becomes part of the gaze service, off by default until it's been tried.
## Bounty board
People pick what to record from a board of bounties. Each bounty is one round of about 5 minutes, in step mode: the headset's right button starts each step (press = next or pause, two presses = redo, hold = stop), as in the hand recorder. Every round starts the same way:
1. **Fitment** (not recorded as a take, but its readings go into fit.json): the fit coach until the headset sits well (below, "Fit coach"). Skippable after a warning, and the round records that it was skipped. On a contributor's first round, and whenever the IPD setting has changed since their last, it ends with an IPD sweep: turn the wheel slowly from narrow to wide and back while looking at a centre dot, with the IPD logged as it changes (the panel looks 30 times a second, and on SteamVR's IPD event). Its own take, `NN-ipd`, before the nine dots.
2. **Nine dots** (recorded): a 3x3 grid to 20 degrees on the mid background. It's the round's own reference, so each round can be labelled alone, even after a re-seat.
3. **The bounty's steps.**
Every round uploads on its own. The board marks the bounties you've done, by your contributor id in `profile.json`, with how many times. You can do one again.
The launch bounties:
| Bounty | What | Edge case it covers |
|---|---|---|
| View edges | Dots at the panel's edges and corners: 30 degrees to the sides, 23 up and down, about 35 in the corners (the rec panel is 64 degrees across; every round's dots are checked against it) | Eyes turned far: the lid, the glints lost, the pupil foreshortened |
| Blinks and lids | Blink on cue, close both for 2 s, wink each eye, squint, eyes wide, half-closed, looking down with lids lowered | Closed and partly closed eyes; one eye missing |
| Headset slips | Nudge the headset up, down, left, right, tilt it; then take it off and put it back on; dots after each | Headset shifting on the face: the put-on check's data |
| Glasses | A 5x5 grid and the edges with glasses or inserts on (offered when the checklist says so) | Lens reflections, the glasses' frame in view |
| Jumps and pursuit | A dot jumping between random spots (0.5 to 1.5 s each), then moving on circles, lines and a figure eight at two speeds | Saccades, overshoot, smooth pursuit, the tracker's lag |
| Depth | Dots at 0.5 m, 1.5 m and 5 m in turn (the panel's distance changes) | Vergence; the eyes' angle with distance |
| Light changes | The background steps dark to bright and back while looking at a dot, then a 5x5 grid at each of three backgrounds | Pupil dilation and constriction; error against pupil size |
| Face moves | Smile, raise eyebrows, frown, yawn, talk (read a line aloud: the microphone isn't recorded), chew | The face moving the headset and the lids |
| Head turning | A dot fixed in the room while turning the head (head poses logged) | The eyes counter-rotating (VOR), headset jiggle |
| Reading | Lines of text to read, then a page of icons to look over | Natural use |
Later candidates, not at launch: eye makeup (the grid and blinks with mascara or eyeliner; the checklist still records makeup on every round), long wear (the grid after 30+ minutes in the headset).
### bounties.json
In the dataset repo, fetched when the board opens (a copy in the app for offline use, used when the fetch fails):
```json
{"schema": 1, "updated": "2026-10-14",
"bounties": [{"id": "edges", "title": "View edges", "blurb": "...", "minutes": 5,
"priority": "high|normal|low|retired", "script": "edges", "needs": {"glasses": true}}]}
```
`script` names a round in the app's `rounds/` folder: a new kind of round needs a release, but the list, wording and priorities don't. `needs` hides a bounty unless the checklist matches. A bounty id the app doesn't know is shown as "needs an update".
The board is in the shared recorder module, so the hand recorder's v2 sections can become bounties later.
### Checklist
Asked once and kept in profile.json, editable before each round, all optional, none identifying: glasses (none, glasses, prescription inserts, contacts), eye makeup today (none, mascara, eyeliner, lash extensions), the face pad and strap in use, and a measured IPD if they know it (from an optician). Separately, behind its own consent tick: eye surgery or conditions (LASIK or other surgery, a lazy or turned eye, a droopy lid, nystagmus, other). Those answers go into `health.json`, which the export encrypts. Eye colour isn't asked: the IR images show what matters about it.
## Panel
ft-gazepanel gains `show rec`: a large head-locked panel (FULL_DEG, 64 degrees, with a solid background whose brightness the script sets) that keeps every existing command (`dot`, `bg`, `title`, `text`, `note`, `eye`, `hints`) and adds what the hand panel has: `step`, `big` (countdown), `action`, `keys`, `rec on|off`, `paused on|off`. New for the ground truth:
- `path <kind> <params> <seconds>`: the panel moves a dot itself (circle, line, figure eight), so it's smooth at the headset's frame rate, not at the socket's.
- `distance <metres>`: moves the panel for the Depth bounty.
- `world <x> <y> <z>`: a dot fixed in the room (the Head turning bounty), as the hand panel's touch target.
- Every picture the panel shows with a dot logs that dot's direction and the frame's time to `targets.jsonl` (CLOCK_MONOTONIC_RAW, the eye frames' clock). The ground truth is what was on screen when, not what was asked.
## Files
```
~/.local/share/frametop/eyes/contrib/
profile.json consent, contributor id, checklist, bounties done
rounds/<YYYYMMDD-HHMMSS>-<bounty>/
session.json the bounty, checklist, versions, takes, eye camera rate, IPD at start
fit.json the fit coach's readings: the fitment step, and any slip warnings
health.json the opt-in health answers (encrypted in the export)
takes/<NN>-<step group>/ numbered in order: NN-ipd (when there's a sweep), NN-dots (the nine dots), then the bounty's
cam0/000000.zst ... right eye: one zstd chunk per second, frames back to back (512x400 u8)
cam1/000000.zst ... left eye
index.tsv per frame: camera, chunk, offset in it, slot, CLOCK_MONOTONIC_RAW time
targets.jsonl what the panel showed, when (direction, distance, state, background)
prompts.jsonl what the person was asked to do, when (as hands)
poses.jsonl head poses, 250 Hz (as hands; needed for Head turning)
ipd.jsonl the IPD setting at the start and when it changes
steamvr.jsonl SteamVR's gaze from ft-gaze, per sample (a baseline, not a label)
own.jsonl ft-eyes' pupils, glints and gaze (a baseline, not a label)
take.json status, deleted ranges, parts, clock samples, as hands
exports/<session>/
```
The export recompresses nothing (the chunks are zstd already), drops deleted ranges by rewriting the chunks they touch, encrypts each chunk and `health.json` to `recipients.txt` (`.age`), and writes the manifest and `SHA256SUMS` over the encrypted files. It never includes `/persist` files: unlike hands, nothing here needs the unit's calibration, and the eye cameras' isn't in `/persist` anyway (2026-10-14: `device_config.json` has the displays' transforms only).
## Shared with the hand recorder
Much of `hands/rec/` isn't about hands: the headset button reader, profile and consent, take bookkeeping (deleted ranges, redo, parts, clock samples), the Hugging Face login and upload, validate's manifest and checksum checks, and most of the window. These live in `recorder/` at the top of the tree, with the bounty board, and both recorders use them: `common.py`, `units.py`, `button.py`, `bounties.py`, `files.py` (ranges, checksums, sizes), `checks.py` (validate's report, SHA256SUMS, typed manifest lookups), `hub.py` (login, errors, upload records, the pull request flow), `age.py` (the export's encryption) and `window.py` (the window backend's shared half: consent, disk, session controls, export, login and upload; each recorder's `Backend` subclasses it). The hand recorder's modules keep their names on top of them, and its tests pass.
Uploads: `gaze/rec/hub.py` sends nothing to the real dataset until `CONSENT.md` and `UPLOAD.md` exist and aren't drafts. `FT_EYEREC_ALLOW_UPLOAD=1` opens rehearsals, and only to another dataset (`FT_EYEREC_DATASET`). Rehearsed 2026-10-14 against the private `DeeJanuz/frametop-eyes-test` with a round of random bytes: uploaded, downloaded, checked, and decrypted with both keys by age 1.1.1 on the 7i.
## Build order
1. **Headset test 1:** do the eye cameras move with the IPD wheel? (Look at one dot, turn the wheel end to end, watch ft-eyes' pupil x.) Decides the IPD guidance.
2. Pull the shared recorder code out of `hands/rec/` (hand recorder tests pass).
3. `eyerec.py` (frame writer) and its replay test against a capture.
4. `fitcoach.py` with readings from a capture, and the fit card on the existing fit panel.
5. ft-gazepanel `rec` mode, `path`, `distance`, target logging.
6. `session.py`, the nine-dot opener and the first rounds, run with `--dry-run`, then on a replay. The bounty board and `bounties.json`.
7. Review, export with encryption (two recipients), `validate.py`, `hub.py` against a test dataset.
8. The window, then the standalone repo.
9. The put-on check in the gaze service. Built 2026-10-14 behind `GAZE_FIT_WATCH=1`: the quick check holds its dot while the coach reads the fit against the saved one (the fit check and the recorder's fitment save a good fit), and the slip note is a strip the gaze panel draws (`show note`) from ft-eyes' `jump_px`. Thresholds are the coach's 5 degrees, not 1.5 mm yet; tuned from the headset tests.
Before uploads open: the consent texts and a review like `frame-hands/notes/legal-review-2026-10-03.md`, with the health opt-in in it.
Not in scope here: the training. The dataset format is designed so that frame-eyes or a later trainer can label pupils from the targets and `own.jsonl`, but that's its own project.
+11
View File
@@ -0,0 +1,11 @@
DRAFT: this text waits for its review, with CONSENT.md.
### About uploading
- **What's sent:** the export in `@EXPORT_PATH@` (@EXPORT_SIZE@), into `contributions/@CONTRIBUTOR@/@ROUND@` in [@DATASET@](https://huggingface.co/datasets/@DATASET@). Upload first checks that every file is complete and matches its checksum, and that the eye images and health answers are encrypted.
- **Who can read it:** the eye images and health answers are encrypted on this headset to the maintainers' keys. Hugging Face and anyone who downloads the dataset get only the encrypted files. The rest (where the dots were, what the trackers found, the fit readings and your checklist answers) stays readable.
- **Your account:** the pull request comes from your Hugging Face account, and anyone can see its username next to your contributor id, `@CONTRIBUTOR@`. 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 Eye Recorder keeps it awake until the upload is done. Keep the Eye 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 decrypt correctly before merging. You can follow it and answer questions on the pull request's page. Once it's merged, you can delete the round and its export here to free the space.
- **Withdrawing:** see "Withdrawing" in the consent text. You'll need your contributor id, `@CONTRIBUTOR@`.
+13
View File
@@ -0,0 +1,13 @@
{"schema": 1, "updated": "2026-10-14",
"bounties": [
{"id": "edges", "title": "View edges", "blurb": "Dots far out to the sides and corners: eyes turned as far as they go.", "minutes": 5, "priority": "high", "script": "edges"},
{"id": "blinks", "title": "Blinks and lids", "blurb": "Blinks, winks, squints and half-closed eyes.", "minutes": 5, "priority": "high", "script": "blinks"},
{"id": "slips", "title": "Headset slips", "blurb": "Nudge the headset on your face, take it off and on: dots after each.", "minutes": 6, "priority": "high", "script": "slips"},
{"id": "glasses", "title": "Glasses", "blurb": "The grid and the edges with glasses or inserts on.", "minutes": 5, "priority": "high", "script": "glasses", "needs": {"glasses": true}},
{"id": "jumps", "title": "Jumps and pursuit", "blurb": "A jumping dot, then one gliding on circles, lines and a figure eight.", "minutes": 5, "priority": "normal", "script": "jumps"},
{"id": "depth", "title": "Depth", "blurb": "Dots near, mid and far.", "minutes": 4, "priority": "normal", "script": "depth"},
{"id": "light", "title": "Light changes", "blurb": "Dark to bright and back: pupils changing size.", "minutes": 5, "priority": "normal", "script": "light"},
{"id": "face", "title": "Face moves", "blurb": "Smile, frown, yawn, talk and chew while looking at a dot.", "minutes": 4, "priority": "normal", "script": "face"},
{"id": "head", "title": "Head turning", "blurb": "A dot fixed in the room while you turn your head.", "minutes": 4, "priority": "normal", "script": "head"},
{"id": "reading", "title": "Reading", "blurb": "Read a few paragraphs and look around freely.", "minutes": 4, "priority": "low", "script": "reading"}
]}
+324
View File
@@ -0,0 +1,324 @@
#!/usr/bin/env python3
"""The eye recorder's frame writer (DESIGN.md: "Files"): every frame of both eye cameras, from
the frames ft-eyegrab shares (gaze/tracker/eyes_share.py), into a take's folder as zstd chunks.
cam0/000000.zst, 000001.zst, ... the right eye (camera 0): up to CHUNK_FRAMES frames each
cam1/... the left eye (camera 1)
index.tsv a header line, then one line per frame:
camera, chunk, frame in the chunk, the tracker's slot, time
(CLOCK_MONOTONIC_RAW seconds, the share's)
A chunk is the frames back to back, 512x400 bytes each, compressed with zstd level 1 (56 % of the
size at about 250 MB/s on one core, measured 2026-10-14; both cameras at 90 fps are 36.9 MB/s
raw). A chunk ends when it's full or the recording pauses, so a pause or a deleted range never
splits one. The index lines of a chunk are written once the chunk is on disk, so the index never
names a chunk that isn't there; they're in chunk order, not time order across the cameras.
One thread copies frames out of the share as they come (it holds only 8 per camera, 89 ms);
another compresses and writes, so a slow chunk never makes the copy fall behind. If the writer
falls MAX_QUEUED chunks behind, the next chunk is dropped and counted rather than held in memory.
Plain Python, standard library: zstd is Python 3.14's compression.zstd (the dev container's), or
zstandard, or the zstd command (SteamOS's host Python 3.12 has neither module).
From the command line, for testing (FT_EYES_CAMS points it at a replay, lab/ft-eyes-replay):
python3 gaze/rec/eyerec.py DIR [SECONDS]
python3 gaze/rec/eyerec.py --read DIR the frames' count and times, decompressed
"""
import os
import queue
import shutil
import subprocess
import sys
import threading
import time
from collections import deque
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(os.path.dirname(HERE), "tracker"))
import eyes_share # noqa: E402 (gaze/tracker/eyes_share.py)
W, H = eyes_share.W, eyes_share.H
FRAME = W * H
CAMERAS = (0, 1) # 0 the right eye, 1 the left (gaze/tracker/README: camera 0 is the steep one)
CHUNK_FRAMES = 90 # a second at 90 fps
LEVEL = 1
MAX_QUEUED = 6 # chunks waiting for the writer (about 18 MB each) before one is dropped
MIN_FREE = 3e9 # bytes: stop before the disk fills
RATE_WINDOW = 2.0 # s of frame times for each camera's rate
SHARE_WAIT = 10.0 # s to wait for the share at the start, or after it was replaced
POLL = 0.002
INDEX_HEADER = "# camera\tchunk\tframe\tslot\tt_raw\n"
def _compressor():
"""(compress(bytes) -> bytes, decompress(bytes) -> bytes, name)."""
try:
from compression import zstd # Python 3.14
return (lambda b: zstd.compress(b, level=LEVEL)), zstd.decompress, "compression.zstd"
except ImportError:
pass
try:
import zstandard
c, d = zstandard.ZstdCompressor(level=LEVEL), zstandard.ZstdDecompressor()
return c.compress, (lambda b: d.decompress(b, max_output_size=CHUNK_FRAMES * FRAME)), "zstandard"
except ImportError:
pass
exe = shutil.which("zstd") or ("/usr/bin/zstd" if os.path.exists("/usr/bin/zstd") else None)
if not exe:
return None, None, None
def run(args, data):
return subprocess.run([exe, *args], input=data, capture_output=True, check=True).stdout
return (lambda b: run(["-q", "-%d" % LEVEL, "-c"], b)), (lambda b: run(["-q", "-d", "-c"], b)), exe
compress, decompress, ZSTD = _compressor()
class Writer:
"""Records the eye cameras into take_dir while recording is on.
start() starts the threads (not recording yet); record(True) and record(False) start and
pause; stop() ends the open chunks, waits for the writer and returns stats(). error is set
(and recording stops) when the disk gets full or the share is gone for good."""
def __init__(self, take_dir, share_path=None, want_path=None, log=None, min_free=MIN_FREE,
chunk_frames=CHUNK_FRAMES):
if compress is None:
raise RuntimeError("no zstd: neither compression.zstd, zstandard nor the zstd command")
self.dir, self.share_path, self.want_path = take_dir, share_path, want_path
self.log = log or (lambda line: None)
self.min_free, self.chunk_frames = min_free, chunk_frames
self.error = None
self._on = False
self._lock = threading.Lock()
self._stop = threading.Event()
self._queue = queue.Queue()
self._open = {c: [] for c in CAMERAS} # the chunk being filled: [(t, slot, bytes)]
self._next = {c: 0 for c in CAMERAS} # the next chunk's number
self._frames = {c: 0 for c in CAMERAS} # frames written (in chunks on disk)
self._dropped = {c: 0 for c in CAMERAS} # frames lost: overwritten in the share, or a dropped chunk
self._times = {c: deque() for c in CAMERAS}
self._last = {c: None for c in CAMERAS}
self._bytes = 0
self._busy = 0.0 # s spent compressing and writing
for c in CAMERAS:
os.makedirs(os.path.join(take_dir, "cam%d" % c), exist_ok=True)
self._index = open(os.path.join(take_dir, "index.tsv"), "a")
if self._index.tell() == 0:
self._index.write(INDEX_HEADER)
# Numbering goes on after any chunks already there (a take resumed after a pause in another run).
for c in CAMERAS:
names = [n for n in os.listdir(os.path.join(take_dir, "cam%d" % c)) if n.endswith(".zst")]
self._next[c] = max((int(n[:-4]) + 1 for n in names if n[:-4].isdigit()), default=0)
self._reader = threading.Thread(target=self._read, name="eyerec-read", daemon=True)
self._writer = threading.Thread(target=self._write, name="eyerec-write", daemon=True)
def start(self):
self._reader.start()
self._writer.start()
return self
def record(self, on):
with self._lock:
if self._on and not on:
for c in CAMERAS:
self._end_chunk(c)
self._on = bool(on) and self.error is None
@property
def recording(self):
return self._on
def stop(self):
self.record(False)
self._stop.set()
self._reader.join(5)
self._queue.put(None)
self._writer.join(60)
self._index.close()
return self.stats()
def stats(self):
"""{"frames": [right, left], "dropped": [...], "fps": [...], "bytes": on disk, "busy": s,
"queued": chunks waiting, "last_t": [the newest frame's time or None], "error"}"""
with self._lock:
fps = []
for c in CAMERAS:
ts = self._times[c]
fps.append(round((len(ts) - 1) / (ts[-1] - ts[0]), 1) if len(ts) > 1 and ts[-1] > ts[0] else 0.0)
return {"frames": [self._frames[c] for c in CAMERAS], "dropped": [self._dropped[c] for c in CAMERAS],
"fps": fps, "bytes": self._bytes, "busy": round(self._busy, 3), "queued": self._queue.qsize(),
"last_t": [self._last[c] for c in CAMERAS], "error": self.error}
# -- the copy
def _read(self):
share = eyes_share.open_share(SHARE_WAIT, self.share_path, self.want_path)
if share is None:
self._fail("no eye camera frames (%s): is frametop-eyegrab.service running?" % (self.share_path or eyes_share.CAMS))
return
seen = {c: share.count(c) for c in CAMERAS}
touched = checked = time.monotonic()
while not self._stop.is_set():
got = False
for c in CAMERAS:
n = share.count(c)
if n - seen[c] > share.slots: # fell behind: those are gone
with self._lock:
if self._on:
self._dropped[c] += n - seen[c] - share.slots
seen[c] = n - share.slots
for i in range(seen[c], n):
f = share.frame(c, i)
got = True
with self._lock:
if f is None:
if self._on:
self._dropped[c] += 1
continue
self._seen(c, f[0])
if self._on:
self._open[c].append(f)
if len(self._open[c]) >= self.chunk_frames:
self._end_chunk(c)
seen[c] = n
now = time.monotonic()
if now - touched >= 1.0:
touched = now
eyes_share.touch_want(self.want_path)
if now - checked >= 2.0:
checked = now
if self._on and shutil.disk_usage(self.dir).free < self.min_free:
self._fail("under %.1f GB free on the disk" % (self.min_free / 1e9))
if share.replaced(): # ft-eyegrab restarted (SteamVR did): follow it
self.log("eye frames: the share was replaced; following it")
share.close()
share = eyes_share.open_share(SHARE_WAIT, self.share_path, self.want_path)
if share is None:
self._fail("the eye camera frames stopped (frametop-eyegrab.service)")
return
seen = {c: share.count(c) for c in CAMERAS}
if not got:
time.sleep(POLL)
share.close()
def _seen(self, c, t):
ts = self._times[c]
ts.append(t)
while ts and ts[0] < t - RATE_WINDOW:
ts.popleft()
self._last[c] = t
def _end_chunk(self, c):
"""Hand the open chunk to the writer (with the lock held)."""
frames = self._open[c]
if not frames:
return
self._open[c] = []
if self._queue.qsize() >= MAX_QUEUED:
self._dropped[c] += len(frames)
self.log("eye frames: the writer is behind; dropped %d frames of camera %d" % (len(frames), c))
return
self._queue.put((c, self._next[c], frames))
self._next[c] += 1
def _fail(self, why):
with self._lock:
if self.error is None:
self.error = why
self.log("eye frames: " + why)
if self._on:
for c in CAMERAS:
self._end_chunk(c)
self._on = False
# -- the writer
def _write(self):
while True:
item = self._queue.get()
if item is None:
return
c, chunk, frames = item
t0 = time.perf_counter()
path = os.path.join(self.dir, "cam%d" % c, "%06d.zst" % chunk)
try:
data = compress(b"".join(f[2] for f in frames))
with open(path + ".tmp", "wb") as f:
f.write(data)
os.replace(path + ".tmp", path)
except (OSError, subprocess.CalledProcessError) as e:
self._fail("can't write %s: %s" % (path, e))
with self._lock:
self._dropped[c] += len(frames)
continue
self._index.write("".join("%d\t%d\t%d\t%d\t%.6f\n" % (c, chunk, i, f[1], f[0]) for i, f in enumerate(frames)))
self._index.flush()
with self._lock:
self._frames[c] += len(frames)
self._bytes += len(data)
self._busy += time.perf_counter() - t0
def read_index(take_dir):
"""index.tsv as [(camera, chunk, frame, slot, t), ...] in its order."""
out = []
try:
with open(os.path.join(take_dir, "index.tsv")) as f:
for line in f:
if line.startswith("#") or not line.strip():
continue
c, chunk, i, slot, t = line.split("\t")
out.append((int(c), int(chunk), int(i), int(slot), float(t)))
except FileNotFoundError:
pass
return out
def read_chunk(take_dir, cam, chunk):
"""The frames of a chunk, as a list of 512x400 byte strings."""
with open(os.path.join(take_dir, "cam%d" % cam, "%06d.zst" % chunk), "rb") as f:
raw = decompress(f.read())
if len(raw) % FRAME:
raise ValueError("cam%d/%06d.zst: %d bytes isn't whole frames" % (cam, chunk, len(raw)))
return [raw[i:i + FRAME] for i in range(0, len(raw), FRAME)]
def iter_frames(take_dir):
"""Every frame in index order: (camera, t, slot, bytes)."""
cache = (None, None)
for c, chunk, i, slot, t in read_index(take_dir):
if cache[0] != (c, chunk):
cache = ((c, chunk), read_chunk(take_dir, c, chunk))
yield c, t, slot, cache[1][i]
def main(argv):
if not argv or argv[0] in ("-h", "--help"):
sys.exit(__doc__)
if argv[0] == "--read":
n, ts = [0, 0], [[], []]
for c, t, _slot, _data in iter_frames(argv[1]):
n[c] += 1
ts[c].append(t)
for c in CAMERAS:
span = max(ts[c]) - min(ts[c]) if len(ts[c]) > 1 else 0.0
print("camera %d: %d frames over %.2f s" % (c, n[c], span))
return
secs = float(argv[1]) if len(argv) > 1 else 10.0
w = Writer(argv[0], log=lambda line: print(line, file=sys.stderr)).start()
w.record(True)
end = time.monotonic() + secs
try:
while time.monotonic() < end and w.error is None:
time.sleep(1)
print(w.stats(), file=sys.stderr)
except KeyboardInterrupt:
pass
print(w.stop())
if __name__ == "__main__":
main(sys.argv[1:])
+21
View File
@@ -0,0 +1,21 @@
#!/bin/bash
# Launch the Frametop Eye 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_eyerec.py: --base DIR, --page NAME, and --dry-run (--hub-dry-run, --ignore-eyes) 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_eyerec.py" "$@"
+9
View File
@@ -0,0 +1,9 @@
[Desktop Entry]
Type=Application
Name=Frametop Eye Recorder
GenericName=Record your eyes for the eye dataset
Comment=Fit the headset, then record, review and export eye recordings for Frametop's eye dataset
Exec=@REPO@/gaze/rec/ft-eyerec
Icon=camera-video
Categories=Utility;
Keywords=eyes;eye tracking;gaze;dataset;record;frametop;
+827
View File
@@ -0,0 +1,827 @@
#!/usr/bin/env python3
"""Frametop Eye Recorder: record your eyes for the eye dataset (gaze/rec/DESIGN.md).
A Kirigami (QML) app with a Python backend, in the dev container, as the hand recorder
(hands/rec/ft_handrec.py); what the two windows share is recorder/window.py:
- Welcome: the consent text (CONSENT.md), the first time and again when its version changes.
Agreeing writes profile.json with a random contributor id.
- Bounties: the bounty board (recorder/bounties.py): what to record, the priority the
maintainers gave it, and how often you've done it. Refresh fetches the dataset's board
(hub.py board). Picking one goes on to the checklist.
- Before you start: the checklist (glasses, eye makeup, face pad and strap, a measured IPD),
kept in profile.json; the health questions behind their own tick, kept in BASE/health.json
and encrypted in the export; free space; the eye camera check (frames from ft-eyegrab at
90 fps, with the fix when SteamVR runs them at 15). Start hands the round to session.py.
- Round: the runner's live status, the fit card while the headset is fitted, Next, Pause,
Redo, Skip and Stop (Space, P, R, S and Esc while the window has focus; the button on the
headset's right side too). The prompts and dots appear in the headset.
- Review: rounds, their takes, and a viewer of both eye cameras a frame at a time, where
ranges, takes and rounds can be deleted (takes.py).
- Export: encrypt what's kept into exports/<round>/ at nice 19 (takes.py).
- Upload: the Hugging Face login, and Upload: hub.py checks the export (validate.py) and
uploads it as a pull request. Nothing reaches the real dataset until CONSENT.md and
UPLOAD.md are reviewed (hub.py's gate); --hub-dry-run does everything but the network calls.
Everything lives under ~/.local/share/frametop/eyes/contrib (--base). Launch with
gaze/rec/ft-eyerec (host wrapper).
"""
import argparse
import bisect
import datetime
import json
import os
import signal
import subprocess
import sys
import threading
import time
from PySide6.QtCore import Property, Qt, QTimer, QUrl, Signal, Slot
from PySide6.QtGui import QColor, QFont, QGuiApplication, QIcon, QImage, QPainter
from PySide6.QtQml import QQmlApplicationEngine
from PySide6.QtQuick import QQuickImageProvider
from PySide6.QtQuickControls2 import QQuickStyle
import shiboken6
HERE = os.path.dirname(os.path.abspath(__file__))
GAZE = os.path.dirname(HERE)
REPO = os.path.dirname(GAZE)
sys.path.insert(0, HERE)
sys.path.insert(0, REPO)
import eyerec # noqa: E402 (next to this file; it imports gaze/tracker/eyes_share.py)
import eyes_share # noqa: E402
import hub # noqa: E402
import takes # noqa: E402
from recorder import bounties # noqa: E402
from recorder.common import host_command, write_json # noqa: E402
from recorder.files import human_bytes, read_json # noqa: E402
from recorder.window import RecorderBackend # noqa: E402
HUB_PATH = os.path.join(HERE, "hub.py")
EYE_RATE = os.path.join(GAZE, "eye-rate.py")
AWAKE_UNIT = "frametop-eyerec-awake.service"
# A round of about 5 recorded minutes is about 6 GB (1.2 GB a minute: DESIGN.md, "Size"), and
# its export as much again.
ROUND_BYTES = 12 * 1000 ** 3
ACTIVE_STATES = ("starting", "fitment", "ready", "countdown", "running", "paused")
EYE_FPS_OK = 60 # under this the cameras run at SteamVR's 15 fps: recordings are worth little
EYE_CHECK_S = 1.5 # how long the eye camera check counts frames
# After the eye rate fix's SteamVR restart: check the cameras this often, for at most this long.
RECHECK_S = 3
RECHECK_FOR_S = 120
FRAME_HEIGHT = 400 # the viewer's height for each camera (the cameras' own)
THUMB_HEIGHT = 96
# The checklist's choices (DESIGN.md, "Checklist"); the keys are what profile.json keeps.
GLASSES = [("none", "No glasses"), ("glasses", "Glasses"), ("inserts", "Prescription lens inserts"),
("contacts", "Contact lenses")]
MAKEUP = [("mascara", "Mascara"), ("eyeliner", "Eyeliner"), ("lashes", "Lash extensions")]
PADS = [("", "Rather not say"), ("stock", "The face pad it came with"), ("other", "Another face pad")]
STRAPS = [("", "Rather not say"), ("stock", "The strap it came with"), ("other", "Another strap")]
# The health questions: only with their own tick, and only ever in health.json(.age).
HEALTH = [("surgery", "LASIK or other eye surgery"), ("strabismus", "A lazy or turned eye"),
("ptosis", "A droopy eyelid"), ("nystagmus", "Nystagmus (eyes that move by themselves)"),
("other", "Another eye condition")]
GROUP_TITLES = {"ipd": "IPD sweep", "dots": "Nine dots"}
STATUS_TEXT = {"running": "interrupted", "error": "ended with an error", "stopped": "stopped early"}
def round_label(rid, title=""):
"""20261014-120000-edges -> 2026-10-14 12:00 · View edges."""
try:
when = datetime.datetime.strptime(rid[:15], "%Y%m%d-%H%M%S").strftime("%Y-%m-%d %H:%M")
except ValueError:
return rid
rest = rid[16:]
n = rest.rsplit("-", 1)[1] if "-" in rest and rest.rsplit("-", 1)[1].isdigit() else ""
return f"{when} · {title or rest}" + (f" ({n})" if n else "")
def take_title(group):
return GROUP_TITLES.get(group) or group.replace("-", " ").replace("_", " ").capitalize()
def clock_text(seconds):
return f"{int(seconds // 60)}:{seconds % 60:04.1f}"
def eye_check(share_path=None, seconds=EYE_CHECK_S):
"""Are the eye cameras' frames coming, and how fast? {"state": ok|slow|none, "fps": [right,
left], "text"}. Counts frames in ft-eyegrab's share (read-only; it touches the want file,
which wakes ft-eyegrab, as every reader does)."""
share = eyes_share.open_share(3.0, share_path)
if share is None:
return {"state": "none", "fps": [0, 0],
"text": "No eye camera frames: frametop-eyegrab.service isn't running. Frametop's gaze setup "
"installs it (gaze/tracker/install.sh), and SteamVR has to be running."}
try:
time.sleep(0.5) # ft-eyegrab starts copying once it sees the want file
eyes_share.touch_want()
a, t0 = [share.count(c) for c in eyerec.CAMERAS], time.monotonic()
time.sleep(seconds)
b, t1 = [share.count(c) for c in eyerec.CAMERAS], time.monotonic()
finally:
share.close()
fps = [round((y - x) / (t1 - t0), 1) for x, y in zip(a, b)]
if max(fps) <= 0:
return {"state": "none", "fps": fps,
"text": "The eye cameras aren't sending frames. Is SteamVR running? If it is, restarting it "
"starts the eye cameras again."}
if min(fps) < EYE_FPS_OK:
return {"state": "slow", "fps": fps,
"text": f"The eye cameras run at {min(fps):.0f} frames a second; recordings need 90. SteamVR runs "
"them at 90 with a setting Frametop can turn on, from SteamVR's next start."}
return {"state": "ok", "fps": fps, "text": ""}
class Timeline:
"""A take's frames for the viewer: the camera with more frames sets the timeline, and the
other camera's frame nearest in time goes beside it. Chunks are decompressed when needed
and the last few kept."""
KEEP = 4
def __init__(self, take_dir, clock):
self.dir = take_dir
self.clock = clock or []
frames = {c: [] for c in eyerec.CAMERAS}
for c, chunk, i, _slot, t in eyerec.read_index(take_dir):
if c in frames:
frames[c].append((t, chunk, i))
for c in frames:
frames[c].sort()
self.main = max(eyerec.CAMERAS, key=lambda c: (len(frames[c]), -c))
self.frames = frames
self.times = {c: [f[0] for f in frames[c]] for c in frames}
self._chunks = {}
self._lock = threading.Lock()
def __len__(self):
return len(self.frames[self.main])
def time(self, i):
return self.frames[self.main][i][0]
def mono_ns(self, t_raw):
"""A frame's RAW seconds as CLOCK_MONOTONIC ns (take.json's clock samples, turned round)."""
raw = int(round(t_raw * 1e9))
guess = raw - takes.raw_offset_ns(raw, self.clock)
return raw - takes.raw_offset_ns(guess, self.clock)
def _chunk(self, cam, chunk):
with self._lock:
key = (cam, chunk)
if key in self._chunks:
self._chunks[key] = self._chunks.pop(key) # the newest at the end
return self._chunks[key]
frames = eyerec.read_chunk(self.dir, cam, chunk)
with self._lock:
self._chunks[key] = frames
while len(self._chunks) > self.KEEP:
self._chunks.pop(next(iter(self._chunks)))
return frames
def pair(self, i):
"""{camera: bytes} at timeline index i: the main camera's frame and the other's nearest."""
out = {}
t, chunk, k = self.frames[self.main][i]
out[self.main] = self._chunk(self.main, chunk)[k]
for c in eyerec.CAMERAS:
if c == self.main or not self.frames[c]:
continue
j = bisect.bisect_left(self.times[c], t)
j = min(range(max(0, j - 1), min(len(self.times[c]), j + 1)), key=lambda n: abs(self.times[c][n] - t))
_, chunk, k = self.frames[c][j]
out[c] = self._chunk(c, chunk)[k]
return out
class Timelines:
"""Timelines by take, made again when the take's index.tsv or take.json changes."""
def __init__(self, store):
self.store = store
self._made = {}
self._lock = threading.Lock()
def get(self, rnd, take):
d = self.store.take_dir(rnd, take)
stamp = tuple(os.path.getmtime(os.path.join(d, n)) if os.path.exists(os.path.join(d, n)) else 0
for n in ("index.tsv", "take.json"))
with self._lock:
got = self._made.get((rnd, take))
if got and got[0] == stamp:
return got[1]
tl = Timeline(d, read_json(os.path.join(d, "take.json")).get("clock"))
with self._lock:
self._made[(rnd, take)] = (stamp, tl)
if len(self._made) > 8:
self._made.pop(next(iter(self._made)))
return tl
def grey_image(data):
img = QImage(data, eyerec.W, eyerec.H, eyerec.W, QImage.Format_Grayscale8)
return img.copy()
class EyeProvider(QQuickImageProvider):
"""image://eyes/pair/ROUND/TAKE/INDEX: both eye cameras at a timeline index, the right eye
(camera 0) first. image://eyes/thumb/ROUND/TAKE: the main camera mid-take, small. Anything
after "?" is ignored (it makes QML load the image again)."""
def __init__(self, timelines):
super().__init__(QQuickImageProvider.ImageType.Image)
self.timelines = timelines
def requestImage(self, ident, size, requested):
parts = ident.split("?", 1)[0].split("/")
try:
if parts[0] == "thumb" and len(parts) == 3:
tl = self.timelines.get(parts[1], parts[2])
if not len(tl):
raise ValueError("no frames")
data = tl.pair(len(tl) // 2)[tl.main]
return grey_image(data).scaledToHeight(THUMB_HEIGHT, Qt.SmoothTransformation)
if parts[0] == "pair" and len(parts) == 4:
return self._pair(self.timelines.get(parts[1], parts[2]), int(parts[3]),
requested.height() if requested.height() > 0 else FRAME_HEIGHT)
except (OSError, ValueError, IndexError, KeyError) as e:
print(f"ft-eyerec: image {ident}: {e}", file=sys.stderr)
img = QImage(4, 3, QImage.Format_Grayscale8)
img.fill(0)
return img
def _pair(self, tl, i, height):
frames = tl.pair(i)
gap = 8
scaled = [(c, grey_image(frames[c]).scaledToHeight(height, Qt.SmoothTransformation))
for c in eyerec.CAMERAS if c in frames]
out = QImage(sum(s.width() for _, s in scaled) + gap * (len(scaled) - 1), height, QImage.Format_RGB32)
out.fill(QColor(30, 30, 30))
p = QPainter(out)
font = QFont()
font.setPixelSize(max(12, height // 22))
p.setFont(font)
x = 0
for c, img in scaled:
p.drawImage(x, 0, img)
p.setPen(QColor(255, 200, 80))
p.drawText(x + 6, 6 + font.pixelSize(), ("Right eye" if c == 0 else "Left eye") + f" (camera {c})")
x += img.width() + gap
p.end()
return out
class Backend(RecorderBackend):
"""The eye recorder's window backend: recorder/window.py's, plus the bounty board, the
checklist and health answers, the eye camera check, the round and the review."""
APP = "Frametop Eye Recorder"
AWAKE_UNIT = AWAKE_UNIT
AWAKE_WHY = "Exporting or uploading eye recordings"
HUB_PATH = HUB_PATH
CONSENT_PATH = hub.CONSENT_PATH
UPLOAD_PATH = hub.UPLOAD_PATH
ACTIVE_STATES = ACTIVE_STATES
ROUND_BYTES = ROUND_BYTES
PROFILE_KEEP = ("checklist", "bounties", "eyes_ipd")
# A property here can't notify with the base's signals (PySide6 6.11 leaves it without
# one), so these relay them.
profileRelay = Signal()
sessionsRelay = Signal()
boardChanged = Signal()
healthChanged = Signal()
eyesChanged = Signal()
_eyesArrived = Signal(dict)
_boardArrived = Signal(dict)
def __init__(self, store, session_options=None, hub_dry_run=False, ignore_eyes=False, timelines=None):
super().__init__(store, hub, hub_dry_run)
self.profileChanged.connect(self.profileRelay)
self.sessionsChanged.connect(self.sessionsRelay)
self.profileChanged.connect(self.boardChanged) # the board's done marks and needs
self._session_options = session_options or {} # Session options: dry_run, speed, cams, button
self._session_mod = None
self._session_error = ""
self._timelines = timelines or Timelines(store)
self._ignore_eyes = ignore_eyes
self._eyes = {}
self._eyes_busy = False
self._restarting = False
self._board = {"state": "", "text": ""}
self._board_busy = False
self._eyesArrived.connect(self._on_eyes)
self._boardArrived.connect(self._on_board)
# --- the session runner, imported when first needed
def _runner(self):
if self._session_mod is None and not self._session_error:
try:
import session as mod
self._session_mod = mod
except Exception as e: # missing, or broken: say so, the rest of the app still works
self._session_error = f"The session runner (gaze/rec/session.py) can't be loaded: {e}"
return self._session_mod
def _runner_error(self):
self._runner()
return self._session_error
def _texts_draft(self):
return not hub.texts_ready()
def _upload_allowed(self):
try:
return hub.upload_allowed(hub.dataset_id())
except hub.HubError:
return False
def _upload_values(self, session, path):
return {"ROUND": session}
@Property(str, constant=True)
def toolVersion(self):
return takes.tool_version()
# --- consent
@Slot(bool, bool, bool)
def acceptConsent(self, adult, region, agree):
"""Write profile.json (recorder/window.py); its checklist and bounties stay."""
optional = self.store.profile().get("optional")
self._write_consent(adult, region, agree, optional if isinstance(optional, dict) else {})
# --- the bounty board
def _checklist(self):
c = self.store.profile().get("checklist")
return c if isinstance(c, dict) else {}
def _board_now(self):
mod = self._runner()
return mod.load_board(self.store.base) if mod else None
@Property("QVariantList", notify=boardChanged)
def bounties(self):
"""The board's bounties (bounties.view), with "lastText" for the last round."""
mod = self._runner()
if not mod:
return []
rows = bounties.view(self._board_now(), self.store.profile(), self._checklist(), mod.have_round)
for b in rows:
b["lastText"] = round_label(b["last"]).split(" · ")[0] if b["last"] else ""
b["minutesText"] = f"about {b['minutes']:g} min" if b["minutes"] else ""
return rows
@Property(str, notify=boardChanged)
def boardUpdated(self):
board = self._board_now()
return board["updated"] if board else ""
@Property("QVariantMap", notify=boardChanged)
def boardFetch(self):
"""The last fetch: {"state": ""|fetching|ok|error, "text"}."""
return self._board
@Slot()
def refreshBoard(self):
"""hub.py board in a child process: the dataset's board into board-cache.json."""
if self._board_busy or self._hub_dry_run:
return
self._board_busy = True
self._board = {"state": "fetching", "text": "Getting the newest board"}
self.boardChanged.emit()
argv = self._hub_argv("board", "--json")
def run():
try:
r = subprocess.run(argv, capture_output=True, text=True, timeout=60)
lines = [json.loads(x) for x in r.stdout.splitlines() if x.startswith("{")]
result = lines[-1] if lines else {"error": {"text": (r.stderr.strip().splitlines() or ["hub.py failed"])[-1]}}
except (OSError, ValueError, subprocess.TimeoutExpired) as e:
result = {"error": {"text": f"The board didn't come: {e}"}}
self._boardArrived.emit(result)
self._thread(run)
def _on_board(self, result):
self._board_busy = False
if "done" in result:
self._board = {"state": "ok", "text": f"The newest board, of {result['done'].get('updated', '?')}"}
else:
self._board = {"state": "error", "text": (result.get("error") or {}).get("text", "The board didn't come")
+ " The board that came with the recorder is used."}
self.boardChanged.emit()
@Slot(str, result=str)
def planText(self, bounty_id):
"""How long a bounty's round takes (session.plan_seconds), with the fit check before it."""
mod = self._runner()
b = next((b for b in self.bounties if b["id"] == bounty_id), None)
if not mod or not b:
return ""
try:
plan = mod.build_plan(mod.load_round(mod.round_path(b["script"])), 0, ipd_sweep=False)
except (OSError, ValueError) as e:
return f"Couldn't read the round: {e}"
return (f"{len(plan)} steps, about {mod.plan_seconds(plan) / 60:.0f} min recorded, after the headset's fit "
"check (and an IPD sweep on your first round, or when the IPD setting changed)")
# --- the checklist and health answers
@Property("QVariantMap", notify=profileRelay)
def checklist(self):
c = self._checklist()
return {"glasses": c.get("glasses") if c.get("glasses") in dict(GLASSES) else "none",
"makeup": [m for m in c.get("makeup") or [] if m in dict(MAKEUP)],
"pad": c.get("pad") if c.get("pad") in dict(PADS) else "",
"strap": c.get("strap") if c.get("strap") in dict(STRAPS) else "",
"ipd_mm": c.get("ipd_mm") if isinstance(c.get("ipd_mm"), (int, float)) else 0}
@Property("QVariantList", constant=True)
def glassesChoices(self):
return [{"value": k, "text": v} for k, v in GLASSES]
@Property("QVariantList", constant=True)
def makeupChoices(self):
return [{"value": k, "text": v} for k, v in MAKEUP]
@Property("QVariantList", constant=True)
def padChoices(self):
return [{"value": k, "text": v} for k, v in PADS]
@Property("QVariantList", constant=True)
def strapChoices(self):
return [{"value": k, "text": v} for k, v in STRAPS]
@Property("QVariantList", constant=True)
def healthChoices(self):
return [{"value": k, "text": v} for k, v in HEALTH]
@Slot("QVariantMap")
def saveChecklist(self, answers):
"""Keep the checklist in profile.json: only the known answers. ipd_mm: 0 when not known,
else 50 to 80 mm."""
a = dict(answers)
try:
ipd = round(float(a.get("ipd_mm") or 0), 1)
except (TypeError, ValueError):
ipd = 0.0
checklist = {"glasses": a.get("glasses") if a.get("glasses") in dict(GLASSES) else "none",
"makeup": sorted({m for m in a.get("makeup") or [] if m in dict(MAKEUP)}),
"pad": a.get("pad") if a.get("pad") in dict(PADS) else "",
"strap": a.get("strap") if a.get("strap") in dict(STRAPS) else "",
"ipd_mm": ipd if 50 <= ipd <= 80 else None}
profile = self.store.profile()
if not profile or profile.get("checklist") == checklist:
return
profile["checklist"] = checklist
write_json(self.store.profile_path, profile)
self.profileChanged.emit()
def _health_path(self):
return os.path.join(self.store.base, "health.json")
def _health(self):
h = read_json(self._health_path())
return h if h.get("opt_in") is True else {}
@Property(bool, notify=healthChanged)
def healthOptIn(self):
return bool(self._health())
@Property("QVariantList", notify=healthChanged)
def healthAnswers(self):
return [k for k in self._health().get("conditions") or [] if k in dict(HEALTH)]
@Slot(bool, "QVariantList")
def saveHealth(self, opt_in, conditions):
"""The health answers, in BASE/health.json (only this user can read it), never in
profile.json; each round gets a copy, which its export encrypts. Opting out deletes them."""
path = self._health_path()
if not opt_in:
try:
os.remove(path)
except FileNotFoundError:
pass
else:
data = {"schema": 1, "opt_in": True, "conditions": sorted({c for c in conditions if c in dict(HEALTH)})}
if read_json(path) == data:
return
fd = os.open(path + ".tmp", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as f:
json.dump(data, f, indent=1)
f.write("\n")
os.replace(path + ".tmp", path)
self.healthChanged.emit()
# --- the eye camera check
@Property(str, notify=eyesChanged)
def eyeState(self):
"""ok, slow, none; checking while it runs; "" before the first check."""
if self._eyes_busy and not self._eyes:
return "checking"
return self._eyes.get("state", "")
@Property(str, notify=eyesChanged)
def eyeText(self):
return self._eyes.get("text", "")
@Property(str, notify=eyesChanged)
def eyeFpsText(self):
fps = self._eyes.get("fps") or []
return " · ".join(f"{name} {f:.0f} fps" for name, f in zip(("right", "left"), fps))
@Property(bool, notify=eyesChanged)
def eyeBusy(self):
return self._eyes_busy
@Property(bool, notify=eyesChanged)
def restartingSteamVR(self):
return self._restarting
@Property(bool, constant=True)
def eyesIgnored(self):
return self._ignore_eyes or bool(self._session_options.get("dry_run"))
@Property(bool, notify=eyesChanged)
def eyesBlockStart(self):
return not self.eyesIgnored and self._eyes.get("state") != "ok"
def _check_now(self):
if self.eyesIgnored:
return {"state": "ok", "fps": [], "text": ""}
try:
return eye_check(self._session_options.get("cams"))
except Exception as e:
return {"state": "none", "fps": [], "text": f"The eye camera check failed: {e}"}
@Slot()
def checkEyes(self):
if self._eyes_busy or self.sessionActive:
return
self._eyes_busy = True
self.eyesChanged.emit()
self._thread(lambda: self._eyesArrived.emit(self._check_now()))
def _on_eyes(self, result):
self._eyes = result
self._eyes_busy = self._restarting
self.eyesChanged.emit()
@Slot(bool)
def restartSteamVR(self, fast):
"""fast: first turn on SteamVR's 90 fps eye cameras (gaze/eye-rate.py on, on the host).
Then systemctl --user restart --no-block steamvr.service (the job runs in systemd, so it
finishes even when this window closes with the Frametop desktop), and the eye check every
few seconds until the frames come at 90."""
if self._restarting or self.sessionActive:
return
self._restarting = self._eyes_busy = True
self.eyesChanged.emit()
def run():
result = None
try:
if fast:
r = subprocess.run(host_command("python3", EYE_RATE, "on"), capture_output=True, text=True,
timeout=60)
if r.returncode != 0:
raise RuntimeError((r.stderr or r.stdout).strip() or "eye-rate.py: exit %d" % r.returncode)
r = subprocess.run(host_command("systemctl", "--user", "restart", "--no-block", "steamvr.service"),
capture_output=True, text=True, timeout=60)
if r.returncode != 0:
raise RuntimeError((r.stderr or r.stdout).strip() or "exit %d" % r.returncode)
end = time.monotonic() + RECHECK_FOR_S
time.sleep(RECHECK_S * 3)
while time.monotonic() < end:
result = self._check_now()
if result.get("state") == "ok":
break
time.sleep(RECHECK_S)
except Exception as e:
result = {"state": "none", "fps": [], "text": f"Couldn't restart SteamVR: {e}"}
self._restarting = False
self._eyesArrived.emit(result or self._check_now())
self._thread(run)
# --- the round
@Slot(str, result=bool)
def startSession(self, bounty_id):
if self.sessionActive:
return False
mod = self._runner()
if not mod:
self.message.emit(self._session_error, True)
return False
if self.needsConsent:
self.message.emit("Agree to the consent text first (Welcome page)", True)
return False
entry = next((b for b in self.bounties if b["id"] == bounty_id), None)
if not entry:
self.message.emit("Pick a bounty first", True)
return False
if entry["available"]:
self.message.emit(entry["available"], True)
return False
if not self.eyesIgnored:
self._eyes = self._check_now() # fresh: it takes two seconds
self.eyesChanged.emit()
if self._eyes.get("state") != "ok":
self.message.emit(self._eyes.get("text", "The eye cameras aren't ready"), True)
return False
board = self._board_now() or {}
try:
self._session = mod.Session(self.store.base, entry["script"], bounty=dict(entry, updated=board.get("updated")),
profile=self.store.profile(), checklist=self._checklist(), health=self._health(),
on_status=lambda s: self._statusArrived.emit(dict(s)),
profile_path=self.store.profile_path, **self._session_options)
except Exception as e:
self.message.emit(f"Couldn't set up the round: {e}", True)
return False
self._session_id = ""
self._status = {"state": "starting", "bounty": bounty_id}
self.statusChanged.emit()
session = self._session
def run():
try:
session.start()
except Exception as e:
self._statusArrived.emit({"state": "error", "error": str(e)})
self._thread(run)
return True
def _on_status(self, status):
super()._on_status(status)
if status.get("state") == "done":
self.profileChanged.emit() # the bounty is marked done, and the IPD kept
# --- review
def _session_rows(self):
out = []
for r in self.store.rounds():
r["label"] = round_label(r["id"], r["title"])
r["sizeText"] = human_bytes(r["bytes"])
r["exportText"] = human_bytes(r["export_bytes"]) if r["exported"] else ""
r["active"] = self.sessionActive and r["id"] == self._session_id
r["statusText"] = "" if r["active"] else STATUS_TEXT.get(r["status"], "")
out.append(r)
return out
@Slot(str, result="QVariantList")
def takeList(self, rnd):
try:
rows = self.store.takes(rnd)
except ValueError:
return []
for t in rows:
t["title"] = take_title(t["group"])
t["durationText"] = f"{int(t['duration_s'] // 60)}:{int(t['duration_s'] % 60):02d}"
t["sizeText"] = human_bytes(t["bytes"])
# Per eye, as the viewer steps (the camera with more frames)
t["frameCount"] = max(t["frames"], default=0)
t["deletedCount"] = max(t["deleted_frames"], default=0)
t.pop("ranges")
return rows
@Slot(str, str, result="QVariantMap")
def takeInfo(self, rnd, take):
"""For the viewer: {count, title, ranges: [[first, last] timeline indexes]}."""
try:
tl = self._timelines.get(rnd, take)
ranges = self.store.ranges(rnd, take)
meta = self.store.take_meta(rnd, take)
except (OSError, ValueError):
return {"count": 0, "title": take, "ranges": []}
marks = []
monos = [tl.mono_ns(t) for t in tl.times[tl.main]]
for a, b in ranges:
first, last = bisect.bisect_left(monos, a), bisect.bisect_right(monos, b) - 1
marks.append([first, last] if first <= last else [-1, -1])
return {"count": len(tl), "title": take_title(meta.get("group", take.split("-", 1)[-1])), "ranges": marks}
@Slot(str, str, int, result=str)
def frameTime(self, rnd, take, i):
"""Frame i's time from the take's first, m:ss.s."""
try:
tl = self._timelines.get(rnd, take)
return clock_text(tl.time(i) - tl.time(0))
except (OSError, ValueError, IndexError):
return ""
@Slot(str, str, int, int)
def deleteRange(self, rnd, take, first, last):
"""Leave frames first..last (timeline indexes, either order) out of the export: both
cameras', by time."""
if self._active_guard(rnd):
return
tl = self._timelines.get(rnd, take)
first, last = sorted((max(0, first), min(len(tl) - 1, last)))
if first > last:
return
# Half a millisecond either side: index.tsv keeps whole microseconds, and the clocks'
# conversion rounds; the frames are 11 ms apart.
self.store.delete_range(rnd, take, tl.mono_ns(tl.time(first)) - 500000, tl.mono_ns(tl.time(last)) + 500000)
self.message.emit(f"Frames {first + 1} to {last + 1} won't be exported", False)
self.sessionsChanged.emit()
@Slot(str, str, int)
def restoreRange(self, rnd, take, k):
self.store.restore_range(rnd, take, k)
self.message.emit("Range restored", False)
self.sessionsChanged.emit()
@Slot(str, str)
def deleteTake(self, rnd, take):
if self._active_guard(rnd):
return
try:
self.store.delete_take(rnd, take)
self.message.emit(f"Deleted {take}", False)
except (OSError, ValueError) as e:
self.message.emit(f"Couldn't delete {take}: {e}", True)
self.refreshSessions()
@Slot(str)
def deleteSession(self, rnd):
if self._active_guard(rnd):
return
try:
self.store.delete_round(rnd)
self.message.emit(f"Deleted the round of {round_label(rnd)}", False)
except (OSError, ValueError) as e:
self.message.emit(f"Couldn't delete the round: {e}", True)
self.refreshSessions()
# --- export
@Property(str, constant=True)
def exportProblem(self):
"""Why nothing can be exported here, or ""."""
if eyerec.compress is None:
return "zstd isn't installed in the dev container, so nothing can be exported. Run setup/dev-container.sh."
try:
import cryptography # noqa: F401 (recorder/age.py's)
except ImportError:
return ("The cryptography library isn't installed in the dev container, so nothing can be encrypted "
"for export. Run setup/dev-container.sh.")
return ""
def main():
ap = argparse.ArgumentParser(description="Frametop Eye Recorder")
ap.add_argument("--base", default=takes.DEFAULT_BASE, help="where profile.json, rounds/ and exports/ go")
ap.add_argument("--page", default="",
help="open on this page: welcome, bounties, checklist, session, review, export, upload")
ap.add_argument("--dry-run", action="store_true",
help="test: rounds start no processes, make up the panel's replies and print its commands")
ap.add_argument("--speed", type=float, default=1.0, help="test, with --dry-run: run rounds this much faster")
ap.add_argument("--cams", help="test: read eye frames from this share (lab/ft-eyes-replay's)")
ap.add_argument("--no-headset-button", action="store_true",
help="rounds don't read the headset's button (Next, pause, resume)")
ap.add_argument("--hub-dry-run", action="store_true",
help="test: Upload checks the export and says what it would send, with no network calls")
ap.add_argument("--ignore-eyes", action="store_true",
help="start rounds even if the eye camera check finds no frames, or slow ones")
ap.add_argument("--qml", default=os.path.join(HERE, "main.qml"),
help="the window (default: this folder's main.qml, which needs Kirigami)")
ap.add_argument("--style", default="org.kde.desktop", help="the Qt Quick Controls style")
a, qt_args = ap.parse_known_args()
app = QGuiApplication([sys.argv[0]] + qt_args)
app.setApplicationName("ft-eyerec")
app.setApplicationDisplayName("Frametop Eye Recorder")
app.setDesktopFileName("ft-eyerec")
if not QIcon.themeName():
QIcon.setThemeName("breeze")
QQuickStyle.setStyle(a.style)
store = takes.Store(a.base)
timelines = Timelines(store)
engine = QQmlApplicationEngine()
engine.addImageProvider("eyes", EyeProvider(timelines))
options = {"dry_run": True, "speed": a.speed} if a.dry_run else {}
if a.cams:
options["cams"] = a.cams
if a.no_headset_button or a.dry_run:
options["button"] = False
backend = Backend(store, options, hub_dry_run=a.hub_dry_run, ignore_eyes=a.ignore_eyes, timelines=timelines)
app.aboutToQuit.connect(backend.shutdown)
mod = None if a.dry_run else backend._runner()
if mod: # Frametop's gaze service, if a round that was killed left it paused
backend._thread(lambda: mod.resume_units(os.path.join(mod.run_dir(), mod.PAUSED_UNITS_FILE)))
engine.rootContext().setContextProperty("backend", backend)
engine.rootContext().setContextProperty("startPage", a.page)
engine.load(QUrl.fromLocalFile(os.path.abspath(a.qml)))
if not engine.rootObjects():
sys.exit(1)
# SIGTERM and Ctrl+C quit as closing does, so a running round still stops cleanly. Python
# runs signal handlers between bytecodes: the timer gives it some while Qt waits.
def on_signal(*_):
engine.rootObjects()[0].setProperty("quitting", True)
app.quit()
signal.signal(signal.SIGTERM, on_signal)
signal.signal(signal.SIGINT, on_signal)
tick = QTimer(interval=500, timeout=lambda: None)
tick.start()
code = app.exec()
# The window goes before the backend (as the hand recorder: bindings would run against it).
shiboken6.delete(engine)
sys.exit(code)
if __name__ == "__main__":
main()
+276
View File
@@ -0,0 +1,276 @@
#!/usr/bin/env python3
"""Upload an eye recorder export to the eye dataset on Hugging Face.
As the hand recorder's hub.py (the shared part is recorder/hub.py): the window runs it as a child
process, it uses huggingface_hub's saved login (`hub.py login` is the browser's device code), and
nobody types a token anywhere. An upload:
1. checks the export with validate.py (against recipients.txt's keys), and stops on errors;
2. stops if this export (same SHA256SUMS) was uploaded before, unless --again;
3. stops unless CONSENT.md and UPLOAD.md are here and neither is a draft. FT_EYEREC_ALLOW_UPLOAD=1
opens it for a rehearsal, and only to another dataset than the real one (FT_EYEREC_DATASET):
the real one takes nothing before the texts are reviewed;
4. checks the login and access to the dataset, opens the pull request first, uploads the folder
to contributions/<contributor>/<round> in it, and records it under "uploads" in session.json.
--dry-run does all of it except the network calls and the records, and says what it would upload.
The images and health answers are encrypted already (takes.py's export): nothing here can read
them, and the dataset's readers need one of its keys.
`hub.py board` fetches the bounty board (bounties.json) from the dataset into BASE/board-cache.json,
with the saved login when there is one (the dataset is gated): the window's board then uses it
when it's newer than the one shipped here (recorder/bounties.py checks what it may say).
usage: hub.py [--base DIR] whoami [--json]
hub.py [--base DIR] login [--json]
hub.py [--base DIR] board [--json]
hub.py [--base DIR] upload ROUND [--dry-run] [--again] [--json]
With --json, each line of output is one JSON object, as the hand recorder's hub.py.
"""
import argparse
import json
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
sys.path.insert(0, os.path.dirname(os.path.dirname(HERE)))
import takes # noqa: E402 (next to this file)
from recorder import bounties # noqa: E402
from recorder import hub as rhub # noqa: E402
from recorder.common import write_json # noqa: E402
from recorder.hub import HubError, export_sha, is_draft, now_iso # noqa: E402,F401
HF_DATASET = "DeeJanuz/frametop-eyes"
DATASET_ENV = "FT_EYEREC_DATASET"
ALLOW_ENV = "FT_EYEREC_ALLOW_UPLOAD"
CONSENT_PATH = os.path.join(HERE, "CONSENT.md")
UPLOAD_PATH = os.path.join(HERE, "UPLOAD.md")
def dataset_id():
"""HF_DATASET, or FT_EYEREC_DATASET when set."""
return rhub.dataset_id(DATASET_ENV, HF_DATASET)
def texts_ready():
return all(os.path.isfile(p) and not is_draft(p) for p in (CONSENT_PATH, UPLOAD_PATH))
def upload_allowed(repo):
"""Real uploads: once the texts are reviewed, or for a rehearsal against another dataset."""
return texts_ready() or (os.environ.get(ALLOW_ENV) == "1" and repo != HF_DATASET)
def meta_path(store, rnd):
return os.path.join(store.round_dir(rnd), "session.json")
def describe(summary, report, sha, nbytes):
"""(commit message, commit description) from validate's summary of the manifest."""
s = summary
message = f"Eyes: {s.get('bounty')} round {s.get('round')} from {s.get('contributor')}"
lines = ["Contribution to the Frametop eye dataset, uploaded from the eye recorder. The eye images "
"and any health answers are encrypted to the dataset's keys.", "",
f"- Round: {s.get('round')}",
f"- Bounty: {s.get('bounty')}",
f"- Contributor: {s.get('contributor')}",
f"- Takes: {s.get('takes')} ({s.get('minutes')} minutes, {s.get('frames')} frames)",
f"- Glasses: {s.get('glasses') or 'not given'}",
f"- Health answers: {'included, encrypted' if s.get('health') else 'none'}",
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 gaze/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"
def _hf():
return rhub.hf_module("run setup/dev-container.sh (or: pip install --user huggingface_hub)")
def whoami():
return rhub.whoami(_hf(), dataset_id())
def login(progress=None):
_hf()
return rhub.login(dataset_id(), progress, lambda: whoami(), "update the dev container (setup/dev-container.sh).")
def board_url(repo):
return f"{rhub.dataset_url(repo)}/resolve/main/bounties.json"
def fetch_board(base):
"""The dataset's bounties.json into base/board-cache.json (session.load_board reads it).
Returns {"updated", "bounties"}; raises HubError."""
repo = dataset_id()
token = None
try:
token = _hf().get_token()
except (HubError, AttributeError):
pass # no huggingface_hub, or an old one: try without a login
try:
board = bounties.fetch(board_url(repo), os.path.join(base, "board-cache.json"), token)
except ValueError as e:
raise HubError("hub", f"The dataset's bounty board isn't valid: {e}") from None
except OSError as e:
status = getattr(e, "code", None)
if status in (401, 403):
raise HubError("terms", "Log in and accept the dataset's terms to get its newest bounty board.",
rhub.dataset_url(repo)) from None
if status == 404:
raise HubError("not-found", f"{repo} has no bounty board yet.") from None
raise HubError("network", f"Couldn't fetch the bounty board ({type(e).__name__}: {e}).") from None
return {"updated": board["updated"], "bounties": len(board["bounties"])}
def upload(store, rnd, dry_run=False, again=False, progress=None, log=None):
"""Upload exports/<round> (the steps in this file's docstring). 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(rnd)
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 round {rnd}: 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 round again; if that doesn't help, report it.", errors=report.errors)
summary = report.summary
sha = export_sha(export)
before = rhub.previous_upload(meta_path(store, rnd), 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(repo):
raise HubError("closed", "Eye contributions aren't open yet: the consent and upload texts are waiting for a "
f"legal review. (A rehearsal: {ALLOW_ENV}=1 with {DATASET_ENV} set to a test dataset.)")
path_in_repo = f"contributions/{summary.get('contributor', '')}/{rnd}"
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)
pr, who, record = rhub.push(_hf(), repo, export, path_in_repo, message, description, meta_path(store, rnd), sha,
len(files), report.bytes, tell, write_json, takes.human_bytes)
tell("done", "Uploaded", 1.0)
return dict(plan, dry_run=False, pr_url=record["pr_url"], pr_num=pr.num, user=who.get("name", ""), record=record)
def main():
ap = argparse.ArgumentParser(description="Upload an eye recorder export to the eye 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")
b = sub.add_parser("board", help="fetch the dataset's bounty board")
b.add_argument("--json", action="store_true")
u = sub.add_parser("upload", help="upload exports/ROUND as a pull request")
u.add_argument("round")
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 == "board":
got = fetch_board(os.path.abspath(os.path.expanduser(a.base)))
if a.json:
emit({"done": got})
else:
print(f"bounty board of {got['updated']}: {got['bounties']} bounties")
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.round, 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())
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env bash
# Install the eye recorder on a Frame that has Frametop (get.sh --experimental): bring the dev
# container's packages up to date, build the gaze tools the round uses (gaze/build.sh: ft-gaze and
# the headset panel ft-gazepanel; gaze/tracker/build.sh: our tracker ft-eyes, which the fit coach
# runs) and add "Frametop Eye Recorder" to the app menu (for Frametop's desktop, as the hand
# recorder's). It doesn't change Frametop's gaze setup; the window offers SteamVR's 90 fps eye
# cameras (gaze/eye-rate.py) when they're slower.
# Usage: gaze/rec/install.sh install or update
# gaze/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-eyerec.desktop'
case ${1:-install} in
install)
echo "== 1/3 dev container packages"
"$root/setup/dev-container.sh"
echo "== 2/3 the gaze tools: ft-gaze, ft-gazepanel and ft-eyes"
"$root/gaze/build.sh"
"$root/gaze/tracker/build.sh"
echo "== 3/3 the menu entry"
fill_template "$root/gaze/rec/ft-eyerec.desktop" |
on_frame "mkdir -p ~/.local/share/applications && cat > $entry"
echo
echo "Installed. On Frametop's desktop, open \"Frametop Eye Recorder\" from the app menu."
echo "Recordings go to ~/.local/share/frametop/eyes/contrib."
;;
uninstall)
on_frame "rm -f $entry"
echo "Removed the menu entry."
echo "Your recordings are still in ~/.local/share/frametop/eyes/contrib:"
echo "delete that folder to remove them."
;;
*) echo "usage: $0 [install|uninstall]" >&2; exit 2 ;;
esac
+1805
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -0,0 +1,4 @@
# The eye dataset's recipients (gaze/rec/DESIGN.md "Files"): exports encrypt each chunk and health.json
# to all of them (recorder/age.py). Key 1 is kept on the maintainer's training machine, key 2 offline.
age1a0tc98pj2s7gdfgrv4gam6ah0qv69ymf3t2cc25hcwepmats69hst35z2e
age1r0zlq7kcyg4dz4y3vkl9j36jw3zc6ly6reddh9ag5kfy6aw0fy6s5hepat
+233
View File
@@ -0,0 +1,233 @@
{
"schema": 1,
"id": "blinks",
"title": "Blinks and lids",
"intro": "Blinks, closed and half-closed eyes. Keep looking at the dot whenever your eyes are open.",
"steps": [
{
"id": "blink-cue",
"kind": "prompt",
"text": "Look at the dot and blink each time the word says so.",
"dot": [
0,
0
],
"cues": [
[
"Blink",
1.5
],
[
"Blink",
1.5
],
[
"Blink",
1.5
],
[
"Blink",
1.5
],
[
"Blink",
1.5
],
[
"Blink",
1.5
],
[
"Blink",
1.5
],
[
"Blink",
1.5
]
]
},
{
"id": "closed",
"kind": "prompt",
"text": "Look at the dot, then close both eyes when it says so.",
"dot": [
0,
0
],
"cues": [
[
"Look",
2
],
[
"Close both eyes",
2.5
],
[
"Open",
2
],
[
"Close both eyes",
2.5
],
[
"Open",
2
]
]
},
{
"id": "winks",
"kind": "prompt",
"text": "Wink each eye in turn when it says so (as well as you can).",
"dot": [
0,
0
],
"cues": [
[
"Look",
1.5
],
[
"Close your left eye",
2
],
[
"Open",
1.5
],
[
"Close your right eye",
2
],
[
"Open",
1.5
],
[
"Close your left eye",
2
],
[
"Open",
1.5
],
[
"Close your right eye",
2
],
[
"Open",
1.5
]
]
},
{
"id": "squint",
"kind": "prompt",
"text": "Keep looking at the dot while you change how open your eyes are.",
"dot": [
0,
0
],
"cues": [
[
"Normal",
2
],
[
"Squint",
3
],
[
"Normal",
2
],
[
"Eyes wide open",
3
],
[
"Normal",
2
],
[
"Half closed",
3
],
[
"Normal",
2
]
]
},
{
"id": "lids-down",
"kind": "dots",
"text": "Look down at each dot. Let your lids drop as they do when you look down.",
"dots": [
[
0,
-12
],
[
0,
-18
],
[
12,
-18
],
[
-12,
-18
],
[
0,
-23
],
[
18,
-20
],
[
-18,
-20
]
],
"hold": 1.5,
"shuffle": true
},
{
"id": "blink-dots",
"kind": "dots",
"text": "Look at each dot and blink once while its ring fills.",
"dots": [
[
0,
0
],
[
15,
10
],
[
-15,
10
],
[
15,
-10
],
[
-15,
-10
]
],
"hold": 2.0
}
]
}
+89
View File
@@ -0,0 +1,89 @@
{
"schema": 1,
"id": "depth",
"title": "Depth",
"intro": "Dots near and far. The panel moves closer and further away; keep the dot sharp.",
"steps": [
{
"id": "near",
"kind": "dots",
"text": "The panel is close now. Look at each dot until its ring fills. Keep your head still.",
"grid": [
3,
3,
15,
15
],
"hold": 1.5,
"shuffle": true,
"distance": 0.5
},
{
"id": "mid",
"kind": "dots",
"text": "The panel is at arm's length and a bit. Look at each dot until its ring fills. Keep your head still.",
"grid": [
3,
3,
15,
15
],
"hold": 1.5,
"shuffle": true,
"distance": 1.5
},
{
"id": "far",
"kind": "dots",
"text": "The panel is far now. Look at each dot until its ring fills. Keep your head still.",
"grid": [
3,
3,
15,
15
],
"hold": 1.5,
"shuffle": true,
"distance": 5.0
},
{
"id": "near-far",
"kind": "prompt",
"text": "Keep looking at the dot as it comes near and goes far.",
"dot": [
0,
0
],
"cues": [
[
"Far",
2.5
],
[
"Near",
2.5
],
[
"Far",
2.5
],
[
"Near",
2.5
],
[
"Far",
2.5
],
[
"Near",
2.5
]
],
"cue_distance": {
"Far": 5.0,
"Near": 0.5
}
}
]
}
+129
View File
@@ -0,0 +1,129 @@
{
"schema": 1,
"id": "edges",
"title": "View edges",
"intro": "Dots out at the edges of the panel and in its corners: turn only your eyes to them, as far as is comfortable.",
"steps": [
{
"id": "edges",
"kind": "dots",
"text": "Look at each dot until its ring fills. Keep your head still.|Some are far out: turn your eyes, not your head.",
"dots": [
[
24,
0
],
[
-24,
0
],
[
30,
0
],
[
-30,
0
],
[
0,
18
],
[
0,
-18
],
[
0,
23
],
[
0,
-23
],
[
30,
20
],
[
-30,
20
],
[
30,
-20
],
[
-30,
-20
],
[
22,
16
],
[
-22,
16
],
[
22,
-16
],
[
-22,
-16
]
],
"hold": 1.2,
"shuffle": true
},
{
"id": "edges-sweep",
"kind": "path",
"text": "Follow the dot with your eyes as it goes round, far out.",
"path": "circle 0 0 22 8",
"seconds": 16
},
{
"id": "edges-again",
"kind": "dots",
"text": "Look at each dot until its ring fills. Keep your head still.",
"dots": [
[
30,
0
],
[
-30,
0
],
[
0,
23
],
[
0,
-23
],
[
30,
20
],
[
-30,
20
],
[
30,
-20
],
[
-30,
-20
]
],
"hold": 1.2,
"shuffle": true
}
]
}
+81
View File
@@ -0,0 +1,81 @@
{
"schema": 1,
"id": "face",
"title": "Face moves",
"intro": "Faces move the headset and the lids. Keep looking at the dot while you make each face. The microphone isn't recorded.",
"steps": [
{
"id": "faces",
"kind": "prompt",
"text": "Keep looking at the dot and do what it says.",
"dot": [
0,
0
],
"cues": [
[
"Smile",
3
],
[
"Relax",
2
],
[
"Raise your eyebrows",
3
],
[
"Relax",
2
],
[
"Frown",
3
],
[
"Relax",
2
],
[
"Yawn (or pretend to)",
4
],
[
"Relax",
2
],
[
"Chew",
4
],
[
"Relax",
2
]
]
},
{
"id": "talk",
"kind": "prompt",
"text": "Read this aloud while looking at the dot as much as you can:|\"The quick brown fox jumps over the lazy dog, then naps in the warm afternoon sun.\"",
"dot": [
0,
10
],
"seconds": 10
},
{
"id": "faces-dots",
"kind": "dots",
"text": "Smile and keep smiling. Look at each dot until its ring fills. Keep your head still.",
"grid": [
3,
3,
15,
15
],
"hold": 1.0
}
]
}
+69
View File
@@ -0,0 +1,69 @@
{
"schema": 1,
"id": "glasses",
"title": "Glasses",
"intro": "With your glasses or inserts on. Wear them as you usually do in the headset.",
"steps": [
{
"id": "grid",
"kind": "dots",
"text": "Look at each dot until its ring fills. Keep your head still.",
"grid": [
5,
5,
24,
18
],
"hold": 1.2,
"shuffle": true
},
{
"id": "edges",
"kind": "dots",
"text": "Look at each dot until its ring fills. Keep your head still.|Some are far out: turn your eyes, not your head.",
"dots": [
[
30,
0
],
[
-30,
0
],
[
0,
23
],
[
0,
-23
],
[
30,
20
],
[
-30,
20
],
[
30,
-20
],
[
-30,
-20
]
],
"hold": 1.2,
"shuffle": true
},
{
"id": "follow",
"kind": "path",
"text": "Follow the dot with your eyes.",
"path": "eight 0 0 22 14 6",
"seconds": 12
}
]
}
+68
View File
@@ -0,0 +1,68 @@
{
"schema": 1,
"id": "head",
"title": "Head turning",
"intro": "A dot that stays put in the room while you turn your head. Keep your eyes on it.",
"steps": [
{
"id": "turn-sides",
"kind": "world",
"group": "head",
"text": "Keep looking at the dot. Turn your head slowly left and right.",
"point": [
0,
0,
-1.5
],
"seconds": 15
},
{
"id": "turn-updown",
"kind": "world",
"group": "head",
"text": "Keep looking at the dot. Nod slowly up and down.",
"point": [
0,
0,
-1.5
],
"seconds": 12
},
{
"id": "tilt",
"kind": "world",
"group": "head",
"text": "Keep looking at the dot. Tilt your head side to side.",
"point": [
0,
0,
-1.5
],
"seconds": 10
},
{
"id": "shake",
"kind": "world",
"group": "head",
"text": "Keep looking at the dot. Shake your head a little, quickly.",
"point": [
0,
0,
-1.5
],
"seconds": 8
},
{
"id": "walk",
"kind": "world",
"group": "head",
"text": "If you have room: take a step to each side while looking at the dot.",
"point": [
0,
0,
-2.0
],
"seconds": 12
}
]
}
+78
View File
@@ -0,0 +1,78 @@
{
"schema": 1,
"id": "jumps",
"title": "Jumps and pursuit",
"intro": "A dot that jumps around, then one that glides. Follow it with your eyes, as quickly as you can, without moving your head.",
"steps": [
{
"id": "jumps",
"kind": "jumps",
"text": "Look at the dot wherever it jumps.",
"count": 40,
"range": [
24,
18
],
"each": [
0.5,
1.5
]
},
{
"id": "circle-slow",
"kind": "path",
"group": "pursuit",
"text": "Follow the dot with your eyes.",
"path": "circle 0 0 15 6",
"seconds": 12
},
{
"id": "circle-fast",
"kind": "path",
"group": "pursuit",
"text": "Follow the dot with your eyes. It's faster now.",
"path": "circle 0 0 15 2.5",
"seconds": 10
},
{
"id": "line-slow",
"kind": "path",
"group": "pursuit",
"text": "Follow the dot from side to side.",
"path": "line -24 0 24 0 3",
"seconds": 12
},
{
"id": "line-fast",
"kind": "path",
"group": "pursuit",
"text": "Follow the dot from side to side, faster.",
"path": "line -24 0 24 0 1.2",
"seconds": 8
},
{
"id": "line-up",
"kind": "path",
"group": "pursuit",
"text": "Follow the dot up and down.",
"path": "line 0 -18 0 18 2.5",
"seconds": 10
},
{
"id": "eight",
"kind": "path",
"group": "pursuit",
"text": "Follow the dot along the figure eight.",
"path": "eight 0 0 22 12 6",
"seconds": 12
},
{
"id": "eight-fast",
"kind": "path",
"group": "pursuit",
"text": "Follow the dot along the figure eight, faster.",
"path": "eight 0 0 22 12 3",
"seconds": 9
}
]
}
+89
View File
@@ -0,0 +1,89 @@
{
"schema": 1,
"id": "light",
"title": "Light changes",
"intro": "The panel goes dark and bright. Your pupils change size with it: that's what this records.",
"steps": [
{
"id": "steps",
"kind": "light",
"text": "Keep looking at the dot while the light changes.",
"dot": [
0,
0
],
"levels": [
[
0.03,
4
],
[
0.9,
4
],
[
0.03,
4
],
[
0.33,
4
],
[
0.9,
4
],
[
0.33,
4
],
[
0.03,
4
]
]
},
{
"id": "grid-dark",
"kind": "dots",
"text": "Look at each dot until its ring fills. Keep your head still.",
"grid": [
5,
5,
24,
18
],
"hold": 1.0,
"shuffle": true,
"bg": 0.03
},
{
"id": "grid-mid",
"kind": "dots",
"text": "Look at each dot until its ring fills. Keep your head still.",
"grid": [
5,
5,
24,
18
],
"hold": 1.0,
"shuffle": true,
"bg": 0.33
},
{
"id": "grid-bright",
"kind": "dots",
"text": "Look at each dot until its ring fills. Keep your head still.",
"grid": [
5,
5,
24,
18
],
"hold": 1.0,
"shuffle": true,
"bg": 0.9
}
]
}
+31
View File
@@ -0,0 +1,31 @@
{
"schema": 1,
"id": "reading",
"title": "Reading",
"intro": "Reading and looking around, as in everyday use.",
"steps": [
{
"id": "read-1",
"kind": "prompt",
"group": "reading",
"dot": null,
"seconds": 20,
"text": "Read this at your own pace.||The lighthouse keeper climbed the spiral stairs every evening, counting each of the one hundred and twelve steps. At the top, he polished the great lens until it shone, then lit the lamp and watched its beam sweep across the dark water. Ships far out at sea would see the flash and know where the rocks were."
},
{
"id": "read-2",
"kind": "prompt",
"group": "reading",
"dot": null,
"seconds": 20,
"text": "And this one.||In the morning the market filled with stalls of oranges, peppers and fresh bread. A boy on a bicycle wove between the crates, ringing his bell. Somewhere a radio played an old song, and an old woman hummed along while she weighed out a bag of cherries for a customer who couldn't decide."
},
{
"id": "free",
"kind": "prompt",
"dot": null,
"seconds": 15,
"text": "Look around the panel freely: the corners, the edges, wherever you like."
}
]
}
+231
View File
@@ -0,0 +1,231 @@
{
"schema": 1,
"id": "slips",
"title": "Headset slips",
"intro": "You'll nudge the headset on your face on purpose, then put it back. Use one hand, gently: a few millimetres is enough.",
"steps": [
{
"id": "nudge-up",
"kind": "prompt",
"group": "nudges",
"text": "Keep looking at the dot and push the headset up a little. Hold it there.",
"dot": [
0,
0
],
"seconds": 5
},
{
"id": "after-up",
"kind": "dots",
"group": "nudges",
"ready": false,
"text": "Hold the headset there. Look at each dot until its ring fills. Keep your head still.",
"dots": [
[
0,
0
],
[
15,
12
],
[
-15,
-12
],
[
15,
-12
],
[
-15,
12
]
],
"hold": 1.0
},
{
"id": "nudge-down",
"kind": "prompt",
"group": "nudges",
"text": "Let go, then pull the headset down a little. Hold it there.",
"dot": [
0,
0
],
"seconds": 5
},
{
"id": "after-down",
"kind": "dots",
"group": "nudges",
"ready": false,
"text": "Hold it there. Look at each dot until its ring fills. Keep your head still.",
"dots": [
[
0,
0
],
[
15,
12
],
[
-15,
-12
],
[
15,
-12
],
[
-15,
12
]
],
"hold": 1.0
},
{
"id": "nudge-left",
"kind": "prompt",
"group": "nudges",
"text": "Let go, then slide the headset a little to your left.",
"dot": [
0,
0
],
"seconds": 5
},
{
"id": "after-left",
"kind": "dots",
"group": "nudges",
"ready": false,
"text": "Hold it there. Look at each dot until its ring fills. Keep your head still.",
"dots": [
[
0,
0
],
[
15,
12
],
[
-15,
-12
],
[
15,
-12
],
[
-15,
12
]
],
"hold": 1.0
},
{
"id": "nudge-right",
"kind": "prompt",
"group": "nudges",
"text": "Let go, then slide it a little to your right.",
"dot": [
0,
0
],
"seconds": 5
},
{
"id": "after-right",
"kind": "dots",
"group": "nudges",
"ready": false,
"text": "Hold it there. Look at each dot until its ring fills. Keep your head still.",
"dots": [
[
0,
0
],
[
15,
12
],
[
-15,
-12
],
[
15,
-12
],
[
-15,
12
]
],
"hold": 1.0
},
{
"id": "nudge-tilt",
"kind": "prompt",
"group": "nudges",
"text": "Let go, then tilt the headset a little: one side up.",
"dot": [
0,
0
],
"seconds": 5
},
{
"id": "after-tilt",
"kind": "dots",
"group": "nudges",
"ready": false,
"text": "Hold it there. Look at each dot until its ring fills. Keep your head still.",
"dots": [
[
0,
0
],
[
15,
12
],
[
-15,
-12
],
[
15,
-12
],
[
-15,
12
]
],
"hold": 1.0
},
{
"id": "reseat",
"kind": "reseat",
"text": "Take the headset off, put it back on as you usually do, then press the button."
},
{
"id": "after-reseat",
"kind": "dots",
"text": "Look at each dot until its ring fills. Keep your head still.",
"grid": [
3,
3,
20,
20
],
"hold": 1.2,
"shuffle": true
}
]
}
+1572
View File
File diff suppressed because it is too large. Load diff
+479
View File
@@ -0,0 +1,479 @@
#!/usr/bin/env python3
"""The eye recorder's rounds and takes on disk: listing, review, deleting, and the encrypted export.
The layout is DESIGN.md's "Files":
BASE/profile.json
BASE/rounds/<YYYYMMDD-HHMMSS>-<bounty>/session.json, fit.json, health.json, session.log
BASE/rounds/<round>/takes/<NN>-<group>/cam0/*.zst, cam1/*.zst, index.tsv (eyerec.py),
targets.jsonl, poses.jsonl, ipd.jsonl, own.jsonl, steamvr.jsonl, prompts.jsonl, take.json
BASE/exports/<round>/
Deleted ranges live in take.json ("deleted": [[from_ns, to_ns], ...]) on CLOCK_MONOTONIC, the
clock of prompts.jsonl, which the window's timeline shows. The frames and the other logs are on
CLOCK_MONOTONIC_RAW seconds; take.json's clock samples ([mono_ns, raw - mono ns]) turn one into
the other. The files keep every frame until export leaves the deleted ones out.
The export (exports/<round>/, built in <round>.partial and moved when it's whole):
manifest.json the round, its profile and session, the recipients, each take
fit.json the fit coach's readings, as recorded
health.json.age the opt-in health answers, encrypted (when there are any)
takes/<id>/take.json as recorded, plus "export": the deleted ranges in RAW seconds
takes/<id>/index.tsv the kept frames; a chunk keeps its number, frames renumbered in it
takes/<id>/cam0/NNNNNN.zst.age ... each chunk encrypted to every recipient (recorder/age.py)
takes/<id>/targets.jsonl, ipd.jsonl, prompts.jsonl whole: they say what was shown and asked
takes/<id>/own.jsonl, steamvr.jsonl, poses.jsonl rows in deleted ranges left out
SHA256SUMS over every file above, the encrypted ones as they are
A chunk none of whose frames are deleted is encrypted as it is; one with some deleted frames is
decompressed, the rest compressed again (zstd 1, as eyerec.py) and encrypted; one with none left
is dropped. Every chunk is decompressed once to check it holds the frames index.tsv says; a
chunk that doesn't, or one index.tsv doesn't name (the recorder was killed before the index
line), is left out and counted in the manifest. session.log isn't exported (it names paths).
Needs the cryptography library to export (recorder/age.py). The rest is standard library.
usage: takes.py [--base DIR] list | takes ROUND | export ROUND
takes.py unpack EXPORT --identity KEYFILE --out DIR decrypt an export (the dataset's side)
"""
import argparse
import datetime
import json
import os
import re
import shutil
import subprocess
import sys
import threading
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(os.path.dirname(HERE))
sys.path.insert(0, REPO)
sys.path.insert(0, HERE)
import eyerec # noqa: E402 (gaze/rec/eyerec.py: the chunks' format)
from recorder import age # noqa: E402
from recorder.common import write_json # noqa: E402
from recorder.files import (Cancelled, human_bytes, in_ranges, merge_ranges, read_json, sha256_file, # noqa: E402,F401
tree_bytes, tree_stat, write_sums)
DEFAULT_BASE = os.path.expanduser("~/.local/share/frametop/eyes/contrib")
RECIPIENTS = os.path.join(HERE, "recipients.txt")
ROUND_RE = re.compile(r"^\d{8}-\d{6}-[a-z0-9][a-z0-9-]{0,39}$") # session.py: <time>-<bounty>[-N]
TAKE_RE = re.compile(r"^\d{2,}-[a-z0-9][a-z0-9_-]{0,63}$")
CHUNK_RE = re.compile(r"^(\d{6})\.zst$")
EXPORT_SCHEMA = 1
WHOLE_LOGS = ("targets.jsonl", "ipd.jsonl", "prompts.jsonl")
CUT_LOGS = ("own.jsonl", "steamvr.jsonl", "poses.jsonl") # "t" in RAW seconds
GAP_S = 0.5 # frames further apart than this are a pause, not recorded time
def tool_version():
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-eyerec " + (described or "unknown")
# ---------------------------------------------------------------- clocks
def raw_offset_ns(t_ns, clock):
"""RAW - MONOTONIC at t_ns (MONOTONIC), from take.json's clock samples: linear between the
two around it, the nearest outside them, 0 without any."""
pts = sorted((int(m), int(d)) for m, d in clock or [] if isinstance(m, (int, float)) and isinstance(d, (int, float)))
if not pts:
return 0
if t_ns <= pts[0][0]:
return pts[0][1]
for (m0, d0), (m1, d1) in zip(pts, pts[1:]):
if t_ns <= m1:
return d0 + (d1 - d0) * (t_ns - m0) // max(1, m1 - m0)
return pts[-1][1]
def raw_ranges(ranges, clock):
"""Deleted ranges (MONOTONIC ns) as [[from, to], ...] in RAW seconds."""
return [[(a + raw_offset_ns(a, clock)) / 1e9, (b + raw_offset_ns(b, clock)) / 1e9] for a, b in merge_ranges(ranges)]
def recorded_seconds(times):
"""Time spent recording: the gaps under GAP_S between sorted frame times."""
total = 0.0
for a, b in zip(times, times[1:]):
if b - a < GAP_S:
total += b - a
return total
def cut_jsonl(src, dst, ranges):
"""Copy a jsonl log, leaving out rows whose "t" (RAW seconds) is in ranges. Lines that don't
parse are copied as they are (validate.py reports them)."""
kept = cut = 0
with open(src, encoding="utf-8", errors="replace") as f, open(dst, "w", encoding="utf-8", newline="\n") as out:
for line in f:
if not line.strip():
continue
try:
t = json.loads(line).get("t")
except (ValueError, AttributeError):
t = None
if isinstance(t, (int, float)) and in_ranges(t, ranges):
cut += 1
continue
out.write(line if line.endswith("\n") else line + "\n")
kept += 1
return kept, cut
# ---------------------------------------------------------------- the store
class Store:
def __init__(self, base=DEFAULT_BASE):
self.base = os.path.abspath(os.path.expanduser(base))
self.rounds_dir = os.path.join(self.base, "rounds")
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 round_dir(self, rnd):
if not ROUND_RE.match(rnd or ""):
raise ValueError(f"not a round id: {rnd!r}")
return os.path.join(self.rounds_dir, rnd)
def take_dir(self, rnd, take):
if not TAKE_RE.match(take or ""):
raise ValueError(f"not a take id: {take!r}")
return os.path.join(self.round_dir(rnd), "takes", take)
def export_dir(self, rnd):
self.round_dir(rnd) # checks the id
return os.path.join(self.exports_dir, rnd)
def profile(self):
return read_json(self.profile_path)
# --- listing
def rounds(self):
"""Newest first: [{id, bounty, title, started, status, dry_run, takes, bytes, exported,
export_stale (changed since), export_bytes}]."""
out = []
try:
names = os.listdir(self.rounds_dir)
except OSError:
return out
for rid in names:
path = os.path.join(self.rounds_dir, rid)
if not ROUND_RE.match(rid) 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(rid), "manifest.json")
exported = os.path.getmtime(manifest) if os.path.isfile(manifest) else 0.0
out.append({"id": rid, "bounty": meta.get("bounty", ""), "title": meta.get("title", ""),
"started": meta.get("started", ""), "status": meta.get("status", ""),
"dry_run": bool(meta.get("dry_run")), "takes": len(self.take_ids(rid)), "bytes": size,
"exported": bool(exported), "export_stale": bool(exported) and changed > exported,
"export_bytes": tree_bytes(self.export_dir(rid)) if exported else 0})
return sorted(out, key=lambda r: r["id"], reverse=True)
def take_ids(self, rnd):
d = os.path.join(self.round_dir(rnd), "takes")
try:
names = os.listdir(d)
except OSError:
return []
return sorted(n for n in names if TAKE_RE.match(n) and os.path.isdir(os.path.join(d, n)))
def takes(self, rnd):
"""[{id, group, status, frames: [right, left], deleted_frames: [..], ranges, duration_s,
bytes, started_ns, ended_ns}]."""
out = []
for tid in self.take_ids(rnd):
path = self.take_dir(rnd, tid)
meta = read_json(os.path.join(path, "take.json"))
ranges = merge_ranges(meta.get("deleted") or [])
raw = raw_ranges(ranges, meta.get("clock"))
times = {c: [] for c in eyerec.CAMERAS}
for c, _chunk, _i, _slot, t in eyerec.read_index(path):
if c in times:
times[c].append(t)
for c in times:
times[c].sort()
out.append({"id": tid, "group": meta.get("group", tid.split("-", 1)[-1]),
"status": meta.get("status", "recording"),
"frames": [len(times[c]) for c in eyerec.CAMERAS],
"deleted_frames": [sum(1 for t in times[c] if in_ranges(t, raw)) for c in eyerec.CAMERAS],
"ranges": ranges, "duration_s": max(recorded_seconds(times[c]) for c in eyerec.CAMERAS),
"bytes": sum(tree_bytes(os.path.join(path, "cam%d" % c)) for c in eyerec.CAMERAS),
"started_ns": meta.get("started_ns"), "ended_ns": meta.get("ended_ns")})
return out
def take_meta(self, rnd, take):
return read_json(os.path.join(self.take_dir(rnd, take), "take.json"))
# --- deleted ranges
def ranges(self, rnd, take):
return merge_ranges(self.take_meta(rnd, take).get("deleted") or [])
def _set_ranges(self, rnd, take, ranges):
path = os.path.join(self.take_dir(rnd, take), "take.json")
meta = read_json(path)
if not meta:
raise RuntimeError(f"no take {rnd}/{take}")
meta["deleted"] = merge_ranges(ranges)
write_json(path, meta)
return meta["deleted"]
def delete_range(self, rnd, take, from_ns, to_ns):
"""Leave the frames from from_ns to to_ns (CLOCK_MONOTONIC, inclusive) out of the export."""
return self._set_ranges(rnd, take, self.ranges(rnd, take) + [[int(from_ns), int(to_ns)]])
def restore_range(self, rnd, take, i):
"""Take deleted range i (in ranges()' order) back."""
ranges = self.ranges(rnd, take)
if 0 <= i < len(ranges):
del ranges[i]
return self._set_ranges(rnd, take, ranges)
# --- deleting files
def delete_take(self, rnd, take):
path = self.take_dir(rnd, take)
if os.path.isdir(path):
shutil.rmtree(path)
meta_path = os.path.join(self.round_dir(rnd), "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_round(self, rnd):
"""The round and its export, if any."""
for path in (self.round_dir(rnd), self.export_dir(rnd)):
if os.path.isdir(path):
shutil.rmtree(path)
def delete_export(self, rnd):
path = self.export_dir(rnd)
if os.path.isdir(path):
shutil.rmtree(path)
# --- export
def export(self, rnd, progress=None, cancel=None, keep_notes=False, low_priority=True, recipients=None):
"""Write exports/<round>/ (the module's docstring). 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.
recipients: "age1..." keys, default recipients.txt's. low_priority: run this thread at
nice 19 (Linux nice is per thread)."""
recipients = list(recipients) if recipients else age.read_recipients(RECIPIENTS)
age._crypto() # fails now, not half way, without the cryptography library
cancelled = getattr(cancel, "is_set", cancel) or (lambda: False)
report = progress or (lambda fraction, text: None)
src = self.round_dir(rnd)
if not os.path.isdir(src):
raise RuntimeError(f"no round {rnd}")
if low_priority:
try:
os.setpriority(os.PRIO_PROCESS, threading.get_native_id(), 19)
except OSError:
pass
final = self.export_dir(rnd)
work = final + ".partial"
if os.path.isdir(work):
shutil.rmtree(work)
os.makedirs(work)
try:
self._export(rnd, src, work, recipients, 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, rnd, src, work, recipients, 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(rnd)
total = sum(t["bytes"] for t in takes) or 1
done = 0
entries = []
for t in takes:
if cancelled():
raise Cancelled()
tdir = self.take_dir(rnd, t["id"])
out = os.path.join(work, "takes", t["id"])
os.makedirs(out)
take_meta = read_json(os.path.join(tdir, "take.json"))
raw = raw_ranges(t["ranges"], take_meta.get("clock"))
logs = {}
for name in WHOLE_LOGS:
if os.path.isfile(os.path.join(tdir, name)):
shutil.copyfile(os.path.join(tdir, name), os.path.join(out, name))
for name in CUT_LOGS:
if os.path.isfile(os.path.join(tdir, name)):
kept, cut = cut_jsonl(os.path.join(tdir, name), os.path.join(out, name), raw)
logs[name] = {"rows": kept, "deleted": cut}
def step(nbytes, title=t["id"]):
nonlocal done
done += nbytes
report(min(done / total, 0.99), f"Encrypting {title}")
chunks = self._chunks(tdir, out, raw, recipients, step, cancelled)
if take_meta:
take_meta["export"] = {"deleted_raw_s": raw}
write_json(os.path.join(out, "take.json"), take_meta)
entries.append({"id": t["id"], "group": t["group"], "status": t["status"],
"frames": chunks["frames"], "frames_deleted": chunks["deleted"],
"duration_s": round(t["duration_s"], 2), "chunks": chunks["chunks"],
"raw_bytes": chunks["raw_bytes"], "left_out": chunks["left_out"], "logs": logs})
if cancelled():
raise Cancelled()
if os.path.isfile(os.path.join(src, "fit.json")):
shutil.copyfile(os.path.join(src, "fit.json"), os.path.join(work, "fit.json"))
health = os.path.join(src, "health.json")
if os.path.isfile(health):
age.encrypt_file(health, os.path.join(work, "health.json.age"), recipients)
shown = json.loads(json.dumps(profile))
shown.pop("health", None) # only ever encrypted, in health.json.age
if not keep_notes and isinstance(shown.get("optional"), dict):
shown["optional"].pop("notes", None)
manifest = {"schema": EXPORT_SCHEMA, "tool": tool_version(),
"exported": datetime.datetime.now().astimezone().isoformat(timespec="seconds"),
"round_id": rnd, "bounty": meta.get("bounty", ""),
"contributor": profile.get("contributor", ""),
"consent_version": (profile.get("consent") or {}).get("version", ""),
"encryption": {"format": "age-encryption.org/v1", "recipients": recipients,
"files": ["takes/*/cam*/*.zst.age"] + (["health.json.age"] if os.path.isfile(health) else [])},
"frame": {"width": eyerec.W, "height": eyerec.H, "format": "u8 grey",
"cameras": {"0": "right eye", "1": "left eye"}},
"profile": shown, "session": meta, "takes": entries}
write_json(os.path.join(work, "manifest.json"), manifest)
report(0.995, "Writing checksums")
write_sums(work, cancelled)
@staticmethod
def _chunks(tdir, out, ranges, recipients, step, cancelled):
"""Each camera's chunks into out/camN/*.zst.age and the kept frames into out/index.tsv."""
rows = {}
for c, chunk, i, slot, t in eyerec.read_index(tdir):
rows.setdefault((c, chunk), []).append((i, slot, t))
on_disk = set()
for c in eyerec.CAMERAS:
try:
names = os.listdir(os.path.join(tdir, "cam%d" % c))
except OSError:
continue
on_disk.update((c, int(m.group(1))) for m in map(CHUNK_RE.match, names) if m)
res = {"frames": [0] * len(eyerec.CAMERAS), "deleted": [0] * len(eyerec.CAMERAS), "chunks": 0,
"raw_bytes": 0, "left_out": {"not_indexed": 0, "missing": 0, "bad": 0}}
res["left_out"]["not_indexed"] = len(on_disk - set(rows))
lines = [eyerec.INDEX_HEADER]
for c, chunk in sorted(rows):
if cancelled():
raise Cancelled()
frames = sorted(rows[(c, chunk)])
if c not in eyerec.CAMERAS:
continue
if (c, chunk) not in on_disk:
res["left_out"]["missing"] += 1
continue
path = os.path.join(tdir, "cam%d" % c, "%06d.zst" % chunk)
with open(path, "rb") as f:
packed = f.read()
step(len(packed))
try:
data = eyerec.decompress(packed)
except Exception:
data = b""
if len(data) != len(frames) * eyerec.FRAME or [i for i, _, _ in frames] != list(range(len(frames))):
res["left_out"]["bad"] += 1
continue
kept = [(i, slot, t) for i, slot, t in frames if not in_ranges(t, ranges)]
res["deleted"][c] += len(frames) - len(kept)
if not kept:
continue
if len(kept) < len(frames):
packed = eyerec.compress(b"".join(data[i * eyerec.FRAME:(i + 1) * eyerec.FRAME] for i, _, _ in kept))
os.makedirs(os.path.join(out, "cam%d" % c), exist_ok=True)
with open(os.path.join(out, "cam%d" % c, "%06d.zst.age" % chunk), "wb") as f:
f.write(age.encrypt_bytes(packed, recipients))
lines.extend("%d\t%d\t%d\t%d\t%.6f\n" % (c, chunk, k, slot, t) for k, (_, slot, t) in enumerate(kept))
res["frames"][c] += len(kept)
res["chunks"] += 1
res["raw_bytes"] += len(kept) * eyerec.FRAME
with open(os.path.join(out, "index.tsv"), "w") as f:
f.writelines(lines)
return res
# ---------------------------------------------------------------- the dataset's side
def read_identity(path):
with open(path) as f:
for line in f:
if line.strip().startswith("AGE-SECRET-KEY-1"):
return line.strip()
raise ValueError(f"{path} has no age identity")
def unpack(export, identity_path, dest, progress=None):
"""Check an export's SHA256SUMS, then copy it to dest with every .age file decrypted (its
name without .age). The output is a take folder eyerec.py can read. Returns dest."""
identity = read_identity(identity_path)
report = progress or (lambda fraction, text: None)
sums = {}
with open(os.path.join(export, "SHA256SUMS")) as f:
for line in f:
digest, rel = line.rstrip("\n").split(" ", 1)
if rel.startswith("/") or ".." in rel.split("/"):
raise ValueError(f"SHA256SUMS names {rel!r}")
sums[rel] = digest
for k, (rel, digest) in enumerate(sorted(sums.items())):
src = os.path.join(export, rel)
if sha256_file(src) != digest:
raise ValueError(f"{rel}: checksum doesn't match")
out = os.path.join(dest, rel[:-4] if rel.endswith(".age") else rel)
os.makedirs(os.path.dirname(out), exist_ok=True)
if rel.endswith(".age"):
age.decrypt_file(src, out, identity)
else:
shutil.copyfile(src, out)
report((k + 1) / len(sums), rel)
return dest
def main():
ap = argparse.ArgumentParser(description="List, export and unpack eye recorder rounds.")
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("round")
sub.add_parser("export").add_argument("round")
up = sub.add_parser("unpack", help="check and decrypt an export (needs one of the dataset's keys)")
up.add_argument("export")
up.add_argument("--identity", required=True, help="an age identity file")
up.add_argument("--out", required=True)
a = ap.parse_args()
store = Store(a.base)
if a.cmd == "list":
for r in store.rounds():
print(f"{r['id']} {r['status'] or '-'} {r['takes']} takes {human_bytes(r['bytes'])}"
+ (" dry run" if r["dry_run"] else "") + (" exported" if r["exported"] else ""))
elif a.cmd == "takes":
for t in store.takes(a.round):
print(f"{t['id']} {t['status']} frames {t['frames']} ({t['deleted_frames']} deleted) "
f"{t['duration_s']:.1f} s {human_bytes(t['bytes'])}")
elif a.cmd == "unpack":
print(unpack(a.export, a.identity, a.out))
else:
path = store.export(a.round, 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()
+253
View File
@@ -0,0 +1,253 @@
#!/usr/bin/env python3
"""The eye recorder's frame writer (gaze/rec/eyerec.py) against a made-up share, laid out as
ft-eyegrab's (gaze/tracker/eyes_share.py). No eye images: each frame is one byte value
repeated, from its camera and number, so the round trip can be checked.
python3 gaze/rec/tests/test_eyerec.py
"""
import mmap
import os
import shutil
import struct
import sys
import tempfile
import threading
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 eyerec # noqa: E402
W, H, SLOTS = eyerec.W, eyerec.H, 8
ESIZE = 64 + W * H
def frame_bytes(cam, n):
return bytes([(cam * 128 + n) % 256]) * (W * H)
class FakeShare:
"""Writes frames into a share file at fps per camera, on a thread, as ft-eyegrab --share does."""
def __init__(self, path, fps=90.0):
self.path, self.fps = path, fps
self.count = [0, 0]
self._stop = threading.Event()
self._make()
self._thread = threading.Thread(target=self._run, daemon=True)
def _make(self):
size = 64 + 2 * SLOTS * ESIZE
tmp = self.path + ".new"
fd = os.open(tmp, os.O_RDWR | os.O_CREAT | os.O_TRUNC, 0o600)
os.ftruncate(fd, size)
self.mm = mmap.mmap(fd, size)
os.close(fd)
struct.pack_into("<6I2QI", self.mm, 0, 0x31434546, 1, W, H, SLOTS, ESIZE, 0, 0, os.getpid())
os.replace(tmp, self.path)
self.count = [0, 0]
def replace(self):
"""As ft-eyegrab restarting: a new file, the counts from 0."""
self._make()
def start(self):
self._thread.start()
return self
def stop(self):
self._stop.set()
self._thread.join(2)
def put(self, cam):
n = self.count[cam]
off = 64 + (cam * SLOTS + n % SLOTS) * ESIZE
seq = struct.unpack_from("<Q", self.mm, off)[0]
struct.pack_into("<Q", self.mm, off, seq + 1)
self.mm[off + 64:off + 64 + W * H] = frame_bytes(cam, n)
struct.pack_into("<dQII", self.mm, off + 8, time.clock_gettime(time.CLOCK_MONOTONIC_RAW), n, cam, n % 4 + 4 * cam)
struct.pack_into("<Q", self.mm, off, seq + 2)
self.count[cam] = n + 1
struct.pack_into("<Q", self.mm, 24 + 8 * cam, n + 1)
def _run(self):
period = 1.0 / self.fps
nxt = time.monotonic()
while not self._stop.is_set():
for c in (0, 1):
self.put(c)
nxt += period
time.sleep(max(0.0, nxt - time.monotonic()))
class WriterTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="eyerec-test-")
self.share_path = os.path.join(self.tmp, "cams")
self.want = os.path.join(self.tmp, "want")
self.take = os.path.join(self.tmp, "take")
self.lines = []
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def writer(self, **kw):
kw.setdefault("min_free", 0)
return eyerec.Writer(self.take, share_path=self.share_path, want_path=self.want, log=self.lines.append, **kw)
def wait_frames(self, w, n, timeout=10):
end = time.monotonic() + timeout
while time.monotonic() < end:
with w._lock:
if all(len(w._times[c]) and w._last[c] is not None for c in (0, 1)) and \
sum(len(w._open[c]) for c in (0, 1)) + sum(w._frames.values()) >= n:
return
time.sleep(0.02)
self.fail("not enough frames")
def test_round_trip_with_a_pause(self):
share = FakeShare(self.share_path).start()
try:
w = self.writer(chunk_frames=20).start()
time.sleep(0.2) # frames before recording aren't kept
w.record(True)
time.sleep(0.6)
w.record(False)
time.sleep(0.3) # nor while paused
w.record(True)
time.sleep(0.4)
stats = w.stop()
finally:
share.stop()
self.assertIsNone(stats["error"])
self.assertEqual(stats["dropped"], [0, 0])
self.assertGreater(min(stats["frames"]), 50)
self.assertGreater(min(stats["fps"]), 60)
rows = eyerec.read_index(self.take)
self.assertEqual(len(rows), sum(stats["frames"]))
got = list(eyerec.iter_frames(self.take))
for c in (0, 1):
ts = [t for cam, t, _s, _d in got if cam == c]
gaps = [b - a for a, b in zip(ts, ts[1:])]
self.assertGreater(max(gaps), 0.25, "the pause leaves a gap")
self.assertEqual(sorted(ts), ts)
# Each frame is what the share had: a byte value from its camera and number, so
# consecutive frames of a camera go up by one (mod 256) outside the gap.
vals = [d[0] for cam, _t, _s, d in got if cam == c]
steps = {(b - a) % 256 for a, b, g in zip(vals, vals[1:], gaps) if g < 0.05}
self.assertEqual(steps, {1})
self.assertTrue(all(d == bytes([d[0]]) * len(d) for cam, _t, _s, d in got if cam == c))
# The pause ended the chunks: none spans it.
for c in (0, 1):
chunks = {}
for cam, chunk, i, _slot, t in rows:
if cam == c:
chunks.setdefault(chunk, []).append(t)
self.assertTrue(all(max(ts) - min(ts) < 0.25 for ts in chunks.values()))
self.assertTrue(os.path.exists(self.want), "ft-eyegrab's want file is touched")
# It compresses: a repeated byte is tiny.
self.assertLess(stats["bytes"], sum(stats["frames"]) * W * H / 100)
def test_a_slow_writer_drops_chunks_not_frames_in_the_share(self):
share = FakeShare(self.share_path).start()
real = eyerec.compress
def slow(b):
time.sleep(0.3)
return real(b)
try:
with mock.patch.object(eyerec, "compress", slow), mock.patch.object(eyerec, "MAX_QUEUED", 1):
w = self.writer(chunk_frames=5).start()
w.record(True)
time.sleep(1.0)
stats = w.stop()
finally:
share.stop()
self.assertGreater(sum(stats["dropped"]), 0)
self.assertTrue(any("behind" in line for line in self.lines))
rows = eyerec.read_index(self.take)
self.assertEqual(len(rows), sum(stats["frames"]))
for c, chunk, _i, _s, _t in rows: # every chunk the index names is there
self.assertTrue(os.path.exists(os.path.join(self.take, "cam%d" % c, "%06d.zst" % chunk)))
def test_follows_a_replaced_share(self):
share = FakeShare(self.share_path).start()
try:
w = self.writer(chunk_frames=10).start()
w.record(True)
time.sleep(0.4)
share.replace() # ft-eyegrab restarted with SteamVR
time.sleep(2.8) # the reader looks every 2 s
before = w.stats()["frames"]
time.sleep(0.5)
stats = w.stop()
finally:
share.stop()
self.assertIsNone(stats["error"])
self.assertTrue(any("replaced" in line for line in self.lines))
self.assertGreater(min(stats["frames"]), min(before))
def test_no_share(self):
with mock.patch.object(eyerec, "SHARE_WAIT", 0.2):
w = self.writer().start()
w.record(True)
time.sleep(0.6)
stats = w.stop()
self.assertIn("frametop-eyegrab", stats["error"])
self.assertFalse(w.recording)
def test_stops_before_the_disk_fills(self):
share = FakeShare(self.share_path).start()
try:
w = self.writer(min_free=1e18).start()
w.record(True)
time.sleep(2.5)
self.assertFalse(w.recording)
stats = w.stop()
finally:
share.stop()
self.assertIn("free on the disk", stats["error"])
w.record(True)
self.assertFalse(w.recording, "it doesn't start again after an error")
def test_numbering_goes_on_in_a_take_already_there(self):
share = FakeShare(self.share_path).start()
try:
for _ in range(2):
w = self.writer(chunk_frames=10).start()
w.record(True)
time.sleep(0.3)
w.stop()
finally:
share.stop()
rows = eyerec.read_index(self.take)
chunks = [chunk for c, chunk, _i, _s, _t in rows if c == 0]
self.assertEqual(len(set(chunks)), len(os.listdir(os.path.join(self.take, "cam0"))))
with open(os.path.join(self.take, "index.tsv")) as f:
self.assertEqual(sum(1 for line in f if line.startswith("#")), 1)
@unittest.skipUnless(shutil.which("zstd") or os.path.exists("/usr/bin/zstd"), "no zstd command")
class CommandFallbackTest(unittest.TestCase):
"""The zstd command, as on the SteamOS host's Python 3.12."""
def test_round_trip(self):
real_import = __import__
def no_modules(name, *a, **kw):
if name in ("compression", "zstandard"):
raise ImportError(name)
return real_import(name, *a, **kw)
with mock.patch("builtins.__import__", no_modules):
c, d, name = eyerec._compressor()
self.assertTrue(name.endswith("zstd"))
data = frame_bytes(0, 3) + frame_bytes(1, 4)
self.assertEqual(d(c(data)), data)
if eyerec.decompress is not None: # the module's and the command's are the same format
self.assertEqual(eyerec.decompress(c(data)), data)
if __name__ == "__main__":
unittest.main()
+134
View File
@@ -0,0 +1,134 @@
#!/usr/bin/env python3
"""The eye recorder's upload (gaze/rec/hub.py) without the network: the dry run, the gate that
keeps the real dataset closed until the texts are reviewed, upload records, and the pull request
flow against a fake Hub. The round is test_takes.make_round's random frames.
python3 gaze/rec/tests/test_hub.py
"""
import json
import os
import shutil
import sys
import tempfile
import unittest
import uuid
from unittest import mock
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
sys.path.insert(0, os.path.join(HERE, ".."))
import hub # noqa: E402
import takes # noqa: E402
from test_takes import HAVE, RID, make_round # noqa: E402
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}"
@unittest.skipUnless(HAVE, "needs zstd and the cryptography library (the dev container)")
class HubTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="eyerec-hub-")
base = os.path.join(self.tmp, "contrib")
make_round(base)
self.contributor = str(uuid.uuid4())
with open(os.path.join(base, "profile.json"), "w") as f:
json.dump({"contributor": self.contributor,
"consent": {"version": "test-1", "adult": True, "region_ok": True, "accepted": "2026-10-14"}}, f)
self.store = takes.Store(base)
meta = hub.meta_path(self.store, RID)
with open(meta) as f:
m = json.load(f)
m.pop("uploads") # the fixture's, for the export's test
with open(meta, "w") as f:
json.dump(m, f)
self.store.export(RID, low_priority=False) # to recipients.txt's keys, as validate wants
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-eyes"}):
result = hub.upload(self.store, RID, dry_run=True, log=logged.append)
self.assertTrue(result["dry_run"])
self.assertEqual(result["repo"], "someone/test-eyes")
self.assertEqual(result["path_in_repo"], f"contributions/{self.contributor}/{RID}")
self.assertIn("- Bounty: edges", result["commit_description"])
self.assertIn("- Health answers: included, encrypted", result["commit_description"])
self.assertTrue(any("health.json.age" in line for line in logged))
self.assertEqual(hub.rhub.uploads(hub.meta_path(self.store, RID)), [])
def test_gate(self):
self.assertFalse(hub.texts_ready(), "the texts are drafts")
with mock.patch.dict(os.environ, {hub.ALLOW_ENV: "1", hub.DATASET_ENV: ""}):
self.assertFalse(hub.upload_allowed(hub.dataset_id()), "never the real dataset before the review")
with self.assertRaises(hub.HubError) as cm:
hub.upload(self.store, RID)
self.assertEqual(cm.exception.kind, "closed")
with mock.patch.dict(os.environ, {hub.ALLOW_ENV: "1", hub.DATASET_ENV: "a/test"}):
self.assertTrue(hub.upload_allowed(hub.dataset_id()))
with mock.patch.dict(os.environ, {hub.ALLOW_ENV: "", hub.DATASET_ENV: "a/test"}):
self.assertFalse(hub.upload_allowed(hub.dataset_id()))
def test_invalid_blocks(self):
with open(os.path.join(self.store.export_dir(RID), "health.json"), "w") as f:
f.write("{}")
with self.assertRaises(hub.HubError) as cm:
hub.upload(self.store, RID, dry_run=True)
self.assertEqual(cm.exception.kind, "invalid")
def test_pull_request_first(self):
calls = []
class Api:
fail = True
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(3)
def get_discussion_details(self, repo, num, repo_type=None):
return Pr(num)
def upload_folder(self, **kw):
calls.append(("upload", kw["revision"], kw["path_in_repo"]))
if Api.fail:
raise ConnectionResetError("reset")
def change_discussion_status(self, repo, num, status, repo_type=None):
calls.append(("status", num, status))
env = {hub.DATASET_ENV: "a/b", hub.ALLOW_ENV: "1"}
meta = hub.meta_path(self.store, RID)
before = os.stat(meta).st_mtime_ns
with mock.patch.dict(os.environ, env), mock.patch.object(hub, "_hf", return_value=mock.Mock(HfApi=Api)):
with self.assertRaises(hub.HubError) as cm:
hub.upload(self.store, RID)
self.assertEqual(cm.exception.kind, "network")
[rec] = hub.rhub.uploads(meta)
self.assertEqual((rec["status"], rec["pr_num"]), ("started", 3))
Api.fail = False
result = hub.upload(self.store, RID)
with self.assertRaises(hub.HubError) as cm:
hub.upload(self.store, RID, dry_run=True)
self.assertEqual(cm.exception.kind, "duplicate")
where = f"contributions/{self.contributor}/{RID}"
self.assertEqual(calls, ["create", ("upload", "refs/pr/3", where), ("upload", "refs/pr/3", where),
("status", 3, "open")])
self.assertEqual(result["pr_num"], 3)
self.assertEqual(os.stat(meta).st_mtime_ns, before, "the record doesn't make the export look stale")
self.assertFalse(self.store.rounds()[0]["export_stale"])
if __name__ == "__main__":
unittest.main()
+173
View File
@@ -0,0 +1,173 @@
#!/usr/bin/env python3
"""The gaze panel's rec mode (gaze/panel/ft-gazepanel.cpp, "show rec") without SteamVR (--no-vr,
a made-up 90 Hz vsync): its commands, and targets.jsonl, the ground truth of where the dot was
when. Needs the built panel (gaze/build.sh); skipped without it.
python3 gaze/rec/tests/test_panel.py
"""
import json
import math
import os
import shutil
import socket
import subprocess
import tempfile
import time
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
PANEL = os.path.join(HERE, "..", "..", "build", "ft-gazepanel")
IN_BOX = os.path.expanduser("~/.local/bin/distrobox")
def command():
"""The panel's argv: in the dev container on the Frame's host, where it was built."""
if os.path.exists("/run/.containerenv") or not os.path.exists(IN_BOX):
return [PANEL]
return [IN_BOX, "enter", "dev", "--", PANEL]
@unittest.skipUnless(os.path.exists(PANEL), "the panel isn't built (gaze/build.sh)")
class RecPanelTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="gazepanel-test-")
self.name = f"ft_gazepanel_test_{os.getpid()}"
self.proc = subprocess.Popen(command() + ["--no-vr", "--watch-stdin", "--socket", self.name, "--dump",
os.path.join(self.tmp, "pics")],
stdin=subprocess.PIPE, stderr=subprocess.PIPE)
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
self.sock.bind("")
self.sock.settimeout(1.0)
end = time.monotonic() + 20
while True:
try:
if self.ask("ping").startswith("ok"):
break
except OSError:
pass
if time.monotonic() > end:
self.fail("the panel didn't start")
time.sleep(0.1)
def tearDown(self):
self.proc.stdin.close()
try:
self.proc.wait(5)
except subprocess.TimeoutExpired:
self.proc.kill()
self.proc.stderr.close()
self.sock.close()
shutil.rmtree(self.tmp, ignore_errors=True)
def ask(self, cmd):
self.sock.sendto(cmd.encode(), "\0" + self.name)
return self.sock.recv(4096).decode()
def rows(self):
with open(os.path.join(self.tmp, "targets.jsonl")) as f:
return [json.loads(line) for line in f]
def test_rec_lines_and_errors(self):
for cmd in ("show rec", "bg 0.3", "title Nine dots", "step Round 1 of 5", "rec on", "text Look at each dot|as it comes",
"big 3", "action Ready? Press the side button", "note Your left eye is hard to see",
"keys Space: go · P: pause", "countdown 0.4", "paused on", "paused off", "countdown off"):
self.assertEqual(self.ask(cmd), "ok", cmd)
self.assertTrue(self.ask("path spiral 0 0 1 2").startswith("error"))
self.assertTrue(self.ask("path circle 0 0 10 0").startswith("error"), "seconds must be positive")
self.assertTrue(self.ask("log start /nonexistent/dir").startswith("error"))
self.assertEqual(self.ask("ipd"), "ok 0.06300")
time.sleep(0.2)
self.assertTrue(os.listdir(os.path.join(self.tmp, "pics")), "pictures were drawn")
self.ask("show quick")
self.assertTrue(self.ask("path circle 0 0 10 2").startswith("error"), "only in rec")
def test_fixed_dot_logs_its_changes(self):
self.ask("show rec")
self.assertEqual(self.ask(f"log start {self.tmp}"), "ok")
self.ask("dot 10 -5 look")
time.sleep(0.15)
self.ask("dot 10 -5 capture 0.5")
time.sleep(0.15)
self.ask("bg 0.8")
time.sleep(0.15)
self.ask("dot 0 0 off")
time.sleep(0.15)
reply = self.ask("log stop").split()
rows = self.rows()
self.assertEqual(int(reply[1]), len(rows))
on = [r for r in rows if r["dot"] == "fixed"]
self.assertEqual([(r["yaw"], r["pitch"], r["state"]) for r in on],
[(10, -5, "look"), (10, -5, "capture"), (10, -5, "capture")])
self.assertEqual(on[-1]["bg"], 0.8)
self.assertEqual(rows[-1]["dot"], "off")
for r in rows:
self.assertGreater(r["t"], r["set"], "the photons come after it's set")
self.assertLess(r["t"] - r["set"], 0.03)
# The RAW clock, as the eye frames' (this process's CLOCK_MONOTONIC_RAW).
self.assertLess(abs(rows[-1]["set"] - time.clock_gettime(time.CLOCK_MONOTONIC_RAW)), 5)
def test_path_every_frame(self):
self.ask("show rec")
self.ask(f"log start {self.tmp}")
self.assertEqual(self.ask("path circle 2 1 10 1.0"), "ok")
time.sleep(1.2)
self.ask("dot 0 0 off")
self.ask("log stop")
rows = [r for r in self.rows() if r["dot"] == "path"]
ts = [r["t"] for r in rows]
self.assertGreater(len(rows), 80, "about one a frame")
gaps = [b - a for a, b in zip(ts, ts[1:])]
self.assertTrue(all(g > 0 for g in gaps))
self.assertAlmostEqual(sorted(gaps)[len(gaps) // 2], 1 / 90, delta=0.002)
self.assertEqual(len({r["frame"] for r in rows}), len(rows), "one row a frame")
for r in rows:
self.assertAlmostEqual(math.hypot(r["yaw"] - 2, r["pitch"] - 1), 10, delta=1e-3)
first = rows[0]
self.assertAlmostEqual((first["yaw"], first["pitch"])[1], 11, delta=0.5, msg="it starts at the top")
# A lap a second: back near the top a second later, having gone left (yaw up) first.
later = min(rows, key=lambda r: abs(r["t"] - first["t"] - 1.0))
self.assertAlmostEqual(later["pitch"], 11, delta=0.5)
self.assertGreater(rows[5]["yaw"], 2)
def test_line_and_eight(self):
self.ask("show rec")
self.ask(f"log start {self.tmp}")
self.ask("path line -10 0 10 0 0.5")
time.sleep(0.8)
self.ask("path eight 0 0 15 8 1")
time.sleep(0.6)
self.ask("log stop")
rows = self.rows()
line = [r for r in rows if r["dot"] == "path" and abs(r["pitch"]) < 1e-6 and abs(r["yaw"]) <= 10 + 1e-6]
self.assertGreater(len(line), 60)
self.assertGreater(max(r["yaw"] for r in line), 9)
self.assertLess(min(r["yaw"] for r in line), -9.5)
eight = [r for r in rows if r["t"] > line[-1]["t"]]
self.assertTrue(all(abs(r["yaw"]) <= 15 + 1e-6 and abs(r["pitch"]) <= 8 + 1e-6 for r in eight if r["dot"] == "path"))
def test_world_dot_and_distance(self):
self.ask("show rec")
self.ask(f"log start {self.tmp}")
reply = self.ask("world 0.5 0 -1")
self.assertTrue(reply.startswith("ok"), reply)
self.assertEqual([round(float(v), 3) for v in reply.split()[1:]], [0.5, 0.0, -1.0])
time.sleep(0.2)
again = self.ask("world 0.5 0 -1 capture 0.5")
self.assertEqual(again, reply, "the same point again: only the state changes")
time.sleep(0.1)
self.ask("dot 0 0 look")
self.assertEqual(self.ask("distance 0.5"), "ok")
time.sleep(0.1)
self.ask("log stop")
rows = self.rows()
world = [r for r in rows if r["dot"] == "world"]
self.assertGreater(len(world), 10)
# --no-vr's head is at the origin looking down -z: half a metre right of a metre ahead.
self.assertAlmostEqual(world[0]["yaw"], -math.degrees(math.atan2(0.5, 1)), delta=0.01)
self.assertAlmostEqual(world[0]["dist"], math.hypot(0.5, 1), delta=0.001)
self.assertEqual(rows[-1]["dist"], 0.5)
self.assertEqual(rows[-1]["dot"], "fixed")
if __name__ == "__main__":
unittest.main()
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""main.qml against ft_eyerec.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 (the hand recorder's Export, 2026-10-03).
Needs PySide6 (the dev container); skipped without it. FT_EYEREC_QML=PATH checks another
window against the same backend (the standalone Eye Recorder's, in its CI).
python3 gaze/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)
QML = os.environ.get("FT_EYEREC_QML") or os.path.join(REC, "main.qml")
class QmlBackendTest(unittest.TestCase):
def setUp(self):
try:
import ft_eyerec
except ImportError as e:
self.skipTest(f"no PySide6: {e}")
meta = self.meta = ft_eyerec.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(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()
+297
View File
@@ -0,0 +1,297 @@
#!/usr/bin/env python3
"""The eye recorder's session runner (gaze/rec/session.py) without the headset: the round
scripts' checks, the plans, the control sockets' answers, and whole rounds in a dry run.
python3 gaze/rec/tests/test_session.py
"""
import glob
import json
import os
import shutil
import socket
import sys
import tempfile
import threading
import time
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, ".."))
import session # noqa: E402
def write_round(tmp, steps, **extra):
d = dict({"schema": 1, "id": "t", "title": "Test", "steps": steps}, **extra)
path = os.path.join(tmp, "t.json")
with open(path, "w") as f:
json.dump(d, f)
return path
class RoundTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="eyerec-round-")
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def bad(self, steps, want):
with self.assertRaises(ValueError) as e:
session.load_round(write_round(self.tmp, steps))
self.assertIn(want, str(e.exception))
def test_shipped_rounds_load(self):
paths = sorted(glob.glob(os.path.join(session.ROUNDS_DIR, "*.json")))
self.assertEqual(len(paths), 10)
for p in paths:
r = session.load_round(p)
self.assertEqual(r["id"], os.path.basename(p)[:-5])
self.assertTrue(r["steps"][0]["ready"], p)
def test_panel_reach(self):
self.assertFalse(session.off_panel(0, 0))
self.assertFalse(session.off_panel(30, 20))
self.assertTrue(session.off_panel(38, 0))
self.assertTrue(session.off_panel(0, 26))
self.assertTrue(session.off_panel(30, 23), "corners reach less far up")
self.bad([{"id": "a", "kind": "dots", "dots": [[40, 0]]}], "off the panel")
self.bad([{"id": "a", "kind": "path", "path": "circle 0 0 26 4", "seconds": 4}], "off the panel")
self.bad([{"id": "a", "kind": "jumps", "count": 3, "range": [40, 10], "each": [0.5, 1]}], "off the panel")
def test_bad_steps(self):
self.bad([{"id": "a", "kind": "dance"}], "unknown kind")
self.bad([{"id": "A b", "kind": "dots", "dots": [[0, 0]]}], "bad id")
self.bad([{"id": "a", "kind": "path", "path": "spiral 0 0 1 2", "seconds": 2}], "bad path")
self.bad([{"id": "a", "kind": "path", "path": "circle 0 0 10 0", "seconds": 2}], "positive")
self.bad([{"id": "a", "kind": "prompt"}], "seconds")
self.bad([{"id": "a", "kind": "world", "point": [0, 0, 1], "seconds": 3}], "ahead")
self.bad([{"id": "a", "kind": "dots", "dots": [[0, 0]]}, {"id": "a", "kind": "dots", "dots": [[0, 0]]}], "repeat")
self.bad([{"id": "a", "kind": "dots", "group": "g", "dots": [[0, 0]]}, {"id": "b", "kind": "dots", "dots": [[0, 0]]},
{"id": "c", "kind": "dots", "group": "g", "dots": [[0, 0]]}], "comes back")
self.bad([{"id": "a", "kind": "dots", "group": "dots", "dots": [[0, 0]]}], "opener")
def test_grid_and_defaults(self):
r = session.load_round(write_round(self.tmp, [{"id": "a", "kind": "dots", "grid": [3, 2, 10, 5], "ready": False},
{"id": "b", "kind": "reseat", "text": "off and on"}]))
a = r["steps"][0]
self.assertEqual(a["dots"], [[10, 5], [0, 5], [-10, 5], [10, -5], [0, -5], [-10, -5]])
self.assertTrue(a["ready"], "the first step always waits")
self.assertEqual((a["bg"], a["distance"], a["group"]), (session.MID_BG, session.PANEL_DISTANCE, "a"))
self.assertFalse(r["shift_check"], "a round that reseats on purpose has no shift check")
def test_plan(self):
rnd = session.load_round(os.path.join(session.ROUNDS_DIR, "jumps.json"))
a = session.build_plan(rnd, 7, ipd_sweep=True)
self.assertEqual([s["group"] for s in a[:3]], ["ipd", "dots", "jumps"])
nine = a[1]["dots"]
self.assertEqual((nine[0], nine[-1], len(nine)), ([0.0, 0.0], [0.0, 0.0], 10))
self.assertEqual(sorted(map(tuple, nine[1:-1])), sorted(map(tuple, (d for d in session.grid(3, 3, 20, 20) if d != [0, 0]))))
jumps = a[2]
self.assertEqual(len(jumps["dots"]), 40)
self.assertTrue(all(0.5 <= t <= 1.5 for t in jumps["times"]))
self.assertTrue(all(not session.off_panel(*d) for d in jumps["dots"]))
self.assertEqual(a, session.build_plan(rnd, 7, ipd_sweep=True), "the same seed, the same round")
self.assertNotEqual(a[1]["dots"], session.build_plan(rnd, 8, ipd_sweep=True)[1]["dots"])
self.assertEqual(session.build_plan(rnd, 7, ipd_sweep=False)[0]["group"], "dots")
self.assertGreater(session.plan_seconds(a), 60)
class SocketTest(unittest.TestCase):
"""The panel and ft-eyes answer every command in order: an answer waited for is the one
after the answers of commands sent before it."""
def setUp(self):
self.name = "eyerec_socket_test_%d_%s" % (os.getpid(), self.id().rsplit(".", 1)[-1])
self.server = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
self.server.bind("\0" + self.name)
self.server.settimeout(0.2)
self.delay = 0.02
self.drop = set()
self.running = True
threading.Thread(target=self.serve, daemon=True).start()
def tearDown(self):
self.running = False
self.server.close()
def serve(self):
while self.running:
try:
data, addr = self.server.recvfrom(4096)
except OSError:
continue
text = data.decode()
time.sleep(self.delay)
if text in self.drop:
continue
try:
self.server.sendto(("ok " + text).encode(), addr)
except OSError:
pass
def test_answers_in_order(self):
s = session.Socket(self.name)
for n in range(5):
s.cmd("dot %d" % n)
self.assertEqual(s.cmd("ipd", reply=True), "ok ipd")
self.assertEqual(s.pending, 0)
s.cmd("bg 1")
self.assertEqual(s.cmd("log stop", reply=True), "ok log stop")
s.close()
def test_lost_answer(self):
s = session.Socket(self.name)
self.drop.add("fit")
self.assertIsNone(s.cmd("fit", reply=True, timeout=0.2))
self.assertEqual(s.cmd("ipd", reply=True), "ok ipd", "counting starts afresh")
s.close()
def test_errors_logged(self):
logs = []
s = session.Socket(self.name, log=logs.append)
s.cmd("x")
time.sleep(0.1)
s._got("error bad")
self.assertEqual(logs, ["%s: error bad" % self.name])
s.close()
class DryRunTest(unittest.TestCase):
"""Whole rounds with no processes: the files, the fitment, the controls."""
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="eyerec-dry-")
self.out = []
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def run_round(self, script, steer=None, profile=None, **kw):
path = os.path.join(self.tmp, "profile.json")
with open(path, "w") as f:
json.dump(profile or {}, f)
states = []
s = session.Session(self.tmp, script, profile=profile, dry_run=True, speed=kw.pop("speed", 40),
next_after=kw.pop("next_after", 0.25), profile_path=path, button=False,
on_status=lambda st: states.append(dict(st)), **kw)
s.print = self.out.append
s.start()
if steer:
steer(s, states)
s.join(60)
self.assertFalse(s._thread.is_alive())
with open(path) as f:
return s, states, json.load(f)
def files(self, s):
with open(os.path.join(s.session_dir, "session.json")) as f:
sj = json.load(f)
with open(os.path.join(s.session_dir, "fit.json")) as f:
fit = json.load(f)
return sj, fit
def prompts(self, s, take):
with open(os.path.join(s.session_dir, "takes", take, "prompts.jsonl")) as f:
return [json.loads(line) for line in f]
def test_round_and_profile(self):
s, states, profile = self.run_round("depth")
self.assertEqual(s.state, "done")
sj, fit = self.files(s)
self.assertEqual(sj["takes"], ["01-ipd", "02-dots", "03-near", "04-mid", "05-far", "06-near-far"])
self.assertEqual((sj["status"], sj["fit"], sj["ipd_sweep"], sj["ipd_start"]), ("done", "good", True, 0.063))
self.assertEqual(fit["fitment"]["result"], "good")
self.assertIsNotNone(fit["baseline"])
self.assertEqual(profile["bounties"]["depth"]["rounds"], 1)
self.assertEqual(profile["eyes_ipd"], 0.063)
for take in sj["takes"]:
with open(os.path.join(s.session_dir, "takes", take, "take.json")) as f:
self.assertEqual(json.load(f)["status"], "complete", take)
events = [e["event"] for e in self.prompts(s, "03-near")]
self.assertEqual(events[:4], ["take", "ready", "rec", "step"])
self.assertEqual(events[-3:], ["wait", "rec", "end"])
self.assertIn("ft_eyerecpanel: distance 0.500", self.out)
self.assertIn("ft_eyerecpanel: distance 5.000", self.out)
# The IPD is the same next time: no sweep.
s2, _, profile = self.run_round("depth", profile=profile)
self.assertEqual(self.files(s2)[0]["takes"][0], "01-dots")
self.assertEqual(profile["bounties"]["depth"]["rounds"], 2)
def test_fitment_warns_then_skips(self):
# Next before the fit has been good for FIT_GOOD_S: a warning, then the round goes on.
s, states, _ = self.run_round("reading", next_after=0.01, speed=20)
sj, fit = self.files(s)
self.assertEqual((sj["fit"], fit["fitment"]["result"]), ("skipped", "skipped"))
self.assertTrue(any(st["note"] == session.FIT_SKIP_NOTE for st in states))
self.assertIsNone(fit["baseline"])
def test_skip_redo_stop(self):
def steer(s, states):
def wait_for(cond):
end = time.monotonic() + 30
while time.monotonic() < end and not cond():
time.sleep(0.01)
# In the jumps take: redo the step while it runs, then skip the rest of the take.
# (Its ready first: the step's name comes one emit before the dots take's "running" goes.)
wait_for(lambda: s._status["step"] == "jumps" and s._status["state"] == "ready")
wait_for(lambda: s._status["step"] == "jumps" and s._status["state"] == "running")
s.redo()
wait_for(lambda: s._status["step"] == "jumps" and s._status["state"] == "ready")
wait_for(lambda: s._status["step"] == "jumps" and s._status["state"] == "running")
s.skip()
wait_for(lambda: s._status["step"] == "circle-slow" and s._status["state"] == "running")
s.stop(wait=0)
s, states, profile = self.run_round("jumps", steer=steer, speed=10, profile={"eyes_ipd": 0.063})
self.assertEqual(s.state, "stopped")
sj, _ = self.files(s)
self.assertEqual(sj["takes"], ["01-dots", "02-jumps", "03-pursuit"])
with open(os.path.join(s.session_dir, "takes", "02-jumps", "take.json")) as f:
self.assertEqual(json.load(f)["status"], "skipped")
with open(os.path.join(s.session_dir, "takes", "03-pursuit", "take.json")) as f:
self.assertEqual(json.load(f)["status"], "stopped")
redo = [e for e in self.prompts(s, "02-jumps") if e["event"] == "redo"]
self.assertEqual(len(redo), 1)
self.assertLess(redo[0]["from"], redo[0]["to"])
self.assertNotIn("bounties", profile, "a stopped round isn't counted")
def test_pause_stops_the_recording(self):
def steer(s, states):
end = time.monotonic() + 30
while time.monotonic() < end and not (s._status["step"] == "dots" and s._status["state"] == "running"):
time.sleep(0.01)
s.pause()
time.sleep(0.3)
self.assertFalse(s._recording)
s.resume()
s, _, _ = self.run_round("face", steer=steer, speed=10, profile={"eyes_ipd": 0.063})
self.assertEqual(s.state, "done")
events = [e["event"] for e in self.prompts(s, "01-dots")]
i = events.index("pause")
self.assertEqual(events[i - 1:i + 3], ["rec", "pause", "resume", "rec"])
def test_shift_check(self):
moved = {"on": False}
def steer(s, states):
# Once the fitment is done, the eyes appear 12 degrees up: the headset slipped down.
end = time.monotonic() + 30
while time.monotonic() < end and s._status["state"] in ("starting", "fitment"):
time.sleep(0.01)
ref = s.ref
summary = {str(cam): {"n": 90, "finds": 90, "found": 1.0,
"x": ref.eyes[cam]["centre"][0] + ref.eyes[cam]["jacobian"][0][1] * 12,
"y": ref.eyes[cam]["centre"][1] + ref.eyes[cam]["jacobian"][1][1] * 12,
"a": 28.0, "spacing": 15.0, "extra": 0.0} for cam in (0, 1)}
s._eyes.fake = lambda text: json.dumps(summary) if text == "fit" else "ok"
moved["on"] = True
s, states, _ = self.run_round("glasses", steer=steer, profile={"eyes_ipd": 0.063})
self.assertTrue(moved["on"])
_, fit = self.files(s)
self.assertGreaterEqual(len(fit["slips"]), 2, "the nine dots' middle, twice, and the grid's")
self.assertIn("up", fit["slips"][0]["hints"])
self.assertTrue(any(st["note"].startswith("The headset moved") for st in states))
self.assertTrue(any(e["event"] == "slip" for e in self.prompts(s, "01-dots")))
if __name__ == "__main__":
unittest.main()
+227
View File
@@ -0,0 +1,227 @@
#!/usr/bin/env python3
"""The eye recorder's store and encrypted export (gaze/rec/takes.py), on a made-up round of
random frames (never real eye images): listing, deleted ranges across the two clocks, the export's
chunks, logs and checksums, and unpacking it with a key. Needs zstd (Python 3.14's, as eyerec.py)
and the cryptography library: the dev container has both.
python3 gaze/rec/tests/test_takes.py
"""
import json
import os
import shutil
import sys
import tempfile
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, ".."))
import eyerec # noqa: E402
import takes # noqa: E402
from recorder import age # noqa: E402
try:
age._crypto()
HAVE = eyerec.compress is not None
except RuntimeError:
HAVE = False
RID = "20261014-120000-edges"
TID = "01-dots"
MONO0 = 1000 * 10**9 # the take starts at 1000 s MONOTONIC
OFF = 5 * 10**9 + 123 # RAW is 5 s ahead
FPS = 90.0
PER_CHUNK = 10
CHUNKS = 3
def raw_s(mono_ns):
return (mono_ns + OFF) / 1e9
def make_round(base, health=True):
"""A round with one take: CHUNKS chunks of PER_CHUNK random frames per camera, frame k of
camera c at MONO0 + k / FPS (plus 1 ms for camera 1). Returns {(c, k): frame bytes}."""
rdir = os.path.join(base, "rounds", RID)
tdir = os.path.join(rdir, "takes", TID)
frames = {}
lines = [eyerec.INDEX_HEADER]
for c in eyerec.CAMERAS:
os.makedirs(os.path.join(tdir, "cam%d" % c))
for chunk in range(CHUNKS):
data = []
for i in range(PER_CHUNK):
k = chunk * PER_CHUNK + i
frames[(c, k)] = os.urandom(eyerec.FRAME)
data.append(frames[(c, k)])
lines.append("%d\t%d\t%d\t%d\t%.6f\n" % (c, chunk, i, k % 8, raw_s(MONO0 + int(k / FPS * 1e9)) + c * 0.001))
with open(os.path.join(tdir, "cam%d" % c, "%06d.zst" % chunk), "wb") as f:
f.write(eyerec.compress(b"".join(data)))
with open(os.path.join(tdir, "index.tsv"), "w") as f:
f.writelines(lines)
end = MONO0 + int(CHUNKS * PER_CHUNK / FPS * 1e9)
with open(os.path.join(tdir, "take.json"), "w") as f:
json.dump({"group": "dots", "started_ns": MONO0, "ended_ns": end, "status": "complete", "steps": [],
"deleted": [], "clock": [[MONO0, OFF], [end, OFF]], "notes": ""}, f)
with open(os.path.join(tdir, "own.jsonl"), "w") as f:
for k in range(CHUNKS * PER_CHUNK):
f.write(json.dumps({"t": raw_s(MONO0 + int(k / FPS * 1e9)), "cam": 0, "x": 1.0}) + "\n")
with open(os.path.join(tdir, "prompts.jsonl"), "w") as f:
f.write(json.dumps({"t": MONO0, "event": "take"}) + "\n")
with open(os.path.join(tdir, "targets.jsonl"), "w") as f:
f.write(json.dumps({"t": raw_s(MONO0), "dot": "on", "yaw": 0, "pitch": 0}) + "\n")
with open(os.path.join(rdir, "session.json"), "w") as f:
json.dump({"schema": 1, "round": RID, "bounty": "edges", "status": "done", "takes": [TID],
"started": "2026-10-14T12:00:00+0000", "checklist": {"glasses": "none"},
"uploads": [{"pr": 1}]}, f)
with open(os.path.join(rdir, "fit.json"), "w") as f:
json.dump({"fitment": {"state": "ok"}}, f)
with open(os.path.join(rdir, "session.log"), "w") as f:
f.write("a log that names /home/someone\n")
if health:
with open(os.path.join(rdir, "health.json"), "w") as f:
json.dump({"conditions": ["test"]}, f)
with open(os.path.join(base, "profile.json"), "w") as f:
json.dump({"contributor": "c0ffee", "consent": {"version": "test-1"}, "health": {"x": 1},
"optional": {"notes": "private"}}, f)
return frames
def load(path, mode="r"):
with open(path, mode) as f:
return json.load(f) if path.endswith(".json") else f.read()
def frame_mono(k):
return MONO0 + int(k / FPS * 1e9)
@unittest.skipUnless(HAVE, "needs zstd and the cryptography library (the dev container)")
class TakesTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="eyerec-takes-")
self.base = os.path.join(self.tmp, "contrib")
self.frames = make_round(self.base)
self.store = takes.Store(self.base)
self.ident, self.rec = age.keygen()
self.key = os.path.join(self.tmp, "key.txt")
with open(self.key, "w") as f:
f.write("# test key\n" + self.ident + "\n")
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def test_ids(self):
for bad in ("../x", "20261014-120000-../x", "", "x"):
with self.assertRaises(ValueError):
self.store.round_dir(bad)
for bad in ("..", "01-a/b", ".x"):
with self.assertRaises(ValueError):
self.store.take_dir(RID, bad)
self.store.round_dir("20261014-120000-edges-2")
def test_clock(self):
clock = [[0, 100], [1000, 200]]
self.assertEqual(takes.raw_offset_ns(-5, clock), 100)
self.assertEqual(takes.raw_offset_ns(500, clock), 150)
self.assertEqual(takes.raw_offset_ns(5000, clock), 200)
self.assertEqual(takes.raw_offset_ns(5, []), 0)
def test_listing(self):
[r] = self.store.rounds()
self.assertEqual((r["id"], r["bounty"], r["takes"], r["exported"]), (RID, "edges", 1, False))
[t] = self.store.takes(RID)
self.assertEqual(t["frames"], [30, 30])
self.assertEqual(t["deleted_frames"], [0, 0])
self.assertAlmostEqual(t["duration_s"], 29 / FPS, places=2)
def test_ranges(self):
# index.tsv's times are whole microseconds: the ranges have a millisecond to spare
self.store.delete_range(RID, TID, frame_mono(12) - 10**6, frame_mono(25))
self.store.delete_range(RID, TID, frame_mono(20), frame_mono(29) + 10**6)
self.assertEqual(self.store.ranges(RID, TID), [[frame_mono(12) - 10**6, frame_mono(29) + 10**6]])
[t] = self.store.takes(RID)
self.assertEqual(t["deleted_frames"][0], 18)
self.store.restore_range(RID, TID, 0)
self.assertEqual(self.store.ranges(RID, TID), [])
def test_export_and_unpack(self):
# frames 15..29 deleted: chunk 0 whole, chunk 1 half (10..14 kept), chunk 2 gone
self.store.delete_range(RID, TID, frame_mono(15) - 1000, frame_mono(29) + 5 * 10**6)
path = self.store.export(RID, recipients=[self.rec])
self.assertFalse(os.path.exists(path + ".partial"))
m = load(os.path.join(path, "manifest.json"))
[e] = m["takes"]
self.assertEqual(e["frames_deleted"][0], 15)
self.assertEqual(e["frames"][0], 15)
self.assertEqual(e["chunks"], 4)
self.assertEqual(e["logs"]["own.jsonl"], {"rows": 15, "deleted": 15})
self.assertNotIn("uploads", m["session"])
self.assertNotIn("health", m["profile"])
self.assertNotIn("notes", m["profile"]["optional"])
self.assertEqual(m["encryption"]["recipients"], [self.rec])
files = sorted(os.path.relpath(os.path.join(r, n), path) for r, _, ns in os.walk(path) for n in ns)
self.assertIn("health.json.age", files)
self.assertNotIn("health.json", files)
self.assertNotIn("session.log", files)
self.assertFalse([f for f in files if f.endswith(".zst")], "every chunk is encrypted")
self.assertIn("takes/%s/cam0/000001.zst.age" % TID, files)
self.assertNotIn("takes/%s/cam0/000002.zst.age" % TID, files)
# chunk 0 untouched: its encrypted copy decrypts to the recorded file
src = load(os.path.join(self.base, "rounds", RID, "takes", TID, "cam0", "000000.zst"), "rb")
enc = load(os.path.join(path, "takes", TID, "cam0", "000000.zst.age"), "rb")
self.assertEqual(age.decrypt_bytes(enc, self.ident), src)
with open(os.path.join(path, "SHA256SUMS")) as f:
self.assertEqual(sorted(line.split(" ", 1)[1].strip() for line in f), [f for f in files if f != "SHA256SUMS"])
out = takes.unpack(path, self.key, os.path.join(self.tmp, "unpacked"))
self.assertEqual(load(os.path.join(out, "health.json")), {"conditions": ["test"]})
got = {}
tdir = os.path.join(out, "takes", TID)
for c, t, slot, data in eyerec.iter_frames(tdir):
got.setdefault(c, []).append(data)
for c in eyerec.CAMERAS:
self.assertEqual(got[c], [self.frames[(c, k)] for k in range(15)])
self.assertEqual(load(os.path.join(tdir, "take.json"))["export"]["deleted_raw_s"][0][0],
raw_s(frame_mono(15) - 1000))
[r] = self.store.rounds()
self.assertTrue(r["exported"] and not r["export_stale"])
def test_default_recipients(self):
path = self.store.export(RID)
m = load(os.path.join(path, "manifest.json"))
self.assertEqual(m["encryption"]["recipients"], age.read_recipients(takes.RECIPIENTS))
with self.assertRaises(ValueError): # the test key isn't one of them
takes.unpack(path, self.key, os.path.join(self.tmp, "no"))
def test_bad_chunks(self):
tdir = os.path.join(self.base, "rounds", RID, "takes", TID)
shutil.copyfile(os.path.join(tdir, "cam0", "000000.zst"), os.path.join(tdir, "cam0", "000007.zst"))
with open(os.path.join(tdir, "cam1", "000001.zst"), "r+b") as f:
f.truncate(100)
os.remove(os.path.join(tdir, "cam1", "000002.zst"))
path = self.store.export(RID, recipients=[self.rec])
[e] = load(os.path.join(path, "manifest.json"))["takes"]
self.assertEqual(e["left_out"], {"not_indexed": 1, "missing": 1, "bad": 1})
self.assertEqual(e["frames"], [30, 10])
with open(os.path.join(path, "takes", TID, "index.tsv")) as f:
self.assertEqual(sum(1 for line in f if line.startswith("1\t")), 10)
def test_cancel(self):
with self.assertRaises(takes.Cancelled):
self.store.export(RID, recipients=[self.rec], cancel=lambda: True)
self.assertFalse(os.path.exists(self.store.export_dir(RID) + ".partial"))
self.assertFalse(os.path.exists(self.store.export_dir(RID)))
def test_delete(self):
self.store.export(RID, recipients=[self.rec])
self.store.delete_take(RID, TID)
meta = load(os.path.join(self.base, "rounds", RID, "session.json"))
self.assertEqual((meta["takes"], meta["deleted_takes"]), ([], [TID]))
self.store.delete_round(RID)
self.assertEqual(self.store.rounds(), [])
self.assertFalse(os.path.exists(self.store.export_dir(RID)))
if __name__ == "__main__":
unittest.main()
+150
View File
@@ -0,0 +1,150 @@
#!/usr/bin/env python3
"""The eye recorder's export check (gaze/rec/validate.py) on takes.py's export of a made-up
round of random frames (test_takes.make_round): a good one, with and without a key, and broken
ones. Needs zstd and the cryptography library: the dev container has both.
python3 gaze/rec/tests/test_validate.py
"""
import json
import os
import shutil
import sys
import tempfile
import unittest
import uuid
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
sys.path.insert(0, os.path.join(HERE, ".."))
import takes # noqa: E402
import validate # noqa: E402
from recorder import age # noqa: E402
from recorder.files import write_sums # noqa: E402
from test_takes import HAVE, RID, TID, make_round # noqa: E402
@unittest.skipUnless(HAVE, "needs zstd and the cryptography library (the dev container)")
class ValidateTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="eyerec-validate-")
base = os.path.join(self.tmp, "contrib")
make_round(base)
self.contributor = str(uuid.uuid4())
with open(os.path.join(base, "profile.json"), "w") as f:
json.dump({"contributor": self.contributor,
"consent": {"version": "test-1", "adult": True, "region_ok": True, "accepted": "2026-10-14"},
"bounties": {}}, f)
self.ident, self.rec = age.keygen()
self.keys = os.path.join(self.tmp, "recipients.txt")
with open(self.keys, "w") as f:
f.write("# test\n%s\n" % self.rec)
self.store = takes.Store(base)
self.path = self.store.export(RID, recipients=[self.rec])
self.take = os.path.join(self.path, "takes", TID)
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def check(self, identity=None, resum=False):
if resum: # a change made on purpose, with checksums to match, so the other checks see it
os.remove(os.path.join(self.path, "SHA256SUMS"))
write_sums(self.path)
return validate.validate(self.path, identity=identity, recipients_path=self.keys)
def has(self, report, text):
self.assertTrue(any(text in e for e in report.errors), (text, report.errors))
def manifest(self, change):
p = os.path.join(self.path, "manifest.json")
with open(p) as f:
m = json.load(f)
change(m)
with open(p, "w") as f:
json.dump(m, f)
def test_good(self):
r = self.check()
self.assertEqual(r.errors, [])
self.assertEqual(r.summary["frames"], 60)
self.assertTrue(r.summary["health"])
r = self.check(identity=self.ident)
self.assertEqual(r.errors, [])
def test_shipped_keys(self):
r = validate.validate(self.path) # recipients.txt's, not the test key
self.has(r, "other keys than the dataset's")
def test_checksum(self):
with open(os.path.join(self.take, "cam0", "000001.zst.age"), "r+b") as f:
f.seek(200)
b = f.read(1)
f.seek(200)
f.write(bytes([b[0] ^ 1]))
self.has(self.check(), "checksum mismatch")
def test_unencrypted(self):
shutil.copyfile(os.path.join(self.take, "index.tsv"), os.path.join(self.take, "cam0", "000009.zst"))
with open(os.path.join(self.path, "health.json"), "w") as f:
f.write("{}")
r = self.check(resum=True)
self.has(r, "cam0/000009.zst: not an allowed file (unencrypted")
self.has(r, "health.json: not an allowed file (unencrypted")
def test_cut_short(self):
# Without a key only some sizes show a cut (a last piece under a tag); the key finds any.
p = os.path.join(self.take, "cam1", "000000.zst.age")
with open(p, "rb") as f:
data = f.read()
body = data.index(b"\n", data.index(b"\n---") + 1) + 1 + 16
whole = (len(data) - body) // (age.CHUNK + age.TAG)
with open(p, "r+b") as f:
f.truncate(body + whole * (age.CHUNK + age.TAG) + 5)
self.has(self.check(resum=True), "cam1/000000.zst.age: a size no age file has")
with open(p, "r+b") as f:
f.truncate(len(data) - 65000)
self.assertEqual(self.check(resum=True).errors, [])
self.has(self.check(identity=self.ident, resum=True), "cam1/000000.zst.age: doesn't decrypt")
def test_wrong_content(self):
with open(os.path.join(self.take, "cam0", "000000.zst.age"), "wb") as f:
f.write(age.encrypt_bytes(os.urandom(1000), [self.rec]))
self.assertEqual(self.check(resum=True).errors, [], "without a key it can't tell")
self.has(self.check(identity=self.ident), "doesn't decompress")
other, _ = age.keygen()
self.has(self.check(identity=other), "doesn't decrypt")
def test_index(self):
p = os.path.join(self.take, "index.tsv")
with open(p) as f:
lines = f.readlines()
with open(p, "w") as f:
f.writelines(lines[:3] + lines[4:]) # camera 0, chunk 0, frame 2 gone
r = self.check(resum=True)
self.has(r, "frames aren't numbered")
self.has(r, "the manifest says [30, 30] frames, index.tsv has [29, 30]")
os.remove(os.path.join(self.take, "cam1", "000001.zst.age"))
self.has(self.check(resum=True), "cam1/000001.zst.age: in index.tsv but missing")
def test_manifest(self):
def change(m):
m["session"]["dry_run"] = True
m["session"]["replay"] = "/dev/shm/x"
m["profile"]["health"] = {"x": 1}
m["profile"]["consent"]["adult"] = False
m["contributor"] = m["profile"]["contributor"] = "c0ffee"
self.manifest(change)
r = self.check(resum=True)
for text in ("dry-run round", "from a replay", "unexpected keys: health", "18 or older", "random uuid4"):
self.has(r, text)
def test_two_recipients(self):
_, second = age.keygen()
with open(self.keys, "a") as f:
f.write(second + "\n")
self.has(self.check(), "other keys than the dataset's")
self.manifest(lambda m: m["encryption"].update(recipients=[self.rec, second]))
self.has(self.check(resum=True), "encrypted to 1 recipients, not 2")
if __name__ == "__main__":
unittest.main()
+467
View File
@@ -0,0 +1,467 @@
#!/usr/bin/env python3
"""Check an eye recorder export before it's uploaded, or when it's received (takes.py's
exports/<round>/).
The window runs it before an upload and refuses on errors; the maintainer runs it on each
submission. The images are encrypted, so without a key it checks everything around them:
- SHA256SUMS: every file listed and matching, nothing missing from it;
- an allow-list of files: anything else (an unencrypted chunk, health.json, a symlink) is an error;
- every .age file is age v1 to as many X25519 recipients as the manifest names, and its size
is one a whole age file can have; the manifest's recipients are recipients.txt's;
- manifest.json: the schema, required keys and types, the consent, a random uuid4 contributor,
no dry run or replay, no health answers outside health.json.age;
- each take's index.tsv against its chunks (every chunk named is there, every one there is
named, frames numbered from 0, times going forward) and against the manifest's counts;
- every .jsonl line is a JSON object with a time "t", and take.json and fit.json parse;
- the total size.
With --identity KEYFILE (one of the dataset's keys, the maintainer's side) it also decrypts each
chunk in memory and checks it decompresses to the frames index.tsv gives it.
Standard library only without --identity (zstd and the cryptography library with it). Python
3.12 or later, Linux or Windows.
usage: validate.py DIR [--json] [--identity KEYFILE]
exit status 0: no errors, 1: errors, 2: not an export
"""
import argparse
import json
import math
import os
import re
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(os.path.dirname(HERE)))
from recorder import age # noqa: E402
from recorder.checks import (Cancelled, Report, check_sums, is_uuid4, listed, need, # noqa: E402,F401
read_json_file)
EXPORT_SCHEMA = 1
RECIPIENTS = os.path.join(HERE, "recipients.txt")
TOP_FILES = {"manifest.json", "fit.json", "health.json.age", "SHA256SUMS"}
TAKE_FILES = {"take.json", "index.tsv", "targets.jsonl", "ipd.jsonl", "prompts.jsonl", "own.jsonl",
"steamvr.jsonl", "poses.jsonl"}
CAM_DIRS = ("cam0", "cam1")
ROUND_RE = re.compile(r"^\d{8}-\d{6}-[a-z0-9][a-z0-9-]{0,39}$")
TAKE_RE = re.compile(r"^\d{2,}-[a-z0-9][a-z0-9_-]{0,63}$")
CHUNK_FILE_RE = re.compile(r"^(\d{6})\.zst\.age$")
TAKE_STATUSES = ("complete", "stopped", "skipped")
PROFILE_KEYS = {"schema", "contributor", "consent", "optional", "checklist", "bounties", "eyes_ipd"}
INDEX_HEADER = "# camera\tchunk\tframe\tslot\tt_raw"
FRAME = 512 * 400
CHUNK_FRAMES_MAX = 1000 # eyerec.py writes 90 a chunk
# One round is about 2.6 GB (2026-10-14 replay: 20 MB/s on disk); encryption adds next to nothing.
WARN_BYTES = 6 * 1000 ** 3
MAX_BYTES = 15 * 1000 ** 3
# ---------------------------------------------------------------- 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
parts = rel_dir.split("/") if rel_dir else []
for d in list(dirnames):
rel = f"{rel_dir}/{d}" if rel_dir else d
ok = ((not parts and d == "takes") or (parts == ["takes"] and TAKE_RE.match(d))
or (len(parts) == 2 and parts[0] == "takes" and d in CAM_DIRS))
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
ok = ((not parts and name in TOP_FILES) or (len(parts) == 2 and name in TAKE_FILES)
or (len(parts) == 3 and CHUNK_FILE_RE.match(name)))
if not ok:
hint = " (unencrypted: export it again)" if name.endswith(".zst") or name == "health.json" else ""
report.error(f"{rel}: not an allowed file{hint}")
files.append(rel)
return sorted(files)
age_shape = age.shape # recorder/age.py: shared with the hand recorder's debug exports
def check_jsonl(path, rel, report, cancelled):
"""Every line a JSON object with a finite time "t" (RAW seconds, or MONOTONIC ns in prompts)."""
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
t = obj.get("t") if isinstance(obj, dict) else None
if isinstance(t, bool) or not isinstance(t, (int, float)) or not math.isfinite(t):
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}")
def read_index(path, rel, report):
"""index.tsv as {(camera, chunk): [(frame, t)]}, or None when it doesn't parse."""
out = {}
with open(path, encoding="utf-8", errors="replace") as f:
for n, line in enumerate(f, 1):
line = line.rstrip("\n")
if n == 1:
if line != INDEX_HEADER:
report.error(f"{rel}: the first line isn't the header")
return None
continue
if not line:
continue
fields = line.split("\t")
try:
c, chunk, i, slot = (int(x) for x in fields[:4])
t = float(fields[4])
if len(fields) != 5 or not math.isfinite(t) or c not in (0, 1) or min(chunk, i, slot) < 0:
raise ValueError
except (ValueError, IndexError):
report.error(f"{rel} line {n}: not camera, chunk, frame, slot, time")
return None
out.setdefault((c, chunk), []).append((i, t))
return out
def check_take(root, tid, entry, sizes, recipients, identity, report, step, cancelled):
base = f"takes/{tid}/"
for name in sorted(TAKE_FILES - {"take.json", "index.tsv"}):
rel = base + name
if rel in sizes:
check_jsonl(os.path.join(root, rel), rel, report, cancelled)
elif name in ("targets.jsonl", "prompts.jsonl", "own.jsonl"):
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")
chunks = {}
for rel in sizes:
if rel.startswith(base) and rel.count("/") == 3:
m = CHUNK_FILE_RE.match(rel.rsplit("/", 1)[1])
if m:
chunks[(int(rel.split("/")[2][3:]), int(m.group(1)))] = rel
if base + "index.tsv" not in sizes:
if chunks:
report.error(f"{base}index.tsv is missing, but there are {len(chunks)} chunks")
return
index = read_index(os.path.join(root, base + "index.tsv"), base + "index.tsv", report)
if index is None:
return
frames = [0, 0]
unnamed = sorted(set(chunks) - set(index))
if unnamed:
report.error(f"{base}: chunks index.tsv doesn't name: {listed(chunks[k] for k in unnamed)}")
last = [-math.inf, -math.inf]
for key in sorted(index):
if cancelled():
raise Cancelled()
c, chunk = key
rows = index[key]
frames[c] += len(rows)
name = f"{base}cam{c}/{chunk:06d}.zst.age"
if key not in chunks:
report.error(f"{name}: in index.tsv but missing")
continue
if [i for i, _ in rows] != list(range(len(rows))) or len(rows) > CHUNK_FRAMES_MAX:
report.error(f"{base}index.tsv: chunk {c}/{chunk:06d}'s frames aren't numbered 0 to {len(rows) - 1}")
times = [t for _, t in rows]
if any(b < a for a, b in zip(times, times[1:])) or times[0] < last[c]:
report.error(f"{base}index.tsv: camera {c}'s times go back at chunk {chunk:06d}")
last[c] = times[-1]
problem = age_shape(os.path.join(root, name), recipients)
if problem:
report.error(f"{name}: {problem}")
elif identity:
problem = decrypted_problem(os.path.join(root, name), identity, len(rows))
if problem:
report.error(f"{name}: {problem}")
step(sizes[name])
if entry is not None and isinstance(entry.get("frames"), list) and entry["frames"] != frames:
report.error(f"take {tid}: the manifest says {entry['frames']} frames, index.tsv has {frames}")
def decrypted_problem(path, identity, nframes):
sys.path.insert(0, HERE)
import eyerec # zstd, as the recorder has it
try:
with open(path, "rb") as f:
data = eyerec.decompress(age.decrypt_bytes(f.read(), identity))
except ValueError as e:
return f"doesn't decrypt: {e}"
except Exception as e:
return f"doesn't decompress: {e}"
if len(data) != nframes * FRAME:
return f"{len(data)} bytes, but index.tsv gives it {nframes} frames"
return None
# ---------------------------------------------------------------- the manifest
def check_manifest(m, report, root, shipped):
"""The manifest's keys and types. Returns ({take id: entry}, the recipients)."""
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-eyerec"):
report.warn(f"manifest: tool is {tool!r}")
need(m, "exported", str, "", report)
need(m, "bounty", str, "", report)
rid = need(m, "round_id", str, "", report)
if rid is not None and not ROUND_RE.match(rid):
report.error(f"manifest: round_id {rid!r} isn't a round id")
if rid and ROUND_RE.match(os.path.basename(root)) and os.path.basename(root) != rid:
report.warn(f"the folder is named {os.path.basename(root)}, the manifest's round is {rid}")
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")
recipients = []
enc = need(m, "encryption", dict, "", report)
if enc is not None:
if enc.get("format") != "age-encryption.org/v1":
report.error(f"manifest: encryption.format {enc.get('format')!r}")
r = enc.get("recipients")
if not isinstance(r, list) or not r or not all(isinstance(x, str) for x in r):
report.error("manifest: encryption.recipients isn't a list of keys")
else:
recipients = r
try:
for x in r:
age.parse_recipient(x)
except ValueError as e:
report.error(f"manifest: encryption.recipients: {e}")
if shipped is not None and sorted(r) != sorted(shipped):
report.error("manifest: encrypted to other keys than the dataset's (recipients.txt)")
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")
if 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) - PROFILE_KEYS
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:
for key, t in (("started", str), ("checklist", dict), ("takes", list), ("bounty", str)):
need(session, key, t, "session.", report)
if session.get("dry_run"):
report.error("this is a dry-run round: it has no real recordings")
if session.get("replay"):
report.error("this round was recorded from a replay, not the headset's cameras")
if session.get("status") not in ("done", None):
report.warn(f"the round's status is {session.get('status')!r}")
if "uploads" in session:
report.warn("manifest: session.uploads is included (earlier uploads' links)")
if "health" in session:
report.error("manifest: health answers outside health.json.age")
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")
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 (("group", str), ("status", str), ("frames", list), ("frames_deleted", list),
("duration_s", (int, float)), ("chunks", int)):
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}")
left = t.get("left_out")
if isinstance(left, dict) and any(left.values()):
report.warn(f"take {tid}: chunks the export left out: {left}")
return entries, recipients
def summarize(m):
"""What a pull request's description says about the export."""
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 {}
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)))
frames = sum(sum(f for f in t.get("frames") or [] if isinstance(f, int)) for t in takes
if isinstance(t.get("frames"), list))
enc = m.get("encryption") if isinstance(m.get("encryption"), dict) else {}
return {"round": m.get("round_id", ""), "bounty": m.get("bounty", ""), "contributor": m.get("contributor", ""),
"takes": len(takes), "frames": frames, "minutes": round(seconds / 60, 1),
"glasses": checklist.get("glasses", ""), "health": "health.json.age" in (enc.get("files") or []),
"consent_version": m.get("consent_version", ""), "tool": m.get("tool", "")}
# ---------------------------------------------------------------- all of it
def validate(root, progress=None, cancel=None, identity=None, recipients_path=RECIPIENTS):
"""Check the export at root. progress(fraction 0..1, text) is called as it goes; cancel()
(or cancel.is_set()) returning true raises Cancelled. identity: an "AGE-SECRET-KEY-1..."
string, to check inside the chunks. recipients_path: the keys the export must be encrypted
to (None: don't compare). 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
shipped = None
if recipients_path:
try:
shipped = age.read_recipients(recipients_path)
except (OSError, ValueError) as e:
report.error(f"the dataset's keys ({recipients_path}): {e}")
files = walk_files(root, report)
sizes = {rel: os.path.getsize(os.path.join(root, rel)) for rel in files}
report.bytes = sum(sizes.values())
total = max(1, 2 * report.bytes) # checksums, then the chunks again
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, recipients = check_manifest(manifest, report, root, shipped) if manifest is not None else ({}, [])
report.summary = summarize(manifest)
if "fit.json" in files:
fit = read_json_file(os.path.join(root, "fit.json"), "fit.json", report)
if fit is not None and not isinstance(fit, dict):
report.error("fit.json: not a JSON object")
else:
report.warn("no fit.json: the round's fit readings are missing")
enc_files = ((manifest or {}).get("encryption") or {}).get("files") if isinstance(manifest, dict) else None
listed_health = isinstance(enc_files, list) and "health.json.age" in enc_files
if ("health.json.age" in files) != listed_health:
report.error("health.json.age and the manifest's encryption.files don't agree")
if "health.json.age" in files and recipients:
problem = age_shape(os.path.join(root, "health.json.age"), recipients)
if problem:
report.error(f"health.json.age: {problem}")
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()
check_take(root, tid, entries.get(tid), sizes, recipients, identity, report,
lambda n, tid=tid: step(n, f"Checking {tid}"), cancelled)
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 an eye recorder export (an exports/<round>/ folder).")
ap.add_argument("dir")
ap.add_argument("--json", action="store_true", help="print the result as JSON")
ap.add_argument("--identity", help="an age identity file: also decrypt and check every chunk")
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) # stay out of VR's way
except OSError:
pass
identity = None
if a.identity:
with open(a.identity) as f:
identity = next((line.strip() for line in f if line.strip().startswith("AGE-SECRET-KEY-1")), None)
if not identity:
print(f"{a.identity}: no age identity in it", file=sys.stderr)
return 2
report = validate(a.dir, identity=identity)
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('round')}: {s.get('takes')} takes, {s.get('frames')} frames, {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())
+7 -3
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env bash
# Install, start, stop, or inspect the gaze service (ft-gazed) on the Frame.
# Usage: gaze/run.sh install|uninstall # user service, starts with SteamVR
# Usage: gaze/run.sh install|uninstall # user service, starts with SteamVR; install also keeps
# # SteamVR's eye cameras at 90 fps (gaze/eye-rate.py)
# gaze/run.sh start|stop|restart|status|log [lines]
set -euo pipefail
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
@@ -11,10 +12,13 @@ case ${1:-status} in
install)
[ "$FRAME_RELEASE" = 1 ] || "$root/gaze/build.sh"
fill_template "$root/gaze/$unit" | on_frame "mkdir -p ~/.config/systemd/user && cat > ~/.config/systemd/user/$unit"
on_frame "chmod +x gaze/ft-gazed gaze/ft-gazectl"
on_frame "chmod +x gaze/ft-gazed gaze/ft-gazectl gaze/eye-rate.py"
on_frame "/usr/bin/python3 gaze/eye-rate.py on" || true
"$frame" --host "set -e; systemctl --user daemon-reload; systemctl --user enable $unit
$(start_with_steamvr $unit)" ;;
uninstall) "$frame" --host "systemctl --user disable --now $unit 2>/dev/null; rm -f ~/.config/systemd/user/$unit; systemctl --user daemon-reload; echo removed" ;;
uninstall)
"$frame" --host "systemctl --user disable --now $unit 2>/dev/null; rm -f ~/.config/systemd/user/$unit; systemctl --user daemon-reload; echo removed"
on_frame "/usr/bin/python3 gaze/eye-rate.py off" || true ;;
start|stop|restart) "$frame" --host "systemctl --user $1 $unit; systemctl --user is-active $unit" ;;
status) "$frame" --host "systemctl --user is-active $unit" || true; on_frame "gaze/ft-gazectl status" || true ;;
log) "$frame" --host "journalctl --user -u $unit --no-pager -o cat -n ${2:-30}" ;;
+138
View File
@@ -0,0 +1,138 @@
#!/usr/bin/env python3
"""Offline test of gaze/eye-rate.py (SteamVR's eye cameras at 90 fps): on, off, and the camera
rate, with SteamVR off (its settings file) and on (vrcmd). HOME is a temporary folder and
vrcmd and pgrep are stand-ins, so the live SteamVR settings are never read or changed.
gaze/test/eye-rate-test.py
"""
import contextlib
import importlib.machinery
import importlib.util
import io
import json
import os
import tempfile
from pathlib import Path
HERE = os.path.dirname(os.path.abspath(__file__))
tmp = Path(tempfile.mkdtemp(prefix="ft-eye-rate-test-"))
os.environ["HOME"] = str(tmp) # eye-rate.py's paths come from it
loader = importlib.machinery.SourceFileLoader("eyerate", os.path.join(HERE, "..", "eye-rate.py"))
er = importlib.util.module_from_spec(importlib.util.spec_from_loader("eyerate", loader))
loader.exec_module(er)
assert str(er.HOME) == str(tmp), "eye-rate.py must take HOME from the environment"
failures = []
def check(what, got, want):
if got != want:
failures.append(what)
print(f"FAIL {what}: got {got!r}, want {want!r}", flush=True)
def main_with(*args):
"""eye-rate.py's main() with these arguments: (exit code, what it printed)."""
er.sys.argv = ["eye-rate.py", *args]
out = io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(out):
code = er.main()
return code, out.getvalue()
settings = er.STEAMVR_SETTINGS[0]
def file_value():
return json.loads(settings.read_text()).get("steamvr", {}).get("gazeDepEyeToHeadEnable")
# --- SteamVR off: the settings file ---
er.steamvr_up = lambda: False
settings.parent.mkdir(parents=True)
settings.write_text(json.dumps({"steamvr": {"analogGain": 0.25}, "dashboard": {"x": 1}}, indent=3))
check("off by default (not in the file)", er.get(), None)
code, _ = main_with("on")
check("on: exit 0", code, 0)
check("on: written to the file", file_value(), True)
check("on: SteamVR's other settings kept", json.loads(settings.read_text())["steamvr"]["analogGain"], 0.25)
check("on: other sections kept", json.loads(settings.read_text())["dashboard"], {"x": 1})
check("on: marked as Frametop's", er.MARK.exists(), True)
code, out = main_with("on")
check("on again: says it's on already", "already" in out, True)
code, _ = main_with("off")
check("off: written to the file", file_value(), False)
check("off: mark gone", er.MARK.exists(), False)
# Someone turned it on themselves: off leaves it.
settings.write_text(json.dumps({"steamvr": {"gazeDepEyeToHeadEnable": True}}))
code, out = main_with("on")
check("on, set by the user: no mark", er.MARK.exists(), False)
code, out = main_with("off")
check("off, set by the user: left on", file_value(), True)
check("off, set by the user: says so", "left as they are" in out, True)
# No settings file yet (SteamVR never ran): on makes one.
settings.unlink()
code, _ = main_with("on")
check("no file: on makes it", file_value(), True)
main_with("off")
# A broken file isn't overwritten.
settings.write_text("{not json")
code, _ = main_with("on")
check("broken file: on fails", code, 1)
check("broken file: left alone", settings.read_text(), "{not json")
check("broken file: no mark", er.MARK.exists(), False)
settings.unlink()
# --- SteamVR on: vrcmd ---
live = {"value": False}
calls = []
def fake_vrcmd(*args):
calls.append(args)
if args[0] == "--settings-bool":
return f"steamvr.gazeDepEyeToHeadEnable={'true' if live['value'] else 'false'}\n"
if args[0] == "--set-settings-bool":
live["value"] = args[2] == "1" # as vrcmd does: "true" would read as 0
return f"steamvr.gazeDepEyeToHeadEnable={args[2]}\n"
return ""
er.steamvr_up = lambda: True
er.vrcmd = fake_vrcmd
code, _ = main_with("on")
check("SteamVR on: set through vrcmd", live["value"], True)
check("SteamVR on: sets 1, never 'true'", [c for c in calls if c[0] == "--set-settings-bool"][-1][2], "1")
check("SteamVR on: the file isn't touched", settings.exists(), False)
check("SteamVR on: marked", er.MARK.exists(), True)
code, _ = main_with("off")
check("SteamVR on: off through vrcmd", live["value"], False)
check("SteamVR on: mark gone", er.MARK.exists(), False)
# vrcmd that doesn't take it: on fails, no mark.
er.vrcmd = lambda *args: "" if args[0] == "--set-settings-bool" else "steamvr.gazeDepEyeToHeadEnable=false\n"
code, _ = main_with("on")
check("vrcmd didn't take it: on fails", code, 1)
check("vrcmd didn't take it: no mark", er.MARK.exists(), False)
# --- The camera rate, from eyetracking.txt ---
check("no eyetracking.txt: unknown", er.camera_rate(), None)
er.EYE_LOG.parent.mkdir(parents=True)
head = "Sat Oct 10 2026 22:35:43.000000 [Info] - "
er.EYE_LOG.write_text("\n".join([
head + "eyetracking 2.18.2 startup with PID=1, config=x",
head + "CStereoAdspCams: Set framerate 15.000000",
head + "Eye tracking shutting down",
head + "eyetracking 2.18.2 startup with PID=2, config=x",
head + "Eye tracking started"]) + "\n")
check("no rate set since the last start: 90", er.camera_rate(), 90.0)
with er.EYE_LOG.open("a") as f:
f.write(head + "CStereoAdspCams: Set framerate 15.000000\n")
check("15 set since the last start", er.camera_rate(), 15.0)
print("eye-rate-test:", "FAILED " + ", ".join(failures) if failures else "all passed")
raise SystemExit(1 if failures else 0)
+60 -8
View File
@@ -6,7 +6,9 @@ its dots. Until 2026-10-05 it couldn't: a fresh install that chose our tracker n
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,
panel (a stand-in process). The fake ft-eyes also answers late or not at all, as a slow one
does: the service must keep running meanwhile (until 2026-10-09 it waited, up to 3 s a dot and
10 s for the fit, and the helper's 3 s panel lease ran out). 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
@@ -43,7 +45,8 @@ 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
gazed.TrackedEye = lambda: lambda now=None: None # both eyes, whatever SteamVR's settings say
DOTS = 4
real_dots = gazecheck.check_dots
gazecheck.check_dots = lambda kind, own: real_dots(kind, own)[:DOTS] # a short calibration
logs = []
@@ -92,8 +95,10 @@ 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}
# The fake ft-eyes: uncalibrated until calib-fit. "fail" answers the next calib-point with that;
# "delay" holds calib-point's and calib-fit's answers that many seconds; "drop" leaves the next
# calib-point unanswered.
eyes_state = {"cal": None, "points": [], "fail": None, "delay": 0.0, "drop": False}
eyes = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
eyes.bind(gazed.EYES_SOCKET)
eyes.settimeout(0.2)
@@ -116,19 +121,31 @@ def eyes_answer():
reply = "ok"
elif w[0] == "calib-point":
eyes_state["points"].append(tuple(map(float, w[1:5])))
if eyes_state["drop"]:
eyes_state["drop"] = False
continue
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:
if addr and w[0] in ("calib-point", "calib-fit") and eyes_state["delay"]:
threading.Timer(eyes_state["delay"], send_late, (reply, addr)).start()
elif addr:
eyes.sendto(reply.encode(), addr)
def send_late(reply, addr):
try:
eyes.sendto(reply.encode(), addr)
except OSError:
pass # the service gave up on it
threading.Thread(target=eyes_answer, daemon=True).start()
helper_state = {"reply": "ok off worn", "heard": []}
helper_state = {"reply": "ok off worn", "heard": [], "calpanel": []} # calpanel: when "calpanel 1" came
helper = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
helper.bind(gazed.POINTER)
helper.settimeout(0.2)
@@ -146,6 +163,8 @@ def helper_answer():
helper.sendto(helper_state["reply"].encode(), addr)
else:
helper_state["heard"].append(data.decode())
if data == b"calpanel 1":
helper_state["calpanel"].append(time.monotonic())
threading.Thread(target=helper_answer, daemon=True).start()
@@ -225,10 +244,43 @@ 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)
# A slow ft-eyes (2.5 s): the service goes on meanwhile, and a second click is ignored.
eyes_state["delay"] = 2.5
wait(lambda: check_state().get("i") == 2 and not check_state().get("done_at"), 3)
time.sleep(gazecheck.CHECK_SETTLE + gazecheck.CHECK_WINDOW + 0.1)
before = len(eyes_state["points"])
ask("calaccept")
check("dot 3, ft-eyes slow: the service waits for it", wait(lambda: svc.checks.asking is not None, 2), True)
t = time.monotonic()
ask("status")
check("the service still answers meanwhile", time.monotonic() - t < 0.5, True)
ask("calaccept")
check("dot 3: taken once ft-eyes answers", wait(lambda: check_state().get("captured") == 3, 4), True)
check("the helper's panel lease was renewed while ft-eyes took its time",
sum(t < at < t + eyes_state["delay"] for at in helper_state["calpanel"]) >= 2, True)
check("and the calibration is still open (a blocked service took that as the headset off)",
check_state().get("kind"), "full")
check("the second click asked ft-eyes nothing", len(eyes_state["points"]), before + 1)
eyes_state["delay"] = 0.0
# No answer: the dot isn't taken, after calib-point's 3 s.
eyes_state["drop"] = True
wait(lambda: check_state().get("i") == 3 and not check_state().get("done_at"), 3)
time.sleep(gazecheck.CHECK_SETTLE + gazecheck.CHECK_WINDOW + 0.1)
ask("calaccept")
check("dot 4, no answer from ft-eyes: not taken, and the panel says so",
wait(lambda: "didn't answer" in check_state().get("note", ""), 5), True)
eyes_state["delay"] = 2.5 # the fit too
check("dot 4, second try: taken", take_dot(3) or wait(lambda: check_state().get("captured") == 4, 4), True)
check("while ours fits, the panel stays", wait(lambda: check_state().get("fitting") is True, 3), True)
ask("calquit")
check("and a right click doesn't close it", check_state().get("kind"), "full")
check("all dots: ours fits its calibration (calib-fit)",
wait(lambda: eyes_state["cal"] is not None and not svc.checks.check, 4), True)
wait(lambda: eyes_state["cal"] is not None and not svc.checks.check, 5), True)
gaps = [b - a for a, b in zip(helper_state["calpanel"], helper_state["calpanel"][1:])]
check("the helper's panel lease (3 s) never ran out", bool(gaps) and max(gaps) < 3.0, 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)
+247
View File
@@ -0,0 +1,247 @@
#!/usr/bin/env python3
"""Offline test of the fit coach in the headset fit check (gaze/gazecheck.py, "fit"): with
SteamVR's tracker in use, the check keeps ft-eyes running (the lease), asks it for the last
second of pupil finds ("fit"), judges them only while the gaze is straight ahead, and puts the
coach's hint first in the panel's hints.
The harness is first-calibration-test.py's: ft-gazed's Service with its sockets renamed, HOME in
a temp folder, a fake pointer helper, a fake ft-gaze (its gaze from a file the test writes), a
fake ft-eyes control socket (its finds from the shipped reference, offset as the test says),
and the panel's commands recorded instead of sent. Safe next to the live gaze service.
gaze/test/fit-coach-check-test.py
"""
import os
import tempfile
HOME = tempfile.mkdtemp(prefix="ft-gaze-fit-coach-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 fitcoach # noqa: E402
import gazecheck # noqa: E402 (the module ft-gazed imported)
tag = f"ft_gaze_fit_coach_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: ("steam", "auto", "auto", 55.0) # SteamVR's tracker in use
gazed.own_installed = lambda: True
gazed.TrackedEye = lambda: lambda now=None: None
logs = []
gazed.log = gazecheck.log = lambda msg: logs.append(msg)
# The fake ft-gaze: 90 samples a second, SteamVR sees both eyes, its gaze from LOOK.
LOOK = os.path.join(HOME, "look.json")
FAKE = os.path.join(HOME, "ft-gaze")
def look(yaw, pitch):
with open(LOOK + ".new", "w") as f:
json.dump([yaw, pitch], f)
os.replace(LOOK + ".new", LOOK)
look(0.0, 0.0)
with open(FAKE, "w") as f:
f.write(f'''import json, os, select, sys, time
while True:
if select.select([sys.stdin], [], [], 1 / 90)[0]:
if not os.read(0, 4096):
break
try:
hy, hp = json.load(open({LOOK!r}))
except (OSError, ValueError):
continue
print(json.dumps({{"t": time.monotonic(), "src": {{"mmap1": {{"hy": hy, "hp": hp, "unc": [0.001, 0.001],
"open": [0.8, 0.8]}}}}}}), flush=True)
''')
SLEEPER = [sys.executable, "-c", "import sys; sys.stdin.read()"] # quits when its stdin closes
started = {"eyes": 0}
def start_helper(self):
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):
started["eyes"] += 1
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")
panel = []
gazed.Service.start_helper = start_helper
gazed.Service.start_eyes = start_eyes
gazecheck.Checks.start_panel = start_panel
gazecheck.Checks.to_panel = lambda self, command: panel.append(command)
# The fake ft-eyes: "fit" answers with finds where the shipped reference puts eyes offset by
# eyes_state["offset"] (yaw, pitch degrees, both eyes alike).
REF = fitcoach.Reference.load()
eyes_state = {"offset": (0.0, 0.0), "asked": 0}
eyes = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
eyes.bind(gazed.EYES_SOCKET)
eyes.settimeout(0.2)
def finds():
yaw, pitch = eyes_state["offset"]
out = {}
for cam in (0, 1):
(cx, cy), ((a, b), (c, d)) = REF.eyes[cam]["centre"], REF.eyes[cam]["jacobian"]
out[cam] = {"n": 90, "finds": 90, "found": 1.0, "x": cx + a * yaw + b * pitch, "y": cy + c * yaw + d * pitch,
"a": 28.0, "spacing": 15.0, "extra": 0.0}
return out
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": None, "calibrating": False, "dots": 0,
"eyes": {"right": {"reseat": False}, "left": {"reseat": False}}})
elif w[0] == "fit":
eyes_state["asked"] += 1
reply = json.dumps(finds())
else:
reply = f"fail unknown command {w[0]}"
if addr:
try:
eyes.sendto(reply.encode(), addr)
except OSError:
pass # the service gave up on it (as ft-eyes' serve() does)
threading.Thread(target=eyes_answer, daemon=True).start()
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(b"ok off worn", addr)
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 coach_line():
"""The first hint line the panel got last, if it's the coach's."""
for cmd in reversed(panel):
if cmd.startswith("hints "):
first = cmd[len("hints "):].split("|")[0]
return first if first.startswith("Headset position") else None
return None
ask("wake 60")
check("the tracker sends", wait(lambda: time.monotonic() - svc.checks.sample_at < 1, 6), True)
check("SteamVR's tracker in use: ft-eyes isn't running", svc.eyes_proc is None, True)
check("fitcheck is taken", ask("fitcheck").startswith("ok"), True)
check("the fit check opens", wait(lambda: (svc.checks.check or {}).get("kind") == "fit", 6), True)
check("the fit check starts ft-eyes for the coach", wait(lambda: svc.eyes_proc is not None, 3), True)
check("and asks it for finds", wait(lambda: eyes_state["asked"] > 0, 3), True)
check("looking ahead, well fitted: good",
wait(lambda: (coach_line() or "").startswith("Headset position: good."), 4), True)
check("marked a first guess (the reference is from one face)", "first guess" in (coach_line() or ""), True)
eyes_state["offset"] = (0.0, 12.0) # both eyes appear to look up: the headset is low
check("the headset low: push it up",
wait(lambda: "Push the headset up" in (coach_line() or ""), 4), True)
check("it's the first hint line", (coach_line() or "").startswith("Headset position: Push"), True)
look(25.0, 0.0) # looking away: the pupils move with the gaze, so no new reading
check("looking away: the last centred reading, marked so",
wait(lambda: "when you last looked straight ahead" in (coach_line() or ""), 4), True)
eyes_state["offset"] = (0.0, 0.0)
time.sleep(1.5)
check("and it isn't judged meanwhile", "Push the headset up" in (coach_line() or ""), True)
look(0.0, 0.0)
check("looking ahead again: judged again", wait(lambda: (coach_line() or "").startswith("Headset position: good."), 4), True)
ask("calquit")
check("closing logs the last reading", wait(lambda: any(m.startswith("fit coach, last reading: ok") for m in logs), 2), True)
check("the check closed", wait(lambda: svc.checks.check is None, 2), True)
check("ft-eyes stops once its lease runs out",
wait(lambda: svc.eyes_proc is None, gazecheck.COACH_LEASE + 4), True)
print("all passed" if not failures else f"{len(failures)} failed: {failures}", flush=True)
shutil.rmtree(HOME, ignore_errors=True)
os._exit(1 if failures else 0)
+316
View File
@@ -0,0 +1,316 @@
#!/usr/bin/env python3
"""Offline test of the fit watch (gaze/gazecheck.py, GAZE_FIT_WATCH): the fit check keeping a
good fit as yours, the put-on check in the quick check that opens when the headset goes on
(holds the dot, says what to move, lets go once it's back or on a click), and the slip note
with our tracker (ft-eyes' glint jump past the threshold for SLIP_HOLD; gone with the slip;
not again within NOTE_COOLDOWN).
fit-coach-check-test.py's harness: ft-gazed's Service with its sockets renamed, HOME in a temp
folder, a fake pointer helper, a fake ft-gaze, a fake ft-eyes control socket (its finds from
the shipped reference, offset as the test says, and its status with the glint jump), and the
panel's commands recorded instead of sent. Safe next to the live gaze service.
gaze/test/fit-watch-test.py
"""
import os
import tempfile
HOME = tempfile.mkdtemp(prefix="ft-gaze-fit-watch-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 fitcoach # noqa: E402
import gazecheck # noqa: E402 (the module ft-gazed imported)
tag = f"ft_gaze_fit_watch_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"
SETTINGS = {"tracker": "steam"} # SteamVR's tracker in use first, then ours
gazed.read_settings = lambda: (SETTINGS["tracker"], "auto", "auto", 55.0)
gazed.own_installed = lambda: True
gazed.TrackedEye = lambda: lambda now=None: None
logs = []
gazed.log = gazecheck.log = lambda msg: logs.append(msg)
# The fake ft-gaze: 90 samples a second, SteamVR sees both eyes, its gaze from LOOK.
LOOK = os.path.join(HOME, "look.json")
FAKE = os.path.join(HOME, "ft-gaze")
def look(yaw, pitch):
with open(LOOK + ".new", "w") as f:
json.dump([yaw, pitch], f)
os.replace(LOOK + ".new", LOOK)
look(0.0, 0.0)
with open(FAKE, "w") as f:
f.write(f'''import json, os, select, sys, time
while True:
if select.select([sys.stdin], [], [], 1 / 90)[0]:
if not os.read(0, 4096):
break
try:
hy, hp = json.load(open({LOOK!r}))
except (OSError, ValueError):
continue
print(json.dumps({{"t": time.monotonic(), "src": {{"mmap1": {{"hy": hy, "hp": hp, "unc": [0.001, 0.001],
"open": [0.8, 0.8]}}}}}}), flush=True)
''')
SLEEPER = [sys.executable, "-c", "import sys; sys.stdin.read()"] # quits when its stdin closes
started = {"eyes": 0}
def start_helper(self):
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):
started["eyes"] += 1
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")
panel = []
gazed.Service.start_helper = start_helper
gazed.Service.start_eyes = start_eyes
gazecheck.Checks.start_panel = start_panel
gazecheck.Checks.to_panel = lambda self, command: panel.append(command)
# The fake ft-eyes: "fit" answers with finds where the shipped reference puts eyes offset by
# eyes_state["offset"] (yaw, pitch degrees, both eyes alike).
REF = fitcoach.Reference.load()
eyes_state = {"offset": (0.0, 0.0), "jump": (0.0, 0.0), "asked": 0}
eyes = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
eyes.bind(gazed.EYES_SOCKET)
eyes.settimeout(0.2)
def finds():
yaw, pitch = eyes_state["offset"]
out = {}
for cam in (0, 1):
(cx, cy), ((a, b), (c, d)) = REF.eyes[cam]["centre"], REF.eyes[cam]["jacobian"]
out[cam] = {"n": 90, "finds": 90, "found": 1.0, "x": cx + a * yaw + b * pitch, "y": cy + c * yaw + d * pitch,
"a": 28.0, "spacing": 15.0, "extra": 0.0}
return out
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":
yaw, pitch = eyes_state["jump"] # the slip, as both pupils' move in degrees
jump = {}
for cam, name in ((0, "right"), (1, "left")):
(a, b), (c, d) = REF.eyes[cam]["jacobian"]
jump[name] = {"reseat": False, "jump": bool(yaw or pitch),
"jump_px": [a * yaw + b * pitch, c * yaw + d * pitch]}
reply = json.dumps({"calibration": {"dots": 27}, "calibrating": False, "dots": 27, "eyes": jump})
elif w[0] == "fit":
eyes_state["asked"] += 1
reply = json.dumps(finds())
else:
reply = f"fail unknown command {w[0]}"
if addr:
try:
eyes.sendto(reply.encode(), addr)
except OSError:
pass # the service gave up on it (as ft-eyes' serve() does)
threading.Thread(target=eyes_answer, daemon=True).start()
HELPER = {"gaze": False}
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(b"ok on worn" if HELPER["gaze"] else b"ok off worn", addr)
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 since(n):
"""The panel's commands from n on."""
return panel[n:]
def quick(label):
"""Opens the quick check as the headset going on does; returns where its panel commands start."""
n = len(panel)
check(label, svc.checks.start("quick", gazecheck.PUTON_REASON), "ok")
return n
def puton():
return ((svc.checks.check or {}).get("puton") or {}).get("state")
def closed_with_capture(seconds=8):
return wait(lambda: svc.checks.check is None and any(m.startswith("quick check done") for m in logs[mark:]), seconds)
ask("wake 60")
check("the tracker sends", wait(lambda: time.monotonic() - svc.checks.sample_at < 1, 6), True)
check("the eyes count as seen", wait(lambda: svc.checks.eyes_seen(), 3), True)
# The fit watch off (the default): the quick check is as it was.
mark = len(logs)
quick("fit watch off: a quick check opens")
check(" without a put-on check", puton(), None)
check(" and takes its dot", closed_with_capture(), True)
# A good fit in the fit check is kept as yours.
check("no saved fit yet", os.path.exists(fitcoach.BASELINE), False)
check("fitcheck is taken", ask("fitcheck").startswith("ok"), True)
check("the fit check opens", wait(lambda: (svc.checks.check or {}).get("kind") == "fit", 6), True)
check("it reads a good fit", wait(lambda: ((svc.checks.check or {}).get("coach") or {}).get("good") is not None, 6), True)
ask("calquit")
check("closing it saves the fit as yours", wait(lambda: os.path.exists(fitcoach.BASELINE), 2), True)
check("with both eyes", sorted(json.load(open(fitcoach.BASELINE))["eyes"]), ["0", "1"])
gazed.CONF.parent.mkdir(parents=True, exist_ok=True)
with open(gazed.CONF, "w") as f:
f.write("GAZE_FIT_WATCH=1\n")
# Put on as saved: the dot is held for the reading, then taken.
mark = len(logs)
quick("put on as saved: the quick check opens")
check(" reading the fit first", puton(), "reading")
check(" sits as saved", wait(lambda: any("sits as your saved fit" in m for m in logs[mark:]), 5), True)
check(" then the dot is taken", closed_with_capture(), True)
# Put on low: it says to push it up, holds the dot past the quick check's timeout, lets go once back.
eyes_state["offset"] = (0.0, 12.0)
mark = len(logs)
n = quick("put on low: the quick check opens")
check(" the headset moved", wait(lambda: puton() == "moved", 5), True)
check(" the panel widens", "show five" in since(n), True)
check(" and says to push it up", wait(lambda: any(c.startswith("text Push the headset up") for c in since(n)), 2), True)
time.sleep(gazecheck.QUICK_TIMEOUT + 1)
check(" the dot waits past the quick check's timeout", (svc.checks.check or {}).get("captured"), 0)
eyes_state["offset"] = (0.0, 0.0)
check(" pushed back: let go", wait(lambda: any("is back as your saved fit" in m for m in logs[mark:]), 5), True)
check(" saying so", "note Good: it's back where it was" in since(n), True)
check(" then the dot is taken", closed_with_capture(), True)
# Put on low, then a click: taken as it sits.
eyes_state["offset"] = (0.0, 12.0)
mark = len(logs)
quick("put on low again")
check(" the headset moved", wait(lambda: puton() == "moved", 5), True)
ask("calaccept")
check(" a click lets go", wait(lambda: any("a click" in m for m in logs[mark:]), 3), True)
check(" and takes the dot", closed_with_capture(), True)
eyes_state["offset"] = (0.0, 0.0)
# The slip note: our tracker, gaze mode on.
SETTINGS["tracker"] = "own"
HELPER["gaze"] = True
with open(gazed.CONF, "w") as f:
f.write("GAZE_FIT_WATCH=1\n# our tracker now\n")
check("our tracker in use", wait(lambda: svc.kind == "own" and svc.eyes_proc is not None, 6), True)
check("gaze mode on", wait(lambda: svc.checks.gaze_on is True, 4), True)
check("ft-eyes' status comes", wait(lambda: time.monotonic() - svc.own_at < 2, 4), True)
n = len(panel)
time.sleep(2)
check("no slip: no note", "show note" in since(n), False)
eyes_state["jump"] = (0.0, -12.0) # the pupils dropped: the headset rode up
start = time.monotonic()
check("a slip: the note", wait(lambda: "show note" in since(n), gazecheck.SLIP_HOLD + 4), True)
check(" not before SLIP_HOLD", time.monotonic() - start >= gazecheck.SLIP_HOLD, True)
check(" saying so", "title Your headset slipped" in since(n), True)
check(" and which way", any(c.startswith("text Let the headset down") for c in since(n)), True)
check(" no pointer hiding for it", any(c == "calpanel 1" for c in since(n)), False)
n = len(panel)
eyes_state["jump"] = (0.0, 0.0)
check("the slip gone: the note goes", wait(lambda: "hide" in since(n), 4), True)
n = len(panel)
eyes_state["jump"] = (0.0, -12.0)
time.sleep(gazecheck.SLIP_HOLD + 3)
check("again within NOTE_COOLDOWN: no note", "show note" in since(n), False)
eyes_state["jump"] = (0.0, 0.0)
print("all passed" if not failures else f"{len(failures)} failed: {failures}", flush=True)
shutil.rmtree(HOME, ignore_errors=True)
os._exit(1 if failures else 0)
+238
View File
@@ -0,0 +1,238 @@
#!/usr/bin/env python3
"""The fit coach (gaze/fitcoach.py) on made-up readings: the reference fit, which way each hint
points with both cameras' orientations, the state's hysteresis, lost eyes, and a baseline.
python3 gaze/test/fitcoach-test.py
"""
import math
import os
import random
import sys
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(HERE))
import fitcoach # noqa: E402
# About the maintainer's headset's (gaze/fit-reference.json): camera 1's image is turned 180
# degrees from camera 0's, so its signs are the other way.
J = {0: [[1.27, -0.42], [-0.48, -1.34]], 1: [[-1.34, -0.53], [-0.48, 1.48]]}
CENTRE = {0: [341.0, 221.4], 1: [334.7, 173.5]}
def ref(follow=None, faces=1):
return fitcoach.Reference({c: {"centre": CENTRE[c], "jacobian": J[c]} for c in (0, 1)}, ipd=0.065,
faces=faces, cameras_follow_lenses=follow)
def pupil(cam, yaw, pitch, centre=None):
"""Where camera cam sees the pupil when the eye appears to look (yaw, pitch) degrees."""
cx, cy = centre or CENTRE[cam]
(a, b), (c, d) = J[cam]
return cx + a * yaw + b * pitch, cy + c * yaw + d * pitch
def summary(right=(0, 0), left=(0, 0), found=(1.0, 1.0), spacing=(14.0, 16.0), extra=(0.0, 0.0)):
out = {}
for cam, (yaw, pitch) in ((0, right), (1, left)):
x, y = pupil(cam, yaw, pitch)
out[cam] = {"n": 90, "finds": int(90 * found[cam]), "found": found[cam], "x": x, "y": y, "a": 28.0,
"spacing": spacing[cam], "extra": extra[cam]}
return out
def keys(reading):
return [h["key"] for h in reading["hints"]]
class ReferenceTest(unittest.TestCase):
def test_fit_recovers_both_orientations(self):
rng = random.Random(1)
rows = []
for made in ("a", "b"):
for _ in range(27):
yaw, pitch = rng.uniform(-20, 20), rng.uniform(-15, 15)
rows.append({"made": made, "truth": [yaw, pitch],
"eye": {str(c): {"pupil": [v + rng.gauss(0, 0.5) for v in pupil(c, yaw, pitch)]} for c in (0, 1)}})
# A third calibration that fits badly is left out.
for _ in range(27):
yaw, pitch = rng.uniform(-20, 20), rng.uniform(-15, 15)
rows.append({"made": "bad", "truth": [yaw, pitch],
"eye": {str(c): {"pupil": [v + rng.gauss(0, 15) for v in pupil(c, yaw, pitch)]} for c in (0, 1)}})
r = fitcoach.Reference.from_dots(rows)
for c in (0, 1):
self.assertEqual(r.eyes[c]["fits"], 2)
for i in range(2):
self.assertAlmostEqual(r.eyes[c]["centre"][i], CENTRE[c][i], delta=0.5)
for j in range(2):
self.assertAlmostEqual(r.eyes[c]["jacobian"][i][j], J[c][i][j], delta=0.05)
# degrees() undoes the Jacobian.
x, y = pupil(1, 7.0, -3.0)
yaw, pitch = r.degrees(1, x - r.eyes[1]["centre"][0], y - r.eyes[1]["centre"][1])
self.assertAlmostEqual(yaw, 7.0, delta=0.2)
self.assertAlmostEqual(pitch, -3.0, delta=0.2)
def test_json_round_trip(self):
r = ref(follow=True, faces=4)
back = fitcoach.Reference.from_json(r.to_json())
self.assertEqual(back.eyes[1]["jacobian"], J[1])
self.assertTrue(back.cameras_follow_lenses)
self.assertFalse(back.provisional)
self.assertTrue(ref().provisional)
def test_the_shipped_reference_loads(self):
r = fitcoach.Reference.load()
self.assertIsNotNone(r, fitcoach.REFERENCE)
self.assertEqual(sorted(r.eyes), [0, 1])
self.assertTrue(r.provisional)
class AssessTest(unittest.TestCase):
def test_centred_is_ok(self):
r = fitcoach.assess(summary(), ref())
self.assertEqual(r["state"], "ok")
self.assertEqual(r["hints"], [])
self.assertTrue(r["provisional"])
def test_eyes_high_means_push_up(self):
r = fitcoach.assess(summary(right=(0, 12), left=(0, 12)), ref())
self.assertEqual(r["state"], "adjust")
self.assertEqual(keys(r), ["up"])
r = fitcoach.assess(summary(right=(0, -12), left=(0, -12)), ref())
self.assertEqual(keys(r), ["down"])
def test_eyes_left_means_slide_left(self):
r = fitcoach.assess(summary(right=(11, 0), left=(11, 0)), ref())
self.assertEqual(keys(r), ["left"])
self.assertAlmostEqual(r["terms"]["left"], 11, delta=0.1)
r = fitcoach.assess(summary(right=(-11, 0), left=(-11, 0)), ref())
self.assertEqual(keys(r), ["right"])
def test_ipd_only_advised_once_the_cameras_are_known_to_follow_the_lenses(self):
apart = summary(right=(-10, 0), left=(10, 0)) # each eye outward of its lens
r = fitcoach.assess(apart, ref(follow=None))
self.assertAlmostEqual(r["terms"]["ipd"], 10, delta=0.1)
self.assertNotIn("ipd-wider", keys(r))
self.assertFalse(r["ipd_advice"])
self.assertEqual(r["state"], "ok", "the common terms are centred")
r = fitcoach.assess(apart, ref(follow=True))
self.assertEqual(keys(r), ["ipd-wider"])
self.assertEqual(r["state"], "adjust")
r = fitcoach.assess(summary(right=(10, 0), left=(-10, 0)), ref(follow=True))
self.assertEqual(keys(r), ["ipd-narrower"])
def test_tilt(self):
r = fitcoach.assess(summary(right=(0, -5), left=(0, 5)), ref())
self.assertEqual(keys(r), ["tilt-left-up"])
r = fitcoach.assess(summary(right=(0, 5), left=(0, -5)), ref())
self.assertEqual(keys(r), ["tilt-right-up"])
def test_hysteresis_between_ok_and_adjust(self):
mid = summary(right=(0, 6.5), left=(0, 6.5))
self.assertEqual(fitcoach.assess(mid, ref(), previous={"state": "ok"})["state"], "ok")
self.assertEqual(fitcoach.assess(mid, ref(), previous={"state": "adjust"})["state"], "adjust")
self.assertEqual(fitcoach.assess(mid, ref())["state"], "adjust")
self.assertEqual(fitcoach.assess(mid, ref(), previous={"state": "lost"})["state"], "adjust")
# Adjust without a term past ADJUST_DEG: the biggest one's hint, so there's something to do.
self.assertEqual(keys(fitcoach.assess(mid, ref())), ["up"])
self.assertEqual(keys(fitcoach.assess(mid, ref(), previous={"state": "ok"})), [])
def test_a_lost_eye_comes_first(self):
r = fitcoach.assess(summary(right=(0, 12), left=(0, 12), found=(1.0, 0.3)), ref())
self.assertEqual(r["state"], "lost")
self.assertEqual(keys(r)[0], "lost")
self.assertIn("left eye", r["hints"][0]["text"])
def test_waiting_without_frames(self):
r = fitcoach.assess({0: {"n": 0}, 1: {"n": 0}}, ref())
self.assertEqual(r["state"], "waiting")
self.assertEqual(fitcoach.assess({}, ref())["state"], "waiting")
def test_reflections(self):
r = fitcoach.assess(summary(extra=(0.0, 0.8)), ref())
self.assertEqual(keys(r), ["reflections"])
self.assertIn("left", r["hints"][0]["text"])
class BaselineTest(unittest.TestCase):
def test_against_the_baseline(self):
good = summary(right=(4, -3), left=(4, -3)) # this face's good fit isn't the reference's
base = fitcoach.make_baseline(good, ipd=0.065)
r = fitcoach.assess(good, ref(), ipd=0.065, baseline=base)
self.assertEqual((r["state"], r["against"]), ("ok", "baseline"))
self.assertFalse(fitcoach.moved(r))
# Back on, 7 degrees lower on the face: moved, and which way to put it back.
slipped = summary(right=(4, 4), left=(4, 4))
r = fitcoach.assess(slipped, ref(), ipd=0.065, baseline=base)
self.assertTrue(fitcoach.moved(r))
self.assertAlmostEqual(r["terms"]["up"], 7, delta=0.1)
def test_eye_relief_and_ipd_change(self):
base = fitcoach.make_baseline(summary(), ipd=0.065)
near = summary(spacing=(14.0 * 1.12, 16.0 * 1.12))
r = fitcoach.assess(near, ref(), ipd=0.0665, baseline=base)
self.assertEqual(keys(r), ["ipd-changed", "nearer"])
self.assertIn("65.0 mm, now 66.5 mm", r["hints"][0]["text"])
self.assertTrue(fitcoach.moved(r))
far = summary(spacing=(14.0 * 0.9, 16.0 * 0.9))
self.assertEqual(keys(fitcoach.assess(far, ref(), ipd=0.065, baseline=base)), ["further"])
class ObservationsTest(unittest.TestCase):
def test_window_and_medians(self):
obs = fitcoach.Observations(window=1.0)
# A pair 14 px apart and four stray ones: MANY_GLINTS.
glints = [(300.0, 200.0), (301.0, 214.0), (250.0, 120.0), (260.0, 120.0), (270.0, 120.0), (280.0, 120.0)]
for i in range(60):
t = i / 30
obs.add(0, t, {"x": 300 + (i % 3), "y": 210.0, "a": 25.0, "glints": glints})
obs.add(1, t, None if i % 2 else {"x": 320.0, "y": 170.0, "a": 30.0, "glints": []})
s = obs.summary()
self.assertEqual(s[0]["n"], 31) # the last second only
self.assertEqual(s[0]["x"], 301)
self.assertAlmostEqual(s[0]["spacing"], math.hypot(1, 14), places=5)
self.assertEqual(s[0]["extra"], 1.0)
self.assertAlmostEqual(s[1]["found"], 15 / 31, places=3)
self.assertIsNone(s[1]["spacing"])
def test_glint_spacing_matches_eyes_pupil(self):
try:
sys.path.insert(0, os.path.join(os.path.dirname(HERE), "tracker"))
import eyes_pupil
except ImportError:
self.skipTest("no numpy or OpenCV here")
rng = random.Random(3)
for _ in range(200):
p = {"x": 300.0, "y": 200.0, "glints": [(rng.uniform(270, 330), rng.uniform(170, 230)) for _ in range(rng.randint(0, 5))]}
pair = eyes_pupil.glint_pair(p)
want = None if pair is None else math.hypot(pair[1][0] - pair[0][0], pair[1][1] - pair[0][1])
got = fitcoach.glint_spacing(p)
if want is None:
self.assertIsNone(got)
else:
self.assertAlmostEqual(got, want, places=6)
class SlipTest(unittest.TestCase):
"""The slip notice's reading: ft-eyes' glint jumps (pupil px) as position terms and a hint."""
def jumps(self, yaw, pitch):
# Both pupils moved as if the eyes looked (yaw, pitch): each camera's own direction.
return {c: (pupil(c, yaw, pitch)[0] - CENTRE[c][0], pupil(c, yaw, pitch)[1] - CENTRE[c][1]) for c in (0, 1)}
def test_terms(self):
t = fitcoach.slip_terms(self.jumps(2.0, 9.0), ref())
self.assertAlmostEqual(t["up"], 9.0, places=6)
self.assertAlmostEqual(t["left"], 2.0, places=6)
self.assertEqual(fitcoach.slip_terms({}, ref()), {})
self.assertEqual(fitcoach.slip_terms({0: (3.0, 4.0)}, None), {})
def test_hint(self):
self.assertEqual(fitcoach.position_hint(fitcoach.slip_terms(self.jumps(0, 9.0), ref()))["key"], "up")
self.assertEqual(fitcoach.position_hint(fitcoach.slip_terms(self.jumps(0, -9.0), ref()))["key"], "down")
self.assertEqual(fitcoach.position_hint(fitcoach.slip_terms(self.jumps(-7.0, 6.0), ref()))["key"], "right")
self.assertIsNone(fitcoach.position_hint(fitcoach.slip_terms(self.jumps(3.0, -4.0), ref())))
if __name__ == "__main__":
unittest.main()
+1
View File
@@ -34,6 +34,7 @@ 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)
gazed.TrackedEye = lambda: lambda now=None: None # both eyes, whatever SteamVR's settings say
logs = []
gazed.log = gazecheck.log = lambda msg: logs.append(msg)
+1 -1
View File
@@ -19,7 +19,7 @@ int failures = 0;
} while (0)
// The file as the eye server writes it, one sample at a time, with every field from the
// timestamp on moved by `shift` (0 stable, 5 the 0.4.x beta).
// timestamp on moved by `shift` (0 on SteamOS 0.3, 5 on 0.4).
struct File {
std::vector<uint8_t> bytes = std::vector<uint8_t>(324122); // eye-server.mmap's size
EyeFile eyes;
+175
View File
@@ -0,0 +1,175 @@
#!/usr/bin/env python3
"""Offline test of Track Dominant Eye Only (SteamOS 0.4): SteamVR's tracker ignores one eye,
and the gaze code then goes by the other (gazecal.tracked_eye, steady_samples' `eye`,
fitcheck's `ignore`, ft-gazed's live gaze). Reads only the temporary settings files it writes;
ft-gazed's Service is built without its sockets, so nothing reaches the live gaze service.
gaze/test/one-eye-test.py
"""
import importlib.machinery
import importlib.util
import json
import os
import sys
import tempfile
from collections import deque
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, ".."))
from fitcheck import FitCheck # noqa: E402
from gazecal import ( # noqa: E402
Correction,
EyeFallback,
EyeWeights,
Fixation,
TrackedEye,
steady_samples,
tracked_eye,
)
loader = importlib.machinery.SourceFileLoader("ftgazed", os.path.join(HERE, "..", "ft-gazed"))
gazed = importlib.util.module_from_spec(importlib.util.spec_from_loader("ftgazed", loader))
loader.exec_module(gazed)
failures = []
def check(what, got, want):
if got != want:
failures.append(what)
print(f"FAIL {what}: got {got!r}, want {want!r}", flush=True)
tmp = tempfile.mkdtemp(prefix="ft-one-eye-test-")
first, second = os.path.join(tmp, "a.vrsettings"), os.path.join(tmp, "b.vrsettings")
paths = (first, second)
def write(path, steamvr):
with open(path, "w") as f:
f.write(steamvr if isinstance(steamvr, str) else json.dumps({"steamvr": steamvr}, indent=3))
# --- Reading SteamVR's settings ---
check("no settings file: both eyes", tracked_eye(paths), None)
write(second, {"eyeTrackingDominantEyeOnly": True})
check("only the second file: it counts (right, SteamVR's default eye)", tracked_eye(paths), 1)
write(first, {"supersampleScale": 1.0})
check("the first file counts, without the setting: both eyes", tracked_eye(paths), None)
write(first, {"eyeTrackingDominantEyeOnly": True, "dominantEye": 0})
check("dominant eye left", tracked_eye(paths), 0)
write(first, {"eyeTrackingDominantEyeOnly": False, "dominantEye": 0})
check("setting off", tracked_eye(paths), None)
write(first, "{ not json")
check("a broken file: both eyes", tracked_eye(paths), None)
eye = TrackedEye(paths)
write(first, {"eyeTrackingDominantEyeOnly": True, "dominantEye": 1})
check("TrackedEye reads it", eye(now=100.0), 1)
write(first, {"eyeTrackingDominantEyeOnly": True, "dominantEye": 0, "pad": "x" * 10})
check("TrackedEye waits CHECK seconds", eye(now=101.0), 1)
check("then sees the change", eye(now=102.5), 0)
# --- One look at a dot: the left eye lost all along (what SteamVR's tracker may report for
# the eye it ignores), the right seen, and the vergence jumping with the lost eye ---
look = [{"t": i / 90, "src": {"mmap1": {"hy": 1.0, "hp": 2.0, "unc": [0.02, 0.001], "open": [0.0, 0.8],
"lr": 2.8 if i % 2 else 9.0}}} for i in range(40)]
why = {}
check("both eyes judged: nothing kept", len(steady_samples(look, why=why)), 0)
check("both eyes judged: why", why, {"lost_left": 40})
why = {}
check("right eye only: all kept", len(steady_samples(look, why=why, eye=1)), 40)
check("right eye only: nothing dropped", why, {})
why = {}
check("left eye only: nothing kept", len(steady_samples(look, why=why, eye=0)), 0)
blink = [dict(s, src={"mmap1": dict(s["src"]["mmap1"], open=[0.0, 0.05])}) if 10 <= i < 15 else s
for i, s in enumerate(look)]
why = {}
check("right eye only: its blinks still drop", len(steady_samples(blink, why=why, eye=1)), 35)
check("right eye only: as blinks", why, {"blink": 5})
# --- The headset fit check ---
fit = FitCheck(ignore=0)
for i in range(400):
fit.feed({"src": {"mmap1": {"hy": 0.0, "hp": 0.0, "unc": [0.02, 0.001], "open": [0.0, 0.8]}}}, i / 90)
check("fit: the ignored eye's card", fit.status(0)[0], "not tracked")
check("fit: the tracked eye's card", fit.status(1)[0], "tracking")
hints = fit.hints()
check("fit: says which eye counts", hints[0].startswith("SteamVR tracks only your right eye"), True)
check("fit: no losses blamed on the ignored eye", any("Left eye: lost" in h for h in hints), False)
check("fit: the tracked eye is fine", hints[-1], "Your right eye is tracked everywhere you've looked so far.")
both = FitCheck()
for i in range(400):
both.feed({"src": {"mmap1": {"hy": 0.0, "hp": 0.0, "unc": [0.02, 0.001], "open": [0.0, 0.8]}}}, i / 90)
check("fit, both eyes judged: the left eye is lost", both.status(0)[0], "LOST")
# --- ft-gazed's live gaze: the parts of Service the samples go through, no sockets ---
def service(one, source="mmap1"):
svc = gazed.Service.__new__(gazed.Service)
svc.override, svc.tracker, svc.source, svc.one_eye = None, "steam", source, one
svc.models = {name: Correction() for name in gazed.SOURCES}
svc.counts = dict.fromkeys(("samples", "sent", "blinks", "one_eye", "one_eye_used", "lost_left", "lost_right",
"looking_down", "dropped"), 0)
svc.opens, svc.vergence = (deque(maxlen=90), deque(maxlen=90)), deque(maxlen=90)
svc.lost, svc.bad_at, svc.fallback = [False, False], [0.0, 0.0], EyeFallback()
svc.fix, svc.last_sample = Fixation(radius=1.0), 0.0
svc.correction = lambda name, hy, hp: (0.0, 0.0)
svc.sent = []
svc.send = lambda t, hy, hp, rhy, rhp, eyes: svc.sent.append((hy, hp))
return svc
def feed(svc, n=90):
for i in range(n):
svc.on_source_sample({"t": i / 90, "src": {
"mmap1": {"hy": 1.0, "hp": 2.0, "unc": [0.02, 0.001], "open": [0.0, 0.8]},
"mmap2": {"hy": 3.0, "hp": 2.0, "eyes": [[9.0, 9.0], [5.0, 2.0]]}}})
svc = service(None, "mmap2")
feed(svc)
check("mmap2, both eyes judged: a lost eye and no fallback yet drop the gaze", svc.sent, [])
svc = service(1, "mmap2")
feed(svc)
check("mmap2, right eye only: its own reading goes out", (len(svc.sent), svc.sent[-1] if svc.sent else None), (90, (5.0, 2.0)))
check("mmap2, right eye only: no blinks counted", svc.counts["blinks"], 0)
svc = service(0, "mmap1")
feed(svc)
check("left eye only, and it's lost: nothing goes out", (svc.sent, svc.counts["blinks"]), ([], 90))
svc = service(1)
check("no calibration: the source, as a whole", svc.kind, "source")
svc.models["right"].samples = 9
check("right eye only and calibrated: each eye's own", svc.kind, "eyes")
svc.one_eye = None
check("both eyes judged: the left needs a calibration too", svc.kind, "source")
# Our own tracker sees both eyes whatever SteamVR tracks; only the blinks come from SteamVR.
def feed_own(svc, n=90, right_open=0.8):
for i in range(n):
svc.on_eyes_sample({"t": i / 90, "src": {
"mmap1": {"unc": [0.02, 0.001], "open": [0.0, right_open]},
"own": {"hy": 5.0, "hp": 2.0, "eyes": [[4.0, 2.0], [6.0, 2.0]]}}}, True)
svc = service(1)
svc.tracker, svc.weights = "own", {"own": EyeWeights()}
check("own tracker, right eye only: our tracker", svc.kind, "own")
feed_own(svc)
check("own tracker, right eye only: SteamVR's closed left doesn't drop our left",
(len(svc.sent), svc.counts["one_eye"], svc.counts["blinks"]), (90, 0, 0))
svc = service(1)
svc.tracker, svc.weights = "own", {"own": EyeWeights()}
feed_own(svc, right_open=0.0)
check("own tracker, right eye only: its blink drops both", (svc.sent, svc.counts["blinks"]), ([], 90))
svc = service(None)
svc.tracker, svc.weights = "own", {"own": EyeWeights()}
feed_own(svc)
check("own tracker, both eyes judged: SteamVR's closed left still drops it", svc.counts["one_eye"], 90)
for p in paths:
if os.path.exists(p):
os.remove(p)
os.rmdir(tmp)
print("FAILED: " + ", ".join(failures) if failures else "all passed")
sys.exit(1 if failures else 0)
+4
View File
@@ -0,0 +1,4 @@
# Installed to /etc/atomic-update.conf.d/frametop-eyegrab.conf by gaze/tracker/install.sh.
# A SteamOS update deletes every /etc file its keep list (/usr/lib/rauc/atomic-update-keep.conf)
# doesn't name. That list keeps the unit, but not the program it runs.
/etc/frametop/ft-eyegrab
+85
View File
@@ -0,0 +1,85 @@
"""The shared eye-camera frames ft-eyegrab keeps in /dev/shm/frametop-eyes-cams, read without
numpy: lab/ft-eyes-record and the eye recorder's frame writer (gaze/rec/eyerec.py) use it.
Layout (ft-eyegrab.c, share_head_t and share_entry_t): a 64-byte header (magic "FEC1", version,
width, height, slots per camera, entry size, then each camera's frame count as u64 at 24 + 8 *
camera, and the tracker's pid at 40), then SLOTS entries per camera. Frame n of camera c is in
entry c * slots + n % slots: a 64-byte block (u64 seq, odd while it's written; f64 time,
CLOCK_MONOTONIC_RAW seconds; u64 n; u32 camera; u32 the tracker's slot), then the image.
"""
import mmap
import os
import struct
import time
CAMS = os.environ.get("FT_EYES_CAMS", "/dev/shm/frametop-eyes-cams") # overrides for replays
WANT = "/dev/shm/frametop-eyes-want"
W, H = 512, 400
MAGIC = 0x31434546
class Share:
"""The shared frames, mapped read-only."""
def __init__(self, path=None):
self.path = path or CAMS
fd = os.open(self.path, os.O_RDONLY)
try:
self.ino = os.fstat(fd).st_ino
self.mm = mmap.mmap(fd, 0, prot=mmap.PROT_READ)
finally:
os.close(fd)
magic, version, w, h, self.slots, self.esize = struct.unpack_from("<6I", self.mm, 0)
if magic != MAGIC or version != 1 or (w, h) != (W, H):
raise RuntimeError(f"{self.path}: unexpected header")
def replaced(self):
"""ft-eyegrab restarted: it makes a new file, and this one is stale."""
try:
return os.stat(self.path).st_ino != self.ino
except OSError:
return True
def count(self, cam):
return struct.unpack_from("<Q", self.mm, 24 + 8 * cam)[0]
def frame(self, cam, n):
"""(time, slot, bytes) of frame n of a camera, or None if it was overwritten."""
off = 64 + (cam * self.slots + n % self.slots) * self.esize
for _ in range(3):
seq = struct.unpack_from("<Q", self.mm, off)[0]
if seq & 1:
continue
data = self.mm[off + 64:off + 64 + W * H]
t, got, _cam, slot = struct.unpack_from("<dQII", self.mm, off + 8)
if struct.unpack_from("<Q", self.mm, off)[0] == seq and got == n:
return t, slot, data
return None
def close(self):
self.mm.close()
def touch_want(path=None):
"""Tell ft-eyegrab someone wants frames (it idles otherwise). Not for replays."""
if path is None and "FT_EYES_CAMS" in os.environ:
return
try:
fd = os.open(path or WANT, os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600)
os.utime(fd)
os.close(fd)
except OSError:
pass
def open_share(timeout, path=None, want=None):
"""The share, waiting up to timeout seconds for it (touching the want file meanwhile), or None."""
deadline = time.monotonic() + timeout
while True:
touch_want(want)
try:
return Share(path)
except (OSError, ValueError, RuntimeError):
if time.monotonic() >= deadline:
return None
time.sleep(0.5)
+3 -3
View File
@@ -111,9 +111,9 @@ reading only.
The file is 324,122 bytes. Only bytes 0x0-0x1f3 are used; the rest is zero. It's packed and
unaligned, so read it with memcpy. Offsets are also in `~/frametop/gaze/ft-gaze.cpp`.
On the SteamOS 0.4.x beta (SteamVR 2.18.2) every field from 0x157 on sits 5 bytes later, and the
counter stays at 0x38 (measured 2026-10-04, PR #26). The offsets below are stable's; ft-gaze detects
which layout is live.
On SteamOS 0.4 (SteamVR 2.18.2: the 0.4.3 beta, and 0.4.5, the release) every field from 0x157 on
sits 5 bytes later, and the counter stays at 0x38 (measured 2026-10-04, PR #26). The offsets below
are SteamOS 0.3's; ft-gaze detects which layout is live.
| Offset | What |
| --- | --- |
+73 -3
View File
@@ -21,8 +21,10 @@ off), the next click starts that eye's shift over, since the headset may sit dif
Control socket: abstract datagram "@ft_eyes"; each command gets one reply line.
status JSON: calibration, and per eye its shift, clicks, whether a
glint jump is applied, and "reseat" (the next click starts
the shift over: the probe asks for a one-dot check then)
glint jump is applied ("jump", and "jump_px": how far, pixels:
the headset slipped since the last click; the gaze service's
slip notice reads it), and "reseat" (the next click starts the
shift over: the probe asks for a one-dot check then)
calib-start a new calibration: collect dots from now on
calib-point T0 T1 YAW PITCH a dot you looked at from T0 to T1 (CLOCK_MONOTONIC_RAW) in
that direction (head-relative degrees): "ok N0 N1 SD0 SD1"
@@ -30,6 +32,13 @@ Control socket: abstract datagram "@ft_eyes"; each command gets one reply line.
calib-fit fit the dots, save, and start the shifts and clicks over
click T YAW PITCH a click: you were looking there just before T; teaches the
shift: "ok DX0 DY0 DX1 DY1" (the shift each eye measured)
fit JSON: the last second of pupil finds per camera, for the fit
coach (gaze/fitcoach.py, Observations.summary); works uncalibrated
finds start PATH | finds stop
append every frame looked at to PATH as JSON lines (the eye
recorder's own.jsonl): {"t", "cam", "x", "y", "a", "b", "angle",
"glints": [[x, y], ...], "gaze": [yaw, pitch] once calibrated},
or {"t", "cam", "lost": true}. "finds stop" replies "ok ROWS"
Environment, for replays (lab/ft-eyes-e2e): FT_EYES_CAMS, FT_EYES_GAZE, FT_EYES_STATE (the
state folder), FT_EYES_SOCKET (the socket's name). With FT_EYES_CAMS set, the want file isn't
@@ -67,8 +76,10 @@ for _var in ("OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS"):
import numpy as np # noqa: E402
sys.path.insert(0, str(Path(__file__).resolve().parent))
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import eyes_model # noqa: E402
import eyes_pupil # noqa: E402
import fitcoach # noqa: E402
CAMS = os.environ.get("FT_EYES_CAMS", "/dev/shm/frametop-eyes-cams") # overrides for replays
OUT = os.environ.get("FT_EYES_GAZE", "/dev/shm/frametop-eyes-gaze")
@@ -173,6 +184,9 @@ class Eye:
self.frames = self.found = 0
self.work = 0.0
self.last_t = None # the previous frame's time
self.obs = None # the fit coach's window (fitcoach.Observations), shared by both eyes
self.fed = None # (frame time, CLOCK_MONOTONIC_RAW then) of the newest frame fed
self.finds = None # the finds log (Tracker.finds), shared by both eyes
def use(self, cal, shift=None):
self.cal = cal if cal is not None and cal.has("pupil", self.eye) else None
@@ -192,6 +206,9 @@ class Eye:
t0 = time.perf_counter()
p = eyes_pupil.find_pupil(img, self.last)
self.last = p
if self.obs is not None:
self.obs.add(self.eye, t, p)
self.fed = (t, time.clock_gettime(time.CLOCK_MONOTONIC_RAW))
if p is not None:
self.found += 1
self.lost = 0
@@ -206,6 +223,8 @@ class Eye:
self.shift.glint(self.slip.get(), t)
g = self.cal.gaze(self.eye, p["x"], p["y"], self.shift.value)
self.gaze = (t, float(g[0]), float(g[1]), p["x"], p["y"])
if self.finds is not None:
self.finds.write(self, t, p)
self.work += time.perf_counter() - t0
def window(self, t0, t1):
@@ -220,12 +239,39 @@ class Eye:
return dict(pupil=pupil, mid=mid, n=len(rows), spread=spread)
class Finds:
"""The finds log (the "finds" command): a JSON line per frame looked at."""
def __init__(self, path):
self.f = open(path, "a", buffering=1 << 16)
self.rows = 0
def write(self, eye, t, p):
if p is None:
row = {"t": round(t, 6), "cam": eye.eye, "lost": True}
else:
row = {"t": round(t, 6), "cam": eye.eye, "x": round(float(p["x"]), 2), "y": round(float(p["y"]), 2),
"a": round(float(p["a"]), 2), "b": round(float(p["b"]), 2), "angle": round(float(p["angle"]), 1),
"glints": [[round(float(x), 1), round(float(y), 1)] for x, y in p.get("glints") or []]}
if eye.gaze and eye.gaze[0] == t:
row["gaze"] = [round(eye.gaze[1], 3), round(eye.gaze[2], 3)]
self.f.write(json.dumps(row) + "\n")
self.rows += 1
def close(self):
self.f.close()
return self.rows
class Tracker:
def __init__(self):
self.eyes = [Eye(0), Eye(1)]
self.cal = None
self.dots = [] # calibration dots so far, in ft-eyes-score's click form
self.calibrating = False
self.fit = fitcoach.Observations()
for e in self.eyes:
e.obs = self.fit
if CALIBRATION.exists():
self.cal = eyes_model.Calibration.load(CALIBRATION)
if not self.cal.spread:
@@ -256,6 +302,30 @@ class Tracker:
return "fail empty"
if w[0] == "status":
return json.dumps(self.status())
if w[0] == "finds" and len(w) >= 2:
rows = None
for e in self.eyes:
if e.finds is not None:
rows = e.finds.close()
break
for e in self.eyes:
e.finds = None
if w[1] == "stop":
return f"ok {rows or 0}"
if w[1] == "start" and len(w) == 3:
log = Finds(w[2])
for e in self.eyes:
e.finds = log
return "ok"
return "fail finds start PATH | finds stop"
if w[0] == "fit":
# In frame time, which a replay's frames keep from the recording: the newest frame's,
# plus how long ago it came (frames stopping, the headset off, empty the window).
fed = [e.fed for e in self.eyes if e.fed]
if not fed:
return json.dumps(self.fit.summary(0.0))
t, at = max(fed)
return json.dumps(self.fit.summary(t + time.clock_gettime(time.CLOCK_MONOTONIC_RAW) - at))
if w[0] == "calib-start":
self.dots, self.calibrating = [], True
return "ok"
@@ -321,7 +391,7 @@ class Tracker:
return {"calibration": self.cal.info if self.cal else None, "calibrating": self.calibrating,
"dots": len(self.dots),
"eyes": {EYES[e.eye]: {"shift": e.shift.value.tolist(), "clicks": len(e.shift.meas),
"jump": bool(np.any(e.shift.jump)),
"jump": bool(np.any(e.shift.jump)), "jump_px": e.shift.jump.tolist(),
"reseat": e.shift.reseated} for e in self.eyes}}
+4 -2
View File
@@ -5,7 +5,8 @@
# ft-eyes wants them. The gaze service (gaze/ft-gazed) runs ft-eyes itself, when ours is the
# tracker in use (GAZE_TRACKER=auto, the default, picks it once this is installed) or the gaze
# probe uses it. install.sh offers this after gaze mode.
# Needs host sudo, for the binary (/etc/frametop/ft-eyegrab, root's) and the unit: it asks for
# Needs host sudo, for the binary (/etc/frametop/ft-eyegrab, root's), the unit, and the entry that
# keeps the binary through SteamOS updates (/etc/atomic-update.conf.d): it asks for
# the password in the terminal, on the Frame or from a PC, or runs SUDO_ASKPASS when that's set
# (frame_sudo in scripts/_env.sh, which also takes it from the repo's .env).
# Usage: gaze/tracker/install.sh [install|uninstall|status|log [lines]]
@@ -27,6 +28,7 @@ case ${1:-install} in
sudo_run "set -e
install -D -m 0755 -o root -g root $src/build/ft-eyegrab /etc/frametop/ft-eyegrab
install -D -m 0644 -o root -g root /tmp/$unit /etc/systemd/system/$unit
install -D -m 0644 -o root -g root $src/atomic-update.conf /etc/atomic-update.conf.d/frametop-eyegrab.conf
rm -f /tmp/$unit
systemctl daemon-reload
systemctl enable $unit
@@ -36,7 +38,7 @@ echo \"$unit: \$(systemctl is-active $unit)\""
;;
uninstall)
sudo_run "systemctl disable --now $unit 2>/dev/null
rm -f /etc/systemd/system/$unit /etc/frametop/ft-eyegrab
rm -f /etc/systemd/system/$unit /etc/frametop/ft-eyegrab /etc/atomic-update.conf.d/frametop-eyegrab.conf
rmdir /etc/frametop 2>/dev/null; systemctl daemon-reload; echo removed" ;;
status) on_frame "systemctl is-active $unit; ls -l /dev/shm/frametop-eyes-cams 2>/dev/null" || true ;;
log) on_frame "journalctl -u $unit --no-pager -o cat -n ${2:-20}" ;;
+9 -65
View File
@@ -12,81 +12,25 @@ clicks are added later, on the Frame: `lab/py lab/ft-eyes-score --clicks NAME`.
Usage: lab/ft-eyes-record NAME [SECONDS] (host Python is enough: no numpy)
"""
import mmap
import os
import shutil
import signal
import struct
import sys
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from eyes_lab import new_capture # noqa: E402
import eyes_share # noqa: E402 (gaze/tracker, on the path through eyes_lab)
from eyes_share import touch_want # noqa: E402
CAMS = os.environ.get("FT_EYES_CAMS", "/dev/shm/frametop-eyes-cams")
WANT = "/dev/shm/frametop-eyes-want"
W, H = 512, 400
MIN_FREE_GB = 20
class Share:
"""The shared frames. Layout: ft-eyegrab.c, share_head_t/share_entry_t."""
def __init__(self):
fd = os.open(CAMS, os.O_RDONLY)
try:
self.ino = os.fstat(fd).st_ino
self.mm = mmap.mmap(fd, 0, prot=mmap.PROT_READ)
finally:
os.close(fd)
magic, version, w, h, self.slots, self.esize = struct.unpack_from("<6I", self.mm, 0)
if magic != 0x31434546 or version != 1 or (w, h) != (W, H):
raise RuntimeError(f"{CAMS}: unexpected header")
def replaced(self):
try:
return os.stat(CAMS).st_ino != self.ino
except OSError:
return True
def count(self, cam):
return struct.unpack_from("<Q", self.mm, 24 + 8 * cam)[0]
def frame(self, cam, n):
"""(time, slot, bytes) of frame n of a camera, or None if it was overwritten."""
off = 64 + (cam * self.slots + n % self.slots) * self.esize
for _ in range(3):
seq = struct.unpack_from("<Q", self.mm, off)[0]
if seq & 1:
continue
data = self.mm[off + 64:off + 64 + W * H]
t, got, _cam, slot = struct.unpack_from("<dQII", self.mm, off + 8)
if struct.unpack_from("<Q", self.mm, off)[0] == seq and got == n:
return t, slot, data
return None
def touch_want():
"""Tell ft-eyegrab someone wants frames (it idles otherwise)."""
if "FT_EYES_CAMS" in os.environ:
return
try:
fd = os.open(WANT, os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600)
os.utime(fd)
os.close(fd)
except OSError:
pass
def open_share(deadline):
while time.monotonic() < deadline:
touch_want()
try:
return Share()
except (OSError, ValueError, RuntimeError):
time.sleep(0.5)
sys.exit(f"ft-eyes-record: no {CAMS} (is frametop-eyegrab.service running? gaze/tracker/install.sh)")
def open_share(timeout):
share = eyes_share.open_share(timeout)
if share is None:
sys.exit(f"ft-eyes-record: no {eyes_share.CAMS} (is frametop-eyegrab.service running? gaze/tracker/install.sh)")
return share
def main(argv):
@@ -97,7 +41,7 @@ def main(argv):
stop = []
for sig in (signal.SIGINT, signal.SIGTERM):
signal.signal(sig, lambda *_: stop.append(1))
share = open_share(time.monotonic() + 10)
share = open_share(10)
(out / "clocks.txt").write_text(f"{time.time()} {time.clock_gettime(time.CLOCK_MONOTONIC_RAW)}\n")
seen = [share.count(0), share.count(1)]
written = dropped = 0
@@ -134,7 +78,7 @@ def main(argv):
break
if share.replaced():
print("ft-eyes-record: the frame share was restarted; following it", file=sys.stderr)
share = open_share(time.monotonic() + 10)
share = open_share(10)
seen = [share.count(0), share.count(1)]
print(f"ft-eyes-record: {written} frames ({dropped} dropped) in {out}", file=sys.stderr)
+24 -12
View File
@@ -2,11 +2,11 @@
# Frametop's one-line installer. In a terminal on the Steam Frame (Konsole in the desktop, or
# over SSH):
#
# curl -fsSL https://deejanuz.github.io/frametop/get.sh | bash
# curl -fsSL https://frametop.github.io/frametop/get.sh | bash
#
# It asks which version to install, clones the repo into ~/frametop (or updates the clone
# that's there), and runs its install.sh. Run it again to update, or to switch versions.
# With --release it installs a release instead: Frametop built, in one file. It downloads the
# Its third and fourth choices, or --release, install a release instead: Frametop built, in one file. It downloads the
# release's Frametop.zip from GitHub (about 1.1 GB: the newest stable release, or with
# --experimental the newest of any), unpacks it in ~/.cache/frametop/release, and runs its
# install-release.sh, which checks this SteamOS build against the releases' SteamOS table and
@@ -23,22 +23,25 @@
# --version V with --release: that release (tag vV), not the newest
# --zip FILE|URL with --release: this Frametop.zip instead of GitHub's newest
# --any-steamos with --release: install even on a SteamOS build the release breaks on
# --yes, --no-eye-tracker, --no-bluetooth, --bluetooth passed to install.sh (--yes also
# --yes, --no-voice, --no-hands, --no-eye-tracker, --no-bluetooth, --bluetooth passed to install.sh (--yes also
# answers this script's questions: the version already there, or stable)
set -euo pipefail
usage() {
cat <<'EOF'
usage: get.sh [--stable | --experimental | --branch NAME] [--dir DIR] [--clone-only] [--yes]
[--no-eye-tracker] [--no-bluetooth | --bluetooth]
[--no-voice] [--no-hands] [--no-eye-tracker] [--no-bluetooth | --bluetooth]
get.sh --release [--stable | --experimental | --version V | --zip FILE|URL]
[--any-steamos] [--dir DIR] [--clone-only] [--yes] [--no-eye-tracker]
[--no-bluetooth | --bluetooth]
piped: curl -fsSL https://deejanuz.github.io/frametop/get.sh | bash -s -- [options]
[--any-steamos] [--dir DIR] [--clone-only] [--yes] [--no-voice] [--no-hands]
[--no-eye-tracker] [--no-bluetooth | --bluetooth]
piped: curl -fsSL https://frametop.github.io/frametop/get.sh | bash -s -- [options]
EOF
}
SLUG=${FRAMETOP_REPO:-DeeJanuz/frametop} # FRAMETOP_REPO: another repo's releases, such as a fork's
# Frametop lives in the Frametop organization's repo: the branches clone from it, and its CI
# runners (Depot, which need an organization) build the releases. It moved there from
# DeeJanuz/frametop on 2026-10-09; GitHub redirects clones made from the old name.
SLUG=${FRAMETOP_REPO:-Frametop/frametop} # FRAMETOP_REPO: another repo's releases, such as a fork's
# release_zip CHANNEL VERSION: the URL of a release's Frametop.zip on GitHub.
release_zip() {
@@ -111,7 +114,7 @@ install_release() {
# Everything happens in main, called on the last line, so a download cut short runs nothing.
main() {
local repo=https://github.com/DeeJanuz/frametop.git dir= branch= clone_only=0
local repo=https://github.com/Frametop/frametop.git dir= branch= clone_only=0
local yes=0 tty=0 current= def answer release=0 zip= want= any=0
local pass=()
while [ $# -gt 0 ]; do
@@ -126,7 +129,7 @@ main() {
--version) want=${2:?--version needs a version}; shift ;;
--any-steamos) any=1 ;;
--yes) yes=1; pass+=("$1") ;;
--no-bluetooth|--bluetooth|--no-eye-tracker) pass+=("$1") ;;
--no-bluetooth|--bluetooth|--no-eye-tracker|--no-voice|--no-hands) pass+=("$1") ;;
-h|--help) usage; return 0 ;;
*) echo "unknown option: $1" >&2; usage >&2; return 2 ;;
esac
@@ -140,6 +143,7 @@ main() {
echo "releases come from the stable or experimental list, not a branch" >&2
return 2
fi
local dir_arg=$dir # the menu's release choice puts releases in their own default place
if [ -z "$dir" ] && [ "$release" = 0 ]; then
dir=$HOME/frametop
fi
@@ -176,12 +180,20 @@ main() {
echo "Which version of Frametop?"
echo " 1) stable: the main branch, tested releases"
echo " 2) experimental: the newest features, less tested"
if [ "$release" = 0 ]; then
echo " 3) stable release: built, nothing to compile (a 1.1 GB download)"
echo " 4) experimental release: built, nothing to compile (a 1.1 GB download)"
fi
[ -n "$current" ] && echo "(installed now: $current)"
read -r -p "Choose 1 or 2 [$([ "$def" = main ] && echo 1 || echo 2)]: " answer </dev/tty || answer=
read -r -p "Choose 1$([ "$release" = 0 ] && echo ", 2, 3, or 4" || echo " or 2") [$([ "$def" = main ] && echo 1 || echo 2)]: " \
answer </dev/tty || answer=
case ${answer:-$def} in
1|main|s*) branch=main ;;
2|experimental|e*) branch=experimental ;;
*) echo "not 1 or 2: $answer" >&2; return 2 ;;
3|4) [ "$release" = 0 ] || { echo "not 1 or 2: $answer" >&2; return 2; }
release=1 dir=$dir_arg
branch=$([ "$answer" = 3 ] && echo main || echo experimental) ;;
*) echo "not one of the choices: $answer" >&2; return 2 ;;
esac
fi
fi
+7 -5
View File
@@ -12,9 +12,11 @@ Join the [Frametop Discord](https://discord.gg/W3X9f7z3Bc) for questions and hel
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.
Installing a Frametop release (Frametop.zip, FrameDrop, or `get.sh --release`) instead? Its installer offers the Hand Recorder, built, so there's nothing to compile: leave Hand Recorder ticked (or answer yes) and skip step 2. To add it to a release later, run `~/.local/share/frametop/releases/current/hands/rec/install.sh`.
## 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 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/Frametop/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.
@@ -27,7 +29,7 @@ For now the recorder runs inside Frametop's desktop, so these steps install Fram
## 1. Install Frametop
```
curl -fsSL https://deejanuz.github.io/frametop/get.sh | bash -s -- --stable
curl -fsSL https://frametop.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.
@@ -49,7 +51,7 @@ Open Frametop Hand Recorder from the desktop's application menu. It walks you th
## Update
```
curl -fsSL https://deejanuz.github.io/frametop/get.sh | bash -s -- --stable
curl -fsSL https://frametop.github.io/frametop/get.sh | bash -s -- --stable
~/frametop/hands/rec/install.sh
```
@@ -61,8 +63,8 @@ Run the second command after SteamVR has restarted, as in the install.
~/frametop/hands/rec/install.sh uninstall
```
This removes the menu entry. With your `sudo` password, it also takes back the camera broker's permission to read the cameras. If you also installed Frametop's live hand tracking, the camera broker keeps that permission, because live hand tracking still uses it. 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.
This removes the menu entry. With your `sudo` password, it also takes back the camera broker's permission to read the cameras. If you also installed Frametop's live hand tracking, the camera broker keeps that permission, because live hand tracking still uses it. 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/Frametop/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.
Ask in the [Frametop Discord](https://discord.gg/W3X9f7z3Bc), the [Frametop issues](https://github.com/Frametop/frametop/issues), or the dataset's [discussion page](https://huggingface.co/datasets/DeeJanuz/frametop-hands/discussions). All three are public.
+10
View File
@@ -1,5 +1,15 @@
# Model sources that tools/convert_models.py downloads; the converted ncnn models are kept
models/onnx/
models/*.task
# the fine-tuned models hands/models.sh fetches (their own licence, CC BY-NC 4.0: not in the repo)
models/student/
# hands/models.sh update's download folder, lock and last check
models/.student-*
# frame-job settings (where replays run, and the lab's capture folder): personal, not shipped
.frame-job
dumps/
# tap replays' output and their per-host drivers (frame-hands notes/taps.md)
taps-out/
tools/taps-*.sh
# recorded demo clips (hands/rec/demo/camgifs.py) show the room around the recorder: never shipped
rec/demos-recorded/
+25 -7
View File
@@ -1,7 +1,8 @@
# 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)
# make check builds and runs the C++ unit tests (tests/sides_test.cpp, tests/skeleton_test.cpp,
# tests/pinch_test.cpp, tests/flagbuf_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
@@ -10,9 +11,11 @@ CFLAGS ?= -O2 -g -Wall -Wextra -Wno-unused-parameter
CXXFLAGS ?= -O2 -g -Wall -Wextra -Wno-unused-parameter -Wno-psabi
CXXFLAGS += -std=c++17 -fopenmp -I$(NCNN)/include/ncnn
LDLIBS = $(NCNN)/lib/libncnn.a -ljsoncpp -fopenmp -lpthread
# The standalone Hand Recorder's release build passes LDFLAGS=-static (it runs on the host).
LDFLAGS ?=
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/sides.cpp
TRACK = track/calib.cpp track/nets.cpp track/tracker.cpp track/io.cpp track/record.cpp track/pinch.cpp track/sides.cpp track/skeleton.cpp track/flagbuf.cpp
HDR = $(wildcard track/*.h) camd/fhring.h include/fh_hands.h include/fh_gestures.h
all: build/ft-camd build/ft-hands
@@ -24,18 +27,33 @@ build/ft-camd: $(CAMD) camd/tp.h camd/xrcams.h camd/fhring.h
build/ft-hands: track/main.cpp $(TRACK) $(HDR) $(NCNN)/lib/libncnn.a
@mkdir -p build
$(CXX) $(CXXFLAGS) -o $@ track/main.cpp $(TRACK) $(LDLIBS)
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o $@ track/main.cpp $(TRACK) $(LDLIBS)
build/ft-handreplay: track/replay.cpp $(TRACK) $(HDR) $(NCNN)/lib/libncnn.a
@mkdir -p build
$(CXX) $(CXXFLAGS) -o $@ track/replay.cpp $(TRACK) $(LDLIBS)
$(CXX) $(CXXFLAGS) $(LDFLAGS) -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)
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o $@ tests/sides_test.cpp $(TRACK) $(LDLIBS)
check: build/sides-test
build/skeleton-test: tests/skeleton_test.cpp track/skeleton.cpp track/skeleton.h track/geom.h
@mkdir -p build
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o $@ tests/skeleton_test.cpp track/skeleton.cpp
build/pinch-test: tests/pinch_test.cpp $(TRACK) $(HDR) $(NCNN)/lib/libncnn.a
@mkdir -p build
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o $@ tests/pinch_test.cpp $(TRACK) $(LDLIBS)
build/flagbuf-test: tests/flagbuf_test.cpp $(TRACK) $(HDR) $(NCNN)/lib/libncnn.a
@mkdir -p build
$(CXX) $(CXXFLAGS) $(LDFLAGS) -o $@ tests/flagbuf_test.cpp $(TRACK) $(LDLIBS)
check: build/sides-test build/skeleton-test build/pinch-test build/flagbuf-test
build/sides-test
build/skeleton-test
build/pinch-test
build/flagbuf-test
build/ft-ringplay: track/ringplay.cpp track/record.h camd/fhring.h
@mkdir -p build
@@ -52,6 +70,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 build/sides-test
rm -f build/ft-camd build/ft-hands build/ft-handreplay build/ft-ringplay build/sides-test build/skeleton-test build/pinch-test build/flagbuf-test
.PHONY: all tools check clean
+203 -26
View File
@@ -1,10 +1,12 @@
# Hands (experimental, deferred)
# Hands (experimental)
Hand tracking from the headset's own cameras. It's deferred: it costs a lot of the headset's CPU and needs more work, so `install.sh` doesn't offer it and the README doesn't list it. It still builds and runs, installed by hand (below), for working on it.
Hand tracking from the headset's own cameras. It's experimental and costs a lot of the headset's CPU. `install.sh` offers it (yes by default; `--no-hands` skips it), a release brings it built, and installed, it runs while the Frametop desktop does (`HANDS_MODE=frametop`). `hands/run.sh install` (below) installs it later.
It serves two things in Frametop:
- **Hand cutouts:** where your hand is between an eye and a screen, that eye sees the room through the screen (ft-screens, `screens/handcut.cpp`), so your hands show over the screens the way they do on a Vision Pro.
- **Hand cutouts:** where your hand is between an eye and a screen, that eye sees the room through the screen (ft-screens, `screens/handcut.cpp`), so your hands show over the screens the way they do on a Vision Pro. The hole is round, one per hand, until the tracking is good enough for a hand-shaped one (also there, built from the skeleton; see "Hand cutouts and near input" below).
- **Rendered hands:** ft-handview draws your hands as a 3D hand model posed by the tracking, Quest-style, over everything (`screens/handview.cpp`; see "Rendered hands" below): with Room View off (a VR game, SteamVR Home, the dashboard, or the panels over the void), where ft-screens doesn't cut, and by default with Room View on too, floating over the hole.
- **Near input on Frametop's panels:** poke a screen with your index finger to click, pinch its bar, edges or any corner to move or resize it, hold it like a card or in a fist to carry and turn it, hold it with both hands to stretch it, flick it away or throw it (ft-screens, `screens/handinput.cpp`; see "Hand cutouts and near input"). SteamVR's own panels (the dashboard, the Steam menu, other apps' overlays) take pokes and pinch clicks through the pointer helper's laser, and the hand ray's pinch on a floating one's grab bar moves it.
- **Pinches and grips:** with `POINTER_HANDS=1`, the pointer helper takes them as clicks and drags. Look at something and pinch to click it, with the eye tracker doing the looking (`gaze/`), or close your hand to press and drag what the pointer is on. See "Pinches and grips in the pointer" below.
Two programs, each a user service that stops when SteamVR does:
@@ -12,20 +14,28 @@ Two programs, each a user service that stops when SteamVR does:
- `ft-camd` (`camd/`, C) borrows XRService's camera buffers and publishes the four IR tracking cameras' frames to a shared-memory ring. It runs on the host.
- `ft-hands` (`track/`, C++) finds hands in those frames with MediaPipe's palm and landmark models on ncnn, triangulates them, and publishes them. It runs in the dev container.
They don't start with SteamVR. `hands/run.sh install` builds them, gives ft-camd its capabilities, installs both services disabled, and links `hands/ft-handsctl` into `~/.local/bin`. Then `ft-handsctl on` starts hand tracking and `ft-handsctl off` stops it. `install.sh` doesn't install it.
`hands/run.sh install` builds them (a release brings them built), gives ft-camd its capabilities, installs both services, and links `hands/ft-handsctl` into `~/.local/bin`. `install.sh` runs it when you choose hand tracking, then sets `HANDS_MODE=frametop` unless it's `always`. When they run is `HANDS_MODE` in `~/.config/frametop.conf`, set on the Hands page of Frametop Input Settings or with `ft-handsctl mode`; `hands/handsmode.py` does the starting and stopping, for these two and the hand view (`frametop-handview.service`, when it's installed):
- `off` (the default before hand tracking is installed): nothing starts them. `ft-handsctl on` starts hand tracking and `ft-handsctl off` stops it, as before; it stops with SteamVR.
- `frametop`: they run while the Frametop desktop does. The session (`session/frametop-session.sh`, screens backend) starts them once ft-screens is up and stops them as it ends.
- `always`: they're wanted by `steamvr.service` (`systemctl --user add-wants`), so they run whenever SteamVR does, in games and the SteamVR dashboard too, with or without the desktop. Pausing Frametop for a VR game leaves them running and unparked.
Choosing a mode applies it at once: the services start or stop, with no desktop restart. Without ft-camd's capabilities nothing starts, and the Hands page says to run `hands/run.sh caps` (it asks for the password in the terminal; the page never does). `hands/run.sh install` and `caps` apply the mode too, but stop nothing, so what `ft-handsctl on` or `ft-cutouts on` started keeps running.
For the cutouts alone, `hands/ft-cutouts on` starts the same two programs with ft-hands' `--no-gestures`: your hands show through the screens, and no pinch or grip is detected, so nothing clicks or drags. It runs this checkout's build as transient user units, so it needs `hands/build.sh` and ft-camd's capabilities (`hands/run.sh caps`) but not `hands/run.sh install`. It and `ft-handsctl on` stop each other's services, and it stops with SteamVR too.
```
ft-handsctl on | off # on the Frame: start or stop hand tracking (SteamVR must be running)
ft-handsctl mode [frametop|always|off] # HANDS_MODE: show it, or set and apply it
ft-handsctl status # the services, and ft-hands' last status lines
ft-handsctl log [lines]
ft-handsctl cutouts on|off|state # ft-screens' hand cutouts, without stopping tracking
ft-handsctl gestures # pinches and grips, live (tools/watch_gestures.py --distance)
ft-handsctl gestures # pinches, grips and middle pinches, live (tools/watch_gestures.py --distance)
ft-handsctl flag [note...] # flag a tracking failure: the last seconds go to a folder (see "Flags")
hands/ft-cutouts on | off | status # the cutouts only: no pinches or grips
hands/run.sh install # build, give ft-camd its capabilities (sudo, once per build), install disabled
hands/run.sh install # build, give ft-camd its capabilities (sudo, once per build), install, apply HANDS_MODE
hands/run.sh start|stop # start or stop the services
hands/run.sh restart # after changing a setting
hands/run.sh status
@@ -40,7 +50,12 @@ Settings in `~/.config/frametop.conf` (`FT_<name>` in the environment overrides
- `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_MODELS` (unset: `hands/models/student`, the fine-tuned models, when `hands/models.sh` fetched them, else `hands/models/ncnn`, the stock MediaPipe models): a folder holding `palm.ncnn.*` and `hand.ncnn.*`, as `--models`. Use it to try other models without passing options to every launcher. The fine-tuned folders lack the `*-int8` files, so `--int8` without `--models` uses the stock ones.
- `HANDS_MODELS_UPDATE=1`: when hand tracking starts, fetch the fine-tuned models GitHub's branch pins if they changed, without a new release (`models.sh` below). `0` keeps the ones it came with.
- `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`.
- `HANDS_SKELETON=1`: fit a skeleton with your bone lengths and publish it (see "Skeleton" below); `0` publishes the filtered landmarks as before. As `--skeleton`.
- `HANDS_PINCH_DIP=0`: `1` also starts a pinch on a quick dip of the thumb-index distance that never reaches 2 cm (see the pinch under "Gestures" below). As `--pinch-dip`.
- `HANDS_FLAG_BUFFER=1`: keep the last seconds of hand crops in RAM for `ft-handsctl flag` (see "Flags"); `0` keeps nothing. As `--flag-buffer`. `HANDS_FLAG_SECONDS` (12), `HANDS_FLAG_CROP` (224 px), `HANDS_FLAG_MB` (80) size it. `HANDS_FLAG_DIR` (`~/.local/share/frametop/hands/flags`) is where flags go; `HANDS_FLAG_FLASH=1` pulses the drawn hands when a flag is taken, `HANDS_FLAG_TONE=1` adds a short tone, `HANDS_FLAG_VIEW=1` saves a frame of your view.
The pointer helper's `POINTER_HANDS` and `POINTER_PINCH_*`/`POINTER_GRIP_*` settings are in "Pinches and grips in the pointer" below.
@@ -49,8 +64,9 @@ Files, all in `/run/user/UID/frametop-hands/` (private to the user; not `/run/us
| File | Written by | Layout | Read by |
| --- | --- | --- | --- |
| `cam-ring` | ft-camd | `camd/fhring.h` | ft-hands, `tools/ring.py` |
| `hands` | ft-hands | `include/fh_hands.h` | ft-screens (`screens/handcut.cpp`) |
| `hands` | ft-hands | `include/fh_hands.h` (version 2: version 1, then a skeleton per hand) | ft-screens (`screens/handcut.cpp`, version 1's part), the hand recorder (`rec/session.py`) |
| `gestures` | ft-hands | `include/fh_gestures.h` | the pointer helper (`pointer/helper/ft-pointer.cpp`), `tools/watch_gestures.py` |
| `flag` | `ft-handsctl flag` (`handsflag.py`) | key=value lines: `dir`, `note`, `flag_unix`, `said_unix` | ft-hands, which removes it when it takes it |
The source keeps the `fh_` names and magic strings of frame-hands, the project it started as, so recordings made with it still work.
@@ -85,9 +101,9 @@ Options:
- `--sensor S`: only the mono cameras whose sensor name contains S.
- `--status S`: a status line every S seconds (0: never).
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.
It exits when XRService exits, when a camera's buffers keep going stale, which means XRService has reallocated them, or when a camera stops while the others keep running (3 s), which means XRService has moved it to another device (the colour module was unplugged or plugged in). 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. ft-hands now catches this by itself (`track/sides.h`, `HANDS_SWAP_SIDES=auto`):
**Which camera is which:** video9 is `slam_right` (sensor `og01a1b 4-0036`), video13 is `slam_left` (`4-0060`), video6 is `upper_left` and video7 is `upper_right`; without the colour module the side pair is on video0 (`slam_right`) and video3. XRService says so in its log: `Found camera 'slam_left': ... v4l_subdev=/dev/v4l-subdev30` names each sensor, and each `TrackingCameraInit` line gives the device and subdev it opened. ft-hands and `camcheck.py` name the devices that way. Until 2026-10-05 they named them by the `TrackingCameraInit` index instead, which is only the order XRService opens them in (index 0 was `slam_right` on every start logged), and ft-camd bound each buffer queue to a device by the order of XRService's file descriptors, which changes when XRService restarts its cameras. The two mistakes made the side names come out swapped on most starts and right on some. ft-camd now asks each device which buffers it holds (`VIDIOC_QUERYBUF` names the descriptor XRService queued at each index) and only falls back to the order if that fails. With the names swapped, every hand is seen by one camera only, at the wrong depth, and the hand holes land beside the hands. ft-hands still checks by itself, in case (`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.
@@ -116,21 +132,29 @@ Options:
- `--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.
- Parked: while `/run/user/UID/frametop-hands/park` exists, ft-hands processes no frames (the models stay loaded), publishes no hands, and ends any gesture down, as lost; it writes `0` to `hands-want` there every second, and ft-camd stops copying the mono cameras' frames while that file is fresh (3 s) and says 0. The input relay parks it while Frametop is paused for a VR game with hand interaction on (`POINTER_HANDS=1`), instead of stopping the services, and unparks it while the dashboard is open, so the hands work there; it tracks again from a palm search. Not while recording.
- `--no-gestures`: hands for the cutouts only. No pinch or grip detection, so nothing reaches the pointer and a closing hand doesn't raise the rate to 30 Hz. The gestures file is removed at start. `ft-cutouts` runs it this way.
- `--record DIR`, `--record-for S`, `--record-hz N`: save every frame set for S seconds (default 120) to `DIR/sets.bin`, or at most N sets a second with `--record-hz` (the hand recorder uses 10). Every set is about 80 MB/s. Sending the tracker SIGUSR1 (`pkill -USR1 -x ft-hands`) starts a recording in `~/.local/share/frametop/hands/rec-<time>` without a restart. Recordings are images of your hands and room: they stay on the headset unless you move them.
- `--record-only`: record without tracking or publishing, so it can run beside the live tracker. Give it `--record DIR`, since SIGUSR1 would reach both trackers. With `ft-camd --with-dark`, recordings also hold each camera's newest dark frame as `<name>_dk`, which doubles the rate. With `--with-color`, each colour camera's newest frame is saved with every set, as `color_video<N>`, which adds about 70 MB/s. Run the recorder at normal I/O priority: idle I/O priority stalled a 165 MB/s recording.
- `--reacquire S` (`HANDS_REACQUIRE`, default 1.5): how long after losing a hand the palm search aims at where it should be (see "Scheduling"). 0 turns it off.
- `--pair-sides 0|1` (`HANDS_PAIR_SIDES`, default 1): two hands seen together are one left and one right (see "Scheduling").
- `--hold S` (default 0.6): how long a lost hand tracked for 30+ frames is held before it's forgotten (0.3 s with `--reacquire 0`, as before).
- `--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.
- `--cams auto|mono|color|all` (`HANDS_CAMERAS`, default `auto`): which cameras to track with. The mono IR cameras light the hands themselves and track well in dim rooms, but in bright light they expose for the room and the hands come out dark. The colour pair is the other way round. `auto` goes by the colour frames' mean brightness: at `--bright-on` (`HANDS_BRIGHT_ON`, 40) or over for 2 s it tracks with `--bright` (`HANDS_BRIGHT`: `all`, every camera, the default, or `color`), and under `--bright-off` (`HANDS_BRIGHT_OFF`, 25) for 2 s with the mono cameras again. A dim evening room read 9. The switch is logged (`cameras: mono -> all (...)`), and the status line gives the colour level, the mono cameras' ambient IR, and how many steps had colour frames. Colour frames arrive on their own schedule, so a step holds the mono set, the colour pair, or both, and views wait in their camera for its next frame. With no colour cameras in the ring (ft-camd without `--with-color`, as the service runs it), ft-hands tracks with the mono cameras whatever this says.
- `--color-left NODE` (`HANDS_COLOR_LEFT`, `color_video0`) and `--color-crop subtract|none` (`HANDS_COLOR_CROP`, `subtract`): how the colour module's calibration maps onto the images. Not settled yet: `tools/check_color.py` on a recording with a lit, textured view tells.
- `--skeleton 0|1` (`HANDS_SKELETON`, 1): the skeleton fit (below). With 0 no skeleton is published, and version 1's points and capsules are the filtered landmarks, as before 2026-10-08.
- `--pinch-dip 0|1` (`HANDS_PINCH_DIP`, 0): the dip rule for pinches (below).
- `--grip-begin R`, `--grip-end R`: the grip detector (below). Defaults 1.2 and 1.45.
- `--gesture-log`: print what the pinch and grip detectors measure, 10 times a second: each hand's thumb-to-index distance (world and triangulated), its palm-down reading and its finger curl.
**Gestures** (`/run/user/UID/frametop-hands/gestures`, `include/fh_gestures.h`), for the pointer helper:
- A pinch: the thumb and index tips within 2 cm, ending past 3.5 cm (see "Pinch" below).
- With `HANDS_PINCH_DIP=1`, also on a sharp dip that doesn't reach 2 cm. Quick taps with the hand raised often read 25-30 mm at contact and spring back, so they never click. The dip rule begins a pinch when, within 150 ms, the distance falls by 40% of its recent highest to under 3.2 cm, with the palm moving under 0.3 m/s and the thumb at least 4 cm from the middle fingertip (a hand closing into a grab brings both in). It ends once the distance is 6 mm over its lowest, and becomes an ordinary pinch (drags and all) if the tips get within 2 cm. It is off by default. In ft-handreplay on frame-hands' guided tap capture (2026-10-09, student v4), it caught 25 of 30 quick taps on a 2 Hz click instead of 10, and 74% of the teacher's clear taps instead of 62% at the same precision (0.91 against 0.93). The cost is that fingers stopped about 1 cm apart click too: 16 pinches in the near-miss segment instead of 5. Pointing and grabs in the hand recorder's takes gave 22 pinches, against 21 without it (`PinchParams::dip`; frame-hands notes/taps.md, Part D).
- A grip, a closed hand: every finger's tip nearer the wrist than 1.2 times its knuckle is (from the model's 3D hand, so hand size doesn't matter), ending when they open past 1.45 on average. It begins only on a hand seen open within the last second (closing it is the gesture), with the palm at most 35 degrees below straight ahead and at least 15 cm in front of the eyes, and not with the thumb within 3 cm of the index tip (that's a pinch with the other fingers curled). A grip ends a pinch on the same hand, as lost. In the 2026-09-30 lit recording (no deliberate fists), the checks cut false grips from 14 to 6, all with the hands on the desk while looking down at it. The pointer helper ignores grips that begin more than `POINTER_GRIP_BELOW` (0.35 m) below the eyes, which it can tell and ft-hands can't.
- `tools/watch_gestures.py --distance` shows both live; `ft-handreplay --timeline` logs them and each hand's finger curl.
- A middle pinch (gestures version 3): the thumb on the middle fingertip, with the pinch's thresholds. It begins only with the thumb at least 1 cm nearer the middle tip than the index tip, the index extended (its tip at least 1.5 times as far from the wrist as its knuckle), and the hand tracked for 5 frames; a pinch and a middle pinch on one hand exclude each other, and a pinch begins only with the thumb nearer the index tip than the middle one. The pointer helper's hand ray turns it into a right click or scrolling. Closing the hand into a grab brought the middle tip to the thumb with the index curled: before the index and frames rules, the recorder's gestures take (PR #8, about 95 s of pinches and grabs, none of them middle pinches) gave 6 false middle pinches; after, 1. The 2026-09-30 lit recording (typing and 26 deliberate pinches) gave none, and the same 48 pinches as without the middle pinch.
- `tools/watch_gestures.py --distance` shows them live; `ft-handreplay --timeline` logs them (middle pinches as `pinch2`) and each hand's finger curl.
The status line also says how often a hand was on each side (by where the wrist is), and why views and hands came and went: views lost (the landmark model stopped seeing the hand), handoff misses (a crop projected from the hand's 3D position found nothing), duplicates, splits (two views disagreed in 3D), and hands created, merged and forgotten.
@@ -138,26 +162,63 @@ The status line also says how often a hand was on each side (by where the wrist
- Each hand is tracked in its best two cameras, the way MediaPipe tracks: the landmark model runs on a crop placed from the previous landmarks, with no palm detection.
- A hand seen in too few cameras is projected into the others through the calibration. Where it lands well inside a camera, that camera gets a crop to try. This is how a hand raised out of the side cameras reaches the upper ones.
- The palm detector runs only while fewer than two hands are tracked, at most 5 times a second, on a few zoomed tiles per search. Tiles are picked in proportion to how likely hands are there. Each tile is turned so the expected shoulder-to-hand direction points up.
- Frame sets are processed at 30 Hz while a hand moves faster than 0.25 m/s (or a pinch is down or closing), at 15 Hz otherwise, and at 5 Hz while no hand is in view.
- The palm detector runs only while fewer than two hands are tracked, at most 5 times a second, on a few zoomed tiles per search. Tiles are picked in proportion to how likely hands are there. Each tile is turned so the expected shoulder-to-hand direction points up. There are 42 tiles and a search tries 2 (3 with no hand tracked), so even the likeliest tile comes round only every 10-11 searches: about 2 s at 5 searches a second, and 4-5 s live, where a search round takes about 50 ms and the tracker manages 2-3 a second.
- **Re-acquiring a lost hand** (`--reacquire`, on by default since 2026-10-08). A hand that stops being seen is first held, not published: 0.6 s if it was tracked for 30 frames or more (`--hold`), else 0.3 s. Meanwhile its crops are retried where it was heading (its last position plus its velocity). From the first step it's missing and for 1.5 s after it's forgotten, the palm search aims up to 2 tiles at where it should be, in the cameras that see that spot best. The aimed tiles grow with the time since the loss, and they run every processed set while such a hand is missing, not only 5 times a second. The rotation keeps at least one tile per search. In replays this brought a lost hand back on the next processed set (median 0.05 s, against 0.12-0.25 s), and the slowest cases from seconds down to under 1 s (see frame-hands' `notes/reacquire.md`).
- **Left and right** (`--pair-sides`, on by default since 2026-10-08). Each hand used to be called left or right by a running average of the landmark model's call, and both hands could get the same side for seconds. Now each hand also accumulates the model's calls as fading log-odds, and two hands seen together are one left and one right: the hand with more right-hand evidence is the right one, and which wrist is further right only tips a close call.
- Frame sets are processed at 30 Hz while a hand moves faster than 0.25 m/s (or a pinch is down or closing), at 15 Hz otherwise, and at 5 Hz while no hand is in view. A reader that needs the full rate writes it to `/run/user/UID/frametop-hands/want-hz` and keeps the file fresh: ft-screens writes 30 there while a hand is near one of its panels, because at 15 Hz a poke's press would come up to 67 ms later. A file older than 1 s lapses.
### 3D
- **Two or more views:** each landmark is triangulated from the camera rays, weighted by the model's presence score. The median ray distance is reported as the residual.
- **Pairing views across cameras.** The side cameras sit side by side, so two hands next to each other at the same height fall on the same epipolar lines, and rays to two different hands can nearly meet close to the cameras. That made phantom hands 12-15 cm in front of the eyes, which tore holes through the screens. Each step now scores every way of pairing the views in two cameras and keeps the best. A pair scores well when its rays meet, when each view's apparent size matches the triangulated distance, and when the model calls both the same hand. The size check uses a fixed prior: with the model's average hand, clean pairs measure 0.71-1.51 times the one-view distance, and mismatched pairs mostly far less.
- **One view:** depth comes from the model's metric world landmarks, their spread across the palm against the angle it covers in the image, scaled by the user's hand size (learned while two views are available). That distance is off by 10-30% and wanders about 10% between frames, so a hand that drops to one camera keeps its last distance and drifts toward the one-view guess by 10% a frame.
- **Smoothing.** The published landmarks go through a One Euro filter: it smooths hard while the hand is still (tracking noise is several mm per frame) and hardly at all while it moves fast. The palm speed that sets the update rate is the filtered one; the raw speed read about 0.25 m/s from noise alone.
- **Smoothing.** The landmarks go through a One Euro filter: it smooths hard while the hand is still (tracking noise is several mm per frame) and hardly at all while it moves fast. The palm speed that sets the update rate is the filtered one; the raw speed read about 0.25 m/s from noise alone. The gestures (pinch point, palm-down reading) use these filtered landmarks. What's published is the skeleton's (below), unless `--skeleton 0`.
- **Capsules.** Forearms follow the hand's own axis, and nothing within 12 cm in front of the eyes is published.
How good the depth is, measured from recordings (2026-09-30, `--depth` below): the two lower cameras see the hands about 77% of the time, a lower and an upper camera 7-12%, and one camera 12-15%. Depth is the noisy direction. With the lower pair, it jitters 4-6 times as much as sideways position (published: 3-7 mm against 1-2 mm). The one-camera guess is a median 2-6 cm off. When a camera drops out, drifting 10% a frame toward that guess is worse than keeping the last distance (after 0.5 s a median 23-30 mm off, against 11-12 mm).
## Skeleton
After the 3D step, ft-hands fits a skeleton with your own bone lengths to each hand (`track/skeleton.h`), so fingers keep their length and don't wobble. It's the base for a hand mesh, colliders and the hand ray. `--skeleton 0` (`HANDS_SKELETON=0`) turns it off.
- **Bone lengths, per side.** From clean stereo frames (residual under 4 mm, the model sure of the side), each of 30 numbers is learned: the thumb's CMC and the four knuckles' places in the palm, and the 15 finger bones. A landmark whose two rays miss each other by more than 4 mm, a finger bent more than 90 degrees, or a bone far off the average hand's proportions (under 0.7 or over 1.5 times them) gives no sample. Each settles on the median of its first 45 samples (3 s of a clean hand at 15 Hz), then moves at most 0.02 mm a sample. Until then the estimate is pulled toward a prior: the other side's lengths if it has more, else MediaPipe's average hand times `Hand::scale`. Nothing is saved: each start learns again.
- **The fit, every frame.** The palm is rigid: its frame from the wrist and knuckles, then Gauss-Newton on its rotation and position. Then the thumb and each finger as a chain from its base: the thumb's CMC turns three ways (±50 degrees from a rest pose, ±35 twist), its MCP bends and spreads a little, its IP is a hinge; a finger's knuckle bends (-35 to 95 degrees), spreads (±25, the little finger ±30) and twists a little (±25), the two joints above it are hinges (-10 to 110, -20 to 90). A chain's base may sit up to 15 mm off the rigid palm, pulled back with a 4 mm prior: the measured knuckles wander far more than a palm bends (the little finger's by 3 cm across the palm). Each chain runs 4 Gauss-Newton steps (the limits as clamps) twice, from the measured bone directions and from last frame's pose, and keeps the better fit, so it doesn't hop between two poses that fit about as well.
- **Weights.** Stereo: each landmark by its own ray miss (2 mm at least), and 3.5 times less sure along the line of sight. One view: 3 mm across, 15 mm along it.
- **Which side.** The model's, but a tracked hand keeps its side while the model's running call is between 0.25 and 0.75. The mirror image is tried when the fit is worse than 15 mm rms, and taken after it fits at least twice as well 3 frames in a row; it then sticks while the hand is tracked (a finger can't bend backward, so a hand fitted as the wrong side fits badly once its fingers bend). Switching restarts the filter.
- **Filtering the pose, not the points.** The palm centre and the palm's rotation go through One Euro filters (2 Hz still, plus 30 Hz per m/s and 10 Hz per rad/s); each finger's angles and base through one whose cutoff follows that finger's own speed (2 Hz plus 3 Hz per rad/s), so a pinch on a still palm doesn't lag the way the One Euro on the points does. A chain that fits its landmarks worse than 15 mm this frame moves its filter less (by the square of 15 mm over its error): that's mostly a hidden landmark misplaced.
- **Elbow.** frame-hands' arm model (`notes/forearm.md`): a neck pivot fixed in the head frame, shoulders 18 cm to each side and 6 cm down, upper arm 1.5 times the forearm, the forearm 2.8 times the palm (wrist to middle knuckle), the elbow on the circle the two bones allow, turned 3 degrees from straight down, and never more than 75 degrees off the hand's own axis. ft-hands has no HMD pose, so "down" is the head frame's -y: published with `FH_FIT_ELBOW_HEAD_UP`. The model's other parameters (neck and shoulder offsets) are its starting values: the fitted ones are on the training PC.
- **Published** in the hands file's version 2 (`include/fh_hands.h`): after version 1's struct, which is unchanged, an `fh_hand_fit_t` per hand with the 21 joints (position, a rough radius, and a quaternion in OpenXR's hand-joint axes), the bone lengths, the joint angles, the elbow, the pinch point (between the index and middle knuckles) and the thumb-index contact point, the thumb-index and thumb-middle distances, the fit's rms and how settled the calibration is, and the palm's velocity and angular velocity. Those two are in the head frame and include the head's own motion; for motion in the room, difference room-frame points across publishes as `screens/handcut.cpp` does. Version 1's points and capsules are the skeleton's too, so ft-screens' cutouts get it without a change. The hand recorder's reader takes version 1 or 2.
- The gestures don't use it: pinches still measure the model's world landmarks, and the pinch point and palm-down reading still come from the filtered landmarks. `ft-handreplay --pinch-fitted` counts pinches on the fitted tips for comparison: they begin about as often as on the triangulated tips, more than on the world landmarks.
What it measured, `ft-handreplay` on three recordings and three takes of the 2026-10-03 hand-recorder session (frame-hands `notes/skeleton-fit.md` has every number):
| 2026-09-29/30 recordings, 30 Hz | dim (typing) | lit | bright |
| --- | --- | --- | --- |
| Bone length spread per track (median CV): measured / One Euro / skeleton | 0.41 / 0.37 / 0.05 | 0.24 / 0.22 / 0.03 | 0.39 / 0.35 / 0.01 |
| Index tip jitter, hand and fingers still, mm (median; 90%): One Euro / skeleton | 4.5 / 3.9; 16.9 / 24.3 | 3.4 / 2.8; 11.0 / 14.7 | 4.2 / 3.2; 11.5 / 10.2 |
| Thumb tip jitter, still, mm (median; 90%) | 3.0 / 2.7; 12.0 / 11.8 | 2.4 / 2.7; 7.8 / 12.0 | 3.0 / 2.2; 10.1 / 8.7 |
| Index tip jitter, palm over 0.3 m/s, median mm | 14.0 / 11.2 | 11.0 / 8.6 | 17.7 / 14.7 |
| Palm jitter, still, median mm | 1.8 / 1.8 | 1.9 / 1.8 | 1.9 / 1.8 |
| Tips trailing, moving over 0.5 m/s, median mm | 6.5 / 5.7 | 5.1 / 4.9 | 5.7 / 4.9 |
| Tips trailing, fingers moving on the palm, median mm | 7.8 / 3.5 | 5.9 / 4.7 | 4.6 / 3.5 |
| Palm normal's turn per update, palm still, fingers moving, median degrees | 2.8 / 1.7 | 2.2 / 1.3 | 2.3 / 2.0 |
| Fit rms against the measured landmarks, stereo, median mm | 10.4 | 9.0 | 7.6 |
| Calibration settled after each side's first sample, s (left, right) | 20.5, 10.9 | 10.8, 3.5 | 15.6, 8.9 |
- **Against the auto-labels** (frame-hands' teacher, triangulated, smoothed and fitted: not ground truth; three takes of the PR #3 session, 10 Hz, stereo hands): mean landmark error measured 10.2, 12.1 and 7.0 mm, the fit before its filter 10.4, 12.2 and 6.5 mm (pose sweeps, gestures, desk work). The index tip: 8.1, 7.7 and 7.9 mm measured, 8.7, 8.7 and 5.5 mm fitted. The labels' ring and little knuckles sit far from MediaPipe's (their wrist to little knuckle is 110-140 mm against our 80-99), so part of every number is the two models' conventions.
- **Cost:** 41-43 us a hand (median; 90% 61-70 us, 99% 91-164 us) on an A720 core, the fit alone replayed on CPU 3; 320-350 us on an A520 (CPU 0). ft-hands runs on CPUs 5-7, which are A720s and the X4.
- **Pinches** don't change: the same counts in every replay, because they don't use the skeleton. On the fitted tips they'd begin more often (lit: 77 against 51; dim: 50 against 35), which is why they stay on the world landmarks.
- **Worse:** the fingertips' jitter tail with the hand still in the dim and lit recordings (index 90% 24 against 17 mm, 15 against 11 mm; thumb in lit 12 against 8 mm). That's the price of each finger's own cutoff: a misplaced tip that the skeleton can reach (a few frames of a hidden finger) gets through where the palm-speed One Euro held it. The fitted landmarks also sit further from a centred average of the measured ones (moving fast: 11.7 against 9.3 mm in lit), mostly the fit's own residual: the labels don't say the fit is the worse of the two.
- **Elbow:** the forearm comes out 231-247 mm, a median 21-27 degrees off the hand's own axis. With gravity's up from the takes' HMD poses instead of the head's, it moves a median 0.6-2.2 degrees (90%: 2.2-5.0): the head-up assumption costs little at a desk. No elbow labels are here to say how right it is.
## Pinch
ft-hands detects a pinch per hand (`track/pinch.h`) and publishes it to the gestures file. The layout, and how to read it without missing quick taps, is in `include/fh_gestures.h`.
- A pinch begins when the thumb and index tips come within `--pinch-begin` (default 0.020 m). It ends when they open past `--pinch-end` (0.035 m) for 2 processed frames in a row, or when the hand stays lost for 0.25 s (flagged lost).
- A pinch begins when the thumb and index tips come within `--pinch-begin` (default 0.020 m). It ends when they open past `--pinch-end` (0.045 m) for 2 processed frames in a row, or when the hand stays lost for 0.25 s (flagged lost).
- A pinch held 0.3 s or longer is a drag, and holds on harder: it ends only once the tips are 5 cm apart (for the same 2 frames), or 0.12 s after they first went past 3.5 cm unless they closed back under 3 cm meanwhile. In the 2026-10-09 headset test drags ended with the tips 3.5-4.0 cm apart, a thumb hidden for a frame or fingers loosened a little mid-drag. On the lit recording's replayed distances, pinches held 0.3 s or more (typing among them) ended 33-134 ms later than before, 200 at most, and one of 25 ran into the next pinch's begin. A grip ends a pinch (as lost) only within 0.3 s of its begin, when closing the hand passes through a pinch; after that no grip begins on that hand, so curling the other fingers around a held pinch doesn't drop it (3 of 28 pinches in the same test). `tests/pinch_test.cpp` (`make check`).
- The distance comes from MediaPipe's world landmarks: the model's own 3D hand pose, averaged over the hand's views, at the user's hand size. `--pinch-triangulated` uses the triangulated tips instead. On two recordings without deliberate pinches, the world landmarks came under 2 cm in 0.2-1% of frames, against 3.3-4.5% for the triangulated tips. In the dim recording, typing still gave 2 pinches a minute (see the next point).
- `--pinch-palm-down MAX` holds back pinches begun with the palm facing down (MAX is the palm normal's share of the head's up axis). The default, 1, turns it off. A close held back that way has to open again before a pinch can begin. Typing curls the thumb onto the index: in the lit recording of 2026-09-30, typing on a keyboard in the lap began 23 pinches in about 2 minutes, all with the palm facing down (0.69-1.00), while the 26 deliberate ones read 0.00-0.50. But in the headset, deliberate pinches with the hand raised in front read 0.90-0.99 too, so the limit is off. Typing is caught by the pointer helper instead: the input relay tells it when you press a key, and no pinch begins within `POINTER_PINCH_TYPING` of one.
- `--pinch-palm-down MAX` holds back pinches begun with the palm facing down (MAX is the palm normal's share of the head's up axis). The default, 1, turns it off. A close held back that way has to open again before a pinch can begin. Typing curls the thumb onto the index: in the lit recording of 2026-09-30, typing on a keyboard in the lap began 23 pinches in about 2 minutes, all with the palm facing down (0.69-1.00), while the 26 deliberate ones read 0.00-0.50. But in the headset, deliberate pinches with the hand raised in front read 0.90-0.99 too, so the limit is off. Typing is caught by the pointer helper instead: the input relay tells it when you press a key, and the hands on the keys are held back (`POINTER_PINCH_TYPING` and the settings after it, below).
- A hand a pinch is down on stays with that side until the pinch ends. The left/right call is a running average of the model's, and when it flipped mid-pinch, the other side took the same hand and both sides pinched at once.
- The pinch point is between the index and middle knuckles, which hold still while the fingers open and close. The tips' midpoint moved 1-2 cm as a pinch opened, which dragged every release off its press. A drag is the pinch point now, minus where it was when the pinch began, both turned into the room with the HMD pose at their capture times.
- `tools/watch_gestures.py` prints begins, ends and drag offsets live, and `--distance` prints each hand's distance.
@@ -166,26 +227,45 @@ ft-hands detects a pinch per hand (`track/pinch.h`) and publishes it to the gest
With `POINTER_HANDS=1`, the pointer helper (`pointer/helper/ft-pointer.cpp`) reads the gestures file every frame. It's off by default.
- **Pinch to click.** In gaze mode a pinch works like the mouse's press: the pointer stops where the gaze put it, and the click comes when the pinch opens, where the pointer is then. A quick tap clicks where you looked. Held, the pinching hand moves the pointer to correct the gaze, and the correction is a lesson for the gaze tracker, as with the mouse.
**The hand ray** (`POINTER_HAND_RAY=1`, the default with `POINTER_HANDS`): a bare hand raised in front and pointing, palm away, shows a ray from it, Quest-style (`include/fh_ray.h`: from a shoulder estimated from the head, through the knuckles), and the ray drives the pointer's virtual controller, so it works on SteamVR's dashboard, Steam's pages, overlays and Frametop's panels like a controller's laser. With the ray up, a pinch clicks (a held pinch drags), a middle pinch right-clicks (held and moved, it scrolls), and while a pinch carries a panel, reaching out pushes it away and pulling in brings it near. With the hand low or the palm toward you, there's no ray, and pinches and grips work as below. In gaze mode there's no ray at all unless `POINTER_GAZE_HAND_RAY=1`. A hand holding a controller, or whose controller was used in the last seconds, has no ray and no gestures (the helper's handoff, `pointer/helper/handoff.h`). The rules, timings and measurements are at the top of `ft-pointer.cpp` ("Handoff", "Hand ray") and in frame-hands' `notes/hand-interaction.md`. `pointer/tools/rayeval` runs the ray over a replay (`ft-handreplay --ray`).
- **Pinch to click, in gaze mode.** Your eyes aim and your hands click, Vision Pro style, and the hand ray stays off (`POINTER_GAZE_HAND_RAY`). A pinch locks the pointer where you were looking just before the fingers began to close (75 ms before ft-hands saw the pinch, since the eyes often move on as the hand closes), and a quick tap clicks there. Pinch, hold and move the hand to nudge the pointer: nothing moves until the hand has moved 4 degrees (about 3 cm at arm's length), then the pointer follows at 0.3 times the hand's movement. Letting go clicks where the pointer is, and the correction is a lesson for the gaze tracker, as with the mouse. Held still for `POINTER_GAZE_HOLD` (0.5 s) instead, the pinch is a real press at that point, and the hand drags at `POINTER_GRIP_GAIN`. A middle pinch is a right click the same way. Hold a pinch with one hand and pinch with the other: both buttons are down, left for the first hand and right for the second, each until its own pinch opens (a first pinch not yet pressed becomes a press at once, where the pointer is), as when you hold both of a mouse's buttons. The rules and timings are in `pointer/helper/gazehand.h`.
- **Without gaze mode,** a pinch is a real press, like the mouse's button: pressed when it closes, released when it opens, and while it's held the hand drags the pointer. A tap is still a click where the pointer is.
- **Grip to drag.** Closing the hand presses where the pointer is, the hand moves the pointer, and opening the hand releases. So a title bar moves its window, a panel's grab bar carries the panel, and text gets selected.
- **Grip to drag.** Closing the hand presses where the pointer is, the hand moves the pointer, and opening the hand releases. So a title bar moves its window, a panel's grab bar carries the panel, and text gets selected. A panel the hand ray carries by its bar (or a floating window by its title bar) stays upright and facing you wherever the ray takes it (2026-10-13: the ray can't tilt it, so the wrist's turn shouldn't either); a controller's laser still carries it rigidly.
- A pinch ended by losing the hand, or by a grip taking over, doesn't click.
- The hand's movement is taken in the room, from where the eye was when the gesture began, so turning your head doesn't move the pointer. The first gesture while the pointer is off only wakes it. Gestures are ignored in a VR game (unless the dashboard is up), with the headset off, and while the mouse's button is held.
Settings in `~/.config/frametop.conf`:
- `POINTER_HANDS` (0): 1 turns pinches and grips on.
- `POINTER_PINCH_GAIN` (0.5): a held pinch moves the pointer this many times the hand's angle, seen from the eye. Under 1 gives precision.
- `POINTER_PINCH_DEADZONE` (1.5): how many degrees the pinching hand moves before the pointer does, so a tap's jitter and the pinch point shifting as the fingers close don't move it.
- `POINTER_GAZE_PINCH` (1): in gaze mode, 0 turns clicks at the gaze off (pinches and grips with no ray do nothing), leaving the ray when gaze is off and direct touch. Frametop Input Settings' Hands page has the three hand inputs as switches of their own (`hands/handsmode.py`, `methods_of`).
- `POINTER_PINCH_GAIN` (0.5): without gaze mode, a held pinch moves the pointer this many times the hand's angle, seen from the eye. Under 1 gives precision.
- `POINTER_PINCH_DEADZONE` (1.5): without gaze mode, how many degrees the pinching hand moves before the pointer does, so a tap's jitter and the pinch point shifting as the fingers close don't move it.
- `POINTER_GAZE_HAND_RAY` (0): in gaze mode, 1 keeps the hand ray beside the gaze (a raised, pointing hand's pinches are then ray pinches).
- `POINTER_GAZE_PINCH_DEADZONE` (4): in gaze mode, how many degrees a held pinch moves before it nudges the pointer. A tap's jitter and a hand drifting while you look stay inside it.
- `POINTER_GAZE_PINCH_GAIN` (0.3): in gaze mode, past the dead zone the pointer moves this many times the hand's angle. Low, so a nudge is a fine correction.
- `POINTER_GRIP_GAIN` (1): a grip moves the pointer this many times the hand's angle.
- `POINTER_GRIP_BELOW` (0.35): grips that begin more than this many metres below the eyes are ignored, because hands resting on a desk curl like a loose fist. Pinches have no such limit: deliberate ones sat 0.35-0.45 m below the eyes with the elbow resting.
- `POINTER_PINCH_TYPING` (1): no pinch begins within this many seconds of a key press, because typing touches thumb to index.
- `POINTER_PINCH_TYPING` (2), `POINTER_TYPING_RAISE` (0.08 m), `POINTER_TYPING_BELOW` (0.2 m), `POINTER_TYPING_POSTURE` (0.3 s), `POINTER_TYPING_RECENT` (600 s): typing on a real keyboard. For `POINTER_PINCH_TYPING` seconds after a key, no hand pinches, grips, pokes or shows a ray, except one lifted off the keys; a hand that was on the keys stays held back through any pause until it rises `POINTER_TYPING_RAISE` above where it typed (or turns its palm up); both hands down on the keys together count as typing before the first key. `pointer/helper/typing.h` and `docs/hands-typing.md` have the rules and the measurements.
- `POINTER_HAND_RAY` (1), `POINTER_RAY_DEADZONE` (2.5 degrees the ray turns during a pinch before the press drags), `POINTER_RAY_PUSH` (1), `POINTER_RAY_SCROLL` (1; -1 turns scrolling round), `POINTER_RAY_RELEASE` (2 s after the ray goes before a pointer it woke lets go), `POINTER_RAY_GRACE` (0.5 s a hand keeps the laser after its ray drops; the other hand's ray takes it after that, or at once by pinching or raising): the hand ray.
- The ray's smoothing (`include/fh_smooth.h`, through `fh_ray.h`): One Euro filters run in continuous time, so the pointer's pose moves at the helper's rate (about 100 Hz) instead of stepping at the tracker's 15-30 Hz; the direction is filtered on the sphere. `POINTER_RAY_SMOOTH_MINCUTOFF` (0.8 Hz with the hand still), `POINTER_RAY_SMOOTH_BETA` (0.06 Hz more per degree a second it turns), `POINTER_RAY_SMOOTH_HOLD` (0.5 Hz still while a pinch is held: a drag's precision). The reach, push and pull's input, has a heavier one of its own. `POINTER_RAY_STEADY` (1): while a pinch is held (and 0.25 s after), the ray pivots on where the shoulder was at the press, then eases back to the body model over 0.5 s; the model's shoulder follows the head, which made looking around move what was dragged. `POINTER_RAY_TAP` (0.3 s) and `POINTER_RAY_TAP_DEADZONE` (6 degrees): a pinch's first 0.3 s takes 6 degrees of turn before it drags, so a quick tap whose hand swung stays a click; after that `POINTER_RAY_DEADZONE` applies. When the press starts dragging the pointer carries on from where it was, no jump. On the probe-moves replay (`pointer/tools/rayeval` on `frame-hands/dumps/probe-moves-v4.dump`, read at 90 Hz) the pose's second difference per tick went from 0.90-0.96 degrees rms (p90 1.4) to 0.24-0.26 (p90 0.24) at about the same lag (110 ms behind the capture, against 105).
- The ray's body and hand models (`include/fh_ray.h`; ideas and formulas from StereoKit, MIT): `POINTER_RAY_TORSO_WRISTS` (1): the shoulders face between the head (counted twice) and the wrists seen, so looking aside while pointing swings the ray less. `POINTER_RAY_HAND_WEIGHT` (0; 0..1): how far the ray turns from the shoulder's line toward the hand's own direction (`POINTER_RAY_HAND_PITCH` -30 and `POINTER_RAY_HAND_YAW` 8 degrees off the palm's axes). `POINTER_RAY_ANCHOR` (0): the knuckle point pinned to the palm while a pinch is held. The last two measured worse on replays (`pointer/tools/rayeval`; numbers in `fh_ray.h`), so they're off.
## Flags
When tracking goes wrong in real use, flag it: `ft-handsctl flag [note]`, or by voice with frame-voice's voice commands (its `commands` setting: "flag that" runs `ft-handsctl flag` with the words after it as the note, e.g. "flag that, fingers crossed"). The offline tools (frame-hands' `train/flags`) relabel what was saved with the teacher, find what went wrong and in which situations, and make guided capture sessions for the weakest ones.
ft-hands keeps a rolling buffer in RAM (`track/flagbuf.h`, `HANDS_FLAG_BUFFER=1`): per processed set, a mono crop around each view the tracker used (its landmark crop's centre, 1.6 times its size, axis aligned, at most `HANDS_FLAG_CROP` px a side), with where it is in the image, so labels made on it lift back to the image and triangulate; a lost view is still cropped where it was for a second, so the teacher can say whether the hand was there; and its hands, gestures and each view's landmarks. It keeps `HANDS_FLAG_SECONDS` and at most `HANDS_FLAG_MB` of crops; nothing is written until a flag. Cost, measured (2026-10-09, a replayed ring with two hands in view): about 80 crops a second at 20 sets a second, 56 MB of crops for 14 s at 224 px (ft-hands' peak RSS 101 -> 159 MB), and 0.1 ms a crop on a tracking core (A720), so about 1% of a core; ft-hands' CPU time was the same with and without it. At 30 sets a second with four views the 80 MB cap can trim the oldest seconds.
`ft-handsctl flag` makes `HANDS_FLAG_DIR/flag-<time>/` and asks ft-hands for the buffer through `run_dir/flag`; ft-hands keeps going for 2 s more, then a thread of its own (off the tracking cores, lowest priority) writes `manifest.json` (written last), `sets.jsonl`, `crops.jsonl` and `crops.bin`. Once ft-hands has taken the request, the drawn hands pulse cyan for half a second (ft-handview's `flash`; `HANDS_FLAG_FLASH=0` turns it off; `HANDS_FLAG_TONE=1` also plays a short tone). It returns then, and in the background saves one frame of your view from `/dev/video99` as `view.jpg` (`HANDS_FLAG_VIEW=0` skips it), the head's poses over the window from ft-handview (`poses`) as `hmd.jsonl`, and `ctl.json`. ft-hands logs each flag ("flag:", "flag written:"), and the status line has the buffer's size and cost. A flag while one is being taken adds its note to it. The format is in frame-hands' `notes/flag-failures.md`. The crops show your hands and some of the room: keep flags with your recordings.
`ft-handreplay REC --flag-at S1,S2 --flag-out DIR` (or `--flag-every S`) makes the same flags from a recording, with the same buffer, for testing the offline tools before real flags exist; `--flag-crop PX`, `--flag-scale F`, `--flag-mb MB` and `--flag-seconds S` change the buffer.
## Recordings
`hands/build.sh --tools` also builds the offline tools.
`ft-handreplay DIR` runs a recording through the tracker with the live scheduling and reports how well it kept the hands: hands per set, left and right coverage, track lengths, pinches, jitter, and the same reasons as the status line.
`ft-handreplay DIR` runs a recording through the tracker with the live scheduling and reports how well it kept the hands: hands per set, left and right coverage, track lengths, pinches, jitter, and the same reasons as the status line. `--publish-dump FILE` also writes what ft-hands would have published after each processed set (the hands and gestures files' bytes, and the set's dequeue time), for ft-screens' offline tests; a hand-recorder take's `poses.jsonl` and `prompts.jsonl` copied next to the dump as `NAME.poses.jsonl` and `NAME.prompts.jsonl` give them the head's poses and the touch take's targets (`scripts/test-handinput.sh`, `scripts/bench-matte.sh`). To match the live tracker, replay with `--reacquire 1.5 --reacquire-fast --pair-sides --hold 0.6` and the models in use.
```
hands/build/ft-handreplay ~/.local/share/frametop/hands/rec-20260929-120000 --cost --oracle 10 --timeline /tmp/tl.txt
@@ -195,9 +275,16 @@ hands/build/ft-handreplay ~/.local/share/frametop/hands/rec-20260929-120000 --co
- `--oracle N`: every N-th set, also search every tile of every camera, and report how often the tracker had the hands that full search could find.
- `--slow F`: live, the tracker skips sets that arrive while it's busy. Replay counts each step's time times F as busy (default 1; the headset is busier live).
- `--timeline FILE`: a line per processed set and hand, with pinch events and distances.
- `--ray FILE`: a line per processed set and hand with what the pointer helper's hand ray reads (time, side, stereo, pinch and grip state, the published points, the wrist's frame, the elbow), for `pointer/tools/rayeval` with the same session's `ft-handtest` probe log (head poses).
- `--cams mono|color|all`: which cameras to track with (default `mono`). `color` tracks with the Arcturus pair alone, for comparing it with the IR cameras on the same recording. It needs a recording made with `ft-camd --with-color`. `--color-left NODE` (`color_video0` or `color_video3`) and `--color-crop subtract|none` say how the module's calibration maps onto the images; `tools/check_color.py` finds out.
- The skeleton (see "Skeleton"): the report ends with its measures for the measured, One Euro filtered and fitted landmarks (and the fit before its filter): its time per hand, also on its own pinned to a little and a big core; its rms; each side's calibration and when it settled; how much bone lengths spread per track; jitter at rest and moving for the palm and the thumb and index tips; how far the tips trail during fast motion (against a centred average of the measured tips); how steady the palm's normal is; and the elbow. `--no-skeleton` replays without it; `--skel NAME=VALUE` changes a setting (`skel::Params`); `--labels FILE` compares with frame-hands' auto-labels (`labels.jsonl`), `--skeleton-dump FILE` writes the matched hands; `--hmd-poses FILE` (a take's `poses.jsonl`) compares the elbow with gravity's up against the head's; `--pinch-fitted` counts pinches on the fitted tips too.
- A hand-recorder take is a recording too: its `sets.bin` is followed by `sets-2.bin` and later parts, which are read in order. It has no `sides.json`: whether its side cameras need exchanging is `take.json`'s `names_swapped` against `session.json`'s `sides` (`rec/sides.py`), so give `--sides 0` or `1` (`--sides auto` checks from the hands).
- `--depth FILE`: a line per hand per processed set for `tools/depth_report.py`, which measures the depth without ground truth: how the hands were seen, the noise along the line of sight against across it, each camera's one-view distance against the triangulated one, and what a camera dropping out would do.
- The pinch, contrast and presence options are ft-hands'.
- The pinch, contrast and presence options are ft-hands'. `--reacquire S` (off unless given; `--reacquire-fast` searches every set as ft-hands does, `--reacquire-tiles N`, `--reacquire-clear M`), `--pair-sides`, `--hold S`, `--near F` and `--search-budget N` are the tracker's re-acquire settings, off or at their old values by default so old replays repeat.
- `--cost-hand MS`, `--cost-palm MS`: with `--cost`, what a round of landmark and palm calls costs. The defaults (10, 18) are the headset's idle costs. The 2026-10-08 live probe (CPUs 0,1,4 beside SteamVR, 3 threads) measured about 14 and 52, and the live tracker loses hands far more at those costs.
- `--drop-every S`: the re-acquire test. Every S s, while two hands are tracked, one of them is made invisible for 0.35 s (just past the 0.3 s the tracker holds a lost hand), and the report gives how long it then took to have two hands again: the time to find a hand that never left the view.
- `--flag-at S1,S2`, `--flag-every S`, `--flag-out DIR`: flags as `ft-handsctl flag` makes them live (see "Flags"), at those times into the recording.
- With `--timeline`, the tracker also writes why views and hands came and went (`ev` lines: lost, miss, split, search and its tiles, palms kept or rejected, new, forget, pair-sides), and `--oracle` writes what the full search found. `tools/gap_report.py TIMELINE --list` turns that into every gap of 0.3 s or more per side, with its cause. `tools/replay_gaps.sh OUT MODELS "ARGS" REC...` runs several replays at once (on the 7i through frame-job) and reports them. For pinches, `--tips FILE` logs each hand's thumb, index and middle tips and the pinch detector's distance measures per processed set, with its pinch events; `--rate HZ` fixes the processing rate (15 or 30, against the live rule) and `--want-hz HZ` plays a reader asking for it; `tools/replay_tips.sh OUT NAME=MODELS "ARGS" REC...` runs them (frame-hands' `train/taps/tapeval.py` scores them against auto-labels).
`ft-ringplay DIR --ring PATH [--from S] [--to S] [--loop]` publishes a recording into a ring file in real time, as ft-camd would, so `ft-hands --ring PATH --no-publish` runs the same frames run after run. It needs no privileges, and it skips the dark frames.
@@ -212,8 +299,96 @@ Python, with NumPy and OpenCV. `setup/dev-container.sh` doesn't install them, be
- `tools/depth_report.py DEPTH`: the depth measures above.
- `tools/cut_sets.py REC OUT [--sets N | --at I,J,...]`: copies a few frame sets (by default 8, spread evenly) out of a recording into a small one, to look at or check elsewhere without moving gigabytes. Plain Python, so it also runs on the Frame's host.
- `tools/convert_models.py`: how `models/ncnn` was made from the OpenCV Zoo ONNX ports of MediaPipe's models (see `models/NOTICE`).
- `models.sh`: fetches the fine-tuned models into `models/student` (`hands/build.sh` runs it, so source installs and the release image both get them): MediaPipe's two models retrained on the Frame's infrared cameras with the [Frametop Hands](https://huggingface.co/datasets/DeeJanuz/frametop-hands) dataset, from a fixed commit of [DeeJanuz/frametop-hands-models](https://huggingface.co/DeeJanuz/frametop-hands-models), each file checked against its SHA-256. They're licensed CC BY-NC 4.0 (non-commercial), not MIT, so they aren't in this repository; `models/student/LICENSE` and `README.md` come with them. `hands/models.pin` pins them: the commit, the version folder and every file's sum (frame-hands' `model-repo/pin.py` writes it); `hands/models.sh check` checks them against it. Installs don't need a release for a new version: when hand tracking starts, `frametop-hands.service` runs `hands/models.sh auto`, which reads `hands/models.pin` from GitHub (main for a stable release, experimental for an experimental one or a clone on that branch; at most every 15 minutes, within a minute) and, if it pins other models, fetches them into `models/.student-new`, checks every sum, and swaps that folder in whole. Offline, or anything not matching, it keeps the models it has. A pin only names the files above, and its `format` says which ft-hands it needs: raise it when a model needs a newer one, and installs without it keep theirs. `HANDS_MODELS_UPDATE=0` turns it off; `hands/models.sh update` checks now.
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.
To try the hand cutouts without restarting the desktop, `screens/build/ft-handtest [--distance m] [--width m] [--seconds s] [--matte circle|mesh|capsules] [--margin deg]` (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. Every 2 s it prints the composite's cost.
## Hand cutouts and near input
ft-screens reads the hands file (version 2's skeleton when it's there, else version 1's points) and the gestures file once per tick (`screens/handcut.cpp`). It cuts only with Room View on: with it off, a hole would show the void or the game, not your hand (see "Rendered hands"). `cutouts state` ends with `room view on|off (why)`; `cutouts roomview auto|on|off` forces it.
**Off by default since 2026-10-09** (`HANDS_CUTOUTS=0`): ft-handview draws the hands over the panels instead (see "Rendered hands"). `HANDS_CUTOUTS=1`, or `ft-handsctl cutouts on` for the session, brings the holes back.
**The matte** (`HANDS_MATTE=circle`, the default since 2026-10-09) is a round hole per hand: a disk facing the eye, centred on the middle of what the head sees of the hand (the box around its joints, each with its half-width, the wrist's 2.5 cm), wide enough to reach the hand's furthest edge from there, plus the margin. Each eye sees the disk on the screen as an ellipse (a circle on a screen square to it), drawn as the stadium around it with the capsules' soft edge (15% of its radius). It hides more of the screen than the hand needs, and with it the hand's tracking error and the few degrees Room View's picture of the hand sits off it, until the tracking is good enough for a hand-shaped hole. The forearm isn't in it. Building and projecting it costs 4 us median on the desk-work replay (the mesh 26 us), the composite the same as the mesh's or less (`scripts/bench-matte.sh` on probe-moves: 2 pieces per eye against 35).
`HANDS_MATTE=mesh` is hand-shaped: a tapered capsule per finger bone, with real fingers' half-widths (10.5 mm at the index's knuckle down to 7.5 mm at its tip, scaled by the hand's palm length); the palm as a 2.4 cm slab through the wrist and the knuckles, widened to the hand's edges; the thumb's web; and an 18 cm stub of the forearm toward the skeleton's elbow (along the hand's axis without a skeleton). The palm, web and forearm are convex pieces, each drawn as its outline grown by the margin with a soft 2 px edge. `HANDS_MATTE=capsules` draws ft-hands' capsules instead, as before, for comparison (`cutouts matte circle|mesh|capsules` switches it live).
Its margin is an angle seen from the eyes, so it covers the same share of the tracking error at any distance: `HANDS_MATTE_MARGIN` (1.5 degrees) with the hand still, plus `HANDS_MATTE_MOTION` (25 ms) of the hand's motion, at most `HANDS_MATTE_MOTION_MAX` (1.5 degrees) more. The cutout placement probes of 2026-10-08 (frame-hands `captures/probe-2026100*/video_analysis`) measured the cutout points against the hand Room View shows: 1.8-2.4 degrees median still (p90 4.1-4.7), 2.3-3.1 moving at 0.1-0.8 m/s, 4-6 above 0.8 m/s. Part of that is the video landmark model's own error, and an edge needs only the error across it (about 70% of a point's). A margin covering the p90 (4.5 degrees, 3 cm at 40 cm) would turn each finger into a 7 cm blob; 1.5 covers about the median. `cutouts margin DEG [MS [MAX]]` changes it live, and so does the Hand cutout margin slider on the Hands page of Frametop Input Settings (0-3 degrees in quarter steps; it sends the still margin only and writes `HANDS_MATTE_MARGIN`). The prediction lead stays 36 ms (`HANDS_MATTE_LEAD`, `cutouts lead`): the probes' best lead for fast hands was 6-14 ms, but 36 costs only 0.1-0.2 degrees.
The probes also saw the hand's picture off by an amount that depended on its distance, but not the same way in any two runs, so the correction is a hook, off: `HANDS_MATTE_SHIFT="0.35:0.5,-0.3 0.6:-1,0"` would turn the matte's hands by those yaw and pitch angles (degrees, right and up positive) at those distances from the head, in between linearly (`cutouts shift ...|off` live).
Cost, offline (`scripts/bench-matte.sh` on the probe-moves and lit replays, a 3440x1935 screen 0.6 m ahead, GPU time to finish each buffer on an otherwise idle GPU): the mesh 3.9-4.1 ms per full buffer against 3.8-3.9 for the capsules, and 3.4-3.6 against 3.0-3.4 when only the hands' boxes are redrawn (the margin is wider than the capsules' 4 mm). CPU 0.2 ms per composite either way; building and projecting the matte 14-24 us median.
**Near input** (`screens/handinput.cpp`, frame-hands `notes/hand-interaction.md` sections 3, 5, 16, 17, 18 and 19): a bare hand whose index tip, thumb-index contact, knuckles or palm is over a panel (or within the grab band outside it) and within `HANDS_NEAR_REACH` (0.075 m, about 3 inches; 0.30 on 2026-10-10 before the live test, 0.15 before that) in front of it touches it: ft-screens tells the pointer helper so ("near ... 1"), which then hides that hand's ray and leaves its pinches and grips to ft-screens. Beyond it a pinch is the ray's or the gaze's. A hand stays near until it's 2.5 cm farther out, then 200 ms on, so the ray doesn't flicker at the edge; in that margin the ray stays hidden ("near ... 2") but the hand's pinches are the helper's again. The ray shows again once its pointing pose has held 120 ms, about 0.35 s after the fingertip passes 10 cm. A hand resting low by the body (the poke's resting rule below: typing, the lap) touches only within 4 cm, so a low panel within reach doesn't take its gaze pinches. While a hand is within 0.30 m of a panel, ft-screens asks ft-hands for its full rate (want-hz), so a tap from outside the zone is seen at 30 Hz. Near a panel:
- **Poke to click:** the index fingertip presses when it comes at the panel's face (user, 2026-10-08): past the surface for two hands frames in a row, or for one when it came in decisively (1.7 cm in on average over the last 0.3 s, on its way in on the frame before too, at 0.1 m/s or more, and under 2.5 cm in coming nearer on each of the last 3 frames: `HANDS_POKE_TRAVEL`, 0 = always two frames; 2.5 cm until the second live test of 2026-10-10, which refused taps that came 1.7 and 2.0 cm). A quick tap at 30 Hz is past the surface for one or two frames, and one the tracker has a centimetre short for none: two frames in a row lost most shallow taps in the live test of 2026-10-10. It also needs: seen by two cameras, moving into the surface at 4 cm/s or more when it crossed (over the last 100 ms), the finger (knuckle to tip) within `HANDS_POKE_ANGLE` (50) degrees of the panel's normal, the index straight (1.5) and either no other fingertip more than 6 mm deeper than its tip or the hand pointing (the index straighter than each other finger by 0.2; until the second live test the index had to be 5 mm nearer than the others, and the tracker often reads a pointing hand's middle finger nearly as straight, its tip within -7 to +4 mm of the index tip's depth: 14 of its 39 refusals), not past the surface for more than 5 frames or 4 cm (reaching through), and not from a hand resting low by the body (palm more than `HANDS_POKE_REST_BELOW`, 0.30 m, under the eyes and within `HANDS_POKE_REST_NEAR`, 0.32 m, of the head across the floor; it stays resting until 5 cm higher or further out). So typing under a low panel doesn't poke it, and reaching out to one does. It lets go 1.5 cm out, or 1 cm back from the deepest point (so a tracker that has the finger behind the panel still lets go). The click stays where it was pressed until the fingertip slides 1.5 cm; then it drags. No new press for 150 ms after a release, nor until the tip has been 1 cm out (a noisy pull-back pressed twice); a finger 8 cm through the panel lets go and needs to come back out first. Within 5 cm the pointer follows the fingertip. A tap up to 1.5 cm past the content's edge presses at the edge (the desktop's taskbar is on the bottom edge). The curve, reset, dock and close buttons take pokes too (below: Buttons). The index crossing the plane farther off the content (a hand reaching for the bar or a corner) isn't a poke: ft-screens logs it once, as "not a poke", with where it crossed. On synthetic taps with 3-6 mm of tracking noise, 50-56 of 60 shallow taps (0.5 cm past the surface) press, against 34-36 with the two-frame rule; a finger held still 1.5-2.5 cm out presses no more often than before (`handinput-test`, TestPokeNoisy).
- **The hand owns the pointer:** while a hand holds the button, SteamVR's laser moves (the pointer helper's head or gaze pointer, a controller) go nowhere, and on a panel whose pointer a fingertip moved in the last 250 ms neither do they. Before, the helper's pointer a few cm off the fingertip pulled the remote host's pointer away between the poke's press and release: a drag, not a click.
- **Why a poke didn't press:** ft-screens' log has a line for each press and release ("hands: right poke pressed screen 104 at 1932,869 (-0.6 cm, in at 0.25 m/s from 3.1 cm out, 1 frame(s) past, the finger 12 deg off)"), and for each time the fingertip crossed a panel's surface without a press, the rules that held it back ("hands: right poke on screen 104 didn't press (0.4 cm deep at most): past the surface for 1 frame(s); ..."). `handinput state` counts them.
- **Pinch to move or resize:** a pinch where the thumb and index meet (not the gestures file's point, the knuckles, 5-8 cm behind them) within the border band takes the panel: 6 cm outside its edges to 2.5 cm inside (`HANDS_GRAB_BAND`), anywhere in the touch zone's depth (in front of it, or a little behind), or up to 3 cm beyond it when the touch zone has the hand (the third live test: "the fingers +9.0 cm from it, out of the touch zone: nothing", the pointer helper having left the pinch to ft-screens). By any corner (6 cm) it resizes, and the opposite corner stays put: a screen or remote display along its diagonal (its aspect is its resolution's), a floating window in pixels from that corner (every corner of a window since 2026-10-10, its title bar's ends too). Anywhere else on the border, the bar, a floating window's title bar, it moves. Moved, it follows the knuckles 1:1 (closer and farther too) and keeps facing you. A soft white glow shows where a pinch would take it (below: Glows at corners, edges and buttons); with `HANDS_EDGE_GLOW=0` the resize handle goes to the corner a pinch is near instead, brighter the nearer, lit blue while resizing. With `HANDS_CUTOUTS=1` a glow on the panel also shows what a pinch would do there: amber at the corner (resize), blue on the border (move), green for a card pinch; a dot while it holds. (The glows are drawn into the cutout buffer, so with the cutouts off, the default since the drawn hands, they don't show.)
- **Resize from any corner, by hand, gaze or laser** (2026-10-10, as on a Vision Pro): each panel has one resize handle, and it goes to the corner something aims at: a laser's ray (a controller's, or the pointer helper's, which the gaze and the hand ray drive) landing within a fifth of the panel's height (5-20 cm) of a corner (or a hand's pinch at one, with `HANDS_EDGE_GLOW=0`; hands have their own glow since the fourth live test). Since 2026-10-13 (user: "remove the radio icon thing on corners for resizing and replace them with the glow that is used for grabbing with hand tracking") the handle draws nothing: the same soft white L round the corner as a hand's pinch gets shows it, brighter as the aim comes to the corner, brightest while resizing (the handle is still there, just outside the corner, to take the laser's press); with no aim for 0.4 s it goes back to the bottom right. Press it with the laser, or look at it and pinch (a gaze pinch on a resize handle or a grab bar is a press after 0.12 s held still, `POINTER_GAZE_CONTROL_HOLD`, not the 0.5 s elsewhere), and drag: the corner follows, the opposite one stays put.
- **Pinch on the content to click** (`HANDS_PINCH_CLICK`, 2026-10-10): a pinch within the touch zone, not in the band, presses where the fingertip's pointer was (if it was there in the last half second, within 4 cm of the fingers), else where the fingers meet; it's held while the pinch is, and moving the pinched hand 1.5 cm drags. Not from a hand resting low by the body or seen by one camera.
- **Card pinch** (`HANDS_CARD_PINCH`, 2026-10-10: "pinch from underneath the display and manipulate it like a card"): a pinch closing on the panel's edge with the panel between the thumb and the index (each tip at least 3 mm from its plane on some frame in the last 0.3 s, the line between them within 60 degrees of its normal, the hand along the panel: at least 45 degrees off its normal, the fingers within 5 cm of its border), and the index and middle fingers together against the thumb (thumb to middle tip within 4.5 cm, index to middle tip within 3.5 cm) or all four fingertips bunched at it (each within 5 cm: the "pinched fingers" hand), holds it like a card (since the second live test; the index alone was enough before, and is now the border's move or a corner's resize; the middle finger joining within 0.3 s of the pinch makes the move a card from there): it goes rigidly with the hand, its place and its turn about all three axes, 1:1, smoothed, past 1 cm and 3 degrees; no facing you, no level snap. An edge pinch from the front or the side has both tips on one side of the plane, or the hand pointing into it: that's the border's move.
- **Fist grab** (`HANDS_FIST_GRAB`, 2026-10-10: "use the fist to expand and rotate the display, as well as change its angle"): a grip (ft-hands' closed hand) made with the palm, knuckles or curled middle finger within the touch zone over a panel (or within 6 cm of its edge) takes it; so does a pinch by a closed hand (the index 1.15 extended or less, the other three 1.05 or less on average: ft-hands calls a fist with the thumb on the index a pinch, and in the third live test two fists clicked the content instead of grabbing it). It's held while either the grip or that pinch is, until the hand opens: the fist carries it 1:1 and turning the fist turns it about all three axes, as the wrist turns a pinched one (below); open the hand to let go. Two fists (or a fist and a pinch) on one panel stretch it and turn it, as two pinches do. Since the fourth live test (2026-10-10, "I can't grab using fists"): a fist is at a panel with its palm, knuckles or curled middle finger up to `HANDS_FIST_REACH` (0.11 m) in front of it or 10 cm behind it (a live fist went 8.5 cm through and wasn't "at it"), and a hand curled that far (the three fingers under 1.2) is ft-screens' that far out, so the pointer helper leaves its grip; a pinch on the content by a hand that's closing (the three fingers under 1.4 and down by 0.1 in the last 150 ms: a fist's thumb meets the index first) waits up to 150 ms to become a fist (then a fist grab) before it clicks, where it began. A fist farther away is the pointer helper's grip (a gaze drag). A fist or a pinch by a hand "grab that" has (held out open, or closing into its fist, aiming at a panel it would take) waits until that gesture fires, and then does nothing, or lets the hand go, at most 0.6 s, and then it's what the hand is by then (a fist, a second anchor, or a pinch): an open hand held out to a panel then a fist pulled back and turned over is "grab that", a fist made at the panel without that is a fist grab. At a panel within arm's reach "grab that" doesn't aim, so nothing waits.
- **Turn it with the wrist** (2026-10-10): while one hand carries a panel (by its border or bar, or a fist), turning the wrist turns the panel the same way, 1:1, about all three axes (yaw, pitch, roll), to line displays up. The hand's turn is read from its wrist and index and little knuckles (they hold still while the fingers pinch), smoothed (One Euro, 1 Hz still), relative to facing your head across the floor from the hand, and applied on top of the panel facing you: carrying a panel round you still only keeps it facing you, and a wrist turn adds to that. Nothing turns until the hand has turned `HANDS_GRAB_ROTATE_DEADZONE` (5 degrees; the hand frame jitters about 1 degree a frame and drifts up to 6 over a second and a half held still), then it turns from there without a jump. Within 2.5 degrees of level it snaps level. Let go and it keeps the turn; the next grab starts from it. Corner and tab grabs only resize (letting go with one of two hands, the other's turn starts afresh). `HANDS_GRAB_ROTATE=0` keeps the old facing-only carry. A panel held near the eyes by a point far from its centre (closer than twice that distance) faces you from a point between the hand and its centre: facing from the centre turned it about the hand, which moved the centre, which turned it, and 0.6 m panels held by an edge at arm's reach spun and flipped between frames on the third live test's replays.
- **Two hands:** both hands holding one panel (pinches or fists) stretch it (its width follows their distance, past a 1 cm dead zone) and turn it with the line between them on every axis: swing the pair round (yaw), raise one hand (roll), bring one nearer, and tip both wrists the same way about the line between them to pitch it (the mean of the two wrists' turns about that line, past `HANDS_GRAB_ROTATE_DEADZONE`); it snaps level within 2.5 degrees. `HANDS_STRETCH_TURN=0`: about the vertical only (before 2026-10-10's third live test). Let go with one and the other carries on. The second hand doesn't have to find a grab zone (since the fourth live test, where it clicked the content instead): while one hand holds a panel, the other's pinch or fist anywhere on it, up to `HANDS_JOIN_REACH` (0.15 m) in front of it, 12 cm behind or 10 cm round it, joins as the second anchor; it never clicks, pokes, pushes or flicks a panel the other hand holds. Replaying the user's two-fist flags (215945 and 215955) with the panel where the live log had it, and 4 cm nearer or 4-8 cm farther: before, a click and no two-hand hold; now both hands hold it 9.4 s, stretching and turning it. A carried panel (one hand or two) turns at most 6 degrees a tick about the hand's point (a fist pulled in toward the face flipped it between ticks in a replay).
- **Holding through tracking loss** (2026-10-10: losing the hand dropped what it held): a pinch, card or fist grab, and a poke's or pinch's press, last until a clear release: the hand seen with its pinch or grip up and its fingers open (thumb to index tip over 3.5 cm; a fist's fingers over 1.35 extended) on 2 hands frames in a row (67 ms), or up for 6 frames whatever the fingers say. A pinch that flickers up for a frame or two in fast motion, or that ft-hands ended as lost while the hand comes back still pinched, holds on. Unseen for `HANDS_HOLD_LOST_MS` (1.75 s), it lets go where it is. Meanwhile the panel coasts on the hand's last velocity, slowing to a stop over 150 ms; a frame whose point jumped more than 12 cm counts as unseen (up to 2 in a row). When the hand is back, the smoothing restarts moving at the gap's average velocity and the panel blends to the hand over 100 ms (longer when that's more than 0.6 m/s on average). Offline, carries at 0.6 m/s losing the hand for 3, 6 and 10 frames hold, the panel's largest step 12-17 mm a 90 Hz tick (6.7 moving). A hold also lasts while the pointer helper's word says that hand is "off" (not a controller's) for up to `HANDS_HOLD_LOST_MS`: the word flickered off 24 times in the third live test's 7 minutes and dropped three holds.
- **Tracking no hand makes** (`HANDS_TRACK_GATE`, 2026-10-10: "grabbing the side of the monitor, my hand moves off to the left and tracking gets lost: the grabbed monitor is jittery"): on that flag the hand, 45-60 degrees off the head's forward, read alternately at two places 10-20 cm apart and its frame flipped 100-180 degrees between frames. A holding hand's frame that moves faster than 4 m/s from the last one kept, or lands more than 0.5 x 100 m/s² x dt² + 2 cm from where its velocity had it, is dropped (three in a row at one new place: it moved there, and the panel blends over); its frame turning faster than 540 degrees a second likewise. Frames seen by one camera, or 50-80 degrees off the head's forward, are smoothed harder (the cutoffs down to 0.35 of theirs) and don't turn the panel; past 80 degrees the hand counts as unseen, so a panel carried out of view at the side holds still until it's back. The turn's smoothing follows at most 4 Hz. On the third live test's ten flags, each pinch or fist held 0.4 s or more replayed against a 0.6 m panel at the hand (`handinput-test --carries`): the carried panel's centre moved with a per-tick second difference of 159 mm rms (99th percentile 898) on hands-throw, 9.7 mm (29) now; its turn 33 degrees rms (187) then, 1.6 (5.2) now; the side-grab flag alone 96 mm (599) to 6.2 (23). All 23 flags: 119 mm (719) to 7.6 (26), 26 degrees (157) to 1.3 (4.8).
- **Flick it away** (`HANDS_FLICK`, 2026-10-10): with the hand at a panel (its palm within 12 cm in front of it, over it, nearly still), flick it out fast with the fingers opening: away from you (within 40 degrees) at `HANDS_FLICK_SPEED` (1.2 m/s) or more, 12 cm or more within 0.2 s, the fingers ending open and opening by `HANDS_FLICK_OPENING` (0.15 of mean extension; 0 lets an open hand pushed out flick too). The panel goes out along the line from your eyes through it, to `HANDS_THROW_DISTANCE` (3 m) from them, facing you, over 0.4 s easing out. A pointing hand doesn't flick (its fingers read about 1.3), and an open hand coming through a panel faster than 0.8 m/s doesn't poke it. On the recordings, with a panel 0.3-0.45 m ahead, once in 11 minutes (6 times without the opening rule); none in the 13 "grab that" flags.
- **Throw it** (`HANDS_THROW`, 2026-10-10): let go of a panel you carry with one hand (a card, a fist, a pinch on its border, bar or title; not a resize or two hands) while the hand moves away from you (within 60 degrees) at `HANDS_THROW_SPEED` (1.0 m/s) or more, over the 0.1 s before the fingers opened, and it flies on that way to 3 m from your eyes, facing you. Let go slower and it stays. "Grab that" brings a thrown or flicked panel back, and the gesture again sends it back out there.
- **Push it away** (`HANDS_PUSH`, 2026-10-10: "pushing against the monitor or window does not make it go away"): an open hand (the four fingers 1.6 extended or more on average, the middle, ring and little too), palm to the panel (within 50 degrees), over it, pushed straight into it (within 30 degrees of its normal) from in front of it or resting on it: at `HANDS_PUSH_SPEED` (0.5 m/s) or more and 5 cm or more in, or slowly 15 cm past its surface. It goes 3 m out like a flick. A pointing index pokes; a flat open hand (1.8 or more) or an open one coming in at the push's speed doesn't. Not from a hand resting low, typing, pinching or gripping, nor within 0.6 s of a hold or a press. On the recordings with a panel 0.3-0.45 m ahead: probe-moves (open hands pushed and pulled to probe the ray's reach) 2-15 pushes in 3.5 minutes, the 2026-09-29 recording none, lit 1; on 23 flags with a panel at arm's reach, one (both hands pushed out 11-19 cm through it at 0.5-0.6 m/s); "grab that"'s open hand held out to a panel at arm's reach (5-10 cm in at 0.14-0.43 m/s) doesn't push.
- **Sent away, a panel keeps its size** (`HANDS_SEND_AWAY_WIDTH`, user, 2026-10-10: "windows should not resize to be smaller when they're sent back"): thrown, flicked, pushed or sent back by "grab that", it keeps its width; one "grab that" shrank to bring it to arm's reach (screens wider than `HANDS_GRAB_THAT_WIDTH`) and still that wide gets the width it had back (`restore`, the default; `keep`: never). In the third live test the 2.5 m desktop came at 0.6 m and was thrown 3 m out at 0.6.
- **The target's glow** (`HANDS_TARGET_GLOW`, user, 2026-10-10: "a glow over the window that grab that is targeting"; after the fourth live test: "too powerful. It should be a white glow and far more subtle. It should only be around the outside of the window"): while an open hand is held out to a panel for "grab that", a soft white halo shows outside that panel's edges, about 1.3 degrees wide (1 cm at arm's reach), at most half opaque at the edge and fading out, nothing over the content; it fades in as the gesture arms (0.2 s) and goes as it fires or is let go. An open palm close in front of a panel, toward it, shows the same halo dimmer (a push or a flick would throw it). One overlay (`frametop.guide.target`) sized and curved to the panel, in its plane, so it shows with the cutouts off.
- **Buttons** (the fourth live test: "it's extremely difficult to interact with the button to make the curve curve and not"): at arm's reach the curve button is 8 mm across, 3.5 mm past the bar's end, and the bar (first in the list, with a 1 cm margin) took the six pokes the log has at it, 3-5 mm left of its centre. Now the nearest control wins, the round buttons (curve, reset, dock, close) take a fingertip or a pinch at least `HANDS_BUTTON_REACH` (0.015 m) each way from their centre, and a pinch there presses the button (`HANDS_PINCH_BUTTONS`; 0: the bar's grab zone takes it, as before). A hand at one lights it and shows a soft ring round it. The log names the control pressed.
- **Glows at corners, edges and buttons** (`HANDS_EDGE_GLOW`, user, after the fourth live test: "almost like a cutout of the soft glow we had for highlighting, just around the edges and corners when you're within the interaction zone"): as a hand comes to a panel (in its touch zone), the same soft white halo shows only where a pinch would take it: an L round the corner it would resize from (along both edges from it), a short segment along the edge it would move the panel by, or a ring round a button; brighter as the fingers come closer, brightest while resizing from that corner or pressing that button. One overlay per hand (`frametop.guide.hand.left`, `.right`), so it shows with the cutouts off. With it the resize handle no longer follows hands (lasers and the gaze keep it); `HANDS_EDGE_GLOW=0` brings back the handle at the hand's corner and the cutout buffer's rings.
- **Remote displays** take all of it as screens do: pokes, pinches, the card and fist, corner resize, throws and "grab that".
- **SteamVR's own panels** (2026-10-13, user: "work on the native SteamVR overlay windows"; `screens/vr.cpp`'s "SteamVR's panels by hand", `screens/steampanels.cpp`): the dashboard, the Steam menu, Steam's keyboard and other apps' overlays take a poke or a pinch on the content as a click. Pinches on the border, at a corner or like a card do nothing there and show no glow (user, 2026-10-13: out of scope for SteamVR's panels; handinput's `GrabZone` gives them none). In the headset tests they never moved one, with the pointer's device as the right hand or as a treadmill. The code for those grabs, described below, stays in `screens/vr.cpp` for a later try. The hand ray's pinch on a floating window's grab bar still moves it, like the 3D mouse's laser. ft-screens can't click them itself, so the pointer helper's laser does what the hand does ("touch" lines, the helper's "Touch"): it goes 10 cm in front of the point, aimed in, and presses there. OpenVR doesn't say where a dashboard panel is or how big, so for each hands frame ft-screens casts 7 x 7 rays from the eyes past each index tip (12 degrees each way), keeps the hits within 40 cm of the tip, and fits the panel to their texture coordinates; the overlay keys come from the helper's overlay list ("steamvr"), which it keeps while hands are allowed. When grabs were on, a move or resize first hovered the laser just inside the edge: a floating panel then showed its window controls (`valve.steam.gamepadui.floatingfooter`) under it, and only then did the laser press its grab bar (7.5 cm under the bottom edge) or its resize margin (1 cm past the corner) and follow the hand. A docked dashboard or another app's overlay showed none: the pinch did nothing, and ft-screens' log said so ("no window controls under it"). No fist grabs, two-hand stretch, throws, flicks, pushes, rewinds or two-finger scroll there. One hand at a time: the laser is one device.
- **Smoothing:** a grab carries the knuckles as the cameras saw them, smoothed (`include/fh_smooth.h`: One Euro in continuous time, read each frame ft-screens draws), not the point moved ahead along the hand's velocity as the cutouts use: that velocity is mostly noise times the lead. It moves the panel only once it's 1 cm from where the pinch began, then carries on from there (no jump), so a still hand leaves the panel still. The head the panel turns to face is smoothed too. `HANDS_GRAB_SMOOTH_MINCUTOFF` (1 Hz), `HANDS_GRAB_SMOOTH_BETA` (15 Hz per m/s), `HANDS_GRAB_DEADZONE` (0.01 m). On the probe-moves replay (`scripts/test-handinput.sh`, 90 Hz ticks), the carried point's per-tick second difference went from 13-17 mm rms (50 mm p99) to 2.3-2.6 mm (11 mm), its still wobble from 1.3-1.5 to 0.8-1.0 mm, and it trails the capture by 85 ms while moving (it was 10 ms ahead, by the prediction, and 18 mm off any delay).
- With the cutouts on, a glow in the cutout buffer shows where the fingertip is on the screen (a ring that tightens as it comes to the surface, a dot while pressed); what a pinch would do where the fingers are shows as the soft white glow (above) either way; the bar and the buttons brighten under a pinch or a fingertip.
- It takes the helper's word on which hands are bare and whether hand input is allowed ("hands"); without that word for 3 s, near input is off. The helper sends it with `POINTER_HANDS=1`. A hand typing holds back (the helper's "typing" word, `POINTER_PINCH_TYPING` above) doesn't poke, grab, move the pointer with its fingertip, or make "grab that" (below). `HANDS_NEAR` (1): `on` has the helper send it without `POINTER_HANDS` too (direct touch alone, no pinches for the pointer), 0 turns it off, `force` turns it on without the helper (testing). `ft-screens` command `handinput on|off|force|state`.
**The palm menu** (`screens/palmmenu.cpp`, frame-hands `notes/hand-interaction.md` sections 11 and 18), like the Vision Pro's home indicator: turn a bare hand palm up toward your face, open, and look at it, still. After 0.3 s a small ring (2.5 cm) shows 4 cm above the palm and follows it. A plain thumb-index pinch tap by that hand opens the Steam menu (`steam/ft-steam menu`, what the input relay's `steam_menu` runs), or closes the SteamVR dashboard if it's open. The ring turns blue while the pinch is held, and the release does it; a pinch that's lost, or let go after the hand turned over, does nothing. Turn the hand away for 0.15 s and the ring goes.
- Palm up means: the palm's normal within 45 degrees of the line to your head (it leaves past 60; 60 and 75 before the third live test), the palm within 45 degrees of where your head points (leaves past 55), 15-70 cm from the head, the middle, ring and little fingers open (tip-to-wrist over knuckle-to-wrist 1.5 on average, leaves under 1.3), and the palm moving under 0.25 m/s. A palm up in your lap while you look at a screen doesn't count. The hand ray needs the palm turned away, so the two never overlap.
- Not by a panel, nor busy (the third live test: the Steam menu opened as the user took a panel's bottom edge from below, palm up, fingers bunched): no ring while the hand is near a panel (in its touch zone or margin, or its fingertip, fingers or palm within 12 cm in front of one and 8 cm round it), while near input presses or holds with it or "grab that" has it, nor for a second after any of those. The pinch must be a plain thumb-index one by a still hand: the middle finger out of it (its tip 4.5 cm or more from the thumb's, the finger 1.35 extended or straighter); a card's index and middle or the bunched fingertips do nothing on the ring.
- While the ring shows, ft-screens reports that hand near ("near"), so the pointer helper leaves its pinches alone (no gaze click), and near input leaves it too. A pinch that began before the ring showed stays the helper's.
- Where: a bare hand (not one holding a controller), with hand input allowed: on the desktop, and during a VR game while its dashboard is open or Frametop's panels are turned back on. So in a game it closes the Steam menu it opened; with the dashboard closed, the game keeps your hands. `HANDS_PALM_MENU` (1): 0 turns it off; `ft-screens` command `palmmenu on|off|state`.
**Grab that** (`screens/grabthat.cpp`, 2026-10-10): hold an open hand out toward a screen, a remote display or a floating window, palm to it, then pull the arm back while making a fist, and the panel comes to arm's reach over a quarter of a second: 45 cm ahead of your eyes (`HANDS_GRAB_THAT_DISTANCE`), at the fist's height (at most 45 cm under the eyes), facing you, so the hands can poke it, carry it and turn it. A screen wider than `HANDS_GRAB_THAT_WIDTH` (0.6 m; 0 keeps the size) comes at that width; floating windows keep their size. It doesn't take a panel within arm's reach (below: Which panel); with `HANDS_GRAB_THAT_FROM=0`, as before the fourth live test, the same gesture at a panel that came that way and is still within arm's reach (its centre within 0.8 m of the eyes, wherever you moved it about there) sends it back where it was (and its width), and at a panel within arm's reach that didn't come that way, it centres it at arm's reach. One at a time: a panel that came and is still where it came goes back as another one comes, so they don't stack up (three remote displays did in the live test of 2026-10-10). The reset button sends floating windows back too (the layout reset puts the screens and remote displays back itself). With the panel that near, the open hand held out to it is in its touch zone: its fingers pointing up don't poke it, and its fist or a pinch as it closes waits on the gesture (above).
- The gesture, from the user's own example (flag 2026-10-10 15:01): the fingers open (each tip from the wrist at least 1.55 times its knuckle's, on average), the palm facing ahead (its normal's forward part at least 0.45), the wrist at least 28 cm ahead of the eyes, all for 0.2 s; then within 0.45 s of the hand last held out: the middle, ring and little fingers close with the palm still toward the panel, and on one frame a fist (under 1.0), the wrist 8 cm or more back from its farthest in the last half second, the palm turned away from the panel. Only two-camera frames count. Not again for a second.
- Which panel (since 2026-10-13, user: "The glow should be where the palm is facing"; the line below lit panels off to the side of a palm that wasn't facing them): the one the open palm faces, the line out of the palm along its normal, with the margins below seen from the palm (`HANDS_GRAB_THAT_AIM=palm`; `eyes` brings back the line from the eyes through the palm). The palm has to face what it takes: in the user's example below the palm was held half down, 41 and 51 degrees off the eyes' line, and that line took both fires where the palm's takes none. With `eyes` (since the fourth live test, user: "make the trigger more precise and only activate if the window is not already held and closed up"): the one the line from your eyes through the open palm meets (`HANDS_GRAB_THAT_MARGIN`, 0: the panel itself; 10 cm or 3 degrees and a 20-degree head cone before), the nearest; else, since the fifth live test ("it couldn't be pulled back in": the palm is held out under the line of sight, so the line runs 12-15 degrees under where the head points and passed just under a desktop thrown 3 m out), the one whose outline it passes nearest within `HANDS_GRAB_THAT_MARGIN_DEG` (10 degrees since 2026-10-11, seen from the eyes; a "no panel there" log line names the nearest and how far off), curved ones on their curve, farther than `HANDS_GRAB_THAT_FROM` (0.8 m: its centre from the eyes). Pinned panels, panels held by a laser or a hand, and panels a hand presses on don't come. A panel at arm's reach is the hands' already: push, flick or throw it to send it away (`HANDS_GRAB_THAT_FROM=0` brings back the gesture sending a near one back, or centring it). The arming hold has the palm facing along that line within `HANDS_GRAB_THAT_FACING` (80 degrees since 2026-10-11) on average and still (under 0.5 m/s over the 0.2 s), else it starts again; the user's example holds 41 and 51 degrees off, at 0.25 and 0.46 m/s. For a second after a panel is sent away (a push, a flick, a throw) the gesture doesn't fire: the push's open hand pulled back closing has its shape.
- The closing hand is ours: from when its fingers close (the thumb clear of the index tip, so not a pinch) until 0.4 s after it fires, ft-screens reports it near, so the pointer helper doesn't take the fist as a gaze grip. While a hand is held out it asks ft-hands for its full rate (want-hz).
- Offline (`scripts/test-handinput.sh` and `handinput-test --grabthat FLAG_DIR...`, which also replays each flag through near input with a panel at arm's reach): the example flag fires twice, right hand, at -11.35 and -5.89 s (the user's -11.4 and -5.9), and twice at a panel 1.6 m out along its aim (with a panel 0.35-0.45 m ahead, where the gesture brings one, it doesn't take it since the fourth live test: the closing fist grabs it); the other 12 flags and 15 minutes of recordings (probe-moves, the 2026-09-29 and lit recordings, the PR #3 takes) none; 1 of 143 pinches and 3 of 12 grips there began on a hand it claimed. Synthetic waves, pushes, fists without the pull, a slow pull, a hand turned over before closing, pinches held out, a hand dropped to the lap and typing don't fire.
- `HANDS_GRAB_THAT` (1): 0 turns it off; `ft-screens` command `grabthat on|off|state`.
The "approach from front" rules, on recordings: in the hand recorder's desk take (PR #3, with head poses), typing under panels 0.30-0.40 m ahead (at eye height, or 0.45 m low and tilted up) made no press; the hand on the mouse (0.37-0.40 m out, past the resting zone) made 2 presses in 13 s under the nearest ones. In its touch-the-dot take the fingertip stopped 0-2 cm short of the dot in the air, its last bone 44-63 degrees off the line from the head: with a panel 3 cm nearer, 2 of 6 touches pressed at 50 degrees, 3 at 65. `HANDS_POKE_REST_NEAR=0.42` takes the mouse hand out too, but then a low dot 25 cm ahead no longer takes a poke.
Offline, `scripts/test-handinput.sh [DUMP...]` runs its unit tests and plays recorded hands (`ft-handreplay --publish-dump`) against panels placed around them. On the probe-moves (v4), lit and dim recordings, in 1 s and longer stretches where a hand held still and pointed (184 s in all; the fingertip still moved 19-23 mm in depth within each, median), a panel 3 cm beyond the fingertip got no press, 2 cm one (in 42 s of probe-moves), 1 cm 7, 0.5 cm 18. frame-hands `notes/hand-interaction.md` section 10 has the rest.
## Rendered hands
`ft-handview` (`screens/handview.cpp`, built by `screens/build.sh`) draws each tracked hand: when Room View is off, and with `HANDS_VIEW_ROOMVIEW=1` (the default) when it's on too, floating over the cutout's hole (the tracking is good enough to look right on its own; `0` draws nothing with Room View on, as before).
**The model** (`HANDS_VIEW_MODEL`): `asset` (the default), the WebXR Input Profiles' `generic-hand` (MIT), a rigged low-poly hand of 1360 vertices and 2314 triangles per hand with the 25 WebXR hand joints as its skeleton; or `babylon` (Babylon.js's hand meshes, CC BY 4.0, 1808 triangles), `mrtk3` (MRTK3's OpenXR hand, BSD-3-Clause, 2794), `godot` (Godot XR Tools' hands, CC0, 3052) or `mrtk2` (MRTK2's rigged hand, MIT, 2664). All are in `screens/assets/hands/`, each with its source, version, licence and conversion in a README (the MRTK ones were FBX, converted with assimp and `screens/tools/hand-glb-clean.py`; MRTK3 has only a right hand, mirrored for the left). `screens/tools/hand-asset.py` maps each one's skeleton onto WebXR's 25 joints by name (MRTK3's names sit a joint along; MRTK2 has no metacarpals but the little finger's, so the others go a third of the way to the knuckle, unweighted; extra joints such as a root or a palm give their weights to the wrist) and turns them all into `screens/handasset.h` (quantized vertices, normals, four joints and weights per vertex, the triangles, the joints' bind pose), compiled in, so there's no glTF code at run time. generic-hand's fingertip joints sit about a centimetre inside its fingertips, so its fingers reach about that far past the tracked tips; Babylon's and MRTK2's end within a few millimetres of them. `screens/handskin.cpp` poses it: each of the model's joints gets a frame, the same way in its bind pose and on the tracked hand (version 2's fitted skeleton, else the landmarks): its bone's direction toward the next joint, and a roll from the palm (across it for the fingers' first bones, its normal for the thumb's; each bone after takes its parent's sideways axis, the axis a finger bends about). WebXR's metacarpal joints, which MediaPipe doesn't have, follow the palm (wrist, index and little knuckles). The model is scaled by the palm's size and each bone along its length to the tracked bone (0.6-1.6 times). A left hand is drawn with the model's left hand, so nothing is mirrored. The vertex shader blends up to four joints' matrices per vertex (linear blend skinning on the GPU); the CPU only works out the 25 matrices and skins a third of the vertices to place the hand's square. The model ends just past the wrist: its heel fades out over the 3 cm before the tracked wrist, and the rest past it isn't drawn. That leaves it open there: with the hand pointing away from you, you'd look into it (a hollow tube, a fist's fingertips through the palm). So it's capped: a stencil pass counts the surfaces along each view (+1 for each front face, -1 for each back face; the GPU's early depth test would drop hidden ones, so it's a pass of its own with the depth test off), and where one more back face than front says the view went in through the cut, a disc where the fade begins (an ellipse fitted to the skinned points there) covers it, solid in the middle and fading toward its edge. Godot's hand has a longer, wider wrist, so more of it is faded, and from above a hand pointing away shows a darker patch there. `HANDS_VIEW_MODEL=robot` draws a robot hand built in code from the tracked skeleton (`screens/handrobot.cpp`; no asset, so no licence): rigid pieces, each fixed to one bone, so nothing bends or stretches out of shape. Each finger bone is a light shell (a tapered box with rounded edges and ends) with a gap at each joint; a dark ball sits at each knuckle and at the thumb's base, a dark hinge (a short cylinder along the axis the bone bends about) at the other joints. The palm is a dark core between a palm plate and a back plate (a dark seam shows round its sides, a panel line across each), ending in a short closed cuff past the wrist with a dark plate in its end. Small accents glow cyan: a pad on each fingertip, a line across the back of the knuckles, a dot in the palm, a ring round the cuff. 2373 vertices and 4360 triangles, one mesh for both hands, built once as a right hand on a reference hand (`handskin::DemoPose`'s open one) in each segment's frame: the frames are handskin's (`handskin::TrackedFrames`: the bone's direction and its roll from the palm, by the models' rule), a left hand's mirrored from a right one's, so the same mesh draws the left mirrored. Posed, each of its 16 segments (the palm, three thumb bones, three for each finger) is scaled by the palm's size against the reference's, and the palm's width by the knuckles' span; each vertex is fixed to its bone's start or end, so a shell's rounded ends keep their shape, its straight middle takes up the tracked bone's length, and a fingertip ends at the tracked tip. The girth follows the palm's size, not ft-hands' joint radii (rough, mostly its defaults). The vertex shader applies one segment's matrix per vertex; the CPU works out 16 matrices and poses a quarter of the vertices to place the square. Nothing fades and nothing is open, so there's no cap pass. In `solid` the shells are matte ceramic white and the joints darLine truncated
**The look** (`HANDS_VIEW_STYLE`): `ghost` (the default) is a light, see-through hand (about a third opaque) that glows white toward its edges, a soft fresnel rim where the surface turns away from you (no drawn outline, so a finger over the palm shows only its own soft edge), with the fingertips a little brighter; `solid` is a matte light grey hand, nearly opaque, lit from above (wrapped, so the underside is dimmer, not dark) with a soft cool rim light, easier to see over bright games. Both shade only the surface nearest the eye (the body pass keeps depth), so a see-through hand never shows its inside or its far side. `model <name>|capsules`, `style ghost|solid` and `inroom 1|0` on `@ft_handview` switch them live until a restart.
Each hand is an overlay of its own (sort order 100, over the panels and the dashboard): a square placed at the hand, facing your head, side by side, each half what one eye sees of the hand projected onto the square. The compositor keeps a placed overlay still in the room as your head turns, so a hand only waits for its own motion; a head-locked layer would have to be redrawn at the display's rate to stay put. It's drawn for each new hands frame and, while the hand moves, at most every 20 ms in between (moved ahead like the cutouts), on the GPU: the body into a scratch buffer (and the model's cap), then the colour into a DMA-BUF SteamVR imports. The `--demo` hands (two hands 45 cm ahead, drawn 30 times a second each) cost 0.5-0.7 ms of CPU per hand per draw (0.3 of it the mesh) and about 4.5% of one core in all on 2026-10-09 with the capsules; idle it's 0.2%, and with Room View on and `HANDS_VIEW_ROOMVIEW=0` it wakes 10 times a second. Offscreen (`--snapshot`, two waving hands at 30 draws a second each, no SteamVR, capped to one core by frame-job, 2026-10-09) the model took 0.36-0.40 ms of CPU per draw (0.08-0.09 of it posing and placing) and 2.2-2.4% of a core, the capsules 0.55-0.62 ms (0.27-0.34) and 3.2-3.5%. With the fresnel look and the cap (the same day, the user in the headset with SteamVR running): `asset` 0.34 ms of CPU against 0.32-0.33 before, and 0.61-0.62 ms of waiting for the GPU per draw (each frame's glFinish, shared between its two draws) against 0.57; the other models 0.27-0.41 ms of CPU and 0.61-0.68 ms of GPU wait, the capsules 0.44-0.45 and 0.53-0.54. The robot (2026-10-09, frame-job at 4 cores, the same run as the others' numbers here): 0.21-0.24 ms of CPU per draw (0.04-0.05 posing and placing) and 0.55-0.57 ms of GPU wait, against `asset` 0.28 and 0.66, `babylon` 0.26 and 0.66, `mrtk3` 0.25 and 0.66.
**Between frames and past them** (`screens/handhold.h`, 2026-10-13, user: "implement interpolation for the rendered hands so that they feel smoother", and "if the hand is lost it's preferable the rendered hand display freeze instead of make impossible movements, spaz out, or vanish until a few seconds have passed"). The tracking comes about 30 times a second. Each new frame blends in, joint by joint, from the pose drawn now over about the time since the frame before (15-70 ms), drawn every 15 ms meanwhile. A hand the tracking loses stays where it was last drawn, still, for `HANDS_VIEW_HOLD` seconds (3), then goes. A frame whose palm is further from the last one taken than a hand moves (15 cm, or 6 m/s over the time since; the lazy susan's strokes peak at 4.5) or whose palm turned over (100 degrees) in under 0.2 s isn't drawn until two frames in a row agree with each other by the same test (or 0.25 s passes): the drawn hand holds still meanwhile, then goes straight there. A hand first seen, or back after a loss, also waits for two frames that agree, about 33 ms. A hand taken off for a controller, Room View or a lost head pose goes at once. `HANDS_VIEW_SMOOTH=0` draws each frame as it comes and a hand only while it's tracked, as before. The status line counts the losses held and the jumps held off.
`--snapshot FILE.png` draws demo poses of both hands offscreen (open palm toward you, palm away, palm up, fist, point, pinch, spread; each row the left hand's two eye halves over dark, the right's over light) with no SteamVR or headset, then the cost loop above (and how long the GPU took after it): for checking the look and the skinning after a change. `FT_HANDS_VIEW_MODEL` and `FT_HANDS_VIEW_STYLE` in its environment pick what it draws.
A hand holding a controller isn't drawn: the pointer helper sends ft-handview its word ("hands L R allowed" on `@ft_handview`, as to ft-screens); while the helper is silent (3 s), a hand within 15 cm of its side's controller counts as holding it. The hands draw in VR games too (hand input keeps its own rules), but only while hand tracking runs: the relay parks it while Frametop is paused for a game, unless the dashboard is open.
**Room View** (`screens/roomview.h`): SteamVR has no public "is Room View on". In a VR game, the compositor's `VREvent_RoomViewShown` and `VREvent_RoomViewHidden` tell it; with no game, the construct shows Room View when `camera/enableConstructRoomView` is on (the default on the Frame). The passthrough shared state (`VR_CameraPassthroughState`, read only) has an `enabled` byte; it read 1 on 2026-10-09 and isn't yet known to follow the dashboard's Room View button, so only a 0 counts (off). `HANDS_ROOMVIEW=auto|on|off` in `~/.config/frametop.conf` forces it for both programs.
```
screens/build/ft-handview [--status S] [--res PX] [--demo] [--seconds S] # in the dev container (scripts/in-box)
screens/build/ft-handview --snapshot /tmp/hands.png [--res PX] [--seconds S] # offscreen, no SteamVR
echo -n state | socat -t 1 - ABSTRACT-SENDTO:ft_handview,bind= # the status line; also: roomview auto|on|off, model, style, inroom
screens/tools/hand-asset.py # screens/handasset.h from screens/assets/hands/*.glb (--check: is it up to date)
screens/tools/hand-glb-clean.py # a converted (FBX -> glTF) hand rewritten for hand-asset.py (screens/assets/hands/*/README.md)
```
`screens/frametop-handview.service` runs it as a user service (`--status 60`), started and stopped with SteamVR; the installer doesn't install it on its own.
## Camera check
@@ -264,10 +439,12 @@ Guesses, not tested:
## 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. 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 side cameras could come out swapped** (fixed 2026-10-05, see "Which camera is which"). If they still do, 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's log says `bound by VIDIOC_QUERYBUF` for each camera when its buffers were matched exactly.
- **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.
- **Pinches aren't reliable enough for everyday use yet.** That's why hand tracking is off by default (`HANDS_MODE=off`: only `ft-handsctl on` starts it), 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`).
- **The skeleton (2026-10-08) is tested on recordings only**, not in the headset: the cutouts now follow it (version 1's points and capsules), so check them there; `HANDS_SKELETON=0` brings back the filtered landmarks.
- **Floating windows don't get hand cutouts or glows.** Their panels show crops of the client buffer, which the cutouts' side-by-side buffer doesn't match (`screens/vr.cpp`, `UpdateCutouts`). Near input works on them.
- **The matte and near input are tested offline only** (2026-10-08): `HEADSET-TESTS.md` has the first headset tests.
+3 -1
View File
@@ -1,11 +1,13 @@
#!/usr/bin/env bash
# Build hand tracking in the dev container on the Frame, into hands/build/: ft-camd and ft-hands,
# and with --tools also ft-handreplay and ft-ringplay. The first build fetches ncnn and builds
# it (a few minutes); NCNN=DIR, an ncnn install already on the Frame, skips that.
# it (a few minutes); NCNN=DIR, an ncnn install already on the Frame, skips that. It also fetches
# the fine-tuned hand models (hands/models.sh) into hands/models/student, which ft-hands prefers.
# A rebuilt ft-camd has lost its capabilities: hands/run.sh install sets them again.
set -euo pipefail
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
targets=all
[ "${1:-}" = --tools ] && targets="all tools"
"$root/scripts/sync.sh" >/dev/null
"$root/hands/models.sh" fetch
exec "$root/scripts/frame.sh" -C hands "make -s ${NCNN:+NCNN=$NCNN} $targets && echo built \$(ls build/ft-* | tr '\n' ' ')"
+47 -14
View File
@@ -3,7 +3,7 @@
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
(/dev/video13 and /dev/video9) 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
@@ -40,7 +40,7 @@ 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)
SIDE_NODES = (9, 13) # the side pair: slam_right on video9, slam_left on video13 (see camera_map)
UPPER_NODES = (6, 7) # the upper pair (index 2 and 3)
TRACKING = 4
@@ -55,15 +55,20 @@ USER_TEXT = ("The headset's upper cameras and IR light are off. SteamVR couldn't
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",
KEYS = ("FPGA", "VCINT", "Created", "TrackingCameraInit", "Found camera", "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).
# The tracking cameras' names. XRService says which sensor subdev each name is ("Found camera
# 'slam_left': ... v4l_subdev=/dev/v4l-subdev30", once per instance) and which subdev and video
# device each TrackingCameraInit index opened. The index is only the order it opens them in: on
# every start logged since 2026-10-04, index 0 was slam_right. A log without the "Found camera"
# lines falls back to this order. ft-hands names them the same way (track/main.cpp,
# cameras_from_xrservice_log).
NAMES = ("slam_left", "slam_right", "upper_left", "upper_right")
RE_FOUND = re.compile(r"Found camera '(\w+)': interface=\S+ v4l_subdev=(\S+)")
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_INIT = re.compile(r"TrackingCameraInit: index: (\d+)\. video device: /dev/video(\d+)(?:\. v4l subdevice: (\S+))?")
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
@@ -85,13 +90,15 @@ class LogState:
self.closed_at = ""
self.episode = None
self.nodes = {} # TrackingCameraInit index -> /dev/videoN, from the whole log
self.subdevs = {} # TrackingCameraInit index -> its sensor subdev, from the whole log
self.found = {} # sensor subdev -> camera name ("Found camera" lines)
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": []}
"inits": {}, "init_subdevs": {}, "stream": "", "isp": None, "failure": "", "evidence": []}
if self.closed_at:
self.episode["evidence"].append(self.closed_at)
@@ -164,12 +171,18 @@ class LogState:
ep["tasks"] = tuple(int(v) for v in m.groups())
ep["evidence"].append(short)
return
m = RE_FOUND.search(text)
if m:
self.found[m.group(2)] = m.group(1)
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
if m.group(3):
ep["init_subdevs"][idx] = self.subdevs[idx] = m.group(3)
ep["evidence"].append(short)
return
m = RE_STREAM.search(text)
@@ -198,9 +211,18 @@ class LogState:
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)}
lines (the whole log's when that start has none yet): each one's subdev named by the
"Found camera" lines, else by the index (see NAMES)."""
ep = self.episode or {}
inits, subdevs = (ep.get("inits"), ep.get("init_subdevs")) if ep.get("inits") else (self.nodes, self.subdevs)
out = {}
for i, node in sorted(inits.items()):
name = self.found.get(subdevs.get(i))
if name not in NAMES:
name = NAMES[i] if 0 <= i < len(NAMES) else None
if name:
out[name] = node
return out
def tracking_nodes(self):
got = tuple(self.nodes[i] for i in range(TRACKING) if i in self.nodes)
@@ -408,12 +430,23 @@ def check(log=None, proc=True, ring=True, ring_path=None):
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))
have = {c["node"] for c in r["mono"]}
want = state.tracking_nodes() if state else SIDE_NODES + UPPER_NODES
missing = [n for n in want if n not in have]
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]
out["ring_missing"] = missing
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 "?"))
len(r["mono"]), TRACKING, " ".join("video%d" % n for n in missing) or "?"))
elif r["alive"] and missing and status == "ok":
# XRService moved the cameras after ft-camd started (the colour module was
# unplugged or plugged in: the side pair goes between video9/13 and video0/3).
# ft-camd keeps publishing the old devices, and ft-hands leaves them out.
out["ring_missing"] = missing
old = sorted(have - set(want))
status, reason = "degraded", ("ft-camd publishes %s, but XRService runs those cameras on %s now "
"(it moved them after ft-camd started)" % (
" ".join("video%d" % n for n in old) or "?",
" ".join("video%d" % n for n in missing)))
out.update(status=status, reason=reason, evidence=evidence,
summary="ok" if status == "ok" else "%s: %s" % (status, reason))
return out
+195 -10
View File
@@ -8,7 +8,8 @@
* Then it gives up its privileges for good, creates the frame ring in the
* user's runtime folder (/run/user/UID/frametop-hands/cam-ring, fhring.h), learns
* which buffer holds which V4L2 index, and copies each complete bright frame
* into the ring. It exits when XRService exits or reallocates its buffers;
* into the ring. It exits when XRService exits, reallocates its buffers or moves
* a camera to another device (SILENT_S);
* start it again (or let systemd) to re-attach.
*
* XRService itself runs as the same user. The privileges are needed only
@@ -67,6 +68,19 @@
#define SEAM_LIMIT 2.0 /* seam_score above this: the frame carries the half-size copy */
#define STALE_RELEARN 30 /* consecutive unchanged frames: the mapping changed */
#define MAX_RELEARNS 5 /* then assume XRService has new buffers, and exit */
/*
* A mono camera that has delivered frames and then stays silent for SILENT_S while another
* keeps going: XRService has moved it to another device. Unplugging or plugging in the colour
* module does that (the side pair goes between video9/13 and video0/3, seen 2026-10-12): the
* old device just stops, nothing gets reallocated, and ft-camd would publish two dead cameras
* for as long as it runs. It exits instead (status 4), so systemd starts it on the new devices.
* The cameras all stop together when the headset is taken off; that isn't this. Nor is one that
* starts later than the others when it goes back on (seen 2026-10-13: video13 just behind, then
* video0 over 3 s behind): for RESUME_GRACE_S after the cameras start again, a camera may stay
* silent. One the module moved while the headset was off is caught after that.
*/
#define SILENT_S 3
#define RESUME_GRACE_S 10
/*
* The color cameras never take the mono ones down with them. Each color buffer is ~9 MB,
* and every probe for a fresh one syncs a whole buffer's cache, so a color camera looks
@@ -102,6 +116,8 @@ typedef struct {
int slot_of[MAX_INDEX]; /* buffer holding each V4L2 index */
int relearns;
bool shared; /* its buffers sit among another camera's */
bool exact; /* its own run, bound to indices by VIDIOC_QUERYBUF */
bool each; /* mapped one by one (resolve_each) */
double recent[8]; /* means of the last frames, for dark detection */
int nrecent;
@@ -116,6 +132,7 @@ typedef struct {
unsigned out_w, out_h; /* image size in the ring */
uint64_t last_pub_ns; /* --color-fps pacing */
uint64_t paced, seams; /* color frames skipped: pacing, the half-size copy */
uint64_t idled; /* mono frames skipped while ft-hands is parked (hands_want) */
uint64_t paused_until; /* color: going stale, left alone until then */
unsigned pause_s; /* ... for this long the next time */
uint64_t pauses;
@@ -126,6 +143,8 @@ typedef struct {
uint64_t events, bright, dark, stale, torn, repairs;
uint64_t sync_ns, copy_ns, nsync; /* cost of cache sync and copy */
uint64_t last_bright; /* for the status line */
uint64_t last_event_ns; /* its last v4l2_dqbuf, 0 before the first (see SILENT_S) */
int vfd; /* our own handle on its node, for format_moved, or -1 */
} cam_t;
static cam_t cams[MAX_CAMS];
@@ -150,6 +169,7 @@ static double opt_color_idle = 2; /* ... and this often while no reader as
* saves most of the decoding (about 11% of a core at 30 fps).
*/
static double color_fps = 2;
static bool hands_parked = false; /* ft-hands is parked: the mono frames aren't copied (hands_want) */
static double opt_status = 10.0;
static volatile sig_atomic_t stop;
@@ -251,6 +271,7 @@ static void setup_camera(cam_t *c, xr_camera_t *cam, int pidfd)
{
memset(c, 0, sizeof(*c));
c->cam = cam;
c->vfd = open(cam->path, O_RDWR | O_CLOEXEC | O_NONBLOCK); /* opened while privileged */
xr_camera_layout(cam, &c->lay);
c->color = c->lay.fmt == XR_FMT_YUV420_10P;
/* Color: just the luma rows, not the chroma after them. Whether a frame is new is judged
@@ -264,11 +285,12 @@ static void setup_camera(cam_t *c, xr_camera_t *cam, int pidfd)
xr_slugify(cam->sensor, sensor, sizeof(sensor));
snprintf(c->slug, sizeof(c->slug), "%.20s_video%d", sensor, cam->node);
bool own = false;
bool own = false, exact = false;
for (int g = 0; g < xr.ngroups; g++)
if (xr.groups[g].cam == cam && group_fits(&xr.groups[g], cam, c->need))
own = true;
own = true, exact = exact || xr.groups[g].exact;
c->exact = own && exact;
char model[16];
model_of(cam->sensor, model, sizeof(model));
@@ -318,7 +340,8 @@ static void setup_camera(cam_t *c, xr_camera_t *cam, int pidfd)
}
printf(" %-24s %-12s %ux%u pitch %u, %d candidate buffers%s\n", c->slug, cam->path,
c->lay.width, c->lay.height, c->lay.pitch, c->nslots, own ? "" : " (shared run)");
c->lay.width, c->lay.height, c->lay.pitch, c->nslots,
!own ? " (shared run)" : exact ? ", bound by VIDIOC_QUERYBUF" : ", bound by open order");
}
/* ------------------------------------------------------ index -> buffer */
@@ -384,6 +407,15 @@ static bool resolve_block(cam_t *c)
* 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.
*
* Which indices are the dark ones doesn't stay put, though: measured 2026-10-13 with
* the headset worn, the bright half moved to other indices every few seconds. With a
* fixed split, bright frames landing on a silent index were dropped unread, and
* find_fresh then published them at the next dequeue under that frame's timestamp,
* 8 ms late. The side cameras lost about 4 of 10 sets with the upper ones, tracking
* ran at half rate with 3x the stereo error. So a camera whose buffers are bound by
* VIDIOC_QUERYBUF maps its silent indices to their own buffers too, and on_frame
* tells bright from dark by each frame's pixels, as for the upper cameras.
*/
static bool resolve_each(cam_t *c)
{
@@ -418,11 +450,18 @@ static bool resolve_each(cam_t *c)
if (silent * 2 > depth)
return false;
for (int i = 0; i < depth && c->exact; i++) /* see above: silent indices get their own buffers */
for (int s = 0; s < c->nslots && c->slot_of[i] < 0; s++)
if (c->slot_pos[s] == i && !taken[s])
taken[s] = true, c->slot_of[i] = s, silent--;
printf("%s: queue depth %d, buffers mapped one by one:", c->slug, depth);
for (int i = 0; i < depth; 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);
else if (c->exact)
printf(" (bright and dark told apart frame by frame)");
printf("\n");
return true;
}
@@ -443,7 +482,8 @@ static void resolve_map(cam_t *c)
/* a shuffled shared run can't be split by change votes alone */
c->shared = shared;
c->mapped = resolve_block(c) || (!shared && resolve_each(c));
c->each = false;
c->mapped = resolve_block(c) || (!shared && (c->each = resolve_each(c)));
if (c->mapped) {
fflush(stdout);
@@ -687,6 +727,11 @@ static void on_frame(cam_t *c, int64_t index, uint32_t seq, uint64_t ts, uint64_
return;
}
if (hands_parked && !c->color) { /* nobody tracks: no copies (the colour ones still tell the light) */
c->idled++;
return;
}
if (index > c->maxindex) {
reset_learning(c); /* the queue grew */
return;
@@ -717,6 +762,14 @@ static void on_frame(cam_t *c, int64_t index, uint32_t seq, uint64_t ts, uint64_
int nchanged;
int found = -1;
if (c->each && c->exact && !fresh(cur, c->samp[slot], &nchanged)) {
/* the same all-zero dark frame again (see resolve_each); never another buffer's frame */
buf_sync(c->fd[slot], DMA_BUF_SYNC_END);
c->dark++;
c->rc->dropped++;
return;
}
if (!fresh(cur, c->samp[slot], &nchanged)) {
buf_sync(c->fd[slot], DMA_BUF_SYNC_END);
found = find_fresh(c, cur);
@@ -830,10 +883,39 @@ static void on_sample(void *ctx, const tp_sample_t *s)
cam_t *c = cam_by_minor(tp_get(s->ev, f_dq_minor, s->raw, s->rawlen));
if (c)
if (c) {
c->last_event_ns = mono_ns();
on_frame(c, tp_get(s->ev, f_dq_index, s->raw, s->rawlen),
(uint32_t)tp_get(s->ev, f_dq_seq, s->raw, s->rawlen),
(uint64_t)tp_get(s->ev, f_dq_ts, s->raw, s->rawlen), s->time);
}
}
/* A mono camera gone silent while another runs (see SILENT_S), or NULL. */
static const cam_t *silent_camera(uint64_t now)
{
static uint64_t running_since; /* when a camera last started again after none ran */
uint64_t newest = 0;
for (int i = 0; i < ncams; i++)
if (!cams[i].color && cams[i].last_event_ns > newest)
newest = cams[i].last_event_ns;
if (!newest || now - newest > 1000000000ull) {
running_since = 0;
return NULL; /* none running: the headset is off or asleep */
}
if (!running_since)
running_since = now;
if (now - running_since < RESUME_GRACE_S * 1000000000ull)
return NULL;
for (int i = 0; i < ncams; i++) {
const cam_t *c = &cams[i];
if (!c->color && c->last_event_ns && now - c->last_event_ns > SILENT_S * 1000000000ull)
return c;
}
return NULL;
}
/* ------------------------------------------------------------ ring + user */
@@ -842,6 +924,49 @@ static void on_sample(void *ctx, const tp_sample_t *s)
* Ring cameras: every camera (mono and color) at its own index, then with --with-dark a
* dark twin for each mono camera. Returns how many, with which camera each one shows.
*/
/*
* A camera whose node now has another format: XRService gave the node to another camera.
* Plugging the colour module in with passthrough working moves the side cameras off the
* ISP nodes (video0/3) and puts the colour cameras there; the nodes keep streaming, so
* silent_camera never sees it (2026-10-13: tracker fed 2464x2464 NV12 as side frames).
*/
static const cam_t *format_moved(void)
{
for (int i = 0; i < ncams; i++) {
const cam_t *c = &cams[i];
struct v4l2_format fmt;
if (c->vfd < 0)
continue;
memset(&fmt, 0, sizeof(fmt));
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
unsigned w, h, bpl;
uint32_t pix;
if (ioctl(c->vfd, VIDIOC_G_FMT, &fmt) == 0) {
w = fmt.fmt.pix_mp.width, h = fmt.fmt.pix_mp.height;
pix = fmt.fmt.pix_mp.pixelformat, bpl = fmt.fmt.pix_mp.plane_fmt[0].bytesperline;
} else {
memset(&fmt, 0, sizeof(fmt));
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (ioctl(c->vfd, VIDIOC_G_FMT, &fmt) < 0) {
if (errno == ENODEV)
return c;
continue;
}
w = fmt.fmt.pix.width, h = fmt.fmt.pix.height;
pix = fmt.fmt.pix.pixelformat, bpl = fmt.fmt.pix.bytesperline;
}
if (w != c->cam->width || h != c->cam->height || pix != c->cam->pixfmt || bpl != c->cam->bytesperline)
return c;
}
return NULL;
}
static int ring_layout(int cam_of[], bool dark_of[], int max)
{
int n = 0;
@@ -897,6 +1022,39 @@ static void color_want(void)
}
}
/*
* Whether ft-hands is parked (hand interaction in VR games, hands/track/main.cpp "Parked"): it writes
* "0" to ring_dir/hands-want every second while parked. A file newer than 3 s saying 0 stops the mono
* frames' copies; anything else (no file, a stale one: ft-hands gone) copies them as usual, so other
* readers of the ring (the hand recorder, ft-cutouts) are never starved by a parked tracker that died.
*/
static void hands_want(void)
{
char path[128], buf[32] = "";
struct stat st;
struct timespec now;
bool parked = false;
snprintf(path, sizeof(path), "%s/hands-want", ring_dir);
clock_gettime(CLOCK_REALTIME, &now);
if (stat(path, &st) == 0 && now.tv_sec - st.st_mtim.tv_sec <= 3) {
FILE *f = fopen(path, "r");
if (f) {
if (fgets(buf, sizeof(buf), f) && buf[0] == '0')
parked = true;
fclose(f);
}
}
if (parked != hands_parked) {
printf("hand tracking %s: %s the mono cameras' frames\n", parked ? "parked" : "back",
parked ? "not copying" : "copying");
fflush(stdout);
hands_parked = parked;
}
}
/* A setting from ~/.config/frametop.conf, or FT_<key> from the environment; "" if unset. */
static void setting(const char *key, char *out, size_t n)
{
@@ -1098,10 +1256,10 @@ static void status(double secs)
c->last_bright = c->bright;
continue;
}
printf(" %s %s%.1f fps (dark %llu at %.1f stale %llu torn %llu remapped %llu, sync %.2f ms copy %.2f ms)",
c->slug, c->mapped ? "" : "learning ", (double)(c->bright - c->last_bright) / opt_status,
printf(" %s %s%s%.1f fps (dark %llu at %.1f stale %llu torn %llu remapped %llu idled %llu, sync %.2f ms copy %.2f ms)",
c->slug, hands_parked ? "PARKED " : "", c->mapped ? "" : "learning ", (double)(c->bright - c->last_bright) / opt_status,
(unsigned long long)c->dark, c->rc->dark_mean, (unsigned long long)c->stale,
(unsigned long long)c->torn, (unsigned long long)c->repairs,
(unsigned long long)c->torn, (unsigned long long)c->repairs, (unsigned long long)c->idled,
c->nsync ? c->sync_ns / 1e6 / c->nsync : 0.0, c->bright ? c->copy_ns / 1e6 / c->bright : 0.0);
c->last_bright = c->bright;
}
@@ -1246,7 +1404,7 @@ int main(int argc, char **argv)
signal(SIGINT, on_signal);
signal(SIGTERM, on_signal);
uint64_t start = mono_ns(), last_status = start, last_want = 0;
uint64_t start = mono_ns(), last_status = start, last_want = 0, last_hands = 0, last_fmt = start;
int rc = 0;
while (!stop) {
@@ -1264,6 +1422,33 @@ int main(int argc, char **argv)
last_want = now;
}
if (now - last_hands >= 200000000ull) { /* a stat: often, so an unparked tracker gets frames soon */
hands_want();
last_hands = now;
}
const cam_t *silent = silent_camera(now);
if (silent) {
fprintf(stderr, "%s (video%d): no frames for %.1f s while the others run: XRService has moved "
"the cameras (colour module unplugged or plugged in?); exiting so ft-camd starts on the "
"new devices\n", silent->slug, silent->cam->node,
(double)(now - silent->last_event_ns) / 1e9);
rc = 4;
break;
}
if (now - last_fmt >= 1000000000ull) {
last_fmt = now;
const cam_t *moved = format_moved();
if (moved) {
fprintf(stderr, "%s (video%d): its node has another format now: XRService has moved the "
"cameras (colour module plugged in or unplugged?); exiting so ft-camd starts on the "
"new devices\n", moved->slug, moved->cam->node);
rc = 4;
break;
}
}
struct pollfd pf = { .fd = pidfd, .events = POLLIN };
if (poll(&pf, 1, 0) > 0) {
+174 -5
View File
@@ -9,8 +9,11 @@
* - The V4L2 nodes and sensor subdevs it holds open come from /proc/<pid>/fd.
* - Each node's geometry comes from VIDIOC_G_FMT on our own handle.
* - Each node is traced back to its sensor through MEDIA_IOC_G_TOPOLOGY.
* - Buffers are split into queues by allocation order: XRService opens a
* sensor subdev, then allocates that camera's buffers.
* - Buffers are split into runs by allocation order, and each run is bound to
* its camera by VIDIOC_QUERYBUF on the camera's node, which names the
* descriptor XRService queued at each index. Where that fails, the sensor
* subdev opened just before the run decides (XRService opens a sensor's
* subdev, then allocates its buffers), which isn't always right.
*/
#define _GNU_SOURCE
@@ -457,6 +460,38 @@ static bool scan_xr_fds(pid_t pid, char *err, size_t errn)
/* ------------------------------------------------------ camera discovery */
/*
* Which of XRService's buffers each V4L2 index of a camera holds. vb2 lets any handle query a
* queue's buffers, and for a DMABUF buffer it returns the descriptor its owner last queued it
* with: that descriptor's number in XRService's fd table, the same numbers scan_xr_fds reads
* from /proc. XRService queues each index with the same buffer every time.
*/
static void query_buffers(int fd, xr_camera_t *c, bool mplane)
{
c->nqbuf = 0;
for (int i = 0; i < XR_MAX_RUNBUFS; i++) {
struct v4l2_buffer b;
struct v4l2_plane planes[VIDEO_MAX_PLANES];
memset(&b, 0, sizeof(b));
memset(planes, 0, sizeof(planes));
b.index = (unsigned)i;
b.type = mplane ? V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE : V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (mplane) {
b.m.planes = planes;
b.length = VIDEO_MAX_PLANES;
}
if (ioctl(fd, VIDIOC_QUERYBUF, &b) < 0 || b.memory != V4L2_MEMORY_DMABUF)
break; /* EINVAL past the last index */
c->qbuf_xfd[c->nqbuf++] = mplane ? planes[0].m.fd : b.m.fd;
}
}
static void probe_cameras(xr_state_t *st)
{
int seen[64];
@@ -521,6 +556,8 @@ static void probe_cameras(xr_state_t *st)
c->planesize[0] = fmt.fmt.pix.sizeimage;
}
query_buffers(fd, c, fmt.type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE);
struct stat sb;
if (fstat(fd, &sb) == 0) {
@@ -630,6 +667,120 @@ const char *xr_fmt_name(xr_fmt_t f)
/* ------------------------------------------------------- buffer grouping */
/* The camera whose VIDIOC_QUERYBUF names this XRService descriptor, or NULL. */
static xr_camera_t *qbuf_owner(xr_state_t *st, int xfd)
{
for (int c = 0; c < st->ncameras; c++)
for (int k = 0; k < st->cameras[c].nqbuf; k++)
if (st->cameras[c].qbuf_xfd[k] == xfd)
return &st->cameras[c];
return NULL;
}
/*
* A run can hold two cameras' queues when nothing between them in the fd table ends it (the
* upper pair, both 640x480). Where VIDIOC_QUERYBUF says so, cut it where the owner changes.
*/
static void split_groups(xr_state_t *st)
{
for (int i = 0; i < st->ngroups && st->ngroups < XR_MAX_GROUPS; i++) {
xr_group_t *g = &st->groups[i];
xr_camera_t *first = qbuf_owner(st, g->buf[0].xfd);
int cut = -1;
for (int b = 1; first && b < g->nbufs && cut < 0; b++) {
xr_camera_t *o = qbuf_owner(st, g->buf[b].xfd);
if (o && o != first)
cut = b;
}
if (cut < 0)
continue;
xr_group_t *t = &st->groups[st->ngroups++];
*t = *g;
t->nbufs = g->nbufs - cut;
memmove(t->buf, g->buf + cut, (size_t)t->nbufs * sizeof(t->buf[0]));
g->nbufs = cut;
}
}
static const fdent_t *fdent_of(int xfd)
{
for (int i = 0; i < nfdents; i++)
if (fdents[i].xfd == xfd)
return &fdents[i];
return NULL;
}
/*
* Another allocation can land between a buffer's two planes (a 16 MB udmabuf, seen after a
* SteamVR restart), and the pairing in build_groups then loses that buffer: the camera had
* 15 of its 16, and one index's frames were never found ("still learning" for good). A run
* bound by VIDIOC_QUERYBUF knows all its camera's buffers, so the missing ones go back in, in
* fd order (the allocation order).
*/
static void complete_exact_groups(xr_state_t *st)
{
for (int i = 0; i < st->ngroups; i++) {
xr_group_t *g = &st->groups[i];
xr_camera_t *cam = g->cam;
bool first = g->exact;
for (int j = 0; j < i && first; j++)
first = !(st->groups[j].exact && st->groups[j].cam == cam);
if (!first) /* the camera's first run takes them all */
continue;
for (int k = 0; k < cam->nqbuf && g->nbufs < XR_MAX_RUNBUFS; k++) {
int xfd = cam->qbuf_xfd[k];
bool have = false;
for (int b = 0; b < g->nbufs && !have; b++)
have = g->buf[b].xfd == xfd;
const fdent_t *e = fdent_of(xfd);
if (have || !e || e->kind != FD_DMABUF || e->size != g->planesize[0])
continue;
/* the run the interruption cut off starts a group of its own: empty it */
for (int j = 0; j < st->ngroups; j++)
for (int b = 0; j != i && b < st->groups[j].nbufs; b++)
if (st->groups[j].buf[b].xfd == xfd) {
xr_group_t *o = &st->groups[j];
memmove(&o->buf[b], &o->buf[b + 1], (size_t)(o->nbufs - b - 1) * sizeof(o->buf[0]));
o->nbufs--;
break;
}
int at = g->nbufs;
while (at > 0 && g->buf[at - 1].xfd > xfd)
at--;
memmove(&g->buf[at + 1], &g->buf[at], (size_t)(g->nbufs - at) * sizeof(g->buf[0]));
g->buf[at] = (xr_bufref_t){ .xfd = xfd, .xfd1 = -1, .size = e->size };
g->nbufs++;
}
}
int keep = 0;
for (int i = 0; i < st->ngroups; i++)
if (st->groups[i].nbufs >= 4)
st->groups[keep++] = st->groups[i];
st->ngroups = keep;
}
/*
* XRService allocates one udmabuf per plane, plane 0 then plane 1, a whole
* queue at a time right after opening the sensor's subdev. Plane 1 matches
@@ -703,6 +854,8 @@ static void build_groups(xr_state_t *st)
i++; /* consume the plane 1 descriptor */
}
split_groups(st);
int keep = 0;
for (int i = 0; i < st->ngroups; i++)
@@ -712,7 +865,23 @@ static void build_groups(xr_state_t *st)
st->ngroups = keep;
/*
* Bind each run to a camera. The sensor marker alone can be wrong: XRService
* Bind each run to a camera: exactly where a camera's VIDIOC_QUERYBUF names the run's first
* buffer (query_buffers). The two side cameras have the same format, so for them nothing
* else is sure.
*/
for (int i = 0; i < st->ngroups; i++)
for (int c = 0; c < st->ncameras && !st->groups[i].cam; c++)
for (int k = 0; k < st->cameras[c].nqbuf; k++)
if (st->cameras[c].qbuf_xfd[k] == st->groups[i].buf[0].xfd) {
st->groups[i].cam = &st->cameras[c];
st->groups[i].exact = true;
break;
}
complete_exact_groups(st);
/*
* The rest by the sensor marker and sizes. The sensor marker alone can be wrong: XRService
* sometimes opens another sensor's subdev (e.g. the idle color camera)
* between an upper camera's subdev and its buffers, and two upper cameras
* can resolve to the same sensor name. So a marker match must also fit the
@@ -792,9 +961,9 @@ void xr_print(const xr_state_t *st, FILE *f)
const xr_group_t *g = &st->groups[i];
fprintf(f, " queue %d: %d buffers plane0=%zu plane1=%zu fds %d..%d sensor '%s' -> %s\n",
fprintf(f, " queue %d: %d buffers plane0=%zu plane1=%zu fds %d..%d sensor '%s' -> %s%s\n",
i, g->nbufs, g->planesize[0], g->planesize[1],
g->buf[0].xfd, g->buf[g->nbufs - 1].xfd1, g->sensor,
g->cam ? g->cam->path : "(unbound)");
g->cam ? g->cam->path : "(unbound)", g->exact ? " (VIDIOC_QUERYBUF)" : "");
}
}
+3
View File
@@ -32,6 +32,8 @@ typedef struct {
uint32_t pixfmt;
char sensor[XR_SENSOR_LEN]; /* media entity name of the sensor */
const char *role;
int nqbuf; /* V4L2 indices VIDIOC_QUERYBUF named */
int qbuf_xfd[XR_MAX_RUNBUFS]; /* index -> its plane 0 fd in XRService */
} xr_camera_t;
typedef struct {
@@ -48,6 +50,7 @@ typedef struct {
xr_bufref_t buf[XR_MAX_RUNBUFS];
char sensor[XR_SENSOR_LEN]; /* from the preceding sensor subdev */
xr_camera_t *cam;
bool exact; /* cam is from VIDIOC_QUERYBUF, not the order */
} xr_group_t;
typedef struct {
+7 -3
View File
@@ -7,11 +7,15 @@ Wants=frametop-camd.service
PartOf=steamvr.service
[Service]
# In the dev container (it's built against Fedora's libraries). It reads ft-camd's ring and
# In the container it was built in (scripts/in-box: dev for a clone, the release's own for a
# release; it's built against Fedora's libraries). It reads ft-camd's ring and
# writes /run/user/UID/frametop-hands/hands and gestures. Settings: HANDS_* in ~/.config/frametop.conf.
ExecStartPre=-@REPO@/scripts/container-up.sh
# Before it starts, newer fine-tuned models if its branch pins them (hands/models.sh auto: at most
# every 15 minutes, never more than a minute, offline or failing it starts with the ones it has).
ExecStartPre=-/usr/bin/pkill -x ft-hands
ExecStart=%h/.local/bin/distrobox enter dev -- @REPO@/hands/build/ft-hands --status 60
ExecStartPre=-/usr/bin/timeout 60 @REPO@/hands/models.sh auto
ExecStart=@REPO@/scripts/in-box @REPO@/hands/build/ft-hands --status 60
ExecStopPost=-/usr/bin/pkill -x ft-hands
Restart=always
RestartSec=5
TimeoutStopSec=5
+9 -3
View File
@@ -1,12 +1,15 @@
#!/usr/bin/env bash
# ft-handsctl: turn hand tracking on and off by hand, on the Frame. With it on, your hands show
# through Frametop's screens (the hand cutouts); pinches and grips only move the pointer with
# POINTER_HANDS=1. It doesn't start with SteamVR (hands/run.sh install leaves it off), and it
# stops when SteamVR does.
# POINTER_HANDS=1. HANDS_MODE says when it starts by itself (off, the default: never); on lasts
# until SteamVR stops, or with HANDS_MODE=frametop, the desktop.
#
# ft-handsctl on | off | status | log [lines]
# ft-handsctl mode [frametop|always|off] HANDS_MODE: with the Frametop desktop, with SteamVR, or off
# ft-handsctl cutouts on|off|state ft-screens' hand cutouts, without stopping tracking
# ft-handsctl gestures watch pinches and grips live (Ctrl+C to stop)
# ft-handsctl flag [note...] flag a tracking failure: the last seconds of hand crops and
# ft-hands' output go to HANDS_FLAG_DIR/flag-<time> (handsflag.py)
#
# Needs the services installed once: hands/run.sh install (it sets ft-camd's capabilities).
set -euo pipefail
@@ -40,9 +43,12 @@ case ${1:-status} in
for u in $units; do echo "$u: $(systemctl --user is-active $u || true)"; done
journalctl --user -u frametop-hands.service --no-pager -o cat -n 40 |
grep -E '^ *[0-9.]+s |sets with a hand|cameras:' | tail -2 | cut -c1-160 || true ;;
mode) # hands/handsmode.py; the Hands page of Frametop Input Settings does the same
if [ -n "${2:-}" ]; then python3 "$here/handsmode.py" set "$2"; else python3 "$here/handsmode.py" status; fi ;;
log) journalctl --user -u frametop-camd.service -u frametop-hands.service --no-pager -o short -n "${2:-30}" ;;
cutouts)
ask_screens "cutouts ${2:-state}" ;;
gestures) exec python3 "$here/tools/watch_gestures.py" --distance ;;
*) sed -n '2,11p' "$0" | sed 's/^# \{0,1\}//'; exit 2 ;;
flag) shift; exec python3 "$here/handsflag.py" "$@" ;;
*) sed -n '2,14p' "$0" | sed 's/^# \{0,1\}//'; exit 2 ;;
esac
+208
View File
@@ -0,0 +1,208 @@
#!/usr/bin/env python3
"""handsflag: `ft-handsctl flag [note...]`: flag a hand tracking failure (hands/README.md, Flags).
Asks ft-hands for its flag buffer (the last HANDS_FLAG_SECONDS of hand crops and what it made of
them, and the next 2 s) through its request file, run_dir/flag, and makes the folder it writes them
to: HANDS_FLAG_DIR/flag-<time>/ (default ~/.local/share/frametop/hands/flags). Once ft-hands has
taken the request (it looks 4 times a second), the drawn hands pulse cyan (ft-handview's flash
command; HANDS_FLAG_FLASH=0 turns it off) and, with HANDS_FLAG_TONE=1, a short tone plays. Then it
returns; in the background it saves one frame of what you saw (/dev/video99, the 60th: the
capture's first frames are black; HANDS_FLAG_VIEW=0 skips it) as view.jpg, ft-handview's head poses
for the window as hmd.jsonl, and what it did as ctl.json.
The note is the rest of the command line; frame-voice's voice commands pass the words after
"flag that" ("fingers crossed"), and FRAME_VOICE_WAKE_UNIX, when the wake word was heard
(said_unix in the manifest).
python3 hands/handsflag.py [note...]
"""
import json
import os
import socket
import subprocess
import sys
import time
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import handsmode # noqa: E402
RUN_DIR = "/run/user/%d/frametop-hands" % os.getuid()
DEFAULT_DIR = os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share"), "frametop/hands/flags")
VIEW_SOCKET = "ft_handview"
TAKE_WAIT_S = 1.5 # ft-hands looks every 0.25 s
AFTER_S = 2.0 # ft-hands keeps taking this long after the flag
VIEW_DEVICE = "/dev/video99"
def setting(key, default="", conf=None):
"""FT_<key> from the environment, else ~/.config/frametop.conf's, else default."""
if "FT_" + key in os.environ:
return os.environ["FT_" + key]
conf = handsmode.read_conf() if conf is None else conf
return conf.get(key, default) or default
def flag_dir(base, now=None):
"""A new folder base/flag-YYYYMMDD-HHMMSS (-2, -3... if taken), made private to the user."""
os.makedirs(base, exist_ok=True)
stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime(now))
for n in range(1, 100):
path = os.path.join(base, "flag-" + stamp + ("" if n == 1 else "-%d" % n))
try:
os.mkdir(path, 0o700)
return path
except FileExistsError:
continue
raise RuntimeError("no free flag folder in " + base)
def one_line(s):
return " ".join(str(s).split())
def request(run_dir, path, note, said_unix, flag_unix):
"""Writes run_dir/flag (key=value lines) whole, through a temporary file."""
os.makedirs(run_dir, mode=0o700, exist_ok=True)
lines = ["dir=" + path, "note=" + one_line(note), "flag_unix=%.3f" % flag_unix]
if said_unix:
lines.append("said_unix=%.3f" % float(said_unix))
tmp = os.path.join(run_dir, "flag.tmp")
with open(tmp, "w") as f:
f.write("\n".join(lines) + "\n")
os.replace(tmp, os.path.join(run_dir, "flag"))
def wait_taken(run_dir, timeout=TAKE_WAIT_S):
"""True once ft-hands has taken the request (the file is gone); else removes it, False."""
path = os.path.join(run_dir, "flag")
end = time.monotonic() + timeout
while time.monotonic() < end:
if not os.path.exists(path):
return True
time.sleep(0.05)
try:
os.unlink(path)
except FileNotFoundError:
return True # taken at the last moment
return False
def ask_view(command, sock_name=VIEW_SOCKET, timeout=1.0, size=65536):
"""A command to ft-handview's socket and its reply, or None if it didn't answer."""
s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
try:
s.bind("")
s.settimeout(timeout)
s.sendto(command.encode(), "\0" + sock_name)
return s.recv(size).decode(errors="replace")
except OSError:
return None
finally:
s.close()
def poses_lines(reply):
"""ft-handview's `poses` reply as hmd.jsonl lines ({"t_ns", "m": 12})."""
out = []
if not reply or not reply.startswith("ok"):
return out
for line in reply.split("\n")[1:]:
parts = line.split()
if len(parts) == 13:
try:
out.append(json.dumps({"t_ns": int(parts[0]), "m": [float(x) for x in parts[1:]]}))
except ValueError:
pass
return out
def tone():
"""A short soft tone (HANDS_FLAG_TONE=1), if the session has pw-play."""
import math
import struct
import tempfile
rate, secs = 48000, 0.18
n = int(rate * secs)
frames = b"".join(struct.pack("<h", int(6000 * math.sin(2 * math.pi * 1175 * i / rate) *
min(1, i / 400, (n - i) / 2000))) for i in range(n))
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
f.write(b"RIFF" + struct.pack("<I", 36 + len(frames)) + b"WAVEfmt " +
struct.pack("<IHHIIHH", 16, 1, 1, rate, rate * 2, 2, 16) + b"data" + struct.pack("<I", len(frames)) + frames)
try:
subprocess.Popen(["pw-play", f.name], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except OSError:
pass
def grab_view(path, device=VIEW_DEVICE):
"""One frame of what the user sees, the 60th (the capture's first frames are black), as path.
On the low cores at the lowest priority; a few seconds at most."""
if not os.path.exists(device):
return "no " + device
cmd = ["nice", "-n", "19", "taskset", "-c", "0-4", "timeout", "15", "ffmpeg", "-loglevel", "error", "-y", "-f", "v4l2",
"-i", device, "-vf", r"select=gte(n\,59)", "-frames:v", "1", "-q:v", "3", path]
try:
r = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, timeout=20)
except (OSError, subprocess.TimeoutExpired) as e:
return str(e)
return "ok" if r.returncode == 0 and os.path.exists(path) else (r.stderr.decode(errors="replace").strip()[-200:] or "failed")
def background(path, ctl, grab=True, sock_name=VIEW_SOCKET, seconds=14.0, wait_s=AFTER_S + 0.7):
"""After the flag: the view frame, then (once ft-hands' window has closed) the head poses, and ctl.json."""
if grab:
ctl["view"] = grab_view(os.path.join(path, "view.jpg"))
ctl["view_unix"] = time.time()
rest = ctl["flag_unix"] + wait_s - time.time()
if rest > 0:
time.sleep(rest)
lines = poses_lines(ask_view("poses %.1f" % (seconds + 1), sock_name, size=1 << 18))
if lines:
with open(os.path.join(path, "hmd.jsonl"), "w") as f:
f.write("\n".join(lines) + "\n")
ctl["hmd_poses"] = len(lines)
with open(os.path.join(path, "ctl.json"), "w") as f:
json.dump(ctl, f, indent=1)
f.write("\n")
def main(argv, run_dir=RUN_DIR, sock_name=VIEW_SOCKET, detach=True):
note = " ".join(argv).strip()
conf = handsmode.read_conf()
base = os.path.expanduser(setting("HANDS_FLAG_DIR", DEFAULT_DIR, conf))
flag_unix = time.time()
path = flag_dir(base, flag_unix)
said = os.environ.get("FRAME_VOICE_WAKE_UNIX") or None
request(run_dir, path, note, said, flag_unix)
taken = wait_taken(run_dir)
ctl = {"flag_unix": flag_unix, "note": note or None, "said_unix": float(said) if said else None, "taken": taken}
if taken:
if setting("HANDS_FLAG_FLASH", "1", conf) != "0":
ctl["flash"] = ask_view("flash", sock_name, timeout=0.5)
if setting("HANDS_FLAG_TONE", "0", conf) == "1":
tone()
print("flag: %s (written in about %.0f s)" % (path, AFTER_S + 0.5))
else:
print("flag: ft-hands didn't take it (is hand tracking on? ft-handsctl status); saving the view only: " + path,
file=sys.stderr)
sys.stdout.flush()
grab = setting("HANDS_FLAG_VIEW", "1", conf) != "0"
seconds = float(setting("HANDS_FLAG_SECONDS", "12", conf) or 12) + AFTER_S
if detach and os.fork() > 0:
return 0 if taken else 1
if detach:
os.setsid()
devnull = os.open(os.devnull, os.O_RDWR)
for fd in (0, 1, 2):
os.dup2(devnull, fd)
try:
background(path, ctl, grab, sock_name, seconds)
finally:
if detach:
os._exit(0)
return 0 if taken else 1
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+358
View File
@@ -0,0 +1,358 @@
#!/usr/bin/env python3
"""handsmode: when hand tracking runs, by HANDS_MODE in ~/.config/frametop.conf.
frametop ft-camd, ft-hands and the hand view run while the Frametop desktop does: the session
(session/frametop-session.sh) says "desktop up" once ft-screens is up and "desktop
down" as it ends.
always they're wanted by steamvr.service (systemctl add-wants), so they run whenever SteamVR
does, in games and the SteamVR dashboard too, with or without the desktop. The input
relay then leaves them running and unparked when Frametop pauses for a game.
off (the default, and anything else) nothing starts them. ft-handsctl on still starts hand
tracking by hand, until SteamVR stops; choosing off stops it, and ft-cutouts' units too.
The units are the ones hands/run.sh install puts in ~/.config/systemd/user, and the hand view's
frametop-handview.service when it's installed; a unit that isn't installed is left out.
ft-camd needs its file capabilities (hands/run.sh caps, with sudo): without them this starts
nothing and says so ("problem"), and never asks for a password.
python3 hands/handsmode.py status [--json] # the mode, what runs, what's wrong
python3 hands/handsmode.py apply # start what HANDS_MODE wants now, fix the SteamVR wants
python3 hands/handsmode.py set MODE # write HANDS_MODE, then apply it, stopping what it
# doesn't want (Frametop Input Settings, ft-handsctl mode)
python3 hands/handsmode.py desktop up|down # the session's hooks; only HANDS_MODE=frametop acts
It also reads and writes the three hand input switches Frametop Input Settings shows (METHODS:
gaze clicks, the hand ray, direct touch), which are pointer and ft-screens settings, not services.
On the host, system Python, standard library only (the settings app runs it through
distrobox-host-exec, and imports it for the settings' defaults).
"""
import json
import os
import re
import shutil
import subprocess
import sys
CONF_PATH = os.path.expanduser("~/.config/frametop.conf")
MODES = ("frametop", "always", "off")
DEFAULT_MODE = "off"
# The cutouts' margin (HANDS_MATTE_MARGIN, degrees seen from the eyes; ft-screens' default) and the
# range Frametop Input Settings offers. ft-screens takes 0-10.
MARGIN_DEFAULT = 1.5
MARGIN_MIN, MARGIN_MAX, MARGIN_STEP = 0.0, 3.0, 0.25
STEAMVR = "steamvr.service"
TRACKING = ("frametop-camd.service", "frametop-hands.service")
VIEW = "frametop-handview.service" # draws the hands where Room View is off (hands-view)
CUTOUTS = ("frametop-cutouts-camd.service", "frametop-cutouts-hands.service") # ft-cutouts' transient units
UNITS = TRACKING + (VIEW,)
CAMD = "frametop-camd.service"
WANTS_DIR = os.path.expanduser("~/.config/systemd/user/" + STEAMVR + ".wants")
def read_conf(path=CONF_PATH):
"""KEY=value lines, as the shell that sources the file would mostly see them."""
conf = {}
try:
with open(path) as f:
for line in f:
line = line.split("#", 1)[0].strip()
if "=" in line:
k, v = line.split("=", 1)
v = v.strip()
if len(v) >= 2 and v[0] == v[-1] and v[0] in "'\"":
v = v[1:-1]
conf[k.strip()] = v
except OSError:
pass
return conf
def write_value(key, value, path=CONF_PATH):
"""Set KEY=value, keeping comments and the rest of the file (as Frametop Input Settings does)."""
try:
with open(path) as f:
lines = f.read().splitlines()
except OSError:
lines = []
for i, line in enumerate(lines):
if line.split("#", 1)[0].strip().startswith(f"{key}="):
comment = line[line.index("#"):] if "#" in line else ""
lines[i] = f"{key}={value}" + (f" {comment}" if comment else "")
break
else:
lines.append(f"{key}={value}")
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
f.write("\n".join(lines) + "\n")
def mode_of(conf):
v = conf.get("HANDS_MODE", "")
return v if v in MODES else DEFAULT_MODE
def margin_of(conf):
"""HANDS_MATTE_MARGIN as ft-screens reads it: a number 0-10, else its default."""
try:
v = float(conf.get("HANDS_MATTE_MARGIN", ""))
except ValueError:
return MARGIN_DEFAULT
return v if 0 <= v <= 10 else MARGIN_DEFAULT
# How the hands work the desktop, as three switches that don't depend on each other (Frametop Input
# Settings' Hands page; user, 2026-10-10). In frametop.conf:
# gaze_clicks gaze mode's hand clicks: a pinch clicks where you look, a middle pinch right-clicks, a
# pinch by each hand holds both buttons. POINTER_HANDS=1 and POINTER_GAZE_PINCH (1).
# ray with gaze mode off, a raised pointing hand's ray drives the pointer (and a low hand's
# pinch presses where it is). POINTER_HANDS=1 and POINTER_HAND_RAY (1).
# touch ft-screens' direct touch, poke and grab its panels, gaze or not. HANDS_NEAR: 1 (the
# default) with POINTER_HANDS=1, on without it, force always, 0 off.
# POINTER_HANDS turns the pointer's hand input on for either of the first two, so the others' keys
# are pinned when it changes, and an old config reads as it always worked (HANDS_NEAR=1 and
# POINTER_HANDS=1: all three on; POINTER_HANDS=0, the default: all three off).
METHODS = ("gaze_clicks", "ray", "touch")
def _flag(conf, key, default):
"""A 0/1 setting as the pointer helper reads it (a number, not 0), else the default."""
v = conf.get(key)
if v is None or v == "":
return default
try:
return float(v) != 0
except ValueError:
return False
def near_of(conf):
"""Whether ft-screens' direct touch is on: HANDS_NEAR as ft-screens and the helper read it."""
v = conf.get("HANDS_NEAR", "1")
if v == "0":
return False
if v in ("on", "force"):
return True
return _flag(conf, "POINTER_HANDS", False)
def methods_of(conf):
"""{method: on} for METHODS."""
hands = _flag(conf, "POINTER_HANDS", False)
return {"gaze_clicks": hands and _flag(conf, "POINTER_GAZE_PINCH", True),
"ray": hands and _flag(conf, "POINTER_HAND_RAY", True),
"touch": near_of(conf)}
def method_writes(conf, method, on):
"""The KEY: value writes that turn one method on or off and leave the other two as they are."""
want = methods_of(conf)
want[method] = bool(on)
writes = {}
hands = want["gaze_clicks"] or want["ray"]
if _flag(conf, "POINTER_HANDS", False) != hands:
writes["POINTER_HANDS"] = "1" if hands else "0"
if hands:
for key, m in (("POINTER_GAZE_PINCH", "gaze_clicks"), ("POINTER_HAND_RAY", "ray")):
if _flag(conf, key, True) != want[m]:
writes[key] = "1" if want[m] else "0"
if near_of(dict(conf, **writes)) != want["touch"]:
writes["HANDS_NEAR"] = "on" if want["touch"] else "0"
return writes
class Host:
"""systemctl --user, pgrep and getcap. Tests replace it."""
def __init__(self):
uid = os.getuid()
# Inside the Frametop session XDG_RUNTIME_DIR is the session's own folder, and the bus is
# its private one: systemctl needs the user manager's.
self.env = dict(os.environ, XDG_RUNTIME_DIR=f"/run/user/{uid}",
DBUS_SESSION_BUS_ADDRESS=f"unix:path=/run/user/{uid}/bus")
def run(self, cmd, timeout=20):
try:
return subprocess.run(cmd, env=self.env, stdin=subprocess.DEVNULL, capture_output=True,
text=True, timeout=timeout)
except (OSError, subprocess.TimeoutExpired) as e:
return subprocess.CompletedProcess(cmd, 1, "", str(e))
def systemctl(self, *args):
return self.run(["systemctl", "--user", *args])
def units(self, names):
"""{unit: {"load": LoadState, "active": ActiveState}} for each."""
out = self.systemctl("show", "-p", "Id,LoadState,ActiveState", *names).stdout
found = {}
for block in out.strip().split("\n\n"):
props = dict(line.split("=", 1) for line in block.splitlines() if "=" in line)
if props.get("Id"):
found[props["Id"]] = {"load": props.get("LoadState", ""), "active": props.get("ActiveState", "")}
return {u: found.get(u, {"load": "not-found", "active": "inactive"}) for u in names}
def exec_path(self, unit):
m = re.search(r"path=(\S+)", self.systemctl("show", "-p", "ExecStart", "--value", unit).stdout)
return m.group(1) if m else ""
def wanted(self, unit):
return os.path.lexists(os.path.join(WANTS_DIR, unit))
def exists(self, path):
return os.path.exists(path)
def caps(self, path):
"""Does ft-camd have its capabilities? None: can't tell (no getcap)."""
if not shutil.which("getcap"):
return None
return "cap_sys_ptrace" in self.run(["getcap", path]).stdout
def desktop_up(self):
return self.run(["pgrep", "-x", "ft-screens"]).returncode == 0
def cameras(self):
"""camcheck's summary ("ok", "degraded: ...", "unknown: ...")."""
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
try:
import camcheck
return camcheck.check()["summary"]
except Exception as e: # a status line, not a crash
return f"unknown: camcheck failed: {e}"
def status(host, conf=None, cameras=True):
"""What the settings app shows: the mode, what's installed and running, and "problem", a
sentence saying why hand tracking can't run (empty when nothing's wrong)."""
conf = read_conf() if conf is None else conf
states = host.units((STEAMVR,) + UNITS + CUTOUTS)
def loaded(u):
return states[u]["load"] == "loaded"
def running(u):
return states[u]["active"] in ("active", "activating", "reloading")
st = {"mode": mode_of(conf), "steamvr": running(STEAMVR), "desktop": host.desktop_up(),
"installed": all(loaded(u) for u in TRACKING), "view": loaded(VIEW),
"tracking": all(running(u) for u in TRACKING), "view_running": running(VIEW),
"cutouts": any(running(u) for u in CUTOUTS), "wanted": [u for u in UNITS if host.wanted(u)],
"active": [u for u in UNITS + CUTOUTS if running(u)],
"camd": "", "built": False, "caps": None, "cameras": "", "problem": ""}
if st["installed"]:
st["camd"] = host.exec_path(CAMD)
st["built"] = bool(st["camd"]) and host.exists(st["camd"])
if st["built"]:
st["caps"] = host.caps(st["camd"])
repo = os.path.dirname(os.path.dirname(os.path.dirname(st["camd"]))) if st["camd"] else "the Frametop folder"
if not st["installed"]:
st["problem"] = ("Hand tracking isn't installed. To install it, run hands/run.sh install in the "
"Frametop folder, in a terminal (it asks for your password once).")
elif not st["built"]:
st["problem"] = f"ft-camd isn't built ({st['camd'] or 'no path'}). Run hands/run.sh install in {repo}."
elif st["caps"] is False:
st["problem"] = (f"ft-camd is missing the permissions it needs to read the cameras (a rebuild clears "
f"them). In a terminal, run {repo}/hands/run.sh caps (it asks for your password).")
elif cameras and st["steamvr"]:
st["cameras"] = host.cameras()
if st["cameras"].startswith("degraded"):
st["problem"] = "The headset's cameras aren't all running: " + st["cameras"].split(": ", 1)[-1]
st["summary"] = summary(st)
return st
def summary(st):
"""One plain line: what runs, or when it will."""
if st["tracking"]:
how = {"off": " (started by hand: ft-handsctl)"}.get(st["mode"], "")
return "Hand tracking is running" + how
if st["cutouts"]:
return "The hand cutouts are running (started by hand: ft-cutouts)"
if st["mode"] == "off":
return "Hand tracking is off"
when = "with the Frametop desktop" if st["mode"] == "frametop" else "with SteamVR"
if st["problem"]:
return "Hand tracking can't start " + when
if not st["steamvr"]:
return "Hand tracking starts " + when
return "Hand tracking is starting" if st["mode"] == "always" or st["desktop"] else "Hand tracking starts " + when
def plan(mode, st, desktop=None, strict=False):
"""The systemctl calls that bring the units to MODE: a list of argument lists. Starting and the
SteamVR wants always follow the mode; stopping only when the desktop just ended (desktop=False,
the session's hook) or with strict (the mode was just chosen), so an install or a caps run
doesn't stop what ft-handsctl or ft-cutouts started by hand.
desktop: True/False from the session's hooks, None to look (st["desktop"])."""
units = [u for u in TRACKING if st["installed"]] + ([VIEW] if st["view"] else [])
up = st["desktop"] if desktop is None else desktop
can_run = st["installed"] and st["built"] and st["caps"] is not False
calls = []
if mode == "always":
missing = [u for u in units if u not in st["wanted"]]
if missing:
calls.append(["add-wants", STEAMVR, *missing])
else:
unwanted = [u for u in units if u in st["wanted"]]
if unwanted:
calls.append(["disable", *unwanted])
run = st["steamvr"] and can_run and (mode == "always" or (mode == "frametop" and up))
if run and units:
calls.append(["start", "--no-block", *units])
elif not (strict or desktop is False):
pass
elif mode == "off" and st["active"]:
calls.append(["stop", "--no-block", *st["active"]]) # ft-handsctl's or ft-cutouts' too
elif mode == "frametop" and not up:
active = [u for u in units if u in st["active"]]
if active:
calls.append(["stop", "--no-block", *active])
return calls
def apply(host, conf=None, desktop=None, strict=False):
"""Bring the units to HANDS_MODE (plan); returns the systemctl calls made, and the status they
started from."""
conf = read_conf() if conf is None else conf
st = status(host, conf, cameras=False)
calls = plan(st["mode"], st, desktop, strict)
for args in calls:
host.systemctl(*args)
return calls, st
def main(argv):
host = Host()
cmd = argv[0] if argv else "status"
if cmd == "status":
st = status(host)
if "--json" in argv:
print(json.dumps(st))
else:
print(f"HANDS_MODE={st['mode']}: {st['summary']}")
if st["problem"]:
print(st["problem"])
return 0
if (cmd == "set" and len(argv) == 2 and argv[1] in MODES) or argv == ["apply"]:
if cmd == "set":
write_value("HANDS_MODE", argv[1])
calls, st = apply(host, strict=cmd == "set")
for args in calls:
print("systemctl --user " + " ".join(args))
if st["problem"]:
print(st["problem"], file=sys.stderr)
return 0
if cmd == "desktop" and len(argv) == 2 and argv[1] in ("up", "down"):
conf = read_conf()
if mode_of(conf) == "frametop":
calls, st = apply(host, conf, desktop=argv[1] == "up")
for args in calls: # into the session's log
print("frametop: hand tracking (HANDS_MODE=frametop): systemctl --user " + " ".join(args))
if st["problem"] and argv[1] == "up":
print("frametop: hand tracking: " + st["problem"])
return 0
print("usage: handsmode.py status [--json] | apply | set frametop|always|off | desktop up|down", file=sys.stderr)
return 2
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+12 -3
View File
@@ -27,7 +27,15 @@
* room with the HMD pose at its capture time (capture_ns, begin_ns) before subtracting,
* so turning your head doesn't drag.
*
* Version 1 had only the pinches (192 bytes); version 2 adds the grips after them.
* Middle pinch (version 3): the thumb on the middle fingertip instead of the index one, with
* the pinch's thresholds and point. distance is thumb tip to middle tip. It begins only while
* the thumb is clearly nearer the middle tip than the index tip, and an index pinch and a middle
* pinch on one hand exclude each other (whichever began first holds until it ends). The pointer
* helper's hand ray turns it into a right click (a tap) or scrolling (held and moved).
*
* Version 1 had only the pinches (192 bytes); version 2 adds the grips after them, version 3
* the middle pinches after those. A reader of an older version maps and copies the size it
* knows: the file only grows at the end.
*/
#pragma once
@@ -36,7 +44,7 @@
#include <stdint.h>
#define FH_GESTURES_MAGIC "FHGEST01"
#define FH_GESTURES_VERSION 2
#define FH_GESTURES_VERSION 3
enum {
FH_PINCH_TRACKED = 1u << 0, /* the hand was tracked in this frame */
@@ -75,7 +83,8 @@ typedef struct {
uint8_t reserved[8];
fh_pinch_t pinch[2]; /* [0] left hand, [1] right hand */
fh_pinch_t grip[2]; /* version 2 */
fh_pinch_t pinch2[2]; /* version 3: thumb to middle fingertip */
} fh_gestures_t;
static_assert(sizeof(fh_pinch_t) == 64, "fh_pinch_t layout");
static_assert(sizeof(fh_gestures_t) == 64 + 4 * 64, "fh_gestures_t layout");
static_assert(sizeof(fh_gestures_t) == 64 + 6 * 64, "fh_gestures_t layout");
+68 -1
View File
@@ -7,6 +7,10 @@
* Positions are metres in the head frame at capture time, which is OpenVR's HMD
* frame (+x right, +y up, -z forward). Turn them into the room with the HMD pose
* at capture_ns (CLOCK_MONOTONIC). Writer: ft-hands (hands/track/io.cpp).
*
* Version 2 appends a skeleton per hand (fh_hand_fit_t) after version 1's fh_hands_t, which is
* unchanged: a version 1 reader that maps sizeof(fh_hands_t) and checks the magic keeps
* working. Readers of the skeleton check version >= 2 and the file's size >= sizeof(fh_hands_v2_t).
*/
#pragma once
@@ -15,7 +19,7 @@
#include <stdint.h>
#define FH_HANDS_MAGIC "FHHANDS1"
#define FH_HANDS_VERSION 1
#define FH_HANDS_VERSION 2
#define FH_HANDS_MAX_HANDS 2
#define FH_HANDS_MAX_CAPSULES 64
@@ -53,6 +57,69 @@ typedef struct {
fh_capsule_t capsules[FH_HANDS_MAX_CAPSULES];
} fh_hands_t;
/* ---- version 2: the fitted skeleton (hands/track/skeleton.h, hands/README.md "Skeleton") ----
*
* Bone lengths are learned per user and side, so fitted fingers keep their length; the pose
* (palm and joint angles) is filtered, not the points. Everything is in the head frame at
* capture time, like pts. Joint frames follow OpenXR's hand joints: -Z along the bone that
* starts at the joint (toward the fingertip), +Y out of the back of the hand, +X = Y x Z
* (so +X points to the little finger on a right hand, to the thumb on a left one). The
* wrist's frame is the palm's: -Z toward the middle knuckle, +Y the back of the hand's normal.
* A tip has its bone's frame. Joints are indexed like MediaPipe's 21 landmarks. */
enum {
FH_FIT_VALID = 1u << 0, /* this hand has a skeleton */
FH_FIT_RIGHT = 1u << 1, /* fitted as a right hand (else left) */
FH_FIT_SETTLED = 1u << 2, /* its side's bone lengths have settled (else partly the prior) */
FH_FIT_FLIPPED = 1u << 3, /* fitted as the other side than the model called it */
FH_FIT_ELBOW_HEAD_UP = 1u << 4, /* elbow from the arm model with the head's +y as up */
};
typedef struct {
float p[3]; /* position, m */
float radius; /* rough, m: for colliders and a mesh's thickness */
float q[4]; /* orientation x, y, z, w: the joint's frame (above) */
} fh_joint_t; /* 32 bytes */
typedef struct {
uint32_t id; /* hands[k].id; this is hands[k]'s skeleton */
uint32_t flags; /* FH_FIT_* */
uint64_t tracked_ns; /* CLOCK_MONOTONIC capture time of the last frame the hand was
measured in (today always capture_ns) */
fh_joint_t joints[21];
float bone_len[20]; /* m; bone b ends at joint b + 1 (bones 0, 4, 8, 12, 16 start
at the wrist) */
float angles[26]; /* rad: thumb CMC abduction, flexion, twist, MCP abduction,
flexion, IP flexion; then per finger (index, middle, ring,
little) MCP abduction, MCP flexion, MCP twist, PIP, DIP.
Flexion is positive toward the palm, abduction toward the
thumb's side */
float elbow[3]; /* the arm model's elbow (notes: frame-hands forearm.md) */
float elbow_conf; /* 0: inferred by the arm model only (as now) */
float pinch_point[3]; /* between the index and middle knuckles: the gestures file's
pinch point, from the skeleton */
float contact[3]; /* midway between the thumb and index tips */
float pinch_d[2]; /* thumb tip to index tip, thumb tip to middle tip, m */
float fit_rms; /* the fit against this frame's measured landmarks, m */
float settled; /* 0..1: how far its side's bone-length calibration is */
float vel_head[3]; /* palm centre velocity in the HEAD frame, m/s, filtered. It
includes the head's own motion: turning the head reads as
hand motion. For motion in the room, difference room-frame
points across publishes (capture_ns) as handcut.cpp does. */
float angvel_head[3]; /* the palm's angular velocity in the head frame, rad/s; it
includes the head's rotation, as vel_head */
float reserved[18];
} fh_hand_fit_t; /* 1024 bytes */
typedef struct {
fh_hands_t v1; /* version 1, unchanged; v1.version is 2 */
fh_hand_fit_t fits[FH_HANDS_MAX_HANDS]; /* fits[k] goes with v1.hands[k]; zero when
k >= nhands or the hand has no skeleton */
} fh_hands_v2_t;
static_assert(sizeof(fh_hand_t) == 272, "fh_hand_t layout");
static_assert(sizeof(fh_joint_t) == 32, "fh_joint_t layout");
static_assert(sizeof(fh_hand_fit_t) == 1024, "fh_hand_fit_t layout");
static_assert(sizeof(fh_capsule_t) == 32, "fh_capsule_t layout");
static_assert(sizeof(fh_hands_t) == 64 + 2 * 272 + 64 * 32, "fh_hands_t layout");
static_assert(sizeof(fh_hands_v2_t) == sizeof(fh_hands_t) + 2 * 1024, "fh_hands_v2_t layout");
+538
View File
@@ -0,0 +1,538 @@
// fh_ray - the hand ray: where a bare hand points, Quest-style, and when it counts as pointing.
// Shared by the pointer helper (the ray drives the ft_pointer SteamVR device: pointer/helper)
// and ft-screens (a second hand's ray for two-hand stretch), so both agree.
// Design: frame-hands/notes/hand-interaction.md, sections 2.4 and 2.5.
//
// Header-only C++17, no dependencies. Everything is in the room (OpenVR's standing universe:
// +x right, +y up, -z forward), metres, radians inside and degrees in Params, seconds on one
// steady clock (CLOCK_MONOTONIC: ft-hands' capture times, as seconds).
//
// Body model (no torso tracking): the torso faces the head's yaw, low-passed (torsoTau, 0.6 s) and
// never more than torsoMaxLag (30 deg) off the head's. With torsoWrists (on), what it faces is the
// head's forward counted twice plus the direction from the neck to each wrist seen, levelled (the
// formula is StereoKit's, MIT: systems/input.cpp, body_make_shoulders): you point where your body
// faces, so looking aside while pointing turns the shoulders less, and the ray with them (with both
// hands ahead, a third as far). On the probe-moves replay (pointer/tools/rayeval) the share of a
// still hand's ray motion that came from the shoulder went from 20 to 18% (p90 1.7-3.6 deg/s from
// 2.0-3.7); on the guided tap capture, where the head mostly faced the panel, nothing got worse.
// The neck is the head moved by neck (10 cm down, 8 cm back), turned by the head's yaw only; a
// shoulder is the neck moved by (+-shoulderX, shoulderY, 0) (17 cm out, 13 cm down), turned by the
// torso's yaw. Head pitch and roll are ignored, so nodding doesn't swing the ray.
//
// Ray: from the shoulder S through the knuckle point K (the index and middle knuckles: the pinch
// point, which holds still as the fingers close, so pinching barely turns the ray). The direction
// is D = normalize(K - S); the origin is K + originAhead (3 cm) along D, in front of the fingers.
// K is predicted predict (20 ms) ahead with its room velocity (differenced across frames).
//
// Hand direction (handWeight, 0 = off, the default): D turned toward where the hand itself points
// by that fraction of the angle between them (StereoKit's aim, MIT: xr_backends/extensions/
// hand_tracking.cpp, which slerps half way). The hand's axes come from the joints that hold still in
// a thumb-index pinch (HandAxes: the wrist and the middle, ring and little knuckles), and its
// direction is their forward (wrist to knuckles) tilted handPitch toward the back of the hand
// (negative: the palm) and handYaw out, away from the thumb. The gate's tests still read the
// shoulder's ray. Off because every weight measured worse (rayeval, the guided tap capture and
// probe-moves, fitted skeleton): our palm's orientation is far noisier than K seen from the
// shoulder 45 cm away. At 0.3 the 90 Hz judder went from 0.07-0.14 to 0.11-0.33 deg rms, a still
// hand's wobble more than doubled, the ray's turn 150 ms into a pinch went from 0.4-0.5 to 1.2-1.7
// deg (p50), and frames where the raw ray turned over 3 deg from 159 to 330. Where the hand's
// direction sits against the shoulder's ray depends on how the hand is held: pitch -15 to -41, yaw
// -4 to 19 (the recordings' medians); handPitch and handYaw are in the middle of that. StereoKit's
// -50 and 20 suit its own axes.
//
// Pinch anchor (pinchAnchor, off by default): while a ray pinch is held, K is pinned to the hand's
// axes where it was at the press, rebuilt from them each frame (StereoKit's pinch point, MIT:
// hands/input_hand.cpp, pinned to the index finger's root while the pinch is active), and eased
// back to the measured K on the steady shoulder's schedule (below). StereoKit pins a point between
// the fingertips, which travels as they open; ours is the knuckles already, and on the guided tap
// capture it held stiller than the axes do: pinned, a held pinch's point (as a near grab carries
// it) shook as much or more (0.15-0.29 against 0.12-0.19 mm per 90 Hz tick, p50) and its release
// kick was no smaller (1.4-2.0 against 1.2-1.6 mm, p50, palm still), from the fitted skeleton and
// from the filtered landmarks alike. The palm's turn, times the 7 cm from its centre to K, is the
// noise it adds.
//
// Pointing (Gate): the ray shows once every "show" test has held for showFor (120 ms), and hides
// once some "keep" test has failed for hideFor (250 ms):
// test show keep (hide past it)
// side the arbiter says hand (and the caller (at once otherwise: "off")
// allows it: in a game, the mouse)
// tracked a two-camera (STEREO) frame within a frame within lostFor (250 ms); one-camera
// stereoWithin (200 ms) depth is 2-6 cm off, fine for a short gap
// raised K at most raisedShow (0.30 m) below raisedHide (0.40 m): gaze pinches sat
// the eyes 0.35-0.45 m below the eyes, elbow resting
// forward K at least forwardShow (0.25 m) ahead forwardHide (0.20 m)
// of the eyes, along the torso's yaw
// palm away palm normal . D >= palmShow (0.3) palmHide (0.0): palm toward you is reserved
// forearm elbow-to-wrist pitch >= forearmShow forearmHide (-50 deg); only with an elbow
// (-35 deg) of elbowConfMin (0.5) confidence
// aim D's pitch in [pitchMin, pitchMax] [pitchMinHide, pitchMaxHide] (-60, 75),
// (-45, 60), yaw within yawShow (70) yawHide (80)
// of the head's
// not near not near a panel (ft-screens' near near: at once (near wins)
// claim, or the fingertip at an overlay)
// not a fist no grip down a grip down
// ready the thumb and index tips within readyHide (0.10 m) apart: the laser is
// readyShow (0.06 m) (user, 2026-10-11: for pinching, not a hand held up (0: off;
// "the aiming laser only activates when frames without the gap pass)
// your fingers get within a distance")
// open not a fist: HandFrame::curl (the more fistCurl - 0.05: a hand closing into a
// open of the index and the other three fist drops its laser, so the fist's
// fingers) at least fistCurl (1.1) thumb-to-index touch isn't a click
// While a ray pinch is held (Hold), the ray stays up whatever the tests say, until hideFor after
// the release. A pinch may also bring a ray up (ShowForPinch): one that hid within a moment (the
// pointer helper's grace; not one hidden for "off", "near" or a reset), or one whose show tests
// all pass but not yet for showFor. Closing the fingers turns the hand a little, so a ray near a
// hide limit can drop just as the pinch begins.
//
// Filter (RayFilter, hands/include/fh_smooth.h): One Euro filters (Casiez, Roussel and Vogel, CHI
// 2012) run in continuous time, so the beam moves at the display's rate rather than in steps at
// the tracker's: the direction on the sphere (minCutoff, beta per deg/s, dCutoff), the origin
// (originMinCutoff, originBeta per m/s): the aim matters more than where the beam starts. While a
// ray pinch is held (a drag), the direction's minimum cutoff drops to holdMinCutoff: a slow drag
// is steadier, a fast one still keeps up. The reach (|K - S|, push and pull's input) has its own
// (reachMinCutoff, reachBeta per m/s): push and pull turns a reach's change into 3 times its share
// of the panel's distance (13 times it for a panel 2 m away). The caller reads the ray at
// the time it draws (At(now)); between tracker frames it glides toward the newest one.
//
// Steady shoulder (holdShoulder): while a ray pinch is held, and hideFor after, the ray's shoulder
// stays where it was in the room at the press; then it eases back to the body model's over
// shoulderBlend (0.5 s). The model's shoulder moves with the head (the neck follows its position,
// the torso its yaw): on a recording, with the hand still, a fifth of the ray's motion came from
// there, up to 2-4 deg/s (p90). Looking around while dragging moved what was dragged. The pinch
// anchor (when on) holds and eases back with it.
#pragma once
#include "fh_smooth.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <string>
namespace fhray {
using fhsmooth::Dot;
using fhsmooth::Len;
using fhsmooth::Norm;
using fhsmooth::V3;
constexpr double kDeg = M_PI / 180;
// Yaw: 0 along -z, positive turning left (about +y), as OpenVR; pitch: up positive.
inline double YawOf(V3 d) { return std::atan2(-d.x, -d.z); }
inline double PitchOf(V3 d) { return std::asin(std::clamp(Norm(d).y, -1.0, 1.0)); }
inline V3 Dir(double yaw, double pitch) {
return {-std::sin(yaw) * std::cos(pitch), std::sin(pitch), -std::cos(yaw) * std::cos(pitch)};
}
// v turned by yaw about +y.
inline V3 TurnYaw(V3 v, double yaw) {
const double c = std::cos(yaw), s = std::sin(yaw);
return {v.x * c + v.z * s, v.y, -v.x * s + v.z * c};
}
inline double WrapPi(double a) { return std::remainder(a, 2 * M_PI); }
struct Params {
// body
double torsoTau = 0.6, torsoMaxLag = 30;
bool torsoWrists = true;
V3 neck{0, -0.10, 0.08};
double shoulderX = 0.17, shoulderY = -0.13;
// ray
double originAhead = 0.03, predict = 0.020;
double handWeight = 0, handPitch = -30, handYaw = 8;
bool pinchAnchor = false;
// gate
double showFor = 0.12, hideFor = 0.25;
double stereoWithin = 0.2, lostFor = 0.25;
double raisedShow = 0.30, raisedHide = 0.40;
double forwardShow = 0.25, forwardHide = 0.20;
double palmShow = 0.3, palmHide = 0.0;
double forearmShow = -35, forearmHide = -50, elbowConfMin = 0.5;
double pitchMin = -45, pitchMax = 60, pitchMinHide = -60, pitchMaxHide = 75;
double yawShow = 70, yawHide = 80;
double readyShow = 0.06, readyHide = 0.10; // the thumb and index tips apart (0: no "ready" test)
double fistCurl = 1.1; // HandFrame::curl under this: a fist (0: no "open" test)
// filter (see the top)
double minCutoff = 0.8, beta = 0.06, dCutoff = 1.0, originMinCutoff = 1.5, originBeta = 0.5;
double holdMinCutoff = 0.5;
bool holdShoulder = true;
double shoulderBlend = 0.5;
double reachMinCutoff = 1.0, reachBeta = 5.0;
};
// The torso and shoulders, from the head (and the wrists: torsoWrists).
class Body {
public:
explicit Body(const Params &p = {}) : p_(p) {}
void SetParams(const Params &p) { p_ = p; }
// The head's position and forward direction (-z of its pose) at time t, and the wrists seen in
// the same frame (none: nullptr, n 0).
void Update(double t, V3 head, V3 forward, const V3 *wrists = nullptr, int n = 0) {
head_ = head;
headYaw_ = YawOf(forward);
// what the torso turns toward: the head's yaw, or with the wrists (see the top)
double target = headYaw_;
if (p_.torsoWrists && n > 0) {
V3 face = Dir(headYaw_, 0) * 2;
for (int i = 0; i < n; ++i) face = face + Norm(wrists[i] - Neck());
face.y = 0;
if (Len(face) > 0.1) target = YawOf(face);
}
if (!init_) {
torso_ = target, t_ = t, init_ = true;
} else {
const double dt = std::clamp(t - t_, 0.0, 0.5);
t_ = t;
const double lag = WrapPi(target - torso_) * std::exp(-dt / std::max(1e-3, p_.torsoTau));
torso_ = WrapPi(target - lag);
}
const double max = p_.torsoMaxLag * kDeg;
torso_ = WrapPi(headYaw_ - std::clamp(WrapPi(headYaw_ - torso_), -max, max));
}
bool Ready() const { return init_; }
V3 Head() const { return head_; }
double HeadYaw() const { return headYaw_; }
double TorsoYaw() const { return torso_; }
V3 TorsoForward() const { return Dir(torso_, 0); }
V3 Neck() const { return head_ + TurnYaw(p_.neck, headYaw_); }
V3 Shoulder(int side) const {
return Neck() + TurnYaw(V3{side ? p_.shoulderX : -p_.shoulderX, p_.shoulderY, 0}, torso_);
}
private:
Params p_;
V3 head_;
double headYaw_ = 0, torso_ = 0, t_ = 0;
bool init_ = false;
};
struct Ray {
V3 origin, dir{0, 0, -1};
};
// A hand's axes from the joints that hold still in a thumb-index pinch: the wrist and the middle,
// ring and little knuckles (MediaPipe 0, 9, 13, 17). f: forward, from the wrist to the ring and
// little knuckles; u: out of the back of the hand; r = f x u (toward the little finger on a right
// hand palm away, toward the thumb on a left one: to the right on both). o: their centre. side: 0
// left, 1 right. Built as StereoKit's hand orientation (MIT: xr_backends/extensions/hand_tracking.cpp),
// with the middle knuckle for the index one and the wrist for the metacarpals' roots.
struct Axes {
V3 o, r, u, f;
bool ok = false;
};
inline Axes HandAxes(V3 wrist, V3 middle, V3 ring, V3 little, int side) {
Axes a;
const V3 fwd = (ring + little) * 0.5 - wrist, across = (little - middle) * (side ? 1.0 : -1.0);
const V3 back = Cross(across, fwd);
if (Len(fwd) < 0.02 || Len(across) < 0.005 || Len(back) < 1e-6) return a; // a collapsed hand
a.f = Norm(fwd);
a.u = Norm(back - a.f * Dot(back, a.f));
a.r = Cross(a.f, a.u);
a.o = (wrist + middle + ring + little) * 0.25;
a.ok = true;
return a;
}
inline V3 ToAxes(const Axes &a, V3 p) {
const V3 d = p - a.o;
return {Dot(d, a.r), Dot(d, a.u), Dot(d, a.f)};
}
inline V3 FromAxes(const Axes &a, V3 l) { return a.o + a.r * l.x + a.u * l.y + a.f * l.z; }
// Where the hand points (see "Hand direction" at the top): the axes' forward turned pitch degrees
// toward the back of the hand (negative: toward the palm) and yaw degrees out, away from the thumb.
// StereoKit's is pitch -50, yaw 20 from its own axes (MIT, quat_from_angles(-50, +-20, 0)).
inline V3 HandDir(const Axes &a, int side, double pitch, double yaw) {
const double p = pitch * kDeg, y = (side ? -yaw : yaw) * kDeg;
return Norm(a.r * (-std::cos(p) * std::sin(y)) + a.u * std::sin(p) + a.f * (std::cos(p) * std::cos(y)));
}
// A point pinned to a hand's axes (see "Pinch anchor" at the top): Pin it, then At rebuilds it from
// the axes now, weighted against the point as measured (1: pinned, 0: as measured, between: easing
// back). Axes that can't be built leave it as measured.
class Anchor {
public:
void Pin(const Axes &a, V3 p) {
pinned_ = a.ok;
if (a.ok) local_ = ToAxes(a, p);
}
void Unpin() { pinned_ = false; }
bool Pinned() const { return pinned_; }
V3 At(const Axes &a, V3 measured, double weight) const {
if (!pinned_ || !a.ok || weight <= 0) return measured;
return measured + (FromAxes(a, local_) - measured) * std::min(weight, 1.0);
}
private:
V3 local_;
bool pinned_ = false;
};
// One hand at one capture time, in the room.
struct HandFrame {
double t = 0; // capture time, s
bool stereo = false; // triangulated from two or more cameras
V3 knuckle; // K: the index and middle knuckles
V3 wrist;
V3 middle, ring, little; // their knuckles (palm: set), for the hand's axes
bool palm = false;
V3 palmNormal; // unit, out of the palm
V3 elbow;
double elbowConf = 0; // 0: the arm model's guess
bool grip = false; // a grip (closed hand) is down
bool near = false; // near a panel (see "not near" at the top)
double gap = -1; // the thumb and index tips apart (m); < 0 unknown (the "ready" test passes)
double curl = -1; // how open the hand is (FistCurl): about 1.9 open, under 1.1 a fist; < 0 unknown
};
// HandFrame::curl from MediaPipe's 21 landmarks (any 3D type with operator-, and len its length): a
// finger's tip-to-wrist distance over its knuckle's; the larger of the index's and the mean of the
// middle, ring and little's. A fist has both low; a pinch with the other fingers curled keeps the index
// out (the flags of 2026-10-09..11, 47k hands: the other three alone read under 1.25 in a fifth of the
// pinches with the index out; both under 1.1 in 70% of the frames with the index curled, a fist).
template <class P, class L> double FistCurl(const P *pts, L len) {
double sum = 0;
for (int tip : {12, 16, 20}) {
const double k = len(pts[tip - 3] - pts[0]);
if (k < 1e-4) return -1;
sum += len(pts[tip] - pts[0]) / k;
}
const double k = len(pts[5] - pts[0]);
if (k < 1e-4) return -1;
return std::max(sum / 3, len(pts[8] - pts[0]) / k);
}
// What each test said for one frame (degrees and metres, for logs and the offline evaluation).
struct Tests {
double below = 0, ahead = 0, palm = 0, forearm = 0, pitch = 0, yawOff = 0;
bool forearmUsed = false;
bool show = false, keep = false; // every show test, every keep test (not counting side, tracking)
std::string fails; // the show tests that failed
};
inline Tests Evaluate(const Params &p, const Body &body, const HandFrame &f, const Ray &ray) {
Tests r;
const V3 eye = body.Head();
r.below = eye.y - f.knuckle.y;
const V3 fwd = body.TorsoForward();
r.ahead = Dot(f.knuckle - eye, fwd);
r.palm = Dot(f.palmNormal, ray.dir);
r.pitch = PitchOf(ray.dir) / kDeg;
r.yawOff = std::fabs(WrapPi(YawOf(ray.dir) - body.HeadYaw())) / kDeg;
r.forearmUsed = f.elbowConf >= p.elbowConfMin;
if (r.forearmUsed) r.forearm = PitchOf(f.wrist - f.elbow) / kDeg;
bool show = true, keep = true;
auto test = [&](bool s, bool k, const char *name) {
if (!s) r.fails += r.fails.empty() ? name : std::string(",") + name;
show = show && s, keep = keep && k;
};
test(r.below <= p.raisedShow, r.below <= p.raisedHide, "raised");
test(r.ahead >= p.forwardShow, r.ahead >= p.forwardHide, "forward");
test(r.palm >= p.palmShow, r.palm >= p.palmHide, "palm");
if (r.forearmUsed) test(r.forearm >= p.forearmShow, r.forearm >= p.forearmHide, "forearm");
test(r.pitch >= p.pitchMin && r.pitch <= p.pitchMax, r.pitch >= p.pitchMinHide && r.pitch <= p.pitchMaxHide, "aim");
test(r.yawOff <= p.yawShow, r.yawOff <= p.yawHide, "yaw");
test(!f.grip, !f.grip, "grip");
if (p.readyShow > 0 && f.gap >= 0) test(f.gap <= p.readyShow, f.gap <= std::max(p.readyShow, p.readyHide), "ready");
if (p.fistCurl > 0 && f.curl >= 0) test(f.curl >= p.fistCurl, f.curl >= p.fistCurl - 0.05, "fist");
r.show = show, r.keep = keep;
return r;
}
// The ray's filter (see the top).
class RayFilter {
public:
explicit RayFilter(const Params &p = {}) { SetParams(p); }
void SetParams(const Params &p) {
p_ = p;
dir_.Set({held_ ? p.holdMinCutoff : p.minCutoff, p.beta, p.dCutoff});
origin_.Set({p.originMinCutoff, p.originBeta, p.dCutoff});
reach_.Set({p.reachMinCutoff, p.reachBeta, p.dCutoff});
}
// A ray pinch held: the direction's precision (holdMinCutoff), from now on.
void SetHeld(bool on) {
if (on == held_) return;
held_ = on;
SetParams(p_);
}
void Reset() { dir_.Reset(), origin_.Reset(), reach_.Reset(); }
// A tracker frame's ray and reach, captured at t, arrived at now.
void Sample(const Ray &raw, double reach, double t, double now) {
dir_.Sample(raw.dir, t, now), origin_.Sample(raw.origin, t, now), reach_.Sample(reach, t, now);
}
// The ray at now (the filters' timeline moves there).
Ray At(double now) {
Ray r;
r.dir = dir_.At(now), r.origin = origin_.At(now);
reach_.At(now);
return r;
}
Ray Last() const {
Ray r;
r.dir = dir_.Last(), r.origin = origin_.Last();
return r;
}
double Reach() const { return reach_.Last(); }
private:
Params p_;
fhsmooth::Direction dir_;
fhsmooth::Point3 origin_;
fhsmooth::Scalar reach_;
bool held_ = false;
};
// One side's ray: prediction, the gate and the filter.
class HandRay {
public:
explicit HandRay(int side, const Params &p = {}) : side_(side), p_(p), filter_(p) {}
void SetParams(const Params &p) { p_ = p, filter_.SetParams(p); }
int Side() const { return side_; }
// A new frame of this side's hand. sideIsHand: the ray may show (the arbiter says this side is a
// bare hand, and the caller allows it); without it, a ray shown hides at once ("hide off").
// now: when it arrived, on the capture times' clock (< 0: at its capture time).
void Frame(const Body &body, const HandFrame &f, bool sideIsHand, double now = -1) {
if (now < 0) now = f.t;
const bool wasShown = shown_;
// K: pinned to the hand's axes during a pinch (see "Pinch anchor" at the top)
axes_ = f.palm ? HandAxes(f.wrist, f.middle, f.ring, f.little, side_) : Axes{};
lastMeasured_ = f.knuckle;
if (pinAt_) anchor_.Pin(axes_, f.knuckle), pinAt_ = false;
const double pinned = Steady(f.t);
const V3 kNow = anchor_.At(axes_, f.knuckle, pinned);
if (pinned <= 0) anchor_.Unpin();
// K's room velocity, for the prediction
V3 vk;
if (haveLast_ && f.t > lastT_ && f.t - lastT_ < 0.2) vk = (kNow - lastK_) * (1 / (f.t - lastT_));
lastK_ = kNow, lastT_ = f.t, haveLast_ = true;
const V3 k = kNow + vk * p_.predict;
const V3 s = Shoulder(body, f.t);
raw_.dir = Norm(k - s);
raw_.origin = k + raw_.dir * p_.originAhead;
reach_ = Len(kNow - s);
lastFrame_ = f.t, arrived_ = now;
if (f.stereo) lastStereo_ = f.t;
tests_ = Evaluate(p_, body, f, raw_); // the shoulder's ray: the tests were tuned on it
// turned toward the hand's own direction (see "Hand direction" at the top)
if (p_.handWeight > 0 && axes_.ok) {
const V3 hand = HandDir(axes_, side_, p_.handPitch, p_.handYaw);
raw_.dir = fhsmooth::Slerp(raw_.dir, hand, std::min(p_.handWeight, 1.0));
raw_.origin = k + raw_.dir * p_.originAhead;
}
const bool tracked = f.t - lastStereo_ <= p_.stereoWithin;
const bool showOk = sideIsHand && tracked && tests_.show && !f.near;
const bool keepOk = tests_.keep;
if (!tests_.fails.empty()) why_ = tests_.fails;
else if (!tracked) why_ = "one camera";
else if (f.near) why_ = "near";
else why_ = "";
if (!sideIsHand) why_ = "off";
// the timers run on capture times
if (!shown_) {
if (showOk) {
if (showSince_ < 0) showSince_ = f.t;
if (f.t - showSince_ >= p_.showFor - 1e-9) Show();
} else {
showSince_ = -1;
}
} else {
if (!sideIsHand) {
Hide("off", f.t);
} else if (f.near && !held_) {
Hide("near", f.t);
} else if (keepOk || held_ || f.t < holdUntil_) {
failSince_ = -1;
} else {
if (failSince_ < 0) failSince_ = f.t;
if (f.t - failSince_ >= p_.hideFor - 1e-9) Hide(tests_.fails.empty() ? "pose" : tests_.fails, f.t);
}
}
if (shown_ && wasShown) filter_.Sample(raw_, reach_, f.t, now); // (Show took this frame already)
}
// Each tick, with the time now on the capture clock: the hand lost (no frame for lostFor) hides it.
void Tick(double now, bool sideIsHand) {
if (!shown_) return;
if (!sideIsHand) Hide("off", now);
else if (!held_ && now - lastFrame_ > p_.lostFor && now >= holdUntil_) Hide("lost", now);
}
// A ray pinch is held: the ray stays up until hideFor after it ends, and its filter takes the
// drag's precision (holdMinCutoff) meanwhile.
void Hold(bool on, double t) {
if (held_ && !on) holdUntil_ = t + p_.hideFor;
if (on && !held_) {
if (p_.holdShoulder) steady_ = true, steadyAt_ = lastS_;
// K pinned where it was in the newest frame, against the axes then (or the next frame's)
if (p_.pinchAnchor) {
if (axes_.ok) anchor_.Pin(axes_, lastMeasured_);
else pinAt_ = true;
}
}
held_ = on;
filter_.SetHeld(on);
}
void Reset() { Hide("reset", -1e9); }
// A pinch began on this hand at t: may its ray show for it (see the top)? within: how long ago
// it may have hidden.
bool CanShowForPinch(double t, double within) const {
return shown_ || showSince_ >= 0 || (revivable_ && t - hidAt_ <= within);
}
// Show it (filter started afresh from the hand now), for a pinch that may (CanShowForPinch).
void ShowForPinch() {
if (!shown_) Show();
}
bool Shown() const { return shown_; }
Ray Current() const { return filter_.Last(); } // filtered, where its timeline stands (the last frame or At)
Ray At(double now) { return filter_.At(now); } // filtered, at now (between frames: on its way to the newest)
const Ray &Raw() const { return raw_; } // unfiltered, predicted
double Reach() const { return filter_.Reach(); } // |K - S|, filtered: arm out or in (push and pull)
double RawReach() const { return reach_; }
const Tests &LastTests() const { return tests_; }
const std::string &Why() const { return why_; } // what fails now ("" if nothing)
// Changes since the caller last cleared it: "show" or "hide <reason>".
std::string event;
private:
// How much of a held pinch's steadiness is left at t: 1 while it's held and hideFor after, then
// down to 0 over shoulderBlend (see "Steady shoulder" at the top).
double Steady(double t) const {
if (held_) return 1;
return 1 - std::clamp((t - holdUntil_) / std::max(1e-3, p_.shoulderBlend), 0.0, 1.0);
}
// The ray's shoulder (see "Steady shoulder" at the top).
V3 Shoulder(const Body &body, double t) {
V3 s = body.Shoulder(side_);
if (steady_) {
const double w = Steady(t);
if (w <= 0) steady_ = false;
else s = steadyAt_ + (s - steadyAt_) * (1 - w);
}
lastS_ = s;
return s;
}
void Show() {
shown_ = true, failSince_ = -1, showSince_ = -1;
filter_.Reset();
filter_.Sample(raw_, reach_, lastFrame_, arrived_);
event = "show";
}
void Hide(const std::string &why, double t) {
if (!shown_) return;
shown_ = false, failSince_ = -1, showSince_ = -1, held_ = false, holdUntil_ = 0, steady_ = false;
anchor_.Unpin(), pinAt_ = false;
filter_.SetHeld(false);
hidAt_ = t, revivable_ = why != "off" && why != "near" && why != "reset";
event = "hide " + why;
}
int side_;
Params p_;
RayFilter filter_;
Ray raw_;
Tests tests_;
std::string why_;
V3 lastK_, lastS_, steadyAt_, lastMeasured_;
Axes axes_;
Anchor anchor_;
bool pinAt_ = false; // pin at the next frame (no axes when the pinch began)
double lastT_ = 0, lastFrame_ = -1e9, lastStereo_ = -1e9, reach_ = 0, arrived_ = 0;
double showSince_ = -1, failSince_ = -1, holdUntil_ = 0, hidAt_ = -1e9;
bool haveLast_ = false, shown_ = false, held_ = false, revivable_ = false, steady_ = false;
};
} // namespace fhray
+265
View File
@@ -0,0 +1,265 @@
// fh_smooth - smoothing for what a hand moves: One Euro filters (Casiez, Roussel and Vogel, CHI
// 2012) run in continuous time, so a hand tracked at 15-30 Hz moves things smoothly at the
// display's rate instead of in steps. Shared by the pointer helper (the hand ray, through
// hands/include/fh_ray.h) and ft-screens (near grabs, screens/handinput.cpp).
// Design: frame-hands/notes/hand-interaction.md, section 13.
//
// The One Euro filter is a first-order low-pass whose cutoff rises with speed: minCutoff (Hz)
// still, plus beta per unit of speed (the speed itself low-passed at dCutoff). Slow and still:
// heavy smoothing, so jitter goes; fast: little, so it keeps up. Here it runs in continuous
// time: each tracker sample sets the cutoff and where the input goes, and At(now) is the
// low-pass's output at now, however often the caller asks. The input slides from the sample
// before to the newest over one frame interval (the capture times' gap, at most 0.1 s), so a
// steady move comes out as a steady move: held still, the input made the output catch up and
// stall each frame, steps again at a high cutoff. The slide costs half a frame of delay
// (17 ms at 30 Hz) over holding the sample. The output never passes the newest sample (no
// overshoot); the classic discrete filter, read at the display's rate, holds still and then
// jumps a whole step each sample. No prediction past the newest sample: the ray and a carried
// panel stay behind the hand by the tracking latency plus the filter's lag, never ahead of it.
//
// Point<N>: N values (1 for a distance, 3 for a point); the speed is the length of the
// change, so it smooths the same along every axis. Direction: a unit vector, filtered on the
// sphere (it turns along the great circle toward the newest sample; speed in degrees per
// second), with no angle to wrap and no trouble pointing straight up.
//
// Times are seconds on one steady clock. Each sample has its capture time (for the speed) and
// the time it arrived (now: where the output's timeline stands). Header-only C++17, no
// dependencies.
#pragma once
#include <algorithm>
#include <cmath>
namespace fhsmooth {
struct V3 {
double x = 0, y = 0, z = 0;
};
inline V3 operator+(V3 a, V3 b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
inline V3 operator-(V3 a, V3 b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; }
inline V3 operator*(V3 a, double s) { return {a.x * s, a.y * s, a.z * s}; }
inline double Dot(V3 a, V3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
inline V3 Cross(V3 a, V3 b) { return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; }
inline double Len(V3 a) { return std::sqrt(Dot(a, a)); }
inline V3 Norm(V3 a) {
const double l = Len(a);
return l > 1e-12 ? a * (1 / l) : V3{0, 0, -1};
}
// The angle between two unit vectors, radians (accurate near 0, unlike acos).
inline double Angle(V3 a, V3 b) { return std::atan2(Len(Cross(a, b)), Dot(a, b)); }
// a turned toward b (unit vectors) by the fraction k of the angle between them.
inline V3 Slerp(V3 a, V3 b, double k) {
const double w = Angle(a, b);
if (w < 1e-9) return b;
if (w > M_PI - 1e-6) return k < 0.5 ? a : b; // opposite: no one way round
const double s = std::sin(w);
return Norm(a * (std::sin((1 - k) * w) / s) + b * (std::sin(k * w) / s));
}
struct Params {
double minCutoff = 1; // Hz, still
double beta = 0; // Hz more per unit of speed (per m/s for points, per deg/s for directions)
double dCutoff = 1; // Hz: the speed's own low-pass
double maxCutoff = 0; // Hz: at most this (0: no limit), however fast it moves
};
inline double CutoffAt(const Params &p, double speed) {
const double c = p.minCutoff + p.beta * speed;
return p.maxCutoff > 0 ? std::min(c, p.maxCutoff) : c;
}
namespace detail {
// The discrete low-pass's weight for a step dt at this cutoff (the derivative's, as One Euro's).
inline double Alpha(double cutoff, double dt) { return 1 / (1 + 1 / (2 * M_PI * cutoff * dt)); }
// How far a continuous first-order low-pass at this cutoff gets toward its input in dt.
inline double Toward(double cutoff, double dt) { return 1 - std::exp(-2 * M_PI * cutoff * dt); }
} // namespace detail
// The input's slide from the sample before to the newest (see the top), and the low-pass's steps
// along it (at most kStep: the input moves within each).
constexpr double kStep = 0.004, kMaxSlide = 0.1;
template <int N>
class Point {
public:
explicit Point(const Params &p = {}) : p_(p) {}
// New settings (a held drag's precision, say): the cutoff changes from now, the output doesn't jump.
void Set(const Params &p) {
p_ = p;
cutoff_ = CutoffAt(p_, speed_);
}
const Params &Get() const { return p_; }
void Reset() { init_ = false; }
bool Ready() const { return init_; }
// A tracker sample, captured at tc, arrived at now (pass tc for both when there's no clock to
// tell them apart). The first one, or one after Reset, is taken as it is.
void Sample(const double v[N], double tc, double now) {
if (!init_) {
std::copy(v, v + N, x_), std::copy(v, v + N, r_), std::copy(v, v + N, from_);
std::fill(d_, d_ + N, 0.0);
speed_ = 0, tc_ = tc, t_ = start_ = now, slide_ = 0, init_ = true;
cutoff_ = p_.minCutoff;
return;
}
Advance(now);
const double dt = tc - tc_;
if (dt > 1e-4) {
// the speed from the raw samples (as the reference implementation), low-passed
const double a = detail::Alpha(p_.dCutoff, std::min(dt, 0.5));
double s2 = 0;
for (int i = 0; i < N; ++i) {
d_[i] += a * ((v[i] - r_[i]) / dt - d_[i]);
s2 += d_[i] * d_[i];
}
speed_ = std::sqrt(s2);
tc_ = tc;
}
Input(now, from_); // the slide starts where the input is now
std::copy(v, v + N, r_);
start_ = now, slide_ = std::clamp(dt, 0.0, kMaxSlide);
cutoff_ = CutoffAt(p_, speed_);
}
// The output at now (moves the filter's timeline there; a time before it reads the output as it is).
const double *At(double now) {
Advance(now);
return x_;
}
// After Reset and a first Sample: the speed it's moving at (units per second, per axis), so it
// follows a moving input at once instead of from rest (a hand back after a gap, at the gap's speed).
void Seed(const double rate[N]) {
double s2 = 0;
for (int i = 0; i < N; ++i) d_[i] = rate[i], s2 += rate[i] * rate[i];
speed_ = std::sqrt(s2), cutoff_ = CutoffAt(p_, speed_);
}
const double *Last() const { return x_; } // the output where the timeline stands
const double *Raw() const { return r_; } // the newest sample
double Speed() const { return speed_; } // low-passed, units per second
double Cutoff() const { return cutoff_; }
private:
void Input(double t, double out[N]) const {
const double u = slide_ > 0 ? std::clamp((t - start_) / slide_, 0.0, 1.0) : 1.0;
for (int i = 0; i < N; ++i) out[i] = from_[i] + u * (r_[i] - from_[i]);
}
void Advance(double now) {
if (now <= t_) return;
if (now - t_ > 1) t_ = now - 1;
while (t_ < now) {
const double h = std::min(kStep, now - t_);
t_ += h;
double in[N];
Input(t_, in);
const double k = detail::Toward(cutoff_, h);
for (int i = 0; i < N; ++i) x_[i] += k * (in[i] - x_[i]);
}
}
Params p_;
double x_[N] = {}, r_[N] = {}, from_[N] = {}, d_[N] = {};
double speed_ = 0, cutoff_ = 1, tc_ = 0, t_ = 0, start_ = 0, slide_ = 0;
bool init_ = false;
};
// A point in 3D (V3 in and out).
class Point3 {
public:
explicit Point3(const Params &p = {}) : f_(p) {}
void Set(const Params &p) { f_.Set(p); }
const Params &Get() const { return f_.Get(); }
void Reset() { f_.Reset(); }
bool Ready() const { return f_.Ready(); }
void Sample(V3 v, double tc, double now) {
const double a[3] = {v.x, v.y, v.z};
f_.Sample(a, tc, now);
}
V3 At(double now) {
const double *x = f_.At(now);
return {x[0], x[1], x[2]};
}
V3 Last() const { return {f_.Last()[0], f_.Last()[1], f_.Last()[2]}; }
double Speed() const { return f_.Speed(); }
void Seed(V3 rate) {
const double a[3] = {rate.x, rate.y, rate.z};
f_.Seed(a);
}
private:
Point<3> f_;
};
// One value (a distance).
class Scalar {
public:
explicit Scalar(const Params &p = {}) : f_(p) {}
void Set(const Params &p) { f_.Set(p); }
void Reset() { f_.Reset(); }
bool Ready() const { return f_.Ready(); }
void Sample(double v, double tc, double now) { f_.Sample(&v, tc, now); }
double At(double now) { return *f_.At(now); }
double Last() const { return *f_.Last(); }
private:
Point<1> f_;
};
// A direction (unit vector), on the sphere; beta per deg/s.
class Direction {
public:
explicit Direction(const Params &p = {}) : p_(p) {}
void Set(const Params &p) {
p_ = p;
cutoff_ = CutoffAt(p_, speed_);
}
const Params &Get() const { return p_; }
void Reset() { init_ = false; }
bool Ready() const { return init_; }
void Sample(V3 v, double tc, double now) {
v = Norm(v);
if (!init_) {
x_ = r_ = from_ = v, w_ = {}, speed_ = 0, tc_ = tc, t_ = start_ = now, slide_ = 0, init_ = true;
cutoff_ = p_.minCutoff;
return;
}
Advance(now);
const double dt = tc - tc_;
if (dt > 1e-4) {
// angular velocity (axis times rate, deg/s) from the raw samples, low-passed as a vector
const V3 axis = Cross(r_, v);
const double s = Len(axis), w = Angle(r_, v) * 180 / M_PI / dt;
const V3 now_w = s > 1e-12 ? axis * (w / s) : V3{};
w_ = w_ + (now_w - w_) * detail::Alpha(p_.dCutoff, std::min(dt, 0.5));
speed_ = Len(w_);
tc_ = tc;
}
from_ = Input(now);
r_ = v;
start_ = now, slide_ = std::clamp(dt, 0.0, kMaxSlide);
cutoff_ = CutoffAt(p_, speed_);
}
V3 At(double now) {
Advance(now);
return x_;
}
V3 Last() const { return x_; }
V3 Raw() const { return r_; }
double Speed() const { return speed_; } // deg/s, low-passed
double Cutoff() const { return cutoff_; }
private:
V3 Input(double t) const {
return Slerp(from_, r_, slide_ > 0 ? std::clamp((t - start_) / slide_, 0.0, 1.0) : 1.0);
}
void Advance(double now) {
if (now <= t_) return;
if (now - t_ > 1) t_ = now - 1;
while (t_ < now) {
const double h = std::min(kStep, now - t_);
t_ += h;
x_ = Slerp(x_, Input(t_), detail::Toward(cutoff_, h));
}
}
Params p_;
V3 x_, r_, from_, w_;
double speed_ = 0, cutoff_ = 1, tc_ = 0, t_ = 0, start_ = 0, slide_ = 0;
bool init_ = false;
};
} // namespace fhsmooth
+16
View File
@@ -0,0 +1,16 @@
# The fine-tuned hand models ft-hands uses by default (hands/models.sh): a version folder of the
# Hugging Face repo DeeJanuz/frametop-hands-models at a fixed commit, and every file's sha256.
# Installs read this file from GitHub (main or experimental, by their channel) when hand tracking
# starts, so a new pin pushed there reaches them without a release. "format" is what ft-hands
# needs to run them: raise it when a model needs a newer ft-hands, and older installs keep theirs.
# Made by frame-hands' model-repo/pin.py.
format 1
rev 41afd78fbd4527456fc4cbd840ffc9f39fdc939a
model v13b-p1
file NOTICE 0e6b4fa8ea37665cb699abc36fcf1ee0ffaa63a78dfee788be6613dea6607f84
file hand.ncnn.bin d6a6f00d845fb9ee490276d84b1e978da884361c372614546ed2b1b4d2f5c449
file hand.ncnn.param 54e08f284ff6f121ff00f4a9c65afc38c0dbb22a32f4af44fc4e0fde6c4a1bbd
file palm.ncnn.bin 9865f5fa3c6bc885cb0b50f201c4ac1bd83b2c1ad64af4e122efa3fc56d61909
file palm.ncnn.param c61df2dde5b221a55c35c9693e530845a95ce2732949a9b3d3c583e3b2bae92e
file LICENSE 41003d4a74749c0220e33dd415042164b5a1093ed401f36277234f772d22d3d0
file README.md 29c6c5460e47412a9a37b22d6a7c8a9ed266a872bbcce93d3867f9e56cfe0ca1
+137
View File
@@ -0,0 +1,137 @@
#!/usr/bin/env bash
# Fetch the fine-tuned hand models into hands/models/student/ on the Frame (in the image build,
# here: pack/Containerfile runs hands/build.sh, which runs this). hands/models.pin names them: a
# fixed commit of the Hugging Face repo below, and every file's sha256. ft-hands uses them when
# they're there (HANDS_MODELS overrides; hands/models/ncnn, the stock MediaPipe models, otherwise).
# palm.ncnn.*, hand.ncnn.* MediaPipe's palm detector and hand landmark model, fine-tuned on the
# Frametop hand dataset (DeeJanuz/frametop-hands)
# LICENSE, README.md their licence (CC BY-NC 4.0, not Frametop's MIT) and model card
# Usage: hands/models.sh [fetch] fetch what's missing or doesn't match models.pin (the default)
# hands/models.sh check check every file against the pin it was fetched by (exit 1 if not)
# hands/models.sh update fetch the models the install's branch pins on GitHub now (main for
# a stable release, experimental for an experimental one or a
# clone on that branch), if they changed. Into a folder of its own,
# swapped in once every file matches. Offline or nothing new: no-op.
# hands/models.sh auto update, as frametop-hands.service runs it when hand tracking
# starts: not with HANDS_MODELS_UPDATE=0 in ~/.config/frametop.conf,
# and at most every 15 minutes.
set -euo pipefail
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
. "$root/scripts/_env.sh"
case ${1:-fetch} in fetch | check | update | auto) ;; *) sed -n '9,18p' "$0" >&2; exit 2 ;; esac
on_frame_script "${1:-fetch}" "$FRAME_REPO" <<'SCRIPT'
set -euo pipefail
mode=$1 tree=$2
models=$tree/hands/models dir=$tree/hands/models/student
hf=DeeJanuz/frametop-hands-models gh=Frametop/frametop
names=" NOTICE hand.ncnn.bin hand.ncnn.param palm.ncnn.bin palm.ncnn.param LICENSE README.md "
# read_pin FILE: check every line of a pin, then set rev, model and files ("name sha256" each).
# Anything unexpected fails it: a pin from GitHub only names files this list allows.
read_pin() {
local key a b n format=
rev= model= files=()
while read -r key a b; do
case $key in '' | '#'*) continue ;; esac
case $key in
format) [ "$a" = 1 ] && [ -z "$b" ] || return 1; format=$a ;;
rev) [[ $a =~ ^[0-9a-f]{40}$ ]] && [ -z "$b" ] || return 1; rev=$a ;;
model) [[ $a =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ ]] && [ -z "$b" ] || return 1; model=$a ;;
file) [[ $names == *" $a "* && $b =~ ^[0-9a-f]{64}$ ]] || return 1; files+=("$a $b") ;;
*) return 1 ;;
esac
done <"$1"
[ -n "$format" ] && [ -n "$rev" ] && [ -n "$model" ] || return 1
for n in hand.ncnn.bin hand.ncnn.param palm.ncnn.bin palm.ncnn.param; do
[[ " ${files[*]} " == *" $n "* ]] || return 1
done
}
matches() { [ -f "$1" ] && [ "$(sha256sum <"$1" | cut -d' ' -f1)" = "$2" ]; }
# fetch_into DIR: fetch the pin's files that are missing there or don't match.
fetch_into() {
local d=$1 entry name sum src
mkdir -p "$d"
for entry in "${files[@]}"; do
read -r name sum <<<"$entry"
matches "$d/$name" "$sum" && continue
src=https://huggingface.co/$hf/resolve/$rev/$model/$name
case $name in LICENSE | README.md) src=https://huggingface.co/$hf/resolve/$rev/$name ;; esac
echo "fetching hand model $name ($model)"
if ! curl -fsSL --retry 3 --connect-timeout 10 --max-filesize 100000000 -o "$d/$name.part" "$src"; then
rm -f "$d/$name.part"; return 1
fi
if ! matches "$d/$name.part" "$sum"; then
echo "hand models: $name's sha256 doesn't match the pin; not kept" >&2
rm -f "$d/$name.part"; return 1
fi
mv "$d/$name.part" "$d/$name"
done
}
stamp() { echo "$hf@${rev::7} $model" >"$1/VERSION"; }
case $mode in
fetch)
read_pin "$tree/hands/models.pin" || { echo "hand models: hands/models.pin isn't a valid pin" >&2; exit 1; }
fetch_into "$dir"
cp "$tree/hands/models.pin" "$dir/PIN"; stamp "$dir"
echo "hand models: $model in $dir"
;;
check)
# Against the pin they were fetched by: an update may have replaced the release's own.
pin=$dir/PIN; [ -f "$pin" ] || pin=$tree/hands/models.pin
[ -d "$dir" ] || { echo "hand models: $dir missing" >&2; exit 1; }
read_pin "$pin" || { echo "hand models: $pin isn't a valid pin" >&2; exit 1; }
bad=0
for entry in "${files[@]}"; do
read -r name sum <<<"$entry"
matches "$dir/$name" "$sum" || { echo "hand models: $name missing or changed" >&2; bad=1; }
done
[ "$bad" = 0 ] || exit 1
echo "hand models: $model in $dir, all files match"
;;
update | auto)
if [ "$mode" = auto ]; then
conf=$(sed -n 's/#.*//; s/^[[:space:]]*HANDS_MODELS_UPDATE[[:space:]]*=[[:space:]]*//p' ~/.config/frametop.conf 2>/dev/null | tail -1)
conf=${FT_HANDS_MODELS_UPDATE:-$conf}
[ "$(echo $conf | tr -d "\"'")" = 0 ] && { echo "hand models: not updating (HANDS_MODELS_UPDATE=0)"; exit 0; }
[ -n "$(find "$models/.student-checked" -mmin -15 2>/dev/null)" ] && exit 0
fi
if [ -f "$tree/.frametop-release" ]; then
case $(sed -n 's/^CHANNEL=//p' "$tree/.frametop-release" | tail -1) in
experimental) branch=experimental ;; *) branch=main ;;
esac
else
branch=$(git -C "$tree" symbolic-ref --short -q HEAD 2>/dev/null || true)
fi
case $branch in main | experimental) ;; *) echo "hand models: no updates for branch '$branch'"; exit 0 ;; esac
mkdir -p "$models"
exec 9>"$models/.student-lock"
flock -n 9 || { echo "hand models: another update is running"; exit 0; }
touch "$models/.student-checked"
tmp=$(mktemp); trap 'rm -f "$tmp"' EXIT
code=$(curl -sS --connect-timeout 4 --max-time 15 --max-filesize 16384 -o "$tmp" -w '%{http_code}' \
"https://raw.githubusercontent.com/$gh/$branch/hands/models.pin") || code=
case $code in
200) ;;
'') echo "hand models: couldn't reach GitHub; keeping these"; exit 0 ;;
*) echo "hand models: $branch pins none ($code); keeping these"; exit 0 ;;
esac
cmp -s "$tmp" "$dir/PIN" 2>/dev/null && { echo "hand models: up to date ($(cat "$dir/VERSION" 2>/dev/null))"; exit 0; }
read_pin "$tmp" || { echo "hand models: $branch's pin isn't valid (or needs a newer Frametop); keeping these" >&2; exit 1; }
# Into .student-new, seeded with the files we have (a stopped update keeps what it fetched),
# then swapped with student in one rename: ft-hands never sees half a set.
new=$models/.student-new
mkdir -p "$new"
[ -d "$dir" ] && cp -a --update=none "$dir/." "$new/"
rm -f "$new"/*.part
fetch_into "$new" || { echo "hand models: update failed; keeping these" >&2; exit 1; }
cp "$tmp" "$new/PIN"; stamp "$new"
if [ -d "$dir" ]; then mv -T --exchange "$new" "$dir"; rm -rf "$new"; else mv -T "$new" "$dir"; fi
echo "hand models: updated to $model from $branch's pin"
;;
esac
SCRIPT
+4
View File
@@ -10,3 +10,7 @@ Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0).
Changes made here: converted to ncnn with pnnx, with the palm detector's channel pads
rewritten as ncnn Padding layers, and quantized to 8 bits (the *-int8.ncnn.* files) with
ncnn's tools.
hands/models.sh fetches fine-tuned versions of the same two models into student/ (not in this
repository): their weights are licensed CC BY-NC 4.0, not Apache-2.0 or MIT; see student/LICENSE and
student/README.md once fetched, or https://huggingface.co/DeeJanuz/frametop-hands-models.
Loaded 100 of 327 files, more files were not shown because too many files have changed in this diff. Show more