mirror of
https://github.com/DeeJanuz/frametop.git
synced 2026-10-14 18:00:45 +02:00
Compare commits
439
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
83ab2f0b5e | ||
|
|
6f63702089 | ||
|
|
36d11c523e | ||
|
|
4b9f5bf8dd | ||
|
|
afab3cbecc | ||
|
|
6d0c542bb8 | ||
|
|
b0af03e83c | ||
|
|
ada9d6e9c9 | ||
|
|
797e5c7b12 | ||
|
|
8f79a90044 | ||
|
|
9d6f5984a8 | ||
|
|
7dfdfd24e1 | ||
|
|
35d30474bc | ||
|
|
f447ecc7ec | ||
|
|
9029a2d7a5 | ||
|
|
09ba8afcf0 | ||
|
|
57d3510ad7 | ||
|
|
45e6759ef2 | ||
|
|
341fa2435f | ||
|
|
0b08bfabaa | ||
|
|
d1b495a7f0 | ||
|
|
e4bc1fbc6e | ||
|
|
9f3dc1ca12 | ||
|
|
0abcda6e80 | ||
|
|
30313ea7db | ||
|
|
b0300387f4 | ||
|
|
7cea0b440a | ||
|
|
54341c5aa4 | ||
|
|
63fb9e0127 | ||
|
|
49411bb828 | ||
|
|
09126151d8 | ||
|
|
870ad7687c | ||
|
|
3fe498ffc3 | ||
|
|
4c20053101 | ||
|
|
1faa0241e2 | ||
|
|
c0947a438e | ||
|
|
60ca2fba69 | ||
|
|
81dbd32812 | ||
|
|
fdf382f0f5 | ||
|
|
53cdefd74b | ||
|
|
672d186faf | ||
|
|
6d74ea2ab3 | ||
|
|
4ef4f5d5ba | ||
|
|
2b79093086 | ||
|
|
d70c99dd7e | ||
|
|
119b248063 | ||
|
|
fabee2b1fe | ||
|
|
fccccbffc6 | ||
|
|
188f107cfc | ||
|
|
db033b238d | ||
|
|
d6d27716e3 | ||
|
|
80bce4cf66 | ||
|
|
0ce6843338 | ||
|
|
b67c1931c6 | ||
|
|
0b72710474 | ||
|
|
02f1575c52 | ||
|
|
90114ed043 | ||
|
|
12b8159d4e | ||
|
|
a546469db6 | ||
|
|
978929ef8c | ||
|
|
6164766efa | ||
|
|
cb109db6ac | ||
|
|
802779cae7 | ||
|
|
114c22e90b | ||
|
|
1202029d43 | ||
|
|
624dc73099 | ||
|
|
f93b0e6c40 | ||
|
|
6d5dfeef6c | ||
|
|
95d2c696ab | ||
|
|
1521420964 | ||
|
|
c5e0c4f529 | ||
|
|
516f2c056d | ||
|
|
1c10e9a717 | ||
|
|
b905a63345 | ||
|
|
5fb194a01f | ||
|
|
639a761d88 | ||
|
|
d1ceb3d744 | ||
|
|
249f622b1b | ||
|
|
cad02f978c | ||
|
|
65105eeb59 | ||
|
|
8ae8b8400e | ||
|
|
d0029054ee | ||
|
|
39198fc1b5 | ||
|
|
f956dd3e52 | ||
|
|
a54d89ee86 | ||
|
|
6c9f86145b | ||
|
|
b1b773551c | ||
|
|
06cdb2ed8b | ||
|
|
c91f4a21f5 | ||
|
|
63c9aafff2 | ||
|
|
2711c8850c | ||
|
|
a4f21a305e | ||
|
|
9972d53fbc | ||
|
|
99da5e8942 | ||
|
|
03fc7eac40 | ||
|
|
b3a26004a8 | ||
|
|
0249491033 | ||
|
|
1f0383ce4c | ||
|
|
a0e46e4954 | ||
|
|
8d3de8e13f | ||
|
|
fae63a8820 | ||
|
|
64d2f018ac | ||
|
|
f025e56d0f | ||
|
|
0571d4a67d | ||
|
|
6c921b113c | ||
|
|
9290ae6c0e | ||
|
|
141fb3b152 | ||
|
|
8135bd351d | ||
|
|
213207309d | ||
|
|
24d2d12397 | ||
|
|
be8f786efd | ||
|
|
b6fff6d491 | ||
|
|
78ec0f14f3 | ||
|
|
e511c705f9 | ||
|
|
f4f526dc08 | ||
|
|
56fb3b3d82 | ||
|
|
a67abc62ff | ||
|
|
388e8584d4 | ||
|
|
8a0c6c707e | ||
|
|
2032a5478d | ||
|
|
2c472879ed | ||
|
|
384e1a84c7 | ||
|
|
b338d04acb | ||
|
|
948017953d | ||
|
|
1d795874e7 | ||
|
|
887afb0090 | ||
|
|
94da65bc93 | ||
|
|
8bc187503b | ||
|
|
5366a8774e | ||
|
|
5459723bda | ||
|
|
939df2f1cd | ||
|
|
5ca7c488b5 | ||
|
|
87c5267f27 | ||
|
|
ca1e5c38ab | ||
|
|
6ccd0be3b7 | ||
|
|
35906887bb | ||
|
|
d7472b78ff | ||
|
|
0ed59fde40 | ||
|
|
f71d2f7887 | ||
|
|
bce02ac568 | ||
|
|
018677bcb1 | ||
|
|
b3275e7843 | ||
|
|
85f920ff58 | ||
|
|
bd44735f3b | ||
|
|
b29adb50cc | ||
|
|
700f534a27 | ||
|
|
995d407328 | ||
|
|
1d88af4c6e | ||
|
|
2a51094d8e | ||
|
|
93adab7302 | ||
|
|
723ad4a6b9 | ||
|
|
ac5111c552 | ||
|
|
26507e62b3 | ||
|
|
cfe227f0d1 | ||
|
|
f7c580506d | ||
|
|
7160180906 | ||
|
|
72d9b79d7b | ||
|
|
2ae1a36b33 | ||
|
|
b5e410b0b9 | ||
|
|
d9f213b872 | ||
|
|
9df7df5f91 | ||
|
|
811e15ed9d | ||
|
|
7f55e9328a | ||
|
|
9def5f1762 | ||
|
|
2af6207862 | ||
|
|
920d16ee5e | ||
|
|
b45a99030a | ||
|
|
f16ad59a92 | ||
|
|
68c783fd20 | ||
|
|
366f5efa4c | ||
|
|
e4c51ccf6b | ||
|
|
8a0176075e | ||
|
|
db2e633502 | ||
|
|
c2a8328f35 | ||
|
|
3a7a532cb9 | ||
|
|
ac94fb2828 | ||
|
|
eafb73483b | ||
|
|
0d6b0c93b5 | ||
|
|
bd7b15613f | ||
|
|
d348e0a260 | ||
|
|
3c4964bc56 | ||
|
|
45c716da7c | ||
|
|
1a575e922a | ||
|
|
7ccf34c042 | ||
|
|
3d1eee828a | ||
|
|
2bb7c43af9 | ||
|
|
2c57eef75c | ||
|
|
64bead79c9 | ||
|
|
2fcd29c0f5 | ||
|
|
07ce0d9d59 | ||
|
|
85d34c73a4 | ||
|
|
98475f2b7d | ||
|
|
2c9924484d | ||
|
|
4c348e6b2b | ||
|
|
b521564a68 | ||
|
|
1fdd6f0e78 | ||
|
|
6b7af52e1c | ||
|
|
a53ced4f88 | ||
|
|
28f91af0d2 | ||
|
|
e69fe11b2a | ||
|
|
65acbd9638 | ||
|
|
ef1c802e2d | ||
|
|
26de1430b0 | ||
|
|
e21a2beae0 | ||
|
|
8d6aa459fc | ||
|
|
b93c25eb7e | ||
|
|
b61aebcf16 | ||
|
|
dba0ef5707 | ||
|
|
70c3ad9b1c | ||
|
|
185cb766b1 | ||
|
|
305dd9bcef | ||
|
|
90698db6c7 | ||
|
|
48a2dcf759 | ||
|
|
06228725cc | ||
|
|
d82364ed00 | ||
|
|
5d214d4c3b | ||
|
|
2852ad9f99 | ||
|
|
be0314867e | ||
|
|
bcc2da2b4a | ||
|
|
08656417e1 | ||
|
|
4f5087201d | ||
|
|
cb417e4fb5 | ||
|
|
400fe0ca5f | ||
|
|
d16f774d50 | ||
|
|
0e036482e0 | ||
|
|
bf6266ce81 | ||
|
|
5d96d211ec | ||
|
|
2ed603b304 | ||
|
|
564bb4bdc5 | ||
|
|
742bd32c32 | ||
|
|
2f0285e22a | ||
|
|
44c99f2980 | ||
|
|
82d09cf98f | ||
|
|
9f567b4bb2 | ||
|
|
eca95477cd | ||
|
|
a57bd822de | ||
|
|
dd777576d8 | ||
|
|
3a63780bbd | ||
|
|
d3ec6877ae | ||
|
|
6accce9769 | ||
|
|
f9408a6612 | ||
|
|
e9cb33389d | ||
|
|
52b10478ad | ||
|
|
275529da8f | ||
|
|
b727b8b8fe | ||
|
|
46bf562c5f | ||
|
|
0ffbf7a718 | ||
|
|
2e293beb3a | ||
|
|
4daa8fea5b | ||
|
|
78fac8ca0a | ||
|
|
09cec0c980 | ||
|
|
325d3d91a4 | ||
|
|
48a3c0af87 | ||
|
|
d7cc82ab09 | ||
|
|
a4a1d8819c | ||
|
|
e2b4eb2a81 | ||
|
|
95938a1f27 | ||
|
|
9c0facd0c5 | ||
|
|
eaaab1ccaf | ||
|
|
84a354536e | ||
|
|
14cbfc310e | ||
|
|
40c7606ace | ||
|
|
00a377a0fb | ||
|
|
8a88fbea05 | ||
|
|
9411148596 | ||
|
|
95ccaa30de | ||
|
|
b655cd7446 | ||
|
|
0e506aaf81 | ||
|
|
fcafd43679 | ||
|
|
4764c21548 | ||
|
|
eae2f0b754 | ||
|
|
38bdfd856a | ||
|
|
6dd9fb1ad8 | ||
|
|
6dc4521905 | ||
|
|
96452bbee5 | ||
|
|
b6908737c4 | ||
|
|
f6a9845996 | ||
|
|
050be96bf0 | ||
|
|
7dfa04aab2 | ||
|
|
2a675b9121 | ||
|
|
f0df502a23 | ||
|
|
e402b134ad | ||
|
|
083fa89f52 | ||
|
|
eb13cfc5dc | ||
|
|
c40bb645f2 | ||
|
|
195fb1e441 | ||
|
|
f6fe1455fc | ||
|
|
2052dff70d | ||
|
|
0d7ed2d75c | ||
|
|
a94af27131 | ||
|
|
d4558c7187 | ||
|
|
aef18d3601 | ||
|
|
221d01db32 | ||
|
|
282b038a3c | ||
|
|
63bcea49a6 | ||
|
|
9b11162b61 | ||
|
|
983a4654b3 | ||
|
|
85b8717bb8 | ||
|
|
e2f51477a3 | ||
|
|
525c77e60c | ||
|
|
64d3a9eb9c | ||
|
|
d1430d20e8 | ||
|
|
6825f80096 | ||
|
|
8086350e06 | ||
|
|
fb6ef934a4 | ||
|
|
54ec0853aa | ||
|
|
8fc8cf2063 | ||
|
|
b15dce6a0a | ||
|
|
b52df75bc0 | ||
|
|
dfd1bbca0f | ||
|
|
0318bb72ab | ||
|
|
3519a7a0e1 | ||
|
|
8117a4fb7e | ||
|
|
4ba49af487 | ||
|
|
82fbc6fc1b | ||
|
|
8bd2ac4c92 | ||
|
|
ac692c38ea | ||
|
|
d6556ca813 | ||
|
|
9d66e36439 | ||
|
|
dac4188392 | ||
|
|
a9f1bcfdde | ||
|
|
effcfd0e48 | ||
|
|
3be79efade | ||
|
|
030ef2faf1 | ||
|
|
44c0b2d796 | ||
|
|
56aa3e4b4b | ||
|
|
977e9a0950 | ||
|
|
82979e4423 | ||
|
|
18e436d7b4 | ||
|
|
bb88599085 | ||
|
|
302df6c2da | ||
|
|
8298754437 | ||
|
|
d6f6f0fe7f | ||
|
|
491202acfc | ||
|
|
b234abc245 | ||
|
|
f8f33c5663 | ||
|
|
b33c5df41f | ||
|
|
06288ff20c | ||
|
|
7854d6ab9d | ||
|
|
891d84ae2b | ||
|
|
434b4aadc9 | ||
|
|
ed6caf6ff0 | ||
|
|
5fa557afbb | ||
|
|
a0a5468c59 | ||
|
|
e984418b25 | ||
|
|
77f7cc82be | ||
|
|
897488ff02 | ||
|
|
17f3a2c55c | ||
|
|
72e5ad4489 | ||
|
|
e88ae95c0c | ||
|
|
2ce81c553a | ||
|
|
332633c919 | ||
|
|
d2a9e2bbc9 | ||
|
|
318a4a1682 | ||
|
|
60095b02bf | ||
|
|
ea47422872 | ||
|
|
c119442c70 | ||
|
|
fb1c587d69 | ||
|
|
102e859cf8 | ||
|
|
b21dfd1bb0 | ||
|
|
bcf8516ebd | ||
|
|
db0d526f81 | ||
|
|
81f24a5d04 | ||
|
|
55f00f300d | ||
|
|
b2d32e8934 | ||
|
|
f6b4323669 | ||
|
|
903abd75dd | ||
|
|
f65afce59a | ||
|
|
1bb8e73cb9 | ||
|
|
0821b1013e | ||
|
|
3cccad3525 | ||
|
|
845bff0037 | ||
|
|
2ede132b62 | ||
|
|
a70463d95b | ||
|
|
a84889b4a5 | ||
|
|
8b9edcfbe2 | ||
|
|
0f1132ed27 | ||
|
|
4828dd46b5 | ||
|
|
d4e5e2b442 | ||
|
|
82da3525b7 | ||
|
|
2a2bca336c | ||
|
|
cd47dde566 | ||
|
|
a5d001d4b5 | ||
|
|
fa65954834 | ||
|
|
c747bea791 | ||
|
|
e918359c8f | ||
|
|
c53a4f07e9 | ||
|
|
cb34ba45a1 | ||
|
|
740aededff | ||
|
|
8655395030 | ||
|
|
6f65145553 | ||
|
|
cce37b5835 | ||
|
|
ff3724cb3c | ||
|
|
48bceaef64 | ||
|
|
c1ba71aba1 | ||
|
|
9c6647538b | ||
|
|
8a77364767 | ||
|
|
b61b4d6c6a | ||
|
|
edf605f896 | ||
|
|
b5fe574ae6 | ||
|
|
76d6542071 | ||
|
|
a94a0fb432 | ||
|
|
b1b1a16f5b | ||
|
|
276c1409e8 | ||
|
|
a0fe3bb55e | ||
|
|
13198bc203 | ||
|
|
42a26753d3 | ||
|
|
0f0674ff36 | ||
|
|
3a796b5013 | ||
|
|
67a3c02e31 | ||
|
|
662919babf | ||
|
|
98bd6ce21c | ||
|
|
608ad6034a | ||
|
|
336a60ce32 | ||
|
|
e1f27958ca | ||
|
|
c969963b83 | ||
|
|
9f2ee5ad68 | ||
|
|
dfc8e6eb5f | ||
|
|
1037d4e125 | ||
|
|
307e2b7308 | ||
|
|
d39fbb9146 | ||
|
|
7fe5d8c0dd | ||
|
|
6df6f97937 | ||
|
|
06f2dd63c1 | ||
|
|
ca9492be00 | ||
|
|
41b5b68a41 | ||
|
|
9d7c8a0b91 | ||
|
|
5e3323c188 | ||
|
|
25504e0ed4 | ||
|
|
66160aed55 | ||
|
|
ec870d2d7a | ||
|
|
64c4eec59f | ||
|
|
a658b80aee | ||
|
|
5cc7da193c | ||
|
|
95574d60d5 | ||
|
|
712bc10af5 | ||
|
|
ef10d84e2f | ||
|
|
128d5a2035 | ||
|
|
7a99a2003e |
No files matched your search
@@ -0,0 +1,18 @@
|
||||
# Keep the build context small: what .gitignore ignores, and regenerated files.
|
||||
# Unlike .gitignore, patterns here only match at the top unless they start
|
||||
# with **/, so the ones that can appear in any folder do.
|
||||
.git/
|
||||
.worktrees/
|
||||
.venv/
|
||||
**/build/
|
||||
**/target/
|
||||
**/captures/
|
||||
**/__pycache__/
|
||||
**/*.pyc
|
||||
# Eye-camera frame dumps are biometric (see .gitignore): never in an image.
|
||||
**/*.raw
|
||||
**/*.pgm
|
||||
**/.env
|
||||
**/.env.*
|
||||
frametop-report-*.txt
|
||||
.frame-job.d/
|
||||
@@ -0,0 +1,100 @@
|
||||
# Build Frametop's release on Depot's arm64 runners (the Frame is aarch64): the image from
|
||||
# pack/Containerfile, the test gate inside it, then Frametop.zip (framedrop/build.sh), the
|
||||
# image with its installer: FrameDrop installs it from a PC, or you unpack it on the headset
|
||||
# and run Frametop/frametop-install.sh, or get.sh --release downloads it (pack/README.md,
|
||||
# Releases). It's about 1.1 GB, under GitHub's 2 GB a file.
|
||||
#
|
||||
# A v* tag makes a draft GitHub release with the zip, its FrameDrop manifest, its
|
||||
# frametop-release.json, and SHA256SUMS (a prerelease when the tag has a "-", like
|
||||
# v0.3.0-exp.1). Nothing is public until someone publishes the draft. A manual run keeps the
|
||||
# zip as the run's artifact for a week.
|
||||
#
|
||||
# podman, as on the Frame: the zip holds podman save's archive, which the headset loads with
|
||||
# podman. Not on pushes or pull requests: Depot's runners are paid, and a fork's pull request
|
||||
# would run on them. Actions are pinned to commit SHAs (the version in the comment).
|
||||
name: release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ["v*"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: write # the draft release
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.ref }}
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: depot-ubuntu-24.04-arm-4
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
FT_ENGINE: podman
|
||||
steps:
|
||||
# actions/checkout@v7.0.1
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
|
||||
|
||||
- name: version
|
||||
run: |
|
||||
if [ "$GITHUB_REF_TYPE" = tag ]; then v=${GITHUB_REF_NAME#v}; else v=0.0.0-ci.${GITHUB_SHA::7}; fi
|
||||
echo "VERSION=$v" >> "$GITHUB_ENV"
|
||||
echo "FT_IMAGE=localhost/frametop:$v" >> "$GITHUB_ENV"
|
||||
|
||||
- name: build the image
|
||||
run: ./ft dev build
|
||||
|
||||
# The unit gate: Python (strict), C, and shell, inside the image, so what passes here is
|
||||
# what the zip installs.
|
||||
- name: test (python, c, bash)
|
||||
run: ./ft dev test
|
||||
|
||||
- name: smoke (what a release installs from the image)
|
||||
run: |
|
||||
podman run --rm --entrypoint sh "$FT_IMAGE" -c '
|
||||
set -e
|
||||
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/pack/build/distrobox/install
|
||||
/src/frametop/gaze/tracker/build/venv/bin/python -c "import numpy, cv2"
|
||||
/src/frametop/voice/build/venv/bin/python -c "import numpy, sentencepiece, sherpa_onnx"
|
||||
python3 -c "import PySide6"'
|
||||
|
||||
# The FrameDrop manifest names the zip's URL in this repo's release (a fork's, in a fork).
|
||||
- name: Frametop.zip
|
||||
run: |
|
||||
url=()
|
||||
[ "$GITHUB_REF_TYPE" = tag ] &&
|
||||
url=("https://github.com/$GITHUB_REPOSITORY/releases/download/$GITHUB_REF_NAME/Frametop.zip")
|
||||
framedrop/build.sh --image "$FT_IMAGE" --version "$VERSION" --commit "$GITHUB_SHA" "${url[@]}"
|
||||
|
||||
- name: keep the zip (manual runs)
|
||||
if: github.ref_type != 'tag'
|
||||
# actions/upload-artifact@v7.0.2
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
|
||||
with:
|
||||
name: Frametop-${{ env.VERSION }}
|
||||
path: framedrop/build/
|
||||
retention-days: 7
|
||||
|
||||
- name: draft release (tags)
|
||||
if: github.ref_type == 'tag'
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
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 "$notes" --generate-notes \
|
||||
framedrop/build/Frametop.zip framedrop/build/frametop.framedrop.json \
|
||||
framedrop/build/frametop-release.json framedrop/build/SHA256SUMS
|
||||
@@ -0,0 +1 @@
|
||||
3.14
|
||||
@@ -25,14 +25,22 @@ scripts/frame.sh --host '<cmd>' # runs on the SteamOS host
|
||||
A Steam Frame is someone's personal headset, and they may be wearing it while you work.
|
||||
|
||||
- Don't kill or restart `gamescope`, `steam`, `vrserver`, `vrcompositor`, the gamescope session, or the Frametop desktop without asking. Each one ends or disrupts whatever is happening in VR.
|
||||
- Don't run host `sudo`, `steamos-readonly disable`, `steamos-devmode` changes, pacman installs, or reboots without explicit approval. Three installers need host `sudo`, and they ask for it: the Bluetooth fixes (`setup/bluetooth/install.sh`), hand tracking (`hands/run.sh install` and `caps`, which set ft-camd's file capabilities with `setcap`), and our own eye tracker's frame grabber (`gaze/tracker/install.sh`).
|
||||
- Write only inside the repo, `/tmp`, and the container unless told otherwise. The installers are the exception: they write the user services, launchers, and the SteamVR driver into the home folder. The Bluetooth fixes and the eye tracker's frame grabber also install root-owned files and system services under `/etc` (`/etc/steamframe`, `/etc/frametop`, `/etc/systemd/system`).
|
||||
- Don't run host `sudo`, `steamos-readonly disable`, `steamos-devmode` changes, pacman installs, or reboots without explicit approval. Three installers need host `sudo`, and they ask for it: the Bluetooth fixes (`setup/bluetooth/install.sh`), hand tracking (`hands/run.sh install` and `caps`, which set ft-camd's file capabilities with `setcap`, and `uninstall` and `uncaps`, which take them back), and our own eye tracker's frame grabber (`gaze/tracker/install.sh`).
|
||||
- Write only inside the repo, `/tmp`, and the container unless told otherwise. The installers are the exception: they write the user services, launchers, and the SteamVR driver into the home folder. The Bluetooth fixes and the eye tracker's frame grabber also install root-owned files and system services under `/etc` (`/etc/steamframe`, `/etc/frametop`, `/etc/systemd/system`). When an installer starts writing something new outside the repo, or sets file capabilities, add it to `uninstall.sh` too: users uninstall with that script, not with each installer's `uninstall`.
|
||||
- Never copy `.netrc`, SSH keys, or Steam config off the Frame or into this repo.
|
||||
|
||||
## SteamOS updates
|
||||
|
||||
A SteamOS update replaces SteamVR, KWin, and gamescope with the rest of the OS image. When a change starts depending on something from the image (a host file, an OpenVR interface outside the bundled header, an undocumented layout or output format, a SteamVR or KWin quirk), add a check for it to `scripts/update-check.py`, or a retest hint for its package there. [docs/design.md](docs/design.md) has the background.
|
||||
|
||||
## The image (`pack/`)
|
||||
|
||||
`pack/Containerfile` builds Frametop as an OCI image, the groundwork for installing without building on the headset; no installer uses it yet. [pack/design.md](pack/design.md) explains why and what is open, and [pack/README.md](pack/README.md) documents the specifics. Rules:
|
||||
|
||||
- **Pin every input.** Base images by digest, Python via `uv.lock` (commit the lock, never a bare `uv pip install`), downloads by tag or commit and sha256, CI actions by commit SHA.
|
||||
- **One build recipe.** The image runs the components' own `build.sh` scripts (`FRAME_IN_BOX=1`), and the OpenVR SDK they build against is pinned in `scripts/openvr.sh`. Change a build there, not in the Containerfile, and keep the Containerfile buildable on arm64, the only architecture the Frame has.
|
||||
- **Keep the tests green in the image.** `./ft dev test` runs `just test` inside it, and CI runs the same recipes. A new offline test that needs no headset goes in the `justfile` too.
|
||||
|
||||
## Names
|
||||
|
||||
User-facing names are "Frametop", "Frametop Display Settings", and "Frametop Input Settings". Programs and files use the `ft-` / `ft_` prefix (`ft-screens`, `ft-pointer`, `ft-layout`, the `ft_pointer` driver); config, units, and overlay keys use `frametop`. Program names must stay within 15 characters: Linux truncates process names there, and the scripts find programs with `pgrep -x` / `pkill -x`.
|
||||
@@ -4,6 +4,7 @@ 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.
|
||||
- **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.
|
||||
@@ -13,11 +14,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,14 +29,16 @@ 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.
|
||||
|
||||
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.
|
||||
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 five things along the way: whether to install voice dictation (yes by default; it downloads about 320 MB of speech models), gaze mode (experimental, yes by default), our own eye tracker for it (yes by default), and the Bluetooth fixes, then whether to restart SteamVR. The eye tracker and the Bluetooth fixes need your `sudo` password; if you've never set one, run `passwd` first, or skip them for now. SteamVR has to restart once at the end, which closes everything open in VR, including the terminal. Rebooting the headset works too.
|
||||
|
||||
After the restart, Launch a program → Desktop opens the multi-screen desktop, with its screens arranged around where you're facing. Frametop Display Settings and Frametop Input Settings are in the desktop's application menu, under Settings. SteamOS's own single-screen desktop is still there, as Native Desktop in the same list.
|
||||
|
||||
If you work in the desktop for long stretches, or leave the headset on a stand, open Frametop Display Settings → Power. Turn on Stay awake while plugged in: by default Steam puts the Frame to sleep after an hour without input, even while it charges. And choose when the displays turn off while the headset isn't used. SteamVR turns them off a few seconds after you take the headset off, but a stand or mount that covers the proximity sensor inside it makes the headset seem worn, and its displays stay on all night.
|
||||
|
||||
@@ -49,7 +54,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 +63,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 +102,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.
|
||||
@@ -133,7 +155,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,37 +179,40 @@ In a terminal on the headset, run:
|
||||
cd ~/frametop && scripts/report.sh
|
||||
```
|
||||
|
||||
This writes `frametop-report-<date>.txt` with version numbers, service states, settings, and recent logs. Bluetooth addresses and the headset's serial number are masked. Then [open an issue](https://github.com/DeeJanuz/frametop/issues), describe what you did, what you expected, and what happened, and attach the file. 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, service states, settings, Frametop's keyboard and the Steam menu, and recent logs. Bluetooth addresses and the headset's serial number are masked.
|
||||
|
||||
If the problem is something you can make happen, like a window that won't drag or a keyboard that doesn't open, run `scripts/report.sh --watch` instead. After the usual report it records for 60 seconds (`--watch 120` for longer) while you make it happen in the headset. It notes 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. 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/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`.
|
||||
|
||||
## Uninstall
|
||||
|
||||
In a terminal on the headset, run:
|
||||
|
||||
```
|
||||
./desktops.sh uninstall # the launcher's Desktop entry goes back to the stock desktop
|
||||
./desktops.sh relay uninstall
|
||||
pointer/helper/run.sh uninstall
|
||||
power/run.sh uninstall
|
||||
pointer/driver/install.sh uninstall # then restart SteamVR
|
||||
input-settings/install.sh uninstall
|
||||
display-settings/install.sh uninstall
|
||||
remote/install.sh uninstall
|
||||
setup/bluetooth/install.sh uninstall # if you installed the Bluetooth fixes
|
||||
hands/run.sh uninstall # if you installed hand tracking by hand
|
||||
gaze/run.sh uninstall # if you installed the gaze service
|
||||
gaze/tracker/install.sh uninstall # if you installed our own eye tracker's frame grabber
|
||||
gaze/probe/install.sh uninstall # if you installed the gaze probe
|
||||
curl -fsSL https://frametop.github.io/frametop/uninstall.sh | bash
|
||||
```
|
||||
|
||||
Your settings stay: `~/.config/frametop.conf`, `frametop-input.json` (button maps and key combinations), `frametop-layout.json` (the layout and profiles), `frametop-float.json`, and `frametop-remote/` in `~/.config`, and the gaze calibration in `~/.local/state/frametop/gaze`. So does the desktop's own Plasma setup, in `~/.config/frametop`. Delete them too for a clean slate.
|
||||
It works in two steps, so it never takes away the keyboard, mouse, or desktop you're using while it runs:
|
||||
|
||||
1. It stops Frametop from starting. Launch a program → Desktop opens the stock desktop again, and the Native Desktop entry, Frametop's services, its SteamVR driver, and its menu entries are removed, along with the system files of our eye tracker and the Bluetooth fixes and the file capabilities of hand tracking's camera broker (those need your `sudo` password). Everything running now keeps running until you restart the headset, and it offers to restart it for you.
|
||||
2. After the restart, run the same command again. It deletes the code in `~/frametop`, and asks whether to delete your settings, any eye or hand recordings, and the build container (1–2 GB) too.
|
||||
|
||||
To see what it would do without changing anything, add `-s -- --dry-run` after `bash`. If the code isn't in `~/frametop`, add `-s -- --dir <folder>`. From the repo, the same script is `./uninstall.sh`.
|
||||
|
||||
Don't delete `~/frametop` by hand before you uninstall and restart: the desktop and the input relay run from it, and without it Launch a program → Desktop no longer opens anything. If you've already deleted it, the command above still works, since it doesn't need the repo.
|
||||
|
||||
Unless you ask for them to go, your settings stay: `~/.config/frametop.conf`, `frametop-input.json` (button maps and key combinations), `frametop-layout.json` (the layout and profiles), `frametop-float.json`, and `frametop-remote/` in `~/.config`, the gaze calibration in `~/.local/state/frametop`, and the desktop's own Plasma setup in `~/.config/frametop`. A later install picks them up again.
|
||||
|
||||
## How it works
|
||||
|
||||
@@ -195,8 +220,9 @@ 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. |
|
||||
| `screens/` | ft-screens, the compositor (wlroots and OpenVR). |
|
||||
| `session/` | The desktop session script and its config example. |
|
||||
@@ -206,13 +232,21 @@ 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). |
|
||||
| `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. |
|
||||
|
||||
## Packaging
|
||||
|
||||
`pack/` builds Frametop as an OCI image: the toolchain, the native binaries, and the locked Python environment (via [uv](https://docs.astral.sh/uv/)), built and tested by GitHub Actions. It is the groundwork for installing Frametop without building anything on the headset. No installer uses it yet. For development, `./ft dev build` builds the image and `./ft dev test` runs the tests inside it. [pack/design.md](pack/design.md) explains why an image and what is still open, and [pack/README.md](pack/README.md) documents the image itself.
|
||||
|
||||
## Developing from a PC
|
||||
|
||||
The scripts also work from a Linux or WSL PC over SSH, which is easier for editing code. On the Frame they use the local checkout; on a PC they sync the repo to `~/dev/frametop` on the Frame and run there.
|
||||
@@ -250,4 +284,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.
|
||||
+13
-2
@@ -1,7 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
# Start, stop, or inspect the multi-screen Plasma desktop in VR on the Frame.
|
||||
# Usage: desktops.sh start [screens] | stop | restart | status | log [lines]
|
||||
# desktops.sh install # make the VR launcher's "Desktop" entry start Frametop
|
||||
# desktops.sh install # make the VR launcher's "Desktop" entry start Frametop, and add
|
||||
# # "Native Desktop" for the stock SteamOS desktop
|
||||
# desktops.sh uninstall # give the launcher back the stock SteamOS desktop
|
||||
# desktops.sh screens N # set the default screen count in ~/.config/frametop.conf
|
||||
# desktops.sh remote on|off|info # VNC access over the tailnet (applies on next start)
|
||||
@@ -16,6 +17,8 @@ action=${1:-start}
|
||||
screens=${2:-${FT_SCREENS:-}}
|
||||
session=$FRAME_REPO/session
|
||||
override=.local/share/applications/deckard-nested-desktop.desktop
|
||||
native_copy=.local/share/applications/native-deckard-nested-desktop.desktop
|
||||
stock=/usr/share/applications/deckard-nested-desktop.desktop
|
||||
log=/tmp/frametop-session.log
|
||||
# Bracketed first letter so pgrep/pkill never match the ssh shell running them.
|
||||
match='[v]r-overlay-key frametop '
|
||||
@@ -35,15 +38,23 @@ systemd-run --user --collect --quiet --unit frametop-desktop \
|
||||
sleep 12; echo \"plasmashell processes: \$(pgrep -c plasmashell)\"
|
||||
$running && echo 'started' || { echo 'failed:'; tail -20 $log; exit 1; }" ;;
|
||||
install)
|
||||
# Also "Native Desktop", a copy of SteamOS's entry for its own desktop. Optional, so a SteamOS
|
||||
# without the stock entry still installs. No X-Steam-Special, so Steam can only single out ours.
|
||||
"$root/scripts/sync.sh" >/dev/null
|
||||
"$frame" --host "set -e; mkdir -p ~/.local/share/applications
|
||||
sed 's|@SESSION@|$session/frametop-session.sh|' $session/deckard-nested-desktop.desktop > ~/$override
|
||||
if [ -r $stock ]; then
|
||||
sed -e 's/^Name=.*/Name=Native Desktop/' -e '/^Name\\[/d' -e '/^X-Steam-Special=/d' -e '/pick this out/d' \\
|
||||
$stock > ~/$native_copy.new && mv ~/$native_copy.new ~/$native_copy
|
||||
else
|
||||
rm -f ~/$native_copy; echo 'no $stock: no Native Desktop entry' >&2
|
||||
fi
|
||||
[ -f ~/.config/frametop.conf ] || cp $session/frametop.conf.example ~/.config/frametop.conf
|
||||
echo \"installed ~/$override\"; grep ^Exec= ~/$override; echo; cat ~/.config/frametop.conf" ;;
|
||||
uninstall)
|
||||
# Also what the session puts in place at each start: Launch as Standalone's app copies and
|
||||
# the title bar decoration (float/ft_apps.py, decoration/).
|
||||
"$frame" --host "rm -f ~/$override
|
||||
"$frame" --host "rm -f ~/$override ~/$native_copy
|
||||
rm -rf ~/.local/share/frametop/apps ~/.local/share/kwin/decorations/kwin4_decoration_qml_frametop
|
||||
rmdir ~/.local/share/frametop 2>/dev/null; echo 'removed; the launcher uses the stock desktop again'" ;;
|
||||
screens)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/bin/bash
|
||||
# Launch Frametop Display Settings from a Plasma session on the Frame host.
|
||||
# The app runs in the dev container (PySide6 and Kirigami come from Fedora there).
|
||||
# The app runs in Frametop's container (PySide6 and Kirigami 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.
|
||||
@@ -10,8 +10,7 @@ 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
|
||||
"$here/../scripts/container-up.sh"
|
||||
exec "$HOME/.local/bin/distrobox" enter dev -- env WAYLAND_DISPLAY="$wl" DISPLAY="${DISPLAY:-}" \
|
||||
exec "$here/../scripts/in-box" env WAYLAND_DISPLAY="$wl" DISPLAY="${DISPLAY:-}" \
|
||||
XAUTHORITY="${XAUTHORITY:-}" DBUS_SESSION_BUS_ADDRESS="$session_bus" \
|
||||
QT_QPA_PLATFORM="wayland;xcb" \
|
||||
python3 "$here/ft_display_settings.py" "$@"
|
||||
@@ -10,12 +10,15 @@ 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
|
||||
desktop starts.
|
||||
- Remote displays (other computers' monitors as screens) have their own app, Frametop
|
||||
Remote Displays (remote-displays/); a button opens it.
|
||||
- Power: how long the headset can go unused before ft-powerd turns its displays off
|
||||
(DISPLAY_OFF_MIN; the service's state comes from its control socket, @ft_powerd),
|
||||
and whether the Frame stays awake while plugged in, which is Steam's own setting
|
||||
@@ -54,11 +57,14 @@ SCREEN_RESOLUTIONS = [(1920, 1080, ""), (2560, 1440, ""), (3840, 2160, "4K"), (2
|
||||
(2560, 1600, "16:10"), (1080, 1920, "portrait"), (1440, 2560, "portrait"),
|
||||
(2160, 3840, "portrait 4K")]
|
||||
FT_SCREENS = "\0ft_screens"
|
||||
REMOTE_DISPLAYS = os.path.join(HERE, "..", "remote-displays", "ft_remote_displays.py")
|
||||
FT_POWERD = "\0ft_powerd"
|
||||
# Steam's default for "When Plugged In and Idle -> Sleep after", to go back to when
|
||||
# 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)")]
|
||||
|
||||
|
||||
@@ -118,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()
|
||||
@@ -130,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
|
||||
@@ -139,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()
|
||||
|
||||
@@ -156,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:
|
||||
@@ -380,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):
|
||||
@@ -658,6 +706,13 @@ class Backend(QObject):
|
||||
def capture(self):
|
||||
self._run("Saving the current arrangement", "capture")
|
||||
|
||||
# --- remote displays: their own app ---
|
||||
@Slot()
|
||||
def openRemoteDisplays(self):
|
||||
"""Frametop Remote Displays (we're in the dev container already, as it runs)."""
|
||||
if not QProcess.startDetached(sys.executable, [os.path.abspath(REMOTE_DISPLAYS)]):
|
||||
self.message.emit("Couldn't start Frametop Remote Displays", True)
|
||||
|
||||
# --- ft-layout on the host ---
|
||||
def _run(self, label, *args):
|
||||
if self._proc is not None:
|
||||
|
||||
@@ -180,6 +180,13 @@ Kirigami.ApplicationWindow {
|
||||
icon.name: "view-visible"
|
||||
onTriggered: backend.toggleScreens()
|
||||
},
|
||||
Kirigami.Action {
|
||||
visible: spage.md
|
||||
text: "Remote displays"
|
||||
icon.name: "network-workgroup"
|
||||
tooltip: "Other computers' monitors as screens: Frametop Remote Displays"
|
||||
onTriggered: backend.openRemoteDisplays()
|
||||
},
|
||||
Kirigami.Action {
|
||||
visible: backend.desktopRunning
|
||||
text: "Restart desktop"
|
||||
@@ -951,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()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+43
-10
@@ -42,6 +42,8 @@ Wherever ft-screens needs to know where a laser points (showing the controls, th
|
||||
|
||||
`ComputeOverlayIntersection` ignores `SetOverlayIntersectionMask`, and a control can't be allowed to cover part of its screen, so the resize tab sits entirely outside the corner.
|
||||
|
||||
What SteamVR hits isn't the texture's shape but the mouse scale's: an overlay is as tall, for SteamVR's laser and `ComputeOverlayIntersection`, as its width times the mouse scale's height over its width, and the default scale is 1 × 1. With it, the grab bar (a 256 × 24 texture) took hits in a square as tall as the bar is wide, so it caught clicks meant for the bottom tenth or so of the screen above it. Measured with a 0.2 m wide 256 × 24 overlay: a hit area 199 mm tall at the default scale, 18 mm at 256 × 24 (the bar itself is 18.8 mm), and no change from an intersection mask. `MakeChrome` sets each control's mouse scale to its texture size.
|
||||
|
||||
### Pinning
|
||||
|
||||
Pinning started as "bring the screen to your wrist", which doesn't work for big screens, because their centre is far from the edge you bring close. It became aiming: while a screen is carried, the line from the carrying device to its bar is tested against the other hand controllers. Crossing a controller's 6 cm ring arms the pin (leaving past 9 cm, so it doesn't flicker), and crossing it again disarms it. The pin happens on release, with the screen's pose at that moment, so you can arm it and then turn the screen. An earlier version pinned the moment the laser touched the wrist, which left the screen at whatever angle the carrying hand had while pointing there.
|
||||
@@ -72,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.
|
||||
@@ -85,12 +87,13 @@ In a game, Frametop's panels work like SteamVR's own floating windows: point a c
|
||||
|
||||
### The KWin script
|
||||
|
||||
The KWin side is a script (`float/frametop-float.js`), not a C++ effect, because a script keeps working across KWin updates and an effect would have to match the host's exact KWin build. KWin scripts can call D-Bus but can't serve it, so ft-floatd's commands come back through a long poll: the script calls `NextCommand`, which answers when a command is ready, or empty after 20 seconds, under KWin's 25-second D-Bus timeout. A few things about KWin's script engine:
|
||||
The KWin side is a script (`float/frametop-float.js`), not a C++ effect, because a script keeps working across KWin updates and an effect would have to match the host's exact KWin build. KWin scripts can call D-Bus but can't serve it, so ft-floatd's commands come back through a long poll: the script calls `NextCommand`, which answers when a command is ready, or empty after 20 seconds, under KWin's 25-second D-Bus timeout. If no reply comes within 30 seconds, a watchdog calls again, and waits twice as long each time until a reply comes (up to 5 minutes). The 30 seconds have to stay above KWin's timeout, or a late reply would start a second poll. A few things about KWin's script engine:
|
||||
|
||||
- `windowAdded` reports popups as windows of their own (`popupWindow` true, `transient` true) with their geometry.
|
||||
- Setting `frameGeometry` applies asynchronously: the app has to answer the new size first.
|
||||
- A script can't read a window's maximize mode, so the script counts a window as maximized when it fills its output's maximize area.
|
||||
- `globalThis` isn't defined. `print` goes to the journal unless `QT_FORCE_STDERR_LOGGING=1`.
|
||||
- `callDBus` never calls back when a call fails (an error reply, the name gone from the bus, or the 25-second timeout). KWin only logs `Received D-Bus message is error`, so a script that waits for the callback waits forever.
|
||||
|
||||
The title bar's float button is Frametop's own window decoration (`decoration/`), written in QML for KWin's Aurorae engine, which loads it without compiling. A C++ fork of Breeze would have to match SteamOS's exact KDecoration build. A decoration can only make the window requests KWin offers it, so the button toggles keep-below, which has no visible effect on a window alone on its own output, and the script treats keep-below as the floating flag.
|
||||
|
||||
@@ -114,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
|
||||
|
||||
@@ -133,7 +142,7 @@ A few overlays need special handling:
|
||||
|
||||
Head follow is experimental and off by default. It works, but it's only lightly tested, and the feel is mostly a matter of its settings; polishing it is left open. With it on (`POINTER_FOLLOW=1`, or a mouse button mapped to Head follow on/off), the cursor rides on a reference direction, where you were facing when your head last settled, and keeps its offset from it. The mouse can put the cursor anywhere up to `POINTER_FOLLOW_REACH` (70 degrees) from the reference, a corner of your view included. While your head stays within `POINTER_LEASH_DEG` of the reference, nothing moves on its own. Once your head has been past the leash for `POINTER_LEASH_DELAY` (0.2 s, so a glance out and back doesn't count), the reference eases to where you're facing (time constant `POINTER_LEASH_RETURN`, 0.2 s), never falling further behind than the leash, and the cursor ends up back where it was in your view. Then it waits for the leash again. Two earlier versions didn't work out. Moving the reference only while your head pulled at the end of the leash left it up to the leash off after you turned back, and getting it centred again meant overshooting with your head. Easing it toward your facing all the time moved the cursor on every small head movement. A leash of 0 makes the reference your facing direction, so the cursor is locked to your view, and mouse movement shifts it within the view. Head roll is ignored, so tilting your head doesn't swing the cursor around. While the left button is held the cursor stays put in the room, so your head can't nudge a click or a drag. When you let go, it carries on from where it is instead of jumping.
|
||||
|
||||
Gaze mode is experimental and off by default (`POINTER_GAZE=1`, the Gaze page of Frametop Input Settings, `gaze/ft-gazectl on`, or a mouse button or key combination mapped to Gaze pointer on/off). It's MAGIC pointing (Zhai, Morimoto and Ihde, 1999): the pointer goes where you look, and the mouse does the last bit. The gaze service (`gaze/ft-gazed`) sends the helper the corrected gaze at 90 Hz (from one eye while the tracker has lost the other), and while the gaze has the pointer, the cursor ray is that gaze from the eye. The pointer is aimed at the gaze each frame, not steered toward it, so nothing can pile up. An earlier try in the gaze probe steered the pointer with relative moves, and lost it when the pointer went idle or a controller had the laser. By default (`POINTER_GAZE_MOUSE_MOVE=held`, the Gaze page's Mouse movement switch) moving the mouse does nothing while the gaze has the pointer: it moves the pointer only while a button is held, as a correction. A bumped or drifting mouse can't pull the pointer off what you're looking at, and every mouse move is a correction, so the lessons aren't polluted by mouse moves to somewhere else (they used to be kept out by an 8 degree limit, which also dropped real corrections when the tracker was further off). With the gaze stale for a second, in a game, or with the headset off, the mouse moves the pointer as usual; with `free`, moving the mouse takes the pointer from the gaze. A left press while the gaze has the pointer isn't sent at once: the pointer stops where the gaze put it, you drag it onto what you meant with the button still down (panels only see it hover), and the release clicks there. Clicking at once clicked wherever the gaze was, often the wrong thing, before you could correct it. The drag is the correction. Snapping the pointer onto buttons and links is deferred: it needs accessibility (AT-SPI) on in the Frametop session, where it's off (no registry runs), plus app restarts, and it makes Chromium and Electron apps use more CPU. A press held still for `POINTER_GAZE_HOLD` (0.5 s) becomes a real press, so drags still work: hold, then move. The right button works the same way, with the right click on the release, and pressing it while the left press is held back starts a drag where the pointer is, like Meta+J then Meta+K. That drag lasts while either button (or key) is held, so a second right press, or a second Meta+K, is free to pan and tilt the panel being dragged; with the keyboard, the head turns it. Outside games the pointer then stays: the mouse going idle doesn't release it. A moving controller still releases it, as without gaze. Gaze mode is a mouse and keyboard feature: Steam reads the Frame controllers itself, outside SteamVR's bindings, so controller clicks at the gaze kept knocking SteamVR out of laser mode (see `docs/gaze-controllers.md`). Keyboard clicks (Meta+J, Meta+K) hold the dot still in your view while the keys are down, so the head, not the mouse, does the last bit; a quick tap clicks where the dot was at the press, since the head moves as you hit the keys. The relay hides Meta from the desktop as soon as such a combination fires, because KWin takes Meta with a mouse button as a window move or resize, which swallowed the clicks. The dot shows all the time by default. With `POINTER_GAZE_DOT=moving` it shows only while the mouse moves it (`POINTER_GAZE_SHOW`), while a press is held, and as a pulse for each click; otherwise it's transparent, so the laser still lands on it. Looking more than `POINTER_GAZE_RETAKE` (5 degrees) away from it, with the mouse still, gives it back, so small eye movements around the pointer don't pull it off what you're doing. A mouse nudge before a click whose correction is within `POINTER_GAZE_NUDGE_MAX` (55 degrees, half of what the headset shows across) is sent to the gaze service as a lesson: you were looking at where you clicked when the mouse took over, so the nudge is the eye tracker's error there. Using it is what calibrates it. A one-dot check in a panel fixed to the headset tops that up when the headset goes on, when our tracker thinks it moved, and when a correction is past that limit (the tracker is far off, so a click there isn't trusted as a lesson), and the full calibration and the headset fit check run in the same panel, so everything a user does to calibrate happens in one place in the headset; the gaze probe, a fullscreen GTK app, is the development tool. The limit was 8 degrees, which dropped every correction while our tracker was 12 off. Its dots sit at known directions from the headset, so the panel needs no screen geometry. The quick check's dot takes the gaze once it has held still, so what the tracker says doesn't have to be close for the capture to work. The full calibration's and the five-dot check's dots wait for a click while you look at the dot (a left click or Meta+J), because a steady gaze isn't always on the dot, and take the gaze held still up to the click; a right click or MetLine truncated
|
||||
Gaze mode is experimental and off by default (`POINTER_GAZE=1`, the Gaze page of Frametop Input Settings, `gaze/ft-gazectl on`, or a mouse button or key combination mapped to Gaze pointer on/off). It's MAGIC pointing (Zhai, Morimoto and Ihde, 1999): the pointer goes where you look, and the mouse does the last bit. The gaze service (`gaze/ft-gazed`) sends the helper the corrected gaze at 90 Hz (from one eye while the tracker has lost the other), and while the gaze has the pointer, the cursor ray is that gaze from the eye. The pointer is aimed at the gaze each frame, not steered toward it, so nothing can pile up. An earlier try in the gaze probe steered the pointer with relative moves, and lost it when the pointer went idle or a controller had the laser. By default (`POINTER_GAZE_MOUSE_MOVE=held`, the Gaze page's Mouse movement switch) moving the mouse does nothing while the gaze has the pointer: it moves the pointer only while a button is held, as a correction. A bumped or drifting mouse can't pull the pointer off what you're looking at, and every mouse move is a correction, so the lessons aren't polluted by mouse moves to somewhere else (they used to be kept out by an 8 degree limit, which also dropped real corrections when the tracker was further off). With the gaze stale for a second, in a game, or with the headset off, the mouse moves the pointer as usual; with `free`, moving the mouse takes the pointer from the gaze. A left press while the gaze has the pointer isn't sent at once: the pointer stops where the gaze put it, you drag it onto what you meant with the button still down (panels only see it hover), and the release clicks there. Clicking at once clicked wherever the gaze was, often the wrong thing, before you could correct it. The drag is the correction. Snapping the pointer onto buttons and links is deferred: the session now starts an AT-SPI registry, but apps still need to expose useful accessibility trees (and may need restarting), and it makes Chromium and Electron apps use more CPU. A press held still for `POINTER_GAZE_HOLD` (0.5 s) becomes a real press, so drags still work: hold, then move. The right button works the same way, with the right click on the release, and pressing it while the left press is held back starts a drag where the pointer is, like Meta+J then Meta+K. That drag lasts while either button (or key) is held, so a second right press, or a second Meta+K, is free to pan and tilt the panel being dragged; with the keyboard, the head turns it. Outside games the pointer then stays: the mouse going idle doesn't release it. A moving controller still releases it, as without gaze. Gaze mode is a mouse and keyboard feature: Steam reads the Frame controllers itself, outside SteamVR's bindings, so controller clicks at the gaze kept knocking SteamVR out of laser mode (see `docs/gaze-controllers.md`). Keyboard clicks (Meta+J, Meta+K) hold the dot still in your view while the keys are down, so the head, not the mouse, does the last bit; a quick tap clicks where the dot was at the press, since the head moves as you hit the keys. The relay hides Meta from the desktop as soon as such a combination fires, because KWin takes Meta with a mouse button as a window move or resize, which swallowed the clicks. The dot shows all the time by default. With `POINTER_GAZE_DOT=moving` it shows only while the mouse moves it (`POINTER_GAZE_SHOW`), while a press is held, and as a pulse for each click; otherwise it's transparent, so the laser still lands on it. Looking more than `POINTER_GAZE_RETAKE` (5 degrees) away from it, with the mouse still, gives it back, so small eye movements around the pointer don't pull it off what you're doing. A mouse nudge before a click whose correction is within `POINTER_GAZE_NUDGE_MAX` (55 degrees, half of what the headset shows across) is sent to the gaze service as a lesson: you were looking at where you clicked when the mouse took over, so the nudge is the eye tracker's error there. Using it is what calibrates it. A one-dot check in a panel fixed to the headset tops that up when the headset goes on, when our tracker thinks it moved, and when a correction is past that limit (the tracker is far off, so a click there isn't trusted as a lesson), and the full calibration and the headset fit check run in the same panel, so everything a user does to calibrate happens in one place in the headset; the gaze probe, a fullscreen GTK app, is the development tool. The limit was 8 degrees, which dropped every correction while our tracker was 12 off. Its dots sit at known directions from the headset, so the panel needs no screen geometry. The quick check's dot takes the gaze once it has held still, so what the tracker says doesn't have to be close for the capture to work. The full calibration's and the five-dot check's dots wait for a click while you look at the dot (a left click or Meta+J), because a steady gaze isn't always on the dot, and take the gaze held still up to the click; a rightLine truncated
|
||||
|
||||
Replacing a loaded driver's files, as re-running the installer used to do, leaves SteamVR honoring the virtual controller's hand role but not its laser claim: the dashboard pointer stays unassigned until SteamVR restarts. The driver installer now leaves an unchanged driver in place.
|
||||
|
||||
@@ -157,22 +166,46 @@ 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.
|
||||
|
||||
Volume keys must never reach gamescope. With the openvr backend, gamescope sends volume up and down to Steam by moving keyboard focus to Steam for the key and then back to the previously focused surface. When nothing had focus, the one it moves back to is null, and wlroots aborts on a null focus surface (`wlr_seat_keyboard_notify_enter: Assertion 'surface' failed`), which ends the whole VR session. Keyboard focus is often empty while you work in VR, so one press of the headset's volume button could take everything down. gamescope reads the headset's buttons and every keyboard itself (`InputStealer`), as do SteamVR's processes, so the relay has to stop volume keys at the device. Grabbing `gpio-keys` would also take the headset's click button, so the relay remaps the volume entries in each device's keymap (`EVIOCSKEYCODE`) and handles the stand-in codes itself. That fix covers every device at once, including keyboards that aren't grabbed.
|
||||
|
||||
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.
|
||||
|
||||
## The desktop session
|
||||
|
||||
The session is modeled on SteamOS's `steamos-nested-desktop` and runs beside it. It has its own runtime directory, config (`~/.config/frametop`), and state, so it never disturbs the stock desktop's layout or panels. It runs on a private D-Bus from `dbus-run-session`, which has two consequences. KDE only launches apps in systemd scopes when systemd is on the session bus, so everything started in the desktop lands in its systemd unit, and stopping the unit would kill all of it; `session/keep-apps.sh` moves those programs out first. And tools that need the real user bus, like podman and `distrobox-host-exec`, have to be pointed at it explicitly.
|
||||
The session is modeled on SteamOS's `steamos-nested-desktop` and runs beside it. It has its own runtime directory, config (`~/.config/frametop`), and state, so it never disturbs the stock desktop's layout or panels. It runs on a private D-Bus from `dbus-run-session`, which has two consequences. KDE only launches apps in systemd scopes when systemd is on the session bus, so everything started in the desktop lands in its systemd unit, and stopping the unit would kill all of it; `session/keep-apps.sh` moves those programs out first. And tools that need the real user bus, like podman and `distrobox-host-exec`, have to be pointed at it explicitly. Its own config folder also hides SteamVR's path registry (`~/.config/openvr/openvrpaths.vrpath`) from everything started in it: OpenVR programs there fail with `VRInitError_Init_PathRegistryNotFound`, and `vrpathreg adddriver` writes a new registry under `~/.config/frametop/openvr` that has no SteamVR in it and that SteamVR never reads. So Frametop's scripts run SteamVR's tools with `XDG_CONFIG_HOME=~/.config`.
|
||||
|
||||
The VR launcher starts the session from the Steam client, and the client's environment came along: `LD_LIBRARY_PATH` pointing at Steam's own runtime, whose `libavcodec` has no H.264 decoder, so VLC in the desktop couldn't play most videos, plus the client's overlay and launch settings. The session script drops the client's variables before it starts anything. SteamOS's global Mesa settings (`/usr/share/deckard/mesavars.sh`) stay, and the gamescope session's Vulkan layer (`ENABLE_GAMESCOPE_WSI`) is only kept for the gamescope backend.
|
||||
|
||||
### Nested accessibility
|
||||
|
||||
The session drops an inherited `AT_SPI_BUS_ADDRESS`, so apps cannot accidentally use the host desktop's registry. It autostarts `session/ft-atspi` in Plasma phase 2, after KWin has set the nested display environment. The helper gets the live accessibility address from `org.a11y.Bus` on the private session bus, preserves any existing registry owner, updates the accessibility bus's activation environment, and tries `StartServiceByName` first.
|
||||
|
||||
On SteamOS 0.3.0 with at-spi2-core 2.52.0, the native launcher can choose dbus-broker because its process belongs to a systemd user unit. Registry activation then fails: this desktop's private session bus does not have a systemd activation manager. In that case the helper starts only `at-spi2-registryd` on the already-existing accessibility bus. The registry refuses duplicate ownership. Unlike native activation's `--use-gnome-session`, the fallback does not try to register with GNOME's session manager; that flag did not explain the observed native activation failure.
|
||||
|
||||
The fallback registry does not exit merely when its bus disconnects in the isolated SteamOS test. Its small watcher checks both private buses every 5 seconds, and terminates and reaps only the child it started when either bus disappears or the watcher is stopped. Each check runs `gdbus` twice; once a second, that cost about 1% of a core. `keep-apps.sh` keeps the watcher in the desktop unit when `desktops.sh start` runs the desktop as `frametop-desktop`. Started from the VR launcher, the desktop runs in steam.service, which doesn't stop with it, so there the watcher is the only thing that stops the registry. There is no second accessibility bus, global systemd environment update, process-name kill, or host registry replacement. Missing accessibility files or bus errors are nonfatal; the desktop still starts. Toolkit-specific accessibility opt-ins and pointer snapping are separate work.
|
||||
|
||||
Run the isolated checks on the host with `/usr/bin/python3 session/test/test_accessibility.py`. They use private D-Bus buses, Xvfb and a GTK3 app, never the production display or input. Native activation uses a small `org.a11y.Bus` test provider pointing to a real private dbus-daemon with the installed registry service; the SteamOS fallback uses the installed bus launcher and broker. The tests check real app-tree discovery, existing owners, concurrent starts, session stop/restart, and teardown. They require test-only PyGObject (Gio and GTK3), Xvfb, and at-spi2-core; the runtime helper uses Python's standard library and the existing host `gdbus`. Actual Plasma autostart and VR desktop restart still require an approved hardware test.
|
||||
|
||||
### 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.
|
||||
|
||||
Flatpak apps need `XDG_DATA_DIRS` to include Flatpak's exports, or Plasma opens Discover instead of launching them, so the session sources `/etc/profile.d/flatpak.sh`.
|
||||
@@ -183,9 +216,9 @@ 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. The file is backed up to `<file>.ft-bak` first. Plasma's scripting can't do this while it runs (`panel.screen` is read-only in 6.2.5), so a lost taskbar comes back at the desktop's next start. `scripts/doctor.sh` and `scripts/report.sh` list the panels and their screens.
|
||||
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.
|
||||
|
||||
Remote desktop is a chain (krdp, then FreeRDP inside Xvnc) because nothing on SteamOS serves KWin over VNC directly. Kept connected all the time, it cost about a core with nobody watching: krdpserver 55 to 78% (it encodes H.264 in software with openh264: VA-API finds no driver for the Frame's GPU in the container), FreeRDP 16 to 27%, Xvnc 6 to 11%, and the bridge's layout check every 5 seconds another 4%. krdp creates its screencast session per RDP connection and drops it when the connection closes (`SessionController::onNewConnection` in krdp 6.7), so an idle krdpserver costs nothing and can stay up; only the RDP connection has to go. The bridge connects FreeRDP when a VNC client appears and disconnects 45 seconds after the last one leaves. Xvnc has no hook for its clients, so the bridge counts established connections to its port with `ss`, woken early by Xvnc's log output; looking with `ss` once a second cost about 0.9% of a core in bash, against about 0.1% this way. `Xvnc -inetd` from a systemd socket would start a server per connection and lose sharing between viewers. The layout check (`ft-layout remote-view`, which scans `/proc` for plasmashell and runs `kscreen-doctor -j`) now runs only while FreeRDP runs, and then only after `kwinoutputconfig.json` or `frametop-layout.json` changes, with one check a minute in case a change touched neither.
|
||||
|
||||
@@ -214,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 sample timestamp is still at the offset ft-gaze reads, 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
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -85,7 +85,7 @@ ft-screens creates a `screen` for each toplevel in the order they appear, and in
|
||||
runs commands ◀─ long poll ─ spare outputs (kscreen-doctor) ◀─ @frametop_float ─ lasers, catcher
|
||||
```
|
||||
|
||||
- **KWin script `frametop-float`** (`float/frametop-float.js`). ft-floatd loads it into the desktop's KWin over D-Bus (`org.kde.kwin.Scripting`). A script keeps working across KWin updates. A C++ effect would have to match the host's exact KWin build, and the build container is Fedora, not SteamOS. The script watches windows (`windowAdded`/`windowRemoved`, `frameGeometryChanged`, `outputChanged`, `interactiveMoveResizeStarted`/`Finished`, `fullScreenChanged`, `maximizedChanged`, `minimizedChanged`, `keepBelowChanged`, `windowActivated`) and the outputs (`screensChanged`). It runs commands: move a window to an output, set its geometry, put it on all virtual desktops, and restore it. It adds "Float in VR" ("Back to Desktop" on a floating window) to the window menu (`registerUserActionsMenu`). It registers no shortcut: the float key belongs to the input relay. KWin scripts can call D-Bus but can't serve it, so commands come back through a long poll. The script calls ft-floatd's `NextCommand`, which answers when a command is ready, and then the script calls it again. It also keeps KWin's placement memory from moving windows (see design.md).
|
||||
- **KWin script `frametop-float`** (`float/frametop-float.js`). ft-floatd loads it into the desktop's KWin over D-Bus (`org.kde.kwin.Scripting`). A script keeps working across KWin updates. A C++ effect would have to match the host's exact KWin build, and the build container is Fedora, not SteamOS. The script watches windows (`windowAdded`/`windowRemoved`, `frameGeometryChanged`, `outputChanged`, `interactiveMoveResizeStarted`/`Finished`, `fullScreenChanged`, `maximizedChanged`, `minimizedChanged`, `keepBelowChanged`, `windowActivated`) and the outputs (`screensChanged`). It runs commands: move a window to an output, set its geometry, put it on all virtual desktops, and restore it. It adds "Float in VR" ("Back to Desktop" on a floating window) to the window menu (`registerUserActionsMenu`). It registers no shortcut: the float key belongs to the input relay. KWin scripts can call D-Bus but can't serve it, so commands come back through a long poll. The script calls ft-floatd's `NextCommand`, which answers when a command is ready, and then the script calls it again, or after 30 seconds without an answer. It also keeps KWin's placement memory from moving windows (see design.md).
|
||||
- **ft-floatd** (`float/ft-floatd`, Python). The host has dbus-python and PyGObject. It runs inside the desktop's Plasma session, started from its autostart. It owns `org.frametop.Float` on the session's private bus, and it keeps the table of which window is on which output and panel. It enables and disables spare outputs and sets their scale and position with `kscreen-doctor`, and their size through ft-screens. It tells ft-screens where each floating window goes and tells the script which window goes where. It launches apps floating, opens profiles' apps, and remembers each app's placement and scale, keyed by desktop file name. Commands come in on `@frametop_float`, from `ft-float`, the input relay, and ft-screens.
|
||||
- **ft-screens.** A spare output's panel is a floating window's. Floating panels get the same bar, curve, roll, resize tab, and wrist and head pins as screens, plus dock and close buttons left of the bar. Other parts: the catcher, popup and dialog overlays, and carrying a panel during a KWin move. `MAX_SCREENS` (screens and spares together) is 24. Commands arrive on `@ft_screens`. Events go out to `@frametop_float` from an unbound socket, the same way ft-screens talks to the input relay.
|
||||
- **Session script.** Adds `FLOAT_SLOTS` to KWin's output count, starts ft-floatd from the desktop's autostart, installs Frametop's window decoration and chooses it in the session's `kwinrc`, and writes the Launch as Standalone copies of the apps' desktop files.
|
||||
|
||||
@@ -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% |
|
||||
+4
-2
@@ -17,12 +17,14 @@ The input relay takes the volume keys from every device that has them, so gamesc
|
||||
ft-screens drops keys while no screen has focus or the SteamVR dashboard is open, but always lets through the release of a key the desktop saw pressed, so a modifier held as the dashboard opens doesn't stay down.
|
||||
|
||||
- **A key whose release never arrives stays held in the desktop until the relay clears it, within about a second.** KWin repeats held keys itself, so a stuck letter repeats and a stuck modifier changes every later key (Ctrl+Alt held turns T into Konsole). The relay remembers which keys it told the desktop went down, and once a second it releases any that no keyboard holds (`reconcile_desktop_keys`, which asks the kernel with `EVIOCGKEY`). Pressing and releasing the key again also clears it.
|
||||
- **A keyboard that disconnects mid-press, or a relay restart with a key down, is how it happens.** The once-a-second check catches the first. A relay that starts doesn't know what an earlier one left down, so it releases the modifiers on the desktop; another key left down that way stays until it's pressed and released again.
|
||||
- **A keyboard that disconnects mid-press, or a relay restart with a key down, is how it happens.** The once-a-second check catches the first. A relay that starts doesn't know what an earlier one left down, so it releases the modifiers and mouse buttons on the desktop; another key left down that way stays until it's pressed and released again.
|
||||
- **To see where a key went,** run `scripts/keys-report.py` and reproduce the problem while it records. It logs the modifiers, Tab, and Esc (no other keys) as the relay reads them and as its virtual keyboard sends them on, with the device roles and grabs, which programs have each keyboard open, and the relay's and desktop's logs.
|
||||
- **Switching where typing goes waits for keys to come up.** The relay changes a keyboard's grab only while none of its keys are down, so a press and its release go to the same side. A key held for a long time delays the switch until it's let go.
|
||||
- **Mouse buttons passed through as keys follow the pointer, not typing.** In pointer mode, a mouse button set to Pass through as key (a side button for Back) goes to the screen under the pointer, only while there is one 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 closes, or Frametop pauses; the real release that comes later is dropped. So a drag held with it ends as the laser leaves a screen, unlike a laser's own click, which KWin keeps until it comes up. wlroots counts presses per button, so a release lost on the way would leave that button dead in the desktop, the lasers' clicks included, until ft-screens restarts. The button also goes to the virtual mouse, which gamescope reads, so the app Steam has focused may see it too.
|
||||
- **Media keys reach both sides.** A keyboard's media keys come from its Consumer Control node, which has volume keys too, so the relay remaps that node rather than grabbing it. Its other keys reach gamescope as well as the desktop, even while typing goes to the desktop and the keyboard itself is grabbed: Play/Pause on the desktop can pause something in Steam too. The headset's own buttons don't go to the desktop.
|
||||
|
||||
## 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
@@ -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.
|
||||
+84
-24
@@ -6,18 +6,22 @@ How each part of Frametop works, where its settings live, and the commands for r
|
||||
|
||||
From the headset, open Launch a program → Desktop. The installer replaces that launcher entry with Frametop's (`~/.local/share/applications/deckard-nested-desktop.desktop`), and `desktops.sh uninstall` gives the stock single-screen desktop back.
|
||||
|
||||
The installer also adds Native Desktop to the same list: a copy of SteamOS's entry for its own desktop (`~/.local/share/applications/native-deckard-nested-desktop.desktop`), skipped when SteamOS has no such entry. The copy is made at install time, so `scripts/update-check.py` warns when SteamOS's entry changes, and `desktops.sh install` refreshes it. In Native Desktop, typing goes to Steam's side, so the input relay doesn't grab keyboards there, and a Meta tap runs Frametop's Meta action (by default, the Steam menu) as well as opening Plasma's launcher.
|
||||
|
||||
From a terminal, on the Frame or from a PC over SSH:
|
||||
|
||||
```
|
||||
desktops.sh install # the launcher's Desktop entry starts Frametop
|
||||
desktops.sh uninstall # back to the stock SteamOS desktop
|
||||
desktops.sh install # the launcher's Desktop entry starts Frametop; Native Desktop is the stock one
|
||||
desktops.sh uninstall # back to the stock SteamOS desktop, as Desktop
|
||||
desktops.sh start | stop | restart | status | log [lines]
|
||||
```
|
||||
|
||||
`session/frametop-session.sh` runs the desktop. It starts ft-screens in the `dev` container (log: `/tmp/frametop-screens.log`), then KWin and Plasma on the host inside it. Only one desktop runs at a time. `desktops.sh start` runs it in its own systemd unit, `frametop-desktop`. It keeps its Plasma config in `~/.config/frametop`, separate from the stock desktop's.
|
||||
`session/frametop-session.sh` runs the desktop. It starts ft-screens in the `dev` container (log: `/tmp/frametop-screens.log`), then KWin and Plasma on the host inside it. Only one Frametop desktop runs at a time. Its check doesn't look for Native Desktop, and running both at once is untested. `desktops.sh start` runs it in its own systemd unit, `frametop-desktop`. It keeps its Plasma config in `~/.config/frametop`, separate from the stock desktop's.
|
||||
|
||||
When the VR launcher starts the desktop, it inherits the Steam client's environment. The session script drops the client's runtime from it (`LD_LIBRARY_PATH`, the `STEAM_*` settings, and the Steam overlay's Vulkan layer), so apps in the desktop use the system's libraries, including its video codecs, just as they would after a normal login.
|
||||
|
||||
The nested session also starts an AT-SPI accessibility registry through `session/ft-atspi` in Plasma's autostart. It discovers the bus from this session, ignores an inherited host accessibility address, and leaves an existing registry alone. Accessibility errors do not stop the desktop. This supplies the registry infrastructure for apps that expose AT-SPI trees; it does not enable gaze snapping or force Chromium/Electron accessibility. After an approved desktop restart, an AT-SPI-aware app should be visible on the nested bus. See [design.md](design.md#nested-accessibility) for native activation, fallback lifecycle, and the isolated test command.
|
||||
|
||||
KWin's blur and background contrast effects and its animations are off in this desktop, because KWin draws on the headset's GPU, which SteamVR needs. The session script turns them off once, the first time it starts (it leaves a setting you already have alone, and marks it done in `~/.config/frametop/frametoprc`), so turning them back on sticks. In the Frametop desktop, System Settings → Window Management → Desktop Effects has Blur and Background Contrast, and General Behavior has Animation speed. Or from a terminal, then restart the desktop:
|
||||
|
||||
```
|
||||
@@ -26,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.
|
||||
|
||||
@@ -43,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.
|
||||
|
||||
@@ -64,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 and any key a pointer device passes through. Typing follows your last click: after a click on a screen it goes to the desktop, even with the SteamVR dashboard open, and after a mouse click on any other panel (the dashboard, Steam, an app like Spotify) it goes there instead. While it goes to the desktop, the relay grabs pass-through keyboards so gamescope, which reads every keyboard itself, doesn't type them into the Steam app too. A program that watches every keyboard for a hotkey loses a grabbed one; with `SHARE_KEYS=1` in `~/.config/frametop.conf`, their keys also go to `@frametop_keys` for it. That's off by default, since any local process that binds the name first would get everything typed into the desktop. Hidden screens don't take typing.
|
||||
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.
|
||||
|
||||
@@ -79,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
|
||||
|
||||
@@ -99,7 +110,7 @@ The relay also owns the volume keys, on every device that has them, the headset'
|
||||
desktops.sh relay install # enable it (starts with the next reboot or SteamVR start)
|
||||
desktops.sh relay status | log | uninstall
|
||||
input/input-relay.py --no-grab # try it without taking devices from SteamVR
|
||||
input/test/keys-test.py # key combinations and modifier taps, against fake devices (safe next to the live relay)
|
||||
input/test/keys-test.py # key combinations, modifier taps, and what reaches the desktop, against fake devices (safe next to the live relay)
|
||||
steam/ft-steam menu # what Open Steam menu does; ft-steam check: Steam's UI still has the calls
|
||||
```
|
||||
|
||||
@@ -111,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.
|
||||
|
||||
@@ -121,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`) and `GAZE_EYE` (the eye bias). The example config explains each. Frametop Input Settings changes them live; after editing the file by hand, restart the relay or the helper (the gaze service reads its two again when the file changes).
|
||||
|
||||
## Frametop Input Settings
|
||||
|
||||
A Kirigami app with a Python backend, in the Plasma menu under Settings. It runs in the `dev` container and talks to the relay over its control socket, `@frametop_relay`. It has 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.
|
||||
@@ -144,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.
|
||||
|
||||
@@ -152,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:
|
||||
@@ -173,13 +187,27 @@ layout/ft-layout hide N|all # hide a screen on its own, whatever the visibility
|
||||
display-settings/install.sh # menu entries and the Meta+Shift+R and Meta+Shift+H shortcuts
|
||||
```
|
||||
|
||||
The layout is stored relative to your head when it's applied. `/tmp/frametop-layout.log` has the run from the last desktop start.
|
||||
The layout is stored relative to your head when it's applied. `/run/user/<uid>/frametop-layout.log`, in the host's runtime directory (not the nested desktop's `/run/user/<uid>/frametop`), has the run from the last desktop start and ft-screens' layout runs after it.
|
||||
|
||||
## Frametop Remote Displays
|
||||
|
||||
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
|
||||
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). [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.
|
||||
|
||||
@@ -191,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
|
||||
@@ -221,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 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.
|
||||
|
||||
@@ -237,10 +279,28 @@ input/ft-pause on | off | toggle # pause or resume
|
||||
input/ft-pause status # the state as JSON (the relay's "pause ?")
|
||||
input/vrws.py 10 # the controllers' buttons from vrserver's web socket, for 10 s
|
||||
input/test/pause-test.py # the gesture and the automatic pause, offline
|
||||
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.
|
||||
@@ -256,12 +316,12 @@ In gaze mode the 3D mouse's pointer goes where you look, and the mouse or the ke
|
||||
|
||||
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.
|
||||
|
||||
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`.
|
||||
- `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` (after some SteamVR restarts the side cameras' names come out swapped, and hands land beside the holes; `hands/tools/check_sides.py --ring` tells), `HANDS_CPUS`, the cameras it tracks with (`HANDS_CAMERAS`, `HANDS_BRIGHT`, `HANDS_BRIGHT_ON`, `HANDS_BRIGHT_OFF`, `HANDS_COLOR_LEFT`, `HANDS_COLOR_CROP`), and the pointer helper's `POINTER_HANDS`, `POINTER_PINCH_GAIN`, `POINTER_PINCH_DEADZONE`, `POINTER_GRIP_GAIN`, `POINTER_GRIP_BELOW`, and `POINTER_PINCH_TYPING`. The example config explains each.
|
||||
- `HANDS_MODE` says when they run: `off` (the default) 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).
|
||||
|
||||
|
||||
@@ -0,0 +1,501 @@
|
||||
# Remote displays: design notes
|
||||
|
||||
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.
|
||||
|
||||
## What the hardware gives us
|
||||
|
||||
These were checked on the Frame (SteamOS kernel 6.18, SM8650 / Snapdragon 8 Gen 3, Mesa 26.3 Turnip on Adreno 750).
|
||||
|
||||
- **Decoder.** `/dev/video22` (`/dev/video-dec0`) is `qcom-iris-decoder`, Qualcomm's downstream iris driver (`drivers/media/platform/qcom/vcodec/iris`). It takes H.264, HEVC, and VP9 up to 8192x8192. AV1 isn't supported. The capture queue can produce `Q08C` (NV12 in Qualcomm's UBWC compressed layout), linear NV12, and NV21. It also lists RGBA (`AB24`, `QC24`), but those write a 10-bit UBWC YUV picture (S1), so the decoder has no usable RGB output.
|
||||
- **10-bit works on Valve's kernel.** Steam Link VR's client (`vrlink.txt`, `SVLCodecV4L2`) decodes into `Q10C`, 10-bit UBWC, at 1152x4608. That is both eyes stacked in one frame, so it uses one decode session. Valve drives the decoder through the raw V4L2 stateful API, as `vr-recorder` does for the encoder.
|
||||
- **Decoder budget.** The driver carries `MAX_SESSION_COUNT`, `MAX_MBPF`, and `MAX_MBPS` capability tables. For SM8650 the upstream values are 16 sessions, 278,528 macroblocks per frame, and 7,776,000 macroblocks per second (one 8K stream at 60 fps). A session that would go over the budget is refused when it starts. The downstream numbers on Valve's kernel are still to be confirmed by spike S2.
|
||||
- **SteamVR imports YUV but doesn't convert it.** `IVRIPCResourceManagerClient::GetDmabufModifiers(VRApplication_Overlay, …)` returns LINEAR and `0x0500000000000001` (`DRM_FORMAT_MOD_QCOM_COMPRESSED`) for NV12, P010, and the RGB formats. The probe is in `~/.cache/remote-displays-spike/modprobe.cpp`. `DmabufAttributes_t` takes multiple planes. This is the call ft-screens already makes for KWin's buffers (`ft_vr_screen_present`, `vr.cpp:2080`). The import works, but vrcompositor samples the planes as they are: red shows Cr, green Y, blue Cb (S1). `DmabufAttributes_t` has no colour-space fields to change that.
|
||||
|
||||
So a decoded frame needs one GPU pass before SteamVR sees it: NV12 to RGBA, about 0.13 ms of GPU time for a 3440x1440 frame at full clock. It is the same kind of pass as the hand cutouts' (`screens/handcut.cpp`), and native screens pay for one of the same size: KWin's composite of each output.
|
||||
|
||||
## Is the decoder the bottleneck?
|
||||
|
||||
Mostly no. Macroblocks per second against the 7,776,000 budget, at 60 fps:
|
||||
|
||||
| Displays | Share of the decoder |
|
||||
|---|---|
|
||||
| 5x 1920x1080 | 31% |
|
||||
| 5x 2560x1440 | 56% |
|
||||
| The current layout (3440x1440 + 2x 1440x1920) | 32% |
|
||||
| 5x 2560x1440 at 90 fps | 83% |
|
||||
| 4x 3840x2160 | 100% |
|
||||
| 5x 3840x2160 | 125%, refused |
|
||||
| Steam Link VR's own stream (1152x4608 at 120 Hz) | about 32% |
|
||||
|
||||
Five 1440p displays fit at full rate with room left. Five 4K displays only fit at about 48 fps or less. That number is what gets declared at session start; actual load is lower, because hosts send frames only when the screen changes (see "Keeping the decoder under budget").
|
||||
|
||||
### 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, which began with one display; it now runs one instance per display (see "Host side"). At 60 fps:
|
||||
|
||||
| Display | Share of the decoder |
|
||||
|---|---|
|
||||
| Super ultrawide 5120x1440 (5160x1440 as given; same load within 0.2%) | 22.2% |
|
||||
| Built-in 3024x1964 (native pixels) | 17.9% |
|
||||
| Ultrawide 3440x1440 | 14.9% |
|
||||
| Mac, one display | 14.9% to 22.2% |
|
||||
| The test PC, ultrawide + super ultrawide | 37.1% |
|
||||
| Both hosts today (three displays) | at most 59.4% |
|
||||
| Five: the three above plus two 3440x1440 virtual displays on the test PC | at most 89.2% |
|
||||
| The original five (all three Mac displays + the test PC's two) | 92.2% |
|
||||
|
||||
Every combination fits under the driver's limit at 60 fps. The original five stay as the worst case for spike S2, so the Mac can grow past one display later without a new budget. These are declared numbers, with every display changing every frame at once. With damage-driven hosts the real load is far lower.
|
||||
|
||||
Notes:
|
||||
|
||||
- The 5120-wide display needs HEVC. H.264 hardware encoders stop at 4096 pixels wide, and the iris decoder takes HEVC up to 8192. HEVC for every stream keeps it simple.
|
||||
- Streams don't need more than 60 fps. The Frame's display runs at 90 Hz, and the MacBook's 120 Hz ProMotion would double the built-in display's load for nothing.
|
||||
- A stream can be smaller than its display, because the host scales before encoding. A panel in VR covers far fewer headset pixels than the display has; a 1 m wide panel at 1 m spans about 53°, which is roughly 1,000 headset pixels across (estimate; the Frame's pixels per degree haven't been measured here). The built-in display at 2268x1473 instead of 3024x1964 would cost 10% instead of 18%. That's the lever when Steam Link VR also needs the decoder, or when a virtual display is made larger.
|
||||
- The desk monitors are shared through input switching. A monitor switched to the other machine may disappear from the first one, depending on the monitor and the cable. Real-display streams only work for monitors that host currently sees. In the headset, virtual displays avoid the question.
|
||||
|
||||
A remote display should cost less than a native one everywhere else:
|
||||
|
||||
| Per display | Native screen | Remote display |
|
||||
|---|---|---|
|
||||
| Apps | Run on the Frame's CPU | Run on the host |
|
||||
| Composition | KWin draws each output on the Adreno GPU | One GPU pass per new frame turns the decoder's NV12 into RGBA |
|
||||
| Hand-off to SteamVR | XRGB dmabuf, zero copy | RGBA UBWC dmabuf, zero copy |
|
||||
| Sampled by vrcompositor | 4 bytes per pixel | The same |
|
||||
| New work | — | Network receive and reassembly, V4L2 queueing |
|
||||
|
||||
The new costs are CPU for receiving packets, plus the decoder's and Wi-Fi radio's power and heat. Heat matters because the SoC slows down when it gets hot. Those are what the spikes need to measure.
|
||||
|
||||
## Keeping the decoder under budget
|
||||
|
||||
1. **Damage-driven hosts.** Sunshine and its forks send a new frame only when the captured screen changes, plus duplicates down to `minimum_fps_target` (default half the stream rate, settable to 1). With `minimum_fps_target = 1`, a static display costs about one decoded frame a second, the same idea as a native screen with no damage. A display playing video costs full rate, as a native video screen does.
|
||||
2. **Out of sight means 1 frame per second, whatever the host sends.** A display outside your view updates once a second, even when the host is sending 60 fps from a game. See "Displays out of sight" below for how. Concealed panels, and every panel while the desktop is paused for a game, disconnect fully after a grace period. That frees the host's encoder and the network.
|
||||
3. **An admission budget.** Before connecting, Frametop adds up the declared load of every stream: width/16 × height/16 × fps. If a new stream would go past the driver's limit, minus whatever else is decoding, Frametop lowers settings before connecting: first fps, then resolution, starting with the displays that get the least attention. Today's three displays come to at most 59%, which fits next to Steam Link VR's stream (about 32%). Five displays (89-92%) fit alone but not next to it, so a streamed PC game with five remote panels up would push them down to about 45 fps (or some lower and others higher).
|
||||
4. **No B-frames, low-latency decode.** Sunshine doesn't send B-frames, so every decoded frame can be shown at once. The decoder gets a small capture pool (6-8 buffers). Valve's client found the standard `DISPLAY_DELAY` controls unsupported on this driver (`EINVAL` in `vrlink.txt`). They aren't needed: S1 showed that with `Q08C` each frame comes out as soon as it's decoded (linear NV12 holds two more).
|
||||
5. **Tiling only as a fallback.** Valve tiles both eyes into one frame because they always change together. Desktops don't: one busy display would make the whole canvas decode at full rate, and a hidden tile can't be skipped. Per-display streams keep each display's cost proportional to its own changes. Tiling makes sense only for a host with many small, mostly static displays, and Sunshine can't capture a spanning desktop on Windows anyway.
|
||||
|
||||
The Moonlight protocol can't change resolution, fps, or bitrate mid-stream; that takes a reconnect. With stock hosts, attention changes therefore act on the client: in what gets decoded (2), not in what the host sends.
|
||||
|
||||
## Displays out of sight
|
||||
|
||||
Remote panels follow the native screens' attention rules (`UpdateAttention`, `vr.cpp:855`):
|
||||
|
||||
| Attention | Native screen | Remote display |
|
||||
|---|---|---|
|
||||
| Focused (within 12° of where you look) | Full rate | Full rate |
|
||||
| In view (within 60°) | 15 Hz, or full rate while it plays video | Full rate. Every frame has to be decoded anyway (below), and the host sends only what changed |
|
||||
| Hidden (out of view) | 1 Hz | 1 Hz, even when the host sends 60 |
|
||||
|
||||
The "video" signal comes for free: a damage-driven host sends frames only when its screen changes, so frames arriving faster than 10 a second for 8 frames in a row mean video, matching `VIDEO_COMMITS` and `VIDEO_HZ` in `compositor.c`.
|
||||
|
||||
The stream's fps is ours to choose. A game running at 144 Hz on the host is captured and sent at the fps the stream asked for (60 at most), so 144 never reaches the decoder.
|
||||
|
||||
**Why 1 Hz can't just skip frames.** Each frame in a stream is coded as changes to the frame before. Decoding frame 60 needs frames 1 to 59. Throwing away 59 of every 60 frames breaks the chain, and the next frame decodes as garbage. Valve's client works the same way: on a stall it asks the host for a new full frame (an "IFrame" in `vrlink.txt`).
|
||||
|
||||
**With stock hosts (Moonlight protocol): keyframe sampling.** While a panel is hidden, ft-stream:
|
||||
|
||||
1. drops every incoming frame before the decoder (moonlight-common-c's decode callback gets a `DECODE_UNIT` with `frameType`; return `DR_OK` without queueing);
|
||||
2. calls `LiRequestIdrFrame()` once a second, and decodes and shows only the IDR frame that comes back, which needs no earlier frames;
|
||||
3. when the panel comes back into view, requests one more IDR and goes back to decoding everything. The last frame, at most a second old, stays up until it arrives, about one round trip plus one frame later.
|
||||
|
||||
What that saves and what it doesn't, for a hidden display whose host sends 60 fps:
|
||||
|
||||
| Cost | Saved? |
|
||||
|---|---|
|
||||
| Decoder work | About 59 of 60 frames. One IDR costs a bit more to decode than one change frame |
|
||||
| Panel updates in vrcompositor | 59 of 60 |
|
||||
| Network traffic | No. The host keeps sending 60 fps, plus one larger IDR a second. A 5120x1440 IDR is a few hundred KB (estimate), so a few Mbit/s extra |
|
||||
| Frame CPU to receive, reassemble, and repair packets | No. moonlight-common-c still handles every packet. Patching it (it's GPL, and so is ft-stream) to discard hidden video packets early would cut most of this |
|
||||
| Host encoder | No |
|
||||
|
||||
**With a host that takes an fps change mid-stream: real 1 Hz.** If the host can be told "this display is out of sight, send 1 fps", the hidden display costs almost nothing anywhere. That's network, Frame CPU, decoder, and host encoder alike, and no IDRs are needed. The 1 Hz frames are ordinary change frames against the one a second earlier. This needs our own streamer, or a Sunshine fork with a control message that changes the capture rate. Owning a host streamer was rejected for its maintenance cost (see "Alternatives considered"), so this stays a possible upstream contribution. Vibepollo is the likeliest place to propose it: it already extends the protocol, since its own Moonlight fork sends a VRR pacing request that changes how the host captures.
|
||||
|
||||
Spike S3 checks the stock-host version: whether Sunshine honours an IDR request every second, how big and how late those IDRs are, and what receiving a hidden 60 fps stream costs the Frame's CPU.
|
||||
|
||||
## Proposed architecture
|
||||
|
||||
Frametop maintains only the headset side. The hosts run existing, separately maintained streamers that speak the Moonlight protocol: Vibepollo on Windows and Linux, Sunshine on macOS (see "Host side").
|
||||
|
||||
```
|
||||
host machine: Vibepollo (Windows, Linux) / Sunshine (macOS), one stream per display
|
||||
│ RTSP + RTP over UDP, ENet control
|
||||
▼
|
||||
ft-stream (one process per remote display, on the Frame, GPLv3)
|
||||
moonlight-common-c (protocol) + pairing (moonlight-embedded's libgamestream)
|
||||
iris decoder session: OUTPUT = HEVC, CAPTURE = Q08C, VIDIOC_EXPBUF
|
||||
GLES pass: Q08C → ring of 3 RGBA buffers (EGL YUV hints = the stream's colour space)
|
||||
│ unix socket, SCM_RIGHTS
|
||||
▼
|
||||
ft-screens (existing, MIT)
|
||||
remote screen type: ImportDmabuf once per ring buffer,
|
||||
SetOverlayTexture per frame, buffer returned to ft-stream when replaced
|
||||
panel input → ft-stream → LiSendMousePositionEvent / LiSendKeyboardEvent / …
|
||||
```
|
||||
|
||||
**Why one process per display.** moonlight-common-c keeps global state, so it runs one stream per process. It and libgamestream are GPLv3 while Frametop is MIT, and a helper that talks over a socket keeps the licences apart (this isn't legal advice). ft-stream lives in its own directory with its own licence file. Separate processes also mean a stalled stream or a decoder reset can't freeze the native screens. Each process pairs as its own client, which Vibepollo needs anyway: it ties each Remote Monitor to the client that opened it, one role per client, so every display needs its own client certificate and pairing.
|
||||
|
||||
**Pairing with a host token (chosen 2026-10-07).** Since every display is its own client, PIN pairing would mean one PIN and one round of permission clicks per display. Vibepollo has neither a multi-use PIN (its one-time PINs pair one client each) nor a way to pair several certificates at once. It does have scoped API tokens for its Web UI API (`POST /api/token`, sent as `Authorization: Bearer`). So the user creates one token on the host, limited to submitting pairing PINs (`POST /api/pin`), listing clients and setting their permissions (`GET /api/clients/list`, `POST /api/clients/update`), listing the host's monitors (`GET /api/display-devices`), and placing Remote Monitors (`GET`/`PUT /api/clients/display-layout`). A script on the host makes it from the Web UI login (`make-frametop-token`), and the user enters it once in Frametop's "add host" dialog. From then on, Frametop makes a client for each new display, pairs it by sending its own PIN, and grants it launch, mouse, and keyboard (Vibepollo gives a new client only list and view). It sizes Remote Monitors like the host's real monitors, and unpairs a display's client with that client's own certificate when the display is removed. The token can't change the host's settings and can be revoked in the Web UI. It can change any client's permissions, though, so Frametop keeps it like a password (a file only the user can read). Vibepollo's client update replaces the whole client record, so Frametop always sends every field.
|
||||
|
||||
**Why ft-stream converts.** ft-screens then gets RGBA dmabufs, as it does from KWin. Each decoder buffer goes back to the decoder right after the pass, so the decoder's pool doesn't depend on what SteamVR still holds. A GPU fault in one stream stays in its own process. ft-stream asks the host for BT.709 limited range (Moonlight's colour space and range settings) and gives the converter the same as EGL hints. S1 showed all four matrix and range combinations come out right when the hints match the stream.
|
||||
|
||||
**Opening a display.** For a host's main session, ft-stream launches the host's desktop app as Moonlight does. For a Vibepollo virtual display it launches the synthetic "Remote Monitor" app (id `2147483505` in `remote_session.h`), and the requested stream size and fps become the virtual display's mode. When the stream drops, Vibepollo keeps that display and its windows by default (`remote_monitor_disconnect_on_stream_end = false`), and ft-stream reconnects with "Resume" (id `2147483501`). So a concealed panel can disconnect fully without the host rearranging its windows.
|
||||
|
||||
**The socket protocol**, roughly:
|
||||
|
||||
- ft-stream → ft-screens: `buffers` (count, width, height, DRM format, modifier, offset and pitch, with the dmabuf fds of the RGBA ring) after each (re)configuration; `frame i` when ring buffer i holds a new picture (sent once the GPU is done, so no fence is needed); `title`, `state` (connecting, live, waiting for a keyframe, lost).
|
||||
- ft-screens → ft-stream: `release i` when buffer i is no longer on screen; `attention focused|view|hidden|concealed`; input events.
|
||||
|
||||
**In ft-screens**, the explorer's map gives the seams:
|
||||
|
||||
- Remote screens get `g_screens` entries through a `MakePanel` variant, with indices out of KWin's first-free-slot range (`compositor.c:279`) and the overlay keys `frametop.remote.N`. That brings visibility, attention, lasers, controls, spin, pinning, and hand cutouts.
|
||||
- Frames enter through an eventfd on the wl event loop and go through the same `ft_vr_screen_present` path, keyed by ring buffer, so the `g_imports` cache hits: 3 imports per display.
|
||||
- The pointer helper needs the new prefix in `FramePanel` (`ft-pointer.cpp:485`). The `screens` reply and `get N` need to list remote screens so gaze hit-testing sees them (`ft-gaze.cpp:302`).
|
||||
- `frametop-layout.json` gets a separate `hosts` list, since the `screens` array also sets KWin's output count. The user adds a host once, and its displays come as a bundle: Frametop pairs a client per display, starts their streams when the desktop starts, and stops them with it. Each host entry has the address, the token's file, and its displays. Each display has which one it is (the main session or a Remote Monitor), its own stream settings (size, fps, bitrate, and later codec and HDR), and the usual place, width, curve, and pin. ft-layout, profiles, and Display Settings learn the new list; Display Settings shows a host with its displays under it, each with its own settings (user decision, 2026-10-07).
|
||||
|
||||
**Input.** `handle_vr_event` (`compositor.c:333`) branches on the screen type. A remote screen sends:
|
||||
|
||||
- pointer motion as `LiSendMousePositionEvent(x, y, w, h)` in stream pixels;
|
||||
- buttons as `LiSendMouseButtonEvent`;
|
||||
- scroll as `LiSendHighResScrollEvent`, which matches the existing notches × 120.
|
||||
|
||||
A drag can cross panels, for example a window dragged from one of the host's displays to another. SteamVR sends a held button's moves only to the panel where the press began, with coordinates off that panel once the laser leaves it. The panel under the laser gets nothing (S3 measured this). So while a button is held on a remote screen, ft-screens hit-tests the laser (`ComputeOverlayIntersection`) against the host's other remote screens and sends the position to the ft-stream of the screen it hits. Moves that land on no panel are dropped, never clamped: clamping pins the host's cursor to the first display's edge. The host's input is shared across its sessions, so Windows sees one drag. But the release goes through the stream the press went through: Vibepollo takes a mouse button's release only from the client that pressed it (`mouse_press_owner` in its `src/input.cpp`). Sent through the display under the laser, it was dropped, and the window stayed on the pointer (found in the headset, 2026-10-07; `g_pressed_on` in `remote.c`).
|
||||
|
||||
Keyboard focus follows the last panel clicked. When it's a remote one, `send_key` and `relay_button` send evdev codes to its ft-stream, which maps them to Windows virtual-key codes (moonlight-qt has the table). Sunshine on macOS maps the Windows key to Cmd and Alt to Option. The host draws its own cursor into the video, so it lags the laser by one round trip.
|
||||
|
||||
**Won't work across the boundary:** drag and drop, the clipboard (the Moonlight protocol has none), floating windows, and KWin window rules. A remote display is a picture of another machine's monitor.
|
||||
|
||||
## Host side
|
||||
|
||||
**Decision for v1 (2026-10-07): real monitors only.** Vibepollo 2.0.0's Remote Monitors broke the test PC's monitor layout every time one was removed (see "S3 results so far"), while streaming a real monitor changes nothing on the host. Frametop can make extra screens in the headset itself, and the feature is mostly for controlling other machines, so v1 streams only a host's real monitors; virtual displays wait until the Vibepollo bugs are fixed. One host program streams one real monitor (a second client launching the main app joins the display already streaming), so each extra real monitor needs its own host instance: its own config file and ports (`port` 100 apart) and `output_name` set to that monitor. On the test PC that's Vibepollo for the primary (it also serves the Steam Deck and the Mac) and a plain Sunshine instance for the LC34G55T. Plain Sunshine has no scoped API tokens, so a Sunshine instance is paired once by PIN; it has a single Frametop client anyway. Frametop's host bundle becomes a list of instances, one per real monitor.
|
||||
|
||||
The requirement: each host streams its real displays, and virtual displays it creates on demand. Frametop doesn't maintain a host streamer; it uses existing ones and ships setup notes or scripts for them. State checked 2026-10-06.
|
||||
|
||||
| Host OS | Streamer | Displays |
|
||||
|---|---|---|
|
||||
| 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 | Every real display, one Sunshine instance each (`host/macos`); no virtual displays |
|
||||
|
||||
### Windows and Linux: Vibepollo
|
||||
|
||||
Vibepollo 2.0.0 (2026-09-30) is a Sunshine fork. One install gives:
|
||||
|
||||
- **A main session.** As on any Sunshine host, this is a real display (`virtual_display_mode = disabled`, picked by `output_name`) or a virtual display created for the client (`per_client`, the default on Windows 11 and Linux).
|
||||
- **Up to four Remote Monitors** (`max_client_vdds = 4` in `remote_session.h`). Each is a virtual display at the size and rate its client asks for, streamed and captured on its own (`capture_plan` in `remote_session.cpp`). They don't need a main session: with nothing running, the app list still offers Remote Monitor. They are always virtual and can't stream a real display.
|
||||
|
||||
That covers virtual displays completely, up to five from one host. Real displays are the limit: only the main session shows one, so one Vibepollo install streams one real display. A second real display at the same time needs a second host instance with its own config file, port, and `output_name`. On Windows that could be a plain Sunshine instance next to Vibepollo (untested). On Linux, Vibepollo expects to be the only host install on the machine. For the test PC this means one desk monitor streams as the main session and further displays are virtual, unless S3 shows a second instance works. Virtual displays also avoid the input-switching question (see "The planned setup").
|
||||
|
||||
Settings Frametop's setup notes change from the defaults:
|
||||
|
||||
- `virtual_display_layout`: the default `exclusive` turns off the host's other monitors while a virtual main session streams. `extended` keeps them on; `extended_isolated` also stops the host's own mouse from wandering onto the virtual display. Remote Monitors don't use it: Vibepollo always adds them next to the monitors already on (`apply_remote_monitor_composition` in `nvhttp.cpp`).
|
||||
- `minimum_fps_target = 1`, so a static display costs about one frame a second.
|
||||
- `remote_monitor_mute_audio = true`, unless that display should carry audio.
|
||||
|
||||
Both platforms send frames only when the screen changes. On Linux the virtual displays use presentation-driven capture: sparse changes are captured at once, and faster ones are coalesced to the stream's fps. The virtual outputs have no cursor plane, so the cursor is in the video, as with every Moonlight host.
|
||||
|
||||
PyroWave, Vibepollo's wavelet codec, isn't usable here. It decodes on the client's GPU and needs hundreds of Mbit/s over wired LAN. Frametop uses HEVC.
|
||||
|
||||
**Windows (the test PC).** The chosen setup (2026-10-06): one desk monitor streams as the main session, a real display (`virtual_display_mode = disabled`, `output_name` set to it). The other desk monitor is replaced by a Remote Monitor, a virtual display at that monitor's size, which Vibepollo releases when Frametop ends the connection (`remote_monitor_disconnect_on_client_disconnect = true`). A dropped connection keeps it (`remote_monitor_disconnect_on_stream_end = false`), so a Wi-Fi drop or a panel that disconnects while out of sight doesn't move its windows; ft-stream releases it explicitly with "Disconnect Monitor" (id `2147483502`) when the remote display is removed or Frametop exits. Each Remote Monitor's place next to the real monitors is set per client in the Web UI. GeForce allows 8 concurrent NVENC sessions per system. Installing Vibepollo and its display driver needs an admin; the test PC's `maptrainer` account isn't one.
|
||||
|
||||
How it's set up on the test PC (2026-10-06). Vibepollo installed over Apollo in `C:\Program Files\Apollo` (service `ApolloService`) and kept Apollo's settings, pairings, and Web UI login. The existing clients (a Steam Deck and a Mac) launch "Desktop" or "Steam Big Picture", which stream a virtual display with the other monitors turned off (`dd_configuration_option = ensure_only_display`). Frametop leaves them alone and gets its own app instead:
|
||||
|
||||
- "Frametop primary display": `"display-output": ""` streams the real primary monitor, and `"dd-configuration-option": "disabled"` leaves the other monitors as they are. ft-stream launches this app for the main session. These are the fields the Web UI writes for "use my own display" (`process.cpp` reads them).
|
||||
- `minimum_fps_target = 1` globally, which Remote Monitors use. "Desktop" and "Steam Big Picture" keep 120 as per-app `config-overrides`, so the Deck and the Mac stream as before.
|
||||
- `remote_monitor_mute_audio`, `remote_monitor_disconnect_on_client_disconnect` on, `remote_monitor_disconnect_on_stream_end` off.
|
||||
|
||||
The config folder is admin-only, so the change is a script for the user to run (`D:\remote-displays\vibepollo-setup\run-setup.cmd`, with a backup and an optional Web UI password reset). It ran on 2026-10-07. Vibepollo rewrites apps.json each time it starts and adds its built-in "Remote Input" and "Remote Monitor" apps, so any later change must start from the live file.
|
||||
|
||||
**Linux (beta).** x86_64 only: Arch Linux or CachyOS, KDE Plasma 6 on Wayland started by SDDM or Plasma Login Manager, Linux 6.16 or newer with matching headers, and a GPU with hardware H.264 encode (tested on NVIDIA and modern AMD). Virtual displays come from Vibepollo's own DKMS module, `vibeshine_drm`, which has four connectors, so at most four virtual displays exist at once. Streaming before login needs NVIDIA. Other distributions aren't covered; plain Sunshine still streams real displays there, without virtual ones.
|
||||
|
||||
**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 instance per display
|
||||
|
||||
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.
|
||||
|
||||
- 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.
|
||||
|
||||
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
|
||||
|
||||
| Limit | Effect | What can be done |
|
||||
|---|---|---|
|
||||
| A stream's fps is fixed at connect | Out-of-sight panels save decoder work through keyframe sampling, but the host keeps encoding and sending 60 fps | Patch ft-stream's copy of moonlight-common-c to drop hidden video packets early (saves Frame CPU). A "change rate" control message needs a host upstream; Vibepollo is the likeliest |
|
||||
| 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: 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.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- **Our own host streamer (ft-host)** on macOS, Windows, and Linux: capture and encode each display at a rate the headset can change mid-stream, real 1 Hz for hidden panels, a separate cursor, one connection per host, virtual displays built in. It solves every limit in the table above, but it means maintaining capture, encoding, transport, input, pairing, and virtual displays on three operating systems. Rejected for a free project (2026-10-06).
|
||||
- **Moonlight-qt in a window on a Frametop screen.** Nothing to build, and a quick way to check that a host and pairing work. But each frame goes decoder → Moonlight's GL renderer → KWin → ft-screens: two GPU passes per display where ft-stream needs one. Hidden panels can't drop to 1 Hz, and FFmpeg's v4l2m2m path on this device hasn't been tried (its encoder segfaults). Useful as a baseline, not as the feature.
|
||||
- **RDP (FreeRDP client, RDPGFX).** The best multi-monitor design on paper: one session, up to 16 monitors as separate surfaces, damage rectangles. But Windows' RDP host takes over the login session (the PC's own monitors lock) and runs at 30 fps by default, macOS has no RDP host, and FreeRDP decodes H.264 on the CPU or through VA-API, which the Frame lacks.
|
||||
- **Parsec, Steam Remote Play, RustDesk, NoMachine, Selkies, Apple Screen Sharing.** No aarch64 Linux client with hardware decode, no per-monitor streams, a closed protocol, or a Mac-only client.
|
||||
|
||||
## Spikes before any Frametop change
|
||||
|
||||
Spikes on the Frame run through `frame-job --local` as a standalone test overlay, with the headset on or with frame-testbench holding its worn state and pose. None of them touches the live desktop. S3 and S4 also need the hosts set up.
|
||||
|
||||
| # | Question | Pass |
|
||||
|---|---|---|
|
||||
| S1 (done) | Does a decoded `Q08C` buffer show in a SteamVR overlay with correct colours? Test pattern clip, BT.709 limited range, then full range | Correct colours; under 3% of a core; no extra missed frames (`~/.cache/frametop-perf/drops`); the decoder's real output delay |
|
||||
| S2 | Concurrency: the original five, the worst case (2x 5120x1440, 2x 3440x1440, 3024x1964), fed from files in real time at 60 fps | Admitted (92% declared); decode time per frame; SoC temperature and clocks over 10 minutes |
|
||||
| S3 | Live streams from the test PC (Vibepollo): the main session on a real desk monitor plus two Remote Monitors, through moonlight-common-c + the S1 decoder; then keyframe sampling on a hidden 60 fps stream | CPU per stream at real bitrates; glass-to-glass latency; time to picture after `LiRequestIdrFrame()`; the host honours one IDR request a second; IDR size; Frame CPU for a hidden stream; each Remote Monitor's mouse lands on its own display; Resume after a dropped stream keeps the windows; whether a second host instance can stream the other real monitor |
|
||||
| S4 | The Mac: one Sunshine instance on the main display. Once the mouse fix ships: one instance per display, then a BetterDisplay virtual display | Mouse and keyboard work; encode rate with full-motion video on the super ultrawide; `minimum_fps_target = 1` keeps a static display near 1 fps; later, all three stream at once with the mouse on the right display |
|
||||
| S5 | The baseline: 5 native screens, one playing video, four static | The CPU, GPU time (DRM fdinfo), temperature, and missed-frame numbers that the remote version must match |
|
||||
|
||||
### S1 results (2026-10-06)
|
||||
|
||||
S1 passes, with one change to the plan: a GPU pass between the decoder and SteamVR.
|
||||
|
||||
`stream/spike/ft-dectest` (built by `stream/build.sh`) decodes a clip with the V4L2 stateful API and hands each picture to SteamVR with `ImportDmabuf`, as the remote screen type would. Clips: a colour test pattern (`stream/spike/pattern.py`) with a moving box, 10 s at 60 fps, encoded by NVENC HEVC on the test PC (`-preset p1 -tune ull -bf 0`, as Sunshine-style streaming), in BT.709 and BT.601, limited and full range. The in-headset runs used frame-testbench to hold the worn state and a still pose, with nobody wearing the headset.
|
||||
|
||||
**Decoding.**
|
||||
|
||||
| | 3440x1440, Q08C | 3024x1964, Q08C | 3440x1440, linear NV12 |
|
||||
|---|---|---|---|
|
||||
| Decoder's buffer (coded size) | 3456x1440, 7,557,120 bytes | 3072x1984, 9,191,424 bytes | 3456x1440, 7,467,008 bytes |
|
||||
| SteamVR import | Works (NV12 + `QCOM_COMPRESSED`) | Works | Works (NV12, linear) |
|
||||
| Decode time, steady | 2.1 ms avg, 2.7 ms worst | 2.6 ms avg, 3.3 ms worst | 2.2 ms avg, 2.8 ms worst |
|
||||
| First picture after | 1 input frame | 1 input frame | 3 input frames |
|
||||
| CPU at 60 fps, no conversion | 1.2% of a core | 1.5% of a core | 1.4% of a core |
|
||||
|
||||
- The buffer layout from `msm_media_info.h` (per plane: UBWC metadata, then pixels, each 4 KiB aligned; Y stride aligned to 128, heights to 32) matches the driver's size to the byte, so the import offsets are right. The visible size comes from `G_SELECTION`; the decoder pads the coded size.
|
||||
- Q08C has no extra delay: each frame comes out as soon as it's decoded. Linear NV12 holds two more frames, so the remote screen type uses Q08C.
|
||||
- The CPU figure is ft-dectest's own process (file reading, V4L2 queueing, the overlay call). Network receive is S3's.
|
||||
|
||||
**Colours.** `stream/spike/s1-colours.py` shows the clip head-locked, switches the panel between the decoded video and an RGB copy of the pattern every 2.5 s, grabs the headset view (`/dev/video99`) in both states, and compares each colour patch.
|
||||
|
||||
- Decoder buffers straight into SteamVR come out wrong. vrcompositor doesn't convert NV12: red carries Cr, green Y, blue Cb. 100% red (Y 63, Cb 102, Cr 240 in BT.709 limited range) showed as 239/62/102, and greys as a dull magenta.
|
||||
- The decoder's RGBA formats don't help. It accepts `AB24` and `QC24` but writes a 10-bit UBWC YUV picture into them: 10,027,008 bytes used, exactly TP10 UBWC at 3456x1440, starting with UBWC metadata. It also reports their `bytesperline` in pixels.
|
||||
- A GPU pass gets them right (`ft-dectest --convert 709|601 --range tv|pc`). GLES samples the decoder's buffer through an external texture with the matrix and range as EGL hints (`EGL_YUV_COLOR_SPACE_HINT_EXT`, `EGL_SAMPLE_RANGE_HINT_EXT`). It draws into a ring of 3 RGBA buffers (UBWC, `QCOM_COMPRESSED`) that SteamVR imported once, set up as in `screens/handcut.cpp`.
|
||||
|
||||
| Clip, converted with its own matrix and range | Mean error | Worst patch |
|
||||
|---|---|---|
|
||||
| 3440x1440, BT.709 limited | 1.4 | 4.0 |
|
||||
| 3440x1440, BT.709 full | 1.2 | 4.0 |
|
||||
| 3440x1440, BT.601 limited | 0.2 | 2.4 |
|
||||
| 3440x1440, BT.601 full | 0.3 | 2.9 |
|
||||
| 3024x1964, BT.709 limited | 1.3 | 4.0 |
|
||||
|
||||
Errors are on the 0-255 scale, over 39-40 patches (27 for 3024x1964, where less of the panel is in view). The near-black steps (0-30) and near-white steps (225-255) all stay apart, so nothing is crushed or clipped. BT.709 sits about 3 low in red throughout, probably a rounding difference between ffmpeg's and Mesa's coefficients. That isn't visible.
|
||||
|
||||
**Cost of the pass**, 3440x1440 at 60 fps:
|
||||
|
||||
| Measure | Result |
|
||||
|---|---|
|
||||
| GPU work | About 118,000 cycles a frame: 0.13 ms at the 903 MHz top clock. With the headset idle, the GPU ran at about 230 MHz and was busy 0.51 ms a frame (DRM fdinfo) |
|
||||
| Time until the GPU is done | 1.1-1.4 ms avg, 2-6 ms worst |
|
||||
| CPU, whole ft-dectest process | 2.2-3.5% of a core, up from 1.2% |
|
||||
| Missed compositor frames, 30 s at 90 Hz | 0 of 2,701 with the stream shown, 0 of 2,700 idle |
|
||||
|
||||
- The CPU is at the 3% pass line. The increase is the GL driver plus the `glFinish` wait; ft-stream should try waiting on a sync file in its poll loop instead.
|
||||
- The five-display worst case (89% of the decoder) is about 360 converted 3440x1440-sized frames a second. That's about 5% of the GPU at top clock, and S2 measures it.
|
||||
- frame-testbench held the pose still and nobody wore the headset, so tracking and eye-tracking load may differ from a real session. S5 rechecks missed frames with the headset worn.
|
||||
|
||||
The benchmark is S5 against the same scene on remote displays: total Frame CPU (Frametop + ft-stream), GPU time, missed frames, and SoC temperature all at or below native.
|
||||
|
||||
### S3 results so far (2026-10-07)
|
||||
|
||||
`stream/spike/ft-streamtest.cpp` is a Moonlight client for one display: moonlight-common-c and libgamestream from moonlight-embedded (pinned in `stream/build.sh`), S1's decoder and GPU pass (`spike/iris.h`), and a SteamVR overlay. It pairs through the host's API token, launches the primary app or a Remote Monitor, and reports every 2 s. Tests ran from the test PC over the LAN, with the headset held by frame-testbench.
|
||||
|
||||
**The primary display (5120x1440 at 60 fps, HEVC, 50 Mbit/s asked).** It works end to end. The picture in the headset is right, colours included. The test PC's primary is an HDR monitor, and Vibepollo sends it as SDR Rec. 709, as asked.
|
||||
|
||||
| | Shown | Hidden (keyframe sampling) |
|
||||
|---|---|---|
|
||||
| Frames received | 60 fps | 60 fps |
|
||||
| Frames decoded and shown | 60 fps | 1 fps |
|
||||
| Network | 12-14 Mbit/s | the same |
|
||||
| ft-streamtest CPU | 4.2-4.6% of a core | 1.5-1.7% of a core |
|
||||
|
||||
- Time from a frame's first packet to the panel: 5.1-5.4 ms on average (worst about 12 ms). Of that, decoding takes 3.7 ms, and receiving the whole frame 0.1 ms. The host reports 3.2 ms from capture to encoded, and half the round trip is 1.5-2.5 ms. So a frame reaches the panel about 10 ms after the host captures it, before vrcompositor shows it. Glass to glass isn't measured yet.
|
||||
- Connecting took 225 ms, and the first picture showed 0.5 s after the launch.
|
||||
- Keyframe sampling: the host answered all 14 IDR requests, one a second. Each IDR arrived 18 ms after the request (worst 25 ms), reached the panel at 25 ms (worst 32 ms), and was about 81 KB for this desktop. Going back to full rate took 17 ms.
|
||||
- No packets were lost.
|
||||
- The test PC's desktop has an animated wallpaper, so the stream ran at 60 fps throughout, though Vibepollo applied a 0.5 fps floor. A still wallpaper would let an idle display drop to about one frame a second.
|
||||
|
||||
**Vibepollo bug: a stale display slot blocks Remote Monitors.** The first Remote Monitor launch failed with 503, "The composed display topology did not apply", for 40 s of retries. Vibepollo still held a display slot for the Mac's earlier "Desktop" session (`/api/clients/display-layout`: the Mac as a client node, its runtime "retryable" with the lease held), though that session's virtual display was gone. Composing the layout includes every held slot, and the Mac's can't be resolved to a device, so every composition fails. The Mac's session had been cut by a Vibepollo restart and reconnected before it ended. The failed launch still created frametop-2's virtual display, and "Disconnect Monitor" then reported success without removing it, because the launch never finished. A Vibepollo restart clears both. ft-stream must detect this state, a 503 that persists, and report it rather than retry forever. It's worth reporting upstream with the steps that cause it.
|
||||
|
||||
**Remote Monitor (frametop-2, 3440x1440 at 60 fps), after a Vibepollo restart.** The launch took 2.3 s (Vibepollo makes the virtual display, then answers), and the first picture came 0.9 s after connecting. The picture was right. An empty, still monitor dropped to 1 fps at once: 0.1 Mbit/s, 0.6% of a core, about 4-5 ms from first packet to panel. Windows moved a window it remembered for that spot onto the new monitor, so a Remote Monitor can take windows off the real screens without being asked.
|
||||
|
||||
**Vibepollo bug: a dropped Remote Monitor reset the host's real monitor layout.** The test killed ft-streamtest to imitate a dropped connection. Vibepollo kept the Remote Monitor for Resume, as configured, and recomposed the display layout. Windows refused it (`SetDisplayConfig`: ERROR_INVALID_PARAMETER, "failed to move device ... to new origin" for the monitor above the primary). Vibepollo's recovery (`SDC_USE_DATABASE_CURRENT`, a topology jog, `CDS_RESET`) then left Windows with a different layout: the monitor above became the primary, beside the old primary. "Disconnect Monitor" again reported success and did nothing. A Vibepollo restart was needed again.
|
||||
|
||||
One more defect that may have contributed: `GET /api/clients/display-layout` rebuilds Vibepollo's record of the real monitors without their positions or modes (every monitor at 0,0, 1920x1080; `refresh_remote_display_physical_baseline` in `confighttp.cpp`). A layout composed from that record stacks the monitors on one another. Launching a Remote Monitor reads the real positions again (`refresh_remote_monitor_baseline` in `nvhttp.cpp`), and the last such call came before the launch here, so this isn't proven to be the cause. Frametop must not call that endpoint until it's fixed.
|
||||
|
||||
So far, Vibepollo 2.0.0's Remote Monitors aren't reliable on the test PC: a stale slot blocks them, a drop can rearrange the host's real monitors, and "Disconnect Monitor" can't release a monitor whose ownership was lost. These go upstream with logs before Frametop depends on them. Further Remote Monitor tests on the test PC need the user's go-ahead, since they can move the user's own screens.
|
||||
|
||||
**The cause, and a fix (frametop-vibepollo, 2026-10-07).** All three Remote Monitor failures come from one call. When a display role ends, Vibepollo's coordinator (`src/remote_display_topology.cpp`) first recomposes the topology without the departing display, and only then removes it. On the test PC, Windows refuses that composed `SetDisplayConfig`. Then:
|
||||
- libdisplaydevice's automatic recovery (`SDC_USE_DATABASE_CURRENT`, a topology jog, `CDS_RESET`) rearranges the real monitors;
|
||||
- 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 [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.
|
||||
|
||||
Four new unit tests cover it, and the coordinator's 40 tests pass. The plan is to offer the fix upstream once it's proven on the test PC. Frametop stays MIT: it only talks to the host over the network.
|
||||
|
||||
**The fix works on the test PC (2026-10-07).** The dev build, `2.0.0` plus the fix, was built on the test PC with MSYS2 (UCRT64, as the CI does, without WebRTC, drivers or packaging; `D:\vp-build`). It links only Windows system DLLs, so it drops into the install as a plain exe swap (`D:\vp-build\deploy.ps1`; the original is kept as `sunshine.exe.2.0.0-original`, and `-Restore` puts it back). Three Remote Monitor cycles left the real layout exactly as it was, with no layout re-apply and no `SetDisplayConfig` errors in Vibepollo's log: a clean end, a killed client, and a relaunch after the kill. Before the fix, the clean end reset the layout twice in a row. Restarting Vibepollo for the deploy also ended a leftover Mac session cleanly and brought the real monitors back.
|
||||
|
||||
A dropped connection removes the Remote Monitor at once (Vibepollo saw the disconnect within 3 s), even with `remote_monitor_disconnect_on_stream_end = disabled`. With `remote_monitor_disconnect_on_client_disconnect = enabled`, a lost connection counts as a client disconnect. Keeping a monitor and its windows across a Wi-Fi drop would need that setting off, and Frametop releasing monitors explicitly with "Disconnect Monitor". That's still to test.
|
||||
|
||||
The development loop is an incremental Ninja build on the test PC (only changed files recompile), the exe swap through the admin SSH login, and `ft-streamtest`: a few minutes per change. Pure logic gets unit tests on the Frame.
|
||||
|
||||
**Real displays, several at once (frametop-vibepollo, 2026-10-07).** A new hidden control, "Frametop display" (id 2147483521), streams one of the host's existing displays, named by the launch argument `frametopDisplay` (a device id from `/api/display-devices`). The session captures that output exactly, the way a Remote Monitor captures its virtual display, but nothing is created and the layout is never touched. Each client holds one such stream, and the main app stays free for the Deck and the Mac. On the test PC:
|
||||
- both real monitors streamed at once (OLED at 5120x1440, LC34G55T at 3440x1440), each to its own client, at about 0.6% of a core each while idle;
|
||||
- a real display and a Remote Monitor streamed side by side, and the layout was unchanged afterwards.
|
||||
|
||||
With that, Frametop no longer needs the "Frametop primary display" app; every real display is captured the same way.
|
||||
|
||||
**Vibepollo bug: one idle HTTPS client froze the API for everyone.** While any stream ran, every other client's HTTPS requests (serverinfo, pairing, launch) waited until it ended, so a second display couldn't start. The stock 2.0.0 build did the same. A stack dump (MSYS2 gdb attached to the service) showed the HTTPS server's only I/O thread blocked in a synchronous TLS shutdown: `SunshineHTTPS`'s destructor (`nvhttp.h`) sends close_notify and then waits for the client's. libgamestream leaves its connection idle in curl's cache (it forbids reuse only on FreeBSD), so the wait lasted as long as the streaming client process. Fixed on both sides:
|
||||
- the fork marks the client's close_notify as received before shutting down, so nothing waits (a deliberately idle client no longer delays another client's request: 0.13 s);
|
||||
- `ft-streamtest` drops libgamestream's curl handle after every request, which ft-stream must do too.
|
||||
|
||||
**The 3D mouse, and dragging windows between displays (2026-10-07).** The setup had three panels from the test PC: the OLED and the LC34G55T as Frametop displays, and a 2560x1440 Remote Monitor. frame-testbench held the headset, and the 3D mouse was driven through `@ft_pointer_helper`. The 3D mouse moved and clicked the test PC's cursor on every panel.
|
||||
|
||||
The first version clamped every move to its own panel. A drag from the Remote Monitor to the OLED left the window below the Remote Monitor's bottom edge, mostly off screen. Removing the Remote Monitor brought it back to the OLED. Drags between monitors that touch in Windows' layout seemed to work, but only because the cursor, pinned at the shared edge, left the window hanging across it. `--input-log` showed why. With the button held, SteamVR kept sending the moves to the panel where the press began (for example -213,2093 on the 2560x1440 panel), and sent the panel under the laser no events at all. The release also went to the first panel, off its edge.
|
||||
|
||||
The spike's fix is the routing described under "Input", with one difference: each panel is its own process. The panel that got the press publishes the laser's device in a small shared file (`/dev/shm/frametop-streamtest-drag`). Every other panel hit-tests that device's ray against itself and moves the host's cursor while the ray hits it. When hovering, the panel's own hit test matched SteamVR's coordinates exactly, so the ray origin and the UV orientation (bottom-left origin, like the mouse events) are right. With the fix, three drags worked:
|
||||
- Remote Monitor to OLED;
|
||||
- OLED to Remote Monitor;
|
||||
- Remote Monitor to LC34G55T.
|
||||
|
||||
In each, the window followed the laser across panels and stayed where it was dropped. The release still went through the first panel's connection and landed right every time.
|
||||
|
||||
Windows' "Remember window locations based on monitor connection" moves windows on its own. When a Remote Monitor appears, Windows puts back windows it remembers there, and when it goes, they move to a real monitor.
|
||||
|
||||
## In ft-screens (2026-10-07)
|
||||
|
||||
The user decided remote displays are Frametop displays, with the same controls as the desktop's screens and their places saved in profiles. The spike's standalone overlays are replaced.
|
||||
|
||||
**What's built (branch `remote-displays`, uncommitted):**
|
||||
- `stream/ft-stream.cpp` is the per-display helper. It pairs, launches and decodes, and converts into a ring of three RGBA buffers. It hands their dmabufs to ft-screens once, then says which buffer holds each new picture. The protocol is in its header comment: frames one way, then release, attention, pointer, keys and blur the other way. `stream/host.cpp` holds the pairing and launch code ft-streamtest had.
|
||||
- `screens/remote.c` starts one ft-stream per remote screen with a socket pair, restarts a stream that ends (2 s, then backing off to 30 s), shows its frames through `ft_vr_screen_present`, and sends it the panel's input and attention. Commands: `remote <N> start <client> <host> <app> <W>x<H> <fps> <kbit/s> <metres> [label]` (`ok restored` when its panel is back where it was, below), `remote <N> stop`, `remote <N> info` (the stream's whole state, such as `lost can't connect`) and `remotes`. Remote screens are numbered from 101, so every other command (`place`, `width`, `curve`, `pin`, `get`, `conceal`) works on them as it is. `screens` leaves them out, because ft-layout, Display Settings and ft-floatd count KWin's outputs with it.
|
||||
- `vr.cpp` gives a remote screen a screen's panel (`frametop.remote.N`) with its controls. A press on a remote screen dragged onto another one is routed there (`UpdateRemoteDrag`). SteamVR keeps sending the moves to the panel the press began on, as if its surface went on past its edges. So every tick the pressing laser is hit-tested against all the remote screens, and the nearest one it meets takes the moves. On the panel the press began on, SteamVR's own moves count only while that panel is the nearest. Before this (2026-10-07), that panel's carried-on surface passed in front of or behind the other panel, and its moves pulled the host's pointer back: drags across worked only some of the time. The release comes up where the host's pointer is, through the stream the press went down on (Vibepollo takes a release only from the client that pressed).
|
||||
- `compositor.c` sends a remote screen's pointer events to its stream. A click on a remote screen takes the typing there (input relay keys and our VR keyboard), and leaving releases the keys it held (`blur`).
|
||||
- `--beside` runs a second ft-screens next to the desktop for tests. It shows remote screens only and sends nothing to the input relay, ft-floatd or ft-layout.
|
||||
- ft-pointer counts `frametop.remote.` panels as screens, and ft-gaze hit-tests them too (`remotes`, then `get N`). Without that, ft-gazed dropped looks below the keyboard pitch (-20°) on a low remote panel, as if you were looking at the keyboard.
|
||||
|
||||
**Tested through frame-testbench, with a `--beside` instance:**
|
||||
- the OLED and a Remote Monitor as panels;
|
||||
- Win+R, `notepad` and Enter typed through ft-screens' key path started Notepad on the test PC;
|
||||
- Notepad dragged from the OLED panel to the Remote Monitor's stayed where it was dropped;
|
||||
- the grab bar moves a remote panel;
|
||||
- stopping the instance released the Remote Monitor.
|
||||
|
||||
**SteamVR's overlay limit.** SteamVR allows 128 overlays in the whole system (`k_unMaxOverlayCount`), its own included. Each Frametop panel takes six or seven with its controls. The desktop's floating-window slots made all of theirs at start: eight empty slots held 56. With three screens, a third remote screen got `VROverlayError_OverlayLimitExceeded`. A floating window's panel and controls are now made when a window floats on it, and destroyed when it docks (`EnsureFloatPanel`, `DropFloatPanel`). This needs a test on the live desktop. The controls of the other panels stay up, invisible until a laser comes near, because SteamVR's laser hover is what brings them in.
|
||||
|
||||
**Layouts, profiles and settings (2026-10-07, same branch):**
|
||||
- `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 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.
|
||||
- Frametop Remote Displays (`remote-displays/`) is the app for them. It was a Display Settings tab at first; the user wanted an app of its own for the connections. Display Settings' Screens page has a button that opens it.
|
||||
- Add a host with its token (written to `~/.local/share/frametop-stream/hosts/ADDRESS.token`, mode 0600). Whether it answers on its Web UI port (47990) is checked every 15 s.
|
||||
- Add a display: one of the host's monitors from its API, or a virtual one.
|
||||
- Per display: Connected, Shown, stream size, fps and bitrate (the stream starts over), width in VR, remove. Each host has a Connected switch for all of its displays. A lost stream shows why (`remote N info`).
|
||||
- A disconnected display comes back where it was. ft-screens keeps a stopped remote panel's place, width, curve, pin and hidden state for the rest of its run (`Parked` in `vr.cpp`), and the next start of that screen restores them and replies `ok restored`. Otherwise ft-layout places it from the head, or with the headset off, from where the last arrangement was made, worked out from screen 1's place (`remote_anchor`).
|
||||
- A vrcompositor crash: ft-screens freed a remote panel's texture imports while the panel still showed one. That happened at quit, at `remote stop`, and when a stream started over. vrcompositor crashed drawing it as the headset left standby. `ft_vr_forget` now clears a panel's texture before its import goes, and remote panels are destroyed before their buffers.
|
||||
|
||||
**vrcompositor crashed again at ft-screens quit (15:42, SIGBUS), and at 14:34.** Both times remote screens were up and the headset was in standby. SteamVR logs "leaving standby" within 2 ms of ft-screens disconnecting, so the compositor wakes in the middle of our cleanup, and it drew a texture that was already freed. The crash took the gamescope session and Steam down with it. The restart at 15:39 under the same conditions didn't crash, so it's a race. Hardened, not yet verified: ft-screens now tears SteamVR down first, while every buffer the panels show still exists (before KWin and the streams go). It clears the panels' textures, destroys the overlays, waits 200 ms, and only then releases the imports; nothing calls SteamVR after `VR_Shutdown`. Until that's checked, restart the desktop only with the compositor awake.
|
||||
|
||||
**Frozen panels, out-of-sight rate, sound (2026-10-07, after the user's test):**
|
||||
- The OLED froze while a video played on it: frames came in at 59 fps and none were shown. ft-stream's message loop asked ft-screens' socket once more after the queue ran dry, to see whether it had closed, and lost whatever came in between. A lost `release` kept one of the three ring buffers from ft-stream for good, and after three nothing could be shown. Every pointer move is a message, so drags made it likely. (A lost button or key release would have stuck on the host the same way.) Fixed; ft-stream also takes the ring back if none of it comes back for 2 s.
|
||||
- Out of sight, a stream used to decode only keyframes, one asked for each second. The user found that too aggressive. Every frame is now decoded, and 10 a second shown (`kHiddenFps`); coming back into view is immediate, with no keyframe requests (those are big frames, and the link already loses some).
|
||||
- ft-stream ignored SIGTERM, ft-screens' death signal included: posix_spawn passed on ft-screens' blocked signals (its event loop takes SIGTERM, SIGINT and SIGCHLD through a signalfd). ft-screens now spawns it with none blocked, and ft-stream clears its mask too.
|
||||
- Sound: ft-stream plays the host's sound (Opus, then PipeWire's PulseAudio server through libpulse-simple, about 40 ms queued). One stream per host plays it, the one holding `$XDG_RUNTIME_DIR/frametop-audio-HOST.lock`; the others try every 3 s, so another takes over when it ends. The host keeps playing its sound too. The test PC sent none: `remote_monitor_mute_audio = enabled` (our setup script) mutes the monitor and display roles. Turning it off needs an admin change on the test PC and a Vibepollo restart.
|
||||
|
||||
**Where the lost frames went, and the dongle (2026-10-07, ~16:40):**
|
||||
- With the streams on the home network, about one frame every 2 s (all three together) was unrecoverable: bursts of 5 to 14 packets of one frame lost, beyond what FEC (Vibepollo's default 20%) repairs, and each loss then waited for a keyframe.
|
||||
- Not on the Frame: UDP `RcvbufErrors` and `InErrors` stayed 0, wlan0 rx drops 0, the driver's misc drops +6 in 90 s. Not on the test PC: I225-V outbound discards and errors 0. The Frame's link was fine (-28 dBm, 2.1 Gbit/s, power save off). So the router loses them, as `~/.cache/wifitest` found for Steam Link VR (2026-10-01).
|
||||
- Same burst test (vrsim, 50 Mbit/s at 60 fps, 20 s) from the test PC: through the router 0.33% of packets and 21 of 1200 frames lost (worst frame 21 ms); over the test PC's Steam Link dongle on the Frame's hotspot (the PC on the Frame's hotspot, the Frame at 10.35.78.1), none (worst 5.6 ms).
|
||||
- So a host can go over its dongle. Its entry in `frametop-layout.json` has `direct` (the dongle's address) and `route`: `auto` (the default: the dongle when its port 47989 answers within 300 ms, else the network), `network` or `dongle` (only: while it's down, the stream is "lost the dongle link is down" and ft-screens tries again). ft-stream reads them itself, so ft-screens passes the host's own address as before. Its state says which way it went (`live via dongle|network`, `remote N info`). Remote Displays has a Connection setting per host, the dongle's address, and Find, which looks for the host among the hotspot's clients (`/proc/net/arp`, device `wlanap`) with the same `<uniqueid>` in its serverinfo. `ft-layout remote host NAME route=... direct=...` saves it and starts the host's running streams over in place.
|
||||
- On the dongle, none of the three streams lost a frame in 2 to 3 minutes each, all at 60 fps.
|
||||
- Sound: `remote_monitor_mute_audio = disabled` on the test PC (backup `D:\remote-displays\vibepollo-setup\sunshine.conf.before-audio-20261007-163556`, ApolloService restarted). One stream plays it (`Remote display: ADDRESS` in PipeWire, through SteamOS's spatial filter chain to the headset's speakers). That stream uses about 5% of a core more than the others (240-sample `pa_simple_write`s; batching them would help).
|
||||
- Seen on the way: a stream that started while Vibepollo restarted chose the network (the dongle didn't answer yet) and then got no video, only sound; starting it over fixed it. Starting one display's stream once ended another's ("lost", back 5 s later). Vibepollo takes about 5 s to answer serverinfo, so every stream start waits that long.
|
||||
|
||||
**Adding a computer: sign in instead of carrying a token (2026-10-07, ~17:00):**
|
||||
- Before, a host's API token came from `make-frametop-token` run on the host (its Web UI login typed there), and the file had to reach the Frame by hand. Now Remote Displays does it. Add computer lists the Vibepollo and Sunshine computers that announce `_nvstream._tcp` over mDNS (`avahi-browse -rpt` on the host; a computer also seen on the hotspot, `wlanap`, has a dongle, and that address is kept as its `direct`), or takes an address. You sign in once with the host's Web UI user name and password. Frametop posts them (HTTP Basic) to `/api/token` for a token with only what it uses: `/api/pin` POST, `/api/clients/list` GET, `/api/clients/update` POST and `/api/display-devices` GET (not `/api/clients/display-layout`, which the old script allowed). It keeps the token, mode 0600, and forgets the password. The sign-in goes over the dongle when there is one. Then Add displays lists the host's monitors, all ticked but those already added, and a virtual display.
|
||||
- Hosts without a dongle use the network, and their card says so, with Find a dongle; the Connection choices only show once a dongle is known. A laptop without one was the test: it's on the network and not on the hotspot.
|
||||
- The Web UI's certificate is self-signed. Its public key is pinned at the first sign-in (`hosts/ADDRESS.pin`, `sha256//...` as curl takes it): ft-stream's API calls set `CURLOPT_PINNEDPUBLICKEY`, and a later sign-in refuses another key ("If Vibepollo was installed again, remove the host and add it again"). The test PC's key is the same on both paths. Checked: the right pin works, a wrong one fails. The test PC's existing token got its pin too.
|
||||
- Checked without the password: discovery found the test PC (its LAN address and its dongle on the hotspot, marked added) and a laptop; a wrong password says "Wrong user name or password". A real sign-in is the user's to try (the password never goes through chat).
|
||||
- Sign in again (on a host card) makes a new token; the old one stays in the host's Web UI under API Tokens until revoked there (Frametop's token can't revoke tokens).
|
||||
|
||||
**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` (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.
|
||||
- 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.
|
||||
- Windows rescales a window that moves between displays with different scaling, so the point you held moves on the window. A second drag from the same spot can land on the address bar instead of the title bar. That's Windows, not the routing.
|
||||
|
||||
**Still to do:**
|
||||
- A headset test of all of it in the live desktop:
|
||||
- the row above the screens;
|
||||
- moving a remote display and saving a profile, then `use` putting it back;
|
||||
- adding a display from Remote Displays;
|
||||
- drags across with a controller, and gaze on the remote panels.
|
||||
- The shutdown hardening above, verified: restart the desktop with remote screens up and the headset in standby (a crash takes the gamescope session down, so only with the user's OK).
|
||||
- The floating windows' panels made on demand, tested live.
|
||||
- Sound in the headset, by ear: one copy, in time with the picture.
|
||||
- Over the network, a lost frame still waits for a keyframe. Reference frame invalidation (moonlight-common-c's `CAPABILITY_REFERENCE_FRAME_INVALIDATION_HEVC`) would recover without one, if the decoder copes.
|
||||
- Find the dongle again if its address changes (the hotspot's DHCP), and a host whose own address changes (the token and pin files are named by it).
|
||||
- "Approve on the PC" instead of the password (our Vibepollo fork), later if wanted.
|
||||
- A per-display mouse mode (relative, for games).
|
||||
- A picture for a stream that's connecting or lost.
|
||||
- The installer doesn't build ft-stream yet (`stream/build.sh`), and `uninstall.sh` leaves `~/.local/share/frametop-stream` (the client keys and host tokens).
|
||||
- For the test, the pointer and gaze services run this branch's builds through drop-ins (`~/.config/systemd/user/frametop-{pointer,gaze}.service.d/remote-displays-worktree.conf`; `gaze/tracker/build` here links to the installed tracker's). Remove them when this is merged and installed.
|
||||
|
||||
## Open questions
|
||||
|
||||
- Which of the test PC's two desk monitors is the real one (the main session)?
|
||||
- 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?
|
||||
- Remote displays outside the desktop: should they also show over games, where the decoder is shared with Steam Link VR?
|
||||
@@ -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.
|
||||
+48
-3
@@ -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) {
|
||||
@@ -411,11 +421,46 @@ function run(c) {
|
||||
}
|
||||
}
|
||||
|
||||
// The long poll has one failure mode: a reply that never comes. KWin's callDBus never calls
|
||||
// back when a call fails (an error reply, ft-floatd gone, or its 25 s D-Bus timeout, which
|
||||
// ft-floatd blocked that long hits); it only logs "Received D-Bus message is error". Then
|
||||
// polling stays true and the script stops hearing commands until KWin reloads it. A watchdog
|
||||
// re-arms the poll. Its period must stay above that 25 s timeout, whatever ft-floatd's
|
||||
// POLL_SECONDS is: by then the call it gives up on has ended. The serial is for a reply that
|
||||
// still comes later (KWin stalled with the reply queued): it runs its commands (ft-floatd
|
||||
// sends each one once) but doesn't poll again. Two polls would answer each other for good,
|
||||
// since ft-floatd answers a waiting poll empty when the next one comes.
|
||||
// When the watchdog fires again and again, ft-floatd is gone, and only starting it again
|
||||
// helps (it reloads the script then). Each failed call is a line in KWin's log, so the
|
||||
// script says so once and waits twice as long each time, up to 5 minutes. A reply starts
|
||||
// over at 30 s, so a lost reply is still polled again after 30 s.
|
||||
const POLL_WAIT = 30000, POLL_WAIT_MAX = 300000;
|
||||
const pollWatchdog = new QTimer();
|
||||
pollWatchdog.singleShot = true;
|
||||
pollWatchdog.interval = POLL_WAIT;
|
||||
let pollLost = false; // the watchdog fired, and no reply since
|
||||
pollWatchdog.timeout.connect(() => {
|
||||
if (!pollLost) print("frametop-float: NextCommand didn't answer, polling again");
|
||||
pollLost = true;
|
||||
pollWatchdog.interval = Math.min(pollWatchdog.interval * 2, POLL_WAIT_MAX);
|
||||
polling = false;
|
||||
poll();
|
||||
});
|
||||
let pollSerial = 0;
|
||||
|
||||
function poll() {
|
||||
if (polling) return;
|
||||
polling = true;
|
||||
const serial = ++pollSerial;
|
||||
pollWatchdog.start();
|
||||
callDBus(SERVICE, PATH, IFACE, "NextCommand", reply => {
|
||||
polling = false;
|
||||
const current = serial === pollSerial; // not a call the watchdog gave up on
|
||||
if (current) {
|
||||
pollWatchdog.stop();
|
||||
pollWatchdog.interval = POLL_WAIT;
|
||||
pollLost = false;
|
||||
polling = false;
|
||||
}
|
||||
if (reply) {
|
||||
try {
|
||||
JSON.parse(reply).forEach(run);
|
||||
@@ -423,7 +468,7 @@ function poll() {
|
||||
print("frametop-float: bad command " + reply + ": " + e);
|
||||
}
|
||||
}
|
||||
poll();
|
||||
if (current) poll();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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
@@ -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")
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
# 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.
|
||||
|
||||
Nothing here is published yet: no release, no button.
|
||||
|
||||
## How FrameDrop installs a Linux zip
|
||||
|
||||
It uses Valve's SteamOS Devkit path: pair once with the headset's devkit service, then rsync the unpacked zip into `~/devkit-game/<name>` over SSH, and register it with Steam as a Devkit Game with a start command. `devkit.sh` here makes the same calls with Valve's devkit-utils, so all of this can be tested on the Frame without a PC.
|
||||
|
||||
## What the probe found (SteamOS 0.3.0, build 20260922.6101926)
|
||||
|
||||
`probe/probe.sh`, started as a Devkit Game, recorded:
|
||||
|
||||
- Devkit titles run on the host, not in a container, as user `steamos`, from a process tree that Steam's reaper owns. This held even with the compat tool set to `SteamLinuxRuntime_4-arm64`: Steam recorded the mapping and still ran it on the host.
|
||||
- On the host, everything the installer needs works: git, curl to GitHub, podman (sees the `dev` container), `systemctl --user`, `systemd-run --user`, and GTK 4 with libadwaita.
|
||||
- A GTK window opens in gamescope (an X11 window on `:1`, drawn through gamescope's Vulkan WSI).
|
||||
- Steam puts its overlay in `LD_PRELOAD` and Steam runtime paths in `LD_LIBRARY_PATH` and `PATH`. Every host tool prints a preload error unless they're cleared.
|
||||
- Inside the Steam Linux Runtime 4 container (started by hand with its `run` script), there's no git, podman, systemctl, or GTK, but `flatpak-spawn --host` runs commands on the host.
|
||||
- Steam refuses Devkit Game names with a `-` ("missing/invalid arguments").
|
||||
- Steam doesn't make the start command executable: without the exec bit, the title exits in a second and nothing runs.
|
||||
|
||||
## The installer
|
||||
|
||||
`installer/frametop-install.sh` is the start command.
|
||||
|
||||
1. In the container, it starts itself again on the host with `flatpak-spawn --host`.
|
||||
2. It clears Steam's preload and library paths, 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.
|
||||
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.
|
||||
|
||||
`--yes` keeps the version that's installed, or installs stable, and skips the SteamVR restart. The window says to restart SteamVR.
|
||||
|
||||
### 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. 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.
|
||||
- With the window closed there's nobody to answer: sudo fails, install.sh says which parts it skipped, and playing Frametop again finishes them.
|
||||
|
||||
`--dry-run` unpacks into `~/.cache/frametop-framedrop/dry-run` and stops there without installing (`install-release.sh --unpack-only`, or `get.sh --clone-only`).
|
||||
|
||||
## Try it on the Frame
|
||||
|
||||
```
|
||||
framedrop/build.sh # a test zip; or --image localhost/frametop:local --version 0.3.0-dev.1
|
||||
unzip -q framedrop/build/Frametop.zip -d /tmp/fd
|
||||
framedrop/devkit.sh add FrametopTest /tmp/fd/Frametop "./frametop-install.sh --dry-run"
|
||||
framedrop/devkit.sh run FrametopTest # or Play it from the Steam library
|
||||
framedrop/devkit.sh remove FrametopTest
|
||||
framedrop/devkit.sh add FrametopProbe framedrop/probe "./probe.sh native" # the probe
|
||||
```
|
||||
|
||||
The probe writes `~/.cache/frametop-framedrop/probe-native.log`, and the installer writes `~/.cache/frametop-framedrop/install.log`.
|
||||
|
||||
## Build the download
|
||||
|
||||
```
|
||||
framedrop/build.sh --image REF --version V [--commit SHA] [--channel C] [ZIP_URL] # a release
|
||||
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/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 `-`.
|
||||
- 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).
|
||||
Executable
+83
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build Frametop's download: framedrop/build/Frametop.zip, a "Frametop" folder that FrameDrop
|
||||
# installs from a PC, or that you unpack on the headset and run (frametop-install.sh). Also
|
||||
# framedrop/build/frametop.framedrop.json, the manifest an "Install with FrameDrop" button
|
||||
# points at, and SHA256SUMS. Same files in, same zip out.
|
||||
#
|
||||
# Usage: framedrop/build.sh --image REF --version V [--commit SHA] [--channel C] [ZIP_URL]
|
||||
# framedrop/build.sh [ZIP_URL]
|
||||
# --image REF a release: the image REF (built from this checkout, pack/Containerfile) goes
|
||||
# in the zip as frametop-image.tar with frametop-release.json, and the
|
||||
# installer installs it, built (pack/install-release.sh). About 1.1 GB.
|
||||
# --version V the release's version (0.3.0, or 0.3.0-exp.1 for an experimental one)
|
||||
# --commit SHA the commit it was built from (default: this checkout's HEAD)
|
||||
# --channel C stable or experimental (default: experimental if V has a "-")
|
||||
# Without --image, a few KB: the installer clones Frametop from GitHub (get.sh), for
|
||||
# testing the installer itself.
|
||||
# ZIP_URL where the zip will be downloaded from (default: the release's asset, or for
|
||||
# a test zip, the framedrop-installer release)
|
||||
set -euo pipefail
|
||||
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
repo=$(cd "$here/.." && pwd)
|
||||
image= version= commit= channel=
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
--image) image=${2:?--image needs an image}; shift ;;
|
||||
--version) version=${2:?--version needs a version}; shift ;;
|
||||
--commit) commit=${2:?--commit needs a commit}; shift ;;
|
||||
--channel) channel=${2:?--channel needs stable or experimental}; shift ;;
|
||||
-*) echo "unknown option: $1" >&2; exit 2 ;;
|
||||
*) break ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
out=$here/build
|
||||
rm -rf "$out"
|
||||
mkdir -p "$out"
|
||||
|
||||
files=("$here/installer/frametop-install.sh" "$here/installer/progress.py" "$here/installer/askpass")
|
||||
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/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/Frametop/frametop/releases/download/framedrop-installer/Frametop.zip}
|
||||
files+=("$repo/get.sh")
|
||||
fi
|
||||
|
||||
python3 - "$out/Frametop.zip" "${files[@]}" <<'EOF'
|
||||
import os, shutil, sys, zipfile
|
||||
dest, *files = sys.argv[1:]
|
||||
with zipfile.ZipFile(dest, "w", allowZip64=True) as z:
|
||||
for path in files:
|
||||
name = os.path.basename(path)
|
||||
info = zipfile.ZipInfo(f"Frametop/{name}", date_time=(2026, 1, 1, 0, 0, 0))
|
||||
info.create_system = 3 # unix, so the permissions below count
|
||||
info.external_attr = (0o100755 if os.access(path, os.X_OK) else 0o100644) << 16
|
||||
# The image's layers are compressed already.
|
||||
info.compress_type = zipfile.ZIP_STORED if name.endswith(".tar") else zipfile.ZIP_DEFLATED
|
||||
info.file_size = os.path.getsize(path)
|
||||
with open(path, "rb") as src, z.open(info, "w", force_zip64=True) as dst:
|
||||
shutil.copyfileobj(src, dst, 1 << 20)
|
||||
EOF
|
||||
rm -f "$out/frametop-image.tar"
|
||||
|
||||
sha=$(sha256sum "$out/Frametop.zip" | cut -d' ' -f1)
|
||||
python3 - "$url" "$sha" >"$out/frametop.framedrop.json" <<'EOF'
|
||||
import json, sys
|
||||
url, sha = sys.argv[1:]
|
||||
print(json.dumps({
|
||||
"schema": "framedrop.install/v1",
|
||||
"name": "Frametop",
|
||||
"files": [{"url": url, "sha256": sha}],
|
||||
}, indent=2))
|
||||
EOF
|
||||
(cd "$out" && sha256sum Frametop.zip frametop.framedrop.json ${image:+frametop-release.json} >SHA256SUMS)
|
||||
echo "built $out/Frametop.zip ($(du -h "$out/Frametop.zip" | cut -f1), sha256 $sha)"
|
||||
echo " $out/frametop.framedrop.json, $out/SHA256SUMS"
|
||||
Executable
+95
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env bash
|
||||
# Do on the Frame what FrameDrop does from a PC: copy a folder into ~/devkit-game/NAME and
|
||||
# register it with Steam as a "Devkit Game" (Valve's devkit-utils, the same calls FrameDrop and
|
||||
# the SteamOS Devkit Client make over SSH). For testing the FrameDrop installer and the probe
|
||||
# without a PC. Steam must be running, and Developer Mode on.
|
||||
#
|
||||
# Usage: devkit.sh add NAME DIR COMMAND [--compat TOOL]
|
||||
# devkit.sh run NAME # start it, as the library's Play button does
|
||||
# devkit.sh remove NAME # delete the folder and the Steam entry
|
||||
# devkit.sh list
|
||||
#
|
||||
# NAME can't contain "-": Steam answers "missing/invalid arguments". COMMAND is relative to
|
||||
# the folder, like FrameDrop's start command ("./probe.sh native"). --compat sets the runtime
|
||||
# (SteamLinuxRuntime_4-arm64, say); on SteamOS 0.3.0 Steam recorded it but still ran the
|
||||
# title on the host. There's no environment option: this Steam ignores the devkit env file.
|
||||
#
|
||||
# devkit-utils is Valve's (LGPL, gitlab.steamos.cloud/devkit/steamos-devkit). FrameDrop and
|
||||
# the devkit client copy it to ~/devkit-utils; if that isn't there, it's fetched at a pinned
|
||||
# commit into ~/.cache/frametop-framedrop.
|
||||
set -euo pipefail
|
||||
|
||||
devkit_rev=a00ceb7d91ea44a0c3e714a91a06417d6e5cdb33
|
||||
cache=$HOME/.cache/frametop-framedrop
|
||||
|
||||
usage() { sed -n '7,10p' "$0" | sed 's/^# \{0,1\}//' >&2; exit 2; }
|
||||
|
||||
utils() {
|
||||
if [ -e "$HOME/devkit-utils/steam-client-create-shortcut" ]; then
|
||||
echo "$HOME/devkit-utils"; return
|
||||
fi
|
||||
if [ ! -e "$cache/devkit-utils/steam-client-create-shortcut" ]; then
|
||||
echo "fetching devkit-utils ($devkit_rev)" >&2
|
||||
local tmp
|
||||
tmp=$(mktemp -d)
|
||||
git -C "$tmp" init -q
|
||||
git -C "$tmp" fetch -q --depth 1 https://gitlab.steamos.cloud/devkit/steamos-devkit.git "$devkit_rev"
|
||||
git -C "$tmp" checkout -q FETCH_HEAD
|
||||
mkdir -p "$cache"
|
||||
rm -rf "$cache/devkit-utils"
|
||||
cp -r "$tmp/client/devkit-utils" "$cache/devkit-utils"
|
||||
rm -rf "$tmp"
|
||||
fi
|
||||
echo "$cache/devkit-utils"
|
||||
}
|
||||
|
||||
[ $# -ge 1 ] || usage
|
||||
cmd=$1; shift
|
||||
case $cmd in
|
||||
add)
|
||||
[ $# -ge 3 ] || usage
|
||||
name=$1 src=$2 start=$3; shift 3
|
||||
case $name in *-*) echo "NAME can't contain '-' (Steam refuses it)" >&2; exit 2 ;; esac
|
||||
compat=
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
--compat) compat=${2:?}; shift ;;
|
||||
*) usage ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
u=$(utils)
|
||||
dir=$(python3 "$u/steamos-prepare-upload" --gameid "$name" | python3 -c 'import json,sys; print(json.load(sys.stdin)["directory"])')
|
||||
# FrameDrop rsyncs the unpacked zip; --delete as a clean upload would.
|
||||
rsync -a --delete "$src/" "$dir/"
|
||||
parms=$(python3 - "$name" "$dir" "$start" "$compat" <<'EOF'
|
||||
import json, sys
|
||||
name, directory, start, compat = sys.argv[1:]
|
||||
print(json.dumps({
|
||||
"gameid": name, "directory": directory,
|
||||
"argv": [start], "env": {},
|
||||
"settings": {"steam_play": "0", "compat_tool": compat},
|
||||
"force_appid": "", "lepton_args": "",
|
||||
}))
|
||||
EOF
|
||||
)
|
||||
res=$(python3 "$u/steam-client-create-shortcut" --parms "$parms" | tail -1)
|
||||
echo "Steam: $res"
|
||||
case $res in *'"error"'*) exit 1 ;; esac
|
||||
echo "registered $name ($dir)"
|
||||
;;
|
||||
run)
|
||||
[ $# -eq 1 ] || usage
|
||||
python3 "$(utils)/steam-devkit-rpc" run-game "gameid=$1" | tail -1
|
||||
echo
|
||||
;;
|
||||
remove)
|
||||
[ $# -eq 1 ] || usage
|
||||
python3 "$(utils)/steamos-delete" --delete-title "$1"
|
||||
rm -f "$HOME/devkit-game/$1"-*.json
|
||||
;;
|
||||
list)
|
||||
python3 "$(utils)/steam-devkit-rpc" list-shortcuts
|
||||
;;
|
||||
*) usage ;;
|
||||
esac
|
||||
Executable
+29
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/python3
|
||||
"""SUDO_ASKPASS for the FrameDrop install: sudo runs this for the password, and it asks the
|
||||
install window (progress.py) for it, over the window's socket in XDG_RUNTIME_DIR. The window
|
||||
answers only programs in the install's own service, and asks you on the headset if it doesn't
|
||||
have the password yet. The password goes to sudo on stdout and nowhere else.
|
||||
|
||||
With the window closed there's nobody to ask: this fails, so sudo does, and install.sh says
|
||||
which parts it skipped. Playing Frametop again reopens the window and the install.
|
||||
"""
|
||||
import os
|
||||
import socket
|
||||
import sys
|
||||
|
||||
path = os.environ.get("FRAMETOP_ASKPASS_SOCKET", f"/run/user/{os.getuid()}/frametop-install/askpass")
|
||||
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
s.settimeout(600) # time for you to type it, if the window has to ask
|
||||
try:
|
||||
s.connect(path) # connecting is the question: the window answers, then closes
|
||||
answer = bytearray()
|
||||
while chunk := s.recv(4096):
|
||||
answer += chunk
|
||||
except OSError as e:
|
||||
print(f"askpass: the install window isn't answering ({e.strerror or e}): play Frametop again",
|
||||
file=sys.stderr)
|
||||
sys.exit(1)
|
||||
if not answer:
|
||||
sys.exit(1) # you cancelled
|
||||
sys.stdout.buffer.write(bytes(answer) + b"\n")
|
||||
answer[:] = bytes(len(answer))
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env bash
|
||||
# Frametop's installer, in a release's Frametop.zip: the start command of the "Frametop" title
|
||||
# FrameDrop puts in the Steam library, or what you run after unpacking the zip on the headset.
|
||||
# It opens the install window (progress.py), which asks what to install, and your password
|
||||
# for the parts that need sudo, then installs Frametop (or updates it) in a service of its own
|
||||
# and shows its progress. A release's zip installs its own image, built
|
||||
# (install-release.sh); a test zip clones Frametop from GitHub (get.sh).
|
||||
#
|
||||
# Usage: frametop-install.sh [--dry-run]
|
||||
# --dry-run unpack into ~/.cache/frametop-framedrop/dry-run and stop there, without
|
||||
# installing, for testing this flow
|
||||
set -u
|
||||
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
self=$here/$(basename "$0")
|
||||
|
||||
# A Linux title can be started in the Steam Linux Runtime container, which has no git, podman,
|
||||
# systemctl, or GTK. Start this again on the host. (SteamOS 0.3.0 runs devkit titles on the
|
||||
# host anyway; this is for when FrameDrop or Steam picks the runtime.)
|
||||
if [ -e /run/pressure-vessel ]; then
|
||||
exec flatpak-spawn --host --watch-bus --env=DISPLAY="${DISPLAY-}" \
|
||||
--env=XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR-}" --env=SteamAppId="${SteamAppId-}" \
|
||||
--env=ENABLE_GAMESCOPE_WSI="${ENABLE_GAMESCOPE_WSI-}" /usr/bin/bash "$self" "$@"
|
||||
fi
|
||||
|
||||
# Steam adds its overlay and runtime libraries to every child; host tools don't want them.
|
||||
unset LD_PRELOAD LD_LIBRARY_PATH
|
||||
export PATH=/usr/local/bin:/usr/bin:/bin
|
||||
|
||||
exec /usr/bin/python3 "$here/progress.py" "$here" "$@"
|
||||
Executable
+547
@@ -0,0 +1,547 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The FrameDrop installer's window: what to install, your password for the parts that need it,
|
||||
then the install's progress.
|
||||
|
||||
Usage: progress.py DIR [--dry-run]
|
||||
DIR the installer's folder. A release's Frametop.zip has install-release.sh, the
|
||||
image (frametop-image.tar), and frametop-release.json: it installs that, built.
|
||||
A test zip has get.sh instead, which clones Frametop from GitHub.
|
||||
--dry-run unpack into ~/.cache/frametop-framedrop/dry-run and stop there, without
|
||||
installing, for testing this flow
|
||||
|
||||
The install runs in a user service of its own (UNIT): Steam ends the title's whole process
|
||||
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
|
||||
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
|
||||
a file, a log, the service's environment, or a command line.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import re
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import gi
|
||||
|
||||
gi.require_version("Gtk", "4.0")
|
||||
gi.require_version("Adw", "1")
|
||||
from gi.repository import Adw, GLib, Gtk, Pango # noqa: E402
|
||||
|
||||
HERE = Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else Path(__file__).resolve().parent
|
||||
DRY_RUN = "--dry-run" in sys.argv[2:]
|
||||
UNIT = "frametop-framedrop-install"
|
||||
HOME = Path.home()
|
||||
STATE = HOME / ".cache" / "frametop-framedrop"
|
||||
LOG = STATE / "install.log"
|
||||
RELEASE = (HERE / "install-release.sh").exists() and (HERE / "frametop-image.tar").exists()
|
||||
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/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.")
|
||||
|
||||
|
||||
def host_env():
|
||||
"""The user's real runtime folder and bus, for systemctl and systemd-run: a window opened
|
||||
from a VR desktop's Dolphin or Konsole has that session's own. GTK keeps the session's."""
|
||||
env = dict(os.environ)
|
||||
env["XDG_RUNTIME_DIR"] = f"/run/user/{os.getuid()}"
|
||||
env["DBUS_SESSION_BUS_ADDRESS"] = f"unix:path=/run/user/{os.getuid()}/bus"
|
||||
return env
|
||||
|
||||
|
||||
def unit_state():
|
||||
out = subprocess.run(["systemctl", "--user", "show", "-P", "ActiveState", UNIT],
|
||||
capture_output=True, text=True, env=host_env()).stdout.strip()
|
||||
return out or "inactive"
|
||||
|
||||
|
||||
def release_version():
|
||||
try:
|
||||
return json.loads((HERE / "frametop-release.json").read_text())["version"]
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
return ""
|
||||
|
||||
|
||||
def password_set():
|
||||
"""Does this user have a password sudo can take? SteamOS starts without one."""
|
||||
user = pwd.getpwuid(os.getuid()).pw_name
|
||||
out = subprocess.run(["passwd", "-S", user], capture_output=True, text=True).stdout.split()
|
||||
return len(out) < 2 or out[1] == "P" # P: usable; NP: none; L: locked
|
||||
|
||||
|
||||
def check_password(pw):
|
||||
"""Does sudo take it? Checked with cached credentials ignored, and forgotten after."""
|
||||
try:
|
||||
r = subprocess.run(["sudo", "-S", "-k", "-v", "-p", ""], input=bytes(pw) + b"\n",
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return False
|
||||
subprocess.run(["sudo", "-k"], stdin=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
return r.returncode == 0
|
||||
|
||||
|
||||
def in_unit(pid):
|
||||
"""Is this process in the install's service?"""
|
||||
try:
|
||||
with open(f"/proc/{pid}/cgroup") as f:
|
||||
return any(line.rstrip("\n").endswith(f"/{UNIT}.service") for line in f)
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def install_command(eye_tracker, bluetooth, voice=True):
|
||||
if RELEASE:
|
||||
args = [str(HERE / "install-release.sh"), "--yes"]
|
||||
if DRY_RUN:
|
||||
args += ["--unpack-only", "--dir", str(STATE / "dry-run")]
|
||||
else:
|
||||
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 eye_tracker:
|
||||
args.append("--no-eye-tracker")
|
||||
if bluetooth:
|
||||
args.append("--bluetooth")
|
||||
return args
|
||||
|
||||
|
||||
def start_unit(args, askpass):
|
||||
env = host_env()
|
||||
subprocess.run(["systemctl", "--user", "stop", UNIT], stderr=subprocess.DEVNULL, env=env)
|
||||
subprocess.run(["systemctl", "--user", "reset-failed", UNIT], stderr=subprocess.DEVNULL, env=env)
|
||||
STATE.mkdir(parents=True, exist_ok=True)
|
||||
LOG.write_bytes(b"")
|
||||
cmd = ["systemd-run", "--user", f"--unit={UNIT}", "--description=Frametop install (FrameDrop)",
|
||||
"--property=Type=oneshot", "--property=RemainAfterExit=yes",
|
||||
f"--property=StandardOutput=truncate:{LOG}", "--property=StandardError=inherit",
|
||||
f"--setenv=HOME={HOME}", f"--setenv=PATH={os.environ.get('PATH', '/usr/bin:/bin')}",
|
||||
"--setenv=TERM=dumb", f"--working-directory={HOME}", "--quiet", "--no-block"]
|
||||
if askpass:
|
||||
cmd += [f"--setenv=SUDO_ASKPASS={HERE / 'askpass'}", f"--setenv=FRAMETOP_ASKPASS_SOCKET={SOCK}"]
|
||||
cmd += ["/usr/bin/bash"] + args
|
||||
return subprocess.run(cmd, env=env).returncode == 0
|
||||
|
||||
|
||||
class Askpass:
|
||||
"""The socket askpass asks: answers programs in the install's service with the password,
|
||||
or holds them while the window asks you for it."""
|
||||
|
||||
def __init__(self, on_ask):
|
||||
self.on_ask = on_ask
|
||||
self.password = None # bytearray, while the install runs
|
||||
self.waiting = []
|
||||
SOCK_DIR.mkdir(mode=0o700, exist_ok=True)
|
||||
st = SOCK_DIR.stat()
|
||||
if st.st_uid != os.getuid():
|
||||
raise OSError(f"{SOCK_DIR} isn't yours")
|
||||
os.chmod(SOCK_DIR, 0o700)
|
||||
SOCK.unlink(missing_ok=True)
|
||||
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
self.sock.bind(str(SOCK))
|
||||
self.sock.listen(4)
|
||||
self.sock.setblocking(False)
|
||||
self.watch = GLib.io_add_watch(GLib.IOChannel.unix_new(self.sock.fileno()), GLib.PRIORITY_DEFAULT,
|
||||
GLib.IO_IN, self.accept)
|
||||
|
||||
def accept(self, *_):
|
||||
try:
|
||||
conn, _ = self.sock.accept()
|
||||
except OSError:
|
||||
return True
|
||||
pid, uid, _ = struct.unpack("3i", conn.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED,
|
||||
struct.calcsize("3i")))
|
||||
if uid != os.getuid() or not in_unit(pid):
|
||||
conn.close()
|
||||
return True
|
||||
if self.password:
|
||||
self.answer(conn)
|
||||
else:
|
||||
self.waiting.append(conn)
|
||||
self.on_ask()
|
||||
return True
|
||||
|
||||
def answer(self, conn):
|
||||
try:
|
||||
conn.setblocking(True)
|
||||
conn.sendall(bytes(self.password) if self.password else b"")
|
||||
except OSError:
|
||||
pass
|
||||
conn.close()
|
||||
|
||||
def give(self, pw):
|
||||
self.password = pw
|
||||
while self.waiting:
|
||||
self.answer(self.waiting.pop())
|
||||
|
||||
def refuse(self):
|
||||
while self.waiting:
|
||||
self.waiting.pop().close()
|
||||
|
||||
def close(self):
|
||||
if self.password:
|
||||
self.password[:] = bytes(len(self.password))
|
||||
self.password = None
|
||||
self.refuse()
|
||||
GLib.source_remove(self.watch)
|
||||
self.sock.close()
|
||||
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, 860 if "SteamAppId" in os.environ else 640)
|
||||
self.offset = 0
|
||||
self.partial = ""
|
||||
self.askpass = None
|
||||
self.checking = False
|
||||
|
||||
self.status = Gtk.Label(label="Install Frametop", xalign=0, wrap=True)
|
||||
self.status.add_css_class("title-2")
|
||||
self.detail = Gtk.Label(xalign=0, wrap=True)
|
||||
self.box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12,
|
||||
margin_top=18, margin_bottom=18, margin_start=18, margin_end=18)
|
||||
self.box.append(self.status)
|
||||
self.box.append(self.detail)
|
||||
view = Adw.ToolbarView(content=self.box)
|
||||
view.add_top_bar(Adw.HeaderBar())
|
||||
self.set_content(view)
|
||||
self.connect("close-request", self.closing)
|
||||
|
||||
if unit_state() == "activating":
|
||||
self.show_progress() # playing the title again: the install is still going
|
||||
else:
|
||||
self.show_choices()
|
||||
|
||||
# --- what to install, and the password
|
||||
|
||||
def show_choices(self):
|
||||
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. Optional: voice dictation, and two "
|
||||
"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.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, "
|
||||
"reconnect after they sleep)")
|
||||
self.pw = Gtk.PasswordEntry(show_peek_icon=True, placeholder_text="Your SteamOS password")
|
||||
pw_note = Gtk.Label(label="It's used only for this install, and isn't saved anywhere.", xalign=0,
|
||||
wrap=True)
|
||||
pw_note.add_css_class("dim-label")
|
||||
self.error = Gtk.Label(xalign=0, wrap=True, visible=False)
|
||||
self.error.add_css_class("error")
|
||||
self.go = Gtk.Button(label="Install", halign=Gtk.Align.END)
|
||||
self.go.add_css_class("suggested-action")
|
||||
self.go.connect("clicked", self.install)
|
||||
self.pw.connect("activate", self.install)
|
||||
pw_row, keypad = keypad_row(self.pw)
|
||||
self.choices = [self.voice, self.eye, self.bt, pw_row, keypad, pw_note, self.error, self.go]
|
||||
if not password_set():
|
||||
for c in (self.eye, self.bt):
|
||||
c.set_active(False)
|
||||
c.set_sensitive(False)
|
||||
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 two 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 *_: pw_row.set_sensitive(self.eye.get_active() or self.bt.get_active()))
|
||||
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:
|
||||
return self.begin(None)
|
||||
text = self.pw.get_text()
|
||||
if not text:
|
||||
return self.say("Type your password, or untick the parts that need it.")
|
||||
pw = bytearray(text.encode())
|
||||
self.pw.set_text("")
|
||||
self.checking = True
|
||||
self.go.set_sensitive(False)
|
||||
self.say("Checking the password...")
|
||||
|
||||
def check():
|
||||
ok = check_password(pw)
|
||||
GLib.idle_add(checked, ok)
|
||||
|
||||
def checked(ok):
|
||||
self.checking = False
|
||||
self.go.set_sensitive(True)
|
||||
if ok:
|
||||
self.begin(pw)
|
||||
else:
|
||||
pw[:] = bytes(len(pw))
|
||||
self.say("sudo didn't take that password. Try again, or untick the parts that need it.")
|
||||
return False
|
||||
|
||||
threading.Thread(target=check, daemon=True).start()
|
||||
|
||||
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(), self.voice.get_active())
|
||||
if pw is not None:
|
||||
try:
|
||||
self.askpass = Askpass(self.ask_again)
|
||||
except OSError as e:
|
||||
pw[:] = bytes(len(pw))
|
||||
return self.say(f"Couldn't make the password's socket: {e}")
|
||||
self.askpass.give(pw)
|
||||
if not start_unit(args, pw is not None):
|
||||
if self.askpass:
|
||||
self.askpass.close()
|
||||
self.askpass = None
|
||||
return self.say("Couldn't start the install service (systemd-run).")
|
||||
for w in self.choices:
|
||||
self.box.remove(w)
|
||||
self.show_progress()
|
||||
|
||||
# --- progress
|
||||
|
||||
def show_progress(self):
|
||||
self.status.set_label("Installing Frametop")
|
||||
self.detail.set_label("Starting...")
|
||||
self.bar = Gtk.ProgressBar()
|
||||
self.bar.pulse()
|
||||
self.text = Gtk.TextView(editable=False, cursor_visible=False, monospace=True,
|
||||
wrap_mode=Pango.WrapMode.WORD_CHAR)
|
||||
self.text.set_left_margin(8)
|
||||
self.text.set_right_margin(8)
|
||||
scroll = Gtk.ScrolledWindow(vexpand=True, child=self.text)
|
||||
|
||||
# The install wants the password and the window doesn't have it (played again).
|
||||
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)
|
||||
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")
|
||||
|
||||
keep = " Keep it open until the install is done: it gives the steps that need it your password." \
|
||||
if self.askpass else ""
|
||||
self.note = Gtk.Label(label="You can close this window: the install keeps going. Play Frametop "
|
||||
"again to come back to it." + keep, xalign=0, wrap=True)
|
||||
self.note.add_css_class("dim-label")
|
||||
close = Gtk.Button(label="Close", halign=Gtk.Align.END)
|
||||
close.connect("clicked", lambda *_: self.close())
|
||||
for w in (self.bar, scroll, self.ask_bar, self.ask_error, self.note, close):
|
||||
self.box.append(w)
|
||||
|
||||
if self.askpass is None:
|
||||
try:
|
||||
self.askpass = Askpass(self.ask_again)
|
||||
except OSError:
|
||||
self.askpass = None # askpass then fails, and install.sh skips those parts
|
||||
GLib.timeout_add(500, self.tick)
|
||||
self.tick()
|
||||
|
||||
def ask_again(self):
|
||||
if hasattr(self, "ask_bar"):
|
||||
self.ask_bar.set_visible(True)
|
||||
self.ask_pw.grab_focus()
|
||||
|
||||
def answer_ask(self, *_):
|
||||
text = self.ask_pw.get_text()
|
||||
if not text or self.checking:
|
||||
return
|
||||
pw = bytearray(text.encode())
|
||||
self.ask_pw.set_text("")
|
||||
self.checking = True
|
||||
|
||||
def check():
|
||||
GLib.idle_add(checked, check_password(pw))
|
||||
|
||||
def checked(ok):
|
||||
self.checking = False
|
||||
if ok and self.askpass:
|
||||
self.askpass.give(pw)
|
||||
self.ask_bar.set_visible(False)
|
||||
self.ask_error.set_visible(False)
|
||||
else:
|
||||
pw[:] = bytes(len(pw))
|
||||
self.ask_error.set_label("sudo didn't take that password.")
|
||||
self.ask_error.set_visible(True)
|
||||
return False
|
||||
|
||||
threading.Thread(target=check, daemon=True).start()
|
||||
|
||||
def skip_ask(self, *_):
|
||||
if self.askpass:
|
||||
self.askpass.refuse()
|
||||
self.ask_bar.set_visible(False)
|
||||
self.ask_error.set_visible(False)
|
||||
|
||||
def add_lines(self, lines):
|
||||
buf = self.text.get_buffer()
|
||||
for line in lines:
|
||||
m = STEP.match(line)
|
||||
if m:
|
||||
n, total, what = int(m[1]), int(m[2]), m[3]
|
||||
self.bar.set_fraction(max(0, n - 1) / total)
|
||||
self.detail.set_label(f"Step {max(n, 1)} of {total}: {what}")
|
||||
buf.insert(buf.get_end_iter(), line + "\n")
|
||||
# Keep the view at the newest line.
|
||||
end = buf.create_mark(None, buf.get_end_iter(), False)
|
||||
self.text.scroll_mark_onscreen(end)
|
||||
buf.delete_mark(end)
|
||||
|
||||
def tick(self):
|
||||
try:
|
||||
with open(LOG, "rb") as f:
|
||||
f.seek(self.offset)
|
||||
data = f.read()
|
||||
self.offset += len(data)
|
||||
except FileNotFoundError:
|
||||
data = b""
|
||||
if data:
|
||||
text = self.partial + ANSI.sub("", data.decode("utf-8", "replace")).replace("\r", "\n")
|
||||
*lines, self.partial = text.split("\n")
|
||||
self.add_lines(lines)
|
||||
|
||||
state = unit_state()
|
||||
if state == "activating":
|
||||
if self.bar.get_fraction() == 0:
|
||||
self.bar.pulse()
|
||||
return True
|
||||
if self.partial:
|
||||
self.add_lines([self.partial])
|
||||
self.partial = ""
|
||||
self.forget()
|
||||
self.note.set_visible(False)
|
||||
self.ask_bar.set_visible(False)
|
||||
if state == "active":
|
||||
self.status.set_label("Done")
|
||||
self.detail.set_label(DONE_TEXT)
|
||||
self.bar.set_fraction(1)
|
||||
else:
|
||||
self.status.set_label("The install stopped")
|
||||
self.detail.set_label("The log above says why. Play Frametop again to try again.")
|
||||
return False
|
||||
|
||||
def forget(self):
|
||||
if self.askpass:
|
||||
self.askpass.close()
|
||||
self.askpass = None
|
||||
|
||||
def closing(self, *_):
|
||||
self.forget()
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
app = Adw.Application(application_id="io.github.deejanuz.FrametopInstall")
|
||||
|
||||
def activate(a):
|
||||
# Played again while the window is open: show that one.
|
||||
win = a.get_active_window() or Window(a)
|
||||
win.present()
|
||||
|
||||
app.connect("activate", activate)
|
||||
app.run([])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+114
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env bash
|
||||
# FrameDrop proof of concept, step 1: run as a Steam "Devkit Game" (what FrameDrop installs a
|
||||
# Linux zip as) and record what an installer started from Steam could use: host or Steam Linux
|
||||
# Runtime container, podman, the user's systemd, git, the network, GTK, and a window on screen.
|
||||
# Register and start it: framedrop/devkit.sh add FrametopProbe framedrop/probe "./probe.sh native"
|
||||
# framedrop/devkit.sh run FrametopProbe
|
||||
# Usage: probe.sh LABEL
|
||||
# Writes ~/.cache/frametop-framedrop/probe-LABEL.log, replacing the previous one.
|
||||
label=${1:-unlabeled}
|
||||
out=$HOME/.cache/frametop-framedrop
|
||||
mkdir -p "$out"
|
||||
log=$out/probe-$label.log
|
||||
exec >"$log" 2>&1
|
||||
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
section() { printf '\n== %s\n' "$1"; }
|
||||
have() { command -v "$1" >/dev/null 2>&1; }
|
||||
check() { # check NAME CMD...: one line, ok or failed with the exit status
|
||||
local name=$1; shift
|
||||
if out_=$(timeout 20 "$@" 2>&1); then echo "ok $name: $(echo "$out_" | head -1)"
|
||||
else echo "FAILED $name (exit $?): $(echo "$out_" | head -2 | tr '\n' ' ')"; fi
|
||||
}
|
||||
|
||||
section "when, who, where"
|
||||
date -Is
|
||||
echo "label=$label uid=$(id -u) user=$(id -un) pwd=$PWD here=$here"
|
||||
echo "args: $*"
|
||||
grep -E '^(ID|VARIANT_ID|VERSION_ID|BUILD_ID|PRETTY_NAME)=' /etc/os-release
|
||||
|
||||
section "container?"
|
||||
for p in /run/pressure-vessel /.flatpak-info /run/host/os-release; do
|
||||
[ -e "$p" ] && echo "present: $p" || echo "absent: $p"
|
||||
done
|
||||
echo "container=${container-} PRESSURE_VESSEL_RUNTIME=${PRESSURE_VESSEL_RUNTIME-}"
|
||||
[ -e /run/host/os-release ] && grep -E '^(ID|VARIANT_ID)=' /run/host/os-release
|
||||
|
||||
section "environment"
|
||||
env | grep -E '^(PATH|HOME|XDG_[A-Z_]+|DISPLAY|WAYLAND_DISPLAY|DBUS_SESSION_BUS_ADDRESS|SteamAppId|SteamGameId|STEAM_COMPAT_[A-Z_]+|LD_LIBRARY_PATH|LD_PRELOAD|SDL_[A-Z_]+|GDK_BACKEND|ENABLE_[A-Z_]+|PRESSURE_VESSEL_[A-Z_]+)=' | sort
|
||||
echo "process tree:"
|
||||
pid=$$
|
||||
for _ in 1 2 3 4 5 6 7 8; do
|
||||
[ "$pid" -le 1 ] 2>/dev/null && break
|
||||
printf ' %s %s\n' "$pid" "$(tr '\0' ' ' </proc/"$pid"/cmdline 2>/dev/null | cut -c1-200)"
|
||||
pid=$(awk '/^PPid:/{print $2}' /proc/"$pid"/status 2>/dev/null)
|
||||
done
|
||||
|
||||
# Steam adds its overlay (LD_PRELOAD) and runtime libraries to every child. An installer has
|
||||
# to drop them before running host tools, as the checks below do.
|
||||
unset LD_PRELOAD
|
||||
LD_LIBRARY_PATH=$(printf %s "${LD_LIBRARY_PATH-}" | tr ':' '\n' | grep -v -e '/Steam/' -e '^$' -e 'x86_64' -e 'i386' | paste -sd:)
|
||||
[ -n "$LD_LIBRARY_PATH" ] && export LD_LIBRARY_PATH || unset LD_LIBRARY_PATH
|
||||
PATH=$(printf %s "$PATH" | tr ':' '\n' | grep -v '/Steam/' | paste -sd:)
|
||||
echo "cleaned: PATH=$PATH LD_LIBRARY_PATH=${LD_LIBRARY_PATH-}"
|
||||
|
||||
section "tools"
|
||||
for t in bash git curl python3 podman distrobox systemctl systemd-run busctl gdbus flatpak-spawn \
|
||||
steam-runtime-launch-client konsole zenity kdialog; do
|
||||
printf '%-28s %s\n' "$t" "$(command -v "$t" || echo -)"
|
||||
done
|
||||
|
||||
section "what an installer needs"
|
||||
check "home writable" sh -c 'f=$HOME/.cache/frametop-framedrop/.w && : >"$f" && rm "$f" && echo yes'
|
||||
check "~/frametop visible" sh -c 'ls -d "$HOME/frametop" && git -C "$HOME/frametop" log -1 --format=%h'
|
||||
have git && check "git ls-remote github" git ls-remote --heads https://github.com/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
|
||||
have systemctl && check "user units visible" systemctl --user is-enabled frametop-input-relay.service
|
||||
have python3 && check "python3 gi Gtk 4" python3 -c 'import gi; gi.require_version("Gtk","4.0"); gi.require_version("Adw","1"); from gi.repository import Gtk, Adw; print(Gtk.get_major_version(), Gtk.get_minor_version())'
|
||||
|
||||
section "escape to the host (needed if this is a container)"
|
||||
# A transient user unit runs in the host's user manager, outside any container.
|
||||
if have systemd-run; then
|
||||
rm -f "$out/escape-$label"
|
||||
check "systemd-run --user" systemd-run --user --wait --collect --quiet -- \
|
||||
sh -c "grep -E '^(ID|VARIANT_ID)=' /etc/os-release > '$out/escape-$label'; command -v podman git >> '$out/escape-$label'"
|
||||
[ -s "$out/escape-$label" ] && sed 's/^/ host says: /' "$out/escape-$label"
|
||||
fi
|
||||
if have busctl; then
|
||||
check "busctl --user (systemd1)" busctl --user get-property org.freedesktop.systemd1 /org/freedesktop/systemd1 org.freedesktop.systemd1.Manager Version
|
||||
fi
|
||||
|
||||
section "window"
|
||||
# A plain GTK 4 window for 20 s. Watch for it on the Frame; "window: mapped" means GTK showed it.
|
||||
if have python3; then
|
||||
timeout 40 python3 - <<'EOF'
|
||||
import sys
|
||||
try:
|
||||
import gi
|
||||
gi.require_version("Gtk", "4.0")
|
||||
from gi.repository import Gtk, GLib
|
||||
except Exception as e:
|
||||
print("window: no GTK 4:", e); sys.exit(0)
|
||||
app = Gtk.Application(application_id="io.github.deejanuz.FrametopProbe")
|
||||
def on_activate(app):
|
||||
w = Gtk.ApplicationWindow(application=app, title="Frametop installer probe")
|
||||
w.set_default_size(640, 240)
|
||||
w.set_child(Gtk.Label(label="Frametop installer probe\n\nIf you can read this, a FrameDrop install can show progress.\nThis window closes in 20 seconds."))
|
||||
w.connect("map", lambda *_: print("window: mapped", flush=True))
|
||||
w.present()
|
||||
GLib.timeout_add_seconds(20, app.quit)
|
||||
app.connect("activate", on_activate)
|
||||
print("window: display", Gtk.Widget.get_display(Gtk.Label()) if hasattr(Gtk.Widget, "get_display") else "?", flush=True)
|
||||
app.run([])
|
||||
print("window: closed")
|
||||
EOF
|
||||
echo "window exit: $?"
|
||||
else
|
||||
echo "window: no python3"
|
||||
fi
|
||||
|
||||
section "done"
|
||||
date -Is
|
||||
@@ -0,0 +1,202 @@
|
||||
#!/usr/bin/env bash
|
||||
# ft — build and run Frametop out of its OCI image (pack/Containerfile).
|
||||
#
|
||||
# The image is the product: one container that holds the frozen toolchain, the
|
||||
# native binaries, and the locked Python environment. Everything Frametop runs
|
||||
# goes through this wrapper, so the integration points (mounts, IPC, devices)
|
||||
# live in exactly one place.
|
||||
#
|
||||
# The wrapper works from two homes:
|
||||
# Repo mode the script sits in a checkout (pack/Containerfile beside it):
|
||||
# development commands build from the sources, and runs mount
|
||||
# the repo at /src/frametop
|
||||
# Installed the script sits in ~/.local/bin (put there by install.sh):
|
||||
# programs run from the image's own copy, no repo needed
|
||||
#
|
||||
# Image reference, in order: $FT_IMAGE, then ~/.config/frametop/image — which
|
||||
# install.sh writes and `ft update` keeps digest-pinned. A moving :latest tag
|
||||
# is refused for what gets deployed (the pinned image and the update source):
|
||||
# what runs on a headset must be reproducible and rollback-able. Local
|
||||
# development is free to use any tag, :latest included.
|
||||
#
|
||||
# Usage:
|
||||
# ft <prog> [args] [both] run a program from /opt/frametop
|
||||
# ft update [both] pull the published image, pin its digest
|
||||
# ft clean [both] remove frametop's leftover containers and
|
||||
# unused frametop images (see below)
|
||||
# Development commands live behind "ft dev" (they need a repo checkout):
|
||||
# ft dev build [repo] build the image from the repo
|
||||
# ft dev shell [repo] interactive shell in the image
|
||||
# ft dev test [repo] run the Python test suites inside the image
|
||||
#
|
||||
# About `ft clean` and the shared podman store: on SteamOS, frametop's
|
||||
# containers share one rootless podman store with Valve's (named
|
||||
# lepton-<context>). `ft clean` touches ONLY objects that are provably
|
||||
# frametop's: containers named frametop-*, and images whose reference
|
||||
# contains a /frametop or frametop: component. Everything else — every
|
||||
# lepton-* container, every dangling image, every cache layer — is left
|
||||
# alone. Never run `podman rm -a`, `podman rmi -a`, or `podman system prune`
|
||||
# on a Frame: those are store-wide and would delete Valve's containers.
|
||||
set -euo pipefail
|
||||
|
||||
root=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
||||
[ -f "$root/pack/Containerfile" ] && repo_mode=1 || repo_mode=0
|
||||
config_dir=${XDG_CONFIG_HOME:-$HOME/.config}/frametop
|
||||
ref_file=$config_dir/image # installed: the pinned image reference
|
||||
published_file=$config_dir/published # installed: where updates come from
|
||||
|
||||
reject_latest() { # reject_latest <what> <ref>
|
||||
# A reference with neither a tag nor a digest means :latest too. The tag is
|
||||
# after the last "/", so a registry port (host:5000/...) isn't one.
|
||||
local name=${2%%@*} latest=0
|
||||
case ${name##*/} in
|
||||
*:latest) latest=1 ;;
|
||||
*:*) ;;
|
||||
*) [[ $2 == *@sha256:* ]] || latest=1 ;;
|
||||
esac
|
||||
if [ "$latest" = 1 ]; then
|
||||
echo "ft: $2 uses the moving :latest tag — refused for $1." >&2
|
||||
echo " Pin a version tag or a digest (repo@sha256:...) instead," >&2
|
||||
echo " e.g. in $published_file or $ref_file." >&2
|
||||
exit 2
|
||||
fi
|
||||
}
|
||||
|
||||
# The reference updates pull from: $FT_IMAGE_PUBLISHED, then the config file.
|
||||
# It must be configured and versioned — there is no silent :latest default,
|
||||
# and there is no default that appears when nothing is configured.
|
||||
# (Deferred: refreshing the installed wrapper from the image, so wrapper and
|
||||
# image ship as one artifact. The wiring broke CI under Docker; revisit after
|
||||
# the smoke job tells us exactly where.)
|
||||
default_published() {
|
||||
local ref
|
||||
if [ -n "${FT_IMAGE_PUBLISHED:-}" ]; then ref=$FT_IMAGE_PUBLISHED
|
||||
elif [ -r "$published_file" ]; then ref=$(<"$published_file")
|
||||
else
|
||||
echo "ft update: no published reference configured." >&2
|
||||
echo " Write a versioned reference (never :latest) to:" >&2
|
||||
echo " $published_file" >&2
|
||||
echo " e.g. ghcr.io/0x1f6/frametop:v0.2.1 — install.sh does this." >&2
|
||||
exit 2
|
||||
fi
|
||||
reject_latest "the update source" "$ref"
|
||||
echo "$ref"
|
||||
}
|
||||
|
||||
# The reference programs run: $FT_IMAGE, then the pinned file. Installed mode
|
||||
# refuses to run without a pin — a headset must never end up on :latest by
|
||||
# accident, and must always know exactly what image it is running.
|
||||
default_image() {
|
||||
if [ "$repo_mode" = 1 ]; then echo "frametop:local"; return; fi
|
||||
local ref
|
||||
if [ -r "$ref_file" ] && [ -n "$(<"$ref_file")" ]; then ref=$(<"$ref_file")
|
||||
elif [ -n "${FT_IMAGE:-}" ]; then echo "$FT_IMAGE"; return
|
||||
else
|
||||
echo "ft: no image pinned. Nothing has been installed yet." >&2
|
||||
echo " install.sh writes the pinned reference to:" >&2
|
||||
echo " $ref_file" >&2
|
||||
exit 2
|
||||
fi
|
||||
reject_latest "the pinned image" "$ref"
|
||||
echo "$ref"
|
||||
}
|
||||
image=${FT_IMAGE:-}
|
||||
published=${FT_IMAGE_PUBLISHED:-}
|
||||
|
||||
# FT_ENGINE picks one when both are installed (CI builds with docker, and
|
||||
# its runner has podman too).
|
||||
engine=${FT_ENGINE:-$(command -v podman || command -v docker || true)}
|
||||
[ -n "$engine" ] || { echo "ft: need podman or docker on PATH" >&2; exit 1; }
|
||||
|
||||
# Repo mode mounts the checkout; installed mode uses the image's own copy.
|
||||
mounts=()
|
||||
[ "$repo_mode" = 1 ] && mounts+=(-v "$root":/src/frametop)
|
||||
# A container's own network namespace starts with the kernel's datagram queue
|
||||
# of 10; systemd sets 512 on the host. The input relay sends without blocking
|
||||
# and drops what a full queue refuses, so at 10 its burst of key and button
|
||||
# releases loses the last ones (keys-test.py caught this).
|
||||
mounts+=(--sysctl net.unix.max_dgram_qlen=512)
|
||||
|
||||
# How the programs run on the Frame (mounts, devices, groups, namespaces) is
|
||||
# not decided yet: see "The runtime on the Frame" in pack/design.md. Runs here
|
||||
# get no access to the host beyond the repo mount.
|
||||
|
||||
run_in_image() {
|
||||
[ -n "$image" ] || image=$(default_image)
|
||||
# frametop-<program>-<pid>: podman ps names the program, two runs of one
|
||||
# program (python3 a.py, python3 b.py) don't replace each other, and
|
||||
# ft clean finds the leftovers of crashed runs by the prefix.
|
||||
local name
|
||||
name=frametop-$(printf '%s' "${1##*/}" | tr -c 'a-zA-Z0-9._-' '-')-$$
|
||||
exec "$engine" run --rm --name "$name" ${mounts[@]+"${mounts[@]}"} \
|
||||
--workdir /src/frametop "$image" "$@"
|
||||
}
|
||||
|
||||
need_repo() {
|
||||
[ "$repo_mode" = 1 ] || { echo "ft $1: only in a repo checkout (this copy runs installed)" >&2; exit 2; }
|
||||
}
|
||||
|
||||
update() {
|
||||
[ -n "$published" ] || published=$(default_published)
|
||||
reject_latest "the update source" "$published"
|
||||
"$engine" pull "$published"
|
||||
# Pin what was pulled, by digest, so every later run and any bug report
|
||||
# names exactly this image — and rollback is editing one file.
|
||||
local digest
|
||||
if digest=$("$engine" inspect --format '{{index .RepoDigests 0}}' "$published" 2>/dev/null) && [ -n "$digest" ]; then
|
||||
mkdir -p "$config_dir"
|
||||
# Written whole or not at all: an empty pin would stop every run.
|
||||
printf '%s\n' "$digest" > "$ref_file.new" && mv "$ref_file.new" "$ref_file"
|
||||
echo "ft update: pinned $digest"
|
||||
else
|
||||
echo "ft update: could not read a digest for $published — keeping $image." >&2
|
||||
fi
|
||||
}
|
||||
|
||||
clean() {
|
||||
# Frametop's leftovers, and nothing else. See the header: the podman store
|
||||
# is shared with Valve's lepton-* containers, so this only deletes objects
|
||||
# whose name proves they are ours.
|
||||
local found=0 obj
|
||||
while IFS= read -r obj; do
|
||||
[ -n "$obj" ] || continue
|
||||
found=1
|
||||
echo "removing container $obj"
|
||||
"$engine" rm -f "$obj" >/dev/null
|
||||
done < <("$engine" ps -a --format '{{.Names}}' 2>/dev/null | grep '^frametop-' || true)
|
||||
# Images: only references that name frametop, and only ones no container
|
||||
# uses (podman rmi refuses those anyway — the guard is belt and braces).
|
||||
while IFS= read -r obj; do
|
||||
[ -n "$obj" ] || continue
|
||||
case $obj in *frametop*) ;; *) continue ;; esac
|
||||
found=1
|
||||
echo "removing image $obj"
|
||||
"$engine" rmi "$obj" >/dev/null 2>&1 \
|
||||
|| echo " (in use or already gone — left in place)" >&2
|
||||
done < <("$engine" images --format '{{.Repository}}:{{.Tag}} {{.ID}}' 2>/dev/null \
|
||||
| grep -E '(^|[ /])frametop(:| |$)' | awk '{print $1}' || true)
|
||||
[ "$found" = 1 ] || echo "nothing of frametop's to clean"
|
||||
[ "$found" = 1 ] || exit 0
|
||||
}
|
||||
|
||||
case "${1:-help}" in
|
||||
dev)
|
||||
shift
|
||||
image=${FT_IMAGE:-frametop:local} # dev always works against the local build
|
||||
case "${1:-help}" in
|
||||
build) need_repo build
|
||||
exec "$engine" build -f "$root/pack/Containerfile" -t "$image" "$root" ;;
|
||||
shell) need_repo shell
|
||||
exec "$engine" run --rm -it ${mounts[@]+"${mounts[@]}"} --workdir /src/frametop "$image" bash ;;
|
||||
test) need_repo test; run_in_image just test ;;
|
||||
help|-h|--help|"") sed -n '2,40p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//' ;;
|
||||
*) echo "ft dev: unknown command: $1 (build, shell, test)" >&2; exit 2 ;;
|
||||
esac ;;
|
||||
update) update ;;
|
||||
clean) clean ;;
|
||||
help|-h|--help)
|
||||
sed -n '2,40p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'
|
||||
[ -z "${1:-}" ] || exit 0 ;;
|
||||
*) [ -z "${1:-}" ] && { echo "ft: no command given" >&2; exit 2; }
|
||||
run_in_image "$@" ;;
|
||||
esac
|
||||
+7
-2
@@ -9,13 +9,17 @@ 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
|
||||
gaze/probe/install.sh # development: build, and add Frametop Gaze Probe to the app menu
|
||||
gaze/probe/ft-gazeprobe --screen 1
|
||||
scripts/gaze-report.py # why gaze or its calibration doesn't work, with what looks wrong first
|
||||
```
|
||||
|
||||
## Gaze pointer
|
||||
@@ -25,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.
|
||||
|
||||
@@ -33,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. 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.
|
||||
|
||||
@@ -54,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).
|
||||
|
||||
|
||||
+4
-5
@@ -3,18 +3,17 @@
|
||||
# (gaze/build/; they also run there). The panel draws its text with stb_truetype (public
|
||||
# domain, one header, pinned as in screens/build.sh).
|
||||
# The eye tracking API (IVRInput::GetEyeTrackingDataRelativeToNow) is newer than the header
|
||||
# shipped with SteamVR's samples, so this uses the pinned public header ft-screens fetches.
|
||||
# shipped with SteamVR's samples, so this uses the pinned public header (scripts/openvr.sh).
|
||||
set -euo pipefail
|
||||
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
|
||||
"$root/scripts/sync.sh" >/dev/null
|
||||
exec "$root/scripts/frame.sh" -C gaze 'set -e; mkdir -p build/include
|
||||
openvr=v2.15.6
|
||||
[ -f build/include/openvr-$openvr ] || { curl -fsSL "https://raw.githubusercontent.com/ValveSoftware/openvr/$openvr/headers/openvr.h" -o build/include/openvr.h && touch build/include/openvr-$openvr; }
|
||||
. ../scripts/openvr.sh
|
||||
g++ -std=c++17 -O2 -Wall -Wno-unused-parameter -Wno-missing-field-initializers -Ibuild/include -I../pointer/common \
|
||||
-o build/ft-gaze ft-gaze.cpp -L/opt/steamvr/bin/linuxarm64 -lopenvr_api -Wl,-rpath,/opt/steamvr/bin/linuxarm64 -lpthread
|
||||
-o build/ft-gaze ft-gaze.cpp $OPENVR_LIBS -lpthread
|
||||
stb=2c980bb59875b0d32144a71867fbdebb2f77cd20
|
||||
[ -f build/include/stb-$stb ] || { curl -fsSL "https://raw.githubusercontent.com/nothings/stb/$stb/stb_truetype.h" -o build/include/stb_truetype.h && touch build/include/stb-$stb; }
|
||||
g++ -std=c++17 -O2 -Wall -Wno-unused-parameter -Wno-missing-field-initializers -Ibuild/include $(pkg-config --cflags gbm libdrm) \
|
||||
-o build/ft-gazepanel panel/ft-gazepanel.cpp -L/opt/steamvr/bin/linuxarm64 -lopenvr_api -Wl,-rpath,/opt/steamvr/bin/linuxarm64 \
|
||||
-o build/ft-gazepanel panel/ft-gazepanel.cpp $OPENVR_LIBS \
|
||||
$(pkg-config --libs gbm libdrm) -lpthread
|
||||
echo "built build/ft-gaze build/ft-gazepanel"'
|
||||
Executable
+141
@@ -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())
|
||||
+17
-4
@@ -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
|
||||
|
||||
@@ -8,8 +8,8 @@ PartOf=steamvr.service
|
||||
Requisite=steamvr.service
|
||||
|
||||
[Service]
|
||||
# Host Python; it runs ft-gaze in the dev container (distrobox enter), which quits when
|
||||
# the service's pipe to it closes.
|
||||
# Host Python; it runs ft-gaze in the container it was built in (scripts/in-box), which
|
||||
# quits when the service's pipe to it closes.
|
||||
ExecStart=/usr/bin/python3 @REPO@/gaze/ft-gazed
|
||||
Restart=on-failure
|
||||
RestartSec=3
|
||||
|
||||
+154
-29
@@ -56,8 +56,8 @@
|
||||
// The mmap samples are in head space, 17 ms or so old when they appear, so each is turned
|
||||
// into the room with the head pose at its own timestamp, from a short pose history.
|
||||
//
|
||||
// Screens come from ft-screens (@ft_screens: "screens", "get N"), refreshed 4 times a
|
||||
// second in the background. A curved screen is a cylinder toward its front (see OnSurface
|
||||
// Screens come from ft-screens (@ft_screens: "screens", "remotes" for other machines'
|
||||
// displays, "get N"), refreshed 4 times a second in the background. A curved screen is a cylinder toward its front (see OnSurface
|
||||
// in screens/vr.cpp).
|
||||
#include <openvr.h>
|
||||
|
||||
@@ -98,6 +98,11 @@ double NowRaw() {
|
||||
}
|
||||
|
||||
// --- eye-server.mmap (packed, unaligned: read with memcpy) ---
|
||||
// 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
|
||||
@@ -110,11 +115,19 @@ constexpr size_t kVar1 = 0x177, kVar2 = 0x1b3;
|
||||
// The measurements the filter is fed: left x, y, right x, y, then the variance of each (left
|
||||
// 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;
|
||||
constexpr size_t kNeed = 0x1f3 + 5; // enough for either layout
|
||||
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 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;
|
||||
bool known = false;
|
||||
const uint8_t *p = nullptr;
|
||||
size_t size = 0;
|
||||
size_t At(size_t base) const { return base + shift; }
|
||||
bool Open() {
|
||||
const int fd = open("/dev/shm/eye-server.mmap", O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return false;
|
||||
@@ -130,6 +143,9 @@ struct EyeFile {
|
||||
size = st.st_size;
|
||||
return true;
|
||||
}
|
||||
// The sample counter, or 0 without the mapping: the one read the loop makes whether or
|
||||
// not the file was there (Get, V and ReadSample need it).
|
||||
uint32_t Counter() const { return p ? Get<uint32_t>(kCounter) : 0; }
|
||||
template <class T> T Get(size_t off) const {
|
||||
T v;
|
||||
std::memcpy(&v, p + off, sizeof v);
|
||||
@@ -140,6 +156,53 @@ struct EyeFile {
|
||||
std::memcpy(f, p + off, sizeof f);
|
||||
return {f[0], f[1], f[2]};
|
||||
}
|
||||
// A live timestamp is near the clock it comes from (its samples are 17 ms or so old).
|
||||
static bool TimePlausible(double t, double now) { return t > now - 2.0 && t <= now + 2.0; }
|
||||
// The eye directions are unit vectors, so their length is a second, independent check
|
||||
// next to the timestamp: a mere coincidence in one field does not confirm a layout.
|
||||
static bool UnitVec(Vec3 v) {
|
||||
const float n = v.x * v.x + v.y * v.y + v.z * v.z;
|
||||
return n > 0.81f && n < 1.21f; // |v| within 0.9 .. 1.1
|
||||
}
|
||||
bool Fits(size_t layout, double now) const {
|
||||
return TimePlausible(Get<double>(kTime + layout), now) && UnitVec(V(kLeft1 + layout)) &&
|
||||
UnitVec(V(kRight1 + layout));
|
||||
}
|
||||
|
||||
// Which layout is live, a step per pass of the loop, so it never stalls it. A layout
|
||||
// fits when its timestamp is near the clock and its two set-1 directions are unit
|
||||
// vectors; it's taken once its timestamp has moved on too, within kConfirm. That allows
|
||||
// for 2 samples a second: the eye server writes 72 or 90 (15 were seen on the beta).
|
||||
// kWaiting: call again on the next pass. kNone: no layout fits (a server that stopped,
|
||||
// SteamVR's tracker warming up, or a layout we don't know), so the mmap stays unused;
|
||||
// try again later. One detection per run is enough: the layout can't change under a
|
||||
// running ft-gaze, since SteamVR starts the eye server that writes the file, and the
|
||||
// gaze service stops and starts with SteamVR.
|
||||
enum Detection { kWaiting, kFound, kNone };
|
||||
static constexpr double kConfirm = 0.5;
|
||||
static constexpr size_t kLayouts = sizeof kShifts / sizeof kShifts[0];
|
||||
Detection Detect(double now) {
|
||||
if (!fit_) {
|
||||
for (size_t i = 0; i < kLayouts; ++i)
|
||||
if (Fits(kShifts[i], now)) fit_ |= 1u << i, t0_[i] = Get<double>(kTime + kShifts[i]);
|
||||
if (!fit_) return kNone;
|
||||
since_ = now;
|
||||
return kWaiting;
|
||||
}
|
||||
for (size_t i = 0; i < kLayouts; ++i)
|
||||
if ((fit_ >> i & 1) && Get<double>(kTime + kShifts[i]) > t0_[i] && Fits(kShifts[i], now)) {
|
||||
fit_ = 0, shift = kShifts[i], known = true;
|
||||
return kFound;
|
||||
}
|
||||
if (now - since_ <= kConfirm) return kWaiting;
|
||||
fit_ = 0;
|
||||
return kNone;
|
||||
}
|
||||
bool Detecting() const { return fit_ != 0; }
|
||||
|
||||
// Detect's state: the layouts that fit at since_ (a bit each), and their timestamps then.
|
||||
unsigned fit_ = 0;
|
||||
double t0_[kLayouts] = {}, since_ = 0;
|
||||
};
|
||||
|
||||
struct EyeSample {
|
||||
@@ -151,20 +214,22 @@ struct EyeSample {
|
||||
};
|
||||
|
||||
// A consistent copy: the writer has no seqlock we can use, so read until the counter and
|
||||
// timestamp are the same before and after.
|
||||
// timestamp are the same before and after. Only call this once the layout is known
|
||||
// (EyeFile::known): on an unknown layout these reads still pass the consistency check,
|
||||
// but yield garbage.
|
||||
bool ReadSample(const EyeFile &f, EyeSample &s) {
|
||||
for (int attempt = 0; attempt < 4; ++attempt) {
|
||||
const uint32_t n0 = f.Get<uint32_t>(kCounter);
|
||||
const double t0 = f.Get<double>(kTime);
|
||||
const double t0 = f.Get<double>(f.At(kTime));
|
||||
std::atomic_thread_fence(std::memory_order_acquire);
|
||||
s.left1 = f.V(kLeft1), s.right1 = f.V(kRight1), s.fix1 = f.V(kFix1);
|
||||
s.left2 = f.V(kLeft2), s.right2 = f.V(kRight2);
|
||||
std::memcpy(s.open, f.p + kOpen, sizeof s.open);
|
||||
std::memcpy(s.var1, f.p + kVar1, sizeof s.var1);
|
||||
std::memcpy(s.var2, f.p + kVar2, sizeof s.var2);
|
||||
std::memcpy(s.meas, f.p + kMeas, sizeof s.meas);
|
||||
s.left1 = f.V(f.At(kLeft1)), s.right1 = f.V(f.At(kRight1)), s.fix1 = f.V(f.At(kFix1));
|
||||
s.left2 = f.V(f.At(kLeft2)), s.right2 = f.V(f.At(kRight2));
|
||||
std::memcpy(s.open, f.p + f.At(kOpen), sizeof s.open);
|
||||
std::memcpy(s.var1, f.p + f.At(kVar1), sizeof s.var1);
|
||||
std::memcpy(s.var2, f.p + f.At(kVar2), sizeof s.var2);
|
||||
std::memcpy(s.meas, f.p + f.At(kMeas), sizeof s.meas);
|
||||
std::atomic_thread_fence(std::memory_order_acquire);
|
||||
if (f.Get<uint32_t>(kCounter) == n0 && f.Get<double>(kTime) == t0) {
|
||||
if (f.Get<uint32_t>(kCounter) == n0 && f.Get<double>(f.At(kTime)) == t0) {
|
||||
s.n = n0, s.t = t0;
|
||||
return true;
|
||||
}
|
||||
@@ -303,18 +368,32 @@ private:
|
||||
Screen s;
|
||||
if (std::sscanf(p, " %d:%dx%d:%lf%n", &s.index, &s.wpx, &s.hpx, &s.metres, &used) != 4) break;
|
||||
p += used;
|
||||
// "ok x y z xx xy xz yx yy yz zx zy zz width height curve hand"
|
||||
const std::string g = Ask(fd, "get " + std::to_string(s.index));
|
||||
double v[15];
|
||||
if (std::sscanf(g.c_str(), "ok %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf", &v[0], &v[1],
|
||||
&v[2], &v[3], &v[4], &v[5], &v[6], &v[7], &v[8], &v[9], &v[10], &v[11], &v[12], &v[13],
|
||||
&v[14]) != 15)
|
||||
continue;
|
||||
s.c = {v[0], v[1], v[2]};
|
||||
s.b = {{v[3], v[4], v[5]}, {v[6], v[7], v[8]}, {v[9], v[10], v[11]}};
|
||||
s.metres = v[12], s.height = v[13], s.curve = v[14];
|
||||
out.push_back(s);
|
||||
if (Place(fd, s)) out.push_back(s);
|
||||
}
|
||||
// Other machines' displays (remote.c): "ok <count> <index>:<client>:<state>:<w>x<h> ..."
|
||||
const std::string remotes = Ask(fd, "remotes");
|
||||
if (remotes.rfind("ok ", 0) != 0) return;
|
||||
p = remotes.c_str() + 3;
|
||||
if (std::sscanf(p, "%d%n", &count, &used) != 1) return;
|
||||
p += used;
|
||||
for (int k = 0; k < count; ++k) {
|
||||
Screen s;
|
||||
if (std::sscanf(p, " %d:%*[^:]:%*[^:]:%dx%d%n", &s.index, &s.wpx, &s.hpx, &used) != 3) break;
|
||||
p += used;
|
||||
if (s.wpx > 0 && s.hpx > 0 && Place(fd, s)) out.push_back(s);
|
||||
}
|
||||
}
|
||||
static bool Place(int fd, Screen &s) {
|
||||
// "ok x y z xx xy xz yx yy yz zx zy zz width height curve hand"
|
||||
const std::string g = Ask(fd, "get " + std::to_string(s.index));
|
||||
double v[15];
|
||||
if (std::sscanf(g.c_str(), "ok %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf", &v[0], &v[1], &v[2],
|
||||
&v[3], &v[4], &v[5], &v[6], &v[7], &v[8], &v[9], &v[10], &v[11], &v[12], &v[13], &v[14]) != 15)
|
||||
return false;
|
||||
s.c = {v[0], v[1], v[2]};
|
||||
s.b = {{v[3], v[4], v[5]}, {v[6], v[7], v[8]}, {v[9], v[10], v[11]}};
|
||||
s.metres = v[12], s.height = v[13], s.curve = v[14];
|
||||
return true;
|
||||
}
|
||||
|
||||
std::thread thread_;
|
||||
@@ -525,7 +604,7 @@ int main(int argc, char **argv) {
|
||||
std::fprintf(stderr, "ft-gaze: action manifest %s: error %d\n", manifest.c_str(), int(me));
|
||||
|
||||
EyeFile eyes;
|
||||
const bool haveMmap = eyes.Open();
|
||||
bool haveMmap = eyes.Open();
|
||||
std::fprintf(stderr, "ft-gaze: eye-server.mmap %s\n", haveMmap ? "open" : "not available");
|
||||
|
||||
OwnFile ownFile;
|
||||
@@ -544,6 +623,19 @@ int main(int argc, char **argv) {
|
||||
// over the dashboard. Games are told apart the way ft-screens does it, by the scene app.
|
||||
bool inGame = false;
|
||||
double nextGameCheck = 0;
|
||||
// The mmap's layout (EyeFile::Detect) is looked for while it isn't known and the eye
|
||||
// server writes: the counter (0x38 in both layouts) ticks once per sample, so a silent
|
||||
// server (headset off) costs nothing and logs nothing. Until a layout is known, SteamVR's
|
||||
// tracker counts as unavailable. "Not recognized" waits until no layout has fitted for
|
||||
// kUnknownAfter of writing, longer than SteamVR's tracker takes to warm up after the
|
||||
// headset goes on (about 20 s), then goes to the journal at most once a minute; ft-gazed
|
||||
// shows it on the Gaze page.
|
||||
constexpr double kUnknownAfter = 30;
|
||||
double nextLayoutCheck = 0, nextLayoutLog = 0, lastWrite = 0, missSince = 0;
|
||||
uint32_t lastCounterSeen = eyes.Counter();
|
||||
// SteamVR's eye tracker creates the mmap a second or two after SteamVR starts, so it can
|
||||
// be missing when we start: look for it again every 2 s until it's there.
|
||||
double nextOpen = NowRaw() + 2.0;
|
||||
|
||||
while (true) {
|
||||
const double now = NowRaw();
|
||||
@@ -559,11 +651,43 @@ int main(int argc, char **argv) {
|
||||
sys->GetDeviceToAbsoluteTrackingPose(vr::TrackingUniverseStanding, 0, &hp, 1);
|
||||
if (hp.bPoseIsValid) history.Add(now, hp.mDeviceToAbsoluteTracking);
|
||||
|
||||
// One line per new eye sample, or at 90 Hz without the mmap.
|
||||
if (!haveMmap && now >= nextOpen) {
|
||||
nextOpen = now + 2.0;
|
||||
if ((haveMmap = eyes.Open())) {
|
||||
std::fprintf(stderr, "ft-gaze: eye-server.mmap open\n");
|
||||
lastCounterSeen = eyes.Counter();
|
||||
}
|
||||
}
|
||||
|
||||
// One line per new eye sample, or at 90 Hz without a usable mmap: none, or one whose
|
||||
// layout isn't known (yet). Our own tracker needs nothing from the mmap, so it keeps
|
||||
// going then; the mmap's sources print as {"ok":0} and "eye" as null.
|
||||
EyeSample s;
|
||||
bool fresh = false;
|
||||
if (haveMmap && ReadSample(eyes, s) && s.n != lastN) fresh = true, lastN = s.n;
|
||||
if (!haveMmap && now - lastEmit >= 1.0 / 90) fresh = true, s.t = now;
|
||||
const uint32_t counter = eyes.Counter();
|
||||
const bool writing = haveMmap && counter != lastCounterSeen;
|
||||
lastCounterSeen = counter;
|
||||
if (writing) {
|
||||
if (now - lastWrite > 2.0) missSince = 0; // it was silent: start counting again
|
||||
lastWrite = now;
|
||||
}
|
||||
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 ? "SteamOS 0.4 (+5)" : "SteamOS 0.3");
|
||||
} else if (d == EyeFile::kNone) {
|
||||
nextLayoutCheck = now + 1.0;
|
||||
if (!missSince) missSince = now;
|
||||
if (now - missSince >= kUnknownAfter && now >= nextLayoutLog) {
|
||||
nextLayoutLog = now + 60.0;
|
||||
std::fprintf(stderr, "ft-gaze: eye-server.mmap has eye data, but its layout is not recognized: "
|
||||
"SteamVR's eye tracking is unavailable\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
const bool mmapOk = haveMmap && eyes.known;
|
||||
if (mmapOk && ReadSample(eyes, s) && s.n != lastN) fresh = true, lastN = s.n;
|
||||
if (!mmapOk && now - lastEmit >= 1.0 / 90) fresh = true, s.t = now;
|
||||
|
||||
if (fresh && hp.bPoseIsValid) {
|
||||
lastEmit = now;
|
||||
@@ -571,7 +695,7 @@ int main(int argc, char **argv) {
|
||||
const auto list = screens.Get();
|
||||
const vr::HmdMatrix34_t &headNow = hp.mDeviceToAbsoluteTracking;
|
||||
vr::HmdMatrix34_t headThen = headNow;
|
||||
if (haveMmap) history.At(s.t, headThen);
|
||||
if (mmapOk) history.At(s.t, headThen);
|
||||
|
||||
// SteamVR's action: a room-space origin and fixation point, turned into the head
|
||||
// frame so every source reports the same kind of angles.
|
||||
@@ -599,7 +723,8 @@ int main(int argc, char **argv) {
|
||||
}
|
||||
|
||||
std::string m1 = "{\"ok\":0}", m2 = m1, left = m1, right = m1, eye = "null";
|
||||
if (haveMmap) {
|
||||
// Only from a known layout: the unread sample's zeros would print an "unc" of 0 (eyes seen).
|
||||
if (mmapOk) {
|
||||
// lr: the angle between the two eyes' directions. It's a fraction of a degree
|
||||
// normally; when the tracker loses one eye (or during a blink) it jumps.
|
||||
auto lr = [](Vec3 l, Vec3 r) {
|
||||
|
||||
@@ -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__)
|
||||
|
||||
|
||||
+68
-20
@@ -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,11 +132,12 @@ 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]
|
||||
HELPER = REPO / "gaze" / "build" / "ft-gaze"
|
||||
IN_BOX = REPO / "scripts" / "in-box" # runs a program in the container it was built in
|
||||
ME = "\0ft_gazed"
|
||||
POINTER = "\0ft_pointer_helper"
|
||||
EYES_PROG = REPO / "gaze" / "tracker" / "ft-eyes" # our own tracker
|
||||
@@ -236,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,
|
||||
@@ -267,6 +274,7 @@ class Service:
|
||||
self.checks = Checks(self, self.sel)
|
||||
self.proc = None
|
||||
self.proc_sources = None # what ft-gaze was last told to print
|
||||
self.mmap_unknown = False # ft-gaze said SteamVR's eye-server.mmap has a layout it doesn't know
|
||||
self.buf = b""
|
||||
self.restart_at = 0.0
|
||||
self.running = True
|
||||
@@ -279,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 ---
|
||||
|
||||
@@ -290,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():
|
||||
@@ -498,19 +511,18 @@ class Service:
|
||||
return
|
||||
env = dict(os.environ)
|
||||
env["XDG_RUNTIME_DIR"] = f"/run/user/{os.getuid()}" # podman needs the real one
|
||||
subprocess.run([str(REPO / "scripts" / "container-up.sh")], env=env, check=False)
|
||||
distrobox = Path.home() / ".local" / "bin" / "distrobox"
|
||||
# ft-gaze quits when its stdin closes: the one thing distrobox passes on.
|
||||
sources = self.wanted_sources()
|
||||
self.proc = subprocess.Popen([str(distrobox), "enter", "dev", "--", str(HELPER), "--watch-stdin",
|
||||
"--sources", sources], env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, start_new_session=True)
|
||||
self.proc = subprocess.Popen([str(IN_BOX), str(HELPER), "--watch-stdin", "--sources", sources], env=env,
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
start_new_session=True)
|
||||
self.proc_sources = sources
|
||||
os.set_blocking(self.proc.stdout.fileno(), False)
|
||||
os.set_blocking(self.proc.stderr.fileno(), False)
|
||||
self.sel.register(self.proc.stdout, selectors.EVENT_READ, "stdout")
|
||||
self.sel.register(self.proc.stderr, selectors.EVENT_READ, "stderr")
|
||||
self.buf = b""
|
||||
self.mmap_unknown = False
|
||||
log("ft-gaze started")
|
||||
|
||||
def stop_helper(self):
|
||||
@@ -531,12 +543,13 @@ class Service:
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
self.proc = None
|
||||
self.mmap_unknown = False
|
||||
|
||||
def eyes_wanted(self):
|
||||
return (self.tracker == "own" and not self.override and self.awake) or time.monotonic() < self.eyes_until
|
||||
|
||||
def start_eyes(self):
|
||||
"""Our own tracker, in the dev container, with build/venv's numpy and OpenCV. Like
|
||||
"""Our own tracker, in the container, with build/venv's numpy and OpenCV. Like
|
||||
ft-gaze, it quits when its stdin closes."""
|
||||
if not EYES_PYTHON.exists():
|
||||
log(f"ft-eyes isn't built: run {REPO}/gaze/tracker/build.sh")
|
||||
@@ -544,11 +557,9 @@ class Service:
|
||||
return
|
||||
env = dict(os.environ)
|
||||
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"
|
||||
self.eyes_proc = subprocess.Popen([str(distrobox), "enter", "dev", "--", str(EYES_PYTHON), str(EYES_PROG), "-v",
|
||||
"--watch-stdin"], env=env, stdin=subprocess.PIPE,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, start_new_session=True)
|
||||
self.eyes_proc = subprocess.Popen([str(IN_BOX), str(EYES_PYTHON), str(EYES_PROG), "-v", "--watch-stdin"],
|
||||
env=env, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE, start_new_session=True)
|
||||
os.set_blocking(self.eyes_proc.stderr.fileno(), False)
|
||||
self.sel.register(self.eyes_proc.stderr, selectors.EVENT_READ, "eyes")
|
||||
log("ft-eyes started" + ("" if EYES_CAMS.exists() else
|
||||
@@ -613,6 +624,11 @@ class Service:
|
||||
for line in data.decode("utf-8", "replace").splitlines():
|
||||
if line.strip():
|
||||
log(line)
|
||||
# For the Gaze page (gazecheck's problem): ft-gaze can't read SteamVR's tracker.
|
||||
if "layout is not recognized" in line:
|
||||
self.mmap_unknown = True
|
||||
elif "eye-server.mmap layout:" in line:
|
||||
self.mmap_unknown = False
|
||||
|
||||
def judge_eyes(self, m1, down):
|
||||
"""Which eyes (left, right) are closed, from SteamVR's openness (set 1); updates
|
||||
@@ -633,11 +649,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:
|
||||
@@ -664,7 +686,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
|
||||
@@ -672,8 +695,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
|
||||
@@ -708,11 +737,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"]
|
||||
@@ -783,7 +828,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:
|
||||
@@ -899,6 +945,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
@@ -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"))
|
||||
|
||||
+194
-35
@@ -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)
|
||||
@@ -45,8 +46,23 @@ 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
|
||||
anyway ("blind"): someone in the headset (SteamVR's tracker sees an eye) and ft-eyes answering
|
||||
are enough to start it, each dot stands in for the gaze, and a click takes the CHECK_WINDOW up
|
||||
to it. ft-eyes then checks that each pupil was seen and held still in that window (calib-point)
|
||||
and says why not. Without this, a fresh install could never calibrate our tracker.
|
||||
|
||||
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:
|
||||
@@ -165,6 +181,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)."""
|
||||
@@ -232,6 +268,7 @@ 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
|
||||
|
||||
@property
|
||||
def active(self):
|
||||
@@ -246,8 +283,7 @@ class Checks:
|
||||
return
|
||||
env = dict(os.environ)
|
||||
env["XDG_RUNTIME_DIR"] = f"/run/user/{os.getuid()}"
|
||||
distrobox = Path.home() / ".local" / "bin" / "distrobox"
|
||||
self.panel_proc = subprocess.Popen([str(distrobox), "enter", "dev", "--", str(PANEL_PROG), "--watch-stdin"],
|
||||
self.panel_proc = subprocess.Popen([str(REPO / "scripts" / "in-box"), str(PANEL_PROG), "--watch-stdin"],
|
||||
env=env, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE, start_new_session=True)
|
||||
os.set_blocking(self.panel_proc.stderr.fileno(), False)
|
||||
@@ -318,6 +354,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):
|
||||
@@ -336,9 +414,17 @@ class Checks:
|
||||
return time.monotonic() - self.seen_at < within
|
||||
|
||||
def can_run(self):
|
||||
"""Someone's in the headset and the tracker is sending."""
|
||||
"""Someone's in the headset and the tracker is sending. Our tracker sends no gaze before
|
||||
its first calibration: then ft-eyes answering (calibrated() is False only once it has)
|
||||
is enough, since the calibration is what it needs (see "first calibration" at the top)."""
|
||||
if self.blind():
|
||||
return self.eyes_seen()
|
||||
return self.eyes_seen() and time.monotonic() - self.svc.last_sample < 2
|
||||
|
||||
def blind(self):
|
||||
"""Our tracker is in use, running, and not calibrated yet: it has no gaze to send."""
|
||||
return self.svc.kind == "own" and self.calibrated() is False
|
||||
|
||||
def on_gaze_on(self):
|
||||
self.full_armed = True
|
||||
self.need_full("gaze mode came on without a calibration")
|
||||
@@ -356,7 +442,7 @@ class Checks:
|
||||
if not self.can_run() and self.svc.waking():
|
||||
return # the tracker is still starting (the service idled)
|
||||
if not self.can_run():
|
||||
why = ("the eye tracker isn't sending" if now - self.svc.last_sample >= 2
|
||||
why = ("the eye tracker isn't sending" if now - self.svc.last_sample >= 2 and not self.blind()
|
||||
else "no eyes seen (is the headset on?)")
|
||||
elif now < self.full_retry_at:
|
||||
return
|
||||
@@ -374,7 +460,16 @@ class Checks:
|
||||
def problem(self):
|
||||
"""Why gaze mode, on, can't follow your eyes yet, or None. Our tracker not having said
|
||||
yet is None: Input Settings has its own line for our tracker."""
|
||||
if not self.gaze_on or self.calibrated() is not False:
|
||||
if not self.gaze_on:
|
||||
return None
|
||||
own = self.svc.kind == "own"
|
||||
if self.svc.mmap_unknown and (not own or self.calibrated() is False):
|
||||
# ft-gaze can't read SteamVR's tracker (EyeFile::Detect in ft-gaze.cpp): not its gaze,
|
||||
# and not the eyes it sees, which our tracker's calibration waits for.
|
||||
return ("SteamVR's eye data has a layout Frametop doesn't know (after a SteamOS update?), so "
|
||||
+ ("the calibration can't open" if own else "SteamVR's eye tracker can't be used")
|
||||
+ ". A newer Frametop may know it")
|
||||
if self.calibrated() is not False:
|
||||
return None
|
||||
if self.check and self.check["kind"] == "full":
|
||||
return "Not calibrated yet: the calibration is open in the headset"
|
||||
@@ -408,6 +503,9 @@ class Checks:
|
||||
if not self.can_run():
|
||||
return "error the headset is off or the tracker isn't sending"
|
||||
own = svc.kind == "own"
|
||||
blind = self.blind()
|
||||
if blind and kind != "full":
|
||||
return "error our tracker isn't calibrated yet: use Calibrate"
|
||||
if kind == "full" and own:
|
||||
reply = ask(EYES, "calib-start", 3.0)
|
||||
if not reply.startswith("ok"):
|
||||
@@ -416,15 +514,20 @@ class Checks:
|
||||
now = time.monotonic()
|
||||
self.check = {"kind": kind, "reason": reason, "own": own, "dots": check_dots(kind, own), "i": 0,
|
||||
"started": now, "shown": now, "run": [], "accept": False, "done_at": None, "tries": 0,
|
||||
"skipped": 0, "captured": 0, "points": {}, "reasons": {}, "fit_reasons": set(), "note": ""}
|
||||
log(f"{kind} check: {reason}")
|
||||
"skipped": 0, "captured": 0, "points": {}, "reasons": {}, "fit_reasons": set(), "note": "",
|
||||
"blind": blind}
|
||||
log(f"{kind} check: {reason}" + (" (our tracker's first: no gaze yet, so each click takes the look "
|
||||
"up to it)" if blind else ""))
|
||||
if kind == "full":
|
||||
st = ask(SCREENS, "state", 0.5).split()
|
||||
if len(st) >= 3 and st[0] == "ok":
|
||||
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
|
||||
@@ -435,9 +538,10 @@ 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}
|
||||
log(f"fit check: {reason}")
|
||||
self.to_helper("calpanel 1")
|
||||
self.to_panel("show fit")
|
||||
@@ -507,7 +611,8 @@ 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
|
||||
@@ -515,10 +620,16 @@ class Checks:
|
||||
if c and c["kind"] == "fit":
|
||||
c["fit"].feed(s, self.sample_at)
|
||||
return
|
||||
if not c or c["done_at"]:
|
||||
return
|
||||
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"]:
|
||||
# Our tracker's first calibration: no gaze yet, so the dot stands in for it (the
|
||||
# gaze can't seem to move) and a click takes the look up to it. ft-eyes checks
|
||||
# the pupils held still (see the top).
|
||||
yaw, pitch, _ = c["dots"][c["i"]]
|
||||
src = {"hy": yaw, "hp": pitch}
|
||||
else:
|
||||
src = s["src"].get("mmap1") or {}
|
||||
if "hy" not in src:
|
||||
@@ -578,9 +689,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)
|
||||
@@ -590,7 +704,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"):
|
||||
@@ -598,11 +713,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))
|
||||
@@ -622,9 +746,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
|
||||
@@ -636,9 +774,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")
|
||||
@@ -703,8 +841,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():
|
||||
@@ -727,6 +872,7 @@ class Checks:
|
||||
return
|
||||
if why:
|
||||
log(f"{self.check['kind']} check closed: {why}")
|
||||
self.drop_ask()
|
||||
self.to_panel("hide")
|
||||
self.to_helper("calpanel 0")
|
||||
if self.check["kind"] == "full" and self.screens_shown:
|
||||
@@ -736,8 +882,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.
|
||||
@@ -773,9 +919,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()
|
||||
@@ -786,10 +932,12 @@ 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: # (asking: this dot's click landed already)
|
||||
if not self.check["accept"]:
|
||||
self.check["accept_at"] = time.monotonic()
|
||||
self.check["accept"] = True
|
||||
@@ -827,6 +975,13 @@ class Checks:
|
||||
else:
|
||||
self.fit_tick(now)
|
||||
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()
|
||||
@@ -840,11 +995,11 @@ class Checks:
|
||||
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")
|
||||
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:
|
||||
self.close("ignored")
|
||||
elif c["kind"] != "quick" and now - c["shown"] > CLICK_IDLE:
|
||||
@@ -868,7 +1023,11 @@ class Checks:
|
||||
self.back_since = None # gone again before DON_DELAY
|
||||
elif self.back_since is not None and now - self.back_since >= DON_DELAY:
|
||||
self.away, self.back_since = False, None
|
||||
self.full_armed = True # a calibration that closed unfinished opens again
|
||||
if not self.check:
|
||||
# A calibration that closed unfinished opens again. Not one still open: gaze mode
|
||||
# coming on wakes our tracker, so its eyes come back just as the calibration
|
||||
# opens, and re-arming then opened a second one when the first ended.
|
||||
self.full_armed = True
|
||||
self.auto_quick("the headset went on")
|
||||
if svc.kind == "own" and now - svc.own_at < 5:
|
||||
reseat = any(e.get("reseat") for e in (svc.own.get("eyes") or {}).values())
|
||||
|
||||
@@ -7,14 +7,17 @@
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// 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 the panel, empty, in front of you
|
||||
// hide
|
||||
// bg <0..1> the background's brightness (full)
|
||||
// dot <yaw> <pitch> <state> [<progress 0..1>]
|
||||
@@ -71,7 +74,8 @@ 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 int kQuickPx = 320, kFullW = 1024, kFullH = 768, kFitW = 800, kFitH = 600, kFiveW = 800, kFiveH = 600;
|
||||
std::atomic<bool> g_stop{false};
|
||||
|
||||
// ---------------------------------------------------------------- text (as screens/keyboard.cpp)
|
||||
@@ -471,9 +475,10 @@ int main(int argc, char **argv) {
|
||||
if (!std::strncmp(buf, "show ", 5)) {
|
||||
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;
|
||||
const bool five = !std::strcmp(buf + 5, "five");
|
||||
p.w = p.full ? kFullW : p.fit ? kFitW : five ? kFiveW : kQuickPx;
|
||||
p.h = p.full ? kFullH : p.fit ? kFitH : five ? kFiveH : kQuickPx;
|
||||
p.wDeg = p.full ? kFullDeg : p.fit ? kFitDeg : five ? kFiveDeg : 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();
|
||||
place();
|
||||
|
||||
@@ -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)
|
||||
@@ -203,7 +202,7 @@ class GazeReader:
|
||||
return
|
||||
print(line, file=sys.stderr)
|
||||
text = line.removeprefix("ft-gaze: ")
|
||||
if not text.startswith(("action manifest", "eye-server.mmap open")):
|
||||
if not text.startswith(("action manifest", "eye-server.mmap open", "eye-server.mmap layout:")):
|
||||
self.last_err = text # worth repeating if ft-gaze stops (not the startup lines)
|
||||
self.on_status(text)
|
||||
stream.read_line_async(GLib.PRIORITY_DEFAULT, self.cancel, got)
|
||||
|
||||
+8
-4
@@ -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)
|
||||
@@ -9,12 +10,15 @@ frame="$root/scripts/frame.sh"
|
||||
unit=frametop-gaze.service
|
||||
case ${1:-status} in
|
||||
install)
|
||||
"$root/gaze/build.sh"
|
||||
[ "$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}" ;;
|
||||
|
||||
Executable
+138
@@ -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)
|
||||
Executable
+293
@@ -0,0 +1,293 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline test of our own eye tracker's first calibration (gaze/gazecheck.py, "blind"): before
|
||||
it has a calibration, ft-eyes publishes no gaze, and the calibration must still open and take
|
||||
its dots. Until 2026-10-05 it couldn't: a fresh install that chose our tracker never calibrated.
|
||||
|
||||
Runs ft-gazed's Service with its sockets renamed and HOME in a temp folder (state and settings
|
||||
go there), a fake pointer helper (gaze mode on, headset worn), a fake ft-gaze (SteamVR sees both
|
||||
eyes; "own" is {"ok":0}, as with an uncalibrated ft-eyes), a fake ft-eyes control socket, and no
|
||||
panel (a stand-in process). 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
|
||||
"""
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
HOME = tempfile.mkdtemp(prefix="ft-gaze-first-cal-test-")
|
||||
os.environ["HOME"] = HOME # before gazecal: its STATE, and frametop.conf, follow HOME
|
||||
|
||||
import importlib.machinery # noqa: E402
|
||||
import importlib.util # noqa: E402
|
||||
import json # noqa: E402
|
||||
import selectors # noqa: E402
|
||||
import shutil # noqa: E402
|
||||
import socket # noqa: E402
|
||||
import subprocess # noqa: E402
|
||||
import sys # noqa: E402
|
||||
import threading # noqa: E402
|
||||
import time # noqa: E402
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
GAZE = os.path.join(HERE, "..")
|
||||
sys.path.insert(0, GAZE)
|
||||
loader = importlib.machinery.SourceFileLoader("ftgazed", os.path.join(GAZE, "ft-gazed"))
|
||||
gazed = importlib.util.module_from_spec(importlib.util.spec_from_loader("ftgazed", loader))
|
||||
loader.exec_module(gazed)
|
||||
import gazecheck # noqa: E402 (the module ft-gazed imported)
|
||||
|
||||
tag = f"ft_gaze_first_cal_test_{os.getpid()}"
|
||||
gazed.ME = f"\0{tag}_gazed"
|
||||
gazed.POINTER = gazecheck.POINTER = f"\0{tag}_helper"
|
||||
gazecheck.SCREENS = f"\0{tag}_screens"
|
||||
gazecheck.PANEL = f"\0{tag}_panel"
|
||||
gazed.EYES_SOCKET = gazecheck.EYES = f"\0{tag}_eyes"
|
||||
gazed.read_settings = lambda: ("own", "auto", "auto", 55.0)
|
||||
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 = []
|
||||
gazed.log = gazecheck.log = lambda msg: logs.append(msg)
|
||||
|
||||
# The fake ft-gaze: 90 samples a second, SteamVR sees both eyes, no gaze from ours.
|
||||
FAKE = os.path.join(HOME, "ft-gaze")
|
||||
with open(FAKE, "w") as f:
|
||||
f.write('''import json, os, select, sys, time
|
||||
while True:
|
||||
if select.select([sys.stdin], [], [], 1 / 90)[0]:
|
||||
if not os.read(0, 4096):
|
||||
break
|
||||
print(json.dumps({"t": time.monotonic(), "src": {"mmap1": {"hy": 1.0, "hp": 2.0, "unc": [0.001, 0.001],
|
||||
"open": [0.8, 0.8]}, "own": {"ok": 0}}}), flush=True)
|
||||
''')
|
||||
SLEEPER = [sys.executable, "-c", "import sys; sys.stdin.read()"] # quits when its stdin closes
|
||||
|
||||
|
||||
def start_helper(self):
|
||||
"""ft-gaze, straight from here instead of the dev container."""
|
||||
self.proc = subprocess.Popen([sys.executable, FAKE], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE)
|
||||
self.proc_sources = self.wanted_sources()
|
||||
os.set_blocking(self.proc.stdout.fileno(), False)
|
||||
os.set_blocking(self.proc.stderr.fileno(), False)
|
||||
self.sel.register(self.proc.stdout, selectors.EVENT_READ, "stdout")
|
||||
self.sel.register(self.proc.stderr, selectors.EVENT_READ, "stderr")
|
||||
self.buf = b""
|
||||
|
||||
|
||||
def start_eyes(self):
|
||||
"""ft-eyes' process: a stand-in. Its control socket is the fake below."""
|
||||
self.eyes_proc = subprocess.Popen(SLEEPER, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
os.set_blocking(self.eyes_proc.stderr.fileno(), False)
|
||||
self.sel.register(self.eyes_proc.stderr, selectors.EVENT_READ, "eyes")
|
||||
|
||||
|
||||
def start_panel(self):
|
||||
self.panel_proc = subprocess.Popen(SLEEPER, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
os.set_blocking(self.panel_proc.stderr.fileno(), False)
|
||||
self.sel.register(self.panel_proc.stderr, selectors.EVENT_READ, "panel")
|
||||
|
||||
|
||||
gazed.Service.start_helper = start_helper
|
||||
gazed.Service.start_eyes = start_eyes
|
||||
gazecheck.Checks.start_panel = start_panel
|
||||
|
||||
# The fake ft-eyes: uncalibrated until calib-fit. "fail" answers the next calib-point with that;
|
||||
# "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)
|
||||
|
||||
|
||||
def eyes_answer():
|
||||
while True:
|
||||
try:
|
||||
data, addr = eyes.recvfrom(512)
|
||||
except socket.timeout:
|
||||
continue
|
||||
except OSError:
|
||||
return
|
||||
w = data.decode().split()
|
||||
if w[0] == "status":
|
||||
reply = json.dumps({"calibration": eyes_state["cal"], "calibrating": False, "dots": 0,
|
||||
"eyes": {"right": {"reseat": False}, "left": {"reseat": False}}})
|
||||
elif w[0] == "calib-start":
|
||||
eyes_state["points"] = []
|
||||
reply = "ok"
|
||||
elif w[0] == "calib-point":
|
||||
eyes_state["points"].append(tuple(map(float, w[1:5])))
|
||||
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 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": [], "calpanel": []} # calpanel: when "calpanel 1" came
|
||||
helper = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
|
||||
helper.bind(gazed.POINTER)
|
||||
helper.settimeout(0.2)
|
||||
|
||||
|
||||
def helper_answer():
|
||||
while True:
|
||||
try:
|
||||
data, addr = helper.recvfrom(512)
|
||||
except socket.timeout:
|
||||
continue
|
||||
except OSError:
|
||||
return
|
||||
if data.startswith(b"gaze ?") and addr:
|
||||
helper.sendto(helper_state["reply"].encode(), addr)
|
||||
else:
|
||||
helper_state["heard"].append(data.decode())
|
||||
if data == b"calpanel 1":
|
||||
helper_state["calpanel"].append(time.monotonic())
|
||||
|
||||
|
||||
threading.Thread(target=helper_answer, daemon=True).start()
|
||||
svc = gazed.Service(None, False, gazed.POINTER)
|
||||
threading.Thread(target=svc.run, daemon=True).start()
|
||||
ctl = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
|
||||
ctl.bind("")
|
||||
ctl.settimeout(3)
|
||||
|
||||
|
||||
def ask(cmd):
|
||||
ctl.sendto(cmd.encode(), gazed.ME)
|
||||
return ctl.recv(65536).decode()
|
||||
|
||||
|
||||
failures = []
|
||||
|
||||
|
||||
def check(label, got, want):
|
||||
ok = got == want
|
||||
print(("ok " if ok else "FAIL ") + label + ("" if ok else f": got {got!r}, want {want!r}"), flush=True)
|
||||
if not ok:
|
||||
failures.append(label)
|
||||
|
||||
|
||||
def wait(cond, seconds):
|
||||
end = time.monotonic() + seconds
|
||||
while time.monotonic() < end:
|
||||
if cond():
|
||||
return True
|
||||
time.sleep(0.05)
|
||||
return cond()
|
||||
|
||||
|
||||
def check_state():
|
||||
return svc.checks.check or {}
|
||||
|
||||
|
||||
def take_dot(i):
|
||||
"""Wait for dot i to settle, then click: is it taken?"""
|
||||
wait(lambda: check_state().get("i") == i and not check_state().get("done_at"), 3)
|
||||
time.sleep(gazecheck.CHECK_SETTLE + gazecheck.CHECK_WINDOW + 0.1)
|
||||
before = check_state().get("captured", 0)
|
||||
ask("calaccept")
|
||||
return wait(lambda: check_state().get("captured", 0) > before, 2)
|
||||
|
||||
|
||||
check("gaze mode off, Gaze page open (wake): ours runs, uncalibrated", ask("wake 60"), "ok")
|
||||
check("the service knows ours has no calibration", wait(lambda: svc.checks.calibrated() is False, 6), True)
|
||||
# ft-eyes' status can come before the fake ft-gaze's first sample, and without one the refusal
|
||||
# below is "the headset is off" instead (failed about 1 run in 4 until 2026-10-06).
|
||||
check("SteamVR sees the eyes (the fake ft-gaze is sending)", wait(svc.checks.eyes_seen, 6), True)
|
||||
check("a quick check is refused while ours has no calibration", svc.checks.start("quick", "test"),
|
||||
"error our tracker isn't calibrated yet: use Calibrate")
|
||||
helper_state["reply"] = "ok on worn"
|
||||
check("gaze mode on: the calibration opens by itself", wait(lambda: check_state().get("kind") == "full", 6), True)
|
||||
check("it runs blind (no gaze from ours yet)", check_state().get("blind"), True)
|
||||
check("nothing says it can't open", any("can't open" in m for m in logs), False)
|
||||
# Live 2026-10-05: turning gaze mode on woke our tracker, and the calibration opened before
|
||||
# DON_DELAY of eyes had passed, so "the headset went on" came while it was open. That re-armed
|
||||
# it, and a second calibration opened as soon as the first ended.
|
||||
svc.checks.away, svc.checks.back_since = True, None
|
||||
|
||||
check("dot 1: a click takes it", take_dot(0), True)
|
||||
check("the headset went on while it was open",
|
||||
wait(lambda: not svc.checks.away, gazecheck.DON_DELAY + 2) and bool(svc.checks.check), True)
|
||||
t0, t1, yaw, pitch = eyes_state["points"][0]
|
||||
dot = gazecheck.check_dots("full", True)[0]
|
||||
check("its window is the look up to the click (about CHECK_WINDOW)",
|
||||
abs((t1 - t0) - gazecheck.CHECK_WINDOW) < 0.15, True)
|
||||
check("ft-eyes got that dot's direction", (round(yaw, 3), round(pitch, 3)), (round(dot[0], 3), round(dot[1], 3)))
|
||||
|
||||
eyes_state["fail"] = "fail the left eye was seen in only 3 frames"
|
||||
wait(lambda: check_state().get("i") == 1 and not check_state().get("done_at"), 3)
|
||||
time.sleep(gazecheck.CHECK_SETTLE + gazecheck.CHECK_WINDOW + 0.1)
|
||||
ask("calaccept")
|
||||
check("ft-eyes refusing a dot: its reason reaches the panel's note",
|
||||
wait(lambda: "left eye in only 3 frames" in check_state().get("note", ""), 2), True)
|
||||
check("dot 2, second try: taken", take_dot(1), True)
|
||||
|
||||
# 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, 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)
|
||||
check("one calibration in the log", sum(m.startswith("full check:") for m in logs), 1)
|
||||
|
||||
print("FAILED: " + ", ".join(failures) if failures else "all passed", flush=True)
|
||||
svc.running = False
|
||||
time.sleep(0.7)
|
||||
shutil.rmtree(HOME, ignore_errors=True)
|
||||
os._exit(1 if failures else 0)
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
// Offline test of ft-gaze's eye-server.mmap layout detection (EyeFile::Detect in
|
||||
// gaze/ft-gaze.cpp) and of reading a sample at the layout it found, on a made-up file in
|
||||
// memory: no SteamVR, no eye tracker. Detect takes the time as an argument, so the passes
|
||||
// of ft-gaze's loop are played here with a made-up clock. mmap-layout-test.sh builds and
|
||||
// runs it in the dev container.
|
||||
#define main ft_gaze_main
|
||||
#include "../ft-gaze.cpp"
|
||||
#undef main
|
||||
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
int failures = 0;
|
||||
#define CHECK(c) \
|
||||
do { \
|
||||
if (!(c)) std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c), ++failures; \
|
||||
} 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 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;
|
||||
uint32_t n = 0;
|
||||
File() { eyes.p = bytes.data(), eyes.size = bytes.size(); }
|
||||
template <class T> void Put(size_t off, const T &v) { std::memcpy(bytes.data() + off, &v, sizeof v); }
|
||||
void Sample(size_t shift, double t, bool leftLost = false) {
|
||||
const float left[3] = {0.05f, 0.02f, -0.9985f}, right[3] = {-0.05f, 0.02f, -0.9985f}, none[3] = {};
|
||||
Put(kCounter, ++n);
|
||||
Put(kTime + shift, t);
|
||||
Put(kLeft1 + shift, leftLost ? none : left);
|
||||
Put(kRight1 + shift, right);
|
||||
Put(kLeft2 + shift, left);
|
||||
Put(kRight2 + shift, right);
|
||||
const float open[2] = {0.8f, 0.7f}, var[6] = {1e-3f, 2e-3f, 3e-3f, 4e-3f, 5e-3f, 6e-3f};
|
||||
const float meas[8] = {0.1f, 0.2f, 0.3f, 0.4f, 2e-5f, 3e-5f, 4e-5f, 5e-5f}, fix[3] = {0, 0.02f, -0.6f};
|
||||
Put(kFix1 + shift, fix);
|
||||
Put(kVar1 + shift, var);
|
||||
Put(kVar2 + shift, var);
|
||||
Put(kOpen + shift, open);
|
||||
Put(kMeas + shift, meas);
|
||||
}
|
||||
};
|
||||
|
||||
constexpr double kStart = 5000; // the made-up CLOCK_MONOTONIC_RAW at the first pass
|
||||
constexpr double kPass = 0.004; // ft-gaze's loop
|
||||
constexpr double kAge = 0.017; // how old a sample is when it appears
|
||||
|
||||
// Samples every 1/hz s in `shift`'s layout, Detect called on every loop pass from the first
|
||||
// sample on (as ft-gaze does once the counter moved), until it decides or `until` s pass.
|
||||
// Returns the outcome and when (s after the first sample) in `at`.
|
||||
EyeFile::Detection Run(File &f, size_t shift, double hz, double until, double &at) {
|
||||
double next = kStart;
|
||||
for (double now = kStart; now < kStart + until; now += kPass) {
|
||||
if (now >= next) f.Sample(shift, now - kAge), next += 1 / hz;
|
||||
const EyeFile::Detection d = f.eyes.Detect(now);
|
||||
if (d != EyeFile::kWaiting) {
|
||||
at = now - kStart;
|
||||
return d;
|
||||
}
|
||||
}
|
||||
at = until;
|
||||
return EyeFile::kWaiting;
|
||||
}
|
||||
|
||||
void Layouts() {
|
||||
for (const size_t shift : {size_t(0), size_t(5)}) {
|
||||
File f;
|
||||
double at;
|
||||
CHECK(Run(f, shift, 90, 2, at) == EyeFile::kFound);
|
||||
CHECK(f.eyes.known && f.eyes.shift == shift);
|
||||
CHECK(at <= 1 / 90.0 + kPass); // the next sample confirms it
|
||||
}
|
||||
}
|
||||
|
||||
void SlowWriters() {
|
||||
// 15 a second, as seen on the beta: the next sample, 67 ms on, confirms it (PR #26's
|
||||
// fixed 60 ms wait missed about 1 try in 10 there).
|
||||
File beta;
|
||||
double at;
|
||||
CHECK(Run(beta, 5, 15, 2, at) == EyeFile::kFound && beta.eyes.shift == 5);
|
||||
CHECK(at > 1 / 15.0 - kPass && at <= 1 / 15.0 + kPass);
|
||||
// 3 a second still works (within kConfirm); 1 a second can't confirm in time.
|
||||
File slow;
|
||||
CHECK(Run(slow, 0, 3, 2, at) == EyeFile::kFound && slow.eyes.shift == 0);
|
||||
File slower;
|
||||
CHECK(Run(slower, 0, 1, 2, at) == EyeFile::kNone && !slower.eyes.known);
|
||||
CHECK(at > EyeFile::kConfirm && at < EyeFile::kConfirm + 2 * kPass);
|
||||
CHECK(!slower.eyes.Detecting()); // and the next try starts over
|
||||
}
|
||||
|
||||
void Refused() {
|
||||
// A layout we don't know: the same fields, moved by some other amount.
|
||||
for (size_t shift = 1; shift <= 16; ++shift) {
|
||||
if (shift == 5) continue;
|
||||
File f;
|
||||
double at;
|
||||
const EyeFile::Detection d = Run(f, shift, 90, 1, at);
|
||||
CHECK(d == EyeFile::kNone && !f.eyes.known);
|
||||
if (d != EyeFile::kNone) std::printf(" (moved by %zu)\n", shift);
|
||||
}
|
||||
// A server that stopped: its last sample is 10 s old. Refused at once, no waiting.
|
||||
File stale;
|
||||
stale.Sample(0, kStart - 10);
|
||||
CHECK(stale.eyes.Detect(kStart) == EyeFile::kNone && !stale.eyes.Detecting());
|
||||
// One that stopped just now: its timestamp fits but never moves on.
|
||||
File stopped;
|
||||
stopped.Sample(0, kStart - kAge);
|
||||
CHECK(stopped.eyes.Detect(kStart) == EyeFile::kWaiting);
|
||||
EyeFile::Detection d = EyeFile::kWaiting;
|
||||
double now = kStart;
|
||||
while (d == EyeFile::kWaiting && now < kStart + 2) d = stopped.eyes.Detect(now += kPass);
|
||||
CHECK(d == EyeFile::kNone && !stopped.eyes.known);
|
||||
// A set-1 direction that isn't a unit vector (here zeros).
|
||||
File warm;
|
||||
warm.Sample(0, kStart - kAge, true);
|
||||
CHECK(warm.eyes.Detect(kStart) == EyeFile::kNone);
|
||||
// An empty file (the server never wrote).
|
||||
File empty;
|
||||
CHECK(empty.eyes.Detect(kStart) == EyeFile::kNone);
|
||||
}
|
||||
|
||||
void TornWrite() {
|
||||
// A pass that reads the timestamp mid-write (the counter already moved on, the top half
|
||||
// of the new timestamp not written yet, so it's nowhere near the clock) keeps waiting:
|
||||
// the next pass confirms it.
|
||||
File f;
|
||||
f.Sample(0, kStart - kAge);
|
||||
CHECK(f.eyes.Detect(kStart) == EyeFile::kWaiting);
|
||||
const double next = kStart + 0.011 - kAge;
|
||||
std::memcpy(f.bytes.data() + kTime, &next, 4);
|
||||
std::memset(f.bytes.data() + kTime + 4, 0, 4);
|
||||
f.Put(kCounter, ++f.n);
|
||||
CHECK(f.eyes.Detect(kStart + 0.012) == EyeFile::kWaiting);
|
||||
f.Put(kTime, next);
|
||||
CHECK(f.eyes.Detect(kStart + 0.016) == EyeFile::kFound && f.eyes.shift == 0);
|
||||
}
|
||||
|
||||
void ReadsTheLayoutFound() {
|
||||
// After detection on the beta, a sample comes from the moved fields.
|
||||
File f;
|
||||
double at;
|
||||
CHECK(Run(f, 5, 90, 1, at) == EyeFile::kFound && f.eyes.shift == 5);
|
||||
f.Sample(5, kStart + 1);
|
||||
EyeSample s;
|
||||
CHECK(ReadSample(f.eyes, s));
|
||||
CHECK(s.n == f.n && s.t == kStart + 1);
|
||||
CHECK(std::fabs(s.left1.x - 0.05) < 1e-6 && std::fabs(s.right2.x + 0.05) < 1e-6);
|
||||
CHECK(std::fabs(s.fix1.z + 0.6) < 1e-6);
|
||||
CHECK(s.open[0] == 0.8f && s.open[1] == 0.7f);
|
||||
CHECK(s.var1[5] == 6e-3f && s.var2[0] == 1e-3f && s.meas[3] == 0.4f && s.meas[7] == 5e-5f);
|
||||
}
|
||||
|
||||
void NoMapping() {
|
||||
// ft-gaze without the file: the loop's one read of it gives 0, and touches no memory.
|
||||
EyeFile none;
|
||||
CHECK(none.Counter() == 0);
|
||||
File f;
|
||||
f.Sample(0, kStart);
|
||||
CHECK(f.eyes.Counter() == f.n);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
Layouts();
|
||||
SlowWriters();
|
||||
Refused();
|
||||
TornWrite();
|
||||
ReadsTheLayoutFound();
|
||||
NoMapping();
|
||||
if (failures) {
|
||||
std::printf("%d failed\n", failures);
|
||||
return 1;
|
||||
}
|
||||
std::printf("all passed\n");
|
||||
return 0;
|
||||
}
|
||||
Executable
+16
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
# Offline test of ft-gaze's eye-server.mmap layout detection (gaze/test/mmap-layout-test.cpp):
|
||||
# builds it against gaze/ft-gaze.cpp in the dev container and runs it there. Nothing reaches
|
||||
# SteamVR or the eye tracker, so it's safe next to them. gaze/build.sh fetches the OpenVR
|
||||
# header it needs, so run that once first.
|
||||
#
|
||||
# gaze/test/mmap-layout-test.sh
|
||||
set -euo pipefail
|
||||
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
"$root/scripts/sync.sh" >/dev/null
|
||||
exec "$root/scripts/frame.sh" -C gaze 'set -e
|
||||
[ -f build/include/openvr.h ] || { echo "no build/include/openvr.h: run gaze/build.sh first" >&2; exit 1; }
|
||||
g++ -std=c++17 -O2 -Wall -Wno-unused-parameter -Wno-missing-field-initializers -Ibuild/include -I../pointer/common \
|
||||
-o build/mmap-layout-test test/mmap-layout-test.cpp -L/opt/steamvr/bin/linuxarm64 -lopenvr_api \
|
||||
-Wl,-rpath,/opt/steamvr/bin/linuxarm64 -lpthread
|
||||
build/mmap-layout-test'
|
||||
Executable
+175
@@ -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)
|
||||
@@ -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
|
||||
+11
-3
@@ -4,7 +4,9 @@
|
||||
# (frametop-eyegrab.service, gaze/tracker/install.sh), so this checks it
|
||||
# only needs glibc symbols the SteamOS host has (2.39; the container has 2.43).
|
||||
# build/venv Python with numpy and OpenCV (requirements.txt) for ft-eyes and lab/,
|
||||
# remade when requirements.txt changes.
|
||||
# remade when requirements.txt changes. In the image (pack/Containerfile)
|
||||
# they're in its locked venv already (uv.lock has the same versions), so
|
||||
# build/venv is a small venv that sees that one's packages, not a copy.
|
||||
# Usage: gaze/tracker/build.sh
|
||||
set -euo pipefail
|
||||
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
@@ -14,10 +16,16 @@ gcc -std=gnu11 -O2 -Wall -Wextra -pthread -o build/ft-eyegrab ft-eyegrab.c
|
||||
max=$(objdump -T build/ft-eyegrab | grep -oE "GLIBC_[0-9.]+" | sort -uV | tail -1)
|
||||
echo "built build/ft-eyegrab, newest glibc symbol: $max"
|
||||
[ "$(printf "%s\n" "$max" GLIBC_2.39 | sort -V | tail -1)" = GLIBC_2.39 ] || { echo "needs newer glibc than the host has" >&2; exit 1; }
|
||||
if ! cmp -s requirements.txt build/venv/requirements.done; then
|
||||
if [ "${FRAME_IN_BOX:-0}" = 1 ] && [ -x /opt/frametop/venv/bin/python ]; then
|
||||
rm -rf build/venv
|
||||
python3 -m venv --without-pip build/venv
|
||||
/opt/frametop/venv/bin/python -c "import sysconfig; print(sysconfig.get_path(\"purelib\"))" \
|
||||
>"$(build/venv/bin/python -c "import sysconfig; print(sysconfig.get_path(\"purelib\"))")/frametop-image.pth"
|
||||
elif ! cmp -s requirements.txt build/venv/requirements.done; then
|
||||
rm -rf build/venv
|
||||
python3 -m venv build/venv
|
||||
build/venv/bin/pip install -q --disable-pip-version-check -r requirements.txt
|
||||
cp requirements.txt build/venv/requirements.done
|
||||
fi
|
||||
echo "build/venv: $(build/venv/bin/python -c "import numpy, cv2; print(\"numpy\", numpy.__version__, \"opencv\", cv2.__version__)")"'
|
||||
v=$(build/venv/bin/python -c "import numpy, cv2; print(\"numpy\", numpy.__version__, \"opencv\", cv2.__version__)")
|
||||
echo "build/venv: $v"'
|
||||
@@ -111,6 +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 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 |
|
||||
| --- | --- |
|
||||
|
||||
@@ -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]]
|
||||
@@ -20,13 +21,14 @@ sudo_run() { frame_sudo "$1"; }
|
||||
|
||||
case ${1:-install} in
|
||||
install)
|
||||
"$root/gaze/tracker/build.sh"
|
||||
[ "$FRAME_RELEASE" = 1 ] || "$root/gaze/tracker/build.sh"
|
||||
ids=$(on_frame 'echo "$(id -u):$(id -g)"')
|
||||
fill_template "$root/gaze/tracker/$unit" | sed "s|@UID@|${ids%:*}|g; s|@GID@|${ids#*:}|g" |
|
||||
on_frame "cat > /tmp/$unit"
|
||||
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}" ;;
|
||||
|
||||
@@ -2,44 +2,151 @@
|
||||
# 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.
|
||||
# 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
|
||||
# installs without building anything (pack/README.md, Releases). The same zip installs with
|
||||
# FrameDrop from a PC, or unpacked by hand on the headset.
|
||||
# Options (piped, they go after "bash -s --"):
|
||||
# --stable the main branch: tested releases (the default for a new install)
|
||||
# --experimental the experimental branch: the newest features, less tested
|
||||
# --dir DIR where the repo goes (default ~/frametop)
|
||||
# --clone-only get or update the repo, but don't run install.sh
|
||||
# --yes, --no-bluetooth passed to install.sh (--yes also answers this script's question:
|
||||
# the version already there, or stable)
|
||||
# --branch NAME another branch, such as a fix to test before it's released
|
||||
# --dir DIR where the repo goes (default ~/frametop; for --release, where the
|
||||
# releases go, default ~/.local/share/frametop/releases)
|
||||
# --clone-only get or update the repo (or unpack the release), but don't run install.sh
|
||||
# --release install a release from GitHub instead of cloning the repo
|
||||
# --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-voice, --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] [--dir DIR] [--clone-only] [--yes] [--no-bluetooth]
|
||||
piped: curl -fsSL https://deejanuz.github.io/frametop/get.sh | bash -s -- [options]
|
||||
usage: get.sh [--stable | --experimental | --branch NAME] [--dir DIR] [--clone-only] [--yes]
|
||||
[--no-voice] [--no-eye-tracker] [--no-bluetooth | --bluetooth]
|
||||
get.sh --release [--stable | --experimental | --version V | --zip FILE|URL]
|
||||
[--any-steamos] [--dir DIR] [--clone-only] [--yes] [--no-voice] [--no-eye-tracker]
|
||||
[--no-bluetooth | --bluetooth]
|
||||
piped: curl -fsSL https://frametop.github.io/frametop/get.sh | bash -s -- [options]
|
||||
EOF
|
||||
}
|
||||
|
||||
# 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() {
|
||||
if [ -n "$2" ]; then
|
||||
echo "https://github.com/$SLUG/releases/download/v$2/Frametop.zip"
|
||||
elif [ "$1" = stable ]; then
|
||||
echo "https://github.com/$SLUG/releases/latest/download/Frametop.zip" # newest non-prerelease
|
||||
else
|
||||
curl -fsSL "https://api.github.com/repos/$SLUG/releases?per_page=30" | python3 -c '
|
||||
import json, sys
|
||||
for r in json.load(sys.stdin): # newest first
|
||||
for a in r.get("assets", []):
|
||||
if a.get("name") == "Frametop.zip" and not r.get("draft"):
|
||||
print(a["browser_download_url"])
|
||||
sys.exit(0)
|
||||
sys.exit(1)'
|
||||
fi
|
||||
}
|
||||
|
||||
# install_release CHANNEL VERSION ZIP DIR CLONE_ONLY ANY_STEAMOS -- INSTALL_ARGS...
|
||||
install_release() {
|
||||
local channel=$1 version=$2 zip=$3 dir=$4 clone_only=$5 any=$6 cache=$HOME/.cache/frametop/release
|
||||
shift 7
|
||||
local args=("$@")
|
||||
[ -n "$dir" ] && args+=(--dir "$dir")
|
||||
[ "$clone_only" = 1 ] && args+=(--unpack-only)
|
||||
[ "$any" = 1 ] && args+=(--any-steamos)
|
||||
mkdir -p "$cache"
|
||||
local url= file loc key status=0
|
||||
case $zip in
|
||||
https://*|'')
|
||||
url=$zip
|
||||
if [ -z "$url" ]; then
|
||||
url=$(release_zip "$channel" "$version") ||
|
||||
{ echo "couldn't find a Frametop release on GitHub (or GitHub can't be reached)" >&2; return 1; }
|
||||
fi
|
||||
# "latest" names a different file after each release: resume only the same release's.
|
||||
if [[ $url == */releases/latest/download/* ]]; then
|
||||
loc=$(curl -fsSI --proto '=https' "$url" | tr -d '\r' | sed -n 's/^[Ll]ocation: //p' | head -1)
|
||||
[[ $loc == https://github.com/* ]] && url=$loc
|
||||
fi
|
||||
key=$(printf %s "$url" | sha256sum | cut -c1-16)
|
||||
file=$cache/Frametop-$key.zip
|
||||
find "$cache" -maxdepth 1 -name 'Frametop-*.zip*' ! -name "Frametop-$key.zip*" -delete
|
||||
if [ ! -f "$file" ]; then
|
||||
echo "Downloading $url (about 1.1 GB; if it stops, run this again to resume)"
|
||||
curl -fL --proto '=https' -C - -o "$file.part" "$url" ||
|
||||
{ echo "the download didn't finish: run this again to resume it" >&2; return 1; }
|
||||
mv "$file.part" "$file"
|
||||
fi ;;
|
||||
*://*) echo "the zip has to come over https: $zip" >&2; return 1 ;;
|
||||
*) file=$zip; [ -f "$file" ] || { echo "no file $file" >&2; return 1; } ;;
|
||||
esac
|
||||
echo "Unpacking $file"
|
||||
rm -rf "$cache/unpacked"
|
||||
if ! unzip -q "$file" -d "$cache/unpacked"; then
|
||||
[ -n "$url" ] && rm -f "$file"
|
||||
echo "$file didn't unpack: run this again to download it again" >&2
|
||||
return 1
|
||||
fi
|
||||
"$cache/unpacked/Frametop/install-release.sh" "${args[@]}" || status=$?
|
||||
rm -rf "$cache/unpacked"
|
||||
if [ "$status" = 3 ] && [ -n "$url" ]; then
|
||||
rm -f "$file" # damaged: the next run downloads it again
|
||||
fi
|
||||
[ "$status" = 0 ] || return "$status"
|
||||
# Loaded into podman and copied out: the download isn't needed any more.
|
||||
[ "$clone_only" = 1 ] || rm -rf "$cache"
|
||||
}
|
||||
|
||||
# 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=$HOME/frametop branch= clone_only=0
|
||||
local yes=0 tty=0 current= def answer
|
||||
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
|
||||
case $1 in
|
||||
--stable) branch=main ;;
|
||||
--experimental) branch=experimental ;;
|
||||
--branch) branch=${2:?--branch needs a branch name}; shift ;;
|
||||
--dir) dir=${2:?--dir needs a folder}; shift ;;
|
||||
--clone-only) clone_only=1 ;;
|
||||
--release) release=1 ;;
|
||||
--zip) zip=${2:?--zip needs a file or URL}; shift ;;
|
||||
--version) want=${2:?--version needs a version}; shift ;;
|
||||
--any-steamos) any=1 ;;
|
||||
--yes) yes=1; pass+=("$1") ;;
|
||||
--no-bluetooth) pass+=("$1") ;;
|
||||
--no-bluetooth|--bluetooth|--no-eye-tracker|--no-voice) pass+=("$1") ;;
|
||||
-h|--help) usage; return 0 ;;
|
||||
*) echo "unknown option: $1" >&2; usage >&2; return 2 ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
if [ "$release" = 0 ] && { [ -n "$zip" ] || [ -n "$want" ] || [ "$any" = 1 ]; }; then
|
||||
echo "--zip, --version, and --any-steamos go with --release" >&2
|
||||
return 2
|
||||
fi
|
||||
if [ "$release" = 1 ] && [ -n "$branch" ] && [ "$branch" != main ] && [ "$branch" != experimental ]; then
|
||||
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
|
||||
|
||||
if ! { grep -qx 'ID=steamos' /etc/os-release && grep -qE '^VARIANT_ID="?vr"?$' /etc/os-release; } 2>/dev/null; then
|
||||
echo "Frametop installs on a Steam Frame (SteamOS, VR variant). Run this in a terminal on the headset." >&2
|
||||
@@ -52,16 +159,19 @@ main() {
|
||||
return 1
|
||||
fi
|
||||
|
||||
if [ -e "$dir/.git" ]; then
|
||||
if [ "$release" = 0 ] && [ -e "$dir/.git" ]; then
|
||||
git -C "$dir" remote get-url origin 2>/dev/null | grep -qi 'frametop' ||
|
||||
{ echo "$dir is a git repo, but not Frametop's. Pick another folder with --dir." >&2; return 1; }
|
||||
current=$(git -C "$dir" branch --show-current)
|
||||
elif [ -e "$dir" ]; then
|
||||
elif [ "$release" = 0 ] && [ -e "$dir" ]; then
|
||||
echo "$dir is there and isn't Frametop's repo. Move it, or pick another folder with --dir." >&2
|
||||
return 1
|
||||
elif [ "$release" = 1 ] && [ -f "${dir:-$HOME/.local/share/frametop/releases}/current/.frametop-release" ]; then
|
||||
current=$(sed -n 's/^CHANNEL=//p' "${dir:-$HOME/.local/share/frametop/releases}/current/.frametop-release")
|
||||
[ "$current" = stable ] && current=main
|
||||
fi
|
||||
|
||||
if [ -z "$branch" ]; then
|
||||
if [ -z "$branch" ] && { [ "$release" = 0 ] || { [ -z "$zip" ] && [ -z "$want" ]; }; }; then
|
||||
def=main
|
||||
[ "$current" = experimental ] && def=experimental
|
||||
if [ "$yes" = 1 ]; then
|
||||
@@ -70,16 +180,35 @@ 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
|
||||
|
||||
if [ "$release" = 1 ]; then
|
||||
install_release "$([ "$branch" = experimental ] && echo experimental || echo stable)" "$want" "$zip" "$dir" \
|
||||
"$clone_only" "$any" -- ${pass[@]+"${pass[@]}"}
|
||||
return
|
||||
fi
|
||||
|
||||
if ! git ls-remote --exit-code --heads "$repo" "$branch" >/dev/null; then
|
||||
echo "Frametop has no branch called $branch (or GitHub can't be reached)." >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
if [ ! -e "$dir" ]; then
|
||||
echo "Cloning Frametop ($branch) into $dir"
|
||||
git clone --branch "$branch" "$repo" "$dir"
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
title: Install the Frametop Hand Recorder
|
||||
---
|
||||
|
||||
# Install the Frametop Hand Recorder
|
||||
|
||||
The Hand Recorder records your hands with the Steam Frame's tracking cameras for Frametop's open hand dataset ([DeeJanuz/frametop-hands](https://huggingface.co/datasets/DeeJanuz/frametop-hands) on Hugging Face). These are the Konsole commands to install it.
|
||||
|
||||
> **Fixed in Frametop 0.2.1 (October 5, 2026):** the recorder now works on headsets without the Arcturus color passthrough module too. If you installed it earlier and the camera check stopped with "Not all of the headset's tracking cameras are running (ft-camd publishes only 2 of 4 mono cameras ...)", run the commands under [Update](#update).
|
||||
|
||||
Join the [Frametop Discord](https://discord.gg/W3X9f7z3Bc) for questions and help with recording.
|
||||
|
||||
For now the recorder runs inside Frametop's desktop, so these steps install Frametop first. A standalone recorder that runs from the SteamVR dashboard without Frametop is planned.
|
||||
|
||||
## Before you start
|
||||
|
||||
- You must be 18 or older, and for now you can't take part if you live in Illinois, Texas or Washington (USA). The [consent text](https://github.com/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.
|
||||
|
||||
## Open Konsole
|
||||
|
||||
1. In the launcher, choose Launch a program → Desktop.
|
||||
2. In the application menu, open System → Konsole.
|
||||
|
||||
## 1. Install Frametop
|
||||
|
||||
```
|
||||
curl -fsSL https://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.
|
||||
|
||||
## 2. Install the Hand Recorder
|
||||
|
||||
After SteamVR restarts, choose Launch a program → Desktop again, open Konsole, and run:
|
||||
|
||||
```
|
||||
~/frametop/hands/rec/install.sh
|
||||
```
|
||||
|
||||
This builds the camera broker, the hand tracker and the headset panel (the first build takes a few minutes), asks for your `sudo` password once to let the camera broker read the cameras, and adds Frametop Hand Recorder to the application menu.
|
||||
|
||||
## 3. Record
|
||||
|
||||
Open Frametop Hand Recorder from the desktop's application menu. It walks you through the consent text, a short checklist, the recording, a review of what you recorded, and the upload to Hugging Face. Nothing leaves the headset until you press Upload.
|
||||
|
||||
## Update
|
||||
|
||||
```
|
||||
curl -fsSL https://frametop.github.io/frametop/get.sh | bash -s -- --stable
|
||||
~/frametop/hands/rec/install.sh
|
||||
```
|
||||
|
||||
Run the second command after SteamVR has restarted, as in the install.
|
||||
|
||||
## Uninstall
|
||||
|
||||
```
|
||||
~/frametop/hands/rec/install.sh uninstall
|
||||
```
|
||||
|
||||
This removes the menu entry. 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/Frametop/frametop/issues), or the dataset's [discussion page](https://huggingface.co/datasets/DeeJanuz/frametop-hands/discussions). All three are public.
|
||||
@@ -3,3 +3,9 @@ models/onnx/
|
||||
models/*.task
|
||||
# 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
@@ -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
|
||||
+201
-25
@@ -4,7 +4,9 @@ Hand tracking from the headset's own cameras. It's deferred: it costs a lot of t
|
||||
|
||||
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,34 +14,47 @@ 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, gives ft-camd its capabilities, installs both services, and links `hands/ft-handsctl` into `~/.local/bin`. `install.sh` doesn't install it. 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): 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
|
||||
hands/run.sh log [lines]
|
||||
hands/run.sh caps # after rebuilding ft-camd (a rebuild clears its capabilities)
|
||||
hands/run.sh uninstall
|
||||
hands/run.sh uncaps # take them back, unless the Hand Recorder or the services use them
|
||||
hands/run.sh uninstall # the services, then uncaps
|
||||
```
|
||||
|
||||
Settings in `~/.config/frametop.conf` (`FT_<name>` in the environment overrides them), read when ft-camd and ft-hands start:
|
||||
|
||||
- `HANDS_SWAP_SIDES=auto` (the default): ft-hands tells from the hands which side camera is which, and corrects ft-camd's names when they're backwards (see "Which camera is which" below). `1` forces them exchanged and `0` forces ft-camd's names; ft-hands still checks and logs a warning if the hands disagree.
|
||||
- `HANDS_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/ncnn`, the stock MediaPipe models): a folder holding `palm.ncnn.*` and `hand.ncnn.*`, as `--models`. Use it to run fine-tuned models, such as the ones trained on the hand dataset, without passing options to every launcher. Those folders usually lack the `*-int8` files, so `--int8` won't load them.
|
||||
- `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.
|
||||
|
||||
@@ -48,8 +63,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.
|
||||
|
||||
@@ -84,9 +100,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.
|
||||
@@ -115,21 +131,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.
|
||||
|
||||
@@ -137,26 +161,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 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.
|
||||
@@ -165,26 +226,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
|
||||
@@ -194,9 +274,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,7 +299,94 @@ Python, with NumPy and OpenCV. `setup/dev-container.sh` doesn't install them, be
|
||||
- `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`).
|
||||
|
||||
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
|
||||
|
||||
@@ -263,10 +437,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.
|
||||
+79
-9
@@ -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,14 +55,25 @@ 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",
|
||||
"systemd suspend", "systemd resume", "XRService logging to", "Exiting XRService")
|
||||
KEYS = ("FPGA", "VCINT", "Created", "TrackingCameraInit", "Found camera", "Closing tracking camera", "Streaming",
|
||||
"systemd suspend", "systemd resume", "XRService logging to", "Exiting XRService", "ISP ")
|
||||
# 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
|
||||
# capture pipes (vfe0 and vfe1), and the upper pair on vfe3 and vfe4.
|
||||
RE_ISP = re.compile(r"ISP (enabled|disabled) for tracking cameras")
|
||||
|
||||
|
||||
class LogState:
|
||||
@@ -79,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": "", "failure": "", "evidence": []}
|
||||
"inits": {}, "init_subdevs": {}, "stream": "", "isp": None, "failure": "", "evidence": []}
|
||||
if self.closed_at:
|
||||
self.episode["evidence"].append(self.closed_at)
|
||||
|
||||
@@ -146,18 +159,30 @@ class LogState:
|
||||
ep["interleave"] = int(m.group(1))
|
||||
ep["evidence"].append(short)
|
||||
return
|
||||
m = RE_ISP.search(text)
|
||||
if m:
|
||||
ep = self._ep(t)
|
||||
ep["isp"] = m.group(1) == "enabled"
|
||||
ep["evidence"].append(short)
|
||||
return
|
||||
m = RE_TASKS.search(text)
|
||||
if m:
|
||||
ep = self._ep(t)
|
||||
ep["tasks"] = tuple(int(v) for v in m.groups())
|
||||
ep["evidence"].append(short)
|
||||
return
|
||||
m = RE_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)
|
||||
@@ -184,6 +209,21 @@ class LogState:
|
||||
got = tuple(self.nodes[i] for i in (2, 3) if i in self.nodes)
|
||||
return got if len(got) == 2 else UPPER_NODES
|
||||
|
||||
def camera_map(self):
|
||||
"""{calibration name: /dev/videoN's N} from the latest camera start's TrackingCameraInit
|
||||
lines (the whole log's when that start has none yet): 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)
|
||||
return got if len(got) == TRACKING else SIDE_NODES + UPPER_NODES
|
||||
@@ -353,7 +393,9 @@ def check(log=None, proc=True, ring=True, ring_path=None):
|
||||
status, reason = "unknown", "no XRService log in %s" % LOG_DIR
|
||||
out = {"log": path, "xrservice": None, "ring": None,
|
||||
"episode": state.snapshot()["episode"] if state else {},
|
||||
"failure": state.snapshot()["failure"] if state else ""}
|
||||
"failure": state.snapshot()["failure"] if state else "",
|
||||
"map": {name: {"node": n, "pipe": pipe_name(n)} for name, n in state.camera_map().items()} if state else {},
|
||||
"ring_missing": []}
|
||||
|
||||
if proc:
|
||||
if pid is None:
|
||||
@@ -388,14 +430,42 @@ 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":
|
||||
status, reason = "degraded", ("ft-camd publishes only %d of %d mono cameras (it started while "
|
||||
"they were missing: restart it)" % (len(r["mono"]), TRACKING))
|
||||
out["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 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
|
||||
|
||||
|
||||
def pipe_name(node):
|
||||
"""The capture pipe behind /dev/videoN (msm_vfe3_video0 and so on), or ""."""
|
||||
try:
|
||||
with open("/sys/class/video4linux/video%d/name" % node) as f:
|
||||
return f.read().strip()
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
|
||||
def is_ring_short(result):
|
||||
"""XRService runs all the tracking cameras, but ft-camd doesn't publish them all."""
|
||||
return bool(result) and result.get("status") == "degraded" and bool(result.get("ring_missing"))
|
||||
|
||||
|
||||
def is_vcint_failure(result):
|
||||
return bool(result) and result.get("status") == "degraded" and result.get("reason") == VCINT_REASON
|
||||
|
||||
|
||||
+220
-12
@@ -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 */
|
||||
@@ -379,9 +402,24 @@ static bool resolve_block(cam_t *c)
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
* Through the ISP (no colour module), the near-black exposures come out all zeros,
|
||||
* the same every time, so their dequeues change no buffer and get no votes. Such
|
||||
* an index is left unmapped (slot -1): on_frame counts its frames as dark without
|
||||
* reading them. Most of a camera's indices silent means it isn't streaming yet.
|
||||
*
|
||||
* 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)
|
||||
{
|
||||
int depth = c->maxindex + 1;
|
||||
int depth = c->maxindex + 1, silent = 0;
|
||||
bool taken[MAX_SLOTS] = { false };
|
||||
|
||||
for (int i = 0; i < depth; i++) {
|
||||
@@ -396,6 +434,12 @@ static bool resolve_each(cam_t *c)
|
||||
}
|
||||
}
|
||||
|
||||
if (c->nobs[i] >= 3 && v1 <= 0.2 * c->nobs[i]) {
|
||||
c->slot_of[i] = -1;
|
||||
silent++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c->nobs[i] < 3 || best < 0 || taken[best] || v1 < 0.8 * c->nobs[i] || v2 > 0.3 * c->nobs[i])
|
||||
return false;
|
||||
|
||||
@@ -403,9 +447,21 @@ static bool resolve_each(cam_t *c)
|
||||
c->slot_of[i] = best;
|
||||
}
|
||||
|
||||
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++)
|
||||
printf(" %d", c->slot_of[i]);
|
||||
c->slot_of[i] < 0 ? printf(" -") : printf(" %d", c->slot_of[i]);
|
||||
if (silent)
|
||||
printf(" (- : %d indices whose frames are all zeros, skipped as dark)", silent);
|
||||
else if (c->exact)
|
||||
printf(" (bright and dark told apart frame by frame)");
|
||||
printf("\n");
|
||||
return true;
|
||||
}
|
||||
@@ -426,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);
|
||||
@@ -670,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;
|
||||
@@ -677,6 +739,12 @@ static void on_frame(cam_t *c, int64_t index, uint32_t seq, uint64_t ts, uint64_
|
||||
|
||||
int slot = c->slot_of[index];
|
||||
|
||||
if (slot < 0) { /* an index whose frames are all zeros (resolve_each): a dark one */
|
||||
c->dark++;
|
||||
c->rc->dropped++;
|
||||
return;
|
||||
}
|
||||
|
||||
/* color runs at 60 fps: skip frames early enough that the asked rate holds, before any sync */
|
||||
if (c->color && color_fps > 0 && evtime - c->last_pub_ns < (uint64_t)(1e9 / color_fps) - 3000000) {
|
||||
c->paced++;
|
||||
@@ -694,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);
|
||||
@@ -807,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 */
|
||||
@@ -819,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;
|
||||
@@ -874,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)
|
||||
{
|
||||
@@ -1075,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;
|
||||
}
|
||||
@@ -1223,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) {
|
||||
@@ -1241,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) {
|
||||
|
||||
+198
-12
@@ -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) {
|
||||
@@ -544,22 +581,26 @@ static void probe_cameras(xr_state_t *st)
|
||||
/*
|
||||
* qcom-camss can report bytesperline as the visible width while the VFE
|
||||
* writes a larger aligned pitch. sizeimage is right, so derive the pitch.
|
||||
* For NV12, plane 0 normally holds the chroma rows after the luma (the side
|
||||
* cameras through the ISP: 1056 wide, 1152 bytes a row); if it's too small for
|
||||
* that, it holds the luma alone.
|
||||
*/
|
||||
unsigned xr_camera_stride(const xr_camera_t *c)
|
||||
{
|
||||
if (!c->height || !c->planesize[0])
|
||||
return c->bytesperline ? c->bytesperline : c->width;
|
||||
|
||||
double bpp = 1.0;
|
||||
|
||||
if (c->pixfmt == V4L2_PIX_FMT_NV12 || c->pixfmt == V4L2_PIX_FMT_NV21)
|
||||
bpp = 1.5;
|
||||
|
||||
unsigned s = (unsigned)((double)c->planesize[0] / ((double)c->height * bpp));
|
||||
bool yuv = c->pixfmt == V4L2_PIX_FMT_NV12 || c->pixfmt == V4L2_PIX_FMT_NV21;
|
||||
unsigned s = (unsigned)((double)c->planesize[0] / ((double)c->height * (yuv ? 1.5 : 1.0)));
|
||||
|
||||
if (s >= c->width && s <= c->width * 4)
|
||||
return s;
|
||||
|
||||
s = (unsigned)(c->planesize[0] / c->height);
|
||||
|
||||
if (yuv && s >= c->width && s <= c->width * 4)
|
||||
return s;
|
||||
|
||||
return c->bytesperline ? c->bytesperline : c->width;
|
||||
}
|
||||
|
||||
@@ -591,7 +632,20 @@ void xr_camera_layout(const xr_camera_t *c, xr_layout_t *l)
|
||||
l->pitch = xr_camera_stride(c);
|
||||
l->width = c->width < l->pitch ? c->width : l->pitch;
|
||||
|
||||
if (c->pixfmt == V4L2_PIX_FMT_NV12 || c->pixfmt == V4L2_PIX_FMT_NV21) {
|
||||
/*
|
||||
* Without the colour module, XRService runs the side cameras through the
|
||||
* ISP ("ISP enabled for tracking cameras (main VFE available)" in its log),
|
||||
* and they come out NV12. They're mono sensors, so the luma is the image.
|
||||
*/
|
||||
bool yuv = c->pixfmt == V4L2_PIX_FMT_NV12 || c->pixfmt == V4L2_PIX_FMT_NV21;
|
||||
|
||||
if (yuv && c->role && !strcmp(c->role, "tracking")) {
|
||||
l->fmt = XR_FMT_GREY8;
|
||||
l->rows = c->height;
|
||||
return;
|
||||
}
|
||||
|
||||
if (yuv) {
|
||||
l->fmt = XR_FMT_NV12;
|
||||
l->rows = c->height + c->height / 2;
|
||||
} else {
|
||||
@@ -613,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
|
||||
@@ -686,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++)
|
||||
@@ -695,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
|
||||
@@ -775,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)" : "");
|
||||
}
|
||||
}
|
||||
@@ -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,11 +7,12 @@ 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
|
||||
ExecStartPre=-/usr/bin/pkill -x ft-hands
|
||||
ExecStart=%h/.local/bin/distrobox enter dev -- @REPO@/hands/build/ft-hands --status 60
|
||||
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
@@ -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
|
||||
@@ -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:]))
|
||||
Executable
+358
@@ -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:]))
|
||||
@@ -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");
|
||||
@@ -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");
|
||||
@@ -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
|
||||
@@ -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
|
||||
+39
-7
@@ -11,7 +11,9 @@ The plan this belongs to is `~/Desktop/Projects/frame-hands/notes/hands-plan.md`
|
||||
| `hands/rec/panel/ft-handpanel.cpp` (C++, dev container) | The headset panel: a SteamVR overlay fixed to the head that shows the prompts. It also places the "touch the dot" target in the room and logs head and controller poses. Driven over `@ft_handpanel`. |
|
||||
| `hands/rec/session.py` (Python, no Qt) | The session runner. It reads `script.json`, starts and stops the recordings, and drives the panel. It reads the live hands file for feedback and writes each take's files. It also runs from the command line (`--dry-run`) for testing. |
|
||||
| `hands/rec/script.json` | The guided script: sections, prompts, timings. |
|
||||
| `hands/rec/script-v2.json` | The v2 script (`ft-handrec --script script-v2.json`, `session.py --script`): a demo clip per step (below). Being tried; it becomes `script.json` once settled. |
|
||||
| `hands/rec/poses/` | The pose pictures, `poses.json` and its PNGs (below). |
|
||||
| `hands/rec/demos/` | The demo clips, `<id>.gif`, made from `demo/parts.json` (below). |
|
||||
| `hands/rec/takes.py` (Python, no Qt) | Reads sessions and takes from disk: frame sets for review, deleted ranges, export (compress, strip, manifest, checksums). |
|
||||
| `hands/rec/ft_handrec.py` + `main.qml` (PySide6 + Kirigami, dev container) | The desktop window: consent, the before-you-start checklist, the session controls, review, export and upload instructions. |
|
||||
| `hands/rec/ft-handrec` | The host launcher, like `input-settings/ft-input-settings`. |
|
||||
@@ -23,13 +25,24 @@ The plan this belongs to is `~/Desktop/Projects/frame-hands/notes/hands-plan.md`
|
||||
|
||||
Every part runs in the dev container, as ft-hands and Input Settings do. The host Python isn't used: it lacks PySide6 and zstd. `setup/dev-container.sh` gains `zstd`.
|
||||
|
||||
### The standalone Hand Recorder
|
||||
|
||||
[frametop-hand-recorder](https://github.com/Frametop/frametop-hand-recorder) is the recorder for people without Frametop. It pins this repo as a submodule and ships the parts above with its own window, a Qt Quick Controls `main.qml` sized for SteamVR's dashboard. Its release builds the binaries for the SteamOS host: ft-camd and ft-hands statically (`make LDFLAGS=-static`), and ft-handpanel against SteamVR's `libopenvr_api`. Everything runs on the host, the Python from a venv (`ft_handrec.py --qml ITS_QML --style Basic`).
|
||||
|
||||
Its tarball keeps this tree's layout (`hands/build/`, `hands/rec/`, `hands/models/`), so the paths here don't change. A `standalone.json` at the top marks it (`takes.standalone()`):
|
||||
- `session.py` starts ft-hands directly, not through distrobox.
|
||||
- session.json's `tool` and the manifest's are `ft-handrec <describe> (frametop-hand-recorder <version>)`.
|
||||
- The repair hints say to run its install command again.
|
||||
|
||||
The recordings go to the same `~/.local/share/frametop/hands/contrib`, so either recorder shows both's sessions.
|
||||
|
||||
## Processes during a session
|
||||
|
||||
- **ft-camd** publishes the camera ring. If it isn't running, the session starts it as the transient user unit `frametop-handrec-camd.service`, the way `hands/ft-cutouts` starts `frametop-cutouts-camd.service` (needs `hands/build/ft-camd` with capabilities: `hands/run.sh caps`). An ft-camd already running from ft-cutouts or ft-handsctl is used as it is.
|
||||
- **A tracking ft-hands** gives feedback through the hands file: which hands are seen, the palm's distance, the index tip. If none is running, the session starts `ft-hands --no-gestures --status 0` (unit `frametop-handrec-hands.service`). An ft-hands already running is used as it is.
|
||||
- **A recording ft-hands** runs once per recording part: `ft-hands --record-only --record DIR --record-for SECONDS --record-hz 10 --status 0 --sides auto|0|1` (below, "Side cameras"). It runs as a plain child process of the session, ended with SIGTERM when the part ends. SIGTERM ends ft-hands' loop, and `Recorder` writes out its queue when it's destroyed. In step mode (below) a part is one step's countdown and hold, so a take has one part per step (about 40 in the hand poses); in auto mode a take is one part, plus one more after each pause. `--record-for` is only a safety net.
|
||||
- Why a process per part rather than one kept alive and paused: measured in the dev container with `ft-ringplay`'s ring (2026-10-02), `ft-hands --record-only` writes its first set 16-27 ms after it starts and ends 4-6 ms after SIGTERM, so a new part costs nothing the 3 s countdown doesn't cover. Every reader already takes parts in order (`takes.py`, `validate.py` through the export's single stream, the labeller's `fhl_io.py`, numbering `sets-10.bin` after `sets-9.bin`), ft-hands needs no new control, and nothing is written while a step waits. Before the hold starts the session checks that the part has written a set (`Recorder.has_data`, up to 3 s more), so the hold is recorded from its first frame.
|
||||
- **Side cameras.** ft-camd can name the two side cameras the wrong way round (hands/README.md, "Which camera is which"). The tracking ft-hands decides from the hands within about 2 s of them being in view (`HANDS_SWAP_SIDES=auto`, hands/track/sides.h) and publishes that in `/run/user/UID/frametop-hands/sides.json`. The session reads it (`sides.py`, `read_live`) and stores it in session.json `"sides"`. Each later part is recorded named right (`--sides 1` or `0`). Parts recorded before the decision use ft-camd's names (`--sides auto`; a record-only ft-hands can't tell), and readers rename them (`sides.py`). Each part's `names_swapped` goes into take.json `"parts"`. Without a tracking ft-hands nothing decides: `"swapped": null`, the names stay as recorded, and the maintainer's check (`hub_review check`, check_sides on a few sets per take) tells. `takes.py sides SESSION --set swapped|named` records a decision by hand.
|
||||
- **Side cameras.** ft-camd can name the two side cameras the wrong way round (hands/README.md, "Which camera is which"). The tracking ft-hands decides from the hands within about 2 s of them being in view (`HANDS_SWAP_SIDES=auto`, hands/track/sides.h) and publishes that in `/run/user/UID/frametop-hands/sides.json`. With `HANDS_SWAP_SIDES` forced to `0` or `1`, the hands still decide what's published once they disagree (state `"forced, disagrees"`; `read_live` also corrects an ft-hands built before that). The session reads it (`sides.py`, `read_live`) and stores it in session.json `"sides"`. Each later part is recorded named right (`--sides 1` or `0`). Parts recorded before the decision use ft-camd's names (`--sides auto`; a record-only ft-hands can't tell), and readers rename them (`sides.py`). Each part's `names_swapped` goes into take.json `"parts"`. Without a tracking ft-hands nothing decides: `"swapped": null`, the names stay as recorded, and the maintainer's check (`hub_review check`, check_sides on a few sets per take) tells. `takes.py sides SESSION --set swapped|named` records a decision by hand.
|
||||
- **ft-handpanel** runs as a child process with `--watch-stdin`. It shows the panel and logs poses during each take.
|
||||
- **The headset button's reader** is a thread of the session (`ButtonReader`, below), not a process.
|
||||
|
||||
@@ -39,7 +52,7 @@ Test hooks:
|
||||
- `--dry-run` runs no processes and only prints the panel commands, with timing sped up by `--speed X`.
|
||||
- `--next-after S` presses Next by itself after S seconds of waiting (real time), so a step-mode session runs unattended. Lines on stdin steer it too: `n` or an empty line is Next, `p` pause or resume, `r` redo, `s` skip the section, `q` stop.
|
||||
- `--no-headset-button` leaves the headset's button alone (`ft-handrec --no-headset-button` too). `--button-device PATH` reads it from PATH instead, an event device or a FIFO of `input_event` structs, also in a dry run: a simulated button for tests.
|
||||
- `--auto` runs the timed flow; `--poses DIR` takes the pose pictures from DIR; `--plan` prints the sections, their steps and length.
|
||||
- `--auto` runs the timed flow; `--poses DIR` takes the pose pictures from DIR, `--demos DIR` the demo clips (`ft-handrec --demos` too); `--plan` prints the sections, their steps and length.
|
||||
- `--ignore-cameras` (`ft-handrec --ignore-cameras` too) starts even when the camera check fails. A dry run and `--ring` skip the check by themselves.
|
||||
|
||||
## Files
|
||||
@@ -120,6 +133,7 @@ One JSON object per line:
|
||||
{"t": 123, "event": "take", "section": "static-poses", "take": "03-static-poses"}
|
||||
{"t": 123, "event": "prompt", "id": "static-poses/fist/left/near", "text": "...", "hands": "left|right|both|none",
|
||||
"pose": "fist", "distance": "near|mid|far|", "position": "centre|left|right|up|down|", "object": "", "controller": false}
|
||||
{"t": 123, "event": "prompt", "id": "index-taps/2a/left", "...": "...", "demo": "2a"}
|
||||
{"t": 123, "event": "target", "id": "touch/3", "head": [x, y, z], "room": [x, y, z], "state": "show|hold|done|timeout"}
|
||||
{"t": 123, "event": "bar", "target": 0.0}
|
||||
{"t": 123, "event": "feedback", "left": true, "right": false, "palm_m": [0.0, 0.0]}
|
||||
@@ -158,7 +172,7 @@ ft-handpanel writes one line per sample, 250 a second, from `GetDeviceToAbsolute
|
||||
|
||||
## The panel (`ft-handpanel`)
|
||||
|
||||
- **Placement.** A SteamVR overlay fixed to the head, like `gaze/panel/ft-gazepanel.cpp`: key `frametop.handpanel`, sort order 250. It sits 1.2 m ahead, centred 12 degrees above straight ahead, so the hands stay clear below it. It's 36 degrees wide, 4:3, 1024x768 pixels, dim and see-through. It's drawn on the CPU with stb_truetype (and stb_image for the pose pictures, PNG only, the same pinned stb commit) into three shared DMA-BUFs SteamVR imports once, as ft-gazepanel does, and is drawn again only when something changes.
|
||||
- **Placement.** A SteamVR overlay fixed to the head, like `gaze/panel/ft-gazepanel.cpp`: key `frametop.handpanel`, sort order 250. It sits 1.2 m ahead, centred 12 degrees above straight ahead, so the hands stay clear below it. It's 36 degrees wide, 4:3, 1024x768 pixels, dim and see-through. It's drawn on the CPU with stb_truetype (and stb_image for the pose pictures and demo clips, PNG and GIF, the same pinned stb commit) into three shared DMA-BUFs SteamVR imports once, as ft-gazepanel does, and is drawn again only when something changes.
|
||||
- **Layout.** The title and step on top (a red "Rec" by the step while recording), a rule. With a pose picture or a diagram, a 14-degree column on the left holds the picture (or the flipped copy and the picture side by side) and the where-to diagram under it; the text takes the right. The text column holds the instruction, the orange note, the big countdown ("3", "2", "1", then "Hold" or "Go") and the cyan action line ("Ready? Press Space or click Next"), centred together. At the bottom: the near/far bar, the hand chips, the time-left bar and the key hints.
|
||||
- **Socket.** Abstract unix datagram `@ft_handpanel` (`--socket NAME`). A sender with an address gets `ok ...` or `error ...`.
|
||||
- **Options:** `--watch-stdin` (quit when stdin closes), `--socket NAME`, `--distance M`, `--no-vr`. `--no-vr` makes no SteamVR connection and prints each picture's text to stdout: for testing without a headset.
|
||||
@@ -176,6 +190,7 @@ Commands (UTF-8; `|` starts a new line in text):
|
||||
| `hands <left> <right>` | Two chips, "Left hand" and "Right hand", each `seen` (green), `lost` (orange) or `off` (hidden). |
|
||||
| `bar <target 0..1> <current 0..1 or -1> [near label] [far label]` / `bar off` | The near/far bar for the push out and back: a horizontal track with a target marker and the hand's current position. |
|
||||
| `paused on` / `paused off` | A "Paused" overlay over the picture. |
|
||||
| `demo <path> [mirror]` / `demo restart` / `demo off` | A demo clip (below) playing in a wider left column (16 degrees), looped, with the key to its colours under it: a light swatch "Light: palm", a dark one "Dark: back of hand". It takes the picture's place, and the text beside it is left-aligned (a list of motions). A new path starts it from its first frame; the same one again leaves it playing (`mirror` only flips it); `restart` starts it again. It stands still while paused. A file that can't be read: `error can't read ...` and no clip. |
|
||||
| `image <path> [mirror\|both]` / `image off` | The pose picture, a PNG (below), in the left column. `mirror` flips it (a left hand); `both` draws a flipped copy on its left. A file that can't be read: `error ...` and no picture. |
|
||||
| `where <position\|-> <distance\|->` / `where off` | The where-to diagram under the picture: a 3x3 front view with the asked cell lit (`centre`, `left`, `right`, `up`, `down`, and the push sections' `chest`, `desk`, `eye`), and a side view of the head and three marks for `near` ("Close"), `mid` ("Halfway out") and `far` ("Arm out"). `-` leaves that half out. |
|
||||
| `action <text>` | The cyan line under the instruction (empty clears it). |
|
||||
@@ -204,6 +219,16 @@ It quits on SteamVR's quit event, as ft-gazepanel does. `--no-vr --dump DIR` wri
|
||||
|
||||
A pose with no entry, or whose file is missing, shows no picture: the text alone. The session reads `poses.json` when it starts. The window shows the same picture (QML `Image.mirror`), its caption, and the same diagram.
|
||||
|
||||
## Demo clips (`demos/`)
|
||||
|
||||
The v2 script shows a looping clip for each step instead of a pose picture: generated animation of a stick-figure hand in the colours of Steam Frame passthrough, one GIF per part of `demo/parts.json` (`<id>.gif`, 640x360, 12 frames a second, 6-16 s, under 2 MB). They're made outside the Frame (Blender), so their source isn't here. The palm side of the hand is drawn light (#d5d1fe) and the back dark (#6a62d8); the panel and the window say so under each clip, and the welcome screen too.
|
||||
|
||||
- A prompt's `"demo": "<id>"` names its clip; `"demo_mirror": true` flips it (`session.demo_view`): the clips show a right hand, or both hands, so a left-hand step flips a right hand's clip. A missing file shows no clip: the text alone.
|
||||
- The clip starts on the step's ready screen and starts again from its first frame when the hold begins (after the 3-2-1), so it can be followed. The status's `demo_run` counts those starts for the window, which plays the same clip (QML `AnimatedImage`).
|
||||
- The panel decodes a frame at a time as it plays (stb_image's GIF decoder, stepped as `stbi_load_gif_from_memory` steps it), so a clip costs three frames of memory however long it is. A frame redraws only the clip's rectangle and copies only that to a buffer that already has the rest of the picture: about 450x250 pixels 12 times a second.
|
||||
- Two kinds, the contributor's choice on the window's start page ("Guidance", kept in `BASE/settings.json`, written to `session.json` as `"guidance"`): **recorded** clips in `demos-recorded/`, a real person's hands from a recorder session's side cameras (`demo/camgifs.py`: each frame drawn again as a plain picture from between the eyes, 640x360, 10 a second, grey), and **skeleton** clips in `demos/`, the drawn hand. Recorded is the default when there are recorded clips. A part with no clip of the chosen kind shows the other kind. Only a skeleton clip shows the key to its colours (the panel's `demo <path> [mirror] [nokey]`; the status's `demo_key`). Recorded clips show the room around the person who recorded them: check them before they go anywhere public.
|
||||
- In `script-v2.json` a one-hand part runs three steps: the left hand alone (the clip flipped), the right alone, then both at once. A part made for two hands runs once. Each step lasts about 1.2 times its clip. `"name": "v2"` goes into `session.json`'s `script`.
|
||||
|
||||
## The script (`script.json`)
|
||||
|
||||
```json
|
||||
@@ -234,6 +259,7 @@ A pose with no entry, or whose file is missing, shows no picture: the text alone
|
||||
- `bar`: the target marker sweeps near to far and back, `reps` times per height, at `period_s` per sweep. The current marker follows the live palm distance.
|
||||
- Each section is one take. Prompts within it are marked in `prompts.jsonl`.
|
||||
- `cue_names`: the short labels under the strip's pictures (otherwise the pose id).
|
||||
- `name`: the script's name, recorded in `session.json` (`script.name`); `demo`, `demo_mirror`: a prompt's demo clip (above).
|
||||
|
||||
### Sweeps
|
||||
|
||||
@@ -283,7 +309,7 @@ Before section 7: "Put on both controllers and tighten the straps". Before secti
|
||||
- **Hands seen:** from the hands file. A hand counts as seen if its flags match the side and the file is fresh (publish within 0.3 s). Prompts with `hands` set show the `hands` chips. If an asked-for hand is lost for more than 1.5 s, the note says "I can't see your left hand: bring it into view".
|
||||
- **Controller tracking:** in sections 8 and 9, `devices` is polled once a second. A result other than 200 for more than 1 s says "The left controller lost tracking: turn your palm slightly toward you". Each such stretch goes into `prompts.jsonl` as `feedback` with `"controller": {...}`.
|
||||
- **Lighting, measured:** the checklist page measures the light when it opens, starting ft-camd (`frametop-handrec-camd.service`) if nothing runs it; the window stops it again on quit if it started it. The mean of every mono camera's `mean` and `dark_mean` from the ring (`hands/tools/ring.py` layout; struct only, no numpy) is compared with the person's earlier sessions. If it matches an earlier round's within 15%, the window says so before starting.
|
||||
- **Lighting label:** "Measured by the cameras" is the default. `ambient_ir`, the mono cameras' mean `dark_mean` (the room's infrared), labels the round `daylight` from 6.0 and `indoor` below (`session.classify_lighting`). Lamps and LEDs give off hardly any infrared, so a dim room and a lit one read about the same (1.8 by one lamp, 2.2 in a lamp-lit room) and the cameras can't tell them apart; the person can pick dim, room or daylight instead (`source: "picked"`). The 6.0 threshold is a guess until a daylight round is measured.
|
||||
- **Lighting label:** "Measured by the cameras" is the default. `ambient_ir`, the mono cameras' mean `dark_mean` (the room's infrared), labels the round `daylight` from 6.0 and `indoor` below (`session.classify_lighting`). Lamps and LEDs give off hardly any infrared, so a dim room and a lit one read about the same (1.8 by one lamp, 2.2 in a lamp-lit room) and the cameras can't tell them apart; the person can pick dim, room or daylight instead (`source: "picked"`). The 6.0 threshold was a guess, and the first daylight round (dataset PR #5, 2026-10-05, a room with big sunlit windows) read 2.38 and was labelled `indoor`: the windows are a small part of each picture. So the checklist now asks people to pick Daylight when sunlight comes in, and the maintainer corrects the label in review (`hub_review.py lighting`) from what the pictures show: windows lit by the sun, the time of day. Hands that stand out little from the room (PR #5: a median 1.15x as bright as their surroundings, against 1.5-1.7x in some lamp-lit rounds) go with daylight, but a pale room at night read 1.22 (PR #6), so that alone doesn't decide it.
|
||||
|
||||
### Camera check
|
||||
|
||||
@@ -291,16 +317,22 @@ On 2026-10-02 a whole session showed "I can't see your hands": after the headset
|
||||
|
||||
- **Before the session.** The window runs `hands/camcheck.py` when the checklist page opens ("Tracking cameras:", with the evidence under Details and Check again), and again when Start is pressed; `session.py` runs it first thing, before it makes the session's folder or starts anything (`Session._preflight`). If it finds the cameras degraded, the session doesn't start. The window says: "The headset's upper cameras and IR light are off. SteamVR couldn't start the colour camera module (it happens sometimes after the headset sleeps). Restart SteamVR, or restart the headset if that doesn't fix it." (another `degraded:` reason gets a sentence naming it), and Start stays off. `unknown` (SteamVR not running, the cameras asleep) doesn't stop it: the session's own start fails clearly then. From the command line, `session.py` prints the check and exits with status 3.
|
||||
- **Restart SteamVR.** The message has a Restart SteamVR button. After a confirmation it runs `systemctl --user restart --no-block steamvr.service` on the host (through `distrobox-host-exec`), then checks the cameras every 3 s, for up to 2 minutes, until a new XRService has opened its cameras. The confirmation says what really happens: every VR app closes, and so does the Frametop desktop with all its windows, this one included, and it doesn't come back by itself (`hands/README.md`, "What a SteamVR restart does to Frametop"). So the check after the restart mostly happens when the recorder is opened again; it re-runs when the checklist page opens. `--no-block` lets the restart finish after the window is gone.
|
||||
- **Frametop's hands are off during a session.** Frametop's drawn hands (`frametop-handview`) cover what the person watches, and its hand pointer (`frametop-pointer`) turns the steps' pinches and taps into clicks, or opens Steam's menu. When a session starts (after the camera check, before the welcome screen), the ones running are stopped, and listed in `/run/user/UID/frametop-hands/handrec-paused-units` first. They're started again when the session ends in any way. If the recorder is killed meanwhile, the window starts them when it opens again, and so does the next session. The hand tracker itself keeps running: the session's hand notes read it.
|
||||
- **Cameras moved or lost.** Unplugging or plugging in the colour camera module makes XRService move the side cameras to other devices (video9/13 and video0/3). On 2026-10-12 an ft-camd started before the move kept publishing the old devices, ft-hands left the side pair out, and a whole session recorded only the upper cameras. Now: the camera check fails when ft-camd's devices aren't the ones XRService runs (`ring_missing`, "it moved them"), and the window's check and the session's preflight restart that ft-camd (the recorder's own unit, or Frametop's live `frametop-camd` and then `frametop-hands`). ft-camd exits by itself when a camera goes silent while the others run (camd.c, `SILENT_S`), and its service starts it on the new devices. In a session, a part whose first set has no `slam_left`/`slam_right`, a recording that exits, or one that writes no set for `STALL_S` (3 s) loses the step (`_CamerasLost`): in step mode its try gets a `redo` event, the panel says "Waiting for the cameras", the session runs the camera check (with its repair) every 2 s for up to `CAMERAS_BACK_S` (120 s), then shows the step's ready screen again. If they don't come back, or after `MAX_CAMERA_LOSSES` (3) losses, the session stops with an error. Auto mode stops at once. Known gap: if a restarted ft-camd binds the side pair the other way round, the session's single `sides` decision (reversed for the later parts) renames the earlier parts wrongly; `hub_review check` tells.
|
||||
- **No hands in the first step.** The first step of the hand-size section has both hands up, about 40 cm away. During its hold, the session counts the hands file's reads (about 20 a second). If the tracker published in at least half of at least 10 reads and never saw a hand, the step stops: a `wait` and the recording stops as usual, then a `nohands` event and a `redo` over the try. The session runs the camera check and shows "I can't see your hands" with its result (the camera text above when it's the VCINT failure, else "The camera check found nothing wrong"). The state is `nohands`, waiting: Next (the headset button, Space, Try again) or R starts the same step's countdown at once; Stop (Esc) ends the session with `stop_reason` set; S skips the section. One missed step costs a retry, not the session, and every hold of that step is logged ("hands check ...: a hand in N of M reads"). Without a tracker publishing the session can't tell, logs that, and goes on. Only that one step is checked: later steps have their notes ("I can't see your left hand") as before. Auto mode does the same; its recording pauses meanwhile.
|
||||
|
||||
### Controls
|
||||
|
||||
- The window has Start, a big Next (while a step waits; its hint is the panel's), Pause/Resume, Redo step, Skip section and Stop. While it has focus: Space is Next, P pauses or resumes, R redoes, S skips the section, Esc stops. The panel's bottom line and the window list them. The window also shows the step's picture, diagram, countdown and "Hold".
|
||||
- **The headset's button.** The Frame has a click button on its right side, for use without controllers: `KEY_SELECT` (353) on the evdev device `gpio-keys`. While a step waits (the welcome, a section's intro, a step's ready screen) a press is Next; during a countdown or hold (and auto mode's timed screens) it pauses; while paused it resumes. The session finds the device in `/proc/bus/input/devices` by name and its KEY bitmap (`event3` on the maintainer's Frame) and reads `input_event` structs with plain `struct` (no python-evdev), from a thread. Only key-downs count (value 1: releases and autorepeat, value 2, don't), and presses closer than 0.3 s count once.
|
||||
- **The headset's button.** The Frame has a click button on its right side, for use without controllers: `KEY_SELECT` (353) on the evdev device `gpio-keys`. It has three gestures (`ButtonGestures`), so a session can run with the window out of reach (the standalone Hand Recorder's window is in SteamVR's dashboard, closed while recording):
|
||||
- **A press.** While a step waits (the welcome, a section's intro, a step's ready screen, the no-hands question) it's Next; during a countdown or hold (and auto mode's timed screens) it pauses; while paused it resumes. It counts once 0.45 s have passed without a second press, so Next and pause come that much after the press.
|
||||
- **Two presses**, the second down within 0.45 s of the first one's release: redo, as R. It counts at the second press. Where R does nothing (nothing recorded yet, a section's intro), neither does this.
|
||||
- **A hold** of 1.5 s: stop, as Esc. It counts after 1.5 s, while the button is still down.
|
||||
- The session finds the device in `/proc/bus/input/devices` by name and its KEY bitmap (`event3` on the maintainer's Frame) and reads `input_event` structs with plain `struct` (no python-evdev), from a thread. Downs (value 1) and ups (value 0) count; autorepeat (value 2) doesn't. The gaps between events come from the kernel's timestamps, so a double press read in one go still counts as two. A release and a press closer than 30 ms are one press (gpio-keys debounces too).
|
||||
- It's read, never grabbed (`EVIOCGRAB`). Frametop's input relay (`input/input-relay.py`), ft-powerd, SteamVR and gamescope read the same device, and the relay remaps its volume keys (the experimental branch's `docs/hazards.md`). A grab would take the volume keys from the relay.
|
||||
- `steamos` is in the `input` group, so it needs no sudo. The dev container sees the host's `/dev/input` and `/proc/bus/input/devices`, and the group carries over (checked 2026-10-02), so it works from the window there and from `session.py` on the host. If the device is missing or can't be opened, the session logs it, keeps trying every 5 s, and the hints don't mention the button.
|
||||
- **Not known yet (needs the headset):** what SteamVR and gamescope do with the same press. They read it too, so it may also click whatever is under the head or gaze pointer in VR, or open something. Check on the first session; if it does, the fix is on their side or a different button, not a grab.
|
||||
- **The Next hint follows what's there.** No mouse connected: "Ready? Press the button on the right side of the headset" (the window's Next can't be clicked, and Space needs the window focused). A mouse: "Ready? Press Space, click Next, or press the headset button". No button: "Ready? Press Space or click Next". The panel's bottom line leads with "Headset button: next, pause". A mouse is a device in `/proc/bus/input/devices` with EV_REL, REL_X and REL_Y that isn't made in software: uinput devices (Frametop's virtual mouse, frame-voice's keyboard) sit under `/devices/virtual/input` or on the virtual bus (6), and are left out; Bluetooth mice come through uhid, under `/devices/virtual/misc/uhid`, and count. It's looked at again at each step, so a mouse plugged in mid-session counts from the next step.
|
||||
- **Not known yet (needs the headset):** what SteamVR and gamescope do with the same press. They read it too, so it may also click whatever is under the head or gaze pointer in VR, or open something, and a hold or a double press may mean something else to them. Check on the first session; if it does, the fix is on their side or a different button, not a grab.
|
||||
- **The Next hint follows what's there.** No mouse connected: "Ready? Press the button on the right side of the headset" (the window's Next can't be clicked, and Space needs the window focused). A mouse: "Ready? Press Space, click Next, or press the headset button". No button: "Ready? Press Space or click Next". The panel's bottom line leads with "Headset button: press for next or pause · press twice to redo · hold to stop", then the window's keys by letter. With the button, the pause note and the no-hands question say how to resume or stop with it too. A mouse is a device in `/proc/bus/input/devices` with EV_REL, REL_X and REL_Y that isn't made in software: uinput devices (Frametop's virtual mouse, frame-voice's keyboard) sit under `/devices/virtual/input` or on the virtual bus (6), and are left out; Bluetooth mice come through uhid, under `/devices/virtual/misc/uhid`, and count. It's looked at again at each step, so a mouse plugged in mid-session counts from the next step.
|
||||
- **R (redo).** During a step's countdown or hold: that step starts again from its ready screen. At a step's ready screen: the step before it (in this section) goes again. Either way a `redo` event marks the range of the try being redone, so its labels are skipped; the sets stay, to delete in review if wanted.
|
||||
- A pause stops the take's recording and starts it again on resume as the next part of the same take (`sets-2.bin`, and so on). takes.py reads all parts in order. A pause while a step waits only shows "Paused"; a Next pressed while paused doesn't count.
|
||||
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
# Build the hand recorder's headset panel ft-handpanel in the dev container on the Frame
|
||||
# (hands/rec/build/; it also runs there). Like gaze/build.sh: the pinned public OpenVR header
|
||||
# (the DMA-BUF import is newer than the header shipped with SteamVR's samples), stb_truetype
|
||||
# for the text and stb_image (PNG only) for the pose pictures, at the same stb commit.
|
||||
# for the text and stb_image (PNG and GIF) for the pose pictures and the demo clips, at the same stb commit.
|
||||
set -euo pipefail
|
||||
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
"$root/scripts/sync.sh" >/dev/null
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# Demo clips for the hand recorder
|
||||
|
||||
The v2 recording script shows a looping GIF for each part of `parts.json` (`script-v2.json` is made
|
||||
from it). There are two kinds (hands/rec/DESIGN.md): skeleton clips in `hands/rec/demos/`, generated
|
||||
animation made outside the Frame, and recorded clips in `hands/rec/demos-recorded/`, made here from a
|
||||
recorder session.
|
||||
|
||||
## Recorded clips from a recorder session
|
||||
|
||||
The window's "Recorded hands" guidance plays clips of real hands from a Hand Recorder session that
|
||||
ran the v2 script, instead of the drawn ones:
|
||||
`frame-job --local -- PYTHON hands/rec/demo/camgifs.py SESSION_DIR` (PYTHON with NumPy, e.g.
|
||||
frame-hands' `.venv/bin/python`) writes `hands/rec/demos-recorded/<id>.gif`. Each part uses its
|
||||
right-hand step (or its both-hands step), redrawn from the two side cameras as a plain picture.
|
||||
`--sheets` writes contact sheets first; `--view ID=PITCH,HFOV` aims a part's view, kept in
|
||||
`views.json` next to the clips. They show the room: check them before they go anywhere public.
|
||||
@@ -0,0 +1,277 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Recorded-guidance demo GIFs from a hand recorder session: the side cameras' own frames.
|
||||
|
||||
frame-job --local -- PYTHON hands/rec/demo/camgifs.py SESSION_DIR [--out DIR] [--part ID]
|
||||
[--sheets] [--view ID=PITCH,HFOV[,YAW]] [--lossy N]
|
||||
|
||||
PYTHON needs NumPy (frame-hands' .venv/bin/python has it). SESSION_DIR is a recorder session
|
||||
(BASE/sessions/<id>) that ran the v2 script. Per demo clip of script-v2.json it takes the part's
|
||||
right-hand step (the window mirrors it for the left hand, like the skeleton clips), or its
|
||||
both-hands step, from the start of its prompt to the end of its last try; a redone step uses
|
||||
the try that was kept.
|
||||
|
||||
The side cameras are fisheyes looking down and out, so each frame is drawn again as a plain
|
||||
picture from between the eyes: a virtual camera PITCH degrees below straight ahead, HFOV wide,
|
||||
filled from both side cameras (the session's calibration.json) for points 45 cm away, each
|
||||
pixel from the camera that sees it nearer its centre. Clips run at the recording's 10 sets/s,
|
||||
640x360 like the skeleton clips, grey, smoothed (steady), gifsicle's lossy pass when it's there
|
||||
(HANDDEMO_GIFSICLE, or gifsicle on the PATH): about 1.4 MB for 10 s.
|
||||
--sheets writes a contact sheet per clip instead (<id>.png, a frame every 2 s), to pick
|
||||
--view per part before making the GIFs; views.json in the out folder keeps them
|
||||
({"12": [-55, 100]}).
|
||||
|
||||
The GIFs show the room around the recorder: check them before they go anywhere public.
|
||||
Writes OUT/<id>.gif (default hands/rec/demos-recorded, where the window's "Recorded" guidance
|
||||
looks).
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
import numpy as np
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
REC = os.path.dirname(HERE)
|
||||
sys.path.insert(0, REC)
|
||||
import takes # noqa: E402 (hands/rec/takes.py)
|
||||
|
||||
GIFSICLE = os.environ.get("HANDDEMO_GIFSICLE") or shutil.which("gifsicle") or os.path.expanduser(
|
||||
"~/.cache/gifwork/gifsicle-src/src/gifsicle")
|
||||
|
||||
SCRIPT = os.path.join(REC, "script-v2.json")
|
||||
OUT = os.path.join(REC, "demos-recorded")
|
||||
W, H, SS = 640, 360, 2 # the clip, drawn at SS x SS and averaged down
|
||||
PITCH, HFOV = -30.0, 100.0 # the default view: degrees below straight ahead, wide
|
||||
DEPTH = 0.45 # metres: where the two side cameras' pictures meet
|
||||
FPS = 10 # the recorder's RECORD_HZ
|
||||
SIDES = ("slam_left", "slam_right")
|
||||
|
||||
|
||||
def _pose(d, scale=1.0):
|
||||
"""4x4 transform from a {plus_x, plus_z, position} pose (child axes in the parent frame)."""
|
||||
x = np.asarray(d["plus_x"], float)
|
||||
z = np.asarray(d["plus_z"], float)
|
||||
m = np.eye(4)
|
||||
m[:3, 0], m[:3, 1], m[:3, 2] = x, np.cross(z, x), z
|
||||
m[:3, 3] = np.asarray(d["position"], float) * scale
|
||||
return m
|
||||
|
||||
|
||||
class Fisheye:
|
||||
"""A side camera: Kannala-Brandt intrinsics, posed in the head frame (OpenVR: +x right, +y up,
|
||||
-z forward) as hands/track does it, from a session's calibration.json: "cameras" are posed in
|
||||
the first camera's frame, "cad" holds every camera and the head in the headset's CAD frame."""
|
||||
|
||||
def __init__(self, cal, name):
|
||||
i, c = next((i, c) for i, c in enumerate(cal["cameras"]) if c["sourceCamera"] == name)
|
||||
kb = next(k for k in c["intrinsics"] if k["cameraModel"] == "kb")
|
||||
self.fx, self.fy, self.cx, self.cy = kb["fx"], kb["fy"], kb["cx"], kb["cy"]
|
||||
self.k = [kb["k1"], kb["k2"], kb["k3"], kb["k4"]]
|
||||
self.width, self.height = c["width"], c["height"]
|
||||
head_from_cad = np.linalg.inv(_pose(cal["cad"]["__head"]))
|
||||
cad_from_cam0 = _pose(cal["cad"]["cameras"][0], 1e-3)
|
||||
head_from_cam = head_from_cad @ cad_from_cam0 @ _pose(c["extrinsics"], 1e-3)
|
||||
self.R, self.origin = head_from_cam[:3, :3], head_from_cam[:3, 3]
|
||||
|
||||
def project(self, p):
|
||||
"""Head-frame points (N,3) -> pixels (N,2) and the angle off the optical axis (N,), degrees."""
|
||||
q = (p - self.origin) @ self.R
|
||||
r = np.hypot(q[:, 0], q[:, 1])
|
||||
theta = np.arctan2(r, q[:, 2])
|
||||
t2 = theta * theta
|
||||
k1, k2, k3, k4 = self.k
|
||||
td = theta * (1 + t2 * (k1 + t2 * (k2 + t2 * (k3 + t2 * k4))))
|
||||
s = np.where(r > 1e-12, td / np.maximum(r, 1e-12), 0.0)
|
||||
uv = np.stack([self.fx * q[:, 0] * s + self.cx, self.fy * q[:, 1] * s + self.cy], axis=1)
|
||||
return uv, np.degrees(theta)
|
||||
|
||||
|
||||
def view_maps(cams, pitch, hfov, yaw=0.0):
|
||||
"""Per side camera: where each pixel of the virtual view samples it, and its weight."""
|
||||
w, h = W * SS, H * SS
|
||||
f = (w / 2) / np.tan(np.radians(hfov / 2))
|
||||
u, v = np.meshgrid(np.arange(w) - (w - 1) / 2, np.arange(h) - (h - 1) / 2)
|
||||
d = np.stack([u / f, -v / f, -np.ones_like(u)], -1).reshape(-1, 3)
|
||||
d /= np.linalg.norm(d, axis=1, keepdims=True)
|
||||
a, b = np.radians(pitch), np.radians(yaw)
|
||||
rx = np.array([[1, 0, 0], [0, np.cos(a), -np.sin(a)], [0, np.sin(a), np.cos(a)]])
|
||||
ry = np.array([[np.cos(b), 0, -np.sin(b)], [0, 1, 0], [np.sin(b), 0, np.cos(b)]])
|
||||
p = d @ (ry @ rx).T * DEPTH
|
||||
maps, total = {}, 0
|
||||
for name, cam in cams.items():
|
||||
uv, ang = cam.project(p)
|
||||
inside = (uv[:, 0] >= 0) & (uv[:, 0] <= cam.width - 1) & (uv[:, 1] >= 0) & (uv[:, 1] <= cam.height - 1)
|
||||
wt = np.where(inside, np.clip((88 - ang) / 48, 0, 1) ** 3, 0) # nearer the centre wins
|
||||
maps[name] = (uv[:, 0].reshape(h, w), uv[:, 1].reshape(h, w), wt.reshape(h, w))
|
||||
total = total + wt.reshape(h, w)
|
||||
return maps, np.maximum(total, 1e-6)
|
||||
|
||||
|
||||
def sample(img, x, y):
|
||||
"""Bilinear lookup of a grey image at float pixel positions."""
|
||||
x = np.clip(x, 0, img.shape[1] - 1.001)
|
||||
y = np.clip(y, 0, img.shape[0] - 1.001)
|
||||
x0, y0 = x.astype(np.int32), y.astype(np.int32)
|
||||
fx, fy = x - x0, y - y0
|
||||
a = img[y0, x0] * (1 - fx) + img[y0, x0 + 1] * fx
|
||||
b = img[y0 + 1, x0] * (1 - fx) + img[y0 + 1, x0 + 1] * fx
|
||||
return a * (1 - fy) + b * fy
|
||||
|
||||
|
||||
def render(maps, total, frames):
|
||||
acc = 0
|
||||
for name, (x, y, wt) in maps.items():
|
||||
acc = acc + sample(frames[name], x, y) * wt
|
||||
out = acc / total
|
||||
return out.reshape(H, SS, W, SS).mean(axis=(1, 3))
|
||||
|
||||
|
||||
def demo_steps(script):
|
||||
"""{demo id: [(section, hands), ...]} in the script's order, the step to use first: the
|
||||
right-hand one where the clip is a right hand's (mirrored for the left), else both hands."""
|
||||
steps = {}
|
||||
for sec in script["sections"]:
|
||||
for p in sec.get("prompts", []):
|
||||
if p.get("demo"):
|
||||
steps.setdefault(p["demo"], []).append((sec["id"], p.get("hands") or ""))
|
||||
rank = {"right": 0, "both": 1}
|
||||
return {d: sorted(s, key=lambda sh: rank.get(sh[1], 2)) for d, s in steps.items()}
|
||||
|
||||
|
||||
def find_window(session, section, demo, hands):
|
||||
"""(take dir, start ns, end ns) of the step's kept try, or None."""
|
||||
tdir = os.path.join(session, "takes")
|
||||
for name in sorted(os.listdir(tdir)):
|
||||
if not name.endswith("-" + section):
|
||||
continue
|
||||
take = os.path.join(tdir, name)
|
||||
prefix = "%s/%s/%s" % (section, demo, hands)
|
||||
t0 = t1 = None
|
||||
with open(os.path.join(take, "prompts.jsonl")) as f:
|
||||
for line in f:
|
||||
e = json.loads(line)
|
||||
ev = e.get("event")
|
||||
if ev == "prompt" and (e.get("id") == prefix or e.get("id", "").startswith(prefix + "/")):
|
||||
t0, t1 = e["t"], None
|
||||
elif t0 is not None and t1 is None and ev in ("wait", "redo", "end", "pause"):
|
||||
t1 = e["t"]
|
||||
if ev == "redo":
|
||||
t0 = None
|
||||
if t0 is not None:
|
||||
return take, t0, t1
|
||||
return None
|
||||
|
||||
|
||||
def clip_sets(take, t0, t1):
|
||||
ti = takes.TakeIndex(take)
|
||||
deleted = takes.read_json(os.path.join(take, "take.json")).get("deleted") or []
|
||||
keep = [i for i in range(len(ti)) if t0 <= ti.time_ns(i) <= (t1 or 1 << 62)
|
||||
and not any(a <= ti.time_ns(i) <= b for a, b in deleted)]
|
||||
return ti, keep
|
||||
|
||||
|
||||
def frames_of(ti, i):
|
||||
out = {}
|
||||
for c in ti.read_set(i):
|
||||
if c["name"] in SIDES:
|
||||
out[c["name"]] = np.frombuffer(c["pixels"], np.uint8).reshape(c["height"], c["width"]).astype(np.float32)
|
||||
return out
|
||||
|
||||
|
||||
def encode(clip, out, lossy, sheet):
|
||||
"""Grey uint8 frames (N,H,W) -> a looping GIF, or a contact sheet PNG."""
|
||||
raw_in = ["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "gray", "-s", "%dx%d" % (W, H),
|
||||
"-r", str(FPS), "-i", "-"]
|
||||
if sheet:
|
||||
n = len(clip[::2 * FPS])
|
||||
cols = min(4, n)
|
||||
rows = (n + cols - 1) // cols
|
||||
cmd = raw_in + ["-vf", "select=not(mod(n\\,%d)),scale=320:-2,tile=%dx%d" % (2 * FPS, cols, rows),
|
||||
"-frames:v", "1", out]
|
||||
subprocess.run(cmd, input=clip.tobytes(), check=True)
|
||||
return
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
raw = os.path.join(tmp, "raw.gif")
|
||||
cmd = raw_in + ["-vf", "split[a][b];[a]palettegen=max_colors=48:stats_mode=full[p];"
|
||||
"[b][p]paletteuse=dither=none:diff_mode=rectangle", "-loop", "0", raw]
|
||||
subprocess.run(cmd, input=clip.tobytes(), check=True)
|
||||
if os.access(GIFSICLE, os.X_OK):
|
||||
subprocess.run([GIFSICLE, "-O3", "--lossy=%d" % lossy, raw, "-o", out], check=True)
|
||||
else:
|
||||
os.replace(raw, out)
|
||||
|
||||
|
||||
def steady(clip, hold=12.0):
|
||||
"""Less sensor noise, for a GIF that compresses (10-15 MB a clip without it, about 1.5 with):
|
||||
two [1 2 1] blurs, then a pixel that changed by less than hold grey levels keeps its last
|
||||
value, so the still parts of a frame repeat the one before."""
|
||||
c = clip.astype(np.float32)
|
||||
for _ in range(2):
|
||||
c[:, 1:-1] = (c[:, :-2] + 2 * c[:, 1:-1] + c[:, 2:]) / 4
|
||||
c[:, :, 1:-1] = (c[:, :, :-2] + 2 * c[:, :, 1:-1] + c[:, :, 2:]) / 4
|
||||
for i in range(1, len(c)):
|
||||
same = np.abs(c[i] - c[i - 1]) < hold
|
||||
c[i][same] = c[i - 1][same]
|
||||
return c
|
||||
|
||||
|
||||
def stretch(clip):
|
||||
"""Levels per clip: the IR frames are dim and flat."""
|
||||
lo, hi = np.percentile(clip[::max(1, len(clip) // 20)], (1, 99.7))
|
||||
x = np.clip((clip - lo) / max(hi - lo, 1), 0, 1) ** 0.8
|
||||
return (x * 255 + 0.5).astype(np.uint8)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
||||
ap.add_argument("session")
|
||||
ap.add_argument("--out", default=OUT)
|
||||
ap.add_argument("--part", help="one demo clip id (e.g. 7a)")
|
||||
ap.add_argument("--sheets", action="store_true", help="contact sheets instead of GIFs")
|
||||
ap.add_argument("--view", action="append", default=[], metavar="ID=PITCH,HFOV[,YAW]")
|
||||
ap.add_argument("--lossy", type=int, default=70, help="gifsicle's lossy level")
|
||||
a = ap.parse_args()
|
||||
with open(SCRIPT) as f:
|
||||
script = json.load(f)
|
||||
with open(os.path.join(a.session, "calibration.json")) as f:
|
||||
cal = json.load(f)
|
||||
cams = {n: Fisheye(cal, n) for n in SIDES}
|
||||
os.makedirs(a.out, exist_ok=True)
|
||||
views = takes.read_json(os.path.join(a.out, "views.json")) or {}
|
||||
for v in a.view:
|
||||
part, _, vals = v.partition("=")
|
||||
views[part] = [float(x) for x in vals.split(",")]
|
||||
if a.view:
|
||||
with open(os.path.join(a.out, "views.json"), "w") as f:
|
||||
json.dump(views, f, indent=1, sort_keys=True)
|
||||
cache = {}
|
||||
for demo, steps in demo_steps(script).items():
|
||||
if a.part and demo != a.part:
|
||||
continue
|
||||
found = next(((s, h, w) for s, h in steps for w in [find_window(a.session, s, demo, h)] if w), None)
|
||||
if not found:
|
||||
print("%-4s not in this session" % demo)
|
||||
continue
|
||||
section, hands, (take, t0, t1) = found
|
||||
ti, keep = clip_sets(take, t0, t1)
|
||||
if not keep:
|
||||
print("%-4s %s/%s: no sets" % (demo, section, hands))
|
||||
continue
|
||||
view = tuple(views.get(demo) or (PITCH, HFOV))
|
||||
if view not in cache:
|
||||
cache[view] = view_maps(cams, *view)
|
||||
maps, total = cache[view]
|
||||
clip = stretch(steady(np.stack([render(maps, total, frames_of(ti, i)) for i in keep])))
|
||||
out = os.path.join(a.out, demo + (".png" if a.sheets else ".gif"))
|
||||
encode(clip, out, a.lossy, a.sheets)
|
||||
print("%-4s %-12s %-5s %5.1f s view %s %.2f MB" % (demo, section, hands, len(keep) / FPS,
|
||||
",".join("%g" % x for x in view),
|
||||
os.path.getsize(out) / 1e6), flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,216 @@
|
||||
{
|
||||
"version": 1,
|
||||
"note": "The demo GIFs for the hand recorder's v2 script: one recording per part, in this order. Motions are what the maintainer performs on camera; the plan is the Claude Doc ee05ba65 (Demo recordings, 2026-10-12).",
|
||||
"parts": [
|
||||
{
|
||||
"id": "1",
|
||||
"section": "Hand size",
|
||||
"motions": [
|
||||
"Both hands about 40 cm out, still",
|
||||
"Palms toward you, then backs toward you",
|
||||
"Fingers spread, then a fist, then point",
|
||||
"About 1 s for each shape"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "2a",
|
||||
"section": "Index taps",
|
||||
"title": "Wrist roll",
|
||||
"motions": [
|
||||
"One hand low and relaxed, other fingers loosely curled: look down at it",
|
||||
"2 light taps palm down",
|
||||
"2 taps edge-on, 2 palm up, 2 palm toward your face"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "2b",
|
||||
"section": "Index taps",
|
||||
"title": "Through the zones",
|
||||
"motions": [
|
||||
"Keep tapping while you move: centre at chest height",
|
||||
"Far out to your side, then crossed past the middle",
|
||||
"Close to your face, then at arm's length",
|
||||
"Quick taps, a double tap, one slow press"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "2c",
|
||||
"section": "Index taps",
|
||||
"title": "Both hands",
|
||||
"motions": [
|
||||
"Both hands tapping",
|
||||
"Then one hand over the other, still tapping"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "3a",
|
||||
"section": "Middle taps",
|
||||
"title": "Wrist roll and zones",
|
||||
"motions": [
|
||||
"Thumb to the middle finger's pad, index half-curled: look down at the hand",
|
||||
"2 taps palm down, edge-on, palm up, toward your face",
|
||||
"Then a few taps out to the side and close to your face"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "3b",
|
||||
"section": "Middle taps",
|
||||
"title": "Firm presses and a head turn",
|
||||
"motions": [
|
||||
"3 slow, firm presses",
|
||||
"Keep tapping and turn your head until the hand reaches the edge of the view",
|
||||
"Then turn the other way"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "4a",
|
||||
"section": "Look-alikes",
|
||||
"title": "Fingers",
|
||||
"motions": [
|
||||
"Stop 1 cm short of a tap",
|
||||
"Rub the thumb along the side of the index",
|
||||
"Ring finger to thumb",
|
||||
"Let a loosely curled hand rest"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "4b",
|
||||
"section": "Look-alikes",
|
||||
"title": "Fists",
|
||||
"motions": [
|
||||
"Close a fist slowly, open it",
|
||||
"Close it fast, open it",
|
||||
"Once at chest height, once low"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "5a",
|
||||
"section": "Hold and drag",
|
||||
"title": "One hand",
|
||||
"motions": [
|
||||
"Pinch and hold 3 s",
|
||||
"Drag up, down, left, right",
|
||||
"Roll the wrist while holding",
|
||||
"Loosen the other fingers without letting go"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "5b",
|
||||
"section": "Hold and drag",
|
||||
"title": "Two hands",
|
||||
"motions": [
|
||||
"One hand holds a pinch, the other taps",
|
||||
"Hands apart, then close, then crossed"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "6",
|
||||
"section": "Three-finger scroll",
|
||||
"motions": [
|
||||
"Thumb on the index and middle tips",
|
||||
"Move up and down slowly, then fast",
|
||||
"Let the ring finger join once"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "7a",
|
||||
"section": "Palm up",
|
||||
"title": "Fingertips drop",
|
||||
"motions": [
|
||||
"Arms forward, palms up, fingers flat: hands close (elbows tucked)",
|
||||
"Fingertips drop toward the floor and back: 1 slow, 2 fast",
|
||||
"Same with forearms half out, then arms straight",
|
||||
"One drop low at the waist, one at eye height"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "7b",
|
||||
"section": "Palm up",
|
||||
"title": "Fingertips rise",
|
||||
"motions": [
|
||||
"Palms up at the same three distances",
|
||||
"Fingertips curl up toward you and back: 1 slow, 2 fast each"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "7c",
|
||||
"section": "Palm up",
|
||||
"title": "Pinch while bent",
|
||||
"motions": [
|
||||
"Palm up, hold a pinch",
|
||||
"Drop the fingertips and raise them, still pinching",
|
||||
"Flip palm up and down with the wrist bent"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "8",
|
||||
"section": "Strokes and gestures",
|
||||
"motions": [
|
||||
"Lazy susan stroke each way, with the return stroke",
|
||||
"A wave",
|
||||
"5 s of talking with your hands"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "9a",
|
||||
"section": "Reach and pull",
|
||||
"title": "Grab that",
|
||||
"motions": [
|
||||
"Open palm at a far target",
|
||||
"Close to a fist and pull back"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "9b",
|
||||
"section": "Reach and pull",
|
||||
"title": "Push, flick, a real object",
|
||||
"motions": [
|
||||
"Push away, then flick away",
|
||||
"Reach for a cup or your phone"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "10",
|
||||
"section": "Fists",
|
||||
"motions": [
|
||||
"Two fists: hold, pull apart, push together",
|
||||
"Fists with the palms in, down, then up"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "11a",
|
||||
"section": "Edges and exits",
|
||||
"title": "Out and back",
|
||||
"motions": [
|
||||
"Right hand open: slide out past the right edge until gone, wait 1 s, back",
|
||||
"Same up past your face",
|
||||
"Left hand pinching: out past the left edge, then down past your lap"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "11b",
|
||||
"section": "Edges and exits",
|
||||
"title": "Crossing",
|
||||
"motions": [
|
||||
"Both hands cross fully to the opposite sides",
|
||||
"Hold a moment, come back"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "12",
|
||||
"section": "Desk work",
|
||||
"motions": [
|
||||
"Type a few words, use the mouse, pick up the phone",
|
||||
"One tap, then back to the keys"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "13",
|
||||
"section": "Controllers",
|
||||
"motions": [
|
||||
"Pick up the controllers, set them down",
|
||||
"A tap in between"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
+80
-12
@@ -7,8 +7,9 @@ A Kirigami (QML) app with a Python backend. It runs in the dev container:
|
||||
- Before you start: the checklist (objects, controller straps, lighting, sleeves, privacy,
|
||||
free space), the camera check (hands/camcheck.py: Start stays off while the upper cameras
|
||||
are off, with a Restart SteamVR button; --ignore-cameras overrides it), a full session or a
|
||||
quick round (suggested once a full one is done) and what will happen. Start hands it to
|
||||
the session runner (session.py).
|
||||
quick round (suggested once a full one is done), the demo clips to follow when the script
|
||||
has them (recorded hands or skeleton hands, kept in settings.json) and what will happen.
|
||||
Start hands it to the session runner (session.py).
|
||||
- Session: the runner's live status with the step's pose picture and where-to diagram, Next,
|
||||
Pause/Resume, Redo, Skip section and Stop (Space: Next, P, R, S and Esc while the window has
|
||||
focus; the button on the headset's right side is Next, pause and resume). The prompts appear
|
||||
@@ -24,7 +25,9 @@ Everything lives under ~/.local/share/frametop/hands/contrib (--base). Nothing i
|
||||
unless the person presses Upload; while CONSENT.md or UPLOAD.md is a draft, Upload stays off
|
||||
unless FT_HANDREC_ALLOW_UPLOAD=1 (the maintainer's rehearsal against a test repo, picked with
|
||||
FT_HANDREC_DATASET). --hub-dry-run does everything but the network calls.
|
||||
Launch with hands/rec/ft-handrec (host wrapper).
|
||||
Launch with hands/rec/ft-handrec (host wrapper). The standalone Hand Recorder
|
||||
(github.com/Frametop/frametop-hand-recorder) runs this backend on the host, from a venv, with
|
||||
its own window for SteamVR's dashboard: --qml its main.qml, --style Basic.
|
||||
"""
|
||||
import argparse
|
||||
import datetime
|
||||
@@ -43,6 +46,7 @@ from PySide6.QtGui import QColor, QDesktopServices, QFont, QGuiApplication, QIco
|
||||
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__))
|
||||
sys.path.insert(0, HERE)
|
||||
@@ -220,6 +224,7 @@ class Backend(QObject):
|
||||
_uploadFinished = Signal(dict)
|
||||
cameraChanged = Signal()
|
||||
_cameraArrived = Signal(dict)
|
||||
guidanceChanged = Signal()
|
||||
|
||||
def __init__(self, store, session_options=None, hub_dry_run=False, ignore_cameras=False):
|
||||
super().__init__()
|
||||
@@ -292,6 +297,11 @@ class Backend(QObject):
|
||||
def consentText(self):
|
||||
return read_text(CONSENT_PATH) or "CONSENT.md is missing."
|
||||
|
||||
@Property(str, constant=True)
|
||||
def toolVersion(self):
|
||||
"""What session.json records as the tool (takes.tool_version), for the window to show."""
|
||||
return takes.tool_version()
|
||||
|
||||
@Property(str, constant=True)
|
||||
def consentVersion(self):
|
||||
return consent_version()
|
||||
@@ -343,6 +353,41 @@ class Backend(QObject):
|
||||
self.profileChanged.emit()
|
||||
self.message.emit("Thank you. Your contributor id: " + profile["contributor"], False)
|
||||
|
||||
# --- the demo clips to follow (the v2 script): kept in BASE/settings.json
|
||||
@Property(bool, constant=True)
|
||||
def scriptHasDemos(self):
|
||||
mod = self._runner()
|
||||
try:
|
||||
script = mod.load_script(SCRIPT_PATH) if mod else {}
|
||||
except Exception:
|
||||
return False
|
||||
return any(p.get("demo") for sec in script.get("sections", []) for p in sec.get("prompts", []))
|
||||
|
||||
@Property("QVariantList", constant=True)
|
||||
def guidanceChoices(self):
|
||||
mod = self._runner()
|
||||
return [{"value": k, "text": v} for k, v in (mod.GUIDANCE if mod else ())]
|
||||
|
||||
@Property(str, notify=guidanceChanged)
|
||||
def guidance(self):
|
||||
mod = self._runner()
|
||||
if not mod:
|
||||
return ""
|
||||
chosen = takes.read_json(os.path.join(self.store.base, "settings.json")).get("guidance")
|
||||
return chosen if chosen in dict(mod.GUIDANCE) else mod.default_guidance(
|
||||
self._session_options.get("recorded_demos_dir"))
|
||||
|
||||
@Slot(str)
|
||||
def setGuidance(self, value):
|
||||
mod = self._runner()
|
||||
if not mod or value not in dict(mod.GUIDANCE) or value == self.guidance:
|
||||
return
|
||||
path = os.path.join(self.store.base, "settings.json")
|
||||
settings = takes.read_json(path)
|
||||
settings["guidance"] = value
|
||||
takes.write_json(path, settings)
|
||||
self.guidanceChanged.emit()
|
||||
|
||||
# --- the checklist
|
||||
@Property("QVariantList", constant=True)
|
||||
def objects(self):
|
||||
@@ -389,7 +434,8 @@ class Backend(QObject):
|
||||
measured = ""
|
||||
try:
|
||||
ring = mod.ring_lighting()
|
||||
if ring is None and not self.sessionActive:
|
||||
# A dry run starts nothing, the camera broker included.
|
||||
if ring is None and not self.sessionActive and not self._session_options.get("dry_run"):
|
||||
if mod.start_camd():
|
||||
self._camd_started = True
|
||||
time.sleep(1.0) # the first near-black frames
|
||||
@@ -457,11 +503,12 @@ class Backend(QObject):
|
||||
"""Start stays off: the check found the cameras degraded (unless --ignore-cameras)."""
|
||||
return not self._ignore_cameras and self._camera.get("status") == "degraded"
|
||||
|
||||
def _check_now(self):
|
||||
def _check_now(self, repair=False):
|
||||
"""repair (off this thread only: it may restart ft-camd, up to 15 s): see session.camera_check."""
|
||||
mod = self._runner()
|
||||
if not mod or self._session_options.get("dry_run"):
|
||||
return {"status": "unknown", "summary": "not checked (dry run)", "reason": "dry run", "evidence": []}
|
||||
return mod.camera_check()
|
||||
return mod.camera_check(repair=repair)
|
||||
|
||||
@Slot()
|
||||
def checkCameras(self):
|
||||
@@ -470,7 +517,7 @@ class Backend(QObject):
|
||||
return
|
||||
self._camera_busy = True
|
||||
self.cameraChanged.emit()
|
||||
self._thread(lambda: self._cameraArrived.emit(self._check_now()))
|
||||
self._thread(lambda: self._cameraArrived.emit(self._check_now(repair=True)))
|
||||
|
||||
def _on_camera(self, result):
|
||||
self._camera = result
|
||||
@@ -499,7 +546,7 @@ class Backend(QObject):
|
||||
end = time.monotonic() + RECHECK_FOR_S
|
||||
time.sleep(RECHECK_S * 2)
|
||||
while time.monotonic() < end:
|
||||
result = self._check_now()
|
||||
result = self._check_now(repair=True)
|
||||
# Done once a new XRService (a new log) has opened its cameras, ok or not.
|
||||
if result.get("status") in ("ok", "degraded") and result.get("log") != before:
|
||||
break
|
||||
@@ -570,7 +617,7 @@ class Backend(QObject):
|
||||
try:
|
||||
self._session = mod.Session(self.store.base, self.store.profile(), checklist, lighting, SCRIPT_PATH,
|
||||
on_status=lambda s: self._statusArrived.emit(dict(s)), auto=auto,
|
||||
quick=quick, **self._session_options)
|
||||
quick=quick, guidance=self.guidance, **self._session_options)
|
||||
except Exception as e:
|
||||
self.message.emit(f"Couldn't set up the session: {e}", True)
|
||||
return False
|
||||
@@ -1166,12 +1213,19 @@ def main():
|
||||
help="test: sessions start no processes and print the panel's commands")
|
||||
ap.add_argument("--speed", type=float, default=1.0, help="test, with --dry-run: run sessions this much faster")
|
||||
ap.add_argument("--poses", help="test: the pose pictures' folder (default hands/rec/poses)")
|
||||
ap.add_argument("--script", help="the recording script (default hands/rec/script.json; script-v2.json: "
|
||||
"the v2 script with demo clips)")
|
||||
ap.add_argument("--demos", help="the skeleton demo clips' folder, <id>.gif (default hands/rec/demos)")
|
||||
ap.add_argument("--recorded-demos", help="the recorded demo clips' folder (default hands/rec/demos-recorded)")
|
||||
ap.add_argument("--no-headset-button", action="store_true",
|
||||
help="sessions 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-cameras", action="store_true",
|
||||
help="start sessions even if the camera check (hands/camcheck.py) finds the upper cameras off")
|
||||
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-handrec")
|
||||
@@ -1179,22 +1233,32 @@ def main():
|
||||
app.setDesktopFileName("ft-handrec")
|
||||
if not QIcon.themeName():
|
||||
QIcon.setThemeName("breeze")
|
||||
QQuickStyle.setStyle("org.kde.desktop")
|
||||
QQuickStyle.setStyle(a.style)
|
||||
store = takes.Store(a.base)
|
||||
engine = QQmlApplicationEngine()
|
||||
engine.addImageProvider("frames", FrameProvider(store))
|
||||
options = {"dry_run": True, "speed": a.speed} if a.dry_run else {}
|
||||
if a.poses:
|
||||
options["poses_dir"] = a.poses
|
||||
if a.demos:
|
||||
options["demos_dir"] = a.demos
|
||||
if a.recorded_demos:
|
||||
options["recorded_demos_dir"] = a.recorded_demos
|
||||
if a.script:
|
||||
global SCRIPT_PATH
|
||||
SCRIPT_PATH = os.path.abspath(a.script if os.path.exists(a.script) else os.path.join(HERE, a.script))
|
||||
if a.no_headset_button:
|
||||
options["button"] = False
|
||||
if a.ignore_cameras:
|
||||
options["check_cameras"] = False
|
||||
backend = Backend(store, options, hub_dry_run=a.hub_dry_run, ignore_cameras=a.ignore_cameras)
|
||||
app.aboutToQuit.connect(backend.shutdown)
|
||||
mod = None if a.dry_run else backend._runner()
|
||||
if mod: # Frametop's drawn hands and hand pointer, if a session that was killed left them 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.join(HERE, "main.qml")))
|
||||
engine.load(QUrl.fromLocalFile(os.path.abspath(a.qml)))
|
||||
if not engine.rootObjects():
|
||||
sys.exit(1)
|
||||
|
||||
@@ -1207,7 +1271,11 @@ def main():
|
||||
signal.signal(signal.SIGINT, on_signal)
|
||||
tick = QTimer(interval=500, timeout=lambda: None)
|
||||
tick.start()
|
||||
sys.exit(app.exec())
|
||||
code = app.exec()
|
||||
# The window goes before the backend: otherwise its bindings run again against a deleted
|
||||
# backend as Python tears down ("Cannot read property ... of null", one per binding).
|
||||
shiboken6.delete(engine)
|
||||
sys.exit(code)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -7,7 +7,9 @@
|
||||
# "Launch a program", which runs apps outside it; the standalone recorder is for that).
|
||||
# It doesn't turn on Frametop's live hand tracking (that's hands/run.sh install, still deferred).
|
||||
# Usage: hands/rec/install.sh install or update
|
||||
# hands/rec/install.sh uninstall remove the menu entry (recordings stay where they are)
|
||||
# hands/rec/install.sh uninstall remove the menu entry, and ft-camd's capabilities unless
|
||||
# hand tracking's services use them (hands/run.sh uncaps).
|
||||
# Recordings stay where they are.
|
||||
set -euo pipefail
|
||||
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
. "$root/scripts/_env.sh"
|
||||
@@ -23,6 +25,7 @@ case ${1:-install} in
|
||||
"$root/hands/rec/build.sh"
|
||||
echo "== 4/4 ft-camd's capabilities (asks for your password) and the menu entry"
|
||||
"$root/hands/run.sh" caps
|
||||
"$root/scripts/conf-migrate.sh" # HANDS_SWAP_SIDES=0, the old default, becomes auto
|
||||
fill_template "$root/hands/rec/ft-handrec.desktop" |
|
||||
on_frame "mkdir -p ~/.local/share/applications && cat > $entry"
|
||||
echo
|
||||
@@ -31,7 +34,9 @@ case ${1:-install} in
|
||||
;;
|
||||
uninstall)
|
||||
on_frame "rm -f $entry"
|
||||
echo "Removed the menu entry. Your recordings are still in ~/.local/share/frametop/hands/contrib:"
|
||||
echo "Removed the menu entry."
|
||||
"$root/hands/run.sh" uncaps # after the entry, which counts as a user of the capabilities
|
||||
echo "Your recordings are still in ~/.local/share/frametop/hands/contrib:"
|
||||
echo "delete that folder to remove them."
|
||||
;;
|
||||
*) echo "usage: $0 [install|uninstall]" >&2; exit 2 ;;
|
||||
|
||||
+80
-4
@@ -362,7 +362,8 @@ Kirigami.ApplicationWindow {
|
||||
wrapMode: Text.Wrap
|
||||
opacity: 0.7
|
||||
text: "Each round in a different light helps the most: dim, a normal room, daylight. The cameras "
|
||||
+ "tell daylight from indoor light themselves; to say dim or a normal room, pick it here."
|
||||
+ "can't tell daylight on their own (a sunlit room has measured as indoor light), so if "
|
||||
+ "sunlight comes into the room, pick Daylight here; dim or a normal room the same way."
|
||||
}
|
||||
Kirigami.InlineMessage {
|
||||
Layout.maximumWidth: Kirigami.Units.gridUnit * 26
|
||||
@@ -486,7 +487,8 @@ Kirigami.ApplicationWindow {
|
||||
+ "Each step waits until you're ready: press the button on the right side of the headset, "
|
||||
+ "or Space or Next in this window. A 3-2-1 "
|
||||
+ "countdown follows, then hold the pose until the bar runs out. Nothing is recorded while "
|
||||
+ "a step waits. The headset button also pauses and resumes a recording. In this window P "
|
||||
+ "a step waits. The headset button also pauses and resumes a recording; press it twice "
|
||||
+ "to record a step again, or hold it to stop. In this window P "
|
||||
+ "pauses, R records the last step again, S skips a section and Esc stops.\n\n"
|
||||
+ "Nothing leaves the headset. Afterwards you watch the takes in Review, delete anything "
|
||||
+ "you don't want to share, and only then export."
|
||||
@@ -527,6 +529,21 @@ Kirigami.ApplicationWindow {
|
||||
+ "know the steps already. "
|
||||
: "") + "Length: " + backend.planText(checklist.answers(), autoAdvance.checked, quickRound.checked) + "."
|
||||
}
|
||||
ColumnLayout {
|
||||
Kirigami.FormData.label: "Guidance:"
|
||||
visible: backend.scriptHasDemos
|
||||
Repeater {
|
||||
model: backend.guidanceChoices
|
||||
Controls.RadioButton {
|
||||
required property var modelData
|
||||
text: modelData.text + (modelData.value === "recorded"
|
||||
? ": clips of a real person's hands, from the headset's cameras"
|
||||
: ": a drawn hand, its palm light and its back dark")
|
||||
checked: backend.guidance === modelData.value
|
||||
onToggled: if (checked) backend.setGuidance(modelData.value)
|
||||
}
|
||||
}
|
||||
}
|
||||
Controls.Button {
|
||||
text: "Start"
|
||||
icon.name: "media-record"
|
||||
@@ -634,6 +651,55 @@ Kirigami.ApplicationWindow {
|
||||
}
|
||||
}
|
||||
|
||||
// A demo clip as the panel plays it (DESIGN.md "Demo clips"): looped, a left hand's
|
||||
// flipped, from its start again when a hold starts (run counts the starts), the key
|
||||
// to a skeleton clip's colours under it.
|
||||
component DemoClip: ColumnLayout {
|
||||
id: demoClip
|
||||
property string path
|
||||
property string mode
|
||||
property int run
|
||||
property bool paused
|
||||
property bool key: true
|
||||
spacing: Kirigami.Units.smallSpacing
|
||||
visible: path !== ""
|
||||
onRunChanged: clip.currentFrame = 0
|
||||
AnimatedImage {
|
||||
id: clip
|
||||
Layout.preferredWidth: Kirigami.Units.gridUnit * 20
|
||||
Layout.preferredHeight: Layout.preferredWidth * 9 / 16
|
||||
source: demoClip.path ? "file://" + demoClip.path : ""
|
||||
fillMode: Image.PreserveAspectFit
|
||||
mirror: demoClip.mode === "mirror"
|
||||
playing: demoClip.visible && !demoClip.paused
|
||||
cache: false
|
||||
smooth: true
|
||||
}
|
||||
RowLayout {
|
||||
Layout.alignment: Qt.AlignHCenter
|
||||
visible: demoClip.key
|
||||
spacing: Kirigami.Units.largeSpacing
|
||||
Repeater {
|
||||
model: [{ color: "#d5d1fe", text: "Light: palm" }, { color: "#6a62d8", text: "Dark: back of hand" }]
|
||||
RowLayout {
|
||||
required property var modelData
|
||||
spacing: Kirigami.Units.smallSpacing
|
||||
Rectangle {
|
||||
implicitWidth: Kirigami.Units.gridUnit * 0.8
|
||||
implicitHeight: implicitWidth
|
||||
radius: implicitWidth / 4
|
||||
color: parent.modelData.color
|
||||
}
|
||||
Controls.Label {
|
||||
text: parent.modelData.text
|
||||
font: Kirigami.Theme.smallFont
|
||||
opacity: 0.8
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Where to hold the hands: a front view (left, centre, right, up, down; the push
|
||||
// sections' chest, desk and eye) and how far out (near, mid, far), as on the panel.
|
||||
component WhereDiagram: RowLayout {
|
||||
@@ -778,8 +844,17 @@ Kirigami.ApplicationWindow {
|
||||
spacing: Kirigami.Units.gridUnit * 1.5
|
||||
|
||||
ColumnLayout {
|
||||
visible: !!sessionView.st.image || !!sessionView.st.position || !!sessionView.st.distance
|
||||
visible: !!sessionView.st.image || !!sessionView.st.demo || !!sessionView.st.position
|
||||
|| !!sessionView.st.distance
|
||||
spacing: Kirigami.Units.largeSpacing
|
||||
DemoClip {
|
||||
Layout.alignment: Qt.AlignHCenter
|
||||
path: sessionView.st.demo || ""
|
||||
mode: sessionView.st.demo_mode || ""
|
||||
run: sessionView.st.demo_run || 0
|
||||
paused: sessionView.state === "paused"
|
||||
key: !!sessionView.st.demo_key
|
||||
}
|
||||
PosePicture {
|
||||
Layout.alignment: Qt.AlignHCenter
|
||||
path: sessionView.st.image || ""
|
||||
@@ -919,7 +994,8 @@ Kirigami.ApplicationWindow {
|
||||
opacity: 0.7
|
||||
text: "The instructions appear in the headset. "
|
||||
+ (sessionView.st.button ? "The button on the right side of the headset: "
|
||||
+ (sessionView.stepMode ? "next, " : "") + "pause or resume. " : "")
|
||||
+ (sessionView.stepMode ? "next, " : "") + "pause or resume; twice: record "
|
||||
+ "the last step again; hold: stop. " : "")
|
||||
+ "While this window has focus: "
|
||||
+ (sessionView.stepMode ? "Space: next · " : "")
|
||||
+ "P: pause or resume · R: record the last step again · S: skip section · Esc: stop. "
|
||||
|
||||
@@ -28,6 +28,14 @@
|
||||
// the pose picture (a PNG, square, RGBA, a right hand as the wearer
|
||||
// sees it) in a column on the left, the text moving right: mirror
|
||||
// flips it (a left hand), both shows a flipped copy on its left
|
||||
// demo <path> [mirror] [nokey] / demo restart / demo off
|
||||
// a demo clip (an animated GIF, hands/rec/demos) playing in a wider
|
||||
// column on the left, looped, with the key to its colours under it
|
||||
// (light: palm, dark: back of hand; nokey: none, for a clip of
|
||||
// real hands from hands/rec/demos-recorded); it takes the place of the
|
||||
// image. A new path starts it from its first frame, the same one
|
||||
// again leaves it playing (mirror only flips it), restart starts
|
||||
// it again. It stands still while paused
|
||||
// where <position|-> <distance|-> / where off
|
||||
// a small diagram under the picture: where to hold the hands, a
|
||||
// front view (centre, left, right, up, down; or the bar's chest,
|
||||
@@ -63,14 +71,17 @@
|
||||
// Each picture goes into the next of three shared buffers (linear DMA-BUFs SteamVR imported
|
||||
// once), and the overlay switches to it, as gaze/panel/ft-gazepanel.cpp does: SetOverlayRaw
|
||||
// flickered and lagged there, so it's only the fallback. The target has its own three small
|
||||
// buffers. Pictures are drawn only when a command changed something.
|
||||
// buffers. Pictures are drawn only when a command changed something; while a demo clip plays,
|
||||
// each of its frames redraws only the clip's rectangle, and copies only that to a buffer that
|
||||
// already has the rest.
|
||||
//
|
||||
// The pose log runs on a thread of its own, so a slow picture or command never delays a
|
||||
// sample. OpenVR's client isn't documented as thread-safe, so both threads take g_vr around
|
||||
// every OpenVR call.
|
||||
//
|
||||
// Options: --watch-stdin (quit when stdin closes: the session runs it), --socket NAME,
|
||||
// --distance METRES, --no-vr. --no-vr is for testing without a headset: no SteamVR at all; each
|
||||
// --distance METRES, --up DEG and --width DEG (UP_DEG and WIDTH_DEG: raise it out of a
|
||||
// recorded headset view), --no-vr. --no-vr is for testing without a headset: no SteamVR at all; each
|
||||
// picture's text goes to stdout instead (and with --dump DIR, the pictures to DIR/panel.pam
|
||||
// and DIR/target.pam), "poses start" writes nothing, "devices" and "head" reply with an error,
|
||||
// and "target" places the point as if the headset were at the room's origin.
|
||||
@@ -81,6 +92,7 @@
|
||||
#include "stb_truetype.h"
|
||||
#define STB_IMAGE_IMPLEMENTATION
|
||||
#define STBI_ONLY_PNG
|
||||
#define STBI_ONLY_GIF
|
||||
#define STBI_NO_HDR
|
||||
#define STBI_NO_LINEAR
|
||||
#pragma GCC diagnostic push
|
||||
@@ -107,6 +119,7 @@
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
@@ -372,6 +385,100 @@ Image &StripImage(const std::string &path) {
|
||||
}
|
||||
|
||||
// The where-to diagram's cells: a front view, 3 x 3, (column, row) from the top left.
|
||||
// A demo clip: an animated GIF decoded a frame at a time as it plays, so a long clip holds
|
||||
// three frames in memory, not all of them. stb_image keeps its GIF decoder to itself, but this
|
||||
// file compiles it, so it steps stbi__gif_load_next as stbi_load_gif_from_memory does.
|
||||
struct Demo {
|
||||
std::string path;
|
||||
bool mirror = false;
|
||||
bool key = true; // the key to the skeleton clips' colours under it
|
||||
std::vector<uint8_t> file;
|
||||
stbi__context ctx{};
|
||||
stbi__gif g{};
|
||||
int w = 0, h = 0, frame = -1; // frame: from 0 at the clip's start
|
||||
int loops = 0; // times it went back to the start by itself
|
||||
std::vector<uint8_t> cur, prev; // this frame and the one before (GIF's "restore to previous")
|
||||
int64_t due = 0; // when the next frame shows (NowNs)
|
||||
Picture scaled{0, 0, {}}; // this frame as drawn
|
||||
bool fresh = false; // scaled is out of date
|
||||
|
||||
Demo() = default;
|
||||
Demo(const Demo &) = delete;
|
||||
Demo &operator=(const Demo &) = delete;
|
||||
~Demo() { Free(); }
|
||||
|
||||
void Free() {
|
||||
STBI_FREE(g.out), STBI_FREE(g.history), STBI_FREE(g.background);
|
||||
std::memset(&g, 0, sizeof g);
|
||||
}
|
||||
|
||||
bool Load(const std::string &p) {
|
||||
FILE *f = std::fopen(p.c_str(), "rb");
|
||||
if (!f) return stbi__err("can't open file", "can't open file"), false;
|
||||
uint8_t chunk[65536];
|
||||
size_t n;
|
||||
while ((n = std::fread(chunk, 1, sizeof chunk, f)) > 0) file.insert(file.end(), chunk, chunk + n);
|
||||
std::fclose(f);
|
||||
path = p;
|
||||
return Start(NowNs());
|
||||
}
|
||||
|
||||
// From the first frame again.
|
||||
bool Start(int64_t now) {
|
||||
Free();
|
||||
stbi__start_mem(&ctx, file.data(), int(file.size()));
|
||||
cur.clear(), prev.clear(), frame = -1;
|
||||
return Next(now, false);
|
||||
}
|
||||
|
||||
// The next frame into cur, the first again after the last. false: the file is no GIF, or broken.
|
||||
bool Next(int64_t now, bool loop = true) {
|
||||
int comp = 0;
|
||||
stbi_uc *u = stbi__gif_load_next(&ctx, &g, &comp, 4, prev.empty() ? nullptr : prev.data());
|
||||
if (u == reinterpret_cast<stbi_uc *>(&ctx)) return loop && frame >= 0 && (++loops, Start(now)); // the end
|
||||
if (!u) return false;
|
||||
w = g.w, h = g.h, ++frame;
|
||||
prev.swap(cur);
|
||||
cur.assign(u, u + size_t(w) * h * 4);
|
||||
// As browsers: a delay under 20 ms is 100 ms.
|
||||
due = now + int64_t(g.delay >= 20 ? g.delay : 100) * 1'000'000;
|
||||
fresh = true;
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
// The demo's frame drawn opaque at x0, y0 in dw x dh, averaging the source pixels each output
|
||||
// pixel covers (the frame is scaled again only when it or the size changed).
|
||||
void DrawDemo(Picture &pic, Demo &d, int x0, int y0, int dw, int dh) {
|
||||
if (d.cur.empty() || dw <= 0 || dh <= 0) return;
|
||||
if (d.fresh || d.scaled.w != dw || d.scaled.h != dh) {
|
||||
d.scaled = Picture{dw, dh, std::vector<uint8_t>(size_t(dw) * dh * 4)};
|
||||
const double sx = double(d.w) / dw, sy = double(d.h) / dh;
|
||||
for (int y = 0; y < dh; ++y) {
|
||||
const int ya = std::min(d.h - 1, int(y * sy)), yb = std::clamp(int(std::ceil((y + 1) * sy)), ya + 1, d.h);
|
||||
for (int x = 0; x < dw; ++x) {
|
||||
const int xa = std::min(d.w - 1, int(x * sx)), xb = std::clamp(int(std::ceil((x + 1) * sx)), xa + 1, d.w);
|
||||
unsigned r = 0, g = 0, b = 0, n = 0;
|
||||
for (int yy = ya; yy < yb; ++yy)
|
||||
for (int xx = xa; xx < xb; ++xx) {
|
||||
const uint8_t *q = &d.cur[(size_t(yy) * d.w + (d.mirror ? d.w - 1 - xx : xx)) * 4];
|
||||
r += q[0], g += q[1], b += q[2], ++n;
|
||||
}
|
||||
uint8_t *o = &d.scaled.px[(size_t(y) * dw + x) * 4];
|
||||
o[0] = uint8_t(r / n), o[1] = uint8_t(g / n), o[2] = uint8_t(b / n), o[3] = 255;
|
||||
}
|
||||
}
|
||||
d.fresh = false;
|
||||
}
|
||||
for (int y = 0; y < dh; ++y) {
|
||||
if (y0 + y < 0 || y0 + y >= pic.h) continue;
|
||||
const int xa = std::max(0, -x0), xb = std::min(dw, pic.w - x0);
|
||||
if (xb > xa)
|
||||
std::memcpy(&pic.px[(size_t(y0 + y) * pic.w + x0 + xa) * 4], &d.scaled.px[(size_t(y) * dw + xa) * 4],
|
||||
size_t(xb - xa) * 4);
|
||||
}
|
||||
}
|
||||
|
||||
bool WhereCell(const std::string &pos, int &col, int &row) {
|
||||
col = 1, row = 1;
|
||||
if (pos == "left") col = 0;
|
||||
@@ -398,6 +505,9 @@ int DistanceStep(const std::string &dist) { return dist == "near" ? 0 : dist ==
|
||||
const char *DistanceLabel(int k) { return k == 0 ? "Close" : k == 1 ? "Halfway out" : "Arm out"; }
|
||||
|
||||
constexpr double kCyan[3] = {0.3, 0.85, 1.0};
|
||||
// The demo clips' palm and back of the hand (hands/rec/demos): the key's swatches.
|
||||
constexpr double kPalm[3] = {0xd5 / 255.0, 0xd1 / 255.0, 0xfe / 255.0};
|
||||
constexpr double kBack[3] = {0x6a / 255.0, 0x62 / 255.0, 0xd8 / 255.0};
|
||||
|
||||
// The diagram in x0..x0+w, y0..y0+h: the front view on the left, the distance on the right
|
||||
// (or either alone, centred), each with its caption under it.
|
||||
@@ -455,6 +565,8 @@ struct Panel {
|
||||
std::string wherePos, whereDist; // the diagram's, "" for none
|
||||
std::vector<StripItem> strip; // a sweep's pictures, or none
|
||||
int stripCue = -1; // the lit one
|
||||
std::unique_ptr<Demo> demo; // the demo clip, or none
|
||||
int demoX = 0, demoY = 0, demoW = 0, demoH = 0; // where the last Draw put it (demoW 0: nowhere)
|
||||
// What the last Draw laid out, for --no-vr's printout.
|
||||
std::vector<std::string> lines, noteLines;
|
||||
double textDeg = 0;
|
||||
@@ -470,6 +582,7 @@ void Draw(Panel &p) {
|
||||
}
|
||||
Picture &pic = p.pic;
|
||||
pic.px = back.px;
|
||||
p.demoW = 0;
|
||||
const double ppd = kPxPerDeg, faint = 0.75;
|
||||
const int margin = int(ppd * 1.6), width = kW - 2 * margin;
|
||||
|
||||
@@ -533,7 +646,8 @@ void Draw(Panel &p) {
|
||||
// diagram at its right end; the text goes above it.
|
||||
int textX0 = margin, textX1 = kW - margin;
|
||||
int col, row;
|
||||
const bool imageOn = !p.image.path.empty() && p.strip.empty();
|
||||
const bool demoOn = p.demo && p.strip.empty();
|
||||
const bool imageOn = !p.image.path.empty() && p.strip.empty() && !demoOn;
|
||||
const bool whereOn = WhereCell(p.wherePos, col, row) || DistanceStep(p.whereDist) >= 0;
|
||||
if (!p.strip.empty()) {
|
||||
const int n = int(p.strip.size()), gap = int(ppd * 0.6), whereW = whereOn ? int(ppd * 9) : 0;
|
||||
@@ -556,6 +670,37 @@ void Draw(Panel &p) {
|
||||
if (whereOn) DrawWhere(pic, kW - margin - whereW, y0 + (side + labelH - int(ppd * 4.4)) / 2, whereW, int(ppd * 4.4),
|
||||
p.wherePos, p.whereDist);
|
||||
bottom = y0 - frame - int(ppd * 0.8);
|
||||
} else if (demoOn) {
|
||||
// The demo clip in a wider column, the key to its colours under it (on one line if it
|
||||
// fits; none for a clip of real hands), the text to the right.
|
||||
const int colW = int(ppd * 16), gap = int(ppd * 0.6), keySize = int(ppd * 0.75), keyLh = int(keySize * 1.6);
|
||||
const int sw = std::max(1, p.demo->w), sh = std::max(1, p.demo->h), swatch = keySize, sgap = int(ppd * 0.3);
|
||||
const std::string light = "Light: palm", dark = "Dark: back of hand";
|
||||
const int lightW = swatch + sgap + TextWidth(light, keySize), darkW = swatch + sgap + TextWidth(dark, keySize);
|
||||
const bool keyOn = p.demo->key, oneLine = lightW + int(ppd) + darkW <= colW;
|
||||
const int room = bottom - top - (keyOn ? gap + (oneLine ? 1 : 2) * keyLh : 0);
|
||||
int dw = colW, dh = dw * sh / sw;
|
||||
if (dh > room) dh = std::max(0, room), dw = dh * sw / sh;
|
||||
int y = top + std::max(0, (room - dh) / 2);
|
||||
const int x = margin + (colW - dw) / 2;
|
||||
RoundRect(pic, x - gap / 2, y - gap / 2, x + dw + gap / 2, y + dh + gap / 2, ppd * 0.6, 1, 1, 1, 0.05);
|
||||
DrawDemo(pic, *p.demo, x, y, dw, dh);
|
||||
p.demoX = x, p.demoY = y, p.demoW = dw, p.demoH = dh;
|
||||
y += dh + gap;
|
||||
auto key = [&](const std::string &label, const double *c, int kx, int cy) {
|
||||
RoundRect(pic, kx, cy - swatch / 2, kx + swatch, cy + swatch / 2, swatch * 0.25, c[0], c[1], c[2], 1);
|
||||
Text(pic, label, keySize, kx + swatch + sgap, cy, 0.85, kLeft);
|
||||
};
|
||||
if (keyOn && oneLine) {
|
||||
const int kx = margin + (colW - lightW - int(ppd) - darkW) / 2;
|
||||
key(light, kPalm, kx, y + keyLh / 2);
|
||||
key(dark, kBack, kx + lightW + int(ppd), y + keyLh / 2);
|
||||
} else if (keyOn) {
|
||||
const int kx = margin + (colW - std::max(lightW, darkW)) / 2;
|
||||
key(light, kPalm, kx, y + keyLh / 2);
|
||||
key(dark, kBack, kx, y + keyLh + keyLh / 2);
|
||||
}
|
||||
textX0 = margin + colW + int(ppd * 1.2);
|
||||
} else if (imageOn || whereOn) {
|
||||
const int colW = int(ppd * 14), gap = int(ppd * 0.6);
|
||||
const int whereH = whereOn ? int(ppd * 4.4) : 0, between = imageOn && whereOn ? gap : 0;
|
||||
@@ -577,6 +722,9 @@ void Draw(Panel &p) {
|
||||
textX0 = margin + colW + int(ppd * 1.2);
|
||||
}
|
||||
const int textW = textX1 - textX0, textCx = (textX0 + textX1) / 2;
|
||||
// Beside a demo clip the text is its list of motions: from the left, not centred.
|
||||
const int textX = demoOn ? textX0 : textCx;
|
||||
const Align textAlign = demoOn ? kLeft : kCentre;
|
||||
|
||||
// The instruction, the note, the big countdown and the action line, centred together in
|
||||
// the space between. A long instruction gets smaller, down to 1 degree a line, before it runs over.
|
||||
@@ -597,20 +745,21 @@ void Draw(Panel &p) {
|
||||
auto gapBefore = [&] { if (!first) y += gapY; first = false; };
|
||||
if (!p.lines.empty()) {
|
||||
first = false;
|
||||
for (const std::string &line : p.lines) Text(pic, line, size, textCx, y + lh / 2, 1.0), y += lh;
|
||||
for (const std::string &line : p.lines) Text(pic, line, size, textX, y + lh / 2, 1.0, textAlign), y += lh;
|
||||
}
|
||||
if (!p.noteLines.empty()) {
|
||||
gapBefore();
|
||||
for (const std::string &line : p.noteLines) Text(pic, line, noteSize, textCx, y + noteLh / 2, 1.0, 0.62, 0.3), y += noteLh;
|
||||
for (const std::string &line : p.noteLines)
|
||||
Text(pic, line, noteSize, textX, y + noteLh / 2, 1.0, 0.62, 0.3, textAlign), y += noteLh;
|
||||
}
|
||||
if (!p.big.empty()) {
|
||||
gapBefore();
|
||||
Text(pic, p.big, bigSize, textCx, y + bigLh / 2, kCyan[0], kCyan[1], kCyan[2]), y += bigLh;
|
||||
Text(pic, p.big, bigSize, textX, y + bigLh / 2, kCyan[0], kCyan[1], kCyan[2], textAlign), y += bigLh;
|
||||
}
|
||||
if (!actionLines.empty()) {
|
||||
gapBefore();
|
||||
for (const std::string &line : actionLines)
|
||||
Text(pic, line, actionSize, textCx, y + actionLh / 2, kCyan[0], kCyan[1], kCyan[2]), y += actionLh;
|
||||
Text(pic, line, actionSize, textX, y + actionLh / 2, kCyan[0], kCyan[1], kCyan[2], textAlign), y += actionLh;
|
||||
}
|
||||
|
||||
if (p.paused) {
|
||||
@@ -689,6 +838,10 @@ void Print(const Panel &p, const Target &t, bool visible, int number) {
|
||||
std::printf("image: %s %dx%d%s%s\n", p.image.path.c_str(), p.image.src.w, p.image.src.h,
|
||||
p.imageMode.empty() ? "" : " ", p.imageMode.c_str());
|
||||
else std::printf("image: off\n");
|
||||
if (p.demo)
|
||||
std::printf("demo: %s %dx%d frame %d loop %d%s%s, drawn %dx%d\n", p.demo->path.c_str(), p.demo->w, p.demo->h,
|
||||
p.demo->frame, p.demo->loops, p.demo->mirror ? " mirror" : "", p.demo->key ? "" : " nokey", p.demoW, p.demoH);
|
||||
else std::printf("demo: off\n");
|
||||
if (!p.wherePos.empty() || !p.whereDist.empty())
|
||||
std::printf("where: %s %s\n", p.wherePos.empty() ? "-" : p.wherePos.c_str(), p.whereDist.empty() ? "-" : p.whereDist.c_str());
|
||||
else std::printf("where: off\n");
|
||||
@@ -714,6 +867,11 @@ struct Buffer {
|
||||
gbm_bo *bo = nullptr;
|
||||
int fd = -1;
|
||||
vr::SharedTextureHandle_t handle = 0;
|
||||
uint64_t whole = 0; // the whole picture it last had (Buffers::whole), 0: none
|
||||
};
|
||||
|
||||
struct Area {
|
||||
int x, y, w, h;
|
||||
};
|
||||
|
||||
struct Buffers {
|
||||
@@ -723,6 +881,7 @@ struct Buffers {
|
||||
Buffer b[3];
|
||||
int next = 0;
|
||||
bool ok = false;
|
||||
uint64_t whole = 0; // counts the pictures presented whole
|
||||
|
||||
bool Make(int width, int height) {
|
||||
w = width, h = height;
|
||||
@@ -766,8 +925,9 @@ struct Buffers {
|
||||
|
||||
// A picture to the overlay: into the next buffer, premultiplied (the overlay's flag says
|
||||
// so), then the overlay switches to it. The copy runs outside g_vr, so the pose log waits
|
||||
// only for the two calls at the end.
|
||||
void Present(vr::IVROverlay *ov, vr::VROverlayHandle_t oh, const Picture &p) {
|
||||
// only for the two calls at the end. With area (a demo clip's frame): only that changed
|
||||
// since the last whole picture, so a buffer that has that picture gets only the area.
|
||||
void Present(vr::IVROverlay *ov, vr::VROverlayHandle_t oh, const Picture &p, const Area *area = nullptr) {
|
||||
vr::EVROverlayError e;
|
||||
if (!ok) {
|
||||
std::lock_guard<std::mutex> lk(g_vr);
|
||||
@@ -775,6 +935,11 @@ struct Buffers {
|
||||
} else {
|
||||
Buffer &x = b[next];
|
||||
next = (next + 1) % 3;
|
||||
if (!area) ++whole;
|
||||
Area all{0, 0, p.w, p.h}, a = area && x.whole == whole ? *area : all;
|
||||
a.x = std::clamp(a.x, 0, p.w), a.y = std::clamp(a.y, 0, p.h);
|
||||
a.w = std::clamp(a.w, 0, p.w - a.x), a.h = std::clamp(a.h, 0, p.h - a.y);
|
||||
x.whole = whole;
|
||||
uint32_t stride = 0;
|
||||
void *mapping = nullptr;
|
||||
auto *dst = static_cast<uint8_t *>(gbm_bo_map(x.bo, 0, 0, p.w, p.h, GBM_BO_TRANSFER_WRITE, &stride, &mapping));
|
||||
@@ -782,10 +947,10 @@ struct Buffers {
|
||||
std::fprintf(stderr, "ft-handpanel: can't map a buffer\n");
|
||||
return;
|
||||
}
|
||||
for (int y = 0; y < p.h; ++y) {
|
||||
const uint8_t *src = &p.px[size_t(y) * p.w * 4];
|
||||
uint8_t *row = dst + size_t(y) * stride;
|
||||
for (int i = 0; i < p.w * 4; i += 4) {
|
||||
for (int y = a.y; y < a.y + a.h; ++y) {
|
||||
const uint8_t *src = &p.px[(size_t(y) * p.w + a.x) * 4];
|
||||
uint8_t *row = dst + size_t(y) * stride + size_t(a.x) * 4;
|
||||
for (int i = 0; i < a.w * 4; i += 4) {
|
||||
const unsigned a = src[i + 3];
|
||||
row[i] = uint8_t(src[i] * a / 255), row[i + 1] = uint8_t(src[i + 1] * a / 255);
|
||||
row[i + 2] = uint8_t(src[i + 2] * a / 255), row[i + 3] = uint8_t(a);
|
||||
@@ -933,15 +1098,17 @@ bool HandState(const std::string &s) { return s == "seen" || s == "lost" || s ==
|
||||
int main(int argc, char **argv) {
|
||||
bool watchStdin = false, noVr = false;
|
||||
std::string sockName = "ft_handpanel", dumpDir;
|
||||
double distance = 1.2;
|
||||
double distance = 1.2, upDeg = kUpDeg, widthDeg = kWidthDeg;
|
||||
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], "--distance") && i + 1 < argc) distance = std::clamp(std::atof(argv[++i]), 0.5, 5.0);
|
||||
else if (!std::strcmp(argv[i], "--up") && i + 1 < argc) upDeg = std::clamp(std::atof(argv[++i]), -60.0, 60.0);
|
||||
else if (!std::strcmp(argv[i], "--width") && i + 1 < argc) widthDeg = std::clamp(std::atof(argv[++i]), 5.0, 90.0);
|
||||
else if (!std::strcmp(argv[i], "--dump") && i + 1 < argc) dumpDir = argv[++i];
|
||||
else {
|
||||
std::fprintf(stderr, "usage: %s [--watch-stdin] [--socket NAME] [--distance METRES] [--no-vr [--dump DIR]]\n",
|
||||
std::fprintf(stderr, "usage: %s [--watch-stdin] [--socket NAME] [--distance METRES] [--up DEG] [--width DEG] [--no-vr [--dump DIR]]\n",
|
||||
argv[0]);
|
||||
return 2;
|
||||
}
|
||||
@@ -992,14 +1159,14 @@ int main(int argc, char **argv) {
|
||||
if (targetBuffers.Make(kTargetPx, kTargetPx)) ov->SetOverlayFlag(th, vr::VROverlayFlags_IsPremultiplied, true);
|
||||
// Fixed to the head: distance along a line UP_DEG above straight ahead, tilted back by
|
||||
// as much so it faces the eyes square on.
|
||||
const double up = kUpDeg * M_PI / 180;
|
||||
const double up = upDeg * M_PI / 180;
|
||||
vr::HmdMatrix34_t m{};
|
||||
m.m[0][0] = 1;
|
||||
m.m[1][1] = float(std::cos(up)), m.m[1][2] = float(-std::sin(up));
|
||||
m.m[2][1] = float(std::sin(up)), m.m[2][2] = float(std::cos(up));
|
||||
m.m[1][3] = float(distance * std::sin(up)), m.m[2][3] = float(-distance * std::cos(up));
|
||||
ov->SetOverlayTransformTrackedDeviceRelative(h, vr::k_unTrackedDeviceIndex_Hmd, &m);
|
||||
ov->SetOverlayWidthInMeters(h, float(2 * distance * std::tan(kWidthDeg * M_PI / 360)));
|
||||
ov->SetOverlayWidthInMeters(h, float(2 * distance * std::tan(widthDeg * M_PI / 360)));
|
||||
ov->SetOverlayWidthInMeters(th, float(kTargetM));
|
||||
}
|
||||
LoadFont();
|
||||
@@ -1014,7 +1181,10 @@ int main(int argc, char **argv) {
|
||||
|
||||
while (!g_stop) {
|
||||
pollfd pfd{sock, POLLIN, 0};
|
||||
poll(&pfd, 1, 50);
|
||||
int wait = 50;
|
||||
if (p.demo && visible && !p.paused) // up to the demo's next frame
|
||||
wait = int(std::clamp<int64_t>((p.demo->due - NowNs()) / 1'000'000 + 1, 0, 50));
|
||||
poll(&pfd, 1, wait);
|
||||
char buf[4096];
|
||||
sockaddr_un from{};
|
||||
socklen_t fromLen = sizeof from;
|
||||
@@ -1100,6 +1270,34 @@ int main(int argc, char **argv) {
|
||||
} else {
|
||||
p.imageMode = mode, dirty = true;
|
||||
}
|
||||
} else if (Is(buf, "demo", &rest)) {
|
||||
// demo <path> [mirror] [nokey] / demo restart / demo off: the path may hold spaces
|
||||
std::string path = rest;
|
||||
auto flag = [&path](const char *word) {
|
||||
const size_t n = std::strlen(word) + 1;
|
||||
if (path.size() <= n || path.compare(path.size() - n, n, std::string(" ") + word)) return false;
|
||||
path.resize(path.size() - n);
|
||||
return true;
|
||||
};
|
||||
const bool nokey = flag("nokey");
|
||||
const bool mirror = flag("mirror");
|
||||
if (path.empty()) {
|
||||
reply = "error usage: demo <path> [mirror] [nokey] | demo restart | demo off";
|
||||
} else if (path == "off") {
|
||||
p.demo.reset(), dirty = true;
|
||||
} else if (path == "restart") {
|
||||
if (p.demo) p.demo->loops = 0;
|
||||
if (p.demo && !p.demo->Start(NowNs())) reply = "error can't read " + p.demo->path, p.demo.reset();
|
||||
dirty = true;
|
||||
} else if (!p.demo || path != p.demo->path) {
|
||||
auto d = std::make_unique<Demo>();
|
||||
d->mirror = mirror, d->key = !nokey;
|
||||
if (d->Load(path)) p.demo = std::move(d);
|
||||
else reply = "error can't read " + path + ": " + stbi_failure_reason(), p.demo.reset();
|
||||
dirty = true; // no clip rather than the last one
|
||||
} else if (mirror != p.demo->mirror || nokey == p.demo->key) {
|
||||
p.demo->mirror = mirror, p.demo->key = !nokey, p.demo->fresh = dirty = true;
|
||||
}
|
||||
} else if (Is(buf, "strip", &rest)) {
|
||||
// strip <cue> <path>|<mode>|<label>;...
|
||||
int cue = -1, used = 0;
|
||||
@@ -1245,6 +1443,16 @@ int main(int argc, char **argv) {
|
||||
g_stop = true;
|
||||
}
|
||||
}
|
||||
// The demo's next frame when it's due: drawn into the picture's clip rectangle alone,
|
||||
// unless something else changed too (then the whole picture). Hidden or paused, it waits.
|
||||
bool frameNow = false;
|
||||
if (p.demo && visible && !p.paused && NowNs() >= p.demo->due) {
|
||||
const int64_t now = NowNs();
|
||||
if (now - p.demo->due > 500'000'000) p.demo->due = now; // after a wait: no catching up
|
||||
if (!p.demo->Next(p.demo->due))
|
||||
std::fprintf(stderr, "ft-handpanel: %s: %s\n", p.demo->path.c_str(), stbi_failure_reason()), p.demo.reset(), dirty = true;
|
||||
else frameNow = !dirty && p.demoW > 0;
|
||||
}
|
||||
const bool panelNow = visible && dirty, targetNow = targetDirty;
|
||||
if (panelNow) {
|
||||
Draw(p);
|
||||
@@ -1254,6 +1462,10 @@ int main(int argc, char **argv) {
|
||||
if (!shown) ov->ShowOverlay(h), shown = true;
|
||||
}
|
||||
dirty = false;
|
||||
} else if (frameNow) {
|
||||
DrawDemo(p.pic, *p.demo, p.demoX, p.demoY, p.demoW, p.demoH);
|
||||
const Area area{p.demoX, p.demoY, p.demoW, p.demoH};
|
||||
if (ov && shown) buffers.Present(ov, h, p.pic, &area);
|
||||
}
|
||||
if (targetNow) {
|
||||
if (t.on) {
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
{
|
||||
"version": 1,
|
||||
"name": "v2",
|
||||
"intro_s": 4,
|
||||
"between_s": 3,
|
||||
"welcome": {"title": "Hand recorder", "seconds": 8, "text": "Follow the steps on this panel. Each one plays a short clip of what to do: copy it. In the clips the palm is light and the back of the hand is dark.|The button on the right side of the headset goes on when a step waits for you, and pauses while recording."},
|
||||
"done": {"title": "All done", "seconds": 6, "text": "Thank you! You can take off the headset.|Review your recordings in the Hand recorder window."},
|
||||
"stopped": {"title": "Stopped", "seconds": 4, "text": "What was recorded so far is saved. Review it in the Hand recorder window."},
|
||||
"objects": {"pencil": "pencil or pen", "phone": "phone", "cup": "cup", "keyboard": "keyboard", "mouse": "mouse", "gamepad": "gamepad", "small": "small thing"},
|
||||
"sections": [
|
||||
{"id": "hand-size", "title": "Hand size", "requires": [], "go": "Hold", "quick": true, "intro": "First, your hand size. Copy the clip: both hands about 40 cm out, still, about 1 s for each shape.",
|
||||
"prompts": [
|
||||
{"text": "Both hands about 40 cm out, still|Palms toward you, then backs toward you|Fingers spread, then a fist, then point|About 1 s for each shape", "seconds": 10, "hands": "both", "demo": "1", "distance": "mid"}
|
||||
]},
|
||||
|
||||
{"id": "index-taps", "title": "Index taps", "requires": [], "quick": true, "intro": "Thumb to index fingertip taps: light and lazy, about 2 a second, the way you'd click.",
|
||||
"prompts": [
|
||||
{"text": "Left hand only, the right one down and out of view.|One hand low and relaxed, other fingers loosely curled: look down at it|2 light taps palm down|2 taps edge-on, 2 palm up, 2 palm toward your face", "seconds": 12, "hands": "left", "demo": "2a", "demo_mirror": true, "quick": false},
|
||||
{"text": "Right hand only, the left one down and out of view.|One hand low and relaxed, other fingers loosely curled: look down at it|2 light taps palm down|2 taps edge-on, 2 palm up, 2 palm toward your face", "seconds": 12, "hands": "right", "demo": "2a"},
|
||||
{"text": "Now both hands at once, each doing the same.|One hand low and relaxed, other fingers loosely curled: look down at it|2 light taps palm down|2 taps edge-on, 2 palm up, 2 palm toward your face", "seconds": 12, "hands": "both", "demo": "2a", "quick": false},
|
||||
{"text": "Left hand only, the right one down and out of view.|Keep tapping while you move: centre at chest height|Far out to your side, then crossed past the middle|Close to your face, then at arm's length|Quick taps, a double tap, one slow press", "seconds": 18, "hands": "left", "demo": "2b", "demo_mirror": true, "quick": false},
|
||||
{"text": "Right hand only, the left one down and out of view.|Keep tapping while you move: centre at chest height|Far out to your side, then crossed past the middle|Close to your face, then at arm's length|Quick taps, a double tap, one slow press", "seconds": 18, "hands": "right", "demo": "2b", "quick": false},
|
||||
{"text": "Now both hands at once, each doing the same.|Keep tapping while you move: centre at chest height|Far out to your side, then crossed past the middle|Close to your face, then at arm's length|Quick taps, a double tap, one slow press", "seconds": 18, "hands": "both", "demo": "2b", "quick": false},
|
||||
{"text": "Both hands tapping|Then one hand over the other, still tapping", "seconds": 10, "hands": "both", "demo": "2c", "quick": false}
|
||||
]},
|
||||
|
||||
{"id": "middle-taps", "title": "Middle taps", "requires": [], "intro": "Now the thumb meets the middle finger's pad. Keep the index half-curled, out of the way.",
|
||||
"prompts": [
|
||||
{"text": "Left hand only, the right one down and out of view.|Thumb to the middle finger's pad, index half-curled: look down at the hand|2 taps palm down, edge-on, palm up, toward your face|Then a few taps out to the side and close to your face", "seconds": 12, "hands": "left", "demo": "3a", "demo_mirror": true},
|
||||
{"text": "Right hand only, the left one down and out of view.|Thumb to the middle finger's pad, index half-curled: look down at the hand|2 taps palm down, edge-on, palm up, toward your face|Then a few taps out to the side and close to your face", "seconds": 12, "hands": "right", "demo": "3a"},
|
||||
{"text": "Now both hands at once, each doing the same.|Thumb to the middle finger's pad, index half-curled: look down at the hand|2 taps palm down, edge-on, palm up, toward your face|Then a few taps out to the side and close to your face", "seconds": 12, "hands": "both", "demo": "3a"},
|
||||
{"text": "Left hand only, the right one down and out of view.|3 slow, firm presses|Keep tapping and turn your head until the hand reaches the edge of the view|Then turn the other way", "seconds": 13, "hands": "left", "demo": "3b", "demo_mirror": true},
|
||||
{"text": "Right hand only, the left one down and out of view.|3 slow, firm presses|Keep tapping and turn your head until the hand reaches the edge of the view|Then turn the other way", "seconds": 13, "hands": "right", "demo": "3b"},
|
||||
{"text": "Now both hands at once, each doing the same.|3 slow, firm presses|Keep tapping and turn your head until the hand reaches the edge of the view|Then turn the other way", "seconds": 13, "hands": "both", "demo": "3b"}
|
||||
]},
|
||||
|
||||
{"id": "look-alikes", "title": "Look-alikes", "requires": [], "intro": "Things that look like taps but aren't: near misses, rubbing, other fingers, fists. None of them should touch thumb to index.",
|
||||
"prompts": [
|
||||
{"text": "Left hand only, the right one down and out of view.|Stop 1 cm short of a tap|Rub the thumb along the side of the index|Ring finger to thumb|Let a loosely curled hand rest", "seconds": 12, "hands": "left", "demo": "4a", "demo_mirror": true},
|
||||
{"text": "Right hand only, the left one down and out of view.|Stop 1 cm short of a tap|Rub the thumb along the side of the index|Ring finger to thumb|Let a loosely curled hand rest", "seconds": 12, "hands": "right", "demo": "4a"},
|
||||
{"text": "Now both hands at once, each doing the same.|Stop 1 cm short of a tap|Rub the thumb along the side of the index|Ring finger to thumb|Let a loosely curled hand rest", "seconds": 12, "hands": "both", "demo": "4a"},
|
||||
{"text": "Left hand only, the right one down and out of view.|Close a fist slowly, open it|Close it fast, open it|Once at chest height, once low", "seconds": 12, "hands": "left", "demo": "4b", "demo_mirror": true},
|
||||
{"text": "Right hand only, the left one down and out of view.|Close a fist slowly, open it|Close it fast, open it|Once at chest height, once low", "seconds": 12, "hands": "right", "demo": "4b"},
|
||||
{"text": "Now both hands at once, each doing the same.|Close a fist slowly, open it|Close it fast, open it|Once at chest height, once low", "seconds": 12, "hands": "both", "demo": "4b"}
|
||||
]},
|
||||
|
||||
{"id": "hold-drag", "title": "Hold and drag", "requires": [], "intro": "Pinch and hold, then move while holding, as if dragging a window.",
|
||||
"prompts": [
|
||||
{"text": "Left hand only, the right one down and out of view.|Pinch and hold 3 s|Drag up, down, left, right|Roll the wrist while holding|Loosen the other fingers without letting go", "seconds": 13, "hands": "left", "demo": "5a", "demo_mirror": true},
|
||||
{"text": "Right hand only, the left one down and out of view.|Pinch and hold 3 s|Drag up, down, left, right|Roll the wrist while holding|Loosen the other fingers without letting go", "seconds": 13, "hands": "right", "demo": "5a"},
|
||||
{"text": "Now both hands at once, each doing the same.|Pinch and hold 3 s|Drag up, down, left, right|Roll the wrist while holding|Loosen the other fingers without letting go", "seconds": 13, "hands": "both", "demo": "5a"},
|
||||
{"text": "One hand holds a pinch, the other taps|Hands apart, then close, then crossed", "seconds": 10, "hands": "both", "demo": "5b"}
|
||||
]},
|
||||
|
||||
{"id": "scroll", "title": "Three-finger scroll", "requires": [], "intro": "Thumb on the index and middle fingertips together, held while the hand moves.",
|
||||
"prompts": [
|
||||
{"text": "Left hand only, the right one down and out of view.|Thumb on the index and middle tips|Move up and down slowly, then fast|Let the ring finger join once", "seconds": 11, "hands": "left", "demo": "6", "demo_mirror": true},
|
||||
{"text": "Right hand only, the left one down and out of view.|Thumb on the index and middle tips|Move up and down slowly, then fast|Let the ring finger join once", "seconds": 11, "hands": "right", "demo": "6"},
|
||||
{"text": "Now both hands at once, each doing the same.|Thumb on the index and middle tips|Move up and down slowly, then fast|Let the ring finger join once", "seconds": 11, "hands": "both", "demo": "6"}
|
||||
]},
|
||||
|
||||
{"id": "palm-up", "title": "Palm up", "requires": [], "quick": true, "intro": "Palms up. This is where tracking gets lost today, so take your time: the fingertips drop toward the floor, then rise toward you.",
|
||||
"prompts": [
|
||||
{"text": "Arms forward, palms up, fingers flat: hands close (elbows tucked)|Fingertips drop toward the floor and back: 1 slow, 2 fast|Same with forearms half out, then arms straight|One drop low at the waist, one at eye height", "seconds": 19, "hands": "both", "demo": "7a"},
|
||||
{"text": "Palms up at the same three distances|Fingertips curl up toward you and back: 1 slow, 2 fast each", "seconds": 15, "hands": "both", "demo": "7b", "quick": false},
|
||||
{"text": "Left hand only, the right one down and out of view.|Palm up, hold a pinch|Drop the fingertips and raise them, still pinching|Flip palm up and down with the wrist bent", "seconds": 12, "hands": "left", "demo": "7c", "demo_mirror": true, "quick": false},
|
||||
{"text": "Right hand only, the left one down and out of view.|Palm up, hold a pinch|Drop the fingertips and raise them, still pinching|Flip palm up and down with the wrist bent", "seconds": 12, "hands": "right", "demo": "7c", "quick": false},
|
||||
{"text": "Now both hands at once, each doing the same.|Palm up, hold a pinch|Drop the fingertips and raise them, still pinching|Flip palm up and down with the wrist bent", "seconds": 12, "hands": "both", "demo": "7c", "quick": false}
|
||||
]},
|
||||
|
||||
{"id": "strokes", "title": "Strokes and gestures", "requires": [], "intro": "Quick strokes, a wave, and talking with your hands.",
|
||||
"prompts": [
|
||||
{"text": "Left hand only, the right one down and out of view.|Lazy susan stroke each way, with the return stroke|A wave|5 s of talking with your hands", "seconds": 14, "hands": "left", "demo": "8", "demo_mirror": true},
|
||||
{"text": "Right hand only, the left one down and out of view.|Lazy susan stroke each way, with the return stroke|A wave|5 s of talking with your hands", "seconds": 14, "hands": "right", "demo": "8"},
|
||||
{"text": "Now both hands at once, each doing the same.|Lazy susan stroke each way, with the return stroke|A wave|5 s of talking with your hands", "seconds": 14, "hands": "both", "demo": "8"}
|
||||
]},
|
||||
|
||||
{"id": "reach", "title": "Reach and pull", "requires": [], "intro": "Reaching out: grab something far away and pull it in, push and flick away, then a real object. Have a cup or your phone in reach.",
|
||||
"prompts": [
|
||||
{"text": "Left hand only, the right one down and out of view.|Open palm at a far target|Close to a fist and pull back", "seconds": 8, "hands": "left", "demo": "9a", "demo_mirror": true},
|
||||
{"text": "Right hand only, the left one down and out of view.|Open palm at a far target|Close to a fist and pull back", "seconds": 8, "hands": "right", "demo": "9a"},
|
||||
{"text": "Now both hands at once, each doing the same.|Open palm at a far target|Close to a fist and pull back", "seconds": 8, "hands": "both", "demo": "9a"},
|
||||
{"text": "Left hand only, the right one down and out of view.|Push away, then flick away|Reach for a cup or your phone", "seconds": 10, "hands": "left", "demo": "9b", "demo_mirror": true},
|
||||
{"text": "Right hand only, the left one down and out of view.|Push away, then flick away|Reach for a cup or your phone", "seconds": 10, "hands": "right", "demo": "9b"},
|
||||
{"text": "Now both hands at once, each doing the same.|Push away, then flick away|Reach for a cup or your phone", "seconds": 10, "hands": "both", "demo": "9b"}
|
||||
]},
|
||||
|
||||
{"id": "fists", "title": "Fists", "requires": [], "intro": "Two fists, as if holding a big screen by its edges.",
|
||||
"prompts": [
|
||||
{"text": "Two fists: hold, pull apart, push together|Fists with the palms in, down, then up", "seconds": 9, "hands": "both", "demo": "10"}
|
||||
]},
|
||||
|
||||
{"id": "edges", "title": "Edges and exits", "requires": [], "intro": "Hands leaving the view and coming back. Keep your head still and go slowly near the edges.",
|
||||
"prompts": [
|
||||
{"text": "Right hand open: slide out past the right edge until gone, wait 1 s, back|Same up past your face|Left hand pinching: out past the left edge, then down past your lap", "seconds": 19, "hands": "both", "demo": "11a"},
|
||||
{"text": "Both hands cross fully to the opposite sides|Hold a moment, come back", "seconds": 10, "hands": "both", "demo": "11b"}
|
||||
]},
|
||||
|
||||
{"id": "desk-work", "title": "Desk work", "requires": [], "intro": "Now your desk. Look down at your hands while you work.", "defaults": {"position": "down"},
|
||||
"prompts": [
|
||||
{"text": "Type a few words, use the mouse, pick up the phone|One tap, then back to the keys", "seconds": 15, "hands": "both", "demo": "12", "when": "objects:keyboard"},
|
||||
{"text": "No keyboard: rest your hands on the desk and pretend.|Type a few words, use the mouse, pick up the phone|One tap, then back to the keys", "seconds": 15, "hands": "both", "demo": "12", "when": "!objects:keyboard"}
|
||||
]},
|
||||
|
||||
{"id": "controllers", "title": "Controllers", "requires": ["controllers"], "intro": "Put both controllers on the desk in front of you, in view.",
|
||||
"prompts": [
|
||||
{"text": "Pick up the controllers, set them down|A tap in between", "seconds": 10, "hands": "both", "demo": "13"}
|
||||
]},
|
||||
|
||||
{"id": "no-hands", "title": "No hands", "requires": [], "quick": true, "intro": "Last one: put your hands down, out of view.",
|
||||
"prompts": [
|
||||
{"text": "Keep your hands out of view and look slowly around the room.", "seconds": 10, "hands": "none", "picture": "no-hands"}
|
||||
]}
|
||||
]
|
||||
}
|
||||
+458
-74
@@ -51,15 +51,38 @@ sys.path.insert(0, HANDS)
|
||||
import camcheck # noqa: E402 (hands/camcheck.py: are all four mono cameras running?)
|
||||
sys.path.insert(0, HERE)
|
||||
import sides # noqa: E402 (hands/rec/sides.py: which side camera is which)
|
||||
import takes # noqa: E402 (hands/rec/takes.py: the version, and the standalone recorder's build info)
|
||||
FT_HANDS = os.path.join(HANDS, "build", "ft-hands")
|
||||
FT_CAMD = os.path.join(HANDS, "build", "ft-camd")
|
||||
PANEL_BIN = os.path.join(HERE, "build", "ft-handpanel")
|
||||
SCRIPT_PATH = os.path.join(HERE, "script.json")
|
||||
POSES_DIR = os.path.join(HERE, "poses") # the pose pictures: poses.json and its PNGs
|
||||
DEMOS_DIR = os.path.join(HERE, "demos") # the demo clips: <id>.gif (DESIGN.md "Demo clips")
|
||||
RECORDED_DEMOS_DIR = os.path.join(HERE, "demos-recorded") # the same parts from real camera frames
|
||||
# The demo clips a contributor follows: recorded (a real person's hands, from a session's side
|
||||
# cameras: demo/camgifs.py) or skeleton (the drawn hand, its palm light and its back dark).
|
||||
GUIDANCE = (("recorded", "Recorded hands"), ("skeleton", "Skeleton hands"))
|
||||
BASE_DIR = os.path.expanduser("~/.local/share/frametop/hands/contrib")
|
||||
PANEL_SOCKET = "ft_handpanel"
|
||||
CAMD_UNIT = "frametop-handrec-camd.service"
|
||||
# Frametop's live hand tracking (hands/run.sh, ft-handsctl): an ft-camd the recorder uses as it is
|
||||
LIVE_CAMD_UNIT, LIVE_HANDS_UNIT = "frametop-camd.service", "frametop-hands.service"
|
||||
# Frametop's drawn hands and hand pointer: off for a session, so no hand overlay is in view and no gesture
|
||||
# clicks or opens Steam's menu while the person performs the steps (Session._quiet_hands)
|
||||
QUIET_UNITS = ("frametop-handview.service", "frametop-pointer.service")
|
||||
PAUSED_UNITS_FILE = "handrec-paused-units" # in run_dir(): the ones to start again, if a session didn't
|
||||
SIDE_CAMERAS = ("slam_left", "slam_right") # a recording needs these (Session._first_set)
|
||||
CAMERAS_BACK_S = 120 # how long a lost recording waits for the cameras (Session._cameras_back)
|
||||
STALL_S = 3.0 # a recording with no new set for this long is lost (Session._watch_recording)
|
||||
MAX_CAMERA_LOSSES = 3 # then the session stops
|
||||
CAMERAS_TITLE = "Waiting for the cameras"
|
||||
CAMERAS_TEXT = ("The headset's cameras restarted (SteamVR moves them when the colour camera module is unplugged "
|
||||
"or plugged in), or they stopped. If you took the headset off, put it back on. This step goes "
|
||||
"again once they're back.")
|
||||
HANDS_UNIT = "frametop-handrec-hands.service"
|
||||
# The standalone Hand Recorder (takes.standalone()): its binaries run on the host, so ft-hands
|
||||
# starts directly rather than in the dev container, and repairs mean its install command.
|
||||
STANDALONE = takes.standalone()
|
||||
|
||||
RECORD_HZ = 10
|
||||
SIDES_READ_S = 0.5 # how often the tracking ft-hands' side camera decision is read
|
||||
@@ -72,15 +95,19 @@ MIN_FREE = 1.5e9 # stop the session before the disk fills
|
||||
COUNTDOWN_S = 3 # step mode: the 3-2-1 before each step, recorded
|
||||
FIRST_SET_S = 3.0 # step mode: how long the hold may wait for its recording's first set
|
||||
RESUME_HINT = "Paused. Resume: P in the Hand recorder window"
|
||||
RESUME_HINT_BUTTON = "Paused. Resume: press the headset button, or P in the Hand recorder window"
|
||||
READY_TEXT = "Ready? Press Space or click Next"
|
||||
# With the headset's button: it leads when no mouse is connected (the window's Next can't be clicked).
|
||||
READY_BUTTON = "Ready? Press the button on the right side of the headset"
|
||||
READY_BUTTON_MOUSE = "Ready? Press Space, click Next, or press the headset button"
|
||||
KEYS_STEP = "Hand recorder window: Space next \u00b7 P pause \u00b7 R redo \u00b7 S skip section \u00b7 Esc stop"
|
||||
KEYS_AUTO = "Hand recorder window: P pause \u00b7 R redo \u00b7 S skip section \u00b7 Esc stop"
|
||||
KEYS_STEP_BUTTON = ("Headset button: next, pause \u00b7 Window: Space next \u00b7 P pause \u00b7 R redo "
|
||||
"\u00b7 S skip \u00b7 Esc stop")
|
||||
KEYS_AUTO_BUTTON = "Headset button: pause \u00b7 Window: P pause \u00b7 R redo \u00b7 S skip section \u00b7 Esc stop"
|
||||
# The headset button: a press, two (redo) and a hold (stop): ButtonGestures. The window's keys follow
|
||||
# by letter: the window lists what they do.
|
||||
KEYS_STEP_BUTTON = ("Headset button: press for next or pause \u00b7 press twice to redo \u00b7 hold to stop "
|
||||
"\u00b7 Window keys: Space P R S Esc")
|
||||
KEYS_AUTO_BUTTON = ("Headset button: press to pause \u00b7 press twice to redo \u00b7 hold to stop "
|
||||
"\u00b7 Window keys: P R S Esc")
|
||||
# The early no-hands stop (DESIGN.md, "Camera check"): the first step of this section has both
|
||||
# hands up. If the live tracker publishes through its hold and never sees a hand, the session
|
||||
# stops that step and asks: try again, or stop. Only when the tracker published in at least
|
||||
@@ -93,6 +120,8 @@ NO_HANDS_TITLE = "I can't see your hands"
|
||||
NO_HANDS_TEXT = "The hand tracker didn't see either of your hands during that whole step."
|
||||
NO_HANDS_RETRY = ("Try again: hold both hands up in front of you, about 40 cm away. To stop instead: "
|
||||
"Esc or Stop in the Hand recorder window.")
|
||||
NO_HANDS_RETRY_BUTTON = ("Try again: hold both hands up in front of you, about 40 cm away, and press the headset "
|
||||
"button. To stop instead: hold the button, or Esc or Stop in the Hand recorder window.")
|
||||
|
||||
|
||||
def mono_ns():
|
||||
@@ -131,6 +160,13 @@ def host_command(*cmd):
|
||||
exe] + list(cmd)
|
||||
|
||||
|
||||
def fix_hint(frametop):
|
||||
"""How to repair a missing or broken part: Frametop's command, or the standalone install's."""
|
||||
if STANDALONE:
|
||||
return STANDALONE.get("reinstall") or "run the Hand Recorder's install command again"
|
||||
return frametop
|
||||
|
||||
|
||||
def host_path(path):
|
||||
"""A host file, from the container (/run/host) or the host itself."""
|
||||
for p in ("/run/host" + path, path):
|
||||
@@ -292,7 +328,7 @@ def similar_lighting(base_dir, lighting):
|
||||
return None
|
||||
|
||||
|
||||
DAYLIGHT_IR = 6.0 # ambient IR (the mono cameras' mean dark_mean) from which it's daylight
|
||||
DAYLIGHT_IR = 6.0 # ambient IR (the mono cameras' mean dark_mean) from which it's daylight; see classify_lighting
|
||||
|
||||
|
||||
def ambient_ir(ring):
|
||||
@@ -306,7 +342,13 @@ def ambient_ir(ring):
|
||||
def classify_lighting(ring):
|
||||
""""daylight" or "indoor" from the room's infrared light, "" if it can't tell. Sunlight
|
||||
carries a lot of infrared; lamps and LEDs hardly any, so a dim room and a bright one read
|
||||
about the same (2026-10: 1.8 by one lamp, 2.2 in a lamp-lit room) and aren't told apart."""
|
||||
about the same (2026-10: 1.8 by one lamp, 2.2 in a lamp-lit room) and aren't told apart.
|
||||
Nor does a sunlit room reliably: the first daylight round (dataset PR #5, big sunlit windows)
|
||||
read 2.38, since the windows are a small part of each picture and the mean barely moves. So
|
||||
"indoor" means "no strong daylight on the cameras", and the window asks people to pick
|
||||
daylight themselves. Review corrects a missed one from the pictures (sunlit windows, the time
|
||||
of day): hands standing out little from the room goes with daylight but also with pale rooms
|
||||
at night, so it isn't a test either."""
|
||||
ir = ambient_ir(ring)
|
||||
if ir is None:
|
||||
return ""
|
||||
@@ -351,6 +393,45 @@ def stop_unit(unit):
|
||||
subprocess.run(host_command("systemctl", "--user", "stop", unit), capture_output=True, timeout=30)
|
||||
|
||||
|
||||
def pause_units(units, path, log=lambda line: None):
|
||||
"""Stop those of units that are running, listed in path first so resume_units starts them again
|
||||
even after a crash. Returns the ones stopped."""
|
||||
paused = [u for u in units if unit_active(u)]
|
||||
if not paused:
|
||||
return []
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w") as f:
|
||||
json.dump(paused, f)
|
||||
for unit in paused:
|
||||
stop_unit(unit)
|
||||
log("paused %s for the session" % unit)
|
||||
return paused
|
||||
|
||||
|
||||
def resume_units(path, log=lambda line: None):
|
||||
"""Start the units pause_units listed in path, and forget them. Returns them."""
|
||||
try:
|
||||
with open(path) as f:
|
||||
units = [u for u in json.load(f) if isinstance(u, str) and u.endswith(".service")]
|
||||
except (OSError, ValueError, TypeError):
|
||||
return []
|
||||
for unit in units:
|
||||
r = subprocess.run(host_command("systemctl", "--user", "start", unit), capture_output=True, text=True, timeout=60)
|
||||
log("started %s again%s" % (unit, "" if r.returncode == 0 else
|
||||
" FAILED (exit %d): %s" % (r.returncode, (r.stderr or r.stdout).strip())))
|
||||
try:
|
||||
os.remove(path)
|
||||
except OSError:
|
||||
pass
|
||||
return units
|
||||
|
||||
|
||||
def restart_units(units):
|
||||
"""Restart those that are running, in order."""
|
||||
for unit in units:
|
||||
subprocess.run(host_command("systemctl", "--user", "try-restart", unit), capture_output=True, timeout=60)
|
||||
|
||||
|
||||
def ring_alive(path=None):
|
||||
try:
|
||||
r = Ring(path or os.path.join(run_dir(), "cam-ring"))
|
||||
@@ -369,10 +450,10 @@ def start_camd(path=None, log=lambda line: None, stop=lambda: False, timeout=15.
|
||||
if ring_alive(path):
|
||||
return False
|
||||
if not os.access(FT_CAMD, os.X_OK):
|
||||
raise RuntimeError("ft-camd isn't built: hands/build.sh")
|
||||
raise RuntimeError("ft-camd isn't built: " + fix_hint("hands/build.sh"))
|
||||
caps = subprocess.run(["getcap", FT_CAMD], capture_output=True, text=True) if shutil.which("getcap") else None
|
||||
if caps is not None and "cap_sys_ptrace" not in caps.stdout:
|
||||
raise RuntimeError("ft-camd needs its capabilities: hands/run.sh caps (asks for sudo)")
|
||||
raise RuntimeError("ft-camd needs its capabilities: " + fix_hint("hands/run.sh caps (asks for sudo)"))
|
||||
started = start_unit(CAMD_UNIT, "the camera broker", [FT_CAMD, "--status", "60"], log)
|
||||
end = time.monotonic() + timeout
|
||||
while time.monotonic() < end:
|
||||
@@ -470,7 +551,7 @@ class HandsFile:
|
||||
if len(data) < size:
|
||||
return None
|
||||
magic, version, _, seq, _, publish_ns, nhands, _ = HANDS_HDR.unpack_from(data, 0)
|
||||
if magic != b"FHHANDS1" or version != 1:
|
||||
if magic != b"FHHANDS1" or version < 1: # 2 appends the skeleton; the start is unchanged
|
||||
return None
|
||||
if seq % 2 or os.pread(fd, 8, 16) != data[16:24]:
|
||||
continue
|
||||
@@ -614,7 +695,7 @@ class Recorder:
|
||||
"--sides", "auto" if swap is None else "1" if swap else "0"]
|
||||
if ring:
|
||||
argv += ["--ring", ring]
|
||||
if not in_container():
|
||||
if not in_container() and not STANDALONE:
|
||||
argv = [os.path.expanduser("~/.local/bin/distrobox"), "enter", "dev", "--"] + argv
|
||||
self.proc = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=log_file, stderr=log_file)
|
||||
self.started_ns = mono_ns()
|
||||
@@ -629,6 +710,30 @@ class Recorder:
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
def sets_written(self):
|
||||
"""How many sets the part has written so far (0 before the first)."""
|
||||
try:
|
||||
path = os.path.join(self.dir, "sets.bin")
|
||||
with open(path, "rb") as f:
|
||||
head = f.read(16)
|
||||
magic, _, size = struct.unpack("<8sII", head)
|
||||
return os.path.getsize(path) // size if magic.rstrip(b"\0") == b"FHSET01" and size else 0
|
||||
except (OSError, struct.error):
|
||||
return 0
|
||||
|
||||
def cameras(self):
|
||||
"""The cameras in the first set written (their calibration names), [] before there is one."""
|
||||
try:
|
||||
with open(os.path.join(self.dir, "sets.bin"), "rb") as f:
|
||||
data = f.read(16 + 8 * 40)
|
||||
magic, n, _ = struct.unpack_from("<8sII", data, 0)
|
||||
if magic.rstrip(b"\0") != b"FHSET01" or len(data) < 16 + n * 40:
|
||||
return []
|
||||
return [struct.unpack_from("<16s", data, 16 + i * 40)[0].split(b"\0", 1)[0].decode(errors="replace")
|
||||
for i in range(n)]
|
||||
except (OSError, struct.error):
|
||||
return []
|
||||
|
||||
def stop(self):
|
||||
"""End it (SIGTERM: ft-hands writes out its queue) and put the part in place. Afterwards
|
||||
names_swapped is what ft-hands says it applied (its DIR/sides.json, which goes into
|
||||
@@ -673,7 +778,9 @@ EV_KEY, EV_REL = 0x01, 0x02
|
||||
REL_X, REL_Y = 0x00, 0x01
|
||||
KEY_SELECT = 353
|
||||
BUTTON_DEVICE = "gpio-keys"
|
||||
BUTTON_DEBOUNCE_S = 0.3 # presses closer than this count once
|
||||
BUTTON_DOUBLE_S = 0.45 # a second press this soon after the first one's release: a double press
|
||||
BUTTON_HOLD_S = 1.5 # held down this long: a hold
|
||||
BUTTON_BOUNCE_S = 0.03 # a release and press closer than this are one press (gpio-keys debounces too)
|
||||
|
||||
|
||||
def parse_input_devices(text):
|
||||
@@ -753,29 +860,84 @@ def mouse_connected(path=INPUT_DEVICES):
|
||||
return any(real_mouse(d) for d in read_input_devices(path))
|
||||
|
||||
|
||||
def button_presses(data):
|
||||
"""KEY_SELECT key-downs in a run of input_event structs (value 1; releases and autorepeat
|
||||
are left out). Returns (how many, the bytes left over after the last whole event)."""
|
||||
n, usable = 0, len(data) - len(data) % INPUT_EVENT.size
|
||||
def button_events(data):
|
||||
"""KEY_SELECT downs and ups in a run of input_event structs: [(True for a down or False for
|
||||
an up, the event's time in seconds), ...] (autorepeat, value 2, is left out). Returns (them,
|
||||
the bytes left over after the last whole event)."""
|
||||
out, usable = [], len(data) - len(data) % INPUT_EVENT.size
|
||||
for off in range(0, usable, INPUT_EVENT.size):
|
||||
_, _, etype, code, value = INPUT_EVENT.unpack_from(data, off)
|
||||
if etype == EV_KEY and code == KEY_SELECT and value == 1:
|
||||
n += 1
|
||||
return n, data[usable:]
|
||||
sec, usec, etype, code, value = INPUT_EVENT.unpack_from(data, off)
|
||||
if etype == EV_KEY and code == KEY_SELECT and value in (0, 1):
|
||||
out.append((value == 1, sec + usec / 1e6))
|
||||
return out, data[usable:]
|
||||
|
||||
|
||||
class ButtonGestures:
|
||||
"""The headset button's downs and ups, with their times, as gestures:
|
||||
"press": one short press, reported once the double-press time has passed without a second;
|
||||
"double": two presses, the second down within double_s of the first one's release, reported
|
||||
at the second down;
|
||||
"hold": held down for hold_s, reported while still down.
|
||||
A release and a press closer than bounce_s are one press. Each call returns the gestures that
|
||||
are due, in order; tick() is called now and then to report the ones that are due by time."""
|
||||
|
||||
def __init__(self, double_s=BUTTON_DOUBLE_S, hold_s=BUTTON_HOLD_S, bounce_s=BUTTON_BOUNCE_S):
|
||||
self.double_s, self.hold_s, self.bounce_s = double_s, hold_s, bounce_s
|
||||
self.down_at = None # when the button went down, while it's down
|
||||
self.done = False # the press that's down was already reported (a double, a hold)
|
||||
self.released = None # when a short press was let go, until it's reported or doubled
|
||||
self._up = None # the last release, for the bounce: (time, down_at, done, released before it)
|
||||
|
||||
def down(self, t):
|
||||
if self.down_at is not None: # a missed release
|
||||
return []
|
||||
if self._up and t - self._up[0] < self.bounce_s: # a bounce: still the same press
|
||||
_, self.down_at, self.done, self.released = self._up
|
||||
self._up = None
|
||||
return []
|
||||
out = self.tick(t)
|
||||
self.down_at, self.done = t, False
|
||||
if self.released is not None: # within the double-press time (else tick reported it)
|
||||
self.released, self.done = None, True
|
||||
out.append("double")
|
||||
return out
|
||||
|
||||
def up(self, t):
|
||||
if self.down_at is None:
|
||||
return []
|
||||
out = self.tick(t)
|
||||
self._up = (t, self.down_at, self.done, self.released)
|
||||
if not self.done:
|
||||
self.released = t
|
||||
self.down_at, self.done = None, False
|
||||
return out
|
||||
|
||||
def tick(self, t):
|
||||
if self.down_at is not None and not self.done and t - self.down_at >= self.hold_s:
|
||||
self.done = True
|
||||
return ["hold"]
|
||||
if self.released is not None and t - self.released > self.double_s:
|
||||
self.released = None
|
||||
return ["press"]
|
||||
return []
|
||||
|
||||
def waiting(self):
|
||||
"""Something is due by time alone: a hold, or a press that may still become a double."""
|
||||
return (self.down_at is not None and not self.done) or self.released is not None
|
||||
|
||||
|
||||
class ButtonReader:
|
||||
"""Reads the headset button on a thread and calls on_press() per press, debounced. path:
|
||||
an event device or, for testing, a FIFO carrying input_event structs. It's opened read-only
|
||||
and shared; if it can't be opened (no device, no permission, /dev/input not reachable in a
|
||||
container) it says so in the log and tries again now and then."""
|
||||
"""Reads the headset button on a thread and calls on_gesture("press" | "double" | "hold")
|
||||
(ButtonGestures). path: an event device or, for testing, a FIFO carrying input_event
|
||||
structs. It's opened read-only and shared; if it can't be opened (no device, no permission,
|
||||
/dev/input not reachable in a container) it says so in the log and tries again now and then."""
|
||||
|
||||
def __init__(self, path, on_press, log=None, debounce_s=BUTTON_DEBOUNCE_S):
|
||||
self.path, self.on_press, self.log = path, on_press, log or (lambda s: None)
|
||||
self.debounce_s = debounce_s
|
||||
def __init__(self, path, on_gesture, log=None, double_s=BUTTON_DOUBLE_S, hold_s=BUTTON_HOLD_S,
|
||||
bounce_s=BUTTON_BOUNCE_S):
|
||||
self.path, self.on_gesture, self.log = path, on_gesture, log or (lambda s: None)
|
||||
self.gestures = ButtonGestures(double_s, hold_s, bounce_s)
|
||||
self.ok = False # opened at least once
|
||||
self._stop = threading.Event()
|
||||
self._last = -1e9
|
||||
self._thread = threading.Thread(target=self._run, name="handrec-button", daemon=True)
|
||||
|
||||
def start(self):
|
||||
@@ -786,11 +948,9 @@ class ButtonReader:
|
||||
self._stop.set()
|
||||
self._thread.join(2)
|
||||
|
||||
def _press(self, n):
|
||||
now = time.monotonic()
|
||||
if n and now - self._last >= self.debounce_s:
|
||||
self._last = now
|
||||
self.on_press()
|
||||
def _report(self, gestures):
|
||||
for g in gestures:
|
||||
self.on_gesture(g)
|
||||
|
||||
def _run(self):
|
||||
failed = False
|
||||
@@ -809,8 +969,9 @@ class ButtonReader:
|
||||
rest = b""
|
||||
try:
|
||||
while not self._stop.is_set():
|
||||
r, _, _ = select.select([fd], [], [], 0.2)
|
||||
r, _, _ = select.select([fd], [], [], 0.02 if self.gestures.waiting() else 0.2)
|
||||
if not r:
|
||||
self._report(self.gestures.tick(time.monotonic()))
|
||||
continue
|
||||
try:
|
||||
data = os.read(fd, INPUT_EVENT.size * 64)
|
||||
@@ -819,8 +980,13 @@ class ButtonReader:
|
||||
if not data: # a FIFO's writer left: open it again
|
||||
self._stop.wait(0.2)
|
||||
break
|
||||
n, rest = button_presses(rest + data)
|
||||
self._press(n)
|
||||
events, rest = button_events(rest + data)
|
||||
# The kernel's times (the realtime clock) keep the gaps between events that
|
||||
# came in one read; the last one is taken as now.
|
||||
now = time.monotonic()
|
||||
for is_down, t in events:
|
||||
at = now - min(max(events[-1][1] - t, 0.0), 2.0)
|
||||
self._report(self.gestures.down(at) if is_down else self.gestures.up(at))
|
||||
except OSError as e: # the device went away
|
||||
self.log("headset button: %s: %s" % (self.path, e.strerror))
|
||||
self._stop.wait(2)
|
||||
@@ -862,11 +1028,47 @@ def pose_view(poses, p):
|
||||
return e["path"], mode, e["caption"]
|
||||
|
||||
|
||||
def demo_view(demos_dir, p):
|
||||
"""A prompt's demo clip: (path, mode), mode "" (as made: a right hand, or both hands) or
|
||||
"mirror" (the prompt's "demo_mirror": a right hand's clip for the left hand). ("", "")
|
||||
when it has none, or its file isn't there."""
|
||||
demo = p.get("demo") or ""
|
||||
path = os.path.join(demos_dir, os.path.basename(demo) + ".gif") if demo else ""
|
||||
if not path or not os.path.isfile(path):
|
||||
return "", ""
|
||||
return path, "mirror" if p.get("demo_mirror") else ""
|
||||
|
||||
|
||||
def has_clips(demos_dir):
|
||||
try:
|
||||
return any(n.endswith(".gif") for n in os.listdir(demos_dir))
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def default_guidance(recorded_dir=None):
|
||||
"""Recorded clips when there are any, else the skeleton ones."""
|
||||
return "recorded" if has_clips(recorded_dir or RECORDED_DEMOS_DIR) else "skeleton"
|
||||
|
||||
|
||||
def guided_demo_view(guidance, skeleton_dir, recorded_dir, p):
|
||||
"""demo_view in the guidance's folder, else the other one (a part with no clip of that kind):
|
||||
(path, mode, key), key true for a skeleton clip (the panel and window show its colours' key)."""
|
||||
dirs = [(recorded_dir, False), (skeleton_dir, True)]
|
||||
if guidance != "recorded":
|
||||
dirs.reverse()
|
||||
for d, key in dirs:
|
||||
path, mode = demo_view(d, p)
|
||||
if path:
|
||||
return path, mode, key
|
||||
return "", "", False
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------
|
||||
# The script
|
||||
|
||||
HAND_VALUES = ("left", "right", "both", "none", "any", "")
|
||||
PROMPT_KEYS = ("text", "seconds", "hands", "pose", "distance", "position", "object", "controller")
|
||||
PROMPT_KEYS = ("text", "seconds", "hands", "pose", "distance", "position", "object", "controller", "demo")
|
||||
|
||||
|
||||
def _when_ok(cond, ctx):
|
||||
@@ -905,7 +1107,7 @@ def _set_ids(section, prompts):
|
||||
for p in prompts:
|
||||
if not p.get("id"):
|
||||
parts = [section["id"]] + [re.sub(r"[^a-z0-9]+", "-", str(p[k]).lower()).strip("-")
|
||||
for k in ("pose", "hands", "distance", "position", "object") if p[k]]
|
||||
for k in ("demo", "pose", "hands", "distance", "position", "object") if p[k]]
|
||||
p["id"] = "/".join(parts) if len(parts) > 1 else "%s/%d" % (section["id"], len(seen) + 1)
|
||||
n = seen.get(p["id"], 0) + 1
|
||||
seen[p["id"]] = n
|
||||
@@ -1117,13 +1319,10 @@ class _Redo(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _git_describe():
|
||||
try:
|
||||
r = subprocess.run(["git", "-C", REPO, "describe", "--always", "--dirty", "--tags"],
|
||||
capture_output=True, text=True, timeout=5)
|
||||
return r.stdout.strip() or "unknown"
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return "unknown"
|
||||
class _CamerasLost(_Fail):
|
||||
"""The recording stopped by itself or has no side cameras: usually ft-camd restarting after
|
||||
XRService moved the cameras (camd.c, SILENT_S). Step mode waits for them and does the step
|
||||
again (Session._cameras_back); anywhere else it fails the session like any _Fail."""
|
||||
|
||||
|
||||
def _os_version():
|
||||
@@ -1153,11 +1352,44 @@ def _steamvr_version():
|
||||
return ""
|
||||
|
||||
|
||||
def camera_check():
|
||||
"""camcheck.check() (the XRService log, its open cameras where readable, ft-camd's ring);
|
||||
never raises: a failure is "unknown"."""
|
||||
_camd_restarted = set() # ft-camd pids camera_check(repair=True) has restarted: once each
|
||||
|
||||
|
||||
def _unit_pid(unit):
|
||||
r = subprocess.run(host_command("systemctl", "--user", "show", "-p", "MainPID", "--value", unit),
|
||||
capture_output=True, text=True, timeout=30)
|
||||
try:
|
||||
return camcheck.check()
|
||||
return int(r.stdout.strip() or 0)
|
||||
except ValueError:
|
||||
return 0
|
||||
|
||||
|
||||
def camera_check(repair=False):
|
||||
"""camcheck.check() (the XRService log, its open cameras where readable, ft-camd's ring);
|
||||
never raises: a failure is "unknown". repair (the window, never during a session): when
|
||||
XRService runs every tracking camera but the recorder's own ft-camd doesn't publish them all
|
||||
(it started while some were missing), restart it, once per ft-camd, and check again."""
|
||||
try:
|
||||
r = camcheck.check()
|
||||
pid = (r.get("ring") or {}).get("writer_pid")
|
||||
if repair and camcheck.is_ring_short(r) and pid not in _camd_restarted:
|
||||
if _unit_pid(CAMD_UNIT) == pid:
|
||||
_camd_restarted.add(pid)
|
||||
stop_unit(CAMD_UNIT)
|
||||
start_camd()
|
||||
elif _unit_pid(LIVE_CAMD_UNIT) == pid:
|
||||
# Frametop's live hand tracking: its ft-hands names the cameras when it starts,
|
||||
# so it goes again after ft-camd
|
||||
_camd_restarted.add(pid)
|
||||
restart_units([LIVE_CAMD_UNIT, LIVE_HANDS_UNIT])
|
||||
end = time.monotonic() + 15
|
||||
while not ring_alive() and time.monotonic() < end:
|
||||
time.sleep(0.2)
|
||||
else:
|
||||
return r
|
||||
r = camcheck.check()
|
||||
r["evidence"].append("restarted ft-camd (pid %d) because it published only some of the cameras" % pid)
|
||||
return r
|
||||
except Exception as e:
|
||||
return {"status": "unknown", "summary": "unknown: the camera check failed (%s)" % e,
|
||||
"reason": str(e), "evidence": []}
|
||||
@@ -1169,6 +1401,14 @@ def camera_text(result):
|
||||
return ""
|
||||
if camcheck.is_vcint_failure(result):
|
||||
return camcheck.USER_TEXT
|
||||
if camcheck.is_ring_short(result) and "moved them" in result.get("reason", ""):
|
||||
return ("SteamVR moved the headset's tracking cameras after the camera broker started (the colour "
|
||||
"camera module was unplugged or plugged in), so the recorder can't read the side cameras. Close "
|
||||
"the Hand Recorder and open it again: it restarts the camera broker.")
|
||||
if camcheck.is_ring_short(result):
|
||||
return ("The headset's tracking cameras are all running, but the recorder can't read some of them (%s). "
|
||||
"Close the Hand Recorder, %s, and open it again. If that doesn't help, ask in the Frametop "
|
||||
"Discord." % (result.get("reason", ""), fix_hint("run ~/frametop/hands/rec/install.sh again")))
|
||||
return ("Not all of the headset's tracking cameras are running (%s). Restart SteamVR, or restart the "
|
||||
"headset if that doesn't fix it." % result.get("reason", ""))
|
||||
|
||||
@@ -1191,7 +1431,8 @@ class Session:
|
||||
def __init__(self, base_dir, profile, checklist, lighting_choice, script_path, *, ring=None,
|
||||
start_processes=True, dry_run=False, speed=1.0, on_status=None, hands_dir=None, panel_bin=None,
|
||||
auto=False, next_after=None, poses_dir=None, button=True, button_device=None,
|
||||
check_cameras=True, hands_reader=None, quick=False, seed=None):
|
||||
check_cameras=True, hands_reader=None, quick=False, seed=None, demos_dir=None,
|
||||
recorded_demos_dir=None, guidance=None):
|
||||
self.base_dir = os.path.abspath(os.path.expanduser(base_dir or BASE_DIR))
|
||||
self.profile = dict(profile or {})
|
||||
self.checklist = dict(checklist or {})
|
||||
@@ -1212,6 +1453,11 @@ class Session:
|
||||
self.seed = seed # set from the session's id when it starts, unless given
|
||||
# the camera check (a test hook: tests swap it); a dry run looks at no real cameras
|
||||
self.camera_check_fn = (lambda: None) if dry_run else camera_check
|
||||
self.repair_cameras_fn = (lambda: None) if dry_run else (lambda: camera_check(repair=True))
|
||||
self._camera_losses = 0
|
||||
# Frametop's drawn hands and hand pointer, paused for the session (a test hook: tests empty it)
|
||||
self.quiet_units = () if dry_run or ring else QUIET_UNITS
|
||||
self._rec_watch = None # (recorder, sets written, when that changed): _watch_recording
|
||||
self.input_devices = INPUT_DEVICES # where mice are looked for (a test hook)
|
||||
self._button = None # the ButtonReader
|
||||
self.print = print # where dry-run panel commands go (the CLI's stdout)
|
||||
@@ -1219,6 +1465,9 @@ class Session:
|
||||
# the plan in the script's order; the session's own shuffle comes with its id (_make_dir)
|
||||
self.plan, self.skipped = build_plan(self.script, self.checklist, seed=seed, quick=self.quick)
|
||||
self._poses = load_poses(poses_dir or POSES_DIR)
|
||||
self._demos_dir = demos_dir or DEMOS_DIR
|
||||
self._recorded_demos_dir = recorded_demos_dir or RECORDED_DEMOS_DIR
|
||||
self.guidance = guidance if guidance in dict(GUIDANCE) else default_guidance(self._recorded_demos_dir)
|
||||
self.session_dir = ""
|
||||
self._thread = None
|
||||
self._lock = threading.Lock()
|
||||
@@ -1233,7 +1482,7 @@ class Session:
|
||||
"prompt": "", "seconds_left": 0.0, "note": "", "hands": {"left": None, "right": None},
|
||||
"take": None, "error": "", "waiting": False, "countdown": 0, "big": "", "can_redo": False,
|
||||
"image": "", "image_mode": "", "caption": "", "position": "", "distance": "",
|
||||
"ready_text": READY_TEXT, "button": False, "mouse": True,
|
||||
"demo": "", "demo_mode": "", "demo_key": False, "demo_run": 0, "ready_text": READY_TEXT, "button": False, "mouse": True,
|
||||
"camera": None, "nohands": False, "strip": [], "cue": -1, "quick": self.quick}
|
||||
self._last_emit = 0.0
|
||||
self._log_file = None
|
||||
@@ -1271,8 +1520,25 @@ class Session:
|
||||
self._want[key] = value
|
||||
self._wake.set()
|
||||
|
||||
def button_gesture(self, gesture):
|
||||
"""The headset's button (ButtonGestures). A press: Next while a step waits, pause during
|
||||
a countdown or hold (and auto mode's timed screens), resume while paused. A double press:
|
||||
redo, as R. A hold: stop, as Esc."""
|
||||
if gesture == "press":
|
||||
self.button_press()
|
||||
elif gesture == "double":
|
||||
if self._status["state"] in ("done", "stopped", "error") or not self._status.get("can_redo"):
|
||||
return
|
||||
self.redo()
|
||||
self._log("headset button (redo)")
|
||||
elif gesture == "hold":
|
||||
if self._status["state"] in ("done", "stopped", "error"):
|
||||
return
|
||||
self._log("headset button (stop)")
|
||||
self.stop(wait=0)
|
||||
|
||||
def button_press(self):
|
||||
"""The headset's button: Next while a step waits, pause during a countdown or hold
|
||||
"""The headset button's press: Next while a step waits, pause during a countdown or hold
|
||||
(and auto mode's timed screens), resume while paused."""
|
||||
with self._lock:
|
||||
paused = self._want["pause"]
|
||||
@@ -1351,6 +1617,7 @@ class Session:
|
||||
# --- the run
|
||||
def _run(self):
|
||||
try:
|
||||
self._resume_quiet() # left paused by a session that crashed
|
||||
if self._preflight():
|
||||
return
|
||||
self._make_dir()
|
||||
@@ -1375,6 +1642,8 @@ class Session:
|
||||
if self.dry_run or self.ring or not self.check_cameras:
|
||||
return False
|
||||
r = self.camera_check_fn()
|
||||
if camcheck.is_ring_short(r): # an ft-camd left on moved cameras: nothing records yet, so restart it
|
||||
r = self.repair_cameras_fn() or r
|
||||
self._status["camera"] = r
|
||||
text = camera_text(r)
|
||||
if not text:
|
||||
@@ -1418,13 +1687,14 @@ class Session:
|
||||
self._ring_path = ring_path
|
||||
if not self.dry_run:
|
||||
if not os.access(FT_HANDS, os.X_OK):
|
||||
raise _Fail("ft-hands isn't built: hands/build.sh")
|
||||
raise _Fail("ft-hands isn't built: " + fix_hint("hands/build.sh"))
|
||||
self._ensure_ring(ring_path)
|
||||
if not tracker_running():
|
||||
if self.start_processes:
|
||||
self._start_tracker()
|
||||
else:
|
||||
self._log("no tracking ft-hands found: feedback only if one publishes")
|
||||
self._quiet_hands()
|
||||
lighting = ring_lighting(ring_path)
|
||||
cams = []
|
||||
try:
|
||||
@@ -1436,21 +1706,26 @@ class Session:
|
||||
pass
|
||||
removed = self._write_calibration() + self._write_device()
|
||||
self._session_json = {
|
||||
"schema": 1, "tool": "ft-handrec " + _git_describe(), "started": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
|
||||
"schema": 1, "tool": takes.tool_version(), "started": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
|
||||
"contributor": self.profile.get("contributor", ""),
|
||||
"lighting": lighting_record(self.lighting_choice, lighting),
|
||||
"checklist": self.checklist,
|
||||
"device": {"steamos": _os_version(), "steamvr": _steamvr_version(), "cameras": cams},
|
||||
"calibration_removed": removed,
|
||||
"script": {"version": self.script.get("version"), "sections": [s["id"] for s in self.plan],
|
||||
"script": {"version": self.script.get("version"), "name": self.script.get("name", ""),
|
||||
"sections": [s["id"] for s in self.plan],
|
||||
"skipped": self.skipped},
|
||||
"mode": "auto" if self.auto else "step", "quick": self.quick,
|
||||
"mode": "auto" if self.auto else "step", "quick": self.quick, "guidance": self.guidance,
|
||||
"shuffle": {"seed": self.seed, "sweeps": plan_record(self.plan)},
|
||||
"takes": [], "status": "recording", "sides": {"swapped": None}}
|
||||
self._read_sides(force=True)
|
||||
cam = self._status.get("camera")
|
||||
if cam:
|
||||
self._session_json["camera"] = {"status": cam.get("status"), "reason": cam.get("reason", "")}
|
||||
# which device each calibrated camera was (XRService's numbering) and whether XRService
|
||||
# ran the side cameras through the ISP (no colour module): to check the names later
|
||||
self._session_json["device"]["camera_map"] = cam.get("map") or {}
|
||||
self._session_json["device"]["isp"] = (cam.get("episode") or {}).get("isp")
|
||||
if self.dry_run:
|
||||
self._session_json["dry_run"] = True
|
||||
if self.speed != 1:
|
||||
@@ -1464,7 +1739,7 @@ class Session:
|
||||
self._panel.cmd("paused off")
|
||||
for key, c in (("note", "note "), ("countdown", "countdown off"), ("hands", "hands off off"),
|
||||
("bar", "bar off"), ("target", "target off"), ("image", "image off"), ("where", "where off"),
|
||||
("big", "big "), ("action", "action "), ("rec", "rec off"), ("strip", "strip off")):
|
||||
("demo", "demo off"), ("big", "big "), ("action", "action "), ("rec", "rec off"), ("strip", "strip off")):
|
||||
self._panel.set(key, c)
|
||||
self._hints(action=False)
|
||||
|
||||
@@ -1477,7 +1752,8 @@ class Session:
|
||||
if not path:
|
||||
self._log("headset button: no %s device with KEY_SELECT in %s" % (BUTTON_DEVICE, INPUT_DEVICES))
|
||||
return
|
||||
self._button = ButtonReader(path, self.button_press, log=self._log, debounce_s=BUTTON_DEBOUNCE_S).start()
|
||||
self._button = ButtonReader(path, self.button_gesture, log=self._log, double_s=BUTTON_DOUBLE_S,
|
||||
hold_s=BUTTON_HOLD_S, bounce_s=BUTTON_BOUNCE_S).start()
|
||||
end = time.monotonic() + 0.5 # opened in a moment, or it isn't reachable
|
||||
while not self._button.ok and time.monotonic() < end:
|
||||
time.sleep(0.01)
|
||||
@@ -1545,6 +1821,9 @@ class Session:
|
||||
self._save_session()
|
||||
self._log("side cameras: %s (%s, %s)" % ("SWAPPED" if swapped else "as named", new["decided_by"],
|
||||
json.dumps(new["evidence"])))
|
||||
if new["state"] == "forced, disagrees":
|
||||
self._log("side cameras: HANDS_SWAP_SIDES in ~/.config/frametop.conf forces names the hands say are "
|
||||
"backwards; the recording goes by the hands. Set HANDS_SWAP_SIDES=auto.")
|
||||
|
||||
def _sides_swapped(self):
|
||||
"""session.json's decision: True, False, or None (not known yet)."""
|
||||
@@ -1566,11 +1845,12 @@ class Session:
|
||||
raise _Stop()
|
||||
|
||||
def _start_tracker(self):
|
||||
up = os.path.join(REPO, "scripts", "container-up.sh")
|
||||
if os.access(up, os.X_OK):
|
||||
subprocess.run(host_command(up), capture_output=True, timeout=120)
|
||||
argv = [os.path.expanduser("~/.local/bin/distrobox"), "enter", "dev", "--", FT_HANDS,
|
||||
"--no-gestures", "--status", "0"]
|
||||
argv = [FT_HANDS, "--no-gestures", "--status", "0"]
|
||||
if not STANDALONE: # built in the dev container: it runs there
|
||||
up = os.path.join(REPO, "scripts", "container-up.sh")
|
||||
if os.access(up, os.X_OK):
|
||||
subprocess.run(host_command(up), capture_output=True, timeout=120)
|
||||
argv = [os.path.expanduser("~/.local/bin/distrobox"), "enter", "dev", "--"] + argv
|
||||
if self.ring:
|
||||
argv += ["--ring", self.ring]
|
||||
self._start_unit(HANDS_UNIT, "hand tracking for feedback", argv)
|
||||
@@ -1582,6 +1862,16 @@ class Session:
|
||||
except RuntimeError as e:
|
||||
raise _Fail(str(e))
|
||||
|
||||
def _quiet_hands(self):
|
||||
"""Frametop's drawn hands and hand pointer off until the session ends: the hand overlay
|
||||
covers what the person watches, and gestures would click or open Steam's menu."""
|
||||
if self.quiet_units:
|
||||
pause_units(self.quiet_units, os.path.join(self.hands_dir, PAUSED_UNITS_FILE), self._log)
|
||||
|
||||
def _resume_quiet(self):
|
||||
if self.quiet_units:
|
||||
resume_units(os.path.join(self.hands_dir, PAUSED_UNITS_FILE), self._log)
|
||||
|
||||
def _stop_units(self):
|
||||
for unit in reversed(self._units):
|
||||
stop_unit(unit)
|
||||
@@ -1593,7 +1883,7 @@ class Session:
|
||||
self._log("using the ft-handpanel that's running")
|
||||
return
|
||||
if not os.access(self.panel_bin, os.X_OK):
|
||||
raise _Fail("ft-handpanel isn't built: hands/rec/build.sh")
|
||||
raise _Fail("ft-handpanel isn't built: " + fix_hint("hands/rec/build.sh"))
|
||||
self._panel_proc = subprocess.Popen([self.panel_bin, "--watch-stdin"], stdin=subprocess.PIPE,
|
||||
stdout=self._log_file, stderr=self._log_file)
|
||||
end = time.monotonic() + 15
|
||||
@@ -1637,6 +1927,7 @@ class Session:
|
||||
if self._stop_note and state == "stopped":
|
||||
self._log(self._stop_note)
|
||||
self._stop_units()
|
||||
self._resume_quiet()
|
||||
if self._button:
|
||||
self._button.stop()
|
||||
self._button = None
|
||||
@@ -1661,7 +1952,7 @@ class Session:
|
||||
prompt=error or (self._stop_note if state == "stopped" else "") or screen.get("text", "").replace("|", "\n"),
|
||||
hands={"left": None, "right": None}, nohands=False,
|
||||
waiting=False, countdown=0, big="", can_redo=False, image="", image_mode="", caption="",
|
||||
position="", distance="", strip=[], cue=-1)
|
||||
position="", distance="", strip=[], cue=-1, demo="", demo_mode="", demo_key=False)
|
||||
|
||||
# --- the timing loop
|
||||
def _controls(self):
|
||||
@@ -1709,9 +2000,10 @@ class Session:
|
||||
if self._recording:
|
||||
self._stop_recording()
|
||||
self._event("pause")
|
||||
hint = RESUME_HINT_BUTTON if self._button_ok() else RESUME_HINT
|
||||
self._panel.cmd("paused on")
|
||||
self._panel.set("note", "note " + RESUME_HINT)
|
||||
self._emit(state="paused", note=RESUME_HINT)
|
||||
self._panel.set("note", "note " + hint)
|
||||
self._emit(state="paused", note=hint)
|
||||
self._log("paused")
|
||||
|
||||
def _unpause(self, record=True):
|
||||
@@ -1760,7 +2052,8 @@ class Session:
|
||||
if self._panel_proc and self._panel_proc.poll() is not None:
|
||||
raise _Fail("The headset panel closed (did SteamVR quit?)")
|
||||
if self._recorder and self._recorder.exited():
|
||||
raise _Fail("The recording stopped by itself: see session.log")
|
||||
raise _CamerasLost("The recording stopped by itself: see session.log")
|
||||
self._watch_recording(now)
|
||||
if not self.dry_run and now - fb.get("disk", 0) > 5:
|
||||
fb["disk"] = now
|
||||
if shutil.disk_usage(self.session_dir).free < MIN_FREE:
|
||||
@@ -1864,10 +2157,14 @@ class Session:
|
||||
self._panel.set("text", "text " + clean_text(text))
|
||||
|
||||
def _view(self, p=None):
|
||||
"""The prompt's picture and where-to diagram, on the panel and in the status (sent with
|
||||
the next _emit); none without a prompt."""
|
||||
"""The prompt's picture or demo clip and where-to diagram, on the panel and in the status
|
||||
(sent with the next _emit); none without a prompt. A demo clip takes the picture's place."""
|
||||
p = p or {}
|
||||
path, mode, caption = ("", "", "") if p.get("cues") else pose_view(self._poses, p)
|
||||
demo, demo_mode, demo_key = guided_demo_view(self.guidance, self._demos_dir, self._recorded_demos_dir, p)
|
||||
path, mode, caption = ("", "", "") if p.get("cues") or demo else pose_view(self._poses, p)
|
||||
self._panel.set("demo", "demo %s%s%s" % (demo, " " + demo_mode if demo_mode else "", "" if demo_key else " nokey")
|
||||
if demo else "demo off")
|
||||
self._status.update(demo=demo, demo_mode=demo_mode, demo_key=demo_key)
|
||||
self._strip(p)
|
||||
pos, dist = p.get("position") or "", p.get("distance") or ""
|
||||
self._panel.set("image", "image %s%s" % (path, " " + mode if mode else "") if path else "image off")
|
||||
@@ -1897,10 +2194,13 @@ class Session:
|
||||
for e in items)))
|
||||
self._status.update(strip=items, cue=cue)
|
||||
|
||||
def _button_ok(self):
|
||||
return bool(self._button and self._button.ok)
|
||||
|
||||
def _hints(self, action=True):
|
||||
"""The Next hint (with action) and the key line for what's there now: the headset button
|
||||
leads when no mouse is connected. Looked at again for each step, so a mouse plugged in counts."""
|
||||
button = bool(self._button and self._button.ok)
|
||||
button = self._button_ok()
|
||||
mouse = mouse_connected(self.input_devices)
|
||||
text = (READY_BUTTON_MOUSE if mouse else READY_BUTTON) if button else READY_TEXT
|
||||
keys = (KEYS_AUTO_BUTTON if self.auto else KEYS_STEP_BUTTON) if button else (KEYS_AUTO if self.auto else KEYS_STEP)
|
||||
@@ -2062,6 +2362,8 @@ class Session:
|
||||
|
||||
def _prompt_event(self, p):
|
||||
extra = {"controllers": p["controllers"]} if p["controllers"] else {}
|
||||
if p.get("demo"):
|
||||
extra["demo"] = p["demo"]
|
||||
if p.get("cue"): # a sweep's cue: the pose highlighted from now, within the step
|
||||
extra.update(cue=True, step=p["step"])
|
||||
return self._event("prompt", id=p["id"], text=p["text"], hands=p["hands"], pose=p["pose"],
|
||||
@@ -2073,6 +2375,11 @@ class Session:
|
||||
self._fb.pop("lost_key", None)
|
||||
self._show(s["title"], step, p["text"])
|
||||
self._view(p)
|
||||
if state == "running" and self._status["demo"]:
|
||||
# The hold starts: the clip from its start, so it can be followed (the window's too:
|
||||
# demo_run counts the starts).
|
||||
self._panel.cmd("demo restart")
|
||||
self._status["demo_run"] += 1
|
||||
t = self._prompt_event(p)
|
||||
if self._step_t0 is None:
|
||||
self._step_t0 = t
|
||||
@@ -2154,6 +2461,16 @@ class Session:
|
||||
self._hold_end()
|
||||
again.discard(k)
|
||||
k += 1
|
||||
except _CamerasLost as e:
|
||||
if self.auto:
|
||||
raise
|
||||
from_ns = started if started is not None else self._step_t0
|
||||
self._hold_end()
|
||||
if from_ns is not None:
|
||||
self._event("redo", id=p["id"], **{"from": from_ns, "to": mono_ns()})
|
||||
self._cameras_back(p, str(e), where)
|
||||
again.add(k)
|
||||
retry = False
|
||||
except _Redo:
|
||||
self._redo_ok = False
|
||||
from_ns = started if started is not None else self._step_t0
|
||||
@@ -2174,6 +2491,55 @@ class Session:
|
||||
self._log(" redo %s" % pid)
|
||||
again.add(k)
|
||||
|
||||
def _watch_recording(self, now):
|
||||
"""A recording that has started writing sets but writes no new one for STALL_S is lost
|
||||
(_CamerasLost): the cameras stopped or moved, and the rest of the hold would be empty."""
|
||||
rec = self._recorder
|
||||
if rec is None or self.dry_run or not hasattr(rec, "sets_written"):
|
||||
self._rec_watch = None
|
||||
return
|
||||
n = rec.sets_written()
|
||||
w = self._rec_watch
|
||||
if w is None or w[0] is not rec or n != w[1]:
|
||||
self._rec_watch = (rec, n, now)
|
||||
elif n > 0 and now - w[2] > STALL_S:
|
||||
self._rec_watch = None
|
||||
raise _CamerasLost("The recording got no new frames for %.0f s (after %d sets)" % (now - w[2], n))
|
||||
|
||||
def _cameras_back(self, p, why, where):
|
||||
"""A step's recording was lost (_CamerasLost): its try is marked redone. Wait for the
|
||||
camera check to pass, restarting a camera broker left on moved cameras (camera_check's
|
||||
repair), then the step shows again. _Fail if they don't come back, or too often."""
|
||||
self._camera_losses += 1
|
||||
self._log(" %s: %s (%d this session); waiting for the cameras" % (p["id"], why, self._camera_losses))
|
||||
if self._camera_losses > MAX_CAMERA_LOSSES:
|
||||
raise _Fail("The recording kept stopping (%d times): %s" % (self._camera_losses, why))
|
||||
self._prompt = None
|
||||
self._view()
|
||||
self._show(CAMERAS_TITLE, where, CAMERAS_TEXT)
|
||||
for key, c in (("big", "big "), ("countdown", "countdown off"), ("note", "note ")):
|
||||
self._panel.set(key, c)
|
||||
self._emit(state="between", prompt=CAMERAS_TEXT, big="", countdown=0, seconds_left=0.0, can_redo=False)
|
||||
if self.ring:
|
||||
return
|
||||
end, r = time.monotonic() + CAMERAS_BACK_S / self.speed, None
|
||||
while time.monotonic() < end:
|
||||
if self._want["stop"]:
|
||||
raise _Stop()
|
||||
r = self.repair_cameras_fn()
|
||||
if r is None: # a dry run: nothing to check
|
||||
return
|
||||
if r.get("status") == "ok":
|
||||
self._log(" cameras back: %s" % r.get("summary", "ok"))
|
||||
return
|
||||
self._wake.wait(2.0 / self.speed)
|
||||
self._wake.clear()
|
||||
summary = (r or {}).get("summary", "not run")
|
||||
for line in (r or {}).get("evidence", []):
|
||||
self._log(" " + line)
|
||||
raise _Fail("The recording stopped and the cameras didn't come back (camera check: %s). %s"
|
||||
% (summary, camera_text(r) or why))
|
||||
|
||||
def _no_hands_seen(self, p, w):
|
||||
"""The no-hands check's verdict on a hold (logged either way): True if the tracker
|
||||
published through it and never saw a hand."""
|
||||
@@ -2206,7 +2572,7 @@ class Session:
|
||||
for line in (cam or {}).get("evidence", []):
|
||||
self._log(" " + line)
|
||||
text = "%s|%s|%s" % (NO_HANDS_TEXT, cam_text or "The camera check found nothing wrong (%s)." % summary,
|
||||
NO_HANDS_RETRY)
|
||||
NO_HANDS_RETRY_BUTTON if self._button_ok() else NO_HANDS_RETRY)
|
||||
self._stop_note = "Stopped: no hands were seen in the first step. Camera check: %s." % summary
|
||||
if cam_text:
|
||||
self._stop_note += " " + cam_text
|
||||
@@ -2282,13 +2648,23 @@ class Session:
|
||||
end = time.monotonic() + FIRST_SET_S
|
||||
while not rec.has_data():
|
||||
if rec.exited():
|
||||
raise _Fail("The recording stopped by itself: see session.log")
|
||||
raise _CamerasLost("The recording stopped by itself: see session.log")
|
||||
if self._want["stop"]:
|
||||
raise _Stop()
|
||||
if time.monotonic() > end:
|
||||
self._log("recording part %d: no set yet after the countdown" % rec.part)
|
||||
return
|
||||
time.sleep(0.02)
|
||||
# Without the side pair a recording is no use for training (2026-10-12: XRService moved
|
||||
# the side cameras while ft-camd kept publishing the old devices, and ft-hands left them
|
||||
# out of a whole session). Stop at once rather than record the rest of the session.
|
||||
cams = rec.cameras()
|
||||
missing = [c for c in SIDE_CAMERAS if c not in cams]
|
||||
if cams and missing:
|
||||
self._log("recording part %d has only %s" % (rec.part, " ".join(cams)))
|
||||
raise _CamerasLost("The recording is missing the side cameras (%s), so it can't be used. Close the "
|
||||
"Hand Recorder and open it again: it checks the cameras and restarts the camera "
|
||||
"broker if it needs to." % " ".join(missing))
|
||||
|
||||
def _hold_end(self):
|
||||
"""Step mode: the step is over. A "wait" event ends its labels and the recording stops
|
||||
@@ -2458,8 +2834,13 @@ def main():
|
||||
ap.add_argument("--next-after", type=float, metavar="S",
|
||||
help="test: press Next by itself after S seconds of waiting (real time)")
|
||||
ap.add_argument("--poses", help="the pose pictures' folder, with poses.json (default hands/rec/poses)")
|
||||
ap.add_argument("--demos", help="the skeleton demo clips' folder, <id>.gif (default hands/rec/demos)")
|
||||
ap.add_argument("--recorded-demos", help="the recorded demo clips' folder (default hands/rec/demos-recorded)")
|
||||
ap.add_argument("--guidance", choices=[k for k, _ in GUIDANCE],
|
||||
help="the demo clips to follow (default recorded when there are any, else skeleton)")
|
||||
ap.add_argument("--no-headset-button", action="store_true",
|
||||
help="don't read the headset's button (gpio-keys KEY_SELECT: Next, pause, resume)")
|
||||
help="don't read the headset's button (gpio-keys KEY_SELECT: a press is Next, pause or resume; "
|
||||
"two are redo; a hold is stop)")
|
||||
ap.add_argument("--button-device", metavar="PATH",
|
||||
help="test: read the button from this event device or FIFO of input_event structs (also in a dry run)")
|
||||
ap.add_argument("--quick", action="store_true",
|
||||
@@ -2503,6 +2884,8 @@ def main():
|
||||
st["prompt"].replace("\n", " | "))
|
||||
if st["image"]:
|
||||
line += " [%s%s]" % (os.path.basename(st["image"]), " " + st["image_mode"] if st["image_mode"] else "")
|
||||
if st["demo"]:
|
||||
line += " [%s%s]" % (os.path.basename(st["demo"]), " " + st["demo_mode"] if st["demo_mode"] else "")
|
||||
if st["waiting"]:
|
||||
line += " (waiting for Next)"
|
||||
if st["note"]:
|
||||
@@ -2514,7 +2897,8 @@ def main():
|
||||
s = Session(base, profile, checklist, a.lighting, a.script, ring=a.ring, start_processes=not a.no_start,
|
||||
dry_run=a.dry_run, speed=a.speed, on_status=on_status, hands_dir=a.hands_dir, panel_bin=a.panel,
|
||||
auto=a.auto, next_after=a.next_after, poses_dir=a.poses, button=not a.no_headset_button,
|
||||
button_device=a.button_device, check_cameras=not a.ignore_cameras, quick=a.quick, seed=a.seed)
|
||||
button_device=a.button_device, check_cameras=not a.ignore_cameras, quick=a.quick, seed=a.seed,
|
||||
demos_dir=a.demos, recorded_demos_dir=a.recorded_demos, guidance=a.guidance)
|
||||
est = plan_seconds(s.script, s.plan, auto=a.auto)
|
||||
worst = plan_seconds(s.script, s.plan, worst=True, auto=a.auto)
|
||||
print("%d sections%s, %s mode: about %.1f min%s (at most %.1f)%s" % (
|
||||
|
||||
+9
-3
@@ -1,8 +1,9 @@
|
||||
"""Which side camera is which, in recordings: the rules every reader shares.
|
||||
|
||||
ft-camd tells slam_left's buffers from slam_right's by the order XRService allocated them, and
|
||||
some XRService starts reverse it: then each side camera's images carry the other's name. A
|
||||
tracking ft-hands tells from the hands (hands/track/sides.h, HANDS_SWAP_SIDES=auto) and publishes
|
||||
Before 2026-10-05, ft-hands named the side cameras by XRService's start-up order and ft-camd bound
|
||||
their buffers by XRService's descriptor order, so on most starts each side camera's images carried
|
||||
the other's name (hands/README.md, "Which camera is which"). Both are exact now, and a
|
||||
tracking ft-hands still tells from the hands (hands/track/sides.h, HANDS_SWAP_SIDES=auto) and publishes
|
||||
what it found in /run/user/UID/frametop-hands/sides.json (read_live). Two things are recorded:
|
||||
|
||||
swapped whether ft-camd's naming was backwards during the recording (the truth);
|
||||
@@ -125,4 +126,9 @@ def read_live(path=None, ring_path=None, now_ns=None):
|
||||
return None
|
||||
except OSError:
|
||||
return None
|
||||
if (s.get("state") == "forced, disagrees" and s.get("swapped") is not None
|
||||
and bool(s["swapped"]) == bool(s.get("names_swapped"))):
|
||||
# An ft-hands built before 2026-10-06 kept a forced HANDS_SWAP_SIDES as the truth even
|
||||
# when the hands disagreed. The hands are right: the truth is the other way round.
|
||||
s = dict(s, swapped=not s["swapped"], decided_by="auto")
|
||||
return s
|
||||
+19
-1
@@ -83,8 +83,26 @@ def find_zstd():
|
||||
return next((p for p in ZSTD_PATHS if os.access(p, os.X_OK)), None)
|
||||
|
||||
|
||||
def standalone(path=None):
|
||||
"""The standalone Hand Recorder's build info, or None in a Frametop checkout. Its release
|
||||
(github.com/Frametop/frametop-hand-recorder) ships this repo's tree with standalone.json at
|
||||
the top: {"name", "version", "frametop": this repo's git describe, "reinstall": how to repair
|
||||
an install}. Its binaries are built for the SteamOS host, so nothing runs in the dev container."""
|
||||
try:
|
||||
with open(path or os.path.join(REPO, "standalone.json")) as f:
|
||||
info = json.load(f)
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
return info if isinstance(info, dict) else None
|
||||
|
||||
|
||||
def tool_version():
|
||||
"""ft-handrec plus the checkout's git describe, for session.json and the manifest."""
|
||||
"""ft-handrec plus the checkout's git describe, for session.json and the manifest. The
|
||||
standalone Hand Recorder has no checkout: the describe it was built from, and its version."""
|
||||
info = standalone()
|
||||
if info:
|
||||
return "ft-handrec %s (%s %s)" % (info.get("frametop") or "unknown", info.get("name") or "standalone",
|
||||
info.get("version") or "unknown")
|
||||
try:
|
||||
out = subprocess.run(["git", "-C", REPO, "describe", "--always", "--dirty", "--tags"],
|
||||
capture_output=True, text=True, timeout=5)
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
"""main.qml against ft_handrec.Backend: every backend.name(...) the window calls is a slot, and
|
||||
every backend.name it reads is a property or a slot. A method that lost its @Slot shows up in
|
||||
QML only as "is not a function" when its button is pressed (2026-10-03: Export did nothing).
|
||||
Needs PySide6 (the dev container); skipped without it.
|
||||
Needs PySide6 (the dev container); skipped without it. FT_HANDREC_QML=PATH checks another
|
||||
window against the same backend (the standalone Hand Recorder's, in its CI).
|
||||
|
||||
python3 hands/rec/tests/test_qml_backend.py
|
||||
"""
|
||||
@@ -14,6 +15,7 @@ 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_HANDREC_QML") or os.path.join(REC, "main.qml")
|
||||
|
||||
|
||||
class QmlBackendTest(unittest.TestCase):
|
||||
@@ -25,7 +27,7 @@ class QmlBackendTest(unittest.TestCase):
|
||||
meta = self.meta = ft_handrec.Backend.staticMetaObject
|
||||
self.slots = {bytes(meta.method(i).name()).decode() for i in range(meta.methodCount())}
|
||||
self.props = {meta.property(i).name() for i in range(meta.propertyCount())}
|
||||
with open(os.path.join(REC, "main.qml")) as f:
|
||||
with open(QML) as f:
|
||||
self.qml = f.read()
|
||||
|
||||
def test_calls_are_slots(self):
|
||||
@@ -66,5 +68,36 @@ class QmlBackendTest(unittest.TestCase):
|
||||
self.assertEqual(sorted(read - self.props - self.slots), [], "read in main.qml but not on Backend")
|
||||
|
||||
|
||||
|
||||
class GuidanceTest(unittest.TestCase):
|
||||
"""The demo clips to follow: recorded by default when there are recorded clips, the choice
|
||||
kept in BASE/settings.json and handed to the session."""
|
||||
|
||||
def test_choice(self):
|
||||
import json
|
||||
import shutil
|
||||
import tempfile
|
||||
try:
|
||||
import ft_handrec
|
||||
import takes
|
||||
except ImportError as e:
|
||||
self.skipTest(f"no PySide6: {e}")
|
||||
tmp = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, tmp)
|
||||
rec = os.path.join(tmp, "rec")
|
||||
os.makedirs(rec)
|
||||
backend = ft_handrec.Backend(takes.Store(os.path.join(tmp, "base")), {"recorded_demos_dir": rec})
|
||||
self.assertEqual([c["value"] for c in backend.guidanceChoices], ["recorded", "skeleton"])
|
||||
self.assertEqual(backend.guidance, "skeleton") # no recorded clips
|
||||
with open(os.path.join(rec, "2a.gif"), "wb") as f:
|
||||
f.write(b"GIF89a")
|
||||
self.assertEqual(backend.guidance, "recorded")
|
||||
backend.setGuidance("skeleton")
|
||||
backend.setGuidance("nonsense")
|
||||
with open(os.path.join(tmp, "base", "settings.json")) as f:
|
||||
self.assertEqual(json.load(f), {"guidance": "skeleton"})
|
||||
self.assertEqual(backend.guidance, "skeleton")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+495
-17
@@ -102,6 +102,31 @@ class SessionTest(SessionBase):
|
||||
self.assertIn("panel: where left near", self.panel)
|
||||
self.assertIn("panel: rec on", self.panel)
|
||||
|
||||
def test_guidance(self):
|
||||
"""The chosen guidance's clip on the panel (a recorded one without the colours' key), and
|
||||
the choice in session.json."""
|
||||
script = json.loads(json.dumps(SCRIPT))
|
||||
script["sections"][0]["prompts"][0].update(demo="2a", demo_mirror=True)
|
||||
with open(self.script, "w") as f:
|
||||
json.dump(script, f)
|
||||
skel, rec = os.path.join(self.tmp, "skel"), os.path.join(self.tmp, "rec")
|
||||
for d in (skel, rec):
|
||||
os.makedirs(d)
|
||||
with open(os.path.join(d, "2a.gif"), "wb") as f:
|
||||
f.write(tiny_gif([[0, 1, 2, 3]]))
|
||||
for guidance, want in (("recorded", "panel: demo %s/2a.gif mirror nokey" % rec),
|
||||
("skeleton", "panel: demo %s/2a.gif mirror" % skel)):
|
||||
self.panel.clear()
|
||||
s = self.session(next_after=0.0, demos_dir=skel, recorded_demos_dir=rec, guidance=guidance)
|
||||
s.start()
|
||||
s.join(20)
|
||||
self.assertEqual(s.state, "done")
|
||||
self.assertIn(want, self.panel)
|
||||
with open(os.path.join(s.session_dir, "session.json")) as f:
|
||||
self.assertEqual(json.load(f)["guidance"], guidance)
|
||||
# no choice: recorded, since there are recorded clips
|
||||
self.assertEqual(self.session(demos_dir=skel, recorded_demos_dir=rec).guidance, "recorded")
|
||||
|
||||
def test_redo(self):
|
||||
s = self.session()
|
||||
s.start()
|
||||
@@ -386,6 +411,148 @@ class StripPanelTest(unittest.TestCase):
|
||||
self.assertIn("strip: off", out)
|
||||
|
||||
|
||||
def tiny_gif(frames, delay_cs=5):
|
||||
"""A GIF of 2x2 frames, each 4 palette indices (0-3: black, red, green, blue). Every pixel
|
||||
is coded after a clear code, so the LZW table never grows (a valid, uncompressed GIF)."""
|
||||
def lzw(pixels):
|
||||
bits, out = [], bytearray()
|
||||
for v in [x for p in pixels for x in (4, p)] + [5]: # clear, pixel ... end
|
||||
bits += [(v >> k) & 1 for k in range(3)]
|
||||
for i in range(0, len(bits), 8):
|
||||
out.append(sum(b << k for k, b in enumerate(bits[i:i + 8])))
|
||||
return bytes([2, len(out)]) + bytes(out) + b"\0"
|
||||
head = b"GIF89a" + struct.pack("<HHBBB", 2, 2, 0xF1, 0, 0) + bytes([0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255])
|
||||
loop = b"\x21\xff\x0bNETSCAPE2.0\x03\x01\0\0\0"
|
||||
body = b"".join(b"\x21\xf9\x04\x04" + struct.pack("<H", delay_cs) + b"\0\0" + b"\x2c" + struct.pack("<HHHHB", 0, 0, 2, 2, 0)
|
||||
+ lzw(f) for f in frames)
|
||||
return head + loop + body + b"\x3b"
|
||||
|
||||
|
||||
class ScriptV2Test(unittest.TestCase):
|
||||
"""script-v2.json: a step per demo clip, one-hand parts left (the clip flipped), right, both."""
|
||||
|
||||
def setUp(self):
|
||||
self.script = session.load_script(os.path.join(session.HERE, "script-v2.json"))
|
||||
with open(os.path.join(session.HERE, "demo", "parts.json")) as f:
|
||||
self.parts = [p["id"] for p in json.load(f)["parts"]]
|
||||
|
||||
def test_plan(self):
|
||||
full, skipped = session.build_plan(self.script, {"controllers": "straps", "objects": ["keyboard"]})
|
||||
self.assertEqual(skipped, [])
|
||||
self.assertEqual(full[0]["id"], session.HANDS_CHECK_SECTION) # the no-hands check runs first
|
||||
demos = [p for s in full for p in s["prompts"] if p.get("demo")]
|
||||
self.assertEqual(sorted(set(p["demo"] for p in demos)), sorted(self.parts)) # every part, and no others
|
||||
ids = [p["id"] for s in full for p in s["prompts"]]
|
||||
self.assertEqual(len(ids), len(set(ids)))
|
||||
for p in demos:
|
||||
self.assertEqual(bool(p.get("demo_mirror")), p["hands"] == "left", p["id"])
|
||||
self.assertGreater(p["seconds"], 0)
|
||||
self.assertEqual([p["hands"] for p in demos if p["demo"] == "2a"], ["left", "right", "both"])
|
||||
self.assertLess(session.plan_seconds(self.script, full, auto=False), 15 * 60)
|
||||
quick, _ = session.build_plan(self.script, {}, quick=True)
|
||||
self.assertEqual([p["id"] for s in quick for p in s["prompts"]],
|
||||
["hand-size/1/both/mid", "index-taps/2a/right", "palm-up/7a/both", "no-hands/none"])
|
||||
|
||||
def test_clips(self):
|
||||
if not os.path.isdir(session.DEMOS_DIR):
|
||||
self.skipTest("no demo clips in %s" % session.DEMOS_DIR)
|
||||
for pid in self.parts:
|
||||
self.assertTrue(os.path.isfile(os.path.join(session.DEMOS_DIR, pid + ".gif")), pid)
|
||||
|
||||
def test_view(self):
|
||||
tmp = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, tmp)
|
||||
with open(os.path.join(tmp, "2a.gif"), "wb") as f:
|
||||
f.write(tiny_gif([[0, 1, 2, 3]]))
|
||||
self.assertEqual(session.demo_view(tmp, {"demo": "2a", "demo_mirror": True}), (os.path.join(tmp, "2a.gif"), "mirror"))
|
||||
self.assertEqual(session.demo_view(tmp, {"demo": "2a"}), (os.path.join(tmp, "2a.gif"), ""))
|
||||
self.assertEqual(session.demo_view(tmp, {"demo": "3a"}), ("", ""))
|
||||
self.assertEqual(session.demo_view(tmp, {}), ("", ""))
|
||||
|
||||
def test_guidance(self):
|
||||
"""Recorded or skeleton clips, each falling back to the other kind for a part it lacks; only
|
||||
a skeleton clip gets the colours' key."""
|
||||
tmp = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, tmp)
|
||||
skel, rec = os.path.join(tmp, "skel"), os.path.join(tmp, "rec")
|
||||
os.makedirs(skel)
|
||||
os.makedirs(rec)
|
||||
self.assertEqual(session.default_guidance(rec), "skeleton") # no recorded clips yet
|
||||
self.assertEqual(session.default_guidance(os.path.join(tmp, "none")), "skeleton")
|
||||
for d, ids in ((skel, ("2a", "3a")), (rec, ("2a",))):
|
||||
for i in ids:
|
||||
with open(os.path.join(d, i + ".gif"), "wb") as f:
|
||||
f.write(tiny_gif([[0, 1, 2, 3]]))
|
||||
self.assertEqual(session.default_guidance(rec), "recorded")
|
||||
left = {"demo": "2a", "demo_mirror": True}
|
||||
self.assertEqual(session.guided_demo_view("recorded", skel, rec, left), (os.path.join(rec, "2a.gif"), "mirror", False))
|
||||
self.assertEqual(session.guided_demo_view("skeleton", skel, rec, left), (os.path.join(skel, "2a.gif"), "mirror", True))
|
||||
self.assertEqual(session.guided_demo_view("recorded", skel, rec, {"demo": "3a"}), (os.path.join(skel, "3a.gif"), "", True))
|
||||
self.assertEqual(session.guided_demo_view("recorded", skel, rec, {"demo": "4a"}), ("", "", False))
|
||||
self.assertEqual(session.guided_demo_view("skeleton", skel, rec, {}), ("", "", False))
|
||||
|
||||
def test_recorded_clips(self):
|
||||
if not session.has_clips(session.RECORDED_DEMOS_DIR):
|
||||
self.skipTest("no recorded demo clips in %s" % session.RECORDED_DEMOS_DIR)
|
||||
for pid in self.parts:
|
||||
self.assertTrue(os.path.isfile(os.path.join(session.RECORDED_DEMOS_DIR, pid + ".gif")), pid)
|
||||
|
||||
|
||||
class DemoPanelTest(unittest.TestCase):
|
||||
"""The panel's demo command on ft-handpanel --no-vr (skipped if it isn't built)."""
|
||||
|
||||
def test_demo(self):
|
||||
import subprocess
|
||||
binary = session.PANEL_BIN
|
||||
if not os.access(binary, os.X_OK):
|
||||
self.skipTest("ft-handpanel isn't built")
|
||||
tmp = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, tmp)
|
||||
clip = os.path.join(tmp, "clip one.gif") # a space: the path may hold them
|
||||
with open(clip, "wb") as f:
|
||||
f.write(tiny_gif([[0, 1, 2, 3], [3, 2, 1, 0], [1, 1, 1, 1]], delay_cs=5))
|
||||
with open(os.path.join(tmp, "bad.gif"), "wb") as f:
|
||||
f.write(b"GIF89a broken")
|
||||
name = "hrtest-demo-%d" % os.getpid()
|
||||
proc = subprocess.Popen([binary, "--no-vr", "--socket", name, "--dump", tmp], stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True)
|
||||
try:
|
||||
panel = session.Panel(name=name)
|
||||
for _ in range(50):
|
||||
if panel.cmd("ping", reply=True, timeout=0.1):
|
||||
break
|
||||
if proc.poll() is not None:
|
||||
self.skipTest("ft-handpanel doesn't run here: " + proc.stderr.read().strip()[-200:])
|
||||
time.sleep(0.1)
|
||||
else:
|
||||
self.fail("ft-handpanel --no-vr doesn't answer")
|
||||
replies = [panel.cmd("demo %s mirror" % clip, reply=True), panel.cmd("show", reply=True)]
|
||||
time.sleep(0.4) # 3 frames of 50 ms: it loops
|
||||
replies.append(panel.cmd("note looped", reply=True))
|
||||
replies.append(panel.cmd("demo restart", reply=True))
|
||||
replies += [panel.cmd("demo", reply=True), panel.cmd("demo %s/missing.gif" % tmp, reply=True),
|
||||
panel.cmd("demo %s/bad.gif" % tmp, reply=True), panel.cmd("demo off", reply=True)]
|
||||
# a recorded clip: no key; the same clip again with the key back
|
||||
replies += [panel.cmd("demo %s mirror nokey" % clip, reply=True), panel.cmd("show", reply=True),
|
||||
panel.cmd("demo %s nokey" % clip, reply=True), panel.cmd("demo %s" % clip, reply=True),
|
||||
panel.cmd("demo off", reply=True)]
|
||||
panel.close()
|
||||
finally:
|
||||
proc.terminate()
|
||||
out = proc.communicate(timeout=5)[0]
|
||||
self.assertEqual(replies[:4], ["ok"] * 4)
|
||||
self.assertTrue(replies[4].startswith("error usage: demo"))
|
||||
self.assertTrue(replies[5].startswith("error can't read"))
|
||||
self.assertTrue(replies[6].startswith("error can't read"))
|
||||
self.assertEqual(replies[7:], ["ok"] * 6)
|
||||
demos = [l for l in out.splitlines() if l.startswith("demo:")]
|
||||
self.assertTrue(any(l.startswith("demo: %s 2x2 frame" % clip) and " mirror nokey, drawn" in l for l in demos), demos)
|
||||
self.assertIn("demo: %s 2x2 frame 0 loop 0 mirror, drawn" % clip, demos[0])
|
||||
self.assertGreater(int(demos[1].split(" loop ")[1].split()[0]), 0) # past the last frame, from the start again
|
||||
self.assertIn("demo: %s 2x2 frame 0 loop 0 mirror" % clip, demos[2]) # restart
|
||||
self.assertEqual(demos[-1], "demo: off")
|
||||
|
||||
|
||||
# /proc/bus/input/devices as the Frame has it (2026-10-02), trimmed, plus a USB mouse.
|
||||
DEVICES = """I: Bus=0019 Vendor=0001 Product=0001 Version=0100
|
||||
N: Name="gpio-keys"
|
||||
@@ -458,8 +625,15 @@ B: MSC=10
|
||||
"""
|
||||
|
||||
|
||||
def event(etype, code, value):
|
||||
return session.INPUT_EVENT.pack(1, 2, etype, code, value)
|
||||
def event(etype, code, value, t=1.000002):
|
||||
return session.INPUT_EVENT.pack(int(t), round(t % 1 * 1e6), etype, code, value)
|
||||
|
||||
|
||||
def taps(*times):
|
||||
"""Presses, each 50 ms down, at these times (the kernel's clock), as one write."""
|
||||
return b"".join(event(session.EV_KEY, session.KEY_SELECT, 1, t) + event(0, 0, 0, t)
|
||||
+ event(session.EV_KEY, session.KEY_SELECT, 0, t + 0.05) + event(0, 0, 0, t + 0.05)
|
||||
for t in times)
|
||||
|
||||
|
||||
PRESS = event(session.EV_KEY, session.KEY_SELECT, 1) + event(0, 0, 0)
|
||||
@@ -479,35 +653,74 @@ class InputTest(unittest.TestCase):
|
||||
# another gpio-keys without KEY_SELECT isn't the button
|
||||
self.assertIsNone(session.find_button(session.parse_input_devices(DEVICES.replace("200000000", "0"))))
|
||||
|
||||
def test_presses(self):
|
||||
data = (PRESS + event(session.EV_KEY, session.KEY_SELECT, 2) * 3 # autorepeat: not presses
|
||||
def test_events(self):
|
||||
data = (PRESS + event(session.EV_KEY, session.KEY_SELECT, 2) * 3 # autorepeat: left out
|
||||
+ RELEASE + event(session.EV_KEY, 115, 1) + PRESS) # another key
|
||||
self.assertEqual(session.button_presses(data), (2, b""))
|
||||
n, rest = session.button_presses(PRESS + PRESS[:10])
|
||||
self.assertEqual((n, rest), (1, PRESS[:10])) # half an event waits for the rest
|
||||
self.assertEqual(session.button_presses(rest + PRESS[10:])[0], 1)
|
||||
self.assertEqual(session.button_events(data), ([(True, 1.000002), (False, 1.000002), (True, 1.000002)], b""))
|
||||
out, rest = session.button_events(PRESS + PRESS[:10])
|
||||
self.assertEqual((out, rest), ([(True, 1.000002)], PRESS[:10])) # half an event waits for the rest
|
||||
self.assertEqual(session.button_events(rest + PRESS[10:])[0], [(True, 1.000002)])
|
||||
self.assertEqual([t for _, t in session.button_events(taps(5.25))[0]], [5.25, 5.3])
|
||||
|
||||
def test_gestures(self):
|
||||
def run(steps, **kw):
|
||||
"""steps: (time, "down" | "up" | "tick"). The gestures, with the time each came."""
|
||||
g, out = session.ButtonGestures(double_s=0.4, hold_s=1.5, bounce_s=0.05, **kw), []
|
||||
for t, what in steps:
|
||||
out += [(t, x) for x in getattr(g, what)(t)]
|
||||
return out
|
||||
# a press comes once the double-press time has passed
|
||||
self.assertEqual(run([(0, "down"), (0.1, "up"), (0.3, "tick"), (0.6, "tick")]), [(0.6, "press")])
|
||||
# two: a double, at the second down, and nothing at its release
|
||||
self.assertEqual(run([(0, "down"), (0.1, "up"), (0.4, "down"), (0.5, "up"), (2, "tick")]),
|
||||
[(0.4, "double")])
|
||||
# the second too late: two presses (the first reported when the second goes down)
|
||||
self.assertEqual(run([(0, "down"), (0.1, "up"), (0.6, "down"), (0.7, "up"), (1.2, "tick")]),
|
||||
[(0.6, "press"), (1.2, "press")])
|
||||
# a hold: while still down, and nothing at the release
|
||||
self.assertEqual(run([(0, "down"), (1.0, "tick"), (1.5, "tick"), (3, "up"), (4, "tick")]),
|
||||
[(1.5, "hold")])
|
||||
# a hold noticed only at the release (a slow read) still counts
|
||||
self.assertEqual(run([(0, "down"), (2, "up"), (3, "tick")]), [(2, "hold")])
|
||||
# a bounce (up and down 20 ms apart) is one press
|
||||
self.assertEqual(run([(0, "down"), (0.1, "up"), (0.12, "down"), (0.2, "up"), (1, "tick")]),
|
||||
[(1, "press")])
|
||||
# a press, then a hold soon after: a double (the hold counts from a fresh down)
|
||||
self.assertEqual(run([(0, "down"), (0.1, "up"), (0.3, "down"), (2, "tick"), (2.1, "up")]),
|
||||
[(0.3, "double")])
|
||||
# a release with no down, and two downs: left alone
|
||||
self.assertEqual(run([(0, "up"), (1, "down"), (1.1, "down"), (1.2, "up"), (2, "tick")]),
|
||||
[(2, "press")])
|
||||
|
||||
def test_reader_fifo(self):
|
||||
tmp = tempfile.mkdtemp(prefix="handrec-button-test-")
|
||||
try:
|
||||
fifo = os.path.join(tmp, "button")
|
||||
os.mkfifo(fifo)
|
||||
presses = []
|
||||
reader = session.ButtonReader(fifo, lambda: presses.append(time.monotonic()), debounce_s=0.3).start()
|
||||
got = []
|
||||
reader = session.ButtonReader(fifo, got.append, double_s=0.15, hold_s=0.5).start()
|
||||
with open(fifo, "wb", buffering=0) as w:
|
||||
w.write(PRESS + RELEASE)
|
||||
w.write(PRESS[:7]) # a press split across writes, a bounce
|
||||
time.sleep(0.05)
|
||||
w.write(PRESS + RELEASE) # a press
|
||||
time.sleep(0.3)
|
||||
w.write(PRESS[:7]) # two, the first split across writes
|
||||
time.sleep(0.02)
|
||||
w.write(PRESS[7:] + RELEASE)
|
||||
time.sleep(0.4)
|
||||
time.sleep(0.07)
|
||||
w.write(PRESS + RELEASE)
|
||||
time.sleep(0.3)
|
||||
w.write(taps(10, 10.1)) # two in one read: the kernel's times tell them apart
|
||||
time.sleep(0.3)
|
||||
w.write(PRESS) # held
|
||||
time.sleep(0.7)
|
||||
self.assertEqual(got, ["press", "double", "double", "hold"]) # the hold came before the release
|
||||
w.write(RELEASE)
|
||||
time.sleep(0.2)
|
||||
with open(fifo, "wb", buffering=0) as w: # the writer comes back: read again
|
||||
time.sleep(0.4)
|
||||
w.write(PRESS)
|
||||
w.write(PRESS + RELEASE)
|
||||
time.sleep(0.3)
|
||||
reader.stop()
|
||||
self.assertEqual(len(presses), 3)
|
||||
self.assertEqual(got, ["press", "double", "double", "hold", "press"])
|
||||
self.assertTrue(reader.ok)
|
||||
finally:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
@@ -533,7 +746,7 @@ class ButtonSessionTest(SessionBase):
|
||||
writer = os.open(fifo, os.O_RDWR) # kept open, so the reader never sees the end
|
||||
press = lambda: os.write(writer, PRESS + RELEASE)
|
||||
try:
|
||||
with mock.patch.object(session, "BUTTON_DEBOUNCE_S", 0.0):
|
||||
with mock.patch.object(session, "BUTTON_DOUBLE_S", 0.1):
|
||||
s = self.session(speed=4, button_device=fifo)
|
||||
s.input_devices = procfile
|
||||
s.start()
|
||||
@@ -563,6 +776,41 @@ class ButtonSessionTest(SessionBase):
|
||||
finally:
|
||||
os.close(writer)
|
||||
|
||||
def test_redo_and_stop(self):
|
||||
"""Two presses redo the step, a hold stops the session; the hints say so."""
|
||||
fifo = os.path.join(self.tmp, "button")
|
||||
os.mkfifo(fifo)
|
||||
writer = os.open(fifo, os.O_RDWR)
|
||||
press = lambda: os.write(writer, PRESS + RELEASE)
|
||||
try:
|
||||
with mock.patch.multiple(session, BUTTON_DOUBLE_S=0.15, BUTTON_HOLD_S=0.4):
|
||||
s = self.session(speed=2, button_device=fifo)
|
||||
s.start()
|
||||
self.waiting(s, "starting")
|
||||
press()
|
||||
self.waiting(s, "intro")
|
||||
press()
|
||||
self.waiting(s, "ready", "Fist.")
|
||||
press()
|
||||
self.wait_for(s, lambda st: st["state"] == "running", "the hold")
|
||||
os.write(writer, taps(1, 1.1)) # twice: redo
|
||||
self.waiting(s, "ready", "Fist.")
|
||||
time.sleep(0.1) # (sooner would be a bounce of the last)
|
||||
press()
|
||||
self.wait_for(s, lambda st: st["state"] == "running", "the hold again")
|
||||
press() # pause
|
||||
st = self.wait_for(s, lambda st: st["state"] == "paused", "paused")
|
||||
self.assertEqual(st["note"], session.RESUME_HINT_BUTTON)
|
||||
os.write(writer, PRESS) # held: stop
|
||||
s.join(20)
|
||||
os.write(writer, RELEASE)
|
||||
self.assertEqual(s.state, "stopped")
|
||||
names = [e["event"] for e in self.events(s)]
|
||||
self.assertEqual(names, ["take", "ready", "prompt", "redo", "wait", "ready", "prompt", "pause", "end"])
|
||||
self.assertIn("panel: keys " + session.KEYS_STEP_BUTTON, self.panel)
|
||||
finally:
|
||||
os.close(writer)
|
||||
|
||||
def test_no_button(self):
|
||||
s = self.session(next_after=0.0, button=False, button_device="/nonexistent")
|
||||
s.start()
|
||||
@@ -630,5 +878,235 @@ class ManyPartsTest(unittest.TestCase):
|
||||
self.assertEqual(r.summary["sets"], 120 + 30)
|
||||
|
||||
|
||||
class StandaloneTest(unittest.TestCase):
|
||||
"""The standalone Hand Recorder's tree (standalone.json at the top): ft-hands runs on the
|
||||
host, the version comes from the build info, and repairs point at its install command."""
|
||||
INFO = {"name": "frametop-hand-recorder", "version": "0.1.0", "frametop": "4ba49af",
|
||||
"reinstall": "run the install command again"}
|
||||
|
||||
def test_build_info(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
path = os.path.join(d, "standalone.json")
|
||||
self.assertIsNone(takes.standalone(path))
|
||||
with open(path, "w") as f:
|
||||
json.dump(self.INFO, f)
|
||||
self.assertEqual(takes.standalone(path), self.INFO)
|
||||
with open(path, "w") as f:
|
||||
f.write("[1]")
|
||||
self.assertIsNone(takes.standalone(path))
|
||||
with mock.patch.object(takes, "standalone", return_value=self.INFO):
|
||||
self.assertEqual(takes.tool_version(), "ft-handrec 4ba49af (frametop-hand-recorder 0.1.0)")
|
||||
|
||||
def recorder_argv(self, standalone):
|
||||
with tempfile.TemporaryDirectory() as d, mock.patch.object(session, "STANDALONE", standalone), \
|
||||
mock.patch.object(session, "in_container", return_value=False), \
|
||||
mock.patch.object(session.subprocess, "Popen") as popen:
|
||||
session.Recorder(d, 1, 10, None, None)
|
||||
return popen.call_args[0][0]
|
||||
|
||||
def tracker_argv(self, standalone):
|
||||
fake = mock.Mock(ring=None)
|
||||
with mock.patch.object(session, "STANDALONE", standalone), \
|
||||
mock.patch.object(session.subprocess, "run") as run:
|
||||
session.Session._start_tracker(fake)
|
||||
return fake._start_unit.call_args[0][2], run
|
||||
|
||||
def test_ft_hands_on_the_host(self):
|
||||
self.assertEqual(self.recorder_argv(self.INFO)[0], session.FT_HANDS)
|
||||
argv, run = self.tracker_argv(self.INFO)
|
||||
self.assertEqual(argv[0], session.FT_HANDS)
|
||||
self.assertIn("--no-gestures", argv)
|
||||
run.assert_not_called() # no container to bring up
|
||||
|
||||
def test_ft_hands_in_the_dev_container(self):
|
||||
self.assertTrue(self.recorder_argv(None)[0].endswith("distrobox"))
|
||||
argv, _ = self.tracker_argv(None)
|
||||
self.assertEqual(argv[:4], [os.path.expanduser("~/.local/bin/distrobox"), "enter", "dev", "--"])
|
||||
self.assertEqual(argv[4], session.FT_HANDS)
|
||||
|
||||
def test_fix_hint(self):
|
||||
with mock.patch.object(session, "STANDALONE", self.INFO):
|
||||
self.assertEqual(session.fix_hint("hands/build.sh"), "run the install command again")
|
||||
text = session.camera_text({"status": "degraded", "reason": "2 of 4", "ring_missing": ["upper_left"]})
|
||||
with mock.patch.object(session, "STANDALONE", None):
|
||||
self.assertEqual(session.fix_hint("hands/build.sh"), "hands/build.sh")
|
||||
self.assertIn("run the install command again", text)
|
||||
self.assertNotIn("~/frametop", text)
|
||||
|
||||
|
||||
class SideCameraGuardTest(unittest.TestCase):
|
||||
"""A part whose first set has no side cameras stops the session (2026-10-12: a whole
|
||||
session recorded only the upper pair after XRService moved the side cameras)."""
|
||||
|
||||
def write_set(self, d, names):
|
||||
data = bytearray(struct.pack("<8sII", b"FHSET01", len(names), 16 + 40 * len(names)))
|
||||
for n in names:
|
||||
data += struct.pack("<16sIIQQ", n.encode(), 2, 2, 1, 1)
|
||||
with open(os.path.join(d, "sets.bin"), "wb") as f:
|
||||
f.write(bytes(data))
|
||||
|
||||
def first_set(self, d):
|
||||
rec = mock.Mock(dir=d, part=1, exited=lambda: False)
|
||||
rec.has_data = lambda: True
|
||||
rec.cameras = lambda: session.Recorder.cameras(rec)
|
||||
fake = mock.Mock(_recorder=rec, _want={"stop": False})
|
||||
session.Session._first_set(fake)
|
||||
return fake
|
||||
|
||||
def test_upper_pair_only(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
self.write_set(d, ["upper_left", "upper_right"])
|
||||
with self.assertRaises(session._Fail) as cm:
|
||||
self.first_set(d)
|
||||
self.assertIn("missing the side cameras (slam_left slam_right)", str(cm.exception))
|
||||
|
||||
def test_all_four(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
self.write_set(d, ["slam_left", "slam_right", "upper_left", "upper_right"])
|
||||
self.first_set(d)
|
||||
|
||||
def test_unreadable_first_set_goes_on(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
with open(os.path.join(d, "sets.bin"), "wb") as f:
|
||||
f.write(b"xx")
|
||||
self.first_set(d)
|
||||
|
||||
def test_moved_cameras_text(self):
|
||||
text = session.camera_text({"status": "degraded", "ring_missing": [0, 3],
|
||||
"reason": "ft-camd publishes video9 video13, but XRService runs those cameras "
|
||||
"on video0 video3 now (it moved them after ft-camd started)"})
|
||||
self.assertIn("open it again: it restarts the camera broker", text)
|
||||
|
||||
|
||||
class CamerasLostTest(SessionBase):
|
||||
"""A step whose recording is lost (ft-camd restarting after XRService moved the cameras)
|
||||
waits for the camera check, then goes again; too many losses stop the session."""
|
||||
|
||||
def lose(self, s, times):
|
||||
real = session.Session._run_step
|
||||
lost = {"n": 0}
|
||||
|
||||
def run_step(self_, *a):
|
||||
if lost["n"] < times:
|
||||
lost["n"] += 1
|
||||
raise session._CamerasLost("The recording stopped by itself: see session.log")
|
||||
return real(self_, *a)
|
||||
return mock.patch.object(session.Session, "_run_step", run_step)
|
||||
|
||||
def test_waits_and_redoes_the_step(self):
|
||||
s = self.session(next_after=0.0)
|
||||
checks = iter([{"status": "degraded", "summary": "degraded: moved"}, {"status": "ok", "summary": "ok"}])
|
||||
s.repair_cameras_fn = lambda: next(checks)
|
||||
with self.lose(s, 1):
|
||||
s.start()
|
||||
s.join(20)
|
||||
self.assertEqual(s.state, "done")
|
||||
ev = self.events(s)
|
||||
self.assertEqual([e["event"] for e in ev],
|
||||
["take", "ready", "wait", "redo", "ready", "prompt", "wait", "ready", "prompt", "wait",
|
||||
"end"])
|
||||
self.assertEqual(ev[3]["id"], ev[5]["id"])
|
||||
with open(os.path.join(s.session_dir, "session.log")) as f:
|
||||
log = f.read()
|
||||
self.assertIn("waiting for the cameras", log)
|
||||
self.assertIn("cameras back: ok", log)
|
||||
|
||||
def test_cameras_dont_come_back(self):
|
||||
s = self.session(next_after=0.0, speed=100)
|
||||
s.repair_cameras_fn = lambda: {"status": "degraded", "summary": "degraded: moved", "reason": "moved",
|
||||
"evidence": []}
|
||||
with self.lose(s, 1):
|
||||
s.start()
|
||||
s.join(20)
|
||||
self.assertEqual(s.state, "error")
|
||||
self.assertIn("the cameras didn't come back", s._status["error"])
|
||||
|
||||
def test_too_many_losses(self):
|
||||
s = self.session(next_after=0.0)
|
||||
s.repair_cameras_fn = lambda: None
|
||||
with self.lose(s, session.MAX_CAMERA_LOSSES + 1):
|
||||
s.start()
|
||||
s.join(20)
|
||||
self.assertEqual(s.state, "error")
|
||||
self.assertIn("kept stopping", s._status["error"])
|
||||
|
||||
def test_stalled_recording(self):
|
||||
rec = mock.Mock(sets_written=mock.Mock(return_value=12))
|
||||
fake = mock.Mock(_recorder=rec, dry_run=False, _rec_watch=None)
|
||||
session.Session._watch_recording(fake, 100.0)
|
||||
session.Session._watch_recording(fake, 100.0 + session.STALL_S - 0.5) # not yet
|
||||
with self.assertRaises(session._CamerasLost) as cm:
|
||||
session.Session._watch_recording(fake, 100.0 + session.STALL_S + 0.5)
|
||||
self.assertIn("no new frames", str(cm.exception))
|
||||
rec.sets_written.return_value = 0 # not started writing yet: the first-set wait covers that
|
||||
fake._rec_watch = None
|
||||
session.Session._watch_recording(fake, 200.0)
|
||||
session.Session._watch_recording(fake, 200.0 + 2 * session.STALL_S)
|
||||
rec.sets_written.side_effect = [20, 21] # writing: fine however long
|
||||
session.Session._watch_recording(fake, 300.0)
|
||||
session.Session._watch_recording(fake, 300.0 + 2 * session.STALL_S)
|
||||
|
||||
def test_sets_written(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
rec = mock.Mock(dir=d)
|
||||
self.assertEqual(session.Recorder.sets_written(rec), 0)
|
||||
one = struct.pack("<8sII", b"FHSET01", 0, 16)
|
||||
with open(os.path.join(d, "sets.bin"), "wb") as f:
|
||||
f.write(one * 5)
|
||||
self.assertEqual(session.Recorder.sets_written(rec), 5)
|
||||
|
||||
|
||||
class QuietHandsTest(SessionBase):
|
||||
"""Frametop's drawn hands and hand pointer are paused for a session and started again after,
|
||||
also when an earlier session was killed and left them paused."""
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.path = os.path.join(self.tmp, "run", session.PAUSED_UNITS_FILE)
|
||||
self.calls = []
|
||||
|
||||
def systemctl(self):
|
||||
calls = self.calls
|
||||
|
||||
def run(cmd, **kw):
|
||||
if "systemctl" in cmd:
|
||||
calls.append(cmd[-2:])
|
||||
return mock.Mock(returncode=0, stdout="", stderr="")
|
||||
return mock.patch.object(session.subprocess, "run", run)
|
||||
|
||||
def test_pauses_only_running_units_and_resumes_them(self):
|
||||
active = {"frametop-handview.service": True, "frametop-pointer.service": False}
|
||||
with mock.patch.object(session, "unit_active", lambda u: active[u]), \
|
||||
mock.patch.object(session, "stop_unit", lambda u: self.calls.append(["stop", u])):
|
||||
paused = session.pause_units(session.QUIET_UNITS, self.path)
|
||||
self.assertEqual(paused, ["frametop-handview.service"])
|
||||
self.assertEqual(self.calls, [["stop", "frametop-handview.service"]])
|
||||
with open(self.path) as f:
|
||||
self.assertEqual(json.load(f), paused)
|
||||
with self.systemctl():
|
||||
self.assertEqual(session.resume_units(self.path), paused)
|
||||
self.assertEqual(self.calls[1:], [["start", "frametop-handview.service"]])
|
||||
self.assertFalse(os.path.exists(self.path))
|
||||
|
||||
def test_nothing_running_nothing_paused(self):
|
||||
with mock.patch.object(session, "unit_active", lambda u: False):
|
||||
self.assertEqual(session.pause_units(session.QUIET_UNITS, self.path), [])
|
||||
self.assertFalse(os.path.exists(self.path))
|
||||
self.assertEqual(session.resume_units(self.path), [])
|
||||
|
||||
def test_a_session_starts_what_a_killed_one_left_paused(self):
|
||||
os.makedirs(os.path.dirname(self.path))
|
||||
with open(self.path, "w") as f:
|
||||
json.dump(["frametop-pointer.service", "rm -rf"], f)
|
||||
s = self.session(next_after=0.0, hands_dir=os.path.dirname(self.path))
|
||||
s.quiet_units = session.QUIET_UNITS
|
||||
with self.systemctl():
|
||||
s.start()
|
||||
s.join(20)
|
||||
self.assertEqual(s.state, "done")
|
||||
self.assertEqual(self.calls, [["start", "frametop-pointer.service"]]) # not the junk entry
|
||||
self.assertFalse(os.path.exists(self.path))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -91,6 +91,29 @@ class RulesTest(unittest.TestCase):
|
||||
finally:
|
||||
shutil.rmtree(d)
|
||||
|
||||
def test_read_live_forced(self):
|
||||
"""HANDS_SWAP_SIDES=0 forced and the hands disagree: the hands are the truth, whether
|
||||
ft-hands published them (built after 2026-10-06) or kept the forced value (before)."""
|
||||
d = tempfile.mkdtemp()
|
||||
try:
|
||||
path = os.path.join(d, "sides.json")
|
||||
|
||||
def live(**kw):
|
||||
s = dict(pid=1, ring_ino=0, mode="0", names_swapped=False,
|
||||
updated_ns=time.clock_gettime_ns(time.CLOCK_MONOTONIC), **kw)
|
||||
with open(path, "w") as f:
|
||||
json.dump(s, f)
|
||||
return sides.read_live(path)
|
||||
|
||||
self.assertEqual(live(state="forced", swapped=False, decided_by="config")["swapped"], False)
|
||||
self.assertEqual(live(state="forced, agrees", swapped=False, decided_by="config")["swapped"], False)
|
||||
old = live(state="forced, disagrees", swapped=False, decided_by="config")
|
||||
self.assertEqual((old["swapped"], old["decided_by"]), (True, "auto"))
|
||||
new = live(state="forced, disagrees", swapped=True, decided_by="auto")
|
||||
self.assertEqual((new["swapped"], new["decided_by"]), (True, "auto"))
|
||||
finally:
|
||||
shutil.rmtree(d)
|
||||
|
||||
|
||||
class TakesTest(unittest.TestCase):
|
||||
"""A swapped session: one take's parts recorded before the decision (ft-camd's names) and
|
||||
@@ -226,6 +249,22 @@ class SessionSidesTest(unittest.TestCase):
|
||||
self.assertTrue(s._session_json["sides"]["reversed_from"]["swapped"])
|
||||
self.assertFalse(takes.read_json(os.path.join(self.tmp, "session.json"))["sides"]["swapped"])
|
||||
|
||||
def test_read_sides_forced(self):
|
||||
"""PR #4 on the dataset: HANDS_SWAP_SIDES=0 from the old example config, and the hands
|
||||
disagree. The session takes the hands' answer, not the forced one."""
|
||||
s = session.Session(os.path.join(self.tmp, "base"), {}, {}, "room", self.script, dry_run=True,
|
||||
hands_dir=self.tmp)
|
||||
s.session_dir = self.tmp
|
||||
s._session_json = {"sides": {"swapped": None}}
|
||||
self.live(mode="0", state="forced", swapped=False, decided_by="config", names_swapped=False, evidence=None)
|
||||
s._read_sides(force=True)
|
||||
self.assertIs(s._sides_swapped(), False)
|
||||
self.live(mode="0", state="forced, disagrees", swapped=False, decided_by="config", names_swapped=False)
|
||||
s._read_sides(force=True)
|
||||
self.assertIs(s._sides_swapped(), True)
|
||||
self.assertEqual(s._session_json["sides"]["decided_by"], "auto")
|
||||
self.assertEqual(s._session_json["sides"]["reversed_from"]["decided_by"], "config")
|
||||
|
||||
def test_recorder_parts(self):
|
||||
calls = []
|
||||
|
||||
|
||||
+47
-15
@@ -1,21 +1,30 @@
|
||||
#!/usr/bin/env bash
|
||||
# Install, start, stop, or inspect hand tracking on the Frame: ft-camd (the camera broker) and
|
||||
# ft-hands (the tracker), user services that stop with SteamVR. They don't start with it:
|
||||
# ft-handsctl on|off (on the Frame) or hands/run.sh start|stop.
|
||||
# Usage: hands/run.sh install|uninstall
|
||||
# ft-hands (the tracker), user services that stop with SteamVR. HANDS_MODE in frametop.conf says
|
||||
# when they start (hands/handsmode.py: with the Frametop desktop, with SteamVR, or off, the
|
||||
# default); ft-handsctl on|off (on the Frame) or hands/run.sh start|stop do it by hand.
|
||||
# Usage: hands/run.sh install|uninstall # install applies HANDS_MODE
|
||||
# hands/run.sh caps # give ft-camd its capabilities again (a rebuild clears them)
|
||||
# hands/run.sh uncaps # take them back, unless the Hand Recorder or the services use them
|
||||
# hands/run.sh start|stop|restart|status|log [lines]
|
||||
# install and caps need the password (sudo setcap, once per build of ft-camd): it's asked in
|
||||
# the terminal, on the Frame or from a PC (frame_sudo in scripts/_env.sh, which also takes it
|
||||
# from the repo's .env).
|
||||
# install and caps need the password (sudo setcap, once per build of ft-camd), and so do
|
||||
# uninstall and uncaps when they take the capabilities back. It's asked in the terminal, on the
|
||||
# Frame or from a PC (frame_sudo in scripts/_env.sh, which also takes it from the repo's .env).
|
||||
set -euo pipefail
|
||||
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
|
||||
. "$root/scripts/_env.sh"
|
||||
frame="$root/scripts/frame.sh"
|
||||
units="frametop-camd.service frametop-hands.service"
|
||||
units="frametop-camd.service frametop-hands.service frametop-handview.service"
|
||||
# ft-handview (the hands drawn with Room View off) is screens/' build (screens/build.sh, which
|
||||
# the desktop's install runs); its unit sits there too.
|
||||
unit_dir() { [ "$1" = frametop-handview.service ] && echo screens || echo hands; }
|
||||
# pidfd_getfd on XRService (ptrace_scope=1), system-wide tracepoints, and their root-only
|
||||
# format files. ft-camd drops them all once it has set up.
|
||||
caps=cap_sys_ptrace,cap_perfmon,cap_dac_read_search+ep
|
||||
# Installed, two things use ft-camd's capabilities: the Hand Recorder (hands/rec/install.sh: its
|
||||
# menu entry) and the services. ft-cutouts uses them too, but installs nothing.
|
||||
handrec_entry='~/.local/share/applications/frametop-handrec.desktop'
|
||||
camd_unit='~/.config/systemd/user/frametop-camd.service'
|
||||
|
||||
sudo_run() { frame_sudo "$1"; }
|
||||
|
||||
@@ -29,6 +38,22 @@ set_caps() { # only when missing: a rebuild clears them, a reinstall doesn't
|
||||
sudo_run "setcap $caps $bin && getcap $bin"
|
||||
}
|
||||
|
||||
# A left-over binary shouldn't keep its read-any-file powers, but while the Hand Recorder or
|
||||
# the services are installed, they still need them. Best effort: without the password it warns.
|
||||
drop_caps() {
|
||||
local bin who
|
||||
bin=$(printf %q "$FRAME_REPO/hands/build/ft-camd")
|
||||
who=$(on_frame "if ! { [ -x $bin ] && getcap $bin | grep -q cap_sys_ptrace; }; then echo none
|
||||
elif [ -e $handrec_entry ]; then echo recorder
|
||||
elif [ -e $camd_unit ]; then echo services
|
||||
else echo nobody; fi") || who=none
|
||||
case $who in
|
||||
recorder) echo "kept ft-camd's capabilities: the Hand Recorder uses them" ;;
|
||||
services) echo "kept ft-camd's capabilities: hand tracking's services use them (hands/run.sh uninstall)" ;;
|
||||
nobody) sudo_run "setcap -r $bin" || echo "warning: couldn't drop ft-camd's capabilities (no password?)" >&2 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
states="for u in $units; do echo \"\$u: \$(systemctl --user is-active \$u)\"; done"
|
||||
|
||||
case ${1:-status} in
|
||||
@@ -36,18 +61,25 @@ case ${1:-status} in
|
||||
"$root/hands/build.sh"
|
||||
set_caps
|
||||
for u in $units; do
|
||||
fill_template "$root/hands/$u" | on_frame "mkdir -p ~/.config/systemd/user && cat > ~/.config/systemd/user/$u"
|
||||
fill_template "$root/$(unit_dir $u)/$u" | on_frame "mkdir -p ~/.config/systemd/user && cat > ~/.config/systemd/user/$u"
|
||||
done
|
||||
# Installed but not started with SteamVR: ft-handsctl on|off (linked into ~/.local/bin).
|
||||
"$frame" --host "set -e; systemctl --user daemon-reload; systemctl --user disable $units 2>/dev/null || true
|
||||
# Started as HANDS_MODE says (off: not at all; Frametop Input Settings, Hands), or by hand
|
||||
# with ft-handsctl on|off (linked into ~/.local/bin).
|
||||
"$frame" --host "set -e; systemctl --user daemon-reload
|
||||
python3 $(printf %q "$FRAME_REPO/hands/handsmode.py") apply
|
||||
mkdir -p ~/.local/bin && ln -sfn $(printf %q "$FRAME_REPO/hands/ft-handsctl") ~/.local/bin/ft-handsctl
|
||||
$states; echo 'start it with: ft-handsctl on'" ;;
|
||||
caps) set_caps ;;
|
||||
uninstall) "$frame" --host "systemctl --user disable --now $units 2>/dev/null
|
||||
$states; python3 $(printf %q "$FRAME_REPO/hands/handsmode.py") status" ;;
|
||||
caps) # then what HANDS_MODE wants starts, if it couldn't without them
|
||||
set_caps
|
||||
on_frame "python3 $(printf %q "$FRAME_REPO/hands/handsmode.py") apply" ;;
|
||||
uncaps) drop_caps ;;
|
||||
uninstall)
|
||||
"$frame" --host "systemctl --user disable --now $units 2>/dev/null
|
||||
for u in $units; do rm -f ~/.config/systemd/user/\$u; done; systemctl --user daemon-reload
|
||||
[ -L ~/.local/bin/ft-handsctl ] && rm -f ~/.local/bin/ft-handsctl; echo removed" ;;
|
||||
[ -L ~/.local/bin/ft-handsctl ] && rm -f ~/.local/bin/ft-handsctl; echo removed"
|
||||
drop_caps ;; # once the units are gone, so they don't count as a user
|
||||
start|stop|restart) "$frame" --host "systemctl --user $1 $units; $states" ;;
|
||||
status) "$frame" --host "$states; journalctl --user -u frametop-hands.service --no-pager -o cat -n 4" || true ;;
|
||||
log) "$frame" --host "journalctl --user -u frametop-camd.service -u frametop-hands.service --no-pager -o short -n ${2:-30}" ;;
|
||||
*) echo "usage: $0 install|uninstall|caps|start|stop|restart|status|log [lines]" >&2; exit 2 ;;
|
||||
*) echo "usage: $0 install|uninstall|caps|uncaps|start|stop|restart|status|log [lines]" >&2; exit 2 ;;
|
||||
esac
|
||||
@@ -0,0 +1,294 @@
|
||||
// Unit tests for the flag buffer (track/flagbuf.h): the crops' geometry, the rolling window, the
|
||||
// slots running out, a flag's window and files, ghosts, a second flag while one waits, and the
|
||||
// clock completing a flag when no sets come. Made-up images and views; no models.
|
||||
// Build and run: make check (in the dev container; hands/build.sh's environment).
|
||||
#include "../track/flagbuf.h"
|
||||
|
||||
#include <json/json.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
static int failures = 0;
|
||||
#define CHECK(cond, ...) \
|
||||
do { \
|
||||
if (!(cond)) { \
|
||||
std::printf("FAIL %s:%d: ", __FILE__, __LINE__); \
|
||||
std::printf(__VA_ARGS__); \
|
||||
std::printf("\n"); \
|
||||
++failures; \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int64_t kSec = 1'000'000'000;
|
||||
|
||||
struct Img {
|
||||
int w, h;
|
||||
std::vector<uint8_t> px;
|
||||
Img(int w_, int h_) : w(w_), h(h_), px(size_t(w_) * h_) {
|
||||
for (int y = 0; y < h; ++y)
|
||||
for (int x = 0; x < w; ++x) px[size_t(y) * w + x] = uint8_t((x + 2 * y) & 255);
|
||||
}
|
||||
Image image() const { return {px.data(), w, h, w}; }
|
||||
int at(int x, int y) const { return px[size_t(y) * w + x]; }
|
||||
};
|
||||
|
||||
Seen view(const std::string &cam, int hand, double cx, double cy, double size) {
|
||||
Seen s;
|
||||
s.cam = cam, s.hand = hand;
|
||||
s.roi.center = {cx, cy}, s.roi.size = size, s.roi.rotation = 0.3;
|
||||
s.lm.presence = 0.9, s.lm.right = 0.8;
|
||||
for (int k = 0; k < 21; ++k) s.lm.pts[k] = {cx + k, cy - k};
|
||||
return s;
|
||||
}
|
||||
|
||||
bool parse(const std::string &text, Json::Value &v) {
|
||||
Json::CharReaderBuilder b;
|
||||
std::string e;
|
||||
std::istringstream in(text);
|
||||
return Json::parseFromStream(b, in, &v, &e);
|
||||
}
|
||||
|
||||
std::vector<Json::Value> lines(const std::string &path) {
|
||||
std::vector<Json::Value> out;
|
||||
std::ifstream f(path);
|
||||
std::string line;
|
||||
while (std::getline(f, line)) {
|
||||
Json::Value v;
|
||||
CHECK(parse(line, v), "%s: a line isn't JSON: %.80s", path.c_str(), line.c_str());
|
||||
out.push_back(v);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
Json::Value file_json(const std::string &path) {
|
||||
std::ifstream f(path);
|
||||
std::stringstream ss;
|
||||
ss << f.rdbuf();
|
||||
Json::Value v;
|
||||
CHECK(parse(ss.str(), v), "%s isn't JSON", path.c_str());
|
||||
return v;
|
||||
}
|
||||
|
||||
std::string temp_dir() {
|
||||
char tmpl[] = "/tmp/flagbuf-test-XXXXXX";
|
||||
const char *d = mkdtemp(tmpl);
|
||||
return d ? d : "/tmp";
|
||||
}
|
||||
|
||||
void test_crop_geometry() {
|
||||
const Img img(320, 240);
|
||||
std::vector<uint8_t> out(224 * 224);
|
||||
// native size: crop pixel (u, v) is image pixel (x0 + u, y0 + v) exactly
|
||||
CropGeom g = crop_square(img.image(), {100.5, 80.5}, 60, 224, out.data());
|
||||
CHECK(g.w == 60 && g.h == 60 && std::fabs(g.scale - 1) < 1e-9, "native crop %dx%d scale %f", g.w, g.h, g.scale);
|
||||
bool same = true;
|
||||
for (int v = 0; v < g.h; ++v)
|
||||
for (int u = 0; u < g.w; ++u) {
|
||||
const int x = int(std::lround(g.x0 + (u + 0.5) * g.scale - 0.5)), y = int(std::lround(g.y0 + (v + 0.5) * g.scale - 0.5));
|
||||
same = same && out[size_t(v) * g.w + u] == img.at(x, y);
|
||||
}
|
||||
CHECK(same, "native crop's pixels aren't the image's at the mapped place");
|
||||
// the crop's middle maps to the centre
|
||||
CHECK(std::fabs(g.x0 + (g.w / 2.0) * g.scale - 0.5 - 100.5) < 1e-9, "centre x %f", g.x0 + (g.w / 2.0) * g.scale - 0.5);
|
||||
// downscaled: at most max_px, the mapping still holds (the pattern is smooth: within a level or two)
|
||||
g = crop_square(img.image(), {160, 120}, 200, 64, out.data());
|
||||
CHECK(g.w == 64 && std::fabs(g.scale - 200.0 / 64) < 1e-9, "downscaled %d scale %f", g.w, g.scale);
|
||||
int worst = 0;
|
||||
for (int v = 0; v < g.h; ++v)
|
||||
for (int u = 0; u < g.w; ++u) {
|
||||
const double x = g.x0 + (u + 0.5) * g.scale - 0.5, y = g.y0 + (v + 0.5) * g.scale - 0.5;
|
||||
const int want = int(std::lround(x + 2 * y)) & 255, got = out[size_t(v) * g.w + u];
|
||||
if (want > 8 && want < 248) worst = std::max(worst, std::abs(want - got));
|
||||
}
|
||||
CHECK(worst <= 3, "downscaled crop off the mapping by %d levels", worst);
|
||||
// past the image's corner: 0 there, the image inside
|
||||
g = crop_square(img.image(), {2, 2}, 40, 224, out.data());
|
||||
CHECK(out[0] == 0 && out[size_t(g.h - 1) * g.w + g.w - 1] == img.at(22, 22), "corner crop: %d, %d (want 0, %d)", out[0],
|
||||
out[size_t(g.h - 1) * g.w + g.w - 1], img.at(22, 22));
|
||||
CHECK(g.x0 < 0 && g.y0 < 0, "corner crop's x0 %f y0 %f", g.x0, g.y0);
|
||||
}
|
||||
|
||||
FlagConfig small_config() {
|
||||
FlagConfig c;
|
||||
c.before_s = 1.0, c.after_s = 0.5, c.ghost_s = 0.25, c.crop_px = 32, c.scale = 1.6;
|
||||
c.max_bytes = 32 * 32 * 20; // 20 slots
|
||||
c.writer_cpus.clear();
|
||||
return c;
|
||||
}
|
||||
|
||||
void test_window_and_slots() {
|
||||
const Img img(128, 128);
|
||||
const std::map<std::string, Image> images = {{"a", img.image()}, {"b", img.image()}};
|
||||
FlagBuffer fb(small_config());
|
||||
// 10 sets a second, two views each (20 slots: 10 sets fit)
|
||||
for (int i = 0; i < 30; ++i)
|
||||
fb.add(i * kSec / 10, i * kSec / 10, i, images, {view("a", 1, 60, 60, 20), view("b", 1, 64, 50, 20)}, "\"hands\": []");
|
||||
FlagBuffer::Stats s = fb.stats();
|
||||
CHECK(s.slots == 20 && s.slots_used <= 20, "slots %zu used %zu", s.slots, s.slots_used);
|
||||
CHECK(s.dropped == 0, "nothing held, so nothing dropped: %zu", s.dropped);
|
||||
CHECK(s.crops == 60, "crops %zu", s.crops);
|
||||
// one view a set: the window (1 s), not the slots, keeps it to about 11 sets
|
||||
for (int i = 30; i < 60; ++i)
|
||||
fb.add(i * kSec / 10, i * kSec / 10, i, images, {view("a", 1, 60, 60, 20)}, "\"hands\": []");
|
||||
s = fb.stats();
|
||||
CHECK(s.slots_used >= 10 && s.slots_used <= 12, "one view a set: %zu slots in use", s.slots_used);
|
||||
}
|
||||
|
||||
void test_flag_files() {
|
||||
const Img img(128, 128);
|
||||
const std::map<std::string, Image> images = {{"a", img.image()}, {"b", img.image()}};
|
||||
FlagBuffer fb(small_config());
|
||||
fb.set_static("{\"a\": {\"width\": 128}}", "{\"models\": \"m\"}");
|
||||
const std::string root = temp_dir(), dir = root + "/flag-1";
|
||||
int i = 0;
|
||||
for (; i < 30; ++i) fb.add(i * kSec / 10, i * kSec / 10, i, images, {view("a", 1, 60, 60, 20)}, "\"hands\": []");
|
||||
CHECK(fb.flag({dir, "\"source\": \"test\", \"note\": \"fingers \\\"crossed\\\"\""}, 29 * kSec / 10), "flag refused");
|
||||
CHECK(!fb.flag({dir + "-2", ""}, 30 * kSec / 10, "again"), "a second flag while one waits was taken");
|
||||
CHECK(fb.waiting(), "not waiting");
|
||||
// two views a set now: the held sets fill the slots, so some crops drop
|
||||
for (; i < 34; ++i)
|
||||
fb.add(i * kSec / 10, i * kSec / 10, i, images, {view("a", 1, 60, 60, 20), view("b", 2, 30, 30, 20)}, "\"hands\": []");
|
||||
CHECK(fb.waiting(), "completed early (0.5 s after 2.9 s is 3.4 s; the last set is 3.3 s)");
|
||||
fb.add(i * kSec / 10, i * kSec / 10, i, images, {}, "\"hands\": []");
|
||||
++i;
|
||||
CHECK(!fb.waiting(), "not completed");
|
||||
fb.wait();
|
||||
const FlagBuffer::Stats s = fb.stats();
|
||||
CHECK(s.flags == 1 && s.last_dir == dir && s.last_error.empty(), "flags %zu dir %s error %s", s.flags, s.last_dir.c_str(),
|
||||
s.last_error.c_str());
|
||||
CHECK(s.slots_used == 0, "the written sets' slots weren't given back: %zu in use", s.slots_used);
|
||||
const Json::Value m = file_json(dir + "/manifest.json");
|
||||
CHECK(m["version"].asInt() == 1 && m["source"].asString() == "test", "manifest version/source");
|
||||
CHECK(m["note"].asString() == "fingers \"crossed\"", "note %s", m["note"].asString().c_str());
|
||||
CHECK(m["more_notes"].size() == 1 && m["more_notes"][0].asString() == "again", "more_notes");
|
||||
CHECK(m["flag_t_raw_ns"].asInt64() == 29 * kSec / 10, "flag time");
|
||||
CHECK(m["settings"]["models"].asString() == "m" && m["cameras"]["a"]["width"].asInt() == 128, "static parts");
|
||||
const std::vector<Json::Value> sets = lines(dir + "/sets.jsonl"), crops = lines(dir + "/crops.jsonl");
|
||||
// held: from 1.9 s (1 s before) to the set at 3.4 s
|
||||
CHECK(!sets.empty() && sets.front()["t_raw_ns"].asInt64() >= 19 * kSec / 10 - 1 &&
|
||||
sets.back()["t_raw_ns"].asInt64() == 34 * kSec / 10,
|
||||
"window %lld..%lld", sets.empty() ? 0LL : (long long)sets.front()["t_raw_ns"].asInt64(),
|
||||
sets.empty() ? 0LL : (long long)sets.back()["t_raw_ns"].asInt64());
|
||||
CHECK(m["counts"]["sets"].asUInt() == sets.size() && m["counts"]["crops"].asUInt() == crops.size(), "counts");
|
||||
CHECK(m["counts"]["crops_dropped"].asUInt() > 0, "held sets filling the slots should drop crops");
|
||||
// every view's crop index points at a crop line of that set and camera; the bytes add up
|
||||
size_t bytes = 0;
|
||||
for (const Json::Value &c : crops) {
|
||||
CHECK(c["offset"].asUInt64() == bytes, "crop %u offset", c["k"].asUInt());
|
||||
bytes += c["bytes"].asUInt64();
|
||||
CHECK(c["bytes"].asUInt64() == c["w"].asUInt64() * c["h"].asUInt64(), "crop bytes");
|
||||
}
|
||||
struct stat st;
|
||||
CHECK(stat((dir + "/crops.bin").c_str(), &st) == 0 && size_t(st.st_size) == bytes, "crops.bin size");
|
||||
for (const Json::Value &set : sets)
|
||||
for (const Json::Value &v : set["views"]) {
|
||||
const int k = v["crop"].asInt();
|
||||
if (k < 0) continue;
|
||||
CHECK(k < int(crops.size()) && crops[size_t(k)]["set"].asInt() == set["i"].asInt() &&
|
||||
crops[size_t(k)]["cam"].asString() == v["cam"].asString(),
|
||||
"view crop %d", k);
|
||||
CHECK(v["lm"].size() == 21 && v["roi"].size() == 4, "view landmarks");
|
||||
}
|
||||
// the first crop's pixels are the image's where the mapping says
|
||||
if (!crops.empty()) {
|
||||
std::ifstream f(dir + "/crops.bin", std::ios::binary);
|
||||
std::vector<uint8_t> px(crops[0]["bytes"].asUInt64());
|
||||
f.read(reinterpret_cast<char *>(px.data()), std::streamsize(px.size()));
|
||||
const double x0 = crops[0]["x0"].asDouble(), y0 = crops[0]["y0"].asDouble(), sc = crops[0]["scale"].asDouble();
|
||||
const int w = crops[0]["w"].asInt(), u = w / 2, v = w / 3;
|
||||
const int x = int(std::lround(x0 + (u + 0.5) * sc - 0.5)), y = int(std::lround(y0 + (v + 0.5) * sc - 0.5));
|
||||
CHECK(std::abs(int(px[size_t(v) * w + u]) - img.at(x, y)) <= 3, "crop pixel %d vs image %d", px[size_t(v) * w + u], img.at(x, y));
|
||||
}
|
||||
std::system(("rm -rf " + root).c_str());
|
||||
}
|
||||
|
||||
void test_ghosts() {
|
||||
const Img img(128, 128);
|
||||
const std::map<std::string, Image> images = {{"a", img.image()}};
|
||||
FlagConfig c = small_config();
|
||||
c.after_s = 0.05;
|
||||
FlagBuffer fb(c);
|
||||
const std::string root = temp_dir(), dir = root + "/flag-g";
|
||||
fb.add(0, 0, 0, images, {view("a", 7, 60, 60, 20)}, "");
|
||||
for (int i = 1; i <= 5; ++i) fb.add(i * kSec / 10, i * kSec / 10, i, images, {}, "");
|
||||
CHECK(fb.stats().ghosts == 2, "ghosts within 0.25 s: %zu (want 2: at 0.1 and 0.2 s)", fb.stats().ghosts);
|
||||
fb.flag({dir, ""}, 5 * kSec / 10);
|
||||
fb.add(6 * kSec / 10, 6 * kSec / 10, 6, images, {}, "");
|
||||
fb.wait();
|
||||
const std::vector<Json::Value> sets = lines(dir + "/sets.jsonl"), crops = lines(dir + "/crops.jsonl");
|
||||
int ghost_lines = 0;
|
||||
for (const Json::Value &s : sets) ghost_lines += int(s["ghosts"].size());
|
||||
CHECK(ghost_lines == 2 && crops.size() == 3, "ghost lines %d crops %zu", ghost_lines, crops.size());
|
||||
if (crops.size() == 3) CHECK(!crops[0]["ghost"].asBool() && crops[1]["ghost"].asBool() && crops[1]["hand"].asInt() == 7, "ghost crop");
|
||||
std::system(("rm -rf " + root).c_str());
|
||||
}
|
||||
|
||||
void test_tick() {
|
||||
const Img img(64, 64);
|
||||
FlagBuffer fb(small_config());
|
||||
const std::string root = temp_dir(), dir = root + "/flag-t";
|
||||
fb.add(0, 0, 0, {{"a", img.image()}}, {view("a", 1, 30, 30, 10)}, "");
|
||||
fb.flag({dir, ""}, 0);
|
||||
fb.tick(kSec / 2); // 0.5 s: not yet (after_s + 0.5)
|
||||
CHECK(fb.waiting(), "ticked too early");
|
||||
fb.tick(kSec + 1);
|
||||
CHECK(!fb.waiting(), "tick didn't complete it");
|
||||
fb.wait();
|
||||
CHECK(file_json(dir + "/manifest.json")["counts"]["sets"].asInt() == 1, "tick flag sets");
|
||||
// a folder it can't make: reported, the slots still come back
|
||||
FlagBuffer fb2(small_config());
|
||||
fb2.add(0, 0, 0, {{"a", img.image()}}, {view("a", 1, 30, 30, 10)}, "");
|
||||
fb2.flag({root + "/missing/deeper", ""}, 0);
|
||||
fb2.finish();
|
||||
fb2.wait();
|
||||
CHECK(!fb2.stats().last_error.empty() && fb2.stats().slots_used == 0, "bad folder: error '%s', %zu slots",
|
||||
fb2.stats().last_error.c_str(), fb2.stats().slots_used);
|
||||
std::system(("rm -rf " + root).c_str());
|
||||
}
|
||||
|
||||
// Not a check: what a crop costs here, a hand at arm's length in a 1056 x 1024 camera (a 375 px crop,
|
||||
// so a 600 px square) down to 224 and 288, and a small one copied as it is.
|
||||
void bench() {
|
||||
const Img img(1056, 1024);
|
||||
std::vector<uint8_t> out(512 * 512);
|
||||
for (int px : {224, 288}) {
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
for (int i = 0; i < 300; ++i) crop_square(img.image(), {500.0 + i % 7, 480}, 600, px, out.data());
|
||||
const double us = std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count() / 300;
|
||||
std::printf("flagbuf_test: a 600 px square to %d px: %.0f us a crop\n", px, us);
|
||||
}
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
for (int i = 0; i < 300; ++i) crop_square(img.image(), {500.0 + i % 7, 480}, 200, 224, out.data());
|
||||
std::printf("flagbuf_test: a 200 px square as it is: %.0f us a crop\n",
|
||||
std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count() / 300);
|
||||
}
|
||||
|
||||
void test_json_string() {
|
||||
CHECK(json_string("a\"b\\c\nd") == "\"a\\\"b\\\\c\\nd\"", "%s", json_string("a\"b\\c\nd").c_str());
|
||||
CHECK(json_string("", true) == "null" && json_string("") == "\"\"", "empty");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
test_crop_geometry();
|
||||
test_window_and_slots();
|
||||
test_flag_files();
|
||||
test_ghosts();
|
||||
test_tick();
|
||||
test_json_string();
|
||||
bench();
|
||||
std::printf("flagbuf_test: %s (%d failures)\n", failures ? "FAILED" : "ok", failures);
|
||||
return failures ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
// Unit tests for the pinch and grip detectors' hold on a drag (track/pinch.h: PinchParams' drag_*
|
||||
// and grip_takeover_s), the dip rule (PinchParams::dip) and the fist guard (fist_curl): made-up hands
|
||||
// at 30 Hz, the distances from their points (no views).
|
||||
// Build and run: make check (in the dev container; hands/build.sh's environment).
|
||||
#include "../track/pinch.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
|
||||
static int failures = 0;
|
||||
#define CHECK(cond, ...) \
|
||||
do { \
|
||||
if (!(cond)) { \
|
||||
std::printf("FAIL %s:%d: ", __FILE__, __LINE__); \
|
||||
std::printf(__VA_ARGS__); \
|
||||
std::printf("\n"); \
|
||||
++failures; \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int64_t kFrame = 33'333'333;
|
||||
|
||||
// A right hand 0.4 m ahead (moved by shift), the thumb tip d from the index tip, the other fingers
|
||||
// open (curl 2) or closed around (fist: curl 0.85); middle_gap > 0 puts the middle tip that far
|
||||
// from the thumb tip (a hand closing into a grab). curled: the fingers closed (bit 0 index .. 3 little)
|
||||
// when not a fist.
|
||||
Hand MakeHand(double d, bool fist = false, V3 shift = {0, 0, 0}, double middle_gap = 0, int curled = 0) {
|
||||
Hand h;
|
||||
h.id = 1, h.side = 1, h.frames = 30, h.has_pts = true;
|
||||
const V3 wrist = V3{0, -0.1, -0.35} + shift;
|
||||
auto at = [&](double x, double y, double z) { return V3{wrist[0] + x, wrist[1] + y, wrist[2] + z}; };
|
||||
const double knuckle = 0.08;
|
||||
h.pts[0] = at(0, 0, 0);
|
||||
for (int f = 0; f < 4; ++f) {
|
||||
const double x = -0.02 + 0.015 * f, tip = fist || (curled >> f & 1) ? 0.068 : 0.16;
|
||||
h.pts[5 + 4 * f] = at(x, 0, -knuckle);
|
||||
h.pts[6 + 4 * f] = at(x, 0, -knuckle - 0.02);
|
||||
h.pts[7 + 4 * f] = at(x, 0, -knuckle - 0.04);
|
||||
h.pts[8 + 4 * f] = at(x, 0, -tip);
|
||||
}
|
||||
// the thumb: its tip d from the index tip, beside it
|
||||
h.pts[1] = at(-0.03, 0, -0.02), h.pts[2] = at(-0.04, 0, -0.04), h.pts[3] = at(-0.045, 0, -0.06);
|
||||
const V3 index = h.pts[8];
|
||||
h.pts[4] = {index[0] - d, index[1], index[2]};
|
||||
if (middle_gap > 0) h.pts[12] = {h.pts[4][0], h.pts[4][1] + middle_gap, h.pts[4][2]};
|
||||
for (int i = 0; i < 21; ++i) h.smooth[i] = h.pts[i];
|
||||
return h;
|
||||
}
|
||||
|
||||
struct Run {
|
||||
Pinch pinch;
|
||||
Grip grip;
|
||||
int64_t t = 1'000'000'000;
|
||||
int ends = 0, lost = 0;
|
||||
int begins = 0;
|
||||
V3 shift{0, 0, 0}, velocity{0, 0, 0}; // the hand's offset and its motion, m/s
|
||||
double middle_gap = 0;
|
||||
int curled = 0;
|
||||
void Step(double d, bool fist = false) {
|
||||
Hand h = MakeHand(d, fist, shift, middle_gap, curled);
|
||||
shift = shift + velocity * (kFrame / 1e9);
|
||||
const std::vector<const Hand *> hands{&h};
|
||||
grip.update(hands, {}, t, pinch.holding(t));
|
||||
pinch.update(hands, {}, t, grip.gripping());
|
||||
for (const Pinch::Event &e : pinch.events) {
|
||||
begins += std::string(e.what) == "begin";
|
||||
ends += std::string(e.what) != "begin";
|
||||
lost += std::string(e.what) == "lost";
|
||||
}
|
||||
t += kFrame;
|
||||
}
|
||||
bool down() const { return pinch.side(1).flags & FH_PINCH_DOWN; }
|
||||
};
|
||||
|
||||
PinchParams Params() {
|
||||
PinchParams p;
|
||||
p.other_finger = 12; // as ft-hands
|
||||
return p;
|
||||
}
|
||||
|
||||
void TestDragSpike() {
|
||||
// a drag (held 1 s): the tips read 3.8 cm for two frames (a hidden thumb), then close again
|
||||
Run r{Pinch(Params()), Grip()};
|
||||
for (int k = 0; k < 5; ++k) r.Step(0.06);
|
||||
for (int k = 0; k < 30; ++k) r.Step(0.01);
|
||||
CHECK(r.down(), "the pinch is down");
|
||||
r.Step(0.038), r.Step(0.038), r.Step(0.01);
|
||||
CHECK(r.down() && r.ends == 0, "a two-frame spike to 3.8 cm doesn't drop a drag");
|
||||
// loosened a little and staying there: it ends after drag_open_s (0.12 s: four frames)
|
||||
int frames = 0;
|
||||
while (r.down() && frames < 20) r.Step(0.04), ++frames;
|
||||
CHECK(!r.down() && frames >= 4 && frames <= 5 && r.lost == 0, "loosened to 4 cm: ended after %d frames", frames);
|
||||
// fingers hovering 3.3-3.8 cm apart (a relaxed hand) end it too: the dips under 3.5 cm aren't
|
||||
// a close
|
||||
Run h{Pinch(Params()), Grip()};
|
||||
for (int k = 0; k < 5; ++k) h.Step(0.06);
|
||||
for (int k = 0; k < 30; ++k) h.Step(0.01);
|
||||
frames = 0;
|
||||
while (h.down() && frames < 30) h.Step(frames % 2 ? 0.033 : 0.038), ++frames;
|
||||
CHECK(!h.down() && frames <= 6, "hovering 3.3-3.8 cm apart: ended after %d frames", frames);
|
||||
// a real release: the tips 6 cm apart end it after end_frames (2), as before
|
||||
Run q{Pinch(Params()), Grip()};
|
||||
for (int k = 0; k < 5; ++k) q.Step(0.06);
|
||||
for (int k = 0; k < 30; ++k) q.Step(0.01);
|
||||
q.Step(0.06);
|
||||
CHECK(q.down(), "one frame open: still down");
|
||||
q.Step(0.07);
|
||||
CHECK(!q.down() && q.lost == 0, "a release to 6-7 cm ends it on the second frame");
|
||||
}
|
||||
|
||||
void TestTapUnchanged() {
|
||||
// a tap (0.1 s): ends after two frames past 3.5 cm, wherever they are
|
||||
Run r{Pinch(Params()), Grip()};
|
||||
for (int k = 0; k < 5; ++k) r.Step(0.06);
|
||||
for (int k = 0; k < 3; ++k) r.Step(0.01);
|
||||
r.Step(0.038);
|
||||
CHECK(r.down(), "a tap's first frame open");
|
||||
r.Step(0.038);
|
||||
CHECK(!r.down(), "a tap ends on the second frame past 3.5 cm");
|
||||
}
|
||||
|
||||
void TestGripTakeover() {
|
||||
// closing the hand passes through a pinch: a grip within 0.3 s takes it (ends it, as lost)
|
||||
Run a{Pinch(Params()), Grip()};
|
||||
for (int k = 0; k < 10; ++k) a.Step(0.06);
|
||||
a.Step(0.015);
|
||||
CHECK(a.down(), "the pinch began");
|
||||
for (int k = 0; k < 4 && a.down(); ++k) a.Step(0.032, true);
|
||||
CHECK(!a.down() && a.lost == 1, "a grip right after the pinch took it (lost %d)", a.lost);
|
||||
// a drag held 1 s, the other fingers curling around it: no grip, and the pinch stays
|
||||
Run b{Pinch(Params()), Grip()};
|
||||
for (int k = 0; k < 10; ++k) b.Step(0.06);
|
||||
for (int k = 0; k < 30; ++k) b.Step(0.015);
|
||||
for (int k = 0; k < 15; ++k) b.Step(0.032, true);
|
||||
CHECK(b.down() && b.ends == 0, "a held pinch survives the hand closing around it");
|
||||
CHECK(!(b.grip.side(1).flags & FH_PINCH_DOWN), "and no grip begins on it");
|
||||
}
|
||||
|
||||
PinchParams DipParams() {
|
||||
PinchParams p = Params();
|
||||
p.dip = true;
|
||||
return p;
|
||||
}
|
||||
|
||||
// open, a quick dip to `low` (two frames) and back open
|
||||
void QuickDip(Run &r, double low) {
|
||||
for (int k = 0; k < 10; ++k) r.Step(0.06);
|
||||
r.Step(0.045), r.Step(low), r.Step(low + 0.001), r.Step(0.045), r.Step(0.06), r.Step(0.06);
|
||||
}
|
||||
|
||||
void TestDip() {
|
||||
// a quick tap that reads 2.8 cm at contact: no pinch without the dip rule, a click with it
|
||||
Run off{Pinch(Params()), Grip()};
|
||||
QuickDip(off, 0.028);
|
||||
CHECK(off.begins == 0, "without the dip rule a 2.8 cm dip is no pinch (%d)", off.begins);
|
||||
Run on{Pinch(DipParams()), Grip()};
|
||||
QuickDip(on, 0.028);
|
||||
CHECK(on.begins == 1 && on.ends == 1 && on.lost == 0 && !on.down(), "a 2.8 cm dip clicks once (%d begins, %d ends)",
|
||||
on.begins, on.ends);
|
||||
CHECK(on.pinch.dip_begins[1] == 1, "counted as a dip");
|
||||
// too shallow: 6 to 3.5 cm (over dip_max_m)
|
||||
Run shallow{Pinch(DipParams()), Grip()};
|
||||
QuickDip(shallow, 0.035);
|
||||
CHECK(shallow.begins == 0, "a dip to 3.5 cm isn't a tap");
|
||||
// closing slowly (1 mm a frame) to 2.8 cm and staying: not a dip
|
||||
Run slow{Pinch(DipParams()), Grip()};
|
||||
for (int k = 0; k < 10; ++k) slow.Step(0.06);
|
||||
for (double d = 0.06; d > 0.028; d -= 0.001) slow.Step(d);
|
||||
for (int k = 0; k < 10; ++k) slow.Step(0.028);
|
||||
CHECK(slow.begins == 0, "a slow close to 2.8 cm isn't a tap (%d)", slow.begins);
|
||||
// the same quick dip while the hand moves at 0.5 m/s: no tap
|
||||
Run moving{Pinch(DipParams()), Grip()};
|
||||
moving.velocity = {0.5, 0, 0};
|
||||
QuickDip(moving, 0.028);
|
||||
CHECK(moving.begins == 0, "a dip while the hand moves fast isn't a tap (%d)", moving.begins);
|
||||
// the middle fingertip coming in with the thumb (a hand closing into a grab): no tap
|
||||
Run grab{Pinch(DipParams()), Grip()};
|
||||
for (int k = 0; k < 10; ++k) grab.Step(0.06);
|
||||
grab.middle_gap = 0.03;
|
||||
grab.Step(0.045), grab.Step(0.028), grab.Step(0.028);
|
||||
CHECK(grab.begins == 0, "a dip with the middle tip 3 cm from the thumb isn't a tap (%d)", grab.begins);
|
||||
// a dip that goes on to contact is an ordinary pinch: held 1 s, a two-frame spike doesn't end it
|
||||
Run hold{Pinch(DipParams()), Grip()};
|
||||
for (int k = 0; k < 10; ++k) hold.Step(0.06);
|
||||
hold.Step(0.045), hold.Step(0.028);
|
||||
CHECK(hold.down(), "the dip began it");
|
||||
for (int k = 0; k < 30; ++k) hold.Step(0.01);
|
||||
hold.Step(0.038), hold.Step(0.038), hold.Step(0.01);
|
||||
CHECK(hold.down() && hold.ends == 0, "after contact it holds like any drag");
|
||||
// a dip held without contact ends once the tips spring back dip_rebound_m (6 mm) over its low
|
||||
Run spring{Pinch(DipParams()), Grip()};
|
||||
for (int k = 0; k < 10; ++k) spring.Step(0.06);
|
||||
spring.Step(0.045), spring.Step(0.026);
|
||||
for (int k = 0; k < 10; ++k) spring.Step(0.027);
|
||||
CHECK(spring.down(), "held at 2.7 cm: still down");
|
||||
spring.Step(0.033);
|
||||
CHECK(spring.down(), "one frame 7 mm over the low: still down");
|
||||
spring.Step(0.033);
|
||||
CHECK(!spring.down() && spring.lost == 0, "two frames 7 mm over the low: released, under end_m");
|
||||
// two taps in a row click twice; one held low after its release doesn't click again: a new dip
|
||||
// needs the hand open again since the release
|
||||
Run twice{Pinch(DipParams()), Grip()};
|
||||
QuickDip(twice, 0.028);
|
||||
QuickDip(twice, 0.028);
|
||||
CHECK(twice.begins == 2, "two dips, two clicks (%d)", twice.begins);
|
||||
Run settle{Pinch(DipParams()), Grip()};
|
||||
for (int k = 0; k < 10; ++k) settle.Step(0.06);
|
||||
settle.Step(0.045), settle.Step(0.026), settle.Step(0.033), settle.Step(0.033); // released at 3.3 cm
|
||||
for (int k = 0; k < 10; ++k) settle.Step(k % 2 ? 0.033 : 0.028);
|
||||
CHECK(settle.begins == 1 && !settle.down(), "jitter at 2.8-3.3 cm after a dip's release: no second click (%d)",
|
||||
settle.begins);
|
||||
}
|
||||
|
||||
void TestFistGuard() {
|
||||
// a fist with the thumb tip 1.5 cm from the curled index tip: no pinch, counted as held back
|
||||
Run fist{Pinch(Params()), Grip()};
|
||||
for (int k = 0; k < 10; ++k) fist.Step(0.06);
|
||||
for (int k = 0; k < 15; ++k) fist.Step(0.015, true);
|
||||
CHECK(fist.begins == 0 && fist.pinch.fist_held[1] == 1, "a fist isn't a pinch (%d begins)", fist.begins);
|
||||
// its curls flickering open for a frame, the thumb still on the index: still no pinch
|
||||
fist.Step(0.015), fist.Step(0.015, true);
|
||||
CHECK(fist.begins == 0, "a fist's curls flickering open don't begin a pinch (%d)", fist.begins);
|
||||
// the hand opens (the tips past end_m), then pinches: it begins
|
||||
fist.Step(0.06), fist.Step(0.015), fist.Step(0.015);
|
||||
CHECK(fist.begins == 1, "a pinch once the fist opened (%d)", fist.begins);
|
||||
// the index and middle curled, ring and little open: still a fist for the guard
|
||||
Run two{Pinch(Params()), Grip()};
|
||||
two.curled = 0b0011;
|
||||
for (int k = 0; k < 15; ++k) two.Step(0.015);
|
||||
CHECK(two.begins == 0, "index and middle curled: no pinch (%d)", two.begins);
|
||||
// ring and little curled (a pinch with the other fingers tucked in), or the index alone: a pinch
|
||||
Run tucked{Pinch(Params()), Grip()};
|
||||
tucked.curled = 0b1100;
|
||||
for (int k = 0; k < 5; ++k) tucked.Step(0.015);
|
||||
CHECK(tucked.begins == 1, "ring and little curled: a pinch (%d)", tucked.begins);
|
||||
Run index{Pinch(Params()), Grip()};
|
||||
index.curled = 0b0001;
|
||||
for (int k = 0; k < 5; ++k) index.Step(0.015);
|
||||
CHECK(index.begins == 1, "the index alone curled: a pinch (%d)", index.begins);
|
||||
// a pinch already down carries on while the index and middle curl around it
|
||||
Run held{Pinch(Params()), Grip()};
|
||||
for (int k = 0; k < 10; ++k) held.Step(0.015);
|
||||
held.curled = 0b0011;
|
||||
for (int k = 0; k < 15; ++k) held.Step(0.015);
|
||||
CHECK(held.down() && held.ends == 0, "a pinch down survives its fingers curling");
|
||||
// the fist opening with the fingers apart, then a pinch: it begins
|
||||
held.curled = 0;
|
||||
held.Step(0.06), held.Step(0.06);
|
||||
for (int k = 0; k < 3; ++k) held.Step(0.015);
|
||||
CHECK(held.begins == 2, "a pinch after the fist opened (%d)", held.begins);
|
||||
// fist_curl 0: the guard off, a fist with the thumb on the index pinches as before
|
||||
PinchParams off = Params();
|
||||
off.fist_curl = 0;
|
||||
Run old{Pinch(off), Grip()};
|
||||
for (int k = 0; k < 5; ++k) old.Step(0.015, true);
|
||||
CHECK(old.begins == 1, "guard off: the fist pinches (%d)", old.begins);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
TestDragSpike();
|
||||
TestTapUnchanged();
|
||||
TestGripTakeover();
|
||||
TestDip();
|
||||
TestFistGuard();
|
||||
if (failures) {
|
||||
std::printf("%d failures\n", failures);
|
||||
return 1;
|
||||
}
|
||||
std::printf("pinch-test: ok\n");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
// Unit tests for the skeleton fit (track/skeleton.h) on made-up hands: poses within the
|
||||
// joint limits are posed with the forward kinematics, noise is added, and the fit has to give
|
||||
// them back. No models, no recordings. make check (in the dev container) builds and runs it.
|
||||
#include "../track/skeleton.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <random>
|
||||
|
||||
using namespace skel;
|
||||
|
||||
namespace {
|
||||
|
||||
int failures = 0;
|
||||
#define CHECK(c) \
|
||||
do { \
|
||||
if (!(c)) std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c), ++failures; \
|
||||
} while (0)
|
||||
|
||||
double lo_hi(std::mt19937 &rng, double lo, double hi) { return std::uniform_real_distribution<double>(lo, hi)(rng); }
|
||||
|
||||
// A random but plausible pose: angles well inside the limits, the palm somewhere in front.
|
||||
void random_pose(std::mt19937 &rng, Rot &R, V3 &t, double q[kParams]) {
|
||||
R = exp_rot({lo_hi(rng, -1.5, 1.5), lo_hi(rng, -1.5, 1.5), lo_hi(rng, -1.5, 1.5)});
|
||||
t = {lo_hi(rng, -0.25, 0.25), lo_hi(rng, -0.4, 0.0), lo_hi(rng, -0.6, -0.25)};
|
||||
const double D = M_PI / 180;
|
||||
q[0] = lo_hi(rng, -30, 30) * D, q[1] = lo_hi(rng, -30, 30) * D, q[2] = lo_hi(rng, -15, 15) * D;
|
||||
q[3] = lo_hi(rng, -10, 10) * D, q[4] = lo_hi(rng, 0, 60) * D, q[5] = lo_hi(rng, 0, 70) * D;
|
||||
for (int f = 0; f < 4; ++f) {
|
||||
double *a = q + 6 + 5 * f;
|
||||
a[0] = lo_hi(rng, -15, 15) * D, a[1] = lo_hi(rng, -10, 80) * D, a[2] = lo_hi(rng, -8, 8) * D;
|
||||
a[3] = lo_hi(rng, 0, 90) * D, a[4] = lo_hi(rng, 0, 60) * D;
|
||||
}
|
||||
}
|
||||
|
||||
V3 cross(V3 a, V3 b) { return {a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]}; }
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
std::mt19937 rng(7);
|
||||
std::normal_distribution<double> noise(0, 1);
|
||||
const Shape s = Skeleton::canonical(1.2);
|
||||
|
||||
// rotations
|
||||
for (int i = 0; i < 100; ++i) {
|
||||
const V3 w{lo_hi(rng, -2, 2), lo_hi(rng, -2, 2), lo_hi(rng, -2, 2)};
|
||||
if (norm(w) > 3.1) continue;
|
||||
const V3 back = log_rot(exp_rot(w));
|
||||
CHECK(norm(back - w) < 1e-9);
|
||||
double q[4];
|
||||
to_quat(exp_rot(w), q);
|
||||
const double a = 2 * std::atan2(std::sqrt(q[0] * q[0] + q[1] * q[1] + q[2] * q[2]), std::fabs(q[3]));
|
||||
CHECK(std::fabs(a - norm(w)) < 1e-9);
|
||||
}
|
||||
|
||||
// the frames: right-handed, -Z along the bone, +Y the back of the hand
|
||||
{
|
||||
Rot R;
|
||||
V3 t{0, 0, -0.4}, pts[21];
|
||||
Rot fr[21];
|
||||
double q[kParams] = {};
|
||||
for (int side : {1, -1}) {
|
||||
Skeleton::pose(s, side, R, t, q, pts, fr);
|
||||
for (int i = 0; i < 21; ++i) {
|
||||
CHECK(norm(cross(fr[i].col(1), fr[i].col(2)) - fr[i].col(0)) < 1e-9);
|
||||
if (i % 4 != 0 && i < 20 && i != 0) {
|
||||
const int child = i + 1;
|
||||
CHECK(dot(unit(pts[child] - pts[i]), fr[i].col(2) * -1) > 0.999);
|
||||
}
|
||||
}
|
||||
// palm down, fingers forward (-z): the back of the hand is +y; the index knuckle is
|
||||
// on the thumb's side: -x on a right hand, +x on a left one
|
||||
CHECK(fr[0].col(1)[1] > 0.99);
|
||||
CHECK(side * pts[5][0] < 0);
|
||||
// flexing a finger moves its tip toward the palm (-y)
|
||||
double qb[kParams] = {};
|
||||
qb[6 + 3] = 1.0; // the index PIP
|
||||
V3 bent[21];
|
||||
Skeleton::pose(s, side, R, t, qb, bent, fr);
|
||||
CHECK(bent[8][1] < pts[8][1] - 0.01);
|
||||
// abduction moves the index toward the thumb
|
||||
double qa[kParams] = {};
|
||||
qa[6] = 0.3;
|
||||
Skeleton::pose(s, side, R, t, qa, bent, fr);
|
||||
CHECK(side * (bent[8][0] - pts[8][0]) < -0.005);
|
||||
}
|
||||
}
|
||||
|
||||
// fits: noise-free poses come back exactly; noisy ones close to the truth
|
||||
double sl[21], sd[21];
|
||||
for (int i = 0; i < 21; ++i) sl[i] = 0.002, sd[i] = 0.007;
|
||||
for (const double sigma : {0.0, 0.002}) {
|
||||
double worst_rms = 0, sum_err = 0, sum_raw = 0, us = 0;
|
||||
int n = 0;
|
||||
for (int trial = 0; trial < 300; ++trial) {
|
||||
const int side = trial % 2 ? 1 : -1;
|
||||
Rot R0, R;
|
||||
V3 t0, t;
|
||||
double q0[kParams] = {}, q[kParams];
|
||||
random_pose(rng, R0, t0, q0);
|
||||
V3 truth[21], meas[21], fit[21];
|
||||
Rot fr[21];
|
||||
Skeleton::pose(s, side, R0, t0, q0, truth, fr);
|
||||
// noise as stereo has it: 3.5 times as much along the line of sight
|
||||
for (int i = 0; i < 21; ++i) {
|
||||
const V3 d = unit(truth[i]), e = V3{noise(rng), noise(rng), noise(rng)} * sigma;
|
||||
meas[i] = truth[i] + e + d * (2.5 * dot(e, d));
|
||||
}
|
||||
double rms = 0;
|
||||
const auto a = std::chrono::steady_clock::now();
|
||||
const double cost = Skeleton::solve(s, side, meas, sl, sd, {0, 0, 0}, nullptr, 4, R, t, q, &rms);
|
||||
us += std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - a).count();
|
||||
CHECK(cost >= 0);
|
||||
Skeleton::pose(s, side, R, t, q, fit, fr);
|
||||
double err = 0, raw = 0;
|
||||
for (int i = 0; i < 21; ++i) err += norm(fit[i] - truth[i]) / 21, raw += norm(meas[i] - truth[i]) / 21;
|
||||
worst_rms = std::max(worst_rms, rms);
|
||||
sum_err += err, sum_raw += raw, ++n;
|
||||
}
|
||||
std::printf("noise %.1f mm (x3.5 in depth): fit rms worst %.2f mm; mean error to the truth: fitted %.2f mm, measured %.2f mm; "
|
||||
"%.1f us a fit\n", sigma * 1000, worst_rms * 1000, sum_err / n * 1000, sum_raw / n * 1000, us / n);
|
||||
if (sigma == 0) CHECK(worst_rms < 0.002);
|
||||
else CHECK(sum_err < sum_raw); // the bone lengths take noise out
|
||||
}
|
||||
|
||||
// calibration: from noisy samples of one hand, the lengths settle on it
|
||||
{
|
||||
Skeleton sk;
|
||||
const Shape truth = Skeleton::canonical(1.3);
|
||||
Fit f;
|
||||
int64_t ns = 1'000'000'000;
|
||||
for (int k = 0; k < 120; ++k, ns += 66'000'000) {
|
||||
Rot R0;
|
||||
V3 t0, pts[21];
|
||||
Rot fr[21];
|
||||
double q0[kParams] = {};
|
||||
random_pose(rng, R0, t0, q0);
|
||||
for (int a = 6; a < kAngles; ++a) q0[a] *= 0.3; // fairly open, so calibration takes it
|
||||
Skeleton::pose(truth, 1, R0, t0, q0, pts, fr);
|
||||
for (V3 &p : pts) p = p + V3{noise(rng), noise(rng), noise(rng)} * 0.0015;
|
||||
sk.update(f, pts, true, 0.95, 2, 0.0015, nullptr, {0, 0, 0}, 1.0, ns);
|
||||
CHECK(f.valid);
|
||||
}
|
||||
const Shape got = sk.shape(1, 1.0);
|
||||
double worst = 0;
|
||||
for (int b = 0; b < 20; ++b) worst = std::max(worst, std::fabs(got.len[b] - truth.len[b]));
|
||||
std::printf("calibration: settled %.2f, worst bone off %.2f mm\n", sk.calibration(1).settled(), worst * 1000);
|
||||
CHECK(sk.calibration(1).settled() >= 1);
|
||||
CHECK(worst < 0.002);
|
||||
// the left hand borrows the right's lengths until it has its own
|
||||
const Shape left = sk.shape(-1, 1.0);
|
||||
CHECK(std::fabs(left.len[5] - got.len[5]) < 1e-9);
|
||||
}
|
||||
|
||||
// the elbow: behind and below a hand held in front, 2.8 palms away
|
||||
{
|
||||
const V3 wrist{0.15, -0.25, -0.35}, knuckle{0.15, -0.22, -0.43};
|
||||
const V3 e = Skeleton::elbow(wrist, knuckle, 1, 0.23, {0, 1, 0});
|
||||
std::printf("elbow for a right hand in front: %+.3f %+.3f %+.3f\n", e[0], e[1], e[2]);
|
||||
CHECK(std::fabs(norm(e - wrist) - 0.23) < 1e-6);
|
||||
CHECK(e[1] < wrist[1] && e[2] > wrist[2]);
|
||||
}
|
||||
|
||||
std::printf(failures ? "%d FAILED\n" : "skeleton tests passed\n", failures);
|
||||
return failures ? 1 : 0;
|
||||
}
|
||||
@@ -66,6 +66,22 @@ RESUME_OK = [L("12:30:00", "[SystemdInhibitor] Received systemd resume notificat
|
||||
for i, n in enumerate((9, 13, 6, 7))] + \
|
||||
[L("12:30:02", "[DeckardCaptureSource] Streaming resumed (FPGA: VCINT, VC interleaving: enabled)")]
|
||||
EXIT = [L("13:00:00", "XRService - main thread exiting"), L("13:00:00", "Exiting XRService")]
|
||||
# The colour module unplugged while SteamVR runs (2026-10-05 12:42): XRService reopens the
|
||||
# cameras with the side pair through the ISP on vfe0 and vfe1 (NV12); VCINT stays loaded, so the
|
||||
# upper pair stays on vfe2.
|
||||
UNPLUG = [L("12:42:25", "Received passthrough camera connection event (connected=0)"),
|
||||
L("12:42:25", "[DeckardCaptureSource] Closing tracking camera interfaces camerasToUse: 1111"),
|
||||
L("12:42:26", "FPGA state check: VCINT (register value: 0x00021211)"),
|
||||
L("12:42:26", "Upper cameras FPGA interleaving support: 1 (Driver features available = 1 | VCINT loaded = 1)"),
|
||||
L("12:42:26", "[buildMediaCtlSetupTasks] ISP enabled for tracking cameras (main VFE available)"),
|
||||
L("12:42:26", "[buildMediaCtlSetupTasks] Created 4 tasks (4 tracking, 0 passthrough)")] + \
|
||||
[L("12:42:26", "TrackingCameraInit: index: %d. video device: /dev/video%d. v4l subdevice: x" % (i, n))
|
||||
for i, n in enumerate((0, 3, 6, 7))]
|
||||
# Started without the module (FrameEyeCameraFeed's layout): the upper pair on vfe3 and vfe4.
|
||||
NO_MODULE = [L("10:00:02", "[buildMediaCtlSetupTasks] ISP enabled for tracking cameras (main VFE available)"),
|
||||
L("10:00:02", "[buildMediaCtlSetupTasks] Created 4 tasks (4 tracking, 0 passthrough)")] + \
|
||||
[L("10:00:03", "TrackingCameraInit: index: %d. video device: /dev/video%d. v4l subdevice: x" % (i, n))
|
||||
for i, n in enumerate((0, 3, 9, 13))]
|
||||
|
||||
|
||||
def state(lines):
|
||||
@@ -128,6 +144,41 @@ class SyntheticLogs(unittest.TestCase):
|
||||
self.assertEqual(status, "degraded")
|
||||
self.assertEqual(reason, "only 2 of 4 tracking cameras running")
|
||||
|
||||
def test_camera_map_with_module(self):
|
||||
st = state(START + GOOD_OPEN)
|
||||
self.assertEqual(st.camera_map(), {"slam_left": 9, "slam_right": 13, "upper_left": 6, "upper_right": 7})
|
||||
|
||||
def test_camera_map_by_found_camera(self):
|
||||
"""XRService's own naming (2026-10-05's log): index 0 is slam_right, by its subdev."""
|
||||
found = [L("10:00:00", "DeckardCaptureSource: Found camera '%s': interface=msm_csiphy%d v4l_subdev=/dev/v4l-subdev%d "
|
||||
"driver=/sys/bus/i2c/drivers/%s" % f) for f in (
|
||||
("slam_left", 0, 30, "og01a1b/4-0060"), ("slam_right", 1, 31, "og01a1b/4-0036"),
|
||||
("upper_left", 0, 32, "og0ve10/5-0060"), ("upper_right", 1, 33, "og0ve10/5-003e"))]
|
||||
inits = [L("10:00:03", "TrackingCameraInit: index: %d. video device: /dev/video%d. v4l subdevice: /dev/v4l-subdev%d"
|
||||
% f) for f in ((0, 9, 31), (1, 13, 30), (2, 6, 32), (3, 7, 33))]
|
||||
st = state(START + found + GOOD_OPEN[:-4] + inits)
|
||||
self.assertEqual(st.camera_map(), {"slam_right": 9, "slam_left": 13, "upper_left": 6, "upper_right": 7})
|
||||
# without the colour module the sides are on video0 and video3, named the same way
|
||||
unplug = [L("10:30:00", "TrackingCameraInit: index: %d. video device: /dev/video%d. v4l subdevice: /dev/v4l-subdev%d"
|
||||
% f) for f in ((0, 0, 31), (1, 3, 30))]
|
||||
st = state(START + found + GOOD_OPEN[:-4] + inits + CLOSE + unplug)
|
||||
self.assertEqual(st.camera_map(), {"slam_right": 0, "slam_left": 3})
|
||||
# a new instance forgets the old one's names: back to the index order
|
||||
self.assertEqual(state(START + found + START + GOOD_OPEN).camera_map()["slam_left"], 9)
|
||||
|
||||
def test_module_unplugged(self):
|
||||
st = state(START + GOOD_OPEN + UNPLUG)
|
||||
self.assertEqual(st.verdict()[0], "ok")
|
||||
self.assertIs(st.episode["isp"], True)
|
||||
self.assertEqual(st.camera_map(), {"slam_left": 0, "slam_right": 3, "upper_left": 6, "upper_right": 7})
|
||||
self.assertEqual(st.tracking_nodes(), (0, 3, 6, 7))
|
||||
|
||||
def test_started_without_module(self):
|
||||
st = state(START + NO_MODULE)
|
||||
self.assertEqual(st.verdict()[0], "ok")
|
||||
self.assertEqual(st.camera_map(), {"slam_left": 0, "slam_right": 3, "upper_left": 9, "upper_right": 13})
|
||||
self.assertEqual(st.upper_nodes(), (9, 13))
|
||||
|
||||
def test_exited_and_empty(self):
|
||||
self.assertEqual(state(START + GOOD_OPEN + EXIT).verdict()[0], "unknown")
|
||||
self.assertEqual(state([]).verdict()[0], "unknown")
|
||||
@@ -223,9 +274,9 @@ class RealLog(unittest.TestCase):
|
||||
self.assertEqual(out.getvalue().split("\n")[0], "ok")
|
||||
|
||||
|
||||
def make_ring(path, mono_names, alive=True):
|
||||
def make_ring(path, mono_names, alive=True, nodes=None):
|
||||
"""A ring header as ft-camd writes it (camd/fhring.h), no frames."""
|
||||
cams = [(b"og01a1b", n.encode(), 9 + i) for i, n in enumerate(mono_names)]
|
||||
cams = [(b"og01a1b", n.encode(), nodes[i] if nodes else 9 + i) for i, n in enumerate(mono_names)]
|
||||
hb = time.clock_gettime_ns(time.CLOCK_MONOTONIC) if alive else 1
|
||||
data = bytearray(camcheck.RING_HDR.pack(b"FHRING01", 1, 0, len(cams), 0, 0, 4242, 0))
|
||||
struct.pack_into("<Q", data, 40, hb)
|
||||
@@ -252,12 +303,43 @@ class Ring(unittest.TestCase):
|
||||
self.assertEqual(r["status"], "degraded")
|
||||
self.assertIn("ft-camd publishes only 2 of 4", r["reason"])
|
||||
|
||||
def test_ring_missing_the_side_cameras(self):
|
||||
# an ft-camd from before NV12 support, without the colour module: only the upper pair
|
||||
with open(self.log, "w") as f:
|
||||
f.write("\n".join(START + NO_MODULE) + "\n")
|
||||
make_ring(self.ring, ["og0ve10_5-003e_video9", "og0ve10_5-0060_video13"], nodes=[9, 13])
|
||||
r = camcheck.check(log=self.log, proc=False, ring_path=self.ring)
|
||||
self.assertEqual(r["status"], "degraded")
|
||||
self.assertEqual(r["ring_missing"], [0, 3])
|
||||
self.assertIn("missing video0 video3", r["reason"])
|
||||
self.assertTrue(camcheck.is_ring_short(r))
|
||||
self.assertFalse(camcheck.is_vcint_failure(r))
|
||||
self.assertEqual(r["map"]["slam_left"]["node"], 0)
|
||||
|
||||
def test_four_cameras_in_ring(self):
|
||||
make_ring(self.ring, ["a_video9", "b_video13", "c_video6", "d_video7", "a_video9_dk"])
|
||||
make_ring(self.ring, ["a_video9", "b_video13", "c_video6", "d_video7", "a_video9_dk"], nodes=[9, 13, 6, 7, 9])
|
||||
r = camcheck.check(log=self.log, proc=False, ring_path=self.ring)
|
||||
self.assertEqual(r["status"], "ok")
|
||||
self.assertEqual(len(r["ring"]["mono"]), 4) # the dark twin doesn't count
|
||||
|
||||
def test_ring_from_before_the_cameras_moved(self):
|
||||
# 2026-10-12: the colour module disconnected at 08:10 and XRService moved the side pair
|
||||
# to video0/3; ft-camd, started the day before, still published video9/13, and a whole
|
||||
# session recorded only the upper pair
|
||||
unplugged = [L("11:00:00", "[buildMediaCtlSetupTasks] ISP enabled for tracking cameras (main VFE available)")] + \
|
||||
[L("11:00:01", "TrackingCameraInit: index: %d. video device: /dev/video%d. v4l subdevice: x" % (i, n))
|
||||
for i, n in enumerate((0, 3, 6, 7))]
|
||||
with open(self.log, "w") as f:
|
||||
f.write("\n".join(START + GOOD_OPEN + unplugged) + "\n")
|
||||
make_ring(self.ring, ["og01a1b_4-0036_video9", "og01a1b_4-0060_video13", "og0ve10_5-0060_video6",
|
||||
"og0ve10_5-0060_video7"], nodes=[9, 13, 6, 7])
|
||||
r = camcheck.check(log=self.log, proc=False, ring_path=self.ring)
|
||||
self.assertEqual(r["status"], "degraded")
|
||||
self.assertEqual(r["ring_missing"], [0, 3])
|
||||
self.assertIn("ft-camd publishes video9 video13, but XRService runs those cameras on video0 video3",
|
||||
r["reason"])
|
||||
self.assertTrue(camcheck.is_ring_short(r))
|
||||
|
||||
def test_stale_ring_ignored(self):
|
||||
make_ring(self.ring, ["slam_video9"], alive=False)
|
||||
r = camcheck.check(log=self.log, proc=False, ring_path=self.ring)
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Tests for hands/handsflag.py (`ft-handsctl flag`): the request ft-hands reads, the folder, the
|
||||
flash and head poses asked of a made-up ft-handview, and a request nobody takes. Nothing here talks
|
||||
to the real ft-hands or ft-handview, or opens /dev/video99.
|
||||
|
||||
python3 hands/tests/test_handsflag.py
|
||||
"""
|
||||
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.dirname(HERE))
|
||||
import handsflag as hf # noqa: E402
|
||||
|
||||
|
||||
class FakeView(threading.Thread):
|
||||
"""ft-handview's socket under another name: answers flash and poses."""
|
||||
|
||||
def __init__(self, name):
|
||||
super().__init__(daemon=True)
|
||||
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
|
||||
self.sock.bind("\0" + name)
|
||||
self.sock.settimeout(0.2)
|
||||
self.got, self.stop = [], False
|
||||
|
||||
def run(self):
|
||||
while not self.stop:
|
||||
try:
|
||||
data, addr = self.sock.recvfrom(256)
|
||||
except socket.timeout:
|
||||
continue
|
||||
cmd = data.decode()
|
||||
self.got.append(cmd)
|
||||
if cmd == "flash":
|
||||
reply = "ok 2"
|
||||
elif cmd.startswith("poses"):
|
||||
m = " ".join("%.5f" % v for v in (1, 0, 0, 0.1, 0, 1, 0, 1.6, 0, 0, 1, -0.2))
|
||||
reply = "ok" + "".join("\n%d %s" % (1000 + 33 * i, m) for i in range(3))
|
||||
else:
|
||||
reply = "error"
|
||||
self.sock.sendto(reply.encode(), addr)
|
||||
|
||||
|
||||
class FakeHands(threading.Thread):
|
||||
"""ft-hands' side: takes run_dir/flag and keeps what it said."""
|
||||
|
||||
def __init__(self, run_dir):
|
||||
super().__init__(daemon=True)
|
||||
self.path, self.seen, self.stop = os.path.join(run_dir, "flag"), None, False
|
||||
|
||||
def run(self):
|
||||
while not self.stop and self.seen is None:
|
||||
if os.path.exists(self.path):
|
||||
with open(self.path) as f:
|
||||
self.seen = dict(line.rstrip("\n").split("=", 1) for line in f if "=" in line)
|
||||
os.unlink(self.path)
|
||||
time.sleep(0.05)
|
||||
|
||||
|
||||
class FlagTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.mkdtemp(prefix="handsflag-test-")
|
||||
self.run_dir = os.path.join(self.tmp, "run")
|
||||
self.env = {k: os.environ.get(k) for k in ("FT_HANDS_FLAG_DIR", "FT_HANDS_FLAG_VIEW", "FT_HANDS_FLAG_TONE",
|
||||
"FT_HANDS_FLAG_FLASH", "FRAME_VOICE_WAKE_UNIX")}
|
||||
os.environ.update(FT_HANDS_FLAG_DIR=os.path.join(self.tmp, "flags"), FT_HANDS_FLAG_VIEW="0", FT_HANDS_FLAG_TONE="0",
|
||||
FT_HANDS_FLAG_FLASH="1")
|
||||
self.view_name = "ft_handview_test_%d" % os.getpid()
|
||||
|
||||
def tearDown(self):
|
||||
for k, v in self.env.items():
|
||||
if v is None:
|
||||
os.environ.pop(k, None)
|
||||
else:
|
||||
os.environ[k] = v
|
||||
shutil.rmtree(self.tmp, ignore_errors=True)
|
||||
|
||||
def test_flag_taken(self):
|
||||
view, hands = FakeView(self.view_name), FakeHands(self.run_dir)
|
||||
view.start(), hands.start()
|
||||
os.environ["FRAME_VOICE_WAKE_UNIX"] = "1760000000.25"
|
||||
try:
|
||||
rc = hf.main(["fingers", "crossed,\nnext", "line"], run_dir=self.run_dir, sock_name=self.view_name, detach=False)
|
||||
finally:
|
||||
view.stop = hands.stop = True
|
||||
view.join(1)
|
||||
view.sock.close()
|
||||
self.assertEqual(rc, 0)
|
||||
self.assertIsNotNone(hands.seen)
|
||||
path = hands.seen["dir"]
|
||||
self.assertTrue(os.path.isdir(path) and os.path.basename(path).startswith("flag-"))
|
||||
self.assertEqual(os.stat(path).st_mode & 0o777, 0o700)
|
||||
self.assertEqual(hands.seen["note"], "fingers crossed, next line") # one line
|
||||
self.assertEqual(float(hands.seen["said_unix"]), 1760000000.25)
|
||||
self.assertIn("flash", view.got)
|
||||
self.assertTrue(any(c.startswith("poses ") for c in view.got))
|
||||
with open(os.path.join(path, "hmd.jsonl")) as f:
|
||||
poses = [json.loads(line) for line in f]
|
||||
self.assertEqual(len(poses), 3)
|
||||
self.assertEqual(len(poses[0]["m"]), 12)
|
||||
with open(os.path.join(path, "ctl.json")) as f:
|
||||
ctl = json.load(f)
|
||||
self.assertTrue(ctl["taken"])
|
||||
self.assertEqual(ctl["flash"], "ok 2")
|
||||
self.assertEqual(ctl["hmd_poses"], 3)
|
||||
self.assertNotIn("view", ctl) # HANDS_FLAG_VIEW=0
|
||||
self.assertFalse(os.path.exists(os.path.join(self.run_dir, "flag")))
|
||||
|
||||
def test_not_taken(self):
|
||||
start = time.monotonic()
|
||||
rc = hf.main([], run_dir=self.run_dir, sock_name=self.view_name, detach=False)
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertLess(time.monotonic() - start, hf.TAKE_WAIT_S + hf.AFTER_S + 2)
|
||||
# the request is gone, so a later ft-hands doesn't take a stale one
|
||||
self.assertFalse(os.path.exists(os.path.join(self.run_dir, "flag")))
|
||||
with open(os.path.join(os.listdir(os.environ["FT_HANDS_FLAG_DIR"]) and os.path.join(
|
||||
os.environ["FT_HANDS_FLAG_DIR"], os.listdir(os.environ["FT_HANDS_FLAG_DIR"])[0]), "ctl.json")) as f:
|
||||
ctl = json.load(f)
|
||||
self.assertFalse(ctl["taken"])
|
||||
self.assertNotIn("flash", ctl)
|
||||
self.assertEqual(ctl["hmd_poses"], 0) # no ft-handview answering
|
||||
|
||||
def test_folders_dont_collide(self):
|
||||
base = os.path.join(self.tmp, "b")
|
||||
a, b = hf.flag_dir(base, 1760000000), hf.flag_dir(base, 1760000000)
|
||||
self.assertNotEqual(a, b)
|
||||
self.assertTrue(b.endswith("-2"))
|
||||
|
||||
def test_poses_lines(self):
|
||||
self.assertEqual(hf.poses_lines(None), [])
|
||||
self.assertEqual(hf.poses_lines("error x"), [])
|
||||
lines = hf.poses_lines("ok\n5 " + " ".join(["0.5"] * 12) + "\nbad line")
|
||||
self.assertEqual(len(lines), 1)
|
||||
self.assertEqual(json.loads(lines[0])["t_ns"], 5)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Executable
+275
@@ -0,0 +1,275 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Tests for hands/handsmode.py: HANDS_MODE and HANDS_MATTE_MARGIN in a temporary frametop.conf, the
|
||||
Hands page's three input switches (methods_of, method_writes), and which units each mode starts,
|
||||
stops and makes SteamVR want, with a made-up systemd (nothing here runs systemctl, getcap or pgrep).
|
||||
|
||||
python3 hands/tests/test_handsmode.py
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.dirname(HERE))
|
||||
import handsmode as hm # noqa: E402
|
||||
|
||||
CAMD, HANDS, VIEW = hm.TRACKING + (hm.VIEW,)
|
||||
CUT_CAMD, CUT_HANDS = hm.CUTOUTS
|
||||
BIN = "/home/u/frametop/hands/build/ft-camd"
|
||||
|
||||
|
||||
class FakeHost:
|
||||
"""systemd as the tests set it up: loaded units, active ones, SteamVR's wants."""
|
||||
|
||||
def __init__(self, loaded=(CAMD, HANDS), active=(), steamvr=True, desktop=True, caps=True, built=True,
|
||||
wanted=()):
|
||||
self.loaded, self.active, self.wanted_units = set(loaded), set(active), set(wanted)
|
||||
self.steamvr, self.desktop, self.has_caps, self.built = steamvr, desktop, caps, built
|
||||
self.calls = []
|
||||
|
||||
def units(self, names):
|
||||
out = {}
|
||||
for u in names:
|
||||
on = u in self.active or (u == hm.STEAMVR and self.steamvr)
|
||||
out[u] = {"load": "loaded" if u in self.loaded or u == hm.STEAMVR or (u in hm.CUTOUTS and on)
|
||||
else "not-found", "active": "active" if on else "inactive"}
|
||||
return out
|
||||
|
||||
def exec_path(self, unit):
|
||||
return BIN if unit == CAMD and CAMD in self.loaded else ""
|
||||
|
||||
def wanted(self, unit):
|
||||
return unit in self.wanted_units
|
||||
|
||||
def exists(self, path):
|
||||
return self.built
|
||||
|
||||
def caps(self, path):
|
||||
return self.has_caps
|
||||
|
||||
def desktop_up(self):
|
||||
return self.desktop
|
||||
|
||||
def cameras(self):
|
||||
return "ok"
|
||||
|
||||
def systemctl(self, *args):
|
||||
self.calls.append(list(args))
|
||||
|
||||
|
||||
def plan(mode, host, desktop=None, strict=False):
|
||||
return hm.plan(mode, hm.status(host, {"HANDS_MODE": mode}, cameras=False), desktop, strict)
|
||||
|
||||
|
||||
class ConfTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = tempfile.mkdtemp(prefix="handsmode-test-")
|
||||
self.conf = os.path.join(self.dir, "frametop.conf")
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.dir)
|
||||
|
||||
def test_mode_default_and_bad_values(self):
|
||||
self.assertEqual(hm.mode_of({}), "off")
|
||||
self.assertEqual(hm.mode_of({"HANDS_MODE": "sometimes"}), "off")
|
||||
for m in hm.MODES:
|
||||
self.assertEqual(hm.mode_of({"HANDS_MODE": m}), m)
|
||||
|
||||
def test_margin(self):
|
||||
self.assertEqual(hm.margin_of({}), hm.MARGIN_DEFAULT)
|
||||
self.assertEqual(hm.margin_of({"HANDS_MATTE_MARGIN": "0.75"}), 0.75)
|
||||
self.assertEqual(hm.margin_of({"HANDS_MATTE_MARGIN": "big"}), hm.MARGIN_DEFAULT)
|
||||
self.assertEqual(hm.margin_of({"HANDS_MATTE_MARGIN": "12"}), hm.MARGIN_DEFAULT) # ft-screens ignores it too
|
||||
|
||||
def test_write_keeps_comment_and_others(self):
|
||||
with open(self.conf, "w") as f:
|
||||
f.write("SCREENS=2\nHANDS_MODE=off # when hand tracking runs\n# HANDS_MODE=always\n")
|
||||
hm.write_value("HANDS_MODE", "frametop", self.conf)
|
||||
with open(self.conf) as f:
|
||||
text = f.read()
|
||||
self.assertIn("HANDS_MODE=frametop # when hand tracking runs\n", text)
|
||||
self.assertIn("SCREENS=2\n", text)
|
||||
self.assertIn("# HANDS_MODE=always\n", text) # a commented line isn't the setting
|
||||
self.assertEqual(hm.read_conf(self.conf), {"SCREENS": "2", "HANDS_MODE": "frametop"})
|
||||
|
||||
def test_write_adds_missing_key_and_file(self):
|
||||
hm.write_value("HANDS_MODE", "always", self.conf)
|
||||
hm.write_value("HANDS_MATTE_MARGIN", "0.75", self.conf)
|
||||
conf = hm.read_conf(self.conf)
|
||||
self.assertEqual((hm.mode_of(conf), hm.margin_of(conf)), ("always", 0.75))
|
||||
|
||||
def test_quoted_values(self):
|
||||
with open(self.conf, "w") as f:
|
||||
f.write('HANDS_MODE="always"\n')
|
||||
self.assertEqual(hm.mode_of(hm.read_conf(self.conf)), "always")
|
||||
|
||||
|
||||
class PlanTest(unittest.TestCase):
|
||||
def test_always_wants_and_starts(self):
|
||||
h = FakeHost(loaded=(CAMD, HANDS, VIEW))
|
||||
self.assertEqual(plan("always", h), [["add-wants", hm.STEAMVR, CAMD, HANDS, VIEW],
|
||||
["start", "--no-block", CAMD, HANDS, VIEW]])
|
||||
|
||||
def test_always_without_steamvr_only_wants(self):
|
||||
h = FakeHost(steamvr=False, wanted=(CAMD,))
|
||||
self.assertEqual(plan("always", h, strict=True), [["add-wants", hm.STEAMVR, HANDS]])
|
||||
|
||||
def test_hand_view_not_installed_is_left_out(self):
|
||||
h = FakeHost(loaded=(CAMD, HANDS))
|
||||
self.assertFalse(any(VIEW in call for call in plan("always", h)))
|
||||
|
||||
def test_frametop_with_desktop(self):
|
||||
h = FakeHost(wanted=(CAMD, HANDS))
|
||||
self.assertEqual(plan("frametop", h), [["disable", CAMD, HANDS], ["start", "--no-block", CAMD, HANDS]])
|
||||
|
||||
def test_frametop_without_desktop(self):
|
||||
h = FakeHost(desktop=False, active=(CAMD, HANDS))
|
||||
self.assertEqual(plan("frametop", h), []) # an install or caps run leaves ft-handsctl's alone
|
||||
self.assertEqual(plan("frametop", h, strict=True), [["stop", "--no-block", CAMD, HANDS]])
|
||||
|
||||
def test_desktop_hooks(self):
|
||||
h = FakeHost(desktop=False) # the hook's word wins over pgrep (ft-screens still starting)
|
||||
self.assertEqual(plan("frametop", h, desktop=True), [["start", "--no-block", CAMD, HANDS]])
|
||||
h = FakeHost(desktop=True, active=(CAMD, HANDS)) # ft-screens still ending
|
||||
self.assertEqual(plan("frametop", h, desktop=False), [["stop", "--no-block", CAMD, HANDS]])
|
||||
|
||||
def test_off_stops_everything_when_chosen(self):
|
||||
h = FakeHost(loaded=(CAMD, HANDS, VIEW), active=(CAMD, HANDS, VIEW, CUT_CAMD), wanted=(CAMD, HANDS, VIEW))
|
||||
self.assertEqual(plan("off", h, strict=True), [["disable", CAMD, HANDS, VIEW],
|
||||
["stop", "--no-block", CAMD, HANDS, VIEW, CUT_CAMD]])
|
||||
self.assertEqual(plan("off", h), [["disable", CAMD, HANDS, VIEW]])
|
||||
|
||||
def test_off_with_nothing_running(self):
|
||||
self.assertEqual(plan("off", FakeHost(), strict=True), [])
|
||||
|
||||
def test_no_caps_starts_nothing(self):
|
||||
h = FakeHost(caps=False)
|
||||
self.assertEqual(plan("always", h), [["add-wants", hm.STEAMVR, CAMD, HANDS]])
|
||||
self.assertEqual(plan("frametop", h), [])
|
||||
|
||||
def test_not_installed(self):
|
||||
h = FakeHost(loaded=())
|
||||
self.assertEqual(plan("always", h), [])
|
||||
self.assertEqual(plan("frametop", h), [])
|
||||
|
||||
def test_apply_runs_the_plan(self):
|
||||
h = FakeHost()
|
||||
calls, _ = hm.apply(h, {"HANDS_MODE": "frametop"})
|
||||
self.assertEqual(h.calls, calls)
|
||||
self.assertEqual(calls, [["start", "--no-block", CAMD, HANDS]])
|
||||
|
||||
|
||||
class StatusTest(unittest.TestCase):
|
||||
def test_problems(self):
|
||||
st = hm.status(FakeHost(loaded=()), {})
|
||||
self.assertIn("hands/run.sh install", st["problem"])
|
||||
st = hm.status(FakeHost(built=False), {})
|
||||
self.assertIn("isn't built", st["problem"])
|
||||
st = hm.status(FakeHost(caps=False), {"HANDS_MODE": "always"})
|
||||
self.assertIn("/home/u/frametop/hands/run.sh caps", st["problem"])
|
||||
self.assertEqual(st["summary"], "Hand tracking can't start with SteamVR")
|
||||
self.assertEqual(hm.status(FakeHost(), {})["problem"], "")
|
||||
|
||||
def test_cameras(self):
|
||||
h = FakeHost()
|
||||
h.cameras = lambda: "degraded: upper cameras and IR light off (VCINT FPGA failed to load)"
|
||||
self.assertIn("upper cameras", hm.status(h, {})["problem"])
|
||||
h.steamvr = False # nothing to check without SteamVR
|
||||
self.assertEqual(hm.status(h, {})["problem"], "")
|
||||
|
||||
def test_summary(self):
|
||||
self.assertEqual(hm.status(FakeHost(), {})["summary"], "Hand tracking is off")
|
||||
self.assertEqual(hm.status(FakeHost(active=(CAMD, HANDS)), {})["summary"],
|
||||
"Hand tracking is running (started by hand: ft-handsctl)")
|
||||
self.assertEqual(hm.status(FakeHost(active=(CAMD, HANDS)), {"HANDS_MODE": "frametop"})["summary"],
|
||||
"Hand tracking is running")
|
||||
self.assertEqual(hm.status(FakeHost(steamvr=False), {"HANDS_MODE": "frametop"})["summary"],
|
||||
"Hand tracking starts with the Frametop desktop")
|
||||
self.assertEqual(hm.status(FakeHost(active=(CUT_CAMD, CUT_HANDS)), {})["summary"],
|
||||
"The hand cutouts are running (started by hand: ft-cutouts)")
|
||||
|
||||
|
||||
class MethodsTest(unittest.TestCase):
|
||||
"""The Hands page's three switches (gaze clicks, the ray, direct touch): read from old configs as
|
||||
they always worked, and each toggled without moving the others."""
|
||||
|
||||
def apply(self, conf, method, on):
|
||||
new = dict(conf, **hm.method_writes(conf, method, on))
|
||||
return new, hm.methods_of(new)
|
||||
|
||||
def test_old_configs_read_as_before(self):
|
||||
self.assertEqual(hm.methods_of({}), {"gaze_clicks": False, "ray": False, "touch": False})
|
||||
on = {"gaze_clicks": True, "ray": True, "touch": True}
|
||||
self.assertEqual(hm.methods_of({"POINTER_HANDS": "1"}), on)
|
||||
self.assertEqual(hm.methods_of({"POINTER_HANDS": "1", "HANDS_NEAR": "1"}), on) # the example config's
|
||||
self.assertEqual(hm.methods_of({"POINTER_HANDS": "1", "POINTER_HAND_RAY": "0"})["ray"], False)
|
||||
self.assertEqual(hm.methods_of({"POINTER_HANDS": "1", "HANDS_NEAR": "0"})["touch"], False)
|
||||
self.assertTrue(hm.methods_of({"HANDS_NEAR": "force"})["touch"])
|
||||
self.assertFalse(hm.methods_of({"HANDS_NEAR": "1"})["touch"], "1 without POINTER_HANDS: off, as before")
|
||||
self.assertTrue(hm.methods_of({"HANDS_NEAR": "on"})["touch"])
|
||||
self.assertFalse(hm.methods_of({"POINTER_HANDS": "yes"})["ray"], "as the helper reads it: not a number, 0")
|
||||
|
||||
def test_each_switch_alone(self):
|
||||
for method in hm.METHODS:
|
||||
conf, got = self.apply({}, method, True)
|
||||
self.assertEqual(got, {m: m == method for m in hm.METHODS}, f"{method} alone: {conf}")
|
||||
conf, got = self.apply(conf, method, False)
|
||||
self.assertEqual(got, {m: False for m in hm.METHODS}, f"{method} off again: {conf}")
|
||||
|
||||
def test_touch_alone_needs_no_pointer_hands(self):
|
||||
conf, got = self.apply({}, "touch", True)
|
||||
self.assertEqual(conf, {"HANDS_NEAR": "on"})
|
||||
conf, got = self.apply({"POINTER_HANDS": "1"}, "gaze_clicks", False)
|
||||
conf, got = self.apply(conf, "ray", False)
|
||||
self.assertEqual(conf["POINTER_HANDS"], "0")
|
||||
self.assertEqual(conf["HANDS_NEAR"], "on", "touch stays on without POINTER_HANDS")
|
||||
self.assertTrue(got["touch"])
|
||||
|
||||
def test_turning_one_on_pins_the_others(self):
|
||||
# all off, then the ray: POINTER_GAZE_PINCH's default (1) and HANDS_NEAR's (1) would turn the
|
||||
# others on with POINTER_HANDS, so they're written off
|
||||
conf, got = self.apply({}, "ray", True)
|
||||
self.assertEqual(got, {"gaze_clicks": False, "ray": True, "touch": False})
|
||||
self.assertEqual(conf, {"POINTER_HANDS": "1", "POINTER_GAZE_PINCH": "0", "HANDS_NEAR": "0"})
|
||||
conf, got = self.apply(conf, "gaze_clicks", True)
|
||||
self.assertEqual(got, {"gaze_clicks": True, "ray": True, "touch": False})
|
||||
|
||||
def test_minimal_writes(self):
|
||||
conf = {"POINTER_HANDS": "1", "HANDS_NEAR": "1"}
|
||||
self.assertEqual(hm.method_writes(conf, "ray", True), {}, "already on: nothing")
|
||||
self.assertEqual(hm.method_writes(conf, "ray", False), {"POINTER_HAND_RAY": "0"})
|
||||
self.assertEqual(hm.method_writes(conf, "touch", False), {"HANDS_NEAR": "0"})
|
||||
self.assertEqual(hm.method_writes({"HANDS_NEAR": "force"}, "touch", True), {}, "force stays force")
|
||||
|
||||
def test_every_combination(self):
|
||||
start = {"POINTER_HANDS": "1", "HANDS_NEAR": "1"}
|
||||
for bits in range(8):
|
||||
want = {m: bool(bits >> i & 1) for i, m in enumerate(hm.METHODS)}
|
||||
conf = dict(start)
|
||||
for m in hm.METHODS:
|
||||
conf, _ = self.apply(conf, m, want[m])
|
||||
self.assertEqual(hm.methods_of(conf), want, f"{want}: {conf}")
|
||||
|
||||
|
||||
class HostTest(unittest.TestCase):
|
||||
def test_units_parses_systemctl_show(self):
|
||||
h = hm.Host()
|
||||
out = ("Id=steamvr.service\nLoadState=loaded\nActiveState=active\n\n"
|
||||
"Id=frametop-camd.service\nLoadState=not-found\nActiveState=inactive\n")
|
||||
h.run = lambda cmd, timeout=20: hm.subprocess.CompletedProcess(cmd, 0, out, "")
|
||||
got = h.units((hm.STEAMVR, CAMD, VIEW))
|
||||
self.assertEqual(got[hm.STEAMVR], {"load": "loaded", "active": "active"})
|
||||
self.assertEqual(got[CAMD]["load"], "not-found")
|
||||
self.assertEqual(got[VIEW], {"load": "not-found", "active": "inactive"}) # no answer for it
|
||||
|
||||
def test_exec_path(self):
|
||||
h = hm.Host()
|
||||
out = "{ path=/x/hands/build/ft-camd ; argv[]=/x/hands/build/ft-camd --status 60 ; ignore_errors=no }\n"
|
||||
h.run = lambda cmd, timeout=20: hm.subprocess.CompletedProcess(cmd, 0, out, "")
|
||||
self.assertEqual(h.exec_path(CAMD), "/x/hands/build/ft-camd")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -14,9 +14,9 @@ line: {"pair", "verdict": "named"|"swapped"|"unknown", "named", "swapped", "matc
|
||||
ft-hands decides the side cameras' naming by itself (HANDS_SWAP_SIDES=auto, track/sides.h);
|
||||
this is the independent check, from the scene rather than hands.
|
||||
|
||||
ft-camd tells the two side cameras' buffers apart by the order XRService allocated them,
|
||||
and after some XRService restarts that order puts each camera's images under the other's
|
||||
name. The tracker then sees every hand in one camera only, at the wrong depth. This
|
||||
Before 2026-10-05 the side cameras' images often carried each other's names (hands/README.md,
|
||||
"Which camera is which"); recordings from then may still. The tracker then sees every hand in
|
||||
one camera only, at the wrong depth. This
|
||||
matches features between the two images and measures how close each pair's rays pass
|
||||
with the factory calibration, once as named and once swapped: true matches meet in
|
||||
front of both cameras only under the right naming.
|
||||
@@ -34,8 +34,28 @@ from tools.show_set import index, read_set # noqa: E402
|
||||
from tools import calib # noqa: E402
|
||||
|
||||
|
||||
PIPES = {'msm_vfe3_video0': 'slam_left', 'msm_vfe4_video0': 'slam_right', # as ft-hands maps them
|
||||
PIPES = {'msm_vfe3_video0': 'slam_right', 'msm_vfe4_video0': 'slam_left', # with the colour module
|
||||
'msm_vfe2_video0': 'upper_left', 'msm_vfe2_video1': 'upper_right'}
|
||||
|
||||
|
||||
def ring_names():
|
||||
"""{/dev/videoN's N: calibration name} as ft-hands names them: by XRService's log
|
||||
(camcheck.py), else by capture pipe (PIPES)."""
|
||||
import camcheck
|
||||
try:
|
||||
by_log = {node: name for name, node in camcheck.read_log(camcheck.newest_log()).camera_map().items()}
|
||||
except (OSError, ValueError):
|
||||
by_log = {}
|
||||
if by_log:
|
||||
return by_log
|
||||
out = {}
|
||||
for path in os.listdir('/sys/class/video4linux'):
|
||||
if path.startswith('video'):
|
||||
with open('/sys/class/video4linux/%s/name' % path) as f:
|
||||
name = PIPES.get(f.read().strip())
|
||||
if name:
|
||||
out[int(path[5:])] = name
|
||||
return out
|
||||
PAIRS = {'side': ('slam_left', 'slam_right'), 'upper': ('upper_left', 'upper_right')}
|
||||
|
||||
|
||||
@@ -100,8 +120,9 @@ def live_pairs(count, names=PAIRS['side']):
|
||||
if not ring.alive():
|
||||
sys.exit('ft-camd isn\'t running (no heartbeat)')
|
||||
cams = {}
|
||||
names_of = ring_names()
|
||||
for c in ring.cams:
|
||||
name = PIPES.get(open('/sys/class/video4linux/video%d/name' % c.node).read().strip())
|
||||
name = names_of.get(c.node)
|
||||
if name and not c.name.endswith('-dark'):
|
||||
cams[name] = c
|
||||
for k in range(count):
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Why did a hand go missing? Reads an ft-handreplay --timeline written with the tracker's trace
|
||||
(and best with --oracle N) and, per side (the tracker's left/right call), finds every
|
||||
gap of 0.3 s or more between processed sets with a hand there, then says what the tracker was doing.
|
||||
|
||||
tools/gap_report.py TIMELINE [--min 0.3] [--list]
|
||||
|
||||
Per gap:
|
||||
- start: what happened to the side's last hand at the first set without it (its views lost, a
|
||||
handoff miss, a split, the misread guard, or the hand crossed to the other side);
|
||||
- time held (the hand kept for 0.3 s, its crops retried where it was), time with the search blocked
|
||||
(two hand ids tracked), time searching, and time waiting between searches;
|
||||
- the oracle (a full search every N sets): in how many of its samples the side's hand was findable,
|
||||
and whether any tile it was found in was searched during the gap; and how late the hand came back:
|
||||
from the oracle's first sample finding it (through to the gap's end) to the end, for gaps where it
|
||||
was out of the full search's reach for a while (back in view) and for the rest;
|
||||
- palms the search found on the way that the landmark model rejected, and how the hand came back.
|
||||
|
||||
Causes, one per gap, by where most of the missing time went:
|
||||
findable-not-searched the oracle found it, but the search never tried a tile it was in
|
||||
searched-missed a tile that holds it was searched, and the palm detector missed it then
|
||||
palm-rejected the search found its palm, but the landmark model said no hand (< 0.5)
|
||||
search-blocked the search didn't run: two hand ids were tracked
|
||||
not-findable the oracle didn't find it either (out of view, or no model sees it)
|
||||
held back within the hold (rare at 0.3 s)
|
||||
label-flip not lost: both hands were published, this one called the other side
|
||||
"""
|
||||
import argparse
|
||||
import collections
|
||||
import re
|
||||
import sys
|
||||
|
||||
|
||||
def parse(path):
|
||||
sets = collections.OrderedDict() # ts -> dict(hands=[...], ev=[...])
|
||||
oracle = collections.defaultdict(list)
|
||||
breaks = [] # a pause in the recording (the hand recorder's takes stop between prompts) ends here
|
||||
for line in open(path):
|
||||
parts = line.split()
|
||||
if len(parts) < 2:
|
||||
continue
|
||||
try:
|
||||
ts = float(parts[0])
|
||||
except ValueError:
|
||||
continue
|
||||
rest = parts[1:]
|
||||
if rest[0] == 'ev':
|
||||
sets.setdefault(ts, {'hands': [], 'ev': [], 'proc': False})['ev'].append(' '.join(rest[1:]))
|
||||
elif rest[0] == 'oracle':
|
||||
# oracle CAM tile N presence P right R wrist X Y Z roi ...
|
||||
oracle[ts].append({'cam': rest[1], 'tile': int(rest[3]), 'presence': float(rest[5]),
|
||||
'x': float(rest[9]), 'right': float(rest[7])})
|
||||
elif rest[0] == 'break':
|
||||
breaks.append(ts)
|
||||
elif rest[0] == 'oracle-done':
|
||||
oracle.setdefault(ts, [])
|
||||
elif rest[0] == '-':
|
||||
sets.setdefault(ts, {'hands': [], 'ev': [], 'proc': False})['proc'] = True
|
||||
elif re.fullmatch(r'\d+', rest[0]) and len(rest) >= 6 and rest[1] in ('L', 'R'):
|
||||
d = sets.setdefault(ts, {'hands': [], 'ev': [], 'proc': False})
|
||||
d['proc'] = True
|
||||
# side: the tracker's left/right call when the line has it (hand L|R), else by the wrist
|
||||
side = rest[7] if len(rest) >= 8 and rest[6] == 'hand' else rest[1]
|
||||
d['hands'].append({'id': int(rest[0]), 'side': side, 'views': int(rest[2]), 'x': float(rest[3])})
|
||||
procs = [(ts, d) for ts, d in sets.items() if d['proc']]
|
||||
return procs, oracle, breaks
|
||||
|
||||
|
||||
def report(path, min_gap=0.3, listing=False):
|
||||
procs, oracle, breaks = parse(path)
|
||||
otimes = sorted(oracle)
|
||||
total_time = procs[-1][0] - procs[0][0] if procs else 0
|
||||
out = {}
|
||||
for side in 'LR':
|
||||
gaps = []
|
||||
last = None # (index, hand id)
|
||||
for i, (ts, d) in enumerate(procs):
|
||||
here = [h for h in d['hands'] if h['side'] == side]
|
||||
if not here:
|
||||
continue
|
||||
if last is not None and any(procs[last[0]][0] < b <= ts for b in breaks):
|
||||
last = None
|
||||
if last is not None and ts - procs[last[0]][0] >= min_gap:
|
||||
gaps.append((last[0], i, last[1], here[0]['id']))
|
||||
last = (i, here[0]['id'])
|
||||
rows = []
|
||||
for a, b, hid, back_id in gaps:
|
||||
t0, t1 = procs[a][0], procs[b][0]
|
||||
nxt = procs[a + 1][1]
|
||||
ev0 = [e for e in nxt['ev'] if re.search(r'\b%d\b' % hid, e)]
|
||||
crossed = any(h['id'] == hid for h in nxt['hands'])
|
||||
start = 'crossed' if crossed else ','.join(sorted(set(e.split()[0] for e in ev0
|
||||
if e.split()[0] in ('lost', 'miss', 'split', 'misread', 'dup', 'over-budget')))) or '?'
|
||||
# state per processed interval in the gap
|
||||
forgotten = crossed
|
||||
t = collections.Counter()
|
||||
searched_tiles = set()
|
||||
rejected = kept = 0
|
||||
blocked_ids = set()
|
||||
for k in range(a + 1, b + 1):
|
||||
ts, d = procs[k]
|
||||
dt = ts - procs[k - 1][0]
|
||||
evs = d['ev']
|
||||
if any(e.startswith('forget %d ' % hid) for e in evs):
|
||||
forgotten = True
|
||||
srch = [e for e in evs if e.startswith('search ')]
|
||||
blk = [e for e in evs if e.startswith('search-blocked')]
|
||||
for e in srch:
|
||||
for m in re.finditer(r'(\S+)#(\d+)', e):
|
||||
searched_tiles.add((m.group(1), int(m.group(2))))
|
||||
for e in evs:
|
||||
if e.startswith('palm '):
|
||||
if e.endswith('rejected'):
|
||||
rejected += 1
|
||||
else:
|
||||
kept += 1
|
||||
for e in blk:
|
||||
blocked_ids.update(e.split()[2:])
|
||||
if len(d['hands']) >= 2 and all(h['side'] != side for h in d['hands']):
|
||||
t['flip'] += dt # two hands published, neither called this side: a labelling error
|
||||
elif not forgotten:
|
||||
t['held'] += dt
|
||||
elif blk:
|
||||
t['blocked'] += dt
|
||||
elif srch:
|
||||
t['search'] += dt
|
||||
else:
|
||||
t['wait'] += dt
|
||||
# oracle samples inside the gap (after the hold)
|
||||
osamp = [o for o in otimes if t0 < o < t1]
|
||||
found = [o for o in osamp if any((h['right'] > 0.5) == (side == 'R') for h in oracle[o])]
|
||||
otiles = set()
|
||||
for o in found:
|
||||
for h in oracle[o]:
|
||||
if (h['right'] > 0.5) == (side == 'R'):
|
||||
otiles.add((h['cam'], h['tile']))
|
||||
frac = len(found) / len(osamp) if osamp else None
|
||||
# how late it came back: from the first of the oracle samples that found it through to the end
|
||||
# of the gap (none of them missing it) to the end; reentry: the gap had samples not finding it
|
||||
late = None
|
||||
fset = set(found)
|
||||
for o in reversed(osamp):
|
||||
if o not in fset:
|
||||
break
|
||||
late = t1 - o
|
||||
end_ev = procs[b][1]['ev']
|
||||
how = 'search' if any(e.startswith('palm ') and e.endswith('kept') for e in end_ev) else \
|
||||
'split-off' if any('split off' in e for e in end_ev) else \
|
||||
'crossed-back' if any(h['id'] == hid for h in procs[b][1]['hands']) else 'handover/other'
|
||||
dur = t1 - t0
|
||||
if t['flip'] >= 0.5 * dur:
|
||||
cause = 'label-flip'
|
||||
elif t['held'] >= 0.8 * dur:
|
||||
cause = 'held'
|
||||
elif t['blocked'] >= 0.5 * dur:
|
||||
cause = 'search-blocked'
|
||||
elif frac is not None and frac < 0.3:
|
||||
cause = 'not-findable'
|
||||
elif rejected >= 2:
|
||||
cause = 'palm-rejected'
|
||||
elif otiles and not (otiles & searched_tiles):
|
||||
cause = 'findable-not-searched'
|
||||
elif otiles & searched_tiles:
|
||||
cause = 'searched-missed'
|
||||
else:
|
||||
cause = 'not-findable' if frac is not None else 'no-oracle'
|
||||
rows.append(dict(t0=t0, t1=t1, dur=dur, hid=hid, back=back_id, start=start, cause=cause, t=t,
|
||||
frac=frac, rejected=rejected, kept=kept, how=how, ntiles=len(searched_tiles),
|
||||
otiles=len(otiles), hit=len(otiles & searched_tiles), blocked=blocked_ids,
|
||||
late=late, reentry=len(found) < len(osamp)))
|
||||
out[side] = rows
|
||||
print(f'{path}: {total_time:.0f} s processed')
|
||||
# label-free: per oracle sample, hands the full search found (distinct left/right calls) against
|
||||
# hands the tracker published at the last processed set
|
||||
import bisect
|
||||
pts = [p[0] for p in procs]
|
||||
oh = om = 0
|
||||
for o in otimes:
|
||||
i = bisect.bisect_right(pts, o + 1e-6) - 1
|
||||
if i < 0:
|
||||
continue
|
||||
n = len(set(h['right'] > 0.5 for h in oracle[o]))
|
||||
oh += n
|
||||
om += max(0, n - min(2, len(procs[i][1]['hands'])))
|
||||
if oh:
|
||||
print(f' oracle: {oh} hands findable, tracker had {om} fewer ({100 * om / oh:.1f}% missed)')
|
||||
for side in 'LR':
|
||||
rows = out[side]
|
||||
tot = sum(r['dur'] for r in rows)
|
||||
longest = max([r['dur'] for r in rows], default=0)
|
||||
print(f' {side}: {len(rows)} gaps >= {min_gap} s, {tot:.1f} s missing, longest {longest:.1f} s')
|
||||
by = collections.Counter()
|
||||
n = collections.Counter()
|
||||
for r in rows:
|
||||
by[r['cause']] += r['dur']
|
||||
n[r['cause']] += 1
|
||||
for c, s in by.most_common():
|
||||
print(f' {c:22s} {n[c]:3d} gaps {s:6.1f} s ({100 * s / max(tot, 1e-9):.0f}%)')
|
||||
for what, sel in (('back in view', True), ('in view all along', False)):
|
||||
lates = sorted(r['late'] for r in rows if r['late'] is not None and r['reentry'] == sel)
|
||||
if lates:
|
||||
q = lambda f: lates[min(len(lates) - 1, int(f * len(lates)))]
|
||||
print(f' {what}: {len(lates)} gaps, found again after it could be: median {q(0.5):.2f} s, '
|
||||
f'90% {q(0.9):.2f} s, total {sum(lates):.1f} s')
|
||||
st = collections.Counter()
|
||||
for r in rows:
|
||||
st[r['start']] += 1
|
||||
tt = collections.Counter()
|
||||
for r in rows:
|
||||
tt.update(r['t'])
|
||||
print(' started by: ' + ', '.join(f'{k} {v}' for k, v in st.most_common()) +
|
||||
'; time labelled as the other side %.1f, held %.1f, blocked %.1f, searching %.1f, waiting %.1f s' %
|
||||
(tt['flip'], tt['held'], tt['blocked'], tt['search'], tt['wait']))
|
||||
if listing:
|
||||
for r in rows:
|
||||
fr = '-' if r['frac'] is None else f"{100 * r['frac']:.0f}%"
|
||||
print(f" {r['t0']:7.2f}-{r['t1']:7.2f} {r['dur']:4.1f}s id {r['hid']}->{r['back']} start {r['start']:12s} "
|
||||
f"{r['cause']:22s} flip {r['t']['flip']:.1f} held {r['t']['held']:.1f} blk {r['t']['blocked']:.1f} srch {r['t']['search']:.1f} "
|
||||
f"wait {r['t']['wait']:.1f} oracle {fr} tiles searched {r['ntiles']} oracle-tiles {r['otiles']} hit {r['hit']} "
|
||||
f"palms rejected {r['rejected']} kept {r['kept']} back by {r['how']}"
|
||||
+ (f" blocked by {sorted(r['blocked'])}" if r['blocked'] else ''))
|
||||
return out
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('timeline', nargs='+')
|
||||
ap.add_argument('--min', type=float, default=0.3)
|
||||
ap.add_argument('--list', action='store_true')
|
||||
a = ap.parse_args()
|
||||
for p in a.timeline:
|
||||
report(p, a.min, a.list)
|
||||
Executable
+39
@@ -0,0 +1,39 @@
|
||||
#!/bin/bash
|
||||
# Replays recordings through ft-handreplay with a timeline (trace events + oracle) for
|
||||
# tools/gap_report.py. Runs several at once; meant for the 7i through frame-job:
|
||||
# frame-job -- tools/replay_gaps.sh OUT MODELS "EXTRA ARGS" REC[:FROM:TO]...
|
||||
# REPLAY=BINARY replays with another ft-handreplay build (a baseline).
|
||||
# OUT gets REC.txt (the summary) and REC.tl (the timeline) per recording.
|
||||
set -uo pipefail
|
||||
out=$1 models=$2 extra=$3
|
||||
shift 3
|
||||
here=$(cd "$(dirname "$0")/.." && pwd)
|
||||
mkdir -p "$out"
|
||||
jobs=${JOBS:-4}
|
||||
for spec in "$@"; do
|
||||
IFS=: read -r rec from to <<<"$spec"
|
||||
name=$(basename "$rec")
|
||||
range=()
|
||||
[ -n "${from:-}" ] && range=(--from "$from" --to "$to") && name=$name-$from-$to
|
||||
# a recorder session (calibration.json + device.json beside sets.bin or two levels up): replay
|
||||
# with that headset's calibration
|
||||
devroot=()
|
||||
for c in "$rec" "$rec/../.."; do
|
||||
if [ -f "$c/calibration.json" ] && [ -f "$c/device.json" ]; then
|
||||
d=$out/devroot-$(basename "$(realpath "$c")")
|
||||
mkdir -p "$d/persist"
|
||||
cp "$c/calibration.json" "$d/persist/xrservice.json"
|
||||
cp "$c/device.json" "$d/persist/device_config.json"
|
||||
devroot=(env FRAME_JOB_DEVICE_ROOT="$d")
|
||||
[ "$c" = "$rec" ] || name=$(basename "$(realpath "$c")")-$name
|
||||
break
|
||||
fi
|
||||
done
|
||||
while [ "$(jobs -rp | wc -l)" -ge "$jobs" ]; do wait -n; done
|
||||
# shellcheck disable=SC2086
|
||||
${devroot[@]+"${devroot[@]}"} "${REPLAY:-$here/build/ft-handreplay}" "$rec" --cost --threads ${THREADS:-3} --models "$models" --timeline "$out/$name.tl" \
|
||||
${range[@]+"${range[@]}"} $extra > "$out/$name.txt" 2>&1 &
|
||||
done
|
||||
wait
|
||||
for f in "$out"/*.txt; do echo "== $f"; grep -E "processed|hands per|gaps|within 8|re-acquire|views lost|model calls|oracle,|full search|jitter" "$f"; done
|
||||
python3 "$here/tools/gap_report.py" "$out"/*.tl > "$out/gaps.txt" 2>&1 || true
|
||||
Executable
+38
@@ -0,0 +1,38 @@
|
||||
#!/bin/bash
|
||||
# Replays recordings through ft-handreplay with --tips (each hand's thumb, index and middle tips and the
|
||||
# pinch detector's measures per processed set, plus its pinch events), for frame-hands'
|
||||
# train/taps/tapeval.py. Runs several at once; meant for a compute host through frame-job:
|
||||
# frame-job -- tools/replay_tips.sh OUT NAME=MODELS "EXTRA ARGS" REC[:FROM:TO]...
|
||||
# OUT gets NAME/<rec>.tips and NAME/<rec>.txt (the summary) per recording. A recorder take
|
||||
# (takes/NN-name, with calibration.json and device.json two levels up) replays with that headset's
|
||||
# calibration and its side cameras as stored (--sides 0: exports are named right).
|
||||
set -uo pipefail
|
||||
out=$1 nm=$2 extra=$3
|
||||
shift 3
|
||||
name=${nm%%=*} models=${nm#*=}
|
||||
here=$(cd "$(dirname "$0")/.." && pwd)
|
||||
mkdir -p "$out/$name"
|
||||
jobs=${JOBS:-4}
|
||||
for spec in "$@"; do
|
||||
IFS=: read -r rec from to <<<"$spec"
|
||||
base=$(basename "$rec")
|
||||
range=()
|
||||
[ -n "${from:-}" ] && range=(--from "$from" --to "$to") && base=$base-$from-$to
|
||||
devroot=() sides=()
|
||||
if [ -f "$rec/../../calibration.json" ] && [ -f "$rec/../../device.json" ]; then
|
||||
s=$(realpath "$rec/../..")
|
||||
d=$out/devroot-$(basename "$(dirname "$s")" | cut -c1-8)-$(basename "$s")
|
||||
mkdir -p "$d/persist"
|
||||
cp "$s/calibration.json" "$d/persist/xrservice.json"
|
||||
cp "$s/device.json" "$d/persist/device_config.json"
|
||||
devroot=(env FRAME_JOB_DEVICE_ROOT="$d")
|
||||
sides=(--sides 0)
|
||||
base=$(basename "$(dirname "$s")" | cut -c1-8)-$base
|
||||
fi
|
||||
while [ "$(jobs -rp | wc -l)" -ge "$jobs" ]; do wait -n; done
|
||||
# shellcheck disable=SC2086
|
||||
${devroot[@]+"${devroot[@]}"} "$here/build/ft-handreplay" "$rec" --cost --threads ${THREADS:-3} --models "$models" \
|
||||
--tips "$out/$name/$base.tips" ${sides[@]+"${sides[@]}"} ${range[@]+"${range[@]}"} $extra > "$out/$name/$base.txt" 2>&1 &
|
||||
done
|
||||
wait
|
||||
for f in "$out/$name"/*.txt; do echo "== $f"; grep -E "processed|pinches" "$f"; done
|
||||
@@ -1,14 +1,15 @@
|
||||
"""Watch the gestures ft-hands publishes, live: pinches and grips, begins, ends, and drags.
|
||||
"""Watch the gestures ft-hands publishes, live: pinches, grips and middle pinches, begins, ends, and drags.
|
||||
|
||||
usage: python3 tools/watch_gestures.py [--every S] [--distance]
|
||||
|
||||
Prints a line when a pinch or a grip (a closed hand) begins or ends on either hand. It goes
|
||||
Prints a line when a pinch, a grip (a closed hand) or a middle pinch (thumb to middle finger)
|
||||
begins or ends on either hand. It goes
|
||||
by the counters, so a quick tap between two reads still shows. While one is held, every
|
||||
--every seconds (default 0.1) it prints how far its point has moved since it began, in the
|
||||
head frame (turning your head moves it too; a real consumer turns both points into the room
|
||||
first, see include/fh_gestures.h). --distance also prints each hand's thumb-to-index
|
||||
distance and finger curl, to see how close a gesture comes to the thresholds.
|
||||
Version 1 files (pinches only) still work.
|
||||
Version 1 files (pinches only) and version 2 files (no middle pinches) still work.
|
||||
"""
|
||||
import argparse
|
||||
import mmap
|
||||
@@ -20,7 +21,7 @@ HDR = struct.Struct('<8sIIQQQffff8x') # 64 bytes
|
||||
SLOT = struct.Struct('<IIIIQQff3f3f') # 64 bytes
|
||||
TRACKED, DOWN, LOST = 1, 2, 4
|
||||
SIDES = ('left ', 'right')
|
||||
KINDS = ('pinch', 'grip ')
|
||||
KINDS = ('pinch', 'grip ', 'middle pinch')
|
||||
|
||||
|
||||
def path():
|
||||
@@ -28,15 +29,20 @@ def path():
|
||||
|
||||
|
||||
def read(m):
|
||||
"""(header, [[pinch left, right], [grip left, right]]) under the sequence lock, or None
|
||||
if it's being written. Version 1 has no grips: they read as all zero."""
|
||||
"""(header, [[pinch left, right], [grip left, right], [middle pinch left, right]]) under the
|
||||
sequence lock, or None if it's being written. Version 1 has no grips and version 2 no middle
|
||||
pinches: they read as all zero."""
|
||||
for _ in range(10):
|
||||
s1 = struct.unpack_from('<Q', m, 16)[0]
|
||||
if s1 % 2 == 0:
|
||||
h = HDR.unpack_from(m, 0)
|
||||
kinds = 2 if h[1] >= 2 and len(m) >= HDR.size + 4 * SLOT.size else 1
|
||||
kinds = 1
|
||||
if h[1] >= 2 and len(m) >= HDR.size + 4 * SLOT.size:
|
||||
kinds = 2
|
||||
if h[1] >= 3 and len(m) >= HDR.size + 6 * SLOT.size:
|
||||
kinds = 3
|
||||
g = [[SLOT.unpack_from(m, HDR.size + (k * 2 + s) * SLOT.size) for s in range(2)] for k in range(kinds)]
|
||||
if kinds == 1:
|
||||
while len(g) < 3:
|
||||
g.append([(0,) * 14, (0,) * 14])
|
||||
if struct.unpack_from('<Q', m, 16)[0] == s1:
|
||||
return h, g
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
// Flagging tracking failures: see flagbuf.h.
|
||||
#include "flagbuf.h"
|
||||
|
||||
#include "pinch.h"
|
||||
|
||||
#include <pthread.h>
|
||||
#include <sched.h>
|
||||
#include <sys/resource.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <ctime>
|
||||
|
||||
namespace {
|
||||
|
||||
void appendf(std::string &s, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
|
||||
void appendf(std::string &s, const char *fmt, ...) {
|
||||
char buf[512];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
const int n = std::vsnprintf(buf, sizeof buf, fmt, ap);
|
||||
va_end(ap);
|
||||
if (n > 0) s.append(buf, size_t(std::min(n, int(sizeof buf) - 1)));
|
||||
}
|
||||
|
||||
void points_json(std::string &s, const V3 *p, int n) {
|
||||
s += '[';
|
||||
for (int i = 0; i < n; ++i) appendf(s, "%s[%.4f, %.4f, %.4f]", i ? ", " : "", p[i][0], p[i][1], p[i][2]);
|
||||
s += ']';
|
||||
}
|
||||
|
||||
double wall_now() {
|
||||
timespec ts;
|
||||
clock_gettime(CLOCK_REALTIME, &ts);
|
||||
return ts.tv_sec + ts.tv_nsec / 1e9;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string json_string(const std::string &s, bool null_if_empty) {
|
||||
if (null_if_empty && s.empty()) return "null";
|
||||
std::string o = "\"";
|
||||
for (unsigned char c : s) {
|
||||
if (c == '"' || c == '\\') o += '\\', o += char(c);
|
||||
else if (c == '\n') o += "\\n";
|
||||
else if (c == '\t') o += "\\t";
|
||||
else if (c < 0x20) appendf(o, "\\u%04x", c);
|
||||
else o += char(c);
|
||||
}
|
||||
return o + "\"";
|
||||
}
|
||||
|
||||
CropGeom crop_square(const Image &img, V2 center, double side, int max_px, uint8_t *out) {
|
||||
CropGeom g;
|
||||
side = std::max(side, 1.0);
|
||||
const int n = std::clamp(int(std::ceil(side - 1e-6)), 1, std::max(1, max_px));
|
||||
g.w = g.h = n;
|
||||
g.scale = side / n;
|
||||
g.x0 = center[0] - side / 2 + 0.5;
|
||||
g.y0 = center[1] - side / 2 + 0.5;
|
||||
// the taps: per output column and row, the image column and row (or -1 outside)
|
||||
const bool area = g.scale > 1.25;
|
||||
const int taps = area ? 2 : 1;
|
||||
const double off[2] = {area ? -g.scale / 4 : 0, area ? g.scale / 4 : 0};
|
||||
thread_local std::vector<int> xs, ys;
|
||||
xs.resize(size_t(n) * taps), ys.resize(size_t(n) * taps);
|
||||
for (int u = 0; u < n; ++u)
|
||||
for (int t = 0; t < taps; ++t) {
|
||||
const double c = (u + 0.5) * g.scale - 0.5 + off[t];
|
||||
const long x = std::lround(g.x0 + c), y = std::lround(g.y0 + c);
|
||||
xs[size_t(u) * taps + t] = x >= 0 && x < img.width ? int(x) : -1;
|
||||
ys[size_t(u) * taps + t] = y >= 0 && y < img.height ? int(y) : -1;
|
||||
}
|
||||
for (int v = 0; v < n; ++v) {
|
||||
uint8_t *o = out + size_t(v) * n;
|
||||
if (!area) {
|
||||
const int y = ys[size_t(v)];
|
||||
if (y < 0) {
|
||||
std::fill(o, o + n, 0);
|
||||
continue;
|
||||
}
|
||||
const uint8_t *row = img.data + size_t(y) * img.stride;
|
||||
for (int u = 0; u < n; ++u) o[u] = xs[size_t(u)] < 0 ? 0 : row[xs[size_t(u)]];
|
||||
continue;
|
||||
}
|
||||
const int y0 = ys[size_t(v) * 2], y1 = ys[size_t(v) * 2 + 1];
|
||||
const uint8_t *r0 = y0 < 0 ? nullptr : img.data + size_t(y0) * img.stride;
|
||||
const uint8_t *r1 = y1 < 0 ? nullptr : img.data + size_t(y1) * img.stride;
|
||||
for (int u = 0; u < n; ++u) {
|
||||
const int x0 = xs[size_t(u) * 2], x1 = xs[size_t(u) * 2 + 1];
|
||||
unsigned sum = 0;
|
||||
if (r0) sum += (x0 < 0 ? 0 : r0[x0]) + (x1 < 0 ? 0 : r0[x1]);
|
||||
if (r1) sum += (x0 < 0 ? 0 : r1[x0]) + (x1 < 0 ? 0 : r1[x1]);
|
||||
o[u] = uint8_t((sum + 2) / 4);
|
||||
}
|
||||
}
|
||||
return g;
|
||||
}
|
||||
|
||||
FlagBuffer::FlagBuffer(const FlagConfig &cfg) : cfg_(cfg) {
|
||||
cfg_.crop_px = std::clamp(cfg_.crop_px, 16, 1024);
|
||||
slot_bytes_ = size_t(cfg_.crop_px) * cfg_.crop_px;
|
||||
nslots_ = int(std::max<size_t>(1, cfg_.max_bytes / slot_bytes_));
|
||||
stats_.slots = size_t(nslots_);
|
||||
}
|
||||
|
||||
FlagBuffer::~FlagBuffer() { wait(); }
|
||||
|
||||
void FlagBuffer::wait() {
|
||||
if (writer_.joinable()) writer_.join();
|
||||
}
|
||||
|
||||
int FlagBuffer::take_slot() {
|
||||
std::lock_guard<std::mutex> l(mu_);
|
||||
if (!free_.empty()) {
|
||||
const int s = free_.back();
|
||||
free_.pop_back();
|
||||
return s;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
void FlagBuffer::give_back(const std::vector<Crop> &crops) {
|
||||
std::lock_guard<std::mutex> l(mu_);
|
||||
for (const Crop &c : crops)
|
||||
if (c.slot >= 0) free_.push_back(c.slot);
|
||||
}
|
||||
|
||||
void FlagBuffer::evict_front() {
|
||||
give_back(sets_.front().crops);
|
||||
sets_.pop_front();
|
||||
}
|
||||
|
||||
void FlagBuffer::add(int64_t t_raw, int64_t t_mono, int rec_set, const std::map<std::string, Image> &images,
|
||||
const std::vector<Seen> &views, const std::string &hands_json) {
|
||||
if (!arena_) {
|
||||
arena_.reset(new uint8_t[size_t(nslots_) * slot_bytes_]); // not zeroed: untouched pages stay unmapped
|
||||
std::lock_guard<std::mutex> l(mu_);
|
||||
free_.clear();
|
||||
for (int s = nslots_ - 1; s >= 0; --s) free_.push_back(s);
|
||||
}
|
||||
const int64_t keep_ns = int64_t(cfg_.before_s * 1e9);
|
||||
while (!sets_.empty() && !sets_.front().held && sets_.front().t_raw < t_raw - keep_ns) evict_front();
|
||||
|
||||
Set set;
|
||||
set.t_raw = t_raw, set.t_mono = t_mono, set.rec_set = rec_set, set.out = hands_json;
|
||||
set.held = pending_ && t_raw >= flag_t_ - keep_ns;
|
||||
auto crop = [&](const std::string &cam, int hand, const Roi &roi, bool ghost) -> int {
|
||||
const auto im = images.find(cam);
|
||||
if (im == images.end() || !im->second.data) return -1;
|
||||
int slot = take_slot();
|
||||
while (slot < 0 && !sets_.empty() && !sets_.front().held) evict_front(), slot = take_slot();
|
||||
if (slot < 0) return ++stats_.dropped, -1;
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
Crop c;
|
||||
c.cam = cam, c.hand = hand, c.ghost = ghost, c.slot = slot;
|
||||
c.g = crop_square(im->second, roi.center, cfg_.scale * roi.size, cfg_.crop_px, slot_ptr(slot));
|
||||
stats_.crop_us += std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count();
|
||||
++stats_.crop_calls, ++stats_.crops;
|
||||
stats_.ghosts += ghost;
|
||||
set.crops.push_back(std::move(c));
|
||||
return int(set.crops.size()) - 1;
|
||||
};
|
||||
for (const Seen &s : views) {
|
||||
View v;
|
||||
v.cam = s.cam, v.hand = s.hand;
|
||||
v.roi[0] = s.roi.center[0], v.roi[1] = s.roi.center[1], v.roi[2] = s.roi.size, v.roi[3] = s.roi.rotation;
|
||||
v.presence = s.lm.presence, v.right = s.lm.right;
|
||||
for (int k = 0; k < 21; ++k) v.lm[2 * k] = float(s.lm.pts[k][0]), v.lm[2 * k + 1] = float(s.lm.pts[k][1]);
|
||||
v.crop = crop(s.cam, s.hand, s.roi, false);
|
||||
set.views.push_back(v);
|
||||
last_[{s.cam, s.hand}] = {s.roi, t_raw};
|
||||
}
|
||||
// ghosts: views lost within ghost_s, cropped where they last were
|
||||
const int64_t ghost_ns = int64_t(cfg_.ghost_s * 1e9);
|
||||
int ghosts = 0;
|
||||
for (auto it = last_.begin(); it != last_.end();) {
|
||||
if (t_raw - it->second.t > ghost_ns) {
|
||||
it = last_.erase(it);
|
||||
continue;
|
||||
}
|
||||
if (it->second.t != t_raw && it->first.second != 0 && ghosts < cfg_.max_ghosts &&
|
||||
crop(it->first.first, it->first.second, it->second.roi, true) >= 0)
|
||||
++ghosts;
|
||||
++it;
|
||||
}
|
||||
sets_.push_back(std::move(set));
|
||||
++stats_.sets;
|
||||
if (pending_ && t_raw >= flag_t_ + int64_t(cfg_.after_s * 1e9)) complete();
|
||||
}
|
||||
|
||||
bool FlagBuffer::flag(const FlagRequest &req, int64_t t_raw, const std::string &extra_note) {
|
||||
if (pending_) {
|
||||
if (!extra_note.empty()) extra_notes_ += (extra_notes_.empty() ? "" : ", ") + json_string(extra_note);
|
||||
return false;
|
||||
}
|
||||
if (req.dir.empty()) return false;
|
||||
pending_ = true, req_ = req, flag_t_ = t_raw, extra_notes_.clear();
|
||||
dropped_at_flag_ = stats_.dropped;
|
||||
const int64_t keep_ns = int64_t(cfg_.before_s * 1e9);
|
||||
for (Set &s : sets_)
|
||||
if (s.t_raw >= flag_t_ - keep_ns) s.held = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
void FlagBuffer::tick(int64_t t_raw_now) {
|
||||
if (pending_ && t_raw_now >= flag_t_ + int64_t((cfg_.after_s + 0.5) * 1e9)) complete();
|
||||
}
|
||||
|
||||
void FlagBuffer::finish() {
|
||||
if (pending_) complete();
|
||||
}
|
||||
|
||||
void FlagBuffer::complete() {
|
||||
Dump d;
|
||||
d.req = req_, d.flag_t = flag_t_, d.first_unix = wall_now();
|
||||
d.dropped = stats_.dropped - dropped_at_flag_;
|
||||
if (!extra_notes_.empty()) d.req.fields += std::string(d.req.fields.empty() ? "" : ", ") + "\"more_notes\": [" + extra_notes_ + "]";
|
||||
auto first = std::find_if(sets_.begin(), sets_.end(), [](const Set &s) { return s.held; });
|
||||
for (auto it = first; it != sets_.end(); ++it) d.sets.push_back(std::move(*it));
|
||||
sets_.erase(first, sets_.end());
|
||||
pending_ = false;
|
||||
wait(); // one writer at a time (a flag takes 14 s; writing one well under that)
|
||||
writer_ = std::thread(&FlagBuffer::write, this, std::move(d));
|
||||
}
|
||||
|
||||
void FlagBuffer::write(Dump d) {
|
||||
// off the tracking cores, at the lowest priority: it's only files
|
||||
if (!cfg_.writer_cpus.empty()) {
|
||||
cpu_set_t set;
|
||||
CPU_ZERO(&set);
|
||||
for (int c : cfg_.writer_cpus) CPU_SET(c, &set);
|
||||
pthread_setaffinity_np(pthread_self(), sizeof set, &set);
|
||||
}
|
||||
setpriority(PRIO_PROCESS, pid_t(syscall(SYS_gettid)), 19);
|
||||
std::string err;
|
||||
const std::string &dir = d.req.dir;
|
||||
mkdir(dir.c_str(), 0700);
|
||||
struct stat st;
|
||||
if (stat(dir.c_str(), &st) != 0 || !S_ISDIR(st.st_mode) || st.st_uid != getuid()) err = "can't use " + dir;
|
||||
FILE *bin = err.empty() ? std::fopen((dir + "/crops.bin").c_str(), "wb") : nullptr;
|
||||
FILE *cj = err.empty() ? std::fopen((dir + "/crops.jsonl").c_str(), "w") : nullptr;
|
||||
FILE *sj = err.empty() ? std::fopen((dir + "/sets.jsonl").c_str(), "w") : nullptr;
|
||||
if (err.empty() && (!bin || !cj || !sj)) err = "can't write in " + dir;
|
||||
size_t k = 0, offset = 0, ghosts = 0;
|
||||
std::string line;
|
||||
for (size_t i = 0; i < d.sets.size(); ++i) {
|
||||
Set &s = d.sets[i];
|
||||
if (err.empty()) {
|
||||
std::vector<size_t> kk(s.crops.size());
|
||||
for (size_t j = 0; j < s.crops.size(); ++j) {
|
||||
const Crop &c = s.crops[j];
|
||||
const size_t bytes = size_t(c.g.w) * c.g.h;
|
||||
if (std::fwrite(slot_ptr(c.slot), 1, bytes, bin) != bytes) err = "write failed in " + dir;
|
||||
line.clear();
|
||||
appendf(line, "{\"k\": %zu, \"set\": %zu, \"cam\": %s, \"hand\": %d, \"ghost\": %s, \"x0\": %.3f, \"y0\": %.3f, "
|
||||
"\"scale\": %.5f, \"w\": %d, \"h\": %d, \"offset\": %zu, \"bytes\": %zu}\n",
|
||||
k, i, json_string(c.cam).c_str(), c.hand, c.ghost ? "true" : "false", c.g.x0, c.g.y0, c.g.scale, c.g.w,
|
||||
c.g.h, offset, bytes);
|
||||
std::fputs(line.c_str(), cj);
|
||||
kk[j] = k++, offset += bytes, ghosts += c.ghost;
|
||||
}
|
||||
line.clear();
|
||||
appendf(line, "{\"i\": %zu, \"t_raw_ns\": %lld, \"t_ns\": %lld", i, (long long)s.t_raw, (long long)s.t_mono);
|
||||
if (s.rec_set >= 0) appendf(line, ", \"rec_set\": %d", s.rec_set);
|
||||
if (!s.out.empty()) line += ", " + s.out;
|
||||
line += ", \"views\": [";
|
||||
for (size_t j = 0; j < s.views.size(); ++j) {
|
||||
const View &v = s.views[j];
|
||||
appendf(line, "%s{\"cam\": %s, \"hand\": %d, \"roi\": [%.2f, %.2f, %.2f, %.4f], \"presence\": %.3f, \"right\": %.3f, \"lm\": [",
|
||||
j ? ", " : "", json_string(v.cam).c_str(), v.hand, v.roi[0], v.roi[1], v.roi[2], v.roi[3], v.presence, v.right);
|
||||
for (int p = 0; p < 21; ++p) appendf(line, "%s[%.2f, %.2f]", p ? ", " : "", v.lm[2 * p], v.lm[2 * p + 1]);
|
||||
appendf(line, "], \"crop\": %lld}", v.crop >= 0 ? (long long)kk[size_t(v.crop)] : -1LL);
|
||||
}
|
||||
line += "], \"ghosts\": [";
|
||||
bool first = true;
|
||||
for (size_t j = 0; j < s.crops.size(); ++j)
|
||||
if (s.crops[j].ghost) {
|
||||
appendf(line, "%s{\"cam\": %s, \"hand\": %d, \"crop\": %zu}", first ? "" : ", ", json_string(s.crops[j].cam).c_str(),
|
||||
s.crops[j].hand, kk[j]);
|
||||
first = false;
|
||||
}
|
||||
line += "]}\n";
|
||||
std::fputs(line.c_str(), sj);
|
||||
}
|
||||
give_back(s.crops); // as it goes: the buffer gets its slots back
|
||||
s.crops.clear();
|
||||
}
|
||||
for (FILE *f : {bin, cj, sj})
|
||||
if (f && std::fclose(f) != 0 && err.empty()) err = "write failed in " + dir;
|
||||
if (err.empty()) {
|
||||
std::string m = "{\"version\": 1";
|
||||
if (!d.req.fields.empty()) m += ", " + d.req.fields;
|
||||
appendf(m, ", \"flag_t_raw_ns\": %lld, \"window\": {\"before_s\": %.2f, \"after_s\": %.2f, \"first_t_raw_ns\": %lld, "
|
||||
"\"last_t_raw_ns\": %lld}",
|
||||
(long long)d.flag_t, cfg_.before_s, cfg_.after_s, (long long)(d.sets.empty() ? 0 : d.sets.front().t_raw),
|
||||
(long long)(d.sets.empty() ? 0 : d.sets.back().t_raw));
|
||||
appendf(m, ", \"crop\": {\"scale\": %.3f, \"px\": %d, \"ghost_s\": %.2f}", cfg_.scale, cfg_.crop_px, cfg_.ghost_s);
|
||||
m += ", \"settings\": " + settings_json_ + ", \"cameras\": " + cameras_json_;
|
||||
appendf(m, ", \"counts\": {\"sets\": %zu, \"crops\": %zu, \"ghosts\": %zu, \"crops_dropped\": %zu, \"bytes\": %zu}", d.sets.size(), k,
|
||||
ghosts, d.dropped, offset);
|
||||
appendf(m, ", \"written_unix\": %.3f}\n", wall_now());
|
||||
const std::string tmp = dir + "/manifest.json.tmp";
|
||||
FILE *f = std::fopen(tmp.c_str(), "w");
|
||||
const bool ok = f && std::fputs(m.c_str(), f) >= 0;
|
||||
if (!f || std::fclose(f) != 0 || !ok || std::rename(tmp.c_str(), (dir + "/manifest.json").c_str()) != 0)
|
||||
err = "can't write " + dir + "/manifest.json";
|
||||
}
|
||||
std::lock_guard<std::mutex> l(mu_);
|
||||
if (err.empty()) ++stats_.flags, stats_.last_dir = dir, stats_.last_error.clear();
|
||||
else stats_.last_error = err;
|
||||
}
|
||||
|
||||
FlagBuffer::Stats FlagBuffer::stats() const {
|
||||
std::lock_guard<std::mutex> l(mu_);
|
||||
Stats s = stats_;
|
||||
s.slots_used = arena_ ? size_t(nslots_) - free_.size() : 0;
|
||||
return s;
|
||||
}
|
||||
|
||||
size_t FlagBuffer::bytes() const {
|
||||
size_t b = stats().slots_used * slot_bytes_;
|
||||
for (const Set &s : sets_) b += sizeof(Set) + s.out.capacity() + s.views.capacity() * sizeof(View) + s.crops.capacity() * sizeof(Crop);
|
||||
return b;
|
||||
}
|
||||
|
||||
std::string cameras_json(const std::map<std::string, Camera> &cams) {
|
||||
std::string s = "{";
|
||||
for (auto &[name, c] : cams) {
|
||||
appendf(s, "%s%s: {\"width\": %d, \"height\": %d, \"fx\": %.6f, \"fy\": %.6f, \"cx\": %.6f, \"cy\": %.6f, ", s.size() > 1 ? ", " : "",
|
||||
json_string(name).c_str(), c.width, c.height, c.fx, c.fy, c.cx, c.cy);
|
||||
appendf(s, "\"k\": [%.9g, %.9g, %.9g, %.9g], \"R\": [", c.k[0], c.k[1], c.k[2], c.k[3]);
|
||||
for (int r = 0; r < 3; ++r) appendf(s, "%s[%.9f, %.9f, %.9f]", r ? ", " : "", c.R[r][0], c.R[r][1], c.R[r][2]);
|
||||
appendf(s, "], \"origin\": [%.6f, %.6f, %.6f]}", c.origin[0], c.origin[1], c.origin[2]);
|
||||
}
|
||||
return s + "}";
|
||||
}
|
||||
|
||||
std::string output_json(const std::vector<const Hand *> &hands, const Pinch *pinch, const Pinch *middle, const Grip *grip) {
|
||||
std::string s = "\"hands\": [";
|
||||
for (size_t i = 0; i < hands.size(); ++i) {
|
||||
const Hand &h = *hands[i];
|
||||
appendf(s, "%s{\"id\": %d, \"side\": \"%s\", \"right_score\": %.3f, \"nviews\": %d, \"residual\": %.4f, \"scale\": %.3f, "
|
||||
"\"speed\": %.3f, \"fit\": %s, \"pts\": ",
|
||||
i ? ", " : "", h.id, h.right() ? "R" : "L", h.right_score, h.nviews, h.residual, h.scale, h.speed,
|
||||
h.fit.valid ? "true" : "false");
|
||||
points_json(s, h.pts, 21);
|
||||
s += ", \"pub\": ";
|
||||
points_json(s, h.fit.valid ? h.fit.pts : h.smooth, 21);
|
||||
s += '}';
|
||||
}
|
||||
s += ']';
|
||||
if (!pinch && !middle && !grip) return s;
|
||||
s += ", \"gestures\": {";
|
||||
bool first = true;
|
||||
auto sides = [&](const char *name, const fh_pinch_t &l, const fh_pinch_t &r) {
|
||||
appendf(s, "%s\"%s\": [{\"flags\": %u, \"d\": %.4f}, {\"flags\": %u, \"d\": %.4f}]", first ? "" : ", ", name, l.flags, l.distance,
|
||||
r.flags, r.distance);
|
||||
first = false;
|
||||
};
|
||||
if (pinch) sides("pinch", pinch->side(0), pinch->side(1));
|
||||
if (middle) sides("middle", middle->side(0), middle->side(1));
|
||||
if (grip) sides("grip", grip->side(0), grip->side(1));
|
||||
return s + "}";
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
// Flagging tracking failures (frame-hands notes/flag-failures.md has the plan and the format): a
|
||||
// rolling buffer, in RAM, of what's needed to relabel and diagnose the last few seconds of
|
||||
// tracking, and on a flag (`ft-handsctl flag [note]`, or a voice command through it), the buffer
|
||||
// and the next couple of seconds written to a folder for the offline tools (frame-hands'
|
||||
// train/flags).
|
||||
//
|
||||
// Per processed set it keeps, per view the tracker used, a mono crop around the tracker's
|
||||
// landmark crop: its centre, `scale` times its size, axis aligned (so it covers the rotated crop
|
||||
// with room to spare), downscaled to at most `crop_px`; with the crop's place in the image, so
|
||||
// labels made on it lift back to the full image and triangulate. A view the tracker lost is still
|
||||
// cropped where it was for `ghost_s` (a "ghost"), so the teacher can say whether the hand was there.
|
||||
// And ft-hands' output for the set (its hands and gestures, as JSON) and each view's crop and
|
||||
// landmarks. Nothing is written until a flag.
|
||||
//
|
||||
// The crops live in fixed slots of one arena (`max_bytes`), taken and given back through a free
|
||||
// list; pages are only touched as slots are used. Sets older than `before_s` are let go; when the
|
||||
// slots run out, the oldest set goes, and while a flag is waiting for its last seconds its sets
|
||||
// are held, so a crop that finds no free slot then is dropped (counted). A flag's sets leave the
|
||||
// buffer when it's complete, and a thread of their own writes them (at low priority, off the
|
||||
// tracking cores), giving the slots back as it goes.
|
||||
#pragma once
|
||||
|
||||
#include "calib.h"
|
||||
#include "tracker.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
class Pinch;
|
||||
class Grip;
|
||||
|
||||
struct FlagConfig {
|
||||
double before_s = 12; // kept before a flag
|
||||
double after_s = 2; // and taken after it
|
||||
double scale = 1.6; // the crop's side over the tracker's crop's
|
||||
double ghost_s = 1.0; // a lost view is still cropped where it was this long
|
||||
int crop_px = 224; // a crop's side at most (larger ones are downscaled)
|
||||
int max_ghosts = 4; // ghost crops per set at most
|
||||
size_t max_bytes = size_t(80) << 20; // the crops' arena
|
||||
std::vector<int> writer_cpus = {0, 1, 2, 3, 4}; // where the writer runs (empty: anywhere)
|
||||
};
|
||||
|
||||
// One crop's place: image pixel (centres at integers) of crop pixel (u, v) is
|
||||
// (x0 + (u + 0.5) * scale - 0.5, y0 + (v + 0.5) * scale - 0.5). Outside the image is 0.
|
||||
struct CropGeom {
|
||||
double x0 = 0, y0 = 0, scale = 1;
|
||||
int w = 0, h = 0;
|
||||
};
|
||||
|
||||
// The square of side `side` centred on `center`, axis aligned, downscaled to at most max_px a side,
|
||||
// into out (w * h bytes). Downscaled by more than 1.25, each pixel averages a 2 x 2 grid of taps
|
||||
// across its footprint; else the nearest pixel.
|
||||
CropGeom crop_square(const Image &img, V2 center, double side, int max_px, uint8_t *out);
|
||||
|
||||
// A flag's request: where it goes and what the manifest says about it besides the buffer's own
|
||||
// (`fields`: JSON members, "\"key\": value, ..." without braces, may be empty).
|
||||
struct FlagRequest {
|
||||
std::string dir; // exists, or is made
|
||||
std::string fields;
|
||||
};
|
||||
|
||||
class FlagBuffer {
|
||||
public:
|
||||
explicit FlagBuffer(const FlagConfig &cfg = {});
|
||||
~FlagBuffer(); // waits for the writer
|
||||
const FlagConfig &config() const { return cfg_; }
|
||||
|
||||
// The manifest's static parts, set once: the cameras (cameras_json) and ft-hands' settings
|
||||
// (a JSON object).
|
||||
void set_static(const std::string &cameras_json, const std::string &settings_json) {
|
||||
cameras_json_ = cameras_json, settings_json_ = settings_json;
|
||||
}
|
||||
// After each processed set: its capture time (t_raw: the cameras' clock, CLOCK_MONOTONIC_RAW;
|
||||
// t_mono: CLOCK_MONOTONIC), its index in a recording (-1 live), the images the tracker had, its
|
||||
// views this step (Tracker::views_now) and the set's output (hands_json: JSON members
|
||||
// "\"hands\": [...], \"gestures\": {...}", see output_json). Completes a waiting flag once
|
||||
// a set comes after_s past it.
|
||||
void add(int64_t t_raw, int64_t t_mono, int rec_set, const std::map<std::string, Image> &images,
|
||||
const std::vector<Seen> &views, const std::string &hands_json);
|
||||
// A flag at t_raw (the newest set's time, or now on that clock): keeps from before_s before it
|
||||
// and completes after_s after. False if a flag is already waiting (this one's note joins it:
|
||||
// `extra_note`) or the request is bad.
|
||||
bool flag(const FlagRequest &req, int64_t t_raw, const std::string &extra_note = "");
|
||||
// Completes a waiting flag if its time is up by the clock (no sets come while parked): call
|
||||
// now and then with the cameras' clock's now.
|
||||
void tick(int64_t t_raw_now);
|
||||
// Completes a waiting flag with what it has (stopping).
|
||||
void finish();
|
||||
bool waiting() const { return pending_; }
|
||||
// Waits for the writer.
|
||||
void wait();
|
||||
|
||||
struct Stats {
|
||||
size_t sets = 0, crops = 0, ghosts = 0;
|
||||
size_t slots_used = 0, slots = 0;
|
||||
size_t dropped = 0; // crops with no free slot
|
||||
size_t flags = 0; // written
|
||||
double crop_us = 0; // summed crop time, microseconds
|
||||
size_t crop_calls = 0;
|
||||
std::string last_dir, last_error;
|
||||
};
|
||||
Stats stats() const;
|
||||
// RAM the buffer holds now: the slots in use (their pages) and the sets' records.
|
||||
size_t bytes() const;
|
||||
|
||||
private:
|
||||
struct Crop {
|
||||
std::string cam;
|
||||
int hand = 0;
|
||||
bool ghost = false;
|
||||
CropGeom g;
|
||||
int slot = -1;
|
||||
};
|
||||
struct View {
|
||||
std::string cam;
|
||||
int hand = 0;
|
||||
double roi[4] = {};
|
||||
double presence = 0, right = 0;
|
||||
float lm[42] = {};
|
||||
int crop = -1; // into the set's crops
|
||||
};
|
||||
struct Set {
|
||||
int64_t t_raw = 0, t_mono = 0;
|
||||
int rec_set = -1;
|
||||
std::string out;
|
||||
std::vector<View> views;
|
||||
std::vector<Crop> crops;
|
||||
bool held = false;
|
||||
};
|
||||
struct Dump {
|
||||
FlagRequest req;
|
||||
std::vector<Set> sets;
|
||||
int64_t flag_t = 0;
|
||||
double first_unix = 0;
|
||||
size_t dropped = 0;
|
||||
};
|
||||
int take_slot();
|
||||
void give_back(const std::vector<Crop> &crops);
|
||||
void evict_front();
|
||||
void complete();
|
||||
void write(Dump d);
|
||||
uint8_t *slot_ptr(int slot) { return arena_.get() + size_t(slot) * slot_bytes_; }
|
||||
|
||||
FlagConfig cfg_;
|
||||
std::string cameras_json_ = "{}", settings_json_ = "{}";
|
||||
size_t slot_bytes_ = 0;
|
||||
int nslots_ = 0;
|
||||
std::unique_ptr<uint8_t[]> arena_; // made at the first set; untouched pages cost nothing
|
||||
mutable std::mutex mu_; // free_ and the stats the writer changes
|
||||
std::vector<int> free_;
|
||||
std::deque<Set> sets_;
|
||||
// where each camera's view of each hand last was, for ghosts
|
||||
struct Last {
|
||||
Roi roi;
|
||||
int64_t t = 0;
|
||||
};
|
||||
std::map<std::pair<std::string, int>, Last> last_;
|
||||
bool pending_ = false;
|
||||
FlagRequest req_;
|
||||
int64_t flag_t_ = 0;
|
||||
size_t dropped_at_flag_ = 0;
|
||||
std::string extra_notes_;
|
||||
std::thread writer_;
|
||||
Stats stats_;
|
||||
};
|
||||
|
||||
// The calibrated cameras as the manifest has them (frame-hands notes/flag-failures.md).
|
||||
std::string cameras_json(const std::map<std::string, Camera> &cams);
|
||||
// A set's output for FlagBuffer::add: the hands (id, side, scores, measured and published points)
|
||||
// and, if given, the gestures' state per side.
|
||||
std::string output_json(const std::vector<const Hand *> &hands, const Pinch *pinch, const Pinch *middle, const Grip *grip);
|
||||
// s as a JSON string ("..." with escapes); "null" when null_if_empty and s is empty.
|
||||
std::string json_string(const std::string &s, bool null_if_empty = false);
|
||||
+57
-11
@@ -122,16 +122,55 @@ std::string run_dir() {
|
||||
bool Publisher::open(std::string &err) {
|
||||
const std::string path = run_dir() + "/hands";
|
||||
const int fd = ::open(path.c_str(), O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0600);
|
||||
if (fd < 0 || ftruncate(fd, sizeof(fh_hands_t)) < 0) return err = path + ": " + std::strerror(errno), false;
|
||||
void *m = mmap(nullptr, sizeof(fh_hands_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
|
||||
if (fd < 0 || ftruncate(fd, sizeof(fh_hands_v2_t)) < 0) return err = path + ": " + std::strerror(errno), false;
|
||||
void *m = mmap(nullptr, sizeof(fh_hands_v2_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
|
||||
close(fd);
|
||||
if (m == MAP_FAILED) return err = path + ": can't map it", false;
|
||||
out_ = static_cast<fh_hands_t *>(m);
|
||||
std::memset(out_, 0, sizeof *out_);
|
||||
use(static_cast<fh_hands_v2_t *>(m));
|
||||
return true;
|
||||
}
|
||||
|
||||
void Publisher::use(fh_hands_v2_t *mem) {
|
||||
file_ = mem;
|
||||
out_ = &file_->v1;
|
||||
std::memset(file_, 0, sizeof *file_);
|
||||
std::memcpy(out_->magic, FH_HANDS_MAGIC, 8);
|
||||
out_->version = FH_HANDS_VERSION;
|
||||
out_->size = sizeof(fh_hands_t);
|
||||
return true;
|
||||
out_->size = sizeof(fh_hands_v2_t);
|
||||
}
|
||||
|
||||
static_assert(sizeof(fh_hand_fit_t::angles) / sizeof(float) == skel::kAngles, "fh_hand_fit_t angles");
|
||||
|
||||
void Publisher::fill_fit(const Hand &h, uint64_t capture_ns, fh_hand_fit_t &o) {
|
||||
std::memset(&o, 0, sizeof o);
|
||||
o.id = uint32_t(h.id);
|
||||
const skel::Fit &f = h.fit;
|
||||
if (!f.valid) return;
|
||||
auto put = [](float *out, V3 v) {
|
||||
for (int k = 0; k < 3; ++k) out[k] = float(v[k]);
|
||||
};
|
||||
o.flags = FH_FIT_VALID | FH_FIT_ELBOW_HEAD_UP | (f.side > 0 ? FH_FIT_RIGHT : 0) | (f.settled >= 1 ? FH_FIT_SETTLED : 0) |
|
||||
(f.flipped ? FH_FIT_FLIPPED : 0);
|
||||
o.tracked_ns = capture_ns;
|
||||
for (int i = 0; i < 21; ++i) {
|
||||
put(o.joints[i].p, f.pts[i]);
|
||||
o.joints[i].radius = float(f.radius[i]);
|
||||
double q[4];
|
||||
skel::to_quat(f.frames[i], q);
|
||||
for (int k = 0; k < 4; ++k) o.joints[i].q[k] = float(q[k]);
|
||||
}
|
||||
for (int b = 0; b < 20; ++b) o.bone_len[b] = float(f.len[b]);
|
||||
for (int a = 0; a < skel::kAngles; ++a) o.angles[a] = float(f.qf[a]);
|
||||
put(o.elbow, f.elbow);
|
||||
o.elbow_conf = 0;
|
||||
put(o.pinch_point, (f.pts[5] + f.pts[9]) * 0.5);
|
||||
put(o.contact, (f.pts[4] + f.pts[8]) * 0.5);
|
||||
o.pinch_d[0] = float(norm(f.pts[4] - f.pts[8]));
|
||||
o.pinch_d[1] = float(norm(f.pts[4] - f.pts[12]));
|
||||
o.fit_rms = float(f.rms);
|
||||
o.settled = float(f.settled);
|
||||
put(o.vel_head, f.vel);
|
||||
put(o.angvel_head, f.angvel);
|
||||
}
|
||||
|
||||
void Publisher::write(const std::vector<const Hand *> &in, uint64_t capture_ns) {
|
||||
@@ -146,22 +185,29 @@ void Publisher::write(const std::vector<const Hand *> &in, uint64_t capture_ns)
|
||||
std::memset(&o, 0, sizeof o);
|
||||
if (k >= hands.size()) continue;
|
||||
const Hand &h = *hands[k];
|
||||
// the fitted skeleton's points when there is one (fingers keep their length), else the
|
||||
// filtered landmarks (ft-hands --skeleton 0)
|
||||
const V3 *pts = h.fit.valid ? h.fit.pts : h.smooth;
|
||||
o.id = uint32_t(h.id);
|
||||
o.flags = (h.right() ? FH_HAND_RIGHT : 0) | (h.nviews >= 2 ? FH_HAND_STEREO : 0);
|
||||
o.confidence = float(std::min(1.0, h.frames / 5.0));
|
||||
for (int i = 0; i < 21; ++i)
|
||||
for (int j = 0; j < 3; ++j) o.pts[i][j] = float(h.smooth[i][j]);
|
||||
for (int j = 0; j < 3; ++j) o.pts[i][j] = float(pts[i][j]);
|
||||
const uint32_t first = nc;
|
||||
for (auto &b : kThumb) put(out_->capsules, nc, h.smooth[b[0]], h.smooth[b[1]], kThumbR, kThumbR);
|
||||
for (auto &b : kFingers) put(out_->capsules, nc, h.smooth[b[0]], h.smooth[b[1]], kFinger, kFinger);
|
||||
for (auto &b : kPalm) put(out_->capsules, nc, h.smooth[b[0]], h.smooth[b[1]], kPalmR, kPalmR);
|
||||
for (auto &b : kThumb) put(out_->capsules, nc, pts[b[0]], pts[b[1]], kThumbR, kThumbR);
|
||||
for (auto &b : kFingers) put(out_->capsules, nc, pts[b[0]], pts[b[1]], kFinger, kFinger);
|
||||
for (auto &b : kPalm) put(out_->capsules, nc, pts[b[0]], pts[b[1]], kPalmR, kPalmR);
|
||||
// the forearm carries on from the hand's own axis (middle knuckle -> wrist); the
|
||||
// wrist bends, but much less than a guess at where the elbow is gets wrong
|
||||
const V3 wrist = h.smooth[0], d = wrist - h.smooth[9];
|
||||
const V3 wrist = pts[0], d = wrist - pts[9];
|
||||
const double n = norm(d);
|
||||
if (n > 0.02) put(out_->capsules, nc, wrist, wrist + d * (kArmLen / n), kArm[0], kArm[1]);
|
||||
o.ncapsules = nc - first;
|
||||
}
|
||||
for (size_t k = 0; k < FH_HANDS_MAX_HANDS; ++k) {
|
||||
if (k < hands.size()) fill_fit(*hands[k], capture_ns, file_->fits[k]);
|
||||
else std::memset(&file_->fits[k], 0, sizeof file_->fits[k]);
|
||||
}
|
||||
for (uint32_t k = nc; k < FH_HANDS_MAX_CAPSULES; ++k) std::memset(&out_->capsules[k], 0, sizeof(fh_capsule_t));
|
||||
out_->capture_ns = capture_ns;
|
||||
out_->publish_ns = mono_ns();
|
||||
|
||||
@@ -35,9 +35,14 @@ private:
|
||||
class Publisher {
|
||||
public:
|
||||
bool open(std::string &err);
|
||||
// Writes into `mem` instead of the hands file (ft-handreplay --publish-dump).
|
||||
void use(fh_hands_v2_t *mem);
|
||||
void write(const std::vector<const Hand *> &hands, uint64_t capture_ns);
|
||||
// Fills one hand's version 2 record (also for ft-handreplay's checks).
|
||||
static void fill_fit(const Hand &h, uint64_t capture_ns, fh_hand_fit_t &o);
|
||||
|
||||
private:
|
||||
fh_hands_v2_t *file_ = nullptr;
|
||||
fh_hands_t *out_ = nullptr;
|
||||
uint64_t seq_ = 0;
|
||||
};
|
||||
|
||||
Loaded 100 of 308 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user