mirror of
https://github.com/saphid/frame-control.git
synced 2026-10-24 10:02:26 +02:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fa40e30f3c | ||
|
|
d7a887b98c | ||
|
|
a5980d8f98 |
No files matched your search
@@ -50,7 +50,7 @@ Charge, charging watts and time left, storage, memory, temperature, Wi-Fi, and w
|
||||
<td valign="top">
|
||||
|
||||
**🎮 Steam games**<br>
|
||||
Everything you own with its Steam Frame rating. Install onto the headset with live progress, and search the store.
|
||||
Everything you own with its Steam Frame rating. Install onto the headset with live progress, search the store, and force quit a game that stops responding.
|
||||
|
||||
</td>
|
||||
<td valign="top">
|
||||
@@ -69,8 +69,8 @@ Drag files onto the window to send them. Drop a game's .zip, folder or .exe to a
|
||||
</td>
|
||||
<td valign="top">
|
||||
|
||||
**📸 Screenshots and recordings**<br>
|
||||
Browse the shots you take in the headset and save them to your Pictures folder. Record what the headset shows, with its sound, or export Steam's clips at any length, as .mp4 files in your Videos folder ([not tested on a headset yet](docs/recording.md)).
|
||||
**📸 Screenshots**<br>
|
||||
Browse the shots you take in the headset and save them to your Pictures folder.
|
||||
|
||||
**⌨️ Keyboard and trackpad**<br>
|
||||
Type and point in the Frame's apps from your computer or phone, through KDE Connect, which Frame Control brings along and sets up on the Frame. Nothing else to install, anywhere.
|
||||
|
||||
+13
-4
@@ -49,15 +49,18 @@ counts them while they run.
|
||||
gamescope's flat layer instead.
|
||||
- **Screenshots** you take in the headset with Steam's shortcut: browse them and
|
||||
save them to `~/Pictures/SteamFrame`.
|
||||
- **Record** what the headset shows, with its sound, to an `.mp4` in
|
||||
`~/Videos/SteamFrame`, and **Steam clips**: export clips and background
|
||||
recordings from Steam's game recording at any length, without re-encoding.
|
||||
See [recording.md](recording.md). Not tested on a headset yet.
|
||||
- **Battery** with charging state: charge rate in watts, time to full or empty,
|
||||
charger type and wattage (for example USB-C PD 20 W), and battery temperature.
|
||||
- **Status**: storage, memory, temperature, Wi-Fi, uptime, and whether SteamVR,
|
||||
the desktop, Lepton and xrdp are running.
|
||||
- **Library** shelf with Steam cover art and a Play button (`steam://rungameid`).
|
||||
- **Force quit** a game that has stopped responding: Steam games, sideloaded
|
||||
titles, non-Steam shortcuts and Android apps. **Running now** at the top of
|
||||
Games lists what's running; each game's own **Force quit…** (on its library
|
||||
tile, or in a sideloaded title's ⋯ menu) and the Control Center's **Force quit
|
||||
a game** card do the same. Each asks first, because unsaved progress is lost.
|
||||
Steam is asked to quit the game, then its processes get SIGTERM and SIGKILL;
|
||||
see [steam-games.md](steam-games.md#force-quitting-a-running-game).
|
||||
- **Get games**: every game you own with its Steam Frame rating (Verified,
|
||||
Playable, Unsupported, Unknown). Install on Frame downloads it to the headset
|
||||
with live progress. Search the Steam store with prices and Frame ratings; Buy
|
||||
@@ -131,6 +134,12 @@ GPU time is render time, not GPU utilisation. The temperature is the hottest
|
||||
readable sensor. Thermal trip warnings use per-zone kernel hot/critical limits,
|
||||
not a guessed universal temperature threshold.
|
||||
|
||||
**Force quit a game** lists what's running only when you choose **Check what's
|
||||
running**, and says so when nothing is. Each **Force quit…** names the game and
|
||||
warns that unsaved progress will be lost before anything is sent; it uses the
|
||||
selected headset, refuses a second quit while one is running, and drops the
|
||||
list when you switch headsets.
|
||||
|
||||
**Audio** controls the default output sink through the existing `/api/volume`
|
||||
endpoint. Moving its slider prepares a value; **Apply volume** sends it. **Mute**
|
||||
and **Unmute** send explicit mute states. The UI captures the selected headset,
|
||||
|
||||
@@ -1,120 +0,0 @@
|
||||
# Recording and Steam clips
|
||||
|
||||
Frame Control can record what the headset shows, with its sound, and save it as
|
||||
an `.mp4` on your computer. It can also export the clips and background
|
||||
recordings from Steam's own game recording, at any length, as one `.mp4` each.
|
||||
Both are on **Tools → Capture & Live**. Everything is saved to
|
||||
`~/Videos/SteamFrame`, next to the screenshots in `~/Pictures/SteamFrame`.
|
||||
Nothing needs installing on the computer or on the Frame: the work is done by
|
||||
the `ffmpeg` that SteamOS ships.
|
||||
|
||||
**Not tested on a headset yet.** This is built from what the code already does
|
||||
on the Frame (the live view, the media player) and from how Steam is reported
|
||||
to store its recordings. The parts we're least sure of are listed under
|
||||
[What hasn't been checked](#what-hasnt-been-checked). Please report what you see.
|
||||
|
||||
## Record
|
||||
|
||||
Press **Record** next to **Live**. The button turns into **Stop**, and a line
|
||||
under the viewer counts the time. Press **Stop**: the recording is finished on
|
||||
the Frame, converted to `.mp4` there (without re-encoding) and copied to
|
||||
`~/Videos/SteamFrame/rec-<date>-<time>.mp4`. The line says when it's saved.
|
||||
|
||||
- **What's in it**: the same picture as **Live**, SteamVR's copy of the headset
|
||||
view (one undistorted 1920×1080 eye, from `/dev/video99`), at 30 fps and
|
||||
8 Mbit/s, encoded with x264 (the Frame's hardware encoder crashes `ffmpeg`).
|
||||
The sound is what the headset plays: the monitor of PipeWire's default
|
||||
output, read through its PulseAudio server (`-f pulse -i @DEFAULT_MONITOR@`).
|
||||
The microphone isn't recorded.
|
||||
- **Without sound**: before each recording Frame Control checks for a fraction
|
||||
of a second that `ffmpeg` can read that audio. If it can't, the recording goes
|
||||
ahead as video only, and the page and the saved message say so.
|
||||
- **Limits**: a recording stops by itself after 20 minutes and is saved as if
|
||||
you'd pressed Stop. It needs about 2.9 GB free on the Frame to start (room for
|
||||
a full-length recording twice, while it's converted), and checks the space on
|
||||
your computer before copying. One recording runs at a time.
|
||||
- **Where it waits on the Frame**: `~/.cache/frame-control/video/`, not `/tmp`,
|
||||
which is a RAM disk on SteamOS. It's deleted once copied.
|
||||
- **If the connection drops or the app quits** while recording, the Frame
|
||||
stops `ffmpeg` cleanly when the SSH channel closes, as the live view does. A
|
||||
recording that was never copied is deleted when the next one starts.
|
||||
|
||||
Recording and **Live** can run together; both read the same device.
|
||||
|
||||
## Steam clips
|
||||
|
||||
**Steam clips** lists what Steam's game recording has kept on the Frame: saved
|
||||
clips and background recordings, newest first, with the game, length and size.
|
||||
**Export** joins one into a single `.mp4` in `~/Videos/SteamFrame`, named after
|
||||
its folder (for example `clip_620_20261020_202134.mp4`), however long it is.
|
||||
Steam's own export is reported to stop at about 60 seconds. Exports run in the
|
||||
background; ones already on your computer are marked.
|
||||
|
||||
How it works: Steam keeps each recording as MPEG-DASH segments, one folder per
|
||||
recording session.
|
||||
|
||||
```
|
||||
~/.local/share/Steam/userdata/<account>/gamerecordings/
|
||||
video/bg_<appid>_<YYYYMMDD>_<HHMMSS>/ background recording
|
||||
clips/clip_<appid>_<YYYYMMDD>_<HHMMSS>/video/bg_<...>/ a saved clip
|
||||
session.mpd
|
||||
init-stream0.m4s chunk-stream0-00001.m4s chunk-stream0-00002.m4s ...
|
||||
init-stream1.m4s chunk-stream1-00001.m4s ...
|
||||
```
|
||||
|
||||
Each stream's `init-stream` segment followed by its chunks, in number order, is
|
||||
a playable fragmented MP4 of that stream. On the Frame, `ui/frame_clips.py`
|
||||
builds those files and has `ffmpeg` put the video and audio into one `.mp4`
|
||||
with `-c copy`, so nothing is re-encoded and it takes seconds. The result is
|
||||
copied to the computer and deleted from the Frame. The export needs free space
|
||||
on the Frame of about twice the recording's size while it runs.
|
||||
|
||||
The listing doesn't rely on the folder names: any folder under `clips/` or
|
||||
`video/` (up to four levels down) holding `init-stream*.m4s` counts. A stream
|
||||
missing its init segment or its chunks is left out. Missing chunk numbers are
|
||||
shown as "pieces missing"; the rest still exports.
|
||||
|
||||
## For developers
|
||||
|
||||
`ui/frame_clips.py` holds the logic, so other features (such as syncing clips
|
||||
automatically) can reuse it:
|
||||
|
||||
- `list_clips(run_frame)` and `export_clip(id, run_frame, run, fetch)` are the
|
||||
computer's side; the server passes how to reach the Frame.
|
||||
- `list_recordings(userdata)` and `export(userdata, id)` are the Frame's side,
|
||||
run as `python3 - list` / `python3 - export ID` with the file on stdin.
|
||||
- `Recorder` runs one recording from Start to the copy.
|
||||
- `parse_id` checks a clip id (`<account>/<clips|video>/<folder>...`, plain
|
||||
names only, no `.` or `..`) before it reaches a path or a shell.
|
||||
|
||||
The API, with the same guards as every other request:
|
||||
|
||||
| Request | Does |
|
||||
|---|---|
|
||||
| `GET /api/record` | The recording's state: `idle`, `starting`, `recording` (with `elapsed`, `audio`, `limit`), `stopping`, `saving`, `saved` (with `file`) or `failed` (with `error`) |
|
||||
| `POST /api/record {"action": "start"\|"stop"}` | Start or stop |
|
||||
| `GET /api/clips` | Steam's recordings on the Frame, each with `saved` |
|
||||
| `POST /api/clips/export {"id"}` | Starts an export; poll `/api/job` |
|
||||
| `POST /api/open {"what": "videos"}` | Opens `~/Videos/SteamFrame` |
|
||||
|
||||
They aren't available when the server runs on the Frame itself (the iPhone
|
||||
app), since they save to a computer.
|
||||
|
||||
Tests: `tests/test_clips.py`. They run the recording's shell under bash with a
|
||||
stand-in `ffmpeg`, so Stop, the time limit and the clean-up are tested as they
|
||||
run on the Frame. Where `ffmpeg` is installed, they also make a 65-second DASH
|
||||
recording with Steam's file names and export it with the real `ffmpeg`.
|
||||
|
||||
## What hasn't been checked
|
||||
|
||||
None of this has run on a Steam Frame yet. In particular:
|
||||
|
||||
- That SteamOS's `ffmpeg` can read `@DEFAULT_MONITOR@`. It has the PulseAudio
|
||||
output device (the media player plays through it), so the input is expected,
|
||||
but if it fails the recording is video only, as above.
|
||||
- Audio and video sync. Both inputs are stamped with the wall clock, because
|
||||
the camera device and the audio server otherwise count from different clocks.
|
||||
- The exact layout of `gamerecordings` on the Frame's SteamOS build, and
|
||||
whether a clip's segments start mid-recording. The parser is deliberately
|
||||
loose about the layout.
|
||||
- How much x264 at 1080p30 costs the Frame while a game is running.
|
||||
+2
-1
@@ -30,7 +30,8 @@ it.) A dialog shows:
|
||||
|
||||
Install copies it to the Frame and registers it with Steam; progress shows in
|
||||
the bar and the activity log. **Sideloaded titles** lists what's installed,
|
||||
with Launch and Remove. **Copy to ~/Downloads instead** keeps the old
|
||||
with Launch, Remove and, for a game that has stopped responding, **Force
|
||||
quit…** in its ⋯ menu ([how](steam-games.md#force-quitting-a-running-game)). **Copy to ~/Downloads instead** keeps the old
|
||||
behaviour for a zip that isn't a game.
|
||||
|
||||
From a terminal:
|
||||
|
||||
@@ -101,6 +101,62 @@ Store search uses `store.steampowered.com/api/storesearch/?term=…&cc=…`. It
|
||||
returns nothing without `cc`, so Frame Control takes the country from
|
||||
`SteamClient.User.GetIPCountry()` on the Frame.
|
||||
|
||||
## Force quitting a running game
|
||||
|
||||
**Running now**, at the top of Games, lists what's running on the Frame: Steam
|
||||
games, sideloaded titles, non-Steam shortcuts and Android apps. A game's library
|
||||
tile, a sideloaded title's ⋯ menu and the Control Center's **Force quit a game**
|
||||
card have **Force quit…** too. Each asks first ("Unsaved progress will be
|
||||
lost"); from a game's own menu it checks that the game is running and says so if
|
||||
it isn't. SteamVR (app 250820, and its beta 1009850) is never listed or quit:
|
||||
on the Frame it shows the headset view, so quitting it isn't a way out of a game.
|
||||
|
||||
`ui/frame_running.py` does the work on the Frame, piped over SSH with
|
||||
`frame_steam.py` as its DevTools client:
|
||||
|
||||
```sh
|
||||
scp ui/frame_steam.py ui/frame_running.py frame:/tmp/
|
||||
ssh frame 'python3 /tmp/frame_running.py list' # {"running": [{appid, gameid, name, kind, ...}]}
|
||||
ssh frame 'python3 /tmp/frame_running.py quit 620' # {"name", "method", "message"}
|
||||
```
|
||||
|
||||
1. **What's running.** Steam starts every game, shortcut and devkit title under
|
||||
its `reaper`, as `reaper SteamLaunch AppId=<id> -- <command>`, and the reaper
|
||||
stays the parent of the game's processes. So a running game is one of your
|
||||
own processes whose program is named `reaper`, with `SteamLaunch` and an
|
||||
`AppId=` before `--`; the game is that reaper's process tree. Steam's own list
|
||||
(`SteamUIStore.RunningApps`) and Android apps whose Lepton container is up
|
||||
(`podman ps`) are added. Names come from `appStore`, else the app manifest,
|
||||
the Android app's `meta.json` or the devkit title's folder.
|
||||
2. **Steam first.** `SteamClient.Apps.TerminateApp(<game id>, false)`, the
|
||||
call Steam's own Stop makes for Android apps ([vr-apks.md](vr-apks.md)). The
|
||||
game id is the appid, or `(appid << 32) | 0x02000000` for a non-Steam
|
||||
shortcut. An Android app's container is also stopped, as the Apps tab's Stop
|
||||
does (`podman stop -t 5 lepton-steamlaunch-<instance>`).
|
||||
3. **Then signals.** If the game's processes are still there after 5 seconds,
|
||||
they get SIGTERM, deepest first; whatever is left 3 seconds later gets
|
||||
SIGKILL, the reaper last, so nothing it holds is orphaned unsignalled. A pid
|
||||
is only signalled while its start time still matches, so a reused pid is safe.
|
||||
|
||||
Nothing is found by name. These are never signalled, even inside a game's tree:
|
||||
init, the helper itself and every process above it (the SSH session), other
|
||||
users' processes, and anything named `steam`, `steamwebhelper`, `gamescope`,
|
||||
`gamescope-wl`, `gamescopereaper`, `gamescope-session`, `sshd`, `sshd-session`,
|
||||
`ssh-agent`, `systemd`, `dbus-daemon`, `dbus-broker`, `pipewire`,
|
||||
`pipewire-pulse`, `wireplumber`, `plasmashell`, `kwin_wayland`, `kwin_x11`,
|
||||
`Xwayland`, `sddm`, `vrserver`, `vrcompositor`, `vrmonitor`, `vrdashboard`,
|
||||
`vrwebhelper` or `vrstartup`, with everything under them.
|
||||
|
||||
**Not tested on a headset.** The reaper command line is how Steam launches games
|
||||
on Linux desktops and the Steam Deck, **inferred** for the Frame.
|
||||
`SteamUIStore.RunningApps` comes from Steam's client code as plugin loaders use
|
||||
it and hasn't been seen on the Frame's build; without it, the reapers alone
|
||||
decide. `TerminateApp` with a shortcut's game id is the call Steam's Stop was
|
||||
seen making for an Android app (docs/vr-apks.md); for Steam games it is
|
||||
**inferred**. Unit tests (`tests/test_force_quit.py`) cover the parsing, the
|
||||
process selection and the escalation; the fake Frame launches its games under a
|
||||
stand-in `reaper` so `tests/e2e/test_running.py` force quits a real process tree.
|
||||
|
||||
## Not yet checked
|
||||
|
||||
- Free-to-play games: `steam://install` should stop at state 3 (free license)
|
||||
|
||||
+13
-2
@@ -76,8 +76,8 @@ its guards want.
|
||||
| `sshd` with key and password logins, `rsync`, `python3` | Real |
|
||||
| Valve's steamos-devkit-service on port 32000 and its hooks, vendored unmodified in `tests/fakeframe/steamos-devkit-service` | Real; only its `dbus` import (for mDNS through systemd-resolved) is a stand-in that logs the registration |
|
||||
| Valve's devkit-utils, copied over by Frame Control itself | Real |
|
||||
| **fakesteam**: `~/.steam/steam.pid`, `steam.token` and the `steam.pipe` FIFO; answers `approve-ssh-key`, `create-shortcut`, `run-game`, `list-shortcuts` and `delete-shortcut` with the response files devkit-utils waits for; takes `steam://rungameid`, `install` and `store` URLs | Fake |
|
||||
| DevTools on `127.0.0.1:8080` with a `SharedJSContext` target. The JavaScript Frame Control sends runs for real in Node against stand-in `SteamClient`, `appStore` and `downloadsStore` objects (`cef_shim.js`), so async functions, optional chaining and `Map`s behave as in Steam's CEF | The JS engine is real; the objects are fake |
|
||||
| **fakesteam**: `~/.steam/steam.pid`, `steam.token` and the `steam.pipe` FIFO; answers `approve-ssh-key`, `create-shortcut`, `run-game`, `list-shortcuts` and `delete-shortcut` with the response files devkit-utils waits for; takes `steam://rungameid`, `install` and `store` URLs. Games it really runs start under a stand-in `reaper SteamLaunch AppId=<id> -- <command>` (bash with that command line), so force quit finds a real process tree | Fake |
|
||||
| DevTools on `127.0.0.1:8080` with a `SharedJSContext` target. The JavaScript Frame Control sends runs for real in Node against stand-in `SteamClient`, `appStore` and `downloadsStore` objects (`cef_shim.js`), so async functions, optional chaining and `Map`s behave as in Steam's CEF. `SteamUIStore.RunningApps` lists launches that haven't exited; `TerminateApp` ends only launches that never ran a process, so a running program needs Frame Control's signals | The JS engine is real; the objects are fake |
|
||||
| `steam`, `wpctl`, `flatpak`, `podman`, `nmcli`, `qdbus6`, `gamescopectl`, SteamOS's `steamos-enable-sshd` helper, and Lepton's launcher | Stubs that record their calls |
|
||||
| Battery, charger and thermal zones under `/sys/class` | Files the supervisor writes. `/sys` is read-only in a container and Docker's AppArmor profile refuses writes under it, so each folder is a volume mounted twice: over `/sys/class/...` for `frame_status.py` to read, and under `/var/lib/fakeframe/sys` for the supervisor to write |
|
||||
| `vrserver` and `plasmashell` | Renamed `sleep` processes, so the status page and the clipboard find them |
|
||||
@@ -267,6 +267,17 @@ connect it to the Frame and follow Remote Desktop through to the Frame's
|
||||
desktop ([what it does](streaming.md#a-see-and-control-the-frame-from-the-mac)).
|
||||
`frame-key` left `authorized_keys` byte-for-byte as it was.
|
||||
|
||||
## Force quit
|
||||
|
||||
`tests/test_force_quit.py` feeds `ui/frame_running.py` made-up process tables:
|
||||
the `reaper SteamLaunch AppId=` parsing, naming from Steam, manifests, Android
|
||||
`meta.json` and devkit folders, and a Frame's worth of Steam, gamescope, SteamVR,
|
||||
sshd and session processes that must never be signalled. Processes that ignore
|
||||
SIGTERM, survive SIGKILL or exit and have their pid reused check the escalation.
|
||||
The Control Center's confirmation, duplicate and headset-switch handling run in
|
||||
`tests/control_center.cjs`. `tests/e2e/test_running.py` force quits real process
|
||||
trees on the fake Frame. None of it has run on a headset.
|
||||
|
||||
## Owned media player
|
||||
|
||||
`tests/test_media.py` covers layout evidence and overrides, OU eye ordering,
|
||||
|
||||
@@ -64,11 +64,11 @@ function sharedPage({productionApi=false} = {}) {
|
||||
const request=deferred();request.path=path;request.opts=opts;requests.push(request);return request.promise;
|
||||
};
|
||||
Object.assign(context,{renderPill(){},renderConnDlg(){},renderBanner(){},viaText(){},netLabel(){},
|
||||
padReset(){},ctrlReset(){},resetShots(){},resetClips(){},closeDevPop(){},loadDevices(){},renderDevices(){},renderTests(){},reloadAll(){},checkContactPrompt(){}});
|
||||
padReset(){},ctrlReset(){},resetShots(){},closeDevPop(){},loadDevices(){},renderDevices(){},renderTests(){},reloadAll(){},checkContactPrompt(){}});
|
||||
vm.runInContext(`const UI_KEY = 'test-only';
|
||||
const link = {s:null,device:'frame-a',phase:'connected',rev:0,net:null};
|
||||
const disp = {}, gm = {seq:0}, cat = {}, wi = {}, sourceState = {jobs:new Map(),detail:null,detailRequest:0};
|
||||
let viewGen = 0, lastImg = null, lastShot = null, androidApps = [], androidSeq = 0, titlesSeq = 0, page = 'control';
|
||||
let viewGen = 0, lastImg = null, lastShot = null, androidApps = [], androidSeq = 0, titlesSeq = 0, runningGames = [], runningSeq = 0, page = 'control';
|
||||
const androidPending = new Set();`,context);
|
||||
const apiStart=pageSource.indexOf('const HEADSET_FREE ='),apiEnd=pageSource.indexOf('// What a panel shows',apiStart);
|
||||
const onlineStart=pageSource.indexOf('function setOnline('),onlineEnd=pageSource.indexOf('function reloadAll()',onlineStart);
|
||||
@@ -449,3 +449,67 @@ test('every Control Center workflow reaches its intentional workspace', () => {
|
||||
}
|
||||
assert.equal(f.run('PAGES.length'),4);
|
||||
});
|
||||
// Force quit: an explicit check, a confirmation naming the game, and the captured headset.
|
||||
function quitPage({confirmAnswer=true, running=[{appid:620,name:'Portal <2>',kind:'steam'}], quit} = {}) {
|
||||
const asked=[], calls=[];
|
||||
const f=mounted({confirm:text=>{asked.push(text);return confirmAnswer;},
|
||||
api:async(path,body,device)=>{calls.push({path,body,device});
|
||||
if(body===undefined)return {running};
|
||||
return quit ? quit(body) : {message:'Quit Portal 2',method:'steam'};}});
|
||||
return Object.assign(f,{asked,apiCalls:calls,click:appid=>f.element('ccRunningList').onclick({target:{closest:()=>({dataset:{ccQuit:String(appid)}})}})});
|
||||
}
|
||||
test('force quit lists what is running and says so when nothing is', async t => {
|
||||
const f=quitPage({running:[]});t.after(()=>f.ui.destroy());
|
||||
await f.element('ccRunningCheck').onclick();
|
||||
assert.deepEqual(f.apiCalls,[{path:'/api/running',body:undefined,device:'frame-a'}]);
|
||||
assert.equal(f.element('ccRunningResult').textContent,'Nothing is running on the Frame.');
|
||||
assert.equal(f.element('ccRunningList').innerHTML,'');
|
||||
const g=quitPage();t.after(()=>g.ui.destroy());
|
||||
await g.element('ccRunningCheck').onclick();
|
||||
assert.match(g.element('ccRunningList').innerHTML,/Portal <2><small>Steam game<\/small>.*data-cc-quit="620"/);
|
||||
assert.match(g.element('ccRunningResult').textContent,/^1 running/);
|
||||
});
|
||||
test('force quit confirms with the unsaved-progress warning before any request', async t => {
|
||||
const f=quitPage({confirmAnswer:false});t.after(()=>f.ui.destroy());
|
||||
await f.element('ccRunningCheck').onclick();
|
||||
f.click(620);await flush();
|
||||
assert.deepEqual(f.asked,['Force quit Portal <2>? Unsaved progress will be lost.']);
|
||||
assert.equal(f.apiCalls.length,1,'declining sends nothing');
|
||||
const g=quitPage();t.after(()=>g.ui.destroy());
|
||||
await g.element('ccRunningCheck').onclick();
|
||||
g.click(620);await flush();
|
||||
assert.deepEqual(g.apiCalls[1],{path:'/api/running',body:{action:'quit',appid:'620'},device:'frame-a'});
|
||||
assert.equal(g.element('ccRunningResult').textContent,'Quit Portal 2');
|
||||
assert.equal(g.element('ccRunningList').innerHTML,'');
|
||||
g.click(999);await flush();
|
||||
assert.equal(g.apiCalls.length,2,'an id that was not listed is ignored');
|
||||
});
|
||||
test('force quit shows errors, refuses duplicates and offline use, and ignores a switched headset', async t => {
|
||||
const pending=deferred();
|
||||
const f=quitPage({quit:()=>pending.promise});t.after(()=>f.ui.destroy());
|
||||
await f.element('ccRunningCheck').onclick();
|
||||
f.click(620);f.click(620);await flush();
|
||||
assert.equal(f.asked.length,1);
|
||||
assert.match(f.element('ccRunningList').innerHTML,/disabled/);
|
||||
pending.reject(Error("That game isn't running any more"));await flush();
|
||||
assert.equal(f.element('ccRunningResult').textContent,"Couldn’t force quit Portal <2>: That game isn't running any more");
|
||||
assert.doesNotMatch(f.element('ccRunningList').innerHTML,/disabled/);
|
||||
// A switch while quitting: the old answer is dropped and the list cleared.
|
||||
const late=deferred(),g=quitPage({quit:()=>late.promise});t.after(()=>g.ui.destroy());
|
||||
await g.element('ccRunningCheck').onclick();g.click(620);await flush();
|
||||
g.context={online:true,generation:2,device:'frame-b'};g.ui.reset();
|
||||
late.resolve({message:'Quit Portal 2'});await flush();
|
||||
assert.equal(g.element('ccRunningResult').textContent,'');
|
||||
assert.equal(g.element('ccRunningList').innerHTML,'');
|
||||
const h=quitPage();t.after(()=>h.ui.destroy());h.context={online:false,generation:1,device:'frame-a'};
|
||||
await h.element('ccRunningCheck').onclick();
|
||||
assert.equal(h.apiCalls.length,0);
|
||||
assert.match(h.element('ccRunningResult').textContent,/Connect to the Frame/);
|
||||
const controller=cc.createController({api:async()=>assert.fail('no request'),getContext:()=>({online:true,generation:1})});
|
||||
await assert.rejects(controller.forceQuit({appid:'620; reboot'}),/Choose a running game/);
|
||||
});
|
||||
test('the Control Center finds force quit by what a stuck game looks like', () => {
|
||||
const item=cc.catalog.find(i=>i.id==='forcequit');
|
||||
for(const q of ['frozen game','hung','not responding','kill','stuck app'])assert.ok(cc.matches(item,q,'all'),q);
|
||||
assert.ok(cc.matches(item,'','apps'));
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Force quit (ui/frame_running.py) through the server's HTTP API, against games the
|
||||
fake Steam client really runs under its stand-in reaper (fakesteam.REAPER)."""
|
||||
import os
|
||||
import unittest
|
||||
|
||||
import harness
|
||||
from harness import api, install_title, launches, ok, ssh, state, wait_for
|
||||
|
||||
harness.require()
|
||||
|
||||
|
||||
class Running(harness.FrameTestCase):
|
||||
def script_title(self, name, body):
|
||||
folder = self.path(name)
|
||||
os.makedirs(folder)
|
||||
with open(os.path.join(folder, 'run.sh'), 'w') as f:
|
||||
f.write('#!/bin/sh\n' + body)
|
||||
os.chmod(os.path.join(folder, 'run.sh'), 0o755)
|
||||
plan, job = install_title(folder)
|
||||
self.assertIsNone(job['error'], job)
|
||||
return plan['id'], plan['name']
|
||||
|
||||
def running(self, match):
|
||||
return next((g for g in ok('GET', '/api/running')['running'] if match(g)), None)
|
||||
|
||||
def launch_title(self, gid):
|
||||
ok('POST', '/api/titles', {'action': 'launch', 'id': gid})
|
||||
game = wait_for(lambda: self.running(lambda g: g.get('title') == gid), 20, f'{gid} to be running')
|
||||
# The fake's reset doesn't stop programs: don't leave one running for the next test.
|
||||
self.addCleanup(ssh, f"pkill -KILL -f '[d]evkit-game/{gid}/' || true", check=False)
|
||||
return game
|
||||
|
||||
def assert_steam_alive(self, pid):
|
||||
self.assertEqual(ssh(f'kill -0 {pid} && echo alive').strip(), 'alive')
|
||||
|
||||
def test_nothing_running(self):
|
||||
self.assertEqual(ok('GET', '/api/running'), {'running': [], 'message': 'Nothing is running on the Frame'})
|
||||
status, out, _ = api('POST', '/api/running', {'action': 'quit', 'appid': '620'})
|
||||
self.assertEqual(status, 409, out)
|
||||
|
||||
def test_sigterm_quits_a_sideloaded_game(self):
|
||||
gid, name = self.script_title('Hang Game', 'sleep 600 &\nwait\n')
|
||||
steam = ssh('cat ~/.steam/steam.pid').strip()
|
||||
game = self.launch_title(gid)
|
||||
self.assertEqual((game['kind'], game['name']), ('devkit', name))
|
||||
self.assertGreaterEqual(game['processes'], 3) # reaper, run.sh, sleep
|
||||
out = ok('POST', '/api/running', {'action': 'quit', 'appid': str(game['appid'])})
|
||||
self.assertEqual(out['method'], 'term', out)
|
||||
self.assertEqual(out['message'], f'Force quit {name}')
|
||||
# Steam was asked first, with the shortcut's game id.
|
||||
self.assertEqual(state()['steam']['last_terminate'], game['gameid'])
|
||||
self.assertIsNone(self.running(lambda g: g['appid'] == game['appid']))
|
||||
self.assertEqual(ssh("pgrep -fc '[s]leep 600' || true").strip(), '0')
|
||||
self.assert_steam_alive(steam)
|
||||
done = wait_for(lambda: launches('devkit')[-1].get('exit') is not None and launches('devkit')[-1],
|
||||
10, 'the reaper to report the exit')
|
||||
self.assertIsNotNone(done['exit'])
|
||||
|
||||
def test_sigkill_when_it_ignores_sigterm(self):
|
||||
gid, name = self.script_title('Stuck Game', "trap '' TERM\nsleep 600 &\nwait\n")
|
||||
steam = ssh('cat ~/.steam/steam.pid').strip()
|
||||
game = self.launch_title(gid)
|
||||
out = ok('POST', '/api/running', {'action': 'quit', 'appid': str(game['appid'])})
|
||||
self.assertEqual(out['method'], 'kill', out)
|
||||
self.assertEqual(out['message'], f'Force quit {name} (it had to be killed)')
|
||||
self.assertIsNone(self.running(lambda g: g['appid'] == game['appid']))
|
||||
self.assertEqual(ssh("pgrep -fc '[s]leep 600' || true").strip(), '0')
|
||||
self.assert_steam_alive(steam)
|
||||
|
||||
def test_steam_game_quits_through_steam(self):
|
||||
ok('POST', '/api/launch', {'appid': 620980})
|
||||
game = wait_for(lambda: self.running(lambda g: g['appid'] == 620980), 20, 'the Steam game to be running')
|
||||
self.assertEqual((game['kind'], game['gameid']), ('steam', '620980'))
|
||||
out = ok('POST', '/api/running', {'action': 'quit', 'appid': '620980'})
|
||||
self.assertEqual(out['method'], 'steam', out)
|
||||
self.assertEqual(state()['steam']['last_terminate'], '620980')
|
||||
self.assertEqual(launches('rungameid')[-1]['exit'], 'terminated')
|
||||
self.assertEqual(ok('GET', '/api/running')['running'], [])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -79,6 +79,12 @@ function build(steam) {
|
||||
return s ? { strShortcutExe: s.exe, strShortcutStartDir: s.start_dir, bShortcutIsVR: !!s.vr } : null;
|
||||
},
|
||||
},
|
||||
// Guess: the running list as Steam's client code and plugin loaders read it
|
||||
// (SteamUIStore.RunningApps of app overviews); not seen on the Frame. fakesteam
|
||||
// passes the ids of launches that haven't exited.
|
||||
SteamUIStore: {
|
||||
get RunningApps() { return (steam.running || []).map(id => allApps().find(a => a.appid === id) || { appid: id }); },
|
||||
},
|
||||
appStore: {
|
||||
get allApps() { return allApps(); },
|
||||
GetAppOverviewByAppID(id) { return allApps().find(a => a.appid === Number(id)) || null; },
|
||||
@@ -109,7 +115,8 @@ function build(steam) {
|
||||
if (s?.artwork) delete s.artwork[type];
|
||||
},
|
||||
// Container fallback in frame_android.stop performs the simulated stop.
|
||||
TerminateApp(gameid) { steam.last_terminate = gameid; },
|
||||
// fakesteam ends pid-less launches for the ids in `terminated`.
|
||||
TerminateApp(gameid) { steam.last_terminate = gameid; (steam.terminated ||= []).push(String(gameid)); },
|
||||
RemoveShortcut(id) {
|
||||
steam.shortcuts = steam.shortcuts.filter(s => s.appid !== Number(id));
|
||||
delete steam.compat_tools[String(id)];
|
||||
|
||||
@@ -47,6 +47,12 @@ COMPAT_LOG = fs.STEAM_ROOT + '/logs/compat_log.txt'
|
||||
DEVTOOLS_PORT = 8080
|
||||
TARGET_ID = 'F0CA11ED5EA4ED0000000000000000AB'
|
||||
GAME_LOGS = '/var/log/fakeframe'
|
||||
# Steam starts a game under its reaper, `reaper SteamLaunch AppId=<id> -- <command>`,
|
||||
# which stays the game's parent until it ends (guess for the Frame: that's how Steam
|
||||
# launches on Linux desktops and the Steam Deck; docs/steam-games.md). The fake's
|
||||
# reaper is bash with that command line: it waits for the game and exits with its status.
|
||||
REAPER = fs.STEAM_ROOT + '/ubuntu12_32/reaper'
|
||||
REAPER_SH = 'while [ "$1" != "--" ]; do shift; done; shift; "$@" & wait $!'
|
||||
|
||||
# The 403 text /register returned while Steam wasn't on "Pair new host"
|
||||
# (docs/ssh.md, verified 2026-09-26). approve-ssh-key passes the Steam
|
||||
@@ -105,11 +111,24 @@ class JS:
|
||||
self._start()
|
||||
self.next += 1
|
||||
with fs.update() as state:
|
||||
self.proc.stdin.write(json.dumps({'id': self.next, 'expression': expression,
|
||||
'awaitPromise': await_promise, 'steam': state['steam']}) + '\n')
|
||||
# What Steam counts as running: launches that started and haven't exited.
|
||||
running = sorted({l['appid'] for l in state['launches']
|
||||
if l.get('started') and l.get('appid') and l.get('exit') is None})
|
||||
self.proc.stdin.write(json.dumps({'id': self.next, 'expression': expression, 'awaitPromise': await_promise,
|
||||
'steam': dict(state['steam'], running=running)}) + '\n')
|
||||
self.proc.stdin.flush()
|
||||
reply = json.loads(self.proc.stdout.readline())
|
||||
state['steam'] = reply['steam']
|
||||
steam = reply['steam']
|
||||
steam.pop('running', None)
|
||||
for gid in map(int, steam.pop('terminated', [])):
|
||||
appid = gid >> 32 if gid >= 1 << 32 else gid
|
||||
# Guess: TerminateApp ends a launch the fake didn't really run (a Steam
|
||||
# game, a Proton title). A real process it leaves alone, so Frame
|
||||
# Control's own fallback (SIGTERM, SIGKILL) is what the e2e tests see.
|
||||
for l in state['launches']:
|
||||
if l.get('appid') == appid and l.get('exit') is None and not l.get('pid'):
|
||||
l['exit'] = 'terminated'
|
||||
state['steam'] = steam
|
||||
return reply['result']
|
||||
|
||||
|
||||
@@ -253,8 +272,10 @@ def add_launch(record):
|
||||
os.makedirs(GAME_LOGS, exist_ok=True)
|
||||
with open(f'{GAME_LOGS}/{label}.log', 'ab') as log:
|
||||
try:
|
||||
proc = subprocess.Popen([path], cwd=cwd if os.path.isdir(cwd) else HOME, env={**os.environ, **env},
|
||||
stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True)
|
||||
argv = [REAPER, '-c', REAPER_SH, 'reaper', 'SteamLaunch', f"AppId={record['appid']}", '--', path]
|
||||
proc = subprocess.Popen(argv, executable='/bin/bash', cwd=cwd if os.path.isdir(cwd) else HOME,
|
||||
env={**os.environ, **env}, stdin=subprocess.DEVNULL, stdout=log, stderr=log,
|
||||
start_new_session=True)
|
||||
record['pid'] = proc.pid
|
||||
except OSError as e:
|
||||
record.update(pid=None, exec_error=str(e))
|
||||
|
||||
@@ -1,559 +0,0 @@
|
||||
"""Recordings of the headset view and Steam clip exports (ui/frame_clips.py), without a headset.
|
||||
|
||||
Steam's recordings are fixture trees in the layout frame_clips.py describes. The
|
||||
recording's shell runs for real under bash with a stand-in ffmpeg, so Stop, the time
|
||||
limit and the clean-up are the real script's behaviour. With ffmpeg installed here, a
|
||||
65-second DASH recording is made in Steam's file naming and exported for real.
|
||||
"""
|
||||
import sandbox # noqa: F401 (first: keeps tests off real data and services)
|
||||
import json
|
||||
import os
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "ui"))
|
||||
import frame_clips as clips # noqa: E402
|
||||
|
||||
POSIX = os.name != "nt" and shutil.which("bash")
|
||||
|
||||
|
||||
def write(path, data=b"x"):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(data)
|
||||
return path
|
||||
|
||||
|
||||
def session(folder, streams=(0, 1), chunks=3, mpd=None, first=1, pad=5):
|
||||
"""A session folder as Steam writes it: init + numbered chunks per stream."""
|
||||
for n in streams:
|
||||
write(folder / f"init-stream{n}.m4s", f"init{n};".encode())
|
||||
for c in range(first, first + chunks):
|
||||
write(folder / f"chunk-stream{n}-{c:0{pad}d}.m4s", f"s{n}c{c};".encode())
|
||||
if mpd is not None:
|
||||
write(folder / "session.mpd", mpd.encode())
|
||||
return folder
|
||||
|
||||
|
||||
class Ids(unittest.TestCase):
|
||||
def test_good_ids(self):
|
||||
for cid in ("123/video/bg_620_20261020_201950",
|
||||
"123/clips/clip_620_20261020_202134/video/bg_620_20261020_201950",
|
||||
"9/clips/a/b/c/d"):
|
||||
self.assertEqual(clips.parse_id(cid)[0], cid.split("/")[0])
|
||||
self.assertEqual(clips.export_name("123/clips/clip_620_20261020_202134/video/bg_620_1"),
|
||||
"clip_620_20261020_202134.mp4")
|
||||
|
||||
def test_no_traversal_or_shell_from_ids(self):
|
||||
for cid in ("", None, 5, "123", "123/video", "123/other/bg", "abc/video/bg", "/123/video/bg",
|
||||
"123/video/..", "123/video/.", "123/video/bg/../../../../.ssh", "123/video/.hidden",
|
||||
"123/video/bg;rm -rf ~", "123/video/bg$(id)", "123/video/bg name", "123/video/bg\n",
|
||||
"123/video/%2e%2e", "123\\video\\bg", "123/video//bg", "123/clips/a/b/c/d/e",
|
||||
"123/video/" + "a" * 101, "1234567890123/video/bg"):
|
||||
with self.subTest(cid=cid), self.assertRaises(ValueError):
|
||||
clips.parse_id(cid)
|
||||
with self.subTest(cid=cid), self.assertRaises(ValueError):
|
||||
clips.export_name(cid)
|
||||
|
||||
def test_export_paths_checked_before_delete(self):
|
||||
good = f"{clips.WORK}/export-0123456789abcdef/clip_620.mp4"
|
||||
self.assertEqual(clips.remove_command(good), f'rm -rf "$HOME"/{clips.WORK}/export-0123456789abcdef')
|
||||
for bad in (None, "", "/etc/passwd", f"{clips.WORK}/export-0123456789abcdef/../../x.mp4",
|
||||
f"{clips.WORK}/export-xyz/clip.mp4", f"{clips.WORK}/../export-0123456789abcdef/a.mp4",
|
||||
f"{clips.WORK}/export-0123456789abcdef/a.mp4; rm -rf ~", ".ssh/export-0123456789abcdef/a.mp4"):
|
||||
with self.subTest(bad=bad), self.assertRaises(ValueError):
|
||||
clips.remove_command(bad)
|
||||
|
||||
def test_recording_names_checked(self):
|
||||
for fn in (clips.finish_command, clips.cleanup_command, lambda n: clips.record_command(n, True)):
|
||||
for bad in ("rec-1", "rec-20261020-201950; rm -rf ~", "../rec-20261020-201950", "*"):
|
||||
with self.subTest(bad=bad), self.assertRaises(ValueError):
|
||||
fn(bad)
|
||||
|
||||
|
||||
class Sessions(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.dir, ignore_errors=True)
|
||||
|
||||
def test_chunks_in_number_order_whatever_the_padding(self):
|
||||
s = self.dir / "s"
|
||||
write(s / "init-stream0.m4s")
|
||||
for c in (10, 2, 1, 100, 9):
|
||||
write(s / f"chunk-stream0-{c}.m4s")
|
||||
write(s / "chunk-stream0-00003.m4s")
|
||||
got = clips.read_session(s)
|
||||
self.assertEqual([os.path.basename(p) for p in got[0]],
|
||||
["init-stream0.m4s", "chunk-stream0-1.m4s", "chunk-stream0-2.m4s", "chunk-stream0-00003.m4s",
|
||||
"chunk-stream0-9.m4s", "chunk-stream0-10.m4s", "chunk-stream0-100.m4s"])
|
||||
self.assertEqual(clips.chunk_gaps(got[0]), 100 - 6)
|
||||
|
||||
def test_unplayable_streams_and_strangers_left_out(self):
|
||||
s = self.dir / "s"
|
||||
session(s, streams=(0,), chunks=2)
|
||||
write(s / "init-stream1.m4s") # no chunks
|
||||
write(s / "chunk-stream2-00001.m4s") # no init
|
||||
write(s / "chunk-stream0-00001.m4s.part") # not a chunk
|
||||
write(s / "thumbnail.jpg")
|
||||
(s / "chunk-stream0-00009.m4s").mkdir() # a folder, not a file
|
||||
if POSIX:
|
||||
os.symlink("/etc/passwd", s / "chunk-stream0-00005.m4s") # links aren't followed
|
||||
got = clips.read_session(s)
|
||||
self.assertEqual(list(got), [0])
|
||||
self.assertEqual(len(got[0]), 3)
|
||||
|
||||
def test_manifest_duration(self):
|
||||
for text, want in (('mediaPresentationDuration="PT1M23.4S"', 83.4), ('mediaPresentationDuration="PT2H"', 7200),
|
||||
('mediaPresentationDuration="PT0H3M0.000S"', 180), ('mediaPresentationDuration="P1DT1S"', 86401),
|
||||
('mediaPresentationDuration="PT"', None), ('nothing here', None), (None, None)):
|
||||
self.assertEqual(clips.mpd_duration(text), want, text)
|
||||
|
||||
def test_listing_a_fixture_tree(self):
|
||||
ud = self.dir / "userdata"
|
||||
gr = ud / "123" / "gamerecordings"
|
||||
session(gr / "clips" / "clip_620_20261020_202134" / "video" / "bg_620_20261020_201950", chunks=40,
|
||||
mpd='<MPD mediaPresentationDuration="PT1M20.0S">')
|
||||
write(gr / "clips" / "clip_620_20261020_202134" / "thumbnail.jpg")
|
||||
session(gr / "video" / "bg_1172470_20261021_090000", streams=(0,), chunks=2)
|
||||
session(gr / "video" / "odd-name", chunks=1) # no stamp: time from the files
|
||||
(gr / "video" / "empty").mkdir()
|
||||
session(gr / "video" / ".hidden", chunks=1) # not a name an id can carry
|
||||
session(gr / "timelines" / "x", chunks=1) # not clips/ or video/
|
||||
session(ud / "notanaccount" / "gamerecordings" / "video" / "bg_1_20260101_000000", chunks=1)
|
||||
session(gr / "video" / "a" / "b" / "c" / "d" / "e", chunks=1) # deeper than ids go
|
||||
if POSIX:
|
||||
os.symlink(gr, gr / "video" / "loop") # links aren't followed
|
||||
for f in (gr / "video" / "odd-name").iterdir():
|
||||
os.utime(f, (1e9, 1e9)) # 2001: older than the others
|
||||
got = clips.list_recordings(ud)
|
||||
self.assertEqual([c["id"] for c in got], ["123/video/bg_1172470_20261021_090000",
|
||||
"123/clips/clip_620_20261020_202134/video/bg_620_20261020_201950",
|
||||
"123/video/odd-name"]) # newest first
|
||||
self.assertEqual(got[-1]["time"], 1e9)
|
||||
by = {c["id"]: c for c in got}
|
||||
clip = by["123/clips/clip_620_20261020_202134/video/bg_620_20261020_201950"]
|
||||
self.assertEqual((clip["kind"], clip["appid"], clip["streams"], clip["chunks"], clip["gaps"], clip["duration"]),
|
||||
("clip", "620", 2, 80, 0, 80.0))
|
||||
self.assertEqual(clip["file"], "clip_620_20261020_202134.mp4")
|
||||
self.assertEqual(clip["time"], time.mktime((2026, 10, 20, 20, 21, 34, 0, 0, -1)))
|
||||
self.assertEqual(clip["size"], sum(f.stat().st_size for f in
|
||||
(gr / "clips" / "clip_620_20261020_202134" / "video" / "bg_620_20261020_201950").iterdir()
|
||||
if f.suffix == ".m4s"))
|
||||
bg = by["123/video/bg_1172470_20261021_090000"]
|
||||
self.assertEqual((bg["kind"], bg["appid"], bg["streams"], bg["duration"]), ("background", "1172470", 1, None))
|
||||
self.assertIsNone(by["123/video/odd-name"]["appid"])
|
||||
self.assertEqual(clips.list_recordings(self.dir / "missing"), [])
|
||||
|
||||
def test_listing_marks_what_is_already_here(self):
|
||||
here = self.dir / "here"
|
||||
write(here / "clip_620_20261020_202134.mp4")
|
||||
frame = lambda args, timeout: {"clips": [{"id": "1/clips/clip_620_20261020_202134/video/bg"},
|
||||
{"id": "1/video/bg_620_20261020_201950"}]}
|
||||
got = clips.list_clips(frame, folder=here)
|
||||
self.assertEqual([c["saved"] for c in got["clips"]], [True, False])
|
||||
self.assertEqual(got["folder"], str(here))
|
||||
|
||||
|
||||
class Export(unittest.TestCase):
|
||||
"""The Frame's half of an export, against a fixture tree, with ffmpeg stood in."""
|
||||
|
||||
def setUp(self):
|
||||
self.dir = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.dir, ignore_errors=True)
|
||||
self.ud = self.dir / "home" / clips.STEAM_USERDATA
|
||||
self.home = self.dir / "home"
|
||||
self.cid = "123/clips/clip_620_20261020_202134/video/bg_620_20261020_201950"
|
||||
session(self.ud / "123" / "gamerecordings" / "clips" / "clip_620_20261020_202134" / "video" /
|
||||
"bg_620_20261020_201950", chunks=12)
|
||||
|
||||
def fake_ffmpeg(self, seen, rc=0):
|
||||
def run(cmd, **kw):
|
||||
ins = [cmd[i + 1] for i, a in enumerate(cmd) if a == "-i"]
|
||||
seen.append({"cmd": cmd, "inputs": {Path(i).name: Path(i).read_bytes() for i in ins}})
|
||||
if rc == 0:
|
||||
Path(cmd[-1]).write_bytes(b"mp4")
|
||||
return subprocess.CompletedProcess(cmd, rc, "", "Invalid data found" if rc else "")
|
||||
return run
|
||||
|
||||
def test_streams_stitched_in_order_and_copied_not_reencoded(self):
|
||||
seen = []
|
||||
with mock.patch.object(clips.subprocess, "run", self.fake_ffmpeg(seen)):
|
||||
got = clips.export(self.ud, self.cid, home=self.home)
|
||||
self.assertRegex(got["path"], clips.EXPORT_PATH)
|
||||
self.assertTrue(got["path"].endswith("/clip_620_20261020_202134.mp4"))
|
||||
self.assertEqual(got["size"], 3)
|
||||
cmd = seen[0]["cmd"]
|
||||
self.assertEqual(cmd[cmd.index("-c") + 1], "copy")
|
||||
self.assertEqual([cmd[i + 1] for i, a in enumerate(cmd) if a == "-map"], ["0", "1"])
|
||||
for n in (0, 1):
|
||||
self.assertEqual(seen[0]["inputs"][f"stream{n}.mp4"],
|
||||
f"init{n};".encode() + b"".join(f"s{n}c{c};".encode() for c in range(1, 13)))
|
||||
out = self.home / got["path"]
|
||||
self.assertEqual(sorted(p.name for p in out.parent.iterdir()), [out.name]) # stream files gone
|
||||
|
||||
def test_failed_join_leaves_nothing_behind(self):
|
||||
with mock.patch.object(clips.subprocess, "run", self.fake_ffmpeg([], rc=1)):
|
||||
with self.assertRaisesRegex(clips.ClipError, "Invalid data"):
|
||||
clips.export(self.ud, self.cid, home=self.home)
|
||||
self.assertEqual(list((self.home / clips.WORK).glob("export-*")), [])
|
||||
|
||||
def test_bad_or_missing_ids(self):
|
||||
with self.assertRaises(ValueError):
|
||||
clips.export(self.ud, "123/video/../../../../etc", home=self.home)
|
||||
with self.assertRaises(ClipErrorOrOSError):
|
||||
clips.export(self.ud, "123/video/nothing_here", home=self.home)
|
||||
|
||||
@unittest.skipUnless(POSIX, "symlinks")
|
||||
def test_a_linked_account_cannot_reach_outside_userdata(self):
|
||||
outside = session(self.dir / "elsewhere" / "gamerecordings" / "video" / "bg_1_20260101_000000", chunks=1)
|
||||
os.symlink(self.dir / "elsewhere", self.ud / "456")
|
||||
self.assertIsNotNone(outside)
|
||||
with self.assertRaises(ValueError):
|
||||
clips.export(self.ud, "456/video/bg_1_20260101_000000", home=self.home)
|
||||
|
||||
def test_no_space_on_the_frame(self):
|
||||
full = mock.Mock(free=10)
|
||||
with mock.patch.object(clips.shutil, "disk_usage", return_value=full):
|
||||
with self.assertRaisesRegex(clips.ClipError, "Not enough free space on the Frame"):
|
||||
clips.export(self.ud, self.cid, home=self.home)
|
||||
|
||||
def test_old_exports_swept(self):
|
||||
work = self.home / clips.WORK
|
||||
old, new = work / "export-aaaaaaaaaaaaaaaa", work / "export-bbbbbbbbbbbbbbbb"
|
||||
write(old / "x.mp4"), write(new / "y.mp4")
|
||||
os.utime(old, (time.time() - 7 * 3600,) * 2)
|
||||
with mock.patch.object(clips.subprocess, "run", self.fake_ffmpeg([])):
|
||||
clips.export(self.ud, self.cid, home=self.home)
|
||||
self.assertFalse(old.exists())
|
||||
self.assertTrue(new.exists())
|
||||
|
||||
def test_main_prints_json(self):
|
||||
with mock.patch.object(clips.Path, "home", return_value=self.home), \
|
||||
mock.patch("sys.stdout", new_callable=lambda: __import__("io").StringIO()) as out:
|
||||
self.assertEqual(clips.main(["list"]), 0)
|
||||
self.assertEqual(json.loads(out.getvalue())["clips"][0]["id"], self.cid)
|
||||
with mock.patch("sys.stdout", new_callable=lambda: __import__("io").StringIO()) as out:
|
||||
self.assertEqual(clips.main(["export", "../../x"]), 1)
|
||||
self.assertEqual(json.loads(out.getvalue()), {"error": "bad clip id"})
|
||||
|
||||
|
||||
ClipErrorOrOSError = (clips.ClipError, OSError)
|
||||
|
||||
|
||||
class ComputerSide(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.dir = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.dir, ignore_errors=True)
|
||||
|
||||
def test_export_copies_then_deletes_on_the_frame(self):
|
||||
path = f"{clips.WORK}/export-0123456789abcdef/clip_620.mp4"
|
||||
calls = []
|
||||
frame = lambda args, timeout: calls.append(("frame", args)) or {"path": path, "size": 3}
|
||||
run = lambda cmd, timeout: calls.append(("run", cmd))
|
||||
fetch = lambda remote, local: calls.append(("fetch", remote)) or Path(local).write_bytes(b"mp4")
|
||||
got = clips.export_clip("1/clips/clip_620/video/bg", frame, run, fetch, folder=self.dir)
|
||||
self.assertEqual(got["message"], "Saved clip_620.mp4 to ~/Videos/SteamFrame")
|
||||
self.assertEqual((self.dir / "clip_620.mp4").read_bytes(), b"mp4")
|
||||
self.assertEqual([c[0] for c in calls], ["frame", "fetch", "run"])
|
||||
self.assertEqual(calls[2][1], clips.remove_command(path))
|
||||
self.assertEqual([p.name for p in self.dir.iterdir()], ["clip_620.mp4"])
|
||||
|
||||
def test_failed_copy_leaves_no_partial_file_and_still_cleans_up(self):
|
||||
path = f"{clips.WORK}/export-0123456789abcdef/clip_620.mp4"
|
||||
ran = []
|
||||
|
||||
def fetch(remote, local):
|
||||
Path(local).write_bytes(b"half")
|
||||
raise RuntimeError("connection lost")
|
||||
with self.assertRaisesRegex(RuntimeError, "connection lost"):
|
||||
clips.export_clip("1/clips/clip_620/video/bg", lambda a, t: {"path": path, "size": 4},
|
||||
lambda cmd, timeout: ran.append(cmd), fetch, folder=self.dir)
|
||||
self.assertEqual(list(self.dir.iterdir()), [])
|
||||
self.assertEqual(ran, [clips.remove_command(path)])
|
||||
|
||||
def test_bad_id_never_reaches_the_frame(self):
|
||||
never = mock.Mock(side_effect=AssertionError("reached the Frame"))
|
||||
with self.assertRaises(ValueError):
|
||||
clips.export_clip("1/video/../../.ssh", never, never, never, folder=self.dir)
|
||||
|
||||
def test_unexpected_path_from_the_frame_refused(self):
|
||||
never = mock.Mock(side_effect=AssertionError("deleted or copied"))
|
||||
with self.assertRaises(ValueError):
|
||||
clips.export_clip("1/video/bg", lambda a, t: {"path": ".ssh/id_ed25519", "size": 1}, never, never,
|
||||
folder=self.dir)
|
||||
|
||||
|
||||
class Commands(unittest.TestCase):
|
||||
def test_record_command_with_and_without_sound(self):
|
||||
with_sound = shlex.split(clips.record_command("rec-20261020-201950", True))
|
||||
self.assertEqual(with_sound[:2], ["bash", "-c"])
|
||||
script = with_sound[2]
|
||||
self.assertIn(f"-f v4l2 -video_size 1920x1080 -i {clips.STREAM_DEVICE}", script)
|
||||
self.assertIn("-c:v libx264", script)
|
||||
self.assertNotIn("v4l2m2m", script) # the hardware encoder crashes ffmpeg
|
||||
self.assertIn(f"-f pulse -i {clips.AUDIO_SOURCE}", script)
|
||||
self.assertIn("-map 1:a:0", script)
|
||||
self.assertIn("-c:a aac", script)
|
||||
self.assertIn(f"-t {clips.MAX_SECONDS} ", script)
|
||||
self.assertIn('"$d/rec-20261020-201950.mkv"', script)
|
||||
self.assertEqual(script.count("-use_wallclock_as_timestamps 1"), 2)
|
||||
quiet = shlex.split(clips.record_command("rec-20261020-201950", False))[2]
|
||||
self.assertNotIn("pulse", quiet)
|
||||
self.assertNotIn("-c:a", quiet)
|
||||
self.assertEqual(quiet.count("-use_wallclock_as_timestamps 1"), 1)
|
||||
with self.assertRaises(ValueError):
|
||||
clips.record_command("rec-20261020-201950", True, max_seconds=clips.MAX_SECONDS + 1)
|
||||
|
||||
def test_probe_checks_device_space_and_sound(self):
|
||||
probe = clips.probe_command()
|
||||
self.assertIn(f"[ -e {clips.STREAM_DEVICE} ]", probe)
|
||||
self.assertIn(f"-ge {clips.NEED_KB} ]", probe)
|
||||
self.assertIn(f"timeout 5 ffmpeg -hide_banner -loglevel error -nostdin -f pulse -i {clips.AUDIO_SOURCE}", probe)
|
||||
self.assertIn("echo audio=1; else echo audio=0", probe)
|
||||
self.assertIn(f'd="$HOME/{clips.WORK}"', probe)
|
||||
|
||||
def test_finish_remuxes_without_reencoding(self):
|
||||
cmd = clips.finish_command("rec-20261020-201950")
|
||||
self.assertIn("-i rec-20261020-201950.mkv -map 0 -c copy -movflags +faststart rec-20261020-201950.mp4", cmd)
|
||||
self.assertNotIn("libx264", cmd)
|
||||
self.assertEqual(clips.cleanup_command("rec-20261020-201950"), f'rm -f "$HOME/{clips.WORK}/rec-20261020-201950".*')
|
||||
|
||||
def test_stitch_command(self):
|
||||
self.assertEqual(clips.stitch_command(["a.mp4", "b.mp4"], "out.mp4"),
|
||||
["ffmpeg", "-hide_banner", "-loglevel", "error", "-nostdin", "-y", "-i", "a.mp4", "-i", "b.mp4",
|
||||
"-map", "0", "-map", "1", "-c", "copy", "-movflags", "+faststart", "out.mp4"])
|
||||
|
||||
|
||||
# A stand-in for ffmpeg on the Frame: records how it was run, writes its output file,
|
||||
# and finishes the file when asked to stop (SIGTERM), as ffmpeg does. FAKE_FFMPEG_RUN
|
||||
# makes the recording end by itself after that many seconds (the time limit).
|
||||
FAKE_FFMPEG = r'''#!/usr/bin/env python3
|
||||
import json, os, signal, sys, time
|
||||
home = os.environ["HOME"]
|
||||
with open(os.path.join(home, "ffmpeg-calls.jsonl"), "a") as f:
|
||||
f.write(json.dumps(sys.argv[1:]) + "\n")
|
||||
out = sys.argv[-1]
|
||||
if "-c" in sys.argv and sys.argv[sys.argv.index("-c") + 1] == "copy": # the remux after a recording
|
||||
src = sys.argv[sys.argv.index("-i") + 1]
|
||||
open(out, "wb").write(open(src, "rb").read() + b"+mp4")
|
||||
sys.exit(0)
|
||||
stop = []
|
||||
signal.signal(signal.SIGTERM, lambda *a: stop.append("TERM"))
|
||||
f = open(out, "wb")
|
||||
f.write(b"v"); f.flush()
|
||||
with open(os.path.join(home, "ffmpeg.pid.tmp"), "w") as p:
|
||||
p.write(str(os.getpid()))
|
||||
os.replace(os.path.join(home, "ffmpeg.pid.tmp"), os.path.join(home, "ffmpeg.pid"))
|
||||
end = time.time() + float(os.environ.get("FAKE_FFMPEG_RUN", "60"))
|
||||
while not stop and time.time() < end:
|
||||
f.write(b"v"); f.flush(); time.sleep(0.05)
|
||||
f.close()
|
||||
open(os.path.join(home, "ffmpeg-ended"), "w").write(stop[0] if stop else "limit")
|
||||
sys.exit(255 if stop else 0)
|
||||
'''
|
||||
|
||||
|
||||
@unittest.skipUnless(POSIX, "the recording's shell is bash on the Frame")
|
||||
class Recording(unittest.TestCase):
|
||||
"""The Recorder with the real record/finish/cleanup shell, run locally under bash."""
|
||||
|
||||
def setUp(self):
|
||||
self.dir = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.dir, ignore_errors=True)
|
||||
self.frame = self.dir / "frame" # the Frame's home
|
||||
(self.frame / clips.WORK).mkdir(parents=True)
|
||||
bin_dir = self.dir / "bin"
|
||||
write(bin_dir / "ffmpeg", FAKE_FFMPEG.encode()).chmod(0o755)
|
||||
self.env = {**os.environ, "HOME": str(self.frame), "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}"}
|
||||
self.here = self.dir / "Videos"
|
||||
self.channels, self.released, self.ran = [], [], []
|
||||
self.audio = "audio=1"
|
||||
|
||||
def open_channel(self, command, stderr):
|
||||
proc = subprocess.Popen(shlex.split(command), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=stderr,
|
||||
env=self.env)
|
||||
self.channels.append(proc)
|
||||
self.addCleanup(lambda: proc.poll() is None and proc.kill())
|
||||
return proc
|
||||
|
||||
def run_cmd(self, command, timeout):
|
||||
self.ran.append(command)
|
||||
if command == clips.probe_command():
|
||||
return self.audio + "\n" # needs /dev/video99, so answered here
|
||||
r = subprocess.run(["bash", "-c", command], capture_output=True, text=True, env=self.env, timeout=timeout)
|
||||
if r.returncode:
|
||||
raise RuntimeError(r.stderr.strip() or f"exit {r.returncode}")
|
||||
return r.stdout
|
||||
|
||||
def fetch(self, remote, local):
|
||||
shutil.copyfile(self.frame / remote, local)
|
||||
|
||||
def recorder(self):
|
||||
rec = clips.Recorder(self.open_channel, self.run_cmd, self.fetch,
|
||||
lambda fn: threading.Thread(target=fn, daemon=True).start(),
|
||||
release=self.released.append, folder=self.here)
|
||||
start = rec.start
|
||||
|
||||
def started():
|
||||
# "started" means ffmpeg was launched; wait until it's running, as it would be by a person's Stop.
|
||||
pid = self.frame / "ffmpeg.pid"
|
||||
for f in (pid, self.frame / "ffmpeg-ended"):
|
||||
f.unlink(missing_ok=True)
|
||||
got = start()
|
||||
for _ in range(200):
|
||||
if pid.exists() or (self.frame / "ffmpeg-ended").exists():
|
||||
break
|
||||
time.sleep(0.02)
|
||||
return got
|
||||
rec.start = started
|
||||
return rec
|
||||
|
||||
def wait_for(self, rec, states, timeout=20):
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
s = rec.status()
|
||||
if s["state"] in states:
|
||||
return s
|
||||
time.sleep(0.05)
|
||||
self.fail(f"still {rec.status()}")
|
||||
|
||||
def ffmpeg_calls(self):
|
||||
return [json.loads(line) for line in (self.frame / "ffmpeg-calls.jsonl").read_text().splitlines()]
|
||||
|
||||
def test_stop_finishes_the_file_and_copies_it_here(self):
|
||||
rec = self.recorder()
|
||||
started = rec.start()
|
||||
self.assertEqual((started["state"], started["audio"], started["message"]), ("recording", True, "Recording"))
|
||||
self.assertIn("pulse", self.ffmpeg_calls()[0])
|
||||
time.sleep(0.3)
|
||||
self.assertEqual(rec.stop()["state"], "stopping")
|
||||
done = self.wait_for(rec, ("saved", "failed"))
|
||||
self.assertEqual(done["state"], "saved", done)
|
||||
self.assertEqual((self.frame / "ffmpeg-ended").read_text(), "TERM") # asked to finish, not killed
|
||||
saved = Path(done["file"])
|
||||
self.assertEqual(saved.parent, self.here)
|
||||
self.assertRegex(saved.name, r"^rec-\d{8}-\d{6}\.mp4$")
|
||||
self.assertTrue(saved.read_bytes().endswith(b"+mp4"))
|
||||
self.assertEqual([p.name for p in self.here.iterdir()], [saved.name]) # no .incoming- left
|
||||
self.assertEqual(list((self.frame / clips.WORK).iterdir()), []) # cleaned on the Frame
|
||||
self.assertIsNotNone(self.channels[0].poll()) # the channel has gone
|
||||
self.assertEqual(self.released, self.channels)
|
||||
self.assertEqual(self.ran[-1], clips.cleanup_command(saved.stem))
|
||||
|
||||
def test_channel_closing_stops_ffmpeg_on_the_frame(self):
|
||||
# The computer's ssh going away closes the channel just as Stop does.
|
||||
rec = self.recorder()
|
||||
rec.start()
|
||||
pid = int((self.frame / "ffmpeg.pid").read_text())
|
||||
self.channels[0].stdin.close()
|
||||
self.wait_for(rec, ("saved", "failed"))
|
||||
self.assertEqual((self.frame / "ffmpeg-ended").read_text(), "TERM")
|
||||
with self.assertRaises(ProcessLookupError):
|
||||
for _ in range(100):
|
||||
os.kill(pid, 0)
|
||||
time.sleep(0.05)
|
||||
|
||||
def test_time_limit_saves_on_its_own(self):
|
||||
self.env["FAKE_FFMPEG_RUN"] = "0.3"
|
||||
rec = self.recorder()
|
||||
rec.start()
|
||||
done = self.wait_for(rec, ("saved", "failed"))
|
||||
self.assertEqual(done["state"], "saved", done)
|
||||
self.assertEqual((self.frame / "ffmpeg-ended").read_text(), "limit")
|
||||
with self.assertRaisesRegex(clips.ClipError, "Not recording"):
|
||||
rec.stop()
|
||||
|
||||
def test_no_sound_records_video_and_says_so(self):
|
||||
self.audio = "audio=0"
|
||||
rec = self.recorder()
|
||||
started = rec.start()
|
||||
self.assertFalse(started["audio"])
|
||||
self.assertIn("without sound", started["message"])
|
||||
self.assertNotIn("pulse", self.ffmpeg_calls()[0])
|
||||
rec.stop()
|
||||
done = self.wait_for(rec, ("saved", "failed"))
|
||||
self.assertIn("(no sound)", done["message"])
|
||||
|
||||
def test_one_at_a_time(self):
|
||||
rec = self.recorder()
|
||||
with self.assertRaisesRegex(clips.ClipError, "Not recording"):
|
||||
rec.stop()
|
||||
rec.start()
|
||||
with self.assertRaises(clips.ClipError) as e:
|
||||
rec.start()
|
||||
self.assertEqual(e.exception.status, 409)
|
||||
rec.stop()
|
||||
self.wait_for(rec, ("saved",))
|
||||
rec.start() # a new one once the last is saved
|
||||
rec.stop()
|
||||
self.wait_for(rec, ("saved",))
|
||||
|
||||
def test_failed_start_reports_why(self):
|
||||
rec = clips.Recorder(lambda cmd, err: subprocess.Popen(["bash", "-c", "echo 'no v4l2 here' >&2; exit 1"],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=err),
|
||||
lambda cmd, t: "audio=1", self.fetch, lambda fn: fn(), release=self.released.append,
|
||||
folder=self.here)
|
||||
with self.assertRaisesRegex(clips.ClipError, "no v4l2 here"):
|
||||
rec.start()
|
||||
self.assertEqual(rec.status()["state"], "failed")
|
||||
self.assertEqual(len(self.released), 1)
|
||||
|
||||
def test_failed_probe_reports_why(self):
|
||||
def run(cmd, timeout):
|
||||
raise clips.ClipError("No headset view device (/dev/video99). Is SteamVR running?")
|
||||
rec = clips.Recorder(mock.Mock(side_effect=AssertionError("recorded anyway")), run, self.fetch,
|
||||
lambda fn: fn(), folder=self.here)
|
||||
with self.assertRaisesRegex(clips.ClipError, "Is SteamVR running"):
|
||||
rec.start()
|
||||
self.assertEqual(rec.status()["state"], "failed")
|
||||
|
||||
def test_empty_recording_is_an_error_not_a_file(self):
|
||||
self.env["FAKE_FFMPEG_RUN"] = "0"
|
||||
rec = self.recorder()
|
||||
with mock.patch.object(clips, "finish_command", lambda name: f"echo 'The recording is empty' >&2; exit 1"):
|
||||
rec.start()
|
||||
done = self.wait_for(rec, ("saved", "failed"))
|
||||
self.assertEqual(done["state"], "failed")
|
||||
self.assertIn("The recording is empty", done["error"])
|
||||
self.assertFalse(self.here.exists() and any(self.here.iterdir()))
|
||||
self.assertEqual(list((self.frame / clips.WORK).iterdir()), [])
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("ffmpeg") and shutil.which("ffprobe"), "needs ffmpeg and ffprobe")
|
||||
class RealFfmpeg(unittest.TestCase):
|
||||
"""A 65 s recording in Steam's DASH naming (ffmpeg's own dash muxer names files the same
|
||||
way), stitched by the real ffmpeg: longer than the 60 s Steam's own export manages."""
|
||||
|
||||
def test_export_of_a_long_recording(self):
|
||||
d = Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, d, ignore_errors=True)
|
||||
ud = d / "home" / clips.STEAM_USERDATA
|
||||
folder = ud / "123" / "gamerecordings" / "video" / "bg_620_20261020_201950"
|
||||
folder.mkdir(parents=True)
|
||||
r = subprocess.run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc=size=64x64:rate=10",
|
||||
"-f", "lavfi", "-i", "sine=frequency=440:sample_rate=8000", "-t", "65",
|
||||
"-c:v", "libx264", "-preset", "ultrafast", "-g", "20", "-c:a", "aac",
|
||||
"-seg_duration", "2", "-use_template", "1", "-use_timeline", "0",
|
||||
"-f", "dash", str(folder / "session.mpd")], capture_output=True, text=True)
|
||||
if r.returncode != 0 or not (folder / "chunk-stream0-00001.m4s").exists():
|
||||
self.skipTest("this ffmpeg can't write DASH with libx264: " + r.stderr[-300:])
|
||||
listed = clips.list_recordings(ud)
|
||||
self.assertEqual(len(listed), 1)
|
||||
self.assertGreater(listed[0]["chunks"], 30)
|
||||
got = clips.export(ud, listed[0]["id"], home=d / "home")
|
||||
out = d / "home" / got["path"]
|
||||
probe = json.loads(subprocess.run(["ffprobe", "-v", "error", "-show_streams", "-show_format", "-of", "json", str(out)],
|
||||
capture_output=True, text=True, check=True).stdout)
|
||||
self.assertEqual(sorted(s["codec_type"] for s in probe["streams"]), ["audio", "video"])
|
||||
self.assertGreater(float(probe["format"]["duration"]), 64)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,398 @@
|
||||
"""Force quit (ui/frame_running.py and /api/running) without a headset: running-game
|
||||
detection, which processes may be signalled, SIGTERM-then-SIGKILL, and the Android path.
|
||||
|
||||
Run: python3 -m unittest discover -s tests
|
||||
"""
|
||||
import sandbox # noqa: F401 (first: keeps tests off real data and services)
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT / "ui"))
|
||||
|
||||
import frame_running # noqa: E402
|
||||
import test_server # noqa: E402 (not `from … import`, or unittest runs ServerGuards twice)
|
||||
|
||||
ME, OTHER = 1000, 0
|
||||
HOME = frame_running.HOME
|
||||
REAPER = f"{HOME}/.local/share/Steam/ubuntu12_32/reaper"
|
||||
|
||||
|
||||
def proc(ppid, comm, argv=None, uid=ME, start=None, state="S"):
|
||||
return {"ppid": ppid, "comm": comm, "argv": argv if argv is not None else [comm], "uid": uid,
|
||||
"start": start or 1000 + ppid, "state": state}
|
||||
|
||||
|
||||
def frame():
|
||||
"""A Frame's processes, as Steam on Linux launches games: Steam's reaper with
|
||||
AppId= is the parent of the game (Portal 2 here, appid 620)."""
|
||||
return {
|
||||
1: proc(0, "systemd", uid=OTHER),
|
||||
200: proc(1, "sshd", uid=OTHER),
|
||||
201: proc(200, "sshd-session"),
|
||||
202: proc(201, "bash"),
|
||||
203: proc(202, "python3", ["python3", "-", "quit", "620"]), # this helper
|
||||
300: proc(1, "systemd", ["/usr/lib/systemd/systemd", "--user"]),
|
||||
301: proc(300, "gamescope-session"),
|
||||
302: proc(301, "gamescope"),
|
||||
303: proc(302, "steam", [f"{HOME}/.local/share/Steam/ubuntu12_32/steam", "-cef-enable-debugging"]),
|
||||
304: proc(303, "steamwebhelper"),
|
||||
305: proc(300, "vrserver"),
|
||||
306: proc(300, "plasmashell"),
|
||||
307: proc(300, "pipewire"),
|
||||
400: proc(303, "reaper", [REAPER, "SteamLaunch", "AppId=620", "--", "steam-launch-wrapper", "--", "portal2.sh"]),
|
||||
401: proc(400, "steam-launch-wr", ["steam-launch-wrapper", "--", "portal2.sh"]),
|
||||
402: proc(401, "portal2.sh", ["/bin/sh", "portal2.sh"]),
|
||||
403: proc(402, "portal2_linux", ["./portal2_linux", "-game", "portal2"]),
|
||||
404: proc(403, "steam", ["steam"]), # a child named like Steam: left alone
|
||||
405: proc(404, "crashhandler"), # and so is anything under it
|
||||
# Another game, and processes that only look like launches.
|
||||
500: proc(303, "reaper", [REAPER, "SteamLaunch", "AppId=999", "--", "other"]),
|
||||
501: proc(500, "other"),
|
||||
600: proc(1, "reaper", [REAPER, "SteamLaunch", "AppId=620", "--", "x"], uid=OTHER),
|
||||
601: proc(300, "bash", ["bash", "-c", "echo reaper SteamLaunch AppId=620"]),
|
||||
602: proc(300, "fakereaper", ["/tmp/notreaper", "SteamLaunch", "AppId=620"]),
|
||||
}
|
||||
|
||||
|
||||
class Parsing(unittest.TestCase):
|
||||
def test_launch_appid(self):
|
||||
cases = [
|
||||
([REAPER, "SteamLaunch", "AppId=620", "--", "game"], 620),
|
||||
(["reaper", "SteamLaunch", "AppId=3346865537", "--", "lepton-app.sh"], 3346865537),
|
||||
([REAPER, "AppId=620", "--", "game"], None), # no SteamLaunch
|
||||
([REAPER, "SteamLaunch", "--", "game", "AppId=620"], None), # the game's own arguments
|
||||
(["/usr/bin/steam", "SteamLaunch", "AppId=620"], None), # not the reaper
|
||||
(["/tmp/reaper-ish", "SteamLaunch", "AppId=620"], None),
|
||||
([REAPER, "SteamLaunch", "AppId=62x0"], None),
|
||||
([REAPER, "SteamLaunch", "AppId=12345678901"], None), # more than 10 digits
|
||||
([], None),
|
||||
]
|
||||
for argv, want in cases:
|
||||
with self.subTest(argv=argv):
|
||||
self.assertEqual(frame_running.launch_appid(argv), want)
|
||||
|
||||
def test_reapers_are_this_users_live_launches(self):
|
||||
procs = frame()
|
||||
procs[700] = proc(303, "reaper", [REAPER, "SteamLaunch", "AppId=777"], state="Z")
|
||||
self.assertEqual(frame_running.reapers(procs, ME), {620: [400], 999: [500]})
|
||||
|
||||
def test_steamvr_is_never_a_game(self):
|
||||
procs = frame()
|
||||
procs[710] = proc(303, "reaper", [REAPER, "SteamLaunch", "AppId=250820", "--", "vrstartup"])
|
||||
procs[711] = proc(710, "vrcompositor-launcher")
|
||||
self.assertNotIn(250820, frame_running.reapers(procs, ME))
|
||||
found = frame_running.running(procs, ME, steam=lambda ids: ([250820], {}),
|
||||
android=dict, containers=set)
|
||||
self.assertNotIn(250820, [a["appid"] for a in found])
|
||||
|
||||
def test_gameid(self):
|
||||
self.assertEqual(frame_running.gameid(620), "620")
|
||||
# A non-Steam shortcut: (appid << 32) | 0x02000000, as steam_shortcuts.py stop sends.
|
||||
self.assertEqual(frame_running.gameid(3346865537), str((3346865537 << 32) | 0x02000000))
|
||||
|
||||
def test_snapshot_reads_proc(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
os.makedirs(f"{tmp}/42")
|
||||
os.makedirs(f"{tmp}/self")
|
||||
fields = " ".join(["S", "7"] + ["0"] * 17 + ["123456"])
|
||||
Path(f"{tmp}/42/stat").write_text(f"42 (my (game) x) {fields} 0 0\n")
|
||||
Path(f"{tmp}/42/cmdline").write_bytes(b"reaper\0SteamLaunch\0AppId=5\0--\0g\0")
|
||||
os.makedirs(f"{tmp}/43") # vanished between listdir and read
|
||||
got = frame_running.snapshot(tmp)
|
||||
self.assertEqual(list(got), [42])
|
||||
self.assertEqual(got[42]["comm"], "my (game) x")
|
||||
self.assertEqual((got[42]["ppid"], got[42]["start"], got[42]["state"]), (7, 123456, "S"))
|
||||
self.assertEqual(got[42]["argv"], ["reaper", "SteamLaunch", "AppId=5", "--", "g"])
|
||||
|
||||
|
||||
class Detection(unittest.TestCase):
|
||||
def run_list(self, procs, steam=(None, {}), android=None, containers=()):
|
||||
return frame_running.running(procs, ME, steam=lambda ids: steam, android=lambda: android or {},
|
||||
containers=lambda: set(containers))
|
||||
|
||||
def test_steam_game_named_by_steam(self):
|
||||
got = self.run_list(frame(), steam=([620], {620: "Portal 2", 999: "Other"}))
|
||||
self.assertEqual([(a["appid"], a["kind"], a["name"]) for a in got],
|
||||
[(620, "steam", "Portal 2"), (999, "steam", "Other")])
|
||||
self.assertEqual(got[0]["gameid"], "620")
|
||||
self.assertEqual(got[0]["processes"], 6)
|
||||
|
||||
def test_without_steam_the_manifest_names_it(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
os.makedirs(f"{tmp}/steamapps")
|
||||
Path(f"{tmp}/steamapps/appmanifest_620.acf").write_text('"AppState"\n{\n\t"appid"\t"620"\n\t"name"\t"Portal 2"\n}')
|
||||
with mock.patch.object(frame_running, "STEAM", tmp):
|
||||
got = self.run_list(frame())
|
||||
self.assertEqual([(a["appid"], a["name"]) for a in got], [(620, "Portal 2"), (999, "App 999")])
|
||||
|
||||
def test_nothing_running(self):
|
||||
procs = {pid: p for pid, p in frame().items() if pid < 400}
|
||||
self.assertEqual(self.run_list(procs), [])
|
||||
|
||||
def test_steam_only_listing_counts(self):
|
||||
# Steam says it's running but no reaper was found: listed, with no processes.
|
||||
got = self.run_list({1: proc(0, "systemd", uid=OTHER)}, steam=([620], {620: "Portal 2"}))
|
||||
self.assertEqual(got, [{"appid": 620, "gameid": "620", "processes": 0, "kind": "steam", "name": "Portal 2"}])
|
||||
|
||||
def test_devkit_title_and_shortcut(self):
|
||||
sid, other = 0x80001234, 0x80005678
|
||||
procs = {1: proc(0, "systemd", uid=OTHER),
|
||||
10: proc(1, "reaper", [REAPER, "SteamLaunch", f"AppId={sid}", "--", f'"{HOME}/devkit-game/Cool_Game/run.sh"']),
|
||||
11: proc(10, "run.sh", ["/bin/sh", f"{HOME}/devkit-game/Cool_Game/run.sh"]),
|
||||
20: proc(1, "reaper", [REAPER, "SteamLaunch", f"AppId={other}", "--", "/usr/bin/flatpak", "run", "x"])}
|
||||
got = self.run_list(procs)
|
||||
self.assertEqual([(a["kind"], a.get("title"), a["name"]) for a in got],
|
||||
[("devkit", "Cool_Game", "Cool_Game"), ("shortcut", None, f"Shortcut {other}")])
|
||||
self.assertEqual(got[0]["gameid"], str((sid << 32) | 0x02000000))
|
||||
|
||||
def test_android_app_from_its_container(self):
|
||||
meta = {"package": "org.example.game", "label": "Example", "shortcut": 3346865537, "instance": 2812345678}
|
||||
apps = {3346865537: meta, 2812345678: meta}
|
||||
got = self.run_list({1: proc(0, "systemd", uid=OTHER)}, android=apps,
|
||||
containers={"lepton-steamlaunch-2812345678"})
|
||||
self.assertEqual(got, [{"appid": 3346865537, "gameid": str((3346865537 << 32) | 0x02000000), "processes": 0,
|
||||
"kind": "android", "package": "org.example.game", "name": "Example"}])
|
||||
# Its container stopped: not running.
|
||||
self.assertEqual(self.run_list({1: proc(0, "systemd", uid=OTHER)}, android=apps, containers=()), [])
|
||||
|
||||
def test_android_meta_reads_shortcut_and_instance(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
os.makedirs(f"{tmp}/org.example.game")
|
||||
Path(f"{tmp}/org.example.game/meta.json").write_text(json.dumps(
|
||||
{"package": "org.example.game", "shortcut": 3346865537, "instance": 2812345678}))
|
||||
os.makedirs(f"{tmp}/broken")
|
||||
Path(f"{tmp}/broken/meta.json").write_text("{")
|
||||
with mock.patch.object(frame_running, "ANDROID", tmp):
|
||||
self.assertEqual(sorted(frame_running.android_apps()), [2812345678, 3346865537])
|
||||
|
||||
|
||||
class World:
|
||||
"""Processes that react to signals: kill() removes them, unless they ignore it."""
|
||||
|
||||
def __init__(self, procs, ignore=(), unkillable=()):
|
||||
self.procs, self.ignore, self.unkillable = dict(procs), set(ignore), set(unkillable)
|
||||
self.sent, self.now = [], 0.0
|
||||
|
||||
def scan(self):
|
||||
return dict(self.procs)
|
||||
|
||||
def kill(self, pid, sig):
|
||||
if pid not in self.procs:
|
||||
raise ProcessLookupError
|
||||
self.sent.append((pid, sig))
|
||||
if pid in self.unkillable or (sig == frame_running.SIGTERM and pid in self.ignore):
|
||||
return
|
||||
self.procs.pop(pid)
|
||||
# A reaper exits once its last child has.
|
||||
for rid, p in list(self.procs.items()):
|
||||
if p["comm"] == "reaper" and not any(c["ppid"] == rid for c in self.procs.values()):
|
||||
self.procs.pop(rid)
|
||||
|
||||
def sleep(self, seconds):
|
||||
self.now += seconds
|
||||
|
||||
def escalate(self, appid=620):
|
||||
return frame_running.escalate(appid, me=203, uid=ME, scan=self.scan, kill=self.kill,
|
||||
sleep=self.sleep, clock=lambda: self.now)
|
||||
|
||||
|
||||
class Escalation(unittest.TestCase):
|
||||
GAME = {401, 402, 403}
|
||||
|
||||
def assert_only_game(self, world, allowed=GAME | {400}):
|
||||
signalled = {pid for pid, _ in world.sent}
|
||||
self.assertTrue(signalled, "nothing was signalled")
|
||||
self.assertLessEqual(signalled, allowed)
|
||||
protected = frame_running.protected(frame(), 203, ME)
|
||||
for pid in (1, 200, 201, 202, 203, 300, 301, 302, 303, 304, 305, 306, 307, 404, 405, 500, 501, 600, 601, 602):
|
||||
self.assertNotIn(pid, signalled)
|
||||
self.assertTrue({1, 201, 202, 203, 302, 303, 304, 305, 306, 307, 404, 600}.issubset(protected))
|
||||
|
||||
def test_sigterm_ends_it(self):
|
||||
world = World(frame())
|
||||
self.assertEqual(world.escalate(), "term")
|
||||
self.assert_only_game(world)
|
||||
self.assertEqual({pid for pid, sig in world.sent}, self.GAME)
|
||||
self.assertTrue(all(sig == frame_running.SIGTERM for _, sig in world.sent))
|
||||
# Deepest first, and the reaper isn't signalled while its children are alive.
|
||||
self.assertEqual([pid for pid, _ in world.sent], [403, 402, 401])
|
||||
self.assertNotIn(400, world.procs)
|
||||
self.assertIn(404, world.procs) # the "steam" child under the game is never touched
|
||||
|
||||
def test_sigkill_after_a_grace_period(self):
|
||||
world = World(frame(), ignore={403})
|
||||
self.assertEqual(world.escalate(), "kill")
|
||||
self.assert_only_game(world)
|
||||
self.assertIn((403, frame_running.SIGTERM), world.sent)
|
||||
self.assertIn((403, frame_running.SIGKILL), world.sent)
|
||||
self.assertGreaterEqual(world.now, frame_running.TERM_WAIT)
|
||||
kills = [pid for pid, sig in world.sent if sig == frame_running.SIGKILL]
|
||||
self.assertEqual(kills[0], 403)
|
||||
|
||||
def test_survivor_is_an_error(self):
|
||||
world = World(frame(), unkillable={403})
|
||||
with self.assertRaisesRegex(frame_running.Fail, "still running after SIGKILL"):
|
||||
world.escalate()
|
||||
self.assert_only_game(world)
|
||||
|
||||
def test_reused_pid_is_not_signalled(self):
|
||||
world = World(frame(), ignore={402, 403})
|
||||
real_scan = world.scan
|
||||
|
||||
def scan():
|
||||
procs = real_scan()
|
||||
if world.sent and 402 in procs: # 402 exits and its pid goes to an unrelated program
|
||||
procs[402] = proc(300, "editor", start=99999)
|
||||
world.procs[402] = procs[402]
|
||||
return procs
|
||||
world.scan = scan
|
||||
world.escalate()
|
||||
self.assertNotIn((402, frame_running.SIGKILL), world.sent)
|
||||
|
||||
def test_nothing_left(self):
|
||||
world = World({pid: p for pid, p in frame().items() if pid < 400})
|
||||
self.assertEqual(world.escalate(), "gone")
|
||||
self.assertEqual(world.sent, [])
|
||||
|
||||
def test_lingering_reaper_alone(self):
|
||||
procs = {pid: p for pid, p in frame().items() if pid not in self.GAME and pid not in (404, 405)}
|
||||
world = World(procs)
|
||||
self.assertEqual(world.escalate(), "term")
|
||||
self.assertEqual(world.sent, [(400, frame_running.SIGTERM)])
|
||||
|
||||
def test_protected_never_signalled_even_as_the_root(self):
|
||||
# A reaper whose only children are protected: nothing to signal but the reaper itself.
|
||||
procs = frame()
|
||||
procs[402]["comm"] = "gamescope"
|
||||
world = World(procs)
|
||||
world.escalate()
|
||||
self.assertNotIn(402, {pid for pid, _ in world.sent})
|
||||
self.assertNotIn(403, {pid for pid, _ in world.sent})
|
||||
|
||||
|
||||
class Quit(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.page = mock.MagicMock()
|
||||
patches = [mock.patch.object(frame_running, "Page", return_value=self.page),
|
||||
mock.patch.object(frame_running, "running", return_value=[
|
||||
{"appid": 620, "gameid": "620", "name": "Portal 2", "kind": "steam", "processes": 4}]),
|
||||
mock.patch.object(frame_running.os, "getuid", return_value=ME, create=True)] # none on Windows
|
||||
for p in patches:
|
||||
p.start()
|
||||
self.addCleanup(p.stop)
|
||||
|
||||
def test_steam_terminate_first(self):
|
||||
scans = iter([frame(), {}])
|
||||
self.page.eval.return_value = {"running": [], "names": {}}
|
||||
with mock.patch.object(frame_running, "snapshot", side_effect=lambda: next(scans)), \
|
||||
mock.patch.object(frame_running, "escalate") as escalate:
|
||||
out = frame_running.quit_game(620, sleep=lambda s: None)
|
||||
self.assertEqual(out["method"], "steam")
|
||||
self.page.eval.assert_any_call('SteamClient.Apps.TerminateApp("620", false)')
|
||||
escalate.assert_not_called()
|
||||
|
||||
def test_signals_when_steam_leaves_it_running(self):
|
||||
now = [0.0]
|
||||
with mock.patch.object(frame_running, "snapshot", return_value=frame()), \
|
||||
mock.patch.object(frame_running, "escalate", return_value="kill") as escalate:
|
||||
out = frame_running.quit_game(620, sleep=lambda s: now.__setitem__(0, now[0] + s), clock=lambda: now[0])
|
||||
escalate.assert_called_once_with(620)
|
||||
self.assertGreaterEqual(now[0], frame_running.STEAM_WAIT)
|
||||
self.assertEqual(out["message"], "Force quit Portal 2 (it had to be killed)")
|
||||
|
||||
def test_without_steam_goes_straight_to_signals(self):
|
||||
frame_running.Page.side_effect = frame_running.Fail("no SharedJSContext page")
|
||||
with mock.patch.object(frame_running, "snapshot", return_value=frame()), \
|
||||
mock.patch.object(frame_running, "escalate", return_value="term") as escalate:
|
||||
out = frame_running.quit_game(620, sleep=self.fail)
|
||||
escalate.assert_called_once_with(620)
|
||||
self.assertEqual(out["method"], "term")
|
||||
|
||||
def test_not_running(self):
|
||||
frame_running.running.return_value = []
|
||||
with mock.patch.object(frame_running, "escalate") as escalate:
|
||||
self.assertEqual(frame_running.quit_game(620)["method"], "gone")
|
||||
escalate.assert_not_called()
|
||||
self.page.eval.assert_not_called()
|
||||
|
||||
|
||||
class Script(unittest.TestCase):
|
||||
def test_server_sends_it_with_frame_steam_inside(self):
|
||||
import server
|
||||
with mock.patch.object(server, "ssh", return_value='{"running": []}') as ssh:
|
||||
self.assertEqual(server.running_games(), {"running": [], "message": "Nothing is running on the Frame"})
|
||||
source = ssh.call_args.kwargs["stdin"]
|
||||
self.assertEqual(ssh.call_args.args[0], "python3 - list")
|
||||
# The same script runs as `python3 -`: frame_steam resolves, and bad usage is one JSON error.
|
||||
r = subprocess.run([sys.executable, "-I", "-", "bogus"], input=source, capture_output=True, text=True,
|
||||
cwd=tempfile.gettempdir(), timeout=30)
|
||||
self.assertEqual(r.returncode, 1, r.stderr)
|
||||
self.assertEqual(json.loads(r.stdout), {"error": "usage: list | quit APPID"})
|
||||
|
||||
|
||||
class Server(unittest.TestCase):
|
||||
def setUp(self):
|
||||
import server
|
||||
self.server = server
|
||||
|
||||
def quit(self, listed, quit_result=None, stop_error=None):
|
||||
calls = []
|
||||
|
||||
def frame(*args, timeout=40):
|
||||
calls.append(args)
|
||||
return {"running": listed} if args == ("list",) else quit_result
|
||||
with mock.patch.object(self.server, "running_frame", side_effect=frame), \
|
||||
mock.patch.object(self.server, "ensure_master"), \
|
||||
mock.patch.object(self.server.frame_android, "stop", side_effect=stop_error) as stop:
|
||||
out = self.server.force_quit({"action": "quit", "appid": "3346865537"})
|
||||
return out, calls, stop
|
||||
|
||||
def test_android_app_stops_its_container_first(self):
|
||||
app = {"appid": 3346865537, "kind": "android", "package": "org.example.game", "name": "Example"}
|
||||
out, calls, stop = self.quit([app], {"name": "Example", "method": "gone", "message": "That game isn't running"})
|
||||
stop.assert_called_once_with("org.example.game")
|
||||
self.assertEqual(calls, [("list",), ("quit", "3346865537")])
|
||||
self.assertEqual(out["message"], "Stopped Example")
|
||||
|
||||
def test_android_stop_failure_falls_back_to_processes(self):
|
||||
app = {"appid": 3346865537, "kind": "android", "package": "org.example.game", "name": "Example"}
|
||||
err = self.server.frame_android.FrameError("podman failed")
|
||||
out, calls, _ = self.quit([app], {"name": "Example", "method": "term", "message": "Force quit Example"}, err)
|
||||
self.assertEqual(calls[-1], ("quit", "3346865537"))
|
||||
self.assertEqual(out["message"], "Force quit Example")
|
||||
|
||||
def test_other_games_skip_the_android_path(self):
|
||||
app = {"appid": 3346865537, "kind": "devkit", "title": "Cool_Game", "name": "Cool_Game"}
|
||||
out, _, stop = self.quit([app], {"name": "Cool_Game", "method": "steam", "message": "Quit Cool_Game"})
|
||||
stop.assert_not_called()
|
||||
self.assertEqual(out["message"], "Quit Cool_Game")
|
||||
|
||||
def test_not_running_is_a_conflict(self):
|
||||
with self.assertRaises(self.server.Failure) as cm:
|
||||
self.quit([])
|
||||
self.assertEqual(cm.exception.status, 409)
|
||||
|
||||
|
||||
class Routes(test_server.ServerGuards):
|
||||
"""Validation runs before any SSH."""
|
||||
|
||||
def test_input_validation(self):
|
||||
for body in ({"action": "quit", "appid": "620; reboot"}, {"action": "quit", "appid": ""},
|
||||
{"action": "kill", "appid": "620"}, {"appid": "620"}, {"action": "quit", "appid": "12345678901"}):
|
||||
status, payload = self.post("/api/running", body)
|
||||
self.assertEqual(status, 400, f"{body} -> {payload}")
|
||||
|
||||
def test_routes_need_custom_header(self):
|
||||
self.assertEqual(self.request("GET", "/api/running")[0], 403)
|
||||
self.assertEqual(self.request("POST", "/api/running", {"action": "quit", "appid": "620"})[0], 403)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -109,10 +109,6 @@ class ServerGuards(unittest.TestCase):
|
||||
self.assertEqual(self.request("GET", "/api/stream")[0], 403)
|
||||
self.assertEqual(self.request("GET", "/api/shots/image?id=1/250820/20260925225208_1.jpg")[0], 403)
|
||||
self.assertEqual(self.request("POST", "/api/launch", {"appid": "620"})[0], 403)
|
||||
self.assertEqual(self.request("GET", "/api/record")[0], 403)
|
||||
self.assertEqual(self.request("GET", "/api/clips")[0], 403)
|
||||
self.assertEqual(self.request("POST", "/api/record", {"action": "start"})[0], 403)
|
||||
self.assertEqual(self.request("POST", "/api/clips/export", {"id": "1/video/bg_620_20261020_201950"})[0], 403)
|
||||
|
||||
def test_captures_are_not_cacheable(self):
|
||||
# Headset captures show everything on screen; nothing may cache them.
|
||||
@@ -138,24 +134,11 @@ class ServerGuards(unittest.TestCase):
|
||||
("/api/shots/save", {"ids": [1]}),
|
||||
("/api/shots/save", {"ids": ["1/250820/../../.ssh/id_ed25519"]}),
|
||||
("/api/shots/save", {"ids": ["1/250820/20260925225208_1.jpg; rm -rf ~"]}),
|
||||
("/api/record", {}),
|
||||
("/api/record", {"action": "explode"}),
|
||||
("/api/clips/export", {}),
|
||||
("/api/clips/export", {"id": 5}),
|
||||
("/api/clips/export", {"id": "1/video/../../../../.ssh"}),
|
||||
("/api/clips/export", {"id": "1/video/bg;rm -rf ~"}),
|
||||
("/api/clips/export", {"id": "../1/video/bg"}),
|
||||
]
|
||||
for path, body in cases:
|
||||
status, payload = self.post(path, body)
|
||||
self.assertEqual(status, 400, f"{path} {body} -> {payload}")
|
||||
|
||||
def test_recorder_idle_until_started(self):
|
||||
status, _, payload = self.request("GET", "/api/record", headers={"X-Frame-UI": "1"})
|
||||
self.assertEqual((status, json.loads(payload)), (200, {"state": "idle"}))
|
||||
status, payload = self.post("/api/record", {"action": "stop"})
|
||||
self.assertEqual(status, 409, payload)
|
||||
|
||||
def test_showing_a_shot_needs_it_saved_here(self):
|
||||
status, payload = self.post("/api/open", {"what": "shot", "id": "1/250820/19990101000000_1.jpg"})
|
||||
self.assertEqual(status, 404, payload)
|
||||
@@ -547,14 +530,6 @@ class LocalMode(unittest.TestCase):
|
||||
self.assertEqual(status, 200, body)
|
||||
self.assertIsInstance(body["titles"], list)
|
||||
|
||||
def test_recordings_are_for_a_computer(self):
|
||||
for method, path, body in (("GET", "/api/record", None), ("GET", "/api/clips", None),
|
||||
("POST", "/api/record", {"action": "start"}),
|
||||
("POST", "/api/clips/export", {"id": "1/video/bg_620_20261020_201950"})):
|
||||
status, payload = self.request(method, path, body)
|
||||
self.assertEqual(status, 400, (path, payload))
|
||||
self.assertIn("computer", payload["error"])
|
||||
|
||||
def test_open_is_for_the_app_and_power_needs_a_password(self):
|
||||
self.assertEqual(self.request("POST", "/api/open", {"what": "terminal"})[0], 400)
|
||||
status, body = self.request("POST", "/api/open", {"what": "reboot"})
|
||||
|
||||
+2
-2
@@ -6,9 +6,9 @@ const pick = (s,a,b) => s.slice(s.indexOf(a),s.indexOf(b,s.indexOf(a)));
|
||||
const tick = async () => { for (let i=0;i<16;i++) await Promise.resolve(); };
|
||||
function connectionFixture() {
|
||||
const f=workspaceFixture(), c=f.context;
|
||||
Object.assign(c,{URLSearchParams,Date,clearTimeout,link:{s:{phase:'connected'},device:'a',phase:'connected',rev:0},disp:{list:[],seq:0},cat:{apps:null},wi:{},devGen:1,androidSeq:0,androidPending:new Set(),titlesSeq:0,volTimer:null,refreshing:null,lastImg:null,lastShot:null,
|
||||
Object.assign(c,{URLSearchParams,Date,clearTimeout,link:{s:{phase:'connected'},device:'a',phase:'connected',rev:0},disp:{list:[],seq:0},cat:{apps:null},wi:{},devGen:1,androidSeq:0,androidPending:new Set(),titlesSeq:0,runningGames:[],runningSeq:0,volTimer:null,refreshing:null,lastImg:null,lastShot:null,
|
||||
sourceState:{jobs:new Map(),detail:null,detailRequest:0},touches:new Map(),gesture:null,padType:{blur(){},value:''},
|
||||
log(){},renderPill(){},renderConnDlg(){},renderHome(){},resetShots(){},resetClips(){},renderBanner(){},loadDevices(){},renderDevices(){},renderTests(){},viaText(){return 'test';},netLabel(){return 'test';},refresh:()=>Promise.resolve(),reloadAll(){},checkContactPrompt(){},ctrlReset(){},padShow:s=>{c.pad.state=s.state;}});
|
||||
log(){},renderPill(){},renderConnDlg(){},renderHome(){},resetShots(){},renderBanner(){},loadDevices(){},renderDevices(){},renderTests(){},viaText(){return 'test';},netLabel(){return 'test';},refresh:()=>Promise.resolve(),reloadAll(){},checkContactPrompt(){},ctrlReset(){},padShow:s=>{c.pad.state=s.state;}});
|
||||
c.window.connDevice='a';
|
||||
f.run('const UI_KEY="test";'+pick(html,'const HEADSET_FREE =','// What a panel shows'));
|
||||
f.run(pick(html,'function onConnection(s) {','// Read the event stream'));
|
||||
|
||||
@@ -47,3 +47,5 @@
|
||||
@media (max-width:900px) { .cc-workspace { grid-template-columns:minmax(0,1fr); }.cc-sidebar { position:static; }.cc-sidebar > p,.cc-status { display:none; }.cc-categories { flex-direction:row; overflow-x:auto; padding-bottom:6px; }.cc-categories button { flex:none; white-space:nowrap; }.cc-category-count { margin-left:2px; }.cc-categories button[aria-pressed=true] { box-shadow:inset 0 -2px var(--blue); }.cc-summary { gap:10px; }.cc-metric { padding:15px; } }
|
||||
@media (max-width:640px) { .cc { gap:20px; }.cc-hero { padding:22px 20px; }.cc-hero p { font-size:12px; }.cc-hero-mark { width:72px; height:55px; }.cc-summary { grid-template-columns:repeat(2,minmax(0,1fr)); }.cc-metric > strong { font-size:24px; }.cc-topline { gap:8px; }.cc-sample { order:3; width:100%; }.cc-device-facts { padding:14px; }.cc-device-facts .cc-readings { grid-template-columns:repeat(2,minmax(0,1fr)); }.cc-cards { grid-template-columns:minmax(0,1fr); gap:12px; }.cc-search-row { gap:8px; }.cc-results { font-size:10px; }.cc-card { padding:20px; }.cc-card h2 { font-size:18px; } }
|
||||
@media (max-width:640px), (max-height:500px) and (hover:none) { .cc-links a { min-height:44px; }.cc-audio-actions button,.cc-topline button { min-height:44px; }.cc-search button { min-width:36px; min-height:44px; } }
|
||||
.cc-running { list-style:none; margin:12px 0 0; padding:0; display:grid; gap:6px; }.cc-running:empty { display:none; }.cc-running li { display:flex; align-items:center; justify-content:space-between; gap:10px; padding:8px 10px; border-radius:6px; background:#ffffff0a; }.cc-running span { min-width:0; overflow-wrap:anywhere; }.cc-running small { display:block; font-size:11px; color:var(--muted); }.cc-running button { border-radius:5px; flex:none; }
|
||||
@media (max-width:640px), (max-height:500px) and (hover:none) { .cc-running button { min-height:44px; } }
|
||||
+73
-4
@@ -54,6 +54,9 @@
|
||||
{id:'steam', category:'apps', icon:'game', title:'Steam library', kind:'flow', label:'Existing controls',
|
||||
description:'Browse owned games and Frame ratings, install with progress, or launch an installed game. Purchases and license prompts use Steam.',
|
||||
keywords:'games download install store owned compatibility rating verified proton', links:[['#library','Installed games'],['#getgames','Library & store']]},
|
||||
{id:'forcequit', category:'apps', icon:'power', title:'Force quit a game', kind:'control', label:'Available here',
|
||||
description:'See what’s running on the Frame and quit a game or app that has stopped responding. Steam is asked first; if the game stays open, its own processes are stopped. Unsaved progress is lost.',
|
||||
keywords:'hang hung frozen freeze crash stuck kill close stop end task running not responding exit', special:'forcequit'},
|
||||
{id:'android', category:'apps', icon:'apps', title:'Android apps', kind:'flow', label:'Existing controls',
|
||||
description:'Discover apps, manage Lepton instances, and launch, stop, test or remove installed apps. View compatibility reports before installing.',
|
||||
keywords:'apk fdroid lepton application sideload sources repository reports', links:[['#appStore','Discover apps'],['#androidLibrary','Manage installed apps']]},
|
||||
@@ -129,6 +132,8 @@
|
||||
categories.find(([id])=>id === item.category)?.[1]].join(' ').toLowerCase();
|
||||
return (category === 'all' || item.category === category) && query.toLowerCase().trim().split(/\s+/).every(word => text.includes(word));
|
||||
}
|
||||
const esc = value => String(value).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''})[c]);
|
||||
const KINDS = {steam:'Steam game', devkit:'Sideloaded game', shortcut:'Non-Steam shortcut', android:'Android app'};
|
||||
const number = (value, suffix = '', digits = 0) => Number.isFinite(value) ? value.toLocaleString(undefined, {maximumFractionDigits:digits}) + suffix : 'Unavailable';
|
||||
const gib = value => Number.isFinite(value) ? number(value / 1073741824, ' GiB', 1) : 'Unavailable';
|
||||
const duration = seconds => Number.isFinite(seconds) && seconds >= 0 ? seconds < 3600 ? `${Math.floor(seconds / 60)} min` : `${Math.floor(seconds / 3600)} h ${Math.floor(seconds % 3600 / 60)} min` : 'Unavailable';
|
||||
@@ -160,9 +165,30 @@
|
||||
// Strict validation and captured device identity apply even if a stale enabled
|
||||
// button is clicked during a disconnect, headset switch, or pending request.
|
||||
function createController({api, getContext}) {
|
||||
let busy = false;
|
||||
let busy = false, quitting = false;
|
||||
const connected = message => {
|
||||
const context = getContext();
|
||||
if (context.online !== true) throw new Error(message);
|
||||
return context;
|
||||
};
|
||||
return {
|
||||
get busy() { return busy; },
|
||||
get quitting() { return quitting; },
|
||||
async running() {
|
||||
const context = connected('Connect to the Frame to see what’s running.');
|
||||
const result = await api('/api/running', undefined, context.device);
|
||||
return getContext().generation === context.generation ? result : null;
|
||||
},
|
||||
async forceQuit(app) {
|
||||
if (quitting) throw new Error('A force quit is still in progress.');
|
||||
if (!/^\d{1,10}$/.test(String(app?.appid))) throw new Error('Choose a running game to quit.');
|
||||
const context = connected('Connect to the Frame before quitting a game.');
|
||||
quitting = true;
|
||||
try {
|
||||
const result = await api('/api/running', {action:'quit', appid:String(app.appid)}, context.device);
|
||||
return getContext().generation === context.generation ? result : null;
|
||||
} finally { quitting = false; }
|
||||
},
|
||||
async audio(change) {
|
||||
if (busy) throw new Error('An audio change is still in progress.');
|
||||
const context = getContext();
|
||||
@@ -180,16 +206,17 @@
|
||||
},
|
||||
};
|
||||
}
|
||||
function mount({document, api, refresh, refreshAudio = refresh, getContext, openConnection, platform}) {
|
||||
function mount({document, api, refresh, refreshAudio = refresh, getContext, openConnection, platform, confirm = text => globalThis.confirm(text)}) {
|
||||
const get = id => document.getElementById(id), page = get('controlCenter');
|
||||
let category = 'all', sample = null, receivedAt = null, available = false, error = '', dirty = false, sampleGeneration = null, audioPending = false;
|
||||
const metric = (id, label) => `<div><dt>${label}</dt><dd data-cc-metric="${id}">Unavailable</dd></div>`;
|
||||
const perf = `<dl class="cc-readings">${[['appFps','Application FPS'],['frame','Compositor period'],['render','Render GPU time'],['compositorCpu','Compositor CPU'],['cpu','System CPU'],['gpu','GPU clock'],['temperature','Hottest sensor']].map(([id,label])=>metric(id,label)).join('')}</dl><p class="cc-note">GPU time is render time, not utilisation. The hottest sensor is not necessarily CPU temperature.</p><p class="cc-note" data-cc-metric="thermal">Trip data unavailable</p>`;
|
||||
const audio = `<div class="cc-audio"><label for="ccVolume">Output volume <output id="ccVolumeValue" for="ccVolume">—</output></label><input id="ccVolume" type="range" min="0" max="100" step="1" value="0" disabled><div class="cc-audio-actions"><button class="action small" id="ccApplyVolume" disabled>Apply volume</button><button class="small" id="ccMute" disabled>Mute</button><span id="ccAudioReadback" class="cc-note">Waiting for an audio reading</span></div><p class="cc-note" id="ccAudioResult" role="status"></p></div>`;
|
||||
const health = `<dl class="cc-readings">${[['battery','Charge'],['power','Battery power · signed'],['charger','Charger'],['estimate','Battery estimate'],['batteryTemp','Battery temperature'],['batteryHealth','Battery health']].map(([id,label])=>metric(id,label)).join('')}</dl>`;
|
||||
const forcequit = `<div class="cc-quit"><div class="cc-audio-actions"><button class="small" type="button" id="ccRunningCheck">Check what’s running</button></div><ul class="cc-running" id="ccRunningList"></ul><p class="cc-note" id="ccRunningResult" role="status"></p></div>`;
|
||||
const storage = `<dl class="cc-readings">${[['storage','User storage free'],['rootFree','System storage free'],['rootTotal','System storage total'],['memoryAvailable','Memory available']].map(([id,label])=>metric(id,label)).join('')}</dl>`;
|
||||
get('ccCategories').innerHTML = categories.map(([id,label,symbol])=>`<button type="button" data-cc-category="${id}" aria-pressed="${id === 'all'}">${icon(symbol)}<span>${label}</span><span class="cc-category-count"></span></button>`).join('');
|
||||
const specials = {audio, performance:perf, health, storage};
|
||||
const specials = {audio, performance:perf, health, storage, forcequit};
|
||||
get('ccCards').innerHTML = catalog.map(item=>`<section class="cc-card" data-cc-card="${item.id}"><div class="cc-card-head"><span class="cc-icon">${icon(item.icon)}</span><span class="cc-kind cc-kind-${item.kind}">${item.label}</span></div><h2>${item.title}</h2><p>${item.description}</p>${specials[item.special] || ''}${item.guidance ? `<div class="cc-guidance">${item.guidance}</div>` : ''}${item.links ? `<div class="cc-links">${item.links.map(([href,label,desktop])=>`<a href="${href}"${desktop ? ' class="desk-only"' : ''}${item.platform === 'mac' ? ' data-cc-mac-link' : ''}>${label}<span aria-hidden="true">↗</span></a>`).join('')}</div>` : ''}</section>`).join('');
|
||||
// Host-only features stay searchable with a reason; only their unsupported
|
||||
// action disappears. The host API, rather than viewport/UA, decides availability.
|
||||
@@ -285,6 +312,48 @@
|
||||
get('ccAudioResult').textContent = `Couldn’t apply audio: ${e.message}`;
|
||||
} finally { audioPending = false; renderSample(); }
|
||||
}
|
||||
// Force quit: an explicit check, then a confirmation for each game. A headset
|
||||
// switch drops the list, so a stale entry can't quit the other Frame's game.
|
||||
let runningApps = [];
|
||||
function renderRunning(message) {
|
||||
get('ccRunningList').innerHTML = runningApps.map(app=>`<li><span>${esc(app.name)}<small>${KINDS[app.kind] || 'Running'}</small></span><button class="small danger" type="button" data-cc-quit="${esc(app.appid)}"${controller.quitting ? ' disabled' : ''}>Force quit…</button></li>`).join('');
|
||||
if (message !== undefined) get('ccRunningResult').textContent = message;
|
||||
}
|
||||
async function checkRunning() {
|
||||
const generation = getContext().generation;
|
||||
get('ccRunningCheck').disabled = true;
|
||||
get('ccRunningResult').textContent = 'Checking…';
|
||||
try {
|
||||
const result = await controller.running();
|
||||
if (!result || generation !== getContext().generation) return;
|
||||
runningApps = Array.isArray(result.running) ? result.running : [];
|
||||
renderRunning(runningApps.length ? `${runningApps.length} running. Force quit only a game that has stopped responding.` : 'Nothing is running on the Frame.');
|
||||
} catch (e) {
|
||||
if (generation !== getContext().generation) return;
|
||||
runningApps = []; renderRunning(`Couldn’t check what’s running: ${e.message}`);
|
||||
} finally { get('ccRunningCheck').disabled = false; }
|
||||
}
|
||||
async function forceQuit(appid) {
|
||||
const app = runningApps.find(item=>String(item.appid) === String(appid));
|
||||
if (!app || controller.quitting) return;
|
||||
if (!confirm(`Force quit ${app.name}? Unsaved progress will be lost.`)) return;
|
||||
const generation = getContext().generation, pending = controller.forceQuit(app);
|
||||
renderRunning(`Quitting ${app.name}…`);
|
||||
try {
|
||||
const result = await pending;
|
||||
if (!result || generation !== getContext().generation) return;
|
||||
runningApps = runningApps.filter(item=>item !== app);
|
||||
renderRunning(result.message || `Quit ${app.name}`);
|
||||
} catch (e) {
|
||||
if (generation !== getContext().generation) return;
|
||||
renderRunning(`Couldn’t force quit ${app.name}: ${e.message}`);
|
||||
} finally { if (generation === getContext().generation) renderRunning(); }
|
||||
}
|
||||
get('ccRunningCheck').onclick = checkRunning;
|
||||
get('ccRunningList').onclick = event => {
|
||||
const button = event.target.closest('[data-cc-quit]');
|
||||
if (button) forceQuit(button.dataset.ccQuit);
|
||||
};
|
||||
get('ccVolume').oninput = () => { dirty = true; get('ccVolumeValue').textContent = `${get('ccVolume').value}%`; };
|
||||
get('ccApplyVolume').onclick = () => changeAudio({level:Number(get('ccVolume').value) / 100});
|
||||
get('ccMute').onclick = () => changeAudio({muted:!sample?.volume?.muted});
|
||||
@@ -310,7 +379,7 @@
|
||||
},
|
||||
unavailable(reason) { if (reason?.stale) return; available = false; error = `No live sample${reason?.message ? ' · ' + reason.message : ''}`; renderSample(); },
|
||||
connection(ok) { if (!ok) { available = false; renderSample(); } else audioAvailability(); },
|
||||
reset() { sample = null; receivedAt = null; available = false; error = ''; dirty = false; get('ccVolume').value = 0; get('ccAudioResult').textContent = ''; renderSample(); },
|
||||
reset() { sample = null; receivedAt = null; available = false; error = ''; dirty = false; get('ccVolume').value = 0; get('ccAudioResult').textContent = ''; runningApps = []; renderRunning(''); renderSample(); },
|
||||
destroy() { clearInterval(timer); },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,580 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Video from the headset: recordings of what it shows, with its sound, and Steam's own clips.
|
||||
|
||||
Two halves share this file.
|
||||
|
||||
On the computer, server.py builds the shell commands below, runs them over SSH and
|
||||
copies the finished .mp4 to ~/Videos/SteamFrame (Recorder does a recording from Start
|
||||
to the copy; export_clip does a Steam clip). Nothing here needs ffmpeg on the computer.
|
||||
|
||||
On the Frame, this file runs as `python3 - list` or `python3 - export ID` (sent on
|
||||
stdin, like frame_steam.py, so stdlib only): it lists Steam's game recordings and
|
||||
stitches one into a single .mp4 with SteamOS's ffmpeg, copying the streams as they are.
|
||||
It prints one JSON object, or {"error": ...}.
|
||||
|
||||
Steam's game recording keeps DASH segments, one folder per recording session:
|
||||
|
||||
~/.local/share/Steam/userdata/<account>/gamerecordings/
|
||||
video/bg_<appid>_<YYYYMMDD>_<HHMMSS>/ background recording
|
||||
clips/clip_<appid>_<YYYYMMDD>_<HHMMSS>/video/bg_<appid>_<...>/ a saved clip
|
||||
session.mpd
|
||||
init-stream0.m4s chunk-stream0-00001.m4s chunk-stream0-00002.m4s ...
|
||||
init-stream1.m4s chunk-stream1-00001.m4s ...
|
||||
|
||||
Each stream's init segment followed by its chunks, in order, is a fragmented MP4 of
|
||||
that stream. The folder names are as users and Steam's own files describe them; the
|
||||
listing doesn't depend on them: any folder under clips/ or video/ (up to four levels)
|
||||
holding init-stream*.m4s counts as a session.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
# ---- where things go ---------------------------------------------------------
|
||||
|
||||
VIDEOS_DIR = Path.home() / "Videos" / "SteamFrame" # on the computer, beside ~/Pictures/SteamFrame
|
||||
# On the Frame, relative to its home: recordings in progress and stitched exports.
|
||||
# Not /tmp: it's a RAM disk there, and a recording can be over a gigabyte.
|
||||
WORK = ".cache/frame-control/video"
|
||||
|
||||
# ---- recording what the headset shows ------------------------------------------
|
||||
#
|
||||
# The same picture the live view streams: SteamVR's copy of the headset view in the
|
||||
# v4l2loopback device, encoded with x264 (the hardware encoder crashes ffmpeg). The
|
||||
# sound is the monitor of PipeWire's default output, read through its PulseAudio
|
||||
# server: SteamOS's ffmpeg has the pulse device (the media player writes to it, see
|
||||
# docs/vr-video.md). If it can't be read, the recording goes ahead without sound and
|
||||
# says so. Both inputs are stamped with the wall clock: the camera device and the
|
||||
# audio server would otherwise count from different clocks.
|
||||
|
||||
STREAM_DEVICE = "/dev/video99"
|
||||
AUDIO_SOURCE = "@DEFAULT_MONITOR@" # PulseAudio's name for the default output's monitor
|
||||
MAX_SECONDS = 20 * 60
|
||||
FPS = 30
|
||||
VIDEO_RATE = 8 # Mbit/s at 1080p
|
||||
AUDIO_RATE = 160 # kbit/s AAC
|
||||
# Room for a full-length recording twice over (the .mkv, then the .mp4 made from it).
|
||||
NEED_KB = (VIDEO_RATE * 1000 + AUDIO_RATE) * MAX_SECONDS // 8 * 2 + 512 * 1024
|
||||
REC_NAME = re.compile(r"rec-\d{8}-\d{6}")
|
||||
|
||||
|
||||
class ClipError(Exception):
|
||||
def __init__(self, message, status=502):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
|
||||
|
||||
def recording_name(now=None):
|
||||
return time.strftime("rec-%Y%m%d-%H%M%S", time.localtime(now))
|
||||
|
||||
|
||||
def probe_command():
|
||||
"""Checks before a recording, run on the Frame: prints audio=1 or audio=0.
|
||||
|
||||
One recording runs at a time, so anything left in the folder is from one that was
|
||||
cut off (the app quit, or the copy failed); it's removed to free the space."""
|
||||
return (f"set -u; export XDG_RUNTIME_DIR=${{XDG_RUNTIME_DIR:-/run/user/$(id -u)}}; "
|
||||
f"[ -e {STREAM_DEVICE} ] || {{ echo 'No headset view device ({STREAM_DEVICE}). Is SteamVR running?' >&2; exit 3; }}; "
|
||||
f"command -v ffmpeg >/dev/null || {{ echo 'ffmpeg is missing on the Frame' >&2; exit 3; }}; "
|
||||
f"d=\"$HOME/{WORK}\"; mkdir -p \"$d\" && rm -f \"$d\"/rec-*; "
|
||||
f"free=$(df -Pk \"$d\" | awk 'NR==2 {{print $4}}'); "
|
||||
f"[ \"${{free:-0}}\" -ge {NEED_KB} ] || {{ echo 'Not enough free space on the Frame to record: "
|
||||
f"it needs {NEED_KB // 1024 // 1024 + 1} GB' >&2; exit 4; }}; "
|
||||
f"if timeout 5 ffmpeg -hide_banner -loglevel error -nostdin -f pulse -i {AUDIO_SOURCE} -t 0.2 -f null - "
|
||||
f">/dev/null 2>&1; then echo audio=1; else echo audio=0; fi")
|
||||
|
||||
|
||||
def record_command(name, audio, max_seconds=MAX_SECONDS):
|
||||
"""The recording, run on the Frame through `bash -c`.
|
||||
|
||||
ffmpeg runs in the background while the shell watches its stdin, which is the SSH
|
||||
channel: when that closes (Stop closed it, or the computer's ssh went away) the
|
||||
shell sends ffmpeg SIGTERM, which makes it finish the file properly (as q or
|
||||
Ctrl-C would; SIGINT itself is ignored by a background job of a script). A recording
|
||||
that ends by itself (the time limit, an error) ends the wait too. The shell prints
|
||||
"started" once ffmpeg is running and "exit N" when it has gone."""
|
||||
if not REC_NAME.fullmatch(name):
|
||||
raise ValueError(f"bad recording name {name!r}")
|
||||
if not 1 <= max_seconds <= MAX_SECONDS:
|
||||
raise ValueError("max_seconds out of range")
|
||||
clock = "-thread_queue_size 1024 -use_wallclock_as_timestamps 1"
|
||||
inputs = f"{clock} -f v4l2 -video_size 1920x1080 -i {STREAM_DEVICE}"
|
||||
maps = "-map 0:v:0"
|
||||
codecs = (f"-vf fps={FPS},scale=-2:1080,format=yuv420p -c:v libx264 -preset ultrafast "
|
||||
f"-b:v {VIDEO_RATE}M -maxrate {VIDEO_RATE}M -bufsize {VIDEO_RATE * 2}M -g {FPS * 2}")
|
||||
if audio:
|
||||
inputs += f" {clock} -f pulse -i {AUDIO_SOURCE}"
|
||||
maps += " -map 1:a:0"
|
||||
codecs += f" -af aresample=async=1 -c:a aac -b:a {AUDIO_RATE}k"
|
||||
script = (f"export XDG_RUNTIME_DIR=${{XDG_RUNTIME_DIR:-/run/user/$(id -u)}}; d=\"$HOME/{WORK}\"; "
|
||||
f"ffmpeg -hide_banner -loglevel error -nostdin -y {inputs} {maps} {codecs} -t {max_seconds} "
|
||||
f"\"$d/{name}.mkv\" </dev/null >/dev/null 2>\"$d/{name}.log\" & p=$!; "
|
||||
f"echo started; "
|
||||
f"while kill -0 $p 2>/dev/null; do read -r -t 1 _; r=$?; [ $r -eq 0 ] || [ $r -gt 128 ] || break; done; "
|
||||
f"kill $p 2>/dev/null; wait $p; echo \"exit $?\"")
|
||||
return "bash -c " + shlex.quote(script)
|
||||
|
||||
|
||||
def finish_command(name):
|
||||
"""After the recording: make the .mp4 the computer gets (no re-encode), on the Frame."""
|
||||
if not REC_NAME.fullmatch(name):
|
||||
raise ValueError(f"bad recording name {name!r}")
|
||||
return (f"cd \"$HOME/{WORK}\" || exit 1; "
|
||||
f"[ -s {name}.mkv ] || {{ tail -c 2000 {name}.log >&2 2>/dev/null; echo 'The recording is empty' >&2; exit 1; }}; "
|
||||
f"ffmpeg -hide_banner -loglevel error -nostdin -y -i {name}.mkv -map 0 -c copy -movflags +faststart {name}.mp4 "
|
||||
f"&& rm -f {name}.mkv && wc -c < {name}.mp4")
|
||||
|
||||
|
||||
def cleanup_command(name):
|
||||
if not REC_NAME.fullmatch(name):
|
||||
raise ValueError(f"bad recording name {name!r}")
|
||||
return f"rm -f \"$HOME/{WORK}/{name}\".*"
|
||||
|
||||
|
||||
class Recorder:
|
||||
"""One recording at a time, from Start to the .mp4 on this computer.
|
||||
|
||||
The server supplies how to reach the Frame, so this can be tested without one:
|
||||
open_channel(command, stderr) -> Popen of `command` on the Frame, stdin and stdout pipes
|
||||
run(command, timeout) -> its stdout; raises on failure
|
||||
fetch(remote, local) copies a file from the Frame (a path relative to its home)
|
||||
start_thread(fn) starts fn in a thread that counts as headset work
|
||||
release(proc) forgets a channel once it has closed
|
||||
"""
|
||||
|
||||
def __init__(self, open_channel, run, fetch, start_thread, release=lambda proc: None, folder=None):
|
||||
self.open_channel, self.run, self.fetch = open_channel, run, fetch
|
||||
self.start_thread, self.release = start_thread, release
|
||||
self.folder = Path(folder) if folder else VIDEOS_DIR
|
||||
self._lock = threading.Lock()
|
||||
self._state = {"state": "idle"}
|
||||
self._proc = None
|
||||
|
||||
def status(self):
|
||||
with self._lock:
|
||||
s = dict(self._state)
|
||||
if s["state"] == "recording":
|
||||
s["elapsed"] = round(time.time() - s["started"], 1)
|
||||
return s
|
||||
|
||||
def start(self):
|
||||
with self._lock:
|
||||
if self._state["state"] in ("starting", "recording", "stopping", "saving"):
|
||||
raise ClipError("Already recording, or still saving the last recording", 409)
|
||||
self._state = {"state": "starting"}
|
||||
try:
|
||||
out = self.run(probe_command(), 30)
|
||||
audio = "audio=1" in out
|
||||
name = recording_name()
|
||||
errors = tempfile.TemporaryFile()
|
||||
proc = self.open_channel(record_command(name, audio), errors)
|
||||
lines = _line_reader(proc.stdout)
|
||||
first = _next_line(lines, 20)
|
||||
if first != "started":
|
||||
_end(proc)
|
||||
errors.seek(0)
|
||||
err = errors.read().decode(errors="replace").strip()
|
||||
errors.close()
|
||||
self.release(proc)
|
||||
raise ClipError(err or "The Frame didn't start recording")
|
||||
except BaseException as e:
|
||||
with self._lock:
|
||||
self._state = {"state": "failed", "error": str(e)}
|
||||
raise
|
||||
with self._lock:
|
||||
self._proc = proc
|
||||
self._state = {"state": "recording", "name": name, "audio": audio, "started": time.time(),
|
||||
"limit": MAX_SECONDS}
|
||||
try:
|
||||
self.start_thread(lambda: self._watch(proc, name, audio, lines, errors))
|
||||
except BaseException:
|
||||
_end(proc)
|
||||
self.release(proc)
|
||||
with self._lock:
|
||||
self._state, self._proc = {"state": "failed", "error": "Couldn't follow the recording"}, None
|
||||
raise
|
||||
return dict(self.status(), message="Recording" + ("" if audio else
|
||||
" without sound: the Frame's audio couldn't be read"))
|
||||
|
||||
def stop(self):
|
||||
"""Ends the recording; the copy to this computer carries on in the background."""
|
||||
with self._lock:
|
||||
if self._state["state"] != "recording":
|
||||
raise ClipError("Not recording", 409)
|
||||
self._state = dict(self._state, state="stopping")
|
||||
proc = self._proc
|
||||
_close(proc.stdin) # the shell on the Frame sees EOF and stops ffmpeg
|
||||
return {"state": "stopping", "message": "Stopping the recording…"}
|
||||
|
||||
def _watch(self, proc, name, audio, lines, errors):
|
||||
# Waits for ffmpeg to finish: after Stop, or at the time limit (a margin
|
||||
# past it, so a stuck channel can't hold the recording open forever).
|
||||
deadline = time.time() + MAX_SECONDS + 60
|
||||
while True:
|
||||
stopping = self.status()["state"] == "stopping"
|
||||
line = _next_line(lines, 30 if stopping else 5)
|
||||
if line is None or line.startswith("exit "):
|
||||
break # ffmpeg has gone and the file is finished
|
||||
if line == "" and (stopping or time.time() > deadline):
|
||||
break # no answer within 30 s of Stop, or well past the limit: close the channel
|
||||
_end(proc)
|
||||
errors.close()
|
||||
self.release(proc)
|
||||
with self._lock:
|
||||
self._proc = None
|
||||
seconds = round(time.time() - self._state["started"])
|
||||
self._state = dict(self._state, state="saving")
|
||||
try:
|
||||
self.save(name)
|
||||
msg = f"Saved {name}.mp4 to ~/Videos/SteamFrame" + ("" if audio else " (no sound)")
|
||||
state = {"state": "saved", "file": str(self.folder / f"{name}.mp4"), "audio": audio,
|
||||
"seconds": seconds, "message": msg}
|
||||
except Exception as e:
|
||||
state = {"state": "failed", "error": f"Couldn't save the recording: {e}"}
|
||||
finally:
|
||||
try:
|
||||
self.run(cleanup_command(name), 20)
|
||||
except Exception:
|
||||
pass # the next recording's checks remove it
|
||||
with self._lock:
|
||||
self._state = state
|
||||
|
||||
def save(self, name):
|
||||
"""Make the .mp4 on the Frame and copy it here, never leaving a partial file in the folder."""
|
||||
out = self.run(finish_command(name), 600)
|
||||
size = int(out.strip().splitlines()[-1]) if out.strip() else 0
|
||||
_make_room(self.folder, size)
|
||||
incoming = Path(tempfile.mkdtemp(prefix=".incoming-", dir=self.folder))
|
||||
try:
|
||||
self.fetch(f"{WORK}/{name}.mp4", incoming / f"{name}.mp4")
|
||||
os.replace(incoming / f"{name}.mp4", self.folder / f"{name}.mp4")
|
||||
finally:
|
||||
shutil.rmtree(incoming, ignore_errors=True)
|
||||
|
||||
|
||||
def _make_room(folder, size):
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
free = shutil.disk_usage(folder).free
|
||||
if size and free < size + 256 * 1024**2:
|
||||
raise ClipError(f"Not enough free space on this computer: it needs {size // 1024**2 + 256} MB", 507)
|
||||
|
||||
|
||||
def _close(f):
|
||||
try:
|
||||
f.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _end(proc):
|
||||
"""Close our end of the channel and make sure the local ssh has gone."""
|
||||
_close(proc.stdin)
|
||||
try:
|
||||
proc.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
proc.wait()
|
||||
_close(proc.stdout)
|
||||
|
||||
|
||||
def _line_reader(pipe):
|
||||
"""Lines from a pipe via a thread (select() can't wait on pipes on Windows); None at EOF."""
|
||||
import queue
|
||||
lines = queue.Queue()
|
||||
|
||||
def pump():
|
||||
try:
|
||||
for raw in iter(pipe.readline, b""):
|
||||
lines.put(raw.decode(errors="replace").strip())
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
lines.put(None)
|
||||
|
||||
threading.Thread(target=pump, daemon=True).start()
|
||||
return lines
|
||||
|
||||
|
||||
def _next_line(lines, timeout):
|
||||
"""The next line, None at EOF, or "" after `timeout` seconds of silence."""
|
||||
import queue
|
||||
try:
|
||||
return lines.get(timeout=timeout)
|
||||
except queue.Empty:
|
||||
return ""
|
||||
|
||||
|
||||
# ---- Steam's game recordings ---------------------------------------------------
|
||||
|
||||
STEAM_USERDATA = ".local/share/Steam/userdata"
|
||||
KINDS = {"clips": "clip", "video": "background"}
|
||||
MAX_DEPTH = 4 # folders below clips/ or video/
|
||||
PART = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.-]{0,99}") # no leading dot, so never "." or ".."
|
||||
INIT = re.compile(r"init-stream(\d{1,3})\.m4s")
|
||||
CHUNK = re.compile(r"chunk-stream(\d{1,3})-(\d{1,9})\.m4s")
|
||||
STAMP = re.compile(r"(?:^|_)(\d{1,10})_(\d{8})_(\d{6})$")
|
||||
EXPORT_PATH = re.compile(re.escape(WORK) + r"/export-[0-9a-f]{16}/[A-Za-z0-9_][A-Za-z0-9_.-]{0,99}\.mp4")
|
||||
|
||||
|
||||
def parse_id(clip_id):
|
||||
"""A recording's id, "<account>/<clips|video>/<folder>[/<folder>...]", as path parts.
|
||||
|
||||
Checked before it goes near a path or a shell: plain names only, no "." or "..",
|
||||
at most MAX_DEPTH folders. Raises ValueError."""
|
||||
parts = clip_id.split("/") if isinstance(clip_id, str) and len(clip_id) <= 600 else []
|
||||
if (len(parts) < 3 or len(parts) > 2 + MAX_DEPTH or not re.fullmatch(r"\d{1,12}", parts[0])
|
||||
or parts[1] not in KINDS or not all(PART.fullmatch(p) for p in parts[2:])):
|
||||
raise ValueError("bad clip id")
|
||||
return parts
|
||||
|
||||
|
||||
def export_name(clip_id):
|
||||
"""The .mp4's name on the computer: the clip's (or background session's) own folder name."""
|
||||
return parse_id(clip_id)[2] + ".mp4"
|
||||
|
||||
|
||||
def read_session(folder):
|
||||
"""{stream number: [init, chunk, chunk...]} for one session folder, chunks in number
|
||||
order. A stream without its init segment or without chunks can't be played, so it's left out."""
|
||||
inits, chunks = {}, {}
|
||||
for entry in os.scandir(folder):
|
||||
if not entry.is_file(follow_symlinks=False):
|
||||
continue
|
||||
m = INIT.fullmatch(entry.name)
|
||||
if m:
|
||||
inits[int(m[1])] = entry.path
|
||||
continue
|
||||
m = CHUNK.fullmatch(entry.name)
|
||||
if m:
|
||||
chunks.setdefault(int(m[1]), []).append((int(m[2]), entry.path))
|
||||
return {n: [inits[n], *(p for _, p in sorted(chunks[n]))] for n in sorted(inits) if chunks.get(n)}
|
||||
|
||||
|
||||
def chunk_gaps(files):
|
||||
"""How many chunk numbers are missing between the first and last (Steam deleted or lost them)."""
|
||||
nums = sorted(int(CHUNK.fullmatch(os.path.basename(f))[2]) for f in files[1:])
|
||||
return nums[-1] - nums[0] + 1 - len(nums) if nums else 0
|
||||
|
||||
|
||||
def mpd_duration(text):
|
||||
"""Seconds from the manifest's mediaPresentationDuration ("PT1M23.4S"), or None."""
|
||||
m = re.search(r'mediaPresentationDuration="P(?:(\d+)D)?T?(?:(\d+)H)?(?:(\d+)M)?(?:([\d.]+)S)?"', text or "")
|
||||
if not m or not any(m.groups()):
|
||||
return None
|
||||
d, h, mi, s = m.groups()
|
||||
try:
|
||||
return int(d or 0) * 86400 + int(h or 0) * 3600 + int(mi or 0) * 60 + float(s or 0)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _sessions(base, depth=0):
|
||||
"""Folders under base (clips/ or video/) that hold init segments, without following links."""
|
||||
try:
|
||||
entries = list(os.scandir(base))
|
||||
except OSError:
|
||||
return
|
||||
if any(e.is_file(follow_symlinks=False) and INIT.fullmatch(e.name) for e in entries):
|
||||
yield base
|
||||
return
|
||||
if depth < MAX_DEPTH:
|
||||
for e in sorted(entries, key=lambda e: e.name):
|
||||
if e.is_dir(follow_symlinks=False) and PART.fullmatch(e.name):
|
||||
yield from _sessions(e.path, depth + 1)
|
||||
|
||||
|
||||
def describe(userdata, clip_id):
|
||||
"""What the list shows about one recording, or None if it holds nothing playable."""
|
||||
parts = parse_id(clip_id)
|
||||
folder = os.path.join(userdata, parts[0], "gamerecordings", *parts[1:])
|
||||
streams = read_session(folder)
|
||||
if not streams:
|
||||
return None
|
||||
files = [f for s in streams.values() for f in s]
|
||||
stats = [os.stat(f) for f in files]
|
||||
duration = None
|
||||
for mpd in sorted(p for p in os.listdir(folder) if p.endswith(".mpd")):
|
||||
try:
|
||||
duration = mpd_duration(Path(folder, mpd).read_text(errors="replace")[:20000])
|
||||
except OSError:
|
||||
pass
|
||||
if duration is not None:
|
||||
break
|
||||
appid, when = None, max(s.st_mtime for s in stats)
|
||||
for p in parts[2:]:
|
||||
m = STAMP.search(p)
|
||||
if m:
|
||||
appid = m[1]
|
||||
try:
|
||||
when = time.mktime(time.strptime(m[2] + m[3], "%Y%m%d%H%M%S"))
|
||||
except ValueError:
|
||||
pass
|
||||
break
|
||||
return {"id": clip_id, "kind": KINDS[parts[1]], "appid": appid, "time": when,
|
||||
"size": sum(s.st_size for s in stats), "streams": len(streams),
|
||||
"chunks": sum(len(s) - 1 for s in streams.values()),
|
||||
"gaps": sum(chunk_gaps(s) for s in streams.values()), "duration": duration,
|
||||
"file": export_name(clip_id)}
|
||||
|
||||
|
||||
def list_recordings(userdata):
|
||||
"""Every Steam recording session on this Frame, newest first (runs on the Frame)."""
|
||||
found = []
|
||||
try:
|
||||
accounts = sorted(e.name for e in os.scandir(userdata) if e.is_dir(follow_symlinks=False)
|
||||
and re.fullmatch(r"\d{1,12}", e.name))
|
||||
except OSError:
|
||||
return []
|
||||
for account in accounts:
|
||||
root = os.path.join(userdata, account, "gamerecordings")
|
||||
for kind in KINDS:
|
||||
for folder in _sessions(os.path.join(root, kind)):
|
||||
clip_id = "/".join([account, *os.path.relpath(folder, root).split(os.sep)])
|
||||
try:
|
||||
info = describe(userdata, clip_id)
|
||||
except (OSError, ValueError):
|
||||
continue # changed while we looked, or a name we don't take
|
||||
if info:
|
||||
found.append(info)
|
||||
found.sort(key=lambda c: c["time"], reverse=True)
|
||||
return found
|
||||
|
||||
|
||||
def stitch_command(inputs, out):
|
||||
"""ffmpeg that puts each stream file in one .mp4, copying the streams as they are."""
|
||||
cmd = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-nostdin", "-y"]
|
||||
for f in inputs:
|
||||
cmd += ["-i", str(f)]
|
||||
for i in range(len(inputs)):
|
||||
cmd += ["-map", str(i)]
|
||||
return cmd + ["-c", "copy", "-movflags", "+faststart", str(out)]
|
||||
|
||||
|
||||
def export(userdata, clip_id, home=None):
|
||||
"""Stitch one recording into an .mp4 under WORK (runs on the Frame). -> its path
|
||||
relative to home and its size. The computer copies it, then deletes it with
|
||||
remove_command."""
|
||||
home = Path(home or Path.home())
|
||||
parts = parse_id(clip_id)
|
||||
folder = Path(userdata, parts[0], "gamerecordings", *parts[1:])
|
||||
real = os.path.realpath(folder)
|
||||
if os.path.commonpath([real, os.path.realpath(userdata)]) != os.path.realpath(userdata):
|
||||
raise ValueError("bad clip id")
|
||||
streams = read_session(real)
|
||||
if not streams:
|
||||
raise ClipError("That recording has no complete streams on the Frame", 404)
|
||||
size = sum(os.path.getsize(f) for s in streams.values() for f in s)
|
||||
work = home / WORK
|
||||
work.mkdir(parents=True, exist_ok=True)
|
||||
_sweep(work)
|
||||
# The stream files and the .mp4 made from them are each about the recording's size.
|
||||
if shutil.disk_usage(work).free < size * 2 + 64 * 1024**2:
|
||||
raise ClipError(f"Not enough free space on the Frame to export it: it needs {(size * 2) // 1024**2 + 64} MB", 507)
|
||||
out_dir = work / f"export-{secrets.token_hex(8)}"
|
||||
out_dir.mkdir()
|
||||
try:
|
||||
inputs = []
|
||||
for n, files in streams.items():
|
||||
path = out_dir / f"stream{n}.mp4"
|
||||
with open(path, "wb") as dst:
|
||||
for f in files:
|
||||
with open(f, "rb") as src:
|
||||
shutil.copyfileobj(src, dst, 1 << 20)
|
||||
inputs.append(path)
|
||||
out = out_dir / export_name(clip_id)
|
||||
r = subprocess.run(stitch_command(inputs, out), capture_output=True, text=True, errors="replace", timeout=1800)
|
||||
if r.returncode != 0 or not out.exists():
|
||||
raise ClipError("ffmpeg couldn't join the recording: " + (r.stderr.strip()[-1500:] or f"exit {r.returncode}"))
|
||||
for f in inputs:
|
||||
f.unlink()
|
||||
except BaseException:
|
||||
shutil.rmtree(out_dir, ignore_errors=True)
|
||||
raise
|
||||
return {"path": out.relative_to(home).as_posix(), "size": out.stat().st_size}
|
||||
|
||||
|
||||
def _sweep(work, older=6 * 3600):
|
||||
"""Exports left behind by a copy that never finished."""
|
||||
for d in work.glob("export-*"):
|
||||
try:
|
||||
if time.time() - d.stat().st_mtime > older:
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def remove_command(path):
|
||||
"""Delete an export on the Frame once it's been copied (path as export returned it)."""
|
||||
if not EXPORT_PATH.fullmatch(path or ""):
|
||||
raise ValueError(f"unexpected export path {path!r}")
|
||||
return f"rm -rf \"$HOME\"/{shlex.quote(path.rsplit('/', 1)[0])}"
|
||||
|
||||
|
||||
# ---- the computer's side of Steam clips -------------------------------------------
|
||||
#
|
||||
# run_frame(args, timeout) runs this file on the Frame with `args` and returns its JSON;
|
||||
# run(command, timeout) and fetch(remote, local) as for Recorder.
|
||||
|
||||
def list_clips(run_frame, folder=None):
|
||||
"""Steam's recordings on the Frame, each marked saved if its .mp4 is already here."""
|
||||
folder = Path(folder) if folder else VIDEOS_DIR
|
||||
clips = run_frame(["list"], 60)["clips"]
|
||||
for c in clips:
|
||||
c["saved"] = (folder / export_name(c["id"])).exists()
|
||||
return {"clips": clips, "folder": str(folder)}
|
||||
|
||||
|
||||
def export_clip(clip_id, run_frame, run, fetch, folder=None):
|
||||
"""Stitch a Steam recording on the Frame and copy the .mp4 here. -> {"message", "file"}."""
|
||||
folder = Path(folder) if folder else VIDEOS_DIR
|
||||
name = export_name(clip_id) # checks the id before anything reaches the Frame
|
||||
made = run_frame(["export", clip_id], 1900)
|
||||
path = made.get("path")
|
||||
remove = remove_command(path) # refuses a path that isn't one of our exports
|
||||
try:
|
||||
_make_room(folder, int(made.get("size") or 0))
|
||||
incoming = Path(tempfile.mkdtemp(prefix=".incoming-", dir=folder))
|
||||
try:
|
||||
fetch(path, incoming / name)
|
||||
os.replace(incoming / name, folder / name)
|
||||
finally:
|
||||
shutil.rmtree(incoming, ignore_errors=True)
|
||||
finally:
|
||||
try:
|
||||
run(remove, 30)
|
||||
except Exception:
|
||||
pass # the next export sweeps it
|
||||
return {"message": f"Saved {name} to ~/Videos/SteamFrame", "file": str(folder / name)}
|
||||
|
||||
|
||||
# ---- on the Frame -----------------------------------------------------------------
|
||||
|
||||
def main(argv):
|
||||
userdata = Path.home() / STEAM_USERDATA
|
||||
try:
|
||||
if argv[:1] == ["list"]:
|
||||
result = {"clips": list_recordings(userdata)}
|
||||
elif len(argv) == 2 and argv[0] == "export":
|
||||
result = export(userdata, argv[1])
|
||||
else:
|
||||
result = {"error": "usage: frame_clips.py list | export ID"}
|
||||
except (ClipError, ValueError, OSError, subprocess.TimeoutExpired) as e:
|
||||
result = {"error": str(e)}
|
||||
print(json.dumps(result))
|
||||
return 1 if "error" in result else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,335 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Runs ON the Frame (piped over SSH, with frame_steam.py): what game is running,
|
||||
and force quit it.
|
||||
|
||||
Steam starts every game, non-Steam shortcut and devkit title under its own
|
||||
`reaper`, as `reaper SteamLaunch AppId=<id> -- <command>`, and the reaper stays
|
||||
the parent of the game's processes. That's how Steam starts games on Linux
|
||||
desktops and the Steam Deck; on the Frame it is **inferred, not yet seen**. So a
|
||||
running game is a reaper with an AppId, and the game is that reaper's process
|
||||
tree. Nothing is matched by name, so Steam, gamescope, SteamVR, sshd or the
|
||||
session can't be picked by mistake, and the names in PROTECTED are skipped
|
||||
even inside a game's tree.
|
||||
|
||||
Quitting asks Steam first (SteamClient.Apps.TerminateApp, what Steam's own Stop
|
||||
uses for Android apps, docs/vr-apks.md). If the game's processes are still
|
||||
there a few seconds later, they get SIGTERM, then SIGKILL.
|
||||
|
||||
Usage: python3 - list # {"running": [{appid, gameid, name, kind, ...}]}
|
||||
python3 - quit APPID # {"name", "method": "steam"|"term"|"kill"|"gone", "message"}
|
||||
Prints one JSON object. Errors are {"error": "..."} with exit status 1.
|
||||
"""
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
from frame_steam import Fail, Page
|
||||
|
||||
# The Frame is Linux; "/" also keeps the unit tests' paths the same on Windows.
|
||||
HOME = os.path.expanduser("~")
|
||||
STEAM = HOME + "/.local/share/Steam"
|
||||
DEVKIT = HOME + "/devkit-game"
|
||||
ANDROID = HOME + "/Applications/Android" # frame_android.APPS_DIR
|
||||
SIGTERM, SIGKILL = signal.SIGTERM, getattr(signal, "SIGKILL", 9) # Windows (unit tests) has no SIGKILL
|
||||
SHORTCUT_BIT = 0x80000000 # non-Steam shortcut ids have the top bit set
|
||||
APPID_ARG = re.compile(r"AppId=(\d{1,10})")
|
||||
# Never signalled, even when found under a game's reaper: Steam, the
|
||||
# compositors, SteamVR, the session, audio, sshd and init.
|
||||
PROTECTED = frozenset({
|
||||
"steam", "steamwebhelper", "gamescope", "gamescope-wl", "gamescopereaper", "gamescope-session",
|
||||
"sshd", "sshd-session", "ssh-agent", "systemd", "init", "dbus-daemon", "dbus-broker", "dbus-broker-lau",
|
||||
"pipewire", "pipewire-pulse", "wireplumber", "plasmashell", "kwin_wayland", "kwin_x11", "Xwayland",
|
||||
"sddm", "vrserver", "vrcompositor", "vrmonitor", "vrdashboard", "vrwebhelper", "vrstartup",
|
||||
})
|
||||
# Steam launches SteamVR under a reaper too, but on the Frame it's the headset's view,
|
||||
# not a game: it's never listed or quit (SteamVR and SteamVR Beta).
|
||||
NOT_GAMES = frozenset({250820, 1009850})
|
||||
STEAM_WAIT = 5 # seconds for Steam's own terminate to end the game
|
||||
TERM_WAIT = 3 # then SIGTERM, and this long before SIGKILL
|
||||
KILL_WAIT = 2
|
||||
|
||||
RUNNING_JS = """((ids) => {
|
||||
const store = globalThis.SteamUIStore;
|
||||
const running = Array.isArray(store?.RunningApps) ? store.RunningApps.map(a => a.appid) : null;
|
||||
const names = {};
|
||||
for (const id of new Set([...ids, ...(running || [])])) {
|
||||
const a = appStore.GetAppOverviewByAppID(id);
|
||||
if (a) names[id] = a.display_name;
|
||||
}
|
||||
return {running, names};
|
||||
})(%s)"""
|
||||
|
||||
|
||||
def read(path, mode="r"):
|
||||
try:
|
||||
with open(path, mode) as f:
|
||||
return f.read()
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def snapshot(proc="/proc"):
|
||||
"""pid -> {ppid, start, state, uid, comm, argv} for every process that can be read."""
|
||||
out = {}
|
||||
for d in os.listdir(proc):
|
||||
if not d.isdigit():
|
||||
continue
|
||||
stat = read(f"{proc}/{d}/stat")
|
||||
try:
|
||||
# comm is in parentheses and may hold spaces or ')': split at the last ')'.
|
||||
comm = stat[stat.index("(") + 1:stat.rindex(")")]
|
||||
fields = stat[stat.rindex(")") + 2:].split()
|
||||
uid = os.stat(f"{proc}/{d}").st_uid
|
||||
except (AttributeError, ValueError, OSError):
|
||||
continue
|
||||
argv = (read(f"{proc}/{d}/cmdline", "rb") or b"").split(b"\0")
|
||||
out[int(d)] = {"ppid": int(fields[1]), "state": fields[0], "start": int(fields[19]), "uid": uid,
|
||||
"comm": comm, "argv": [a.decode(errors="replace") for a in argv if a]}
|
||||
return out
|
||||
|
||||
|
||||
def launch_appid(argv):
|
||||
"""The AppId of `reaper SteamLaunch AppId=<id> -- ...`, or None for any other process."""
|
||||
if not argv or os.path.basename(argv[0]) != "reaper" or "SteamLaunch" not in argv:
|
||||
return None
|
||||
for arg in argv[1:]:
|
||||
if arg == "--":
|
||||
break
|
||||
m = APPID_ARG.fullmatch(arg)
|
||||
if m:
|
||||
return int(m.group(1))
|
||||
return None
|
||||
|
||||
|
||||
def reapers(procs, uid):
|
||||
"""appid -> [reaper pid], for this user's game launches."""
|
||||
out = {}
|
||||
for pid, p in procs.items():
|
||||
appid = launch_appid(p["argv"])
|
||||
if appid and appid not in NOT_GAMES and p["uid"] == uid and p["state"] != "Z":
|
||||
out.setdefault(appid, []).append(pid)
|
||||
return out
|
||||
|
||||
|
||||
def children(procs):
|
||||
kids = {}
|
||||
for pid, p in procs.items():
|
||||
kids.setdefault(p["ppid"], []).append(pid)
|
||||
return kids
|
||||
|
||||
|
||||
def protected(procs, me, uid):
|
||||
"""Pids never to signal: init, this helper and its parents (the SSH session),
|
||||
other users' processes and anything named in PROTECTED."""
|
||||
keep, pid = {0, 1}, me
|
||||
while pid > 1 and pid not in keep:
|
||||
keep.add(pid)
|
||||
pid = procs.get(pid, {}).get("ppid", 0)
|
||||
for pid, p in procs.items():
|
||||
argv0 = os.path.basename(p["argv"][0]) if p["argv"] else ""
|
||||
if p["uid"] != uid or p["comm"] in PROTECTED or argv0 in PROTECTED:
|
||||
keep.add(pid)
|
||||
return keep
|
||||
|
||||
|
||||
def tree(procs, roots, keep):
|
||||
"""The roots and their descendants, deepest first, leaving out kept processes
|
||||
and everything under them."""
|
||||
kids, out, level = children(procs), [], [r for r in roots if r not in keep]
|
||||
while level:
|
||||
out = level + out
|
||||
level = [c for pid in level for c in kids.get(pid, ()) if c not in keep and procs[c]["state"] != "Z"]
|
||||
return out
|
||||
|
||||
|
||||
def alive(procs, pid, start):
|
||||
p = procs.get(pid)
|
||||
return bool(p) and p["start"] == start and p["state"] != "Z"
|
||||
|
||||
|
||||
def escalate(appid, me=None, uid=None, scan=snapshot, kill=os.kill, sleep=time.sleep, clock=time.monotonic):
|
||||
"""SIGTERM the game's processes, then SIGKILL what's left. The reaper itself
|
||||
is only killed last, so its orphans can't escape to init before they're
|
||||
signalled. Returns "term", "kill" or "gone"; raises Fail if any survive."""
|
||||
me = os.getpid() if me is None else me
|
||||
uid = os.getuid() if uid is None else uid
|
||||
seen = {} # pid -> start time, so a reused pid is never signalled
|
||||
|
||||
def targets(include_roots):
|
||||
procs = scan()
|
||||
keep = protected(procs, me, uid)
|
||||
roots = reapers(procs, uid).get(appid, [])
|
||||
for pid in tree(procs, roots, keep):
|
||||
seen.setdefault(pid, procs[pid]["start"])
|
||||
return procs, [pid for pid, start in seen.items() if alive(procs, pid, start) and pid not in keep
|
||||
and (include_roots or pid not in roots)]
|
||||
|
||||
def wait(seconds, include_roots):
|
||||
end = clock() + seconds
|
||||
while True:
|
||||
procs, left = targets(include_roots)
|
||||
if not left or clock() >= end:
|
||||
return left
|
||||
sleep(0.2)
|
||||
|
||||
method = "gone"
|
||||
for sig, seconds, include_roots in ((SIGTERM, TERM_WAIT, False), (SIGKILL, KILL_WAIT, True)):
|
||||
_, left = targets(include_roots)
|
||||
if not left:
|
||||
# The reaper exits when its last child does; a lingering one is all that's left.
|
||||
_, left = targets(True)
|
||||
if not left:
|
||||
return method
|
||||
for pid in left:
|
||||
try:
|
||||
kill(pid, sig)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
except PermissionError:
|
||||
continue
|
||||
method = "term" if sig == SIGTERM else "kill"
|
||||
if not wait(seconds, True):
|
||||
return method
|
||||
raise Fail(f"{len(targets(True)[1])} of its processes are still running after SIGKILL")
|
||||
|
||||
|
||||
def gameid(appid):
|
||||
"""The game id Steam's Apps API takes: the appid, or (appid << 32) | 0x02000000
|
||||
for a non-Steam shortcut (docs/apks.md)."""
|
||||
return str((appid << 32) | 0x02000000 if appid >= SHORTCUT_BIT else appid)
|
||||
|
||||
|
||||
def android_apps():
|
||||
"""Shortcut or instance id -> Frame Control's Android app meta."""
|
||||
out = {}
|
||||
for path in glob.glob(os.path.join(ANDROID, "*/meta.json")):
|
||||
try:
|
||||
m = json.loads(read(path) or "null")
|
||||
except ValueError:
|
||||
continue
|
||||
if isinstance(m, dict) and m.get("package"):
|
||||
for key in ("shortcut", "instance"):
|
||||
if str(m.get(key) or "").isdigit():
|
||||
out[int(m[key])] = m
|
||||
return out
|
||||
|
||||
|
||||
def lepton_containers():
|
||||
try:
|
||||
r = subprocess.run(["podman", "ps", "--format", "{{.Names}}"], capture_output=True, text=True, timeout=10)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return set()
|
||||
return set(r.stdout.split())
|
||||
|
||||
|
||||
def manifest_name(appid):
|
||||
m = re.search(r'"name"\s+"([^"]*)"', read(os.path.join(STEAM, f"steamapps/appmanifest_{appid}.acf")) or "")
|
||||
return m.group(1) if m else None
|
||||
|
||||
|
||||
def devkit_title(procs, pids):
|
||||
"""A devkit title's id from its processes' arguments (~/devkit-game/<id>/...)."""
|
||||
prefix = DEVKIT + "/"
|
||||
for pid in pids:
|
||||
for arg in procs[pid]["argv"]:
|
||||
arg = arg.strip('"')
|
||||
if arg.startswith(prefix) and "/" in arg[len(prefix):]:
|
||||
return arg[len(prefix):].split("/", 1)[0]
|
||||
return None
|
||||
|
||||
|
||||
def steam_view(ids, page=None):
|
||||
"""Steam's own running list and app names, or (None, {}) without Steam."""
|
||||
try:
|
||||
r = (page or Page()).eval(RUNNING_JS % json.dumps(sorted(ids)))
|
||||
except (Fail, OSError):
|
||||
return None, {}
|
||||
return r.get("running"), {int(k): v for k, v in (r.get("names") or {}).items()}
|
||||
|
||||
|
||||
def running(procs=None, uid=None, steam=steam_view, android=android_apps, containers=lepton_containers):
|
||||
"""Every game running now: reapers on this Frame, Steam's running list, and
|
||||
Android apps whose Lepton container is up."""
|
||||
procs = snapshot() if procs is None else procs
|
||||
uid = os.getuid() if uid is None else uid
|
||||
found = reapers(procs, uid)
|
||||
apps = android()
|
||||
up = containers() if apps else set()
|
||||
for m in apps.values():
|
||||
if f"lepton-steamlaunch-{m.get('instance')}" in up and str(m.get("shortcut") or "").isdigit():
|
||||
found.setdefault(int(m["shortcut"]), [])
|
||||
listed, names = steam(set(found))
|
||||
for appid in listed or ():
|
||||
if int(appid) not in NOT_GAMES:
|
||||
found.setdefault(int(appid), [])
|
||||
out = []
|
||||
for appid, roots in sorted(found.items()):
|
||||
pids = tree(procs, roots, set())
|
||||
app = {"appid": appid, "gameid": gameid(appid), "processes": len(pids)}
|
||||
meta = apps.get(appid)
|
||||
title = devkit_title(procs, pids)
|
||||
if meta:
|
||||
app.update(kind="android", package=meta["package"], name=names.get(appid) or meta.get("label") or meta["package"])
|
||||
elif title:
|
||||
app.update(kind="devkit", title=title, name=names.get(appid) or title)
|
||||
elif appid >= SHORTCUT_BIT:
|
||||
app.update(kind="shortcut", name=names.get(appid) or f"Shortcut {appid}")
|
||||
else:
|
||||
app.update(kind="steam", name=names.get(appid) or manifest_name(appid) or f"App {appid}")
|
||||
out.append(app)
|
||||
return out
|
||||
|
||||
|
||||
def quit_game(appid, sleep=time.sleep, clock=time.monotonic):
|
||||
apps = {a["appid"]: a for a in running()}
|
||||
app = apps.get(appid)
|
||||
if not app:
|
||||
return {"name": None, "method": "gone", "message": "That game isn't running"}
|
||||
name = app["name"]
|
||||
try:
|
||||
page = Page()
|
||||
page.eval(f"SteamClient.Apps.TerminateApp({json.dumps(app['gameid'])}, false)")
|
||||
except (Fail, OSError):
|
||||
page = None # Steam isn't answering: the processes are all that's left to stop
|
||||
end = clock() + (STEAM_WAIT if page else 0)
|
||||
while True:
|
||||
procs = snapshot()
|
||||
left = reapers(procs, os.getuid()).get(appid) or (page and appid in (steam_view({appid}, page)[0] or ()))
|
||||
if not left:
|
||||
return {"name": name, "method": "steam" if page else "gone", "message": f"Quit {name}"}
|
||||
if clock() >= end:
|
||||
break
|
||||
sleep(0.5)
|
||||
if not reapers(procs, os.getuid()).get(appid):
|
||||
# Steam still lists it, but there's no process of it to stop.
|
||||
raise Fail(f"Steam didn't quit {name}, and none of its processes were found on the Frame")
|
||||
method = escalate(appid)
|
||||
return {"name": name, "method": method,
|
||||
"message": f"Force quit {name}" + (" (it had to be killed)" if method == "kill" else "")}
|
||||
|
||||
|
||||
def main():
|
||||
try:
|
||||
cmd = sys.argv[1] if len(sys.argv) > 1 else ""
|
||||
if cmd == "list":
|
||||
out = {"running": running()}
|
||||
elif cmd == "quit" and len(sys.argv) == 3 and sys.argv[2].isdigit() and len(sys.argv[2]) <= 10:
|
||||
out = quit_game(int(sys.argv[2]))
|
||||
else:
|
||||
raise Fail("usage: list | quit APPID")
|
||||
except (Fail, OSError) as e:
|
||||
print(json.dumps({"error": str(e)}))
|
||||
sys.exit(1)
|
||||
except Exception as e: # keep the one-JSON-object contract for the server
|
||||
print(json.dumps({"error": f"{type(e).__name__}: {e}"}))
|
||||
sys.exit(1)
|
||||
print(json.dumps(out))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+61
-120
@@ -1182,7 +1182,6 @@
|
||||
<span class="view-actions">
|
||||
<button class="action" id="shotBtn">Capture</button>
|
||||
<button id="liveBtn" title="Keep updating, as video">Live</button>
|
||||
<button id="recBtn" title="Record what the headset shows, with its sound, to ~/Videos/SteamFrame on this computer">Record</button>
|
||||
<button id="ctrlBtn" title="Control the Frame by tapping or clicking on the view (C)">Control</button>
|
||||
<button id="copyBtn" disabled title="Copy the image to the clipboard (or right-click it)">Copy</button>
|
||||
<button id="saveBtn" disabled>Save</button>
|
||||
@@ -1227,7 +1226,6 @@
|
||||
<button data-ctrl-key="28" title="Enter">Enter</button>
|
||||
</span>
|
||||
</div>
|
||||
<div class="hint" id="recStatus" role="status" hidden></div>
|
||||
<div class="hint" id="viewHint"></div>
|
||||
</section>
|
||||
|
||||
@@ -1249,20 +1247,17 @@
|
||||
<div class="shot-grid" id="shotGrid"><div class="sub">Loading…</div></div>
|
||||
<div class="hint">Screenshots you take in the headset with Steam's screenshot shortcut. New ones appear on their own. Click one to open it in the viewer, Copy puts it on the clipboard, and Save copies it to <code>~/Pictures/SteamFrame</code>. Right-click for more.</div>
|
||||
</section>
|
||||
<section id="clips">
|
||||
<div class="shelf-head"><h2>Steam clips</h2><span class="count" id="clipCount"></span><span class="spacer"></span>
|
||||
<button class="small" id="clipsRefresh">Refresh</button>
|
||||
<button class="small" id="videosFolder" title="Open the SteamFrame folder in your Videos">Show folder</button>
|
||||
</div>
|
||||
<div class="list" id="clipList"><div class="sub">Loading…</div></div>
|
||||
<div class="hint">Clips and background recordings from Steam's game recording in the headset. Export joins one into a single <code>.mp4</code> in <code>~/Videos/SteamFrame</code>, however long it is, without re-encoding it. Recordings you make with <b>Record</b> go there too.</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="page" data-page="games">
|
||||
<div class="workspace-heading"><div><span class="eyebrow">Play on your Frame</span><h1>Games</h1><p>Your Steam library and games you add yourself.</p></div><button class="action add-install" data-open-install>+ Add / Install</button></div>
|
||||
<div class="library-controls"><div class="scope-tabs" id="libraryScope" aria-label="Game library"><button data-scope="installed" aria-pressed="true">Installed</button><button data-scope="owned" aria-pressed="false">Owned</button><button data-scope="store" aria-pressed="false">Store</button></div>
|
||||
<div class="scope-tabs" id="librarySources" aria-label="Installed content source"><button data-library-source="all" aria-pressed="true">All</button><button data-library-source="steam" aria-pressed="false">Steam</button><button data-library-source="sideloaded" aria-pressed="false">Sideloaded</button></div></div>
|
||||
<section class="panel now-running" id="nowRunning" aria-labelledby="nowRunningTitle" hidden>
|
||||
<div class="shelf-head"><h2 id="nowRunningTitle">Running now</h2><span class="spacer"></span><button class="small" id="runningCheck">Check again</button></div>
|
||||
<div class="list" id="runningList"></div>
|
||||
<div class="hint">Force quit a game that has stopped responding. Steam is asked to quit it first; unsaved progress is lost.</div>
|
||||
</section>
|
||||
<div id="libraryOwned"></div><div id="steamDiscover" hidden></div>
|
||||
<section id="library">
|
||||
<div class="shelf-head"><h2>Steam games</h2><span class="count" id="gameCount"></span></div>
|
||||
@@ -2023,10 +2018,9 @@ function applyHostWording(h) {
|
||||
// The iPhone app: the server runs on the Frame, and saving goes to the phone's Photos.
|
||||
document.body.classList.toggle("mobile", !!h.mobile);
|
||||
$("shotsFolder").hidden = !!h.mobile;
|
||||
$("recBtn").hidden = $("clips").hidden = !!h.mobile; // recordings are saved to a computer
|
||||
$("quest").hidden = !!h.mobile;
|
||||
$("metaLib").hidden = !!h.mobile; // the Quest plugs into a computer; the phone app's server runs on the Frame
|
||||
if (!h.mobile) $("shotsFolder").textContent = $("videosFolder").textContent = h.fileManager === "your file manager" ? "Open folder" : `Show in ${h.fileManager}`;
|
||||
if (!h.mobile) $("shotsFolder").textContent = h.fileManager === "your file manager" ? "Open folder" : `Show in ${h.fileManager}`;
|
||||
$("shotsSaveNew").textContent = h.mobile ? `Save all to ${h.computer}` : `Save new to ${h.computer}`;
|
||||
$("clipMac").textContent = `Send ${h.computer} clipboard`;
|
||||
$('mobileConnection').hidden = !h.mobile;
|
||||
@@ -2139,7 +2133,7 @@ function setOnline(ok, why) {
|
||||
reloadAll();
|
||||
}
|
||||
}
|
||||
function reloadAll() { loadTitles(); loadOwned(); loadAndroid(); loadDisplays(); loadShots(); loadClips(); }
|
||||
function reloadAll() { loadTitles(); loadOwned(); loadAndroid(); loadDisplays(); loadShots(); }
|
||||
$("offRetry").onclick = () => refresh();
|
||||
if (window.frameApp && window.frameApp.setUpConnection) {
|
||||
$("offSetup").hidden = false;
|
||||
@@ -2426,6 +2420,7 @@ function render(s) {
|
||||
<div class="name">${esc(g.name)}</div>
|
||||
<div class="size">${gb(g.size)}</div>
|
||||
<button class="play small" data-launch="${g.appid}" data-name="${esc(g.name)}">▶ Play</button>
|
||||
<button class="small danger" data-force-quit-app="${g.appid}" data-name="${esc(g.name)}" title="Quit it if it has stopped responding">Force quit…</button>
|
||||
</div>
|
||||
</div>`).join("") : `<div class="sub">No games installed.</div>`;
|
||||
// Tall library art, falling back to the wide header, then to the name card.
|
||||
@@ -3218,7 +3213,7 @@ $("ctrlKeys").addEventListener("click", e => {
|
||||
});
|
||||
|
||||
// ---- controls ----
|
||||
$("refreshAll").onclick = () => { refresh(); loadTitles(); loadAndroid(); }; // titles too: the Frame may have been asleep at start
|
||||
$("refreshAll").onclick = () => { refresh(); loadTitles(); loadAndroid(); loadRunning().catch(() => {}); }; // titles too: the Frame may have been asleep at start
|
||||
document.addEventListener("keydown", e => {
|
||||
if (e.key === "r" && !e.metaKey && !e.ctrlKey && !/INPUT|TEXTAREA|SELECT/.test(document.activeElement.tagName)) $("refreshAll").onclick();
|
||||
});
|
||||
@@ -3226,6 +3221,7 @@ document.body.addEventListener("click", async (e) => {
|
||||
const b = e.target.closest("button");
|
||||
if (!b) return;
|
||||
if (b.dataset.launch) act(`Launch ${b.dataset.name}`, () => api("/api/launch", { appid: b.dataset.launch }), b);
|
||||
else if (b.dataset.forceQuitApp) forceQuitFrom(g => String(g.appid) === b.dataset.forceQuitApp, b.dataset.name, b);
|
||||
else if (b.dataset.uninstall) {
|
||||
if (confirm(`Remove ${b.dataset.name} from the Frame?`))
|
||||
act(`Remove ${b.dataset.name}`, () => api("/api/flatpak", { action: "uninstall", id: b.dataset.uninstall }), b).then(refresh);
|
||||
@@ -3794,6 +3790,7 @@ async function loadTitles() {
|
||||
<button class="play small" data-title="launch" data-id="${esc(t.id)}" title="Launch in the headset">Play</button>
|
||||
<details class="lib-more"><summary aria-label="More for ${esc(t.id)}">⋯</summary><div class="lib-menu">
|
||||
${t.art_missing ? `<button data-title="refresh-art" data-id="${esc(t.id)}">Add artwork<small>Its Steam library tile has none yet</small></button>` : ""}
|
||||
<button class="danger" data-title="force-quit" data-id="${esc(t.id)}">Force quit…<small>If it has stopped responding</small></button>
|
||||
<button class="danger" data-title="remove" data-id="${esc(t.id)}">Remove…<small>Deletes the game and its files</small></button>
|
||||
</div></details>
|
||||
</div>`).join("") : `<div class="sub">None yet.</div>`;
|
||||
@@ -3806,6 +3803,8 @@ $("titleList").onclick = async e => {
|
||||
if (!confirm(`Remove ${id} and its files from the Frame?`)) return;
|
||||
await act(`Remove ${id}`, () => api("/api/titles", { action: "remove", id }), b);
|
||||
loadTitles();
|
||||
} else if (b.dataset.title === "force-quit") {
|
||||
forceQuitFrom(g => g.kind === "devkit" && g.title === id, id, b);
|
||||
} else if (b.dataset.title === "refresh-art") {
|
||||
await runJob(`Add Steam artwork for ${id}`, "art-" + id, () => api("/api/titles", { action: "refresh-art", id }));
|
||||
loadTitles();
|
||||
@@ -3814,6 +3813,48 @@ $("titleList").onclick = async e => {
|
||||
loadTitles();
|
||||
$("titleAdd").onclick = () => $("fileInput").click();
|
||||
|
||||
// ---- what's running, and force quit (frame_running.py on the Frame) ----
|
||||
let runningGames = [], runningSeq = 0;
|
||||
async function loadRunning() {
|
||||
const seq = ++runningSeq;
|
||||
try {
|
||||
const list = (await api("/api/running")).running;
|
||||
if (seq === runningSeq) runningGames = list;
|
||||
} catch (e) {
|
||||
if (seq === runningSeq && !e.stale) runningGames = [];
|
||||
throw e;
|
||||
} finally { if (seq === runningSeq) renderRunning(); }
|
||||
return seq === runningSeq;
|
||||
}
|
||||
const RUNNING_KIND = { steam: "Steam game", devkit: "Sideloaded game", shortcut: "Non-Steam shortcut", android: "Android app" };
|
||||
function renderRunning() {
|
||||
$("nowRunning").hidden = !runningGames.length;
|
||||
$("runningList").innerHTML = runningGames.map(g => `
|
||||
<div class="item"><div class="grow"><div class="t">${esc(g.name)}</div><div class="s">${RUNNING_KIND[g.kind] || "Running"} · running on the Frame</div></div>
|
||||
<button class="small danger" data-force-quit="${esc(g.appid)}">Force quit…</button></div>`).join("");
|
||||
}
|
||||
async function forceQuit(appid, btn) {
|
||||
const g = runningGames.find(x => String(x.appid) === String(appid));
|
||||
if (!g) return;
|
||||
if (!confirm(`Force quit ${g.name}? Unsaved progress will be lost.`)) return;
|
||||
await act(`Force quit ${g.name}`, () => api("/api/running", { action: "quit", appid: String(g.appid) }), btn);
|
||||
loadRunning().catch(() => {});
|
||||
if (g.kind === "android") loadAndroid();
|
||||
}
|
||||
// From a game's own menu: check it's running first, so a stopped game says so.
|
||||
async function forceQuitFrom(match, name, btn) {
|
||||
if (btn) btn.disabled = true;
|
||||
try { if (!await loadRunning()) return; }
|
||||
catch (e) { if (!e.stale) toast(`Couldn't check what's running: ${e.message}`, true); return; }
|
||||
finally { if (btn) btn.disabled = false; }
|
||||
const g = runningGames.find(match);
|
||||
if (!g) { log(`${name} isn't running`); toast(`${name} isn't running`); return; }
|
||||
forceQuit(g.appid, btn);
|
||||
}
|
||||
$("runningList").onclick = e => { const b = e.target.closest("[data-force-quit]"); if (b) forceQuit(b.dataset.forceQuit, b); };
|
||||
$("runningCheck").onclick = () => loadRunning().then(() => { if (!runningGames.length) toast("Nothing is running on the Frame"); },
|
||||
e => { if (!e.stale) toast(`Couldn't check what's running: ${e.message}`, true); });
|
||||
|
||||
|
||||
// ---- Steam games: install owned games, find and buy on the store ----
|
||||
const FLABEL = { 3: "Frame Verified", 2: "Playable", 1: "Unsupported", 0: "Unknown" };
|
||||
@@ -5125,107 +5166,6 @@ $("shotsFolder").onclick = e => act($("shotsFolder").textContent, () => api("/ap
|
||||
// Watch for new shots: a cheap listing over the shared SSH connection while the
|
||||
// window is visible and the Frame is reachable, and again on coming back to it.
|
||||
setInterval(() => { if (!document.hidden && online) loadShots(true); }, SHOTS_POLL_MS);
|
||||
|
||||
// ---- Recording the headset view, and Steam's own clips (server.py, frame_clips.py) ----
|
||||
// A recording runs on the Frame until Stop; the server then copies the .mp4 here
|
||||
// and the page follows it by polling /api/record.
|
||||
const rec = { state: "idle", timer: null };
|
||||
const clock = t => `${Math.floor(t / 60)}:${String(Math.floor(t % 60)).padStart(2, "0")}`;
|
||||
function showRec(s) {
|
||||
const was = rec.state;
|
||||
rec.state = s.state;
|
||||
const busy = ["starting", "recording", "stopping", "saving"].includes(s.state);
|
||||
const b = $("recBtn");
|
||||
b.textContent = s.state === "recording" ? "Stop" : "Record";
|
||||
b.classList.toggle("on", s.state === "recording");
|
||||
b.disabled = busy && s.state !== "recording";
|
||||
const line = $("recStatus");
|
||||
line.textContent = s.state === "recording" ? `Recording ${clock(s.elapsed || 0)} (stops by itself at ${clock(s.limit)})` +
|
||||
(s.audio ? "" : ". No sound: the Frame's audio couldn't be read, so this is video only.")
|
||||
: s.state === "starting" ? "Starting the recording…"
|
||||
: s.state === "stopping" ? "Stopping the recording…"
|
||||
: s.state === "saving" ? `Copying the recording to this ${HOST.computer}…`
|
||||
: s.state === "saved" ? s.message
|
||||
: s.state === "failed" ? `Recording failed: ${s.error}` : "";
|
||||
line.hidden = !line.textContent;
|
||||
if (was !== s.state && was !== "idle" && s.state === "saved") { log(s.message, "ok"); toast(s.message); }
|
||||
if (was !== s.state && was !== "idle" && was !== "starting" && s.state === "failed") { log(line.textContent, "e"); toast(line.textContent, true); }
|
||||
clearTimeout(rec.timer);
|
||||
if (busy) rec.timer = setTimeout(pollRec, 1000);
|
||||
}
|
||||
async function pollRec() {
|
||||
if (HOST.mobile) return;
|
||||
clearTimeout(rec.timer);
|
||||
let s;
|
||||
try { s = await api("/api/record"); }
|
||||
catch { if (rec.state !== "idle") rec.timer = setTimeout(pollRec, 3000); return; }
|
||||
showRec(s);
|
||||
}
|
||||
$("recBtn").onclick = async e => {
|
||||
const start = rec.state !== "recording";
|
||||
const res = await act(start ? "Start recording" : "Stop recording",
|
||||
() => api("/api/record", { action: start ? "start" : "stop" }), e.currentTarget);
|
||||
if (res) showRec(res); else pollRec();
|
||||
};
|
||||
|
||||
const clipsState = { list: [], gen: 0, exporting: new Set() };
|
||||
async function loadClips() {
|
||||
if (HOST.mobile) return;
|
||||
const gen = clipsState.gen;
|
||||
$("clipsRefresh").disabled = true;
|
||||
let got;
|
||||
try { got = await api("/api/clips"); }
|
||||
catch (e) { if (gen === clipsState.gen) failed($("clipList"), e); return; }
|
||||
finally { $("clipsRefresh").disabled = false; }
|
||||
if (gen !== clipsState.gen) return;
|
||||
clipsState.list = got.clips;
|
||||
drawClips();
|
||||
}
|
||||
// Forget the clips of a headset we've switched away from.
|
||||
function resetClips() {
|
||||
clipsState.gen++; clipsState.list = [];
|
||||
$("clipCount").textContent = "";
|
||||
$("clipList").innerHTML = `<div class="sub">Loading…</div>`;
|
||||
}
|
||||
const megabytes = n => n >= 1e9 ? `${(n / 1e9).toFixed(1)} GB` : `${Math.max(1, Math.round(n / 1e6))} MB`;
|
||||
function drawClips() {
|
||||
const list = clipsState.list;
|
||||
$("clipCount").textContent = list.length ? `${list.length} on the Frame` : "";
|
||||
$("clipList").innerHTML = list.length ? list.map((c, i) => `<div class="item"><div class="grow">
|
||||
<div class="t">${esc(c.appid ? shotApp(c.appid) : "Steam recording")} · ${c.kind === "clip" ? "Clip" : "Background recording"}</div>
|
||||
<div class="s" title="${esc(new Date(c.time * 1000).toLocaleString())}">${esc([shotTime(c.time), c.duration ? clock(c.duration) : "",
|
||||
megabytes(c.size), c.gaps ? `${c.gaps} pieces missing` : ""].filter(Boolean).join(" · "))}</div></div>
|
||||
${c.saved ? `<span class="tag">On ${HOST.computer}</span>` : ""}
|
||||
<button class="small" data-clip-export="${i}"${clipsState.exporting.has(c.id) ? " disabled" : ""}>${c.saved ? "Export again" : "Export"}</button>
|
||||
</div>`).join("")
|
||||
: `<div class="sub">No Steam clips or background recordings on the Frame.</div>`;
|
||||
}
|
||||
async function exportClip(c, btn) {
|
||||
const label = `Export ${c.file}`;
|
||||
clipsState.exporting.add(c.id); btn.disabled = true;
|
||||
log(label + "…"); toast(label + "…");
|
||||
try {
|
||||
const { job } = await api("/api/clips/export", { id: c.id });
|
||||
for (let misses = 0; ;) {
|
||||
await new Promise(ok => setTimeout(ok, 1500));
|
||||
let j;
|
||||
try { j = await api(`/api/job?id=${encodeURIComponent(job)}`); misses = 0; }
|
||||
catch (e) { if (++misses >= 20 || /no such job/.test(e.message)) throw e; continue; }
|
||||
if (!j.done) continue;
|
||||
if (j.error) throw new Error(j.error);
|
||||
log(j.message, "ok"); toast(j.message);
|
||||
break;
|
||||
}
|
||||
} catch (e) {
|
||||
log(`${label} failed: ${e.message}`, "e"); toast(`${label} failed: ${e.message}`, true);
|
||||
} finally { clipsState.exporting.delete(c.id); loadClips(); }
|
||||
}
|
||||
$("clipList").onclick = e => {
|
||||
const b = e.target.closest("[data-clip-export]");
|
||||
if (b) exportClip(clipsState.list[+b.dataset.clipExport], b);
|
||||
};
|
||||
$("clipsRefresh").onclick = () => loadClips();
|
||||
$("videosFolder").onclick = e => act($("videosFolder").textContent, () => api("/api/open", { what: "videos" }), e.currentTarget);
|
||||
document.addEventListener("visibilitychange", () => { if (!document.hidden && online) loadShots(true); });
|
||||
|
||||
// ---- Panel switcher: our UI over SteamVR's panel API ----
|
||||
@@ -5451,7 +5391,7 @@ function showPage(e) {
|
||||
if (page === 'games') selectLibrary(workspace.source, workspace.scope, false);
|
||||
// Another computer may have added or removed a title: phones have no Refresh button. Only
|
||||
// on navigating here (e: the hashchange); at startup the first load is already on its way.
|
||||
if (e && page === 'games' && previousPage !== 'games') loadTitles();
|
||||
if (e && page === 'games' && previousPage !== 'games') { loadTitles(); loadRunning().catch(() => {}); }
|
||||
if (page === 'apps') {
|
||||
selectApps(workspace.apps, false);
|
||||
if ((previousPage !== 'apps' || id === 'androidLibrary') && workspace.apps === 'installed') loadAndroid();
|
||||
@@ -6151,7 +6091,7 @@ if (window.frameApp && window.frameApp.onInstallLink) {
|
||||
}
|
||||
|
||||
setView("headset");
|
||||
refresh().then(() => { loadShots(); loadClips(); pollRec(); pollComfort(); }); // after status, so app names resolve and comfort knows if the Frame answers
|
||||
refresh().then(() => { loadShots(); pollComfort(); }); // after status, so app names resolve and comfort knows if the Frame answers
|
||||
document.addEventListener("visibilitychange", () => { if (!document.hidden && online === false) refresh(); });
|
||||
</script>
|
||||
<script>
|
||||
@@ -6442,9 +6382,10 @@ function onConnection(s) {
|
||||
disp.list = []; disp.port = null;
|
||||
// The lists behind those panels too, so filters can't bring the old ones back.
|
||||
gm.storeDraft = ""; gm.owned = null; gm.byId = new Map(); gm.results = []; gm.store = []; gm.storeQ = null; gm.shown = 0; gm.shownBySource = {owned:0, store:0}; gm.seq++;
|
||||
androidApps = []; androidSeq++; androidPending.clear(); $('installedDetail').close(); resetShots(); resetClips();
|
||||
androidApps = []; androidSeq++; androidPending.clear(); $('installedDetail').close(); resetShots();
|
||||
renderHome();
|
||||
titlesSeq++; disp.seq++; // answers to loads already on their way are ignored
|
||||
titlesSeq++; disp.seq++; runningSeq++; // answers to loads already on their way are ignored
|
||||
runningGames = []; $("nowRunning").hidden = true; $("runningList").innerHTML = "";
|
||||
if (cat.apps) filterCatalog(); // "Installed" tags were the other headset's
|
||||
// Confirmations still open were checked against the other headset.
|
||||
["titleDlg", "apkAltDlg", "pwDlg", "repDlg"].forEach(id => { if ($(id) && $(id).open) $(id).close(); });
|
||||
@@ -6868,7 +6809,7 @@ api("/api/host").then(h => {
|
||||
<script>
|
||||
window.frameControlCenter = FrameControlCenter.mount({document, api, refresh, refreshAudio: refreshAfterAudio,
|
||||
getContext: () => ({sample: state, online, generation: devGen, device: window.connDevice}),
|
||||
openConnection: () => $("conn").click(), platform: window.frameApp?.platform || ""});
|
||||
openConnection: () => $("conn").click(), platform: window.frameApp?.platform || "", confirm: text => confirm(text)});
|
||||
window.frameControlCenter.host(HOST);
|
||||
if (state) window.frameControlCenter.status(state, stateReceivedAt, stateRead);
|
||||
else if (stateRead.error) window.frameControlCenter.unavailable(stateRead.error);
|
||||
|
||||
+42
-85
@@ -49,7 +49,6 @@ from apk_sources import search as apk_search, SourceError # noqa: E402
|
||||
from apk_sources import fdroid as apk_fdroid # noqa: E402
|
||||
import frame_apk_versions # noqa: E402
|
||||
import frame_catalog # noqa: E402
|
||||
import frame_clips # noqa: E402
|
||||
import frame_devices # noqa: E402
|
||||
import frame_steamgriddb
|
||||
import frame_comfort # noqa: E402
|
||||
@@ -747,77 +746,6 @@ def stream_command(query):
|
||||
f"exec >&-; cat >/dev/null; kill $p 2>/dev/null; wait $p")
|
||||
|
||||
|
||||
# Recordings of the headset view with its sound, and Steam's own clips, saved as .mp4
|
||||
# in ~/Videos/SteamFrame (frame_clips.py has the commands and the Frame-side half).
|
||||
|
||||
def fetch_file(remote, local):
|
||||
"""Copy one file from the Frame (a path relative to its home) to `local`."""
|
||||
ensure_master()
|
||||
try:
|
||||
# Modern scp uses SFTP, so the remote path isn't parsed by a shell. -p keeps its time.
|
||||
r = frame_host.run_ssh(["scp", "-p", *SSH[1:], f"{FRAME}:{remote}", str(local)], capture_output=True,
|
||||
stdin=subprocess.DEVNULL, text=True, errors="replace", timeout=3600)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise Failure(f"Copying {Path(remote).name} timed out")
|
||||
if r.returncode != 0:
|
||||
raise Failure(strip_ansi(r.stderr or r.stdout).strip() or f"scp exited {r.returncode}")
|
||||
|
||||
|
||||
def _record_channel(command, stderr):
|
||||
ensure_master()
|
||||
proc = subprocess.Popen([*SSH, FRAME, command], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=stderr)
|
||||
_live_tunnels.add(proc) # killed if the server stops: the Frame then finishes the file
|
||||
return proc
|
||||
|
||||
|
||||
recorder = frame_clips.Recorder(_record_channel, lambda cmd, timeout: ssh(cmd, timeout=timeout), fetch_file,
|
||||
lambda fn: busy_thread(fn).start(), release=lambda proc: _live_tunnels.discard(proc))
|
||||
|
||||
|
||||
def _clips_here():
|
||||
if LOCAL:
|
||||
raise Failure("Recordings are saved to a computer: use Frame Control on your computer", 400)
|
||||
|
||||
|
||||
def record(body):
|
||||
"""{"action": "start"|"stop"}: record what the headset shows, with its sound."""
|
||||
_clips_here()
|
||||
action = body.get("action")
|
||||
if action not in ("start", "stop"):
|
||||
raise Failure("action must be start or stop", 400)
|
||||
try:
|
||||
return recorder.start() if action == "start" else recorder.stop()
|
||||
except frame_clips.ClipError as e:
|
||||
raise Failure(str(e), e.status)
|
||||
|
||||
|
||||
def _clips_frame(args, timeout):
|
||||
return steam_frame(*args, timeout=timeout, script="frame_clips.py")
|
||||
|
||||
|
||||
def list_clips():
|
||||
_clips_here()
|
||||
try:
|
||||
return frame_clips.list_clips(_clips_frame)
|
||||
except frame_clips.ClipError as e:
|
||||
raise Failure(str(e), e.status)
|
||||
|
||||
|
||||
def export_clip(body):
|
||||
"""{"id"}: stitch one of Steam's recordings on the Frame and copy the .mp4 here (a job)."""
|
||||
_clips_here()
|
||||
clip_id = body.get("id")
|
||||
name = frame_clips.export_name(clip_id) # ValueError, so 400, for a bad id
|
||||
|
||||
def work():
|
||||
try:
|
||||
return frame_clips.export_clip(clip_id, _clips_frame, lambda cmd, timeout: ssh(cmd, timeout=timeout),
|
||||
fetch_file)
|
||||
except frame_clips.ClipError as e:
|
||||
raise Failure(str(e), e.status)
|
||||
return start_job(f"Export {name}", work)
|
||||
|
||||
|
||||
def launch(body):
|
||||
appid = str(body.get("appid", ""))
|
||||
if not APPID.match(appid):
|
||||
@@ -826,12 +754,12 @@ def launch(body):
|
||||
return {"message": f"Launching {appid}"}
|
||||
|
||||
|
||||
def steam_frame(*args, timeout=40, script="frame_steam.py"):
|
||||
def steam_frame(*args, timeout=40, script="frame_steam.py", source=None):
|
||||
"""Run frame_steam.py (it drives the Steam client), or another on-Frame
|
||||
helper with the same JSON contract, on the Frame and return its JSON."""
|
||||
try:
|
||||
out = ssh("python3 - " + " ".join(map(shlex.quote, args)),
|
||||
stdin=(HERE / script).read_text(), timeout=timeout)
|
||||
stdin=source or (HERE / script).read_text(), timeout=timeout)
|
||||
except Failure as e:
|
||||
# The helper prints {"error": ...} on stdout when it fails, but ssh()
|
||||
# reports stderr instead if there was any, so look in both.
|
||||
@@ -844,6 +772,43 @@ def steam_frame(*args, timeout=40, script="frame_steam.py"):
|
||||
return json.loads(out)
|
||||
|
||||
|
||||
def running_frame(*args, timeout=40):
|
||||
"""frame_running.py on the Frame, with frame_steam.py (its DevTools client) as a module."""
|
||||
source = ("import sys, types\nm = types.ModuleType('frame_steam'); sys.modules['frame_steam'] = m\n"
|
||||
f"exec({(HERE / 'frame_steam.py').read_text()!r}, m.__dict__)\n" + (HERE / "frame_running.py").read_text())
|
||||
return steam_frame(*args, timeout=timeout, source=source)
|
||||
|
||||
|
||||
def running_games():
|
||||
games = running_frame("list")["running"]
|
||||
return {"running": games, "message": None if games else "Nothing is running on the Frame"}
|
||||
|
||||
|
||||
def force_quit(body):
|
||||
"""Quit a running game: Steam's own terminate, then its processes (frame_running.py).
|
||||
An Android app's Lepton container is stopped the way the Apps tab's Stop does."""
|
||||
appid = str(body.get("appid", ""))
|
||||
if body.get("action") != "quit":
|
||||
raise Failure("action must be quit", 400)
|
||||
if not APPID.match(appid):
|
||||
raise Failure("bad appid", 400)
|
||||
app = next((a for a in running_frame("list")["running"] if str(a.get("appid")) == appid), None)
|
||||
if not app:
|
||||
raise Failure("That game isn't running any more", 409)
|
||||
stopped = False
|
||||
if app.get("kind") == "android" and app.get("package"):
|
||||
ensure_master()
|
||||
try:
|
||||
frame_android.stop(app["package"])
|
||||
stopped = True
|
||||
except frame_android.FrameError:
|
||||
pass # the process fallback below still runs
|
||||
res = running_frame("quit", appid, timeout=60)
|
||||
if res.get("method") == "gone":
|
||||
res["message"] = f"{'Stopped' if stopped else 'Quit'} {app['name']}"
|
||||
return dict(res, appid=int(appid), name=app["name"])
|
||||
|
||||
|
||||
def steam(body):
|
||||
"""Steam games: install an owned game, or open its store page in the headset."""
|
||||
appid, action = str(body.get("appid", "")), body.get("action")
|
||||
@@ -1540,10 +1505,6 @@ def open_thing(body):
|
||||
SHOTS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
frame_host.open_path(SHOTS_DIR)
|
||||
return {"message": f"Opened {SHOTS_DIR} in {frame_host.FILE_MANAGER}"}
|
||||
if what == "videos":
|
||||
frame_clips.VIDEOS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
frame_host.open_path(frame_clips.VIDEOS_DIR)
|
||||
return {"message": f"Opened {frame_clips.VIDEOS_DIR} in {frame_host.FILE_MANAGER}"}
|
||||
if what == "shot":
|
||||
saved = SHOTS_DIR / shot_path(body.get("id")).rsplit("/", 1)[-1]
|
||||
if not saved.exists():
|
||||
@@ -2783,9 +2744,8 @@ POST = {
|
||||
"/api/agent/approval": agent_approval, "/api/assistant/chat": assistant_chat,
|
||||
"/api/input": remote_input, "/api/touch": remote_touch,
|
||||
"/api/settings/artwork": frame_steamgriddb.save_settings,
|
||||
"/api/sources": source_manage, "/api/sources/install": source_install, "/api/android/display": android_display, "/api/android": android, "/api/quest": quest, "/api/meta": meta, "/api/queue": queue_action, "/api/titles": titles, "/api/launch": launch, "/api/steam": steam, "/api/mods": mods, "/api/volume": set_volume, "/api/clipboard": clipboard,
|
||||
"/api/sources": source_manage, "/api/sources/install": source_install, "/api/android/display": android_display, "/api/android": android, "/api/quest": quest, "/api/meta": meta, "/api/queue": queue_action, "/api/titles": titles, "/api/launch": launch, "/api/running": force_quit, "/api/steam": steam, "/api/mods": mods, "/api/volume": set_volume, "/api/clipboard": clipboard,
|
||||
"/api/flatpak": flatpak, "/api/open": open_thing, "/api/shots/save": save_shots,
|
||||
"/api/record": record, "/api/clips/export": export_clip,
|
||||
"/api/webinstall/check": webinstall_check, "/api/webinstall/start": webinstall_start,
|
||||
"/api/webinstall/cancel": webinstall_cancel,
|
||||
"/api/telemetry": frame_telemetry.update_settings, "/api/telemetry/event": frame_telemetry.page_event,
|
||||
@@ -3068,6 +3028,8 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.send_json(json.loads(ssh("python3 -", stdin=(HERE / "frame_computer.py").read_text(), timeout=20)))
|
||||
elif path == "/api/status":
|
||||
self.send_json(status({}))
|
||||
elif path == "/api/running":
|
||||
self.send_json(running_games())
|
||||
elif path == "/api/steam/owned":
|
||||
self.send_json(steam_frame("owned"))
|
||||
elif path == "/api/steam/search":
|
||||
@@ -3078,11 +3040,6 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.send_json(list_shots())
|
||||
elif path == "/api/shots/image":
|
||||
self.send_bytes(*shot_image(url.query))
|
||||
elif path == "/api/record":
|
||||
_clips_here()
|
||||
self.send_json(recorder.status())
|
||||
elif path == "/api/clips":
|
||||
self.send_json(list_clips())
|
||||
elif path == "/api/stream":
|
||||
self.stream_video(url.query)
|
||||
elif path == "/api/screenshot" and parse_qs(url.query).get("view") == ["panel"]:
|
||||
|
||||
Reference in new issue
Block a user