Compare commits

...
Author SHA1 Message Date
poli0981 0378b7dfa2 Merge main (#466 squashed) into feat/input-reader: the trees are the same below this branch's own commits 2026-11-14 23:04:44 +07:00
poli0981andClaude Fable 5.2 5d6434c360 feat(input): a session can store what it was played with - schema 0024, the .partial file's chunk 11, both tiers (D160) (#466)
* feat(input): the arithmetic of controller statistics - classes, batteries, makers, one pad seen twice (D155-D163)

Nothing reads a device yet. Domain.Input says whether an XInput state or a DualSense report is a pad in use and what
its battery is, adds a battery's readings up, counts switches and decides when two entries are one pad;
Application.Input holds one session's slices and turns them into a reading a second; InputSessionBuilder turns a
session's readings into its totals, its controllers as JSON and its timeline. TelemetrySample can carry a reading.

Every byte and reading under test was written by hand: no report from a real controller has passed through this code.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* feat(input): a session can store what it was played with - schema 0024, the .partial file's chunk 11, both tiers (D160)

Nine columns on sessions (the time in front and its four classes, the switches of method, the sources that answered,
the controllers as JSON) and three on games (what a store lists of controller support), ADD COLUMN only. The .partial
file gains chunk 11, so a session recovered after the Agent died keeps its readings. SessionFinalizer.Build stores
them before the tier branch: hooked, unhooked and recovered sessions alike. The input series are sensor_blobs rows
named input.*, which the sensors' read now leaves out and FindInputSensorsAsync returns.

Nothing produces a reading yet. A ledger this build has opened cannot be opened by 0.1.0-beta.49 or earlier.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* fix(input): an arm of XInputPad.Battery's switch said what the default says (Qodana, on #464 after it merged)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* test(input): no using that makes the file's own qualified names redundant (InspectCode)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 16:02:29 +00:00
poli0981 102dcdd3f1 Merge feat/input-storage (main at 1d1d4ff) into feat/input-reader 2026-11-14 22:52:58 +07:00
poli0981 43e0c2b347 Merge branch 'main' into feat/input-storage 2026-11-14 22:48:46 +07:00
poli0981andClaude Fable 5.2 1d1d4ff855 docs(roadmap): the owner's order of work after the controller train (#465)
* docs(roadmap): the owner's order of work after the controller train - time played, more from stored data, shader-compilation stutter, the in-game overlay, winget and the Microsoft Store

The owner was shown six directions on 2026-11-14 and chose four, and added distribution; the
Store upload and its listing are the owner's by hand. What must be verified before anything is
promised of the two channels is listed as leads, not findings. Documents only.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* docs(roadmap): FrameLedger has no product in Partner Center yet - the one there is another program of the owner's

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 15:31:51 +00:00
poli0981andClaude Fable 5.2 f7129807e6 test(input): what InspectCode reported in the reader's tests - redundant casts, a hub disposed twice, a suppression not needed
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 22:20:52 +07:00
poli0981 be96564a8f Merge feat/input-storage (the inspection fix) into feat/input-reader 2026-11-14 22:19:55 +07:00
poli0981andClaude Fable 5.2 e24f09ae8a test(input): no using that makes the file's own qualified names redundant (InspectCode)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 22:19:52 +07:00
poli0981 80155d7638 Merge feat/input-storage (main at 8f24854, the Qodana fix) into feat/input-reader 2026-11-14 22:14:22 +07:00
poli0981andClaude Fable 5.2 8b4cccbb25 fix(input): an arm of XInputPad.Battery's switch said what the default says (Qodana, on #464 after it merged)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 22:14:11 +07:00
poli0981 2dd0e4f271 Merge main (8f24854, #464 squashed) into feat/input-storage: the trees are the same below this branch's own commit 2026-11-14 22:13:56 +07:00
poli0981andClaude Fable 5.2 e2675cd91c feat(input): the input reader, which the Agent does not start yet - raw input for controllers, XInput, the time of the last input (D155, D158, D159)
Application.Input.InputReader takes a slice about ten times a second from Infrastructure.Input.Win32InputBackend, on
the thread of InputDeviceHub, which exists only while a session has a view of it. It opens no device, sends nothing
to one and registers for no keyboard or mouse. tools/input-readonly-check.ps1 holds its Windows calls to a list.

With no controller at hand, what the reader does with one connected is not established.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 22:12:33 +07:00
poli0981andClaude Fable 5.2 8f24854aa5 feat(input): the arithmetic of controller statistics - classes, batteries, makers, one pad seen twice (D155-D163) (#464)
Nothing reads a device yet. Domain.Input says whether an XInput state or a DualSense report is a pad in use and what
its battery is, adds a battery's readings up, counts switches and decides when two entries are one pad;
Application.Input holds one session's slices and turns them into a reading a second; InputSessionBuilder turns a
session's readings into its totals, its controllers as JSON and its timeline. TelemetrySample can carry a reading.

Every byte and reading under test was written by hand: no report from a real controller has passed through this code.

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 15:02:57 +00:00
poli0981andClaude Fable 5.2 dca740e94b feat(input): a session can store what it was played with - schema 0024, the .partial file's chunk 11, both tiers (D160)
Nine columns on sessions (the time in front and its four classes, the switches of method, the sources that answered,
the controllers as JSON) and three on games (what a store lists of controller support), ADD COLUMN only. The .partial
file gains chunk 11, so a session recovered after the Agent died keeps its readings. SessionFinalizer.Build stores
them before the tier branch: hooked, unhooked and recovered sessions alike. The input series are sensor_blobs rows
named input.*, which the sensors' read now leaves out and FindInputSensorsAsync returns.

Nothing produces a reading yet. A ledger this build has opened cannot be opened by 0.1.0-beta.49 or earlier.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-14 21:54:13 +07:00
47 changed files with 4207 additions and 23 deletions

No files matched your search

+17
View File
@@ -44,6 +44,23 @@ numeric core and does not move; the heading is the full version — corrected 20
slices and turns them into a reading a second; `InputSessionBuilder` turns a session's readings into its totals, its
controllers as JSON and its timeline. A telemetry sample can carry a reading; none does. **Every byte and reading
under test was written by hand — no report from a real controller has passed through this code.**
- **For developers: a session can store what it was played with — schema 0024** (D160; `docs/06_DATA_MODEL.md`). Nine
columns on `sessions` (the time in front and its four classes, the switches of method, the sources that answered,
the controllers as JSON) and three on `games` (what a store lists of controller support), ADD COLUMN only; the
`.partial` file gains chunk 11, so a session recovered after the Agent died keeps its readings; the finalizer
stores them for hooked and unhooked sessions alike; the input series are `sensor_blobs` rows named `input.*`, which
the sensors' read leaves out. Nothing produces a reading yet. **A ledger this build has opened cannot be opened by
0.1.0-beta.49 or earlier.**
- **For developers: the input reader, which the Agent does not start yet** (D155, D158, D159; `docs/21_INPUT_DEVICES.md`
§The reader). `Application.Input.InputReader` takes a slice about ten times a second from
`Infrastructure.Input.Win32InputBackend` — raw input for joysticks and gamepads delivered to a window that is never
shown, three of XInput's getters, the time of the last keyboard or mouse input, the window in front — on the thread
of `InputDeviceHub`, which exists only while a session has a view of it. It opens no device, sends nothing to one,
and registers for no keyboard or mouse. A new gate, `tools/input-readonly-check.ps1`, holds the reader's Windows
calls to a committed list and refuses, on the list or off it, a call that sends to a device, injects input or reads
a key; no other managed source and no native source may name an input function. **With no controller at hand, what
the reader does with one connected is not established**: its tests use a Windows whose answers they write, and one
suite runs it on the real Windows of the machine and asserts only that it opens, answers and closes.
### Changed
+5 -1
View File
@@ -208,7 +208,11 @@ tools/ # accuracy-check, changelog-check, chokepoint-che
# the two on overlay-nvapi-allowed.txt),
# overlay-fields-check (D116, 2026-11-12: every member of a vendor's struct the
# Overlay reads for Advanced metrics is in fl_adv_fields.h and on
# overlay-allowed-fields.txt; a camera's position, axes and matrices nowhere)
# overlay-allowed-fields.txt; a camera's position, axes and matrices nowhere),
# input-readonly-check (D155-D163, 2026-11-14: every Windows function the input reader
# calls is declared in Infrastructure/Input/Win32Input.cs and on input-allowed-calls.txt;
# none sends to a device, injects input or reads a key; raw input is registered for
# joysticks and gamepads only; no native source names an input function)
# (six names added 2026-10-04)
# (PowerShell). This line used to name three, one of which
# — resx-audit — ~~does not exist~~ exists since 2026-09-13 with
+9
View File
@@ -499,6 +499,15 @@ function Invoke-ProjectGates {
Invoke-Checked 'overlay-fields-check (self-test)' { & $fieldsTool -SelfTest }
Invoke-Checked 'overlay-fields-check' { & $fieldsTool -RepoRoot $repo }
# 2026-11-14 (D155-D163): what is asked of Windows about controllers, the keyboard and the mouse. The reader's
# calls are declared in one file and held to tools/input-allowed-calls.txt in both directions; a call that sends to
# a device, injects input or reads a key is red even when the list names it; no managed source outside the reader
# and no native source names an input function; raw input is registered for joysticks and gamepads only. Text only.
Write-Step 'input-readonly-check'
$inputTool = Join-Path $repo 'tools/input-readonly-check.ps1'
Invoke-Checked 'input-readonly-check (self-test)' { & $inputTool -SelfTest }
Invoke-Checked 'input-readonly-check' { & $inputTool -RepoRoot $repo }
Write-Step 'docs-split-check'
$splitTool = Join-Path $repo 'tools/docs-split-check.ps1'
Invoke-Checked 'docs-split-check (self-test)' { & $splitTool -SelfTest }
+57 -1
View File
@@ -342,7 +342,25 @@ CREATE TABLE sessions (
display_source TEXT, -- swapchain | opengl | window: the strongest witness any sample had
display_window_w INTEGER, display_window_h INTEGER, -- client area, in the mode that lasted longest (the last seen, beta.27)
display_buffer_w INTEGER, display_buffer_h INTEGER, -- the swap chain's back buffer, same mode
display_monitor_w INTEGER, display_monitor_h INTEGER, display_monitor_hz INTEGER
display_monitor_w INTEGER, display_monitor_h INTEGER, display_monitor_hz INTEGER,
-- schema 0024 (2026-11-14, beta.50, D155-D163): what the session was played with, both tiers (03_METRICS §Input) -
-- read by the Agent from outside the game. Milliseconds. NULL before, with the option off, and before the terms
-- that describe the reading were accepted - N/A, never 0. From the samples, so a recovered session has them.
input_observed_ms INTEGER, -- the reader ran and the session was not paused
input_foreground_ms INTEGER, -- of it, a window of the game was in front: the four below add up to this
input_controller_ms INTEGER, -- a controller in use, the keyboard and mouse not
input_km_ms INTEGER, -- the keyboard or mouse in use (one class - only a time is read), no controller
input_both_ms INTEGER,
input_idle_ms INTEGER, -- no input at all
input_method_switches INTEGER, -- changes between a controller and the keyboard and mouse
input_source TEXT, -- the sources that answered: rawinput, xinput, lastinput, joined by +
input_devices TEXT -- InputDevicesRecord's JSON: {"V":1,"Devices":[{"Index","Family","VendorId",
-- "ProductId","Model","Connection","XInputSlot","Virtual","Remapped",
-- "ConnectedMs","ActiveMs","Connects","Disconnects","Battery":{"Scale",
-- "States":[{"State","Level","Ms"}],"First","Last","DrainPercentPerHour"}}],
-- "Families":[{"Family","ActiveMs","Share"}],"FamilySwitches","VirtualPad",
-- "Health":{...counts...}} - no serial number, no address, no path
);
CREATE INDEX ix_sessions_game_started ON sessions(game_id, started_at DESC);
@@ -402,6 +420,12 @@ CREATE TABLE sensor_blobs (
-- since schema 0023 (2026-11-11, D102) also the ADVANCED series, every one under a name
-- that starts with `adv.` (Application.Advanced.AdvancedMetricCatalog): NaN, not -1,
-- for a tick with no reading, and read by FindAdvancedSensorsAsync only
-- since schema 0024 (2026-11-14, D155-D163) also the INPUT series, every one under a
-- name that starts with `input.`: input.class (what the tick was mostly played with:
-- 0 no input, 1 controller, 2 keyboard and mouse, 3 both), input.dev.N.active (the
-- part of the tick's time in front controller N was in use, 0-1) and
-- input.dev.N.battery (its level, in its own scale) - NaN for a tick with nothing to
-- say, and read by FindInputSensorsAsync only
-- cpu_load / ram_mb / cpu_temp and sessions.avg_cpu_load, avg_cpu_temp, max_cpu_temp,
-- avg_ram_mb were in schema 0001 with NO producer until 2026-09-21 (Telemetry.SystemTelemetrySource
-- on the poller's tick). Rows before that date hold NULL, which is what they measured; no migration.
@@ -528,6 +552,15 @@ Because Tier-1 and Tier-2 sessions carry different fields, every query that comp
> (`AdvancedSessionBuilder.MaxSeries`); what is beyond is counted in its directory, not stored.
> **Size, measured 2026-11-11** on values shaped like the dev box's reader (17 series with a reading every tick, 41
> with one every fifth): one hour is 816 KiB raw and **189 KiB stored** — well inside NFR-5's 3 MB an hour.
>
> **The input series follow the same rule under their own name (schema 0024, owner decisions D155–D163).** A series
> whose name starts with `input.` stores NaN for a tick with nothing to say — the game was not in front, the
> controller was not connected, the tick carried no reading — through the same sparse encoder. `FindSensorsAsync`
> leaves them out as well (`series NOT LIKE 'input.%'`): a class's number is not a sensor's value, and the sensors'
> statistics and chart would take it for one. `FindInputSensorsAsync` returns them with `t_ms` first. A session
> stores `input.class` and, for each of its first eight controllers (`InputSessionBuilder.MaxDevices`),
> `input.dev.N.active` and — where the battery has a level — `input.dev.N.battery`: at most seventeen, a few KiB an
> hour stored.
## The `.partial` file
@@ -552,6 +585,7 @@ Because Tier-1 and Tier-2 sessions carry different fields, every query that comp
> | 8 `SensorsWide` | the same samples under a 32-bit presence mask that carries the game process's memory (D43) | each flush, since beta.12 *(row added 2026-10-04)* |
> | 9 `SensorsAdvanced` | the advanced readings of the samples of the type-8 chunk before it (D101): `u16` names, then per name `u16` bytes and UTF-8; `u32` samples, then per sample `i64` QPC, `u16` readings and per reading `u16` name, `f64` value. Each chunk carries its own names, so it reads without any earlier chunk | each flush **in which a sample carries any** — with Advanced metrics off, never; the file is then byte for byte what it was (2026-11-11) |
> | 10 `AdvancedContext` | UTF-8 JSON (`AdvancedJson.OfContext`): the PC's facts, the session's, its series' directory, each source's state; the last one wins | the first flush after the recorder set it, and again only when it changed (2026-11-11) |
> | 11 `SensorsInput` | the input readings of the samples of the type-8 chunk before it (D155–D163, `InputSampleCodec`): `u32` samples, then per sample `i64` QPC, seven `i32` (span, observed, in front, controller, keyboard and mouse, both, no input), `u8` flags, the reader's health (`u8` answers, six `i64` counts, `i32` faults), `u8` controllers and 23 bytes a controller — what it is (maker, the two USB ids, connection, XInput pad) and its part of the tick (connected, time in use, battery, connections, drops). Each sample describes every controller it counts, so a chunk reads without any earlier one | each flush **in which a sample carries one** — with the option off, never; the file is then byte for byte what it was (2026-11-14) |
>
> **A chunk of a type the reader does not know is skipped, not the end of the file (owner decision D106,
> 2026-11-11).** Its length and checksum have been verified by then, so it is a whole chunk a newer build wrote.
@@ -802,6 +836,28 @@ Sequential embedded SQL (`Migrations/0001_init.sql`, `0002_*.sql`, …), applied
> **Nothing produces a row yet**: the option that switches the reader on is the next pull request's.
> **A beta.38 cannot open a ledger a later build migrated.**
> **`0024_input_devices.sql` (0.1.0-beta.50, 2026-11-14, owner decisions D155–D163) — what a session was played
> with, and what a store lists.** ADD COLUMN only, twelve columns. **Nine on `sessions`**: `input_observed_ms`,
> `input_foreground_ms` and the four classes that add up to it (`input_controller_ms`, `input_km_ms`,
> `input_both_ms`, `input_idle_ms`), `input_method_switches`, `input_source`, and `input_devices` — the session's
> controllers as `Application.Recording.InputDevicesRecord`'s JSON (`03_METRICS` §Input). **On `sessions` and not in
> a table of their own, on purpose** (D160) — the opposite of 0023's choice, for the opposite reason: the trend and
> the comparison read a session's row, and these numbers are meant to be in the JSON export and the bug bundle,
> which carry the whole row; the Privacy Policy's §3A says so. What may never be a column or a key of that JSON: a
> controller's serial number, its Bluetooth address, its device path
> (`LedgerDatabaseTests.ScriptTwentyFourOnlyAddsColumnsAndNamesNoIdentifier`,
> `InputSessionBuilderTests.TheStoredJsonHasNoKeyThatCouldCarryASerialNumberAnAddressOrAPath`). **Three on
> `games`**: `controller_support` (`full`, `partial`, or `none` for a game the store knows and lists no support
> for), `controller_support_source` (`steam-appinfo`) and `controller_support_at` — the store's own word, from its
> file on the disk, never a verdict of FrameLedger's (D163). Written by `SessionFinalizer.Build` from the session's
> samples, before the tier branch — both tiers, and a session recovered from its crash file, which carries the
> readings in chunk 11. NULL before; with the option off; before the terms that describe the reading were accepted
> (D156); on a game no store file describes. The series are `sensor_blobs` rows named `input.*` (§Blob encoding).
> `LatestVersion` is 24; `LedgerDatabaseTests.ScriptTwentyFourAddsTheInputColumnsAndAnEarlierSessionAndGameHaveNone`,
> the repository round trip. **Nothing produces a reading yet, and nothing writes the three `games` columns yet**:
> the reader, the switch and the store file are the pull requests after this one.
> **A beta.49 cannot open a ledger a later build migrated.**
> **`0022_dlss_nr.sql` (beta.34, 2026-11-06, owner decision D84) — DLSS 5's neural rendering, measured.** One REAL column,
> ADD COLUMN only: `dlss_nr_pct`, the share (0–100) of the presents that drained a Streamline evaluation on which the game
> evaluated `kFeatureDLSS_NR` (`Domain.Metrics.NeuralRendering`). Written by the recorder's aggregation
+1
View File
@@ -411,6 +411,7 @@ Seven self-test cases, both directions; `./tools/notice-check.ps1 -Fix` writes a
14. `tools/changelog-check.ps1 -SelfTest` — nine cases, five expected RED. The live half needs a pull request's changed-file list and is supplied by `ci.yml`
14b. `tools/release-notes.ps1 -SelfTest` — five cases over a fixture changelog (a dated and an undated section, a missing one, a prefix that must not match, an empty one), and since beta.24 three over a temporary tree: a version with its own `docs/changelog/<version>.md` is read from it, one without from `CHANGELOG.md`, a prefix of a file name is not that file. The live half needs a tag's version and runs in `release.yml`, where a missing or empty section is a red release (P4 PR-5)
14e. **`tools/nvapi-readonly-check.ps1 -SelfTest`, then live** (owner decision D108, 2026-11-11) — every `NvAPI_*` call in `src/native/FrameLedger.NvapiBridge/src/fl_nvapi_bridge.cpp`, the one translation unit that links `nvapi64.lib` into a shipped binary, is on `tools/nvapi-allowed-calls.txt` and every name there is called; a name that sets, saves, restores, deletes, registers, resets, enables, disables or controls something is red **even when the list names it**, and so is one that returns an identifier (D104) — three reads the verb rule would refuse are exempt by name, each with its reason. Comments and string literals are taken out first, so a setter named in the comment that says it is never called is not a call. Seventeen self-test cases, both directions. Text only: it runs with or without the native build. `18_GPU_VENDOR_APIS` §Runtime policy's "never call a setter", which was a sentence until the bridge went from fourteen calls to forty-four
14g. **`tools/input-readonly-check.ps1 -SelfTest`, then live** (owner decisions D155–D163, 2026-11-14) — what FrameLedger asks Windows about controllers, the keyboard and the mouse. Every Windows function the input reader calls is declared in ONE file, `src/FrameLedger.Infrastructure/Input/Win32Input.cs`, and is on `tools/input-allowed-calls.txt`; every name there is declared; a name that sends to a controller (`XInputSetState`, any `HidD_*`), injects input (`SendInput`), reads a key (`GetAsyncKeyState`, `GetKeyState`, `GetKeyboardState`, `XInputGetKeystroke`) or installs a hook is red **even when the list names it**; no managed source outside `src/FrameLedger.Infrastructure/Input/` names an input function at all, and `NativeMethods.txt` asks CsWin32 for none; raw input is registered for joysticks and gamepads only — `InputReader.RegisteredUsages` is exactly usage page 1, usages 4 and 5, and the backend builds its registration from it and writes no usage as a number; and **no native source names an input function** — nothing loaded into a game reads input. Comments and string literals are taken out first. Seventeen self-test cases, both directions. Text only; it does not look at the tests, which may drive a real keyboard for the App's own shortcuts. `21_INPUT_DEVICES` §What is never read, which the Privacy Policy repeats to the user
14f. **`tools/overlay-fields-check.ps1 -SelfTest`, then live** (owner decision D116, 2026-11-12) — the same for the code loaded into a game: every member of a vendor's struct the Overlay reads for Advanced metrics is read in ONE header, `src/native/FrameLedger.Overlay/include/fl_adv_fields.h`, through parameters with fixed names, and is on `tools/overlay-allowed-fields.txt`; every name there is read; the parameters are not aliased and `->` reaches nothing but `desc` and the Overlay's own `region`; no other Overlay or Vulkan-layer source reads a listed member; **a camera's position, axes and matrices** (`cameraPos`, `cameraUp`, `cameraRight`, `cameraFwd`, the five matrices, `cameraPinholeOffset`, `cameraPosition`, `cameraForward`) **are named nowhere in those sources and not on the list, whatever the list says**; and neither `sl::Constants` nor `ffxDispatchDescFrameGenerationPrepareV2` is copied by value or measured with `sizeof`. Comments and string literals are taken out first. Nineteen self-test cases, both directions. Text only. It reads names, not types — which struct version carries a member is `17_HOOK_ENGINE` §Which struct version carries which field and ctest `fl_adv_fields`
14d. **`tools/docs-split-check.ps1 -SelfTest`, then live** (beta.24, owner decision D66) — `CHANGELOG.md` holds no released section beside `[Unreleased]`; each `docs/changelog/<version>.md` holds one `## ` heading, its own `## [<version>] - date`, and no relative link (the App renders release notes as `CHANGELOG.md`); `CHANGELOG.md` and the files under `docs/changelog/`, and `docs/HANDOFF.md` and the files under `docs/handoff/` — and since PR-5 `docs/20_OPEN_QUESTIONS.md` and `docs/open-questions/`, `docs/spike-notes.md` and `docs/spike-notes/` — name each other in both directions. Eleven self-test cases, both directions
14c. **`tools/buildid-check.ps1 -SelfTest`** (beta.18) — eight cases, both directions: a binary built from a dirty tree (`-dirty`, or the short form's `+`), one with no id, a missing one, and an expected id that is dirty or not an id are red. The live half needs the release's clean-checkout id and runs in `release.yml` over the published tree (§Release-time token substitution)
+44
View File
@@ -332,6 +332,50 @@ CI/CD with the native build (`release.yml` exists since P4 PR-5, 2026-09-14 —
**Total ≈ 5.5–6.5 weeks full-time** — roughly 1.5–2 weeks more than the ETW design, which is the honest price of the accuracy.
## After the controller train — the owner's order (2026-11-14)
Advanced metrics is closed (D154) and the controller feature is being built as 0.1.0-beta.50's train. Asked what
comes after, the owner was shown six directions and chose four of them, and added distribution. **This is the
order of work after the controller train; each begins with a plan of its own and the owner's approval.** Nothing
here is designed yet, and what is marked *to verify* is a lead, not a finding.
1. **Time actually played (AFK segmentation).** The v2 backlog's "AFK segmentation via `GetLastInputInfo`", moved
up: the controller train already stores when the keyboard, the mouse or a controller was in use, so the time
nobody was at the game can be told apart and left out of a session's averages. Timestamps of activity only —
never a key, as that train's Privacy text says.
2. **More from what is already stored — interface only, no hook.** The comparison of two stretches of one
session ("before and after I changed DLSS Quality to Balanced", v1.1 below), and a timeline for a game that
marks where the driver, the game's build or the settings changed, so a drop in frame rate has a date. *To
verify*: which of those changes the ledger already records for every session.
3. **Stutter from shader compilation (PSO).** `03_METRICS` defines *PSO stutter %* and `05_DETECTION` says no
writer exists. New hooks at pipeline creation: staged like Advanced metrics' train B — small releases, the
overhead measured, the owner's real games between them, never first on a game inside the user-mode
exception's trial (D38).
4. **The in-game overlay (FR-15).** v1.1's first line below: live frame rate, frame time, upscaler and
ray-tracing state drawn in the game, per game, off by default. The largest and the riskiest of the four — it
draws in the game's process — so it comes last, with a risk review of its own (rule 5, and what an
anti-cheat makes of a drawing module).
5. **Distribution: winget and the Microsoft Store.** The owner uploads to the Store and fills in its listing by
hand. FrameLedger has no product in Partner Center yet — the one there today is another program of the
owner's — so which type it is submitted as (*EXE or MSI app*, or *MSIX or PWA app*) is part of what the plan
settles. The repository's part is what the two channels need from a release. *To verify, before anything is promised*:
- whether the Store accepts an **unsigned** installer for an *EXE or MSI app* — the installer is unsigned
today (`CLAUDE.md`, Packaging), and if the Store wants a certificate that is a cost and a decision of the
owner's; whether an MSIX package is a real alternative for a program that loads a library into games and
registers a Vulkan layer;
- the installer's silent switch and a versioned, permanent download address for each release, which both
channels ask for; whether either takes a pre-release version;
- who updates an installation that came from winget or the Store — the App's own updater (Velopack) or the
channel — and that the two cannot fight;
- a winget manifest per release (address, SHA-256, switches) and whether `release.yml` writes it or the owner
submits it;
- rule 8 is untouched: a channel that delivers the installer is not a network call of the App's.
**Not chosen, and not refused**: a stabilising pass with a cross-check against another tool (the limits page
still says no reading has been checked against one), and export for CapFrameX and for video overlays. Two things
only the owner can settle stay open beside them: what leaving beta takes, and code signing — which direction 5
may force.
## v1.1 — earned features (only after the data path is stable)
- **In-game overlay** (FR-15): we are already in the process; draw live FPS/frametime/upscaler/RT state. Opt-in per game, off by default. Borderless and fullscreen-flip both handled since we own the swapchain.
+54 -6
View File
@@ -4,10 +4,12 @@ What FrameLedger reads about game controllers and about the keyboard and mouse,
The numbers a session makes of it are in [`03_METRICS.md`](03_METRICS.md) §Input; the columns are in
[`06_DATA_MODEL.md`](06_DATA_MODEL.md).
> **Status, 2026-11-14 — nothing reads a device yet.** The model and the arithmetic exist (`FrameLedger.Domain.Input`,
> `FrameLedger.Application.Input`, `Application.Recording.InputSessionBuilder`), under tests whose every byte and
> reading was written by hand. The reader, the storage, the switch and the screens come in the pull requests after
> it, and this note is rewritten by each. **No report from a real controller has passed through any of this code**
> **Status, 2026-11-14 — the reader exists and the Agent does not start it yet.** The model and the arithmetic
> (`FrameLedger.Domain.Input`, `FrameLedger.Application.Input`, `Application.Recording.InputSessionBuilder`), the
> storage (schema 0024, the `.partial` file's chunk 11, the finalizer for both tiers — `06_DATA_MODEL`) and the reader
> itself (`Application.Input.InputReader`, `Infrastructure.Input`) are written and under test. Nothing composes the
> reader into the Agent: the switch, the terms and the screens come in the pull requests after this one, and this
> note is rewritten by each. **No report from a real controller has passed through any of this code**
> (owner decision D157): the developer has no controller, and what happens on a real one is owner-only item 48.
## The owner's request and decisions (2026-11-14)
@@ -35,8 +37,7 @@ Everything is a Windows API in a library Windows ships. **No third-party library
| Source | What it gives | Why this one |
|---|---|---|
| Raw Input (`RegisterRawInputDevices`, usage page 1, usages 4 and 5, `RIDEV_INPUTSINK \| RIDEV_DEVNOTIFY`) | the reports game controllers send, while the Agent is in the background; a controller arriving and leaving; its vendor and product ids | the documented way to receive a HID controller's reports without being in front, and it opens no handle to the device |
| `hid.dll`'s parser (`HidP_GetCaps`, `HidP_GetUsages`, `HidP_GetUsageValue`) | which usages of a report are set | a parser, not I/O: it reads the bytes Raw Input handed over |
| Raw Input (`RegisterRawInputDevices`, usage page 1, usages 4 and 5, `RIDEV_INPUTSINK \| RIDEV_DEVNOTIFY`; `GetRawInputBuffer`, `GetRawInputData`, `GetRawInputDeviceInfo`, `GetRawInputDeviceList`) | the reports game controllers send, while the Agent is in the background; a controller arriving and leaving; its vendor and product ids | the documented way to receive a HID controller's reports without being in front, and it opens no handle to the device |
| XInput 1.4 (`XInputGetState`, `XInputGetCapabilities`, `XInputGetBatteryInformation`) | each of its four pads: its state, wired or wireless, a battery in four levels | what an Xbox pad's battery is reported through |
| `GetLastInputInfo` | the time of the last keyboard or mouse input in the user's session | a time and nothing else (D158) |
| `GetForegroundWindow`, `GetWindowThreadProcessId` | whose window is in front | already used for the focus sample (`04_CAPTURE`) |
@@ -50,6 +51,10 @@ Everything is a Windows API in a library Windows ships. **No third-party library
remapper's, exclusive open of it fail. Raw Input needs none.
- **A sixth native library** — parsing bytes a device controls in C++, inside an Agent that may run as administrator.
The reader is C#, and what parses a report is `FrameLedger.Domain.Input`, with no pointer in it.
- **Windows' own HID parser** (`hid.dll`'s `HidP_*`), to read *any* controller generically. It would have let a
controller of a maker this build does not know count as *in use* — and nothing here could be tried on one. A
controller whose layout this build does not know is listed, with its connections and drops, and is never *in
use*: a guess would be a made-up number (§The reader).
## What is never read
@@ -99,6 +104,49 @@ arrives padded to 78 bytes with the id the USB report has: the connection, not t
The layout was written from the open descriptions of the protocol. No code was taken from the Linux kernel's driver,
which is under a licence this project cannot take code from.
## The reader
`Application.Input.InputReader` over `Infrastructure.Input.Win32InputBackend`, on the thread of
`Infrastructure.Input.InputDeviceHub` — named `fl-input`, and **there only while a session has a view of the hub**:
with no session there is no thread, no window and no registration.
**A slice, about ten times a second.** The reader takes what Windows has: the controllers that came and went, the
reports that arrived (in bulk — `GetRawInputBuffer` — not one message at a time: a DualSense sends some hundreds a
second, and the Agent's whole budget is 2.5 % of one core, NFR-2), the state of XInput's connected pads, the time of
the last keyboard or mouse input, and the process whose window is in front. From that it makes one `InputSlice`,
the same for every session that is running; each session's view counts it when a window of *its* game was in front
(`Application.Input.InputTickAccumulator`), and the telemetry poller takes the sum once a second.
**The window.** Raw input is delivered to a window. The reader's is a child of `HWND_MESSAGE`: never shown, in no
task bar, receiving no broadcast, answered by Windows' default procedure. It is registered for HID usage page 1,
usages 4 (joystick) and 5 (gamepad) — `InputReader.RegisteredUsages` — and for nothing else.
**What a controller is.** Each of XInput's pads that is connected is one; each controller Windows does *not* present
through XInput is one. A device Windows presents through XInput is also seen by raw input and is **not** a second
controller: it gives the pads their name where that cannot be mistaken — every XInput-class device a player could
hold has the same two ids — and is otherwise only the witness of the next paragraph. An empty XInput slot is asked
about once in twenty slices (XInput looks for a device each time) and at once when a controller arrives or leaves;
a connected pad's battery once in fifty.
**Where XInput says nothing.** If XInput returns a pad at rest for ever because the Agent's window is never in front
(§XInput), the device's own reports are the evidence: a slice in which an XInput-class device's reports *changed*
while no pad's packet number moved — in that slice or the one before — is counted (`XInputSilent`). After ten of
them, **and only if XInput has never once been seen to move**, such a slice counts the lowest connected pad as in
use. That is coarser than XInput's dead zones — a stick that drifts counts — and is used only where the better
source is silent; a session's stored counts say which it was.
**Which controllers are read for use.** XInput's pads, and a DualSense by its own reports. Any other controller —
a DualShock 4, a Switch Pro controller — is listed with its connections and drops and is never *in use*.
**Faults.** A slice that throws is counted and skipped; twenty in a row end the run with one line in the Agent's
log, and the sessions go on without readings. When a run ends, one line says what it did: slices, whether Windows
accepted the registration, reports received and not read, XInput's reads and silent slices, whether the time of the
last input could be read, the thread's processor time, faults. Nothing in it names a device.
**Held by a gate.** `tools/input-readonly-check.ps1` (`12_BUILD` step 14g): the reader's calls are a committed list,
none of which sends to a device, injects input or reads a key; no other managed source and no native source names
an input function.
## What the reader says about itself
`Application.Input.InputHealth`, carried by every reading and stored with the session: whether Windows accepted the
@@ -0,0 +1,38 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
namespace FrameLedger.Application.Input;
/// <summary>
/// The Windows calls the input reader makes, behind one interface (<c>21_INPUT_DEVICES</c> §What is read): raw input
/// for game controllers, XInput, the time of the last keyboard or mouse input, the window in front. Everything here
/// reads; nothing writes to a device, and nothing asks about a keyboard or a mouse beyond that one time
/// (<c>tools/input-readonly-check.ps1</c> holds the calls behind it to a list).
/// </summary>
/// <remarks>Every member is called on the reader's own thread, the one that called <see cref="Open"/>.</remarks>
public interface IInputBackend : IDisposable
{
/// <summary>Makes what the reader needs on the calling thread; returns whether Windows accepted the registration for game controllers' reports.</summary>
bool Open();
/// <summary>Hands over what arrived since the last call: the controllers that came and went, then their reports.</summary>
void Drain(IInputBackendSink sink);
/// <summary>Whether XInput's library is there to ask.</summary>
bool XInputAvailable { get; }
/// <summary>The state of one of XInput's four pads; false when it is not connected.</summary>
bool TryReadPad(int slot, out XInputReading pad);
/// <summary>Whether the pad is wireless, and its battery; false when XInput did not answer.</summary>
bool TryReadPadDetails(int slot, out XInputDetails details);
/// <summary>The time of the last keyboard or mouse input in the user's session, as Windows' tick count; false when Windows did not give it.</summary>
bool TryReadLastInputTick(out uint tick);
/// <summary>The process whose window is in front; 0 when there is none.</summary>
uint ForegroundProcessId();
/// <summary>The processor time the calling thread has used, in milliseconds.</summary>
long ThreadCpuMs();
}
@@ -0,0 +1,17 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
namespace FrameLedger.Application.Input;
/// <summary>What <see cref="IInputBackend.Drain"/> hands over. A device is named by the handle Windows gave it for as long as it is connected: a key, never stored.</summary>
public interface IInputBackendSink
{
/// <summary>A game controller is there: at the start, or newly connected.</summary>
void Arrived(nint device, RawController controller);
/// <summary>It left.</summary>
void Removed(nint device);
/// <summary>One input report of a controller, its report id first, at the length Windows hands the device's reports over.</summary>
void Report(nint device, ReadOnlySpan<byte> report);
}
@@ -0,0 +1,373 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using FrameLedger.Domain.Input;
namespace FrameLedger.Application.Input;
/// <summary>
/// The input reader itself (<c>21_INPUT_DEVICES</c> §The reader): about ten times a second it takes what Windows has
/// to say - the controllers' reports that arrived, XInput's four pads, the time of the last keyboard or mouse input,
/// the window in front - and makes one <see cref="InputSlice"/> of it. It is the same for every session running; whose
/// game a slice counts for is <see cref="InputTickAccumulator"/>'s to decide.
/// </summary>
/// <remarks>
/// <para>
/// <b>What a controller is here.</b> Each of XInput's pads that is connected is one; each controller Windows does not
/// present through XInput is one. A device Windows presents through XInput is ALSO seen by raw input, and is not a
/// second controller: it gives the pads their name, when that cannot be mistaken, and is the witness of the next
/// paragraph.
/// </para>
/// <para>
/// <b>XInput in the background is not documented</b>: Microsoft's page for <c>XInputEnable</c> says that since
/// Windows 10 the system switches a program's controller input by its window's focus, and the Agent has no window in
/// front, ever. So the reader watches for it. A slice in which an XInput-class device's own reports changed while no
/// pad's packet number moved - not in this slice nor the one before - is counted
/// (<see cref="InputHealth.XInputSilent"/>). Once there are <see cref="SilentBeforeFallback"/> of them and XInput has
/// never once been seen to move, XInput is taken to be answering nothing here, and from then on such a slice counts
/// the lowest connected pad as in use: its reports changed, which a pad at rest does not do. That is coarser than
/// XInput's own dead zones - a drifting stick counts - and it is used only where the better source is silent.
/// </para>
/// <para>
/// <b>Which controllers are read for use.</b> XInput's pads, and a DualSense by its own reports
/// (<see cref="DualSenseReport"/>). Any other controller is listed, with its connections and drops, and is never "in
/// use": its report layout is not known to this build, and a guess would be a made-up number.
/// </para>
/// </remarks>
public sealed class InputReader : IInputBackendSink
{
/// <summary>XInput's four pads.</summary>
public const int Slots = 4;
/// <summary>A pad that is not connected is asked about once in this many slices - XInput looks for a device each time it is asked about an empty one - and at once when a controller arrives or leaves.</summary>
public const int ProbeEverySlices = 20;
/// <summary>A connected pad's battery is asked for once in this many slices.</summary>
public const int DetailsEverySlices = 50;
/// <summary>How many silent slices, with XInput never seen to move, before a device's own reports stand in for it.</summary>
public const int SilentBeforeFallback = 10;
/// <summary>The number the first controller that is not one of XInput's gets; the pads are 1 to 4.</summary>
private const int _firstRawId = 16;
private readonly IInputBackend _backend;
private readonly Dictionary<nint, Raw> _raw = [];
private readonly Dictionary<(RawController Controller, int Instance), int> _rawIds = [];
private readonly Pad[] _pads = [new(0), new(1), new(2), new(3)];
private bool _registered;
private bool _lastInputAvailable;
private uint? _lastInputTick;
private bool _probeNow = true;
private bool _renamePads = true;
private bool _movedLastSlice;
private bool _xinputEverMoved;
private long _slices;
private long _rawReports;
private long _rawReportsUnread;
private long _xinputReads;
private long _xinputSilent;
private int _faults;
public InputReader(IInputBackend backend) => _backend = backend ?? throw new ArgumentNullException(nameof(backend));
/// <summary>
/// The only device classes the reader registers raw input for: HID usage page 1 (generic desktop), usages 4
/// (joystick) and 5 (gamepad). Never 2 (mouse) or 6 (keyboard): what is known of those is one time, from
/// <see cref="IInputBackend.TryReadLastInputTick"/> (owner decision D158).
/// </summary>
public static IReadOnlyList<(ushort UsagePage, ushort Usage)> RegisteredUsages { get; } = [(1, 4), (1, 5)];
/// <summary>Opens the backend on the calling thread, which is the one every <see cref="Slice"/> must then be called on.</summary>
public void Open() => _registered = _backend.Open();
/// <summary>A slice that threw is counted and skipped.</summary>
public void Fault() => _faults++;
/// <summary>What Windows has to say since the slice before, <paramref name="elapsedMs"/> ago.</summary>
public InputSlice Slice(int elapsedMs)
{
_slices++;
foreach (Raw raw in _raw.Values)
{
raw.Active = false;
raw.Changed = false;
}
_backend.Drain(this);
bool moved = ReadPads();
WatchForSilence(moved);
if (_renamePads)
{
NamePads();
}
bool keyboardMouse = false;
if (_backend.TryReadLastInputTick(out uint tick))
{
_lastInputAvailable = true;
keyboardMouse = _lastInputTick is { } before && tick != before;
_lastInputTick = tick;
}
var devices = new List<InputSliceDevice>(Slots + _raw.Count);
foreach (Pad pad in _pads)
{
if (pad.Connected)
{
devices.Add(new InputSliceDevice(pad.Device, pad.Active, pad.Details is { } d ? XInputPad.Battery(d.BatteryType, d.BatteryLevel) : null));
}
}
foreach (Raw raw in _raw.Values.Where(static r => !r.Controller.XInputClass).OrderBy(static r => r.Device.Id))
{
devices.Add(new InputSliceDevice(raw.Device, raw.Active, raw.Battery));
}
return new InputSlice
{
ElapsedMs = Math.Max(0, elapsedMs),
ForegroundProcessId = _backend.ForegroundProcessId(),
KeyboardMouseActive = keyboardMouse,
VirtualPad = _raw.Values.Any(static r => r.Controller is { XInputClass: true, IsVirtual: true }),
Devices = devices,
Health = new InputHealth
{
RawInputRegistered = _registered,
RawReports = _rawReports,
RawReportsUnread = _rawReportsUnread,
XInputAvailable = _backend.XInputAvailable,
XInputReads = _xinputReads,
XInputSilent = _xinputSilent,
LastInputAvailable = _lastInputAvailable,
Slices = _slices,
ThreadCpuMs = _backend.ThreadCpuMs(),
Faults = _faults,
},
};
}
void IInputBackendSink.Arrived(nint device, RawController controller)
{
if (_raw.TryGetValue(device, out Raw? known) && known.Controller == controller)
{
// Windows names the controllers that are already there when the registration is made, and the reader has
// asked for the list as well: the same device twice is one device.
return;
}
int id = 0;
if (!controller.XInputClass)
{
int instance = _raw.Values.Count(r => r.Controller == controller);
if (!_rawIds.TryGetValue((controller, instance), out id))
{
id = _firstRawId + _rawIds.Count;
_rawIds[(controller, instance)] = id;
}
}
_raw[device] = new Raw(controller, new InputDevice
{
Id = id,
Family = ControllerCatalog.FamilyOf(controller.VendorId, xinput: false),
VendorId = controller.VendorId,
ProductId = controller.ProductId,
Connection = controller.Connection,
});
DevicesChanged(controller);
}
void IInputBackendSink.Removed(nint device)
{
if (_raw.Remove(device, out Raw? gone))
{
DevicesChanged(gone.Controller);
}
}
void IInputBackendSink.Report(nint device, ReadOnlySpan<byte> report)
{
_rawReports++;
if (!_raw.TryGetValue(device, out Raw? raw))
{
_rawReportsUnread++;
return;
}
if (raw.Controller.XInputClass)
{
// The witness only: did the device say something new. What it said is XInput's to tell.
raw.Changed |= raw.Last is not null && !report.SequenceEqual(raw.Last);
if (raw.Last is null || raw.Last.Length != report.Length)
{
raw.Last = report.ToArray();
}
else
{
report.CopyTo(raw.Last);
}
}
else if (raw.Controller.IsDualSense)
{
if (DualSenseReport.TryRead(report, raw.Controller.Connection == ControllerConnection.Bluetooth, out bool active, out BatteryReading? battery))
{
raw.Active |= active;
raw.Battery = battery ?? raw.Battery;
}
else
{
_rawReportsUnread++;
}
}
}
private void DevicesChanged(RawController controller)
{
if (controller.XInputClass)
{
_probeNow = true;
_renamePads = true;
}
}
/// <summary>Asks XInput about its pads; returns whether any connected pad's packet number moved since the slice before.</summary>
private bool ReadPads()
{
bool moved = false;
bool probe = _probeNow || _slices % ProbeEverySlices == 1;
_probeNow = false;
foreach (Pad pad in _pads)
{
pad.Active = false;
if (!_backend.XInputAvailable || (!pad.Connected && !probe))
{
continue;
}
if (!_backend.TryReadPad(pad.Slot, out XInputReading state))
{
if (pad.Connected)
{
pad.Connected = false;
pad.Details = null;
_renamePads = true;
}
continue;
}
_xinputReads++;
if (!pad.Connected)
{
pad.Connected = true;
pad.Details = null;
_renamePads = true;
}
else if (state.Packet != pad.Packet)
{
moved = true;
}
pad.Packet = state.Packet;
pad.Active = XInputPad.IsActive(state.Buttons, state.LeftTrigger, state.RightTrigger, state.ThumbLx, state.ThumbLy, state.ThumbRx, state.ThumbRy);
if (pad.Details is null || _slices - pad.DetailsAt >= DetailsEverySlices)
{
pad.DetailsAt = _slices;
if (_backend.TryReadPadDetails(pad.Slot, out XInputDetails details))
{
_renamePads |= pad.Details?.Wireless != details.Wireless;
pad.Details = details;
}
}
}
return moved;
}
private void WatchForSilence(bool moved)
{
_xinputEverMoved |= moved;
bool deviceSpoke = _raw.Values.Any(static r => r.Controller.XInputClass && r.Changed);
if (deviceSpoke && !moved && !_movedLastSlice && !_pads.Any(static p => p is { Connected: true, Active: true }))
{
_xinputSilent++;
if (!_xinputEverMoved && _xinputSilent >= SilentBeforeFallback && _pads.FirstOrDefault(static p => p.Connected) is { } lowest)
{
lowest.Active = true;
}
}
_movedLastSlice = moved;
}
/// <summary>
/// What each connected pad is. XInput does not say which device a pad is, so a pad is named only when it cannot be
/// another: every XInput-class device a player could hold has the same two ids, or the only ones there are
/// Steam's. Otherwise it is "one of XInput's pads" - the Xbox family, no ids, no model.
/// </summary>
private void NamePads()
{
_renamePads = false;
RawController[] presented = [.. _raw.Values.Where(static r => r.Controller.XInputClass).Select(static r => r.Controller)];
RawController[] held = [.. presented.Where(static c => !c.IsVirtual)];
RawController? name = held.Length > 0
? held.All(c => c.VendorId == held[0].VendorId && c.ProductId == held[0].ProductId) ? held[0] : null
: presented.Length > 0 ? presented[0] : null;
bool bluetooth = name is not null && held.Length > 0 && held.All(static c => c.Connection == ControllerConnection.Bluetooth);
foreach (Pad pad in _pads)
{
pad.Device = new InputDevice
{
Id = pad.Slot + 1,
XInputSlot = pad.Slot,
Family = ControllerCatalog.FamilyOf(name?.VendorId ?? 0, xinput: true),
VendorId = name?.VendorId ?? 0,
ProductId = name?.ProductId ?? 0,
IsVirtual = name?.IsVirtual ?? false,
Connection = bluetooth
? ControllerConnection.Bluetooth
: pad.Details switch
{
{ Wireless: true } => ControllerConnection.Wireless,
{ } => ControllerConnection.Usb,
_ => ControllerConnection.Unknown,
},
};
}
}
/// <summary>One of XInput's pads.</summary>
private sealed class Pad(int slot)
{
public int Slot { get; } = slot;
public bool Connected { get; set; }
public uint Packet { get; set; }
public bool Active { get; set; }
public XInputDetails? Details { get; set; }
public long DetailsAt { get; set; }
public InputDevice Device { get; set; } = new() { Id = slot + 1, XInputSlot = slot, Family = ControllerFamily.Xbox };
}
/// <summary>A controller raw input named.</summary>
private sealed class Raw(RawController controller, InputDevice device)
{
public RawController Controller { get; } = controller;
public InputDevice Device { get; } = device;
public bool Active { get; set; }
public bool Changed { get; set; }
public BatteryReading? Battery { get; set; }
public byte[]? Last { get; set; }
}
}
@@ -0,0 +1,24 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Runtime.InteropServices;
using FrameLedger.Domain.Input;
namespace FrameLedger.Application.Input;
/// <summary>
/// A game controller as Windows' raw input describes it, reduced to what the reader keeps: its two USB ids, whether
/// Windows presents it through XInput, and how it is connected. The name these were read from is not here - it can
/// carry an address - and nothing else of the device is asked for.
/// </summary>
/// <param name="VendorId">The USB vendor id.</param>
/// <param name="ProductId">The USB product id.</param>
/// <param name="XInputClass">Whether Windows presents the device through XInput (<see cref="RawDeviceName.IsXInputClass"/>).</param>
/// <param name="Connection">How it is connected (<see cref="RawDeviceName.ConnectionOf"/>).</param>
[StructLayout(LayoutKind.Auto)]
public readonly record struct RawController(int VendorId, int ProductId, bool XInputClass, ControllerConnection Connection)
{
public bool IsVirtual => ControllerCatalog.IsVirtual(VendorId, ProductId);
public bool IsDualSense => !XInputClass && ControllerCatalog.IsDualSense(VendorId, ProductId);
}
@@ -0,0 +1,13 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Runtime.InteropServices;
namespace FrameLedger.Application.Input;
/// <summary>What XInput says of one of its pads beside its state: whether it is wireless, and its battery in XInput's own words.</summary>
/// <param name="Wireless"><c>XINPUT_CAPS_WIRELESS</c>.</param>
/// <param name="BatteryType"><c>XINPUT_BATTERY_INFORMATION.BatteryType</c>; 0 (disconnected) when XInput did not answer.</param>
/// <param name="BatteryLevel"><c>XINPUT_BATTERY_INFORMATION.BatteryLevel</c>.</param>
[StructLayout(LayoutKind.Auto)]
public readonly record struct XInputDetails(bool Wireless, int BatteryType, int BatteryLevel);
@@ -0,0 +1,22 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Runtime.InteropServices;
namespace FrameLedger.Application.Input;
/// <summary>
/// One of XInput's pads at one read: <c>XINPUT_STATE</c> as it came. The reader asks one thing of it - is this a pad
/// in use (<c>Domain.Input.XInputPad.IsActive</c>) - and whether its packet number moved; neither it nor anything
/// derived from a single button or axis is kept.
/// </summary>
/// <param name="Packet"><c>dwPacketNumber</c>: it moves whenever anything on the pad changed.</param>
/// <param name="Buttons"><c>wButtons</c>.</param>
/// <param name="LeftTrigger"><c>bLeftTrigger</c>, 0-255.</param>
/// <param name="RightTrigger"><c>bRightTrigger</c>, 0-255.</param>
/// <param name="ThumbLx"><c>sThumbLX</c>.</param>
/// <param name="ThumbLy"><c>sThumbLY</c>.</param>
/// <param name="ThumbRx"><c>sThumbRX</c>.</param>
/// <param name="ThumbRy"><c>sThumbRY</c>.</param>
[StructLayout(LayoutKind.Auto)]
public readonly record struct XInputReading(uint Packet, int Buttons, int LeftTrigger, int RightTrigger, int ThumbLx, int ThumbLy, int ThumbRx, int ThumbRy);
@@ -128,6 +128,19 @@ public sealed record GameRow
/// </summary>
public AntiCheatExceptionState AcException { get; init; } = AntiCheatExceptionState.None;
/// <summary>
/// What the store's own file on the disk says of controller support (schema 0024, D163): <c>full</c>, <c>partial</c>,
/// or <c>none</c> for a game the store knows and lists no support for. Null when no store file describes the game or
/// none was read yet. It is the store's word, one of three pieces of evidence - never a verdict of FrameLedger's.
/// </summary>
public string? ControllerSupport { get; init; }
/// <summary>The file <see cref="ControllerSupport"/> was read from: <c>steam-appinfo</c> (schema 0024).</summary>
public string? ControllerSupportSource { get; init; }
/// <summary>When <see cref="ControllerSupport"/> was read (schema 0024).</summary>
public DateTimeOffset? ControllerSupportAt { get; init; }
public bool InLibrary => RemovedAt is null;
/// <summary>
@@ -88,6 +88,14 @@ public interface ISessionRepository
/// </summary>
ValueTask<IReadOnlyList<SensorBlob>> FindAdvancedSensorsAsync(long sessionId, CancellationToken ct = default);
/// <summary>
/// The session's input series (schema 0024, <c>03_METRICS</c> §Input), still encoded, with <c>t_ms</c> first: what
/// each tick was mostly played with, and each controller's part and battery. For a session that stored none that
/// is <c>t_ms</c> alone, or nothing. They are not among <see cref="FindSensorsAsync"/>'s for the reason the advanced
/// ones are not: NaN marks a tick with nothing to say, and their values are not a sensor's.
/// </summary>
ValueTask<IReadOnlyList<SensorBlob>> FindInputSensorsAsync(long sessionId, CancellationToken ct = default);
/// <summary>
/// The session's row of <c>session_advanced</c> with the machine profile it points to, or null: it was recorded
/// with Advanced metrics off (or before they existed).
@@ -401,4 +401,38 @@ public sealed record SessionRow
/// <summary>Application frames per joule of the card's power — FPS per watt; never over displayed frames (rule 6).</summary>
public double? AppFramesPerJoule { get; init; }
// --- Schema 0024 (beta.50, D155-D163): what the session was played with (03_METRICS §Input), both tiers - read by the
// Agent from outside the game. Null on a row written before it, with the option off, and before the terms that
// describe the reading were accepted.
/// <summary>The time the input reader ran and the session was not paused, in milliseconds.</summary>
public long? InputObservedMs { get; init; }
/// <summary>Of <see cref="InputObservedMs"/>, the time a window of the game was in front: what every share is a share of.</summary>
public long? InputForegroundMs { get; init; }
/// <summary>The time in front a controller was in use and the keyboard and mouse were not.</summary>
public long? InputControllerMs { get; init; }
/// <summary>The time in front the keyboard or mouse was in use and no controller was. One class: only the time of the last input is read (D158).</summary>
public long? InputKeyboardMouseMs { get; init; }
public long? InputBothMs { get; init; }
/// <summary>The time in front with no input at all.</summary>
public long? InputIdleMs { get; init; }
/// <summary>How many times the player went from a controller to the keyboard and mouse or back.</summary>
public int? InputMethodSwitches { get; init; }
/// <summary>The sources that answered: <c>rawinput</c>, <c>xinput</c>, <c>lastinput</c>, joined by <c>+</c>.</summary>
public string? InputSource { get; init; }
/// <summary>The session's controllers, their batteries and makers, and what the reader's sources did, as <c>InputDevicesRecord</c>'s JSON.</summary>
public string? InputDevicesJson { get; init; }
/// <summary>The share of the time in front spent in one class, 0-100; null when nothing was read or the game was never in front.</summary>
public double? InputSharePercent(long? classMs) =>
InputForegroundMs is > 0 and var front && classMs is { } ms ? 100d * ms / front : null;
}
@@ -61,6 +61,12 @@ public sealed class SessionFinalizer
// hooked has them all the same. Nothing when the option was off - no series, no row.
double hz = SampleRate(input.Sensors, row.QpcFrequency);
(IReadOnlyList<SensorBlob> advancedBlobs, AdvancedSessionRow? advanced) = AdvancedSessionBuilder.Build(input.Sensors, input.Advanced, _codec, hz);
// What the session was played with (D155-D163), both tiers and for the same reason: the Agent reads it from outside
// the game. From the samples alone, so a session recovered from its .partial file has it. Nothing when no sample
// carries a reading - the option was off, or the terms that describe the reading were not accepted yet.
(IReadOnlyList<SensorBlob> inputBlobs, InputSessionSummary? played) = InputSessionBuilder.Build(input.Sensors, _codec, hz);
row = WithInput(row, played);
if (input.Hooked is null)
{
// A Tier-2 row has no frames and every sensor the machine provided (2026-09-22): the same averages a
@@ -68,7 +74,7 @@ public sealed class SessionFinalizer
return new FinalizedSession
{
Row = SessionAggregator.WithSensorAggregates(row with { Tier = CaptureTier.NotHooked }, input.Sensors),
Sensors = [.. EncodeSensors(input.Sensors, row.QpcEpoch, row.QpcFrequency, hz), .. advancedBlobs],
Sensors = [.. EncodeSensors(input.Sensors, row.QpcEpoch, row.QpcFrequency, hz), .. advancedBlobs, .. inputBlobs],
Advanced = advanced,
};
}
@@ -83,11 +89,27 @@ public sealed class SessionFinalizer
{
FirstPresentMs = FirstPresentMs(r.Dominant, row.QpcEpoch, row.QpcFrequency),
},
Sensors = [.. EncodeSensors(input.Sensors, row.QpcEpoch, row.QpcFrequency, hz), .. advancedBlobs],
Sensors = [.. EncodeSensors(input.Sensors, row.QpcEpoch, row.QpcFrequency, hz), .. advancedBlobs, .. inputBlobs],
Advanced = advanced,
};
}
/// <summary>The row with what the session was played with (schema 0024); unchanged when nothing was read.</summary>
private static SessionRow WithInput(SessionRow row, InputSessionSummary? played) => played is null
? row
: row with
{
InputObservedMs = played.ObservedMs,
InputForegroundMs = played.ForegroundMs,
InputControllerMs = played.ControllerMs,
InputKeyboardMouseMs = played.KeyboardMouseMs,
InputBothMs = played.BothMs,
InputIdleMs = played.IdleMs,
InputMethodSwitches = played.MethodSwitches,
InputSource = played.Source,
InputDevicesJson = played.DevicesJson,
};
/// <summary>
/// The rate the session's samples had, a second (owner decision D146): the gaps between the first and the last
/// over the time between them, to a thousandth. 1 where there are fewer than two samples or no time between them.
@@ -0,0 +1,49 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
namespace FrameLedger.Domain.Input;
/// <summary>
/// The two things FrameLedger takes from the name Windows gives a controller's device interface, after which the name
/// is dropped (<c>21_INPUT_DEVICES</c> §What is never read): whether Windows presents the device through XInput, and
/// how it is connected.
/// </summary>
/// <remarks>
/// <para>
/// The name is a path such as <c>\\?\HID#VID_045E&amp;PID_0B12&amp;IG_00#…</c>. On Bluetooth it carries the service's
/// identifier - and, further along, an instance id that on some stacks is derived from the device's address. That is
/// why the name is never kept, logged or stored: this type returns two facts and holds no string.
/// </para>
/// <para>
/// <b><c>IG_</c></b> is Microsoft's documented mark of a device XInput presents ("XInput and DirectInput": a device id
/// that contains <c>IG_</c> is an XInput device). <b>The connection</b> is Bluetooth when the name carries the
/// identifier of the Bluetooth HID service, classic (<c>00001124-…</c>) or low energy (<c>00001812-…</c>), and USB
/// when it carries a USB vendor id written <c>VID_</c>; anything else is not known.
/// </para>
/// </remarks>
public static class RawDeviceName
{
private const string _xinputMark = "IG_";
private const string _bluetoothClassicService = "{00001124-0000-1000-8000-00805f9b34fb}";
private const string _bluetoothLowEnergyService = "{00001812-0000-1000-8000-00805f9b34fb}";
private const string _usbVendor = "VID_";
/// <summary>Whether Windows presents the device through XInput.</summary>
public static bool IsXInputClass(string? name) => name is not null && name.Contains(_xinputMark, StringComparison.OrdinalIgnoreCase);
/// <summary>How the device is connected, as far as its name says.</summary>
public static ControllerConnection ConnectionOf(string? name)
{
if (string.IsNullOrEmpty(name))
{
return ControllerConnection.Unknown;
}
if (name.Contains(_bluetoothClassicService, StringComparison.OrdinalIgnoreCase) || name.Contains(_bluetoothLowEnergyService, StringComparison.OrdinalIgnoreCase))
{
return ControllerConnection.Bluetooth;
}
return name.Contains(_usbVendor, StringComparison.OrdinalIgnoreCase) ? ControllerConnection.Usb : ControllerConnection.Unknown;
}
}
+2 -2
View File
@@ -19,7 +19,6 @@ public static class XInputPad
/// <summary><c>XINPUT_GAMEPAD_TRIGGER_THRESHOLD</c>.</summary>
public const int TriggerThreshold = 30;
private const int _typeDisconnected = 0x00;
private const int _typeWired = 0x01;
private const int _typeAlkaline = 0x02;
private const int _typeNimh = 0x03;
@@ -42,7 +41,8 @@ public static class XInputPad
{
_typeWired => BatteryReading.Wired,
_typeAlkaline or _typeNimh => new BatteryReading(BatteryState.Discharging, BatteryScale.FourLevels, Math.Clamp(level, 0, _levelFull)),
_typeDisconnected => null,
// 0 is XInput's "disconnected" and 0xFF its "unknown": neither is a battery to show.
_ => null,
};
@@ -0,0 +1,253 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using FrameLedger.Application.Input;
using FrameLedger.Application.Telemetry;
namespace FrameLedger.Infrastructure.Input;
/// <summary>
/// The Agent's one input reader, on a thread of its own, running only while a session has a view of it (owner
/// decisions D155-D163, <c>21_INPUT_DEVICES</c> §The reader). With no session it has no thread, no window and no
/// registration: FrameLedger reads nothing about a controller, the keyboard or the mouse.
/// </summary>
/// <remarks>
/// <para>
/// <b>One reader, several sessions.</b> Sessions run side by side (the watcher keeps a table of them), and a
/// controller's reports arrive once. So the thread makes one <see cref="InputSlice"/> about ten times a second and
/// hands it to every view; each view counts it for its own session when a window of that session's game was in front
/// (<see cref="InputTickAccumulator"/>).
/// </para>
/// <para>
/// <b>A pause is a gap here too.</b> While recording is paused (FR-3.9) a slice is not observed by any session.
/// </para>
/// <para>
/// <b>A slice that throws is counted and skipped</b>; <see cref="MaxFaults"/> in a row end the run with one line in
/// the Agent's log, and the sessions go on without readings. Nothing the reader does may end a session.
/// </para>
/// </remarks>
public sealed class InputDeviceHub : IInputDevices, IDisposable
{
/// <summary>Slices that may throw in a row before the run ends.</summary>
public const int MaxFaults = 20;
/// <summary>How long a slice is.</summary>
public static readonly TimeSpan SliceInterval = TimeSpan.FromMilliseconds(100);
private readonly Lock _gate = new();
private readonly Func<IInputBackend> _backendFactory;
private readonly Func<bool> _paused;
private readonly TimeSpan _interval;
private readonly Action<string> _note;
private readonly ManualResetEventSlim _wake = new(initialState: false);
private readonly List<View> _views = [];
private Thread? _thread;
private bool _disposed;
/// <summary>A hub that reads nothing until a view of it is opened.</summary>
/// <param name="backendFactory">Makes the Windows side a run uses; called on the hub's thread, once per run.</param>
/// <param name="paused">Whether recording is paused now; null is never.</param>
/// <param name="interval">How long a slice is; null is <see cref="SliceInterval"/>.</param>
/// <param name="note">Told, in one line, when a run ends - the Agent's log. No line names a device.</param>
public InputDeviceHub(Func<IInputBackend> backendFactory, Func<bool>? paused = null, TimeSpan? interval = null, Action<string>? note = null)
{
ArgumentNullException.ThrowIfNull(backendFactory);
_backendFactory = backendFactory;
_paused = paused ?? (static () => false);
_interval = interval ?? SliceInterval;
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(_interval, TimeSpan.Zero, nameof(interval));
_note = note ?? (static _ => { });
}
/// <summary>Whether a run is in progress.</summary>
public bool IsRunning
{
get
{
lock (_gate)
{
return _thread is not null;
}
}
}
public IInputActivitySource Open()
{
var view = new View(this);
lock (_gate)
{
ObjectDisposedException.ThrowIf(_disposed, this);
_views.Add(view);
if (_thread is null)
{
_thread = new Thread(Run) { IsBackground = true, Name = "fl-input" };
_thread.Start();
}
}
return view;
}
public void Dispose()
{
Thread? thread;
lock (_gate)
{
if (_disposed)
{
return;
}
_disposed = true;
thread = _thread;
}
_wake.Set();
if (thread is not null && thread != Thread.CurrentThread)
{
thread.Join(TimeSpan.FromSeconds(5));
}
_wake.Dispose();
}
private void Close(View view)
{
lock (_gate)
{
_views.Remove(view);
}
}
private void Run()
{
IInputBackend? backend = null;
InputHealth last = new();
try
{
backend = _backendFactory();
var reader = new InputReader(backend);
reader.Open();
long before = Stopwatch.GetTimestamp();
int faults = 0;
while (Wait())
{
long now = Stopwatch.GetTimestamp();
int elapsed = (int)Math.Min(Stopwatch.GetElapsedTime(before, now).TotalMilliseconds, int.MaxValue);
before = now;
try
{
InputSlice slice = reader.Slice(elapsed);
last = slice.Health;
faults = 0;
Hand(slice);
}
catch (Exception e) when (e is not OperationCanceledException)
{
reader.Fault();
if (++faults >= MaxFaults)
{
_note($"input: the reader's slice threw {MaxFaults} times running and the run ends ({e.GetType().Name}: {e.Message})");
break;
}
}
}
}
catch (Exception e) when (e is not OperationCanceledException)
{
_note($"input: the reader did not start ({e.GetType().Name}: {e.Message})");
}
finally
{
lock (_gate)
{
if (ReferenceEquals(_thread, Thread.CurrentThread))
{
_thread = null;
}
}
backend?.Dispose();
_note(Summary(last));
}
}
/// <summary>What a run did, as the Agent's log keeps it: counts and yes-or-no answers, nothing of any device.</summary>
private static string Summary(InputHealth h) => string.Create(CultureInfo.InvariantCulture,
$"input: run ended - slices {h.Slices}, raw input {(h.RawInputRegistered ? "registered" : "NOT registered")}, reports {h.RawReports} ({h.RawReportsUnread} not read), "
+ $"xinput {(h.XInputAvailable ? "there" : "absent")} with {h.XInputReads} reads and {h.XInputSilent} silent slices, last input {(h.LastInputAvailable ? "read" : "NOT read")}, "
+ $"thread cpu {h.ThreadCpuMs} ms, faults {h.Faults}");
/// <summary>Waits a slice; false when the run is over - the hub is disposed, or no view is open.</summary>
private bool Wait()
{
try
{
_wake.Wait(_interval);
}
catch (ObjectDisposedException)
{
// Dispose gave up waiting for this thread and released the event.
return false;
}
lock (_gate)
{
if (!_disposed && _views.Count > 0)
{
return true;
}
// Decided under the lock and the slot cleared in the same step, so an Open that arrives a moment later
// starts a run of its own rather than joining one that is closing.
if (ReferenceEquals(_thread, Thread.CurrentThread))
{
_thread = null;
}
return false;
}
}
private void Hand(InputSlice slice)
{
View[] views;
lock (_gate)
{
views = [.. _views];
}
bool paused = _paused();
foreach (View view in views)
{
view.Add(slice, paused);
}
}
/// <summary>One session's view.</summary>
private sealed class View(InputDeviceHub hub) : IInputActivitySource
{
private readonly InputTickAccumulator _sum = new();
private volatile int[] _pids = [];
public void Follow(GameProcess target)
{
ArgumentNullException.ThrowIfNull(target);
_pids = target.Pid is { } pinned ? [pinned] : [.. target.Processes.Select(static p => p.Pid)];
}
public bool TryRead([NotNullWhen(true)] out InputReading? reading)
{
reading = _sum.Take();
return reading is not null;
}
public void Add(InputSlice slice, bool paused) =>
_sum.Add(slice, inFront: slice.ForegroundProcessId != 0 && Array.IndexOf(_pids, (int)slice.ForegroundProcessId) >= 0, paused);
public void Dispose() => hub.Close(this);
}
}
@@ -0,0 +1,98 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Buffers.Binary;
using FrameLedger.Application.Input;
namespace FrameLedger.Infrastructure.Input;
/// <summary>
/// The bytes <c>GetRawInputBuffer</c> and <c>GetRawInputData</c> fill, walked without a pointer: a run of
/// <c>RAWINPUT</c> blocks, each a header and - for a HID device - a count of reports of one size
/// (<c>21_INPUT_DEVICES</c> §The reader).
/// </summary>
/// <remarks>
/// <para>
/// Layout on 64-bit Windows, which is all this project builds for: <c>RAWINPUTHEADER</c> is 24 bytes - <c>u32 type</c>,
/// <c>u32 size</c> of the whole block, the device's handle, a parameter - and a <c>RAWHID</c> follows it: <c>u32</c>
/// the size of one report, <c>u32</c> how many, then the reports. The next block starts at the next multiple of eight
/// (<c>NEXTRAWINPUTBLOCK</c>).
/// </para>
/// <para>
/// <b>It trusts no length it reads.</b> A block that claims more than the buffer holds, or less than its own header,
/// ends the walk: what was handed over before it stands, and nothing is read past the buffer. The bytes come from a
/// device by way of Windows, into an Agent that may run as administrator.
/// </para>
/// </remarks>
public static class RawInputBuffer
{
/// <summary><c>sizeof(RAWINPUTHEADER)</c> on 64-bit Windows.</summary>
public const int HeaderBytes = 24;
/// <summary><c>RIM_TYPEHID</c>: the block is a HID device's, the only kind the reader registers for.</summary>
public const uint TypeHid = 2;
private const int _hidHeaderBytes = 8;
/// <summary>Hands each report of each HID block to <paramref name="sink"/>; returns how many blocks were walked.</summary>
/// <param name="buffer">The bytes Windows filled.</param>
/// <param name="blocks">How many blocks Windows said it wrote.</param>
/// <param name="sink">Told each report with its device's handle.</param>
public static int Walk(ReadOnlySpan<byte> buffer, int blocks, IInputBackendSink sink)
{
ArgumentNullException.ThrowIfNull(sink);
int at = 0;
int walked = 0;
for (; walked < blocks; walked++)
{
if (buffer.Length - at < HeaderBytes)
{
break;
}
uint type = BinaryPrimitives.ReadUInt32LittleEndian(buffer[at..]);
uint size = BinaryPrimitives.ReadUInt32LittleEndian(buffer[(at + 4)..]);
if (size < HeaderBytes || size > buffer.Length - at)
{
break;
}
if (type == TypeHid)
{
Reports(buffer.Slice(at, (int)size), sink);
}
// Each block starts on a multiple of eight. The last one may end the buffer without the padding.
at += (int)((size + 7) & ~7u);
if (at > buffer.Length)
{
walked++;
break;
}
}
return walked;
}
private static void Reports(ReadOnlySpan<byte> block, IInputBackendSink sink)
{
if (block.Length < HeaderBytes + _hidHeaderBytes)
{
return;
}
nint device = (nint)BinaryPrimitives.ReadInt64LittleEndian(block[8..]);
uint reportBytes = BinaryPrimitives.ReadUInt32LittleEndian(block[HeaderBytes..]);
uint count = BinaryPrimitives.ReadUInt32LittleEndian(block[(HeaderBytes + 4)..]);
ReadOnlySpan<byte> reports = block[(HeaderBytes + _hidHeaderBytes)..];
if (reportBytes == 0 || count == 0 || (ulong)reportBytes * count > (ulong)reports.Length)
{
return;
}
for (int i = 0; i < count; i++)
{
sink.Report(device, reports.Slice(i * (int)reportBytes, (int)reportBytes));
}
}
}
@@ -0,0 +1,259 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Runtime.InteropServices;
namespace FrameLedger.Infrastructure.Input;
/// <summary>
/// Every Windows function the input reader calls, declared in one place so that the list can be held
/// (<c>tools/input-readonly-check.ps1</c>, <c>21_INPUT_DEVICES</c> §What is read): raw input for game controllers,
/// three of XInput's getters, the time of the last input, and the message-only window raw input is delivered to.
/// </summary>
/// <remarks>
/// <b>What is not here is not called.</b> No function that sends anything to a device (<c>XInputSetState</c>, a HID
/// output or feature report), none that reads a key or a button of the keyboard or mouse, no hook. The structures are
/// declared by hand, blittable, with the sizes the tests assert - the reader passes them to Windows by pointer.
/// </remarks>
internal static unsafe class Win32Input
{
public const uint WmInputDeviceChange = 0x00FE;
public const uint WmInput = 0x00FF;
/// <summary><c>GIDC_ARRIVAL</c> / <c>GIDC_REMOVAL</c>: <c>WM_INPUT_DEVICE_CHANGE</c>'s wParam.</summary>
public const nuint DeviceArrival = 1;
public const nuint DeviceRemoval = 2;
/// <summary><c>RIDEV_INPUTSINK</c>: reports are delivered while the caller is not in front.</summary>
public const uint RidevInputSink = 0x00000100;
/// <summary><c>RIDEV_DEVNOTIFY</c>: a device arriving or leaving is told.</summary>
public const uint RidevDevNotify = 0x00002000;
/// <summary><c>RIDEV_REMOVE</c>: ends a registration.</summary>
public const uint RidevRemove = 0x00000001;
public const uint RidiDeviceName = 0x20000007;
public const uint RidiDeviceInfo = 0x2000000B;
/// <summary><c>RID_INPUT</c>: <c>GetRawInputData</c> returns the whole block.</summary>
public const uint RidInput = 0x10000003;
public const uint PmRemove = 0x0001;
/// <summary><c>XINPUT_CAPS_WIRELESS</c>.</summary>
public const ushort XInputCapsWireless = 0x0002;
/// <summary><c>XINPUT_FLAG_GAMEPAD</c>.</summary>
public const uint XInputFlagGamepad = 0x00000001;
/// <summary><c>BATTERY_DEVTYPE_GAMEPAD</c>.</summary>
public const byte BatteryDevTypeGamepad = 0x00;
/// <summary><c>HWND_MESSAGE</c>: the parent of a window that is never shown and receives no broadcast.</summary>
public static readonly nint HwndMessage = -3;
private const string _user32 = "user32.dll";
private const string _kernel32 = "kernel32.dll";
private const string _xinput = "xinput1_4.dll";
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_user32, ExactSpelling = true, SetLastError = true)]
public static extern ushort RegisterClassExW(WndClassEx* windowClass);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_user32, ExactSpelling = true)]
public static extern int UnregisterClassW(char* className, nint instance);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_user32, ExactSpelling = true, SetLastError = true)]
public static extern nint CreateWindowExW(uint exStyle, char* className, char* windowName, uint style, int x, int y, int width, int height, nint parent, nint menu, nint instance, void* param);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_user32, ExactSpelling = true)]
public static extern int DestroyWindow(nint window);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_user32, ExactSpelling = true)]
public static extern nint DefWindowProcW(nint window, uint message, nuint wParam, nint lParam);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_user32, ExactSpelling = true)]
public static extern int PeekMessageW(Message* message, nint window, uint filterMin, uint filterMax, uint remove);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_user32, ExactSpelling = true)]
public static extern nint DispatchMessageW(Message* message);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_user32, ExactSpelling = true, SetLastError = true)]
public static extern int RegisterRawInputDevices(RawInputDevice* devices, uint count, uint size);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_user32, ExactSpelling = true, SetLastError = true)]
public static extern uint GetRawInputBuffer(void* data, uint* size, uint headerSize);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_user32, ExactSpelling = true, SetLastError = true)]
public static extern uint GetRawInputData(nint rawInput, uint command, void* data, uint* size, uint headerSize);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_user32, ExactSpelling = true, SetLastError = true)]
public static extern uint GetRawInputDeviceInfoW(nint device, uint command, void* data, uint* size);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_user32, ExactSpelling = true, SetLastError = true)]
public static extern uint GetRawInputDeviceList(RawInputDeviceListEntry* list, uint* count, uint size);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_user32, ExactSpelling = true)]
public static extern int GetLastInputInfo(LastInputInfo* info);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_kernel32, ExactSpelling = true)]
public static extern nint GetModuleHandleW(char* name);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_kernel32, ExactSpelling = true)]
public static extern nint GetCurrentThread();
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_kernel32, ExactSpelling = true)]
public static extern int GetThreadTimes(nint thread, long* creation, long* exit, long* kernel, long* user);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_xinput, ExactSpelling = true)]
public static extern uint XInputGetState(uint userIndex, XInputState* state);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_xinput, ExactSpelling = true)]
public static extern uint XInputGetCapabilities(uint userIndex, uint flags, XInputCapabilities* capabilities);
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[DllImport(_xinput, ExactSpelling = true)]
public static extern uint XInputGetBatteryInformation(uint userIndex, byte deviceType, XInputBatteryInformation* battery);
/// <summary><c>WNDCLASSEXW</c>.</summary>
[StructLayout(LayoutKind.Sequential)]
public struct WndClassEx
{
public uint Size;
public uint Style;
public delegate* unmanaged[Stdcall]<nint, uint, nuint, nint, nint> WndProc;
public int ClassExtra;
public int WindowExtra;
public nint Instance;
public nint Icon;
public nint Cursor;
public nint Background;
public char* MenuName;
public char* ClassName;
public nint SmallIcon;
}
/// <summary><c>MSG</c>.</summary>
[StructLayout(LayoutKind.Sequential)]
public struct Message
{
public nint Window;
public uint Id;
public nuint WParam;
public nint LParam;
public uint Time;
public int X;
public int Y;
}
/// <summary><c>RAWINPUTDEVICE</c>.</summary>
[StructLayout(LayoutKind.Sequential)]
public struct RawInputDevice
{
public ushort UsagePage;
public ushort Usage;
public uint Flags;
public nint Target;
}
/// <summary><c>RAWINPUTDEVICELIST</c>.</summary>
[StructLayout(LayoutKind.Sequential)]
public struct RawInputDeviceListEntry
{
public nint Device;
public uint Type;
}
/// <summary><c>RID_DEVICE_INFO</c>, with the HID member of its union - the only one the reader looks at.</summary>
[StructLayout(LayoutKind.Explicit, Size = 32)]
public struct RidDeviceInfo
{
[FieldOffset(0)]
public uint Size;
[FieldOffset(4)]
public uint Type;
[FieldOffset(8)]
public uint VendorId;
[FieldOffset(12)]
public uint ProductId;
[FieldOffset(16)]
public uint VersionNumber;
[FieldOffset(20)]
public ushort UsagePage;
[FieldOffset(22)]
public ushort Usage;
}
/// <summary><c>XINPUT_GAMEPAD</c>.</summary>
[StructLayout(LayoutKind.Sequential)]
public struct XInputGamepad
{
public ushort Buttons;
public byte LeftTrigger;
public byte RightTrigger;
public short ThumbLx;
public short ThumbLy;
public short ThumbRx;
public short ThumbRy;
}
/// <summary><c>XINPUT_STATE</c>.</summary>
[StructLayout(LayoutKind.Sequential)]
public struct XInputState
{
public uint PacketNumber;
public XInputGamepad Gamepad;
}
/// <summary><c>XINPUT_CAPABILITIES</c>.</summary>
[StructLayout(LayoutKind.Sequential)]
public struct XInputCapabilities
{
public byte Type;
public byte SubType;
public ushort Flags;
public XInputGamepad Gamepad;
public ushort LeftMotor;
public ushort RightMotor;
}
/// <summary><c>XINPUT_BATTERY_INFORMATION</c>.</summary>
[StructLayout(LayoutKind.Sequential)]
public struct XInputBatteryInformation
{
public byte Type;
public byte Level;
}
/// <summary><c>LASTINPUTINFO</c>.</summary>
[StructLayout(LayoutKind.Sequential)]
public struct LastInputInfo
{
public uint Size;
public uint Time;
}
}
@@ -0,0 +1,383 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using FrameLedger.Application.Input;
using FrameLedger.Domain.Input;
using FrameLedger.Infrastructure.Io;
using Microsoft.Win32.SafeHandles;
namespace FrameLedger.Infrastructure.Input;
/// <summary>
/// The input reader's Windows side (<c>21_INPUT_DEVICES</c> §The reader): a window that is never shown, registered to
/// receive game controllers' reports while the Agent is in the background; three of XInput's getters; the time of the
/// last keyboard or mouse input; the window in front.
/// </summary>
/// <remarks>
/// <para>
/// <b>It opens no device.</b> Raw input hands the reports over; a handle of FrameLedger's on a controller could make a
/// game's own exclusive open of it fail. <b>It sends nothing to a device</b> and asks none for a feature report (owner
/// decision D159). <b>It registers for game controllers only</b> - <see cref="InputReader.RegisteredUsages"/> - never
/// for a keyboard or a mouse (D158).
/// </para>
/// <para>
/// <b>Reports are read in bulk, once a slice</b> (<c>GetRawInputBuffer</c>), not one message at a time: a DualSense
/// sends some hundreds a second, and the Agent's whole budget is 2.5 % of one core (NFR-2). A report that still comes
/// as a message is read too, so that neither path alone has to be the one that works on a given PC.
/// </para>
/// <para>
/// <b>A device's name is read and dropped.</b> It says whether Windows presents the device through XInput and how it
/// is connected (<see cref="RawDeviceName"/>); it can also carry an address, so it is never kept, logged or returned.
/// </para>
/// <para>
/// <b>No controller was at hand when this was written</b> (owner decision D157). What it does with none connected is
/// under test; what it does with one is owner-only item 48, read from the counts every session stores.
/// </para>
/// </remarks>
public sealed unsafe class Win32InputBackend : IInputBackend
{
/// <summary>The most messages one drain takes off the queue, and the most reads of the buffer: a slice is short.</summary>
private const int _maxMessages = 2048;
private const int _maxBufferReads = 64;
private const int _bufferBytes = 64 * 1024;
private const int _maxNameChars = 1024;
private const uint _success = 0;
private const uint _failed = unchecked((uint)-1);
private const string _className = "FrameLedger.InputReader";
private readonly List<(nint Device, RawController Controller)> _present = [];
private byte[]? _buffer;
private MessageWindow? _window;
private bool _classRegistered;
private bool _registered;
private bool _xinputAvailable = true;
private bool _disposed;
public bool XInputAvailable => _xinputAvailable;
public bool Open()
{
ObjectDisposedException.ThrowIf(_disposed, this);
AssertLayout();
// On the pinned heap and so at an address a multiple of eight, which GetRawInputBuffer requires of its buffer.
_buffer = GC.AllocateUninitializedArray<byte>(_bufferBytes, pinned: true);
nint instance = Win32Input.GetModuleHandleW(null);
nint window;
fixed (char* name = _className)
{
var windowClass = new Win32Input.WndClassEx
{
Size = (uint)sizeof(Win32Input.WndClassEx),
WndProc = &WindowProcedure,
Instance = instance,
ClassName = name,
};
// Zero with the class already there is fine: an earlier reader of this process registered it.
_classRegistered = Win32Input.RegisterClassExW(&windowClass) != 0;
window = Win32Input.CreateWindowExW(0, name, name, 0, 0, 0, 0, 0, Win32Input.HwndMessage, 0, instance, null);
}
if (window == 0)
{
return false;
}
_window = new MessageWindow(window);
_registered = Register(Win32Input.RidevInputSink | Win32Input.RidevDevNotify, window);
if (_registered)
{
ListPresent();
}
return _registered;
}
public void Drain(IInputBackendSink sink)
{
ArgumentNullException.ThrowIfNull(sink);
if (_window is null || _buffer is null)
{
return;
}
// The controllers that were there when the reader opened, once.
foreach ((nint device, RawController controller) in _present)
{
sink.Arrived(device, controller);
}
_present.Clear();
// First who came and went, so that a report is never of a device nobody has named yet.
Win32Input.Message message;
for (int i = 0; i < _maxMessages && Win32Input.PeekMessageW(&message, 0, Win32Input.WmInputDeviceChange, Win32Input.WmInputDeviceChange, Win32Input.PmRemove) != 0; i++)
{
DeviceChanged(message, sink);
}
ReadBuffered(sink);
// Then whatever is left on the queue. A report that came as a message is read as one; anything else is the
// window's to answer, which for this window is the default.
for (int i = 0; i < _maxMessages && Win32Input.PeekMessageW(&message, 0, 0, 0, Win32Input.PmRemove) != 0; i++)
{
if (message.Id == Win32Input.WmInputDeviceChange)
{
DeviceChanged(message, sink);
}
else if (message.Id == Win32Input.WmInput)
{
ReadMessage(message.LParam, sink);
}
Win32Input.DispatchMessageW(&message);
}
}
public bool TryReadPad(int slot, out XInputReading pad)
{
pad = default;
if (!_xinputAvailable)
{
return false;
}
Win32Input.XInputState state;
try
{
if (Win32Input.XInputGetState((uint)slot, &state) != _success)
{
return false;
}
}
catch (Exception e) when (e is DllNotFoundException or EntryPointNotFoundException)
{
_xinputAvailable = false;
return false;
}
Win32Input.XInputGamepad g = state.Gamepad;
pad = new XInputReading(state.PacketNumber, g.Buttons, g.LeftTrigger, g.RightTrigger, g.ThumbLx, g.ThumbLy, g.ThumbRx, g.ThumbRy);
return true;
}
public bool TryReadPadDetails(int slot, out XInputDetails details)
{
details = default;
if (!_xinputAvailable)
{
return false;
}
try
{
Win32Input.XInputCapabilities capabilities;
if (Win32Input.XInputGetCapabilities((uint)slot, Win32Input.XInputFlagGamepad, &capabilities) != _success)
{
return false;
}
// A pad whose battery XInput does not answer about - one on Bluetooth is reported not to - still has its
// wireless flag: type 0 is XInput's own "disconnected", which reads as no battery to show.
Win32Input.XInputBatteryInformation battery = default;
bool answered = Win32Input.XInputGetBatteryInformation((uint)slot, Win32Input.BatteryDevTypeGamepad, &battery) == _success;
details = new XInputDetails((capabilities.Flags & Win32Input.XInputCapsWireless) != 0, answered ? battery.Type : 0, answered ? battery.Level : 0);
return true;
}
catch (Exception e) when (e is DllNotFoundException or EntryPointNotFoundException)
{
_xinputAvailable = false;
return false;
}
}
public bool TryReadLastInputTick(out uint tick)
{
var info = new Win32Input.LastInputInfo { Size = (uint)sizeof(Win32Input.LastInputInfo) };
bool read = Win32Input.GetLastInputInfo(&info) != 0;
tick = read ? info.Time : 0;
return read;
}
public uint ForegroundProcessId() => ForegroundWindowProbe.ForegroundProcessId();
public long ThreadCpuMs()
{
long creation;
long exit;
long kernel;
long user;
return Win32Input.GetThreadTimes(Win32Input.GetCurrentThread(), &creation, &exit, &kernel, &user) != 0
? (kernel + user) / TimeSpan.TicksPerMillisecond
: 0;
}
/// <summary>
/// Ends the registration and destroys the window. Called on the thread that opened it: a window belongs to its
/// thread, and Windows refuses another's attempt to destroy it.
/// </summary>
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
if (_registered)
{
// Ending a registration names no window (the API refuses one there).
Register(Win32Input.RidevRemove, target: 0);
_registered = false;
}
_window?.Dispose();
_window = null;
if (_classRegistered)
{
fixed (char* name = _className)
{
_ = Win32Input.UnregisterClassW(name, Win32Input.GetModuleHandleW(null));
}
_classRegistered = false;
}
_buffer = null;
}
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])]
private static nint WindowProcedure(nint window, uint message, nuint wParam, nint lParam) => Win32Input.DefWindowProcW(window, message, wParam, lParam);
/// <summary>The structures are passed to Windows by pointer: a size that is not Windows' is a bug to stop on, not to read with.</summary>
private static void AssertLayout()
{
if (sizeof(Win32Input.WndClassEx) != 80 || sizeof(Win32Input.Message) != 48 || sizeof(Win32Input.RawInputDevice) != 16
|| sizeof(Win32Input.RawInputDeviceListEntry) != 16 || sizeof(Win32Input.RidDeviceInfo) != 32 || sizeof(Win32Input.XInputState) != 16
|| sizeof(Win32Input.XInputCapabilities) != 20 || sizeof(Win32Input.XInputBatteryInformation) != 2 || sizeof(Win32Input.LastInputInfo) != 8
|| nint.Size != 8)
{
throw new InvalidOperationException("the input reader's structures are not the size Windows expects of them");
}
}
private static bool Register(uint flags, nint target)
{
IReadOnlyList<(ushort UsagePage, ushort Usage)> usages = InputReader.RegisteredUsages;
Win32Input.RawInputDevice* devices = stackalloc Win32Input.RawInputDevice[usages.Count];
for (int i = 0; i < usages.Count; i++)
{
devices[i] = new Win32Input.RawInputDevice { UsagePage = usages[i].UsagePage, Usage = usages[i].Usage, Flags = flags, Target = target };
}
return Win32Input.RegisterRawInputDevices(devices, (uint)usages.Count, (uint)sizeof(Win32Input.RawInputDevice)) != 0;
}
private void ListPresent()
{
uint count = 0;
uint entry = (uint)sizeof(Win32Input.RawInputDeviceListEntry);
if (Win32Input.GetRawInputDeviceList(null, &count, entry) == _failed || count is 0 or > 4096)
{
return;
}
var list = new Win32Input.RawInputDeviceListEntry[count];
fixed (Win32Input.RawInputDeviceListEntry* p = list)
{
uint written = Win32Input.GetRawInputDeviceList(p, &count, entry);
if (written == _failed)
{
return;
}
for (int i = 0; i < written && i < list.Length; i++)
{
if (list[i].Type == RawInputBuffer.TypeHid && Describe(list[i].Device) is { } controller)
{
_present.Add((list[i].Device, controller));
}
}
}
}
private static void DeviceChanged(Win32Input.Message message, IInputBackendSink sink)
{
if (message.WParam == Win32Input.DeviceArrival)
{
if (Describe(message.LParam) is { } controller)
{
sink.Arrived(message.LParam, controller);
}
}
else if (message.WParam == Win32Input.DeviceRemoval)
{
sink.Removed(message.LParam);
}
}
/// <summary>What a device is, when it is a game controller; null for anything else, and for a device that left before it could be asked.</summary>
private static RawController? Describe(nint device)
{
var info = new Win32Input.RidDeviceInfo { Size = (uint)sizeof(Win32Input.RidDeviceInfo) };
uint size = info.Size;
uint written = Win32Input.GetRawInputDeviceInfoW(device, Win32Input.RidiDeviceInfo, &info, &size);
if (written is 0 or _failed || info.Type != RawInputBuffer.TypeHid
|| !InputReader.RegisteredUsages.Contains((info.UsagePage, info.Usage)))
{
return null;
}
// The name is used for the two facts below and goes no further than this method.
char* name = stackalloc char[_maxNameChars];
uint chars = _maxNameChars;
uint copied = Win32Input.GetRawInputDeviceInfoW(device, Win32Input.RidiDeviceName, name, &chars);
string? path = copied is 0 or _failed || copied > _maxNameChars ? null : new string(name, 0, (int)copied).TrimEnd('\0');
return new RawController((int)(info.VendorId & 0xFFFF), (int)(info.ProductId & 0xFFFF), RawDeviceName.IsXInputClass(path), RawDeviceName.ConnectionOf(path));
}
private void ReadBuffered(IInputBackendSink sink)
{
fixed (byte* buffer = _buffer)
{
for (int i = 0; i < _maxBufferReads; i++)
{
uint size = _bufferBytes;
uint blocks = Win32Input.GetRawInputBuffer(buffer, &size, RawInputBuffer.HeaderBytes);
if (blocks is 0 or _failed)
{
return;
}
RawInputBuffer.Walk(new ReadOnlySpan<byte>(buffer, _bufferBytes), (int)Math.Min(blocks, int.MaxValue), sink);
}
}
}
/// <summary>The message-only window, as a handle that is destroyed once.</summary>
private sealed class MessageWindow : SafeHandleZeroOrMinusOneIsInvalid
{
public MessageWindow(nint window)
: base(ownsHandle: true) => SetHandle(window);
protected override bool ReleaseHandle() => Win32Input.DestroyWindow(handle) != 0;
}
private void ReadMessage(nint rawInput, IInputBackendSink sink)
{
fixed (byte* buffer = _buffer)
{
uint size = _bufferBytes;
uint written = Win32Input.GetRawInputData(rawInput, Win32Input.RidInput, buffer, &size, RawInputBuffer.HeaderBytes);
if (written is not (0 or _failed) && written <= _bufferBytes)
{
RawInputBuffer.Walk(new ReadOnlySpan<byte>(buffer, (int)written), 1, sink);
}
}
}
}
@@ -0,0 +1,35 @@
-- 0024 (2026-11-14, 0.1.0-beta.50, owner decisions D155-D163): what a session was played with, and whether a game's
-- store lists controller support (03_METRICS §Input, 21_INPUT_DEVICES).
--
-- sessions: milliseconds, read by the Agent from outside the game - so both tiers have them. `input_observed_ms` is the
-- time the reader ran and the session was not paused; `input_foreground_ms` is the part of it a window of the game was
-- in front, and the four classes add up to it: a controller in use, the keyboard or mouse in use (one class - only the
-- time of the last input is read), both, neither. `input_method_switches` counts the changes between a controller and
-- the keyboard and mouse. `input_source` names the sources that answered (rawinput, xinput, lastinput, joined by +).
-- `input_devices` is InputDevicesRecord's JSON: each controller's maker, model and connection, its time connected and
-- in use, its connections and drops, its battery; each maker's share; what the reader's sources did. No serial number,
-- no address, no path. The series of the timeline are sensor_blobs rows named input.* (NaN where there is no value).
--
-- These are columns of sessions, not a table of their own, on purpose (D160): the trend and the comparison read a
-- session's row, and the CSV/JSON export and the bug bundle carry it - the Privacy Policy's section 3A says so.
--
-- games: `controller_support` is what the store's own file on the disk says - 'full', 'partial', or 'none' for a game
-- the store knows and lists no support for; `controller_support_source` names the file ('steam-appinfo');
-- `controller_support_at` is when it was read (unix ms). No network request is made for it.
--
-- NULL on every row written before; on a session recorded with the option off, or before the terms that describe the
-- reading were accepted (D156); on a game no store file describes. ADD COLUMN only.
ALTER TABLE sessions ADD COLUMN input_observed_ms INTEGER;
ALTER TABLE sessions ADD COLUMN input_foreground_ms INTEGER;
ALTER TABLE sessions ADD COLUMN input_controller_ms INTEGER;
ALTER TABLE sessions ADD COLUMN input_km_ms INTEGER;
ALTER TABLE sessions ADD COLUMN input_both_ms INTEGER;
ALTER TABLE sessions ADD COLUMN input_idle_ms INTEGER;
ALTER TABLE sessions ADD COLUMN input_method_switches INTEGER;
ALTER TABLE sessions ADD COLUMN input_source TEXT;
ALTER TABLE sessions ADD COLUMN input_devices TEXT;
ALTER TABLE games ADD COLUMN controller_support TEXT;
ALTER TABLE games ADD COLUMN controller_support_source TEXT;
ALTER TABLE games ADD COLUMN controller_support_at INTEGER;
@@ -19,10 +19,10 @@ namespace FrameLedger.Infrastructure.Persistence;
internal static class SessionRowColumns
{
public const string Insert =
"INSERT INTO sessions (session_guid, game_id, snapshot_id, started_at, ended_at, duration_s, qpc_epoch, qpc_frequency, capture_tier, capture_mode, capture_notes, ac_exception_family, late_attach, telemetry_source, overlay_build_id, exit_status, drain_ticks, foreground_ticks, records_before_attach, dxgi_presents_before_hook, gap_count, guard_ticks_published, launch_wait_ms, api, present_mode, swap_effect, hdr_flag, hdr_source, sync_interval_mode, upscaler, upscaler_quality, upscaler_sharpness, upscaler_driver_reported, render_w, render_h, output_w, output_h, upscale_ratio, settings_changed_midsession, fg_mode, fg_source, fg_factor, fg_driver_reported, fg_runtime_census, fg_none_withheld_reason, fg_refusal, fg_refusal_detail, fg_factor_scope, fg_steady_share, presented_fps, presented_qualifier, dxgi_unseen_total, dxgi_present_samples, displayed_counted_by, sl_tag_census, sl_interposer_version, runtime_modules, driver_profile, executable_markers, ngx_driver_words, rt_flag, rt_source, pt_flag, pt_source, pt_confidence, rr_flag, rr_source, rt_frame_pct, rays_per_pixel, rt_pso_count, rt_tier, hooks_installed_mask, raster_pso_count, frame_count, app_frame_count, displayed_frame_count, dropped_frames, native_fps, displayed_fps, median_fps, p1_low_fps, p01_low_fps, displayed_p1_low_fps, min_fps, max_fps, frametime_stddev_ms, stutter_count, stutter_time_pct, pso_stutter_pct, reflex_active, latency_avg_us, latency_p95_us, dropped_records, fault_count, data_quality_warnings, writer_status_at_end, early_stop_family, loader_signals, vram_proc_avg_mb, vram_proc_max_mb, vram_budget_exceeded_pct, vram_adapter_max_mb, avg_cpu_temp, max_cpu_temp, avg_gpu_temp, max_gpu_temp, max_gpu_hotspot, avg_gpu_load, avg_cpu_load, avg_ram_mb, avg_gpu_power_w, throttle_pct, display_exclusive_ms, display_borderless_ms, display_windowed_ms, display_covers_ms, display_minimized_ms, display_nowindow_ms, display_changes, display_source, display_window_w, display_window_h, display_buffer_w, display_buffer_h, display_monitor_w, display_monitor_h, display_monitor_hz, game_vram_dedicated_avg_mb, game_vram_dedicated_median_mb, game_vram_dedicated_max_mb, game_vram_shared_max_mb, game_ram_private_avg_mb, game_ram_private_median_mb, game_ram_private_max_mb, game_ram_ws_max_mb, game_commit_max_mb, game_memory_processes, game_memory_source, sensor_stats_json, time_below_30_pct, time_below_60_pct, time_below_refresh_pct, frametime_delta_mean_ms, vsync_present_pct, tearing_allowed_pct, avg_gpu_core_clock_mhz, avg_gpu_mem_clock_mhz, avg_gpu_fan_rpm, max_gpu_mem_temp, power_limit_pct, thermal_limit_pct, app_frames_per_joule, fg_mix, runtime_module_sources, dlss_nr_pct) "
+ "VALUES (@session_guid, @game_id, @snapshot_id, @started_at, @ended_at, @duration_s, @qpc_epoch, @qpc_frequency, @capture_tier, @capture_mode, @capture_notes, @ac_exception_family, @late_attach, @telemetry_source, @overlay_build_id, @exit_status, @drain_ticks, @foreground_ticks, @records_before_attach, @dxgi_presents_before_hook, @gap_count, @guard_ticks_published, @launch_wait_ms, @api, @present_mode, @swap_effect, @hdr_flag, @hdr_source, @sync_interval_mode, @upscaler, @upscaler_quality, @upscaler_sharpness, @upscaler_driver_reported, @render_w, @render_h, @output_w, @output_h, @upscale_ratio, @settings_changed_midsession, @fg_mode, @fg_source, @fg_factor, @fg_driver_reported, @fg_runtime_census, @fg_none_withheld_reason, @fg_refusal, @fg_refusal_detail, @fg_factor_scope, @fg_steady_share, @presented_fps, @presented_qualifier, @dxgi_unseen_total, @dxgi_present_samples, @displayed_counted_by, @sl_tag_census, @sl_interposer_version, @runtime_modules, @driver_profile, @executable_markers, @ngx_driver_words, @rt_flag, @rt_source, @pt_flag, @pt_source, @pt_confidence, @rr_flag, @rr_source, @rt_frame_pct, @rays_per_pixel, @rt_pso_count, @rt_tier, @hooks_installed_mask, @raster_pso_count, @frame_count, @app_frame_count, @displayed_frame_count, @dropped_frames, @native_fps, @displayed_fps, @median_fps, @p1_low_fps, @p01_low_fps, @displayed_p1_low_fps, @min_fps, @max_fps, @frametime_stddev_ms, @stutter_count, @stutter_time_pct, @pso_stutter_pct, @reflex_active, @latency_avg_us, @latency_p95_us, @dropped_records, @fault_count, @data_quality_warnings, @writer_status_at_end, @early_stop_family, @loader_signals, @vram_proc_avg_mb, @vram_proc_max_mb, @vram_budget_exceeded_pct, @vram_adapter_max_mb, @avg_cpu_temp, @max_cpu_temp, @avg_gpu_temp, @max_gpu_temp, @max_gpu_hotspot, @avg_gpu_load, @avg_cpu_load, @avg_ram_mb, @avg_gpu_power_w, @throttle_pct, @display_exclusive_ms, @display_borderless_ms, @display_windowed_ms, @display_covers_ms, @display_minimized_ms, @display_nowindow_ms, @display_changes, @display_source, @display_window_w, @display_window_h, @display_buffer_w, @display_buffer_h, @display_monitor_w, @display_monitor_h, @display_monitor_hz, @game_vram_dedicated_avg_mb, @game_vram_dedicated_median_mb, @game_vram_dedicated_max_mb, @game_vram_shared_max_mb, @game_ram_private_avg_mb, @game_ram_private_median_mb, @game_ram_private_max_mb, @game_ram_ws_max_mb, @game_commit_max_mb, @game_memory_processes, @game_memory_source, @sensor_stats_json, @time_below_30_pct, @time_below_60_pct, @time_below_refresh_pct, @frametime_delta_mean_ms, @vsync_present_pct, @tearing_allowed_pct, @avg_gpu_core_clock_mhz, @avg_gpu_mem_clock_mhz, @avg_gpu_fan_rpm, @max_gpu_mem_temp, @power_limit_pct, @thermal_limit_pct, @app_frames_per_joule, @fg_mix, @runtime_module_sources, @dlss_nr_pct) RETURNING id";
"INSERT INTO sessions (session_guid, game_id, snapshot_id, started_at, ended_at, duration_s, qpc_epoch, qpc_frequency, capture_tier, capture_mode, capture_notes, ac_exception_family, late_attach, telemetry_source, overlay_build_id, exit_status, drain_ticks, foreground_ticks, records_before_attach, dxgi_presents_before_hook, gap_count, guard_ticks_published, launch_wait_ms, api, present_mode, swap_effect, hdr_flag, hdr_source, sync_interval_mode, upscaler, upscaler_quality, upscaler_sharpness, upscaler_driver_reported, render_w, render_h, output_w, output_h, upscale_ratio, settings_changed_midsession, fg_mode, fg_source, fg_factor, fg_driver_reported, fg_runtime_census, fg_none_withheld_reason, fg_refusal, fg_refusal_detail, fg_factor_scope, fg_steady_share, presented_fps, presented_qualifier, dxgi_unseen_total, dxgi_present_samples, displayed_counted_by, sl_tag_census, sl_interposer_version, runtime_modules, driver_profile, executable_markers, ngx_driver_words, rt_flag, rt_source, pt_flag, pt_source, pt_confidence, rr_flag, rr_source, rt_frame_pct, rays_per_pixel, rt_pso_count, rt_tier, hooks_installed_mask, raster_pso_count, frame_count, app_frame_count, displayed_frame_count, dropped_frames, native_fps, displayed_fps, median_fps, p1_low_fps, p01_low_fps, displayed_p1_low_fps, min_fps, max_fps, frametime_stddev_ms, stutter_count, stutter_time_pct, pso_stutter_pct, reflex_active, latency_avg_us, latency_p95_us, dropped_records, fault_count, data_quality_warnings, writer_status_at_end, early_stop_family, loader_signals, vram_proc_avg_mb, vram_proc_max_mb, vram_budget_exceeded_pct, vram_adapter_max_mb, avg_cpu_temp, max_cpu_temp, avg_gpu_temp, max_gpu_temp, max_gpu_hotspot, avg_gpu_load, avg_cpu_load, avg_ram_mb, avg_gpu_power_w, throttle_pct, display_exclusive_ms, display_borderless_ms, display_windowed_ms, display_covers_ms, display_minimized_ms, display_nowindow_ms, display_changes, display_source, display_window_w, display_window_h, display_buffer_w, display_buffer_h, display_monitor_w, display_monitor_h, display_monitor_hz, game_vram_dedicated_avg_mb, game_vram_dedicated_median_mb, game_vram_dedicated_max_mb, game_vram_shared_max_mb, game_ram_private_avg_mb, game_ram_private_median_mb, game_ram_private_max_mb, game_ram_ws_max_mb, game_commit_max_mb, game_memory_processes, game_memory_source, sensor_stats_json, time_below_30_pct, time_below_60_pct, time_below_refresh_pct, frametime_delta_mean_ms, vsync_present_pct, tearing_allowed_pct, avg_gpu_core_clock_mhz, avg_gpu_mem_clock_mhz, avg_gpu_fan_rpm, max_gpu_mem_temp, power_limit_pct, thermal_limit_pct, app_frames_per_joule, fg_mix, runtime_module_sources, dlss_nr_pct, input_observed_ms, input_foreground_ms, input_controller_ms, input_km_ms, input_both_ms, input_idle_ms, input_method_switches, input_source, input_devices) "
+ "VALUES (@session_guid, @game_id, @snapshot_id, @started_at, @ended_at, @duration_s, @qpc_epoch, @qpc_frequency, @capture_tier, @capture_mode, @capture_notes, @ac_exception_family, @late_attach, @telemetry_source, @overlay_build_id, @exit_status, @drain_ticks, @foreground_ticks, @records_before_attach, @dxgi_presents_before_hook, @gap_count, @guard_ticks_published, @launch_wait_ms, @api, @present_mode, @swap_effect, @hdr_flag, @hdr_source, @sync_interval_mode, @upscaler, @upscaler_quality, @upscaler_sharpness, @upscaler_driver_reported, @render_w, @render_h, @output_w, @output_h, @upscale_ratio, @settings_changed_midsession, @fg_mode, @fg_source, @fg_factor, @fg_driver_reported, @fg_runtime_census, @fg_none_withheld_reason, @fg_refusal, @fg_refusal_detail, @fg_factor_scope, @fg_steady_share, @presented_fps, @presented_qualifier, @dxgi_unseen_total, @dxgi_present_samples, @displayed_counted_by, @sl_tag_census, @sl_interposer_version, @runtime_modules, @driver_profile, @executable_markers, @ngx_driver_words, @rt_flag, @rt_source, @pt_flag, @pt_source, @pt_confidence, @rr_flag, @rr_source, @rt_frame_pct, @rays_per_pixel, @rt_pso_count, @rt_tier, @hooks_installed_mask, @raster_pso_count, @frame_count, @app_frame_count, @displayed_frame_count, @dropped_frames, @native_fps, @displayed_fps, @median_fps, @p1_low_fps, @p01_low_fps, @displayed_p1_low_fps, @min_fps, @max_fps, @frametime_stddev_ms, @stutter_count, @stutter_time_pct, @pso_stutter_pct, @reflex_active, @latency_avg_us, @latency_p95_us, @dropped_records, @fault_count, @data_quality_warnings, @writer_status_at_end, @early_stop_family, @loader_signals, @vram_proc_avg_mb, @vram_proc_max_mb, @vram_budget_exceeded_pct, @vram_adapter_max_mb, @avg_cpu_temp, @max_cpu_temp, @avg_gpu_temp, @max_gpu_temp, @max_gpu_hotspot, @avg_gpu_load, @avg_cpu_load, @avg_ram_mb, @avg_gpu_power_w, @throttle_pct, @display_exclusive_ms, @display_borderless_ms, @display_windowed_ms, @display_covers_ms, @display_minimized_ms, @display_nowindow_ms, @display_changes, @display_source, @display_window_w, @display_window_h, @display_buffer_w, @display_buffer_h, @display_monitor_w, @display_monitor_h, @display_monitor_hz, @game_vram_dedicated_avg_mb, @game_vram_dedicated_median_mb, @game_vram_dedicated_max_mb, @game_vram_shared_max_mb, @game_ram_private_avg_mb, @game_ram_private_median_mb, @game_ram_private_max_mb, @game_ram_ws_max_mb, @game_commit_max_mb, @game_memory_processes, @game_memory_source, @sensor_stats_json, @time_below_30_pct, @time_below_60_pct, @time_below_refresh_pct, @frametime_delta_mean_ms, @vsync_present_pct, @tearing_allowed_pct, @avg_gpu_core_clock_mhz, @avg_gpu_mem_clock_mhz, @avg_gpu_fan_rpm, @max_gpu_mem_temp, @power_limit_pct, @thermal_limit_pct, @app_frames_per_joule, @fg_mix, @runtime_module_sources, @dlss_nr_pct, @input_observed_ms, @input_foreground_ms, @input_controller_ms, @input_km_ms, @input_both_ms, @input_idle_ms, @input_method_switches, @input_source, @input_devices) RETURNING id";
public const string Select = "SELECT id, session_guid, game_id, snapshot_id, started_at, ended_at, duration_s, qpc_epoch, qpc_frequency, capture_tier, capture_mode, capture_notes, ac_exception_family, late_attach, telemetry_source, overlay_build_id, exit_status, drain_ticks, foreground_ticks, records_before_attach, dxgi_presents_before_hook, gap_count, guard_ticks_published, launch_wait_ms, api, present_mode, swap_effect, hdr_flag, hdr_source, sync_interval_mode, upscaler, upscaler_quality, upscaler_sharpness, upscaler_driver_reported, render_w, render_h, output_w, output_h, upscale_ratio, settings_changed_midsession, fg_mode, fg_source, fg_factor, fg_driver_reported, fg_runtime_census, fg_none_withheld_reason, fg_refusal, fg_refusal_detail, fg_factor_scope, fg_steady_share, presented_fps, presented_qualifier, dxgi_unseen_total, dxgi_present_samples, displayed_counted_by, sl_tag_census, sl_interposer_version, runtime_modules, driver_profile, executable_markers, ngx_driver_words, rt_flag, rt_source, pt_flag, pt_source, pt_confidence, rr_flag, rr_source, rt_frame_pct, rays_per_pixel, rt_pso_count, rt_tier, hooks_installed_mask, raster_pso_count, frame_count, app_frame_count, displayed_frame_count, dropped_frames, native_fps, displayed_fps, median_fps, p1_low_fps, p01_low_fps, displayed_p1_low_fps, min_fps, max_fps, frametime_stddev_ms, stutter_count, stutter_time_pct, pso_stutter_pct, reflex_active, latency_avg_us, latency_p95_us, dropped_records, fault_count, data_quality_warnings, writer_status_at_end, early_stop_family, loader_signals, vram_proc_avg_mb, vram_proc_max_mb, vram_budget_exceeded_pct, vram_adapter_max_mb, avg_cpu_temp, max_cpu_temp, avg_gpu_temp, max_gpu_temp, max_gpu_hotspot, avg_gpu_load, avg_cpu_load, avg_ram_mb, avg_gpu_power_w, throttle_pct, display_exclusive_ms, display_borderless_ms, display_windowed_ms, display_covers_ms, display_minimized_ms, display_nowindow_ms, display_changes, display_source, display_window_w, display_window_h, display_buffer_w, display_buffer_h, display_monitor_w, display_monitor_h, display_monitor_hz, game_vram_dedicated_avg_mb, game_vram_dedicated_median_mb, game_vram_dedicated_max_mb, game_vram_shared_max_mb, game_ram_private_avg_mb, game_ram_private_median_mb, game_ram_private_max_mb, game_ram_ws_max_mb, game_commit_max_mb, game_memory_processes, game_memory_source, sensor_stats_json, time_below_30_pct, time_below_60_pct, time_below_refresh_pct, frametime_delta_mean_ms, vsync_present_pct, tearing_allowed_pct, avg_gpu_core_clock_mhz, avg_gpu_mem_clock_mhz, avg_gpu_fan_rpm, max_gpu_mem_temp, power_limit_pct, thermal_limit_pct, app_frames_per_joule, fg_mix, runtime_module_sources, dlss_nr_pct FROM sessions";
public const string Select = "SELECT id, session_guid, game_id, snapshot_id, started_at, ended_at, duration_s, qpc_epoch, qpc_frequency, capture_tier, capture_mode, capture_notes, ac_exception_family, late_attach, telemetry_source, overlay_build_id, exit_status, drain_ticks, foreground_ticks, records_before_attach, dxgi_presents_before_hook, gap_count, guard_ticks_published, launch_wait_ms, api, present_mode, swap_effect, hdr_flag, hdr_source, sync_interval_mode, upscaler, upscaler_quality, upscaler_sharpness, upscaler_driver_reported, render_w, render_h, output_w, output_h, upscale_ratio, settings_changed_midsession, fg_mode, fg_source, fg_factor, fg_driver_reported, fg_runtime_census, fg_none_withheld_reason, fg_refusal, fg_refusal_detail, fg_factor_scope, fg_steady_share, presented_fps, presented_qualifier, dxgi_unseen_total, dxgi_present_samples, displayed_counted_by, sl_tag_census, sl_interposer_version, runtime_modules, driver_profile, executable_markers, ngx_driver_words, rt_flag, rt_source, pt_flag, pt_source, pt_confidence, rr_flag, rr_source, rt_frame_pct, rays_per_pixel, rt_pso_count, rt_tier, hooks_installed_mask, raster_pso_count, frame_count, app_frame_count, displayed_frame_count, dropped_frames, native_fps, displayed_fps, median_fps, p1_low_fps, p01_low_fps, displayed_p1_low_fps, min_fps, max_fps, frametime_stddev_ms, stutter_count, stutter_time_pct, pso_stutter_pct, reflex_active, latency_avg_us, latency_p95_us, dropped_records, fault_count, data_quality_warnings, writer_status_at_end, early_stop_family, loader_signals, vram_proc_avg_mb, vram_proc_max_mb, vram_budget_exceeded_pct, vram_adapter_max_mb, avg_cpu_temp, max_cpu_temp, avg_gpu_temp, max_gpu_temp, max_gpu_hotspot, avg_gpu_load, avg_cpu_load, avg_ram_mb, avg_gpu_power_w, throttle_pct, display_exclusive_ms, display_borderless_ms, display_windowed_ms, display_covers_ms, display_minimized_ms, display_nowindow_ms, display_changes, display_source, display_window_w, display_window_h, display_buffer_w, display_buffer_h, display_monitor_w, display_monitor_h, display_monitor_hz, game_vram_dedicated_avg_mb, game_vram_dedicated_median_mb, game_vram_dedicated_max_mb, game_vram_shared_max_mb, game_ram_private_avg_mb, game_ram_private_median_mb, game_ram_private_max_mb, game_ram_ws_max_mb, game_commit_max_mb, game_memory_processes, game_memory_source, sensor_stats_json, time_below_30_pct, time_below_60_pct, time_below_refresh_pct, frametime_delta_mean_ms, vsync_present_pct, tearing_allowed_pct, avg_gpu_core_clock_mhz, avg_gpu_mem_clock_mhz, avg_gpu_fan_rpm, max_gpu_mem_temp, power_limit_pct, thermal_limit_pct, app_frames_per_joule, fg_mix, runtime_module_sources, dlss_nr_pct, input_observed_ms, input_foreground_ms, input_controller_ms, input_km_ms, input_both_ms, input_idle_ms, input_method_switches, input_source, input_devices FROM sessions";
public static Dictionary<string, object?> Parameters(SessionRow s)
{
@@ -35,10 +35,11 @@ internal static class SessionRowColumns
Parameters5(d, s);
Parameters6(d, s);
Parameters7(d, s);
Parameters8(d, s);
return d;
}
public static SessionRow Read(DbDataReader r) => Read7(Read6(Read5(Read4(Read3(Read2(Read1(Read0(r), r), r), r), r), r), r), r);
public static SessionRow Read(DbDataReader r) => Read8(Read7(Read6(Read5(Read4(Read3(Read2(Read1(Read0(r), r), r), r), r), r), r), r), r);
private static void Parameters0(Dictionary<string, object?> d, SessionRow s)
@@ -425,6 +426,33 @@ internal static class SessionRowColumns
DlssNrPct = D(r, "dlss_nr_pct"),
};
// Schema 0024 (beta.50, D155-D163): what the session was played with - read by the Agent from outside the game.
private static void Parameters8(Dictionary<string, object?> d, SessionRow s)
{
d["input_observed_ms"] = s.InputObservedMs;
d["input_foreground_ms"] = s.InputForegroundMs;
d["input_controller_ms"] = s.InputControllerMs;
d["input_km_ms"] = s.InputKeyboardMouseMs;
d["input_both_ms"] = s.InputBothMs;
d["input_idle_ms"] = s.InputIdleMs;
d["input_method_switches"] = s.InputMethodSwitches;
d["input_source"] = s.InputSource;
d["input_devices"] = s.InputDevicesJson;
}
private static SessionRow Read8(SessionRow row, DbDataReader r) => row with
{
InputObservedMs = L(r, "input_observed_ms"),
InputForegroundMs = L(r, "input_foreground_ms"),
InputControllerMs = L(r, "input_controller_ms"),
InputKeyboardMouseMs = L(r, "input_km_ms"),
InputBothMs = L(r, "input_both_ms"),
InputIdleMs = L(r, "input_idle_ms"),
InputMethodSwitches = I(r, "input_method_switches"),
InputSource = S(r, "input_source"),
InputDevicesJson = S(r, "input_devices"),
};
public static string ExitStatusText(ExitStatus status) => Vocabulary.ExitStatusText(status);
public static ExitStatus ParseExitStatus(string text) => text switch
@@ -33,7 +33,8 @@ public sealed class SqliteGameRepository : IGameRepository
+ "ac_exception_eligible, ac_exception_verdict, ac_exception_sessions, ac_exception_checked_rules_version, "
+ "ac_exception_checked_exe_size_bytes, ac_exception_checked_exe_mtime_ms, ac_exception_checked_block, ac_exception_at, "
+ "ac_exception_family, ac_exception_disclosure_version, ac_exception_exe_size_bytes, ac_exception_exe_mtime_ms, "
+ "ac_exception_lapsed_at, ac_exception_lapsed_reason, engine_version_source, ac_exception_trial_failed_at";
+ "ac_exception_lapsed_at, ac_exception_lapsed_reason, engine_version_source, ac_exception_trial_failed_at, "
+ "controller_support, controller_support_source, controller_support_at";
private const string _selectByPath = $"SELECT {_columns} FROM games WHERE exe_path = @path";
@@ -376,8 +377,11 @@ public sealed class SqliteGameRepository : IGameRepository
ExeFileVersion = SqliteReaders.String(r, 36),
ExeProductVersion = SqliteReaders.String(r, 37),
Libraries = LibraryVersionsJson.Parse(SqliteReaders.String(r, 38)),
AcException = ReadException(r) with { TrialFailedAt = At(SqliteReaders.Int64(r, 54)) }, // schema 0017, the last column
AcException = ReadException(r) with { TrialFailedAt = At(SqliteReaders.Int64(r, 54)) }, // schema 0017
EngineVersionSource = SqliteReaders.String(r, 53), // schema 0015
ControllerSupport = SqliteReaders.String(r, 55), // schema 0024, the last three columns
ControllerSupportSource = SqliteReaders.String(r, 56),
ControllerSupportAt = At(SqliteReaders.Int64(r, 57)),
};
/// <summary>Schema 0014's columns, 39 onwards in <see cref="_columns"/>' order.</summary>
@@ -53,8 +53,14 @@ public sealed class SqliteSessionRepository : ISessionRepository
// The fixed series; an advanced one (schema 0023) is a row of the same table under a name that starts with 'adv.'.
// In LIKE the dot is a literal and the only wildcard is the trailing %, so 'adv.%' is exactly that prefix.
// The input series (schema 0024) are rows of it too, under 'input.': a class's number and a controller's part are
// not sensor values, and they too mark a tick with nothing to say by NaN.
private const string _selectSensors =
"SELECT series, hz, codec, data FROM sensor_blobs WHERE session_id = @sessionId AND series NOT LIKE 'adv.%' ORDER BY series";
"SELECT series, hz, codec, data FROM sensor_blobs WHERE session_id = @sessionId AND series NOT LIKE 'adv.%' AND series NOT LIKE 'input.%' ORDER BY series";
private const string _selectInputSensors =
"SELECT series, hz, codec, data FROM sensor_blobs WHERE session_id = @sessionId AND (series = 't_ms' OR series LIKE 'input.%') "
+ "ORDER BY CASE WHEN series = 't_ms' THEN 0 ELSE 1 END, series";
private const string _selectAdvancedSensors =
"SELECT series, hz, codec, data FROM sensor_blobs WHERE session_id = @sessionId AND (series = 't_ms' OR series LIKE 'adv.%') "
@@ -217,6 +223,11 @@ public sealed class SqliteSessionRepository : ISessionRepository
c, new CommandDefinition(_selectAdvancedSensors, new { sessionId }, cancellationToken: token),
static r => new SensorBlob { Series = r.GetString(0), Hz = r.GetDouble(1), Codec = r.GetString(2), Data = (byte[])r.GetValue(3) }), ct);
public ValueTask<IReadOnlyList<SensorBlob>> FindInputSensorsAsync(long sessionId, CancellationToken ct = default) =>
_db.ReadAsync((c, token) => SqliteReaders.ReadAllAsync(
c, new CommandDefinition(_selectInputSensors, new { sessionId }, cancellationToken: token),
static r => new SensorBlob { Series = r.GetString(0), Hz = r.GetDouble(1), Codec = r.GetString(2), Data = (byte[])r.GetValue(3) }), ct);
public ValueTask<AdvancedSessionRow?> FindAdvancedAsync(long sessionId, CancellationToken ct = default) =>
_db.ReadAsync((c, token) => SqliteReaders.ReadOneAsync(
c, new CommandDefinition(_selectAdvanced, new { sessionId }, cancellationToken: token),
@@ -0,0 +1,286 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Buffers.Binary;
using FrameLedger.Application.Input;
using FrameLedger.Application.Telemetry;
using FrameLedger.Domain.Input;
namespace FrameLedger.Infrastructure.Recording;
/// <summary>
/// The input readings of a batch of telemetry samples, as one chunk of a <c>.partial</c> file (owner decisions
/// D155-D163, <c>06_DATA_MODEL</c> §<c>.partial</c>): so a session that is recovered after the Agent died has what it
/// was played with, as a finished one does.
/// </summary>
/// <remarks>
/// <para>
/// A chunk of its own, after the sensors' and the advanced one, for the reason <see cref="AdvancedSampleCodec"/> has
/// one: the sensor chunk's form is fixed, and a reading is attached to its sample by the QPC the sample already has. A
/// session recorded with the option off never writes one, and its file is byte for byte what it was.
/// </para>
/// <para>
/// <b>Each chunk stands alone</b>: every controller a sample counts is described in that sample - its maker, its two
/// USB ids, its connection - so a file cut anywhere still reads up to its last whole chunk.
/// </para>
/// <para>
/// Layout, little-endian: <c>u32 samples</c>, then per sample <c>i64 qpc</c>, seven <c>i32</c> (span, observed, in
/// front, controller, keyboard and mouse, both, no input), <c>u8 flags</c> (1 a virtual pad), the health (<c>u8</c>
/// answers: 1 raw input registered, 2 XInput there, 4 last input readable; six <c>i64</c> counts; <c>i32 faults</c>),
/// <c>u8 controllers</c> and per controller 23 bytes: <c>i32 id</c>, <c>u8 family</c>, <c>u16 vendor</c>,
/// <c>u16 product</c>, <c>u8 connection</c>, <c>u8 flags</c> (1 virtual, 2 one of XInput's pads, 4 connected, 8 a
/// battery), <c>u8 slot</c>, <c>i32 active ms</c>, <c>u8</c> battery state, scale and level, <c>u16 connects</c>,
/// <c>u16 disconnects</c>.
/// </para>
/// </remarks>
internal static class InputSampleCodec
{
private const int _sampleBytes = 8 + (7 * 4) + 1 + _healthBytes + 1;
private const int _healthBytes = 1 + (6 * 8) + 4;
private const int _deviceBytes = 23;
private const byte _virtualPad = 1;
private const byte _rawRegistered = 1;
private const byte _xinputAvailable = 2;
private const byte _lastInputAvailable = 4;
private const byte _deviceVirtual = 1;
private const byte _deviceXInput = 2;
private const byte _deviceConnected = 4;
private const byte _deviceBattery = 8;
/// <summary>The chunk for the samples of <paramref name="samples"/> that carry an input reading, or null when none does.</summary>
public static byte[]? Write(ReadOnlySpan<TelemetrySample> samples)
{
int carrying = 0;
int bytes = 4;
foreach (ref readonly TelemetrySample sample in samples)
{
if (sample.Input is { } reading)
{
carrying++;
bytes += _sampleBytes + (Devices(reading).Count * _deviceBytes);
}
}
if (carrying == 0)
{
return null;
}
byte[] payload = new byte[bytes];
BinaryPrimitives.WriteUInt32LittleEndian(payload, (uint)carrying);
int at = 4;
foreach (ref readonly TelemetrySample sample in samples)
{
if (sample.Input is { } reading)
{
at += WriteSample(payload.AsSpan(at), sample.QpcTicks, reading);
}
}
return payload;
}
/// <summary>The reading of each sample in a chunk, by the sample's QPC; false when the chunk is not well formed.</summary>
public static bool TryRead(ReadOnlySpan<byte> payload, List<(long Qpc, InputReading Reading)> into)
{
if (payload.Length < 4)
{
return false;
}
uint samples = BinaryPrimitives.ReadUInt32LittleEndian(payload);
int at = 4;
var read = new List<(long, InputReading)>();
for (uint s = 0; s < samples; s++)
{
if (payload.Length - at < _sampleBytes)
{
return false;
}
int devices = payload[at + _sampleBytes - 1];
if (payload.Length - at - _sampleBytes < devices * _deviceBytes)
{
return false;
}
read.Add(ReadSample(payload.Slice(at, _sampleBytes + (devices * _deviceBytes)), devices));
at += _sampleBytes + (devices * _deviceBytes);
}
if (at != payload.Length)
{
return false;
}
into.AddRange(read);
return true;
}
/// <summary>The controllers of a reading that can be written: each with its description, at most 255.</summary>
private static List<(InputDevice Device, InputDeviceReading Reading)> Devices(InputReading reading)
{
var devices = new List<(InputDevice, InputDeviceReading)>(reading.Devices.Count);
foreach (InputDeviceReading d in reading.Devices)
{
if (devices.Count < byte.MaxValue && reading.Table.FirstOrDefault(t => t.Id == d.DeviceId) is { } device)
{
devices.Add((device, d));
}
}
return devices;
}
private static int WriteSample(Span<byte> to, long qpc, InputReading reading)
{
BinaryPrimitives.WriteInt64LittleEndian(to, qpc);
int at = 8;
foreach (int ms in (ReadOnlySpan<int>)[reading.SpanMs, reading.ObservedMs, reading.ForegroundMs, reading.ControllerMs, reading.KeyboardMouseMs, reading.BothMs, reading.IdleMs])
{
BinaryPrimitives.WriteInt32LittleEndian(to[at..], ms);
at += 4;
}
to[at++] = reading.VirtualPad ? _virtualPad : (byte)0;
InputHealth h = reading.Health;
to[at++] = (byte)((h.RawInputRegistered ? _rawRegistered : 0) | (h.XInputAvailable ? _xinputAvailable : 0) | (h.LastInputAvailable ? _lastInputAvailable : 0));
foreach (long count in (ReadOnlySpan<long>)[h.RawReports, h.RawReportsUnread, h.XInputReads, h.XInputSilent, h.Slices, h.ThreadCpuMs])
{
BinaryPrimitives.WriteInt64LittleEndian(to[at..], count);
at += 8;
}
BinaryPrimitives.WriteInt32LittleEndian(to[at..], h.Faults);
at += 4;
List<(InputDevice Device, InputDeviceReading Reading)> devices = Devices(reading);
to[at++] = (byte)devices.Count;
foreach ((InputDevice device, InputDeviceReading d) in devices)
{
WriteDevice(to.Slice(at, _deviceBytes), device, d);
at += _deviceBytes;
}
return at;
}
private static void WriteDevice(Span<byte> to, InputDevice device, InputDeviceReading d)
{
BinaryPrimitives.WriteInt32LittleEndian(to, device.Id);
to[4] = (byte)device.Family;
BinaryPrimitives.WriteUInt16LittleEndian(to[5..], (ushort)Math.Clamp(device.VendorId, 0, ushort.MaxValue));
BinaryPrimitives.WriteUInt16LittleEndian(to[7..], (ushort)Math.Clamp(device.ProductId, 0, ushort.MaxValue));
to[9] = (byte)device.Connection;
to[10] = (byte)((device.IsVirtual ? _deviceVirtual : 0)
| (device.XInputSlot is not null ? _deviceXInput : 0)
| (d.Connected ? _deviceConnected : 0)
| (d.Battery is not null ? _deviceBattery : 0));
to[11] = (byte)Math.Clamp(device.XInputSlot ?? 0, 0, byte.MaxValue);
BinaryPrimitives.WriteInt32LittleEndian(to[12..], d.ActiveMs);
to[16] = (byte)(d.Battery?.State ?? BatteryState.Unknown);
to[17] = (byte)(d.Battery?.Scale ?? BatteryScale.None);
to[18] = (byte)Math.Clamp(d.Battery?.Level ?? 0, 0, byte.MaxValue);
BinaryPrimitives.WriteUInt16LittleEndian(to[19..], (ushort)Math.Clamp(d.Connects, 0, ushort.MaxValue));
BinaryPrimitives.WriteUInt16LittleEndian(to[21..], (ushort)Math.Clamp(d.Disconnects, 0, ushort.MaxValue));
}
private static (long Qpc, InputReading Reading) ReadSample(ReadOnlySpan<byte> from, int deviceCount)
{
long qpc = BinaryPrimitives.ReadInt64LittleEndian(from);
int at = 8;
Span<int> ms = stackalloc int[7];
for (int i = 0; i < ms.Length; i++)
{
ms[i] = BinaryPrimitives.ReadInt32LittleEndian(from[at..]);
at += 4;
}
bool virtualPad = (from[at++] & _virtualPad) != 0;
byte answers = from[at++];
Span<long> counts = stackalloc long[6];
for (int i = 0; i < counts.Length; i++)
{
counts[i] = BinaryPrimitives.ReadInt64LittleEndian(from[at..]);
at += 8;
}
int faults = BinaryPrimitives.ReadInt32LittleEndian(from[at..]);
at += 4 + 1;
var devices = new InputDeviceReading[deviceCount];
var table = new InputDevice[deviceCount];
for (int i = 0; i < deviceCount; i++)
{
(table[i], devices[i]) = ReadDevice(from.Slice(at, _deviceBytes));
at += _deviceBytes;
}
return (qpc, new InputReading
{
SpanMs = ms[0],
ObservedMs = ms[1],
ForegroundMs = ms[2],
ControllerMs = ms[3],
KeyboardMouseMs = ms[4],
BothMs = ms[5],
IdleMs = ms[6],
VirtualPad = virtualPad,
Devices = devices,
Table = table,
Health = new InputHealth
{
RawInputRegistered = (answers & _rawRegistered) != 0,
XInputAvailable = (answers & _xinputAvailable) != 0,
LastInputAvailable = (answers & _lastInputAvailable) != 0,
RawReports = counts[0],
RawReportsUnread = counts[1],
XInputReads = counts[2],
XInputSilent = counts[3],
Slices = counts[4],
ThreadCpuMs = counts[5],
Faults = faults,
},
});
}
private static (InputDevice Device, InputDeviceReading Reading) ReadDevice(ReadOnlySpan<byte> from)
{
byte flags = from[10];
int id = BinaryPrimitives.ReadInt32LittleEndian(from);
var device = new InputDevice
{
Id = id,
// A value this build has no name for was written by a later one: it reads as the word for "do not know".
Family = Known<ControllerFamily>(from[4]),
VendorId = BinaryPrimitives.ReadUInt16LittleEndian(from[5..]),
ProductId = BinaryPrimitives.ReadUInt16LittleEndian(from[7..]),
Connection = Known<ControllerConnection>(from[9]),
IsVirtual = (flags & _deviceVirtual) != 0,
XInputSlot = (flags & _deviceXInput) != 0 ? from[11] : null,
};
BatteryReading? battery = (flags & _deviceBattery) != 0
? new BatteryReading(Known<BatteryState>(from[16]), Known<BatteryScale>(from[17]), from[18])
: null;
return (device, new InputDeviceReading(
id,
Connected: (flags & _deviceConnected) != 0,
ActiveMs: BinaryPrimitives.ReadInt32LittleEndian(from[12..]),
battery,
Connects: BinaryPrimitives.ReadUInt16LittleEndian(from[19..]),
Disconnects: BinaryPrimitives.ReadUInt16LittleEndian(from[21..])));
}
private static T Known<T>(byte value)
where T : struct, Enum
{
T parsed = (T)Enum.ToObject(typeof(T), value);
return Enum.IsDefined(parsed) ? parsed : default;
}
}
@@ -49,4 +49,12 @@ internal enum PartialChunkType
/// last one wins.
/// </summary>
AdvancedContext = 10,
/// <summary>
/// The input readings of the samples of the <see cref="SensorsWide"/> chunk before it (owner decisions D155-D163):
/// <c>InputSampleCodec</c> - per sample its QPC, how its time in front divides between a controller, the keyboard
/// and mouse, both and neither, and each controller's part with what the controller is. Written only when a sample
/// of the batch carries one, so a session recorded with the option off has none.
/// </summary>
SensorsInput = 11,
}
@@ -6,6 +6,7 @@ using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using FrameLedger.Application.Advanced;
using FrameLedger.Application.Input;
using FrameLedger.Application.Recording;
using FrameLedger.Application.Telemetry;
using FrameLedger.Shared;
@@ -166,6 +167,7 @@ public static class PartialSessionFile
PartialChunkType.Touches => Int64s(payload, _touches),
PartialChunkType.SensorsAdvanced => AdvancedSensors(payload),
PartialChunkType.AdvancedContext => AdvancedContext(payload),
PartialChunkType.SensorsInput => InputSensors(payload),
// A type this build does not know, in a chunk whose length and checksum are right (TryReadChunk has
// verified both): a newer build wrote it, and it is passed over (owner decision D106, 2026-11-11).
@@ -302,6 +304,30 @@ public static class PartialSessionFile
return true;
}
/// <summary>The input readings of samples already read, attached as <see cref="AdvancedSensors"/> attaches its own: by QPC, to the last sample that has none yet.</summary>
private bool InputSensors(ReadOnlySpan<byte> payload)
{
var read = new List<(long Qpc, InputReading Reading)>();
if (!InputSampleCodec.TryRead(payload, read))
{
return false;
}
foreach ((long qpc, InputReading reading) in read)
{
for (int i = _sensors.Count - 1; i >= 0; i--)
{
if (_sensors[i].QpcTicks == qpc && _sensors[i].Input is null)
{
_sensors[i] = _sensors[i] with { Input = reading };
break;
}
}
}
return true;
}
private bool AdvancedContext(ReadOnlySpan<byte> payload)
{
_advancedContext = Encoding.UTF8.GetString(payload);
@@ -405,6 +431,12 @@ public static class PartialSessionFile
{
Append(PartialChunkType.SensorsAdvanced, advanced);
}
// And the input readings, the same way and for the same reason (D155-D163).
if (InputSampleCodec.Write(samples) is byte[] input)
{
Append(PartialChunkType.SensorsInput, input);
}
}
public void AppendAdvancedContext(string json)
@@ -143,6 +143,8 @@ public sealed class SeriesDigestTests
public ValueTask<IReadOnlyList<SensorBlob>> FindAdvancedSensorsAsync(long sessionId, CancellationToken ct = default) => inner.FindAdvancedSensorsAsync(sessionId, ct);
public ValueTask<IReadOnlyList<SensorBlob>> FindInputSensorsAsync(long sessionId, CancellationToken ct = default) => inner.FindInputSensorsAsync(sessionId, ct);
public ValueTask<AdvancedSessionRow?> FindAdvancedAsync(long sessionId, CancellationToken ct = default) => inner.FindAdvancedAsync(sessionId, ct);
public ValueTask<long> InsertFinalizedAsync(FinalizedSession session, CancellationToken ct = default) => inner.InsertFinalizedAsync(session, ct);
@@ -29,4 +29,9 @@
<Using Include="Xunit" />
</ItemGroup>
<!-- Windows as the input reader asks it, with every answer written by the test (D157): shared with the other suites that drive the reader. -->
<ItemGroup>
<Compile Include="..\Shared\FakeInputBackend.cs" Link="Shared\FakeInputBackend.cs" />
</ItemGroup>
</Project>
@@ -0,0 +1,456 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using FluentAssertions;
using FrameLedger.Application.Input;
using FrameLedger.Domain.Input;
using FrameLedger.Testing;
namespace FrameLedger.Application.Tests.Input;
/// <summary>
/// The input reader over a Windows whose every answer the test writes (<c>21_INPUT_DEVICES</c> §The reader): what a
/// controller is, when it is in use, what stands in for XInput where XInput says nothing, and what the reader says of
/// itself. <b>No device is behind any of it</b> - what a real controller answers is owner-only item 48.
/// </summary>
public sealed class InputReaderTests
{
private const nint _deviceA = 0x1001;
private const nint _deviceB = 0x1002;
private static readonly RawController _xboxBluetooth = new(ControllerCatalog.Microsoft, 0x0B13, XInputClass: true, ControllerConnection.Bluetooth);
private static readonly RawController _xboxUsb = new(ControllerCatalog.Microsoft, 0x0B12, XInputClass: true, ControllerConnection.Usb);
private static readonly RawController _steamPad = new(ControllerCatalog.Valve, ControllerCatalog.SteamVirtualGamepad, XInputClass: true, ControllerConnection.Usb);
private static readonly RawController _dualSenseUsb = new(ControllerCatalog.Sony, ControllerCatalog.DualSense, XInputClass: false, ControllerConnection.Usb);
private static readonly RawController _dualSenseBluetooth = _dualSenseUsb with { Connection = ControllerConnection.Bluetooth };
private static readonly RawController _dualShock = new(ControllerCatalog.Sony, 0x09CC, XInputClass: false, ControllerConnection.Usb);
private static readonly XInputReading _atRest = new(Packet: 7, 0, 0, 0, 0, 0, 0, 0);
private static readonly XInputReading _buttonDown = _atRest with { Packet = 8, Buttons = 0x1000 };
private static (InputReader Reader, FakeInputBackend Backend) Make()
{
var backend = new FakeInputBackend();
var reader = new InputReader(backend);
reader.Open();
return (reader, backend);
}
/// <summary>A USB report of a DualSense: at rest, or with a button down; the battery byte as given.</summary>
private static byte[] DualSenseUsb(bool pressed = false, byte status = 0x08)
{
byte[] report = new byte[DualSenseReport.UsbLength];
report[0] = 0x01;
report[1] = report[2] = report[3] = report[4] = 128;
report[8] = pressed ? (byte)0x28 : (byte)0x08;
report[53] = status;
return report;
}
[Fact]
public void WithNothingConnectedASliceHasNoControllerAndSaysWhatAnswered()
{
(InputReader reader, FakeInputBackend backend) = Make();
backend.CpuMs = 3;
InputSlice slice = reader.Slice(104);
backend.Opened.Should().BeTrue();
slice.ElapsedMs.Should().Be(104);
slice.ForegroundProcessId.Should().Be(42);
slice.Devices.Should().BeEmpty();
slice.KeyboardMouseActive.Should().BeFalse("the first slice has no time before it to compare with");
slice.VirtualPad.Should().BeFalse();
slice.Health.Should().Be(new InputHealth { RawInputRegistered = true, XInputAvailable = true, LastInputAvailable = true, Slices = 1, ThreadCpuMs = 3 });
}
[Fact]
public void TheOnlyDevicesRawInputIsRegisteredForAreJoysticksAndGamepads() =>
InputReader.RegisteredUsages.Should().Equal([(1, 4), (1, 5)], "usage 2 is a mouse and 6 a keyboard: neither is ever registered for (D158)");
/// <summary>XInput looks for a device each time it is asked about an empty slot, so an empty slot is asked about rarely.</summary>
[Fact]
public void AnEmptySlotIsAskedAboutOnceInTwentySlicesAndAConnectedOneEverySlice()
{
(InputReader reader, FakeInputBackend backend) = Make();
backend.Pads[1] = _atRest;
for (int i = 0; i < InputReader.ProbeEverySlices; i++)
{
reader.Slice(100);
}
backend.PadAsks.Should().Equal(1, InputReader.ProbeEverySlices, 1, 1);
reader.Slice(100);
backend.PadAsks.Should().Equal(2, InputReader.ProbeEverySlices + 1, 2, 2);
}
[Fact]
public void AnXInputPadIsAControllerOfTheXboxFamilyAndIsInUseWhenItsStateSaysSo()
{
(InputReader reader, FakeInputBackend backend) = Make();
backend.Pads[2] = _buttonDown;
InputSliceDevice pad = reader.Slice(100).Devices.Should().ContainSingle().Subject;
pad.Device.Should().Be(new InputDevice { Id = 3, Family = ControllerFamily.Xbox, XInputSlot = 2 });
pad.Device.Model.Should().BeNull("XInput does not say which device a pad is, and nothing else named it");
pad.Active.Should().BeTrue();
pad.Battery.Should().BeNull("XInput was not asked, or did not answer");
backend.Pads[2] = _atRest with { ThumbLx = 5000, ThumbLy = 5000 };
reader.Slice(100).Devices[0].Active.Should().BeFalse("a stick inside its dead zone is drift");
backend.Pads.Remove(2);
reader.Slice(100).Devices.Should().BeEmpty("XInput says it is not connected any more");
}
[Fact]
public void APadsBatteryAndWirelessFlagAreAskedForWhenItConnectsAndThenOnceInFiftySlices()
{
(InputReader reader, FakeInputBackend backend) = Make();
backend.Pads[0] = _atRest;
backend.Details[0] = new XInputDetails(Wireless: true, BatteryType: 3, BatteryLevel: 2);
InputSliceDevice pad = reader.Slice(100).Devices[0];
pad.Battery.Should().Be(new BatteryReading(BatteryState.Discharging, BatteryScale.FourLevels, 2));
pad.Device.Connection.Should().Be(ControllerConnection.Wireless);
backend.DetailAsks.Should().Be(1);
backend.Details[0] = new XInputDetails(Wireless: false, BatteryType: 1, BatteryLevel: 0);
for (int i = 0; i < InputReader.DetailsEverySlices - 1; i++)
{
reader.Slice(100);
}
backend.DetailAsks.Should().Be(1, "not yet");
pad = reader.Slice(100).Devices[0];
backend.DetailAsks.Should().Be(2);
pad.Battery.Should().Be(BatteryReading.Wired);
pad.Device.Connection.Should().Be(ControllerConnection.Usb, "the pad is wired now, and its description follows");
}
[Fact]
public void APadIsNamedWhenTheOnlyXInputClassDeviceThereCanBeIt()
{
(InputReader reader, FakeInputBackend backend) = Make();
backend.Pads[0] = _atRest;
backend.Details[0] = new XInputDetails(Wireless: true, BatteryType: 0, BatteryLevel: 0);
backend.Arrive(_deviceA, _xboxBluetooth);
InputSlice slice = reader.Slice(100);
InputSliceDevice pad = slice.Devices.Should().ContainSingle("the device raw input named IS the pad, not a second controller").Subject;
pad.Device.Should().Be(new InputDevice
{
Id = 1,
Family = ControllerFamily.Xbox,
VendorId = ControllerCatalog.Microsoft,
ProductId = 0x0B13,
Connection = ControllerConnection.Bluetooth,
XInputSlot = 0,
});
pad.Device.Model.Should().Be("Xbox Wireless Controller");
pad.Battery.Should().BeNull("type 0 is XInput's own word for nothing to show - a pad on Bluetooth is reported not to answer");
slice.VirtualPad.Should().BeFalse();
}
[Fact]
public void TwoDifferentXInputClassDevicesLeaveThePadsUnnamed()
{
(InputReader reader, FakeInputBackend backend) = Make();
backend.Pads[0] = _atRest;
backend.Pads[1] = _atRest;
backend.Arrive(_deviceA, _xboxBluetooth);
backend.Arrive(_deviceB, _xboxUsb);
IReadOnlyList<InputSliceDevice> pads = reader.Slice(100).Devices;
pads.Should().HaveCount(2);
pads.Should().OnlyContain(static p => p.Device.VendorId == 0 && p.Device.Family == ControllerFamily.Xbox, "which pad is which device cannot be told, and a wrong name is worse than none");
backend.Leave(_deviceB);
reader.Slice(100).Devices.Should().OnlyContain(static p => p.Device.ProductId == 0x0B13, "one device left: both pads can only be it");
}
[Fact]
public void SteamsVirtualGamepadMarksTheSliceAndNamesThePadsOnlyWhenNothingElseCan()
{
(InputReader reader, FakeInputBackend backend) = Make();
backend.Pads[0] = _atRest;
backend.Arrive(_deviceA, _steamPad);
InputSlice alone = reader.Slice(100);
alone.VirtualPad.Should().BeTrue();
alone.Devices.Should().ContainSingle().Which.Device.Should().BeEquivalentTo(new InputDevice
{
Id = 1,
Family = ControllerFamily.Xbox,
VendorId = ControllerCatalog.Valve,
ProductId = ControllerCatalog.SteamVirtualGamepad,
IsVirtual = true,
XInputSlot = 0,
});
backend.Arrive(_deviceB, _xboxUsb);
InputSlice beside = reader.Slice(100);
beside.VirtualPad.Should().BeTrue();
beside.Devices[0].Device.IsVirtual.Should().BeFalse("with a pad a player holds beside it, the pads take that pad's name");
beside.Devices[0].Device.ProductId.Should().Be(0x0B12);
}
[Fact]
public void ADualSenseIsReadFromItsOwnReports()
{
(InputReader reader, FakeInputBackend backend) = Make();
backend.Arrive(_deviceA, _dualSenseUsb);
backend.Send(_deviceA, DualSenseUsb());
backend.Send(_deviceA, DualSenseUsb(pressed: true, status: 0x07));
backend.Send(_deviceA, DualSenseUsb(status: 0x06));
InputSlice slice = reader.Slice(100);
InputSliceDevice pad = slice.Devices.Should().ContainSingle().Subject;
pad.Device.Should().Be(new InputDevice { Id = 16, Family = ControllerFamily.PlayStation, VendorId = ControllerCatalog.Sony, ProductId = ControllerCatalog.DualSense, Connection = ControllerConnection.Usb });
pad.Active.Should().BeTrue("one of the slice's reports was a pad in use");
pad.Battery.Should().Be(new BatteryReading(BatteryState.Discharging, BatteryScale.Percent, 60), "the last report's");
slice.Health.RawReports.Should().Be(3);
slice.Health.RawReportsUnread.Should().Be(0);
InputSliceDevice later = reader.Slice(100).Devices[0];
later.Active.Should().BeFalse("no report in this slice said so");
later.Battery.Should().Be(pad.Battery, "the level a pad last reported is still its level");
}
[Fact]
public void ADualSenseOnBluetoothIsReadByItsShortReportUntilSomethingElseSwitchesIt()
{
(InputReader reader, FakeInputBackend backend) = Make();
byte[] shortReport = new byte[DualSenseReport.BluetoothLength];
shortReport[0] = 0x01;
shortReport[1] = shortReport[2] = shortReport[3] = shortReport[4] = 128;
shortReport[5] = 0x08;
shortReport[8] = 200;
backend.Arrive(_deviceA, _dualSenseBluetooth);
backend.Send(_deviceA, shortReport);
InputSliceDevice pad = reader.Slice(100).Devices[0];
pad.Active.Should().BeTrue();
pad.Battery.Should().BeNull("the short report has none, and the reader never asks the pad for the long one (D159)");
pad.Device.Connection.Should().Be(ControllerConnection.Bluetooth);
}
[Fact]
public void AReportTheParserCannotReadAndAReportOfADeviceNobodyNamedAreCountedAsNotRead()
{
(InputReader reader, FakeInputBackend backend) = Make();
backend.Arrive(_deviceA, _dualSenseUsb);
backend.Send(_deviceA, 0x7F, 1, 2, 3);
backend.Send(_deviceB, DualSenseUsb(pressed: true));
InputSlice slice = reader.Slice(100);
slice.Health.RawReports.Should().Be(2);
slice.Health.RawReportsUnread.Should().Be(2);
slice.Devices.Should().ContainSingle().Which.Active.Should().BeFalse();
}
/// <summary>A controller whose layout this build does not know is listed, with its connections and drops, and is never "in use": a guess would be a made-up number.</summary>
[Fact]
public void AControllerWhoseReportsThisBuildCannotReadIsListedAndNeverInUse()
{
(InputReader reader, FakeInputBackend backend) = Make();
backend.Arrive(_deviceA, _dualShock);
backend.Send(_deviceA, 1, 255, 255, 255, 255, 255, 255, 255);
InputSlice slice = reader.Slice(100);
InputSliceDevice pad = slice.Devices.Should().ContainSingle().Subject;
pad.Device.Family.Should().Be(ControllerFamily.PlayStation);
pad.Device.Model.Should().Be("DualShock 4");
pad.Active.Should().BeFalse();
pad.Battery.Should().BeNull();
slice.Health.RawReportsUnread.Should().Be(0, "it is not a report the reader set out to read");
}
[Fact]
public void AControllerKeepsItsNumberAcrossAReconnectAndASecondOfTheSameModelHasItsOwn()
{
(InputReader reader, FakeInputBackend backend) = Make();
backend.Arrive(_deviceA, _dualSenseUsb);
backend.Arrive(_deviceA, _dualSenseUsb);
reader.Slice(100).Devices.Select(static d => d.Device.Id).Should().Equal([16], "Windows naming a device twice is one device");
backend.Leave(_deviceA);
reader.Slice(100).Devices.Should().BeEmpty();
backend.Arrive(_deviceB, _dualSenseUsb);
reader.Slice(100).Devices.Select(static d => d.Device.Id).Should().Equal([16], "the same model on the same connection, back under another handle");
backend.Arrive(_deviceA, _dualSenseUsb);
backend.Arrive(0x1003, _dualSenseBluetooth);
reader.Slice(100).Devices.Select(static d => d.Device.Id).Should().Equal(16, 17, 18);
backend.Leave(0x4242);
reader.Slice(100).Devices.Should().HaveCount(3, "a device nobody named leaving changes nothing");
}
[Fact]
public void TheKeyboardOrMouseWasInUseWhenWindowsTimeOfTheLastInputMoved()
{
(InputReader reader, FakeInputBackend backend) = Make();
reader.Slice(100).KeyboardMouseActive.Should().BeFalse();
reader.Slice(100).KeyboardMouseActive.Should().BeFalse("the time did not move");
backend.LastInputTick = 1090;
reader.Slice(100).KeyboardMouseActive.Should().BeTrue();
reader.Slice(100).KeyboardMouseActive.Should().BeFalse();
backend.LastInputTick = 900;
reader.Slice(100).KeyboardMouseActive.Should().BeTrue("Windows does not promise the time only goes forward; a different one is input all the same");
}
[Fact]
public void WhenWindowsDoesNotGiveTheTimeOfTheLastInputNothingIsSaidOfTheKeyboardAndTheHealthSaysSo()
{
(InputReader reader, FakeInputBackend backend) = Make();
backend.LastInputTick = null;
InputSlice slice = reader.Slice(100);
slice.KeyboardMouseActive.Should().BeFalse();
slice.Health.LastInputAvailable.Should().BeFalse();
slice.Health.Sources().Should().Be("rawinput+xinput");
}
[Fact]
public void WithoutXInputsLibraryNoPadIsAskedAbout()
{
(InputReader reader, FakeInputBackend backend) = Make();
backend.XInputAvailable = false;
backend.Pads[0] = _buttonDown;
InputSlice slice = reader.Slice(100);
slice.Devices.Should().BeEmpty();
slice.Health.XInputAvailable.Should().BeFalse();
backend.PadAsks.Should().Equal(0, 0, 0, 0);
}
/// <summary>
/// Microsoft's page for XInputEnable says the system switches a program's controller input by its window's focus.
/// Where that leaves the Agent with a pad that reads at rest for ever, the device's own reports stand in.
/// </summary>
[Fact]
public void WhereXInputSaysNothingWhileTheDevicesReportsChangeThePadCountsAsInUseAfterTenSuchSlices()
{
(InputReader reader, FakeInputBackend backend) = Make();
backend.Pads[1] = _atRest;
backend.Arrive(_deviceA, _xboxUsb);
backend.Send(_deviceA, 0, 1);
reader.Slice(100).Devices[0].Active.Should().BeFalse("the first report has nothing before it to differ from");
for (int i = 1; i < InputReader.SilentBeforeFallback; i++)
{
backend.Send(_deviceA, 0, (byte)(i + 1));
InputSlice early = reader.Slice(100);
early.Devices[0].Active.Should().BeFalse($"silent slice {i}: not enough of them yet");
early.Health.XInputSilent.Should().Be(i);
}
backend.Send(_deviceA, 0, 200);
InputSlice slice = reader.Slice(100);
slice.Health.XInputSilent.Should().Be(InputReader.SilentBeforeFallback);
slice.Devices.Should().ContainSingle().Which.Active.Should().BeTrue("XInput has never once been seen to move, and the device keeps saying something new");
backend.Send(_deviceA, 0, 200);
reader.Slice(100).Devices[0].Active.Should().BeFalse("the same report again is a pad at rest");
}
[Fact]
public void WhereXInputHasBeenSeenToMoveTheDevicesReportsNeverStandInForIt()
{
(InputReader reader, FakeInputBackend backend) = Make();
backend.Pads[0] = _atRest;
backend.Arrive(_deviceA, _xboxUsb);
backend.Send(_deviceA, 0, 1);
reader.Slice(100);
// XInput moves: it answers this program. The slice it moved in and the one after are not silent ones.
backend.Pads[0] = _atRest with { Packet = 9, ThumbLx = 3000 };
backend.Send(_deviceA, 0, 2);
reader.Slice(100).Health.XInputSilent.Should().Be(0);
backend.Send(_deviceA, 0, 3);
reader.Slice(100).Health.XInputSilent.Should().Be(0, "the report may be the one XInput already answered for");
// From here the device's reports change - a stick that drifts - and XInput's packet stays: counted, never used.
for (int i = 0; i < InputReader.SilentBeforeFallback + 5; i++)
{
backend.Send(_deviceA, 0, (byte)(10 + i));
reader.Slice(100).Devices[0].Active.Should().BeFalse("XInput is the one to say, and it says at rest");
}
reader.Slice(100).Health.XInputSilent.Should().Be(InputReader.SilentBeforeFallback + 5);
}
[Fact]
public void ASliceInWhichXInputSaysThePadIsInUseIsNotASilentOne()
{
(InputReader reader, FakeInputBackend backend) = Make();
backend.Pads[0] = _buttonDown;
backend.Arrive(_deviceA, _xboxUsb);
backend.Send(_deviceA, 0, 1);
reader.Slice(100);
backend.Send(_deviceA, 0, 2);
InputSlice slice = reader.Slice(100);
slice.Health.XInputSilent.Should().Be(0, "a button held gives the same packet number and a pad in use");
slice.Devices[0].Active.Should().BeTrue();
}
[Fact]
public void AFaultIsCountedAndANegativeElapsedTimeIsNone()
{
(InputReader reader, FakeInputBackend backend) = Make();
backend.ThrowOnDrain = true;
Action slice = () => reader.Slice(100);
slice.Should().Throw<InvalidOperationException>("the reader does not hide a failure; the hub counts it");
reader.Fault();
backend.ThrowOnDrain = false;
InputSlice after = reader.Slice(-5);
after.ElapsedMs.Should().Be(0);
after.Health.Faults.Should().Be(1);
after.Health.Slices.Should().Be(2);
}
[Fact]
public void ARegistrationWindowsRefusedIsSaidInEverySlice()
{
using var backend = new FakeInputBackend { Registers = false };
var reader = new InputReader(backend);
reader.Open();
InputHealth health = reader.Slice(100).Health;
health.RawInputRegistered.Should().BeFalse();
health.Sources().Should().Be("xinput+lastinput");
}
[Fact]
public void WhatADescriptionSaysOfADevice()
{
_steamPad.IsVirtual.Should().BeTrue();
_xboxUsb.IsVirtual.Should().BeFalse();
_dualSenseBluetooth.IsDualSense.Should().BeTrue();
_dualShock.IsDualSense.Should().BeFalse();
(_dualSenseUsb with { XInputClass = true }).IsDualSense.Should().BeFalse("presented through XInput, it is one of XInput's pads");
}
}
@@ -130,7 +130,12 @@ internal sealed class FakeSessionRepository : ISessionRepository
public ValueTask<IReadOnlyList<SensorBlob>> FindSensorsAsync(long sessionId, CancellationToken ct = default) =>
ValueTask.FromResult<IReadOnlyList<SensorBlob>>(sessionId >= 1 && sessionId <= Stored.Count
? [.. Stored[(int)sessionId - 1].Sensors.Where(static s => !s.Series.StartsWith("adv.", StringComparison.Ordinal))]
? [.. Stored[(int)sessionId - 1].Sensors.Where(static s => !s.Series.StartsWith("adv.", StringComparison.Ordinal) && !s.Series.StartsWith("input.", StringComparison.Ordinal))]
: []);
public ValueTask<IReadOnlyList<SensorBlob>> FindInputSensorsAsync(long sessionId, CancellationToken ct = default) =>
ValueTask.FromResult<IReadOnlyList<SensorBlob>>(sessionId >= 1 && sessionId <= Stored.Count
? [.. Stored[(int)sessionId - 1].Sensors.Where(static s => string.Equals(s.Series, "t_ms", StringComparison.Ordinal) || s.Series.StartsWith("input.", StringComparison.Ordinal))]
: []);
public ValueTask<IReadOnlyList<SensorBlob>> FindAdvancedSensorsAsync(long sessionId, CancellationToken ct = default) =>
@@ -3,8 +3,10 @@
using System.Reflection;
using FluentAssertions;
using FrameLedger.Application.Input;
using FrameLedger.Application.Persistence;
using FrameLedger.Application.Recording;
using FrameLedger.Domain.Input;
using FrameLedger.Domain.Sessions;
using FrameLedger.Shared;
@@ -218,6 +220,71 @@ public sealed class SessionFinalizerTests
SensorSeriesStats.Parse("{not json").Should().BeEmpty("text this build cannot read is no statistics, never a throw into the UI");
}
/// <summary>
/// What a session was played with (D155-D163) is read by the Agent from outside the game, so a session that was not
/// hooked has it as a hooked one does: the totals on the row, the series beside the sensors'.
/// </summary>
[Theory]
[InlineData(false)]
[InlineData(true)]
public void BothTiersStoreWhatTheSessionWasPlayedWith(bool hooked)
{
(SessionFinalizer finalizer, _) = Make();
List<Application.Telemetry.TelemetrySample> sensors = SessionFixtures.Sensors(3);
var pad = new InputDevice { Id = 1, Family = ControllerFamily.Xbox, XInputSlot = 0 };
sensors[0] = sensors[0] with { Input = Played(controller: 1000, pad) };
sensors[2] = sensors[2] with { Input = Played(controller: 0, pad) with { KeyboardMouseMs = 700, IdleMs = 300 } };
FinalizedSession built = finalizer.Build(hooked
? new FinalizeInput { Skeleton = SessionFixtures.Skeleton(), Hooked = SessionFixtures.Hooked(SessionFixtures.Stream(600, FlMeasured.None)), Sensors = sensors }
: new FinalizeInput { Skeleton = SessionFixtures.Skeleton(tier: CaptureTier.NotHooked), Sensors = sensors });
built.Row.Tier.Should().Be(hooked ? CaptureTier.Hooked : CaptureTier.NotHooked);
built.Row.InputObservedMs.Should().Be(2000);
built.Row.InputForegroundMs.Should().Be(2000);
built.Row.InputControllerMs.Should().Be(1000);
built.Row.InputKeyboardMouseMs.Should().Be(700);
built.Row.InputBothMs.Should().Be(0);
built.Row.InputIdleMs.Should().Be(300);
built.Row.InputMethodSwitches.Should().Be(1);
built.Row.InputSource.Should().Be("rawinput+lastinput");
built.Row.InputSharePercent(built.Row.InputControllerMs).Should().Be(50);
InputDevicesRecord.Parse(built.Row.InputDevicesJson)!.Devices.Should().ContainSingle().Which.XInputSlot.Should().Be(0);
built.Sensors.Select(static s => s.Series).Should().Contain(["t_ms", "input.class", "input.dev.1.active"]);
float[] timeline = RawSeriesCodec.Floats(built.Sensors.Single(static s => string.Equals(s.Series, "input.class", StringComparison.Ordinal)).Data);
timeline[0].Should().Be((float)InputClass.Controller);
float.IsNaN(timeline[1]).Should().BeTrue("the tick the reader took no slice in");
timeline[2].Should().Be((float)InputClass.KeyboardMouse);
}
[Fact]
public void ASessionWithNoInputReadingKeepsEveryInputColumnNullAndStoresNoInputSeries()
{
(SessionFinalizer finalizer, _) = Make();
FinalizedSession built = finalizer.Build(new FinalizeInput { Skeleton = SessionFixtures.Skeleton(tier: CaptureTier.NotHooked), Sensors = SessionFixtures.Sensors(3) });
built.Row.InputObservedMs.Should().BeNull("the option was off, or the terms that describe the reading were not accepted yet: N/A, never a zero");
built.Row.InputForegroundMs.Should().BeNull();
built.Row.InputControllerMs.Should().BeNull();
built.Row.InputMethodSwitches.Should().BeNull();
built.Row.InputSource.Should().BeNull();
built.Row.InputDevicesJson.Should().BeNull();
built.Sensors.Should().NotContain(static s => s.Series.StartsWith("input.", StringComparison.Ordinal));
}
private static InputReading Played(int controller, InputDevice pad) => new()
{
SpanMs = 1000,
ObservedMs = 1000,
ForegroundMs = 1000,
ControllerMs = controller,
IdleMs = 1000 - controller,
Devices = [new InputDeviceReading(pad.Id, Connected: true, ActiveMs: controller, Battery: null, Connects: 0, Disconnects: 0)],
Table = [pad],
Health = new InputHealth { RawInputRegistered = true, LastInputAvailable = true },
};
[Fact]
public async Task TooShortIsDiscardedAndNothingIsWritten()
{
@@ -0,0 +1,41 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using FluentAssertions;
using FrameLedger.Domain.Input;
namespace FrameLedger.Domain.Tests.Input;
/// <summary>
/// The two facts taken from the name Windows gives a controller's device interface (<c>21_INPUT_DEVICES</c> §What is
/// never read). The names here have the shape Windows writes; their instance parts are made up.
/// </summary>
public sealed class RawDeviceNameTests
{
private const string _xboxUsb = @"\\?\HID#VID_045E&PID_0B12&IG_00#8&1a2b3c4d&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}";
private const string _xboxBluetooth = @"\\?\HID#{00001812-0000-1000-8000-00805f9b34fb}&Dev&VID_045e&PID_0b13&REV_0520&IG_00#9&2b3c4d5e&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}";
private const string _dualSenseUsb = @"\\?\HID#VID_054C&PID_0CE6&MI_03#8&3c4d5e6f&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}";
private const string _dualSenseBluetooth = @"\\?\HID#{00001124-0000-1000-8000-00805F9B34FB}_VID&0002054c_PID&0ce6#8&4d5e6f70&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}";
[Theory]
[InlineData(_xboxUsb, true)]
[InlineData(_xboxBluetooth, true)]
[InlineData(@"\\?\hid#vid_28de&pid_11ff&ig_00#7&5e6f7081&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}", true)]
[InlineData(_dualSenseUsb, false)]
[InlineData(_dualSenseBluetooth, false)]
[InlineData("", false)]
[InlineData(null, false)]
public void ADeviceWindowsPresentsThroughXInputCarriesMicrosoftsMarkInItsName(string? name, bool xinput) =>
RawDeviceName.IsXInputClass(name).Should().Be(xinput);
[Theory]
[InlineData(_xboxUsb, ControllerConnection.Usb)]
[InlineData(_dualSenseUsb, ControllerConnection.Usb)]
[InlineData(_dualSenseBluetooth, ControllerConnection.Bluetooth)] // classic Bluetooth's HID service
[InlineData(_xboxBluetooth, ControllerConnection.Bluetooth)] // low energy's, which also carries VID_
[InlineData(@"\\?\HID#SOMETHING_ELSE#1&2&3#{4d1e55b2-f16f-11cf-88cb-001111000030}", ControllerConnection.Unknown)]
[InlineData("", ControllerConnection.Unknown)]
[InlineData(null, ControllerConnection.Unknown)]
public void TheConnectionIsBluetoothByTheServicesIdentifierAndUsbByAUsbVendorId(string? name, ControllerConnection connection) =>
RawDeviceName.ConnectionOf(name).Should().Be(connection);
}
@@ -28,6 +28,11 @@
<Using Include="Xunit" />
</ItemGroup>
<!-- Windows as the input reader asks it, with every answer written by the test (D157): shared with the other suites that drive the reader. -->
<ItemGroup>
<Compile Include="..\Shared\FakeInputBackend.cs" Link="Shared\FakeInputBackend.cs" />
</ItemGroup>
<!--
GuardMirrorTests and RulesPathAgreementTests P/Invoke into the real
FrameLedger.Guard.dll, which NativeAntiCheatGuard loads by absolute path from
@@ -0,0 +1,276 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Diagnostics;
using FluentAssertions;
using FrameLedger.Application.Capture;
using FrameLedger.Application.Input;
using FrameLedger.Application.Telemetry;
using FrameLedger.Infrastructure.Input;
using FrameLedger.Testing;
namespace FrameLedger.Infrastructure.Tests.Input;
/// <summary>
/// The Agent's one input reader and the sessions' views of it (<c>21_INPUT_DEVICES</c> §The reader): it runs only
/// while a view is open, each view counts the slices in which its own game was in front, a pause is not observed, and
/// a reader that keeps failing ends its run with one line and takes no session with it. The Windows behind it is the
/// tests' own.
/// </summary>
public sealed class InputDeviceHubTests
{
private static readonly TimeSpan _slice = TimeSpan.FromMilliseconds(5);
private static readonly TimeSpan _patience = TimeSpan.FromSeconds(10);
private static GameProcess Pids(params int[] pids) => GameProcess.Unpinned([.. pids.Select(static p => new GameProcessId(p, DateTimeOffset.UnixEpoch))]);
/// <summary>Reads the view until <paramref name="enough"/> says so, adding up what it returned.</summary>
private static (int Span, int Observed, int Foreground, int Controller, long Slices) ReadUntil(IInputActivitySource view, Func<(int Span, int Observed, int Foreground, int Controller, long Slices), bool> enough)
{
(int Span, int Observed, int Foreground, int Controller, long Slices) sum = default;
var clock = Stopwatch.StartNew();
while (!enough(sum) && clock.Elapsed < _patience)
{
if (view.TryRead(out InputReading? reading))
{
sum = (sum.Span + reading.SpanMs, sum.Observed + reading.ObservedMs, sum.Foreground + reading.ForegroundMs, sum.Controller + reading.ControllerMs, reading.Health.Slices);
}
else
{
Thread.Sleep(2);
}
}
return sum;
}
private static int Count(List<string> notes)
{
lock (notes)
{
return notes.Count;
}
}
private static void WaitUntil(Func<bool> condition)
{
var clock = Stopwatch.StartNew();
while (!condition() && clock.Elapsed < _patience)
{
Thread.Sleep(2);
}
condition().Should().BeTrue("it should have happened within the patience of the test");
}
[Fact]
public void WithNoViewTheHubHasNoThreadAndMakesNoBackend()
{
int made = 0;
using var hub = new InputDeviceHub(
() =>
{
made++;
return new FakeInputBackend();
},
interval: _slice);
hub.IsRunning.Should().BeFalse("with no session nothing is read: no thread, no window, no registration");
made.Should().Be(0);
}
[Fact]
public void AViewCountsTheSlicesItsOwnGameWasInFrontOfAndAnotherViewItsOwn()
{
using var backend = new FakeInputBackend { Foreground = 500 };
backend.Pads[0] = new XInputReading(1, Buttons: 0x1000, 0, 0, 0, 0, 0, 0);
backend.Details[0] = new XInputDetails(Wireless: false, BatteryType: 1, BatteryLevel: 0);
using var hub = new InputDeviceHub(() => backend, interval: _slice);
using IInputActivitySource mine = hub.Open();
using IInputActivitySource other = hub.Open();
mine.Follow(Pids(400, 500));
other.Follow(Pids(600));
(int span, int observed, int foreground, int controller, long slices) = ReadUntil(mine, static s => s.Controller > 0 && s.Slices >= 3);
(int otherSpan, int otherObserved, int otherForeground, int otherController, _) = ReadUntil(other, static s => s.Slices >= 3);
hub.IsRunning.Should().BeTrue();
backend.Opened.Should().BeTrue();
slices.Should().BeGreaterThanOrEqualTo(3);
foreground.Should().BeGreaterThan(0).And.BeLessThanOrEqualTo(observed);
controller.Should().BeGreaterThan(0).And.BeLessThanOrEqualTo(foreground);
observed.Should().BeLessThanOrEqualTo(span);
otherObserved.Should().BeGreaterThan(0, "the other session is observed too");
otherSpan.Should().BeGreaterThan(0);
otherForeground.Should().Be(0, "its game was never in front");
otherController.Should().Be(0, "a controller in use while another program is in front is not that session's");
}
[Fact]
public void APinnedProcessIsTheSessionsGame()
{
using var backend = new FakeInputBackend { Foreground = 77 };
using var hub = new InputDeviceHub(() => backend, interval: _slice);
using IInputActivitySource view = hub.Open();
view.Follow(GameProcess.Pinned(77, NSubstitute.Substitute.For<ITargetLiveness>()));
ReadUntil(view, static s => s.Foreground > 0).Foreground.Should().BeGreaterThan(0);
}
[Fact]
public void WithNoWindowInFrontNoSessionIsInFront()
{
using var backend = new FakeInputBackend { Foreground = 0 };
using var hub = new InputDeviceHub(() => backend, interval: _slice);
using IInputActivitySource view = hub.Open();
view.Follow(Pids(0));
(_, int observed, int foreground, _, _) = ReadUntil(view, static s => s.Slices >= 3);
observed.Should().BeGreaterThan(0);
foreground.Should().Be(0, "pid 0 is Windows' word for no window in front, never a game");
}
[Fact]
public void WhileRecordingIsPausedASliceIsNotObserved()
{
bool paused = true;
using var backend = new FakeInputBackend { Foreground = 500 };
using var hub = new InputDeviceHub(() => backend, () => Volatile.Read(ref paused), _slice);
using IInputActivitySource view = hub.Open();
view.Follow(Pids(500));
(int span, int observed, _, _, _) = ReadUntil(view, static s => s.Slices >= 3);
observed.Should().Be(0, "a pause is a gap");
span.Should().BeGreaterThan(0, "the clock does not stop for a pause: a battery level is timed by it");
Volatile.Write(ref paused, false);
ReadUntil(view, static s => s.Observed > 0).Observed.Should().BeGreaterThan(0);
}
[Fact]
public void TheRunEndsWithItsLastViewAndANewViewStartsANewOne()
{
var made = new List<FakeInputBackend>();
var notes = new List<string>();
using var hub = new InputDeviceHub(
() =>
{
var backend = new FakeInputBackend();
lock (made)
{
made.Add(backend);
}
return backend;
},
interval: _slice,
note: line =>
{
lock (notes)
{
notes.Add(line);
}
});
IInputActivitySource first = hub.Open();
ReadUntil(first, static s => s.Slices >= 2);
first.Dispose();
// The run's last act is its line in the log: by then the backend is disposed and the thread's slot is free.
WaitUntil(() => Count(notes) == 1);
hub.IsRunning.Should().BeFalse();
lock (made)
{
made.Should().ContainSingle().Which.Disposed.Should().BeTrue("the window and the registration go with the last session");
}
lock (notes)
{
notes.Should().ContainSingle().Which.Should().StartWith("input: run ended - slices ").And.Contain("raw input registered").And.Contain("xinput there").And.Contain("last input read");
}
using IInputActivitySource second = hub.Open();
ReadUntil(second, static s => s.Slices >= 1).Slices.Should().BeGreaterThanOrEqualTo(1);
lock (made)
{
made.Should().HaveCount(2, "a new session opens a new run, with a backend of its own");
}
}
[Fact]
public void AReaderThatKeepsFailingEndsItsRunWithOneLineAndTheViewSimplyHasNothingMore()
{
var notes = new List<string>();
using var backend = new FakeInputBackend { ThrowOnDrain = true };
using var hub = new InputDeviceHub(() => backend, interval: _slice, note: line =>
{
lock (notes)
{
notes.Add(line);
}
});
using IInputActivitySource view = hub.Open();
WaitUntil(() => Count(notes) == 2);
hub.IsRunning.Should().BeFalse();
view.TryRead(out _).Should().BeFalse("no slice was ever made");
lock (notes)
{
notes.Should().HaveCount(2);
notes[0].Should().StartWith($"input: the reader's slice threw {InputDeviceHub.MaxFaults} times running and the run ends (InvalidOperationException");
notes[1].Should().StartWith("input: run ended");
}
}
[Fact]
public void ABackendThatCannotBeMadeEndsTheRunWithOneLine()
{
var notes = new List<string>();
using var hub = new InputDeviceHub(() => throw new InvalidOperationException("no window station"), interval: _slice, note: line =>
{
lock (notes)
{
notes.Add(line);
}
});
using IInputActivitySource view = hub.Open();
WaitUntil(() => Count(notes) == 2);
hub.IsRunning.Should().BeFalse();
lock (notes)
{
notes[0].Should().Be("input: the reader did not start (InvalidOperationException: no window station)");
}
}
[Fact]
public void ADisposedHubOpensNoViewAndDisposingTwiceIsNothing()
{
using var backend = new FakeInputBackend();
var hub = new InputDeviceHub(() => backend, interval: _slice);
IInputActivitySource view = hub.Open();
ReadUntil(view, static s => s.Slices >= 1);
hub.Dispose();
hub.Dispose();
hub.IsRunning.Should().BeFalse();
Action open = () => hub.Open();
open.Should().Throw<ObjectDisposedException>();
view.Dispose();
}
[Fact]
public void ASliceMustBeLongerThanNothing()
{
Action zero = () => _ = new InputDeviceHub(static () => new FakeInputBackend(), interval: TimeSpan.Zero);
Action none = () => _ = new InputDeviceHub(null!);
zero.Should().Throw<ArgumentOutOfRangeException>();
none.Should().Throw<ArgumentNullException>();
}
}
@@ -0,0 +1,178 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Buffers.Binary;
using FluentAssertions;
using FrameLedger.Application.Input;
using FrameLedger.Infrastructure.Input;
namespace FrameLedger.Infrastructure.Tests.Input;
/// <summary>
/// The bytes <c>GetRawInputBuffer</c> fills, walked (<c>21_INPUT_DEVICES</c> §The reader): each report of each HID block
/// reaches the sink with its device, and a block that claims more than the buffer holds ends the walk without a byte
/// read past it. The buffers are built here to the documented layout - <b>none was filled by Windows</b>.
/// </summary>
public sealed class RawInputBufferTests
{
/// <summary>One block: the header, then for a HID device the size and count of its reports and the reports themselves.</summary>
private static byte[] Block(nint device, int reportBytes, params byte[][] reports)
{
byte[] block = new byte[RawInputBuffer.HeaderBytes + 8 + reports.Sum(static r => r.Length)];
BinaryPrimitives.WriteUInt32LittleEndian(block, RawInputBuffer.TypeHid);
BinaryPrimitives.WriteUInt32LittleEndian(block.AsSpan(4), (uint)block.Length);
BinaryPrimitives.WriteInt64LittleEndian(block.AsSpan(8), device);
BinaryPrimitives.WriteUInt32LittleEndian(block.AsSpan(RawInputBuffer.HeaderBytes), (uint)reportBytes);
BinaryPrimitives.WriteUInt32LittleEndian(block.AsSpan(RawInputBuffer.HeaderBytes + 4), (uint)reports.Length);
int at = RawInputBuffer.HeaderBytes + 8;
foreach (byte[] report in reports)
{
report.CopyTo(block, at);
at += report.Length;
}
return block;
}
/// <summary>Blocks one after another, each starting on a multiple of eight as Windows lays them out.</summary>
private static byte[] Buffer(params byte[][] blocks)
{
var bytes = new List<byte>();
foreach (byte[] block in blocks)
{
bytes.AddRange(block);
while (bytes.Count % 8 != 0)
{
bytes.Add(0xEE);
}
}
return [.. bytes];
}
[Fact]
public void EachReportOfEachBlockReachesTheSinkWithItsDevice()
{
var sink = new Recorder();
byte[] buffer = Buffer(
Block(0x10, 3, [1, 2, 3], [4, 5, 6]),
Block(0x20, 5, [9, 9, 9, 9, 9]));
RawInputBuffer.Walk(buffer, 2, sink).Should().Be(2);
sink.Reports.Should().HaveCount(3);
sink.Reports[0].Should().Be((0x10, "010203"));
sink.Reports[1].Should().Be((0x10, "040506"));
sink.Reports[2].Should().Be((0x20, "0909090909"));
}
[Fact]
public void OnlyAsManyBlocksAsWindowsSaidItWroteAreWalked()
{
var sink = new Recorder();
byte[] buffer = Buffer(Block(0x10, 1, [1]), Block(0x20, 1, [2]));
RawInputBuffer.Walk(buffer, 1, sink).Should().Be(1);
sink.Reports.Should().ContainSingle().Which.Device.Should().Be(0x10);
RawInputBuffer.Walk(buffer, 0, sink).Should().Be(0);
RawInputBuffer.Walk([], 3, sink).Should().Be(0);
}
[Fact]
public void ABlockThatIsNotAHidDevicesIsPassedOver()
{
var sink = new Recorder();
byte[] keyboard = new byte[RawInputBuffer.HeaderBytes + 16];
BinaryPrimitives.WriteUInt32LittleEndian(keyboard, 1);
BinaryPrimitives.WriteUInt32LittleEndian(keyboard.AsSpan(4), (uint)keyboard.Length);
RawInputBuffer.Walk(Buffer(keyboard, Block(0x20, 1, [7])), 2, sink).Should().Be(2);
sink.Reports.Should().ContainSingle("the reader registers for controllers only; a block of another kind is never read").Which.Device.Should().Be(0x20);
}
[Fact]
public void TheLastBlockMayEndTheBufferWithoutItsPadding()
{
var sink = new Recorder();
byte[] block = Block(0x10, 3, [1, 2, 3]);
block.Length.Should().Be(35, "not a multiple of eight: the walk must not want the five bytes after it");
RawInputBuffer.Walk(block, 1, sink).Should().Be(1);
sink.Reports.Should().ContainSingle();
}
/// <summary>The bytes come from a device by way of Windows: no length in them is trusted.</summary>
[Fact]
public void ABlockThatClaimsMoreThanTheBufferHoldsEndsTheWalkAndWhatCameBeforeStands()
{
var sink = new Recorder();
byte[] good = Block(0x10, 2, [1, 2]);
byte[] lying = Block(0x20, 2, [3, 4]);
BinaryPrimitives.WriteUInt32LittleEndian(lying.AsSpan(4), 4096);
RawInputBuffer.Walk(Buffer(good, lying), 2, sink).Should().Be(1);
sink.Reports.Should().ContainSingle().Which.Device.Should().Be(0x10);
}
[Fact]
public void ABlockSmallerThanItsOwnHeaderEndsTheWalk()
{
var sink = new Recorder();
byte[] tiny = Block(0x10, 1, [1]);
BinaryPrimitives.WriteUInt32LittleEndian(tiny.AsSpan(4), 8);
RawInputBuffer.Walk(Buffer(tiny, Block(0x20, 1, [2])), 2, sink).Should().Be(0);
sink.Reports.Should().BeEmpty();
RawInputBuffer.Walk(new byte[10], 1, sink).Should().Be(0, "not even a header");
}
[Theory]
[InlineData(0u, 4u)] // reports of no size
[InlineData(4u, 0u)] // no reports
[InlineData(4u, 3u)] // three reports of four bytes where eight bytes follow
[InlineData(0xFFFFFFFFu, 0xFFFFFFFFu)] // a product that would not fit in 32 bits
public void ReportsThatDoNotFitTheirBlockAreNotHandedOver(uint reportBytes, uint count)
{
var sink = new Recorder();
byte[] block = Block(0x10, 4, [1, 2, 3, 4], [5, 6, 7, 8]);
BinaryPrimitives.WriteUInt32LittleEndian(block.AsSpan(RawInputBuffer.HeaderBytes), reportBytes);
BinaryPrimitives.WriteUInt32LittleEndian(block.AsSpan(RawInputBuffer.HeaderBytes + 4), count);
RawInputBuffer.Walk(Buffer(block, Block(0x20, 1, [9])), 2, sink).Should().Be(2, "the block is walked over by its own size, which is sound");
sink.Reports.Should().ContainSingle("only the block after it").Which.Device.Should().Be(0x20);
}
[Fact]
public void AHidBlockWithNoRoomForItsCountsHasNoReports()
{
var sink = new Recorder();
byte[] header = new byte[RawInputBuffer.HeaderBytes + 4];
BinaryPrimitives.WriteUInt32LittleEndian(header, RawInputBuffer.TypeHid);
BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(4), (uint)header.Length);
RawInputBuffer.Walk(header, 1, sink).Should().Be(1);
sink.Reports.Should().BeEmpty();
}
private sealed class Recorder : IInputBackendSink
{
public List<(nint Device, string Hex)> Reports { get; } = [];
public void Arrived(nint device, RawController controller)
{
}
public void Removed(nint device)
{
}
public void Report(nint device, ReadOnlySpan<byte> report) => Reports.Add((device, Convert.ToHexString(report)));
}
}
@@ -0,0 +1,153 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using System.Diagnostics;
using FluentAssertions;
using FrameLedger.Application.Input;
using FrameLedger.Infrastructure.Input;
namespace FrameLedger.Infrastructure.Tests.Input;
/// <summary>
/// The reader's Windows side against the real Windows of whatever machine runs this - a developer's PC with or without
/// a controller, CI's runner with none. It asserts the CONTRACT, never the hardware: it opens, answers every question
/// without throwing, says honestly what it could register, and leaves nothing behind. <b>What it reads from a real
/// controller is not established by this</b>; that is owner-only item 48.
/// </summary>
[Trait("Category", "Integration")]
public sealed class Win32InputBackendTests
{
[Fact]
public void ItOpensAnswersEveryQuestionAndClosesWithOrWithoutAController()
{
using var backend = new Win32InputBackend();
var sink = new Recorder();
// Refused is a valid answer - a session with no interactive desktop gives none - and is said, not hidden.
bool registered = backend.Open();
backend.Drain(sink);
backend.Drain(sink);
for (int slot = 0; slot < InputReader.Slots; slot++)
{
if (backend.TryReadPad(slot, out XInputReading pad))
{
pad.LeftTrigger.Should().BeInRange(0, 255);
backend.TryReadPadDetails(slot, out XInputDetails details).Should().BeTrue("a pad XInput has a state for has capabilities");
details.BatteryType.Should().BeOneOf(0, 1, 2, 3, 0xFF);
}
}
if (backend.TryReadLastInputTick(out uint tick))
{
// The same clock as Environment.TickCount, and never ahead of it by more than a moment.
unchecked((int)((uint)Environment.TickCount - tick)).Should().BeGreaterThan(-60_000);
}
uint front = backend.ForegroundProcessId();
if (front != 0)
{
Action named = () => Process.GetProcessById((int)front).Dispose();
named.Should().NotThrow("what is in front is a live process");
}
backend.ThreadCpuMs().Should().BeGreaterThanOrEqualTo(0);
sink.Reports.Should().BeGreaterThanOrEqualTo(0);
if (!registered)
{
sink.Arrived.Should().Be(0, "nothing is listed for a registration Windows refused");
}
}
[Fact]
public void AReaderOverItTakesSlicesAndSaysWhatAnswered()
{
using var backend = new Win32InputBackend();
var reader = new InputReader(backend);
reader.Open();
InputSlice first = reader.Slice(100);
InputSlice second = reader.Slice(100);
second.Health.Slices.Should().Be(2);
second.Health.Faults.Should().Be(0);
second.Health.ThreadCpuMs.Should().BeGreaterThanOrEqualTo(first.Health.ThreadCpuMs);
second.Health.XInputAvailable.Should().Be(backend.XInputAvailable);
// All(), not OnlyContain: with no controller connected the list is empty, and that is a valid answer.
second.Devices.All(static d => d.Device.Id > 0).Should().BeTrue("every controller it lists has a number");
}
[Fact]
public void TheHubRunsOverItAndEndsCleanly()
{
var notes = new List<string>();
using var hub = new InputDeviceHub(static () => new Win32InputBackend(), interval: TimeSpan.FromMilliseconds(10), note: line =>
{
lock (notes)
{
notes.Add(line);
}
});
IInputActivitySource view = hub.Open();
var clock = Stopwatch.StartNew();
InputReading? reading = null;
while (reading is null && clock.Elapsed < TimeSpan.FromSeconds(10))
{
if (!view.TryRead(out reading))
{
Thread.Sleep(5);
}
}
view.Dispose();
reading.Should().NotBeNull("the reader's thread made a slice");
reading.SpanMs.Should().BeGreaterThanOrEqualTo(0);
reading.ForegroundMs.Should().Be(0, "this view followed no process");
lock (notes)
{
notes.Should().NotContain(static n => n.Contains("did not start", StringComparison.Ordinal) || n.Contains("threw", StringComparison.Ordinal));
}
}
[Fact]
public void ItCanBeOpenedAgainAfterItWasClosedAndClosedTwice()
{
var first = new Win32InputBackend();
bool registered = first.Open();
first.Dispose();
first.Dispose();
using var second = new Win32InputBackend();
second.Open().Should().Be(registered, "the window's class and the registration were given back");
Action reopen = () => first.Open();
reopen.Should().Throw<ObjectDisposedException>();
}
[Fact]
public void BeforeItIsOpenedItHandsOverNothing()
{
using var backend = new Win32InputBackend();
var sink = new Recorder();
backend.Drain(sink);
sink.Arrived.Should().Be(0);
sink.Reports.Should().Be(0);
}
private sealed class Recorder : IInputBackendSink
{
public int Arrived { get; private set; }
public int Reports { get; private set; }
void IInputBackendSink.Arrived(nint device, RawController controller) => Arrived++;
public void Removed(nint device)
{
}
public void Report(nint device, ReadOnlySpan<byte> report) => Reports++;
}
}
@@ -962,6 +962,79 @@ public sealed class LedgerDatabaseTests
}
}
/// <summary>
/// Schema 0024 (2026-11-14, owner decisions D155-D163): what a session was played with, nine columns of
/// <c>sessions</c>, and what a game's store lists of controller support, three of <c>games</c> - ADD COLUMN only. A
/// session and a game written before have none of them: N/A, never a zero.
/// </summary>
[Fact]
public async Task ScriptTwentyFourAddsTheInputColumnsAndAnEarlierSessionAndGameHaveNone()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
MigrationRunner.LatestVersion.Should().BeGreaterThanOrEqualTo(24);
long gameId = (await new SqliteGameRepository(f.Db).EnsureAsync(
new() { ExePath = @"C:\Games\A\a.exe", SizeBytes = 1, MtimeUnixMs = 2 }, "A", Ct).ConfigureAwait(true)).Id;
long snapshotId = await new SqliteHardwareSnapshotRepository(f.Db).EnsureAsync(new HardwareSnapshot { GpuName = "g" }, DateTimeOffset.UnixEpoch, Ct)
.ConfigureAwait(true);
string path = f.Path;
await f.Db.DisposeAsync().ConfigureAwait(true);
var c23 = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString());
await using (c23.ConfigureAwait(true))
{
await c23.OpenAsync(Ct).ConfigureAwait(true);
await RewindToAsync(c23, 23).ConfigureAwait(true);
(await c23.ExecuteScalarAsync<long>(new CommandDefinition(
"SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE name LIKE 'input!_%' ESCAPE '!'", cancellationToken: Ct)).ConfigureAwait(true))
.Should().Be(0, "a ledger at schema 23 has no input column");
await c23.ExecuteAsync(new CommandDefinition(
"INSERT INTO sessions (session_guid, game_id, snapshot_id, started_at, ended_at, duration_s, qpc_epoch, qpc_frequency, capture_tier, capture_mode, exit_status, frame_count, app_frame_count, displayed_frame_count, dropped_frames) "
+ "VALUES ('00000000-0000-0000-0000-000000000024', @gameId, @snapshotId, 0, 60000, 60, 0, 10000000, 2, 'attach', 'normal', 0, 0, 0, 0)",
new { gameId, snapshotId }, cancellationToken: Ct)).ConfigureAwait(true);
}
LedgerDatabase migrated = await LedgerDatabase.OpenAsync(path, ct: Ct).ConfigureAwait(true);
await using (migrated.ConfigureAwait(true))
{
migrated.SchemaVersion.Should().Be(MigrationRunner.LatestVersion);
IReadOnlyList<string> sessionColumns = await migrated.ReadAsync(async (c, ct) => (IReadOnlyList<string>)[.. await c.QueryAsync<string>(new CommandDefinition(
"SELECT name FROM pragma_table_info('sessions') WHERE name LIKE 'input!_%' ESCAPE '!' ORDER BY cid", cancellationToken: ct)).ConfigureAwait(false)], Ct).ConfigureAwait(true);
IReadOnlyList<string> gameColumns = await migrated.ReadAsync(async (c, ct) => (IReadOnlyList<string>)[.. await c.QueryAsync<string>(new CommandDefinition(
"SELECT name FROM pragma_table_info('games') WHERE name LIKE 'controller!_%' ESCAPE '!' ORDER BY cid", cancellationToken: ct)).ConfigureAwait(false)], Ct).ConfigureAwait(true);
sessionColumns.Should().Equal(
"input_observed_ms", "input_foreground_ms", "input_controller_ms", "input_km_ms", "input_both_ms", "input_idle_ms", "input_method_switches", "input_source", "input_devices");
gameColumns.Should().Equal("controller_support", "controller_support_source", "controller_support_at");
var sessions = new SqliteSessionRepository(migrated);
SessionRow before = (await sessions.FindAsync(Guid.Parse("00000000-0000-0000-0000-000000000024"), Ct).ConfigureAwait(true))!;
before.InputObservedMs.Should().BeNull("a session recorded before the reading existed has none - N/A, never a zero");
before.InputForegroundMs.Should().BeNull();
before.InputMethodSwitches.Should().BeNull();
before.InputSource.Should().BeNull();
before.InputDevicesJson.Should().BeNull();
before.InputSharePercent(before.InputControllerMs).Should().BeNull();
(await sessions.FindInputSensorsAsync(before.Id, Ct).ConfigureAwait(true)).Should().BeEmpty();
GameRow game = (await new SqliteGameRepository(migrated).FindByIdAsync(gameId, Ct).ConfigureAwait(true))!;
game.ControllerSupport.Should().BeNull();
game.ControllerSupportSource.Should().BeNull();
game.ControllerSupportAt.Should().BeNull();
}
}
[Fact]
public void ScriptTwentyFourOnlyAddsColumnsAndNamesNoIdentifier()
{
// D160: the numbers are columns of sessions on purpose - the trend, the comparison, the export and the bug bundle
// read a session's row. What may never be a column: a controller's serial number, its address, its path.
string sql = MigrationRunner.Scripts()[24];
string statements = string.Join('\n', sql.Split('\n').Where(static l => !l.TrimStart().StartsWith("--", StringComparison.Ordinal)).Select(static l => l.Split("--")[0]));
statements.Should().NotContainAny("CREATE", "DROP", "UPDATE", "DELETE");
statements.Should().NotContainAny("serial", "address", "path", "mac", "uuid");
Regex.Matches(statements, @"ALTER\s+TABLE\s+(?<table>\w+)\s+ADD\s+COLUMN", RegexOptions.ExplicitCapture, TimeSpan.FromSeconds(1)).Select(static m => m.Groups["table"].Value)
.Distinct(StringComparer.Ordinal).Should().Equal("sessions", "games");
}
[Fact]
public void ScriptTwentyThreeAddsNoColumnToSessionsAndNamesNoIdentifier()
{
@@ -111,6 +111,15 @@ public sealed class SqliteSessionRepositoryTests
AppFramesPerJoule = 0.3125,
RuntimeModuleSourcesJson = "{\"nvngx_dlss.dll\":\"graphics_driver\"}",
DlssNrPct = 97.25,
InputObservedMs = 5_400_000,
InputForegroundMs = 5_000_000,
InputControllerMs = 3_500_000,
InputKeyboardMouseMs = 900_000,
InputBothMs = 100_000,
InputIdleMs = 500_000,
InputMethodSwitches = 4,
InputSource = "rawinput+xinput+lastinput",
InputDevicesJson = "{\"V\":1,\"Devices\":[{\"Index\":1,\"Family\":\"playstation\",\"Model\":\"DualSense\"}]}",
FgMixJson = "{\"Rows\":[{\"Kind\":\"generated\",\"Factor\":3.99,\"NativeFps\":70.5,\"DisplayedFps\":281.3,\"Seconds\":120,\"Share\":0.75,\"Windows\":24}]}",
};
@@ -547,6 +556,34 @@ public sealed class SqliteSessionRepositoryTests
float.IsNaN(rail[1]).Should().BeTrue("a tick with no reading is NaN");
}
[Fact]
public async Task TheInputSeriesAreReadOnTheirOwnAndTheFixedReadNeverSeesThem()
{
// Schema 0024 (D155-D163). The input series are rows of sensor_blobs too, and the read every summary and chart
// uses leaves them out: a class's number is not a sensor's value, and NaN marks a tick with nothing to say.
await using LedgerFixture f = await LedgerFixture.OpenAsync();
(long gameId, long snapshotId) = await SeedAsync(f);
var repo = new SqliteSessionRepository(f.Db);
SensorBlob[] sensors =
[
.. SensorsWithAdvanced(),
new() { Series = "input.class", Hz = 1, Codec = SeriesCodec.Tag, Data = SeriesCodec.EncodeSparseFloat32([1f, float.NaN, 2f]) },
new() { Series = "input.dev.1.active", Hz = 1, Codec = SeriesCodec.Tag, Data = SeriesCodec.EncodeSparseFloat32([1f, float.NaN, 0f]) },
];
long id = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId), Sensors = sensors, Advanced = Advanced() }, Ct);
long without = await repo.InsertFinalizedAsync(new FinalizedSession { Row = Row(gameId, snapshotId, started: DateTimeOffset.FromUnixTimeMilliseconds(1_700_000_000_000)), Sensors = [.. SensorsWithAdvanced().Take(2)] }, Ct);
(await repo.FindSensorsAsync(id, Ct)).Select(static s => s.Series).Should().Equal("gpu_temp", "t_ms");
(await repo.FindAdvancedSensorsAsync(id, Ct)).Select(static s => s.Series).Should().NotContain(static s => s.StartsWith("input.", StringComparison.Ordinal));
IReadOnlyList<SensorBlob> series = await repo.FindInputSensorsAsync(id, Ct);
series.Select(static s => s.Series).Should().Equal("t_ms", "input.class", "input.dev.1.active");
float[] timeline = SeriesCodec.DecodeFloat32(series[1].Data.ToArray());
timeline[0].Should().Be(1f);
float.IsNaN(timeline[1]).Should().BeTrue("a tick with the game not in front has no class");
(await repo.FindInputSensorsAsync(without, Ct)).Select(static s => s.Series).Should().Equal("t_ms");
}
[Fact]
public async Task TheAdvancedListNamesOnlySessionsRecordedWithTheOptionOnNewestFirst()
{
@@ -269,7 +269,7 @@ public sealed class PartialSessionFileAdvancedTests : IDisposable
}
/// <summary>One chunk as the format frames it: type, length, payload, then the IEEE CRC-32 of the first three.</summary>
private static byte[] Chunk(uint type, byte[] payload)
internal static byte[] Chunk(uint type, byte[] payload)
{
byte[] chunk = new byte[12 + payload.Length];
BinaryPrimitives.WriteUInt32LittleEndian(chunk, type);
@@ -289,7 +289,7 @@ public sealed class PartialSessionFileAdvancedTests : IDisposable
return chunk;
}
private static List<int> ChunkOffsets(byte[] file)
internal static List<int> ChunkOffsets(byte[] file)
{
var offsets = new List<int>();
for (int at = 0; at < file.Length; at += 12 + BitConverter.ToInt32(file, at + 4))
@@ -300,5 +300,5 @@ public sealed class PartialSessionFileAdvancedTests : IDisposable
return offsets;
}
private static uint[] ChunkTypes(byte[] file) => [.. ChunkOffsets(file).Select(at => BitConverter.ToUInt32(file, at))];
internal static uint[] ChunkTypes(byte[] file) => [.. ChunkOffsets(file).Select(at => BitConverter.ToUInt32(file, at))];
}
@@ -0,0 +1,287 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using FluentAssertions;
using FrameLedger.Application.Input;
using FrameLedger.Application.Recording;
using FrameLedger.Application.Telemetry;
using FrameLedger.Domain.Input;
using FrameLedger.Domain.Sessions;
using FrameLedger.Infrastructure.Recording;
namespace FrameLedger.Infrastructure.Tests.Recording;
/// <summary>
/// The <c>.partial</c> and the input readings (owner decisions D155-D163): a sample's reading survives the round trip
/// with every controller it counts; with the option off the file is byte for byte what it was; a file cut at every byte
/// still reads up to its last whole chunk; and a chunk that is not well formed ends the read.
/// </summary>
public sealed class PartialSessionFileInputTests : IDisposable
{
private static readonly DateTimeOffset _t0 = new(2026, 11, 14, 9, 0, 0, TimeSpan.Zero);
private static readonly InputDevice _xbox = new() { Id = 3, Family = ControllerFamily.Xbox, VendorId = ControllerCatalog.Microsoft, ProductId = 0x0B12, Connection = ControllerConnection.Wireless, XInputSlot = 2 };
private static readonly InputDevice _dualSense = new() { Id = 70_000, Family = ControllerFamily.PlayStation, VendorId = ControllerCatalog.Sony, ProductId = ControllerCatalog.DualSense, Connection = ControllerConnection.Bluetooth };
private static readonly InputDevice _steam = new() { Id = 5, Family = ControllerFamily.Xbox, VendorId = ControllerCatalog.Valve, ProductId = ControllerCatalog.SteamVirtualGamepad, IsVirtual = true, XInputSlot = 0 };
private readonly string _dir = Path.Combine(Path.GetTempPath(), "fl-partial-input-" + Guid.NewGuid().ToString("N"));
public PartialSessionFileInputTests() => Directory.CreateDirectory(_dir);
public void Dispose()
{
try
{
Directory.Delete(_dir, recursive: true);
}
catch (IOException)
{
}
}
private static PartialHeader Header() => new()
{
SessionGuid = Guid.Parse("00000000-0000-0000-0000-0000000000b1"),
StartedAt = _t0,
QpcEpoch = 1_000_000,
QpcFrequency = 10_000_000,
GameId = 7,
SnapshotId = 3,
ExePath = @"C:\Games\Title\game.exe",
Pid = 4242,
Tier = CaptureTier.NotHooked,
Mode = CaptureMode.Attach,
TelemetryDescriptor = "l1+lhm",
};
private static TelemetrySample Sample(long qpc, InputReading? input = null) => new(
qpc,
new GpuSample { TakenAt = _t0.AddSeconds(qpc / 10_000_000.0), Layer = TelemetryLayer.Lhm, TempCoreC = 60 },
Input: input);
/// <summary>A reading with every field set to something a default would not be.</summary>
private static InputReading Full() => new()
{
SpanMs = 1004,
ObservedMs = 903,
ForegroundMs = 802,
ControllerMs = 401,
KeyboardMouseMs = 200,
BothMs = 101,
IdleMs = 100,
VirtualPad = true,
Devices =
[
new InputDeviceReading(_xbox.Id, Connected: true, ActiveMs: 502, new BatteryReading(BatteryState.Discharging, BatteryScale.FourLevels, 2), Connects: 1, Disconnects: 0),
new InputDeviceReading(_dualSense.Id, Connected: false, ActiveMs: 0, new BatteryReading(BatteryState.Charging, BatteryScale.Percent, 100), Connects: 2, Disconnects: 3),
new InputDeviceReading(_steam.Id, Connected: true, ActiveMs: 490, Battery: null, Connects: 0, Disconnects: 0),
],
Table = [_xbox, _dualSense, _steam],
Health = new InputHealth
{
RawInputRegistered = true,
XInputAvailable = true,
LastInputAvailable = true,
RawReports = 5_000_000_000,
RawReportsUnread = 7,
XInputReads = 1234,
XInputSilent = 5,
Slices = 10,
ThreadCpuMs = 3,
Faults = 1,
},
};
private static InputReading Quiet() => new() { SpanMs = 1000, ObservedMs = 1000, ForegroundMs = 1000, IdleMs = 1000, Health = new InputHealth { LastInputAvailable = true, Slices = 20 } };
[Fact]
public void ASamplesReadingRoundTripsWithEveryControllerAndASampleWithoutOneHasNone()
{
string path = Path.Combine(_dir, "input.partial");
using (IPartialSessionWriter w = PartialSessionFile.Create(path, Header()))
{
w.AppendSensors([Sample(1_100_000, Full()), Sample(1_200_000), Sample(1_300_000, Quiet())]);
w.AppendSensors([Sample(1_400_000, Full() with { VirtualPad = false })]);
}
PartialSession p = PartialSessionFile.Read(path)!;
p.Truncated.Should().BeFalse();
p.Sensors.Should().HaveCount(4);
p.Sensors[0].Input.Should().BeEquivalentTo(Full(), static o => o.WithStrictOrdering());
p.Sensors[0].Input!.Table[1].Model.Should().Be("DualSense", "a controller is what its two ids say, and they travel with the reading");
p.Sensors[1].Input.Should().BeNull("a tick the reader took no slice in carries none, and is not given the last one's");
p.Sensors[2].Input.Should().BeEquivalentTo(Quiet());
p.Sensors[3].Input!.VirtualPad.Should().BeFalse();
PartialSessionFileAdvancedTests.ChunkTypes(File.ReadAllBytes(path)).Should().Equal(1u, 8u, 11u, 8u, 11u);
}
[Fact]
public void WithTheOptionOffTheFileIsByteForByteWhatItWasBeforeTheReadingExisted()
{
string off = Path.Combine(_dir, "off.partial");
string on = Path.Combine(_dir, "on.partial");
using (IPartialSessionWriter w = PartialSessionFile.Create(off, Header()))
{
w.AppendSensors([Sample(1_100_000), Sample(1_200_000)]);
w.AppendNote(_t0, "end");
}
using (IPartialSessionWriter w = PartialSessionFile.Create(on, Header()))
{
w.AppendSensors([Sample(1_100_000, Quiet()), Sample(1_200_000)]);
w.AppendNote(_t0, "end");
}
byte[] offBytes = File.ReadAllBytes(off);
byte[] onBytes = File.ReadAllBytes(on);
PartialSessionFileAdvancedTests.ChunkTypes(offBytes).Should().Equal(1u, 8u, 6u);
PartialSessionFileAdvancedTests.ChunkTypes(onBytes).Should().Equal(1u, 8u, 11u, 6u);
int inputChunk = PartialSessionFileAdvancedTests.ChunkOffsets(onBytes)[2];
int inputLength = 12 + BitConverter.ToInt32(onBytes, inputChunk + 4);
onBytes.AsSpan(0, inputChunk).ToArray().Should().Equal(offBytes.AsSpan(0, inputChunk).ToArray(), "the sensor chunk does not change when a reading rides beside it");
onBytes.AsSpan(inputChunk + inputLength).ToArray().Should().Equal(offBytes.AsSpan(inputChunk).ToArray());
}
[Fact]
public void AKillAtEveryByteOffsetYieldsExactlyTheReadingsWhoseChunkWasComplete()
{
string path = Path.Combine(_dir, "cut.partial");
using (IPartialSessionWriter w = PartialSessionFile.Create(path, Header()))
{
w.AppendSensors([Sample(1_100_000, Full()), Sample(1_200_000, Quiet())]);
w.AppendSensors([Sample(1_300_000, Full())]);
}
byte[] whole = File.ReadAllBytes(path);
List<int> starts = PartialSessionFileAdvancedTests.ChunkOffsets(whole);
PartialSessionFileAdvancedTests.ChunkTypes(whole).Should().Equal(1u, 8u, 11u, 8u, 11u);
int[] ends = [.. starts.Skip(1), whole.Length];
for (int cut = ends[0]; cut <= whole.Length; cut++)
{
PartialSession p = PartialSessionFile.Parse(whole.AsSpan(0, cut))!;
int complete = ends.Count(e => e <= cut);
p.Sensors.Should().HaveCount(complete >= 4 ? 3 : complete >= 2 ? 2 : 0, $"cut at {cut}, {complete} complete chunk(s)");
p.Sensors.Count(static s => s.Input is not null).Should().Be(complete >= 5 ? 3 : complete >= 3 ? 2 : 0, $"cut at {cut}: a reading arrives with its own chunk and never before it");
p.Truncated.Should().Be(cut != whole.Length && !ends.Contains(cut), $"cut at {cut}");
}
}
[Fact]
public void AnInputChunkThatIsNotWellFormedEndsTheReadLikeAnyKnownChunkThatIsNot()
{
string path = Path.Combine(_dir, "bad.partial");
using (IPartialSessionWriter w = PartialSessionFile.Create(path, Header()))
{
w.AppendSensors([Sample(1_100_000, Quiet())]);
}
byte[] file = File.ReadAllBytes(path);
int at = PartialSessionFileAdvancedTests.ChunkOffsets(file)[2];
byte[] good = file.AsSpan(at + 8, BitConverter.ToInt32(file, at + 4)).ToArray();
byte[] head = file[..at];
byte[][] bad =
[
[],
[1, 0],
good[..^1], // a sample cut short
[.. good, 0], // a byte too many
[2, 0, 0, 0, .. good[4..]], // two samples declared, one there
[.. good[..^1], 1], // a controller declared and not there
];
foreach (byte[] payload in bad)
{
PartialSession p = PartialSessionFile.Parse([.. head, .. PartialSessionFileAdvancedTests.Chunk(type: 11, payload)])!;
p.Truncated.Should().BeTrue($"a payload of {payload.Length} byte(s)");
p.Sensors.Should().ContainSingle().Which.Input.Should().BeNull();
}
PartialSessionFile.Parse([.. head, .. PartialSessionFileAdvancedTests.Chunk(type: 11, good)])!.Sensors[0].Input.Should().BeEquivalentTo(Quiet(), "the same chunk, whole");
}
[Fact]
public void AReadingWhoseSampleIsNotInTheFileBelongsToNoTickAndIsLeftOut()
{
string source = Path.Combine(_dir, "source.partial");
using (IPartialSessionWriter w = PartialSessionFile.Create(source, Header()))
{
w.AppendSensors([Sample(9_999_999, Quiet())]);
}
string path = Path.Combine(_dir, "orphan.partial");
using (IPartialSessionWriter w = PartialSessionFile.Create(path, Header()))
{
w.AppendSensors([Sample(1_100_000)]);
}
byte[] other = File.ReadAllBytes(source);
byte[] orphan = other[PartialSessionFileAdvancedTests.ChunkOffsets(other)[2]..];
PartialSession p = PartialSessionFile.Parse([.. File.ReadAllBytes(path), .. orphan])!;
p.Truncated.Should().BeFalse();
p.Sensors.Should().ContainSingle().Which.Input.Should().BeNull();
}
/// <summary>A later build may know a maker, a connection or a battery state this one has no name for: it reads as "do not know", and the rest of the reading is kept.</summary>
[Fact]
public void AValueThisBuildHasNoNameForReadsAsUnknownAndTheRestIsKept()
{
string path = Path.Combine(_dir, "later.partial");
using (IPartialSessionWriter w = PartialSessionFile.Create(path, Header()))
{
w.AppendSensors([Sample(1_100_000, Full() with { Devices = [Full().Devices[0]], Table = [_xbox] })]);
}
byte[] file = File.ReadAllBytes(path);
int at = PartialSessionFileAdvancedTests.ChunkOffsets(file)[2];
byte[] payload = file.AsSpan(at + 8, BitConverter.ToInt32(file, at + 4)).ToArray();
int device = payload.Length - 23;
payload[device + 4] = 200; // the family
payload[device + 9] = 201; // the connection
payload[device + 16] = 202; // the battery's state
payload[device + 17] = 203; // and its scale
InputReading reading = PartialSessionFile.Parse([.. file[..at], .. PartialSessionFileAdvancedTests.Chunk(type: 11, payload)])!.Sensors[0].Input!;
reading.Table[0].Family.Should().Be(ControllerFamily.Other);
reading.Table[0].Connection.Should().Be(ControllerConnection.Unknown);
reading.Devices[0].Battery.Should().Be(new BatteryReading(BatteryState.Unknown, BatteryScale.None, 2));
reading.Devices[0].ActiveMs.Should().Be(502);
reading.Table[0].XInputSlot.Should().Be(2);
}
/// <summary>A controller the reading counts and does not describe cannot be written whole, and is left out; ids past sixteen bits are held to them.</summary>
[Fact]
public void AControllerWithNoDescriptionIsLeftOutAndOutOfRangeValuesAreHeld()
{
var wide = new InputDevice { Id = 9, VendorId = 0x12345, ProductId = -4, XInputSlot = 300 };
var reading = new InputReading
{
Devices =
[
new InputDeviceReading(404, Connected: true, ActiveMs: 10, Battery: null, Connects: 0, Disconnects: 0),
new InputDeviceReading(9, Connected: true, ActiveMs: 20, new BatteryReading(BatteryState.Discharging, BatteryScale.Percent, 900), Connects: 70_000, Disconnects: -1),
],
Table = [wide],
};
string path = Path.Combine(_dir, "held.partial");
using (IPartialSessionWriter w = PartialSessionFile.Create(path, Header()))
{
w.AppendSensors([Sample(1_100_000, reading)]);
}
InputReading back = PartialSessionFile.Read(path)!.Sensors[0].Input!;
back.Devices.Should().ContainSingle().Which.Should().Be(
new InputDeviceReading(9, Connected: true, ActiveMs: 20, new BatteryReading(BatteryState.Discharging, BatteryScale.Percent, 255), Connects: 65_535, Disconnects: 0));
back.Table.Should().ContainSingle().Which.Should().BeEquivalentTo(wide with { VendorId = 65_535, ProductId = 0, XInputSlot = 255 });
}
}
+90
View File
@@ -0,0 +1,90 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
using FrameLedger.Application.Input;
namespace FrameLedger.Testing;
/// <summary>Windows, as the input reader asks it, with every answer written by the test: <b>no device is behind it</b>.</summary>
internal sealed class FakeInputBackend : IInputBackend
{
private readonly List<Action<IInputBackendSink>> _pending = [];
public bool Registers { get; set; } = true;
public bool XInputAvailable { get; set; } = true;
/// <summary>The pads XInput has, by slot.</summary>
public Dictionary<int, XInputReading> Pads { get; } = [];
public Dictionary<int, XInputDetails> Details { get; } = [];
/// <summary>Windows' time of the last keyboard or mouse input; null is "Windows did not give it".</summary>
public uint? LastInputTick { get; set; } = 1000;
public uint Foreground { get; set; } = 42;
public long CpuMs { get; set; }
public bool ThrowOnDrain { get; set; }
/// <summary>How many times each slot was asked for its state.</summary>
public int[] PadAsks { get; } = new int[InputReader.Slots];
public int DetailAsks { get; private set; }
public bool Opened { get; private set; }
public bool Disposed { get; private set; }
public void Arrive(nint device, RawController controller) => _pending.Add(sink => sink.Arrived(device, controller));
public void Leave(nint device) => _pending.Add(sink => sink.Removed(device));
public void Send(nint device, params byte[] report) => _pending.Add(sink => sink.Report(device, report));
public bool Open()
{
Opened = true;
return Registers;
}
public void Drain(IInputBackendSink sink)
{
if (ThrowOnDrain)
{
throw new InvalidOperationException("the drain failed");
}
foreach (Action<IInputBackendSink> step in _pending)
{
step(sink);
}
_pending.Clear();
}
public bool TryReadPad(int slot, out XInputReading pad)
{
PadAsks[slot]++;
return Pads.TryGetValue(slot, out pad);
}
public bool TryReadPadDetails(int slot, out XInputDetails details)
{
DetailAsks++;
return Details.TryGetValue(slot, out details);
}
public bool TryReadLastInputTick(out uint tick)
{
tick = LastInputTick ?? 0;
return LastInputTick is not null;
}
public uint ForegroundProcessId() => Foreground;
public long ThreadCpuMs() => CpuMs;
public void Dispose() => Disposed = true;
}
+33
View File
@@ -0,0 +1,33 @@
# The Windows functions the input reader calls (docs/21_INPUT_DEVICES.md, owner decisions D155-D163).
# One name a line. tools/input-readonly-check.ps1 holds this list to src/FrameLedger.Infrastructure/Input/Win32Input.cs
# in both directions, and refuses a name that sends to a device, injects input or reads a key whatever this file says.
# Raw input for game controllers: their reports while the Agent is in the background, who arrived and left, and what
# a device is by its two USB ids. It opens no device.
RegisterRawInputDevices
GetRawInputBuffer
GetRawInputData
GetRawInputDeviceInfoW
GetRawInputDeviceList
# XInput: a pad's state, whether it is wireless, its battery. Getters only.
XInputGetState
XInputGetCapabilities
XInputGetBatteryInformation
# Keyboard and mouse: the time of the last input, and nothing else (D158).
GetLastInputInfo
# The window raw input is delivered to: never shown, a child of HWND_MESSAGE, answered by the default procedure.
RegisterClassExW
UnregisterClassW
CreateWindowExW
DestroyWindow
DefWindowProcW
PeekMessageW
DispatchMessageW
GetModuleHandleW
# The reader's own cost: the processor time its thread used.
GetCurrentThread
GetThreadTimes
+287
View File
@@ -0,0 +1,287 @@
# SPDX-License-Identifier: GPL-3.0-only
# Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
#Requires -Version 7.0
<#
.SYNOPSIS
What FrameLedger asks Windows about controllers, the keyboard and the mouse is a committed list of calls, none of
which sends anything to a device or reads a key.
.DESCRIPTION
docs/21_INPUT_DEVICES.md makes three promises a reviewer would otherwise have to check by reading (owner decisions
D155-D163, 2026-11-14):
- keyboard and mouse are known only by the time of the last input: no key, no button, no position is ever read,
and no hook is installed (D158);
- nothing is ever sent to a controller: no output report, no feature-report request, no vibration (D159);
- controllers are read by the Agent from outside the game: the code loaded into a game reads no input (D155).
The legal texts say the same to the user. A sentence does not keep itself true; this does.
WHAT IT HOLDS:
1. every Windows function declared in src/FrameLedger.Infrastructure/Input/Win32Input.cs - the one file the
input reader's calls are declared in - is on tools/input-allowed-calls.txt, and every name there is declared
(a list longer than the code is a list nobody reads);
2. no name on the list is one that writes to a device, injects input or reads a key - whatever the list says.
This rule judges the LIST, so the way to let such a call in is not "add a line to the text file";
3. no managed source outside src/FrameLedger.Infrastructure/Input/ names an input function at all, and none
anywhere - nor NativeMethods.txt, where CsWin32 would be asked for one - names a forbidden one;
4. raw input is registered for joysticks and gamepads only: InputReader.RegisteredUsages is exactly usage page 1,
usages 4 and 5, and the registration is built from it and from nothing else;
5. no native source (src/native, the vendored code aside) names an input function: nothing loaded into a game,
and no other native binary, reads input.
WHAT IT DOES NOT DO. It reads names, not behaviour: it cannot tell what a call is used for. It does not look at
the tests, which may drive a real keyboard to test the App's own shortcuts. Comments and string literals are taken
out first, so a function named in the comment that says it is never called is not a call.
-SelfTest proves every rule in both directions on in-memory sources.
#>
[CmdletBinding()]
param(
[string]$RepoRoot = (Split-Path $PSScriptRoot -Parent),
[switch]$SelfTest
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
# The names of Windows' input functions, as tokens. XInput's functions are XInputGet*, XInputSet* and XInputEnable;
# the project's own types are XInputReading, XInputPad and the like, and are not these.
$script:InputCall = '\b(XInput(?:Get|Set|Enable)[A-Za-z]*|GetRawInput[A-Za-z]*|RegisterRawInputDevices|GetRegisteredRawInputDevices|GetLastInputInfo|HidD_\w+|HidP_\w+|SendInput|keybd_event|mouse_event|GetAsyncKeyState|GetKeyState|GetKeyboardState|GetKeyNameText[AW]?|MapVirtualKey(?:Ex)?[AW]?|ToUnicode(?:Ex)?|SetWindowsHookEx[AW]?|BlockInput|DirectInput8Create|GameInputCreate)\b'
# A namespace is not a call, and is refused all the same: its readings stop when the program is not in front, and it
# is not on the list of what was decided (21_INPUT_DEVICES section Rejected).
$script:InputNamespace = 'Windows\.Gaming\.Input'
# What may never be called, on the list or off it. Each with its reason, because a list judged by a pattern nobody
# can read is a list nobody trusts.
$script:Forbidden = [ordered]@{
'^XInputSet' = 'sends to a controller (D159)'
'^XInputEnable$' = 'changes what every XInput call of the process returns'
'^XInputGetKeystroke$' = 'reads which button was pressed, as a key (D158, 21_INPUT_DEVICES section What is never read)'
'^XInputGetAudioDeviceIds$' = 'identifies the audio devices of a headset'
'^XInputGetDSoundAudioDeviceGuids$' = 'identifies the audio devices of a headset'
'^HidD_' = 'opens or talks to a HID device: an output report, a feature report, a serial number (D159)'
'^HidP_' = 'not decided: 21_INPUT_DEVICES reads a DualSense by its own layout and no other HID controller'
'^SendInput$' = 'injects input'
'^keybd_event$' = 'injects input'
'^mouse_event$' = 'injects input'
'^BlockInput$' = 'blocks input'
'^GetAsyncKeyState$' = 'reads a key (D158)'
'^GetKeyState$' = 'reads a key (D158)'
'^GetKeyboardState$' = 'reads every key (D158)'
'^GetKeyNameText' = 'names a key (D158)'
'^MapVirtualKey' = 'translates a key (D158)'
'^ToUnicode' = 'turns keys into text (D158)'
'^SetWindowsHookEx' = 'installs a hook (D158; tools/chokepoint-check.ps1 refuses it as well)'
'^GetRegisteredRawInputDevices$' = 'not needed: the reader knows what it registered'
'^DirectInput8Create$' = 'DirectInput: not decided, and it does not read in the background'
'^GameInputCreate$' = 'GameInput: rejected (21_INPUT_DEVICES section Rejected)'
}
# Source text without its comments and string literals.
function Get-Code([string]$Source) {
$code = [regex]::Replace($Source, '/\*.*?\*/', ' ', 'Singleline')
$code = [regex]::Replace($code, '//[^\r\n]*', ' ')
$code = [regex]::Replace($code, '@"(""|[^"])*"', '""')
return [regex]::Replace($code, '"(\\.|[^"\\\r\n])*"', '""')
}
# The names of the list, and what is wrong with the list itself.
function Read-AllowedList([string]$Text) {
$names = [System.Collections.Generic.List[string]]::new()
$problems = [System.Collections.Generic.List[string]]::new()
$number = 0
foreach ($raw in ($Text -split "`r?`n")) {
$number++
$line = $raw.Trim()
if ($line.Length -eq 0 -or $line.StartsWith('#')) { continue }
if ($line -cnotmatch '^[A-Za-z_]\w*$') { $problems.Add("the list's line $number is not one function name: '$line'"); continue }
if ($names.Contains($line)) { $problems.Add("the list names $line twice"); continue }
$names.Add($line)
}
return @{ Names = @($names); Problems = @($problems) }
}
function Get-ForbiddenReason([string]$Name) {
foreach ($pattern in $script:Forbidden.Keys) {
if ($Name -cmatch $pattern) { return $script:Forbidden[$pattern] }
}
return $null
}
# Every rule, on text. $Declarations is Win32Input.cs; $Managed maps a repository path to a managed source (the
# declarations' own file among them); $NativeMethods is CsWin32's list; $Reader is InputReader.cs; $Backend is
# Win32InputBackend.cs; $Native maps a path to a native source.
function Test-Input([string]$Declarations, [string]$ListText, [hashtable]$Managed, [string]$NativeMethods, [string]$Reader, [string]$Backend, [hashtable]$Native) {
$problems = [System.Collections.Generic.List[string]]::new()
$list = Read-AllowedList $ListText
foreach ($p in $list.Problems) { $problems.Add($p) }
$allowed = $list.Names
# 1. The declarations and the list say the same.
$declared = @([regex]::Matches((Get-Code $Declarations), '\bstatic\s+extern\s+[^;(]*?\b([A-Za-z_]\w*)\s*\(') | ForEach-Object { $_.Groups[1].Value } | Sort-Object -Unique)
if ($declared.Count -eq 0) { $problems.Add('the declarations file declares no function: the check would hold nothing') }
foreach ($name in $declared) {
if ($allowed -cnotcontains $name) { $problems.Add("$name is declared and is not on the list") }
}
foreach ($name in $allowed) {
if ($declared -cnotcontains $name) { $problems.Add("$name is on the list and is not declared: a list longer than the code is a list nobody reads") }
}
# 2. The list itself.
foreach ($name in $allowed) {
$why = Get-ForbiddenReason $name
if ($why) { $problems.Add("$name may not be on the list: it $why") }
}
# 3. The managed sources, and what CsWin32 is asked for.
foreach ($path in ($Managed.Keys | Sort-Object)) {
$code = Get-Code $Managed[$path]
$inReader = $path -like 'src/FrameLedger.Infrastructure/Input/*'
foreach ($m in [regex]::Matches($code, $script:InputCall)) {
$name = $m.Groups[1].Value
$why = Get-ForbiddenReason $name
if ($why) { $problems.Add("$path names ${name}: it $why") }
elseif (-not $inReader) { $problems.Add("$path names ${name}: input is read in src/FrameLedger.Infrastructure/Input/ and nowhere else") }
elseif ($allowed -cnotcontains $name) { $problems.Add("$path names ${name}, which is not on the list") }
}
if ($code -cmatch $script:InputNamespace) { $problems.Add("$path names Windows.Gaming.Input: rejected (21_INPUT_DEVICES section Rejected)") }
}
foreach ($raw in ($NativeMethods -split "`r?`n")) {
$line = $raw.Trim()
if ($line.Length -eq 0 -or $line.StartsWith('//')) { continue }
if ($line -cmatch ('^' + $script:InputCall.Trim('\', 'b') + '$') -or $line -cmatch $script:InputCall) {
$problems.Add("NativeMethods.txt asks CsWin32 for ${line}: the input reader's calls are declared in Win32Input.cs, where this check reads them")
}
}
# 4. What raw input is registered for.
$readerCode = Get-Code $Reader
if ($readerCode -cnotmatch 'RegisteredUsages\s*\{\s*get;\s*\}\s*=\s*\[\s*\(\s*1\s*,\s*4\s*\)\s*,\s*\(\s*1\s*,\s*5\s*\)\s*\]\s*;') {
$problems.Add('InputReader.RegisteredUsages is not exactly [(1, 4), (1, 5)]: raw input is registered for joysticks and gamepads only - usage 2 is a mouse and 6 a keyboard (D158)')
}
$backendCode = Get-Code $Backend
if ($backendCode -cnotmatch 'InputReader\.RegisteredUsages') { $problems.Add('the backend does not build its registration from InputReader.RegisteredUsages') }
if ($backendCode -cmatch '\bUsage(Page)?\s*=\s*(0x[0-9A-Fa-f]+|\d)') { $problems.Add('the backend registers a usage written as a number: the registration is InputReader.RegisteredUsages and nothing else') }
# 5. The native sources.
foreach ($path in ($Native.Keys | Sort-Object)) {
$code = Get-Code $Native[$path]
foreach ($m in [regex]::Matches($code, $script:InputCall)) {
$problems.Add("$path names $($m.Groups[1].Value): no native code reads input - controllers are read by the Agent, in C#, from outside the game (D155)")
}
}
return @($problems)
}
if ($SelfTest) {
$goodDeclarations = @'
internal static unsafe class Win32Input
{
// XInputSetState is never declared here.
[DllImport("user32.dll")] public static extern int RegisterRawInputDevices(RawInputDevice* devices, uint count, uint size);
[DllImport("user32.dll")] public static extern uint GetRawInputBuffer(void* data, uint* size, uint headerSize);
[DllImport("user32.dll")] public static extern int GetLastInputInfo(LastInputInfo* info);
[DllImport("xinput1_4.dll")] public static extern uint XInputGetState(uint userIndex, XInputState* state);
public struct XInputState { public uint PacketNumber; }
}
'@
$goodList = "# the reader's calls`nRegisterRawInputDevices`nGetRawInputBuffer`nGetLastInputInfo`nXInputGetState`n"
$goodReader = 'public static IReadOnlyList<(ushort UsagePage, ushort Usage)> RegisteredUsages { get; } = [(1, 4), (1, 5)];'
$goodBackend = 'IReadOnlyList<(ushort UsagePage, ushort Usage)> usages = InputReader.RegisteredUsages; devices[i] = new Win32Input.RawInputDevice { UsagePage = usages[i].UsagePage, Usage = usages[i].Usage, Flags = flags }; Win32Input.RegisterRawInputDevices(devices, 2, 16); Win32Input.XInputGetState(0, &state);'
$goodManaged = @{
'src/FrameLedger.Infrastructure/Input/Win32Input.cs' = $goodDeclarations
'src/FrameLedger.Infrastructure/Input/Win32InputBackend.cs' = $goodBackend
'src/FrameLedger.Application/Input/InputReader.cs' = $goodReader + ' public bool XInputAvailable => true; XInputReading r; // GetAsyncKeyState is never called'
'src/FrameLedger.App/Charts/ChartWheel.cs' = '/// <c>GetKeyState</c> reported the machine''s NumLock.' + "`n" + 'var s = "SendInput"; Keyboard.GetKeyStates(Key.A);'
}
$goodNativeMethods = "// the window`nIsWindow`nGetWindowThreadProcessId`n"
$goodNative = @{ 'src/native/FrameLedger.Overlay/src/dllmain.cpp' = '// XInputGetState is the Agent''s to call' + "`n" + 'void Hook() {}' }
function New-Case([string]$Name, [int]$Expect, [hashtable]$Change = @{}) {
$managed = @{}
foreach ($k in $goodManaged.Keys) { $managed[$k] = $goodManaged[$k] }
if ($Change.ContainsKey('Managed')) { foreach ($k in $Change.Managed.Keys) { $managed[$k] = $Change.Managed[$k] } }
$backend = if ($Change.ContainsKey('Backend')) { $Change.Backend } else { $goodBackend }
if ($Change.ContainsKey('Backend')) { $managed['src/FrameLedger.Infrastructure/Input/Win32InputBackend.cs'] = $backend }
return @{
Name = $Name
Expect = $Expect
Declarations = if ($Change.ContainsKey('Declarations')) { $Change.Declarations } else { $goodDeclarations }
List = if ($Change.ContainsKey('List')) { $Change.List } else { $goodList }
Managed = $managed
NativeMethods = if ($Change.ContainsKey('NativeMethods')) { $Change.NativeMethods } else { $goodNativeMethods }
Reader = if ($Change.ContainsKey('Reader')) { $Change.Reader } else { $goodReader }
Backend = $backend
Native = if ($Change.ContainsKey('Native')) { $Change.Native } else { $goodNative }
}
}
$setter = $goodDeclarations.Replace('public struct XInputState', '[DllImport("xinput1_4.dll")] public static extern uint XInputSetState(uint userIndex, void* vibration);' + "`n public struct XInputState")
$cases = @(
(New-Case 'the reader as it is, with the project''s own XInput types and a key function named in comments, passes' 0),
(New-Case 'a declared function that is not on the list FAILS, and so does each source that names it' 3 @{ List = "RegisterRawInputDevices`nGetRawInputBuffer`nGetLastInputInfo`n" }),
(New-Case 'a name on the list that is not declared FAILS' 1 @{ List = $goodList + "GetRawInputDeviceList`n" }),
(New-Case 'a line of the list that is not one name FAILS, and the same name twice' 2 @{ List = $goodList + "Get Raw Input`nXInputGetState`n" }),
(New-Case 'XInputSetState declared and put on the list FAILS twice: the list may not hold it, and the source may not name it' 2 @{ Declarations = $setter; List = $goodList + "XInputSetState`n"; Managed = @{ 'src/FrameLedger.Infrastructure/Input/Win32Input.cs' = $setter } }),
(New-Case 'a declarations file that declares nothing FAILS, with every name of the list then undeclared' 5 @{ Declarations = '// nothing' }),
(New-Case 'a key read anywhere in the managed sources FAILS' 1 @{ Managed = @{ 'src/FrameLedger.App/Services/Shortcut.cs' = 'if (GetAsyncKeyState(0x41) != 0) { }' } }),
(New-Case 'a HID feature report in the reader FAILS' 1 @{ Backend = $goodBackend + ' HidD_GetFeature(handle, buffer, 41);' }),
(New-Case 'an allowed call made outside the reader''s folder FAILS' 1 @{ Managed = @{ 'src/FrameLedger.Agent/Program.cs' = 'XInputGetState(0, &state);' } }),
(New-Case 'a call in the reader''s folder that is not on the list FAILS' 1 @{ Backend = $goodBackend + ' Win32Input.GetRawInputDeviceList(null, &n, 16);' }),
(New-Case 'Windows.Gaming.Input named in a source FAILS' 1 @{ Managed = @{ 'src/FrameLedger.Infrastructure/Input/Wgi.cs' = 'using Windows.Gaming.Input;' } }),
(New-Case 'an input function asked of CsWin32 FAILS' 1 @{ NativeMethods = $goodNativeMethods + "XInputGetState`n" }),
(New-Case 'a keyboard added to what raw input is registered for FAILS' 1 @{ Reader = $goodReader.Replace('(1, 5)]', '(1, 5), (1, 6)]') }),
(New-Case 'a backend that registers a usage written as a number FAILS' 1 @{ Backend = $goodBackend.Replace('Usage = usages[i].Usage', 'Usage = 6') }),
(New-Case 'a backend that does not use the registered usages FAILS' 1 @{ Backend = 'devices[i] = new Win32Input.RawInputDevice { UsagePage = page, Usage = usage };' }),
(New-Case 'an input function in the code loaded into a game FAILS' 1 @{ Native = @{ 'src/native/FrameLedger.Overlay/src/dllmain.cpp' = 'XINPUT_STATE s; XInputGetState(0, &s);' } }),
(New-Case 'a hook named in a native source FAILS' 1 @{ Native = @{ 'src/native/FrameLedger.Injector/src/injector.cpp' = 'SetWindowsHookExW(WH_KEYBOARD_LL, proc, nullptr, 0);' } })
)
$failed = 0
foreach ($c in $cases) {
$problems = @(Test-Input $c.Declarations $c.List $c.Managed $c.NativeMethods $c.Reader $c.Backend $c.Native)
$ok = $problems.Count -eq $c.Expect
Write-Host (" {0,-4} {1}{2}" -f ($(if ($ok) { 'ok' } else { 'FAIL' })), $c.Name, ($(if (-not $ok) { " -> $($problems.Count): $($problems -join '; ')" } else { '' })))
if (-not $ok) { $failed++ }
}
if ($failed -gt 0) { Write-Host "input-readonly-check self-test FAILED ($failed)" -ForegroundColor Red; exit 1 }
Write-Host "input-readonly-check self-test: $($cases.Count) cases, both directions" -ForegroundColor Green
exit 0
}
$declarationsPath = Join-Path $RepoRoot 'src/FrameLedger.Infrastructure/Input/Win32Input.cs'
$backendPath = Join-Path $RepoRoot 'src/FrameLedger.Infrastructure/Input/Win32InputBackend.cs'
$readerPath = Join-Path $RepoRoot 'src/FrameLedger.Application/Input/InputReader.cs'
$listPath = Join-Path $RepoRoot 'tools/input-allowed-calls.txt'
$nativeMethodsPath = Join-Path $RepoRoot 'src/FrameLedger.Infrastructure/NativeMethods.txt'
foreach ($path in $declarationsPath, $backendPath, $readerPath, $listPath, $nativeMethodsPath) {
if (-not (Test-Path -LiteralPath $path)) { Write-Host "INPUT READ-ONLY CHECK FAILED: $path is missing" -ForegroundColor Red; exit 1 }
}
$skip = [regex]'[\\/](bin|obj)[\\/]'
$managed = @{}
foreach ($file in Get-ChildItem -LiteralPath (Join-Path $RepoRoot 'src') -Recurse -File -Filter '*.cs') {
if ($skip.IsMatch($file.FullName) -or $file.FullName -like '*\native\*') { continue }
$managed[[IO.Path]::GetRelativePath($RepoRoot, $file.FullName).Replace('\', '/')] = Get-Content -LiteralPath $file.FullName -Raw
}
$native = @{}
foreach ($file in Get-ChildItem -LiteralPath (Join-Path $RepoRoot 'src/native') -Recurse -File -Include '*.cpp', '*.h', '*.inl', '*.c', '*.hpp') {
if ($file.FullName -like '*\third_party\*') { continue }
$native[[IO.Path]::GetRelativePath($RepoRoot, $file.FullName).Replace('\', '/')] = Get-Content -LiteralPath $file.FullName -Raw
}
if ($managed.Count -eq 0 -or $native.Count -eq 0) { Write-Host 'INPUT READ-ONLY CHECK FAILED: no managed or no native source was found' -ForegroundColor Red; exit 1 }
$listText = Get-Content -LiteralPath $listPath -Raw
$problems = @(Test-Input (Get-Content -LiteralPath $declarationsPath -Raw) $listText $managed (Get-Content -LiteralPath $nativeMethodsPath -Raw) (Get-Content -LiteralPath $readerPath -Raw) (Get-Content -LiteralPath $backendPath -Raw) $native)
if ($problems.Count -gt 0) {
Write-Host 'INPUT READ-ONLY CHECK FAILED:' -ForegroundColor Red
foreach ($p in $problems) { Write-Host " - $p" -ForegroundColor Red }
exit 1
}
$count = (Read-AllowedList $listText).Names.Count
Write-Host "input-readonly-check OK - the input reader declares $count Windows functions, each on the list; none sends to a device, injects input or reads a key; no input function in $($managed.Count) managed sources outside the reader, nor in $($native.Count) native sources" -ForegroundColor Green
exit 0